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 |
|---|---|---|---|---|---|---|
Q42/Jue | jue/src/nl/q42/jue/HueBridge.java | // Path: jue/src/nl/q42/jue/HttpClient.java
// public static class Result {
// private String body;
// private int responseCode;
//
// public Result(String body, int responseCode) {
// this.body = body;
// this.responseCode = responseCode;
// }
//
// public String getBody() {
// return body;
// }
//
// public int getResponseCode() {
// return responseCode;
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/ApiException.java
// @SuppressWarnings("serial")
// public class ApiException extends Exception {
// public ApiException() {}
//
// public ApiException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/DeviceOffException.java
// @SuppressWarnings("serial")
// public class DeviceOffException extends ApiException {
// public DeviceOffException() {}
//
// public DeviceOffException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/EntityNotAvailableException.java
// @SuppressWarnings("serial")
// public class EntityNotAvailableException extends ApiException {
// public EntityNotAvailableException() {}
//
// public EntityNotAvailableException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/GroupTableFullException.java
// @SuppressWarnings("serial")
// public class GroupTableFullException extends ApiException {
// public GroupTableFullException() {}
//
// public GroupTableFullException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/InvalidCommandException.java
// @SuppressWarnings("serial")
// public class InvalidCommandException extends ApiException {
// public InvalidCommandException() {}
//
// public InvalidCommandException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/LinkButtonException.java
// @SuppressWarnings("serial")
// public class LinkButtonException extends ApiException {
// public LinkButtonException() {}
//
// public LinkButtonException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/UnauthorizedException.java
// @SuppressWarnings("serial")
// public class UnauthorizedException extends ApiException {
// public UnauthorizedException() {}
//
// public UnauthorizedException(String message) {
// super(message);
// }
// }
| import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import nl.q42.jue.HttpClient.Result;
import nl.q42.jue.exceptions.ApiException;
import nl.q42.jue.exceptions.DeviceOffException;
import nl.q42.jue.exceptions.EntityNotAvailableException;
import nl.q42.jue.exceptions.GroupTableFullException;
import nl.q42.jue.exceptions.InvalidCommandException;
import nl.q42.jue.exceptions.LinkButtonException;
import nl.q42.jue.exceptions.UnauthorizedException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser; | package nl.q42.jue;
/**
* Representation of a connection with a Hue bridge.
*/
public class HueBridge {
private final static String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss";
private String ip;
private String username;
private Gson gson = new GsonBuilder().setDateFormat(DATE_FORMAT).create();
private HttpClient http = new HttpClient();
/**
* Connect with a bridge as a new user.
* @param ip ip address of bridge
*/
public HueBridge(String ip) {
this.ip = ip;
}
/**
* Connect with a bridge as an existing user.
*
* The username is verified by requesting the list of lights.
* Use the ip only constructor and authenticate() function if
* you don't want to connect right now.
* @param ip ip address of bridge
* @param username username to authenticate with
*/
public HueBridge(String ip, String username) throws IOException, ApiException {
this.ip = ip;
authenticate(username);
}
/**
* Set the connect and read timeout for HTTP requests.
* @param timeout timeout in milliseconds or 0 for indefinitely
*/
public void setTimeout(int timeout) {
http.setTimeout(timeout);
}
/**
* Returns the IP address of the bridge.
* @return ip address of bridge
*/
public String getIPAddress() {
return ip;
}
/**
* Returns the username currently authenticated with or null if there isn't one.
* @return username or null
*/
public String getUsername() {
return username;
}
/**
* Returns if authentication was successful on the bridge.
* @return true if authenticated on the bridge, false otherwise
*/
public boolean isAuthenticated() {
return getUsername() != null;
}
/**
* Returns a list of lights known to the bridge.
* @return list of known lights
* @throws UnauthorizedException thrown if the user no longer exists
*/
public List<Light> getLights() throws IOException, ApiException {
requireAuthentication();
| // Path: jue/src/nl/q42/jue/HttpClient.java
// public static class Result {
// private String body;
// private int responseCode;
//
// public Result(String body, int responseCode) {
// this.body = body;
// this.responseCode = responseCode;
// }
//
// public String getBody() {
// return body;
// }
//
// public int getResponseCode() {
// return responseCode;
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/ApiException.java
// @SuppressWarnings("serial")
// public class ApiException extends Exception {
// public ApiException() {}
//
// public ApiException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/DeviceOffException.java
// @SuppressWarnings("serial")
// public class DeviceOffException extends ApiException {
// public DeviceOffException() {}
//
// public DeviceOffException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/EntityNotAvailableException.java
// @SuppressWarnings("serial")
// public class EntityNotAvailableException extends ApiException {
// public EntityNotAvailableException() {}
//
// public EntityNotAvailableException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/GroupTableFullException.java
// @SuppressWarnings("serial")
// public class GroupTableFullException extends ApiException {
// public GroupTableFullException() {}
//
// public GroupTableFullException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/InvalidCommandException.java
// @SuppressWarnings("serial")
// public class InvalidCommandException extends ApiException {
// public InvalidCommandException() {}
//
// public InvalidCommandException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/LinkButtonException.java
// @SuppressWarnings("serial")
// public class LinkButtonException extends ApiException {
// public LinkButtonException() {}
//
// public LinkButtonException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/UnauthorizedException.java
// @SuppressWarnings("serial")
// public class UnauthorizedException extends ApiException {
// public UnauthorizedException() {}
//
// public UnauthorizedException(String message) {
// super(message);
// }
// }
// Path: jue/src/nl/q42/jue/HueBridge.java
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import nl.q42.jue.HttpClient.Result;
import nl.q42.jue.exceptions.ApiException;
import nl.q42.jue.exceptions.DeviceOffException;
import nl.q42.jue.exceptions.EntityNotAvailableException;
import nl.q42.jue.exceptions.GroupTableFullException;
import nl.q42.jue.exceptions.InvalidCommandException;
import nl.q42.jue.exceptions.LinkButtonException;
import nl.q42.jue.exceptions.UnauthorizedException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
package nl.q42.jue;
/**
* Representation of a connection with a Hue bridge.
*/
public class HueBridge {
private final static String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss";
private String ip;
private String username;
private Gson gson = new GsonBuilder().setDateFormat(DATE_FORMAT).create();
private HttpClient http = new HttpClient();
/**
* Connect with a bridge as a new user.
* @param ip ip address of bridge
*/
public HueBridge(String ip) {
this.ip = ip;
}
/**
* Connect with a bridge as an existing user.
*
* The username is verified by requesting the list of lights.
* Use the ip only constructor and authenticate() function if
* you don't want to connect right now.
* @param ip ip address of bridge
* @param username username to authenticate with
*/
public HueBridge(String ip, String username) throws IOException, ApiException {
this.ip = ip;
authenticate(username);
}
/**
* Set the connect and read timeout for HTTP requests.
* @param timeout timeout in milliseconds or 0 for indefinitely
*/
public void setTimeout(int timeout) {
http.setTimeout(timeout);
}
/**
* Returns the IP address of the bridge.
* @return ip address of bridge
*/
public String getIPAddress() {
return ip;
}
/**
* Returns the username currently authenticated with or null if there isn't one.
* @return username or null
*/
public String getUsername() {
return username;
}
/**
* Returns if authentication was successful on the bridge.
* @return true if authenticated on the bridge, false otherwise
*/
public boolean isAuthenticated() {
return getUsername() != null;
}
/**
* Returns a list of lights known to the bridge.
* @return list of known lights
* @throws UnauthorizedException thrown if the user no longer exists
*/
public List<Light> getLights() throws IOException, ApiException {
requireAuthentication();
| Result result = http.get(getRelativeURL("lights")); |
Q42/Jue | jue/src/nl/q42/jue/HueBridge.java | // Path: jue/src/nl/q42/jue/HttpClient.java
// public static class Result {
// private String body;
// private int responseCode;
//
// public Result(String body, int responseCode) {
// this.body = body;
// this.responseCode = responseCode;
// }
//
// public String getBody() {
// return body;
// }
//
// public int getResponseCode() {
// return responseCode;
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/ApiException.java
// @SuppressWarnings("serial")
// public class ApiException extends Exception {
// public ApiException() {}
//
// public ApiException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/DeviceOffException.java
// @SuppressWarnings("serial")
// public class DeviceOffException extends ApiException {
// public DeviceOffException() {}
//
// public DeviceOffException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/EntityNotAvailableException.java
// @SuppressWarnings("serial")
// public class EntityNotAvailableException extends ApiException {
// public EntityNotAvailableException() {}
//
// public EntityNotAvailableException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/GroupTableFullException.java
// @SuppressWarnings("serial")
// public class GroupTableFullException extends ApiException {
// public GroupTableFullException() {}
//
// public GroupTableFullException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/InvalidCommandException.java
// @SuppressWarnings("serial")
// public class InvalidCommandException extends ApiException {
// public InvalidCommandException() {}
//
// public InvalidCommandException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/LinkButtonException.java
// @SuppressWarnings("serial")
// public class LinkButtonException extends ApiException {
// public LinkButtonException() {}
//
// public LinkButtonException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/UnauthorizedException.java
// @SuppressWarnings("serial")
// public class UnauthorizedException extends ApiException {
// public UnauthorizedException() {}
//
// public UnauthorizedException(String message) {
// super(message);
// }
// }
| import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import nl.q42.jue.HttpClient.Result;
import nl.q42.jue.exceptions.ApiException;
import nl.q42.jue.exceptions.DeviceOffException;
import nl.q42.jue.exceptions.EntityNotAvailableException;
import nl.q42.jue.exceptions.GroupTableFullException;
import nl.q42.jue.exceptions.InvalidCommandException;
import nl.q42.jue.exceptions.LinkButtonException;
import nl.q42.jue.exceptions.UnauthorizedException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser; |
private ScheduleCommand scheduleCommand = null;
private ScheduleCommand handleCommandCallback(ScheduleCallback callback) throws ApiException {
// Temporarily reroute requests to a fake HTTP client
HttpClient realClient = http;
http = new HttpClient() {
@Override
protected Result doNetwork(String address, String requestMethod, String body) throws IOException {
// GET requests cannot be scheduled, so will continue working normally for convenience
if (requestMethod.equals("GET")) {
return super.doNetwork(address, requestMethod, body);
} else {
address = Util.quickMatch("^http://[^/]+(.+)$", address);
JsonElement commandBody = new JsonParser().parse(body);
scheduleCommand = new ScheduleCommand(address, requestMethod, commandBody);
// Return a fake result that will cause an exception and the callback to end
return new Result(null, 405);
}
}
};
// Run command
try {
scheduleCommand = null;
callback.onScheduleCommand(this);
} catch (IOException e) {
// Command will automatically fail to return a result because of deferred execution
} finally {
if (scheduleCommand != null && Util.stringSize(scheduleCommand.getBody()) > 90) { | // Path: jue/src/nl/q42/jue/HttpClient.java
// public static class Result {
// private String body;
// private int responseCode;
//
// public Result(String body, int responseCode) {
// this.body = body;
// this.responseCode = responseCode;
// }
//
// public String getBody() {
// return body;
// }
//
// public int getResponseCode() {
// return responseCode;
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/ApiException.java
// @SuppressWarnings("serial")
// public class ApiException extends Exception {
// public ApiException() {}
//
// public ApiException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/DeviceOffException.java
// @SuppressWarnings("serial")
// public class DeviceOffException extends ApiException {
// public DeviceOffException() {}
//
// public DeviceOffException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/EntityNotAvailableException.java
// @SuppressWarnings("serial")
// public class EntityNotAvailableException extends ApiException {
// public EntityNotAvailableException() {}
//
// public EntityNotAvailableException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/GroupTableFullException.java
// @SuppressWarnings("serial")
// public class GroupTableFullException extends ApiException {
// public GroupTableFullException() {}
//
// public GroupTableFullException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/InvalidCommandException.java
// @SuppressWarnings("serial")
// public class InvalidCommandException extends ApiException {
// public InvalidCommandException() {}
//
// public InvalidCommandException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/LinkButtonException.java
// @SuppressWarnings("serial")
// public class LinkButtonException extends ApiException {
// public LinkButtonException() {}
//
// public LinkButtonException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/UnauthorizedException.java
// @SuppressWarnings("serial")
// public class UnauthorizedException extends ApiException {
// public UnauthorizedException() {}
//
// public UnauthorizedException(String message) {
// super(message);
// }
// }
// Path: jue/src/nl/q42/jue/HueBridge.java
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import nl.q42.jue.HttpClient.Result;
import nl.q42.jue.exceptions.ApiException;
import nl.q42.jue.exceptions.DeviceOffException;
import nl.q42.jue.exceptions.EntityNotAvailableException;
import nl.q42.jue.exceptions.GroupTableFullException;
import nl.q42.jue.exceptions.InvalidCommandException;
import nl.q42.jue.exceptions.LinkButtonException;
import nl.q42.jue.exceptions.UnauthorizedException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
private ScheduleCommand scheduleCommand = null;
private ScheduleCommand handleCommandCallback(ScheduleCallback callback) throws ApiException {
// Temporarily reroute requests to a fake HTTP client
HttpClient realClient = http;
http = new HttpClient() {
@Override
protected Result doNetwork(String address, String requestMethod, String body) throws IOException {
// GET requests cannot be scheduled, so will continue working normally for convenience
if (requestMethod.equals("GET")) {
return super.doNetwork(address, requestMethod, body);
} else {
address = Util.quickMatch("^http://[^/]+(.+)$", address);
JsonElement commandBody = new JsonParser().parse(body);
scheduleCommand = new ScheduleCommand(address, requestMethod, commandBody);
// Return a fake result that will cause an exception and the callback to end
return new Result(null, 405);
}
}
};
// Run command
try {
scheduleCommand = null;
callback.onScheduleCommand(this);
} catch (IOException e) {
// Command will automatically fail to return a result because of deferred execution
} finally {
if (scheduleCommand != null && Util.stringSize(scheduleCommand.getBody()) > 90) { | throw new InvalidCommandException("Commmand body is larger than 90 bytes"); |
Q42/Jue | jue/src/nl/q42/jue/HueBridge.java | // Path: jue/src/nl/q42/jue/HttpClient.java
// public static class Result {
// private String body;
// private int responseCode;
//
// public Result(String body, int responseCode) {
// this.body = body;
// this.responseCode = responseCode;
// }
//
// public String getBody() {
// return body;
// }
//
// public int getResponseCode() {
// return responseCode;
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/ApiException.java
// @SuppressWarnings("serial")
// public class ApiException extends Exception {
// public ApiException() {}
//
// public ApiException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/DeviceOffException.java
// @SuppressWarnings("serial")
// public class DeviceOffException extends ApiException {
// public DeviceOffException() {}
//
// public DeviceOffException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/EntityNotAvailableException.java
// @SuppressWarnings("serial")
// public class EntityNotAvailableException extends ApiException {
// public EntityNotAvailableException() {}
//
// public EntityNotAvailableException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/GroupTableFullException.java
// @SuppressWarnings("serial")
// public class GroupTableFullException extends ApiException {
// public GroupTableFullException() {}
//
// public GroupTableFullException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/InvalidCommandException.java
// @SuppressWarnings("serial")
// public class InvalidCommandException extends ApiException {
// public InvalidCommandException() {}
//
// public InvalidCommandException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/LinkButtonException.java
// @SuppressWarnings("serial")
// public class LinkButtonException extends ApiException {
// public LinkButtonException() {}
//
// public LinkButtonException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/UnauthorizedException.java
// @SuppressWarnings("serial")
// public class UnauthorizedException extends ApiException {
// public UnauthorizedException() {}
//
// public UnauthorizedException(String message) {
// super(message);
// }
// }
| import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import nl.q42.jue.HttpClient.Result;
import nl.q42.jue.exceptions.ApiException;
import nl.q42.jue.exceptions.DeviceOffException;
import nl.q42.jue.exceptions.EntityNotAvailableException;
import nl.q42.jue.exceptions.GroupTableFullException;
import nl.q42.jue.exceptions.InvalidCommandException;
import nl.q42.jue.exceptions.LinkButtonException;
import nl.q42.jue.exceptions.UnauthorizedException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser; | }
/**
* Delete a schedule.
* @param schedule schedule
* @throws UnauthorizedException thrown if the user no longer exists
* @throws EntityNotAvailableException thrown if the schedule no longer exists
*/
public void deleteSchedule(Schedule schedule) throws IOException, ApiException {
requireAuthentication();
Result result = http.delete(getRelativeURL("schedules/" + enc(schedule.getId())));
handleErrors(result);
}
/**
* Authenticate on the bridge as the specified user.
* This function verifies that the specified username is valid and will use
* it for subsequent requests if it is, otherwise an UnauthorizedException
* is thrown and the internal username is not changed.
* @param username username to authenticate
* @throws UnauthorizedException thrown if authentication failed
*/
public void authenticate(String username) throws IOException, ApiException {
try {
this.username = username;
getLights();
} catch (Exception e) {
this.username = null; | // Path: jue/src/nl/q42/jue/HttpClient.java
// public static class Result {
// private String body;
// private int responseCode;
//
// public Result(String body, int responseCode) {
// this.body = body;
// this.responseCode = responseCode;
// }
//
// public String getBody() {
// return body;
// }
//
// public int getResponseCode() {
// return responseCode;
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/ApiException.java
// @SuppressWarnings("serial")
// public class ApiException extends Exception {
// public ApiException() {}
//
// public ApiException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/DeviceOffException.java
// @SuppressWarnings("serial")
// public class DeviceOffException extends ApiException {
// public DeviceOffException() {}
//
// public DeviceOffException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/EntityNotAvailableException.java
// @SuppressWarnings("serial")
// public class EntityNotAvailableException extends ApiException {
// public EntityNotAvailableException() {}
//
// public EntityNotAvailableException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/GroupTableFullException.java
// @SuppressWarnings("serial")
// public class GroupTableFullException extends ApiException {
// public GroupTableFullException() {}
//
// public GroupTableFullException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/InvalidCommandException.java
// @SuppressWarnings("serial")
// public class InvalidCommandException extends ApiException {
// public InvalidCommandException() {}
//
// public InvalidCommandException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/LinkButtonException.java
// @SuppressWarnings("serial")
// public class LinkButtonException extends ApiException {
// public LinkButtonException() {}
//
// public LinkButtonException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/UnauthorizedException.java
// @SuppressWarnings("serial")
// public class UnauthorizedException extends ApiException {
// public UnauthorizedException() {}
//
// public UnauthorizedException(String message) {
// super(message);
// }
// }
// Path: jue/src/nl/q42/jue/HueBridge.java
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import nl.q42.jue.HttpClient.Result;
import nl.q42.jue.exceptions.ApiException;
import nl.q42.jue.exceptions.DeviceOffException;
import nl.q42.jue.exceptions.EntityNotAvailableException;
import nl.q42.jue.exceptions.GroupTableFullException;
import nl.q42.jue.exceptions.InvalidCommandException;
import nl.q42.jue.exceptions.LinkButtonException;
import nl.q42.jue.exceptions.UnauthorizedException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
}
/**
* Delete a schedule.
* @param schedule schedule
* @throws UnauthorizedException thrown if the user no longer exists
* @throws EntityNotAvailableException thrown if the schedule no longer exists
*/
public void deleteSchedule(Schedule schedule) throws IOException, ApiException {
requireAuthentication();
Result result = http.delete(getRelativeURL("schedules/" + enc(schedule.getId())));
handleErrors(result);
}
/**
* Authenticate on the bridge as the specified user.
* This function verifies that the specified username is valid and will use
* it for subsequent requests if it is, otherwise an UnauthorizedException
* is thrown and the internal username is not changed.
* @param username username to authenticate
* @throws UnauthorizedException thrown if authentication failed
*/
public void authenticate(String username) throws IOException, ApiException {
try {
this.username = username;
getLights();
} catch (Exception e) {
this.username = null; | throw new UnauthorizedException(e.toString()); |
Q42/Jue | jue/src/nl/q42/jue/HueBridge.java | // Path: jue/src/nl/q42/jue/HttpClient.java
// public static class Result {
// private String body;
// private int responseCode;
//
// public Result(String body, int responseCode) {
// this.body = body;
// this.responseCode = responseCode;
// }
//
// public String getBody() {
// return body;
// }
//
// public int getResponseCode() {
// return responseCode;
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/ApiException.java
// @SuppressWarnings("serial")
// public class ApiException extends Exception {
// public ApiException() {}
//
// public ApiException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/DeviceOffException.java
// @SuppressWarnings("serial")
// public class DeviceOffException extends ApiException {
// public DeviceOffException() {}
//
// public DeviceOffException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/EntityNotAvailableException.java
// @SuppressWarnings("serial")
// public class EntityNotAvailableException extends ApiException {
// public EntityNotAvailableException() {}
//
// public EntityNotAvailableException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/GroupTableFullException.java
// @SuppressWarnings("serial")
// public class GroupTableFullException extends ApiException {
// public GroupTableFullException() {}
//
// public GroupTableFullException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/InvalidCommandException.java
// @SuppressWarnings("serial")
// public class InvalidCommandException extends ApiException {
// public InvalidCommandException() {}
//
// public InvalidCommandException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/LinkButtonException.java
// @SuppressWarnings("serial")
// public class LinkButtonException extends ApiException {
// public LinkButtonException() {}
//
// public LinkButtonException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/UnauthorizedException.java
// @SuppressWarnings("serial")
// public class UnauthorizedException extends ApiException {
// public UnauthorizedException() {}
//
// public UnauthorizedException(String message) {
// super(message);
// }
// }
| import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import nl.q42.jue.HttpClient.Result;
import nl.q42.jue.exceptions.ApiException;
import nl.q42.jue.exceptions.DeviceOffException;
import nl.q42.jue.exceptions.EntityNotAvailableException;
import nl.q42.jue.exceptions.GroupTableFullException;
import nl.q42.jue.exceptions.InvalidCommandException;
import nl.q42.jue.exceptions.LinkButtonException;
import nl.q42.jue.exceptions.UnauthorizedException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser; | try {
return gson.fromJson(json, typeOfT);
} catch (JsonParseException e) {
throw new ApiException("API returned unexpected result: " + e.getMessage());
}
}
private <T> T safeFromJson(String json, Class<T> classOfT) throws ApiException {
try {
return gson.fromJson(json, classOfT);
} catch (JsonParseException e) {
throw new ApiException("API returned unexpected result: " + e.getMessage());
}
}
// Used as assert in all requests to elegantly catch common errors
private void handleErrors(Result result) throws IOException, ApiException {
if (result.getResponseCode() != 200) {
throw new IOException();
} else {
try {
List<ErrorResponse> errors = gson.fromJson(result.getBody(), ErrorResponse.gsonType);
if (errors == null) return;
for (ErrorResponse error : errors) {
switch (error.getType()) {
case 1:
username = null;
throw new UnauthorizedException(error.getDescription());
case 3: | // Path: jue/src/nl/q42/jue/HttpClient.java
// public static class Result {
// private String body;
// private int responseCode;
//
// public Result(String body, int responseCode) {
// this.body = body;
// this.responseCode = responseCode;
// }
//
// public String getBody() {
// return body;
// }
//
// public int getResponseCode() {
// return responseCode;
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/ApiException.java
// @SuppressWarnings("serial")
// public class ApiException extends Exception {
// public ApiException() {}
//
// public ApiException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/DeviceOffException.java
// @SuppressWarnings("serial")
// public class DeviceOffException extends ApiException {
// public DeviceOffException() {}
//
// public DeviceOffException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/EntityNotAvailableException.java
// @SuppressWarnings("serial")
// public class EntityNotAvailableException extends ApiException {
// public EntityNotAvailableException() {}
//
// public EntityNotAvailableException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/GroupTableFullException.java
// @SuppressWarnings("serial")
// public class GroupTableFullException extends ApiException {
// public GroupTableFullException() {}
//
// public GroupTableFullException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/InvalidCommandException.java
// @SuppressWarnings("serial")
// public class InvalidCommandException extends ApiException {
// public InvalidCommandException() {}
//
// public InvalidCommandException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/LinkButtonException.java
// @SuppressWarnings("serial")
// public class LinkButtonException extends ApiException {
// public LinkButtonException() {}
//
// public LinkButtonException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/UnauthorizedException.java
// @SuppressWarnings("serial")
// public class UnauthorizedException extends ApiException {
// public UnauthorizedException() {}
//
// public UnauthorizedException(String message) {
// super(message);
// }
// }
// Path: jue/src/nl/q42/jue/HueBridge.java
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import nl.q42.jue.HttpClient.Result;
import nl.q42.jue.exceptions.ApiException;
import nl.q42.jue.exceptions.DeviceOffException;
import nl.q42.jue.exceptions.EntityNotAvailableException;
import nl.q42.jue.exceptions.GroupTableFullException;
import nl.q42.jue.exceptions.InvalidCommandException;
import nl.q42.jue.exceptions.LinkButtonException;
import nl.q42.jue.exceptions.UnauthorizedException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
try {
return gson.fromJson(json, typeOfT);
} catch (JsonParseException e) {
throw new ApiException("API returned unexpected result: " + e.getMessage());
}
}
private <T> T safeFromJson(String json, Class<T> classOfT) throws ApiException {
try {
return gson.fromJson(json, classOfT);
} catch (JsonParseException e) {
throw new ApiException("API returned unexpected result: " + e.getMessage());
}
}
// Used as assert in all requests to elegantly catch common errors
private void handleErrors(Result result) throws IOException, ApiException {
if (result.getResponseCode() != 200) {
throw new IOException();
} else {
try {
List<ErrorResponse> errors = gson.fromJson(result.getBody(), ErrorResponse.gsonType);
if (errors == null) return;
for (ErrorResponse error : errors) {
switch (error.getType()) {
case 1:
username = null;
throw new UnauthorizedException(error.getDescription());
case 3: | throw new EntityNotAvailableException(error.getDescription()); |
Q42/Jue | jue/src/nl/q42/jue/HueBridge.java | // Path: jue/src/nl/q42/jue/HttpClient.java
// public static class Result {
// private String body;
// private int responseCode;
//
// public Result(String body, int responseCode) {
// this.body = body;
// this.responseCode = responseCode;
// }
//
// public String getBody() {
// return body;
// }
//
// public int getResponseCode() {
// return responseCode;
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/ApiException.java
// @SuppressWarnings("serial")
// public class ApiException extends Exception {
// public ApiException() {}
//
// public ApiException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/DeviceOffException.java
// @SuppressWarnings("serial")
// public class DeviceOffException extends ApiException {
// public DeviceOffException() {}
//
// public DeviceOffException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/EntityNotAvailableException.java
// @SuppressWarnings("serial")
// public class EntityNotAvailableException extends ApiException {
// public EntityNotAvailableException() {}
//
// public EntityNotAvailableException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/GroupTableFullException.java
// @SuppressWarnings("serial")
// public class GroupTableFullException extends ApiException {
// public GroupTableFullException() {}
//
// public GroupTableFullException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/InvalidCommandException.java
// @SuppressWarnings("serial")
// public class InvalidCommandException extends ApiException {
// public InvalidCommandException() {}
//
// public InvalidCommandException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/LinkButtonException.java
// @SuppressWarnings("serial")
// public class LinkButtonException extends ApiException {
// public LinkButtonException() {}
//
// public LinkButtonException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/UnauthorizedException.java
// @SuppressWarnings("serial")
// public class UnauthorizedException extends ApiException {
// public UnauthorizedException() {}
//
// public UnauthorizedException(String message) {
// super(message);
// }
// }
| import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import nl.q42.jue.HttpClient.Result;
import nl.q42.jue.exceptions.ApiException;
import nl.q42.jue.exceptions.DeviceOffException;
import nl.q42.jue.exceptions.EntityNotAvailableException;
import nl.q42.jue.exceptions.GroupTableFullException;
import nl.q42.jue.exceptions.InvalidCommandException;
import nl.q42.jue.exceptions.LinkButtonException;
import nl.q42.jue.exceptions.UnauthorizedException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser; | }
}
private <T> T safeFromJson(String json, Class<T> classOfT) throws ApiException {
try {
return gson.fromJson(json, classOfT);
} catch (JsonParseException e) {
throw new ApiException("API returned unexpected result: " + e.getMessage());
}
}
// Used as assert in all requests to elegantly catch common errors
private void handleErrors(Result result) throws IOException, ApiException {
if (result.getResponseCode() != 200) {
throw new IOException();
} else {
try {
List<ErrorResponse> errors = gson.fromJson(result.getBody(), ErrorResponse.gsonType);
if (errors == null) return;
for (ErrorResponse error : errors) {
switch (error.getType()) {
case 1:
username = null;
throw new UnauthorizedException(error.getDescription());
case 3:
throw new EntityNotAvailableException(error.getDescription());
case 7:
throw new InvalidCommandException(error.getDescription());
case 101: | // Path: jue/src/nl/q42/jue/HttpClient.java
// public static class Result {
// private String body;
// private int responseCode;
//
// public Result(String body, int responseCode) {
// this.body = body;
// this.responseCode = responseCode;
// }
//
// public String getBody() {
// return body;
// }
//
// public int getResponseCode() {
// return responseCode;
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/ApiException.java
// @SuppressWarnings("serial")
// public class ApiException extends Exception {
// public ApiException() {}
//
// public ApiException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/DeviceOffException.java
// @SuppressWarnings("serial")
// public class DeviceOffException extends ApiException {
// public DeviceOffException() {}
//
// public DeviceOffException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/EntityNotAvailableException.java
// @SuppressWarnings("serial")
// public class EntityNotAvailableException extends ApiException {
// public EntityNotAvailableException() {}
//
// public EntityNotAvailableException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/GroupTableFullException.java
// @SuppressWarnings("serial")
// public class GroupTableFullException extends ApiException {
// public GroupTableFullException() {}
//
// public GroupTableFullException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/InvalidCommandException.java
// @SuppressWarnings("serial")
// public class InvalidCommandException extends ApiException {
// public InvalidCommandException() {}
//
// public InvalidCommandException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/LinkButtonException.java
// @SuppressWarnings("serial")
// public class LinkButtonException extends ApiException {
// public LinkButtonException() {}
//
// public LinkButtonException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/UnauthorizedException.java
// @SuppressWarnings("serial")
// public class UnauthorizedException extends ApiException {
// public UnauthorizedException() {}
//
// public UnauthorizedException(String message) {
// super(message);
// }
// }
// Path: jue/src/nl/q42/jue/HueBridge.java
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import nl.q42.jue.HttpClient.Result;
import nl.q42.jue.exceptions.ApiException;
import nl.q42.jue.exceptions.DeviceOffException;
import nl.q42.jue.exceptions.EntityNotAvailableException;
import nl.q42.jue.exceptions.GroupTableFullException;
import nl.q42.jue.exceptions.InvalidCommandException;
import nl.q42.jue.exceptions.LinkButtonException;
import nl.q42.jue.exceptions.UnauthorizedException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
}
}
private <T> T safeFromJson(String json, Class<T> classOfT) throws ApiException {
try {
return gson.fromJson(json, classOfT);
} catch (JsonParseException e) {
throw new ApiException("API returned unexpected result: " + e.getMessage());
}
}
// Used as assert in all requests to elegantly catch common errors
private void handleErrors(Result result) throws IOException, ApiException {
if (result.getResponseCode() != 200) {
throw new IOException();
} else {
try {
List<ErrorResponse> errors = gson.fromJson(result.getBody(), ErrorResponse.gsonType);
if (errors == null) return;
for (ErrorResponse error : errors) {
switch (error.getType()) {
case 1:
username = null;
throw new UnauthorizedException(error.getDescription());
case 3:
throw new EntityNotAvailableException(error.getDescription());
case 7:
throw new InvalidCommandException(error.getDescription());
case 101: | throw new LinkButtonException(error.getDescription()); |
Q42/Jue | jue/src/nl/q42/jue/HueBridge.java | // Path: jue/src/nl/q42/jue/HttpClient.java
// public static class Result {
// private String body;
// private int responseCode;
//
// public Result(String body, int responseCode) {
// this.body = body;
// this.responseCode = responseCode;
// }
//
// public String getBody() {
// return body;
// }
//
// public int getResponseCode() {
// return responseCode;
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/ApiException.java
// @SuppressWarnings("serial")
// public class ApiException extends Exception {
// public ApiException() {}
//
// public ApiException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/DeviceOffException.java
// @SuppressWarnings("serial")
// public class DeviceOffException extends ApiException {
// public DeviceOffException() {}
//
// public DeviceOffException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/EntityNotAvailableException.java
// @SuppressWarnings("serial")
// public class EntityNotAvailableException extends ApiException {
// public EntityNotAvailableException() {}
//
// public EntityNotAvailableException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/GroupTableFullException.java
// @SuppressWarnings("serial")
// public class GroupTableFullException extends ApiException {
// public GroupTableFullException() {}
//
// public GroupTableFullException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/InvalidCommandException.java
// @SuppressWarnings("serial")
// public class InvalidCommandException extends ApiException {
// public InvalidCommandException() {}
//
// public InvalidCommandException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/LinkButtonException.java
// @SuppressWarnings("serial")
// public class LinkButtonException extends ApiException {
// public LinkButtonException() {}
//
// public LinkButtonException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/UnauthorizedException.java
// @SuppressWarnings("serial")
// public class UnauthorizedException extends ApiException {
// public UnauthorizedException() {}
//
// public UnauthorizedException(String message) {
// super(message);
// }
// }
| import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import nl.q42.jue.HttpClient.Result;
import nl.q42.jue.exceptions.ApiException;
import nl.q42.jue.exceptions.DeviceOffException;
import nl.q42.jue.exceptions.EntityNotAvailableException;
import nl.q42.jue.exceptions.GroupTableFullException;
import nl.q42.jue.exceptions.InvalidCommandException;
import nl.q42.jue.exceptions.LinkButtonException;
import nl.q42.jue.exceptions.UnauthorizedException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser; |
private <T> T safeFromJson(String json, Class<T> classOfT) throws ApiException {
try {
return gson.fromJson(json, classOfT);
} catch (JsonParseException e) {
throw new ApiException("API returned unexpected result: " + e.getMessage());
}
}
// Used as assert in all requests to elegantly catch common errors
private void handleErrors(Result result) throws IOException, ApiException {
if (result.getResponseCode() != 200) {
throw new IOException();
} else {
try {
List<ErrorResponse> errors = gson.fromJson(result.getBody(), ErrorResponse.gsonType);
if (errors == null) return;
for (ErrorResponse error : errors) {
switch (error.getType()) {
case 1:
username = null;
throw new UnauthorizedException(error.getDescription());
case 3:
throw new EntityNotAvailableException(error.getDescription());
case 7:
throw new InvalidCommandException(error.getDescription());
case 101:
throw new LinkButtonException(error.getDescription());
case 201: | // Path: jue/src/nl/q42/jue/HttpClient.java
// public static class Result {
// private String body;
// private int responseCode;
//
// public Result(String body, int responseCode) {
// this.body = body;
// this.responseCode = responseCode;
// }
//
// public String getBody() {
// return body;
// }
//
// public int getResponseCode() {
// return responseCode;
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/ApiException.java
// @SuppressWarnings("serial")
// public class ApiException extends Exception {
// public ApiException() {}
//
// public ApiException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/DeviceOffException.java
// @SuppressWarnings("serial")
// public class DeviceOffException extends ApiException {
// public DeviceOffException() {}
//
// public DeviceOffException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/EntityNotAvailableException.java
// @SuppressWarnings("serial")
// public class EntityNotAvailableException extends ApiException {
// public EntityNotAvailableException() {}
//
// public EntityNotAvailableException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/GroupTableFullException.java
// @SuppressWarnings("serial")
// public class GroupTableFullException extends ApiException {
// public GroupTableFullException() {}
//
// public GroupTableFullException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/InvalidCommandException.java
// @SuppressWarnings("serial")
// public class InvalidCommandException extends ApiException {
// public InvalidCommandException() {}
//
// public InvalidCommandException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/LinkButtonException.java
// @SuppressWarnings("serial")
// public class LinkButtonException extends ApiException {
// public LinkButtonException() {}
//
// public LinkButtonException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/UnauthorizedException.java
// @SuppressWarnings("serial")
// public class UnauthorizedException extends ApiException {
// public UnauthorizedException() {}
//
// public UnauthorizedException(String message) {
// super(message);
// }
// }
// Path: jue/src/nl/q42/jue/HueBridge.java
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import nl.q42.jue.HttpClient.Result;
import nl.q42.jue.exceptions.ApiException;
import nl.q42.jue.exceptions.DeviceOffException;
import nl.q42.jue.exceptions.EntityNotAvailableException;
import nl.q42.jue.exceptions.GroupTableFullException;
import nl.q42.jue.exceptions.InvalidCommandException;
import nl.q42.jue.exceptions.LinkButtonException;
import nl.q42.jue.exceptions.UnauthorizedException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
private <T> T safeFromJson(String json, Class<T> classOfT) throws ApiException {
try {
return gson.fromJson(json, classOfT);
} catch (JsonParseException e) {
throw new ApiException("API returned unexpected result: " + e.getMessage());
}
}
// Used as assert in all requests to elegantly catch common errors
private void handleErrors(Result result) throws IOException, ApiException {
if (result.getResponseCode() != 200) {
throw new IOException();
} else {
try {
List<ErrorResponse> errors = gson.fromJson(result.getBody(), ErrorResponse.gsonType);
if (errors == null) return;
for (ErrorResponse error : errors) {
switch (error.getType()) {
case 1:
username = null;
throw new UnauthorizedException(error.getDescription());
case 3:
throw new EntityNotAvailableException(error.getDescription());
case 7:
throw new InvalidCommandException(error.getDescription());
case 101:
throw new LinkButtonException(error.getDescription());
case 201: | throw new DeviceOffException(error.getDescription()); |
Q42/Jue | jue/src/nl/q42/jue/HueBridge.java | // Path: jue/src/nl/q42/jue/HttpClient.java
// public static class Result {
// private String body;
// private int responseCode;
//
// public Result(String body, int responseCode) {
// this.body = body;
// this.responseCode = responseCode;
// }
//
// public String getBody() {
// return body;
// }
//
// public int getResponseCode() {
// return responseCode;
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/ApiException.java
// @SuppressWarnings("serial")
// public class ApiException extends Exception {
// public ApiException() {}
//
// public ApiException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/DeviceOffException.java
// @SuppressWarnings("serial")
// public class DeviceOffException extends ApiException {
// public DeviceOffException() {}
//
// public DeviceOffException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/EntityNotAvailableException.java
// @SuppressWarnings("serial")
// public class EntityNotAvailableException extends ApiException {
// public EntityNotAvailableException() {}
//
// public EntityNotAvailableException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/GroupTableFullException.java
// @SuppressWarnings("serial")
// public class GroupTableFullException extends ApiException {
// public GroupTableFullException() {}
//
// public GroupTableFullException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/InvalidCommandException.java
// @SuppressWarnings("serial")
// public class InvalidCommandException extends ApiException {
// public InvalidCommandException() {}
//
// public InvalidCommandException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/LinkButtonException.java
// @SuppressWarnings("serial")
// public class LinkButtonException extends ApiException {
// public LinkButtonException() {}
//
// public LinkButtonException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/UnauthorizedException.java
// @SuppressWarnings("serial")
// public class UnauthorizedException extends ApiException {
// public UnauthorizedException() {}
//
// public UnauthorizedException(String message) {
// super(message);
// }
// }
| import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import nl.q42.jue.HttpClient.Result;
import nl.q42.jue.exceptions.ApiException;
import nl.q42.jue.exceptions.DeviceOffException;
import nl.q42.jue.exceptions.EntityNotAvailableException;
import nl.q42.jue.exceptions.GroupTableFullException;
import nl.q42.jue.exceptions.InvalidCommandException;
import nl.q42.jue.exceptions.LinkButtonException;
import nl.q42.jue.exceptions.UnauthorizedException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser; | try {
return gson.fromJson(json, classOfT);
} catch (JsonParseException e) {
throw new ApiException("API returned unexpected result: " + e.getMessage());
}
}
// Used as assert in all requests to elegantly catch common errors
private void handleErrors(Result result) throws IOException, ApiException {
if (result.getResponseCode() != 200) {
throw new IOException();
} else {
try {
List<ErrorResponse> errors = gson.fromJson(result.getBody(), ErrorResponse.gsonType);
if (errors == null) return;
for (ErrorResponse error : errors) {
switch (error.getType()) {
case 1:
username = null;
throw new UnauthorizedException(error.getDescription());
case 3:
throw new EntityNotAvailableException(error.getDescription());
case 7:
throw new InvalidCommandException(error.getDescription());
case 101:
throw new LinkButtonException(error.getDescription());
case 201:
throw new DeviceOffException(error.getDescription());
case 301: | // Path: jue/src/nl/q42/jue/HttpClient.java
// public static class Result {
// private String body;
// private int responseCode;
//
// public Result(String body, int responseCode) {
// this.body = body;
// this.responseCode = responseCode;
// }
//
// public String getBody() {
// return body;
// }
//
// public int getResponseCode() {
// return responseCode;
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/ApiException.java
// @SuppressWarnings("serial")
// public class ApiException extends Exception {
// public ApiException() {}
//
// public ApiException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/DeviceOffException.java
// @SuppressWarnings("serial")
// public class DeviceOffException extends ApiException {
// public DeviceOffException() {}
//
// public DeviceOffException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/EntityNotAvailableException.java
// @SuppressWarnings("serial")
// public class EntityNotAvailableException extends ApiException {
// public EntityNotAvailableException() {}
//
// public EntityNotAvailableException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/GroupTableFullException.java
// @SuppressWarnings("serial")
// public class GroupTableFullException extends ApiException {
// public GroupTableFullException() {}
//
// public GroupTableFullException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/InvalidCommandException.java
// @SuppressWarnings("serial")
// public class InvalidCommandException extends ApiException {
// public InvalidCommandException() {}
//
// public InvalidCommandException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/LinkButtonException.java
// @SuppressWarnings("serial")
// public class LinkButtonException extends ApiException {
// public LinkButtonException() {}
//
// public LinkButtonException(String message) {
// super(message);
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/UnauthorizedException.java
// @SuppressWarnings("serial")
// public class UnauthorizedException extends ApiException {
// public UnauthorizedException() {}
//
// public UnauthorizedException(String message) {
// super(message);
// }
// }
// Path: jue/src/nl/q42/jue/HueBridge.java
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import nl.q42.jue.HttpClient.Result;
import nl.q42.jue.exceptions.ApiException;
import nl.q42.jue.exceptions.DeviceOffException;
import nl.q42.jue.exceptions.EntityNotAvailableException;
import nl.q42.jue.exceptions.GroupTableFullException;
import nl.q42.jue.exceptions.InvalidCommandException;
import nl.q42.jue.exceptions.LinkButtonException;
import nl.q42.jue.exceptions.UnauthorizedException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
try {
return gson.fromJson(json, classOfT);
} catch (JsonParseException e) {
throw new ApiException("API returned unexpected result: " + e.getMessage());
}
}
// Used as assert in all requests to elegantly catch common errors
private void handleErrors(Result result) throws IOException, ApiException {
if (result.getResponseCode() != 200) {
throw new IOException();
} else {
try {
List<ErrorResponse> errors = gson.fromJson(result.getBody(), ErrorResponse.gsonType);
if (errors == null) return;
for (ErrorResponse error : errors) {
switch (error.getType()) {
case 1:
username = null;
throw new UnauthorizedException(error.getDescription());
case 3:
throw new EntityNotAvailableException(error.getDescription());
case 7:
throw new InvalidCommandException(error.getDescription());
case 101:
throw new LinkButtonException(error.getDescription());
case 201:
throw new DeviceOffException(error.getDescription());
case 301: | throw new GroupTableFullException(error.getDescription()); |
Q42/Jue | jue/src/nl/q42/jue/BridgeDiscovery.java | // Path: jue/src/nl/q42/jue/HttpClient.java
// public static class Result {
// private String body;
// private int responseCode;
//
// public Result(String body, int responseCode) {
// this.body = body;
// this.responseCode = responseCode;
// }
//
// public String getBody() {
// return body;
// }
//
// public int getResponseCode() {
// return responseCode;
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/ApiException.java
// @SuppressWarnings("serial")
// public class ApiException extends Exception {
// public ApiException() {}
//
// public ApiException(String message) {
// super(message);
// }
// }
| import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import nl.q42.jue.HttpClient.Result;
import nl.q42.jue.exceptions.ApiException;
import com.google.gson.Gson; | upnpSock.receive(responsePacket);
} catch (SocketTimeoutException e) {
if (System.currentTimeMillis() - start > timeout) {
break;
} else {
continue;
}
}
final String ip = responsePacket.getAddress().getHostAddress();
final String response = new String(responsePacket.getData());
if (!ips.contains(ip)) {
Matcher m = Pattern.compile("LOCATION: (.*)", Pattern.CASE_INSENSITIVE).matcher(response);
if (m.find()) {
final String description = new HttpClient().get(m.group(1)).getBody();
// Parsing with RegEx allowed here because the output format is fairly strict
final String modelName = Util.quickMatch("<modelName>(.*?)</modelName>", description);
// Check from description if we're dealing with a hue bridge or some other device
if (modelName.toLowerCase().contains("philips hue bridge")) {
try {
final HueBridge bridgeToBe = new HueBridge(ip);
bridgeToBe.getConfig();
bridges.add(bridgeToBe);
if (callback != null) callback.onBridgeDiscovered(bridgeToBe); | // Path: jue/src/nl/q42/jue/HttpClient.java
// public static class Result {
// private String body;
// private int responseCode;
//
// public Result(String body, int responseCode) {
// this.body = body;
// this.responseCode = responseCode;
// }
//
// public String getBody() {
// return body;
// }
//
// public int getResponseCode() {
// return responseCode;
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/ApiException.java
// @SuppressWarnings("serial")
// public class ApiException extends Exception {
// public ApiException() {}
//
// public ApiException(String message) {
// super(message);
// }
// }
// Path: jue/src/nl/q42/jue/BridgeDiscovery.java
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import nl.q42.jue.HttpClient.Result;
import nl.q42.jue.exceptions.ApiException;
import com.google.gson.Gson;
upnpSock.receive(responsePacket);
} catch (SocketTimeoutException e) {
if (System.currentTimeMillis() - start > timeout) {
break;
} else {
continue;
}
}
final String ip = responsePacket.getAddress().getHostAddress();
final String response = new String(responsePacket.getData());
if (!ips.contains(ip)) {
Matcher m = Pattern.compile("LOCATION: (.*)", Pattern.CASE_INSENSITIVE).matcher(response);
if (m.find()) {
final String description = new HttpClient().get(m.group(1)).getBody();
// Parsing with RegEx allowed here because the output format is fairly strict
final String modelName = Util.quickMatch("<modelName>(.*?)</modelName>", description);
// Check from description if we're dealing with a hue bridge or some other device
if (modelName.toLowerCase().contains("philips hue bridge")) {
try {
final HueBridge bridgeToBe = new HueBridge(ip);
bridgeToBe.getConfig();
bridges.add(bridgeToBe);
if (callback != null) callback.onBridgeDiscovered(bridgeToBe); | } catch (ApiException e) { |
Q42/Jue | jue/src/nl/q42/jue/BridgeDiscovery.java | // Path: jue/src/nl/q42/jue/HttpClient.java
// public static class Result {
// private String body;
// private int responseCode;
//
// public Result(String body, int responseCode) {
// this.body = body;
// this.responseCode = responseCode;
// }
//
// public String getBody() {
// return body;
// }
//
// public int getResponseCode() {
// return responseCode;
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/ApiException.java
// @SuppressWarnings("serial")
// public class ApiException extends Exception {
// public ApiException() {}
//
// public ApiException(String message) {
// super(message);
// }
// }
| import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import nl.q42.jue.HttpClient.Result;
import nl.q42.jue.exceptions.ApiException;
import com.google.gson.Gson; |
// Check from description if we're dealing with a hue bridge or some other device
if (modelName.toLowerCase().contains("philips hue bridge")) {
try {
final HueBridge bridgeToBe = new HueBridge(ip);
bridgeToBe.getConfig();
bridges.add(bridgeToBe);
if (callback != null) callback.onBridgeDiscovered(bridgeToBe);
} catch (ApiException e) {
// Do nothing, this basically serves as an extra check to see if it's really a hue bridge
}
}
}
// Ignore subsequent packets
ips.add(ip);
}
}
return bridges;
}
/**
* Search for local bridges using the portal API.
* See: http://developers.meethue.com/5_portalapi.html
* @return list of bridges
*/
public static List<HueBridge> searchPortal() throws IOException { | // Path: jue/src/nl/q42/jue/HttpClient.java
// public static class Result {
// private String body;
// private int responseCode;
//
// public Result(String body, int responseCode) {
// this.body = body;
// this.responseCode = responseCode;
// }
//
// public String getBody() {
// return body;
// }
//
// public int getResponseCode() {
// return responseCode;
// }
// }
//
// Path: jue/src/nl/q42/jue/exceptions/ApiException.java
// @SuppressWarnings("serial")
// public class ApiException extends Exception {
// public ApiException() {}
//
// public ApiException(String message) {
// super(message);
// }
// }
// Path: jue/src/nl/q42/jue/BridgeDiscovery.java
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import nl.q42.jue.HttpClient.Result;
import nl.q42.jue.exceptions.ApiException;
import com.google.gson.Gson;
// Check from description if we're dealing with a hue bridge or some other device
if (modelName.toLowerCase().contains("philips hue bridge")) {
try {
final HueBridge bridgeToBe = new HueBridge(ip);
bridgeToBe.getConfig();
bridges.add(bridgeToBe);
if (callback != null) callback.onBridgeDiscovered(bridgeToBe);
} catch (ApiException e) {
// Do nothing, this basically serves as an extra check to see if it's really a hue bridge
}
}
}
// Ignore subsequent packets
ips.add(ip);
}
}
return bridges;
}
/**
* Search for local bridges using the portal API.
* See: http://developers.meethue.com/5_portalapi.html
* @return list of bridges
*/
public static List<HueBridge> searchPortal() throws IOException { | Result result = new HttpClient().get("http://www.meethue.com/api/nupnp"); |
cytomine/Cytomine-java-client | src/main/java/be/cytomine/client/models/User.java | // Path: src/main/java/be/cytomine/client/CytomineException.java
// public class CytomineException extends Exception {
//
// private static final Logger log = LogManager.getLogger(CytomineException.class);
//
// int httpCode;
// String message = "";
//
// public CytomineException(Exception e) {
// super(e);
// this.message = e.getMessage();
// }
//
// public CytomineException(int httpCode, String message) {
// this.httpCode = httpCode;
// this.message = message;
// }
//
// public CytomineException(int httpCode, JSONObject json) {
// this.httpCode = httpCode;
// getMessage(json);
// }
//
// public int getHttpCode() {
// return this.httpCode;
// }
//
// public String getMsg() {
// return this.message;
// }
//
// private String getMessage(JSONObject json) {
// try {
// String msg = "";
// if (json != null) {
// Iterator iter = json.entrySet().iterator();
// while (iter.hasNext()) {
// Map.Entry entry = (Map.Entry) iter.next();
// msg = msg + entry.getValue();
// }
// }
// message = msg;
// } catch (Exception e) {
// log.error(e);
// }
// return message;
// }
//
// public String toString() {
// return httpCode + " " + message;
// }
// }
| import be.cytomine.client.CytomineException; | package be.cytomine.client.models;
/*
* Copyright (c) 2009-2020. Authors: see NOTICE file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public class User extends Model<User> {
public User(){}
public User(String username, String firstname, String lastname, String email, String password){
this.set("username", username);
this.set("firstname", firstname);
this.set("lastname", lastname);
this.set("email", email);
this.set("password", password);
}
| // Path: src/main/java/be/cytomine/client/CytomineException.java
// public class CytomineException extends Exception {
//
// private static final Logger log = LogManager.getLogger(CytomineException.class);
//
// int httpCode;
// String message = "";
//
// public CytomineException(Exception e) {
// super(e);
// this.message = e.getMessage();
// }
//
// public CytomineException(int httpCode, String message) {
// this.httpCode = httpCode;
// this.message = message;
// }
//
// public CytomineException(int httpCode, JSONObject json) {
// this.httpCode = httpCode;
// getMessage(json);
// }
//
// public int getHttpCode() {
// return this.httpCode;
// }
//
// public String getMsg() {
// return this.message;
// }
//
// private String getMessage(JSONObject json) {
// try {
// String msg = "";
// if (json != null) {
// Iterator iter = json.entrySet().iterator();
// while (iter.hasNext()) {
// Map.Entry entry = (Map.Entry) iter.next();
// msg = msg + entry.getValue();
// }
// }
// message = msg;
// } catch (Exception e) {
// log.error(e);
// }
// return message;
// }
//
// public String toString() {
// return httpCode + " " + message;
// }
// }
// Path: src/main/java/be/cytomine/client/models/User.java
import be.cytomine.client.CytomineException;
package be.cytomine.client.models;
/*
* Copyright (c) 2009-2020. Authors: see NOTICE file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public class User extends Model<User> {
public User(){}
public User(String username, String firstname, String lastname, String email, String password){
this.set("username", username);
this.set("firstname", firstname);
this.set("lastname", lastname);
this.set("email", email);
this.set("password", password);
}
| public static User getCurrent() throws CytomineException { |
cytomine/Cytomine-java-client | src/main/java/be/cytomine/client/collections/ReviewedAnnotationCollection.java | // Path: src/main/java/be/cytomine/client/CytomineException.java
// public class CytomineException extends Exception {
//
// private static final Logger log = LogManager.getLogger(CytomineException.class);
//
// int httpCode;
// String message = "";
//
// public CytomineException(Exception e) {
// super(e);
// this.message = e.getMessage();
// }
//
// public CytomineException(int httpCode, String message) {
// this.httpCode = httpCode;
// this.message = message;
// }
//
// public CytomineException(int httpCode, JSONObject json) {
// this.httpCode = httpCode;
// getMessage(json);
// }
//
// public int getHttpCode() {
// return this.httpCode;
// }
//
// public String getMsg() {
// return this.message;
// }
//
// private String getMessage(JSONObject json) {
// try {
// String msg = "";
// if (json != null) {
// Iterator iter = json.entrySet().iterator();
// while (iter.hasNext()) {
// Map.Entry entry = (Map.Entry) iter.next();
// msg = msg + entry.getValue();
// }
// }
// message = msg;
// } catch (Exception e) {
// log.error(e);
// }
// return message;
// }
//
// public String toString() {
// return httpCode + " " + message;
// }
// }
//
// Path: src/main/java/be/cytomine/client/models/ReviewedAnnotation.java
// public class ReviewedAnnotation extends Model<ReviewedAnnotation> {}
| import be.cytomine.client.CytomineException;
import be.cytomine.client.models.ReviewedAnnotation;
import org.json.simple.JSONObject; | package be.cytomine.client.collections;
/*
* Copyright (c) 2009-2020. Authors: see NOTICE file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public class ReviewedAnnotationCollection extends Collection<ReviewedAnnotation> {
public ReviewedAnnotationCollection(int offset, int max) {
super(ReviewedAnnotation.class, max, offset);
}
@Override | // Path: src/main/java/be/cytomine/client/CytomineException.java
// public class CytomineException extends Exception {
//
// private static final Logger log = LogManager.getLogger(CytomineException.class);
//
// int httpCode;
// String message = "";
//
// public CytomineException(Exception e) {
// super(e);
// this.message = e.getMessage();
// }
//
// public CytomineException(int httpCode, String message) {
// this.httpCode = httpCode;
// this.message = message;
// }
//
// public CytomineException(int httpCode, JSONObject json) {
// this.httpCode = httpCode;
// getMessage(json);
// }
//
// public int getHttpCode() {
// return this.httpCode;
// }
//
// public String getMsg() {
// return this.message;
// }
//
// private String getMessage(JSONObject json) {
// try {
// String msg = "";
// if (json != null) {
// Iterator iter = json.entrySet().iterator();
// while (iter.hasNext()) {
// Map.Entry entry = (Map.Entry) iter.next();
// msg = msg + entry.getValue();
// }
// }
// message = msg;
// } catch (Exception e) {
// log.error(e);
// }
// return message;
// }
//
// public String toString() {
// return httpCode + " " + message;
// }
// }
//
// Path: src/main/java/be/cytomine/client/models/ReviewedAnnotation.java
// public class ReviewedAnnotation extends Model<ReviewedAnnotation> {}
// Path: src/main/java/be/cytomine/client/collections/ReviewedAnnotationCollection.java
import be.cytomine.client.CytomineException;
import be.cytomine.client.models.ReviewedAnnotation;
import org.json.simple.JSONObject;
package be.cytomine.client.collections;
/*
* Copyright (c) 2009-2020. Authors: see NOTICE file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public class ReviewedAnnotationCollection extends Collection<ReviewedAnnotation> {
public ReviewedAnnotationCollection(int offset, int max) {
super(ReviewedAnnotation.class, max, offset);
}
@Override | protected String getJSONResourceURL() throws CytomineException { |
cytomine/Cytomine-java-client | src/main/java/be/cytomine/client/CytomineConnection.java | // Path: src/main/java/be/cytomine/client/models/User.java
// public class User extends Model<User> {
//
// public User(){}
// public User(String username, String firstname, String lastname, String email, String password){
// this.set("username", username);
// this.set("firstname", firstname);
// this.set("lastname", lastname);
// this.set("email", email);
// this.set("password", password);
// }
//
// public static User getCurrent() throws CytomineException {
// User user = new User();
// user.set("current", "current");
// return user.fetch(null);
// }
//
// public boolean isHuman() throws CytomineException {
// return this.get("algo") == null;
// }
//
// @Override
// public String toURL() {
//
// if (getLong("id") != null) {
// return getJSONResourceURL();
// /*} else if (getStr("username get") != null) {
// return getJSONResourceURL(getStr("username get")); ???*/
// } else if (getStr("current") != null) {
// return "/api/user/current.json";
// } else if (isFilterBy("publicKeyFilter")) {
// return "/api/userkey/" + getFilter("publicKeyFilter") + "/keys.json";
// } else if (isFilterBy("id") && isFilterBy("keys")) {
// return "/api/user/" + getFilter("id") + "/keys.json";
// } else {
// return getJSONResourceURL();
// }
// }
// }
| import java.io.IOException;
import java.nio.file.Files;
import java.util.*;
import be.cytomine.client.models.User;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File; | package be.cytomine.client;
/*
* Copyright (c) 2009-2020. Authors: see NOTICE file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public class CytomineConnection {
private static final Logger log = LogManager.getLogger(Cytomine.class);
private String host;
private String login;
private String pass;
private String publicKey;
private String privateKey;
| // Path: src/main/java/be/cytomine/client/models/User.java
// public class User extends Model<User> {
//
// public User(){}
// public User(String username, String firstname, String lastname, String email, String password){
// this.set("username", username);
// this.set("firstname", firstname);
// this.set("lastname", lastname);
// this.set("email", email);
// this.set("password", password);
// }
//
// public static User getCurrent() throws CytomineException {
// User user = new User();
// user.set("current", "current");
// return user.fetch(null);
// }
//
// public boolean isHuman() throws CytomineException {
// return this.get("algo") == null;
// }
//
// @Override
// public String toURL() {
//
// if (getLong("id") != null) {
// return getJSONResourceURL();
// /*} else if (getStr("username get") != null) {
// return getJSONResourceURL(getStr("username get")); ???*/
// } else if (getStr("current") != null) {
// return "/api/user/current.json";
// } else if (isFilterBy("publicKeyFilter")) {
// return "/api/userkey/" + getFilter("publicKeyFilter") + "/keys.json";
// } else if (isFilterBy("id") && isFilterBy("keys")) {
// return "/api/user/" + getFilter("id") + "/keys.json";
// } else {
// return getJSONResourceURL();
// }
// }
// }
// Path: src/main/java/be/cytomine/client/CytomineConnection.java
import java.io.IOException;
import java.nio.file.Files;
import java.util.*;
import be.cytomine.client.models.User;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
package be.cytomine.client;
/*
* Copyright (c) 2009-2020. Authors: see NOTICE file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public class CytomineConnection {
private static final Logger log = LogManager.getLogger(Cytomine.class);
private String host;
private String login;
private String pass;
private String publicKey;
private String privateKey;
| private User currentUser; |
cytomine/Cytomine-java-client | src/main/java/be/cytomine/client/collections/DeleteCommandCollection.java | // Path: src/main/java/be/cytomine/client/models/DeleteCommand.java
// public class DeleteCommand extends Model<DeleteCommand> {
// }
| import be.cytomine.client.models.DeleteCommand; | package be.cytomine.client.collections;
/*
* Copyright (c) 2009-2020. Authors: see NOTICE file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public class DeleteCommandCollection extends Collection {
public DeleteCommandCollection(int max, int offset) { | // Path: src/main/java/be/cytomine/client/models/DeleteCommand.java
// public class DeleteCommand extends Model<DeleteCommand> {
// }
// Path: src/main/java/be/cytomine/client/collections/DeleteCommandCollection.java
import be.cytomine.client.models.DeleteCommand;
package be.cytomine.client.collections;
/*
* Copyright (c) 2009-2020. Authors: see NOTICE file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public class DeleteCommandCollection extends Collection {
public DeleteCommandCollection(int max, int offset) { | super(DeleteCommand.class, max, offset); |
zhuzhijie/util | src/com/jing/test/MD5UtilTest.java | // Path: src/com/jing/lang/MD5Util.java
// public class MD5Util {
//
// protected static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6',
// '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
//
// protected static MessageDigest messagedigest = null;
//
// static {
// try {
// messagedigest = MessageDigest.getInstance("MD5");
// } catch (NoSuchAlgorithmException nsaex) {
// System.err.println(MD5Util.class.getName()
// + "初始化失败,MessageDigest不支持MD5Util。");
// nsaex.printStackTrace();
// }
// }
//
// /**
// * 功能:加盐版的MD5.返回格式为MD5(密码+{盐值})
// * @author 朱志杰 QQ:862990787
// * 2013-11-29 下午04:33:55
// * @param password 密码
// * @param salt 盐值
// * @return String
// */
// public static String getMD5StringWithSalt(String password, String salt) {
// if (password == null) {
// throw new IllegalArgumentException("password不能为null");
// }
// if(StringUtil.isEmpty(salt)){
// throw new IllegalArgumentException("salt不能为空");
// }
// if ((salt.toString().lastIndexOf("{") != -1) || (salt.toString().lastIndexOf("}") != -1)) {
// throw new IllegalArgumentException("salt中不能包含 { 或者 }");
// }
// return getMD5String(password + "{" + salt.toString() + "}");
// }
//
// /**
// * 功能:得到文件的md5值。
// * @author 朱志杰 QQ:695520848
// * Jun 9, 2013 1:46:59 PM
// * @param file 文件。
// * @return String
// * @throws IOException 读取文件IO异常时。
// */
// public static String getFileMD5String(File file) throws IOException {
// FileInputStream in = new FileInputStream(file);
// FileChannel ch = in.getChannel();
// MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0,
// file.length());
// messagedigest.update(byteBuffer);
// return bufferToHex(messagedigest.digest());
// }
//
// /**
// * 功能:得到一个字符串的MD5值。
// * @author 朱志杰 QQ:695520848
// * Jun 9, 2013 1:47:51 PM
// * @param str 字符串
// * @return String
// */
// public static String getMD5String(String str) {
// return getMD5String(str.getBytes());
// }
//
// private static String getMD5String(byte[] bytes) {
// messagedigest.update(bytes);
// return bufferToHex(messagedigest.digest());
// }
//
// private static String bufferToHex(byte bytes[]) {
// return bufferToHex(bytes, 0, bytes.length);
// }
//
// private static String bufferToHex(byte bytes[], int m, int n) {
// StringBuffer stringbuffer = new StringBuffer(2 * n);
// int k = m + n;
// for (int l = m; l < k; l++) {
// appendHexPair(bytes[l], stringbuffer);
// }
// return stringbuffer.toString();
// }
//
// private static void appendHexPair(byte bt, StringBuffer stringbuffer) {
// char c0 = hexDigits[(bt & 0xf0) >> 4];
// char c1 = hexDigits[bt & 0xf];
// stringbuffer.append(c0);
// stringbuffer.append(c1);
// }
// }
| import java.io.File;
import java.io.IOException;
import com.jing.lang.MD5Util; | package com.jing.test;
public class MD5UtilTest {
/**
* 功能:
* @author 朱志杰 QQ:695520848
* Jun 9, 2013 1:50:17 PM
* @param args
*/
public static void main(String[] args) { | // Path: src/com/jing/lang/MD5Util.java
// public class MD5Util {
//
// protected static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6',
// '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
//
// protected static MessageDigest messagedigest = null;
//
// static {
// try {
// messagedigest = MessageDigest.getInstance("MD5");
// } catch (NoSuchAlgorithmException nsaex) {
// System.err.println(MD5Util.class.getName()
// + "初始化失败,MessageDigest不支持MD5Util。");
// nsaex.printStackTrace();
// }
// }
//
// /**
// * 功能:加盐版的MD5.返回格式为MD5(密码+{盐值})
// * @author 朱志杰 QQ:862990787
// * 2013-11-29 下午04:33:55
// * @param password 密码
// * @param salt 盐值
// * @return String
// */
// public static String getMD5StringWithSalt(String password, String salt) {
// if (password == null) {
// throw new IllegalArgumentException("password不能为null");
// }
// if(StringUtil.isEmpty(salt)){
// throw new IllegalArgumentException("salt不能为空");
// }
// if ((salt.toString().lastIndexOf("{") != -1) || (salt.toString().lastIndexOf("}") != -1)) {
// throw new IllegalArgumentException("salt中不能包含 { 或者 }");
// }
// return getMD5String(password + "{" + salt.toString() + "}");
// }
//
// /**
// * 功能:得到文件的md5值。
// * @author 朱志杰 QQ:695520848
// * Jun 9, 2013 1:46:59 PM
// * @param file 文件。
// * @return String
// * @throws IOException 读取文件IO异常时。
// */
// public static String getFileMD5String(File file) throws IOException {
// FileInputStream in = new FileInputStream(file);
// FileChannel ch = in.getChannel();
// MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0,
// file.length());
// messagedigest.update(byteBuffer);
// return bufferToHex(messagedigest.digest());
// }
//
// /**
// * 功能:得到一个字符串的MD5值。
// * @author 朱志杰 QQ:695520848
// * Jun 9, 2013 1:47:51 PM
// * @param str 字符串
// * @return String
// */
// public static String getMD5String(String str) {
// return getMD5String(str.getBytes());
// }
//
// private static String getMD5String(byte[] bytes) {
// messagedigest.update(bytes);
// return bufferToHex(messagedigest.digest());
// }
//
// private static String bufferToHex(byte bytes[]) {
// return bufferToHex(bytes, 0, bytes.length);
// }
//
// private static String bufferToHex(byte bytes[], int m, int n) {
// StringBuffer stringbuffer = new StringBuffer(2 * n);
// int k = m + n;
// for (int l = m; l < k; l++) {
// appendHexPair(bytes[l], stringbuffer);
// }
// return stringbuffer.toString();
// }
//
// private static void appendHexPair(byte bt, StringBuffer stringbuffer) {
// char c0 = hexDigits[(bt & 0xf0) >> 4];
// char c1 = hexDigits[bt & 0xf];
// stringbuffer.append(c0);
// stringbuffer.append(c1);
// }
// }
// Path: src/com/jing/test/MD5UtilTest.java
import java.io.File;
import java.io.IOException;
import com.jing.lang.MD5Util;
package com.jing.test;
public class MD5UtilTest {
/**
* 功能:
* @author 朱志杰 QQ:695520848
* Jun 9, 2013 1:50:17 PM
* @param args
*/
public static void main(String[] args) { | System.out.println(MD5Util.getMD5String("123")); |
yiyongfei/jea | architecture-cache/src/main/java/com/ea/core/cache/CacheContext.java | // Path: architecture-cache/src/main/java/com/ea/core/cache/handle/ICacheHandle.java
// public interface ICacheHandle {
//
// public void set(String cacheLevel, Map<String, String> map, int seconds) throws Exception;
//
// public boolean set(String cacheLevel, String key, String value, int seconds) throws Exception;
//
// public void add(String cacheLevel, Map<String, String> map, int seconds) throws Exception;
//
// public boolean add(String cacheLevel, String key, String value, int seconds) throws Exception;
//
// public void replace(String cacheLevel, Map<String, String> map, int seconds) throws Exception;
//
// public boolean replace(String cacheLevel, String key, String value, int seconds) throws Exception;
//
// public Set<String> keys(String pattern, String regexp) throws Exception;
//
// public Boolean expire(String key, int seconds) throws Exception;
//
// public String get(String key) throws Exception;
//
// public Boolean exists(String key) throws Exception;
//
// public Map<String, String> getByRegexp(String pattern, String regexp) throws Exception;
//
// public String showRedisByRegexp(String pattern, String regexp) throws Exception;
//
// public Boolean delete(String key) throws Exception;
//
// public int deleteByRegexp(String pattern, String regexp) throws Exception;
//
// public boolean isActivate();
// }
//
// Path: architecture-core/src/main/java/com/ea/core/kryo/ISerializer.java
// public interface ISerializer extends Serializable{
//
// /**
// * 序列化成字符串,字符串以ISO-8859-1编码
// * 目前框架里所有序列化的内容都以字符串方式存在
// *
// * @param obj
// * @return
// * @throws Exception
// */
// public String serialize(Object obj) throws Exception;
//
// /**
// * 序列化成byte数组
// *
// * @param obj
// * @return
// * @throws Exception
// */
// public byte[] Serialize(Object obj) throws Exception;
//
// /**
// * 根据字符串内容反序列化成对象
// *
// * @param serialString
// * @return
// * @throws Exception
// */
// public Object deserialize(String serialString) throws Exception;
//
// public Object Deserialize(byte[] aryByte) throws Exception;
//
// /**
// * 注册Class
// *
// * @param type
// */
// public void register(Class<?> type);
//
// public void register(Class<?> type, Serializer<?> serializer);
// }
| import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ea.core.cache.handle.ICacheHandle;
import com.ea.core.cache.request.Request;
import com.ea.core.kryo.ISerializer;
import com.ea.core.kryo.impl.DefaultSerializer;
import com.ea.core.kryo.impl.JavaSerializer;
import com.ea.core.kryo.impl.ObjectSerializer; | /**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.cache;
/**
* 缓存上下文
*
* @author yiyongfei
*
*/
@Component
public class CacheContext {
@Autowired | // Path: architecture-cache/src/main/java/com/ea/core/cache/handle/ICacheHandle.java
// public interface ICacheHandle {
//
// public void set(String cacheLevel, Map<String, String> map, int seconds) throws Exception;
//
// public boolean set(String cacheLevel, String key, String value, int seconds) throws Exception;
//
// public void add(String cacheLevel, Map<String, String> map, int seconds) throws Exception;
//
// public boolean add(String cacheLevel, String key, String value, int seconds) throws Exception;
//
// public void replace(String cacheLevel, Map<String, String> map, int seconds) throws Exception;
//
// public boolean replace(String cacheLevel, String key, String value, int seconds) throws Exception;
//
// public Set<String> keys(String pattern, String regexp) throws Exception;
//
// public Boolean expire(String key, int seconds) throws Exception;
//
// public String get(String key) throws Exception;
//
// public Boolean exists(String key) throws Exception;
//
// public Map<String, String> getByRegexp(String pattern, String regexp) throws Exception;
//
// public String showRedisByRegexp(String pattern, String regexp) throws Exception;
//
// public Boolean delete(String key) throws Exception;
//
// public int deleteByRegexp(String pattern, String regexp) throws Exception;
//
// public boolean isActivate();
// }
//
// Path: architecture-core/src/main/java/com/ea/core/kryo/ISerializer.java
// public interface ISerializer extends Serializable{
//
// /**
// * 序列化成字符串,字符串以ISO-8859-1编码
// * 目前框架里所有序列化的内容都以字符串方式存在
// *
// * @param obj
// * @return
// * @throws Exception
// */
// public String serialize(Object obj) throws Exception;
//
// /**
// * 序列化成byte数组
// *
// * @param obj
// * @return
// * @throws Exception
// */
// public byte[] Serialize(Object obj) throws Exception;
//
// /**
// * 根据字符串内容反序列化成对象
// *
// * @param serialString
// * @return
// * @throws Exception
// */
// public Object deserialize(String serialString) throws Exception;
//
// public Object Deserialize(byte[] aryByte) throws Exception;
//
// /**
// * 注册Class
// *
// * @param type
// */
// public void register(Class<?> type);
//
// public void register(Class<?> type, Serializer<?> serializer);
// }
// Path: architecture-cache/src/main/java/com/ea/core/cache/CacheContext.java
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ea.core.cache.handle.ICacheHandle;
import com.ea.core.cache.request.Request;
import com.ea.core.kryo.ISerializer;
import com.ea.core.kryo.impl.DefaultSerializer;
import com.ea.core.kryo.impl.JavaSerializer;
import com.ea.core.kryo.impl.ObjectSerializer;
/**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.cache;
/**
* 缓存上下文
*
* @author yiyongfei
*
*/
@Component
public class CacheContext {
@Autowired | private ICacheHandle l1CacheHandle; |
yiyongfei/jea | architecture-cache/src/main/java/com/ea/core/cache/CacheContext.java | // Path: architecture-cache/src/main/java/com/ea/core/cache/handle/ICacheHandle.java
// public interface ICacheHandle {
//
// public void set(String cacheLevel, Map<String, String> map, int seconds) throws Exception;
//
// public boolean set(String cacheLevel, String key, String value, int seconds) throws Exception;
//
// public void add(String cacheLevel, Map<String, String> map, int seconds) throws Exception;
//
// public boolean add(String cacheLevel, String key, String value, int seconds) throws Exception;
//
// public void replace(String cacheLevel, Map<String, String> map, int seconds) throws Exception;
//
// public boolean replace(String cacheLevel, String key, String value, int seconds) throws Exception;
//
// public Set<String> keys(String pattern, String regexp) throws Exception;
//
// public Boolean expire(String key, int seconds) throws Exception;
//
// public String get(String key) throws Exception;
//
// public Boolean exists(String key) throws Exception;
//
// public Map<String, String> getByRegexp(String pattern, String regexp) throws Exception;
//
// public String showRedisByRegexp(String pattern, String regexp) throws Exception;
//
// public Boolean delete(String key) throws Exception;
//
// public int deleteByRegexp(String pattern, String regexp) throws Exception;
//
// public boolean isActivate();
// }
//
// Path: architecture-core/src/main/java/com/ea/core/kryo/ISerializer.java
// public interface ISerializer extends Serializable{
//
// /**
// * 序列化成字符串,字符串以ISO-8859-1编码
// * 目前框架里所有序列化的内容都以字符串方式存在
// *
// * @param obj
// * @return
// * @throws Exception
// */
// public String serialize(Object obj) throws Exception;
//
// /**
// * 序列化成byte数组
// *
// * @param obj
// * @return
// * @throws Exception
// */
// public byte[] Serialize(Object obj) throws Exception;
//
// /**
// * 根据字符串内容反序列化成对象
// *
// * @param serialString
// * @return
// * @throws Exception
// */
// public Object deserialize(String serialString) throws Exception;
//
// public Object Deserialize(byte[] aryByte) throws Exception;
//
// /**
// * 注册Class
// *
// * @param type
// */
// public void register(Class<?> type);
//
// public void register(Class<?> type, Serializer<?> serializer);
// }
| import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ea.core.cache.handle.ICacheHandle;
import com.ea.core.cache.request.Request;
import com.ea.core.kryo.ISerializer;
import com.ea.core.kryo.impl.DefaultSerializer;
import com.ea.core.kryo.impl.JavaSerializer;
import com.ea.core.kryo.impl.ObjectSerializer; | */
public String showRedisByRegexp(String pattern, String regexp) throws Exception{
return l1CacheHandle.showRedisByRegexp(pattern, regexp);
}
/**
* 根据Key删除缓存数据
*
* @param key
* @throws Exception
*/
public void delete(String key) throws Exception{
l1CacheHandle.delete(key);
}
/**
* 根据正则表达式删除符合条件的缓存数据
*
* @param pattern
* @param regexp
* @return
* @throws Exception
*/
public int deleteByRegexp(String pattern, String regexp) throws Exception{
return l1CacheHandle.deleteByRegexp(pattern, regexp);
}
protected String serialize(Object model) throws Exception{
Request request = new Request();
| // Path: architecture-cache/src/main/java/com/ea/core/cache/handle/ICacheHandle.java
// public interface ICacheHandle {
//
// public void set(String cacheLevel, Map<String, String> map, int seconds) throws Exception;
//
// public boolean set(String cacheLevel, String key, String value, int seconds) throws Exception;
//
// public void add(String cacheLevel, Map<String, String> map, int seconds) throws Exception;
//
// public boolean add(String cacheLevel, String key, String value, int seconds) throws Exception;
//
// public void replace(String cacheLevel, Map<String, String> map, int seconds) throws Exception;
//
// public boolean replace(String cacheLevel, String key, String value, int seconds) throws Exception;
//
// public Set<String> keys(String pattern, String regexp) throws Exception;
//
// public Boolean expire(String key, int seconds) throws Exception;
//
// public String get(String key) throws Exception;
//
// public Boolean exists(String key) throws Exception;
//
// public Map<String, String> getByRegexp(String pattern, String regexp) throws Exception;
//
// public String showRedisByRegexp(String pattern, String regexp) throws Exception;
//
// public Boolean delete(String key) throws Exception;
//
// public int deleteByRegexp(String pattern, String regexp) throws Exception;
//
// public boolean isActivate();
// }
//
// Path: architecture-core/src/main/java/com/ea/core/kryo/ISerializer.java
// public interface ISerializer extends Serializable{
//
// /**
// * 序列化成字符串,字符串以ISO-8859-1编码
// * 目前框架里所有序列化的内容都以字符串方式存在
// *
// * @param obj
// * @return
// * @throws Exception
// */
// public String serialize(Object obj) throws Exception;
//
// /**
// * 序列化成byte数组
// *
// * @param obj
// * @return
// * @throws Exception
// */
// public byte[] Serialize(Object obj) throws Exception;
//
// /**
// * 根据字符串内容反序列化成对象
// *
// * @param serialString
// * @return
// * @throws Exception
// */
// public Object deserialize(String serialString) throws Exception;
//
// public Object Deserialize(byte[] aryByte) throws Exception;
//
// /**
// * 注册Class
// *
// * @param type
// */
// public void register(Class<?> type);
//
// public void register(Class<?> type, Serializer<?> serializer);
// }
// Path: architecture-cache/src/main/java/com/ea/core/cache/CacheContext.java
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ea.core.cache.handle.ICacheHandle;
import com.ea.core.cache.request.Request;
import com.ea.core.kryo.ISerializer;
import com.ea.core.kryo.impl.DefaultSerializer;
import com.ea.core.kryo.impl.JavaSerializer;
import com.ea.core.kryo.impl.ObjectSerializer;
*/
public String showRedisByRegexp(String pattern, String regexp) throws Exception{
return l1CacheHandle.showRedisByRegexp(pattern, regexp);
}
/**
* 根据Key删除缓存数据
*
* @param key
* @throws Exception
*/
public void delete(String key) throws Exception{
l1CacheHandle.delete(key);
}
/**
* 根据正则表达式删除符合条件的缓存数据
*
* @param pattern
* @param regexp
* @return
* @throws Exception
*/
public int deleteByRegexp(String pattern, String regexp) throws Exception{
return l1CacheHandle.deleteByRegexp(pattern, regexp);
}
protected String serialize(Object model) throws Exception{
Request request = new Request();
| ISerializer contentSerializer = new ObjectSerializer(); |
yiyongfei/jea | architecture-orm/src/main/java/com/ea/core/orm/handle/AbstractORMHandle.java | // Path: architecture-orm/src/main/java/com/ea/core/orm/handle/dto/ORMParamsDTO.java
// public class ORMParamsDTO implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private Object param;
// private String sqlid;
//
// public Object getParam() {
// return param;
// }
// public void setParam(Object param) {
// this.param = param;
// }
// public String getSqlid() {
// return sqlid;
// }
// public void setSqlid(String sqlid) {
// this.sqlid = sqlid;
// }
//
// }
| import org.mybatis.spring.SqlSessionTemplate;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import com.ea.core.orm.handle.dto.ORMParamsDTO; | /**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.orm.handle;
public abstract class AbstractORMHandle implements ORMHandle, ApplicationContextAware {
protected ApplicationContext context = null;
@Autowired
private SqlSessionTemplate mybatisSessionTemplate;
@Autowired
private SessionFactory hibernateSessionFactory;
private String level;
private ORMHandle nextHandle;
public AbstractORMHandle(String level){
this.level = level;
}
/**
* 符合当前Level,则执行DB操作,否则交由下个Handle去执行
*/ | // Path: architecture-orm/src/main/java/com/ea/core/orm/handle/dto/ORMParamsDTO.java
// public class ORMParamsDTO implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private Object param;
// private String sqlid;
//
// public Object getParam() {
// return param;
// }
// public void setParam(Object param) {
// this.param = param;
// }
// public String getSqlid() {
// return sqlid;
// }
// public void setSqlid(String sqlid) {
// this.sqlid = sqlid;
// }
//
// }
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/AbstractORMHandle.java
import org.mybatis.spring.SqlSessionTemplate;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import com.ea.core.orm.handle.dto.ORMParamsDTO;
/**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.orm.handle;
public abstract class AbstractORMHandle implements ORMHandle, ApplicationContextAware {
protected ApplicationContext context = null;
@Autowired
private SqlSessionTemplate mybatisSessionTemplate;
@Autowired
private SessionFactory hibernateSessionFactory;
private String level;
private ORMHandle nextHandle;
public AbstractORMHandle(String level){
this.level = level;
}
/**
* 符合当前Level,则执行DB操作,否则交由下个Handle去执行
*/ | public final Object handle(String level, ORMParamsDTO dto) throws Exception { |
yiyongfei/jea | architecture-integration/src/main/java/com/ea/core/integration/bridge/StormIntegration.java | // Path: architecture-integration/src/main/java/com/ea/core/integration/IntegrationContext.java
// public class IntegrationContext {
// private Logger logger = LoggerFactory.getLogger(IntegrationContext.class);
//
// public Object connect(String connectMode, Map<String, String> conf, String connectorId, String facadeId, Object... models) throws Exception {
// // TODO Auto-generated method stub
// long startTime = Calendar.getInstance().getTimeInMillis();
// IConnector connector = null;
// if(connectMode.equals(IntegrationConstant.CONNECTOR_MODE.MQ.getCode())){
// IClient client = new MqSendClient(conf.get(IntegrationConstant.CONF.HOST.getCode()),
// conf.get(IntegrationConstant.CONF.USERNAME.getCode()),
// conf.get(IntegrationConstant.CONF.PASSWORD.getCode()));
// connector = new MqConnector();
// ((AbstractConnector)connector).setClient(client);
// }
// else if(connectMode.equals(IntegrationConstant.CONNECTOR_MODE.STORM.getCode())){
// IClient client = new RemoteClient(conf.get(IntegrationConstant.CONF.HOST.getCode()),
// new Integer(conf.get(IntegrationConstant.CONF.PORT.getCode())),
// new Integer(conf.get(IntegrationConstant.CONF.TIMEOUT.getCode())));
// connector = new StormConnector();
// ((AbstractConnector)connector).setClient(client);
// }
// else if(connectMode.equals(IntegrationConstant.CONNECTOR_MODE.SOAP.getCode())){
// IWSClient client = new SoapClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// connector = new SoapConnector();
// ((AbstractWSConnector)connector).setClient(client);
// }
// else {
// IWSClient client = null;
// if(HttpMethod.GET.equals(conf.get(IntegrationConstant.CONF.HTTP_METHOD.getCode()))){
// client = new GetClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// } else if(HttpMethod.POST.equals(conf.get(IntegrationConstant.CONF.HTTP_METHOD.getCode()))){
// client = new PostClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// } else if(HttpMethod.PUT.equals(conf.get(IntegrationConstant.CONF.HTTP_METHOD.getCode()))){
// client = new PutClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// } else if(HttpMethod.DELETE.equals(conf.get(IntegrationConstant.CONF.HTTP_METHOD.getCode()))){
// client = new DeleteClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// } else {
// throw new RuntimeException("提供的HttpMethod方法有误,请检查!");
// }
// connector = new RestConnector();
// ((AbstractWSConnector)connector).setClient(client);
// }
// long endTime1 = Calendar.getInstance().getTimeInMillis();
// logger.info("初始化连接共耗时" + (endTime1 - startTime) + "毫秒");
// Object result = connector.connect(connectorId, facadeId, models);
// long endTime2 = Calendar.getInstance().getTimeInMillis();
// logger.info("本次执行共耗时" + (endTime2 - startTime) + "毫秒,排除初始化连接后的耗时" + (endTime2 - endTime1) + "毫秒,连接方式:" + connectMode + ",调用Facade:" + facadeId);
// return result;
// }
//
// }
| import java.util.HashMap;
import java.util.Map;
import com.ea.core.integration.IntegrationConstant;
import com.ea.core.integration.IntegrationContext; | package com.ea.core.integration.bridge;
public class StormIntegration {
public void connect(String host, String port, String timeout, String topologyName, String facadeId, Object... obj) throws Exception{ | // Path: architecture-integration/src/main/java/com/ea/core/integration/IntegrationContext.java
// public class IntegrationContext {
// private Logger logger = LoggerFactory.getLogger(IntegrationContext.class);
//
// public Object connect(String connectMode, Map<String, String> conf, String connectorId, String facadeId, Object... models) throws Exception {
// // TODO Auto-generated method stub
// long startTime = Calendar.getInstance().getTimeInMillis();
// IConnector connector = null;
// if(connectMode.equals(IntegrationConstant.CONNECTOR_MODE.MQ.getCode())){
// IClient client = new MqSendClient(conf.get(IntegrationConstant.CONF.HOST.getCode()),
// conf.get(IntegrationConstant.CONF.USERNAME.getCode()),
// conf.get(IntegrationConstant.CONF.PASSWORD.getCode()));
// connector = new MqConnector();
// ((AbstractConnector)connector).setClient(client);
// }
// else if(connectMode.equals(IntegrationConstant.CONNECTOR_MODE.STORM.getCode())){
// IClient client = new RemoteClient(conf.get(IntegrationConstant.CONF.HOST.getCode()),
// new Integer(conf.get(IntegrationConstant.CONF.PORT.getCode())),
// new Integer(conf.get(IntegrationConstant.CONF.TIMEOUT.getCode())));
// connector = new StormConnector();
// ((AbstractConnector)connector).setClient(client);
// }
// else if(connectMode.equals(IntegrationConstant.CONNECTOR_MODE.SOAP.getCode())){
// IWSClient client = new SoapClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// connector = new SoapConnector();
// ((AbstractWSConnector)connector).setClient(client);
// }
// else {
// IWSClient client = null;
// if(HttpMethod.GET.equals(conf.get(IntegrationConstant.CONF.HTTP_METHOD.getCode()))){
// client = new GetClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// } else if(HttpMethod.POST.equals(conf.get(IntegrationConstant.CONF.HTTP_METHOD.getCode()))){
// client = new PostClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// } else if(HttpMethod.PUT.equals(conf.get(IntegrationConstant.CONF.HTTP_METHOD.getCode()))){
// client = new PutClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// } else if(HttpMethod.DELETE.equals(conf.get(IntegrationConstant.CONF.HTTP_METHOD.getCode()))){
// client = new DeleteClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// } else {
// throw new RuntimeException("提供的HttpMethod方法有误,请检查!");
// }
// connector = new RestConnector();
// ((AbstractWSConnector)connector).setClient(client);
// }
// long endTime1 = Calendar.getInstance().getTimeInMillis();
// logger.info("初始化连接共耗时" + (endTime1 - startTime) + "毫秒");
// Object result = connector.connect(connectorId, facadeId, models);
// long endTime2 = Calendar.getInstance().getTimeInMillis();
// logger.info("本次执行共耗时" + (endTime2 - startTime) + "毫秒,排除初始化连接后的耗时" + (endTime2 - endTime1) + "毫秒,连接方式:" + connectMode + ",调用Facade:" + facadeId);
// return result;
// }
//
// }
// Path: architecture-integration/src/main/java/com/ea/core/integration/bridge/StormIntegration.java
import java.util.HashMap;
import java.util.Map;
import com.ea.core.integration.IntegrationConstant;
import com.ea.core.integration.IntegrationContext;
package com.ea.core.integration.bridge;
public class StormIntegration {
public void connect(String host, String port, String timeout, String topologyName, String facadeId, Object... obj) throws Exception{ | IntegrationContext context = new IntegrationContext(); |
yiyongfei/jea | architecture-orm/src/main/java/com/ea/core/orm/handle/impl/HibernateSqlORMHandle.java | // Path: architecture-orm/src/main/java/com/ea/core/orm/handle/AbstractORMHandle.java
// public abstract class AbstractORMHandle implements ORMHandle, ApplicationContextAware {
// protected ApplicationContext context = null;
//
// @Autowired
// private SqlSessionTemplate mybatisSessionTemplate;
// @Autowired
// private SessionFactory hibernateSessionFactory;
//
// private String level;
// private ORMHandle nextHandle;
//
// public AbstractORMHandle(String level){
// this.level = level;
// }
//
// /**
// * 符合当前Level,则执行DB操作,否则交由下个Handle去执行
// */
// public final Object handle(String level, ORMParamsDTO dto) throws Exception {
// if(this.level.equals(level)){
// return this.execute(dto);
// } else {
// this.setNextHandle();
// if(this.nextHandle != null){
// return this.nextHandle.handle(level, dto);
// } else {
// throw new Exception("必须设置ORMHandle处理当前请求");
// }
// }
// }
//
// /**
// * 执行DB操作
// * @param dto
// * @return
// * @throws Exception
// */
// protected abstract Object execute(ORMParamsDTO dto) throws Exception;
//
// /**
// * 设置下个Handle,子类设置,如果是最后一个Handle,不设置
// */
// public abstract void setNextHandle();
//
// protected SqlSessionTemplate getMybatisSessionTemplate() {
// return mybatisSessionTemplate;
// }
//
// protected SessionFactory getHibernateSessionFactory() {
// return hibernateSessionFactory;
// }
//
// public void setApplicationContext(ApplicationContext applicationContext) {
// // TODO Auto-generated method stub
// context = applicationContext;
// }
//
// protected void setNextHandle(ORMHandle nextHandle){
// this.nextHandle = nextHandle;
// }
//
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/ORMHandle.java
// public interface ORMHandle {
//
// public Object handle(String level, ORMParamsDTO dto) throws Exception;
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/dto/ORMParamsDTO.java
// public class ORMParamsDTO implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private Object param;
// private String sqlid;
//
// public Object getParam() {
// return param;
// }
// public void setParam(Object param) {
// this.param = param;
// }
// public String getSqlid() {
// return sqlid;
// }
// public void setSqlid(String sqlid) {
// this.sqlid = sqlid;
// }
//
// }
| import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Collection;
import org.hibernate.Session;
import org.hibernate.jdbc.Work;
import org.springframework.stereotype.Component;
import com.ea.core.orm.handle.AbstractORMHandle;
import com.ea.core.orm.handle.ORMConstants;
import com.ea.core.orm.handle.ORMHandle;
import com.ea.core.orm.handle.dto.ORMParamsDTO; | /**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.orm.handle.impl;
/**
* SQL执行,通过Hibernate完成,用于数据的新增或更新
* @author yiyongfei
*
*/
@Component
public class HibernateSqlORMHandle extends AbstractORMHandle {
public HibernateSqlORMHandle() {
super(ORMConstants.ORM_LEVEL.H_SQL.getCode());
}
@Override | // Path: architecture-orm/src/main/java/com/ea/core/orm/handle/AbstractORMHandle.java
// public abstract class AbstractORMHandle implements ORMHandle, ApplicationContextAware {
// protected ApplicationContext context = null;
//
// @Autowired
// private SqlSessionTemplate mybatisSessionTemplate;
// @Autowired
// private SessionFactory hibernateSessionFactory;
//
// private String level;
// private ORMHandle nextHandle;
//
// public AbstractORMHandle(String level){
// this.level = level;
// }
//
// /**
// * 符合当前Level,则执行DB操作,否则交由下个Handle去执行
// */
// public final Object handle(String level, ORMParamsDTO dto) throws Exception {
// if(this.level.equals(level)){
// return this.execute(dto);
// } else {
// this.setNextHandle();
// if(this.nextHandle != null){
// return this.nextHandle.handle(level, dto);
// } else {
// throw new Exception("必须设置ORMHandle处理当前请求");
// }
// }
// }
//
// /**
// * 执行DB操作
// * @param dto
// * @return
// * @throws Exception
// */
// protected abstract Object execute(ORMParamsDTO dto) throws Exception;
//
// /**
// * 设置下个Handle,子类设置,如果是最后一个Handle,不设置
// */
// public abstract void setNextHandle();
//
// protected SqlSessionTemplate getMybatisSessionTemplate() {
// return mybatisSessionTemplate;
// }
//
// protected SessionFactory getHibernateSessionFactory() {
// return hibernateSessionFactory;
// }
//
// public void setApplicationContext(ApplicationContext applicationContext) {
// // TODO Auto-generated method stub
// context = applicationContext;
// }
//
// protected void setNextHandle(ORMHandle nextHandle){
// this.nextHandle = nextHandle;
// }
//
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/ORMHandle.java
// public interface ORMHandle {
//
// public Object handle(String level, ORMParamsDTO dto) throws Exception;
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/dto/ORMParamsDTO.java
// public class ORMParamsDTO implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private Object param;
// private String sqlid;
//
// public Object getParam() {
// return param;
// }
// public void setParam(Object param) {
// this.param = param;
// }
// public String getSqlid() {
// return sqlid;
// }
// public void setSqlid(String sqlid) {
// this.sqlid = sqlid;
// }
//
// }
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/impl/HibernateSqlORMHandle.java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Collection;
import org.hibernate.Session;
import org.hibernate.jdbc.Work;
import org.springframework.stereotype.Component;
import com.ea.core.orm.handle.AbstractORMHandle;
import com.ea.core.orm.handle.ORMConstants;
import com.ea.core.orm.handle.ORMHandle;
import com.ea.core.orm.handle.dto.ORMParamsDTO;
/**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.orm.handle.impl;
/**
* SQL执行,通过Hibernate完成,用于数据的新增或更新
* @author yiyongfei
*
*/
@Component
public class HibernateSqlORMHandle extends AbstractORMHandle {
public HibernateSqlORMHandle() {
super(ORMConstants.ORM_LEVEL.H_SQL.getCode());
}
@Override | protected Object execute(ORMParamsDTO dto) throws Exception { |
yiyongfei/jea | architecture-orm/src/main/java/com/ea/core/orm/handle/impl/HibernateSqlORMHandle.java | // Path: architecture-orm/src/main/java/com/ea/core/orm/handle/AbstractORMHandle.java
// public abstract class AbstractORMHandle implements ORMHandle, ApplicationContextAware {
// protected ApplicationContext context = null;
//
// @Autowired
// private SqlSessionTemplate mybatisSessionTemplate;
// @Autowired
// private SessionFactory hibernateSessionFactory;
//
// private String level;
// private ORMHandle nextHandle;
//
// public AbstractORMHandle(String level){
// this.level = level;
// }
//
// /**
// * 符合当前Level,则执行DB操作,否则交由下个Handle去执行
// */
// public final Object handle(String level, ORMParamsDTO dto) throws Exception {
// if(this.level.equals(level)){
// return this.execute(dto);
// } else {
// this.setNextHandle();
// if(this.nextHandle != null){
// return this.nextHandle.handle(level, dto);
// } else {
// throw new Exception("必须设置ORMHandle处理当前请求");
// }
// }
// }
//
// /**
// * 执行DB操作
// * @param dto
// * @return
// * @throws Exception
// */
// protected abstract Object execute(ORMParamsDTO dto) throws Exception;
//
// /**
// * 设置下个Handle,子类设置,如果是最后一个Handle,不设置
// */
// public abstract void setNextHandle();
//
// protected SqlSessionTemplate getMybatisSessionTemplate() {
// return mybatisSessionTemplate;
// }
//
// protected SessionFactory getHibernateSessionFactory() {
// return hibernateSessionFactory;
// }
//
// public void setApplicationContext(ApplicationContext applicationContext) {
// // TODO Auto-generated method stub
// context = applicationContext;
// }
//
// protected void setNextHandle(ORMHandle nextHandle){
// this.nextHandle = nextHandle;
// }
//
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/ORMHandle.java
// public interface ORMHandle {
//
// public Object handle(String level, ORMParamsDTO dto) throws Exception;
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/dto/ORMParamsDTO.java
// public class ORMParamsDTO implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private Object param;
// private String sqlid;
//
// public Object getParam() {
// return param;
// }
// public void setParam(Object param) {
// this.param = param;
// }
// public String getSqlid() {
// return sqlid;
// }
// public void setSqlid(String sqlid) {
// this.sqlid = sqlid;
// }
//
// }
| import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Collection;
import org.hibernate.Session;
import org.hibernate.jdbc.Work;
import org.springframework.stereotype.Component;
import com.ea.core.orm.handle.AbstractORMHandle;
import com.ea.core.orm.handle.ORMConstants;
import com.ea.core.orm.handle.ORMHandle;
import com.ea.core.orm.handle.dto.ORMParamsDTO; | for(Object obj : array){
setParam(ps, index++, obj);
}
ps.execute();
} else if (data instanceof Collection) {
for(Object array : (Collection)data){
if(array instanceof Object[]){
int index = 1;
for(Object obj : (Object[])array){
setParam(ps, index++, obj);
}
ps.addBatch();
} else {
throw new SQLException("执行SQL时,参数请以Object[]的方式提供!");
}
}
ps.executeBatch();
} else {
throw new SQLException("ͨ执行SQL时,如果是单条记录操作,参数请以Object[]的方式提供,如果多条记录操作,请提供Collection实例,实例里存放Object[]!");
}
}
}
});
return null;
}
@Override
public void setNextHandle() { | // Path: architecture-orm/src/main/java/com/ea/core/orm/handle/AbstractORMHandle.java
// public abstract class AbstractORMHandle implements ORMHandle, ApplicationContextAware {
// protected ApplicationContext context = null;
//
// @Autowired
// private SqlSessionTemplate mybatisSessionTemplate;
// @Autowired
// private SessionFactory hibernateSessionFactory;
//
// private String level;
// private ORMHandle nextHandle;
//
// public AbstractORMHandle(String level){
// this.level = level;
// }
//
// /**
// * 符合当前Level,则执行DB操作,否则交由下个Handle去执行
// */
// public final Object handle(String level, ORMParamsDTO dto) throws Exception {
// if(this.level.equals(level)){
// return this.execute(dto);
// } else {
// this.setNextHandle();
// if(this.nextHandle != null){
// return this.nextHandle.handle(level, dto);
// } else {
// throw new Exception("必须设置ORMHandle处理当前请求");
// }
// }
// }
//
// /**
// * 执行DB操作
// * @param dto
// * @return
// * @throws Exception
// */
// protected abstract Object execute(ORMParamsDTO dto) throws Exception;
//
// /**
// * 设置下个Handle,子类设置,如果是最后一个Handle,不设置
// */
// public abstract void setNextHandle();
//
// protected SqlSessionTemplate getMybatisSessionTemplate() {
// return mybatisSessionTemplate;
// }
//
// protected SessionFactory getHibernateSessionFactory() {
// return hibernateSessionFactory;
// }
//
// public void setApplicationContext(ApplicationContext applicationContext) {
// // TODO Auto-generated method stub
// context = applicationContext;
// }
//
// protected void setNextHandle(ORMHandle nextHandle){
// this.nextHandle = nextHandle;
// }
//
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/ORMHandle.java
// public interface ORMHandle {
//
// public Object handle(String level, ORMParamsDTO dto) throws Exception;
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/dto/ORMParamsDTO.java
// public class ORMParamsDTO implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private Object param;
// private String sqlid;
//
// public Object getParam() {
// return param;
// }
// public void setParam(Object param) {
// this.param = param;
// }
// public String getSqlid() {
// return sqlid;
// }
// public void setSqlid(String sqlid) {
// this.sqlid = sqlid;
// }
//
// }
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/impl/HibernateSqlORMHandle.java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Collection;
import org.hibernate.Session;
import org.hibernate.jdbc.Work;
import org.springframework.stereotype.Component;
import com.ea.core.orm.handle.AbstractORMHandle;
import com.ea.core.orm.handle.ORMConstants;
import com.ea.core.orm.handle.ORMHandle;
import com.ea.core.orm.handle.dto.ORMParamsDTO;
for(Object obj : array){
setParam(ps, index++, obj);
}
ps.execute();
} else if (data instanceof Collection) {
for(Object array : (Collection)data){
if(array instanceof Object[]){
int index = 1;
for(Object obj : (Object[])array){
setParam(ps, index++, obj);
}
ps.addBatch();
} else {
throw new SQLException("执行SQL时,参数请以Object[]的方式提供!");
}
}
ps.executeBatch();
} else {
throw new SQLException("ͨ执行SQL时,如果是单条记录操作,参数请以Object[]的方式提供,如果多条记录操作,请提供Collection实例,实例里存放Object[]!");
}
}
}
});
return null;
}
@Override
public void setNextHandle() { | ORMHandle nextHandle = (MybatisSqlORMHandle)this.context.getBean("mybatisSqlORMHandle"); |
yiyongfei/jea | architecture-integration/src/main/java/com/ea/core/integration/bridge/MQIntegration.java | // Path: architecture-integration/src/main/java/com/ea/core/integration/IntegrationContext.java
// public class IntegrationContext {
// private Logger logger = LoggerFactory.getLogger(IntegrationContext.class);
//
// public Object connect(String connectMode, Map<String, String> conf, String connectorId, String facadeId, Object... models) throws Exception {
// // TODO Auto-generated method stub
// long startTime = Calendar.getInstance().getTimeInMillis();
// IConnector connector = null;
// if(connectMode.equals(IntegrationConstant.CONNECTOR_MODE.MQ.getCode())){
// IClient client = new MqSendClient(conf.get(IntegrationConstant.CONF.HOST.getCode()),
// conf.get(IntegrationConstant.CONF.USERNAME.getCode()),
// conf.get(IntegrationConstant.CONF.PASSWORD.getCode()));
// connector = new MqConnector();
// ((AbstractConnector)connector).setClient(client);
// }
// else if(connectMode.equals(IntegrationConstant.CONNECTOR_MODE.STORM.getCode())){
// IClient client = new RemoteClient(conf.get(IntegrationConstant.CONF.HOST.getCode()),
// new Integer(conf.get(IntegrationConstant.CONF.PORT.getCode())),
// new Integer(conf.get(IntegrationConstant.CONF.TIMEOUT.getCode())));
// connector = new StormConnector();
// ((AbstractConnector)connector).setClient(client);
// }
// else if(connectMode.equals(IntegrationConstant.CONNECTOR_MODE.SOAP.getCode())){
// IWSClient client = new SoapClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// connector = new SoapConnector();
// ((AbstractWSConnector)connector).setClient(client);
// }
// else {
// IWSClient client = null;
// if(HttpMethod.GET.equals(conf.get(IntegrationConstant.CONF.HTTP_METHOD.getCode()))){
// client = new GetClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// } else if(HttpMethod.POST.equals(conf.get(IntegrationConstant.CONF.HTTP_METHOD.getCode()))){
// client = new PostClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// } else if(HttpMethod.PUT.equals(conf.get(IntegrationConstant.CONF.HTTP_METHOD.getCode()))){
// client = new PutClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// } else if(HttpMethod.DELETE.equals(conf.get(IntegrationConstant.CONF.HTTP_METHOD.getCode()))){
// client = new DeleteClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// } else {
// throw new RuntimeException("提供的HttpMethod方法有误,请检查!");
// }
// connector = new RestConnector();
// ((AbstractWSConnector)connector).setClient(client);
// }
// long endTime1 = Calendar.getInstance().getTimeInMillis();
// logger.info("初始化连接共耗时" + (endTime1 - startTime) + "毫秒");
// Object result = connector.connect(connectorId, facadeId, models);
// long endTime2 = Calendar.getInstance().getTimeInMillis();
// logger.info("本次执行共耗时" + (endTime2 - startTime) + "毫秒,排除初始化连接后的耗时" + (endTime2 - endTime1) + "毫秒,连接方式:" + connectMode + ",调用Facade:" + facadeId);
// return result;
// }
//
// }
| import java.util.HashMap;
import java.util.Map;
import com.ea.core.integration.IntegrationConstant;
import com.ea.core.integration.IntegrationContext; | package com.ea.core.integration.bridge;
public class MQIntegration {
public void connect(String host, String username, String password, String queueName, String facadeId, Object... obj) throws Exception{ | // Path: architecture-integration/src/main/java/com/ea/core/integration/IntegrationContext.java
// public class IntegrationContext {
// private Logger logger = LoggerFactory.getLogger(IntegrationContext.class);
//
// public Object connect(String connectMode, Map<String, String> conf, String connectorId, String facadeId, Object... models) throws Exception {
// // TODO Auto-generated method stub
// long startTime = Calendar.getInstance().getTimeInMillis();
// IConnector connector = null;
// if(connectMode.equals(IntegrationConstant.CONNECTOR_MODE.MQ.getCode())){
// IClient client = new MqSendClient(conf.get(IntegrationConstant.CONF.HOST.getCode()),
// conf.get(IntegrationConstant.CONF.USERNAME.getCode()),
// conf.get(IntegrationConstant.CONF.PASSWORD.getCode()));
// connector = new MqConnector();
// ((AbstractConnector)connector).setClient(client);
// }
// else if(connectMode.equals(IntegrationConstant.CONNECTOR_MODE.STORM.getCode())){
// IClient client = new RemoteClient(conf.get(IntegrationConstant.CONF.HOST.getCode()),
// new Integer(conf.get(IntegrationConstant.CONF.PORT.getCode())),
// new Integer(conf.get(IntegrationConstant.CONF.TIMEOUT.getCode())));
// connector = new StormConnector();
// ((AbstractConnector)connector).setClient(client);
// }
// else if(connectMode.equals(IntegrationConstant.CONNECTOR_MODE.SOAP.getCode())){
// IWSClient client = new SoapClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// connector = new SoapConnector();
// ((AbstractWSConnector)connector).setClient(client);
// }
// else {
// IWSClient client = null;
// if(HttpMethod.GET.equals(conf.get(IntegrationConstant.CONF.HTTP_METHOD.getCode()))){
// client = new GetClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// } else if(HttpMethod.POST.equals(conf.get(IntegrationConstant.CONF.HTTP_METHOD.getCode()))){
// client = new PostClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// } else if(HttpMethod.PUT.equals(conf.get(IntegrationConstant.CONF.HTTP_METHOD.getCode()))){
// client = new PutClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// } else if(HttpMethod.DELETE.equals(conf.get(IntegrationConstant.CONF.HTTP_METHOD.getCode()))){
// client = new DeleteClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// } else {
// throw new RuntimeException("提供的HttpMethod方法有误,请检查!");
// }
// connector = new RestConnector();
// ((AbstractWSConnector)connector).setClient(client);
// }
// long endTime1 = Calendar.getInstance().getTimeInMillis();
// logger.info("初始化连接共耗时" + (endTime1 - startTime) + "毫秒");
// Object result = connector.connect(connectorId, facadeId, models);
// long endTime2 = Calendar.getInstance().getTimeInMillis();
// logger.info("本次执行共耗时" + (endTime2 - startTime) + "毫秒,排除初始化连接后的耗时" + (endTime2 - endTime1) + "毫秒,连接方式:" + connectMode + ",调用Facade:" + facadeId);
// return result;
// }
//
// }
// Path: architecture-integration/src/main/java/com/ea/core/integration/bridge/MQIntegration.java
import java.util.HashMap;
import java.util.Map;
import com.ea.core.integration.IntegrationConstant;
import com.ea.core.integration.IntegrationContext;
package com.ea.core.integration.bridge;
public class MQIntegration {
public void connect(String host, String username, String password, String queueName, String facadeId, Object... obj) throws Exception{ | IntegrationContext context = new IntegrationContext(); |
yiyongfei/jea | architecture-orm/src/main/java/com/ea/core/orm/handle/impl/QueryListORMHandle.java | // Path: architecture-orm/src/main/java/com/ea/core/orm/handle/AbstractORMHandle.java
// public abstract class AbstractORMHandle implements ORMHandle, ApplicationContextAware {
// protected ApplicationContext context = null;
//
// @Autowired
// private SqlSessionTemplate mybatisSessionTemplate;
// @Autowired
// private SessionFactory hibernateSessionFactory;
//
// private String level;
// private ORMHandle nextHandle;
//
// public AbstractORMHandle(String level){
// this.level = level;
// }
//
// /**
// * 符合当前Level,则执行DB操作,否则交由下个Handle去执行
// */
// public final Object handle(String level, ORMParamsDTO dto) throws Exception {
// if(this.level.equals(level)){
// return this.execute(dto);
// } else {
// this.setNextHandle();
// if(this.nextHandle != null){
// return this.nextHandle.handle(level, dto);
// } else {
// throw new Exception("必须设置ORMHandle处理当前请求");
// }
// }
// }
//
// /**
// * 执行DB操作
// * @param dto
// * @return
// * @throws Exception
// */
// protected abstract Object execute(ORMParamsDTO dto) throws Exception;
//
// /**
// * 设置下个Handle,子类设置,如果是最后一个Handle,不设置
// */
// public abstract void setNextHandle();
//
// protected SqlSessionTemplate getMybatisSessionTemplate() {
// return mybatisSessionTemplate;
// }
//
// protected SessionFactory getHibernateSessionFactory() {
// return hibernateSessionFactory;
// }
//
// public void setApplicationContext(ApplicationContext applicationContext) {
// // TODO Auto-generated method stub
// context = applicationContext;
// }
//
// protected void setNextHandle(ORMHandle nextHandle){
// this.nextHandle = nextHandle;
// }
//
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/ORMHandle.java
// public interface ORMHandle {
//
// public Object handle(String level, ORMParamsDTO dto) throws Exception;
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/dto/ORMParamsDTO.java
// public class ORMParamsDTO implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private Object param;
// private String sqlid;
//
// public Object getParam() {
// return param;
// }
// public void setParam(Object param) {
// this.param = param;
// }
// public String getSqlid() {
// return sqlid;
// }
// public void setSqlid(String sqlid) {
// this.sqlid = sqlid;
// }
//
// }
| import org.springframework.stereotype.Component;
import com.ea.core.orm.handle.AbstractORMHandle;
import com.ea.core.orm.handle.ORMConstants;
import com.ea.core.orm.handle.ORMHandle;
import com.ea.core.orm.handle.dto.ORMParamsDTO; | /**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.orm.handle.impl;
/**
* 查询一批符合条件的数据操作,由Mybatis完成
*
* @author yiyongfei
*
*/
@Component
public class QueryListORMHandle extends AbstractORMHandle {
public QueryListORMHandle() {
super(ORMConstants.ORM_LEVEL.QUERYLIST.getCode());
}
@Override | // Path: architecture-orm/src/main/java/com/ea/core/orm/handle/AbstractORMHandle.java
// public abstract class AbstractORMHandle implements ORMHandle, ApplicationContextAware {
// protected ApplicationContext context = null;
//
// @Autowired
// private SqlSessionTemplate mybatisSessionTemplate;
// @Autowired
// private SessionFactory hibernateSessionFactory;
//
// private String level;
// private ORMHandle nextHandle;
//
// public AbstractORMHandle(String level){
// this.level = level;
// }
//
// /**
// * 符合当前Level,则执行DB操作,否则交由下个Handle去执行
// */
// public final Object handle(String level, ORMParamsDTO dto) throws Exception {
// if(this.level.equals(level)){
// return this.execute(dto);
// } else {
// this.setNextHandle();
// if(this.nextHandle != null){
// return this.nextHandle.handle(level, dto);
// } else {
// throw new Exception("必须设置ORMHandle处理当前请求");
// }
// }
// }
//
// /**
// * 执行DB操作
// * @param dto
// * @return
// * @throws Exception
// */
// protected abstract Object execute(ORMParamsDTO dto) throws Exception;
//
// /**
// * 设置下个Handle,子类设置,如果是最后一个Handle,不设置
// */
// public abstract void setNextHandle();
//
// protected SqlSessionTemplate getMybatisSessionTemplate() {
// return mybatisSessionTemplate;
// }
//
// protected SessionFactory getHibernateSessionFactory() {
// return hibernateSessionFactory;
// }
//
// public void setApplicationContext(ApplicationContext applicationContext) {
// // TODO Auto-generated method stub
// context = applicationContext;
// }
//
// protected void setNextHandle(ORMHandle nextHandle){
// this.nextHandle = nextHandle;
// }
//
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/ORMHandle.java
// public interface ORMHandle {
//
// public Object handle(String level, ORMParamsDTO dto) throws Exception;
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/dto/ORMParamsDTO.java
// public class ORMParamsDTO implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private Object param;
// private String sqlid;
//
// public Object getParam() {
// return param;
// }
// public void setParam(Object param) {
// this.param = param;
// }
// public String getSqlid() {
// return sqlid;
// }
// public void setSqlid(String sqlid) {
// this.sqlid = sqlid;
// }
//
// }
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/impl/QueryListORMHandle.java
import org.springframework.stereotype.Component;
import com.ea.core.orm.handle.AbstractORMHandle;
import com.ea.core.orm.handle.ORMConstants;
import com.ea.core.orm.handle.ORMHandle;
import com.ea.core.orm.handle.dto.ORMParamsDTO;
/**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.orm.handle.impl;
/**
* 查询一批符合条件的数据操作,由Mybatis完成
*
* @author yiyongfei
*
*/
@Component
public class QueryListORMHandle extends AbstractORMHandle {
public QueryListORMHandle() {
super(ORMConstants.ORM_LEVEL.QUERYLIST.getCode());
}
@Override | protected Object execute(ORMParamsDTO dto) { |
yiyongfei/jea | architecture-orm/src/main/java/com/ea/core/orm/handle/impl/QueryListORMHandle.java | // Path: architecture-orm/src/main/java/com/ea/core/orm/handle/AbstractORMHandle.java
// public abstract class AbstractORMHandle implements ORMHandle, ApplicationContextAware {
// protected ApplicationContext context = null;
//
// @Autowired
// private SqlSessionTemplate mybatisSessionTemplate;
// @Autowired
// private SessionFactory hibernateSessionFactory;
//
// private String level;
// private ORMHandle nextHandle;
//
// public AbstractORMHandle(String level){
// this.level = level;
// }
//
// /**
// * 符合当前Level,则执行DB操作,否则交由下个Handle去执行
// */
// public final Object handle(String level, ORMParamsDTO dto) throws Exception {
// if(this.level.equals(level)){
// return this.execute(dto);
// } else {
// this.setNextHandle();
// if(this.nextHandle != null){
// return this.nextHandle.handle(level, dto);
// } else {
// throw new Exception("必须设置ORMHandle处理当前请求");
// }
// }
// }
//
// /**
// * 执行DB操作
// * @param dto
// * @return
// * @throws Exception
// */
// protected abstract Object execute(ORMParamsDTO dto) throws Exception;
//
// /**
// * 设置下个Handle,子类设置,如果是最后一个Handle,不设置
// */
// public abstract void setNextHandle();
//
// protected SqlSessionTemplate getMybatisSessionTemplate() {
// return mybatisSessionTemplate;
// }
//
// protected SessionFactory getHibernateSessionFactory() {
// return hibernateSessionFactory;
// }
//
// public void setApplicationContext(ApplicationContext applicationContext) {
// // TODO Auto-generated method stub
// context = applicationContext;
// }
//
// protected void setNextHandle(ORMHandle nextHandle){
// this.nextHandle = nextHandle;
// }
//
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/ORMHandle.java
// public interface ORMHandle {
//
// public Object handle(String level, ORMParamsDTO dto) throws Exception;
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/dto/ORMParamsDTO.java
// public class ORMParamsDTO implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private Object param;
// private String sqlid;
//
// public Object getParam() {
// return param;
// }
// public void setParam(Object param) {
// this.param = param;
// }
// public String getSqlid() {
// return sqlid;
// }
// public void setSqlid(String sqlid) {
// this.sqlid = sqlid;
// }
//
// }
| import org.springframework.stereotype.Component;
import com.ea.core.orm.handle.AbstractORMHandle;
import com.ea.core.orm.handle.ORMConstants;
import com.ea.core.orm.handle.ORMHandle;
import com.ea.core.orm.handle.dto.ORMParamsDTO; | /**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.orm.handle.impl;
/**
* 查询一批符合条件的数据操作,由Mybatis完成
*
* @author yiyongfei
*
*/
@Component
public class QueryListORMHandle extends AbstractORMHandle {
public QueryListORMHandle() {
super(ORMConstants.ORM_LEVEL.QUERYLIST.getCode());
}
@Override
protected Object execute(ORMParamsDTO dto) {
// TODO Auto-generated method stub
if(dto.getParam() == null){
return this.getMybatisSessionTemplate().selectList(dto.getSqlid());
}
return this.getMybatisSessionTemplate().selectList(dto.getSqlid(), dto.getParam());
}
@Override
public void setNextHandle() { | // Path: architecture-orm/src/main/java/com/ea/core/orm/handle/AbstractORMHandle.java
// public abstract class AbstractORMHandle implements ORMHandle, ApplicationContextAware {
// protected ApplicationContext context = null;
//
// @Autowired
// private SqlSessionTemplate mybatisSessionTemplate;
// @Autowired
// private SessionFactory hibernateSessionFactory;
//
// private String level;
// private ORMHandle nextHandle;
//
// public AbstractORMHandle(String level){
// this.level = level;
// }
//
// /**
// * 符合当前Level,则执行DB操作,否则交由下个Handle去执行
// */
// public final Object handle(String level, ORMParamsDTO dto) throws Exception {
// if(this.level.equals(level)){
// return this.execute(dto);
// } else {
// this.setNextHandle();
// if(this.nextHandle != null){
// return this.nextHandle.handle(level, dto);
// } else {
// throw new Exception("必须设置ORMHandle处理当前请求");
// }
// }
// }
//
// /**
// * 执行DB操作
// * @param dto
// * @return
// * @throws Exception
// */
// protected abstract Object execute(ORMParamsDTO dto) throws Exception;
//
// /**
// * 设置下个Handle,子类设置,如果是最后一个Handle,不设置
// */
// public abstract void setNextHandle();
//
// protected SqlSessionTemplate getMybatisSessionTemplate() {
// return mybatisSessionTemplate;
// }
//
// protected SessionFactory getHibernateSessionFactory() {
// return hibernateSessionFactory;
// }
//
// public void setApplicationContext(ApplicationContext applicationContext) {
// // TODO Auto-generated method stub
// context = applicationContext;
// }
//
// protected void setNextHandle(ORMHandle nextHandle){
// this.nextHandle = nextHandle;
// }
//
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/ORMHandle.java
// public interface ORMHandle {
//
// public Object handle(String level, ORMParamsDTO dto) throws Exception;
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/dto/ORMParamsDTO.java
// public class ORMParamsDTO implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private Object param;
// private String sqlid;
//
// public Object getParam() {
// return param;
// }
// public void setParam(Object param) {
// this.param = param;
// }
// public String getSqlid() {
// return sqlid;
// }
// public void setSqlid(String sqlid) {
// this.sqlid = sqlid;
// }
//
// }
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/impl/QueryListORMHandle.java
import org.springframework.stereotype.Component;
import com.ea.core.orm.handle.AbstractORMHandle;
import com.ea.core.orm.handle.ORMConstants;
import com.ea.core.orm.handle.ORMHandle;
import com.ea.core.orm.handle.dto.ORMParamsDTO;
/**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.orm.handle.impl;
/**
* 查询一批符合条件的数据操作,由Mybatis完成
*
* @author yiyongfei
*
*/
@Component
public class QueryListORMHandle extends AbstractORMHandle {
public QueryListORMHandle() {
super(ORMConstants.ORM_LEVEL.QUERYLIST.getCode());
}
@Override
protected Object execute(ORMParamsDTO dto) {
// TODO Auto-generated method stub
if(dto.getParam() == null){
return this.getMybatisSessionTemplate().selectList(dto.getSqlid());
}
return this.getMybatisSessionTemplate().selectList(dto.getSqlid(), dto.getParam());
}
@Override
public void setNextHandle() { | ORMHandle nextHandle = (HibernateSqlORMHandle)this.context.getBean("hibernateSqlORMHandle"); |
yiyongfei/jea | architecture-orm/src/main/java/com/ea/core/orm/handle/impl/SaveORMHandle.java | // Path: architecture-orm/src/main/java/com/ea/core/orm/handle/AbstractORMHandle.java
// public abstract class AbstractORMHandle implements ORMHandle, ApplicationContextAware {
// protected ApplicationContext context = null;
//
// @Autowired
// private SqlSessionTemplate mybatisSessionTemplate;
// @Autowired
// private SessionFactory hibernateSessionFactory;
//
// private String level;
// private ORMHandle nextHandle;
//
// public AbstractORMHandle(String level){
// this.level = level;
// }
//
// /**
// * 符合当前Level,则执行DB操作,否则交由下个Handle去执行
// */
// public final Object handle(String level, ORMParamsDTO dto) throws Exception {
// if(this.level.equals(level)){
// return this.execute(dto);
// } else {
// this.setNextHandle();
// if(this.nextHandle != null){
// return this.nextHandle.handle(level, dto);
// } else {
// throw new Exception("必须设置ORMHandle处理当前请求");
// }
// }
// }
//
// /**
// * 执行DB操作
// * @param dto
// * @return
// * @throws Exception
// */
// protected abstract Object execute(ORMParamsDTO dto) throws Exception;
//
// /**
// * 设置下个Handle,子类设置,如果是最后一个Handle,不设置
// */
// public abstract void setNextHandle();
//
// protected SqlSessionTemplate getMybatisSessionTemplate() {
// return mybatisSessionTemplate;
// }
//
// protected SessionFactory getHibernateSessionFactory() {
// return hibernateSessionFactory;
// }
//
// public void setApplicationContext(ApplicationContext applicationContext) {
// // TODO Auto-generated method stub
// context = applicationContext;
// }
//
// protected void setNextHandle(ORMHandle nextHandle){
// this.nextHandle = nextHandle;
// }
//
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/ORMHandle.java
// public interface ORMHandle {
//
// public Object handle(String level, ORMParamsDTO dto) throws Exception;
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/dto/ORMParamsDTO.java
// public class ORMParamsDTO implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private Object param;
// private String sqlid;
//
// public Object getParam() {
// return param;
// }
// public void setParam(Object param) {
// this.param = param;
// }
// public String getSqlid() {
// return sqlid;
// }
// public void setSqlid(String sqlid) {
// this.sqlid = sqlid;
// }
//
// }
| import org.hibernate.Session;
import org.springframework.stereotype.Component;
import com.ea.core.base.po.BasePO;
import com.ea.core.orm.handle.AbstractORMHandle;
import com.ea.core.orm.handle.ORMConstants;
import com.ea.core.orm.handle.ORMHandle;
import com.ea.core.orm.handle.dto.ORMParamsDTO; | /**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.orm.handle.impl;
/**
* 新增操作,由Hibnerate完成
*
* @author yiyongfei
*
*/
@Component
public class SaveORMHandle extends AbstractORMHandle {
public SaveORMHandle() {
super(ORMConstants.ORM_LEVEL.SAVE.getCode());
}
@Override | // Path: architecture-orm/src/main/java/com/ea/core/orm/handle/AbstractORMHandle.java
// public abstract class AbstractORMHandle implements ORMHandle, ApplicationContextAware {
// protected ApplicationContext context = null;
//
// @Autowired
// private SqlSessionTemplate mybatisSessionTemplate;
// @Autowired
// private SessionFactory hibernateSessionFactory;
//
// private String level;
// private ORMHandle nextHandle;
//
// public AbstractORMHandle(String level){
// this.level = level;
// }
//
// /**
// * 符合当前Level,则执行DB操作,否则交由下个Handle去执行
// */
// public final Object handle(String level, ORMParamsDTO dto) throws Exception {
// if(this.level.equals(level)){
// return this.execute(dto);
// } else {
// this.setNextHandle();
// if(this.nextHandle != null){
// return this.nextHandle.handle(level, dto);
// } else {
// throw new Exception("必须设置ORMHandle处理当前请求");
// }
// }
// }
//
// /**
// * 执行DB操作
// * @param dto
// * @return
// * @throws Exception
// */
// protected abstract Object execute(ORMParamsDTO dto) throws Exception;
//
// /**
// * 设置下个Handle,子类设置,如果是最后一个Handle,不设置
// */
// public abstract void setNextHandle();
//
// protected SqlSessionTemplate getMybatisSessionTemplate() {
// return mybatisSessionTemplate;
// }
//
// protected SessionFactory getHibernateSessionFactory() {
// return hibernateSessionFactory;
// }
//
// public void setApplicationContext(ApplicationContext applicationContext) {
// // TODO Auto-generated method stub
// context = applicationContext;
// }
//
// protected void setNextHandle(ORMHandle nextHandle){
// this.nextHandle = nextHandle;
// }
//
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/ORMHandle.java
// public interface ORMHandle {
//
// public Object handle(String level, ORMParamsDTO dto) throws Exception;
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/dto/ORMParamsDTO.java
// public class ORMParamsDTO implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private Object param;
// private String sqlid;
//
// public Object getParam() {
// return param;
// }
// public void setParam(Object param) {
// this.param = param;
// }
// public String getSqlid() {
// return sqlid;
// }
// public void setSqlid(String sqlid) {
// this.sqlid = sqlid;
// }
//
// }
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/impl/SaveORMHandle.java
import org.hibernate.Session;
import org.springframework.stereotype.Component;
import com.ea.core.base.po.BasePO;
import com.ea.core.orm.handle.AbstractORMHandle;
import com.ea.core.orm.handle.ORMConstants;
import com.ea.core.orm.handle.ORMHandle;
import com.ea.core.orm.handle.dto.ORMParamsDTO;
/**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.orm.handle.impl;
/**
* 新增操作,由Hibnerate完成
*
* @author yiyongfei
*
*/
@Component
public class SaveORMHandle extends AbstractORMHandle {
public SaveORMHandle() {
super(ORMConstants.ORM_LEVEL.SAVE.getCode());
}
@Override | protected Object execute(ORMParamsDTO dto) throws Exception { |
yiyongfei/jea | architecture-orm/src/main/java/com/ea/core/orm/handle/impl/SaveORMHandle.java | // Path: architecture-orm/src/main/java/com/ea/core/orm/handle/AbstractORMHandle.java
// public abstract class AbstractORMHandle implements ORMHandle, ApplicationContextAware {
// protected ApplicationContext context = null;
//
// @Autowired
// private SqlSessionTemplate mybatisSessionTemplate;
// @Autowired
// private SessionFactory hibernateSessionFactory;
//
// private String level;
// private ORMHandle nextHandle;
//
// public AbstractORMHandle(String level){
// this.level = level;
// }
//
// /**
// * 符合当前Level,则执行DB操作,否则交由下个Handle去执行
// */
// public final Object handle(String level, ORMParamsDTO dto) throws Exception {
// if(this.level.equals(level)){
// return this.execute(dto);
// } else {
// this.setNextHandle();
// if(this.nextHandle != null){
// return this.nextHandle.handle(level, dto);
// } else {
// throw new Exception("必须设置ORMHandle处理当前请求");
// }
// }
// }
//
// /**
// * 执行DB操作
// * @param dto
// * @return
// * @throws Exception
// */
// protected abstract Object execute(ORMParamsDTO dto) throws Exception;
//
// /**
// * 设置下个Handle,子类设置,如果是最后一个Handle,不设置
// */
// public abstract void setNextHandle();
//
// protected SqlSessionTemplate getMybatisSessionTemplate() {
// return mybatisSessionTemplate;
// }
//
// protected SessionFactory getHibernateSessionFactory() {
// return hibernateSessionFactory;
// }
//
// public void setApplicationContext(ApplicationContext applicationContext) {
// // TODO Auto-generated method stub
// context = applicationContext;
// }
//
// protected void setNextHandle(ORMHandle nextHandle){
// this.nextHandle = nextHandle;
// }
//
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/ORMHandle.java
// public interface ORMHandle {
//
// public Object handle(String level, ORMParamsDTO dto) throws Exception;
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/dto/ORMParamsDTO.java
// public class ORMParamsDTO implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private Object param;
// private String sqlid;
//
// public Object getParam() {
// return param;
// }
// public void setParam(Object param) {
// this.param = param;
// }
// public String getSqlid() {
// return sqlid;
// }
// public void setSqlid(String sqlid) {
// this.sqlid = sqlid;
// }
//
// }
| import org.hibernate.Session;
import org.springframework.stereotype.Component;
import com.ea.core.base.po.BasePO;
import com.ea.core.orm.handle.AbstractORMHandle;
import com.ea.core.orm.handle.ORMConstants;
import com.ea.core.orm.handle.ORMHandle;
import com.ea.core.orm.handle.dto.ORMParamsDTO; | /**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.orm.handle.impl;
/**
* 新增操作,由Hibnerate完成
*
* @author yiyongfei
*
*/
@Component
public class SaveORMHandle extends AbstractORMHandle {
public SaveORMHandle() {
super(ORMConstants.ORM_LEVEL.SAVE.getCode());
}
@Override
protected Object execute(ORMParamsDTO dto) throws Exception {
// TODO Auto-generated method stub
Object po = dto.getParam();
if(po instanceof BasePO){
Session session = this.getHibernateSessionFactory().getCurrentSession();
((BasePO) po).getPk().generatorPK();
Object obj = session.save(po);
return obj;
} else {
throw new Exception("参数请确认是否继承BasePO!");
}
}
@Override
public void setNextHandle() {
// TODO Auto-generated method stub | // Path: architecture-orm/src/main/java/com/ea/core/orm/handle/AbstractORMHandle.java
// public abstract class AbstractORMHandle implements ORMHandle, ApplicationContextAware {
// protected ApplicationContext context = null;
//
// @Autowired
// private SqlSessionTemplate mybatisSessionTemplate;
// @Autowired
// private SessionFactory hibernateSessionFactory;
//
// private String level;
// private ORMHandle nextHandle;
//
// public AbstractORMHandle(String level){
// this.level = level;
// }
//
// /**
// * 符合当前Level,则执行DB操作,否则交由下个Handle去执行
// */
// public final Object handle(String level, ORMParamsDTO dto) throws Exception {
// if(this.level.equals(level)){
// return this.execute(dto);
// } else {
// this.setNextHandle();
// if(this.nextHandle != null){
// return this.nextHandle.handle(level, dto);
// } else {
// throw new Exception("必须设置ORMHandle处理当前请求");
// }
// }
// }
//
// /**
// * 执行DB操作
// * @param dto
// * @return
// * @throws Exception
// */
// protected abstract Object execute(ORMParamsDTO dto) throws Exception;
//
// /**
// * 设置下个Handle,子类设置,如果是最后一个Handle,不设置
// */
// public abstract void setNextHandle();
//
// protected SqlSessionTemplate getMybatisSessionTemplate() {
// return mybatisSessionTemplate;
// }
//
// protected SessionFactory getHibernateSessionFactory() {
// return hibernateSessionFactory;
// }
//
// public void setApplicationContext(ApplicationContext applicationContext) {
// // TODO Auto-generated method stub
// context = applicationContext;
// }
//
// protected void setNextHandle(ORMHandle nextHandle){
// this.nextHandle = nextHandle;
// }
//
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/ORMHandle.java
// public interface ORMHandle {
//
// public Object handle(String level, ORMParamsDTO dto) throws Exception;
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/dto/ORMParamsDTO.java
// public class ORMParamsDTO implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private Object param;
// private String sqlid;
//
// public Object getParam() {
// return param;
// }
// public void setParam(Object param) {
// this.param = param;
// }
// public String getSqlid() {
// return sqlid;
// }
// public void setSqlid(String sqlid) {
// this.sqlid = sqlid;
// }
//
// }
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/impl/SaveORMHandle.java
import org.hibernate.Session;
import org.springframework.stereotype.Component;
import com.ea.core.base.po.BasePO;
import com.ea.core.orm.handle.AbstractORMHandle;
import com.ea.core.orm.handle.ORMConstants;
import com.ea.core.orm.handle.ORMHandle;
import com.ea.core.orm.handle.dto.ORMParamsDTO;
/**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.orm.handle.impl;
/**
* 新增操作,由Hibnerate完成
*
* @author yiyongfei
*
*/
@Component
public class SaveORMHandle extends AbstractORMHandle {
public SaveORMHandle() {
super(ORMConstants.ORM_LEVEL.SAVE.getCode());
}
@Override
protected Object execute(ORMParamsDTO dto) throws Exception {
// TODO Auto-generated method stub
Object po = dto.getParam();
if(po instanceof BasePO){
Session session = this.getHibernateSessionFactory().getCurrentSession();
((BasePO) po).getPk().generatorPK();
Object obj = session.save(po);
return obj;
} else {
throw new Exception("参数请确认是否继承BasePO!");
}
}
@Override
public void setNextHandle() {
// TODO Auto-generated method stub | ORMHandle nextHandle = (DeleteORMHandle)this.context.getBean("deleteORMHandle"); |
yiyongfei/jea | architecture-core/src/main/java/com/ea/core/base/dto/DynamicDTO.java | // Path: architecture-core/src/main/java/com/ea/core/base/model/BaseModel.java
// public class BaseModel implements Serializable {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// }
//
// Path: architecture-core/src/main/java/com/ea/core/typeconverter/impl/StringConverter.java
// public class StringConverter extends jodd.typeconverter.impl.StringConverter {
// private String dateFormat = "YYYY-MM-DD hh:mm:ss";
//
// @Override
// public String convert(Object value) {
// if(value instanceof Date){
// JDateTime jDateTime = new JDateTime(((Date)value));
// return jDateTime.toString(dateFormat);
// }
// return super.convert(value);
// }
//
// public String getDateFormat() {
// return dateFormat;
// }
//
// public void setDateFormat(String dateFormat) {
// this.dateFormat = dateFormat;
// }
//
// }
| import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import jodd.typeconverter.TypeConverterManager;
import org.springframework.cglib.beans.BeanGenerator;
import org.springframework.cglib.beans.BeanMap;
import com.ea.core.base.model.BaseModel;
import com.ea.core.typeconverter.impl.StringConverter; | }
public Object getCloneBean() {
try {
Object tmpObject = generator.create();
BeanMap tmpMap = BeanMap.create(tmpObject);
tmpMap.putAll(valueMap);
return tmpObject;
} catch (Exception e) {
return null;
}
}
public Map<String, Object> getMap(){
return valueMap;
}
/**
* 转换器,设置DynamicDTO的属性值到对应的Model对象
*
* @param target
*/
@SuppressWarnings("unchecked")
public void convert(BaseModel target) {
BeanMap tmp = BeanMap.create(target);
Iterator<String> keys = tmp.keySet().iterator();
String key = null;
while(keys.hasNext()){
key = keys.next();
if(beanMap.containsKey(key)){ | // Path: architecture-core/src/main/java/com/ea/core/base/model/BaseModel.java
// public class BaseModel implements Serializable {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// }
//
// Path: architecture-core/src/main/java/com/ea/core/typeconverter/impl/StringConverter.java
// public class StringConverter extends jodd.typeconverter.impl.StringConverter {
// private String dateFormat = "YYYY-MM-DD hh:mm:ss";
//
// @Override
// public String convert(Object value) {
// if(value instanceof Date){
// JDateTime jDateTime = new JDateTime(((Date)value));
// return jDateTime.toString(dateFormat);
// }
// return super.convert(value);
// }
//
// public String getDateFormat() {
// return dateFormat;
// }
//
// public void setDateFormat(String dateFormat) {
// this.dateFormat = dateFormat;
// }
//
// }
// Path: architecture-core/src/main/java/com/ea/core/base/dto/DynamicDTO.java
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import jodd.typeconverter.TypeConverterManager;
import org.springframework.cglib.beans.BeanGenerator;
import org.springframework.cglib.beans.BeanMap;
import com.ea.core.base.model.BaseModel;
import com.ea.core.typeconverter.impl.StringConverter;
}
public Object getCloneBean() {
try {
Object tmpObject = generator.create();
BeanMap tmpMap = BeanMap.create(tmpObject);
tmpMap.putAll(valueMap);
return tmpObject;
} catch (Exception e) {
return null;
}
}
public Map<String, Object> getMap(){
return valueMap;
}
/**
* 转换器,设置DynamicDTO的属性值到对应的Model对象
*
* @param target
*/
@SuppressWarnings("unchecked")
public void convert(BaseModel target) {
BeanMap tmp = BeanMap.create(target);
Iterator<String> keys = tmp.keySet().iterator();
String key = null;
while(keys.hasNext()){
key = keys.next();
if(beanMap.containsKey(key)){ | StringConverter converter = new StringConverter(); |
yiyongfei/jea | architecture-orm/src/main/java/com/ea/core/orm/handle/impl/DeleteORMHandle.java | // Path: architecture-orm/src/main/java/com/ea/core/orm/handle/AbstractORMHandle.java
// public abstract class AbstractORMHandle implements ORMHandle, ApplicationContextAware {
// protected ApplicationContext context = null;
//
// @Autowired
// private SqlSessionTemplate mybatisSessionTemplate;
// @Autowired
// private SessionFactory hibernateSessionFactory;
//
// private String level;
// private ORMHandle nextHandle;
//
// public AbstractORMHandle(String level){
// this.level = level;
// }
//
// /**
// * 符合当前Level,则执行DB操作,否则交由下个Handle去执行
// */
// public final Object handle(String level, ORMParamsDTO dto) throws Exception {
// if(this.level.equals(level)){
// return this.execute(dto);
// } else {
// this.setNextHandle();
// if(this.nextHandle != null){
// return this.nextHandle.handle(level, dto);
// } else {
// throw new Exception("必须设置ORMHandle处理当前请求");
// }
// }
// }
//
// /**
// * 执行DB操作
// * @param dto
// * @return
// * @throws Exception
// */
// protected abstract Object execute(ORMParamsDTO dto) throws Exception;
//
// /**
// * 设置下个Handle,子类设置,如果是最后一个Handle,不设置
// */
// public abstract void setNextHandle();
//
// protected SqlSessionTemplate getMybatisSessionTemplate() {
// return mybatisSessionTemplate;
// }
//
// protected SessionFactory getHibernateSessionFactory() {
// return hibernateSessionFactory;
// }
//
// public void setApplicationContext(ApplicationContext applicationContext) {
// // TODO Auto-generated method stub
// context = applicationContext;
// }
//
// protected void setNextHandle(ORMHandle nextHandle){
// this.nextHandle = nextHandle;
// }
//
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/ORMHandle.java
// public interface ORMHandle {
//
// public Object handle(String level, ORMParamsDTO dto) throws Exception;
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/dto/ORMParamsDTO.java
// public class ORMParamsDTO implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private Object param;
// private String sqlid;
//
// public Object getParam() {
// return param;
// }
// public void setParam(Object param) {
// this.param = param;
// }
// public String getSqlid() {
// return sqlid;
// }
// public void setSqlid(String sqlid) {
// this.sqlid = sqlid;
// }
//
// }
| import org.hibernate.Session;
import org.springframework.stereotype.Component;
import com.ea.core.base.po.BasePO;
import com.ea.core.orm.handle.AbstractORMHandle;
import com.ea.core.orm.handle.ORMConstants;
import com.ea.core.orm.handle.ORMHandle;
import com.ea.core.orm.handle.dto.ORMParamsDTO; | /**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.orm.handle.impl;
/**
* 删除操作,由Hibnerate完成
*
* @author yiyongfei
*
*/
@Component
public class DeleteORMHandle extends AbstractORMHandle {
public DeleteORMHandle() {
super(ORMConstants.ORM_LEVEL.DELETE.getCode());
}
@Override | // Path: architecture-orm/src/main/java/com/ea/core/orm/handle/AbstractORMHandle.java
// public abstract class AbstractORMHandle implements ORMHandle, ApplicationContextAware {
// protected ApplicationContext context = null;
//
// @Autowired
// private SqlSessionTemplate mybatisSessionTemplate;
// @Autowired
// private SessionFactory hibernateSessionFactory;
//
// private String level;
// private ORMHandle nextHandle;
//
// public AbstractORMHandle(String level){
// this.level = level;
// }
//
// /**
// * 符合当前Level,则执行DB操作,否则交由下个Handle去执行
// */
// public final Object handle(String level, ORMParamsDTO dto) throws Exception {
// if(this.level.equals(level)){
// return this.execute(dto);
// } else {
// this.setNextHandle();
// if(this.nextHandle != null){
// return this.nextHandle.handle(level, dto);
// } else {
// throw new Exception("必须设置ORMHandle处理当前请求");
// }
// }
// }
//
// /**
// * 执行DB操作
// * @param dto
// * @return
// * @throws Exception
// */
// protected abstract Object execute(ORMParamsDTO dto) throws Exception;
//
// /**
// * 设置下个Handle,子类设置,如果是最后一个Handle,不设置
// */
// public abstract void setNextHandle();
//
// protected SqlSessionTemplate getMybatisSessionTemplate() {
// return mybatisSessionTemplate;
// }
//
// protected SessionFactory getHibernateSessionFactory() {
// return hibernateSessionFactory;
// }
//
// public void setApplicationContext(ApplicationContext applicationContext) {
// // TODO Auto-generated method stub
// context = applicationContext;
// }
//
// protected void setNextHandle(ORMHandle nextHandle){
// this.nextHandle = nextHandle;
// }
//
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/ORMHandle.java
// public interface ORMHandle {
//
// public Object handle(String level, ORMParamsDTO dto) throws Exception;
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/dto/ORMParamsDTO.java
// public class ORMParamsDTO implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private Object param;
// private String sqlid;
//
// public Object getParam() {
// return param;
// }
// public void setParam(Object param) {
// this.param = param;
// }
// public String getSqlid() {
// return sqlid;
// }
// public void setSqlid(String sqlid) {
// this.sqlid = sqlid;
// }
//
// }
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/impl/DeleteORMHandle.java
import org.hibernate.Session;
import org.springframework.stereotype.Component;
import com.ea.core.base.po.BasePO;
import com.ea.core.orm.handle.AbstractORMHandle;
import com.ea.core.orm.handle.ORMConstants;
import com.ea.core.orm.handle.ORMHandle;
import com.ea.core.orm.handle.dto.ORMParamsDTO;
/**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.orm.handle.impl;
/**
* 删除操作,由Hibnerate完成
*
* @author yiyongfei
*
*/
@Component
public class DeleteORMHandle extends AbstractORMHandle {
public DeleteORMHandle() {
super(ORMConstants.ORM_LEVEL.DELETE.getCode());
}
@Override | protected Object execute(ORMParamsDTO dto) throws Exception { |
yiyongfei/jea | architecture-orm/src/main/java/com/ea/core/orm/handle/impl/DeleteORMHandle.java | // Path: architecture-orm/src/main/java/com/ea/core/orm/handle/AbstractORMHandle.java
// public abstract class AbstractORMHandle implements ORMHandle, ApplicationContextAware {
// protected ApplicationContext context = null;
//
// @Autowired
// private SqlSessionTemplate mybatisSessionTemplate;
// @Autowired
// private SessionFactory hibernateSessionFactory;
//
// private String level;
// private ORMHandle nextHandle;
//
// public AbstractORMHandle(String level){
// this.level = level;
// }
//
// /**
// * 符合当前Level,则执行DB操作,否则交由下个Handle去执行
// */
// public final Object handle(String level, ORMParamsDTO dto) throws Exception {
// if(this.level.equals(level)){
// return this.execute(dto);
// } else {
// this.setNextHandle();
// if(this.nextHandle != null){
// return this.nextHandle.handle(level, dto);
// } else {
// throw new Exception("必须设置ORMHandle处理当前请求");
// }
// }
// }
//
// /**
// * 执行DB操作
// * @param dto
// * @return
// * @throws Exception
// */
// protected abstract Object execute(ORMParamsDTO dto) throws Exception;
//
// /**
// * 设置下个Handle,子类设置,如果是最后一个Handle,不设置
// */
// public abstract void setNextHandle();
//
// protected SqlSessionTemplate getMybatisSessionTemplate() {
// return mybatisSessionTemplate;
// }
//
// protected SessionFactory getHibernateSessionFactory() {
// return hibernateSessionFactory;
// }
//
// public void setApplicationContext(ApplicationContext applicationContext) {
// // TODO Auto-generated method stub
// context = applicationContext;
// }
//
// protected void setNextHandle(ORMHandle nextHandle){
// this.nextHandle = nextHandle;
// }
//
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/ORMHandle.java
// public interface ORMHandle {
//
// public Object handle(String level, ORMParamsDTO dto) throws Exception;
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/dto/ORMParamsDTO.java
// public class ORMParamsDTO implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private Object param;
// private String sqlid;
//
// public Object getParam() {
// return param;
// }
// public void setParam(Object param) {
// this.param = param;
// }
// public String getSqlid() {
// return sqlid;
// }
// public void setSqlid(String sqlid) {
// this.sqlid = sqlid;
// }
//
// }
| import org.hibernate.Session;
import org.springframework.stereotype.Component;
import com.ea.core.base.po.BasePO;
import com.ea.core.orm.handle.AbstractORMHandle;
import com.ea.core.orm.handle.ORMConstants;
import com.ea.core.orm.handle.ORMHandle;
import com.ea.core.orm.handle.dto.ORMParamsDTO; | /**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.orm.handle.impl;
/**
* 删除操作,由Hibnerate完成
*
* @author yiyongfei
*
*/
@Component
public class DeleteORMHandle extends AbstractORMHandle {
public DeleteORMHandle() {
super(ORMConstants.ORM_LEVEL.DELETE.getCode());
}
@Override
protected Object execute(ORMParamsDTO dto) throws Exception {
// TODO Auto-generated method stub
Object po = dto.getParam();
if(po instanceof BasePO){
Session session = this.getHibernateSessionFactory().getCurrentSession();
session.delete(po);
return null;
} else {
throw new Exception("参数请确认是否继承BasePO!");
}
}
@Override
public void setNextHandle() {
// TODO Auto-generated method stub | // Path: architecture-orm/src/main/java/com/ea/core/orm/handle/AbstractORMHandle.java
// public abstract class AbstractORMHandle implements ORMHandle, ApplicationContextAware {
// protected ApplicationContext context = null;
//
// @Autowired
// private SqlSessionTemplate mybatisSessionTemplate;
// @Autowired
// private SessionFactory hibernateSessionFactory;
//
// private String level;
// private ORMHandle nextHandle;
//
// public AbstractORMHandle(String level){
// this.level = level;
// }
//
// /**
// * 符合当前Level,则执行DB操作,否则交由下个Handle去执行
// */
// public final Object handle(String level, ORMParamsDTO dto) throws Exception {
// if(this.level.equals(level)){
// return this.execute(dto);
// } else {
// this.setNextHandle();
// if(this.nextHandle != null){
// return this.nextHandle.handle(level, dto);
// } else {
// throw new Exception("必须设置ORMHandle处理当前请求");
// }
// }
// }
//
// /**
// * 执行DB操作
// * @param dto
// * @return
// * @throws Exception
// */
// protected abstract Object execute(ORMParamsDTO dto) throws Exception;
//
// /**
// * 设置下个Handle,子类设置,如果是最后一个Handle,不设置
// */
// public abstract void setNextHandle();
//
// protected SqlSessionTemplate getMybatisSessionTemplate() {
// return mybatisSessionTemplate;
// }
//
// protected SessionFactory getHibernateSessionFactory() {
// return hibernateSessionFactory;
// }
//
// public void setApplicationContext(ApplicationContext applicationContext) {
// // TODO Auto-generated method stub
// context = applicationContext;
// }
//
// protected void setNextHandle(ORMHandle nextHandle){
// this.nextHandle = nextHandle;
// }
//
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/ORMHandle.java
// public interface ORMHandle {
//
// public Object handle(String level, ORMParamsDTO dto) throws Exception;
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/dto/ORMParamsDTO.java
// public class ORMParamsDTO implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private Object param;
// private String sqlid;
//
// public Object getParam() {
// return param;
// }
// public void setParam(Object param) {
// this.param = param;
// }
// public String getSqlid() {
// return sqlid;
// }
// public void setSqlid(String sqlid) {
// this.sqlid = sqlid;
// }
//
// }
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/impl/DeleteORMHandle.java
import org.hibernate.Session;
import org.springframework.stereotype.Component;
import com.ea.core.base.po.BasePO;
import com.ea.core.orm.handle.AbstractORMHandle;
import com.ea.core.orm.handle.ORMConstants;
import com.ea.core.orm.handle.ORMHandle;
import com.ea.core.orm.handle.dto.ORMParamsDTO;
/**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.orm.handle.impl;
/**
* 删除操作,由Hibnerate完成
*
* @author yiyongfei
*
*/
@Component
public class DeleteORMHandle extends AbstractORMHandle {
public DeleteORMHandle() {
super(ORMConstants.ORM_LEVEL.DELETE.getCode());
}
@Override
protected Object execute(ORMParamsDTO dto) throws Exception {
// TODO Auto-generated method stub
Object po = dto.getParam();
if(po instanceof BasePO){
Session session = this.getHibernateSessionFactory().getCurrentSession();
session.delete(po);
return null;
} else {
throw new Exception("参数请确认是否继承BasePO!");
}
}
@Override
public void setNextHandle() {
// TODO Auto-generated method stub | ORMHandle nextHandle = (UpdateORMHandle)this.context.getBean("updateORMHandle"); |
yiyongfei/jea | architecture-orm/src/main/java/com/ea/core/orm/handle/impl/LoadORMHandle.java | // Path: architecture-orm/src/main/java/com/ea/core/orm/handle/AbstractORMHandle.java
// public abstract class AbstractORMHandle implements ORMHandle, ApplicationContextAware {
// protected ApplicationContext context = null;
//
// @Autowired
// private SqlSessionTemplate mybatisSessionTemplate;
// @Autowired
// private SessionFactory hibernateSessionFactory;
//
// private String level;
// private ORMHandle nextHandle;
//
// public AbstractORMHandle(String level){
// this.level = level;
// }
//
// /**
// * 符合当前Level,则执行DB操作,否则交由下个Handle去执行
// */
// public final Object handle(String level, ORMParamsDTO dto) throws Exception {
// if(this.level.equals(level)){
// return this.execute(dto);
// } else {
// this.setNextHandle();
// if(this.nextHandle != null){
// return this.nextHandle.handle(level, dto);
// } else {
// throw new Exception("必须设置ORMHandle处理当前请求");
// }
// }
// }
//
// /**
// * 执行DB操作
// * @param dto
// * @return
// * @throws Exception
// */
// protected abstract Object execute(ORMParamsDTO dto) throws Exception;
//
// /**
// * 设置下个Handle,子类设置,如果是最后一个Handle,不设置
// */
// public abstract void setNextHandle();
//
// protected SqlSessionTemplate getMybatisSessionTemplate() {
// return mybatisSessionTemplate;
// }
//
// protected SessionFactory getHibernateSessionFactory() {
// return hibernateSessionFactory;
// }
//
// public void setApplicationContext(ApplicationContext applicationContext) {
// // TODO Auto-generated method stub
// context = applicationContext;
// }
//
// protected void setNextHandle(ORMHandle nextHandle){
// this.nextHandle = nextHandle;
// }
//
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/ORMHandle.java
// public interface ORMHandle {
//
// public Object handle(String level, ORMParamsDTO dto) throws Exception;
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/dto/ORMParamsDTO.java
// public class ORMParamsDTO implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private Object param;
// private String sqlid;
//
// public Object getParam() {
// return param;
// }
// public void setParam(Object param) {
// this.param = param;
// }
// public String getSqlid() {
// return sqlid;
// }
// public void setSqlid(String sqlid) {
// this.sqlid = sqlid;
// }
//
// }
| import org.hibernate.Session;
import org.springframework.stereotype.Component;
import com.ea.core.base.po.BasePO;
import com.ea.core.orm.handle.AbstractORMHandle;
import com.ea.core.orm.handle.ORMConstants;
import com.ea.core.orm.handle.ORMHandle;
import com.ea.core.orm.handle.dto.ORMParamsDTO; | /**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.orm.handle.impl;
/**
* 打开操作,由Hibnerate完成
*
* @author yiyongfei
*
*/
@Component
public class LoadORMHandle extends AbstractORMHandle {
public LoadORMHandle() {
super(ORMConstants.ORM_LEVEL.LOAD.getCode());
}
@Override | // Path: architecture-orm/src/main/java/com/ea/core/orm/handle/AbstractORMHandle.java
// public abstract class AbstractORMHandle implements ORMHandle, ApplicationContextAware {
// protected ApplicationContext context = null;
//
// @Autowired
// private SqlSessionTemplate mybatisSessionTemplate;
// @Autowired
// private SessionFactory hibernateSessionFactory;
//
// private String level;
// private ORMHandle nextHandle;
//
// public AbstractORMHandle(String level){
// this.level = level;
// }
//
// /**
// * 符合当前Level,则执行DB操作,否则交由下个Handle去执行
// */
// public final Object handle(String level, ORMParamsDTO dto) throws Exception {
// if(this.level.equals(level)){
// return this.execute(dto);
// } else {
// this.setNextHandle();
// if(this.nextHandle != null){
// return this.nextHandle.handle(level, dto);
// } else {
// throw new Exception("必须设置ORMHandle处理当前请求");
// }
// }
// }
//
// /**
// * 执行DB操作
// * @param dto
// * @return
// * @throws Exception
// */
// protected abstract Object execute(ORMParamsDTO dto) throws Exception;
//
// /**
// * 设置下个Handle,子类设置,如果是最后一个Handle,不设置
// */
// public abstract void setNextHandle();
//
// protected SqlSessionTemplate getMybatisSessionTemplate() {
// return mybatisSessionTemplate;
// }
//
// protected SessionFactory getHibernateSessionFactory() {
// return hibernateSessionFactory;
// }
//
// public void setApplicationContext(ApplicationContext applicationContext) {
// // TODO Auto-generated method stub
// context = applicationContext;
// }
//
// protected void setNextHandle(ORMHandle nextHandle){
// this.nextHandle = nextHandle;
// }
//
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/ORMHandle.java
// public interface ORMHandle {
//
// public Object handle(String level, ORMParamsDTO dto) throws Exception;
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/dto/ORMParamsDTO.java
// public class ORMParamsDTO implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private Object param;
// private String sqlid;
//
// public Object getParam() {
// return param;
// }
// public void setParam(Object param) {
// this.param = param;
// }
// public String getSqlid() {
// return sqlid;
// }
// public void setSqlid(String sqlid) {
// this.sqlid = sqlid;
// }
//
// }
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/impl/LoadORMHandle.java
import org.hibernate.Session;
import org.springframework.stereotype.Component;
import com.ea.core.base.po.BasePO;
import com.ea.core.orm.handle.AbstractORMHandle;
import com.ea.core.orm.handle.ORMConstants;
import com.ea.core.orm.handle.ORMHandle;
import com.ea.core.orm.handle.dto.ORMParamsDTO;
/**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.orm.handle.impl;
/**
* 打开操作,由Hibnerate完成
*
* @author yiyongfei
*
*/
@Component
public class LoadORMHandle extends AbstractORMHandle {
public LoadORMHandle() {
super(ORMConstants.ORM_LEVEL.LOAD.getCode());
}
@Override | protected Object execute(ORMParamsDTO dto) throws Exception { |
yiyongfei/jea | architecture-orm/src/main/java/com/ea/core/orm/handle/impl/LoadORMHandle.java | // Path: architecture-orm/src/main/java/com/ea/core/orm/handle/AbstractORMHandle.java
// public abstract class AbstractORMHandle implements ORMHandle, ApplicationContextAware {
// protected ApplicationContext context = null;
//
// @Autowired
// private SqlSessionTemplate mybatisSessionTemplate;
// @Autowired
// private SessionFactory hibernateSessionFactory;
//
// private String level;
// private ORMHandle nextHandle;
//
// public AbstractORMHandle(String level){
// this.level = level;
// }
//
// /**
// * 符合当前Level,则执行DB操作,否则交由下个Handle去执行
// */
// public final Object handle(String level, ORMParamsDTO dto) throws Exception {
// if(this.level.equals(level)){
// return this.execute(dto);
// } else {
// this.setNextHandle();
// if(this.nextHandle != null){
// return this.nextHandle.handle(level, dto);
// } else {
// throw new Exception("必须设置ORMHandle处理当前请求");
// }
// }
// }
//
// /**
// * 执行DB操作
// * @param dto
// * @return
// * @throws Exception
// */
// protected abstract Object execute(ORMParamsDTO dto) throws Exception;
//
// /**
// * 设置下个Handle,子类设置,如果是最后一个Handle,不设置
// */
// public abstract void setNextHandle();
//
// protected SqlSessionTemplate getMybatisSessionTemplate() {
// return mybatisSessionTemplate;
// }
//
// protected SessionFactory getHibernateSessionFactory() {
// return hibernateSessionFactory;
// }
//
// public void setApplicationContext(ApplicationContext applicationContext) {
// // TODO Auto-generated method stub
// context = applicationContext;
// }
//
// protected void setNextHandle(ORMHandle nextHandle){
// this.nextHandle = nextHandle;
// }
//
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/ORMHandle.java
// public interface ORMHandle {
//
// public Object handle(String level, ORMParamsDTO dto) throws Exception;
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/dto/ORMParamsDTO.java
// public class ORMParamsDTO implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private Object param;
// private String sqlid;
//
// public Object getParam() {
// return param;
// }
// public void setParam(Object param) {
// this.param = param;
// }
// public String getSqlid() {
// return sqlid;
// }
// public void setSqlid(String sqlid) {
// this.sqlid = sqlid;
// }
//
// }
| import org.hibernate.Session;
import org.springframework.stereotype.Component;
import com.ea.core.base.po.BasePO;
import com.ea.core.orm.handle.AbstractORMHandle;
import com.ea.core.orm.handle.ORMConstants;
import com.ea.core.orm.handle.ORMHandle;
import com.ea.core.orm.handle.dto.ORMParamsDTO; | /**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.orm.handle.impl;
/**
* 打开操作,由Hibnerate完成
*
* @author yiyongfei
*
*/
@Component
public class LoadORMHandle extends AbstractORMHandle {
public LoadORMHandle() {
super(ORMConstants.ORM_LEVEL.LOAD.getCode());
}
@Override
protected Object execute(ORMParamsDTO dto) throws Exception {
// TODO Auto-generated method stub
Object po = dto.getParam();
if(po instanceof BasePO){
Session session = this.getHibernateSessionFactory().getCurrentSession();
Object obj = session.load(po.getClass(), ((BasePO) po).getPk());
return obj;
} else {
throw new Exception("参数请确认是否继承BasePO!");
}
}
@Override
public void setNextHandle() {
// TODO Auto-generated method stub | // Path: architecture-orm/src/main/java/com/ea/core/orm/handle/AbstractORMHandle.java
// public abstract class AbstractORMHandle implements ORMHandle, ApplicationContextAware {
// protected ApplicationContext context = null;
//
// @Autowired
// private SqlSessionTemplate mybatisSessionTemplate;
// @Autowired
// private SessionFactory hibernateSessionFactory;
//
// private String level;
// private ORMHandle nextHandle;
//
// public AbstractORMHandle(String level){
// this.level = level;
// }
//
// /**
// * 符合当前Level,则执行DB操作,否则交由下个Handle去执行
// */
// public final Object handle(String level, ORMParamsDTO dto) throws Exception {
// if(this.level.equals(level)){
// return this.execute(dto);
// } else {
// this.setNextHandle();
// if(this.nextHandle != null){
// return this.nextHandle.handle(level, dto);
// } else {
// throw new Exception("必须设置ORMHandle处理当前请求");
// }
// }
// }
//
// /**
// * 执行DB操作
// * @param dto
// * @return
// * @throws Exception
// */
// protected abstract Object execute(ORMParamsDTO dto) throws Exception;
//
// /**
// * 设置下个Handle,子类设置,如果是最后一个Handle,不设置
// */
// public abstract void setNextHandle();
//
// protected SqlSessionTemplate getMybatisSessionTemplate() {
// return mybatisSessionTemplate;
// }
//
// protected SessionFactory getHibernateSessionFactory() {
// return hibernateSessionFactory;
// }
//
// public void setApplicationContext(ApplicationContext applicationContext) {
// // TODO Auto-generated method stub
// context = applicationContext;
// }
//
// protected void setNextHandle(ORMHandle nextHandle){
// this.nextHandle = nextHandle;
// }
//
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/ORMHandle.java
// public interface ORMHandle {
//
// public Object handle(String level, ORMParamsDTO dto) throws Exception;
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/dto/ORMParamsDTO.java
// public class ORMParamsDTO implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private Object param;
// private String sqlid;
//
// public Object getParam() {
// return param;
// }
// public void setParam(Object param) {
// this.param = param;
// }
// public String getSqlid() {
// return sqlid;
// }
// public void setSqlid(String sqlid) {
// this.sqlid = sqlid;
// }
//
// }
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/impl/LoadORMHandle.java
import org.hibernate.Session;
import org.springframework.stereotype.Component;
import com.ea.core.base.po.BasePO;
import com.ea.core.orm.handle.AbstractORMHandle;
import com.ea.core.orm.handle.ORMConstants;
import com.ea.core.orm.handle.ORMHandle;
import com.ea.core.orm.handle.dto.ORMParamsDTO;
/**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.orm.handle.impl;
/**
* 打开操作,由Hibnerate完成
*
* @author yiyongfei
*
*/
@Component
public class LoadORMHandle extends AbstractORMHandle {
public LoadORMHandle() {
super(ORMConstants.ORM_LEVEL.LOAD.getCode());
}
@Override
protected Object execute(ORMParamsDTO dto) throws Exception {
// TODO Auto-generated method stub
Object po = dto.getParam();
if(po instanceof BasePO){
Session session = this.getHibernateSessionFactory().getCurrentSession();
Object obj = session.load(po.getClass(), ((BasePO) po).getPk());
return obj;
} else {
throw new Exception("参数请确认是否继承BasePO!");
}
}
@Override
public void setNextHandle() {
// TODO Auto-generated method stub | ORMHandle nextHandle = (QueryORMHandle)this.context.getBean("queryORMHandle"); |
yiyongfei/jea | architecture-orm/src/main/java/com/ea/core/orm/handle/impl/UpdateORMHandle.java | // Path: architecture-orm/src/main/java/com/ea/core/orm/handle/AbstractORMHandle.java
// public abstract class AbstractORMHandle implements ORMHandle, ApplicationContextAware {
// protected ApplicationContext context = null;
//
// @Autowired
// private SqlSessionTemplate mybatisSessionTemplate;
// @Autowired
// private SessionFactory hibernateSessionFactory;
//
// private String level;
// private ORMHandle nextHandle;
//
// public AbstractORMHandle(String level){
// this.level = level;
// }
//
// /**
// * 符合当前Level,则执行DB操作,否则交由下个Handle去执行
// */
// public final Object handle(String level, ORMParamsDTO dto) throws Exception {
// if(this.level.equals(level)){
// return this.execute(dto);
// } else {
// this.setNextHandle();
// if(this.nextHandle != null){
// return this.nextHandle.handle(level, dto);
// } else {
// throw new Exception("必须设置ORMHandle处理当前请求");
// }
// }
// }
//
// /**
// * 执行DB操作
// * @param dto
// * @return
// * @throws Exception
// */
// protected abstract Object execute(ORMParamsDTO dto) throws Exception;
//
// /**
// * 设置下个Handle,子类设置,如果是最后一个Handle,不设置
// */
// public abstract void setNextHandle();
//
// protected SqlSessionTemplate getMybatisSessionTemplate() {
// return mybatisSessionTemplate;
// }
//
// protected SessionFactory getHibernateSessionFactory() {
// return hibernateSessionFactory;
// }
//
// public void setApplicationContext(ApplicationContext applicationContext) {
// // TODO Auto-generated method stub
// context = applicationContext;
// }
//
// protected void setNextHandle(ORMHandle nextHandle){
// this.nextHandle = nextHandle;
// }
//
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/ORMHandle.java
// public interface ORMHandle {
//
// public Object handle(String level, ORMParamsDTO dto) throws Exception;
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/dto/ORMParamsDTO.java
// public class ORMParamsDTO implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private Object param;
// private String sqlid;
//
// public Object getParam() {
// return param;
// }
// public void setParam(Object param) {
// this.param = param;
// }
// public String getSqlid() {
// return sqlid;
// }
// public void setSqlid(String sqlid) {
// this.sqlid = sqlid;
// }
//
// }
| import org.hibernate.Session;
import org.springframework.stereotype.Component;
import com.ea.core.base.po.BasePO;
import com.ea.core.orm.handle.AbstractORMHandle;
import com.ea.core.orm.handle.ORMConstants;
import com.ea.core.orm.handle.ORMHandle;
import com.ea.core.orm.handle.dto.ORMParamsDTO; | /**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.orm.handle.impl;
/**
* 更新操作,由Hibnerate完成
*
* @author yiyongfei
*
*/
@Component
public class UpdateORMHandle extends AbstractORMHandle {
public UpdateORMHandle() {
super(ORMConstants.ORM_LEVEL.UPDATE.getCode());
}
@Override | // Path: architecture-orm/src/main/java/com/ea/core/orm/handle/AbstractORMHandle.java
// public abstract class AbstractORMHandle implements ORMHandle, ApplicationContextAware {
// protected ApplicationContext context = null;
//
// @Autowired
// private SqlSessionTemplate mybatisSessionTemplate;
// @Autowired
// private SessionFactory hibernateSessionFactory;
//
// private String level;
// private ORMHandle nextHandle;
//
// public AbstractORMHandle(String level){
// this.level = level;
// }
//
// /**
// * 符合当前Level,则执行DB操作,否则交由下个Handle去执行
// */
// public final Object handle(String level, ORMParamsDTO dto) throws Exception {
// if(this.level.equals(level)){
// return this.execute(dto);
// } else {
// this.setNextHandle();
// if(this.nextHandle != null){
// return this.nextHandle.handle(level, dto);
// } else {
// throw new Exception("必须设置ORMHandle处理当前请求");
// }
// }
// }
//
// /**
// * 执行DB操作
// * @param dto
// * @return
// * @throws Exception
// */
// protected abstract Object execute(ORMParamsDTO dto) throws Exception;
//
// /**
// * 设置下个Handle,子类设置,如果是最后一个Handle,不设置
// */
// public abstract void setNextHandle();
//
// protected SqlSessionTemplate getMybatisSessionTemplate() {
// return mybatisSessionTemplate;
// }
//
// protected SessionFactory getHibernateSessionFactory() {
// return hibernateSessionFactory;
// }
//
// public void setApplicationContext(ApplicationContext applicationContext) {
// // TODO Auto-generated method stub
// context = applicationContext;
// }
//
// protected void setNextHandle(ORMHandle nextHandle){
// this.nextHandle = nextHandle;
// }
//
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/ORMHandle.java
// public interface ORMHandle {
//
// public Object handle(String level, ORMParamsDTO dto) throws Exception;
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/dto/ORMParamsDTO.java
// public class ORMParamsDTO implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private Object param;
// private String sqlid;
//
// public Object getParam() {
// return param;
// }
// public void setParam(Object param) {
// this.param = param;
// }
// public String getSqlid() {
// return sqlid;
// }
// public void setSqlid(String sqlid) {
// this.sqlid = sqlid;
// }
//
// }
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/impl/UpdateORMHandle.java
import org.hibernate.Session;
import org.springframework.stereotype.Component;
import com.ea.core.base.po.BasePO;
import com.ea.core.orm.handle.AbstractORMHandle;
import com.ea.core.orm.handle.ORMConstants;
import com.ea.core.orm.handle.ORMHandle;
import com.ea.core.orm.handle.dto.ORMParamsDTO;
/**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.orm.handle.impl;
/**
* 更新操作,由Hibnerate完成
*
* @author yiyongfei
*
*/
@Component
public class UpdateORMHandle extends AbstractORMHandle {
public UpdateORMHandle() {
super(ORMConstants.ORM_LEVEL.UPDATE.getCode());
}
@Override | protected Object execute(ORMParamsDTO dto) throws Exception { |
yiyongfei/jea | architecture-orm/src/main/java/com/ea/core/orm/handle/impl/UpdateORMHandle.java | // Path: architecture-orm/src/main/java/com/ea/core/orm/handle/AbstractORMHandle.java
// public abstract class AbstractORMHandle implements ORMHandle, ApplicationContextAware {
// protected ApplicationContext context = null;
//
// @Autowired
// private SqlSessionTemplate mybatisSessionTemplate;
// @Autowired
// private SessionFactory hibernateSessionFactory;
//
// private String level;
// private ORMHandle nextHandle;
//
// public AbstractORMHandle(String level){
// this.level = level;
// }
//
// /**
// * 符合当前Level,则执行DB操作,否则交由下个Handle去执行
// */
// public final Object handle(String level, ORMParamsDTO dto) throws Exception {
// if(this.level.equals(level)){
// return this.execute(dto);
// } else {
// this.setNextHandle();
// if(this.nextHandle != null){
// return this.nextHandle.handle(level, dto);
// } else {
// throw new Exception("必须设置ORMHandle处理当前请求");
// }
// }
// }
//
// /**
// * 执行DB操作
// * @param dto
// * @return
// * @throws Exception
// */
// protected abstract Object execute(ORMParamsDTO dto) throws Exception;
//
// /**
// * 设置下个Handle,子类设置,如果是最后一个Handle,不设置
// */
// public abstract void setNextHandle();
//
// protected SqlSessionTemplate getMybatisSessionTemplate() {
// return mybatisSessionTemplate;
// }
//
// protected SessionFactory getHibernateSessionFactory() {
// return hibernateSessionFactory;
// }
//
// public void setApplicationContext(ApplicationContext applicationContext) {
// // TODO Auto-generated method stub
// context = applicationContext;
// }
//
// protected void setNextHandle(ORMHandle nextHandle){
// this.nextHandle = nextHandle;
// }
//
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/ORMHandle.java
// public interface ORMHandle {
//
// public Object handle(String level, ORMParamsDTO dto) throws Exception;
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/dto/ORMParamsDTO.java
// public class ORMParamsDTO implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private Object param;
// private String sqlid;
//
// public Object getParam() {
// return param;
// }
// public void setParam(Object param) {
// this.param = param;
// }
// public String getSqlid() {
// return sqlid;
// }
// public void setSqlid(String sqlid) {
// this.sqlid = sqlid;
// }
//
// }
| import org.hibernate.Session;
import org.springframework.stereotype.Component;
import com.ea.core.base.po.BasePO;
import com.ea.core.orm.handle.AbstractORMHandle;
import com.ea.core.orm.handle.ORMConstants;
import com.ea.core.orm.handle.ORMHandle;
import com.ea.core.orm.handle.dto.ORMParamsDTO; | /**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.orm.handle.impl;
/**
* 更新操作,由Hibnerate完成
*
* @author yiyongfei
*
*/
@Component
public class UpdateORMHandle extends AbstractORMHandle {
public UpdateORMHandle() {
super(ORMConstants.ORM_LEVEL.UPDATE.getCode());
}
@Override
protected Object execute(ORMParamsDTO dto) throws Exception {
Object po = dto.getParam();
if(po instanceof BasePO){
Session session = this.getHibernateSessionFactory().getCurrentSession();
session.update(po);
return null;
} else {
throw new Exception("参数请确认是否继承BasePO!");
}
}
@Override
public void setNextHandle() {
// TODO Auto-generated method stub | // Path: architecture-orm/src/main/java/com/ea/core/orm/handle/AbstractORMHandle.java
// public abstract class AbstractORMHandle implements ORMHandle, ApplicationContextAware {
// protected ApplicationContext context = null;
//
// @Autowired
// private SqlSessionTemplate mybatisSessionTemplate;
// @Autowired
// private SessionFactory hibernateSessionFactory;
//
// private String level;
// private ORMHandle nextHandle;
//
// public AbstractORMHandle(String level){
// this.level = level;
// }
//
// /**
// * 符合当前Level,则执行DB操作,否则交由下个Handle去执行
// */
// public final Object handle(String level, ORMParamsDTO dto) throws Exception {
// if(this.level.equals(level)){
// return this.execute(dto);
// } else {
// this.setNextHandle();
// if(this.nextHandle != null){
// return this.nextHandle.handle(level, dto);
// } else {
// throw new Exception("必须设置ORMHandle处理当前请求");
// }
// }
// }
//
// /**
// * 执行DB操作
// * @param dto
// * @return
// * @throws Exception
// */
// protected abstract Object execute(ORMParamsDTO dto) throws Exception;
//
// /**
// * 设置下个Handle,子类设置,如果是最后一个Handle,不设置
// */
// public abstract void setNextHandle();
//
// protected SqlSessionTemplate getMybatisSessionTemplate() {
// return mybatisSessionTemplate;
// }
//
// protected SessionFactory getHibernateSessionFactory() {
// return hibernateSessionFactory;
// }
//
// public void setApplicationContext(ApplicationContext applicationContext) {
// // TODO Auto-generated method stub
// context = applicationContext;
// }
//
// protected void setNextHandle(ORMHandle nextHandle){
// this.nextHandle = nextHandle;
// }
//
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/ORMHandle.java
// public interface ORMHandle {
//
// public Object handle(String level, ORMParamsDTO dto) throws Exception;
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/dto/ORMParamsDTO.java
// public class ORMParamsDTO implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private Object param;
// private String sqlid;
//
// public Object getParam() {
// return param;
// }
// public void setParam(Object param) {
// this.param = param;
// }
// public String getSqlid() {
// return sqlid;
// }
// public void setSqlid(String sqlid) {
// this.sqlid = sqlid;
// }
//
// }
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/impl/UpdateORMHandle.java
import org.hibernate.Session;
import org.springframework.stereotype.Component;
import com.ea.core.base.po.BasePO;
import com.ea.core.orm.handle.AbstractORMHandle;
import com.ea.core.orm.handle.ORMConstants;
import com.ea.core.orm.handle.ORMHandle;
import com.ea.core.orm.handle.dto.ORMParamsDTO;
/**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.orm.handle.impl;
/**
* 更新操作,由Hibnerate完成
*
* @author yiyongfei
*
*/
@Component
public class UpdateORMHandle extends AbstractORMHandle {
public UpdateORMHandle() {
super(ORMConstants.ORM_LEVEL.UPDATE.getCode());
}
@Override
protected Object execute(ORMParamsDTO dto) throws Exception {
Object po = dto.getParam();
if(po instanceof BasePO){
Session session = this.getHibernateSessionFactory().getCurrentSession();
session.update(po);
return null;
} else {
throw new Exception("参数请确认是否继承BasePO!");
}
}
@Override
public void setNextHandle() {
// TODO Auto-generated method stub | ORMHandle nextHandle = (LoadORMHandle)this.context.getBean("loadORMHandle"); |
yiyongfei/jea | architecture-web/src/main/java/com/ea/core/web/controller/AbstractController.java | // Path: architecture-web/src/main/java/com/ea/core/web/bridge/BridgeConstant.java
// public class BridgeConstant {
// public enum CONNECTOR_MODE {
// MQ("MQ"),
// SPRING("SPRING"),
// STORM_LOCAL("STORM.LOCAL"),
// STORM_REMOTE("STORM.REMOTE");
//
// private String code;
//
// private CONNECTOR_MODE(String code) {
// this.code = code;
// }
//
// public String getCode() {
// return code;
// }
// }
//
// }
//
// Path: architecture-core/src/main/java/com/ea/core/base/CoreDefinition.java
// public class CoreDefinition {
// static Map<String, String> mapProperty = new HashMap<String, String>();
//
// static{
// ClassPathResource resource = new ClassPathResource("jea-core.properties");
// try {
// Props p = new Props();
// p.load(resource.getInputStream());
// Iterator<PropsEntry> entries = p.iterator();
// while(entries.hasNext()){
// PropsEntry entry = entries.next();
// mapProperty.put(entry.getKey(), entry.getValue());
// }
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
//
// public static String getPropertyValue(String key){
// return mapProperty.get(key);
// }
// }
| import org.springframework.beans.factory.annotation.Autowired;
import com.ea.core.web.bridge.BridgeConstant;
import com.ea.core.web.bridge.BridgeContext;
import com.ea.core.base.CoreDefinition; | /**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.web.controller;
public abstract class AbstractController {
@Autowired
BridgeContext abuttingContext;
public Object dispatch(String callback, String facadeId, Object... models) throws Exception{
String connectorMode = null;
if(WebConstant.CALL_BACK.ASYNC.getCode().equals(callback)){ | // Path: architecture-web/src/main/java/com/ea/core/web/bridge/BridgeConstant.java
// public class BridgeConstant {
// public enum CONNECTOR_MODE {
// MQ("MQ"),
// SPRING("SPRING"),
// STORM_LOCAL("STORM.LOCAL"),
// STORM_REMOTE("STORM.REMOTE");
//
// private String code;
//
// private CONNECTOR_MODE(String code) {
// this.code = code;
// }
//
// public String getCode() {
// return code;
// }
// }
//
// }
//
// Path: architecture-core/src/main/java/com/ea/core/base/CoreDefinition.java
// public class CoreDefinition {
// static Map<String, String> mapProperty = new HashMap<String, String>();
//
// static{
// ClassPathResource resource = new ClassPathResource("jea-core.properties");
// try {
// Props p = new Props();
// p.load(resource.getInputStream());
// Iterator<PropsEntry> entries = p.iterator();
// while(entries.hasNext()){
// PropsEntry entry = entries.next();
// mapProperty.put(entry.getKey(), entry.getValue());
// }
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
//
// public static String getPropertyValue(String key){
// return mapProperty.get(key);
// }
// }
// Path: architecture-web/src/main/java/com/ea/core/web/controller/AbstractController.java
import org.springframework.beans.factory.annotation.Autowired;
import com.ea.core.web.bridge.BridgeConstant;
import com.ea.core.web.bridge.BridgeContext;
import com.ea.core.base.CoreDefinition;
/**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.web.controller;
public abstract class AbstractController {
@Autowired
BridgeContext abuttingContext;
public Object dispatch(String callback, String facadeId, Object... models) throws Exception{
String connectorMode = null;
if(WebConstant.CALL_BACK.ASYNC.getCode().equals(callback)){ | connectorMode = BridgeConstant.CONNECTOR_MODE.MQ.getCode(); |
yiyongfei/jea | architecture-web/src/main/java/com/ea/core/web/controller/AbstractController.java | // Path: architecture-web/src/main/java/com/ea/core/web/bridge/BridgeConstant.java
// public class BridgeConstant {
// public enum CONNECTOR_MODE {
// MQ("MQ"),
// SPRING("SPRING"),
// STORM_LOCAL("STORM.LOCAL"),
// STORM_REMOTE("STORM.REMOTE");
//
// private String code;
//
// private CONNECTOR_MODE(String code) {
// this.code = code;
// }
//
// public String getCode() {
// return code;
// }
// }
//
// }
//
// Path: architecture-core/src/main/java/com/ea/core/base/CoreDefinition.java
// public class CoreDefinition {
// static Map<String, String> mapProperty = new HashMap<String, String>();
//
// static{
// ClassPathResource resource = new ClassPathResource("jea-core.properties");
// try {
// Props p = new Props();
// p.load(resource.getInputStream());
// Iterator<PropsEntry> entries = p.iterator();
// while(entries.hasNext()){
// PropsEntry entry = entries.next();
// mapProperty.put(entry.getKey(), entry.getValue());
// }
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
//
// public static String getPropertyValue(String key){
// return mapProperty.get(key);
// }
// }
| import org.springframework.beans.factory.annotation.Autowired;
import com.ea.core.web.bridge.BridgeConstant;
import com.ea.core.web.bridge.BridgeContext;
import com.ea.core.base.CoreDefinition; | /**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.web.controller;
public abstract class AbstractController {
@Autowired
BridgeContext abuttingContext;
public Object dispatch(String callback, String facadeId, Object... models) throws Exception{
String connectorMode = null;
if(WebConstant.CALL_BACK.ASYNC.getCode().equals(callback)){
connectorMode = BridgeConstant.CONNECTOR_MODE.MQ.getCode();
} else { | // Path: architecture-web/src/main/java/com/ea/core/web/bridge/BridgeConstant.java
// public class BridgeConstant {
// public enum CONNECTOR_MODE {
// MQ("MQ"),
// SPRING("SPRING"),
// STORM_LOCAL("STORM.LOCAL"),
// STORM_REMOTE("STORM.REMOTE");
//
// private String code;
//
// private CONNECTOR_MODE(String code) {
// this.code = code;
// }
//
// public String getCode() {
// return code;
// }
// }
//
// }
//
// Path: architecture-core/src/main/java/com/ea/core/base/CoreDefinition.java
// public class CoreDefinition {
// static Map<String, String> mapProperty = new HashMap<String, String>();
//
// static{
// ClassPathResource resource = new ClassPathResource("jea-core.properties");
// try {
// Props p = new Props();
// p.load(resource.getInputStream());
// Iterator<PropsEntry> entries = p.iterator();
// while(entries.hasNext()){
// PropsEntry entry = entries.next();
// mapProperty.put(entry.getKey(), entry.getValue());
// }
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
//
// public static String getPropertyValue(String key){
// return mapProperty.get(key);
// }
// }
// Path: architecture-web/src/main/java/com/ea/core/web/controller/AbstractController.java
import org.springframework.beans.factory.annotation.Autowired;
import com.ea.core.web.bridge.BridgeConstant;
import com.ea.core.web.bridge.BridgeContext;
import com.ea.core.base.CoreDefinition;
/**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.web.controller;
public abstract class AbstractController {
@Autowired
BridgeContext abuttingContext;
public Object dispatch(String callback, String facadeId, Object... models) throws Exception{
String connectorMode = null;
if(WebConstant.CALL_BACK.ASYNC.getCode().equals(callback)){
connectorMode = BridgeConstant.CONNECTOR_MODE.MQ.getCode();
} else { | connectorMode = CoreDefinition.getPropertyValue("sync.mode"); |
yiyongfei/jea | architecture-integration/src/main/java/com/ea/core/integration/bridge/SoapIntegration.java | // Path: architecture-integration/src/main/java/com/ea/core/integration/IntegrationContext.java
// public class IntegrationContext {
// private Logger logger = LoggerFactory.getLogger(IntegrationContext.class);
//
// public Object connect(String connectMode, Map<String, String> conf, String connectorId, String facadeId, Object... models) throws Exception {
// // TODO Auto-generated method stub
// long startTime = Calendar.getInstance().getTimeInMillis();
// IConnector connector = null;
// if(connectMode.equals(IntegrationConstant.CONNECTOR_MODE.MQ.getCode())){
// IClient client = new MqSendClient(conf.get(IntegrationConstant.CONF.HOST.getCode()),
// conf.get(IntegrationConstant.CONF.USERNAME.getCode()),
// conf.get(IntegrationConstant.CONF.PASSWORD.getCode()));
// connector = new MqConnector();
// ((AbstractConnector)connector).setClient(client);
// }
// else if(connectMode.equals(IntegrationConstant.CONNECTOR_MODE.STORM.getCode())){
// IClient client = new RemoteClient(conf.get(IntegrationConstant.CONF.HOST.getCode()),
// new Integer(conf.get(IntegrationConstant.CONF.PORT.getCode())),
// new Integer(conf.get(IntegrationConstant.CONF.TIMEOUT.getCode())));
// connector = new StormConnector();
// ((AbstractConnector)connector).setClient(client);
// }
// else if(connectMode.equals(IntegrationConstant.CONNECTOR_MODE.SOAP.getCode())){
// IWSClient client = new SoapClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// connector = new SoapConnector();
// ((AbstractWSConnector)connector).setClient(client);
// }
// else {
// IWSClient client = null;
// if(HttpMethod.GET.equals(conf.get(IntegrationConstant.CONF.HTTP_METHOD.getCode()))){
// client = new GetClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// } else if(HttpMethod.POST.equals(conf.get(IntegrationConstant.CONF.HTTP_METHOD.getCode()))){
// client = new PostClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// } else if(HttpMethod.PUT.equals(conf.get(IntegrationConstant.CONF.HTTP_METHOD.getCode()))){
// client = new PutClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// } else if(HttpMethod.DELETE.equals(conf.get(IntegrationConstant.CONF.HTTP_METHOD.getCode()))){
// client = new DeleteClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// } else {
// throw new RuntimeException("提供的HttpMethod方法有误,请检查!");
// }
// connector = new RestConnector();
// ((AbstractWSConnector)connector).setClient(client);
// }
// long endTime1 = Calendar.getInstance().getTimeInMillis();
// logger.info("初始化连接共耗时" + (endTime1 - startTime) + "毫秒");
// Object result = connector.connect(connectorId, facadeId, models);
// long endTime2 = Calendar.getInstance().getTimeInMillis();
// logger.info("本次执行共耗时" + (endTime2 - startTime) + "毫秒,排除初始化连接后的耗时" + (endTime2 - endTime1) + "毫秒,连接方式:" + connectMode + ",调用Facade:" + facadeId);
// return result;
// }
//
// }
| import java.util.HashMap;
import java.util.Map;
import com.ea.core.integration.IntegrationConstant;
import com.ea.core.integration.IntegrationContext; | package com.ea.core.integration.bridge;
public class SoapIntegration {
public void connect(String host, String method, Object... obj) throws Exception{ | // Path: architecture-integration/src/main/java/com/ea/core/integration/IntegrationContext.java
// public class IntegrationContext {
// private Logger logger = LoggerFactory.getLogger(IntegrationContext.class);
//
// public Object connect(String connectMode, Map<String, String> conf, String connectorId, String facadeId, Object... models) throws Exception {
// // TODO Auto-generated method stub
// long startTime = Calendar.getInstance().getTimeInMillis();
// IConnector connector = null;
// if(connectMode.equals(IntegrationConstant.CONNECTOR_MODE.MQ.getCode())){
// IClient client = new MqSendClient(conf.get(IntegrationConstant.CONF.HOST.getCode()),
// conf.get(IntegrationConstant.CONF.USERNAME.getCode()),
// conf.get(IntegrationConstant.CONF.PASSWORD.getCode()));
// connector = new MqConnector();
// ((AbstractConnector)connector).setClient(client);
// }
// else if(connectMode.equals(IntegrationConstant.CONNECTOR_MODE.STORM.getCode())){
// IClient client = new RemoteClient(conf.get(IntegrationConstant.CONF.HOST.getCode()),
// new Integer(conf.get(IntegrationConstant.CONF.PORT.getCode())),
// new Integer(conf.get(IntegrationConstant.CONF.TIMEOUT.getCode())));
// connector = new StormConnector();
// ((AbstractConnector)connector).setClient(client);
// }
// else if(connectMode.equals(IntegrationConstant.CONNECTOR_MODE.SOAP.getCode())){
// IWSClient client = new SoapClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// connector = new SoapConnector();
// ((AbstractWSConnector)connector).setClient(client);
// }
// else {
// IWSClient client = null;
// if(HttpMethod.GET.equals(conf.get(IntegrationConstant.CONF.HTTP_METHOD.getCode()))){
// client = new GetClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// } else if(HttpMethod.POST.equals(conf.get(IntegrationConstant.CONF.HTTP_METHOD.getCode()))){
// client = new PostClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// } else if(HttpMethod.PUT.equals(conf.get(IntegrationConstant.CONF.HTTP_METHOD.getCode()))){
// client = new PutClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// } else if(HttpMethod.DELETE.equals(conf.get(IntegrationConstant.CONF.HTTP_METHOD.getCode()))){
// client = new DeleteClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// } else {
// throw new RuntimeException("提供的HttpMethod方法有误,请检查!");
// }
// connector = new RestConnector();
// ((AbstractWSConnector)connector).setClient(client);
// }
// long endTime1 = Calendar.getInstance().getTimeInMillis();
// logger.info("初始化连接共耗时" + (endTime1 - startTime) + "毫秒");
// Object result = connector.connect(connectorId, facadeId, models);
// long endTime2 = Calendar.getInstance().getTimeInMillis();
// logger.info("本次执行共耗时" + (endTime2 - startTime) + "毫秒,排除初始化连接后的耗时" + (endTime2 - endTime1) + "毫秒,连接方式:" + connectMode + ",调用Facade:" + facadeId);
// return result;
// }
//
// }
// Path: architecture-integration/src/main/java/com/ea/core/integration/bridge/SoapIntegration.java
import java.util.HashMap;
import java.util.Map;
import com.ea.core.integration.IntegrationConstant;
import com.ea.core.integration.IntegrationContext;
package com.ea.core.integration.bridge;
public class SoapIntegration {
public void connect(String host, String method, Object... obj) throws Exception{ | IntegrationContext context = new IntegrationContext(); |
yiyongfei/jea | architecture-integration/src/main/java/com/ea/core/integration/IntegrationContext.java | // Path: architecture-ws/src/main/java/com/ea/core/bridge/AbstractWSConnector.java
// public abstract class AbstractWSConnector implements IConnector {
//
// public Object connect(String methodName, String facadeId, Object... models) throws Exception{
// return client().execute(methodName, models);
// }
//
// protected abstract IWSClient client();
// public abstract void setClient(IWSClient client);
//
// @Override
// public String findByFacade(String facadeId) {
// // TODO Auto-generated method stub
// return null;
// }
// }
//
// Path: architecture-ws/src/main/java/com/ea/core/bridge/ws/rest/client/GetClient.java
// public class GetClient extends AbstractRestClient{
//
// public GetClient(URL httpUrl) {
// super(httpUrl);
// }
//
// @Override
// protected HttpRequestBase getMethod(String url) {
// // TODO Auto-generated method stub
// return new HttpGet(url);
// }
//
// }
| import java.net.URL;
import java.util.Calendar;
import java.util.Map;
import javax.ws.rs.HttpMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ea.core.bridge.AbstractConnector;
import com.ea.core.bridge.AbstractWSConnector;
import com.ea.core.bridge.IClient;
import com.ea.core.bridge.IConnector;
import com.ea.core.bridge.IWSClient;
import com.ea.core.bridge.async.mq.client.MqSendClient;
import com.ea.core.bridge.sync.storm.client.RemoteClient;
import com.ea.core.bridge.ws.rest.client.DeleteClient;
import com.ea.core.bridge.ws.rest.client.GetClient;
import com.ea.core.bridge.ws.rest.client.PostClient;
import com.ea.core.bridge.ws.rest.client.PutClient;
import com.ea.core.bridge.ws.soap.client.SoapClient;
import com.ea.core.integration.mq.MqConnector;
import com.ea.core.integration.rest.RestConnector;
import com.ea.core.integration.soap.SoapConnector;
import com.ea.core.integration.storm.StormConnector; | /**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.integration;
public class IntegrationContext {
private Logger logger = LoggerFactory.getLogger(IntegrationContext.class);
public Object connect(String connectMode, Map<String, String> conf, String connectorId, String facadeId, Object... models) throws Exception {
// TODO Auto-generated method stub
long startTime = Calendar.getInstance().getTimeInMillis();
IConnector connector = null;
if(connectMode.equals(IntegrationConstant.CONNECTOR_MODE.MQ.getCode())){
IClient client = new MqSendClient(conf.get(IntegrationConstant.CONF.HOST.getCode()),
conf.get(IntegrationConstant.CONF.USERNAME.getCode()),
conf.get(IntegrationConstant.CONF.PASSWORD.getCode()));
connector = new MqConnector();
((AbstractConnector)connector).setClient(client);
}
else if(connectMode.equals(IntegrationConstant.CONNECTOR_MODE.STORM.getCode())){
IClient client = new RemoteClient(conf.get(IntegrationConstant.CONF.HOST.getCode()),
new Integer(conf.get(IntegrationConstant.CONF.PORT.getCode())),
new Integer(conf.get(IntegrationConstant.CONF.TIMEOUT.getCode())));
connector = new StormConnector();
((AbstractConnector)connector).setClient(client);
}
else if(connectMode.equals(IntegrationConstant.CONNECTOR_MODE.SOAP.getCode())){
IWSClient client = new SoapClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
connector = new SoapConnector(); | // Path: architecture-ws/src/main/java/com/ea/core/bridge/AbstractWSConnector.java
// public abstract class AbstractWSConnector implements IConnector {
//
// public Object connect(String methodName, String facadeId, Object... models) throws Exception{
// return client().execute(methodName, models);
// }
//
// protected abstract IWSClient client();
// public abstract void setClient(IWSClient client);
//
// @Override
// public String findByFacade(String facadeId) {
// // TODO Auto-generated method stub
// return null;
// }
// }
//
// Path: architecture-ws/src/main/java/com/ea/core/bridge/ws/rest/client/GetClient.java
// public class GetClient extends AbstractRestClient{
//
// public GetClient(URL httpUrl) {
// super(httpUrl);
// }
//
// @Override
// protected HttpRequestBase getMethod(String url) {
// // TODO Auto-generated method stub
// return new HttpGet(url);
// }
//
// }
// Path: architecture-integration/src/main/java/com/ea/core/integration/IntegrationContext.java
import java.net.URL;
import java.util.Calendar;
import java.util.Map;
import javax.ws.rs.HttpMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ea.core.bridge.AbstractConnector;
import com.ea.core.bridge.AbstractWSConnector;
import com.ea.core.bridge.IClient;
import com.ea.core.bridge.IConnector;
import com.ea.core.bridge.IWSClient;
import com.ea.core.bridge.async.mq.client.MqSendClient;
import com.ea.core.bridge.sync.storm.client.RemoteClient;
import com.ea.core.bridge.ws.rest.client.DeleteClient;
import com.ea.core.bridge.ws.rest.client.GetClient;
import com.ea.core.bridge.ws.rest.client.PostClient;
import com.ea.core.bridge.ws.rest.client.PutClient;
import com.ea.core.bridge.ws.soap.client.SoapClient;
import com.ea.core.integration.mq.MqConnector;
import com.ea.core.integration.rest.RestConnector;
import com.ea.core.integration.soap.SoapConnector;
import com.ea.core.integration.storm.StormConnector;
/**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.integration;
public class IntegrationContext {
private Logger logger = LoggerFactory.getLogger(IntegrationContext.class);
public Object connect(String connectMode, Map<String, String> conf, String connectorId, String facadeId, Object... models) throws Exception {
// TODO Auto-generated method stub
long startTime = Calendar.getInstance().getTimeInMillis();
IConnector connector = null;
if(connectMode.equals(IntegrationConstant.CONNECTOR_MODE.MQ.getCode())){
IClient client = new MqSendClient(conf.get(IntegrationConstant.CONF.HOST.getCode()),
conf.get(IntegrationConstant.CONF.USERNAME.getCode()),
conf.get(IntegrationConstant.CONF.PASSWORD.getCode()));
connector = new MqConnector();
((AbstractConnector)connector).setClient(client);
}
else if(connectMode.equals(IntegrationConstant.CONNECTOR_MODE.STORM.getCode())){
IClient client = new RemoteClient(conf.get(IntegrationConstant.CONF.HOST.getCode()),
new Integer(conf.get(IntegrationConstant.CONF.PORT.getCode())),
new Integer(conf.get(IntegrationConstant.CONF.TIMEOUT.getCode())));
connector = new StormConnector();
((AbstractConnector)connector).setClient(client);
}
else if(connectMode.equals(IntegrationConstant.CONNECTOR_MODE.SOAP.getCode())){
IWSClient client = new SoapClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
connector = new SoapConnector(); | ((AbstractWSConnector)connector).setClient(client); |
yiyongfei/jea | architecture-integration/src/main/java/com/ea/core/integration/IntegrationContext.java | // Path: architecture-ws/src/main/java/com/ea/core/bridge/AbstractWSConnector.java
// public abstract class AbstractWSConnector implements IConnector {
//
// public Object connect(String methodName, String facadeId, Object... models) throws Exception{
// return client().execute(methodName, models);
// }
//
// protected abstract IWSClient client();
// public abstract void setClient(IWSClient client);
//
// @Override
// public String findByFacade(String facadeId) {
// // TODO Auto-generated method stub
// return null;
// }
// }
//
// Path: architecture-ws/src/main/java/com/ea/core/bridge/ws/rest/client/GetClient.java
// public class GetClient extends AbstractRestClient{
//
// public GetClient(URL httpUrl) {
// super(httpUrl);
// }
//
// @Override
// protected HttpRequestBase getMethod(String url) {
// // TODO Auto-generated method stub
// return new HttpGet(url);
// }
//
// }
| import java.net.URL;
import java.util.Calendar;
import java.util.Map;
import javax.ws.rs.HttpMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ea.core.bridge.AbstractConnector;
import com.ea.core.bridge.AbstractWSConnector;
import com.ea.core.bridge.IClient;
import com.ea.core.bridge.IConnector;
import com.ea.core.bridge.IWSClient;
import com.ea.core.bridge.async.mq.client.MqSendClient;
import com.ea.core.bridge.sync.storm.client.RemoteClient;
import com.ea.core.bridge.ws.rest.client.DeleteClient;
import com.ea.core.bridge.ws.rest.client.GetClient;
import com.ea.core.bridge.ws.rest.client.PostClient;
import com.ea.core.bridge.ws.rest.client.PutClient;
import com.ea.core.bridge.ws.soap.client.SoapClient;
import com.ea.core.integration.mq.MqConnector;
import com.ea.core.integration.rest.RestConnector;
import com.ea.core.integration.soap.SoapConnector;
import com.ea.core.integration.storm.StormConnector; | /**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.integration;
public class IntegrationContext {
private Logger logger = LoggerFactory.getLogger(IntegrationContext.class);
public Object connect(String connectMode, Map<String, String> conf, String connectorId, String facadeId, Object... models) throws Exception {
// TODO Auto-generated method stub
long startTime = Calendar.getInstance().getTimeInMillis();
IConnector connector = null;
if(connectMode.equals(IntegrationConstant.CONNECTOR_MODE.MQ.getCode())){
IClient client = new MqSendClient(conf.get(IntegrationConstant.CONF.HOST.getCode()),
conf.get(IntegrationConstant.CONF.USERNAME.getCode()),
conf.get(IntegrationConstant.CONF.PASSWORD.getCode()));
connector = new MqConnector();
((AbstractConnector)connector).setClient(client);
}
else if(connectMode.equals(IntegrationConstant.CONNECTOR_MODE.STORM.getCode())){
IClient client = new RemoteClient(conf.get(IntegrationConstant.CONF.HOST.getCode()),
new Integer(conf.get(IntegrationConstant.CONF.PORT.getCode())),
new Integer(conf.get(IntegrationConstant.CONF.TIMEOUT.getCode())));
connector = new StormConnector();
((AbstractConnector)connector).setClient(client);
}
else if(connectMode.equals(IntegrationConstant.CONNECTOR_MODE.SOAP.getCode())){
IWSClient client = new SoapClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
connector = new SoapConnector();
((AbstractWSConnector)connector).setClient(client);
}
else {
IWSClient client = null;
if(HttpMethod.GET.equals(conf.get(IntegrationConstant.CONF.HTTP_METHOD.getCode()))){ | // Path: architecture-ws/src/main/java/com/ea/core/bridge/AbstractWSConnector.java
// public abstract class AbstractWSConnector implements IConnector {
//
// public Object connect(String methodName, String facadeId, Object... models) throws Exception{
// return client().execute(methodName, models);
// }
//
// protected abstract IWSClient client();
// public abstract void setClient(IWSClient client);
//
// @Override
// public String findByFacade(String facadeId) {
// // TODO Auto-generated method stub
// return null;
// }
// }
//
// Path: architecture-ws/src/main/java/com/ea/core/bridge/ws/rest/client/GetClient.java
// public class GetClient extends AbstractRestClient{
//
// public GetClient(URL httpUrl) {
// super(httpUrl);
// }
//
// @Override
// protected HttpRequestBase getMethod(String url) {
// // TODO Auto-generated method stub
// return new HttpGet(url);
// }
//
// }
// Path: architecture-integration/src/main/java/com/ea/core/integration/IntegrationContext.java
import java.net.URL;
import java.util.Calendar;
import java.util.Map;
import javax.ws.rs.HttpMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ea.core.bridge.AbstractConnector;
import com.ea.core.bridge.AbstractWSConnector;
import com.ea.core.bridge.IClient;
import com.ea.core.bridge.IConnector;
import com.ea.core.bridge.IWSClient;
import com.ea.core.bridge.async.mq.client.MqSendClient;
import com.ea.core.bridge.sync.storm.client.RemoteClient;
import com.ea.core.bridge.ws.rest.client.DeleteClient;
import com.ea.core.bridge.ws.rest.client.GetClient;
import com.ea.core.bridge.ws.rest.client.PostClient;
import com.ea.core.bridge.ws.rest.client.PutClient;
import com.ea.core.bridge.ws.soap.client.SoapClient;
import com.ea.core.integration.mq.MqConnector;
import com.ea.core.integration.rest.RestConnector;
import com.ea.core.integration.soap.SoapConnector;
import com.ea.core.integration.storm.StormConnector;
/**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.integration;
public class IntegrationContext {
private Logger logger = LoggerFactory.getLogger(IntegrationContext.class);
public Object connect(String connectMode, Map<String, String> conf, String connectorId, String facadeId, Object... models) throws Exception {
// TODO Auto-generated method stub
long startTime = Calendar.getInstance().getTimeInMillis();
IConnector connector = null;
if(connectMode.equals(IntegrationConstant.CONNECTOR_MODE.MQ.getCode())){
IClient client = new MqSendClient(conf.get(IntegrationConstant.CONF.HOST.getCode()),
conf.get(IntegrationConstant.CONF.USERNAME.getCode()),
conf.get(IntegrationConstant.CONF.PASSWORD.getCode()));
connector = new MqConnector();
((AbstractConnector)connector).setClient(client);
}
else if(connectMode.equals(IntegrationConstant.CONNECTOR_MODE.STORM.getCode())){
IClient client = new RemoteClient(conf.get(IntegrationConstant.CONF.HOST.getCode()),
new Integer(conf.get(IntegrationConstant.CONF.PORT.getCode())),
new Integer(conf.get(IntegrationConstant.CONF.TIMEOUT.getCode())));
connector = new StormConnector();
((AbstractConnector)connector).setClient(client);
}
else if(connectMode.equals(IntegrationConstant.CONNECTOR_MODE.SOAP.getCode())){
IWSClient client = new SoapClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
connector = new SoapConnector();
((AbstractWSConnector)connector).setClient(client);
}
else {
IWSClient client = null;
if(HttpMethod.GET.equals(conf.get(IntegrationConstant.CONF.HTTP_METHOD.getCode()))){ | client = new GetClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode()))); |
yiyongfei/jea | architecture-achieve/src/main/java/com/ea/core/achieve/mq/consumer/DefaultConsumer.java | // Path: architecture-core/src/main/java/com/ea/core/kryo/ISerializer.java
// public interface ISerializer extends Serializable{
//
// /**
// * 序列化成字符串,字符串以ISO-8859-1编码
// * 目前框架里所有序列化的内容都以字符串方式存在
// *
// * @param obj
// * @return
// * @throws Exception
// */
// public String serialize(Object obj) throws Exception;
//
// /**
// * 序列化成byte数组
// *
// * @param obj
// * @return
// * @throws Exception
// */
// public byte[] Serialize(Object obj) throws Exception;
//
// /**
// * 根据字符串内容反序列化成对象
// *
// * @param serialString
// * @return
// * @throws Exception
// */
// public Object deserialize(String serialString) throws Exception;
//
// public Object Deserialize(byte[] aryByte) throws Exception;
//
// /**
// * 注册Class
// *
// * @param type
// */
// public void register(Class<?> type);
//
// public void register(Class<?> type, Serializer<?> serializer);
// }
//
// Path: architecture-core/src/main/java/com/ea/core/mq/consumer/AbstractConsumer.java
// public abstract class AbstractConsumer implements IConsumer {
// private Logger logger = LoggerFactory.getLogger(AbstractConsumer.class);
// private MQClient client = null;
// private String queueName;
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// public AbstractConsumer(){
// client = new MQClient(MQDefinition.getPropertyValue("mq.server.host"), MQDefinition.getPropertyValue("mq.server.username"), MQDefinition.getPropertyValue("mq.server.password"));
// }
// @Override
// public void setQueueName(String queueName) {
// this.queueName = queueName;
// }
//
// @Override
// public void run() {
// // TODO Auto-generated method stub
// try {
// execute();
// } catch (Exception e) {
// //异常处理(策略是记录原始取到的队列信息和异常信息,并写到队列里,队列名为errorQueue)
// //
// }
// }
//
// protected void execute() throws Exception {
// byte[] queueContent = client.receiveMessage(queueName);
// if(queueContent == null){
// return;
// }
// ReceiveDTO request = deserialize(queueContent);
// logger.info("从队列" + queueName + "收到消息,该消息将交由" + request.getRequestId() + "处理!");
// perform(request.getRequestId(), request.getParams());
// }
//
// /**
// * 反序列化,默认反序列化方式在DefaultReceive实现
// * @param aryByte
// * @return
// * @throws Exception
// */
// protected abstract ReceiveDTO deserialize(byte[] aryByte) throws Exception;
//
// protected abstract Object perform(String facadeName, Object... models) throws Exception;
//
// }
| import com.ea.core.base.context.AppServerBeanFactory;
import com.ea.core.base.request.Request;
import com.ea.core.facade.IFacade;
import com.ea.core.kryo.ISerializer;
import com.ea.core.kryo.impl.DefaultSerializer;
import com.ea.core.kryo.impl.JavaSerializer;
import com.ea.core.kryo.impl.ObjectSerializer;
import com.ea.core.mq.consumer.AbstractConsumer;
import com.ea.core.mq.consumer.ReceiveDTO; | /**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.achieve.mq.consumer;
public class DefaultConsumer extends AbstractConsumer {
/**
*
*/
private static final long serialVersionUID = 2267877435951577268L;
@Override
protected Object perform(String facadeName, Object... models) throws Exception {
IFacade facade = (IFacade) AppServerBeanFactory.getBeanFactory().getBean(facadeName);
return facade.facade(models);
}
@Override
protected ReceiveDTO deserialize(byte[] aryByte) throws Exception {
// TODO Auto-generated method stub
ReceiveDTO dto = new ReceiveDTO();
Request request = deserializeRequest(aryByte);
dto.setRequestId(request.getRequestId());
if(request.getContent() != null){
dto.setParams((Object[])deserializeContent(request));
}
return dto;
}
protected Request deserializeRequest(byte[] aryByte) throws Exception{ | // Path: architecture-core/src/main/java/com/ea/core/kryo/ISerializer.java
// public interface ISerializer extends Serializable{
//
// /**
// * 序列化成字符串,字符串以ISO-8859-1编码
// * 目前框架里所有序列化的内容都以字符串方式存在
// *
// * @param obj
// * @return
// * @throws Exception
// */
// public String serialize(Object obj) throws Exception;
//
// /**
// * 序列化成byte数组
// *
// * @param obj
// * @return
// * @throws Exception
// */
// public byte[] Serialize(Object obj) throws Exception;
//
// /**
// * 根据字符串内容反序列化成对象
// *
// * @param serialString
// * @return
// * @throws Exception
// */
// public Object deserialize(String serialString) throws Exception;
//
// public Object Deserialize(byte[] aryByte) throws Exception;
//
// /**
// * 注册Class
// *
// * @param type
// */
// public void register(Class<?> type);
//
// public void register(Class<?> type, Serializer<?> serializer);
// }
//
// Path: architecture-core/src/main/java/com/ea/core/mq/consumer/AbstractConsumer.java
// public abstract class AbstractConsumer implements IConsumer {
// private Logger logger = LoggerFactory.getLogger(AbstractConsumer.class);
// private MQClient client = null;
// private String queueName;
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// public AbstractConsumer(){
// client = new MQClient(MQDefinition.getPropertyValue("mq.server.host"), MQDefinition.getPropertyValue("mq.server.username"), MQDefinition.getPropertyValue("mq.server.password"));
// }
// @Override
// public void setQueueName(String queueName) {
// this.queueName = queueName;
// }
//
// @Override
// public void run() {
// // TODO Auto-generated method stub
// try {
// execute();
// } catch (Exception e) {
// //异常处理(策略是记录原始取到的队列信息和异常信息,并写到队列里,队列名为errorQueue)
// //
// }
// }
//
// protected void execute() throws Exception {
// byte[] queueContent = client.receiveMessage(queueName);
// if(queueContent == null){
// return;
// }
// ReceiveDTO request = deserialize(queueContent);
// logger.info("从队列" + queueName + "收到消息,该消息将交由" + request.getRequestId() + "处理!");
// perform(request.getRequestId(), request.getParams());
// }
//
// /**
// * 反序列化,默认反序列化方式在DefaultReceive实现
// * @param aryByte
// * @return
// * @throws Exception
// */
// protected abstract ReceiveDTO deserialize(byte[] aryByte) throws Exception;
//
// protected abstract Object perform(String facadeName, Object... models) throws Exception;
//
// }
// Path: architecture-achieve/src/main/java/com/ea/core/achieve/mq/consumer/DefaultConsumer.java
import com.ea.core.base.context.AppServerBeanFactory;
import com.ea.core.base.request.Request;
import com.ea.core.facade.IFacade;
import com.ea.core.kryo.ISerializer;
import com.ea.core.kryo.impl.DefaultSerializer;
import com.ea.core.kryo.impl.JavaSerializer;
import com.ea.core.kryo.impl.ObjectSerializer;
import com.ea.core.mq.consumer.AbstractConsumer;
import com.ea.core.mq.consumer.ReceiveDTO;
/**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.achieve.mq.consumer;
public class DefaultConsumer extends AbstractConsumer {
/**
*
*/
private static final long serialVersionUID = 2267877435951577268L;
@Override
protected Object perform(String facadeName, Object... models) throws Exception {
IFacade facade = (IFacade) AppServerBeanFactory.getBeanFactory().getBean(facadeName);
return facade.facade(models);
}
@Override
protected ReceiveDTO deserialize(byte[] aryByte) throws Exception {
// TODO Auto-generated method stub
ReceiveDTO dto = new ReceiveDTO();
Request request = deserializeRequest(aryByte);
dto.setRequestId(request.getRequestId());
if(request.getContent() != null){
dto.setParams((Object[])deserializeContent(request));
}
return dto;
}
protected Request deserializeRequest(byte[] aryByte) throws Exception{ | ISerializer serializer = new DefaultSerializer(); |
yiyongfei/jea | architecture-web/src/main/java/com/ea/core/web/bridge/sync/storm/client/RemoteClient.java | // Path: architecture-core/src/main/java/com/ea/core/base/CoreDefinition.java
// public class CoreDefinition {
// static Map<String, String> mapProperty = new HashMap<String, String>();
//
// static{
// ClassPathResource resource = new ClassPathResource("jea-core.properties");
// try {
// Props p = new Props();
// p.load(resource.getInputStream());
// Iterator<PropsEntry> entries = p.iterator();
// while(entries.hasNext()){
// PropsEntry entry = entries.next();
// mapProperty.put(entry.getKey(), entry.getValue());
// }
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
//
// public static String getPropertyValue(String key){
// return mapProperty.get(key);
// }
// }
//
// Path: architecture-web/src/main/java/com/ea/core/web/bridge/BridgeConstant.java
// public class BridgeConstant {
// public enum CONNECTOR_MODE {
// MQ("MQ"),
// SPRING("SPRING"),
// STORM_LOCAL("STORM.LOCAL"),
// STORM_REMOTE("STORM.REMOTE");
//
// private String code;
//
// private CONNECTOR_MODE(String code) {
// this.code = code;
// }
//
// public String getCode() {
// return code;
// }
// }
//
// }
| import org.springframework.stereotype.Component;
import com.ea.core.base.CoreDefinition;
import com.ea.core.storm.StormDefinition;
import com.ea.core.web.bridge.BridgeConstant; | /**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.web.bridge.sync.storm.client;
@Component
public class RemoteClient extends com.ea.core.bridge.sync.storm.client.RemoteClient {
public RemoteClient(){
super(); | // Path: architecture-core/src/main/java/com/ea/core/base/CoreDefinition.java
// public class CoreDefinition {
// static Map<String, String> mapProperty = new HashMap<String, String>();
//
// static{
// ClassPathResource resource = new ClassPathResource("jea-core.properties");
// try {
// Props p = new Props();
// p.load(resource.getInputStream());
// Iterator<PropsEntry> entries = p.iterator();
// while(entries.hasNext()){
// PropsEntry entry = entries.next();
// mapProperty.put(entry.getKey(), entry.getValue());
// }
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
//
// public static String getPropertyValue(String key){
// return mapProperty.get(key);
// }
// }
//
// Path: architecture-web/src/main/java/com/ea/core/web/bridge/BridgeConstant.java
// public class BridgeConstant {
// public enum CONNECTOR_MODE {
// MQ("MQ"),
// SPRING("SPRING"),
// STORM_LOCAL("STORM.LOCAL"),
// STORM_REMOTE("STORM.REMOTE");
//
// private String code;
//
// private CONNECTOR_MODE(String code) {
// this.code = code;
// }
//
// public String getCode() {
// return code;
// }
// }
//
// }
// Path: architecture-web/src/main/java/com/ea/core/web/bridge/sync/storm/client/RemoteClient.java
import org.springframework.stereotype.Component;
import com.ea.core.base.CoreDefinition;
import com.ea.core.storm.StormDefinition;
import com.ea.core.web.bridge.BridgeConstant;
/**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.web.bridge.sync.storm.client;
@Component
public class RemoteClient extends com.ea.core.bridge.sync.storm.client.RemoteClient {
public RemoteClient(){
super(); | if(BridgeConstant.CONNECTOR_MODE.STORM_REMOTE.getCode().equals(CoreDefinition.getPropertyValue("sync.mode"))){ |
yiyongfei/jea | architecture-web/src/main/java/com/ea/core/web/bridge/sync/storm/client/RemoteClient.java | // Path: architecture-core/src/main/java/com/ea/core/base/CoreDefinition.java
// public class CoreDefinition {
// static Map<String, String> mapProperty = new HashMap<String, String>();
//
// static{
// ClassPathResource resource = new ClassPathResource("jea-core.properties");
// try {
// Props p = new Props();
// p.load(resource.getInputStream());
// Iterator<PropsEntry> entries = p.iterator();
// while(entries.hasNext()){
// PropsEntry entry = entries.next();
// mapProperty.put(entry.getKey(), entry.getValue());
// }
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
//
// public static String getPropertyValue(String key){
// return mapProperty.get(key);
// }
// }
//
// Path: architecture-web/src/main/java/com/ea/core/web/bridge/BridgeConstant.java
// public class BridgeConstant {
// public enum CONNECTOR_MODE {
// MQ("MQ"),
// SPRING("SPRING"),
// STORM_LOCAL("STORM.LOCAL"),
// STORM_REMOTE("STORM.REMOTE");
//
// private String code;
//
// private CONNECTOR_MODE(String code) {
// this.code = code;
// }
//
// public String getCode() {
// return code;
// }
// }
//
// }
| import org.springframework.stereotype.Component;
import com.ea.core.base.CoreDefinition;
import com.ea.core.storm.StormDefinition;
import com.ea.core.web.bridge.BridgeConstant; | /**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.web.bridge.sync.storm.client;
@Component
public class RemoteClient extends com.ea.core.bridge.sync.storm.client.RemoteClient {
public RemoteClient(){
super(); | // Path: architecture-core/src/main/java/com/ea/core/base/CoreDefinition.java
// public class CoreDefinition {
// static Map<String, String> mapProperty = new HashMap<String, String>();
//
// static{
// ClassPathResource resource = new ClassPathResource("jea-core.properties");
// try {
// Props p = new Props();
// p.load(resource.getInputStream());
// Iterator<PropsEntry> entries = p.iterator();
// while(entries.hasNext()){
// PropsEntry entry = entries.next();
// mapProperty.put(entry.getKey(), entry.getValue());
// }
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
//
// public static String getPropertyValue(String key){
// return mapProperty.get(key);
// }
// }
//
// Path: architecture-web/src/main/java/com/ea/core/web/bridge/BridgeConstant.java
// public class BridgeConstant {
// public enum CONNECTOR_MODE {
// MQ("MQ"),
// SPRING("SPRING"),
// STORM_LOCAL("STORM.LOCAL"),
// STORM_REMOTE("STORM.REMOTE");
//
// private String code;
//
// private CONNECTOR_MODE(String code) {
// this.code = code;
// }
//
// public String getCode() {
// return code;
// }
// }
//
// }
// Path: architecture-web/src/main/java/com/ea/core/web/bridge/sync/storm/client/RemoteClient.java
import org.springframework.stereotype.Component;
import com.ea.core.base.CoreDefinition;
import com.ea.core.storm.StormDefinition;
import com.ea.core.web.bridge.BridgeConstant;
/**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.web.bridge.sync.storm.client;
@Component
public class RemoteClient extends com.ea.core.bridge.sync.storm.client.RemoteClient {
public RemoteClient(){
super(); | if(BridgeConstant.CONNECTOR_MODE.STORM_REMOTE.getCode().equals(CoreDefinition.getPropertyValue("sync.mode"))){ |
yiyongfei/jea | architecture-orm/src/main/java/com/ea/core/orm/handle/impl/QueryORMHandle.java | // Path: architecture-orm/src/main/java/com/ea/core/orm/handle/AbstractORMHandle.java
// public abstract class AbstractORMHandle implements ORMHandle, ApplicationContextAware {
// protected ApplicationContext context = null;
//
// @Autowired
// private SqlSessionTemplate mybatisSessionTemplate;
// @Autowired
// private SessionFactory hibernateSessionFactory;
//
// private String level;
// private ORMHandle nextHandle;
//
// public AbstractORMHandle(String level){
// this.level = level;
// }
//
// /**
// * 符合当前Level,则执行DB操作,否则交由下个Handle去执行
// */
// public final Object handle(String level, ORMParamsDTO dto) throws Exception {
// if(this.level.equals(level)){
// return this.execute(dto);
// } else {
// this.setNextHandle();
// if(this.nextHandle != null){
// return this.nextHandle.handle(level, dto);
// } else {
// throw new Exception("必须设置ORMHandle处理当前请求");
// }
// }
// }
//
// /**
// * 执行DB操作
// * @param dto
// * @return
// * @throws Exception
// */
// protected abstract Object execute(ORMParamsDTO dto) throws Exception;
//
// /**
// * 设置下个Handle,子类设置,如果是最后一个Handle,不设置
// */
// public abstract void setNextHandle();
//
// protected SqlSessionTemplate getMybatisSessionTemplate() {
// return mybatisSessionTemplate;
// }
//
// protected SessionFactory getHibernateSessionFactory() {
// return hibernateSessionFactory;
// }
//
// public void setApplicationContext(ApplicationContext applicationContext) {
// // TODO Auto-generated method stub
// context = applicationContext;
// }
//
// protected void setNextHandle(ORMHandle nextHandle){
// this.nextHandle = nextHandle;
// }
//
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/ORMHandle.java
// public interface ORMHandle {
//
// public Object handle(String level, ORMParamsDTO dto) throws Exception;
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/dto/ORMParamsDTO.java
// public class ORMParamsDTO implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private Object param;
// private String sqlid;
//
// public Object getParam() {
// return param;
// }
// public void setParam(Object param) {
// this.param = param;
// }
// public String getSqlid() {
// return sqlid;
// }
// public void setSqlid(String sqlid) {
// this.sqlid = sqlid;
// }
//
// }
| import org.springframework.stereotype.Component;
import com.ea.core.orm.handle.AbstractORMHandle;
import com.ea.core.orm.handle.ORMConstants;
import com.ea.core.orm.handle.ORMHandle;
import com.ea.core.orm.handle.dto.ORMParamsDTO; | /**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.orm.handle.impl;
/**
* 查询一条符合条件的数据操作,由Mybatis完成
*
* @author yiyongfei
*
*/
@Component
public class QueryORMHandle extends AbstractORMHandle {
public QueryORMHandle() {
super(ORMConstants.ORM_LEVEL.QUERY.getCode());
}
@Override | // Path: architecture-orm/src/main/java/com/ea/core/orm/handle/AbstractORMHandle.java
// public abstract class AbstractORMHandle implements ORMHandle, ApplicationContextAware {
// protected ApplicationContext context = null;
//
// @Autowired
// private SqlSessionTemplate mybatisSessionTemplate;
// @Autowired
// private SessionFactory hibernateSessionFactory;
//
// private String level;
// private ORMHandle nextHandle;
//
// public AbstractORMHandle(String level){
// this.level = level;
// }
//
// /**
// * 符合当前Level,则执行DB操作,否则交由下个Handle去执行
// */
// public final Object handle(String level, ORMParamsDTO dto) throws Exception {
// if(this.level.equals(level)){
// return this.execute(dto);
// } else {
// this.setNextHandle();
// if(this.nextHandle != null){
// return this.nextHandle.handle(level, dto);
// } else {
// throw new Exception("必须设置ORMHandle处理当前请求");
// }
// }
// }
//
// /**
// * 执行DB操作
// * @param dto
// * @return
// * @throws Exception
// */
// protected abstract Object execute(ORMParamsDTO dto) throws Exception;
//
// /**
// * 设置下个Handle,子类设置,如果是最后一个Handle,不设置
// */
// public abstract void setNextHandle();
//
// protected SqlSessionTemplate getMybatisSessionTemplate() {
// return mybatisSessionTemplate;
// }
//
// protected SessionFactory getHibernateSessionFactory() {
// return hibernateSessionFactory;
// }
//
// public void setApplicationContext(ApplicationContext applicationContext) {
// // TODO Auto-generated method stub
// context = applicationContext;
// }
//
// protected void setNextHandle(ORMHandle nextHandle){
// this.nextHandle = nextHandle;
// }
//
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/ORMHandle.java
// public interface ORMHandle {
//
// public Object handle(String level, ORMParamsDTO dto) throws Exception;
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/dto/ORMParamsDTO.java
// public class ORMParamsDTO implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private Object param;
// private String sqlid;
//
// public Object getParam() {
// return param;
// }
// public void setParam(Object param) {
// this.param = param;
// }
// public String getSqlid() {
// return sqlid;
// }
// public void setSqlid(String sqlid) {
// this.sqlid = sqlid;
// }
//
// }
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/impl/QueryORMHandle.java
import org.springframework.stereotype.Component;
import com.ea.core.orm.handle.AbstractORMHandle;
import com.ea.core.orm.handle.ORMConstants;
import com.ea.core.orm.handle.ORMHandle;
import com.ea.core.orm.handle.dto.ORMParamsDTO;
/**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.orm.handle.impl;
/**
* 查询一条符合条件的数据操作,由Mybatis完成
*
* @author yiyongfei
*
*/
@Component
public class QueryORMHandle extends AbstractORMHandle {
public QueryORMHandle() {
super(ORMConstants.ORM_LEVEL.QUERY.getCode());
}
@Override | protected Object execute(ORMParamsDTO dto) { |
yiyongfei/jea | architecture-orm/src/main/java/com/ea/core/orm/handle/impl/QueryORMHandle.java | // Path: architecture-orm/src/main/java/com/ea/core/orm/handle/AbstractORMHandle.java
// public abstract class AbstractORMHandle implements ORMHandle, ApplicationContextAware {
// protected ApplicationContext context = null;
//
// @Autowired
// private SqlSessionTemplate mybatisSessionTemplate;
// @Autowired
// private SessionFactory hibernateSessionFactory;
//
// private String level;
// private ORMHandle nextHandle;
//
// public AbstractORMHandle(String level){
// this.level = level;
// }
//
// /**
// * 符合当前Level,则执行DB操作,否则交由下个Handle去执行
// */
// public final Object handle(String level, ORMParamsDTO dto) throws Exception {
// if(this.level.equals(level)){
// return this.execute(dto);
// } else {
// this.setNextHandle();
// if(this.nextHandle != null){
// return this.nextHandle.handle(level, dto);
// } else {
// throw new Exception("必须设置ORMHandle处理当前请求");
// }
// }
// }
//
// /**
// * 执行DB操作
// * @param dto
// * @return
// * @throws Exception
// */
// protected abstract Object execute(ORMParamsDTO dto) throws Exception;
//
// /**
// * 设置下个Handle,子类设置,如果是最后一个Handle,不设置
// */
// public abstract void setNextHandle();
//
// protected SqlSessionTemplate getMybatisSessionTemplate() {
// return mybatisSessionTemplate;
// }
//
// protected SessionFactory getHibernateSessionFactory() {
// return hibernateSessionFactory;
// }
//
// public void setApplicationContext(ApplicationContext applicationContext) {
// // TODO Auto-generated method stub
// context = applicationContext;
// }
//
// protected void setNextHandle(ORMHandle nextHandle){
// this.nextHandle = nextHandle;
// }
//
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/ORMHandle.java
// public interface ORMHandle {
//
// public Object handle(String level, ORMParamsDTO dto) throws Exception;
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/dto/ORMParamsDTO.java
// public class ORMParamsDTO implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private Object param;
// private String sqlid;
//
// public Object getParam() {
// return param;
// }
// public void setParam(Object param) {
// this.param = param;
// }
// public String getSqlid() {
// return sqlid;
// }
// public void setSqlid(String sqlid) {
// this.sqlid = sqlid;
// }
//
// }
| import org.springframework.stereotype.Component;
import com.ea.core.orm.handle.AbstractORMHandle;
import com.ea.core.orm.handle.ORMConstants;
import com.ea.core.orm.handle.ORMHandle;
import com.ea.core.orm.handle.dto.ORMParamsDTO; | /**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.orm.handle.impl;
/**
* 查询一条符合条件的数据操作,由Mybatis完成
*
* @author yiyongfei
*
*/
@Component
public class QueryORMHandle extends AbstractORMHandle {
public QueryORMHandle() {
super(ORMConstants.ORM_LEVEL.QUERY.getCode());
}
@Override
protected Object execute(ORMParamsDTO dto) {
// TODO Auto-generated method stub
if(dto.getParam() == null){
return this.getMybatisSessionTemplate().selectOne(dto.getSqlid());
}
return this.getMybatisSessionTemplate().selectOne(dto.getSqlid(), dto.getParam());
}
@Override
public void setNextHandle() {
// TODO Auto-generated method stub | // Path: architecture-orm/src/main/java/com/ea/core/orm/handle/AbstractORMHandle.java
// public abstract class AbstractORMHandle implements ORMHandle, ApplicationContextAware {
// protected ApplicationContext context = null;
//
// @Autowired
// private SqlSessionTemplate mybatisSessionTemplate;
// @Autowired
// private SessionFactory hibernateSessionFactory;
//
// private String level;
// private ORMHandle nextHandle;
//
// public AbstractORMHandle(String level){
// this.level = level;
// }
//
// /**
// * 符合当前Level,则执行DB操作,否则交由下个Handle去执行
// */
// public final Object handle(String level, ORMParamsDTO dto) throws Exception {
// if(this.level.equals(level)){
// return this.execute(dto);
// } else {
// this.setNextHandle();
// if(this.nextHandle != null){
// return this.nextHandle.handle(level, dto);
// } else {
// throw new Exception("必须设置ORMHandle处理当前请求");
// }
// }
// }
//
// /**
// * 执行DB操作
// * @param dto
// * @return
// * @throws Exception
// */
// protected abstract Object execute(ORMParamsDTO dto) throws Exception;
//
// /**
// * 设置下个Handle,子类设置,如果是最后一个Handle,不设置
// */
// public abstract void setNextHandle();
//
// protected SqlSessionTemplate getMybatisSessionTemplate() {
// return mybatisSessionTemplate;
// }
//
// protected SessionFactory getHibernateSessionFactory() {
// return hibernateSessionFactory;
// }
//
// public void setApplicationContext(ApplicationContext applicationContext) {
// // TODO Auto-generated method stub
// context = applicationContext;
// }
//
// protected void setNextHandle(ORMHandle nextHandle){
// this.nextHandle = nextHandle;
// }
//
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/ORMHandle.java
// public interface ORMHandle {
//
// public Object handle(String level, ORMParamsDTO dto) throws Exception;
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/dto/ORMParamsDTO.java
// public class ORMParamsDTO implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private Object param;
// private String sqlid;
//
// public Object getParam() {
// return param;
// }
// public void setParam(Object param) {
// this.param = param;
// }
// public String getSqlid() {
// return sqlid;
// }
// public void setSqlid(String sqlid) {
// this.sqlid = sqlid;
// }
//
// }
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/impl/QueryORMHandle.java
import org.springframework.stereotype.Component;
import com.ea.core.orm.handle.AbstractORMHandle;
import com.ea.core.orm.handle.ORMConstants;
import com.ea.core.orm.handle.ORMHandle;
import com.ea.core.orm.handle.dto.ORMParamsDTO;
/**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.orm.handle.impl;
/**
* 查询一条符合条件的数据操作,由Mybatis完成
*
* @author yiyongfei
*
*/
@Component
public class QueryORMHandle extends AbstractORMHandle {
public QueryORMHandle() {
super(ORMConstants.ORM_LEVEL.QUERY.getCode());
}
@Override
protected Object execute(ORMParamsDTO dto) {
// TODO Auto-generated method stub
if(dto.getParam() == null){
return this.getMybatisSessionTemplate().selectOne(dto.getSqlid());
}
return this.getMybatisSessionTemplate().selectOne(dto.getSqlid(), dto.getParam());
}
@Override
public void setNextHandle() {
// TODO Auto-generated method stub | ORMHandle nextHandle = (QueryListORMHandle)this.context.getBean("queryListORMHandle"); |
yiyongfei/jea | architecture-integration/src/main/java/com/ea/core/integration/bridge/RestIntegration.java | // Path: architecture-integration/src/main/java/com/ea/core/integration/IntegrationContext.java
// public class IntegrationContext {
// private Logger logger = LoggerFactory.getLogger(IntegrationContext.class);
//
// public Object connect(String connectMode, Map<String, String> conf, String connectorId, String facadeId, Object... models) throws Exception {
// // TODO Auto-generated method stub
// long startTime = Calendar.getInstance().getTimeInMillis();
// IConnector connector = null;
// if(connectMode.equals(IntegrationConstant.CONNECTOR_MODE.MQ.getCode())){
// IClient client = new MqSendClient(conf.get(IntegrationConstant.CONF.HOST.getCode()),
// conf.get(IntegrationConstant.CONF.USERNAME.getCode()),
// conf.get(IntegrationConstant.CONF.PASSWORD.getCode()));
// connector = new MqConnector();
// ((AbstractConnector)connector).setClient(client);
// }
// else if(connectMode.equals(IntegrationConstant.CONNECTOR_MODE.STORM.getCode())){
// IClient client = new RemoteClient(conf.get(IntegrationConstant.CONF.HOST.getCode()),
// new Integer(conf.get(IntegrationConstant.CONF.PORT.getCode())),
// new Integer(conf.get(IntegrationConstant.CONF.TIMEOUT.getCode())));
// connector = new StormConnector();
// ((AbstractConnector)connector).setClient(client);
// }
// else if(connectMode.equals(IntegrationConstant.CONNECTOR_MODE.SOAP.getCode())){
// IWSClient client = new SoapClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// connector = new SoapConnector();
// ((AbstractWSConnector)connector).setClient(client);
// }
// else {
// IWSClient client = null;
// if(HttpMethod.GET.equals(conf.get(IntegrationConstant.CONF.HTTP_METHOD.getCode()))){
// client = new GetClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// } else if(HttpMethod.POST.equals(conf.get(IntegrationConstant.CONF.HTTP_METHOD.getCode()))){
// client = new PostClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// } else if(HttpMethod.PUT.equals(conf.get(IntegrationConstant.CONF.HTTP_METHOD.getCode()))){
// client = new PutClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// } else if(HttpMethod.DELETE.equals(conf.get(IntegrationConstant.CONF.HTTP_METHOD.getCode()))){
// client = new DeleteClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// } else {
// throw new RuntimeException("提供的HttpMethod方法有误,请检查!");
// }
// connector = new RestConnector();
// ((AbstractWSConnector)connector).setClient(client);
// }
// long endTime1 = Calendar.getInstance().getTimeInMillis();
// logger.info("初始化连接共耗时" + (endTime1 - startTime) + "毫秒");
// Object result = connector.connect(connectorId, facadeId, models);
// long endTime2 = Calendar.getInstance().getTimeInMillis();
// logger.info("本次执行共耗时" + (endTime2 - startTime) + "毫秒,排除初始化连接后的耗时" + (endTime2 - endTime1) + "毫秒,连接方式:" + connectMode + ",调用Facade:" + facadeId);
// return result;
// }
//
// }
| import java.util.HashMap;
import java.util.Map;
import com.ea.core.integration.IntegrationConstant;
import com.ea.core.integration.IntegrationContext; | package com.ea.core.integration.bridge;
public class RestIntegration {
public void connect(String host, String httpMethod, String method, Object... obj) throws Exception{ | // Path: architecture-integration/src/main/java/com/ea/core/integration/IntegrationContext.java
// public class IntegrationContext {
// private Logger logger = LoggerFactory.getLogger(IntegrationContext.class);
//
// public Object connect(String connectMode, Map<String, String> conf, String connectorId, String facadeId, Object... models) throws Exception {
// // TODO Auto-generated method stub
// long startTime = Calendar.getInstance().getTimeInMillis();
// IConnector connector = null;
// if(connectMode.equals(IntegrationConstant.CONNECTOR_MODE.MQ.getCode())){
// IClient client = new MqSendClient(conf.get(IntegrationConstant.CONF.HOST.getCode()),
// conf.get(IntegrationConstant.CONF.USERNAME.getCode()),
// conf.get(IntegrationConstant.CONF.PASSWORD.getCode()));
// connector = new MqConnector();
// ((AbstractConnector)connector).setClient(client);
// }
// else if(connectMode.equals(IntegrationConstant.CONNECTOR_MODE.STORM.getCode())){
// IClient client = new RemoteClient(conf.get(IntegrationConstant.CONF.HOST.getCode()),
// new Integer(conf.get(IntegrationConstant.CONF.PORT.getCode())),
// new Integer(conf.get(IntegrationConstant.CONF.TIMEOUT.getCode())));
// connector = new StormConnector();
// ((AbstractConnector)connector).setClient(client);
// }
// else if(connectMode.equals(IntegrationConstant.CONNECTOR_MODE.SOAP.getCode())){
// IWSClient client = new SoapClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// connector = new SoapConnector();
// ((AbstractWSConnector)connector).setClient(client);
// }
// else {
// IWSClient client = null;
// if(HttpMethod.GET.equals(conf.get(IntegrationConstant.CONF.HTTP_METHOD.getCode()))){
// client = new GetClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// } else if(HttpMethod.POST.equals(conf.get(IntegrationConstant.CONF.HTTP_METHOD.getCode()))){
// client = new PostClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// } else if(HttpMethod.PUT.equals(conf.get(IntegrationConstant.CONF.HTTP_METHOD.getCode()))){
// client = new PutClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// } else if(HttpMethod.DELETE.equals(conf.get(IntegrationConstant.CONF.HTTP_METHOD.getCode()))){
// client = new DeleteClient(new URL(conf.get(IntegrationConstant.CONF.HOST.getCode())));
// } else {
// throw new RuntimeException("提供的HttpMethod方法有误,请检查!");
// }
// connector = new RestConnector();
// ((AbstractWSConnector)connector).setClient(client);
// }
// long endTime1 = Calendar.getInstance().getTimeInMillis();
// logger.info("初始化连接共耗时" + (endTime1 - startTime) + "毫秒");
// Object result = connector.connect(connectorId, facadeId, models);
// long endTime2 = Calendar.getInstance().getTimeInMillis();
// logger.info("本次执行共耗时" + (endTime2 - startTime) + "毫秒,排除初始化连接后的耗时" + (endTime2 - endTime1) + "毫秒,连接方式:" + connectMode + ",调用Facade:" + facadeId);
// return result;
// }
//
// }
// Path: architecture-integration/src/main/java/com/ea/core/integration/bridge/RestIntegration.java
import java.util.HashMap;
import java.util.Map;
import com.ea.core.integration.IntegrationConstant;
import com.ea.core.integration.IntegrationContext;
package com.ea.core.integration.bridge;
public class RestIntegration {
public void connect(String host, String httpMethod, String method, Object... obj) throws Exception{ | IntegrationContext context = new IntegrationContext(); |
yiyongfei/jea | architecture-orm/src/main/java/com/ea/core/orm/handle/impl/TriggerORMHandle.java | // Path: architecture-orm/src/main/java/com/ea/core/orm/handle/AbstractORMHandle.java
// public abstract class AbstractORMHandle implements ORMHandle, ApplicationContextAware {
// protected ApplicationContext context = null;
//
// @Autowired
// private SqlSessionTemplate mybatisSessionTemplate;
// @Autowired
// private SessionFactory hibernateSessionFactory;
//
// private String level;
// private ORMHandle nextHandle;
//
// public AbstractORMHandle(String level){
// this.level = level;
// }
//
// /**
// * 符合当前Level,则执行DB操作,否则交由下个Handle去执行
// */
// public final Object handle(String level, ORMParamsDTO dto) throws Exception {
// if(this.level.equals(level)){
// return this.execute(dto);
// } else {
// this.setNextHandle();
// if(this.nextHandle != null){
// return this.nextHandle.handle(level, dto);
// } else {
// throw new Exception("必须设置ORMHandle处理当前请求");
// }
// }
// }
//
// /**
// * 执行DB操作
// * @param dto
// * @return
// * @throws Exception
// */
// protected abstract Object execute(ORMParamsDTO dto) throws Exception;
//
// /**
// * 设置下个Handle,子类设置,如果是最后一个Handle,不设置
// */
// public abstract void setNextHandle();
//
// protected SqlSessionTemplate getMybatisSessionTemplate() {
// return mybatisSessionTemplate;
// }
//
// protected SessionFactory getHibernateSessionFactory() {
// return hibernateSessionFactory;
// }
//
// public void setApplicationContext(ApplicationContext applicationContext) {
// // TODO Auto-generated method stub
// context = applicationContext;
// }
//
// protected void setNextHandle(ORMHandle nextHandle){
// this.nextHandle = nextHandle;
// }
//
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/ORMHandle.java
// public interface ORMHandle {
//
// public Object handle(String level, ORMParamsDTO dto) throws Exception;
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/dto/ORMParamsDTO.java
// public class ORMParamsDTO implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private Object param;
// private String sqlid;
//
// public Object getParam() {
// return param;
// }
// public void setParam(Object param) {
// this.param = param;
// }
// public String getSqlid() {
// return sqlid;
// }
// public void setSqlid(String sqlid) {
// this.sqlid = sqlid;
// }
//
// }
| import org.springframework.stereotype.Component;
import com.ea.core.orm.handle.AbstractORMHandle;
import com.ea.core.orm.handle.ORMConstants;
import com.ea.core.orm.handle.ORMHandle;
import com.ea.core.orm.handle.dto.ORMParamsDTO; | /**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.orm.handle.impl;
/**
* 只用于触发DB操作,不做实际动作
*
* @author yiyongfei
*
*/
@Component
public class TriggerORMHandle extends AbstractORMHandle {
public TriggerORMHandle() {
super(ORMConstants.ORM_LEVEL.TRIGGER.getCode());
}
@Override | // Path: architecture-orm/src/main/java/com/ea/core/orm/handle/AbstractORMHandle.java
// public abstract class AbstractORMHandle implements ORMHandle, ApplicationContextAware {
// protected ApplicationContext context = null;
//
// @Autowired
// private SqlSessionTemplate mybatisSessionTemplate;
// @Autowired
// private SessionFactory hibernateSessionFactory;
//
// private String level;
// private ORMHandle nextHandle;
//
// public AbstractORMHandle(String level){
// this.level = level;
// }
//
// /**
// * 符合当前Level,则执行DB操作,否则交由下个Handle去执行
// */
// public final Object handle(String level, ORMParamsDTO dto) throws Exception {
// if(this.level.equals(level)){
// return this.execute(dto);
// } else {
// this.setNextHandle();
// if(this.nextHandle != null){
// return this.nextHandle.handle(level, dto);
// } else {
// throw new Exception("必须设置ORMHandle处理当前请求");
// }
// }
// }
//
// /**
// * 执行DB操作
// * @param dto
// * @return
// * @throws Exception
// */
// protected abstract Object execute(ORMParamsDTO dto) throws Exception;
//
// /**
// * 设置下个Handle,子类设置,如果是最后一个Handle,不设置
// */
// public abstract void setNextHandle();
//
// protected SqlSessionTemplate getMybatisSessionTemplate() {
// return mybatisSessionTemplate;
// }
//
// protected SessionFactory getHibernateSessionFactory() {
// return hibernateSessionFactory;
// }
//
// public void setApplicationContext(ApplicationContext applicationContext) {
// // TODO Auto-generated method stub
// context = applicationContext;
// }
//
// protected void setNextHandle(ORMHandle nextHandle){
// this.nextHandle = nextHandle;
// }
//
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/ORMHandle.java
// public interface ORMHandle {
//
// public Object handle(String level, ORMParamsDTO dto) throws Exception;
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/dto/ORMParamsDTO.java
// public class ORMParamsDTO implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private Object param;
// private String sqlid;
//
// public Object getParam() {
// return param;
// }
// public void setParam(Object param) {
// this.param = param;
// }
// public String getSqlid() {
// return sqlid;
// }
// public void setSqlid(String sqlid) {
// this.sqlid = sqlid;
// }
//
// }
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/impl/TriggerORMHandle.java
import org.springframework.stereotype.Component;
import com.ea.core.orm.handle.AbstractORMHandle;
import com.ea.core.orm.handle.ORMConstants;
import com.ea.core.orm.handle.ORMHandle;
import com.ea.core.orm.handle.dto.ORMParamsDTO;
/**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.orm.handle.impl;
/**
* 只用于触发DB操作,不做实际动作
*
* @author yiyongfei
*
*/
@Component
public class TriggerORMHandle extends AbstractORMHandle {
public TriggerORMHandle() {
super(ORMConstants.ORM_LEVEL.TRIGGER.getCode());
}
@Override | protected Object execute(ORMParamsDTO dto) { |
yiyongfei/jea | architecture-orm/src/main/java/com/ea/core/orm/handle/impl/TriggerORMHandle.java | // Path: architecture-orm/src/main/java/com/ea/core/orm/handle/AbstractORMHandle.java
// public abstract class AbstractORMHandle implements ORMHandle, ApplicationContextAware {
// protected ApplicationContext context = null;
//
// @Autowired
// private SqlSessionTemplate mybatisSessionTemplate;
// @Autowired
// private SessionFactory hibernateSessionFactory;
//
// private String level;
// private ORMHandle nextHandle;
//
// public AbstractORMHandle(String level){
// this.level = level;
// }
//
// /**
// * 符合当前Level,则执行DB操作,否则交由下个Handle去执行
// */
// public final Object handle(String level, ORMParamsDTO dto) throws Exception {
// if(this.level.equals(level)){
// return this.execute(dto);
// } else {
// this.setNextHandle();
// if(this.nextHandle != null){
// return this.nextHandle.handle(level, dto);
// } else {
// throw new Exception("必须设置ORMHandle处理当前请求");
// }
// }
// }
//
// /**
// * 执行DB操作
// * @param dto
// * @return
// * @throws Exception
// */
// protected abstract Object execute(ORMParamsDTO dto) throws Exception;
//
// /**
// * 设置下个Handle,子类设置,如果是最后一个Handle,不设置
// */
// public abstract void setNextHandle();
//
// protected SqlSessionTemplate getMybatisSessionTemplate() {
// return mybatisSessionTemplate;
// }
//
// protected SessionFactory getHibernateSessionFactory() {
// return hibernateSessionFactory;
// }
//
// public void setApplicationContext(ApplicationContext applicationContext) {
// // TODO Auto-generated method stub
// context = applicationContext;
// }
//
// protected void setNextHandle(ORMHandle nextHandle){
// this.nextHandle = nextHandle;
// }
//
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/ORMHandle.java
// public interface ORMHandle {
//
// public Object handle(String level, ORMParamsDTO dto) throws Exception;
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/dto/ORMParamsDTO.java
// public class ORMParamsDTO implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private Object param;
// private String sqlid;
//
// public Object getParam() {
// return param;
// }
// public void setParam(Object param) {
// this.param = param;
// }
// public String getSqlid() {
// return sqlid;
// }
// public void setSqlid(String sqlid) {
// this.sqlid = sqlid;
// }
//
// }
| import org.springframework.stereotype.Component;
import com.ea.core.orm.handle.AbstractORMHandle;
import com.ea.core.orm.handle.ORMConstants;
import com.ea.core.orm.handle.ORMHandle;
import com.ea.core.orm.handle.dto.ORMParamsDTO; | /**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.orm.handle.impl;
/**
* 只用于触发DB操作,不做实际动作
*
* @author yiyongfei
*
*/
@Component
public class TriggerORMHandle extends AbstractORMHandle {
public TriggerORMHandle() {
super(ORMConstants.ORM_LEVEL.TRIGGER.getCode());
}
@Override
protected Object execute(ORMParamsDTO dto) {
return null;
}
@Override
public void setNextHandle() {
// TODO Auto-generated method stub | // Path: architecture-orm/src/main/java/com/ea/core/orm/handle/AbstractORMHandle.java
// public abstract class AbstractORMHandle implements ORMHandle, ApplicationContextAware {
// protected ApplicationContext context = null;
//
// @Autowired
// private SqlSessionTemplate mybatisSessionTemplate;
// @Autowired
// private SessionFactory hibernateSessionFactory;
//
// private String level;
// private ORMHandle nextHandle;
//
// public AbstractORMHandle(String level){
// this.level = level;
// }
//
// /**
// * 符合当前Level,则执行DB操作,否则交由下个Handle去执行
// */
// public final Object handle(String level, ORMParamsDTO dto) throws Exception {
// if(this.level.equals(level)){
// return this.execute(dto);
// } else {
// this.setNextHandle();
// if(this.nextHandle != null){
// return this.nextHandle.handle(level, dto);
// } else {
// throw new Exception("必须设置ORMHandle处理当前请求");
// }
// }
// }
//
// /**
// * 执行DB操作
// * @param dto
// * @return
// * @throws Exception
// */
// protected abstract Object execute(ORMParamsDTO dto) throws Exception;
//
// /**
// * 设置下个Handle,子类设置,如果是最后一个Handle,不设置
// */
// public abstract void setNextHandle();
//
// protected SqlSessionTemplate getMybatisSessionTemplate() {
// return mybatisSessionTemplate;
// }
//
// protected SessionFactory getHibernateSessionFactory() {
// return hibernateSessionFactory;
// }
//
// public void setApplicationContext(ApplicationContext applicationContext) {
// // TODO Auto-generated method stub
// context = applicationContext;
// }
//
// protected void setNextHandle(ORMHandle nextHandle){
// this.nextHandle = nextHandle;
// }
//
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/ORMHandle.java
// public interface ORMHandle {
//
// public Object handle(String level, ORMParamsDTO dto) throws Exception;
// }
//
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/dto/ORMParamsDTO.java
// public class ORMParamsDTO implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private Object param;
// private String sqlid;
//
// public Object getParam() {
// return param;
// }
// public void setParam(Object param) {
// this.param = param;
// }
// public String getSqlid() {
// return sqlid;
// }
// public void setSqlid(String sqlid) {
// this.sqlid = sqlid;
// }
//
// }
// Path: architecture-orm/src/main/java/com/ea/core/orm/handle/impl/TriggerORMHandle.java
import org.springframework.stereotype.Component;
import com.ea.core.orm.handle.AbstractORMHandle;
import com.ea.core.orm.handle.ORMConstants;
import com.ea.core.orm.handle.ORMHandle;
import com.ea.core.orm.handle.dto.ORMParamsDTO;
/**
* Copyright 2014 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ea.core.orm.handle.impl;
/**
* 只用于触发DB操作,不做实际动作
*
* @author yiyongfei
*
*/
@Component
public class TriggerORMHandle extends AbstractORMHandle {
public TriggerORMHandle() {
super(ORMConstants.ORM_LEVEL.TRIGGER.getCode());
}
@Override
protected Object execute(ORMParamsDTO dto) {
return null;
}
@Override
public void setNextHandle() {
// TODO Auto-generated method stub | ORMHandle nextHandle = (SaveORMHandle)this.context.getBean("saveORMHandle"); |
Samourai-Wallet/sentinel-android | app/src/main/java/com/samourai/sentinel/segwit/SegwitAddress.java | // Path: app/src/main/java/com/samourai/sentinel/segwit/bech32/Bech32Segwit.java
// public class Bech32Segwit {
//
// public static Pair<Byte, byte[]> decode(String hrp, String addr) throws Exception {
//
// Pair<String, byte[]> p = Bech32.bech32Decode(addr);
//
// String hrpgotStr = p.getLeft();
// if(hrpgotStr == null) {
// return null;
// }
// if (!hrp.equalsIgnoreCase(hrpgotStr)) {
// return null;
// }
// if (!hrpgotStr.equalsIgnoreCase("bc") && !hrpgotStr.equalsIgnoreCase("tb")) {
// throw new Exception("invalid segwit human readable part");
// }
//
// byte[] data = p.getRight();
// List<Byte> progBytes = new ArrayList<Byte>();
// for(int i = 1; i < data.length; i++) {
// progBytes.add(data[i]);
// }
// byte[] decoded = convertBits(progBytes, 5, 8, false);
// if(decoded.length < 2 || decoded.length > 40) {
// throw new Exception("invalid decoded data length");
// }
//
// byte witnessVersion = data[0];
// if (witnessVersion > 16) {
// throw new Exception("invalid decoded witness version");
// }
//
// if (witnessVersion == 0 && decoded.length != 20 && decoded.length != 32) {
// throw new Exception("decoded witness version 0 with unknown length");
// }
//
// return Pair.of(witnessVersion, decoded);
// }
//
// public static String encode(String hrp, byte witnessVersion, byte[] witnessProgram) throws Exception {
//
// List<Byte> progBytes = new ArrayList<Byte>();
// for(int i = 0; i < witnessProgram.length; i++) {
// progBytes.add(witnessProgram[i]);
// }
//
// byte[] prog = convertBits(progBytes, 8, 5, true);
// byte[] data = new byte[1 + prog.length];
//
// System.arraycopy(new byte[] { witnessVersion }, 0, data, 0, 1);
// System.arraycopy(prog, 0, data, 1, prog.length);
//
// String ret = Bech32.bech32Encode(hrp, data);
//
// return ret;
// }
//
// private static byte[] convertBits(List<Byte> data, int fromBits, int toBits, boolean pad) throws Exception {
//
// int acc = 0;
// int bits = 0;
// int maxv = (1 << toBits) - 1;
// List<Byte> ret = new ArrayList<Byte>();
//
// for(Byte value : data) {
//
// short b = (short)(value.byteValue() & 0xff);
//
// if (b < 0) {
// throw new Exception();
// }
// else if ((b >> fromBits) > 0) {
// throw new Exception();
// }
// else {
// ;
// }
//
// acc = (acc << fromBits) | b;
// bits += fromBits;
// while (bits >= toBits) {
// bits -= toBits;
// ret.add((byte)((acc >> bits) & maxv));
// }
// }
//
// if(pad && (bits > 0)) {
// ret.add((byte)((acc << (toBits - bits)) & maxv));
// }
// else if (bits >= fromBits || (byte)(((acc << (toBits - bits)) & maxv)) != 0) {
// return null;
// }
// else {
// ;
// }
//
// byte[] buf = new byte[ret.size()];
// for(int i = 0; i < ret.size(); i++) {
// buf[i] = ret.get(i);
// }
//
// return buf;
// }
//
// public static byte[] getScriptPubkey(byte witver, byte[] witprog) {
//
// byte v = (witver > 0) ? (byte)(witver + 0x50) : (byte)0;
// byte[] ver = new byte[] { v, (byte)witprog.length };
//
// byte[] ret = new byte[witprog.length + ver.length];
// System.arraycopy(ver, 0, ret, 0, ver.length);
// System.arraycopy(witprog, 0, ret, ver.length, witprog.length);
//
// return ret;
// }
//
// }
| import com.samourai.sentinel.segwit.bech32.Bech32Segwit;
import org.bitcoinj.core.Address;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.core.Utils;
import org.bitcoinj.params.TestNet3Params;
import org.bitcoinj.script.Script; | public SegwitAddress(byte[] pubkey, NetworkParameters params) {
this.ecKey = ECKey.fromPublicOnly(pubkey);
this.params = params;
}
public ECKey getECKey() {
return ecKey;
}
public void setECKey(ECKey ecKey) {
this.ecKey = ecKey;
}
public Address segWitAddress() {
return Address.fromP2SHScript(params, segWitOutputScript());
}
public String getAddressAsString() {
return segWitAddress().toString();
}
public String getBech32AsString() {
String address = null;
try { | // Path: app/src/main/java/com/samourai/sentinel/segwit/bech32/Bech32Segwit.java
// public class Bech32Segwit {
//
// public static Pair<Byte, byte[]> decode(String hrp, String addr) throws Exception {
//
// Pair<String, byte[]> p = Bech32.bech32Decode(addr);
//
// String hrpgotStr = p.getLeft();
// if(hrpgotStr == null) {
// return null;
// }
// if (!hrp.equalsIgnoreCase(hrpgotStr)) {
// return null;
// }
// if (!hrpgotStr.equalsIgnoreCase("bc") && !hrpgotStr.equalsIgnoreCase("tb")) {
// throw new Exception("invalid segwit human readable part");
// }
//
// byte[] data = p.getRight();
// List<Byte> progBytes = new ArrayList<Byte>();
// for(int i = 1; i < data.length; i++) {
// progBytes.add(data[i]);
// }
// byte[] decoded = convertBits(progBytes, 5, 8, false);
// if(decoded.length < 2 || decoded.length > 40) {
// throw new Exception("invalid decoded data length");
// }
//
// byte witnessVersion = data[0];
// if (witnessVersion > 16) {
// throw new Exception("invalid decoded witness version");
// }
//
// if (witnessVersion == 0 && decoded.length != 20 && decoded.length != 32) {
// throw new Exception("decoded witness version 0 with unknown length");
// }
//
// return Pair.of(witnessVersion, decoded);
// }
//
// public static String encode(String hrp, byte witnessVersion, byte[] witnessProgram) throws Exception {
//
// List<Byte> progBytes = new ArrayList<Byte>();
// for(int i = 0; i < witnessProgram.length; i++) {
// progBytes.add(witnessProgram[i]);
// }
//
// byte[] prog = convertBits(progBytes, 8, 5, true);
// byte[] data = new byte[1 + prog.length];
//
// System.arraycopy(new byte[] { witnessVersion }, 0, data, 0, 1);
// System.arraycopy(prog, 0, data, 1, prog.length);
//
// String ret = Bech32.bech32Encode(hrp, data);
//
// return ret;
// }
//
// private static byte[] convertBits(List<Byte> data, int fromBits, int toBits, boolean pad) throws Exception {
//
// int acc = 0;
// int bits = 0;
// int maxv = (1 << toBits) - 1;
// List<Byte> ret = new ArrayList<Byte>();
//
// for(Byte value : data) {
//
// short b = (short)(value.byteValue() & 0xff);
//
// if (b < 0) {
// throw new Exception();
// }
// else if ((b >> fromBits) > 0) {
// throw new Exception();
// }
// else {
// ;
// }
//
// acc = (acc << fromBits) | b;
// bits += fromBits;
// while (bits >= toBits) {
// bits -= toBits;
// ret.add((byte)((acc >> bits) & maxv));
// }
// }
//
// if(pad && (bits > 0)) {
// ret.add((byte)((acc << (toBits - bits)) & maxv));
// }
// else if (bits >= fromBits || (byte)(((acc << (toBits - bits)) & maxv)) != 0) {
// return null;
// }
// else {
// ;
// }
//
// byte[] buf = new byte[ret.size()];
// for(int i = 0; i < ret.size(); i++) {
// buf[i] = ret.get(i);
// }
//
// return buf;
// }
//
// public static byte[] getScriptPubkey(byte witver, byte[] witprog) {
//
// byte v = (witver > 0) ? (byte)(witver + 0x50) : (byte)0;
// byte[] ver = new byte[] { v, (byte)witprog.length };
//
// byte[] ret = new byte[witprog.length + ver.length];
// System.arraycopy(ver, 0, ret, 0, ver.length);
// System.arraycopy(witprog, 0, ret, ver.length, witprog.length);
//
// return ret;
// }
//
// }
// Path: app/src/main/java/com/samourai/sentinel/segwit/SegwitAddress.java
import com.samourai.sentinel.segwit.bech32.Bech32Segwit;
import org.bitcoinj.core.Address;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.core.Utils;
import org.bitcoinj.params.TestNet3Params;
import org.bitcoinj.script.Script;
public SegwitAddress(byte[] pubkey, NetworkParameters params) {
this.ecKey = ECKey.fromPublicOnly(pubkey);
this.params = params;
}
public ECKey getECKey() {
return ecKey;
}
public void setECKey(ECKey ecKey) {
this.ecKey = ecKey;
}
public Address segWitAddress() {
return Address.fromP2SHScript(params, segWitOutputScript());
}
public String getAddressAsString() {
return segWitAddress().toString();
}
public String getBech32AsString() {
String address = null;
try { | address = Bech32Segwit.encode(params instanceof TestNet3Params ? "tb" : "bc", (byte)0x00, getHash160()); |
Samourai-Wallet/sentinel-android | app/src/main/java/com/samourai/sentinel/crypto/AESUtil.java | // Path: app/src/main/java/com/samourai/sentinel/util/CharSequenceX.java
// public class CharSequenceX implements CharSequence {
//
// private char[] chars;
// private int rounds = 100;
//
// private CharSequenceX(CharSequence charSequence, int start, int end) {
// zap();
// int len = end - start;
// chars = new char[len];
// for(int i = start; i < end; i++) {
// chars[i - start] = charSequence.charAt(i);
// }
// }
//
// public CharSequenceX(int len) {
// chars = new char[len];
// }
//
// public CharSequenceX(CharSequence charSequence) {
// this(charSequence, 0, charSequence.length());
// }
//
// public CharSequenceX(char[] chars) {
// zap();
// this.chars = chars;
// }
//
// public void zap() {
// if(chars != null) {
// for(int i = 0; i < rounds; i++) {
// fill('0');
// rfill();
// fill('0');
// }
// }
// }
//
// public void setRounds(int rounds) {
// if(rounds < 100) {
// this.rounds = 100;
// }
// else {
// this.rounds = rounds;
// }
// }
//
// @Override
// public char charAt(int index) {
// if(chars != null) {
// return chars[index];
// }
// else {
// return 0;
// }
// }
//
// @Override
// public int length() {
// if(chars != null) {
// return chars.length;
// }
// else {
// return 0;
// }
// }
//
// @Override
// public String toString() {
// return new String(chars);
// }
//
// @Override
// public boolean equals(Object o) {
// if(o instanceof CharSequenceX) {
// return Arrays.equals(chars, ((CharSequenceX) o).chars);
// }
// else {
// return false;
// }
// }
//
// @Override
// public CharSequence subSequence(int start, int end) {
// CharSequenceX s = new CharSequenceX(this, start, end);
// return s;
// }
//
// protected void finalize() {
// zap();
// }
//
// private void fill(char c) {
// for(int i = 0; i < chars.length; i++) {
// chars[i] = c;
// }
// }
//
// private void rfill() {
// SecureRandom r = new SecureRandom();
// byte[] b = new byte[chars.length];
// r.nextBytes(b);
// for(int i = 0; i < chars.length; i++) {
// chars[i] = (char)b[i];
// }
// }
//
// }
| import com.samourai.sentinel.util.CharSequenceX;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.crypto.BufferedBlockCipher;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.PBEParametersGenerator;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.paddings.BlockCipherPadding;
import org.bouncycastle.crypto.paddings.ISO10126d2Padding;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import java.io.UnsupportedEncodingException;
import java.security.SecureRandom; | package com.samourai.sentinel.crypto;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.apache.commons.lang.ArrayUtils;
public class AESUtil {
// private static Logger mLogger = LoggerFactory.getLogger(AESUtil.class);
public static final int DefaultPBKDF2Iterations = 5000;
private static byte[] copyOfRange(byte[] source, int from, int to) {
byte[] range = new byte[to - from];
System.arraycopy(source, from, range, 0, range.length);
return range;
}
// AES 256 PBKDF2 CBC iso10126 decryption
// 16 byte IV must be prepended to ciphertext - Compatible with crypto-js | // Path: app/src/main/java/com/samourai/sentinel/util/CharSequenceX.java
// public class CharSequenceX implements CharSequence {
//
// private char[] chars;
// private int rounds = 100;
//
// private CharSequenceX(CharSequence charSequence, int start, int end) {
// zap();
// int len = end - start;
// chars = new char[len];
// for(int i = start; i < end; i++) {
// chars[i - start] = charSequence.charAt(i);
// }
// }
//
// public CharSequenceX(int len) {
// chars = new char[len];
// }
//
// public CharSequenceX(CharSequence charSequence) {
// this(charSequence, 0, charSequence.length());
// }
//
// public CharSequenceX(char[] chars) {
// zap();
// this.chars = chars;
// }
//
// public void zap() {
// if(chars != null) {
// for(int i = 0; i < rounds; i++) {
// fill('0');
// rfill();
// fill('0');
// }
// }
// }
//
// public void setRounds(int rounds) {
// if(rounds < 100) {
// this.rounds = 100;
// }
// else {
// this.rounds = rounds;
// }
// }
//
// @Override
// public char charAt(int index) {
// if(chars != null) {
// return chars[index];
// }
// else {
// return 0;
// }
// }
//
// @Override
// public int length() {
// if(chars != null) {
// return chars.length;
// }
// else {
// return 0;
// }
// }
//
// @Override
// public String toString() {
// return new String(chars);
// }
//
// @Override
// public boolean equals(Object o) {
// if(o instanceof CharSequenceX) {
// return Arrays.equals(chars, ((CharSequenceX) o).chars);
// }
// else {
// return false;
// }
// }
//
// @Override
// public CharSequence subSequence(int start, int end) {
// CharSequenceX s = new CharSequenceX(this, start, end);
// return s;
// }
//
// protected void finalize() {
// zap();
// }
//
// private void fill(char c) {
// for(int i = 0; i < chars.length; i++) {
// chars[i] = c;
// }
// }
//
// private void rfill() {
// SecureRandom r = new SecureRandom();
// byte[] b = new byte[chars.length];
// r.nextBytes(b);
// for(int i = 0; i < chars.length; i++) {
// chars[i] = (char)b[i];
// }
// }
//
// }
// Path: app/src/main/java/com/samourai/sentinel/crypto/AESUtil.java
import com.samourai.sentinel.util.CharSequenceX;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.crypto.BufferedBlockCipher;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.PBEParametersGenerator;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.paddings.BlockCipherPadding;
import org.bouncycastle.crypto.paddings.ISO10126d2Padding;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;
package com.samourai.sentinel.crypto;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.apache.commons.lang.ArrayUtils;
public class AESUtil {
// private static Logger mLogger = LoggerFactory.getLogger(AESUtil.class);
public static final int DefaultPBKDF2Iterations = 5000;
private static byte[] copyOfRange(byte[] source, int from, int to) {
byte[] range = new byte[to - from];
System.arraycopy(source, from, range, 0, range.length);
return range;
}
// AES 256 PBKDF2 CBC iso10126 decryption
// 16 byte IV must be prepended to ciphertext - Compatible with crypto-js | public static String decrypt(String ciphertext, CharSequenceX password, int iterations) { |
Samourai-Wallet/sentinel-android | tor/src/main/java/net/freehaven/tor/control/TorControlConnection.java | // Path: tor/src/main/java/com/msopentech/thali/toronionproxy/OnionProxyManagerEventHandler.java
// public class OnionProxyManagerEventHandler implements EventHandler {
// private static final Logger LOG = LoggerFactory.getLogger(OnionProxyManagerEventHandler.class);
// private String lastLog="";
// public String getLastLog()
// {
// return lastLog;
// }
// /*
// public void circuitStatus(String status, String id, List<String> path, Map<String, String> info) {
// String msg = "CircuitStatus: " + id + " " + status;
// String purpose = info.get("PURPOSE");
// if(purpose != null) msg += ", purpose: " + purpose;
// String hsState = info.get("HS_STATE");
// if(hsState != null) msg += ", state: " + hsState;
// String rendQuery = info.get("REND_QUERY");
// if(rendQuery != null) msg += ", service: " + rendQuery;
// if(!path.isEmpty()) msg += ", path: " + shortenPath(path);
// LOG.info(msg);
// }*/
// public void circuitStatus(String status, String circID, String path) {
// String msg = "CircuitStatus: " + circID + " " + status;
// //String purpose = info.get("PURPOSE");
// //if(purpose != null) msg += ", purpose: " + purpose;
// //String hsState = info.get("HS_STATE");
// //if(hsState != null) msg += ", state: " + hsState;
// //String rendQuery = info.get("REND_QUERY");
// //if(rendQuery != null) msg += ", service: " + rendQuery;
// if(!path.isEmpty()) msg += ", path: " + shortenPath(path);
// // LOG.info(msg);
// lastLog=msg;
// }
//
// public void streamStatus(String status, String id, String target) {
// LOG.info("streamStatus: status: " + status + ", id: " + id + ", target: " + target);
// }
//
// public void orConnStatus(String status, String orName) {
// LOG.info("OR connection: status: " + status + ", orName: " + orName);
// }
//
// public void bandwidthUsed(long read, long written) {
// LOG.info("bandwidthUsed: read: " + read + ", written: " + written);
// }
//
// public void newDescriptors(List<String> orList) {
// Iterator<String> iterator = orList.iterator();
// StringBuilder stringBuilder = new StringBuilder();
// while(iterator.hasNext()) {
// stringBuilder.append(iterator.next());
// }
// LOG.info("newDescriptors: " + stringBuilder.toString());
// }
//
// public void message(String severity, String msg) {
// LOG.info("message: severity: " + severity + ", msg: " + msg);
// lastLog=msg;
// }
//
// public void unrecognized(String type, String msg) {
// LOG.info("unrecognized: type: " + type + ", msg: " + msg);
// lastLog=msg;
// }
//
// private String shortenPath(List<String> path) {
// StringBuilder s = new StringBuilder();
// for(String id : path) {
// if(s.length() > 0) s.append(',');
// s.append(id.substring(1, 7));
// }
// return s.toString();
// }
// private String shortenPath(String id) {
// StringBuilder s = new StringBuilder();
// if(s.length() > 0) s.append(',');
// s.append(id.substring(1, 7));
// return s.toString();
// }
//
// }
| import com.msopentech.thali.toronionproxy.OnionProxyManagerEventHandler;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer; | }
}
/** Sets <b>w</b> as the PrintWriter for debugging output,
* which writes out all messages passed between Tor and the controller.
* Outgoing messages are preceded by "\>\>" and incoming messages are preceded
* by "\<\<"
*/
public void setDebugging(PrintWriter w) {
debugOutput = w;
}
/** Sets <b>s</b> as the PrintStream for debugging output,
* which writes out all messages passed between Tor and the controller.
* Outgoing messages are preceded by "\>\>" and incoming messages are preceded
* by "\<\<"
*/
public void setDebugging(PrintStream s) {
debugOutput = new PrintWriter(s, true);
}
/** Set the EventHandler object that will be notified of any
* events Tor delivers to this connection. To make Tor send us
* events, call setEvents(). */
public void setEventHandler(EventHandler handler) {
this.handler = handler;
}
public String getLastLog()
{ | // Path: tor/src/main/java/com/msopentech/thali/toronionproxy/OnionProxyManagerEventHandler.java
// public class OnionProxyManagerEventHandler implements EventHandler {
// private static final Logger LOG = LoggerFactory.getLogger(OnionProxyManagerEventHandler.class);
// private String lastLog="";
// public String getLastLog()
// {
// return lastLog;
// }
// /*
// public void circuitStatus(String status, String id, List<String> path, Map<String, String> info) {
// String msg = "CircuitStatus: " + id + " " + status;
// String purpose = info.get("PURPOSE");
// if(purpose != null) msg += ", purpose: " + purpose;
// String hsState = info.get("HS_STATE");
// if(hsState != null) msg += ", state: " + hsState;
// String rendQuery = info.get("REND_QUERY");
// if(rendQuery != null) msg += ", service: " + rendQuery;
// if(!path.isEmpty()) msg += ", path: " + shortenPath(path);
// LOG.info(msg);
// }*/
// public void circuitStatus(String status, String circID, String path) {
// String msg = "CircuitStatus: " + circID + " " + status;
// //String purpose = info.get("PURPOSE");
// //if(purpose != null) msg += ", purpose: " + purpose;
// //String hsState = info.get("HS_STATE");
// //if(hsState != null) msg += ", state: " + hsState;
// //String rendQuery = info.get("REND_QUERY");
// //if(rendQuery != null) msg += ", service: " + rendQuery;
// if(!path.isEmpty()) msg += ", path: " + shortenPath(path);
// // LOG.info(msg);
// lastLog=msg;
// }
//
// public void streamStatus(String status, String id, String target) {
// LOG.info("streamStatus: status: " + status + ", id: " + id + ", target: " + target);
// }
//
// public void orConnStatus(String status, String orName) {
// LOG.info("OR connection: status: " + status + ", orName: " + orName);
// }
//
// public void bandwidthUsed(long read, long written) {
// LOG.info("bandwidthUsed: read: " + read + ", written: " + written);
// }
//
// public void newDescriptors(List<String> orList) {
// Iterator<String> iterator = orList.iterator();
// StringBuilder stringBuilder = new StringBuilder();
// while(iterator.hasNext()) {
// stringBuilder.append(iterator.next());
// }
// LOG.info("newDescriptors: " + stringBuilder.toString());
// }
//
// public void message(String severity, String msg) {
// LOG.info("message: severity: " + severity + ", msg: " + msg);
// lastLog=msg;
// }
//
// public void unrecognized(String type, String msg) {
// LOG.info("unrecognized: type: " + type + ", msg: " + msg);
// lastLog=msg;
// }
//
// private String shortenPath(List<String> path) {
// StringBuilder s = new StringBuilder();
// for(String id : path) {
// if(s.length() > 0) s.append(',');
// s.append(id.substring(1, 7));
// }
// return s.toString();
// }
// private String shortenPath(String id) {
// StringBuilder s = new StringBuilder();
// if(s.length() > 0) s.append(',');
// s.append(id.substring(1, 7));
// return s.toString();
// }
//
// }
// Path: tor/src/main/java/net/freehaven/tor/control/TorControlConnection.java
import com.msopentech.thali.toronionproxy.OnionProxyManagerEventHandler;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
}
}
/** Sets <b>w</b> as the PrintWriter for debugging output,
* which writes out all messages passed between Tor and the controller.
* Outgoing messages are preceded by "\>\>" and incoming messages are preceded
* by "\<\<"
*/
public void setDebugging(PrintWriter w) {
debugOutput = w;
}
/** Sets <b>s</b> as the PrintStream for debugging output,
* which writes out all messages passed between Tor and the controller.
* Outgoing messages are preceded by "\>\>" and incoming messages are preceded
* by "\<\<"
*/
public void setDebugging(PrintStream s) {
debugOutput = new PrintWriter(s, true);
}
/** Set the EventHandler object that will be notified of any
* events Tor delivers to this connection. To make Tor send us
* events, call setEvents(). */
public void setEventHandler(EventHandler handler) {
this.handler = handler;
}
public String getLastLog()
{ | return ((OnionProxyManagerEventHandler)handler).getLastLog(); |
Samourai-Wallet/sentinel-android | app/src/main/java/com/samourai/sentinel/tor/TorService.java | // Path: app/src/main/java/com/samourai/sentinel/util/LogUtil.java
// public class LogUtil {
//
// public static void debug(final String tag, String message) {
// if (BuildConfig.DEBUG) {
// android.util.Log.d(tag, message);
// }
// }
//
// public static void info(final String tag, String message) {
// if (BuildConfig.DEBUG) {
// android.util.Log.i(tag, message);
// }
// }
//
// public static void error(final String tag, String message) {
// if (BuildConfig.DEBUG) {
// android.util.Log.e(tag, message);
// }
// }
//
// }
//
// Path: app/src/main/java/com/samourai/sentinel/SentinelApplication.java
// public static String TOR_CHANNEL_ID = "TOR_CHANNEL";
| import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.Toast;
import com.samourai.sentinel.BuildConfig;
import com.samourai.sentinel.R;
import com.samourai.sentinel.util.LogUtil;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import static android.support.v4.app.NotificationCompat.GROUP_ALERT_SUMMARY;
import static com.samourai.sentinel.SentinelApplication.TOR_CHANNEL_ID; | package com.samourai.sentinel.tor;
public class TorService extends Service {
public static String START_SERVICE = "START_SERVICE";
public static String STOP_SERVICE = "STOP_SERVICE";
public static String RESTART_SERVICE = "RESTART_SERVICE";
public static String RENEW_IDENTITY = "RENEW_IDENTITY";
public static int TOR_SERVICE_NOTIFICATION_ID = 95;
private static final String TAG = "TorService";
private CompositeDisposable compositeDisposable = new CompositeDisposable();
private String title = "TOR";
private Disposable torDisposable;
private boolean identityChanging;
@Override
public void onCreate() {
super.onCreate(); | // Path: app/src/main/java/com/samourai/sentinel/util/LogUtil.java
// public class LogUtil {
//
// public static void debug(final String tag, String message) {
// if (BuildConfig.DEBUG) {
// android.util.Log.d(tag, message);
// }
// }
//
// public static void info(final String tag, String message) {
// if (BuildConfig.DEBUG) {
// android.util.Log.i(tag, message);
// }
// }
//
// public static void error(final String tag, String message) {
// if (BuildConfig.DEBUG) {
// android.util.Log.e(tag, message);
// }
// }
//
// }
//
// Path: app/src/main/java/com/samourai/sentinel/SentinelApplication.java
// public static String TOR_CHANNEL_ID = "TOR_CHANNEL";
// Path: app/src/main/java/com/samourai/sentinel/tor/TorService.java
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.Toast;
import com.samourai.sentinel.BuildConfig;
import com.samourai.sentinel.R;
import com.samourai.sentinel.util.LogUtil;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import static android.support.v4.app.NotificationCompat.GROUP_ALERT_SUMMARY;
import static com.samourai.sentinel.SentinelApplication.TOR_CHANNEL_ID;
package com.samourai.sentinel.tor;
public class TorService extends Service {
public static String START_SERVICE = "START_SERVICE";
public static String STOP_SERVICE = "STOP_SERVICE";
public static String RESTART_SERVICE = "RESTART_SERVICE";
public static String RENEW_IDENTITY = "RENEW_IDENTITY";
public static int TOR_SERVICE_NOTIFICATION_ID = 95;
private static final String TAG = "TorService";
private CompositeDisposable compositeDisposable = new CompositeDisposable();
private String title = "TOR";
private Disposable torDisposable;
private boolean identityChanging;
@Override
public void onCreate() {
super.onCreate(); | Notification notification = new NotificationCompat.Builder(this, TOR_CHANNEL_ID) |
Samourai-Wallet/sentinel-android | app/src/main/java/com/samourai/sentinel/tor/TorService.java | // Path: app/src/main/java/com/samourai/sentinel/util/LogUtil.java
// public class LogUtil {
//
// public static void debug(final String tag, String message) {
// if (BuildConfig.DEBUG) {
// android.util.Log.d(tag, message);
// }
// }
//
// public static void info(final String tag, String message) {
// if (BuildConfig.DEBUG) {
// android.util.Log.i(tag, message);
// }
// }
//
// public static void error(final String tag, String message) {
// if (BuildConfig.DEBUG) {
// android.util.Log.e(tag, message);
// }
// }
//
// }
//
// Path: app/src/main/java/com/samourai/sentinel/SentinelApplication.java
// public static String TOR_CHANNEL_ID = "TOR_CHANNEL";
| import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.Toast;
import com.samourai.sentinel.BuildConfig;
import com.samourai.sentinel.R;
import com.samourai.sentinel.util.LogUtil;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import static android.support.v4.app.NotificationCompat.GROUP_ALERT_SUMMARY;
import static com.samourai.sentinel.SentinelApplication.TOR_CHANNEL_ID; | Intent broadcastIntent = new Intent(this, TorBroadCastReceiver.class);
broadcastIntent.setAction(RENEW_IDENTITY);
PendingIntent actionIntent = PendingIntent.getBroadcast(this,
0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
return new NotificationCompat.Action(R.drawable.ic_tor_notification, "New identity", actionIntent);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (Objects.requireNonNull(intent.getAction()).equals(TorService.STOP_SERVICE)) {
//
// if (DojoUtil.getInstance(getApplicationContext()).getDojoParams() != null && !intent.hasExtra("KILL_TOR")) {
// Toast.makeText(getApplicationContext(), "You cannot stop Tor service when dojo is connected", Toast.LENGTH_SHORT).show();
// return START_STICKY;
// }
Disposable disposable = TorManager.getInstance(getApplicationContext())
.stopTor()
.subscribe(stat -> {
compositeDisposable.dispose();
stopSelf();
}, error -> {
//
});
compositeDisposable.add(disposable);
} else if (intent.getAction().equals(TorService.RENEW_IDENTITY)) { | // Path: app/src/main/java/com/samourai/sentinel/util/LogUtil.java
// public class LogUtil {
//
// public static void debug(final String tag, String message) {
// if (BuildConfig.DEBUG) {
// android.util.Log.d(tag, message);
// }
// }
//
// public static void info(final String tag, String message) {
// if (BuildConfig.DEBUG) {
// android.util.Log.i(tag, message);
// }
// }
//
// public static void error(final String tag, String message) {
// if (BuildConfig.DEBUG) {
// android.util.Log.e(tag, message);
// }
// }
//
// }
//
// Path: app/src/main/java/com/samourai/sentinel/SentinelApplication.java
// public static String TOR_CHANNEL_ID = "TOR_CHANNEL";
// Path: app/src/main/java/com/samourai/sentinel/tor/TorService.java
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.Toast;
import com.samourai.sentinel.BuildConfig;
import com.samourai.sentinel.R;
import com.samourai.sentinel.util.LogUtil;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import static android.support.v4.app.NotificationCompat.GROUP_ALERT_SUMMARY;
import static com.samourai.sentinel.SentinelApplication.TOR_CHANNEL_ID;
Intent broadcastIntent = new Intent(this, TorBroadCastReceiver.class);
broadcastIntent.setAction(RENEW_IDENTITY);
PendingIntent actionIntent = PendingIntent.getBroadcast(this,
0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
return new NotificationCompat.Action(R.drawable.ic_tor_notification, "New identity", actionIntent);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (Objects.requireNonNull(intent.getAction()).equals(TorService.STOP_SERVICE)) {
//
// if (DojoUtil.getInstance(getApplicationContext()).getDojoParams() != null && !intent.hasExtra("KILL_TOR")) {
// Toast.makeText(getApplicationContext(), "You cannot stop Tor service when dojo is connected", Toast.LENGTH_SHORT).show();
// return START_STICKY;
// }
Disposable disposable = TorManager.getInstance(getApplicationContext())
.stopTor()
.subscribe(stat -> {
compositeDisposable.dispose();
stopSelf();
}, error -> {
//
});
compositeDisposable.add(disposable);
} else if (intent.getAction().equals(TorService.RENEW_IDENTITY)) { | LogUtil.info(TAG, "onStartCommand: RENEW_IDENTITY"); |
Samourai-Wallet/sentinel-android | app/src/main/java/com/samourai/sentinel/util/AddressFactory.java | // Path: app/src/main/java/com/samourai/sentinel/access/AccessFactory.java
// public class AccessFactory {
//
// public static final int MIN_PIN_LENGTH = 5;
// public static final int MAX_PIN_LENGTH = 8;
//
// private static boolean isLoggedIn = false;
//
// private static Context context = null;
// private static AccessFactory instance = null;
//
// private AccessFactory() { ; }
//
// public static AccessFactory getInstance(Context ctx) {
//
// context = ctx;
//
// if (instance == null) {
// instance = new AccessFactory();
// }
//
// return instance;
// }
//
// public void setIsLoggedIn(boolean logged) {
// isLoggedIn = logged;
// }
//
// }
//
// Path: app/src/main/java/com/samourai/sentinel/hd/HD_Address.java
// public class HD_Address {
//
// private int mChildNum;
// private String strPath = null;
// private ECKey ecKey = null;
//
// private NetworkParameters mParams = null;
//
// private HD_Address() { ; }
//
// public HD_Address(NetworkParameters params, DeterministicKey cKey, int child) {
//
// mParams = params;
// mChildNum = child;
//
// DeterministicKey dk = HDKeyDerivation.deriveChildKey(cKey, new ChildNumber(mChildNum, false));
// if(dk.hasPrivKey()) {
// ecKey = new ECKey(dk.getPrivKeyBytes(), dk.getPubKey());
// }
// else {
// ecKey = ECKey.fromPublicOnly(dk.getPubKey());
// }
//
// long now = Utils.now().getTime() / 1000;
// ecKey.setCreationTimeSeconds(now);
//
// strPath = dk.getPath().toString();
// }
//
// public String getAddressString() {
// return ecKey.toAddress(mParams).toString();
// }
//
// public Address getAddress() {
// return ecKey.toAddress(mParams);
// }
//
// public ECKey getECKey() {
// return ecKey;
// }
//
// public JSONObject toJSON() {
// try {
// JSONObject obj = new JSONObject();
//
// obj.put("path", strPath);
// obj.put("address", getAddressString());
//
// return obj;
// }
// catch(JSONException ex) {
// throw new RuntimeException(ex);
// }
// }
// }
//
// Path: app/src/main/java/com/samourai/sentinel/hd/HD_WalletFactory.java
// public class HD_WalletFactory {
//
// private static HD_WalletFactory instance = null;
// private static List<HD_Wallet> wallets = null;
//
// public static String strJSONFilePath = null;
//
// private static Context context = null;
//
// private HD_WalletFactory() { ; }
//
// public static HD_WalletFactory getInstance(Context ctx) {
//
// context = ctx;
//
// if (instance == null) {
// wallets = new ArrayList<HD_Wallet>();
// instance = new HD_WalletFactory();
// }
//
// return instance;
// }
//
// public static HD_WalletFactory getInstance(Context ctx, String path) {
//
// context = ctx;
// strJSONFilePath = path;
//
// if (instance == null) {
// wallets = new ArrayList<HD_Wallet>();
// instance = new HD_WalletFactory();
// }
//
// return instance;
// }
//
// public HD_Wallet restoreWallet(String data, String passphrase, int nbAccounts) throws AddressFormatException, DecoderException {
//
// HD_Wallet hdw = null;
//
// if(passphrase == null) {
// passphrase = "";
// }
//
// NetworkParameters params = SamouraiSentinel.getInstance().getCurrentNetworkParams();
//
// if(data.startsWith("xpub") || data.startsWith("ypub") || data.startsWith("zpub") || data.startsWith("tpub") || data.startsWith("upub") || data.startsWith("vpub")) {
// String[] xpub = data.split(":");
// // Log.i("HD_WalletFactory", "xpubs:" + xpub.length);
// hdw = new HD_Wallet(params, xpub);
// }
//
// if(hdw == null) {
// PrefsUtil.getInstance(context).clear();
// return null;
// }
//
// wallets.clear();
// wallets.add(hdw);
//
// return hdw;
// }
//
// public HD_Wallet get() throws IOException, MnemonicException.MnemonicLengthException {
//
// if(wallets.size() < 1) {
// // if wallets list is empty, create 12-word wallet without passphrase and 2 accounts
// // wallets.add(0, newWallet(12, "", 2));
// /*
// wallets.clear();
// wallets.add(newWallet(12, "", 2));
// */
// return null;
// }
//
// return wallets.get(0);
// }
//
// }
| import android.content.Context;
import android.widget.Toast;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.crypto.MnemonicException;
import com.samourai.sentinel.access.AccessFactory;
import com.samourai.sentinel.hd.HD_Address;
import com.samourai.sentinel.hd.HD_WalletFactory;
import org.json.JSONException;
import java.io.IOException;
import java.util.HashMap; |
if(instance == null) {
instance = new AddressFactory();
highestTxReceiveIdx = new HashMap<Integer,Integer>();
highestTxChangeIdx = new HashMap<Integer,Integer>();
xpub2account = new HashMap<String,Integer>();
account2xpub = new HashMap<Integer,String>();
}
return instance;
}
public static AddressFactory getInstance() {
if(instance == null) {
instance = new AddressFactory();
highestTxReceiveIdx = new HashMap<Integer,Integer>();
highestTxChangeIdx = new HashMap<Integer,Integer>();
xpub2account = new HashMap<String,Integer>();
account2xpub = new HashMap<Integer,String>();
}
return instance;
}
public String get(int chain, int accountIdx) {
int idx = 0; | // Path: app/src/main/java/com/samourai/sentinel/access/AccessFactory.java
// public class AccessFactory {
//
// public static final int MIN_PIN_LENGTH = 5;
// public static final int MAX_PIN_LENGTH = 8;
//
// private static boolean isLoggedIn = false;
//
// private static Context context = null;
// private static AccessFactory instance = null;
//
// private AccessFactory() { ; }
//
// public static AccessFactory getInstance(Context ctx) {
//
// context = ctx;
//
// if (instance == null) {
// instance = new AccessFactory();
// }
//
// return instance;
// }
//
// public void setIsLoggedIn(boolean logged) {
// isLoggedIn = logged;
// }
//
// }
//
// Path: app/src/main/java/com/samourai/sentinel/hd/HD_Address.java
// public class HD_Address {
//
// private int mChildNum;
// private String strPath = null;
// private ECKey ecKey = null;
//
// private NetworkParameters mParams = null;
//
// private HD_Address() { ; }
//
// public HD_Address(NetworkParameters params, DeterministicKey cKey, int child) {
//
// mParams = params;
// mChildNum = child;
//
// DeterministicKey dk = HDKeyDerivation.deriveChildKey(cKey, new ChildNumber(mChildNum, false));
// if(dk.hasPrivKey()) {
// ecKey = new ECKey(dk.getPrivKeyBytes(), dk.getPubKey());
// }
// else {
// ecKey = ECKey.fromPublicOnly(dk.getPubKey());
// }
//
// long now = Utils.now().getTime() / 1000;
// ecKey.setCreationTimeSeconds(now);
//
// strPath = dk.getPath().toString();
// }
//
// public String getAddressString() {
// return ecKey.toAddress(mParams).toString();
// }
//
// public Address getAddress() {
// return ecKey.toAddress(mParams);
// }
//
// public ECKey getECKey() {
// return ecKey;
// }
//
// public JSONObject toJSON() {
// try {
// JSONObject obj = new JSONObject();
//
// obj.put("path", strPath);
// obj.put("address", getAddressString());
//
// return obj;
// }
// catch(JSONException ex) {
// throw new RuntimeException(ex);
// }
// }
// }
//
// Path: app/src/main/java/com/samourai/sentinel/hd/HD_WalletFactory.java
// public class HD_WalletFactory {
//
// private static HD_WalletFactory instance = null;
// private static List<HD_Wallet> wallets = null;
//
// public static String strJSONFilePath = null;
//
// private static Context context = null;
//
// private HD_WalletFactory() { ; }
//
// public static HD_WalletFactory getInstance(Context ctx) {
//
// context = ctx;
//
// if (instance == null) {
// wallets = new ArrayList<HD_Wallet>();
// instance = new HD_WalletFactory();
// }
//
// return instance;
// }
//
// public static HD_WalletFactory getInstance(Context ctx, String path) {
//
// context = ctx;
// strJSONFilePath = path;
//
// if (instance == null) {
// wallets = new ArrayList<HD_Wallet>();
// instance = new HD_WalletFactory();
// }
//
// return instance;
// }
//
// public HD_Wallet restoreWallet(String data, String passphrase, int nbAccounts) throws AddressFormatException, DecoderException {
//
// HD_Wallet hdw = null;
//
// if(passphrase == null) {
// passphrase = "";
// }
//
// NetworkParameters params = SamouraiSentinel.getInstance().getCurrentNetworkParams();
//
// if(data.startsWith("xpub") || data.startsWith("ypub") || data.startsWith("zpub") || data.startsWith("tpub") || data.startsWith("upub") || data.startsWith("vpub")) {
// String[] xpub = data.split(":");
// // Log.i("HD_WalletFactory", "xpubs:" + xpub.length);
// hdw = new HD_Wallet(params, xpub);
// }
//
// if(hdw == null) {
// PrefsUtil.getInstance(context).clear();
// return null;
// }
//
// wallets.clear();
// wallets.add(hdw);
//
// return hdw;
// }
//
// public HD_Wallet get() throws IOException, MnemonicException.MnemonicLengthException {
//
// if(wallets.size() < 1) {
// // if wallets list is empty, create 12-word wallet without passphrase and 2 accounts
// // wallets.add(0, newWallet(12, "", 2));
// /*
// wallets.clear();
// wallets.add(newWallet(12, "", 2));
// */
// return null;
// }
//
// return wallets.get(0);
// }
//
// }
// Path: app/src/main/java/com/samourai/sentinel/util/AddressFactory.java
import android.content.Context;
import android.widget.Toast;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.crypto.MnemonicException;
import com.samourai.sentinel.access.AccessFactory;
import com.samourai.sentinel.hd.HD_Address;
import com.samourai.sentinel.hd.HD_WalletFactory;
import org.json.JSONException;
import java.io.IOException;
import java.util.HashMap;
if(instance == null) {
instance = new AddressFactory();
highestTxReceiveIdx = new HashMap<Integer,Integer>();
highestTxChangeIdx = new HashMap<Integer,Integer>();
xpub2account = new HashMap<String,Integer>();
account2xpub = new HashMap<Integer,String>();
}
return instance;
}
public static AddressFactory getInstance() {
if(instance == null) {
instance = new AddressFactory();
highestTxReceiveIdx = new HashMap<Integer,Integer>();
highestTxChangeIdx = new HashMap<Integer,Integer>();
xpub2account = new HashMap<String,Integer>();
account2xpub = new HashMap<Integer,String>();
}
return instance;
}
public String get(int chain, int accountIdx) {
int idx = 0; | HD_Address addr = null; |
Samourai-Wallet/sentinel-android | app/src/main/java/com/samourai/sentinel/util/AddressFactory.java | // Path: app/src/main/java/com/samourai/sentinel/access/AccessFactory.java
// public class AccessFactory {
//
// public static final int MIN_PIN_LENGTH = 5;
// public static final int MAX_PIN_LENGTH = 8;
//
// private static boolean isLoggedIn = false;
//
// private static Context context = null;
// private static AccessFactory instance = null;
//
// private AccessFactory() { ; }
//
// public static AccessFactory getInstance(Context ctx) {
//
// context = ctx;
//
// if (instance == null) {
// instance = new AccessFactory();
// }
//
// return instance;
// }
//
// public void setIsLoggedIn(boolean logged) {
// isLoggedIn = logged;
// }
//
// }
//
// Path: app/src/main/java/com/samourai/sentinel/hd/HD_Address.java
// public class HD_Address {
//
// private int mChildNum;
// private String strPath = null;
// private ECKey ecKey = null;
//
// private NetworkParameters mParams = null;
//
// private HD_Address() { ; }
//
// public HD_Address(NetworkParameters params, DeterministicKey cKey, int child) {
//
// mParams = params;
// mChildNum = child;
//
// DeterministicKey dk = HDKeyDerivation.deriveChildKey(cKey, new ChildNumber(mChildNum, false));
// if(dk.hasPrivKey()) {
// ecKey = new ECKey(dk.getPrivKeyBytes(), dk.getPubKey());
// }
// else {
// ecKey = ECKey.fromPublicOnly(dk.getPubKey());
// }
//
// long now = Utils.now().getTime() / 1000;
// ecKey.setCreationTimeSeconds(now);
//
// strPath = dk.getPath().toString();
// }
//
// public String getAddressString() {
// return ecKey.toAddress(mParams).toString();
// }
//
// public Address getAddress() {
// return ecKey.toAddress(mParams);
// }
//
// public ECKey getECKey() {
// return ecKey;
// }
//
// public JSONObject toJSON() {
// try {
// JSONObject obj = new JSONObject();
//
// obj.put("path", strPath);
// obj.put("address", getAddressString());
//
// return obj;
// }
// catch(JSONException ex) {
// throw new RuntimeException(ex);
// }
// }
// }
//
// Path: app/src/main/java/com/samourai/sentinel/hd/HD_WalletFactory.java
// public class HD_WalletFactory {
//
// private static HD_WalletFactory instance = null;
// private static List<HD_Wallet> wallets = null;
//
// public static String strJSONFilePath = null;
//
// private static Context context = null;
//
// private HD_WalletFactory() { ; }
//
// public static HD_WalletFactory getInstance(Context ctx) {
//
// context = ctx;
//
// if (instance == null) {
// wallets = new ArrayList<HD_Wallet>();
// instance = new HD_WalletFactory();
// }
//
// return instance;
// }
//
// public static HD_WalletFactory getInstance(Context ctx, String path) {
//
// context = ctx;
// strJSONFilePath = path;
//
// if (instance == null) {
// wallets = new ArrayList<HD_Wallet>();
// instance = new HD_WalletFactory();
// }
//
// return instance;
// }
//
// public HD_Wallet restoreWallet(String data, String passphrase, int nbAccounts) throws AddressFormatException, DecoderException {
//
// HD_Wallet hdw = null;
//
// if(passphrase == null) {
// passphrase = "";
// }
//
// NetworkParameters params = SamouraiSentinel.getInstance().getCurrentNetworkParams();
//
// if(data.startsWith("xpub") || data.startsWith("ypub") || data.startsWith("zpub") || data.startsWith("tpub") || data.startsWith("upub") || data.startsWith("vpub")) {
// String[] xpub = data.split(":");
// // Log.i("HD_WalletFactory", "xpubs:" + xpub.length);
// hdw = new HD_Wallet(params, xpub);
// }
//
// if(hdw == null) {
// PrefsUtil.getInstance(context).clear();
// return null;
// }
//
// wallets.clear();
// wallets.add(hdw);
//
// return hdw;
// }
//
// public HD_Wallet get() throws IOException, MnemonicException.MnemonicLengthException {
//
// if(wallets.size() < 1) {
// // if wallets list is empty, create 12-word wallet without passphrase and 2 accounts
// // wallets.add(0, newWallet(12, "", 2));
// /*
// wallets.clear();
// wallets.add(newWallet(12, "", 2));
// */
// return null;
// }
//
// return wallets.get(0);
// }
//
// }
| import android.content.Context;
import android.widget.Toast;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.crypto.MnemonicException;
import com.samourai.sentinel.access.AccessFactory;
import com.samourai.sentinel.hd.HD_Address;
import com.samourai.sentinel.hd.HD_WalletFactory;
import org.json.JSONException;
import java.io.IOException;
import java.util.HashMap; |
highestTxReceiveIdx = new HashMap<Integer,Integer>();
highestTxChangeIdx = new HashMap<Integer,Integer>();
xpub2account = new HashMap<String,Integer>();
account2xpub = new HashMap<Integer,String>();
}
return instance;
}
public static AddressFactory getInstance() {
if(instance == null) {
instance = new AddressFactory();
highestTxReceiveIdx = new HashMap<Integer,Integer>();
highestTxChangeIdx = new HashMap<Integer,Integer>();
xpub2account = new HashMap<String,Integer>();
account2xpub = new HashMap<Integer,String>();
}
return instance;
}
public String get(int chain, int accountIdx) {
int idx = 0;
HD_Address addr = null;
try { | // Path: app/src/main/java/com/samourai/sentinel/access/AccessFactory.java
// public class AccessFactory {
//
// public static final int MIN_PIN_LENGTH = 5;
// public static final int MAX_PIN_LENGTH = 8;
//
// private static boolean isLoggedIn = false;
//
// private static Context context = null;
// private static AccessFactory instance = null;
//
// private AccessFactory() { ; }
//
// public static AccessFactory getInstance(Context ctx) {
//
// context = ctx;
//
// if (instance == null) {
// instance = new AccessFactory();
// }
//
// return instance;
// }
//
// public void setIsLoggedIn(boolean logged) {
// isLoggedIn = logged;
// }
//
// }
//
// Path: app/src/main/java/com/samourai/sentinel/hd/HD_Address.java
// public class HD_Address {
//
// private int mChildNum;
// private String strPath = null;
// private ECKey ecKey = null;
//
// private NetworkParameters mParams = null;
//
// private HD_Address() { ; }
//
// public HD_Address(NetworkParameters params, DeterministicKey cKey, int child) {
//
// mParams = params;
// mChildNum = child;
//
// DeterministicKey dk = HDKeyDerivation.deriveChildKey(cKey, new ChildNumber(mChildNum, false));
// if(dk.hasPrivKey()) {
// ecKey = new ECKey(dk.getPrivKeyBytes(), dk.getPubKey());
// }
// else {
// ecKey = ECKey.fromPublicOnly(dk.getPubKey());
// }
//
// long now = Utils.now().getTime() / 1000;
// ecKey.setCreationTimeSeconds(now);
//
// strPath = dk.getPath().toString();
// }
//
// public String getAddressString() {
// return ecKey.toAddress(mParams).toString();
// }
//
// public Address getAddress() {
// return ecKey.toAddress(mParams);
// }
//
// public ECKey getECKey() {
// return ecKey;
// }
//
// public JSONObject toJSON() {
// try {
// JSONObject obj = new JSONObject();
//
// obj.put("path", strPath);
// obj.put("address", getAddressString());
//
// return obj;
// }
// catch(JSONException ex) {
// throw new RuntimeException(ex);
// }
// }
// }
//
// Path: app/src/main/java/com/samourai/sentinel/hd/HD_WalletFactory.java
// public class HD_WalletFactory {
//
// private static HD_WalletFactory instance = null;
// private static List<HD_Wallet> wallets = null;
//
// public static String strJSONFilePath = null;
//
// private static Context context = null;
//
// private HD_WalletFactory() { ; }
//
// public static HD_WalletFactory getInstance(Context ctx) {
//
// context = ctx;
//
// if (instance == null) {
// wallets = new ArrayList<HD_Wallet>();
// instance = new HD_WalletFactory();
// }
//
// return instance;
// }
//
// public static HD_WalletFactory getInstance(Context ctx, String path) {
//
// context = ctx;
// strJSONFilePath = path;
//
// if (instance == null) {
// wallets = new ArrayList<HD_Wallet>();
// instance = new HD_WalletFactory();
// }
//
// return instance;
// }
//
// public HD_Wallet restoreWallet(String data, String passphrase, int nbAccounts) throws AddressFormatException, DecoderException {
//
// HD_Wallet hdw = null;
//
// if(passphrase == null) {
// passphrase = "";
// }
//
// NetworkParameters params = SamouraiSentinel.getInstance().getCurrentNetworkParams();
//
// if(data.startsWith("xpub") || data.startsWith("ypub") || data.startsWith("zpub") || data.startsWith("tpub") || data.startsWith("upub") || data.startsWith("vpub")) {
// String[] xpub = data.split(":");
// // Log.i("HD_WalletFactory", "xpubs:" + xpub.length);
// hdw = new HD_Wallet(params, xpub);
// }
//
// if(hdw == null) {
// PrefsUtil.getInstance(context).clear();
// return null;
// }
//
// wallets.clear();
// wallets.add(hdw);
//
// return hdw;
// }
//
// public HD_Wallet get() throws IOException, MnemonicException.MnemonicLengthException {
//
// if(wallets.size() < 1) {
// // if wallets list is empty, create 12-word wallet without passphrase and 2 accounts
// // wallets.add(0, newWallet(12, "", 2));
// /*
// wallets.clear();
// wallets.add(newWallet(12, "", 2));
// */
// return null;
// }
//
// return wallets.get(0);
// }
//
// }
// Path: app/src/main/java/com/samourai/sentinel/util/AddressFactory.java
import android.content.Context;
import android.widget.Toast;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.crypto.MnemonicException;
import com.samourai.sentinel.access.AccessFactory;
import com.samourai.sentinel.hd.HD_Address;
import com.samourai.sentinel.hd.HD_WalletFactory;
import org.json.JSONException;
import java.io.IOException;
import java.util.HashMap;
highestTxReceiveIdx = new HashMap<Integer,Integer>();
highestTxChangeIdx = new HashMap<Integer,Integer>();
xpub2account = new HashMap<String,Integer>();
account2xpub = new HashMap<Integer,String>();
}
return instance;
}
public static AddressFactory getInstance() {
if(instance == null) {
instance = new AddressFactory();
highestTxReceiveIdx = new HashMap<Integer,Integer>();
highestTxChangeIdx = new HashMap<Integer,Integer>();
xpub2account = new HashMap<String,Integer>();
account2xpub = new HashMap<Integer,String>();
}
return instance;
}
public String get(int chain, int accountIdx) {
int idx = 0;
HD_Address addr = null;
try { | idx = HD_WalletFactory.getInstance(context).get().getAccount(accountIdx).getChain(chain).getAddrIdx(); |
PioBeat/GravSupport | src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/files/ThemeBlueprintsFileType.java | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/icons/GravIcons.java
// public class GravIcons {
//
// private static @NotNull Icon load(@NotNull String path) {
// return IconLoader.getIcon(path, GravIcons.class);
// // return IconManager.getInstance().getIcon(path, GravIcons.class);
// }
//
// public static final Icon GravDefaultIcon = load("/icons/gravLogo.svg");
// public static final Icon ThemeBlueprints = load("/icons/gravFileIcon.svg");
// public static final Icon ThemeConfiguration = load("/icons/gravFileIcon.svg");
// public static final Icon GravFileLogoIcon = load("/icons/gravToolWindowIcon.svg");
// public static final Icon GravToolWindowIcon = load("/icons/gravToolWindowIcon.svg");
// public static final Icon GravProjectWizardIcon = load("/icons/gravToolWindowIcon.svg");
// }
| import com.intellij.openapi.fileTypes.LanguageFileType;
import net.offbeatpioneer.intellij.plugins.grav.extensions.icons.GravIcons;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*; | package net.offbeatpioneer.intellij.plugins.grav.extensions.files;
/**
* Concrete implementation of Grav's theme blueprint configuration file.
*
* @author Dominik Grzelak
* @since 16.07.2017.
*/
public class ThemeBlueprintsFileType extends AbstractGravFileType {
public static final LanguageFileType INSTANCE = new ThemeBlueprintsFileType();
public ThemeBlueprintsFileType() {
super();
}
@NotNull
@Override
public String getName() {
return "Theme blueprints";
}
@NotNull
@Override
public String getDescription() {
return "Theme Blueprints File";
}
@Nullable
@Override
public Icon getIcon() { | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/icons/GravIcons.java
// public class GravIcons {
//
// private static @NotNull Icon load(@NotNull String path) {
// return IconLoader.getIcon(path, GravIcons.class);
// // return IconManager.getInstance().getIcon(path, GravIcons.class);
// }
//
// public static final Icon GravDefaultIcon = load("/icons/gravLogo.svg");
// public static final Icon ThemeBlueprints = load("/icons/gravFileIcon.svg");
// public static final Icon ThemeConfiguration = load("/icons/gravFileIcon.svg");
// public static final Icon GravFileLogoIcon = load("/icons/gravToolWindowIcon.svg");
// public static final Icon GravToolWindowIcon = load("/icons/gravToolWindowIcon.svg");
// public static final Icon GravProjectWizardIcon = load("/icons/gravToolWindowIcon.svg");
// }
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/files/ThemeBlueprintsFileType.java
import com.intellij.openapi.fileTypes.LanguageFileType;
import net.offbeatpioneer.intellij.plugins.grav.extensions.icons.GravIcons;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
package net.offbeatpioneer.intellij.plugins.grav.extensions.files;
/**
* Concrete implementation of Grav's theme blueprint configuration file.
*
* @author Dominik Grzelak
* @since 16.07.2017.
*/
public class ThemeBlueprintsFileType extends AbstractGravFileType {
public static final LanguageFileType INSTANCE = new ThemeBlueprintsFileType();
public ThemeBlueprintsFileType() {
super();
}
@NotNull
@Override
public String getName() {
return "Theme blueprints";
}
@NotNull
@Override
public String getDescription() {
return "Theme Blueprints File";
}
@Nullable
@Override
public Icon getIcon() { | return GravIcons.ThemeBlueprints; |
PioBeat/GravSupport | src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/files/ThemeConfigurationFileType.java | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/icons/GravIcons.java
// public class GravIcons {
//
// private static @NotNull Icon load(@NotNull String path) {
// return IconLoader.getIcon(path, GravIcons.class);
// // return IconManager.getInstance().getIcon(path, GravIcons.class);
// }
//
// public static final Icon GravDefaultIcon = load("/icons/gravLogo.svg");
// public static final Icon ThemeBlueprints = load("/icons/gravFileIcon.svg");
// public static final Icon ThemeConfiguration = load("/icons/gravFileIcon.svg");
// public static final Icon GravFileLogoIcon = load("/icons/gravToolWindowIcon.svg");
// public static final Icon GravToolWindowIcon = load("/icons/gravToolWindowIcon.svg");
// public static final Icon GravProjectWizardIcon = load("/icons/gravToolWindowIcon.svg");
// }
| import com.intellij.openapi.fileTypes.LanguageFileType;
import net.offbeatpioneer.intellij.plugins.grav.extensions.icons.GravIcons;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*; | package net.offbeatpioneer.intellij.plugins.grav.extensions.files;
/**
* Concrete implementation of Grav's theme configuration file.
*
* @author Dominik Grzelak
* @since 16.07.2017.
*/
public class ThemeConfigurationFileType extends AbstractGravFileType {
public static final LanguageFileType INSTANCE = new ThemeConfigurationFileType();
private String defaultFileName;
public ThemeConfigurationFileType() {
super();
}
@NotNull
@Override
public String getName() {
return "Theme configuration";
}
@NotNull
@Override
public String getDescription() {
return "Theme Configuration File";
}
@Nullable
@Override
public Icon getIcon() { | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/icons/GravIcons.java
// public class GravIcons {
//
// private static @NotNull Icon load(@NotNull String path) {
// return IconLoader.getIcon(path, GravIcons.class);
// // return IconManager.getInstance().getIcon(path, GravIcons.class);
// }
//
// public static final Icon GravDefaultIcon = load("/icons/gravLogo.svg");
// public static final Icon ThemeBlueprints = load("/icons/gravFileIcon.svg");
// public static final Icon ThemeConfiguration = load("/icons/gravFileIcon.svg");
// public static final Icon GravFileLogoIcon = load("/icons/gravToolWindowIcon.svg");
// public static final Icon GravToolWindowIcon = load("/icons/gravToolWindowIcon.svg");
// public static final Icon GravProjectWizardIcon = load("/icons/gravToolWindowIcon.svg");
// }
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/files/ThemeConfigurationFileType.java
import com.intellij.openapi.fileTypes.LanguageFileType;
import net.offbeatpioneer.intellij.plugins.grav.extensions.icons.GravIcons;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
package net.offbeatpioneer.intellij.plugins.grav.extensions.files;
/**
* Concrete implementation of Grav's theme configuration file.
*
* @author Dominik Grzelak
* @since 16.07.2017.
*/
public class ThemeConfigurationFileType extends AbstractGravFileType {
public static final LanguageFileType INSTANCE = new ThemeConfigurationFileType();
private String defaultFileName;
public ThemeConfigurationFileType() {
super();
}
@NotNull
@Override
public String getName() {
return "Theme configuration";
}
@NotNull
@Override
public String getDescription() {
return "Theme Configuration File";
}
@Nullable
@Override
public Icon getIcon() { | return GravIcons.ThemeConfiguration; |
PioBeat/GravSupport | src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/module/GravModuleBuilder.java | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/module/wizard/CreateGravProjectWizardStep.java
// public class CreateGravProjectWizardStep extends ModuleWizardStep { //implements Disposable {
// public static final String LAST_USED_GRAV_HOME = "LAST_USED_GRAV_HOME";
// private GravModuleBuilder builder;
// private GravCreateProjectForm form = new GravCreateProjectForm();
// private GravPersistentStateComponent storage;
// private final Project project;
//
// public CreateGravProjectWizardStep(GravModuleBuilder builder, @Nullable Project project) {
// this.builder = builder;
// this.storage = GravPersistentStateComponent.getInstance();
// this.project = project;
//
// String path = storage.getDefaultGravDownloadPath();
// if ((path == null || path.isEmpty())) {
// path = System.getProperty("user.home");
// } else if (PropertiesComponent.getInstance().getValue(LAST_USED_GRAV_HOME) != null) {
// path = PropertiesComponent.getInstance().getValue(LAST_USED_GRAV_HOME);
// }
// form.setDefaultInstallationPath(path);
// form.initLayout();
// }
//
// @Override
// public JComponent getComponent() {
// return form.getContentPane();
// }
//
// @Override
// public boolean validate() throws ConfigurationException {
// String finalGravInstallDir = form.getGravFinalInstallationDirectory().trim();
// if (finalGravInstallDir.isEmpty()) {
// form.showHint(true);
// throw new ConfigurationException("The path pointing to Grav is empty for the selected option");
// } else {
// VirtualFile vf = LocalFileSystem.getInstance().findFileByIoFile(new File(finalGravInstallDir));
// if (vf == null) {
// form.showHint(true);
// throw new ConfigurationException("The path pointing to Grav doesn't exist for the selected option");
// } else {
// if (!GravSdkType.isValidGravSDK(vf)) {
// form.showHint(true);
// throw new ConfigurationException("The selected Grav 'SDK' seems not valid for the selected option");
// }
// }
// String gravSdkVersion = GravSdkType.findGravSdkVersion(finalGravInstallDir);
// form.setDeterminedGravVersion(gravSdkVersion);
// }
// form.showHint(false);
// return true;
// }
//
// /**
// * Is called after {@link CreateGravProjectWizardStep#validate()}.
// */
// @Override
// public void updateDataModel() {
// String file = form.getGravFinalInstallationDirectory();
// builder.setGravInstallPath(LocalFileSystem.getInstance().findFileByIoFile(new File(file)));
// PropertiesComponent.getInstance().setValue(LAST_USED_GRAV_HOME, new File(file).getAbsolutePath());
// }
//
// @Override
// public void updateStep() {
// super.updateStep();
// }
//
// // @Override
// // public void dispose() {
// // if (Objects.nonNull(form) && Objects.nonNull(form.getMainPanel())) {
// // DialogWrapper.cleanupRootPane(form.getMainPanel().getRootPane());
// // }
// // }
// }
//
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/storage/GravProjectSettings.java
// @State(
// name = "GravProjectSettings",
// storages = {
// @Storage("grav-plugin.xml")
// }
// )
// public class GravProjectSettings implements PersistentStateComponent<GravProjectSettings> {
// public String gravInstallationPath = "";
// public boolean pluginEnabled = false;
// public boolean dismissEnableNotification = false;
//
// public GravProjectSettings() {
// }
//
// @Nullable
// public static GravProjectSettings getInstance(@NotNull Project project) {
// return ServiceManager.getService(project, GravProjectSettings.class);
// }
//
// @Nullable
// @Override
// public GravProjectSettings getState() {
// return this;
// }
//
// @Override
// public void loadState(GravProjectSettings state) {
// XmlSerializerUtil.copyBean(state, this);
// }
// }
| import com.intellij.ide.util.projectWizard.ModuleBuilder;
import com.intellij.ide.util.projectWizard.ModuleBuilderListener;
import com.intellij.ide.util.projectWizard.ModuleWizardStep;
import com.intellij.ide.util.projectWizard.WizardContext;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleType;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ContentEntry;
import com.intellij.openapi.roots.ModifiableRootModel;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.StatusBar;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.ui.awt.RelativePoint;
import net.offbeatpioneer.intellij.plugins.grav.extensions.module.wizard.CreateGravProjectWizardStep;
import net.offbeatpioneer.intellij.plugins.grav.storage.GravProjectSettings;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.nio.file.Paths;
import java.util.Objects; | package net.offbeatpioneer.intellij.plugins.grav.extensions.module;
public class GravModuleBuilder extends ModuleBuilder implements ModuleBuilderListener {
private VirtualFile gravInstallPath; | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/module/wizard/CreateGravProjectWizardStep.java
// public class CreateGravProjectWizardStep extends ModuleWizardStep { //implements Disposable {
// public static final String LAST_USED_GRAV_HOME = "LAST_USED_GRAV_HOME";
// private GravModuleBuilder builder;
// private GravCreateProjectForm form = new GravCreateProjectForm();
// private GravPersistentStateComponent storage;
// private final Project project;
//
// public CreateGravProjectWizardStep(GravModuleBuilder builder, @Nullable Project project) {
// this.builder = builder;
// this.storage = GravPersistentStateComponent.getInstance();
// this.project = project;
//
// String path = storage.getDefaultGravDownloadPath();
// if ((path == null || path.isEmpty())) {
// path = System.getProperty("user.home");
// } else if (PropertiesComponent.getInstance().getValue(LAST_USED_GRAV_HOME) != null) {
// path = PropertiesComponent.getInstance().getValue(LAST_USED_GRAV_HOME);
// }
// form.setDefaultInstallationPath(path);
// form.initLayout();
// }
//
// @Override
// public JComponent getComponent() {
// return form.getContentPane();
// }
//
// @Override
// public boolean validate() throws ConfigurationException {
// String finalGravInstallDir = form.getGravFinalInstallationDirectory().trim();
// if (finalGravInstallDir.isEmpty()) {
// form.showHint(true);
// throw new ConfigurationException("The path pointing to Grav is empty for the selected option");
// } else {
// VirtualFile vf = LocalFileSystem.getInstance().findFileByIoFile(new File(finalGravInstallDir));
// if (vf == null) {
// form.showHint(true);
// throw new ConfigurationException("The path pointing to Grav doesn't exist for the selected option");
// } else {
// if (!GravSdkType.isValidGravSDK(vf)) {
// form.showHint(true);
// throw new ConfigurationException("The selected Grav 'SDK' seems not valid for the selected option");
// }
// }
// String gravSdkVersion = GravSdkType.findGravSdkVersion(finalGravInstallDir);
// form.setDeterminedGravVersion(gravSdkVersion);
// }
// form.showHint(false);
// return true;
// }
//
// /**
// * Is called after {@link CreateGravProjectWizardStep#validate()}.
// */
// @Override
// public void updateDataModel() {
// String file = form.getGravFinalInstallationDirectory();
// builder.setGravInstallPath(LocalFileSystem.getInstance().findFileByIoFile(new File(file)));
// PropertiesComponent.getInstance().setValue(LAST_USED_GRAV_HOME, new File(file).getAbsolutePath());
// }
//
// @Override
// public void updateStep() {
// super.updateStep();
// }
//
// // @Override
// // public void dispose() {
// // if (Objects.nonNull(form) && Objects.nonNull(form.getMainPanel())) {
// // DialogWrapper.cleanupRootPane(form.getMainPanel().getRootPane());
// // }
// // }
// }
//
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/storage/GravProjectSettings.java
// @State(
// name = "GravProjectSettings",
// storages = {
// @Storage("grav-plugin.xml")
// }
// )
// public class GravProjectSettings implements PersistentStateComponent<GravProjectSettings> {
// public String gravInstallationPath = "";
// public boolean pluginEnabled = false;
// public boolean dismissEnableNotification = false;
//
// public GravProjectSettings() {
// }
//
// @Nullable
// public static GravProjectSettings getInstance(@NotNull Project project) {
// return ServiceManager.getService(project, GravProjectSettings.class);
// }
//
// @Nullable
// @Override
// public GravProjectSettings getState() {
// return this;
// }
//
// @Override
// public void loadState(GravProjectSettings state) {
// XmlSerializerUtil.copyBean(state, this);
// }
// }
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/module/GravModuleBuilder.java
import com.intellij.ide.util.projectWizard.ModuleBuilder;
import com.intellij.ide.util.projectWizard.ModuleBuilderListener;
import com.intellij.ide.util.projectWizard.ModuleWizardStep;
import com.intellij.ide.util.projectWizard.WizardContext;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleType;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ContentEntry;
import com.intellij.openapi.roots.ModifiableRootModel;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.StatusBar;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.ui.awt.RelativePoint;
import net.offbeatpioneer.intellij.plugins.grav.extensions.module.wizard.CreateGravProjectWizardStep;
import net.offbeatpioneer.intellij.plugins.grav.storage.GravProjectSettings;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.nio.file.Paths;
import java.util.Objects;
package net.offbeatpioneer.intellij.plugins.grav.extensions.module;
public class GravModuleBuilder extends ModuleBuilder implements ModuleBuilderListener {
private VirtualFile gravInstallPath; | private GravProjectSettings settings; |
PioBeat/GravSupport | src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/module/GravModuleBuilder.java | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/module/wizard/CreateGravProjectWizardStep.java
// public class CreateGravProjectWizardStep extends ModuleWizardStep { //implements Disposable {
// public static final String LAST_USED_GRAV_HOME = "LAST_USED_GRAV_HOME";
// private GravModuleBuilder builder;
// private GravCreateProjectForm form = new GravCreateProjectForm();
// private GravPersistentStateComponent storage;
// private final Project project;
//
// public CreateGravProjectWizardStep(GravModuleBuilder builder, @Nullable Project project) {
// this.builder = builder;
// this.storage = GravPersistentStateComponent.getInstance();
// this.project = project;
//
// String path = storage.getDefaultGravDownloadPath();
// if ((path == null || path.isEmpty())) {
// path = System.getProperty("user.home");
// } else if (PropertiesComponent.getInstance().getValue(LAST_USED_GRAV_HOME) != null) {
// path = PropertiesComponent.getInstance().getValue(LAST_USED_GRAV_HOME);
// }
// form.setDefaultInstallationPath(path);
// form.initLayout();
// }
//
// @Override
// public JComponent getComponent() {
// return form.getContentPane();
// }
//
// @Override
// public boolean validate() throws ConfigurationException {
// String finalGravInstallDir = form.getGravFinalInstallationDirectory().trim();
// if (finalGravInstallDir.isEmpty()) {
// form.showHint(true);
// throw new ConfigurationException("The path pointing to Grav is empty for the selected option");
// } else {
// VirtualFile vf = LocalFileSystem.getInstance().findFileByIoFile(new File(finalGravInstallDir));
// if (vf == null) {
// form.showHint(true);
// throw new ConfigurationException("The path pointing to Grav doesn't exist for the selected option");
// } else {
// if (!GravSdkType.isValidGravSDK(vf)) {
// form.showHint(true);
// throw new ConfigurationException("The selected Grav 'SDK' seems not valid for the selected option");
// }
// }
// String gravSdkVersion = GravSdkType.findGravSdkVersion(finalGravInstallDir);
// form.setDeterminedGravVersion(gravSdkVersion);
// }
// form.showHint(false);
// return true;
// }
//
// /**
// * Is called after {@link CreateGravProjectWizardStep#validate()}.
// */
// @Override
// public void updateDataModel() {
// String file = form.getGravFinalInstallationDirectory();
// builder.setGravInstallPath(LocalFileSystem.getInstance().findFileByIoFile(new File(file)));
// PropertiesComponent.getInstance().setValue(LAST_USED_GRAV_HOME, new File(file).getAbsolutePath());
// }
//
// @Override
// public void updateStep() {
// super.updateStep();
// }
//
// // @Override
// // public void dispose() {
// // if (Objects.nonNull(form) && Objects.nonNull(form.getMainPanel())) {
// // DialogWrapper.cleanupRootPane(form.getMainPanel().getRootPane());
// // }
// // }
// }
//
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/storage/GravProjectSettings.java
// @State(
// name = "GravProjectSettings",
// storages = {
// @Storage("grav-plugin.xml")
// }
// )
// public class GravProjectSettings implements PersistentStateComponent<GravProjectSettings> {
// public String gravInstallationPath = "";
// public boolean pluginEnabled = false;
// public boolean dismissEnableNotification = false;
//
// public GravProjectSettings() {
// }
//
// @Nullable
// public static GravProjectSettings getInstance(@NotNull Project project) {
// return ServiceManager.getService(project, GravProjectSettings.class);
// }
//
// @Nullable
// @Override
// public GravProjectSettings getState() {
// return this;
// }
//
// @Override
// public void loadState(GravProjectSettings state) {
// XmlSerializerUtil.copyBean(state, this);
// }
// }
| import com.intellij.ide.util.projectWizard.ModuleBuilder;
import com.intellij.ide.util.projectWizard.ModuleBuilderListener;
import com.intellij.ide.util.projectWizard.ModuleWizardStep;
import com.intellij.ide.util.projectWizard.WizardContext;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleType;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ContentEntry;
import com.intellij.openapi.roots.ModifiableRootModel;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.StatusBar;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.ui.awt.RelativePoint;
import net.offbeatpioneer.intellij.plugins.grav.extensions.module.wizard.CreateGravProjectWizardStep;
import net.offbeatpioneer.intellij.plugins.grav.storage.GravProjectSettings;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.nio.file.Paths;
import java.util.Objects; | @Override
public String getPresentableName() {
return "Grav";
}
@Override
public void setupRootModel(ModifiableRootModel rootModel) throws ConfigurationException {
super.setupRootModel(rootModel);
ContentEntry contentEntry = doAddContentEntry(rootModel);
}
@Override
public String getGroupName() {
return "PHP"; //super.getGroupName();
}
@Override
public String getDescription() {
return "Create a new Grav project. A PHP interpreter is required.";
}
@Override
public ModuleType<GravModuleBuilder> getModuleType() {
return GravModuleType.getInstance();
}
@Override
@Nullable
public ModuleWizardStep getCustomOptionsStep(WizardContext wizardContext, Disposable parentDisposable) { | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/module/wizard/CreateGravProjectWizardStep.java
// public class CreateGravProjectWizardStep extends ModuleWizardStep { //implements Disposable {
// public static final String LAST_USED_GRAV_HOME = "LAST_USED_GRAV_HOME";
// private GravModuleBuilder builder;
// private GravCreateProjectForm form = new GravCreateProjectForm();
// private GravPersistentStateComponent storage;
// private final Project project;
//
// public CreateGravProjectWizardStep(GravModuleBuilder builder, @Nullable Project project) {
// this.builder = builder;
// this.storage = GravPersistentStateComponent.getInstance();
// this.project = project;
//
// String path = storage.getDefaultGravDownloadPath();
// if ((path == null || path.isEmpty())) {
// path = System.getProperty("user.home");
// } else if (PropertiesComponent.getInstance().getValue(LAST_USED_GRAV_HOME) != null) {
// path = PropertiesComponent.getInstance().getValue(LAST_USED_GRAV_HOME);
// }
// form.setDefaultInstallationPath(path);
// form.initLayout();
// }
//
// @Override
// public JComponent getComponent() {
// return form.getContentPane();
// }
//
// @Override
// public boolean validate() throws ConfigurationException {
// String finalGravInstallDir = form.getGravFinalInstallationDirectory().trim();
// if (finalGravInstallDir.isEmpty()) {
// form.showHint(true);
// throw new ConfigurationException("The path pointing to Grav is empty for the selected option");
// } else {
// VirtualFile vf = LocalFileSystem.getInstance().findFileByIoFile(new File(finalGravInstallDir));
// if (vf == null) {
// form.showHint(true);
// throw new ConfigurationException("The path pointing to Grav doesn't exist for the selected option");
// } else {
// if (!GravSdkType.isValidGravSDK(vf)) {
// form.showHint(true);
// throw new ConfigurationException("The selected Grav 'SDK' seems not valid for the selected option");
// }
// }
// String gravSdkVersion = GravSdkType.findGravSdkVersion(finalGravInstallDir);
// form.setDeterminedGravVersion(gravSdkVersion);
// }
// form.showHint(false);
// return true;
// }
//
// /**
// * Is called after {@link CreateGravProjectWizardStep#validate()}.
// */
// @Override
// public void updateDataModel() {
// String file = form.getGravFinalInstallationDirectory();
// builder.setGravInstallPath(LocalFileSystem.getInstance().findFileByIoFile(new File(file)));
// PropertiesComponent.getInstance().setValue(LAST_USED_GRAV_HOME, new File(file).getAbsolutePath());
// }
//
// @Override
// public void updateStep() {
// super.updateStep();
// }
//
// // @Override
// // public void dispose() {
// // if (Objects.nonNull(form) && Objects.nonNull(form.getMainPanel())) {
// // DialogWrapper.cleanupRootPane(form.getMainPanel().getRootPane());
// // }
// // }
// }
//
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/storage/GravProjectSettings.java
// @State(
// name = "GravProjectSettings",
// storages = {
// @Storage("grav-plugin.xml")
// }
// )
// public class GravProjectSettings implements PersistentStateComponent<GravProjectSettings> {
// public String gravInstallationPath = "";
// public boolean pluginEnabled = false;
// public boolean dismissEnableNotification = false;
//
// public GravProjectSettings() {
// }
//
// @Nullable
// public static GravProjectSettings getInstance(@NotNull Project project) {
// return ServiceManager.getService(project, GravProjectSettings.class);
// }
//
// @Nullable
// @Override
// public GravProjectSettings getState() {
// return this;
// }
//
// @Override
// public void loadState(GravProjectSettings state) {
// XmlSerializerUtil.copyBean(state, this);
// }
// }
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/module/GravModuleBuilder.java
import com.intellij.ide.util.projectWizard.ModuleBuilder;
import com.intellij.ide.util.projectWizard.ModuleBuilderListener;
import com.intellij.ide.util.projectWizard.ModuleWizardStep;
import com.intellij.ide.util.projectWizard.WizardContext;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleType;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ContentEntry;
import com.intellij.openapi.roots.ModifiableRootModel;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.StatusBar;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.ui.awt.RelativePoint;
import net.offbeatpioneer.intellij.plugins.grav.extensions.module.wizard.CreateGravProjectWizardStep;
import net.offbeatpioneer.intellij.plugins.grav.storage.GravProjectSettings;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.nio.file.Paths;
import java.util.Objects;
@Override
public String getPresentableName() {
return "Grav";
}
@Override
public void setupRootModel(ModifiableRootModel rootModel) throws ConfigurationException {
super.setupRootModel(rootModel);
ContentEntry contentEntry = doAddContentEntry(rootModel);
}
@Override
public String getGroupName() {
return "PHP"; //super.getGroupName();
}
@Override
public String getDescription() {
return "Create a new Grav project. A PHP interpreter is required.";
}
@Override
public ModuleType<GravModuleBuilder> getModuleType() {
return GravModuleType.getInstance();
}
@Override
@Nullable
public ModuleWizardStep getCustomOptionsStep(WizardContext wizardContext, Disposable parentDisposable) { | CreateGravProjectWizardStep step = new CreateGravProjectWizardStep(this, wizardContext.getProject()); |
PioBeat/GravSupport | src/main/java/net/offbeatpioneer/intellij/plugins/grav/action/CustomCreateFileFromTemplateDialog.java | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/files/AbstractGravFileType.java
// public abstract class AbstractGravFileType extends LanguageFileType {
//
// public static final String DEFAULT_EXTENSION = "yaml";
//
// protected AbstractGravFileType() {
// super(YAMLLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public String getDefaultExtension() {
// return DEFAULT_EXTENSION;
// }
//
// public abstract boolean needsFilename();
//
// public abstract String getCorrespondingTemplateFile();
//
// public String getDefaultFilename() {
// return "untitled";
// }
// }
//
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/files/GravFileTypes.java
// public class GravFileTypes {
//
// public static AbstractGravFileType[] CONFIGURATION_FILE_TYPES = new AbstractGravFileType[]{
// new ThemeBlueprintsFileType(),
// new ThemeConfigurationFileType()
// };
//
// public static void setModuleName(String moduleName) {
// ((ThemeConfigurationFileType) CONFIGURATION_FILE_TYPES[1]).setDefaultFileName(moduleName);
// }
// }
| import com.intellij.ide.actions.ElementCreator;
import com.intellij.ide.actions.TemplateKindCombo;
import com.intellij.lang.LangBundle;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.InputValidator;
import com.intellij.openapi.ui.InputValidatorEx;
import com.intellij.openapi.ui.ValidationInfo;
import com.intellij.openapi.util.Ref;
import com.intellij.psi.PsiElement;
import com.intellij.util.PlatformIcons;
import com.intellij.util.ui.JBUI;
import net.offbeatpioneer.intellij.plugins.grav.extensions.files.AbstractGravFileType;
import net.offbeatpioneer.intellij.plugins.grav.extensions.files.GravFileTypes;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Map; | c.gridx = 1;
c.gridy = 0;
myPanel.add(myNameField, c);
c.weightx = 0.3;
c.gridx = 2;
c.gridy = 0;
c.insets = JBUI.insetsLeft(12);
myPanel.add(myUpDownHint, c);
c.insets = JBUI.insets(10, 0);
c.gridx = 0;
c.gridy = 1;
myPanel.add(myKindLabel, c);
c.gridx = 1;
c.gridwidth = 2;
c.gridy = 1;
c.insets = JBUI.insets(10, 0, 10, 12);
myPanel.add(myKindCombo, c);
myKindLabel.setLabelFor(myKindCombo);
myKindCombo.registerUpDownHint(myNameField);
myUpDownHint.setIcon(PlatformIcons.UP_DOWN_ARROWS);
setTemplateKindComponentsVisible(false);
init();
myKindCombo.getComboBox().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) { | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/files/AbstractGravFileType.java
// public abstract class AbstractGravFileType extends LanguageFileType {
//
// public static final String DEFAULT_EXTENSION = "yaml";
//
// protected AbstractGravFileType() {
// super(YAMLLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public String getDefaultExtension() {
// return DEFAULT_EXTENSION;
// }
//
// public abstract boolean needsFilename();
//
// public abstract String getCorrespondingTemplateFile();
//
// public String getDefaultFilename() {
// return "untitled";
// }
// }
//
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/files/GravFileTypes.java
// public class GravFileTypes {
//
// public static AbstractGravFileType[] CONFIGURATION_FILE_TYPES = new AbstractGravFileType[]{
// new ThemeBlueprintsFileType(),
// new ThemeConfigurationFileType()
// };
//
// public static void setModuleName(String moduleName) {
// ((ThemeConfigurationFileType) CONFIGURATION_FILE_TYPES[1]).setDefaultFileName(moduleName);
// }
// }
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/action/CustomCreateFileFromTemplateDialog.java
import com.intellij.ide.actions.ElementCreator;
import com.intellij.ide.actions.TemplateKindCombo;
import com.intellij.lang.LangBundle;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.InputValidator;
import com.intellij.openapi.ui.InputValidatorEx;
import com.intellij.openapi.ui.ValidationInfo;
import com.intellij.openapi.util.Ref;
import com.intellij.psi.PsiElement;
import com.intellij.util.PlatformIcons;
import com.intellij.util.ui.JBUI;
import net.offbeatpioneer.intellij.plugins.grav.extensions.files.AbstractGravFileType;
import net.offbeatpioneer.intellij.plugins.grav.extensions.files.GravFileTypes;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Map;
c.gridx = 1;
c.gridy = 0;
myPanel.add(myNameField, c);
c.weightx = 0.3;
c.gridx = 2;
c.gridy = 0;
c.insets = JBUI.insetsLeft(12);
myPanel.add(myUpDownHint, c);
c.insets = JBUI.insets(10, 0);
c.gridx = 0;
c.gridy = 1;
myPanel.add(myKindLabel, c);
c.gridx = 1;
c.gridwidth = 2;
c.gridy = 1;
c.insets = JBUI.insets(10, 0, 10, 12);
myPanel.add(myKindCombo, c);
myKindLabel.setLabelFor(myKindCombo);
myKindCombo.registerUpDownHint(myNameField);
myUpDownHint.setIcon(PlatformIcons.UP_DOWN_ARROWS);
setTemplateKindComponentsVisible(false);
init();
myKindCombo.getComboBox().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) { | for (AbstractGravFileType each : GravFileTypes.CONFIGURATION_FILE_TYPES) { |
PioBeat/GravSupport | src/main/java/net/offbeatpioneer/intellij/plugins/grav/action/CustomCreateFileFromTemplateDialog.java | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/files/AbstractGravFileType.java
// public abstract class AbstractGravFileType extends LanguageFileType {
//
// public static final String DEFAULT_EXTENSION = "yaml";
//
// protected AbstractGravFileType() {
// super(YAMLLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public String getDefaultExtension() {
// return DEFAULT_EXTENSION;
// }
//
// public abstract boolean needsFilename();
//
// public abstract String getCorrespondingTemplateFile();
//
// public String getDefaultFilename() {
// return "untitled";
// }
// }
//
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/files/GravFileTypes.java
// public class GravFileTypes {
//
// public static AbstractGravFileType[] CONFIGURATION_FILE_TYPES = new AbstractGravFileType[]{
// new ThemeBlueprintsFileType(),
// new ThemeConfigurationFileType()
// };
//
// public static void setModuleName(String moduleName) {
// ((ThemeConfigurationFileType) CONFIGURATION_FILE_TYPES[1]).setDefaultFileName(moduleName);
// }
// }
| import com.intellij.ide.actions.ElementCreator;
import com.intellij.ide.actions.TemplateKindCombo;
import com.intellij.lang.LangBundle;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.InputValidator;
import com.intellij.openapi.ui.InputValidatorEx;
import com.intellij.openapi.ui.ValidationInfo;
import com.intellij.openapi.util.Ref;
import com.intellij.psi.PsiElement;
import com.intellij.util.PlatformIcons;
import com.intellij.util.ui.JBUI;
import net.offbeatpioneer.intellij.plugins.grav.extensions.files.AbstractGravFileType;
import net.offbeatpioneer.intellij.plugins.grav.extensions.files.GravFileTypes;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Map; | c.gridx = 1;
c.gridy = 0;
myPanel.add(myNameField, c);
c.weightx = 0.3;
c.gridx = 2;
c.gridy = 0;
c.insets = JBUI.insetsLeft(12);
myPanel.add(myUpDownHint, c);
c.insets = JBUI.insets(10, 0);
c.gridx = 0;
c.gridy = 1;
myPanel.add(myKindLabel, c);
c.gridx = 1;
c.gridwidth = 2;
c.gridy = 1;
c.insets = JBUI.insets(10, 0, 10, 12);
myPanel.add(myKindCombo, c);
myKindLabel.setLabelFor(myKindCombo);
myKindCombo.registerUpDownHint(myNameField);
myUpDownHint.setIcon(PlatformIcons.UP_DOWN_ARROWS);
setTemplateKindComponentsVisible(false);
init();
myKindCombo.getComboBox().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) { | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/files/AbstractGravFileType.java
// public abstract class AbstractGravFileType extends LanguageFileType {
//
// public static final String DEFAULT_EXTENSION = "yaml";
//
// protected AbstractGravFileType() {
// super(YAMLLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public String getDefaultExtension() {
// return DEFAULT_EXTENSION;
// }
//
// public abstract boolean needsFilename();
//
// public abstract String getCorrespondingTemplateFile();
//
// public String getDefaultFilename() {
// return "untitled";
// }
// }
//
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/files/GravFileTypes.java
// public class GravFileTypes {
//
// public static AbstractGravFileType[] CONFIGURATION_FILE_TYPES = new AbstractGravFileType[]{
// new ThemeBlueprintsFileType(),
// new ThemeConfigurationFileType()
// };
//
// public static void setModuleName(String moduleName) {
// ((ThemeConfigurationFileType) CONFIGURATION_FILE_TYPES[1]).setDefaultFileName(moduleName);
// }
// }
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/action/CustomCreateFileFromTemplateDialog.java
import com.intellij.ide.actions.ElementCreator;
import com.intellij.ide.actions.TemplateKindCombo;
import com.intellij.lang.LangBundle;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.InputValidator;
import com.intellij.openapi.ui.InputValidatorEx;
import com.intellij.openapi.ui.ValidationInfo;
import com.intellij.openapi.util.Ref;
import com.intellij.psi.PsiElement;
import com.intellij.util.PlatformIcons;
import com.intellij.util.ui.JBUI;
import net.offbeatpioneer.intellij.plugins.grav.extensions.files.AbstractGravFileType;
import net.offbeatpioneer.intellij.plugins.grav.extensions.files.GravFileTypes;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Map;
c.gridx = 1;
c.gridy = 0;
myPanel.add(myNameField, c);
c.weightx = 0.3;
c.gridx = 2;
c.gridy = 0;
c.insets = JBUI.insetsLeft(12);
myPanel.add(myUpDownHint, c);
c.insets = JBUI.insets(10, 0);
c.gridx = 0;
c.gridy = 1;
myPanel.add(myKindLabel, c);
c.gridx = 1;
c.gridwidth = 2;
c.gridy = 1;
c.insets = JBUI.insets(10, 0, 10, 12);
myPanel.add(myKindCombo, c);
myKindLabel.setLabelFor(myKindCombo);
myKindCombo.registerUpDownHint(myNameField);
myUpDownHint.setIcon(PlatformIcons.UP_DOWN_ARROWS);
setTemplateKindComponentsVisible(false);
init();
myKindCombo.getComboBox().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) { | for (AbstractGravFileType each : GravFileTypes.CONFIGURATION_FILE_TYPES) { |
PioBeat/GravSupport | src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/module/php/GravProjectTemplateFactory.java | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/icons/GravIcons.java
// public class GravIcons {
//
// private static @NotNull Icon load(@NotNull String path) {
// return IconLoader.getIcon(path, GravIcons.class);
// // return IconManager.getInstance().getIcon(path, GravIcons.class);
// }
//
// public static final Icon GravDefaultIcon = load("/icons/gravLogo.svg");
// public static final Icon ThemeBlueprints = load("/icons/gravFileIcon.svg");
// public static final Icon ThemeConfiguration = load("/icons/gravFileIcon.svg");
// public static final Icon GravFileLogoIcon = load("/icons/gravToolWindowIcon.svg");
// public static final Icon GravToolWindowIcon = load("/icons/gravToolWindowIcon.svg");
// public static final Icon GravProjectWizardIcon = load("/icons/gravToolWindowIcon.svg");
// }
| import com.intellij.ide.util.projectWizard.WizardContext;
import com.intellij.platform.ProjectTemplate;
import com.intellij.platform.ProjectTemplatesFactory;
import net.offbeatpioneer.intellij.plugins.grav.extensions.icons.GravIcons;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*; | package net.offbeatpioneer.intellij.plugins.grav.extensions.module.php;
/**
* @author Dominik Grzelak
* @since 2017-08-11
*/
public class GravProjectTemplateFactory extends ProjectTemplatesFactory {
public GravProjectTemplateFactory() {
}
@Override
public String @NotNull [] getGroups() {
return new String[]{"PHP"}; //WebModuleBuilder.GROUP_NAME
}
@Override
public Icon getGroupIcon(String group) { | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/icons/GravIcons.java
// public class GravIcons {
//
// private static @NotNull Icon load(@NotNull String path) {
// return IconLoader.getIcon(path, GravIcons.class);
// // return IconManager.getInstance().getIcon(path, GravIcons.class);
// }
//
// public static final Icon GravDefaultIcon = load("/icons/gravLogo.svg");
// public static final Icon ThemeBlueprints = load("/icons/gravFileIcon.svg");
// public static final Icon ThemeConfiguration = load("/icons/gravFileIcon.svg");
// public static final Icon GravFileLogoIcon = load("/icons/gravToolWindowIcon.svg");
// public static final Icon GravToolWindowIcon = load("/icons/gravToolWindowIcon.svg");
// public static final Icon GravProjectWizardIcon = load("/icons/gravToolWindowIcon.svg");
// }
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/module/php/GravProjectTemplateFactory.java
import com.intellij.ide.util.projectWizard.WizardContext;
import com.intellij.platform.ProjectTemplate;
import com.intellij.platform.ProjectTemplatesFactory;
import net.offbeatpioneer.intellij.plugins.grav.extensions.icons.GravIcons;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
package net.offbeatpioneer.intellij.plugins.grav.extensions.module.php;
/**
* @author Dominik Grzelak
* @since 2017-08-11
*/
public class GravProjectTemplateFactory extends ProjectTemplatesFactory {
public GravProjectTemplateFactory() {
}
@Override
public String @NotNull [] getGroups() {
return new String[]{"PHP"}; //WebModuleBuilder.GROUP_NAME
}
@Override
public Icon getGroupIcon(String group) { | return GravIcons.GravProjectWizardIcon; |
PioBeat/GravSupport | src/main/java/net/offbeatpioneer/intellij/plugins/grav/action/CustomCreateFromTemplateAction.java | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/listener/GravProjectComponent.java
// public class GravProjectComponent {
//
// /**
// * May be used to check whether a project is able to process Grav actions.
// * The settings are also consulted.
// *
// * @param project the project to check
// * @return {@code true} if project may/can use Grav plugin
// */
// public static boolean isEnabled(Project project) {
// if (project == null) return false;
// if (GravSdkType.isOperationBasicallyAvailableFor(project)) {
// GravProjectSettings settings = GravProjectSettings.getInstance(project);
// if (settings == null)
// return false;
// return settings.pluginEnabled;
// }
// return false;
// }
//
// /**
// * Sets for all modules of a project the module type to {@link GravModuleType}.
// *
// * @param project the project
// */
// public static synchronized void convertProjectToGravProject(@NotNull Project project) {
// if (!project.isDisposed()) {
// for (Module module : ModuleManager.getInstance(project).getModules()) {
// convertModuleToGravModule(module);
// }
// }
// }
//
// /**
// * Sets the module type for the given module to {@link GravModuleType}.
// *
// * @param module the module
// */
// public static synchronized void convertModuleToGravModule(@NotNull Module module) {
// if (!module.isDisposed())
// module.setModuleType(GravModuleType.ID);
// }
//
// /**
// * Returns the current project for which the plugin is enabled from all opened projects of the IDE
// *
// * @return current opened project or null, if none exists or plugin is not enabled
// */
// @Nullable
// public static Project getEnabledProject() {
// for (Project each : ProjectManager.getInstance().getOpenProjects()) {
// if (GravProjectComponent.isEnabled(each)) {
// return each;
// }
// }
// return null;
// }
//
// }
| import com.intellij.CommonBundle;
import com.intellij.ide.IdeView;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.WriteActionAware;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiNameIdentifierOwner;
import net.offbeatpioneer.intellij.plugins.grav.listener.GravProjectComponent;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.Map; | @Nullable
protected abstract T createFile(String name, String templateName, PsiDirectory dir);
protected abstract void buildDialog(Project project, PsiDirectory directory, CustomCreateFileFromTemplateDialog.Builder builder);
@Nullable
protected String getDefaultTemplateName(@NotNull PsiDirectory dir) {
String property = getDefaultTemplateProperty();
return property == null ? null : PropertiesComponent.getInstance(dir.getProject()).getValue(property);
}
@Nullable
protected String getDefaultTemplateProperty() {
return null;
}
@Override
public void update(final AnActionEvent e) {
final DataContext dataContext = e.getDataContext();
final Presentation presentation = e.getPresentation();
final boolean enabled = isAvailable(dataContext);
presentation.setVisible(enabled);
presentation.setEnabled(enabled);
}
protected boolean isAvailable(DataContext dataContext) {
final Project project = CommonDataKeys.PROJECT.getData(dataContext);
final IdeView view = LangDataKeys.IDE_VIEW.getData(dataContext); | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/listener/GravProjectComponent.java
// public class GravProjectComponent {
//
// /**
// * May be used to check whether a project is able to process Grav actions.
// * The settings are also consulted.
// *
// * @param project the project to check
// * @return {@code true} if project may/can use Grav plugin
// */
// public static boolean isEnabled(Project project) {
// if (project == null) return false;
// if (GravSdkType.isOperationBasicallyAvailableFor(project)) {
// GravProjectSettings settings = GravProjectSettings.getInstance(project);
// if (settings == null)
// return false;
// return settings.pluginEnabled;
// }
// return false;
// }
//
// /**
// * Sets for all modules of a project the module type to {@link GravModuleType}.
// *
// * @param project the project
// */
// public static synchronized void convertProjectToGravProject(@NotNull Project project) {
// if (!project.isDisposed()) {
// for (Module module : ModuleManager.getInstance(project).getModules()) {
// convertModuleToGravModule(module);
// }
// }
// }
//
// /**
// * Sets the module type for the given module to {@link GravModuleType}.
// *
// * @param module the module
// */
// public static synchronized void convertModuleToGravModule(@NotNull Module module) {
// if (!module.isDisposed())
// module.setModuleType(GravModuleType.ID);
// }
//
// /**
// * Returns the current project for which the plugin is enabled from all opened projects of the IDE
// *
// * @return current opened project or null, if none exists or plugin is not enabled
// */
// @Nullable
// public static Project getEnabledProject() {
// for (Project each : ProjectManager.getInstance().getOpenProjects()) {
// if (GravProjectComponent.isEnabled(each)) {
// return each;
// }
// }
// return null;
// }
//
// }
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/action/CustomCreateFromTemplateAction.java
import com.intellij.CommonBundle;
import com.intellij.ide.IdeView;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.WriteActionAware;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiNameIdentifierOwner;
import net.offbeatpioneer.intellij.plugins.grav.listener.GravProjectComponent;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.Map;
@Nullable
protected abstract T createFile(String name, String templateName, PsiDirectory dir);
protected abstract void buildDialog(Project project, PsiDirectory directory, CustomCreateFileFromTemplateDialog.Builder builder);
@Nullable
protected String getDefaultTemplateName(@NotNull PsiDirectory dir) {
String property = getDefaultTemplateProperty();
return property == null ? null : PropertiesComponent.getInstance(dir.getProject()).getValue(property);
}
@Nullable
protected String getDefaultTemplateProperty() {
return null;
}
@Override
public void update(final AnActionEvent e) {
final DataContext dataContext = e.getDataContext();
final Presentation presentation = e.getPresentation();
final boolean enabled = isAvailable(dataContext);
presentation.setVisible(enabled);
presentation.setEnabled(enabled);
}
protected boolean isAvailable(DataContext dataContext) {
final Project project = CommonDataKeys.PROJECT.getData(dataContext);
final IdeView view = LangDataKeys.IDE_VIEW.getData(dataContext); | final boolean pluginEnabled = GravProjectComponent.isEnabled(project); |
PioBeat/GravSupport | src/main/java/net/offbeatpioneer/intellij/plugins/grav/application/settings/GravApplicationConfigurable.java | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/storage/GravPersistentStateComponent.java
// @State(
// name = "GravPersistentStateComponent",
// storages = {
// @Storage("net.offbeatpioneer.gravsupport.GravSettings.xml")
// }
// )
// public class GravPersistentStateComponent implements PersistentStateComponent<GravPersistentStateComponent> {
//
// private String defaultGravDownloadPath;
//
// public GravPersistentStateComponent() {
// defaultGravDownloadPath = "";
// }
//
// public String getDefaultGravDownloadPath() {
// return defaultGravDownloadPath;
// }
//
// public void setDefaultGravDownloadPath(String defaultGravDownloadPath) {
// this.defaultGravDownloadPath = defaultGravDownloadPath;
// }
//
// @Nullable
// @Override
// public GravPersistentStateComponent getState() {
// return this;
// }
//
// @Override
// public void loadState(@NotNull GravPersistentStateComponent state) {
// XmlSerializerUtil.copyBean(state, this);
// }
//
// @Nullable
// public static GravPersistentStateComponent getInstance(Project project) {
// return ServiceManager.getService(project, GravPersistentStateComponent.class);
// }
//
// @Nullable
// public static GravPersistentStateComponent getInstance() {
// return ServiceManager.getService(GravPersistentStateComponent.class);
// }
// }
| import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import net.offbeatpioneer.intellij.plugins.grav.storage.GravPersistentStateComponent;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.Nullable;
import javax.swing.*; | package net.offbeatpioneer.intellij.plugins.grav.application.settings;
/**
* Application based configuration for Grav in the settings menu of IntelliJ IDEA.
* <p>
* What it does:
* <ul>
* <li>Enables to specify the default Grav 'SDK' installation folder that is used when a new Grav project shall be created.</li>
* </ul>
*
* @author Dominik Grzelak
*/
public class GravApplicationConfigurable implements Configurable {
private ApplicationConfigForm applicationConfigForm = new ApplicationConfigForm(); | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/storage/GravPersistentStateComponent.java
// @State(
// name = "GravPersistentStateComponent",
// storages = {
// @Storage("net.offbeatpioneer.gravsupport.GravSettings.xml")
// }
// )
// public class GravPersistentStateComponent implements PersistentStateComponent<GravPersistentStateComponent> {
//
// private String defaultGravDownloadPath;
//
// public GravPersistentStateComponent() {
// defaultGravDownloadPath = "";
// }
//
// public String getDefaultGravDownloadPath() {
// return defaultGravDownloadPath;
// }
//
// public void setDefaultGravDownloadPath(String defaultGravDownloadPath) {
// this.defaultGravDownloadPath = defaultGravDownloadPath;
// }
//
// @Nullable
// @Override
// public GravPersistentStateComponent getState() {
// return this;
// }
//
// @Override
// public void loadState(@NotNull GravPersistentStateComponent state) {
// XmlSerializerUtil.copyBean(state, this);
// }
//
// @Nullable
// public static GravPersistentStateComponent getInstance(Project project) {
// return ServiceManager.getService(project, GravPersistentStateComponent.class);
// }
//
// @Nullable
// public static GravPersistentStateComponent getInstance() {
// return ServiceManager.getService(GravPersistentStateComponent.class);
// }
// }
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/application/settings/GravApplicationConfigurable.java
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import net.offbeatpioneer.intellij.plugins.grav.storage.GravPersistentStateComponent;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
package net.offbeatpioneer.intellij.plugins.grav.application.settings;
/**
* Application based configuration for Grav in the settings menu of IntelliJ IDEA.
* <p>
* What it does:
* <ul>
* <li>Enables to specify the default Grav 'SDK' installation folder that is used when a new Grav project shall be created.</li>
* </ul>
*
* @author Dominik Grzelak
*/
public class GravApplicationConfigurable implements Configurable {
private ApplicationConfigForm applicationConfigForm = new ApplicationConfigForm(); | private GravPersistentStateComponent storage; |
PioBeat/GravSupport | src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/module/GravSdkType.java | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/icons/GravIcons.java
// public class GravIcons {
//
// private static @NotNull Icon load(@NotNull String path) {
// return IconLoader.getIcon(path, GravIcons.class);
// // return IconManager.getInstance().getIcon(path, GravIcons.class);
// }
//
// public static final Icon GravDefaultIcon = load("/icons/gravLogo.svg");
// public static final Icon ThemeBlueprints = load("/icons/gravFileIcon.svg");
// public static final Icon ThemeConfiguration = load("/icons/gravFileIcon.svg");
// public static final Icon GravFileLogoIcon = load("/icons/gravToolWindowIcon.svg");
// public static final Icon GravToolWindowIcon = load("/icons/gravToolWindowIcon.svg");
// public static final Icon GravProjectWizardIcon = load("/icons/gravToolWindowIcon.svg");
// }
//
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/helper/NotificationHelper.java
// public class NotificationHelper {
//
// public static void showBaloon(String msg, MessageType messageType, @NotNull Project project) {
// showBaloon(msg, messageType, project, Balloon.Position.above, 3500);
// }
//
// public static void showBaloon(String msg, MessageType messageType, @NotNull Project project, int time) {
// showBaloon(msg, messageType, project, Balloon.Position.above, time);
// }
//
// public static void showBaloon(String msg, MessageType messageType, @NotNull Project project, Balloon.Position position) {
// StatusBar statusBar = WindowManager.getInstance().getStatusBar(project);
// showBaloon(msg, messageType, RelativePoint.getSouthEastOf(statusBar.getComponent()), position, 3500);
// }
//
// public static void showBaloon(String msg, MessageType messageType, @NotNull Project project, Balloon.Position position, int time) {
// StatusBar statusBar = WindowManager.getInstance().getStatusBar(project);
// showBaloon(msg, messageType, RelativePoint.getSouthEastOf(statusBar.getComponent()), position, time);
// }
//
// public static void showBaloon(String msg, MessageType messageType, RelativePoint relativePoint, Balloon.Position position, int time) {
// JBPopupFactory.getInstance()
// .createHtmlTextBalloonBuilder(msg, messageType, null)
// .setFadeoutTime(time)
// .createBalloon()
// .show(relativePoint, position);
// }
//
// public static void showErrorNotification(@Nullable Project project, @NotNull String content) {
// Notifications.Bus.notify(new Notification("GRAV_BUS_NOTIFICATIONS", "Grav", content, NotificationType.ERROR, null), project);
// }
//
// public static void showInfoNotification(@Nullable Project project, @NotNull String content) {
// Notifications.Bus.notify(new Notification("GRAV_BUS_NOTIFICATIONS", "Grav", content, NotificationType.INFORMATION, null), project);
// }
// }
| import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.projectRoots.*;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import net.offbeatpioneer.intellij.plugins.grav.extensions.icons.GravIcons;
import net.offbeatpioneer.intellij.plugins.grav.helper.NotificationHelper;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException; | package net.offbeatpioneer.intellij.plugins.grav.extensions.module;
/**
* Created by Dome on 16.07.2017.
*/
public class GravSdkType extends SdkType {
public final static String UNSPECIFIED = "unspecified";
public GravSdkType() {
super("Grav");
}
@Nullable
@Override
public String suggestHomePath() {
return System.getenv().get("GRAV_HOME");
}
@Override
public boolean isValidSdkHome(String path) {
return true;
}
@Override
public String suggestSdkName(String currentSdkName, String sdkHome) {
return "Grav SDK";
}
@Override
public Icon getIcon() { | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/icons/GravIcons.java
// public class GravIcons {
//
// private static @NotNull Icon load(@NotNull String path) {
// return IconLoader.getIcon(path, GravIcons.class);
// // return IconManager.getInstance().getIcon(path, GravIcons.class);
// }
//
// public static final Icon GravDefaultIcon = load("/icons/gravLogo.svg");
// public static final Icon ThemeBlueprints = load("/icons/gravFileIcon.svg");
// public static final Icon ThemeConfiguration = load("/icons/gravFileIcon.svg");
// public static final Icon GravFileLogoIcon = load("/icons/gravToolWindowIcon.svg");
// public static final Icon GravToolWindowIcon = load("/icons/gravToolWindowIcon.svg");
// public static final Icon GravProjectWizardIcon = load("/icons/gravToolWindowIcon.svg");
// }
//
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/helper/NotificationHelper.java
// public class NotificationHelper {
//
// public static void showBaloon(String msg, MessageType messageType, @NotNull Project project) {
// showBaloon(msg, messageType, project, Balloon.Position.above, 3500);
// }
//
// public static void showBaloon(String msg, MessageType messageType, @NotNull Project project, int time) {
// showBaloon(msg, messageType, project, Balloon.Position.above, time);
// }
//
// public static void showBaloon(String msg, MessageType messageType, @NotNull Project project, Balloon.Position position) {
// StatusBar statusBar = WindowManager.getInstance().getStatusBar(project);
// showBaloon(msg, messageType, RelativePoint.getSouthEastOf(statusBar.getComponent()), position, 3500);
// }
//
// public static void showBaloon(String msg, MessageType messageType, @NotNull Project project, Balloon.Position position, int time) {
// StatusBar statusBar = WindowManager.getInstance().getStatusBar(project);
// showBaloon(msg, messageType, RelativePoint.getSouthEastOf(statusBar.getComponent()), position, time);
// }
//
// public static void showBaloon(String msg, MessageType messageType, RelativePoint relativePoint, Balloon.Position position, int time) {
// JBPopupFactory.getInstance()
// .createHtmlTextBalloonBuilder(msg, messageType, null)
// .setFadeoutTime(time)
// .createBalloon()
// .show(relativePoint, position);
// }
//
// public static void showErrorNotification(@Nullable Project project, @NotNull String content) {
// Notifications.Bus.notify(new Notification("GRAV_BUS_NOTIFICATIONS", "Grav", content, NotificationType.ERROR, null), project);
// }
//
// public static void showInfoNotification(@Nullable Project project, @NotNull String content) {
// Notifications.Bus.notify(new Notification("GRAV_BUS_NOTIFICATIONS", "Grav", content, NotificationType.INFORMATION, null), project);
// }
// }
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/module/GravSdkType.java
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.projectRoots.*;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import net.offbeatpioneer.intellij.plugins.grav.extensions.icons.GravIcons;
import net.offbeatpioneer.intellij.plugins.grav.helper.NotificationHelper;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
package net.offbeatpioneer.intellij.plugins.grav.extensions.module;
/**
* Created by Dome on 16.07.2017.
*/
public class GravSdkType extends SdkType {
public final static String UNSPECIFIED = "unspecified";
public GravSdkType() {
super("Grav");
}
@Nullable
@Override
public String suggestHomePath() {
return System.getenv().get("GRAV_HOME");
}
@Override
public boolean isValidSdkHome(String path) {
return true;
}
@Override
public String suggestSdkName(String currentSdkName, String sdkHome) {
return "Grav SDK";
}
@Override
public Icon getIcon() { | return GravIcons.GravDefaultIcon; |
PioBeat/GravSupport | src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/module/GravSdkType.java | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/icons/GravIcons.java
// public class GravIcons {
//
// private static @NotNull Icon load(@NotNull String path) {
// return IconLoader.getIcon(path, GravIcons.class);
// // return IconManager.getInstance().getIcon(path, GravIcons.class);
// }
//
// public static final Icon GravDefaultIcon = load("/icons/gravLogo.svg");
// public static final Icon ThemeBlueprints = load("/icons/gravFileIcon.svg");
// public static final Icon ThemeConfiguration = load("/icons/gravFileIcon.svg");
// public static final Icon GravFileLogoIcon = load("/icons/gravToolWindowIcon.svg");
// public static final Icon GravToolWindowIcon = load("/icons/gravToolWindowIcon.svg");
// public static final Icon GravProjectWizardIcon = load("/icons/gravToolWindowIcon.svg");
// }
//
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/helper/NotificationHelper.java
// public class NotificationHelper {
//
// public static void showBaloon(String msg, MessageType messageType, @NotNull Project project) {
// showBaloon(msg, messageType, project, Balloon.Position.above, 3500);
// }
//
// public static void showBaloon(String msg, MessageType messageType, @NotNull Project project, int time) {
// showBaloon(msg, messageType, project, Balloon.Position.above, time);
// }
//
// public static void showBaloon(String msg, MessageType messageType, @NotNull Project project, Balloon.Position position) {
// StatusBar statusBar = WindowManager.getInstance().getStatusBar(project);
// showBaloon(msg, messageType, RelativePoint.getSouthEastOf(statusBar.getComponent()), position, 3500);
// }
//
// public static void showBaloon(String msg, MessageType messageType, @NotNull Project project, Balloon.Position position, int time) {
// StatusBar statusBar = WindowManager.getInstance().getStatusBar(project);
// showBaloon(msg, messageType, RelativePoint.getSouthEastOf(statusBar.getComponent()), position, time);
// }
//
// public static void showBaloon(String msg, MessageType messageType, RelativePoint relativePoint, Balloon.Position position, int time) {
// JBPopupFactory.getInstance()
// .createHtmlTextBalloonBuilder(msg, messageType, null)
// .setFadeoutTime(time)
// .createBalloon()
// .show(relativePoint, position);
// }
//
// public static void showErrorNotification(@Nullable Project project, @NotNull String content) {
// Notifications.Bus.notify(new Notification("GRAV_BUS_NOTIFICATIONS", "Grav", content, NotificationType.ERROR, null), project);
// }
//
// public static void showInfoNotification(@Nullable Project project, @NotNull String content) {
// Notifications.Bus.notify(new Notification("GRAV_BUS_NOTIFICATIONS", "Grav", content, NotificationType.INFORMATION, null), project);
// }
// }
| import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.projectRoots.*;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import net.offbeatpioneer.intellij.plugins.grav.extensions.icons.GravIcons;
import net.offbeatpioneer.intellij.plugins.grav.helper.NotificationHelper;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException; | public String suggestSdkName(String currentSdkName, String sdkHome) {
return "Grav SDK";
}
@Override
public Icon getIcon() {
return GravIcons.GravDefaultIcon;
}
@Override
public Icon getIconForAddAction() {
return getIcon();
}
@Nullable
@Override
public AdditionalDataConfigurable createAdditionalDataConfigurable(@NotNull SdkModel sdkModel, @NotNull SdkModificator sdkModificator) {
return null;
}
public static SdkTypeId getInstance() {
return SdkType.findInstance(GravSdkType.class);
}
//TODO
@Nullable
@Override
public String getVersionString(Sdk sdk) {
String path = sdk.getHomePath();
if (path == null) { | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/icons/GravIcons.java
// public class GravIcons {
//
// private static @NotNull Icon load(@NotNull String path) {
// return IconLoader.getIcon(path, GravIcons.class);
// // return IconManager.getInstance().getIcon(path, GravIcons.class);
// }
//
// public static final Icon GravDefaultIcon = load("/icons/gravLogo.svg");
// public static final Icon ThemeBlueprints = load("/icons/gravFileIcon.svg");
// public static final Icon ThemeConfiguration = load("/icons/gravFileIcon.svg");
// public static final Icon GravFileLogoIcon = load("/icons/gravToolWindowIcon.svg");
// public static final Icon GravToolWindowIcon = load("/icons/gravToolWindowIcon.svg");
// public static final Icon GravProjectWizardIcon = load("/icons/gravToolWindowIcon.svg");
// }
//
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/helper/NotificationHelper.java
// public class NotificationHelper {
//
// public static void showBaloon(String msg, MessageType messageType, @NotNull Project project) {
// showBaloon(msg, messageType, project, Balloon.Position.above, 3500);
// }
//
// public static void showBaloon(String msg, MessageType messageType, @NotNull Project project, int time) {
// showBaloon(msg, messageType, project, Balloon.Position.above, time);
// }
//
// public static void showBaloon(String msg, MessageType messageType, @NotNull Project project, Balloon.Position position) {
// StatusBar statusBar = WindowManager.getInstance().getStatusBar(project);
// showBaloon(msg, messageType, RelativePoint.getSouthEastOf(statusBar.getComponent()), position, 3500);
// }
//
// public static void showBaloon(String msg, MessageType messageType, @NotNull Project project, Balloon.Position position, int time) {
// StatusBar statusBar = WindowManager.getInstance().getStatusBar(project);
// showBaloon(msg, messageType, RelativePoint.getSouthEastOf(statusBar.getComponent()), position, time);
// }
//
// public static void showBaloon(String msg, MessageType messageType, RelativePoint relativePoint, Balloon.Position position, int time) {
// JBPopupFactory.getInstance()
// .createHtmlTextBalloonBuilder(msg, messageType, null)
// .setFadeoutTime(time)
// .createBalloon()
// .show(relativePoint, position);
// }
//
// public static void showErrorNotification(@Nullable Project project, @NotNull String content) {
// Notifications.Bus.notify(new Notification("GRAV_BUS_NOTIFICATIONS", "Grav", content, NotificationType.ERROR, null), project);
// }
//
// public static void showInfoNotification(@Nullable Project project, @NotNull String content) {
// Notifications.Bus.notify(new Notification("GRAV_BUS_NOTIFICATIONS", "Grav", content, NotificationType.INFORMATION, null), project);
// }
// }
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/module/GravSdkType.java
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.projectRoots.*;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import net.offbeatpioneer.intellij.plugins.grav.extensions.icons.GravIcons;
import net.offbeatpioneer.intellij.plugins.grav.helper.NotificationHelper;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
public String suggestSdkName(String currentSdkName, String sdkHome) {
return "Grav SDK";
}
@Override
public Icon getIcon() {
return GravIcons.GravDefaultIcon;
}
@Override
public Icon getIconForAddAction() {
return getIcon();
}
@Nullable
@Override
public AdditionalDataConfigurable createAdditionalDataConfigurable(@NotNull SdkModel sdkModel, @NotNull SdkModificator sdkModificator) {
return null;
}
public static SdkTypeId getInstance() {
return SdkType.findInstance(GravSdkType.class);
}
//TODO
@Nullable
@Override
public String getVersionString(Sdk sdk) {
String path = sdk.getHomePath();
if (path == null) { | NotificationHelper.showBaloon("No home path specified", MessageType.ERROR, ProjectManager.getInstance().getDefaultProject()); |
PioBeat/GravSupport | src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/toolwindow/SystemSettingsToolWindowFactory.java | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/listener/GravProjectComponent.java
// public class GravProjectComponent {
//
// /**
// * May be used to check whether a project is able to process Grav actions.
// * The settings are also consulted.
// *
// * @param project the project to check
// * @return {@code true} if project may/can use Grav plugin
// */
// public static boolean isEnabled(Project project) {
// if (project == null) return false;
// if (GravSdkType.isOperationBasicallyAvailableFor(project)) {
// GravProjectSettings settings = GravProjectSettings.getInstance(project);
// if (settings == null)
// return false;
// return settings.pluginEnabled;
// }
// return false;
// }
//
// /**
// * Sets for all modules of a project the module type to {@link GravModuleType}.
// *
// * @param project the project
// */
// public static synchronized void convertProjectToGravProject(@NotNull Project project) {
// if (!project.isDisposed()) {
// for (Module module : ModuleManager.getInstance(project).getModules()) {
// convertModuleToGravModule(module);
// }
// }
// }
//
// /**
// * Sets the module type for the given module to {@link GravModuleType}.
// *
// * @param module the module
// */
// public static synchronized void convertModuleToGravModule(@NotNull Module module) {
// if (!module.isDisposed())
// module.setModuleType(GravModuleType.ID);
// }
//
// /**
// * Returns the current project for which the plugin is enabled from all opened projects of the IDE
// *
// * @return current opened project or null, if none exists or plugin is not enabled
// */
// @Nullable
// public static Project getEnabledProject() {
// for (Project each : ProjectManager.getInstance().getOpenProjects()) {
// if (GravProjectComponent.isEnabled(each)) {
// return each;
// }
// }
// return null;
// }
//
// }
| import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowFactory;
import com.intellij.psi.*;
import com.intellij.psi.impl.smartPointers.SmartPointerManagerImpl;
import com.intellij.ui.components.labels.ActionLink;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentFactory;
import com.intellij.util.ThrowableRunnable;
import net.offbeatpioneer.intellij.plugins.grav.helper.*;
import net.offbeatpioneer.intellij.plugins.grav.listener.GravProjectComponent;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.yaml.YAMLElementGenerator;
import org.jetbrains.yaml.YAMLUtil;
import org.jetbrains.yaml.psi.YAMLDocument;
import org.jetbrains.yaml.psi.YAMLFile;
import org.jetbrains.yaml.psi.YAMLKeyValue;
import org.jetbrains.yaml.psi.YAMLValue;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects; | } catch (Throwable throwable) {
throwable.printStackTrace();
NotificationHelper.showBaloon("Could not replace value in /system/config/system.yaml", MessageType.ERROR, systemYamlFile.getProject());
}
}
});
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
error = true;
}
if (error) {
component.setEnabled(false);
} else {
component.setEnabled(true);
}
}
@Override
public boolean isApplicable(@NotNull Project project) {
return shouldBeAvailable(project);
}
@Override
public boolean shouldBeAvailable(@NotNull Project project) {
systemYamlFile = null; | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/listener/GravProjectComponent.java
// public class GravProjectComponent {
//
// /**
// * May be used to check whether a project is able to process Grav actions.
// * The settings are also consulted.
// *
// * @param project the project to check
// * @return {@code true} if project may/can use Grav plugin
// */
// public static boolean isEnabled(Project project) {
// if (project == null) return false;
// if (GravSdkType.isOperationBasicallyAvailableFor(project)) {
// GravProjectSettings settings = GravProjectSettings.getInstance(project);
// if (settings == null)
// return false;
// return settings.pluginEnabled;
// }
// return false;
// }
//
// /**
// * Sets for all modules of a project the module type to {@link GravModuleType}.
// *
// * @param project the project
// */
// public static synchronized void convertProjectToGravProject(@NotNull Project project) {
// if (!project.isDisposed()) {
// for (Module module : ModuleManager.getInstance(project).getModules()) {
// convertModuleToGravModule(module);
// }
// }
// }
//
// /**
// * Sets the module type for the given module to {@link GravModuleType}.
// *
// * @param module the module
// */
// public static synchronized void convertModuleToGravModule(@NotNull Module module) {
// if (!module.isDisposed())
// module.setModuleType(GravModuleType.ID);
// }
//
// /**
// * Returns the current project for which the plugin is enabled from all opened projects of the IDE
// *
// * @return current opened project or null, if none exists or plugin is not enabled
// */
// @Nullable
// public static Project getEnabledProject() {
// for (Project each : ProjectManager.getInstance().getOpenProjects()) {
// if (GravProjectComponent.isEnabled(each)) {
// return each;
// }
// }
// return null;
// }
//
// }
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/toolwindow/SystemSettingsToolWindowFactory.java
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowFactory;
import com.intellij.psi.*;
import com.intellij.psi.impl.smartPointers.SmartPointerManagerImpl;
import com.intellij.ui.components.labels.ActionLink;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentFactory;
import com.intellij.util.ThrowableRunnable;
import net.offbeatpioneer.intellij.plugins.grav.helper.*;
import net.offbeatpioneer.intellij.plugins.grav.listener.GravProjectComponent;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.yaml.YAMLElementGenerator;
import org.jetbrains.yaml.YAMLUtil;
import org.jetbrains.yaml.psi.YAMLDocument;
import org.jetbrains.yaml.psi.YAMLFile;
import org.jetbrains.yaml.psi.YAMLKeyValue;
import org.jetbrains.yaml.psi.YAMLValue;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
} catch (Throwable throwable) {
throwable.printStackTrace();
NotificationHelper.showBaloon("Could not replace value in /system/config/system.yaml", MessageType.ERROR, systemYamlFile.getProject());
}
}
});
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
error = true;
}
if (error) {
component.setEnabled(false);
} else {
component.setEnabled(true);
}
}
@Override
public boolean isApplicable(@NotNull Project project) {
return shouldBeAvailable(project);
}
@Override
public boolean shouldBeAvailable(@NotNull Project project) {
systemYamlFile = null; | boolean pluginEnabled = GravProjectComponent.isEnabled(project); |
PioBeat/GravSupport | src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/intentions/ConvertTwigResource.java | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/helper/GravFileTemplateUtil.java
// public class GravFileTemplateUtil {
// private final static String GRAV_TEMPLATE_PREFIX = "Grav ";
//
// public static List<FileTemplate> getAvailableThemeConfigurationTemplates(@NotNull Project project) {
// return getApplicableTemplates(new Condition<FileTemplate>() {
// @Override
// public boolean value(FileTemplate fileTemplate) {
// return AbstractGravFileType.DEFAULT_EXTENSION.equals(fileTemplate.getExtension());
// }
// }, project);
// }
//
// public static FileTemplate getThemeConfigurationTemplateByName(String name, @NotNull Project project) {
// List<FileTemplate> buf = GravFileTemplateUtil.getAvailableThemeConfigurationTemplates(project);
// for (FileTemplate each : buf) {
// if (each.getName().equalsIgnoreCase(name)) {
// return each;
// }
// }
// return null;
// }
//
// /**
// * Finds the value to a header variable in a Grav markdown file
// *
// * @param variable PsiElement of a valid header variable in a Grav markdown file
// * @return PsiElement of the value of the variable
// */
// public static PsiElement getValueFromVariable(PsiElement variable) {
// PsiElement sibling = variable.getNextSibling();
// int maxIter = 50, iterCount = 0;
// while (sibling != null && sibling.getText().matches(":|\\s*|(:\\s*)") && iterCount < maxIter) {
// sibling = sibling.getNextSibling();
// iterCount++;
// }
// return sibling;
// }
//
// public static boolean isTwigTemplateFile(PsiFile file) {
// try {
// return file instanceof TwigFile;
// } catch (NoClassDefFoundError e) {
// return false;
// }
// }
//
// /**
// * Return the current theme which is set in the system/config/system.yaml file
// *
// * @param project the project
// * @return theme name or null
// */
// public static String getDefaultTheme(Project project) {
// if (Objects.isNull(project.getBasePath())) {
// IdeHelper.notifyShowGenericErrorMessage();
// return "";
// }
// VirtualFile projectPath = LocalFileSystem.getInstance().findFileByIoFile(new File(project.getBasePath()));
// VirtualFile vfile = VfsUtil.findRelativeFile(projectPath, "system", "config", "system.yaml");
// if (vfile == null) return null;
// PsiFile psiFile = PsiManager.getInstance(project).findFile(vfile);
// if (psiFile == null) return null;
//
// YAMLKeyValue yamlKeyValue = GravYAMLUtils.getKeyValue((YAMLFile) psiFile, Arrays.asList(new String[]{"pages", "theme"}));
// if (yamlKeyValue == null) return null;
//
// return yamlKeyValue.getValueText();
// }
//
// public static List<FileTemplate> getApplicableTemplates(Condition<FileTemplate> filter, @NotNull Project project) {
// final List<FileTemplate> applicableTemplates = new SmartList<FileTemplate>();
// applicableTemplates.addAll(ContainerUtil.findAll(FileTemplateManager.getInstance(project).getInternalTemplates(), filter));
// applicableTemplates.addAll(ContainerUtil.findAll(FileTemplateManager.getInstance(project).getAllTemplates(), filter));
// return applicableTemplates;
// }
//
// public static String getTemplateShortName(String templateName) {
// if (templateName.startsWith(GRAV_TEMPLATE_PREFIX)) {
// return templateName.substring(GRAV_TEMPLATE_PREFIX.length());
// }
// return templateName;
// }
// }
| import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.impl.source.html.HtmlFileImpl;
import com.intellij.psi.impl.source.xml.XmlAttributeImpl;
import com.intellij.psi.impl.source.xml.XmlAttributeValueImpl;
import com.intellij.psi.templateLanguages.OuterLanguageElement;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import com.jetbrains.twig.elements.TwigElementFactory;
import com.jetbrains.twig.elements.TwigElementTypes;
import net.offbeatpioneer.intellij.plugins.grav.helper.GravFileTemplateUtil;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull; | package net.offbeatpioneer.intellij.plugins.grav.extensions.intentions;
public class ConvertTwigResource extends PsiElementBaseIntentionAction implements IntentionAction {
@NotNull
@Override
public String getText() {
return "Convert to theme resource link";
}
@Override
public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element) throws IncorrectOperationException {
String text = "{{ url(\"theme://" + element.getText() + "\") }}";
PsiElement psiElement = TwigElementFactory.createPsiElement(project, text, TwigElementTypes.PRINT_BLOCK);
if (psiElement != null)
element.replace(psiElement);
}
@Override
public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiElement element) {
if (!element.isWritable()) return false; | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/helper/GravFileTemplateUtil.java
// public class GravFileTemplateUtil {
// private final static String GRAV_TEMPLATE_PREFIX = "Grav ";
//
// public static List<FileTemplate> getAvailableThemeConfigurationTemplates(@NotNull Project project) {
// return getApplicableTemplates(new Condition<FileTemplate>() {
// @Override
// public boolean value(FileTemplate fileTemplate) {
// return AbstractGravFileType.DEFAULT_EXTENSION.equals(fileTemplate.getExtension());
// }
// }, project);
// }
//
// public static FileTemplate getThemeConfigurationTemplateByName(String name, @NotNull Project project) {
// List<FileTemplate> buf = GravFileTemplateUtil.getAvailableThemeConfigurationTemplates(project);
// for (FileTemplate each : buf) {
// if (each.getName().equalsIgnoreCase(name)) {
// return each;
// }
// }
// return null;
// }
//
// /**
// * Finds the value to a header variable in a Grav markdown file
// *
// * @param variable PsiElement of a valid header variable in a Grav markdown file
// * @return PsiElement of the value of the variable
// */
// public static PsiElement getValueFromVariable(PsiElement variable) {
// PsiElement sibling = variable.getNextSibling();
// int maxIter = 50, iterCount = 0;
// while (sibling != null && sibling.getText().matches(":|\\s*|(:\\s*)") && iterCount < maxIter) {
// sibling = sibling.getNextSibling();
// iterCount++;
// }
// return sibling;
// }
//
// public static boolean isTwigTemplateFile(PsiFile file) {
// try {
// return file instanceof TwigFile;
// } catch (NoClassDefFoundError e) {
// return false;
// }
// }
//
// /**
// * Return the current theme which is set in the system/config/system.yaml file
// *
// * @param project the project
// * @return theme name or null
// */
// public static String getDefaultTheme(Project project) {
// if (Objects.isNull(project.getBasePath())) {
// IdeHelper.notifyShowGenericErrorMessage();
// return "";
// }
// VirtualFile projectPath = LocalFileSystem.getInstance().findFileByIoFile(new File(project.getBasePath()));
// VirtualFile vfile = VfsUtil.findRelativeFile(projectPath, "system", "config", "system.yaml");
// if (vfile == null) return null;
// PsiFile psiFile = PsiManager.getInstance(project).findFile(vfile);
// if (psiFile == null) return null;
//
// YAMLKeyValue yamlKeyValue = GravYAMLUtils.getKeyValue((YAMLFile) psiFile, Arrays.asList(new String[]{"pages", "theme"}));
// if (yamlKeyValue == null) return null;
//
// return yamlKeyValue.getValueText();
// }
//
// public static List<FileTemplate> getApplicableTemplates(Condition<FileTemplate> filter, @NotNull Project project) {
// final List<FileTemplate> applicableTemplates = new SmartList<FileTemplate>();
// applicableTemplates.addAll(ContainerUtil.findAll(FileTemplateManager.getInstance(project).getInternalTemplates(), filter));
// applicableTemplates.addAll(ContainerUtil.findAll(FileTemplateManager.getInstance(project).getAllTemplates(), filter));
// return applicableTemplates;
// }
//
// public static String getTemplateShortName(String templateName) {
// if (templateName.startsWith(GRAV_TEMPLATE_PREFIX)) {
// return templateName.substring(GRAV_TEMPLATE_PREFIX.length());
// }
// return templateName;
// }
// }
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/intentions/ConvertTwigResource.java
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.impl.source.html.HtmlFileImpl;
import com.intellij.psi.impl.source.xml.XmlAttributeImpl;
import com.intellij.psi.impl.source.xml.XmlAttributeValueImpl;
import com.intellij.psi.templateLanguages.OuterLanguageElement;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import com.jetbrains.twig.elements.TwigElementFactory;
import com.jetbrains.twig.elements.TwigElementTypes;
import net.offbeatpioneer.intellij.plugins.grav.helper.GravFileTemplateUtil;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
package net.offbeatpioneer.intellij.plugins.grav.extensions.intentions;
public class ConvertTwigResource extends PsiElementBaseIntentionAction implements IntentionAction {
@NotNull
@Override
public String getText() {
return "Convert to theme resource link";
}
@Override
public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element) throws IncorrectOperationException {
String text = "{{ url(\"theme://" + element.getText() + "\") }}";
PsiElement psiElement = TwigElementFactory.createPsiElement(project, text, TwigElementTypes.PRINT_BLOCK);
if (psiElement != null)
element.replace(psiElement);
}
@Override
public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiElement element) {
if (!element.isWritable()) return false; | boolean isTwigFile = GravFileTemplateUtil.isTwigTemplateFile(element.getContainingFile()) || element.getContainingFile() instanceof HtmlFileImpl; |
PioBeat/GravSupport | src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/module/GravModuleType.java | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/icons/GravIcons.java
// public class GravIcons {
//
// private static @NotNull Icon load(@NotNull String path) {
// return IconLoader.getIcon(path, GravIcons.class);
// // return IconManager.getInstance().getIcon(path, GravIcons.class);
// }
//
// public static final Icon GravDefaultIcon = load("/icons/gravLogo.svg");
// public static final Icon ThemeBlueprints = load("/icons/gravFileIcon.svg");
// public static final Icon ThemeConfiguration = load("/icons/gravFileIcon.svg");
// public static final Icon GravFileLogoIcon = load("/icons/gravToolWindowIcon.svg");
// public static final Icon GravToolWindowIcon = load("/icons/gravToolWindowIcon.svg");
// public static final Icon GravProjectWizardIcon = load("/icons/gravToolWindowIcon.svg");
// }
//
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/listener/GravProjectComponent.java
// public class GravProjectComponent {
//
// /**
// * May be used to check whether a project is able to process Grav actions.
// * The settings are also consulted.
// *
// * @param project the project to check
// * @return {@code true} if project may/can use Grav plugin
// */
// public static boolean isEnabled(Project project) {
// if (project == null) return false;
// if (GravSdkType.isOperationBasicallyAvailableFor(project)) {
// GravProjectSettings settings = GravProjectSettings.getInstance(project);
// if (settings == null)
// return false;
// return settings.pluginEnabled;
// }
// return false;
// }
//
// /**
// * Sets for all modules of a project the module type to {@link GravModuleType}.
// *
// * @param project the project
// */
// public static synchronized void convertProjectToGravProject(@NotNull Project project) {
// if (!project.isDisposed()) {
// for (Module module : ModuleManager.getInstance(project).getModules()) {
// convertModuleToGravModule(module);
// }
// }
// }
//
// /**
// * Sets the module type for the given module to {@link GravModuleType}.
// *
// * @param module the module
// */
// public static synchronized void convertModuleToGravModule(@NotNull Module module) {
// if (!module.isDisposed())
// module.setModuleType(GravModuleType.ID);
// }
//
// /**
// * Returns the current project for which the plugin is enabled from all opened projects of the IDE
// *
// * @return current opened project or null, if none exists or plugin is not enabled
// */
// @Nullable
// public static Project getEnabledProject() {
// for (Project each : ProjectManager.getInstance().getOpenProjects()) {
// if (GravProjectComponent.isEnabled(each)) {
// return each;
// }
// }
// return null;
// }
//
// }
| import com.intellij.openapi.module.ModuleType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import net.offbeatpioneer.intellij.plugins.grav.extensions.icons.GravIcons;
import net.offbeatpioneer.intellij.plugins.grav.listener.GravProjectComponent;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.io.File; | package net.offbeatpioneer.intellij.plugins.grav.extensions.module;
public class GravModuleType extends ModuleType<GravModuleBuilder> {
public static final String ID = "GRAV_TYPE";
private static final GravModuleType INSTANCE = new GravModuleType();
public GravModuleType() {
super(ID);
}
@NotNull
@Override
public GravModuleBuilder createModuleBuilder() {
return new GravModuleBuilder();
}
@NotNull
@Override
public String getName() {
return "Grav";
}
@NotNull
@Override
public String getDescription() {
return "Add support for Grav";
}
@Override
public @NotNull Icon getIcon() { | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/icons/GravIcons.java
// public class GravIcons {
//
// private static @NotNull Icon load(@NotNull String path) {
// return IconLoader.getIcon(path, GravIcons.class);
// // return IconManager.getInstance().getIcon(path, GravIcons.class);
// }
//
// public static final Icon GravDefaultIcon = load("/icons/gravLogo.svg");
// public static final Icon ThemeBlueprints = load("/icons/gravFileIcon.svg");
// public static final Icon ThemeConfiguration = load("/icons/gravFileIcon.svg");
// public static final Icon GravFileLogoIcon = load("/icons/gravToolWindowIcon.svg");
// public static final Icon GravToolWindowIcon = load("/icons/gravToolWindowIcon.svg");
// public static final Icon GravProjectWizardIcon = load("/icons/gravToolWindowIcon.svg");
// }
//
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/listener/GravProjectComponent.java
// public class GravProjectComponent {
//
// /**
// * May be used to check whether a project is able to process Grav actions.
// * The settings are also consulted.
// *
// * @param project the project to check
// * @return {@code true} if project may/can use Grav plugin
// */
// public static boolean isEnabled(Project project) {
// if (project == null) return false;
// if (GravSdkType.isOperationBasicallyAvailableFor(project)) {
// GravProjectSettings settings = GravProjectSettings.getInstance(project);
// if (settings == null)
// return false;
// return settings.pluginEnabled;
// }
// return false;
// }
//
// /**
// * Sets for all modules of a project the module type to {@link GravModuleType}.
// *
// * @param project the project
// */
// public static synchronized void convertProjectToGravProject(@NotNull Project project) {
// if (!project.isDisposed()) {
// for (Module module : ModuleManager.getInstance(project).getModules()) {
// convertModuleToGravModule(module);
// }
// }
// }
//
// /**
// * Sets the module type for the given module to {@link GravModuleType}.
// *
// * @param module the module
// */
// public static synchronized void convertModuleToGravModule(@NotNull Module module) {
// if (!module.isDisposed())
// module.setModuleType(GravModuleType.ID);
// }
//
// /**
// * Returns the current project for which the plugin is enabled from all opened projects of the IDE
// *
// * @return current opened project or null, if none exists or plugin is not enabled
// */
// @Nullable
// public static Project getEnabledProject() {
// for (Project each : ProjectManager.getInstance().getOpenProjects()) {
// if (GravProjectComponent.isEnabled(each)) {
// return each;
// }
// }
// return null;
// }
//
// }
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/module/GravModuleType.java
import com.intellij.openapi.module.ModuleType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import net.offbeatpioneer.intellij.plugins.grav.extensions.icons.GravIcons;
import net.offbeatpioneer.intellij.plugins.grav.listener.GravProjectComponent;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.io.File;
package net.offbeatpioneer.intellij.plugins.grav.extensions.module;
public class GravModuleType extends ModuleType<GravModuleBuilder> {
public static final String ID = "GRAV_TYPE";
private static final GravModuleType INSTANCE = new GravModuleType();
public GravModuleType() {
super(ID);
}
@NotNull
@Override
public GravModuleBuilder createModuleBuilder() {
return new GravModuleBuilder();
}
@NotNull
@Override
public String getName() {
return "Grav";
}
@NotNull
@Override
public String getDescription() {
return "Add support for Grav";
}
@Override
public @NotNull Icon getIcon() { | return GravIcons.GravDefaultIcon; |
PioBeat/GravSupport | src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/lang/substitutor/GravFileLanguageSubstitutor.java | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/files/ThemeBlueprintsFileType.java
// public class ThemeBlueprintsFileType extends AbstractGravFileType {
// public static final LanguageFileType INSTANCE = new ThemeBlueprintsFileType();
//
// public ThemeBlueprintsFileType() {
// super();
// }
//
// @NotNull
// @Override
// public String getName() {
// return "Theme blueprints";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return "Theme Blueprints File";
// }
//
// @Nullable
// @Override
// public Icon getIcon() {
// return GravIcons.ThemeBlueprints;
// }
//
// @Override
// public boolean needsFilename() {
// return false;
// }
//
// @Override
// public String getCorrespondingTemplateFile() {
// return "Grav Theme Blueprints";
// }
//
// @Override
// public String getDefaultFilename() {
// return "blueprints";
// }
// }
//
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/files/ThemeConfigurationFileType.java
// public class ThemeConfigurationFileType extends AbstractGravFileType {
// public static final LanguageFileType INSTANCE = new ThemeConfigurationFileType();
// private String defaultFileName;
//
// public ThemeConfigurationFileType() {
// super();
// }
//
// @NotNull
// @Override
// public String getName() {
// return "Theme configuration";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return "Theme Configuration File";
// }
//
// @Nullable
// @Override
// public Icon getIcon() {
// return GravIcons.ThemeConfiguration;
// }
//
// @Override
// public boolean needsFilename() {
// return false;
// }
//
// @Override
// public String getCorrespondingTemplateFile() {
// return "Grav Theme Configuration";
// }
//
// public void setDefaultFileName(String defaultFileName) {
// this.defaultFileName = defaultFileName;
// }
//
// @Override
// public String getDefaultFilename() {
// return this.defaultFileName;
// }
// }
//
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/listener/GravProjectComponent.java
// public class GravProjectComponent {
//
// /**
// * May be used to check whether a project is able to process Grav actions.
// * The settings are also consulted.
// *
// * @param project the project to check
// * @return {@code true} if project may/can use Grav plugin
// */
// public static boolean isEnabled(Project project) {
// if (project == null) return false;
// if (GravSdkType.isOperationBasicallyAvailableFor(project)) {
// GravProjectSettings settings = GravProjectSettings.getInstance(project);
// if (settings == null)
// return false;
// return settings.pluginEnabled;
// }
// return false;
// }
//
// /**
// * Sets for all modules of a project the module type to {@link GravModuleType}.
// *
// * @param project the project
// */
// public static synchronized void convertProjectToGravProject(@NotNull Project project) {
// if (!project.isDisposed()) {
// for (Module module : ModuleManager.getInstance(project).getModules()) {
// convertModuleToGravModule(module);
// }
// }
// }
//
// /**
// * Sets the module type for the given module to {@link GravModuleType}.
// *
// * @param module the module
// */
// public static synchronized void convertModuleToGravModule(@NotNull Module module) {
// if (!module.isDisposed())
// module.setModuleType(GravModuleType.ID);
// }
//
// /**
// * Returns the current project for which the plugin is enabled from all opened projects of the IDE
// *
// * @return current opened project or null, if none exists or plugin is not enabled
// */
// @Nullable
// public static Project getEnabledProject() {
// for (Project each : ProjectManager.getInstance().getOpenProjects()) {
// if (GravProjectComponent.isEnabled(each)) {
// return each;
// }
// }
// return null;
// }
//
// }
| import com.intellij.lang.Language;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.LanguageSubstitutor;
import net.offbeatpioneer.intellij.plugins.grav.extensions.files.ThemeBlueprintsFileType;
import net.offbeatpioneer.intellij.plugins.grav.extensions.files.ThemeConfigurationFileType;
import net.offbeatpioneer.intellij.plugins.grav.listener.GravProjectComponent;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.yaml.YAMLFileType; | package net.offbeatpioneer.intellij.plugins.grav.extensions.lang.substitutor;
/**
* File Language substitutor for non-Grav projects.
* <p>
* We don't want that *.yaml files are displayed as "Grav files" when the project isn't assigned the
* {@link net.offbeatpioneer.intellij.plugins.grav.extensions.module.GravModuleType}.
* In that case we display the default one.
*
* @author Dominik Grzelak
*/
public class GravFileLanguageSubstitutor extends LanguageSubstitutor {
@Override
public @Nullable Language getLanguage(@NotNull VirtualFile file, @NotNull Project project) { | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/files/ThemeBlueprintsFileType.java
// public class ThemeBlueprintsFileType extends AbstractGravFileType {
// public static final LanguageFileType INSTANCE = new ThemeBlueprintsFileType();
//
// public ThemeBlueprintsFileType() {
// super();
// }
//
// @NotNull
// @Override
// public String getName() {
// return "Theme blueprints";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return "Theme Blueprints File";
// }
//
// @Nullable
// @Override
// public Icon getIcon() {
// return GravIcons.ThemeBlueprints;
// }
//
// @Override
// public boolean needsFilename() {
// return false;
// }
//
// @Override
// public String getCorrespondingTemplateFile() {
// return "Grav Theme Blueprints";
// }
//
// @Override
// public String getDefaultFilename() {
// return "blueprints";
// }
// }
//
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/files/ThemeConfigurationFileType.java
// public class ThemeConfigurationFileType extends AbstractGravFileType {
// public static final LanguageFileType INSTANCE = new ThemeConfigurationFileType();
// private String defaultFileName;
//
// public ThemeConfigurationFileType() {
// super();
// }
//
// @NotNull
// @Override
// public String getName() {
// return "Theme configuration";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return "Theme Configuration File";
// }
//
// @Nullable
// @Override
// public Icon getIcon() {
// return GravIcons.ThemeConfiguration;
// }
//
// @Override
// public boolean needsFilename() {
// return false;
// }
//
// @Override
// public String getCorrespondingTemplateFile() {
// return "Grav Theme Configuration";
// }
//
// public void setDefaultFileName(String defaultFileName) {
// this.defaultFileName = defaultFileName;
// }
//
// @Override
// public String getDefaultFilename() {
// return this.defaultFileName;
// }
// }
//
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/listener/GravProjectComponent.java
// public class GravProjectComponent {
//
// /**
// * May be used to check whether a project is able to process Grav actions.
// * The settings are also consulted.
// *
// * @param project the project to check
// * @return {@code true} if project may/can use Grav plugin
// */
// public static boolean isEnabled(Project project) {
// if (project == null) return false;
// if (GravSdkType.isOperationBasicallyAvailableFor(project)) {
// GravProjectSettings settings = GravProjectSettings.getInstance(project);
// if (settings == null)
// return false;
// return settings.pluginEnabled;
// }
// return false;
// }
//
// /**
// * Sets for all modules of a project the module type to {@link GravModuleType}.
// *
// * @param project the project
// */
// public static synchronized void convertProjectToGravProject(@NotNull Project project) {
// if (!project.isDisposed()) {
// for (Module module : ModuleManager.getInstance(project).getModules()) {
// convertModuleToGravModule(module);
// }
// }
// }
//
// /**
// * Sets the module type for the given module to {@link GravModuleType}.
// *
// * @param module the module
// */
// public static synchronized void convertModuleToGravModule(@NotNull Module module) {
// if (!module.isDisposed())
// module.setModuleType(GravModuleType.ID);
// }
//
// /**
// * Returns the current project for which the plugin is enabled from all opened projects of the IDE
// *
// * @return current opened project or null, if none exists or plugin is not enabled
// */
// @Nullable
// public static Project getEnabledProject() {
// for (Project each : ProjectManager.getInstance().getOpenProjects()) {
// if (GravProjectComponent.isEnabled(each)) {
// return each;
// }
// }
// return null;
// }
//
// }
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/lang/substitutor/GravFileLanguageSubstitutor.java
import com.intellij.lang.Language;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.LanguageSubstitutor;
import net.offbeatpioneer.intellij.plugins.grav.extensions.files.ThemeBlueprintsFileType;
import net.offbeatpioneer.intellij.plugins.grav.extensions.files.ThemeConfigurationFileType;
import net.offbeatpioneer.intellij.plugins.grav.listener.GravProjectComponent;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.yaml.YAMLFileType;
package net.offbeatpioneer.intellij.plugins.grav.extensions.lang.substitutor;
/**
* File Language substitutor for non-Grav projects.
* <p>
* We don't want that *.yaml files are displayed as "Grav files" when the project isn't assigned the
* {@link net.offbeatpioneer.intellij.plugins.grav.extensions.module.GravModuleType}.
* In that case we display the default one.
*
* @author Dominik Grzelak
*/
public class GravFileLanguageSubstitutor extends LanguageSubstitutor {
@Override
public @Nullable Language getLanguage(@NotNull VirtualFile file, @NotNull Project project) { | if (!GravProjectComponent.isEnabled(project) && file.getName().endsWith(ThemeConfigurationFileType.DEFAULT_EXTENSION)) { |
PioBeat/GravSupport | src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/lang/substitutor/GravFileLanguageSubstitutor.java | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/files/ThemeBlueprintsFileType.java
// public class ThemeBlueprintsFileType extends AbstractGravFileType {
// public static final LanguageFileType INSTANCE = new ThemeBlueprintsFileType();
//
// public ThemeBlueprintsFileType() {
// super();
// }
//
// @NotNull
// @Override
// public String getName() {
// return "Theme blueprints";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return "Theme Blueprints File";
// }
//
// @Nullable
// @Override
// public Icon getIcon() {
// return GravIcons.ThemeBlueprints;
// }
//
// @Override
// public boolean needsFilename() {
// return false;
// }
//
// @Override
// public String getCorrespondingTemplateFile() {
// return "Grav Theme Blueprints";
// }
//
// @Override
// public String getDefaultFilename() {
// return "blueprints";
// }
// }
//
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/files/ThemeConfigurationFileType.java
// public class ThemeConfigurationFileType extends AbstractGravFileType {
// public static final LanguageFileType INSTANCE = new ThemeConfigurationFileType();
// private String defaultFileName;
//
// public ThemeConfigurationFileType() {
// super();
// }
//
// @NotNull
// @Override
// public String getName() {
// return "Theme configuration";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return "Theme Configuration File";
// }
//
// @Nullable
// @Override
// public Icon getIcon() {
// return GravIcons.ThemeConfiguration;
// }
//
// @Override
// public boolean needsFilename() {
// return false;
// }
//
// @Override
// public String getCorrespondingTemplateFile() {
// return "Grav Theme Configuration";
// }
//
// public void setDefaultFileName(String defaultFileName) {
// this.defaultFileName = defaultFileName;
// }
//
// @Override
// public String getDefaultFilename() {
// return this.defaultFileName;
// }
// }
//
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/listener/GravProjectComponent.java
// public class GravProjectComponent {
//
// /**
// * May be used to check whether a project is able to process Grav actions.
// * The settings are also consulted.
// *
// * @param project the project to check
// * @return {@code true} if project may/can use Grav plugin
// */
// public static boolean isEnabled(Project project) {
// if (project == null) return false;
// if (GravSdkType.isOperationBasicallyAvailableFor(project)) {
// GravProjectSettings settings = GravProjectSettings.getInstance(project);
// if (settings == null)
// return false;
// return settings.pluginEnabled;
// }
// return false;
// }
//
// /**
// * Sets for all modules of a project the module type to {@link GravModuleType}.
// *
// * @param project the project
// */
// public static synchronized void convertProjectToGravProject(@NotNull Project project) {
// if (!project.isDisposed()) {
// for (Module module : ModuleManager.getInstance(project).getModules()) {
// convertModuleToGravModule(module);
// }
// }
// }
//
// /**
// * Sets the module type for the given module to {@link GravModuleType}.
// *
// * @param module the module
// */
// public static synchronized void convertModuleToGravModule(@NotNull Module module) {
// if (!module.isDisposed())
// module.setModuleType(GravModuleType.ID);
// }
//
// /**
// * Returns the current project for which the plugin is enabled from all opened projects of the IDE
// *
// * @return current opened project or null, if none exists or plugin is not enabled
// */
// @Nullable
// public static Project getEnabledProject() {
// for (Project each : ProjectManager.getInstance().getOpenProjects()) {
// if (GravProjectComponent.isEnabled(each)) {
// return each;
// }
// }
// return null;
// }
//
// }
| import com.intellij.lang.Language;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.LanguageSubstitutor;
import net.offbeatpioneer.intellij.plugins.grav.extensions.files.ThemeBlueprintsFileType;
import net.offbeatpioneer.intellij.plugins.grav.extensions.files.ThemeConfigurationFileType;
import net.offbeatpioneer.intellij.plugins.grav.listener.GravProjectComponent;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.yaml.YAMLFileType; | package net.offbeatpioneer.intellij.plugins.grav.extensions.lang.substitutor;
/**
* File Language substitutor for non-Grav projects.
* <p>
* We don't want that *.yaml files are displayed as "Grav files" when the project isn't assigned the
* {@link net.offbeatpioneer.intellij.plugins.grav.extensions.module.GravModuleType}.
* In that case we display the default one.
*
* @author Dominik Grzelak
*/
public class GravFileLanguageSubstitutor extends LanguageSubstitutor {
@Override
public @Nullable Language getLanguage(@NotNull VirtualFile file, @NotNull Project project) { | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/files/ThemeBlueprintsFileType.java
// public class ThemeBlueprintsFileType extends AbstractGravFileType {
// public static final LanguageFileType INSTANCE = new ThemeBlueprintsFileType();
//
// public ThemeBlueprintsFileType() {
// super();
// }
//
// @NotNull
// @Override
// public String getName() {
// return "Theme blueprints";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return "Theme Blueprints File";
// }
//
// @Nullable
// @Override
// public Icon getIcon() {
// return GravIcons.ThemeBlueprints;
// }
//
// @Override
// public boolean needsFilename() {
// return false;
// }
//
// @Override
// public String getCorrespondingTemplateFile() {
// return "Grav Theme Blueprints";
// }
//
// @Override
// public String getDefaultFilename() {
// return "blueprints";
// }
// }
//
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/files/ThemeConfigurationFileType.java
// public class ThemeConfigurationFileType extends AbstractGravFileType {
// public static final LanguageFileType INSTANCE = new ThemeConfigurationFileType();
// private String defaultFileName;
//
// public ThemeConfigurationFileType() {
// super();
// }
//
// @NotNull
// @Override
// public String getName() {
// return "Theme configuration";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return "Theme Configuration File";
// }
//
// @Nullable
// @Override
// public Icon getIcon() {
// return GravIcons.ThemeConfiguration;
// }
//
// @Override
// public boolean needsFilename() {
// return false;
// }
//
// @Override
// public String getCorrespondingTemplateFile() {
// return "Grav Theme Configuration";
// }
//
// public void setDefaultFileName(String defaultFileName) {
// this.defaultFileName = defaultFileName;
// }
//
// @Override
// public String getDefaultFilename() {
// return this.defaultFileName;
// }
// }
//
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/listener/GravProjectComponent.java
// public class GravProjectComponent {
//
// /**
// * May be used to check whether a project is able to process Grav actions.
// * The settings are also consulted.
// *
// * @param project the project to check
// * @return {@code true} if project may/can use Grav plugin
// */
// public static boolean isEnabled(Project project) {
// if (project == null) return false;
// if (GravSdkType.isOperationBasicallyAvailableFor(project)) {
// GravProjectSettings settings = GravProjectSettings.getInstance(project);
// if (settings == null)
// return false;
// return settings.pluginEnabled;
// }
// return false;
// }
//
// /**
// * Sets for all modules of a project the module type to {@link GravModuleType}.
// *
// * @param project the project
// */
// public static synchronized void convertProjectToGravProject(@NotNull Project project) {
// if (!project.isDisposed()) {
// for (Module module : ModuleManager.getInstance(project).getModules()) {
// convertModuleToGravModule(module);
// }
// }
// }
//
// /**
// * Sets the module type for the given module to {@link GravModuleType}.
// *
// * @param module the module
// */
// public static synchronized void convertModuleToGravModule(@NotNull Module module) {
// if (!module.isDisposed())
// module.setModuleType(GravModuleType.ID);
// }
//
// /**
// * Returns the current project for which the plugin is enabled from all opened projects of the IDE
// *
// * @return current opened project or null, if none exists or plugin is not enabled
// */
// @Nullable
// public static Project getEnabledProject() {
// for (Project each : ProjectManager.getInstance().getOpenProjects()) {
// if (GravProjectComponent.isEnabled(each)) {
// return each;
// }
// }
// return null;
// }
//
// }
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/lang/substitutor/GravFileLanguageSubstitutor.java
import com.intellij.lang.Language;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.LanguageSubstitutor;
import net.offbeatpioneer.intellij.plugins.grav.extensions.files.ThemeBlueprintsFileType;
import net.offbeatpioneer.intellij.plugins.grav.extensions.files.ThemeConfigurationFileType;
import net.offbeatpioneer.intellij.plugins.grav.listener.GravProjectComponent;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.yaml.YAMLFileType;
package net.offbeatpioneer.intellij.plugins.grav.extensions.lang.substitutor;
/**
* File Language substitutor for non-Grav projects.
* <p>
* We don't want that *.yaml files are displayed as "Grav files" when the project isn't assigned the
* {@link net.offbeatpioneer.intellij.plugins.grav.extensions.module.GravModuleType}.
* In that case we display the default one.
*
* @author Dominik Grzelak
*/
public class GravFileLanguageSubstitutor extends LanguageSubstitutor {
@Override
public @Nullable Language getLanguage(@NotNull VirtualFile file, @NotNull Project project) { | if (!GravProjectComponent.isEnabled(project) && file.getName().endsWith(ThemeConfigurationFileType.DEFAULT_EXTENSION)) { |
PioBeat/GravSupport | src/main/java/net/offbeatpioneer/intellij/plugins/grav/helper/GravFileTemplateUtil.java | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/files/AbstractGravFileType.java
// public abstract class AbstractGravFileType extends LanguageFileType {
//
// public static final String DEFAULT_EXTENSION = "yaml";
//
// protected AbstractGravFileType() {
// super(YAMLLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public String getDefaultExtension() {
// return DEFAULT_EXTENSION;
// }
//
// public abstract boolean needsFilename();
//
// public abstract String getCorrespondingTemplateFile();
//
// public String getDefaultFilename() {
// return "untitled";
// }
// }
| import com.intellij.ide.fileTemplates.FileTemplate;
import com.intellij.ide.fileTemplates.FileTemplateManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ContainerUtil;
import com.jetbrains.twig.TwigFile;
import net.offbeatpioneer.intellij.plugins.grav.extensions.files.AbstractGravFileType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.yaml.psi.YAMLFile;
import org.jetbrains.yaml.psi.YAMLKeyValue;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Objects; | package net.offbeatpioneer.intellij.plugins.grav.helper;
/**
* @author Dominik Grzelak
*/
public class GravFileTemplateUtil {
private final static String GRAV_TEMPLATE_PREFIX = "Grav ";
public static List<FileTemplate> getAvailableThemeConfigurationTemplates(@NotNull Project project) {
return getApplicableTemplates(new Condition<FileTemplate>() {
@Override
public boolean value(FileTemplate fileTemplate) { | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/files/AbstractGravFileType.java
// public abstract class AbstractGravFileType extends LanguageFileType {
//
// public static final String DEFAULT_EXTENSION = "yaml";
//
// protected AbstractGravFileType() {
// super(YAMLLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public String getDefaultExtension() {
// return DEFAULT_EXTENSION;
// }
//
// public abstract boolean needsFilename();
//
// public abstract String getCorrespondingTemplateFile();
//
// public String getDefaultFilename() {
// return "untitled";
// }
// }
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/helper/GravFileTemplateUtil.java
import com.intellij.ide.fileTemplates.FileTemplate;
import com.intellij.ide.fileTemplates.FileTemplateManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ContainerUtil;
import com.jetbrains.twig.TwigFile;
import net.offbeatpioneer.intellij.plugins.grav.extensions.files.AbstractGravFileType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.yaml.psi.YAMLFile;
import org.jetbrains.yaml.psi.YAMLKeyValue;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
package net.offbeatpioneer.intellij.plugins.grav.helper;
/**
* @author Dominik Grzelak
*/
public class GravFileTemplateUtil {
private final static String GRAV_TEMPLATE_PREFIX = "Grav ";
public static List<FileTemplate> getAvailableThemeConfigurationTemplates(@NotNull Project project) {
return getApplicableTemplates(new Condition<FileTemplate>() {
@Override
public boolean value(FileTemplate fileTemplate) { | return AbstractGravFileType.DEFAULT_EXTENSION.equals(fileTemplate.getExtension()); |
PioBeat/GravSupport | src/main/java/net/offbeatpioneer/intellij/plugins/grav/editor/TranslationTableModel.java | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/helper/GravYAMLUtils.java
// public class GravYAMLUtils {
//
// public static String[] splitKey(String key) {
// return key.split("\\.");
// }
//
// public static List<String> splitKeyAsList(String key) {
// return new ArrayList<>(Arrays.asList(key.split("\\.")));
// }
//
// public static String prettyPrint(YAMLSequence yamlSequence) {
// StringBuilder builder = new StringBuilder("[");
// if (yamlSequence.getItems().size() != 0) {
// for (YAMLSequenceItem each : yamlSequence.getItems()) {
// builder.append(each.getText()).append(",");
// }
// int ix = builder.lastIndexOf(",");
// if (ix != -1)
// builder.deleteCharAt(ix);
// }
// builder.append("]");
// return builder.toString();
// }
//
// public static YAMLKeyValue getKeyValue(YAMLFile yamlFile, List<String> key) {
// YAMLDocument document = (YAMLDocument) yamlFile.getDocuments().get(0);
// YAMLMapping mapping = (YAMLMapping) ObjectUtils.tryCast(document.getTopLevelValue(), YAMLMapping.class);
// for (int i = 0; i < key.size(); ++i) {
// if (mapping == null) {
// return null;
// }
// YAMLKeyValue keyValue = null;
// for (YAMLKeyValue each : mapping.getKeyValues()) {
// if (each.getKeyText().equals(key.get(i))) {
// keyValue = each;
// break;
// }
// }
//
// if (keyValue == null || i + 1 == key.size()) {
// return keyValue;
// }
//
// mapping = ObjectUtils.tryCast(keyValue.getValue(), YAMLMapping.class);
// }
//
// throw new IllegalStateException("Should have returned from the loop");
// }
// }
| import net.offbeatpioneer.intellij.plugins.grav.helper.GravYAMLUtils;
import org.jetbrains.yaml.YAMLUtil;
import org.jetbrains.yaml.psi.*;
import javax.swing.table.AbstractTableModel;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap; | return this.availableKeys.size();
}
@Override
public int getColumnCount() {
return columnNames.size();
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
if (languages == null || languages.size() == 0) {
return null;
}
List<String> keys = getKeys(true);
switch (columnIndex) {
case 0:
return keys.get(rowIndex);
default:
Collection<YAMLKeyValue> collection = dataMap.get(languages.get(columnIndex - 1));
YAMLKeyValue correctKeyValue = findByKey(keys.get(rowIndex), collection);
if (collection == null || collection.size() == 0) {
return "";
}
YAMLFile yamlFile;
if (correctKeyValue == null) { //may be null because keys can be also written with dots and the above function couldn't find it
yamlFile = (YAMLFile) new ArrayList<>(collection).get(0).getContainingFile();
} else {
yamlFile = (YAMLFile) correctKeyValue.getContainingFile();
}
String keyValueText = prefixKey ? languages.get(columnIndex - 1) + "." + keys.get(rowIndex) : keys.get(rowIndex); | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/helper/GravYAMLUtils.java
// public class GravYAMLUtils {
//
// public static String[] splitKey(String key) {
// return key.split("\\.");
// }
//
// public static List<String> splitKeyAsList(String key) {
// return new ArrayList<>(Arrays.asList(key.split("\\.")));
// }
//
// public static String prettyPrint(YAMLSequence yamlSequence) {
// StringBuilder builder = new StringBuilder("[");
// if (yamlSequence.getItems().size() != 0) {
// for (YAMLSequenceItem each : yamlSequence.getItems()) {
// builder.append(each.getText()).append(",");
// }
// int ix = builder.lastIndexOf(",");
// if (ix != -1)
// builder.deleteCharAt(ix);
// }
// builder.append("]");
// return builder.toString();
// }
//
// public static YAMLKeyValue getKeyValue(YAMLFile yamlFile, List<String> key) {
// YAMLDocument document = (YAMLDocument) yamlFile.getDocuments().get(0);
// YAMLMapping mapping = (YAMLMapping) ObjectUtils.tryCast(document.getTopLevelValue(), YAMLMapping.class);
// for (int i = 0; i < key.size(); ++i) {
// if (mapping == null) {
// return null;
// }
// YAMLKeyValue keyValue = null;
// for (YAMLKeyValue each : mapping.getKeyValues()) {
// if (each.getKeyText().equals(key.get(i))) {
// keyValue = each;
// break;
// }
// }
//
// if (keyValue == null || i + 1 == key.size()) {
// return keyValue;
// }
//
// mapping = ObjectUtils.tryCast(keyValue.getValue(), YAMLMapping.class);
// }
//
// throw new IllegalStateException("Should have returned from the loop");
// }
// }
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/editor/TranslationTableModel.java
import net.offbeatpioneer.intellij.plugins.grav.helper.GravYAMLUtils;
import org.jetbrains.yaml.YAMLUtil;
import org.jetbrains.yaml.psi.*;
import javax.swing.table.AbstractTableModel;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
return this.availableKeys.size();
}
@Override
public int getColumnCount() {
return columnNames.size();
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
if (languages == null || languages.size() == 0) {
return null;
}
List<String> keys = getKeys(true);
switch (columnIndex) {
case 0:
return keys.get(rowIndex);
default:
Collection<YAMLKeyValue> collection = dataMap.get(languages.get(columnIndex - 1));
YAMLKeyValue correctKeyValue = findByKey(keys.get(rowIndex), collection);
if (collection == null || collection.size() == 0) {
return "";
}
YAMLFile yamlFile;
if (correctKeyValue == null) { //may be null because keys can be also written with dots and the above function couldn't find it
yamlFile = (YAMLFile) new ArrayList<>(collection).get(0).getContainingFile();
} else {
yamlFile = (YAMLFile) correctKeyValue.getContainingFile();
}
String keyValueText = prefixKey ? languages.get(columnIndex - 1) + "." + keys.get(rowIndex) : keys.get(rowIndex); | String[] keySplitted = GravYAMLUtils.splitKey(keyValueText); |
PioBeat/GravSupport | src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/icons/GravIconProvider.java | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/files/ThemeConfigurationFileType.java
// public class ThemeConfigurationFileType extends AbstractGravFileType {
// public static final LanguageFileType INSTANCE = new ThemeConfigurationFileType();
// private String defaultFileName;
//
// public ThemeConfigurationFileType() {
// super();
// }
//
// @NotNull
// @Override
// public String getName() {
// return "Theme configuration";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return "Theme Configuration File";
// }
//
// @Nullable
// @Override
// public Icon getIcon() {
// return GravIcons.ThemeConfiguration;
// }
//
// @Override
// public boolean needsFilename() {
// return false;
// }
//
// @Override
// public String getCorrespondingTemplateFile() {
// return "Grav Theme Configuration";
// }
//
// public void setDefaultFileName(String defaultFileName) {
// this.defaultFileName = defaultFileName;
// }
//
// @Override
// public String getDefaultFilename() {
// return this.defaultFileName;
// }
// }
//
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/listener/GravProjectComponent.java
// public class GravProjectComponent {
//
// /**
// * May be used to check whether a project is able to process Grav actions.
// * The settings are also consulted.
// *
// * @param project the project to check
// * @return {@code true} if project may/can use Grav plugin
// */
// public static boolean isEnabled(Project project) {
// if (project == null) return false;
// if (GravSdkType.isOperationBasicallyAvailableFor(project)) {
// GravProjectSettings settings = GravProjectSettings.getInstance(project);
// if (settings == null)
// return false;
// return settings.pluginEnabled;
// }
// return false;
// }
//
// /**
// * Sets for all modules of a project the module type to {@link GravModuleType}.
// *
// * @param project the project
// */
// public static synchronized void convertProjectToGravProject(@NotNull Project project) {
// if (!project.isDisposed()) {
// for (Module module : ModuleManager.getInstance(project).getModules()) {
// convertModuleToGravModule(module);
// }
// }
// }
//
// /**
// * Sets the module type for the given module to {@link GravModuleType}.
// *
// * @param module the module
// */
// public static synchronized void convertModuleToGravModule(@NotNull Module module) {
// if (!module.isDisposed())
// module.setModuleType(GravModuleType.ID);
// }
//
// /**
// * Returns the current project for which the plugin is enabled from all opened projects of the IDE
// *
// * @return current opened project or null, if none exists or plugin is not enabled
// */
// @Nullable
// public static Project getEnabledProject() {
// for (Project each : ProjectManager.getInstance().getOpenProjects()) {
// if (GravProjectComponent.isEnabled(each)) {
// return each;
// }
// }
// return null;
// }
//
// }
| import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import net.offbeatpioneer.intellij.plugins.grav.extensions.files.ThemeConfigurationFileType;
import net.offbeatpioneer.intellij.plugins.grav.listener.GravProjectComponent;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.yaml.YAMLFileType;
import org.jetbrains.yaml.YAMLLanguage;
import javax.swing.*; | package net.offbeatpioneer.intellij.plugins.grav.extensions.icons;
public class GravIconProvider extends com.intellij.ide.IconProvider {
// private static final boolean isPhpStorm = PlatformUtils.isPhpStorm();
@Override
public @Nullable Icon getIcon(@NotNull PsiElement element, int flags) {
// if (isPhpStorm) {
if (YAMLLanguage.INSTANCE.isKindOf(element.getLanguage())) { | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/files/ThemeConfigurationFileType.java
// public class ThemeConfigurationFileType extends AbstractGravFileType {
// public static final LanguageFileType INSTANCE = new ThemeConfigurationFileType();
// private String defaultFileName;
//
// public ThemeConfigurationFileType() {
// super();
// }
//
// @NotNull
// @Override
// public String getName() {
// return "Theme configuration";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return "Theme Configuration File";
// }
//
// @Nullable
// @Override
// public Icon getIcon() {
// return GravIcons.ThemeConfiguration;
// }
//
// @Override
// public boolean needsFilename() {
// return false;
// }
//
// @Override
// public String getCorrespondingTemplateFile() {
// return "Grav Theme Configuration";
// }
//
// public void setDefaultFileName(String defaultFileName) {
// this.defaultFileName = defaultFileName;
// }
//
// @Override
// public String getDefaultFilename() {
// return this.defaultFileName;
// }
// }
//
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/listener/GravProjectComponent.java
// public class GravProjectComponent {
//
// /**
// * May be used to check whether a project is able to process Grav actions.
// * The settings are also consulted.
// *
// * @param project the project to check
// * @return {@code true} if project may/can use Grav plugin
// */
// public static boolean isEnabled(Project project) {
// if (project == null) return false;
// if (GravSdkType.isOperationBasicallyAvailableFor(project)) {
// GravProjectSettings settings = GravProjectSettings.getInstance(project);
// if (settings == null)
// return false;
// return settings.pluginEnabled;
// }
// return false;
// }
//
// /**
// * Sets for all modules of a project the module type to {@link GravModuleType}.
// *
// * @param project the project
// */
// public static synchronized void convertProjectToGravProject(@NotNull Project project) {
// if (!project.isDisposed()) {
// for (Module module : ModuleManager.getInstance(project).getModules()) {
// convertModuleToGravModule(module);
// }
// }
// }
//
// /**
// * Sets the module type for the given module to {@link GravModuleType}.
// *
// * @param module the module
// */
// public static synchronized void convertModuleToGravModule(@NotNull Module module) {
// if (!module.isDisposed())
// module.setModuleType(GravModuleType.ID);
// }
//
// /**
// * Returns the current project for which the plugin is enabled from all opened projects of the IDE
// *
// * @return current opened project or null, if none exists or plugin is not enabled
// */
// @Nullable
// public static Project getEnabledProject() {
// for (Project each : ProjectManager.getInstance().getOpenProjects()) {
// if (GravProjectComponent.isEnabled(each)) {
// return each;
// }
// }
// return null;
// }
//
// }
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/icons/GravIconProvider.java
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import net.offbeatpioneer.intellij.plugins.grav.extensions.files.ThemeConfigurationFileType;
import net.offbeatpioneer.intellij.plugins.grav.listener.GravProjectComponent;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.yaml.YAMLFileType;
import org.jetbrains.yaml.YAMLLanguage;
import javax.swing.*;
package net.offbeatpioneer.intellij.plugins.grav.extensions.icons;
public class GravIconProvider extends com.intellij.ide.IconProvider {
// private static final boolean isPhpStorm = PlatformUtils.isPhpStorm();
@Override
public @Nullable Icon getIcon(@NotNull PsiElement element, int flags) {
// if (isPhpStorm) {
if (YAMLLanguage.INSTANCE.isKindOf(element.getLanguage())) { | if (!GravProjectComponent.isEnabled(element.getProject()) && |
PioBeat/GravSupport | src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/icons/GravIconProvider.java | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/files/ThemeConfigurationFileType.java
// public class ThemeConfigurationFileType extends AbstractGravFileType {
// public static final LanguageFileType INSTANCE = new ThemeConfigurationFileType();
// private String defaultFileName;
//
// public ThemeConfigurationFileType() {
// super();
// }
//
// @NotNull
// @Override
// public String getName() {
// return "Theme configuration";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return "Theme Configuration File";
// }
//
// @Nullable
// @Override
// public Icon getIcon() {
// return GravIcons.ThemeConfiguration;
// }
//
// @Override
// public boolean needsFilename() {
// return false;
// }
//
// @Override
// public String getCorrespondingTemplateFile() {
// return "Grav Theme Configuration";
// }
//
// public void setDefaultFileName(String defaultFileName) {
// this.defaultFileName = defaultFileName;
// }
//
// @Override
// public String getDefaultFilename() {
// return this.defaultFileName;
// }
// }
//
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/listener/GravProjectComponent.java
// public class GravProjectComponent {
//
// /**
// * May be used to check whether a project is able to process Grav actions.
// * The settings are also consulted.
// *
// * @param project the project to check
// * @return {@code true} if project may/can use Grav plugin
// */
// public static boolean isEnabled(Project project) {
// if (project == null) return false;
// if (GravSdkType.isOperationBasicallyAvailableFor(project)) {
// GravProjectSettings settings = GravProjectSettings.getInstance(project);
// if (settings == null)
// return false;
// return settings.pluginEnabled;
// }
// return false;
// }
//
// /**
// * Sets for all modules of a project the module type to {@link GravModuleType}.
// *
// * @param project the project
// */
// public static synchronized void convertProjectToGravProject(@NotNull Project project) {
// if (!project.isDisposed()) {
// for (Module module : ModuleManager.getInstance(project).getModules()) {
// convertModuleToGravModule(module);
// }
// }
// }
//
// /**
// * Sets the module type for the given module to {@link GravModuleType}.
// *
// * @param module the module
// */
// public static synchronized void convertModuleToGravModule(@NotNull Module module) {
// if (!module.isDisposed())
// module.setModuleType(GravModuleType.ID);
// }
//
// /**
// * Returns the current project for which the plugin is enabled from all opened projects of the IDE
// *
// * @return current opened project or null, if none exists or plugin is not enabled
// */
// @Nullable
// public static Project getEnabledProject() {
// for (Project each : ProjectManager.getInstance().getOpenProjects()) {
// if (GravProjectComponent.isEnabled(each)) {
// return each;
// }
// }
// return null;
// }
//
// }
| import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import net.offbeatpioneer.intellij.plugins.grav.extensions.files.ThemeConfigurationFileType;
import net.offbeatpioneer.intellij.plugins.grav.listener.GravProjectComponent;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.yaml.YAMLFileType;
import org.jetbrains.yaml.YAMLLanguage;
import javax.swing.*; | package net.offbeatpioneer.intellij.plugins.grav.extensions.icons;
public class GravIconProvider extends com.intellij.ide.IconProvider {
// private static final boolean isPhpStorm = PlatformUtils.isPhpStorm();
@Override
public @Nullable Icon getIcon(@NotNull PsiElement element, int flags) {
// if (isPhpStorm) {
if (YAMLLanguage.INSTANCE.isKindOf(element.getLanguage())) {
if (!GravProjectComponent.isEnabled(element.getProject()) &&
(element instanceof PsiFile) && | // Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/files/ThemeConfigurationFileType.java
// public class ThemeConfigurationFileType extends AbstractGravFileType {
// public static final LanguageFileType INSTANCE = new ThemeConfigurationFileType();
// private String defaultFileName;
//
// public ThemeConfigurationFileType() {
// super();
// }
//
// @NotNull
// @Override
// public String getName() {
// return "Theme configuration";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return "Theme Configuration File";
// }
//
// @Nullable
// @Override
// public Icon getIcon() {
// return GravIcons.ThemeConfiguration;
// }
//
// @Override
// public boolean needsFilename() {
// return false;
// }
//
// @Override
// public String getCorrespondingTemplateFile() {
// return "Grav Theme Configuration";
// }
//
// public void setDefaultFileName(String defaultFileName) {
// this.defaultFileName = defaultFileName;
// }
//
// @Override
// public String getDefaultFilename() {
// return this.defaultFileName;
// }
// }
//
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/listener/GravProjectComponent.java
// public class GravProjectComponent {
//
// /**
// * May be used to check whether a project is able to process Grav actions.
// * The settings are also consulted.
// *
// * @param project the project to check
// * @return {@code true} if project may/can use Grav plugin
// */
// public static boolean isEnabled(Project project) {
// if (project == null) return false;
// if (GravSdkType.isOperationBasicallyAvailableFor(project)) {
// GravProjectSettings settings = GravProjectSettings.getInstance(project);
// if (settings == null)
// return false;
// return settings.pluginEnabled;
// }
// return false;
// }
//
// /**
// * Sets for all modules of a project the module type to {@link GravModuleType}.
// *
// * @param project the project
// */
// public static synchronized void convertProjectToGravProject(@NotNull Project project) {
// if (!project.isDisposed()) {
// for (Module module : ModuleManager.getInstance(project).getModules()) {
// convertModuleToGravModule(module);
// }
// }
// }
//
// /**
// * Sets the module type for the given module to {@link GravModuleType}.
// *
// * @param module the module
// */
// public static synchronized void convertModuleToGravModule(@NotNull Module module) {
// if (!module.isDisposed())
// module.setModuleType(GravModuleType.ID);
// }
//
// /**
// * Returns the current project for which the plugin is enabled from all opened projects of the IDE
// *
// * @return current opened project or null, if none exists or plugin is not enabled
// */
// @Nullable
// public static Project getEnabledProject() {
// for (Project each : ProjectManager.getInstance().getOpenProjects()) {
// if (GravProjectComponent.isEnabled(each)) {
// return each;
// }
// }
// return null;
// }
//
// }
// Path: src/main/java/net/offbeatpioneer/intellij/plugins/grav/extensions/icons/GravIconProvider.java
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import net.offbeatpioneer.intellij.plugins.grav.extensions.files.ThemeConfigurationFileType;
import net.offbeatpioneer.intellij.plugins.grav.listener.GravProjectComponent;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.yaml.YAMLFileType;
import org.jetbrains.yaml.YAMLLanguage;
import javax.swing.*;
package net.offbeatpioneer.intellij.plugins.grav.extensions.icons;
public class GravIconProvider extends com.intellij.ide.IconProvider {
// private static final boolean isPhpStorm = PlatformUtils.isPhpStorm();
@Override
public @Nullable Icon getIcon(@NotNull PsiElement element, int flags) {
// if (isPhpStorm) {
if (YAMLLanguage.INSTANCE.isKindOf(element.getLanguage())) {
if (!GravProjectComponent.isEnabled(element.getProject()) &&
(element instanceof PsiFile) && | ((PsiFile) element).getName().endsWith(ThemeConfigurationFileType.DEFAULT_EXTENSION)) { |
rapidftr/RapidFTR-Android | RapidFTR-Android/src/main/java/com/rapidftr/task/SyncSingleRecordTask.java | // Path: RapidFTR-Android/src/main/java/com/rapidftr/model/User.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// @EqualsAndHashCode(of = {"userName", "verified"})
// @AllArgsConstructor(suppressConstructorProperties = true)
// public class User {
//
// public static final ObjectMapper JSON_MAPPER = new ObjectMapper();
// public static final String UNAUTHENTICATED_DB_KEY = "UNAUTHENTICATED_DB_KEY";
// public static final String UNAUTHENTICATED_DB_NAME = "DB-" + UNAUTHENTICATED_DB_KEY.hashCode();
//
// @Getter @JsonProperty("user_name")
// protected String userName;
//
// @Getter @Setter @JsonIgnore
// protected String password;
//
// @Getter @Setter @JsonProperty("verified")
// protected boolean verified;
//
// @Getter @Setter @JsonProperty("server_url")
// protected String serverUrl;
//
// @Getter @Setter @JsonProperty("db_key")
// protected String dbKey;
//
// @Getter @Setter @JsonProperty("organisation")
// protected String organisation;
//
// @Getter @Setter @JsonProperty("full_name")
// protected String fullName;
//
// @Getter @Setter @JsonProperty("unauthenticated_password")
// protected String unauthenticatedPassword;
//
// @Getter @Setter @JsonProperty("language")
// protected String language;
//
// protected User() {
// }
//
// public User(String userName) {
// this(userName, null, false, null, null, null, null, null, null);
// }
//
// public User(String userName, String password) {
// this(userName, password, false, null, null, null, null, null, null);
// }
//
// public User(String userName, String password, boolean authenticated) {
// this(userName, password, authenticated, null, null, null, null, null, null);
// }
//
// public User(String userName, String password, boolean authenticated, String serverUrl) {
// this(userName, password, authenticated, serverUrl, null, null, null, null, null);
// }
//
// public String getDbName() {
// return getDbKey() == null ? null : ("DB-" + getDbKey().hashCode());
// }
//
// public String asJSON() throws IOException {
// return getJsonMapper().writeValueAsString(this);
// }
//
// public String asEncryptedJSON() throws IOException, GeneralSecurityException {
// if (this.password == null)
// throw new GeneralSecurityException("User password not available to encrypt");
// else
// return EncryptionUtil.encrypt(this.password, this.userName, this.asJSON());
// }
//
// public User read(String json) throws IOException {
// getJsonMapper().readerForUpdating(this).readValue(json);
// return this;
// }
//
// public User load() throws GeneralSecurityException, IOException {
// String encryptedJson = getSharedPreferences().getString(prefKey(userName), null);
// String json = EncryptionUtil.decrypt(password, this.userName, encryptedJson);
// return read(json);
// }
//
// public void save() throws IOException, GeneralSecurityException {
// if (!this.isVerified()) {
// this.setUnauthenticatedPassword(this.getPassword());
// this.setDbKey(getUnauthenticatedDbKey());
// }
//
// getSharedPreferences().edit().putString(prefKey(userName), asEncryptedJSON()).commit();
// }
//
// public boolean exists() {
// return getSharedPreferences().contains(prefKey(userName));
// }
//
// protected ObjectMapper getJsonMapper() {
// return JSON_MAPPER;
// }
//
// public static User readFromJSON(String json) throws IOException {
// return new User().read(json);
// }
//
// protected static SharedPreferences getSharedPreferences() {
// return RapidFtrApplication.getApplicationInstance().getSharedPreferences();
// }
//
// protected static String getUnauthenticatedDbKey() {
// String dbKey = getSharedPreferences().getString(UNAUTHENTICATED_DB_KEY, null);
// return dbKey != null ? dbKey : createUnauthenticatedDbKey();
// }
//
// protected static String createUnauthenticatedDbKey() {
// String dbKey = UUID.randomUUID().toString();
// getSharedPreferences().edit().putString(UNAUTHENTICATED_DB_KEY, dbKey).commit();
// return dbKey;
// }
//
// protected static String prefKey(String userName) {
// return "user_" + userName;
// }
//
// }
| import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import com.google.inject.Inject;
import com.rapidftr.RapidFtrApplication;
import com.rapidftr.model.BaseModel;
import com.rapidftr.model.User;
import com.rapidftr.repository.Repository;
import com.rapidftr.service.SyncService;
import static com.rapidftr.RapidFtrApplication.APP_IDENTIFIER; | package com.rapidftr.task;
public class SyncSingleRecordTask extends AsyncTaskWithDialog<BaseModel, Void, Boolean> {
protected SyncService service;
protected Repository repository; | // Path: RapidFTR-Android/src/main/java/com/rapidftr/model/User.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// @EqualsAndHashCode(of = {"userName", "verified"})
// @AllArgsConstructor(suppressConstructorProperties = true)
// public class User {
//
// public static final ObjectMapper JSON_MAPPER = new ObjectMapper();
// public static final String UNAUTHENTICATED_DB_KEY = "UNAUTHENTICATED_DB_KEY";
// public static final String UNAUTHENTICATED_DB_NAME = "DB-" + UNAUTHENTICATED_DB_KEY.hashCode();
//
// @Getter @JsonProperty("user_name")
// protected String userName;
//
// @Getter @Setter @JsonIgnore
// protected String password;
//
// @Getter @Setter @JsonProperty("verified")
// protected boolean verified;
//
// @Getter @Setter @JsonProperty("server_url")
// protected String serverUrl;
//
// @Getter @Setter @JsonProperty("db_key")
// protected String dbKey;
//
// @Getter @Setter @JsonProperty("organisation")
// protected String organisation;
//
// @Getter @Setter @JsonProperty("full_name")
// protected String fullName;
//
// @Getter @Setter @JsonProperty("unauthenticated_password")
// protected String unauthenticatedPassword;
//
// @Getter @Setter @JsonProperty("language")
// protected String language;
//
// protected User() {
// }
//
// public User(String userName) {
// this(userName, null, false, null, null, null, null, null, null);
// }
//
// public User(String userName, String password) {
// this(userName, password, false, null, null, null, null, null, null);
// }
//
// public User(String userName, String password, boolean authenticated) {
// this(userName, password, authenticated, null, null, null, null, null, null);
// }
//
// public User(String userName, String password, boolean authenticated, String serverUrl) {
// this(userName, password, authenticated, serverUrl, null, null, null, null, null);
// }
//
// public String getDbName() {
// return getDbKey() == null ? null : ("DB-" + getDbKey().hashCode());
// }
//
// public String asJSON() throws IOException {
// return getJsonMapper().writeValueAsString(this);
// }
//
// public String asEncryptedJSON() throws IOException, GeneralSecurityException {
// if (this.password == null)
// throw new GeneralSecurityException("User password not available to encrypt");
// else
// return EncryptionUtil.encrypt(this.password, this.userName, this.asJSON());
// }
//
// public User read(String json) throws IOException {
// getJsonMapper().readerForUpdating(this).readValue(json);
// return this;
// }
//
// public User load() throws GeneralSecurityException, IOException {
// String encryptedJson = getSharedPreferences().getString(prefKey(userName), null);
// String json = EncryptionUtil.decrypt(password, this.userName, encryptedJson);
// return read(json);
// }
//
// public void save() throws IOException, GeneralSecurityException {
// if (!this.isVerified()) {
// this.setUnauthenticatedPassword(this.getPassword());
// this.setDbKey(getUnauthenticatedDbKey());
// }
//
// getSharedPreferences().edit().putString(prefKey(userName), asEncryptedJSON()).commit();
// }
//
// public boolean exists() {
// return getSharedPreferences().contains(prefKey(userName));
// }
//
// protected ObjectMapper getJsonMapper() {
// return JSON_MAPPER;
// }
//
// public static User readFromJSON(String json) throws IOException {
// return new User().read(json);
// }
//
// protected static SharedPreferences getSharedPreferences() {
// return RapidFtrApplication.getApplicationInstance().getSharedPreferences();
// }
//
// protected static String getUnauthenticatedDbKey() {
// String dbKey = getSharedPreferences().getString(UNAUTHENTICATED_DB_KEY, null);
// return dbKey != null ? dbKey : createUnauthenticatedDbKey();
// }
//
// protected static String createUnauthenticatedDbKey() {
// String dbKey = UUID.randomUUID().toString();
// getSharedPreferences().edit().putString(UNAUTHENTICATED_DB_KEY, dbKey).commit();
// return dbKey;
// }
//
// protected static String prefKey(String userName) {
// return "user_" + userName;
// }
//
// }
// Path: RapidFTR-Android/src/main/java/com/rapidftr/task/SyncSingleRecordTask.java
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import com.google.inject.Inject;
import com.rapidftr.RapidFtrApplication;
import com.rapidftr.model.BaseModel;
import com.rapidftr.model.User;
import com.rapidftr.repository.Repository;
import com.rapidftr.service.SyncService;
import static com.rapidftr.RapidFtrApplication.APP_IDENTIFIER;
package com.rapidftr.task;
public class SyncSingleRecordTask extends AsyncTaskWithDialog<BaseModel, Void, Boolean> {
protected SyncService service;
protected Repository repository; | protected User currentUser; |
rapidftr/RapidFTR-Android | RapidFTR-Android/src/main/java/com/rapidftr/service/GenericSyncService.java | // Path: RapidFTR-Android/src/main/java/com/rapidftr/utils/RapidFtrDateTime.java
// public class RapidFtrDateTime {
//
// private static final String defaultFormat = "yyyy-MM-dd HH:mm:ss";
// public static final String formatForChildRegister = "dd MMM yyyy";
//
// private Date dateTime;
//
// private RapidFtrDateTime() {
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
// this.dateTime = calendar.getTime();
// }
//
// public RapidFtrDateTime(int day, int month, int year) {
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
// calendar.set(year, month-1, day, 0, 0, 0);
// this.dateTime = calendar.getTime();
// }
//
// public static RapidFtrDateTime now() {
// return new RapidFtrDateTime();
// }
//
// public String defaultFormat(){
// SimpleDateFormat simpleDateFormat = getDefaultSimpleDateFormat();
// return simpleDateFormat.format(dateTime);
// }
//
// public static Calendar getDateTime(String dateTime) throws ParseException {
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
// SimpleDateFormat simpleDateFormat = getDefaultSimpleDateFormat();
// calendar.setTime(simpleDateFormat.parse(dateTime));
// return calendar;
// }
//
// private static SimpleDateFormat getDefaultSimpleDateFormat() {
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat(defaultFormat);
// simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
// return simpleDateFormat;
// }
//
// @Override
// public String toString() {
// return defaultFormat();
// }
// }
| import com.rapidftr.model.BaseModel;
import com.rapidftr.model.History;
import com.rapidftr.repository.Repository;
import com.rapidftr.utils.RapidFtrDateTime;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.IOException;
import java.io.SyncFailedException;
import java.util.HashMap;
import java.util.Map; | model.remove(History.HISTORIES);
repository.createOrUpdateWithoutHistory(model);
setMedia(model);
} catch (Exception e) {
model.setSynced(false);
model.setSyncLog(e.getMessage());
model.put("photo_keys", photoKeys);
model.put("audio_attachments", audioAttachments);
repository.createOrUpdateWithoutHistory(model);
repository.close();
throw new SyncFailedException(e.getMessage());
}
return model;
}
private void removeUnusedParametersBeforeSync(T model) {
photoKeys = (JSONArray) model.remove("photo_keys");
audioAttachments = model.remove("audio_attachments");
model.remove("synced");
model.remove("_rev");
}
private void setMedia(T model) throws IOException, JSONException {
mediaSyncHelper.setPhoto(model);
mediaSyncHelper.setAudio(model);
}
public static void setAttributes(BaseModel model) throws JSONException {
model.setSynced(true); | // Path: RapidFTR-Android/src/main/java/com/rapidftr/utils/RapidFtrDateTime.java
// public class RapidFtrDateTime {
//
// private static final String defaultFormat = "yyyy-MM-dd HH:mm:ss";
// public static final String formatForChildRegister = "dd MMM yyyy";
//
// private Date dateTime;
//
// private RapidFtrDateTime() {
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
// this.dateTime = calendar.getTime();
// }
//
// public RapidFtrDateTime(int day, int month, int year) {
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
// calendar.set(year, month-1, day, 0, 0, 0);
// this.dateTime = calendar.getTime();
// }
//
// public static RapidFtrDateTime now() {
// return new RapidFtrDateTime();
// }
//
// public String defaultFormat(){
// SimpleDateFormat simpleDateFormat = getDefaultSimpleDateFormat();
// return simpleDateFormat.format(dateTime);
// }
//
// public static Calendar getDateTime(String dateTime) throws ParseException {
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
// SimpleDateFormat simpleDateFormat = getDefaultSimpleDateFormat();
// calendar.setTime(simpleDateFormat.parse(dateTime));
// return calendar;
// }
//
// private static SimpleDateFormat getDefaultSimpleDateFormat() {
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat(defaultFormat);
// simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
// return simpleDateFormat;
// }
//
// @Override
// public String toString() {
// return defaultFormat();
// }
// }
// Path: RapidFTR-Android/src/main/java/com/rapidftr/service/GenericSyncService.java
import com.rapidftr.model.BaseModel;
import com.rapidftr.model.History;
import com.rapidftr.repository.Repository;
import com.rapidftr.utils.RapidFtrDateTime;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.IOException;
import java.io.SyncFailedException;
import java.util.HashMap;
import java.util.Map;
model.remove(History.HISTORIES);
repository.createOrUpdateWithoutHistory(model);
setMedia(model);
} catch (Exception e) {
model.setSynced(false);
model.setSyncLog(e.getMessage());
model.put("photo_keys", photoKeys);
model.put("audio_attachments", audioAttachments);
repository.createOrUpdateWithoutHistory(model);
repository.close();
throw new SyncFailedException(e.getMessage());
}
return model;
}
private void removeUnusedParametersBeforeSync(T model) {
photoKeys = (JSONArray) model.remove("photo_keys");
audioAttachments = model.remove("audio_attachments");
model.remove("synced");
model.remove("_rev");
}
private void setMedia(T model) throws IOException, JSONException {
mediaSyncHelper.setPhoto(model);
mediaSyncHelper.setAudio(model);
}
public static void setAttributes(BaseModel model) throws JSONException {
model.setSynced(true); | model.setLastSyncedAt(RapidFtrDateTime.now().defaultFormat()); |
rapidftr/RapidFTR-Android | RapidFTR-Android/src/test/java/com/rapidftr/forms/FormSectionTest.java | // Path: RapidFTR-Android/src/main/java/com/rapidftr/utils/ResourceLoader.java
// public class ResourceLoader {
//
// public static InputStream loadResourceFromClasspath(String resourceName) {
// return ResourceLoader.class.getClassLoader().getResourceAsStream(resourceName);
// }
//
// public static String loadResourceAsStringFromClasspath(String resourceName) throws IOException {
// @Cleanup InputStream inputStream = loadResourceFromClasspath(resourceName);
// return CharStreams.toString(new InputStreamReader(inputStream));
// }
//
// public static String loadStringFromRawResource(Context context, int resourceId) throws IOException {
// @Cleanup InputStream inputStream = context.getResources().openRawResource(resourceId);
// return CharStreams.toString(new InputStreamReader(inputStream));
// }
// }
| import com.fasterxml.jackson.databind.ObjectMapper;
import com.rapidftr.utils.ResourceLoader;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals; | package com.rapidftr.forms;
public class FormSectionTest {
private static final String NAME_FIELD_ID = "name";
private static final String RC_ID_NO_FIELD_ID = "rc_id_no";
private static final String PROTECTION_STATUS_FIELD_ID = "protection_status";
private static final String FTR_STATUS_FIELD_ID = "ftr_status";
private List<FormSection> formSections;
@Before
public void setUp() throws IOException {
this.formSections = loadFormSectionsFromClassPathResource();
}
@Test
public void shouldReturnSortedHighlightedFields() {
assertEquals(10, formSections.size());
assertEquals("Basic Identity", formSections.get(0).getName().get("en"));
List<FormField> formFields = formSections.get(0).getOrderedHighLightedFields();
assertEquals(4, formFields.size());
assertEquals(NAME_FIELD_ID, formFields.get(0).getId());
assertEquals(RC_ID_NO_FIELD_ID, formFields.get(1).getId());
assertEquals(PROTECTION_STATUS_FIELD_ID, formFields.get(2).getId());
assertEquals(FTR_STATUS_FIELD_ID, formFields.get(3).getId());
}
public static List<FormSection> loadFormSectionsFromClassPathResource() throws IOException { | // Path: RapidFTR-Android/src/main/java/com/rapidftr/utils/ResourceLoader.java
// public class ResourceLoader {
//
// public static InputStream loadResourceFromClasspath(String resourceName) {
// return ResourceLoader.class.getClassLoader().getResourceAsStream(resourceName);
// }
//
// public static String loadResourceAsStringFromClasspath(String resourceName) throws IOException {
// @Cleanup InputStream inputStream = loadResourceFromClasspath(resourceName);
// return CharStreams.toString(new InputStreamReader(inputStream));
// }
//
// public static String loadStringFromRawResource(Context context, int resourceId) throws IOException {
// @Cleanup InputStream inputStream = context.getResources().openRawResource(resourceId);
// return CharStreams.toString(new InputStreamReader(inputStream));
// }
// }
// Path: RapidFTR-Android/src/test/java/com/rapidftr/forms/FormSectionTest.java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rapidftr.utils.ResourceLoader;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals;
package com.rapidftr.forms;
public class FormSectionTest {
private static final String NAME_FIELD_ID = "name";
private static final String RC_ID_NO_FIELD_ID = "rc_id_no";
private static final String PROTECTION_STATUS_FIELD_ID = "protection_status";
private static final String FTR_STATUS_FIELD_ID = "ftr_status";
private List<FormSection> formSections;
@Before
public void setUp() throws IOException {
this.formSections = loadFormSectionsFromClassPathResource();
}
@Test
public void shouldReturnSortedHighlightedFields() {
assertEquals(10, formSections.size());
assertEquals("Basic Identity", formSections.get(0).getName().get("en"));
List<FormField> formFields = formSections.get(0).getOrderedHighLightedFields();
assertEquals(4, formFields.size());
assertEquals(NAME_FIELD_ID, formFields.get(0).getId());
assertEquals(RC_ID_NO_FIELD_ID, formFields.get(1).getId());
assertEquals(PROTECTION_STATUS_FIELD_ID, formFields.get(2).getId());
assertEquals(FTR_STATUS_FIELD_ID, formFields.get(3).getId());
}
public static List<FormSection> loadFormSectionsFromClassPathResource() throws IOException { | String json = ResourceLoader.loadResourceAsStringFromClasspath("form_sections.json"); |
rapidftr/RapidFTR-Android | RapidFTR-Android/src/main/java/com/rapidftr/adapter/pagination/PaginatedSearchResultsScrollListener.java | // Path: RapidFTR-Android/src/main/java/com/rapidftr/adapter/HighlightedFieldsViewAdapter.java
// public class HighlightedFieldsViewAdapter<T extends BaseModel> extends BaseModelViewAdapter<T> {
//
// protected Map<Integer, FormField> highlightedFields;
// private FormService formService;
// private Class<CollectionActivity> activityToLaunch;
// private final List<FormField> titleFields;
//
// public HighlightedFieldsViewAdapter(Context context, List<T> baseModels, String formName, Class<CollectionActivity> activityToLaunch) {
// super(context, R.layout.row_highlighted_fields, baseModels);
//
// formService = RapidFtrApplication.getApplicationInstance().getBean(FormService.class);
//
// List<FormField> fields = formService.getHighlightedFields(formName);
// titleFields = formService.getTitleFields(formName);
//
// highlightedFields = new TreeMap<Integer, FormField>();
// this.activityToLaunch = activityToLaunch;
//
// int counter = 0;
// for (FormField formField : fields) {
// int id = ++counter;
// highlightedFields.put(id, formField);
// }
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup viewGroup){
// View view = convertView;
// if (view == null) {
// LayoutInflater vi = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
// view = vi.inflate(textViewResourceId, null);
// }
//
// final T baseModel = objects.get(position) ;
// if (baseModel != null) {
// TextView uniqueIdView = (TextView) view.findViewById(R.id.row_child_unique_id);
//
// HighlightedFieldViewGroup highlightedFieldViewGroup = (HighlightedFieldViewGroup) view.findViewById(R.id.child_field_group);
// highlightedFieldViewGroup.prepare(baseModel, highlightedFields);
//
// ImageView imageView = (ImageView) view.findViewById(R.id.thumbnail);
// try {
// setFields(String.valueOf(buildTitle(baseModel)), uniqueIdView);
// assignThumbnail(baseModel, imageView);
//
// view.setOnClickListener(createClickListener(baseModel, activityToLaunch));
// } catch (JSONException e) {
// throw new RuntimeException(e);
// }
// }
// return view;
// }
//
// private String buildTitle(T baseModel) throws JSONException {
// if(titleFields.size() == 0) {
// return baseModel.getShortId();
// }
// StringBuilder titleBuilder = new StringBuilder();
// for (int i = 0; i < titleFields.size(); i++) {
// FormField titleField = titleFields.get(i);
// titleBuilder.append(baseModel.optString(titleField.getId()));
// if((i + 1) < titleFields.size()) {
// titleBuilder.append(" ");
// }
// }
// return String.format("%s (%s)", titleBuilder.toString(), baseModel.getShortId());
// }
// }
| import android.widget.AbsListView;
import com.rapidftr.adapter.HighlightedFieldsViewAdapter;
import com.rapidftr.model.Child;
import com.rapidftr.repository.ChildSearch;
import org.json.JSONException; | package com.rapidftr.adapter.pagination;
public class PaginatedSearchResultsScrollListener implements AbsListView.OnScrollListener {
private PaginatedSearchResultsScroller scroller;
public PaginatedSearchResultsScrollListener( | // Path: RapidFTR-Android/src/main/java/com/rapidftr/adapter/HighlightedFieldsViewAdapter.java
// public class HighlightedFieldsViewAdapter<T extends BaseModel> extends BaseModelViewAdapter<T> {
//
// protected Map<Integer, FormField> highlightedFields;
// private FormService formService;
// private Class<CollectionActivity> activityToLaunch;
// private final List<FormField> titleFields;
//
// public HighlightedFieldsViewAdapter(Context context, List<T> baseModels, String formName, Class<CollectionActivity> activityToLaunch) {
// super(context, R.layout.row_highlighted_fields, baseModels);
//
// formService = RapidFtrApplication.getApplicationInstance().getBean(FormService.class);
//
// List<FormField> fields = formService.getHighlightedFields(formName);
// titleFields = formService.getTitleFields(formName);
//
// highlightedFields = new TreeMap<Integer, FormField>();
// this.activityToLaunch = activityToLaunch;
//
// int counter = 0;
// for (FormField formField : fields) {
// int id = ++counter;
// highlightedFields.put(id, formField);
// }
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup viewGroup){
// View view = convertView;
// if (view == null) {
// LayoutInflater vi = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
// view = vi.inflate(textViewResourceId, null);
// }
//
// final T baseModel = objects.get(position) ;
// if (baseModel != null) {
// TextView uniqueIdView = (TextView) view.findViewById(R.id.row_child_unique_id);
//
// HighlightedFieldViewGroup highlightedFieldViewGroup = (HighlightedFieldViewGroup) view.findViewById(R.id.child_field_group);
// highlightedFieldViewGroup.prepare(baseModel, highlightedFields);
//
// ImageView imageView = (ImageView) view.findViewById(R.id.thumbnail);
// try {
// setFields(String.valueOf(buildTitle(baseModel)), uniqueIdView);
// assignThumbnail(baseModel, imageView);
//
// view.setOnClickListener(createClickListener(baseModel, activityToLaunch));
// } catch (JSONException e) {
// throw new RuntimeException(e);
// }
// }
// return view;
// }
//
// private String buildTitle(T baseModel) throws JSONException {
// if(titleFields.size() == 0) {
// return baseModel.getShortId();
// }
// StringBuilder titleBuilder = new StringBuilder();
// for (int i = 0; i < titleFields.size(); i++) {
// FormField titleField = titleFields.get(i);
// titleBuilder.append(baseModel.optString(titleField.getId()));
// if((i + 1) < titleFields.size()) {
// titleBuilder.append(" ");
// }
// }
// return String.format("%s (%s)", titleBuilder.toString(), baseModel.getShortId());
// }
// }
// Path: RapidFTR-Android/src/main/java/com/rapidftr/adapter/pagination/PaginatedSearchResultsScrollListener.java
import android.widget.AbsListView;
import com.rapidftr.adapter.HighlightedFieldsViewAdapter;
import com.rapidftr.model.Child;
import com.rapidftr.repository.ChildSearch;
import org.json.JSONException;
package com.rapidftr.adapter.pagination;
public class PaginatedSearchResultsScrollListener implements AbsListView.OnScrollListener {
private PaginatedSearchResultsScroller scroller;
public PaginatedSearchResultsScrollListener( | ChildSearch childSearch, HighlightedFieldsViewAdapter<Child> highlightedFieldsViewAdapter) { |
rapidftr/RapidFTR-Android | RapidFTR-Android/src/main/java/com/rapidftr/activity/ChangePasswordActivity.java | // Path: RapidFTR-Android/src/main/java/com/rapidftr/task/ChangePasswordTask.java
// public class ChangePasswordTask extends AsyncTask<String, Boolean, Boolean> {
//
// private ChangePasswordService changePasswordService;
// private String username;
// private RapidFtrApplication context;
// private Activity activity;
// private String currentPassword;
// private String newPassword;
//
//
// @Inject
// public ChangePasswordTask(ChangePasswordService changePasswordService, RapidFtrApplication context) {
// this.changePasswordService = changePasswordService;
// this.context = context;
// this.username = context.getCurrentUser().getUserName();
// }
//
// @Override
// protected Boolean doInBackground(String... params) {
// try {
// currentPassword = params[0];
// newPassword = params[1];
// HttpResponse response = changePasswordService.updatePassword(currentPassword, newPassword , params[2]);
// return response.getStatusLine().getStatusCode() == SC_OK;
// } catch (IOException e) {
// return false;
// }
// }
//
// @Override
// protected void onPostExecute(Boolean result) {
// super.onPostExecute(result);
// if (result) {
// activity.finish();
// try {
// User user = new User(this.username, this.currentPassword).load();
// user.setPassword(newPassword);
// user.save();
// } catch (Exception e) {
// Log.e("ChangePasswordTask",e.getMessage());
// }
// Toast.makeText(context, R.string.password_change_success, Toast.LENGTH_LONG).show();
// } else {
// Toast.makeText(context, R.string.password_change_failed, Toast.LENGTH_LONG).show();
// }
// }
//
//
// public void setActivity(Activity activity) {
// this.activity = activity;
// }
// }
| import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.rapidftr.R;
import com.rapidftr.RapidFtrApplication;
import com.rapidftr.task.ChangePasswordTask; | public void onClick(DialogInterface dialog, int id) {
cancelSync(RapidFtrApplication.getApplicationInstance());
sendRequestToServer(old,new_password,confirmation);
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {}
});
builder.create().show();
}
protected void cancelSync(RapidFtrApplication context) {
RapidFtrApplication.getApplicationInstance().cleanSyncTask();
}
protected boolean isPasswordSameAsConfirmPassword() {
if (!getEditText(R.id.new_password).equals(getEditText(R.id.new_password_confirm))) {
((EditText) findViewById(R.id.new_password_confirm)).setError(getString(R.string.password_mismatch));
return false;
}
return true;
}
protected boolean validatesPresenceOfMandatoryFields() {
return validateTextFieldNotEmpty(R.id.current_password, R.string.mandatory) &
validateTextFieldNotEmpty(R.id.new_password, R.string.mandatory) &
validateTextFieldNotEmpty(R.id.new_password_confirm, R.string.mandatory);
}
protected void sendRequestToServer(String old_password, String new_password, String confirmation) { | // Path: RapidFTR-Android/src/main/java/com/rapidftr/task/ChangePasswordTask.java
// public class ChangePasswordTask extends AsyncTask<String, Boolean, Boolean> {
//
// private ChangePasswordService changePasswordService;
// private String username;
// private RapidFtrApplication context;
// private Activity activity;
// private String currentPassword;
// private String newPassword;
//
//
// @Inject
// public ChangePasswordTask(ChangePasswordService changePasswordService, RapidFtrApplication context) {
// this.changePasswordService = changePasswordService;
// this.context = context;
// this.username = context.getCurrentUser().getUserName();
// }
//
// @Override
// protected Boolean doInBackground(String... params) {
// try {
// currentPassword = params[0];
// newPassword = params[1];
// HttpResponse response = changePasswordService.updatePassword(currentPassword, newPassword , params[2]);
// return response.getStatusLine().getStatusCode() == SC_OK;
// } catch (IOException e) {
// return false;
// }
// }
//
// @Override
// protected void onPostExecute(Boolean result) {
// super.onPostExecute(result);
// if (result) {
// activity.finish();
// try {
// User user = new User(this.username, this.currentPassword).load();
// user.setPassword(newPassword);
// user.save();
// } catch (Exception e) {
// Log.e("ChangePasswordTask",e.getMessage());
// }
// Toast.makeText(context, R.string.password_change_success, Toast.LENGTH_LONG).show();
// } else {
// Toast.makeText(context, R.string.password_change_failed, Toast.LENGTH_LONG).show();
// }
// }
//
//
// public void setActivity(Activity activity) {
// this.activity = activity;
// }
// }
// Path: RapidFTR-Android/src/main/java/com/rapidftr/activity/ChangePasswordActivity.java
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.rapidftr.R;
import com.rapidftr.RapidFtrApplication;
import com.rapidftr.task.ChangePasswordTask;
public void onClick(DialogInterface dialog, int id) {
cancelSync(RapidFtrApplication.getApplicationInstance());
sendRequestToServer(old,new_password,confirmation);
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {}
});
builder.create().show();
}
protected void cancelSync(RapidFtrApplication context) {
RapidFtrApplication.getApplicationInstance().cleanSyncTask();
}
protected boolean isPasswordSameAsConfirmPassword() {
if (!getEditText(R.id.new_password).equals(getEditText(R.id.new_password_confirm))) {
((EditText) findViewById(R.id.new_password_confirm)).setError(getString(R.string.password_mismatch));
return false;
}
return true;
}
protected boolean validatesPresenceOfMandatoryFields() {
return validateTextFieldNotEmpty(R.id.current_password, R.string.mandatory) &
validateTextFieldNotEmpty(R.id.new_password, R.string.mandatory) &
validateTextFieldNotEmpty(R.id.new_password_confirm, R.string.mandatory);
}
protected void sendRequestToServer(String old_password, String new_password, String confirmation) { | ChangePasswordTask task = inject(ChangePasswordTask.class); |
rapidftr/RapidFTR-Android | RapidFTR-Android/src/main/java/com/rapidftr/service/ChildSyncService.java | // Path: RapidFTR-Android/src/main/java/com/rapidftr/model/User.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// @EqualsAndHashCode(of = {"userName", "verified"})
// @AllArgsConstructor(suppressConstructorProperties = true)
// public class User {
//
// public static final ObjectMapper JSON_MAPPER = new ObjectMapper();
// public static final String UNAUTHENTICATED_DB_KEY = "UNAUTHENTICATED_DB_KEY";
// public static final String UNAUTHENTICATED_DB_NAME = "DB-" + UNAUTHENTICATED_DB_KEY.hashCode();
//
// @Getter @JsonProperty("user_name")
// protected String userName;
//
// @Getter @Setter @JsonIgnore
// protected String password;
//
// @Getter @Setter @JsonProperty("verified")
// protected boolean verified;
//
// @Getter @Setter @JsonProperty("server_url")
// protected String serverUrl;
//
// @Getter @Setter @JsonProperty("db_key")
// protected String dbKey;
//
// @Getter @Setter @JsonProperty("organisation")
// protected String organisation;
//
// @Getter @Setter @JsonProperty("full_name")
// protected String fullName;
//
// @Getter @Setter @JsonProperty("unauthenticated_password")
// protected String unauthenticatedPassword;
//
// @Getter @Setter @JsonProperty("language")
// protected String language;
//
// protected User() {
// }
//
// public User(String userName) {
// this(userName, null, false, null, null, null, null, null, null);
// }
//
// public User(String userName, String password) {
// this(userName, password, false, null, null, null, null, null, null);
// }
//
// public User(String userName, String password, boolean authenticated) {
// this(userName, password, authenticated, null, null, null, null, null, null);
// }
//
// public User(String userName, String password, boolean authenticated, String serverUrl) {
// this(userName, password, authenticated, serverUrl, null, null, null, null, null);
// }
//
// public String getDbName() {
// return getDbKey() == null ? null : ("DB-" + getDbKey().hashCode());
// }
//
// public String asJSON() throws IOException {
// return getJsonMapper().writeValueAsString(this);
// }
//
// public String asEncryptedJSON() throws IOException, GeneralSecurityException {
// if (this.password == null)
// throw new GeneralSecurityException("User password not available to encrypt");
// else
// return EncryptionUtil.encrypt(this.password, this.userName, this.asJSON());
// }
//
// public User read(String json) throws IOException {
// getJsonMapper().readerForUpdating(this).readValue(json);
// return this;
// }
//
// public User load() throws GeneralSecurityException, IOException {
// String encryptedJson = getSharedPreferences().getString(prefKey(userName), null);
// String json = EncryptionUtil.decrypt(password, this.userName, encryptedJson);
// return read(json);
// }
//
// public void save() throws IOException, GeneralSecurityException {
// if (!this.isVerified()) {
// this.setUnauthenticatedPassword(this.getPassword());
// this.setDbKey(getUnauthenticatedDbKey());
// }
//
// getSharedPreferences().edit().putString(prefKey(userName), asEncryptedJSON()).commit();
// }
//
// public boolean exists() {
// return getSharedPreferences().contains(prefKey(userName));
// }
//
// protected ObjectMapper getJsonMapper() {
// return JSON_MAPPER;
// }
//
// public static User readFromJSON(String json) throws IOException {
// return new User().read(json);
// }
//
// protected static SharedPreferences getSharedPreferences() {
// return RapidFtrApplication.getApplicationInstance().getSharedPreferences();
// }
//
// protected static String getUnauthenticatedDbKey() {
// String dbKey = getSharedPreferences().getString(UNAUTHENTICATED_DB_KEY, null);
// return dbKey != null ? dbKey : createUnauthenticatedDbKey();
// }
//
// protected static String createUnauthenticatedDbKey() {
// String dbKey = UUID.randomUUID().toString();
// getSharedPreferences().edit().putString(UNAUTHENTICATED_DB_KEY, dbKey).commit();
// return dbKey;
// }
//
// protected static String prefKey(String userName) {
// return "user_" + userName;
// }
//
// }
| import com.google.inject.Inject;
import com.rapidftr.R;
import com.rapidftr.RapidFtrApplication;
import com.rapidftr.model.Child;
import com.rapidftr.model.User;
import com.rapidftr.repository.ChildRepository;
import org.apache.http.HttpException;
import org.joda.time.DateTime;
import org.json.JSONException;
import java.io.IOException;
import java.util.List;
import static com.rapidftr.database.Database.ChildTableColumn.internal_id; | package com.rapidftr.service;
public class ChildSyncService implements SyncService<Child> {
public static final String CHILDREN_API_PATH = "/api/children";
public static final String CHILDREN_API_PARAMETER = "child";
public static final String UNVERIFIED_USER_CHILDREN_API_PATH = "/api/children/unverified";
private MediaSyncHelper mediaSyncHelper;
private RapidFtrApplication context;
private ChildRepository childRepository;
private static final int NOTIFICATION_ID = 1022;
private EntityHttpDao<Child> childEntityHttpDao;
@Inject
public ChildSyncService(RapidFtrApplication context, EntityHttpDao<Child> childHttpDao, ChildRepository childRepository) {
this.context = context;
this.childRepository = childRepository;
this.childEntityHttpDao = childHttpDao;
this.mediaSyncHelper = new MediaSyncHelper(childEntityHttpDao, context);
}
@Override | // Path: RapidFTR-Android/src/main/java/com/rapidftr/model/User.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// @EqualsAndHashCode(of = {"userName", "verified"})
// @AllArgsConstructor(suppressConstructorProperties = true)
// public class User {
//
// public static final ObjectMapper JSON_MAPPER = new ObjectMapper();
// public static final String UNAUTHENTICATED_DB_KEY = "UNAUTHENTICATED_DB_KEY";
// public static final String UNAUTHENTICATED_DB_NAME = "DB-" + UNAUTHENTICATED_DB_KEY.hashCode();
//
// @Getter @JsonProperty("user_name")
// protected String userName;
//
// @Getter @Setter @JsonIgnore
// protected String password;
//
// @Getter @Setter @JsonProperty("verified")
// protected boolean verified;
//
// @Getter @Setter @JsonProperty("server_url")
// protected String serverUrl;
//
// @Getter @Setter @JsonProperty("db_key")
// protected String dbKey;
//
// @Getter @Setter @JsonProperty("organisation")
// protected String organisation;
//
// @Getter @Setter @JsonProperty("full_name")
// protected String fullName;
//
// @Getter @Setter @JsonProperty("unauthenticated_password")
// protected String unauthenticatedPassword;
//
// @Getter @Setter @JsonProperty("language")
// protected String language;
//
// protected User() {
// }
//
// public User(String userName) {
// this(userName, null, false, null, null, null, null, null, null);
// }
//
// public User(String userName, String password) {
// this(userName, password, false, null, null, null, null, null, null);
// }
//
// public User(String userName, String password, boolean authenticated) {
// this(userName, password, authenticated, null, null, null, null, null, null);
// }
//
// public User(String userName, String password, boolean authenticated, String serverUrl) {
// this(userName, password, authenticated, serverUrl, null, null, null, null, null);
// }
//
// public String getDbName() {
// return getDbKey() == null ? null : ("DB-" + getDbKey().hashCode());
// }
//
// public String asJSON() throws IOException {
// return getJsonMapper().writeValueAsString(this);
// }
//
// public String asEncryptedJSON() throws IOException, GeneralSecurityException {
// if (this.password == null)
// throw new GeneralSecurityException("User password not available to encrypt");
// else
// return EncryptionUtil.encrypt(this.password, this.userName, this.asJSON());
// }
//
// public User read(String json) throws IOException {
// getJsonMapper().readerForUpdating(this).readValue(json);
// return this;
// }
//
// public User load() throws GeneralSecurityException, IOException {
// String encryptedJson = getSharedPreferences().getString(prefKey(userName), null);
// String json = EncryptionUtil.decrypt(password, this.userName, encryptedJson);
// return read(json);
// }
//
// public void save() throws IOException, GeneralSecurityException {
// if (!this.isVerified()) {
// this.setUnauthenticatedPassword(this.getPassword());
// this.setDbKey(getUnauthenticatedDbKey());
// }
//
// getSharedPreferences().edit().putString(prefKey(userName), asEncryptedJSON()).commit();
// }
//
// public boolean exists() {
// return getSharedPreferences().contains(prefKey(userName));
// }
//
// protected ObjectMapper getJsonMapper() {
// return JSON_MAPPER;
// }
//
// public static User readFromJSON(String json) throws IOException {
// return new User().read(json);
// }
//
// protected static SharedPreferences getSharedPreferences() {
// return RapidFtrApplication.getApplicationInstance().getSharedPreferences();
// }
//
// protected static String getUnauthenticatedDbKey() {
// String dbKey = getSharedPreferences().getString(UNAUTHENTICATED_DB_KEY, null);
// return dbKey != null ? dbKey : createUnauthenticatedDbKey();
// }
//
// protected static String createUnauthenticatedDbKey() {
// String dbKey = UUID.randomUUID().toString();
// getSharedPreferences().edit().putString(UNAUTHENTICATED_DB_KEY, dbKey).commit();
// return dbKey;
// }
//
// protected static String prefKey(String userName) {
// return "user_" + userName;
// }
//
// }
// Path: RapidFTR-Android/src/main/java/com/rapidftr/service/ChildSyncService.java
import com.google.inject.Inject;
import com.rapidftr.R;
import com.rapidftr.RapidFtrApplication;
import com.rapidftr.model.Child;
import com.rapidftr.model.User;
import com.rapidftr.repository.ChildRepository;
import org.apache.http.HttpException;
import org.joda.time.DateTime;
import org.json.JSONException;
import java.io.IOException;
import java.util.List;
import static com.rapidftr.database.Database.ChildTableColumn.internal_id;
package com.rapidftr.service;
public class ChildSyncService implements SyncService<Child> {
public static final String CHILDREN_API_PATH = "/api/children";
public static final String CHILDREN_API_PARAMETER = "child";
public static final String UNVERIFIED_USER_CHILDREN_API_PATH = "/api/children/unverified";
private MediaSyncHelper mediaSyncHelper;
private RapidFtrApplication context;
private ChildRepository childRepository;
private static final int NOTIFICATION_ID = 1022;
private EntityHttpDao<Child> childEntityHttpDao;
@Inject
public ChildSyncService(RapidFtrApplication context, EntityHttpDao<Child> childHttpDao, ChildRepository childRepository) {
this.context = context;
this.childRepository = childRepository;
this.childEntityHttpDao = childHttpDao;
this.mediaSyncHelper = new MediaSyncHelper(childEntityHttpDao, context);
}
@Override | public Child sync(Child child, User currentUser) throws IOException, JSONException { |
rapidftr/RapidFTR-Android | RapidFTR-Android/src/main/java/com/rapidftr/model/User.java | // Path: RapidFTR-Android/src/main/java/com/rapidftr/utils/EncryptionUtil.java
// public class EncryptionUtil {
//
// public static final Integer KEY_ITERATION_COUNT = 100;
// public static final Integer KEY_LENGTH = 128;
// public static final String SECRET_KEY_FACTORY_ALGORITHM = "PBKDF2WithHmacSHA1";
// public static final String SECRET_KEY_ALGORITHM = "AES";
// public static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
//
// /**
// * Reference: http://nelenkov.blogspot.in/2012/04/using-password-based-encryption-on.html
// * NOTE: Using the seed as both Salt & IV, since we have no space to store the Salt & IV in the encrypted data
// */
// public static Cipher getCipher(String password, String seed, int mode) throws IOException, GeneralSecurityException {
// byte salt[] = seed.getBytes();
// KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, KEY_ITERATION_COUNT, KEY_LENGTH);
// SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(SECRET_KEY_FACTORY_ALGORITHM);
// byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
// SecretKey key = new SecretKeySpec(keyBytes, SECRET_KEY_ALGORITHM);
//
// Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
// byte[] iv = paddedByteArray(seed, cipher.getBlockSize());
// IvParameterSpec ivSpec = new IvParameterSpec(iv);
// cipher.init(mode, key, ivSpec);
// return cipher;
// }
//
// public static String encrypt(String password, String seed, String textToEncrypt) throws GeneralSecurityException, IOException {
// Cipher cipher = getCipher(password, seed, Cipher.ENCRYPT_MODE);
// return Base64.encodeToString(cipher.doFinal(textToEncrypt.getBytes()), Base64.DEFAULT);
// }
//
// public static String decrypt(String password, String seed, String encrypted) throws GeneralSecurityException, IOException {
// Cipher cipher = getCipher(password, seed, Cipher.DECRYPT_MODE);
// return new String(cipher.doFinal(Base64.decode(encrypted, Base64.DEFAULT)));
// }
//
// public static OutputStream getCipherOutputStream(File file, String password) throws GeneralSecurityException, IOException {
// return new CipherOutputStream(new FileOutputStream(file), getCipher(password, file.getName(), Cipher.ENCRYPT_MODE));
// }
//
// public static InputStream getCipherInputStream(File file, String password) throws GeneralSecurityException, IOException {
// return new CipherInputStream(new FileInputStream(file), getCipher(password, file.getName(), Cipher.DECRYPT_MODE));
// }
//
// public static byte[] paddedByteArray(String str, int size) {
// byte[] dst = new byte[size];
// byte[] src = str.getBytes();
// int length = str.length() > size ? size : str.length();
// System.arraycopy(src, 0, dst, 0, length);
// return dst;
// }
//
// }
| import android.content.SharedPreferences;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rapidftr.RapidFtrApplication;
import com.rapidftr.utils.EncryptionUtil;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.UUID; | }
public User(String userName) {
this(userName, null, false, null, null, null, null, null, null);
}
public User(String userName, String password) {
this(userName, password, false, null, null, null, null, null, null);
}
public User(String userName, String password, boolean authenticated) {
this(userName, password, authenticated, null, null, null, null, null, null);
}
public User(String userName, String password, boolean authenticated, String serverUrl) {
this(userName, password, authenticated, serverUrl, null, null, null, null, null);
}
public String getDbName() {
return getDbKey() == null ? null : ("DB-" + getDbKey().hashCode());
}
public String asJSON() throws IOException {
return getJsonMapper().writeValueAsString(this);
}
public String asEncryptedJSON() throws IOException, GeneralSecurityException {
if (this.password == null)
throw new GeneralSecurityException("User password not available to encrypt");
else | // Path: RapidFTR-Android/src/main/java/com/rapidftr/utils/EncryptionUtil.java
// public class EncryptionUtil {
//
// public static final Integer KEY_ITERATION_COUNT = 100;
// public static final Integer KEY_LENGTH = 128;
// public static final String SECRET_KEY_FACTORY_ALGORITHM = "PBKDF2WithHmacSHA1";
// public static final String SECRET_KEY_ALGORITHM = "AES";
// public static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
//
// /**
// * Reference: http://nelenkov.blogspot.in/2012/04/using-password-based-encryption-on.html
// * NOTE: Using the seed as both Salt & IV, since we have no space to store the Salt & IV in the encrypted data
// */
// public static Cipher getCipher(String password, String seed, int mode) throws IOException, GeneralSecurityException {
// byte salt[] = seed.getBytes();
// KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, KEY_ITERATION_COUNT, KEY_LENGTH);
// SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(SECRET_KEY_FACTORY_ALGORITHM);
// byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
// SecretKey key = new SecretKeySpec(keyBytes, SECRET_KEY_ALGORITHM);
//
// Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
// byte[] iv = paddedByteArray(seed, cipher.getBlockSize());
// IvParameterSpec ivSpec = new IvParameterSpec(iv);
// cipher.init(mode, key, ivSpec);
// return cipher;
// }
//
// public static String encrypt(String password, String seed, String textToEncrypt) throws GeneralSecurityException, IOException {
// Cipher cipher = getCipher(password, seed, Cipher.ENCRYPT_MODE);
// return Base64.encodeToString(cipher.doFinal(textToEncrypt.getBytes()), Base64.DEFAULT);
// }
//
// public static String decrypt(String password, String seed, String encrypted) throws GeneralSecurityException, IOException {
// Cipher cipher = getCipher(password, seed, Cipher.DECRYPT_MODE);
// return new String(cipher.doFinal(Base64.decode(encrypted, Base64.DEFAULT)));
// }
//
// public static OutputStream getCipherOutputStream(File file, String password) throws GeneralSecurityException, IOException {
// return new CipherOutputStream(new FileOutputStream(file), getCipher(password, file.getName(), Cipher.ENCRYPT_MODE));
// }
//
// public static InputStream getCipherInputStream(File file, String password) throws GeneralSecurityException, IOException {
// return new CipherInputStream(new FileInputStream(file), getCipher(password, file.getName(), Cipher.DECRYPT_MODE));
// }
//
// public static byte[] paddedByteArray(String str, int size) {
// byte[] dst = new byte[size];
// byte[] src = str.getBytes();
// int length = str.length() > size ? size : str.length();
// System.arraycopy(src, 0, dst, 0, length);
// return dst;
// }
//
// }
// Path: RapidFTR-Android/src/main/java/com/rapidftr/model/User.java
import android.content.SharedPreferences;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rapidftr.RapidFtrApplication;
import com.rapidftr.utils.EncryptionUtil;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.UUID;
}
public User(String userName) {
this(userName, null, false, null, null, null, null, null, null);
}
public User(String userName, String password) {
this(userName, password, false, null, null, null, null, null, null);
}
public User(String userName, String password, boolean authenticated) {
this(userName, password, authenticated, null, null, null, null, null, null);
}
public User(String userName, String password, boolean authenticated, String serverUrl) {
this(userName, password, authenticated, serverUrl, null, null, null, null, null);
}
public String getDbName() {
return getDbKey() == null ? null : ("DB-" + getDbKey().hashCode());
}
public String asJSON() throws IOException {
return getJsonMapper().writeValueAsString(this);
}
public String asEncryptedJSON() throws IOException, GeneralSecurityException {
if (this.password == null)
throw new GeneralSecurityException("User password not available to encrypt");
else | return EncryptionUtil.encrypt(this.password, this.userName, this.asJSON()); |
rapidftr/RapidFTR-Android | RapidFTR-Android/src/main/java/com/rapidftr/utils/PhotoCaptureHelper.java | // Path: RapidFTR-Android/src/main/java/com/rapidftr/utils/EncryptionUtil.java
// public static InputStream getCipherInputStream(File file, String password) throws GeneralSecurityException, IOException {
// return new CipherInputStream(new FileInputStream(file), getCipher(password, file.getName(), Cipher.DECRYPT_MODE));
// }
//
// Path: RapidFTR-Android/src/main/java/com/rapidftr/utils/EncryptionUtil.java
// public static OutputStream getCipherOutputStream(File file, String password) throws GeneralSecurityException, IOException {
// return new CipherOutputStream(new FileOutputStream(file), getCipher(password, file.getName(), Cipher.ENCRYPT_MODE));
// }
| import android.content.ContentResolver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;
import com.rapidftr.R;
import com.rapidftr.RapidFtrApplication;
import lombok.Cleanup;
import java.io.*;
import java.security.GeneralSecurityException;
import java.util.Calendar;
import static android.graphics.BitmapFactory.decodeResource;
import static com.rapidftr.utils.EncryptionUtil.getCipherInputStream;
import static com.rapidftr.utils.EncryptionUtil.getCipherOutputStream; | Bitmap rotated = rotateBitmap(scaled, rotationDegree);
save(rotated, fileNameWithoutExtension, QUALITY, application.getCurrentUser().getDbKey());
scaled.recycle();
rotated.recycle();
}
protected Bitmap resizeImageTo(Bitmap image, int width, int height) {
return Bitmap.createScaledBitmap(image, width, height, false);
}
protected Bitmap scaleImageTo(Bitmap image, int maxWidth, int maxHeight) {
double givenWidth = image.getWidth(), givenHeight = image.getHeight();
double scaleRatio = 1.0;
if (givenWidth > maxWidth || givenHeight > maxHeight) {
if (givenWidth > givenHeight) {
scaleRatio = maxWidth / givenWidth;
} else {
scaleRatio = maxHeight / givenHeight;
}
}
return resizeImageTo(image, (int) (givenWidth * scaleRatio), (int) (givenHeight * scaleRatio));
}
protected void save(Bitmap bitmap, String fileNameWithoutExtension, int quality, String key) throws IOException, GeneralSecurityException {
fileNameWithoutExtension = fileNameWithoutExtension.contains(".jpg")? fileNameWithoutExtension : fileNameWithoutExtension + ".jpg";
File file = new File(getDir(), fileNameWithoutExtension);
if (!file.exists())
file.createNewFile(); | // Path: RapidFTR-Android/src/main/java/com/rapidftr/utils/EncryptionUtil.java
// public static InputStream getCipherInputStream(File file, String password) throws GeneralSecurityException, IOException {
// return new CipherInputStream(new FileInputStream(file), getCipher(password, file.getName(), Cipher.DECRYPT_MODE));
// }
//
// Path: RapidFTR-Android/src/main/java/com/rapidftr/utils/EncryptionUtil.java
// public static OutputStream getCipherOutputStream(File file, String password) throws GeneralSecurityException, IOException {
// return new CipherOutputStream(new FileOutputStream(file), getCipher(password, file.getName(), Cipher.ENCRYPT_MODE));
// }
// Path: RapidFTR-Android/src/main/java/com/rapidftr/utils/PhotoCaptureHelper.java
import android.content.ContentResolver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;
import com.rapidftr.R;
import com.rapidftr.RapidFtrApplication;
import lombok.Cleanup;
import java.io.*;
import java.security.GeneralSecurityException;
import java.util.Calendar;
import static android.graphics.BitmapFactory.decodeResource;
import static com.rapidftr.utils.EncryptionUtil.getCipherInputStream;
import static com.rapidftr.utils.EncryptionUtil.getCipherOutputStream;
Bitmap rotated = rotateBitmap(scaled, rotationDegree);
save(rotated, fileNameWithoutExtension, QUALITY, application.getCurrentUser().getDbKey());
scaled.recycle();
rotated.recycle();
}
protected Bitmap resizeImageTo(Bitmap image, int width, int height) {
return Bitmap.createScaledBitmap(image, width, height, false);
}
protected Bitmap scaleImageTo(Bitmap image, int maxWidth, int maxHeight) {
double givenWidth = image.getWidth(), givenHeight = image.getHeight();
double scaleRatio = 1.0;
if (givenWidth > maxWidth || givenHeight > maxHeight) {
if (givenWidth > givenHeight) {
scaleRatio = maxWidth / givenWidth;
} else {
scaleRatio = maxHeight / givenHeight;
}
}
return resizeImageTo(image, (int) (givenWidth * scaleRatio), (int) (givenHeight * scaleRatio));
}
protected void save(Bitmap bitmap, String fileNameWithoutExtension, int quality, String key) throws IOException, GeneralSecurityException {
fileNameWithoutExtension = fileNameWithoutExtension.contains(".jpg")? fileNameWithoutExtension : fileNameWithoutExtension + ".jpg";
File file = new File(getDir(), fileNameWithoutExtension);
if (!file.exists())
file.createNewFile(); | @Cleanup OutputStream outputStream = getCipherOutputStream(file, key); |
rapidftr/RapidFTR-Android | RapidFTR-Android/src/main/java/com/rapidftr/utils/PhotoCaptureHelper.java | // Path: RapidFTR-Android/src/main/java/com/rapidftr/utils/EncryptionUtil.java
// public static InputStream getCipherInputStream(File file, String password) throws GeneralSecurityException, IOException {
// return new CipherInputStream(new FileInputStream(file), getCipher(password, file.getName(), Cipher.DECRYPT_MODE));
// }
//
// Path: RapidFTR-Android/src/main/java/com/rapidftr/utils/EncryptionUtil.java
// public static OutputStream getCipherOutputStream(File file, String password) throws GeneralSecurityException, IOException {
// return new CipherOutputStream(new FileOutputStream(file), getCipher(password, file.getName(), Cipher.ENCRYPT_MODE));
// }
| import android.content.ContentResolver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;
import com.rapidftr.R;
import com.rapidftr.RapidFtrApplication;
import lombok.Cleanup;
import java.io.*;
import java.security.GeneralSecurityException;
import java.util.Calendar;
import static android.graphics.BitmapFactory.decodeResource;
import static com.rapidftr.utils.EncryptionUtil.getCipherInputStream;
import static com.rapidftr.utils.EncryptionUtil.getCipherOutputStream; | @Cleanup OutputStream outputStream = getCipherOutputStream(file, key);
saveImage(bitmap, outputStream, quality);
}
private void saveImage(Bitmap bitmap, OutputStream outputStream, int quality) {
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
}
public void saveThumbnail(Bitmap original, int rotationDegree, String fileNameWithoutExtension) throws IOException, GeneralSecurityException {
Bitmap scaled = resizeImageTo(original, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT);
Bitmap rotated = rotateBitmap(scaled, rotationDegree);
save(rotated, fileNameWithoutExtension + "_thumb", QUALITY, application.getCurrentUser().getDbKey());
}
public Bitmap loadThumbnail(String fileNameWithoutExtension) throws IOException, GeneralSecurityException {
return loadPhoto(fileNameWithoutExtension + "_thumb");
}
public Bitmap loadPhoto(String fileNameWithoutExtension) throws IOException, GeneralSecurityException {
@Cleanup InputStream inputStream = getDecodedImageStream(fileNameWithoutExtension);
return decodeStreamToBitMap(inputStream);
}
public InputStream getDecodedImageStream(String fileNameWithoutExtension) throws GeneralSecurityException, IOException {
return decodeImage(fileNameWithoutExtension, application.getCurrentUser().getDbKey());
}
private InputStream decodeImage(String fileNameWithoutExtension, String password) throws GeneralSecurityException, IOException {
File file = getFile(fileNameWithoutExtension, ".jpg"); | // Path: RapidFTR-Android/src/main/java/com/rapidftr/utils/EncryptionUtil.java
// public static InputStream getCipherInputStream(File file, String password) throws GeneralSecurityException, IOException {
// return new CipherInputStream(new FileInputStream(file), getCipher(password, file.getName(), Cipher.DECRYPT_MODE));
// }
//
// Path: RapidFTR-Android/src/main/java/com/rapidftr/utils/EncryptionUtil.java
// public static OutputStream getCipherOutputStream(File file, String password) throws GeneralSecurityException, IOException {
// return new CipherOutputStream(new FileOutputStream(file), getCipher(password, file.getName(), Cipher.ENCRYPT_MODE));
// }
// Path: RapidFTR-Android/src/main/java/com/rapidftr/utils/PhotoCaptureHelper.java
import android.content.ContentResolver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;
import com.rapidftr.R;
import com.rapidftr.RapidFtrApplication;
import lombok.Cleanup;
import java.io.*;
import java.security.GeneralSecurityException;
import java.util.Calendar;
import static android.graphics.BitmapFactory.decodeResource;
import static com.rapidftr.utils.EncryptionUtil.getCipherInputStream;
import static com.rapidftr.utils.EncryptionUtil.getCipherOutputStream;
@Cleanup OutputStream outputStream = getCipherOutputStream(file, key);
saveImage(bitmap, outputStream, quality);
}
private void saveImage(Bitmap bitmap, OutputStream outputStream, int quality) {
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
}
public void saveThumbnail(Bitmap original, int rotationDegree, String fileNameWithoutExtension) throws IOException, GeneralSecurityException {
Bitmap scaled = resizeImageTo(original, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT);
Bitmap rotated = rotateBitmap(scaled, rotationDegree);
save(rotated, fileNameWithoutExtension + "_thumb", QUALITY, application.getCurrentUser().getDbKey());
}
public Bitmap loadThumbnail(String fileNameWithoutExtension) throws IOException, GeneralSecurityException {
return loadPhoto(fileNameWithoutExtension + "_thumb");
}
public Bitmap loadPhoto(String fileNameWithoutExtension) throws IOException, GeneralSecurityException {
@Cleanup InputStream inputStream = getDecodedImageStream(fileNameWithoutExtension);
return decodeStreamToBitMap(inputStream);
}
public InputStream getDecodedImageStream(String fileNameWithoutExtension) throws GeneralSecurityException, IOException {
return decodeImage(fileNameWithoutExtension, application.getCurrentUser().getDbKey());
}
private InputStream decodeImage(String fileNameWithoutExtension, String password) throws GeneralSecurityException, IOException {
File file = getFile(fileNameWithoutExtension, ".jpg"); | return getCipherInputStream(file, password); |
rapidftr/RapidFTR-Android | RapidFTR-Android/src/main/java/com/rapidftr/adapter/pagination/ViewAllChildScroller.java | // Path: RapidFTR-Android/src/main/java/com/rapidftr/adapter/HighlightedFieldsViewAdapter.java
// public class HighlightedFieldsViewAdapter<T extends BaseModel> extends BaseModelViewAdapter<T> {
//
// protected Map<Integer, FormField> highlightedFields;
// private FormService formService;
// private Class<CollectionActivity> activityToLaunch;
// private final List<FormField> titleFields;
//
// public HighlightedFieldsViewAdapter(Context context, List<T> baseModels, String formName, Class<CollectionActivity> activityToLaunch) {
// super(context, R.layout.row_highlighted_fields, baseModels);
//
// formService = RapidFtrApplication.getApplicationInstance().getBean(FormService.class);
//
// List<FormField> fields = formService.getHighlightedFields(formName);
// titleFields = formService.getTitleFields(formName);
//
// highlightedFields = new TreeMap<Integer, FormField>();
// this.activityToLaunch = activityToLaunch;
//
// int counter = 0;
// for (FormField formField : fields) {
// int id = ++counter;
// highlightedFields.put(id, formField);
// }
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup viewGroup){
// View view = convertView;
// if (view == null) {
// LayoutInflater vi = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
// view = vi.inflate(textViewResourceId, null);
// }
//
// final T baseModel = objects.get(position) ;
// if (baseModel != null) {
// TextView uniqueIdView = (TextView) view.findViewById(R.id.row_child_unique_id);
//
// HighlightedFieldViewGroup highlightedFieldViewGroup = (HighlightedFieldViewGroup) view.findViewById(R.id.child_field_group);
// highlightedFieldViewGroup.prepare(baseModel, highlightedFields);
//
// ImageView imageView = (ImageView) view.findViewById(R.id.thumbnail);
// try {
// setFields(String.valueOf(buildTitle(baseModel)), uniqueIdView);
// assignThumbnail(baseModel, imageView);
//
// view.setOnClickListener(createClickListener(baseModel, activityToLaunch));
// } catch (JSONException e) {
// throw new RuntimeException(e);
// }
// }
// return view;
// }
//
// private String buildTitle(T baseModel) throws JSONException {
// if(titleFields.size() == 0) {
// return baseModel.getShortId();
// }
// StringBuilder titleBuilder = new StringBuilder();
// for (int i = 0; i < titleFields.size(); i++) {
// FormField titleField = titleFields.get(i);
// titleBuilder.append(baseModel.optString(titleField.getId()));
// if((i + 1) < titleFields.size()) {
// titleBuilder.append(" ");
// }
// }
// return String.format("%s (%s)", titleBuilder.toString(), baseModel.getShortId());
// }
// }
//
// Path: RapidFTR-Android/src/main/java/com/rapidftr/adapter/pagination/ViewAllChildrenPaginatedScrollListener.java
// public static final int DEFAULT_PAGE_SIZE = 30;
| import com.rapidftr.adapter.HighlightedFieldsViewAdapter;
import com.rapidftr.model.Child;
import com.rapidftr.repository.ChildRepository;
import org.json.JSONException;
import java.util.List;
import static com.rapidftr.adapter.pagination.ViewAllChildrenPaginatedScrollListener.DEFAULT_PAGE_SIZE; | package com.rapidftr.adapter.pagination;
public class ViewAllChildScroller extends Scroller {
private final ChildRepository repository; | // Path: RapidFTR-Android/src/main/java/com/rapidftr/adapter/HighlightedFieldsViewAdapter.java
// public class HighlightedFieldsViewAdapter<T extends BaseModel> extends BaseModelViewAdapter<T> {
//
// protected Map<Integer, FormField> highlightedFields;
// private FormService formService;
// private Class<CollectionActivity> activityToLaunch;
// private final List<FormField> titleFields;
//
// public HighlightedFieldsViewAdapter(Context context, List<T> baseModels, String formName, Class<CollectionActivity> activityToLaunch) {
// super(context, R.layout.row_highlighted_fields, baseModels);
//
// formService = RapidFtrApplication.getApplicationInstance().getBean(FormService.class);
//
// List<FormField> fields = formService.getHighlightedFields(formName);
// titleFields = formService.getTitleFields(formName);
//
// highlightedFields = new TreeMap<Integer, FormField>();
// this.activityToLaunch = activityToLaunch;
//
// int counter = 0;
// for (FormField formField : fields) {
// int id = ++counter;
// highlightedFields.put(id, formField);
// }
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup viewGroup){
// View view = convertView;
// if (view == null) {
// LayoutInflater vi = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
// view = vi.inflate(textViewResourceId, null);
// }
//
// final T baseModel = objects.get(position) ;
// if (baseModel != null) {
// TextView uniqueIdView = (TextView) view.findViewById(R.id.row_child_unique_id);
//
// HighlightedFieldViewGroup highlightedFieldViewGroup = (HighlightedFieldViewGroup) view.findViewById(R.id.child_field_group);
// highlightedFieldViewGroup.prepare(baseModel, highlightedFields);
//
// ImageView imageView = (ImageView) view.findViewById(R.id.thumbnail);
// try {
// setFields(String.valueOf(buildTitle(baseModel)), uniqueIdView);
// assignThumbnail(baseModel, imageView);
//
// view.setOnClickListener(createClickListener(baseModel, activityToLaunch));
// } catch (JSONException e) {
// throw new RuntimeException(e);
// }
// }
// return view;
// }
//
// private String buildTitle(T baseModel) throws JSONException {
// if(titleFields.size() == 0) {
// return baseModel.getShortId();
// }
// StringBuilder titleBuilder = new StringBuilder();
// for (int i = 0; i < titleFields.size(); i++) {
// FormField titleField = titleFields.get(i);
// titleBuilder.append(baseModel.optString(titleField.getId()));
// if((i + 1) < titleFields.size()) {
// titleBuilder.append(" ");
// }
// }
// return String.format("%s (%s)", titleBuilder.toString(), baseModel.getShortId());
// }
// }
//
// Path: RapidFTR-Android/src/main/java/com/rapidftr/adapter/pagination/ViewAllChildrenPaginatedScrollListener.java
// public static final int DEFAULT_PAGE_SIZE = 30;
// Path: RapidFTR-Android/src/main/java/com/rapidftr/adapter/pagination/ViewAllChildScroller.java
import com.rapidftr.adapter.HighlightedFieldsViewAdapter;
import com.rapidftr.model.Child;
import com.rapidftr.repository.ChildRepository;
import org.json.JSONException;
import java.util.List;
import static com.rapidftr.adapter.pagination.ViewAllChildrenPaginatedScrollListener.DEFAULT_PAGE_SIZE;
package com.rapidftr.adapter.pagination;
public class ViewAllChildScroller extends Scroller {
private final ChildRepository repository; | private final HighlightedFieldsViewAdapter<Child> adapter; |
rapidftr/RapidFTR-Android | RapidFTR-Android/src/main/java/com/rapidftr/adapter/pagination/ViewAllChildScroller.java | // Path: RapidFTR-Android/src/main/java/com/rapidftr/adapter/HighlightedFieldsViewAdapter.java
// public class HighlightedFieldsViewAdapter<T extends BaseModel> extends BaseModelViewAdapter<T> {
//
// protected Map<Integer, FormField> highlightedFields;
// private FormService formService;
// private Class<CollectionActivity> activityToLaunch;
// private final List<FormField> titleFields;
//
// public HighlightedFieldsViewAdapter(Context context, List<T> baseModels, String formName, Class<CollectionActivity> activityToLaunch) {
// super(context, R.layout.row_highlighted_fields, baseModels);
//
// formService = RapidFtrApplication.getApplicationInstance().getBean(FormService.class);
//
// List<FormField> fields = formService.getHighlightedFields(formName);
// titleFields = formService.getTitleFields(formName);
//
// highlightedFields = new TreeMap<Integer, FormField>();
// this.activityToLaunch = activityToLaunch;
//
// int counter = 0;
// for (FormField formField : fields) {
// int id = ++counter;
// highlightedFields.put(id, formField);
// }
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup viewGroup){
// View view = convertView;
// if (view == null) {
// LayoutInflater vi = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
// view = vi.inflate(textViewResourceId, null);
// }
//
// final T baseModel = objects.get(position) ;
// if (baseModel != null) {
// TextView uniqueIdView = (TextView) view.findViewById(R.id.row_child_unique_id);
//
// HighlightedFieldViewGroup highlightedFieldViewGroup = (HighlightedFieldViewGroup) view.findViewById(R.id.child_field_group);
// highlightedFieldViewGroup.prepare(baseModel, highlightedFields);
//
// ImageView imageView = (ImageView) view.findViewById(R.id.thumbnail);
// try {
// setFields(String.valueOf(buildTitle(baseModel)), uniqueIdView);
// assignThumbnail(baseModel, imageView);
//
// view.setOnClickListener(createClickListener(baseModel, activityToLaunch));
// } catch (JSONException e) {
// throw new RuntimeException(e);
// }
// }
// return view;
// }
//
// private String buildTitle(T baseModel) throws JSONException {
// if(titleFields.size() == 0) {
// return baseModel.getShortId();
// }
// StringBuilder titleBuilder = new StringBuilder();
// for (int i = 0; i < titleFields.size(); i++) {
// FormField titleField = titleFields.get(i);
// titleBuilder.append(baseModel.optString(titleField.getId()));
// if((i + 1) < titleFields.size()) {
// titleBuilder.append(" ");
// }
// }
// return String.format("%s (%s)", titleBuilder.toString(), baseModel.getShortId());
// }
// }
//
// Path: RapidFTR-Android/src/main/java/com/rapidftr/adapter/pagination/ViewAllChildrenPaginatedScrollListener.java
// public static final int DEFAULT_PAGE_SIZE = 30;
| import com.rapidftr.adapter.HighlightedFieldsViewAdapter;
import com.rapidftr.model.Child;
import com.rapidftr.repository.ChildRepository;
import org.json.JSONException;
import java.util.List;
import static com.rapidftr.adapter.pagination.ViewAllChildrenPaginatedScrollListener.DEFAULT_PAGE_SIZE; | package com.rapidftr.adapter.pagination;
public class ViewAllChildScroller extends Scroller {
private final ChildRepository repository;
private final HighlightedFieldsViewAdapter<Child> adapter;
public ViewAllChildScroller(ChildRepository repository, HighlightedFieldsViewAdapter<Child> adapter) {
super();
this.repository = repository;
this.adapter = adapter;
}
@Override
public void loadRecordsForNextPage() throws JSONException {
if (shouldQueryForMoreData()) { | // Path: RapidFTR-Android/src/main/java/com/rapidftr/adapter/HighlightedFieldsViewAdapter.java
// public class HighlightedFieldsViewAdapter<T extends BaseModel> extends BaseModelViewAdapter<T> {
//
// protected Map<Integer, FormField> highlightedFields;
// private FormService formService;
// private Class<CollectionActivity> activityToLaunch;
// private final List<FormField> titleFields;
//
// public HighlightedFieldsViewAdapter(Context context, List<T> baseModels, String formName, Class<CollectionActivity> activityToLaunch) {
// super(context, R.layout.row_highlighted_fields, baseModels);
//
// formService = RapidFtrApplication.getApplicationInstance().getBean(FormService.class);
//
// List<FormField> fields = formService.getHighlightedFields(formName);
// titleFields = formService.getTitleFields(formName);
//
// highlightedFields = new TreeMap<Integer, FormField>();
// this.activityToLaunch = activityToLaunch;
//
// int counter = 0;
// for (FormField formField : fields) {
// int id = ++counter;
// highlightedFields.put(id, formField);
// }
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup viewGroup){
// View view = convertView;
// if (view == null) {
// LayoutInflater vi = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
// view = vi.inflate(textViewResourceId, null);
// }
//
// final T baseModel = objects.get(position) ;
// if (baseModel != null) {
// TextView uniqueIdView = (TextView) view.findViewById(R.id.row_child_unique_id);
//
// HighlightedFieldViewGroup highlightedFieldViewGroup = (HighlightedFieldViewGroup) view.findViewById(R.id.child_field_group);
// highlightedFieldViewGroup.prepare(baseModel, highlightedFields);
//
// ImageView imageView = (ImageView) view.findViewById(R.id.thumbnail);
// try {
// setFields(String.valueOf(buildTitle(baseModel)), uniqueIdView);
// assignThumbnail(baseModel, imageView);
//
// view.setOnClickListener(createClickListener(baseModel, activityToLaunch));
// } catch (JSONException e) {
// throw new RuntimeException(e);
// }
// }
// return view;
// }
//
// private String buildTitle(T baseModel) throws JSONException {
// if(titleFields.size() == 0) {
// return baseModel.getShortId();
// }
// StringBuilder titleBuilder = new StringBuilder();
// for (int i = 0; i < titleFields.size(); i++) {
// FormField titleField = titleFields.get(i);
// titleBuilder.append(baseModel.optString(titleField.getId()));
// if((i + 1) < titleFields.size()) {
// titleBuilder.append(" ");
// }
// }
// return String.format("%s (%s)", titleBuilder.toString(), baseModel.getShortId());
// }
// }
//
// Path: RapidFTR-Android/src/main/java/com/rapidftr/adapter/pagination/ViewAllChildrenPaginatedScrollListener.java
// public static final int DEFAULT_PAGE_SIZE = 30;
// Path: RapidFTR-Android/src/main/java/com/rapidftr/adapter/pagination/ViewAllChildScroller.java
import com.rapidftr.adapter.HighlightedFieldsViewAdapter;
import com.rapidftr.model.Child;
import com.rapidftr.repository.ChildRepository;
import org.json.JSONException;
import java.util.List;
import static com.rapidftr.adapter.pagination.ViewAllChildrenPaginatedScrollListener.DEFAULT_PAGE_SIZE;
package com.rapidftr.adapter.pagination;
public class ViewAllChildScroller extends Scroller {
private final ChildRepository repository;
private final HighlightedFieldsViewAdapter<Child> adapter;
public ViewAllChildScroller(ChildRepository repository, HighlightedFieldsViewAdapter<Child> adapter) {
super();
this.repository = repository;
this.adapter = adapter;
}
@Override
public void loadRecordsForNextPage() throws JSONException {
if (shouldQueryForMoreData()) { | List<Child> records = repository.getRecordsBetween(adapter.getCount(), adapter.getCount() + DEFAULT_PAGE_SIZE); |
rapidftr/RapidFTR-Android | RapidFTR-Android/src/main/java/com/rapidftr/service/ChangePasswordService.java | // Path: RapidFTR-Android/src/main/java/com/rapidftr/utils/http/FluentResponse.java
// @RequiredArgsConstructor(suppressConstructorProperties = true)
// public class FluentResponse implements HttpResponse {
//
// protected
// @Delegate
// final HttpResponse response;
//
// public boolean isSuccess() {
// int statusCode = response.getStatusLine().getStatusCode();
// return statusCode >= 200 && statusCode < 300;
// }
//
// public FluentResponse ensureSuccess() throws HttpException {
// if (this.isSuccess()) {
// return this;
// } else {
// String message = "HTTP Request Failed";
// try {
// message = CharStreams.toString(new InputStreamReader(response.getEntity().getContent()));
// } catch (IOException e) {
// Log.e("HTTP Failure", e.getMessage(), e);
// }
// throw new HttpException(message);
// }
// }
//
// public boolean equals(Object other) {
// return response.equals(other);
// }
//
// }
| import com.google.inject.Inject;
import com.rapidftr.RapidFtrApplication;
import com.rapidftr.utils.http.FluentRequest;
import com.rapidftr.utils.http.FluentResponse;
import java.io.IOException; | package com.rapidftr.service;
public class ChangePasswordService {
private final RapidFtrApplication context;
private final FluentRequest fluentRequest;
@Inject
public ChangePasswordService(RapidFtrApplication context, FluentRequest fluentRequest) {
this.context = context;
this.fluentRequest = fluentRequest;
}
| // Path: RapidFTR-Android/src/main/java/com/rapidftr/utils/http/FluentResponse.java
// @RequiredArgsConstructor(suppressConstructorProperties = true)
// public class FluentResponse implements HttpResponse {
//
// protected
// @Delegate
// final HttpResponse response;
//
// public boolean isSuccess() {
// int statusCode = response.getStatusLine().getStatusCode();
// return statusCode >= 200 && statusCode < 300;
// }
//
// public FluentResponse ensureSuccess() throws HttpException {
// if (this.isSuccess()) {
// return this;
// } else {
// String message = "HTTP Request Failed";
// try {
// message = CharStreams.toString(new InputStreamReader(response.getEntity().getContent()));
// } catch (IOException e) {
// Log.e("HTTP Failure", e.getMessage(), e);
// }
// throw new HttpException(message);
// }
// }
//
// public boolean equals(Object other) {
// return response.equals(other);
// }
//
// }
// Path: RapidFTR-Android/src/main/java/com/rapidftr/service/ChangePasswordService.java
import com.google.inject.Inject;
import com.rapidftr.RapidFtrApplication;
import com.rapidftr.utils.http.FluentRequest;
import com.rapidftr.utils.http.FluentResponse;
import java.io.IOException;
package com.rapidftr.service;
public class ChangePasswordService {
private final RapidFtrApplication context;
private final FluentRequest fluentRequest;
@Inject
public ChangePasswordService(RapidFtrApplication context, FluentRequest fluentRequest) {
this.context = context;
this.fluentRequest = fluentRequest;
}
| public FluentResponse updatePassword(String old_password, String new_password, String new_password_confirmation) throws IOException { |
rapidftr/RapidFTR-Android | RapidFTR-Android/src/main/java/com/rapidftr/service/FormService.java | // Path: RapidFTR-Android/src/main/java/com/rapidftr/utils/ResourceLoader.java
// public class ResourceLoader {
//
// public static InputStream loadResourceFromClasspath(String resourceName) {
// return ResourceLoader.class.getClassLoader().getResourceAsStream(resourceName);
// }
//
// public static String loadResourceAsStringFromClasspath(String resourceName) throws IOException {
// @Cleanup InputStream inputStream = loadResourceFromClasspath(resourceName);
// return CharStreams.toString(new InputStreamReader(inputStream));
// }
//
// public static String loadStringFromRawResource(Context context, int resourceId) throws IOException {
// @Cleanup InputStream inputStream = context.getResources().openRawResource(resourceId);
// return CharStreams.toString(new InputStreamReader(inputStream));
// }
// }
//
// Path: RapidFTR-Android/src/main/java/com/rapidftr/utils/http/FluentResponse.java
// @RequiredArgsConstructor(suppressConstructorProperties = true)
// public class FluentResponse implements HttpResponse {
//
// protected
// @Delegate
// final HttpResponse response;
//
// public boolean isSuccess() {
// int statusCode = response.getStatusLine().getStatusCode();
// return statusCode >= 200 && statusCode < 300;
// }
//
// public FluentResponse ensureSuccess() throws HttpException {
// if (this.isSuccess()) {
// return this;
// } else {
// String message = "HTTP Request Failed";
// try {
// message = CharStreams.toString(new InputStreamReader(response.getEntity().getContent()));
// } catch (IOException e) {
// Log.e("HTTP Failure", e.getMessage(), e);
// }
// throw new HttpException(message);
// }
// }
//
// public boolean equals(Object other) {
// return response.equals(other);
// }
//
// }
| import android.util.Log;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.io.CharStreams;
import com.google.inject.Inject;
import com.rapidftr.R;
import com.rapidftr.RapidFtrApplication;
import com.rapidftr.forms.Form;
import com.rapidftr.forms.FormField;
import com.rapidftr.forms.FormSection;
import com.rapidftr.utils.ResourceLoader;
import com.rapidftr.utils.StringUtils;
import com.rapidftr.utils.http.FluentResponse;
import lombok.Cleanup;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
import static com.rapidftr.utils.http.FluentRequest.http; | package com.rapidftr.service;
public class FormService {
public static final String FORM_SECTIONS_PREF = "FORM_SECTION";
public static final String API_FORM_SECTIONS_PATH = "/api/form_sections";
private RapidFtrApplication context;
private Map<String, Form> formsMap = new HashMap<String, Form>();
@Inject
public FormService(RapidFtrApplication context) {
this.context = context;
try {
loadFormSections();
} catch (IOException e) {
Log.e(RapidFtrApplication.APP_IDENTIFIER, e.getMessage());
}
}
public void downloadPublishedFormSections() throws IOException { | // Path: RapidFTR-Android/src/main/java/com/rapidftr/utils/ResourceLoader.java
// public class ResourceLoader {
//
// public static InputStream loadResourceFromClasspath(String resourceName) {
// return ResourceLoader.class.getClassLoader().getResourceAsStream(resourceName);
// }
//
// public static String loadResourceAsStringFromClasspath(String resourceName) throws IOException {
// @Cleanup InputStream inputStream = loadResourceFromClasspath(resourceName);
// return CharStreams.toString(new InputStreamReader(inputStream));
// }
//
// public static String loadStringFromRawResource(Context context, int resourceId) throws IOException {
// @Cleanup InputStream inputStream = context.getResources().openRawResource(resourceId);
// return CharStreams.toString(new InputStreamReader(inputStream));
// }
// }
//
// Path: RapidFTR-Android/src/main/java/com/rapidftr/utils/http/FluentResponse.java
// @RequiredArgsConstructor(suppressConstructorProperties = true)
// public class FluentResponse implements HttpResponse {
//
// protected
// @Delegate
// final HttpResponse response;
//
// public boolean isSuccess() {
// int statusCode = response.getStatusLine().getStatusCode();
// return statusCode >= 200 && statusCode < 300;
// }
//
// public FluentResponse ensureSuccess() throws HttpException {
// if (this.isSuccess()) {
// return this;
// } else {
// String message = "HTTP Request Failed";
// try {
// message = CharStreams.toString(new InputStreamReader(response.getEntity().getContent()));
// } catch (IOException e) {
// Log.e("HTTP Failure", e.getMessage(), e);
// }
// throw new HttpException(message);
// }
// }
//
// public boolean equals(Object other) {
// return response.equals(other);
// }
//
// }
// Path: RapidFTR-Android/src/main/java/com/rapidftr/service/FormService.java
import android.util.Log;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.io.CharStreams;
import com.google.inject.Inject;
import com.rapidftr.R;
import com.rapidftr.RapidFtrApplication;
import com.rapidftr.forms.Form;
import com.rapidftr.forms.FormField;
import com.rapidftr.forms.FormSection;
import com.rapidftr.utils.ResourceLoader;
import com.rapidftr.utils.StringUtils;
import com.rapidftr.utils.http.FluentResponse;
import lombok.Cleanup;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
import static com.rapidftr.utils.http.FluentRequest.http;
package com.rapidftr.service;
public class FormService {
public static final String FORM_SECTIONS_PREF = "FORM_SECTION";
public static final String API_FORM_SECTIONS_PATH = "/api/form_sections";
private RapidFtrApplication context;
private Map<String, Form> formsMap = new HashMap<String, Form>();
@Inject
public FormService(RapidFtrApplication context) {
this.context = context;
try {
loadFormSections();
} catch (IOException e) {
Log.e(RapidFtrApplication.APP_IDENTIFIER, e.getMessage());
}
}
public void downloadPublishedFormSections() throws IOException { | FluentResponse formSectionsResponse = http() |
rapidftr/RapidFTR-Android | RapidFTR-Android/src/main/java/com/rapidftr/service/FormService.java | // Path: RapidFTR-Android/src/main/java/com/rapidftr/utils/ResourceLoader.java
// public class ResourceLoader {
//
// public static InputStream loadResourceFromClasspath(String resourceName) {
// return ResourceLoader.class.getClassLoader().getResourceAsStream(resourceName);
// }
//
// public static String loadResourceAsStringFromClasspath(String resourceName) throws IOException {
// @Cleanup InputStream inputStream = loadResourceFromClasspath(resourceName);
// return CharStreams.toString(new InputStreamReader(inputStream));
// }
//
// public static String loadStringFromRawResource(Context context, int resourceId) throws IOException {
// @Cleanup InputStream inputStream = context.getResources().openRawResource(resourceId);
// return CharStreams.toString(new InputStreamReader(inputStream));
// }
// }
//
// Path: RapidFTR-Android/src/main/java/com/rapidftr/utils/http/FluentResponse.java
// @RequiredArgsConstructor(suppressConstructorProperties = true)
// public class FluentResponse implements HttpResponse {
//
// protected
// @Delegate
// final HttpResponse response;
//
// public boolean isSuccess() {
// int statusCode = response.getStatusLine().getStatusCode();
// return statusCode >= 200 && statusCode < 300;
// }
//
// public FluentResponse ensureSuccess() throws HttpException {
// if (this.isSuccess()) {
// return this;
// } else {
// String message = "HTTP Request Failed";
// try {
// message = CharStreams.toString(new InputStreamReader(response.getEntity().getContent()));
// } catch (IOException e) {
// Log.e("HTTP Failure", e.getMessage(), e);
// }
// throw new HttpException(message);
// }
// }
//
// public boolean equals(Object other) {
// return response.equals(other);
// }
//
// }
| import android.util.Log;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.io.CharStreams;
import com.google.inject.Inject;
import com.rapidftr.R;
import com.rapidftr.RapidFtrApplication;
import com.rapidftr.forms.Form;
import com.rapidftr.forms.FormField;
import com.rapidftr.forms.FormSection;
import com.rapidftr.utils.ResourceLoader;
import com.rapidftr.utils.StringUtils;
import com.rapidftr.utils.http.FluentResponse;
import lombok.Cleanup;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
import static com.rapidftr.utils.http.FluentRequest.http; | }
}
protected void saveFormSections(String formSectionJson) throws IOException {
context.getSharedPreferences().edit().putString(FORM_SECTIONS_PREF, formSectionJson).commit();
}
protected void loadFormSections() throws IOException {
String formSections = context.getSharedPreferences().getString(FORM_SECTIONS_PREF, null);
if (formSections == null) {
formSections = loadDefaultFormSections();
}
parseFormSections(formSections);
}
private void parseFormSections(String formSections) throws IOException {
if (StringUtils.isNotEmpty(formSections)) {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = objectMapper.readTree(formSections);
Iterator<Map.Entry<String, JsonNode>> childNodes = rootNode.fields();
while (childNodes.hasNext()) {
Map.Entry<String, JsonNode> entry = childNodes.next();
Form form = new Form(entry.getKey(), new ArrayList<FormSection>(Arrays.asList(objectMapper.readValue(entry.getValue().toString(), FormSection[].class))));
this.formsMap.put(entry.getKey(), form);
}
}
}
private String loadDefaultFormSections() throws IOException { | // Path: RapidFTR-Android/src/main/java/com/rapidftr/utils/ResourceLoader.java
// public class ResourceLoader {
//
// public static InputStream loadResourceFromClasspath(String resourceName) {
// return ResourceLoader.class.getClassLoader().getResourceAsStream(resourceName);
// }
//
// public static String loadResourceAsStringFromClasspath(String resourceName) throws IOException {
// @Cleanup InputStream inputStream = loadResourceFromClasspath(resourceName);
// return CharStreams.toString(new InputStreamReader(inputStream));
// }
//
// public static String loadStringFromRawResource(Context context, int resourceId) throws IOException {
// @Cleanup InputStream inputStream = context.getResources().openRawResource(resourceId);
// return CharStreams.toString(new InputStreamReader(inputStream));
// }
// }
//
// Path: RapidFTR-Android/src/main/java/com/rapidftr/utils/http/FluentResponse.java
// @RequiredArgsConstructor(suppressConstructorProperties = true)
// public class FluentResponse implements HttpResponse {
//
// protected
// @Delegate
// final HttpResponse response;
//
// public boolean isSuccess() {
// int statusCode = response.getStatusLine().getStatusCode();
// return statusCode >= 200 && statusCode < 300;
// }
//
// public FluentResponse ensureSuccess() throws HttpException {
// if (this.isSuccess()) {
// return this;
// } else {
// String message = "HTTP Request Failed";
// try {
// message = CharStreams.toString(new InputStreamReader(response.getEntity().getContent()));
// } catch (IOException e) {
// Log.e("HTTP Failure", e.getMessage(), e);
// }
// throw new HttpException(message);
// }
// }
//
// public boolean equals(Object other) {
// return response.equals(other);
// }
//
// }
// Path: RapidFTR-Android/src/main/java/com/rapidftr/service/FormService.java
import android.util.Log;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.io.CharStreams;
import com.google.inject.Inject;
import com.rapidftr.R;
import com.rapidftr.RapidFtrApplication;
import com.rapidftr.forms.Form;
import com.rapidftr.forms.FormField;
import com.rapidftr.forms.FormSection;
import com.rapidftr.utils.ResourceLoader;
import com.rapidftr.utils.StringUtils;
import com.rapidftr.utils.http.FluentResponse;
import lombok.Cleanup;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
import static com.rapidftr.utils.http.FluentRequest.http;
}
}
protected void saveFormSections(String formSectionJson) throws IOException {
context.getSharedPreferences().edit().putString(FORM_SECTIONS_PREF, formSectionJson).commit();
}
protected void loadFormSections() throws IOException {
String formSections = context.getSharedPreferences().getString(FORM_SECTIONS_PREF, null);
if (formSections == null) {
formSections = loadDefaultFormSections();
}
parseFormSections(formSections);
}
private void parseFormSections(String formSections) throws IOException {
if (StringUtils.isNotEmpty(formSections)) {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = objectMapper.readTree(formSections);
Iterator<Map.Entry<String, JsonNode>> childNodes = rootNode.fields();
while (childNodes.hasNext()) {
Map.Entry<String, JsonNode> entry = childNodes.next();
Form form = new Form(entry.getKey(), new ArrayList<FormSection>(Arrays.asList(objectMapper.readValue(entry.getValue().toString(), FormSection[].class))));
this.formsMap.put(entry.getKey(), form);
}
}
}
private String loadDefaultFormSections() throws IOException { | return ResourceLoader.loadStringFromRawResource(context, R.raw.default_form_sections); |
rapidftr/RapidFTR-Android | RapidFTR-Android/src/main/java/com/rapidftr/view/fields/AudioUploadBox.java | // Path: RapidFTR-Android/src/main/java/com/rapidftr/activity/CollectionActivity.java
// public abstract class CollectionActivity extends RapidFtrActivity {
// @Getter
// @Setter
// MediaRecorder mediaRecorder;
// @Getter
// @Setter
// MediaPlayer mediaPlayer;
//
// protected FormService formService;
// protected List<FormSection> formSections;
//
// protected abstract BaseModel getModel();
//
// protected abstract Boolean getEditable();
//
// protected Spinner getSpinner() {
// return ((Spinner) findViewById(R.id.spinner));
// }
//
// protected ViewPager getPager() {
// return (ViewPager) findViewById(R.id.pager);
// }
//
// protected CollectionActivity() {
// super();
// }
//
// protected void initializePager() {
// getPager().setAdapter(new FormSectionPagerAdapter(formSections, getModel(), getEditable()));
// getPager().setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
// @Override
// public void onPageSelected(int position) {
// getSpinner().setSelection(position);
// }
//
// });
// }
//
// protected void initializeSpinner() {
// getSpinner().setAdapter(new ArrayAdapter<FormSection>(this, android.R.layout.simple_spinner_item, formSections));
// getSpinner().setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
// @Override
// public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// getPager().setCurrentItem(position);
// }
//
// public void onNothingSelected(AdapterView<?> parent) {
// }
// });
// }
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// try {
// formService = inject(FormService.class);
// initializeView();
//
// try {
// initializeData(savedInstanceState);
// } catch (IOException e) {
// e.printStackTrace();
// }
// initializePager();
// initializeSpinner();
// initializeLabels();
// } catch (JSONException e) {
// throw new RuntimeException(e);
// }
// }
//
// protected void initializeLabels() throws JSONException {
// }
//
// ;
//
// protected abstract void initializeView();
//
// protected abstract void initializeData(Bundle savedInstanceState) throws JSONException, IOException;
//
// protected void setLabel(int label) {
// ((Button) findViewById(R.id.submit)).setText(label);
// }
//
// protected void setTitle(String title) {
// ((TextView) findViewById(R.id.title)).setText(title);
// }
//
// protected FormService getFormService() {
// if (this.formService == null)
// formService = inject(FormService.class);
//
// return formService;
// }
// }
| import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.rapidftr.R;
import com.rapidftr.RapidFtrApplication;
import com.rapidftr.activity.CollectionActivity;
import com.rapidftr.activity.RapidFtrActivity;
import com.rapidftr.utils.AudioCaptureHelper;
import org.json.JSONException;
import java.io.IOException;
import java.util.Date; | package com.rapidftr.view.fields;
public class AudioUploadBox extends BaseView {
private MediaRecorder mRecorder;
private MediaPlayer mPlayer;
private String fileName; | // Path: RapidFTR-Android/src/main/java/com/rapidftr/activity/CollectionActivity.java
// public abstract class CollectionActivity extends RapidFtrActivity {
// @Getter
// @Setter
// MediaRecorder mediaRecorder;
// @Getter
// @Setter
// MediaPlayer mediaPlayer;
//
// protected FormService formService;
// protected List<FormSection> formSections;
//
// protected abstract BaseModel getModel();
//
// protected abstract Boolean getEditable();
//
// protected Spinner getSpinner() {
// return ((Spinner) findViewById(R.id.spinner));
// }
//
// protected ViewPager getPager() {
// return (ViewPager) findViewById(R.id.pager);
// }
//
// protected CollectionActivity() {
// super();
// }
//
// protected void initializePager() {
// getPager().setAdapter(new FormSectionPagerAdapter(formSections, getModel(), getEditable()));
// getPager().setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
// @Override
// public void onPageSelected(int position) {
// getSpinner().setSelection(position);
// }
//
// });
// }
//
// protected void initializeSpinner() {
// getSpinner().setAdapter(new ArrayAdapter<FormSection>(this, android.R.layout.simple_spinner_item, formSections));
// getSpinner().setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
// @Override
// public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// getPager().setCurrentItem(position);
// }
//
// public void onNothingSelected(AdapterView<?> parent) {
// }
// });
// }
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// try {
// formService = inject(FormService.class);
// initializeView();
//
// try {
// initializeData(savedInstanceState);
// } catch (IOException e) {
// e.printStackTrace();
// }
// initializePager();
// initializeSpinner();
// initializeLabels();
// } catch (JSONException e) {
// throw new RuntimeException(e);
// }
// }
//
// protected void initializeLabels() throws JSONException {
// }
//
// ;
//
// protected abstract void initializeView();
//
// protected abstract void initializeData(Bundle savedInstanceState) throws JSONException, IOException;
//
// protected void setLabel(int label) {
// ((Button) findViewById(R.id.submit)).setText(label);
// }
//
// protected void setTitle(String title) {
// ((TextView) findViewById(R.id.title)).setText(title);
// }
//
// protected FormService getFormService() {
// if (this.formService == null)
// formService = inject(FormService.class);
//
// return formService;
// }
// }
// Path: RapidFTR-Android/src/main/java/com/rapidftr/view/fields/AudioUploadBox.java
import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.rapidftr.R;
import com.rapidftr.RapidFtrApplication;
import com.rapidftr.activity.CollectionActivity;
import com.rapidftr.activity.RapidFtrActivity;
import com.rapidftr.utils.AudioCaptureHelper;
import org.json.JSONException;
import java.io.IOException;
import java.util.Date;
package com.rapidftr.view.fields;
public class AudioUploadBox extends BaseView {
private MediaRecorder mRecorder;
private MediaPlayer mPlayer;
private String fileName; | private CollectionActivity context; |
rapidftr/RapidFTR-Android | RapidFTR-Android/src/main/java/com/rapidftr/adapter/FormSectionPagerAdapter.java | // Path: RapidFTR-Android/src/main/java/com/rapidftr/view/DefaultFormSectionView.java
// public class DefaultFormSectionView extends ScrollView implements FormSectionView {
//
// private FormSection formSection;
//
// private BaseModel model;
//
// public DefaultFormSectionView(Context context) {
// super(context);
// inflateView(context);
// }
//
// public DefaultFormSectionView(Context context, AttributeSet attrs) {
// super(context, attrs);
// inflateView(context);
// }
//
// public DefaultFormSectionView(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// inflateView(context);
// }
//
//
// private void inflateView(Context context) {
// LayoutInflater layoutInflater = LayoutInflater.from(context);
// layoutInflater.inflate(R.layout.form_section, this);
// }
//
// protected TextView getLabel() {
// return (TextView) findViewById(R.id.label);
// }
//
// protected TextView getHelpText() {
// return (TextView) findViewById(R.id.help_text);
// }
//
// protected LinearLayout getContainer() {
// return (LinearLayout) findViewById(R.id.container);
// }
//
// public void initialize(FormSection formSection, BaseModel model) {
// if (this.formSection != null)
// throw new IllegalArgumentException("Form section is already initialized!");
//
// this.formSection = formSection;
// this.model = model;
// this.initialize();
// }
//
// protected void initialize() {
// getLabel().setText(formSection.getLocalizedName());
// getHelpText().setText(formSection.getLocalizedHelpText());
// for (FormField field : formSection.getFields()) {
// BaseView fieldView = createFormField(field);
// if (fieldView != null)
// getContainer().addView(fieldView);
// }
// }
//
// protected int getFieldLayoutId(String fieldType) {
// return getResources().getIdentifier("form_" + fieldType, "layout", "com.rapidftr");
// }
//
// protected BaseView createFormField(FormField field) {
// int resourceId = getFieldLayoutId(field.getType());
//
// if (resourceId > 0) {
// BaseView fieldView = (BaseView) LayoutInflater.from(getContext()).inflate(resourceId, null);
// fieldView.initialize(field, model);
//
// return fieldView;
// }
//
// return null;
// }
//
// @Override
// public void setEnabled(boolean enabled) {
// super.setEnabled(enabled);
//
// LinearLayout container = getContainer();
// for (int i = 0, j = container.getChildCount(); i < j; i++)
// container.getChildAt(i).setEnabled(enabled);
// }
// }
| import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import com.rapidftr.forms.FormSection;
import com.rapidftr.model.BaseModel;
import com.rapidftr.view.DefaultFormSectionView;
import lombok.AllArgsConstructor;
import java.util.List; | package com.rapidftr.adapter;
@AllArgsConstructor(suppressConstructorProperties = true)
public class FormSectionPagerAdapter extends PagerAdapter {
protected List<FormSection> formSections;
protected BaseModel baseModel;
protected boolean editable;
@Override
public int getCount() {
return formSections.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return (view == object);
}
@Override
public Object instantiateItem(ViewGroup container, int position) { | // Path: RapidFTR-Android/src/main/java/com/rapidftr/view/DefaultFormSectionView.java
// public class DefaultFormSectionView extends ScrollView implements FormSectionView {
//
// private FormSection formSection;
//
// private BaseModel model;
//
// public DefaultFormSectionView(Context context) {
// super(context);
// inflateView(context);
// }
//
// public DefaultFormSectionView(Context context, AttributeSet attrs) {
// super(context, attrs);
// inflateView(context);
// }
//
// public DefaultFormSectionView(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// inflateView(context);
// }
//
//
// private void inflateView(Context context) {
// LayoutInflater layoutInflater = LayoutInflater.from(context);
// layoutInflater.inflate(R.layout.form_section, this);
// }
//
// protected TextView getLabel() {
// return (TextView) findViewById(R.id.label);
// }
//
// protected TextView getHelpText() {
// return (TextView) findViewById(R.id.help_text);
// }
//
// protected LinearLayout getContainer() {
// return (LinearLayout) findViewById(R.id.container);
// }
//
// public void initialize(FormSection formSection, BaseModel model) {
// if (this.formSection != null)
// throw new IllegalArgumentException("Form section is already initialized!");
//
// this.formSection = formSection;
// this.model = model;
// this.initialize();
// }
//
// protected void initialize() {
// getLabel().setText(formSection.getLocalizedName());
// getHelpText().setText(formSection.getLocalizedHelpText());
// for (FormField field : formSection.getFields()) {
// BaseView fieldView = createFormField(field);
// if (fieldView != null)
// getContainer().addView(fieldView);
// }
// }
//
// protected int getFieldLayoutId(String fieldType) {
// return getResources().getIdentifier("form_" + fieldType, "layout", "com.rapidftr");
// }
//
// protected BaseView createFormField(FormField field) {
// int resourceId = getFieldLayoutId(field.getType());
//
// if (resourceId > 0) {
// BaseView fieldView = (BaseView) LayoutInflater.from(getContext()).inflate(resourceId, null);
// fieldView.initialize(field, model);
//
// return fieldView;
// }
//
// return null;
// }
//
// @Override
// public void setEnabled(boolean enabled) {
// super.setEnabled(enabled);
//
// LinearLayout container = getContainer();
// for (int i = 0, j = container.getChildCount(); i < j; i++)
// container.getChildAt(i).setEnabled(enabled);
// }
// }
// Path: RapidFTR-Android/src/main/java/com/rapidftr/adapter/FormSectionPagerAdapter.java
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import com.rapidftr.forms.FormSection;
import com.rapidftr.model.BaseModel;
import com.rapidftr.view.DefaultFormSectionView;
import lombok.AllArgsConstructor;
import java.util.List;
package com.rapidftr.adapter;
@AllArgsConstructor(suppressConstructorProperties = true)
public class FormSectionPagerAdapter extends PagerAdapter {
protected List<FormSection> formSections;
protected BaseModel baseModel;
protected boolean editable;
@Override
public int getCount() {
return formSections.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return (view == object);
}
@Override
public Object instantiateItem(ViewGroup container, int position) { | DefaultFormSectionView view = createFormSectionView(container); |
rapidftr/RapidFTR-Android | RapidFTR-Android/src/main/java/com/rapidftr/adapter/pagination/ViewAllChildrenPaginatedScrollListener.java | // Path: RapidFTR-Android/src/main/java/com/rapidftr/adapter/HighlightedFieldsViewAdapter.java
// public class HighlightedFieldsViewAdapter<T extends BaseModel> extends BaseModelViewAdapter<T> {
//
// protected Map<Integer, FormField> highlightedFields;
// private FormService formService;
// private Class<CollectionActivity> activityToLaunch;
// private final List<FormField> titleFields;
//
// public HighlightedFieldsViewAdapter(Context context, List<T> baseModels, String formName, Class<CollectionActivity> activityToLaunch) {
// super(context, R.layout.row_highlighted_fields, baseModels);
//
// formService = RapidFtrApplication.getApplicationInstance().getBean(FormService.class);
//
// List<FormField> fields = formService.getHighlightedFields(formName);
// titleFields = formService.getTitleFields(formName);
//
// highlightedFields = new TreeMap<Integer, FormField>();
// this.activityToLaunch = activityToLaunch;
//
// int counter = 0;
// for (FormField formField : fields) {
// int id = ++counter;
// highlightedFields.put(id, formField);
// }
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup viewGroup){
// View view = convertView;
// if (view == null) {
// LayoutInflater vi = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
// view = vi.inflate(textViewResourceId, null);
// }
//
// final T baseModel = objects.get(position) ;
// if (baseModel != null) {
// TextView uniqueIdView = (TextView) view.findViewById(R.id.row_child_unique_id);
//
// HighlightedFieldViewGroup highlightedFieldViewGroup = (HighlightedFieldViewGroup) view.findViewById(R.id.child_field_group);
// highlightedFieldViewGroup.prepare(baseModel, highlightedFields);
//
// ImageView imageView = (ImageView) view.findViewById(R.id.thumbnail);
// try {
// setFields(String.valueOf(buildTitle(baseModel)), uniqueIdView);
// assignThumbnail(baseModel, imageView);
//
// view.setOnClickListener(createClickListener(baseModel, activityToLaunch));
// } catch (JSONException e) {
// throw new RuntimeException(e);
// }
// }
// return view;
// }
//
// private String buildTitle(T baseModel) throws JSONException {
// if(titleFields.size() == 0) {
// return baseModel.getShortId();
// }
// StringBuilder titleBuilder = new StringBuilder();
// for (int i = 0; i < titleFields.size(); i++) {
// FormField titleField = titleFields.get(i);
// titleBuilder.append(baseModel.optString(titleField.getId()));
// if((i + 1) < titleFields.size()) {
// titleBuilder.append(" ");
// }
// }
// return String.format("%s (%s)", titleBuilder.toString(), baseModel.getShortId());
// }
// }
| import android.widget.AbsListView;
import com.rapidftr.adapter.HighlightedFieldsViewAdapter;
import com.rapidftr.model.Child;
import com.rapidftr.repository.ChildRepository;
import org.json.JSONException; | package com.rapidftr.adapter.pagination;
public class ViewAllChildrenPaginatedScrollListener implements AbsListView.OnScrollListener{
public static final int DEFAULT_PAGE_SIZE = 30;
public static final int FIRST_PAGE = 30;
private ViewAllChildScroller scroller;
public ViewAllChildrenPaginatedScrollListener(ChildRepository repository, | // Path: RapidFTR-Android/src/main/java/com/rapidftr/adapter/HighlightedFieldsViewAdapter.java
// public class HighlightedFieldsViewAdapter<T extends BaseModel> extends BaseModelViewAdapter<T> {
//
// protected Map<Integer, FormField> highlightedFields;
// private FormService formService;
// private Class<CollectionActivity> activityToLaunch;
// private final List<FormField> titleFields;
//
// public HighlightedFieldsViewAdapter(Context context, List<T> baseModels, String formName, Class<CollectionActivity> activityToLaunch) {
// super(context, R.layout.row_highlighted_fields, baseModels);
//
// formService = RapidFtrApplication.getApplicationInstance().getBean(FormService.class);
//
// List<FormField> fields = formService.getHighlightedFields(formName);
// titleFields = formService.getTitleFields(formName);
//
// highlightedFields = new TreeMap<Integer, FormField>();
// this.activityToLaunch = activityToLaunch;
//
// int counter = 0;
// for (FormField formField : fields) {
// int id = ++counter;
// highlightedFields.put(id, formField);
// }
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup viewGroup){
// View view = convertView;
// if (view == null) {
// LayoutInflater vi = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
// view = vi.inflate(textViewResourceId, null);
// }
//
// final T baseModel = objects.get(position) ;
// if (baseModel != null) {
// TextView uniqueIdView = (TextView) view.findViewById(R.id.row_child_unique_id);
//
// HighlightedFieldViewGroup highlightedFieldViewGroup = (HighlightedFieldViewGroup) view.findViewById(R.id.child_field_group);
// highlightedFieldViewGroup.prepare(baseModel, highlightedFields);
//
// ImageView imageView = (ImageView) view.findViewById(R.id.thumbnail);
// try {
// setFields(String.valueOf(buildTitle(baseModel)), uniqueIdView);
// assignThumbnail(baseModel, imageView);
//
// view.setOnClickListener(createClickListener(baseModel, activityToLaunch));
// } catch (JSONException e) {
// throw new RuntimeException(e);
// }
// }
// return view;
// }
//
// private String buildTitle(T baseModel) throws JSONException {
// if(titleFields.size() == 0) {
// return baseModel.getShortId();
// }
// StringBuilder titleBuilder = new StringBuilder();
// for (int i = 0; i < titleFields.size(); i++) {
// FormField titleField = titleFields.get(i);
// titleBuilder.append(baseModel.optString(titleField.getId()));
// if((i + 1) < titleFields.size()) {
// titleBuilder.append(" ");
// }
// }
// return String.format("%s (%s)", titleBuilder.toString(), baseModel.getShortId());
// }
// }
// Path: RapidFTR-Android/src/main/java/com/rapidftr/adapter/pagination/ViewAllChildrenPaginatedScrollListener.java
import android.widget.AbsListView;
import com.rapidftr.adapter.HighlightedFieldsViewAdapter;
import com.rapidftr.model.Child;
import com.rapidftr.repository.ChildRepository;
import org.json.JSONException;
package com.rapidftr.adapter.pagination;
public class ViewAllChildrenPaginatedScrollListener implements AbsListView.OnScrollListener{
public static final int DEFAULT_PAGE_SIZE = 30;
public static final int FIRST_PAGE = 30;
private ViewAllChildScroller scroller;
public ViewAllChildrenPaginatedScrollListener(ChildRepository repository, | HighlightedFieldsViewAdapter<Child> adapter) { |
rapidftr/RapidFTR-Android | RapidFTR-Android/src/test/java/com/rapidftr/database/ShadowSQLiteHelper.java | // Path: RapidFTR-Android/src/main/java/com/rapidftr/database/migration/Migrations.java
// public enum Migrations {
//
// v001_createChildTable(1, MigrationSQL.createChildTable),
// v001_addCreatedAtColumn(1, MigrationSQL.addCreatedAtColumn),
// v001_addUpdatedAtColumn(1, MigrationSQL.addLastUpdatedAtColumn),
// v001_add_idColumn(1, MigrationSQL.addIdColumn),
// v001_add_revColumn(1, MigrationSQL.addRevColumn),
// v001_add_last_synced_at_column(1,MigrationSQL.addLastSyncedAtColumn),
// v001_createEnquiryTable(1, MigrationSQL.createEnquiryTable),
// v002_createPotentialMatchTable(2, MigrationSQL.createPotentialMatchTable)
// ;
//
// private int databaseVersion;
// private String sql;
//
//
// Migrations(int databaseVersion, String sql) {
// this.databaseVersion = databaseVersion;
// this.sql = sql;
// }
//
// public String getSql() {
// return sql;
// }
//
// public boolean isForVersion(int databaseVersion){
// return this.databaseVersion == databaseVersion;
// }
//
// public static List<Migrations> forVersion(final int databaseVersion){
// return newArrayList(filter(asList(values()), new Predicate<Migrations>() {
// public boolean apply(Migrations migration) {
// return migration.isForVersion(databaseVersion);
// }
// }));
// }
//
// }
| import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.rapidftr.database.migration.Migrations;
import lombok.Delegate;
import lombok.Getter;
import lombok.RequiredArgsConstructor; | package com.rapidftr.database;
/*
* Stub SQLite Helper class which uses an in-memory database provided by Robolectric
* Database is freshly created Whenever "getWritableDatabase" or "getReadableDatabase" is called
*/
public class ShadowSQLiteHelper extends SQLiteOpenHelper implements DatabaseHelper {
private static DatabaseHelper instance;
public static DatabaseHelper getInstance() {
return instance == null ? resetDatabase() : instance;
}
public static DatabaseHelper resetDatabase() {
return (instance = new ShadowSQLiteHelper("test_database"));
}
@RequiredArgsConstructor(suppressConstructorProperties = true)
public static class ShadowSQLiteSession implements DatabaseSession {
@Delegate(types = DatabaseSession.class)
private final SQLiteDatabase database;
}
private @Getter DatabaseSession session;
public ShadowSQLiteHelper(String dbName) {
super(new Activity(), dbName, null, 2);
session = new ShadowSQLiteSession(getWritableDatabase());
}
@Override
public void onCreate(SQLiteDatabase database) { | // Path: RapidFTR-Android/src/main/java/com/rapidftr/database/migration/Migrations.java
// public enum Migrations {
//
// v001_createChildTable(1, MigrationSQL.createChildTable),
// v001_addCreatedAtColumn(1, MigrationSQL.addCreatedAtColumn),
// v001_addUpdatedAtColumn(1, MigrationSQL.addLastUpdatedAtColumn),
// v001_add_idColumn(1, MigrationSQL.addIdColumn),
// v001_add_revColumn(1, MigrationSQL.addRevColumn),
// v001_add_last_synced_at_column(1,MigrationSQL.addLastSyncedAtColumn),
// v001_createEnquiryTable(1, MigrationSQL.createEnquiryTable),
// v002_createPotentialMatchTable(2, MigrationSQL.createPotentialMatchTable)
// ;
//
// private int databaseVersion;
// private String sql;
//
//
// Migrations(int databaseVersion, String sql) {
// this.databaseVersion = databaseVersion;
// this.sql = sql;
// }
//
// public String getSql() {
// return sql;
// }
//
// public boolean isForVersion(int databaseVersion){
// return this.databaseVersion == databaseVersion;
// }
//
// public static List<Migrations> forVersion(final int databaseVersion){
// return newArrayList(filter(asList(values()), new Predicate<Migrations>() {
// public boolean apply(Migrations migration) {
// return migration.isForVersion(databaseVersion);
// }
// }));
// }
//
// }
// Path: RapidFTR-Android/src/test/java/com/rapidftr/database/ShadowSQLiteHelper.java
import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.rapidftr.database.migration.Migrations;
import lombok.Delegate;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
package com.rapidftr.database;
/*
* Stub SQLite Helper class which uses an in-memory database provided by Robolectric
* Database is freshly created Whenever "getWritableDatabase" or "getReadableDatabase" is called
*/
public class ShadowSQLiteHelper extends SQLiteOpenHelper implements DatabaseHelper {
private static DatabaseHelper instance;
public static DatabaseHelper getInstance() {
return instance == null ? resetDatabase() : instance;
}
public static DatabaseHelper resetDatabase() {
return (instance = new ShadowSQLiteHelper("test_database"));
}
@RequiredArgsConstructor(suppressConstructorProperties = true)
public static class ShadowSQLiteSession implements DatabaseSession {
@Delegate(types = DatabaseSession.class)
private final SQLiteDatabase database;
}
private @Getter DatabaseSession session;
public ShadowSQLiteHelper(String dbName) {
super(new Activity(), dbName, null, 2);
session = new ShadowSQLiteSession(getWritableDatabase());
}
@Override
public void onCreate(SQLiteDatabase database) { | for (Migrations migration : Migrations.values()) { |
rapidftr/RapidFTR-Android | RapidFTR-Android/src/main/java/com/rapidftr/activity/ViewAllChildrenActivity.java | // Path: RapidFTR-Android/src/main/java/com/rapidftr/adapter/HighlightedFieldsViewAdapter.java
// public class HighlightedFieldsViewAdapter<T extends BaseModel> extends BaseModelViewAdapter<T> {
//
// protected Map<Integer, FormField> highlightedFields;
// private FormService formService;
// private Class<CollectionActivity> activityToLaunch;
// private final List<FormField> titleFields;
//
// public HighlightedFieldsViewAdapter(Context context, List<T> baseModels, String formName, Class<CollectionActivity> activityToLaunch) {
// super(context, R.layout.row_highlighted_fields, baseModels);
//
// formService = RapidFtrApplication.getApplicationInstance().getBean(FormService.class);
//
// List<FormField> fields = formService.getHighlightedFields(formName);
// titleFields = formService.getTitleFields(formName);
//
// highlightedFields = new TreeMap<Integer, FormField>();
// this.activityToLaunch = activityToLaunch;
//
// int counter = 0;
// for (FormField formField : fields) {
// int id = ++counter;
// highlightedFields.put(id, formField);
// }
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup viewGroup){
// View view = convertView;
// if (view == null) {
// LayoutInflater vi = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
// view = vi.inflate(textViewResourceId, null);
// }
//
// final T baseModel = objects.get(position) ;
// if (baseModel != null) {
// TextView uniqueIdView = (TextView) view.findViewById(R.id.row_child_unique_id);
//
// HighlightedFieldViewGroup highlightedFieldViewGroup = (HighlightedFieldViewGroup) view.findViewById(R.id.child_field_group);
// highlightedFieldViewGroup.prepare(baseModel, highlightedFields);
//
// ImageView imageView = (ImageView) view.findViewById(R.id.thumbnail);
// try {
// setFields(String.valueOf(buildTitle(baseModel)), uniqueIdView);
// assignThumbnail(baseModel, imageView);
//
// view.setOnClickListener(createClickListener(baseModel, activityToLaunch));
// } catch (JSONException e) {
// throw new RuntimeException(e);
// }
// }
// return view;
// }
//
// private String buildTitle(T baseModel) throws JSONException {
// if(titleFields.size() == 0) {
// return baseModel.getShortId();
// }
// StringBuilder titleBuilder = new StringBuilder();
// for (int i = 0; i < titleFields.size(); i++) {
// FormField titleField = titleFields.get(i);
// titleBuilder.append(baseModel.optString(titleField.getId()));
// if((i + 1) < titleFields.size()) {
// titleBuilder.append(" ");
// }
// }
// return String.format("%s (%s)", titleBuilder.toString(), baseModel.getShortId());
// }
// }
//
// Path: RapidFTR-Android/src/main/java/com/rapidftr/adapter/pagination/ViewAllChildrenPaginatedScrollListener.java
// public class ViewAllChildrenPaginatedScrollListener implements AbsListView.OnScrollListener{
//
// public static final int DEFAULT_PAGE_SIZE = 30;
// public static final int FIRST_PAGE = 30;
// private ViewAllChildScroller scroller;
//
// public ViewAllChildrenPaginatedScrollListener(ChildRepository repository,
// HighlightedFieldsViewAdapter<Child> adapter) {
// scroller = new ViewAllChildScroller(repository, adapter);
// }
//
// @Override
// public void onScroll(AbsListView absListView, int firstVisibleItem,
// int numberOfVisibleItems, int numberOfItemsInAdapter) {
// scroller.updateRecordNumbers(firstVisibleItem, numberOfVisibleItems, numberOfItemsInAdapter);
//
// try {
// scroller.loadRecordsForNextPage();
// } catch (JSONException e) {
// throw new RuntimeException(e);
// }
// }
//
// @Override
// public void onScrollStateChanged(AbsListView absListView, int i) {}
// }
| import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import com.rapidftr.R;
import com.rapidftr.RapidFtrApplication;
import com.rapidftr.adapter.HighlightedFieldsViewAdapter;
import com.rapidftr.adapter.pagination.ViewAllChildrenPaginatedScrollListener;
import com.rapidftr.model.Child;
import com.rapidftr.repository.ChildRepository;
import lombok.Cleanup;
import org.json.JSONException;
import java.util.ArrayList;
import java.util.List; | package com.rapidftr.activity;
public class ViewAllChildrenActivity extends RapidFtrActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_all_children);
try {
hideEnquiriesTabIfRapidReg();
} catch (JSONException e) {
e.printStackTrace();
}
listView(getChildren());
}
private List<Child> getChildren() {
List<Child> children = new ArrayList<Child>();
@Cleanup ChildRepository childRepository = inject(ChildRepository.class);
try {
children = childRepository.getRecordsForFirstPage();
} catch (JSONException e) {
Log.e("ViewAllChildrenActivity", "Error while displaying children list");
makeToast(R.string.fetch_child_error);
}
return children;
}
private void listView(List<Child> children) { | // Path: RapidFTR-Android/src/main/java/com/rapidftr/adapter/HighlightedFieldsViewAdapter.java
// public class HighlightedFieldsViewAdapter<T extends BaseModel> extends BaseModelViewAdapter<T> {
//
// protected Map<Integer, FormField> highlightedFields;
// private FormService formService;
// private Class<CollectionActivity> activityToLaunch;
// private final List<FormField> titleFields;
//
// public HighlightedFieldsViewAdapter(Context context, List<T> baseModels, String formName, Class<CollectionActivity> activityToLaunch) {
// super(context, R.layout.row_highlighted_fields, baseModels);
//
// formService = RapidFtrApplication.getApplicationInstance().getBean(FormService.class);
//
// List<FormField> fields = formService.getHighlightedFields(formName);
// titleFields = formService.getTitleFields(formName);
//
// highlightedFields = new TreeMap<Integer, FormField>();
// this.activityToLaunch = activityToLaunch;
//
// int counter = 0;
// for (FormField formField : fields) {
// int id = ++counter;
// highlightedFields.put(id, formField);
// }
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup viewGroup){
// View view = convertView;
// if (view == null) {
// LayoutInflater vi = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
// view = vi.inflate(textViewResourceId, null);
// }
//
// final T baseModel = objects.get(position) ;
// if (baseModel != null) {
// TextView uniqueIdView = (TextView) view.findViewById(R.id.row_child_unique_id);
//
// HighlightedFieldViewGroup highlightedFieldViewGroup = (HighlightedFieldViewGroup) view.findViewById(R.id.child_field_group);
// highlightedFieldViewGroup.prepare(baseModel, highlightedFields);
//
// ImageView imageView = (ImageView) view.findViewById(R.id.thumbnail);
// try {
// setFields(String.valueOf(buildTitle(baseModel)), uniqueIdView);
// assignThumbnail(baseModel, imageView);
//
// view.setOnClickListener(createClickListener(baseModel, activityToLaunch));
// } catch (JSONException e) {
// throw new RuntimeException(e);
// }
// }
// return view;
// }
//
// private String buildTitle(T baseModel) throws JSONException {
// if(titleFields.size() == 0) {
// return baseModel.getShortId();
// }
// StringBuilder titleBuilder = new StringBuilder();
// for (int i = 0; i < titleFields.size(); i++) {
// FormField titleField = titleFields.get(i);
// titleBuilder.append(baseModel.optString(titleField.getId()));
// if((i + 1) < titleFields.size()) {
// titleBuilder.append(" ");
// }
// }
// return String.format("%s (%s)", titleBuilder.toString(), baseModel.getShortId());
// }
// }
//
// Path: RapidFTR-Android/src/main/java/com/rapidftr/adapter/pagination/ViewAllChildrenPaginatedScrollListener.java
// public class ViewAllChildrenPaginatedScrollListener implements AbsListView.OnScrollListener{
//
// public static final int DEFAULT_PAGE_SIZE = 30;
// public static final int FIRST_PAGE = 30;
// private ViewAllChildScroller scroller;
//
// public ViewAllChildrenPaginatedScrollListener(ChildRepository repository,
// HighlightedFieldsViewAdapter<Child> adapter) {
// scroller = new ViewAllChildScroller(repository, adapter);
// }
//
// @Override
// public void onScroll(AbsListView absListView, int firstVisibleItem,
// int numberOfVisibleItems, int numberOfItemsInAdapter) {
// scroller.updateRecordNumbers(firstVisibleItem, numberOfVisibleItems, numberOfItemsInAdapter);
//
// try {
// scroller.loadRecordsForNextPage();
// } catch (JSONException e) {
// throw new RuntimeException(e);
// }
// }
//
// @Override
// public void onScrollStateChanged(AbsListView absListView, int i) {}
// }
// Path: RapidFTR-Android/src/main/java/com/rapidftr/activity/ViewAllChildrenActivity.java
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import com.rapidftr.R;
import com.rapidftr.RapidFtrApplication;
import com.rapidftr.adapter.HighlightedFieldsViewAdapter;
import com.rapidftr.adapter.pagination.ViewAllChildrenPaginatedScrollListener;
import com.rapidftr.model.Child;
import com.rapidftr.repository.ChildRepository;
import lombok.Cleanup;
import org.json.JSONException;
import java.util.ArrayList;
import java.util.List;
package com.rapidftr.activity;
public class ViewAllChildrenActivity extends RapidFtrActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_all_children);
try {
hideEnquiriesTabIfRapidReg();
} catch (JSONException e) {
e.printStackTrace();
}
listView(getChildren());
}
private List<Child> getChildren() {
List<Child> children = new ArrayList<Child>();
@Cleanup ChildRepository childRepository = inject(ChildRepository.class);
try {
children = childRepository.getRecordsForFirstPage();
} catch (JSONException e) {
Log.e("ViewAllChildrenActivity", "Error while displaying children list");
makeToast(R.string.fetch_child_error);
}
return children;
}
private void listView(List<Child> children) { | HighlightedFieldsViewAdapter highlightedFieldsViewAdapter = new HighlightedFieldsViewAdapter(this, children, Child.CHILD_FORM_NAME, ViewChildActivity.class); |
rapidftr/RapidFTR-Android | RapidFTR-Android/src/main/java/com/rapidftr/activity/ViewAllChildrenActivity.java | // Path: RapidFTR-Android/src/main/java/com/rapidftr/adapter/HighlightedFieldsViewAdapter.java
// public class HighlightedFieldsViewAdapter<T extends BaseModel> extends BaseModelViewAdapter<T> {
//
// protected Map<Integer, FormField> highlightedFields;
// private FormService formService;
// private Class<CollectionActivity> activityToLaunch;
// private final List<FormField> titleFields;
//
// public HighlightedFieldsViewAdapter(Context context, List<T> baseModels, String formName, Class<CollectionActivity> activityToLaunch) {
// super(context, R.layout.row_highlighted_fields, baseModels);
//
// formService = RapidFtrApplication.getApplicationInstance().getBean(FormService.class);
//
// List<FormField> fields = formService.getHighlightedFields(formName);
// titleFields = formService.getTitleFields(formName);
//
// highlightedFields = new TreeMap<Integer, FormField>();
// this.activityToLaunch = activityToLaunch;
//
// int counter = 0;
// for (FormField formField : fields) {
// int id = ++counter;
// highlightedFields.put(id, formField);
// }
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup viewGroup){
// View view = convertView;
// if (view == null) {
// LayoutInflater vi = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
// view = vi.inflate(textViewResourceId, null);
// }
//
// final T baseModel = objects.get(position) ;
// if (baseModel != null) {
// TextView uniqueIdView = (TextView) view.findViewById(R.id.row_child_unique_id);
//
// HighlightedFieldViewGroup highlightedFieldViewGroup = (HighlightedFieldViewGroup) view.findViewById(R.id.child_field_group);
// highlightedFieldViewGroup.prepare(baseModel, highlightedFields);
//
// ImageView imageView = (ImageView) view.findViewById(R.id.thumbnail);
// try {
// setFields(String.valueOf(buildTitle(baseModel)), uniqueIdView);
// assignThumbnail(baseModel, imageView);
//
// view.setOnClickListener(createClickListener(baseModel, activityToLaunch));
// } catch (JSONException e) {
// throw new RuntimeException(e);
// }
// }
// return view;
// }
//
// private String buildTitle(T baseModel) throws JSONException {
// if(titleFields.size() == 0) {
// return baseModel.getShortId();
// }
// StringBuilder titleBuilder = new StringBuilder();
// for (int i = 0; i < titleFields.size(); i++) {
// FormField titleField = titleFields.get(i);
// titleBuilder.append(baseModel.optString(titleField.getId()));
// if((i + 1) < titleFields.size()) {
// titleBuilder.append(" ");
// }
// }
// return String.format("%s (%s)", titleBuilder.toString(), baseModel.getShortId());
// }
// }
//
// Path: RapidFTR-Android/src/main/java/com/rapidftr/adapter/pagination/ViewAllChildrenPaginatedScrollListener.java
// public class ViewAllChildrenPaginatedScrollListener implements AbsListView.OnScrollListener{
//
// public static final int DEFAULT_PAGE_SIZE = 30;
// public static final int FIRST_PAGE = 30;
// private ViewAllChildScroller scroller;
//
// public ViewAllChildrenPaginatedScrollListener(ChildRepository repository,
// HighlightedFieldsViewAdapter<Child> adapter) {
// scroller = new ViewAllChildScroller(repository, adapter);
// }
//
// @Override
// public void onScroll(AbsListView absListView, int firstVisibleItem,
// int numberOfVisibleItems, int numberOfItemsInAdapter) {
// scroller.updateRecordNumbers(firstVisibleItem, numberOfVisibleItems, numberOfItemsInAdapter);
//
// try {
// scroller.loadRecordsForNextPage();
// } catch (JSONException e) {
// throw new RuntimeException(e);
// }
// }
//
// @Override
// public void onScrollStateChanged(AbsListView absListView, int i) {}
// }
| import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import com.rapidftr.R;
import com.rapidftr.RapidFtrApplication;
import com.rapidftr.adapter.HighlightedFieldsViewAdapter;
import com.rapidftr.adapter.pagination.ViewAllChildrenPaginatedScrollListener;
import com.rapidftr.model.Child;
import com.rapidftr.repository.ChildRepository;
import lombok.Cleanup;
import org.json.JSONException;
import java.util.ArrayList;
import java.util.List; | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_all_children);
try {
hideEnquiriesTabIfRapidReg();
} catch (JSONException e) {
e.printStackTrace();
}
listView(getChildren());
}
private List<Child> getChildren() {
List<Child> children = new ArrayList<Child>();
@Cleanup ChildRepository childRepository = inject(ChildRepository.class);
try {
children = childRepository.getRecordsForFirstPage();
} catch (JSONException e) {
Log.e("ViewAllChildrenActivity", "Error while displaying children list");
makeToast(R.string.fetch_child_error);
}
return children;
}
private void listView(List<Child> children) {
HighlightedFieldsViewAdapter highlightedFieldsViewAdapter = new HighlightedFieldsViewAdapter(this, children, Child.CHILD_FORM_NAME, ViewChildActivity.class);
ListView childListView = (ListView) findViewById(R.id.child_list);
if (children.isEmpty()) {
childListView.setEmptyView(findViewById(R.id.no_child_view));
}
childListView.setAdapter(highlightedFieldsViewAdapter); | // Path: RapidFTR-Android/src/main/java/com/rapidftr/adapter/HighlightedFieldsViewAdapter.java
// public class HighlightedFieldsViewAdapter<T extends BaseModel> extends BaseModelViewAdapter<T> {
//
// protected Map<Integer, FormField> highlightedFields;
// private FormService formService;
// private Class<CollectionActivity> activityToLaunch;
// private final List<FormField> titleFields;
//
// public HighlightedFieldsViewAdapter(Context context, List<T> baseModels, String formName, Class<CollectionActivity> activityToLaunch) {
// super(context, R.layout.row_highlighted_fields, baseModels);
//
// formService = RapidFtrApplication.getApplicationInstance().getBean(FormService.class);
//
// List<FormField> fields = formService.getHighlightedFields(formName);
// titleFields = formService.getTitleFields(formName);
//
// highlightedFields = new TreeMap<Integer, FormField>();
// this.activityToLaunch = activityToLaunch;
//
// int counter = 0;
// for (FormField formField : fields) {
// int id = ++counter;
// highlightedFields.put(id, formField);
// }
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup viewGroup){
// View view = convertView;
// if (view == null) {
// LayoutInflater vi = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
// view = vi.inflate(textViewResourceId, null);
// }
//
// final T baseModel = objects.get(position) ;
// if (baseModel != null) {
// TextView uniqueIdView = (TextView) view.findViewById(R.id.row_child_unique_id);
//
// HighlightedFieldViewGroup highlightedFieldViewGroup = (HighlightedFieldViewGroup) view.findViewById(R.id.child_field_group);
// highlightedFieldViewGroup.prepare(baseModel, highlightedFields);
//
// ImageView imageView = (ImageView) view.findViewById(R.id.thumbnail);
// try {
// setFields(String.valueOf(buildTitle(baseModel)), uniqueIdView);
// assignThumbnail(baseModel, imageView);
//
// view.setOnClickListener(createClickListener(baseModel, activityToLaunch));
// } catch (JSONException e) {
// throw new RuntimeException(e);
// }
// }
// return view;
// }
//
// private String buildTitle(T baseModel) throws JSONException {
// if(titleFields.size() == 0) {
// return baseModel.getShortId();
// }
// StringBuilder titleBuilder = new StringBuilder();
// for (int i = 0; i < titleFields.size(); i++) {
// FormField titleField = titleFields.get(i);
// titleBuilder.append(baseModel.optString(titleField.getId()));
// if((i + 1) < titleFields.size()) {
// titleBuilder.append(" ");
// }
// }
// return String.format("%s (%s)", titleBuilder.toString(), baseModel.getShortId());
// }
// }
//
// Path: RapidFTR-Android/src/main/java/com/rapidftr/adapter/pagination/ViewAllChildrenPaginatedScrollListener.java
// public class ViewAllChildrenPaginatedScrollListener implements AbsListView.OnScrollListener{
//
// public static final int DEFAULT_PAGE_SIZE = 30;
// public static final int FIRST_PAGE = 30;
// private ViewAllChildScroller scroller;
//
// public ViewAllChildrenPaginatedScrollListener(ChildRepository repository,
// HighlightedFieldsViewAdapter<Child> adapter) {
// scroller = new ViewAllChildScroller(repository, adapter);
// }
//
// @Override
// public void onScroll(AbsListView absListView, int firstVisibleItem,
// int numberOfVisibleItems, int numberOfItemsInAdapter) {
// scroller.updateRecordNumbers(firstVisibleItem, numberOfVisibleItems, numberOfItemsInAdapter);
//
// try {
// scroller.loadRecordsForNextPage();
// } catch (JSONException e) {
// throw new RuntimeException(e);
// }
// }
//
// @Override
// public void onScrollStateChanged(AbsListView absListView, int i) {}
// }
// Path: RapidFTR-Android/src/main/java/com/rapidftr/activity/ViewAllChildrenActivity.java
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import com.rapidftr.R;
import com.rapidftr.RapidFtrApplication;
import com.rapidftr.adapter.HighlightedFieldsViewAdapter;
import com.rapidftr.adapter.pagination.ViewAllChildrenPaginatedScrollListener;
import com.rapidftr.model.Child;
import com.rapidftr.repository.ChildRepository;
import lombok.Cleanup;
import org.json.JSONException;
import java.util.ArrayList;
import java.util.List;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_all_children);
try {
hideEnquiriesTabIfRapidReg();
} catch (JSONException e) {
e.printStackTrace();
}
listView(getChildren());
}
private List<Child> getChildren() {
List<Child> children = new ArrayList<Child>();
@Cleanup ChildRepository childRepository = inject(ChildRepository.class);
try {
children = childRepository.getRecordsForFirstPage();
} catch (JSONException e) {
Log.e("ViewAllChildrenActivity", "Error while displaying children list");
makeToast(R.string.fetch_child_error);
}
return children;
}
private void listView(List<Child> children) {
HighlightedFieldsViewAdapter highlightedFieldsViewAdapter = new HighlightedFieldsViewAdapter(this, children, Child.CHILD_FORM_NAME, ViewChildActivity.class);
ListView childListView = (ListView) findViewById(R.id.child_list);
if (children.isEmpty()) {
childListView.setEmptyView(findViewById(R.id.no_child_view));
}
childListView.setAdapter(highlightedFieldsViewAdapter); | ViewAllChildrenPaginatedScrollListener scrollListener = new ViewAllChildrenPaginatedScrollListener(inject(ChildRepository.class), highlightedFieldsViewAdapter); |
mesosphere/mesos-rxjava | mesos-rxjava-test/src/test/java/com/mesosphere/mesos/rx/java/test/simulation/AwaitableEventSubscriberDecoratorTest.java | // Path: mesos-rxjava-test/src/main/java/com/mesosphere/mesos/rx/java/test/Async.java
// public final class Async extends Verifier {
//
// @NotNull
// private final AtomicInteger counter;
//
// @NotNull
// private final ExecutorService executor;
//
// @NotNull
// private final List<Task> tasks;
//
// public Async() {
// counter = new AtomicInteger(0);
// executor = Executors.newCachedThreadPool(new DefaultThreadFactory(Async.class, true));
// tasks = Collections.synchronizedList(new ArrayList<>());
// }
//
// /**
// * Run {@code r} on a background CachedThreadPool
// * @param r The task to run
// */
// public void run(@NotNull final ErrorableRunnable r) {
// run(String.format("Async-%d", counter.getAndIncrement()), r);
// }
//
// /**
// * Run {@code r} on a background CachedThreadPool
// * @param taskName The name of the task (used for error messages)
// * @param r The task to run
// */
// public void run(@NotNull final String taskName, @NotNull final ErrorableRunnable r) {
// tasks.add(new Task(taskName, executor.submit(r)));
// }
//
// @Override
// protected void verify() throws Throwable {
// final List<Throwable> errors = tasks.stream()
// .map(task -> {
// try {
// task.future.get(10, TimeUnit.MILLISECONDS);
// return Optional.<Throwable>empty();
// } catch (ExecutionException e) {
// final Throwable cause = e.getCause();
// if (cause != null && cause instanceof AssertionError) {
// return Optional.of(cause);
// }
// final String baseMessage = "Error while running Async";
// final String message = Optional.ofNullable(cause)
// .map(c -> baseMessage + ": " + c.getMessage())
// .orElse(baseMessage);
// return Optional.of(new AssertionError(message, cause));
// } catch (TimeoutException te) {
// return Optional.of(new AssertionError(String.format("Task [%s] still running after test completion", task.name)));
// } catch (InterruptedException e) {
// return Optional.of(new AssertionError(e));
// }
// })
// .filter(Optional::isPresent)
// .map(Optional::get)
// .collect(Collectors.toList());
// executor.shutdown();
// MultipleFailureException.assertEmpty(errors);
// }
//
// /**
// * Convenience type that allows submitting a runnable that may throw a checked exception.
// * <p>
// * If a checked exception is throw while running the task it will be wrapped in a {@link RuntimeException} and
// * rethrown. If an {@link AssertionError} or {@link RuntimeException} is throw it will be rethrown without being
// * wrapped.
// */
// @FunctionalInterface
// public interface ErrorableRunnable extends Runnable {
// void invoke() throws Throwable;
// default void run() {
// try {
// invoke();
// } catch(AssertionError | RuntimeException e) {
// throw e;
// } catch (Throwable throwable) {
// throw new RuntimeException(throwable);
// }
// }
// }
//
// private static final class Task {
// @NotNull
// private final Future<?> future;
// @NotNull
// private final String name;
//
// public Task(@NotNull final String name, @NotNull final Future<?> future) {
// this.future = future;
// this.name = name;
// }
// }
// }
| import com.mesosphere.mesos.rx.java.test.Async;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
import rx.Subscription;
import rx.observers.TestSubscriber;
import rx.subjects.BehaviorSubject;
import java.util.concurrent.TimeUnit; | /*
* Copyright (C) 2016 Mesosphere, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mesosphere.mesos.rx.java.test.simulation;
public final class AwaitableEventSubscriberDecoratorTest {
@Rule
public Timeout timeout = new Timeout(1000, TimeUnit.MILLISECONDS);
@Rule | // Path: mesos-rxjava-test/src/main/java/com/mesosphere/mesos/rx/java/test/Async.java
// public final class Async extends Verifier {
//
// @NotNull
// private final AtomicInteger counter;
//
// @NotNull
// private final ExecutorService executor;
//
// @NotNull
// private final List<Task> tasks;
//
// public Async() {
// counter = new AtomicInteger(0);
// executor = Executors.newCachedThreadPool(new DefaultThreadFactory(Async.class, true));
// tasks = Collections.synchronizedList(new ArrayList<>());
// }
//
// /**
// * Run {@code r} on a background CachedThreadPool
// * @param r The task to run
// */
// public void run(@NotNull final ErrorableRunnable r) {
// run(String.format("Async-%d", counter.getAndIncrement()), r);
// }
//
// /**
// * Run {@code r} on a background CachedThreadPool
// * @param taskName The name of the task (used for error messages)
// * @param r The task to run
// */
// public void run(@NotNull final String taskName, @NotNull final ErrorableRunnable r) {
// tasks.add(new Task(taskName, executor.submit(r)));
// }
//
// @Override
// protected void verify() throws Throwable {
// final List<Throwable> errors = tasks.stream()
// .map(task -> {
// try {
// task.future.get(10, TimeUnit.MILLISECONDS);
// return Optional.<Throwable>empty();
// } catch (ExecutionException e) {
// final Throwable cause = e.getCause();
// if (cause != null && cause instanceof AssertionError) {
// return Optional.of(cause);
// }
// final String baseMessage = "Error while running Async";
// final String message = Optional.ofNullable(cause)
// .map(c -> baseMessage + ": " + c.getMessage())
// .orElse(baseMessage);
// return Optional.of(new AssertionError(message, cause));
// } catch (TimeoutException te) {
// return Optional.of(new AssertionError(String.format("Task [%s] still running after test completion", task.name)));
// } catch (InterruptedException e) {
// return Optional.of(new AssertionError(e));
// }
// })
// .filter(Optional::isPresent)
// .map(Optional::get)
// .collect(Collectors.toList());
// executor.shutdown();
// MultipleFailureException.assertEmpty(errors);
// }
//
// /**
// * Convenience type that allows submitting a runnable that may throw a checked exception.
// * <p>
// * If a checked exception is throw while running the task it will be wrapped in a {@link RuntimeException} and
// * rethrown. If an {@link AssertionError} or {@link RuntimeException} is throw it will be rethrown without being
// * wrapped.
// */
// @FunctionalInterface
// public interface ErrorableRunnable extends Runnable {
// void invoke() throws Throwable;
// default void run() {
// try {
// invoke();
// } catch(AssertionError | RuntimeException e) {
// throw e;
// } catch (Throwable throwable) {
// throw new RuntimeException(throwable);
// }
// }
// }
//
// private static final class Task {
// @NotNull
// private final Future<?> future;
// @NotNull
// private final String name;
//
// public Task(@NotNull final String name, @NotNull final Future<?> future) {
// this.future = future;
// this.name = name;
// }
// }
// }
// Path: mesos-rxjava-test/src/test/java/com/mesosphere/mesos/rx/java/test/simulation/AwaitableEventSubscriberDecoratorTest.java
import com.mesosphere.mesos.rx.java.test.Async;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
import rx.Subscription;
import rx.observers.TestSubscriber;
import rx.subjects.BehaviorSubject;
import java.util.concurrent.TimeUnit;
/*
* Copyright (C) 2016 Mesosphere, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mesosphere.mesos.rx.java.test.simulation;
public final class AwaitableEventSubscriberDecoratorTest {
@Rule
public Timeout timeout = new Timeout(1000, TimeUnit.MILLISECONDS);
@Rule | public Async async = new Async(); |
mesosphere/mesos-rxjava | mesos-rxjava-test/src/test/java/com/mesosphere/mesos/rx/java/test/simulation/MesosServerSimulationTest.java | // Path: mesos-rxjava-test/src/main/java/com/mesosphere/mesos/rx/java/test/StringMessageCodec.java
// public final class StringMessageCodec implements MessageCodec<String> {
//
// @NotNull
// public static final MessageCodec<String> UTF8_STRING = new StringMessageCodec();
//
// private StringMessageCodec() {}
//
// @NotNull
// @Override
// public byte[] encode(@NotNull final String message) {
// return message.getBytes(StandardCharsets.UTF_8);
// }
//
// @NotNull
// @Override
// public String decode(@NotNull final byte[] bytes) {
// return new String(bytes, StandardCharsets.UTF_8);
// }
//
// @NotNull
// @Override
// public String decode(@NotNull final InputStream in) {
// try {
// final StringBuilder sb = new StringBuilder();
// final Reader reader = new InputStreamReader(in, StandardCharsets.UTF_8);
// final CharBuffer buffer = CharBuffer.allocate(0x800);// 2k chars (4k bytes)
// while (reader.read(buffer) != -1) {
// buffer.flip();
// sb.append(buffer);
// buffer.clear();
// }
// return sb.toString();
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// @NotNull
// @Override
// public String mediaType() {
// return "text/plain;charset=utf-8";
// }
//
// @NotNull
// @Override
// public String show(@NotNull final String message) {
// return message;
// }
// }
| import static org.assertj.core.api.Assertions.assertThat;
import com.mesosphere.mesos.rx.java.test.StringMessageCodec;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.reactivex.netty.RxNetty;
import io.reactivex.netty.protocol.http.client.*;
import org.jetbrains.annotations.NotNull;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import rx.subjects.BehaviorSubject;
import java.net.URI;
import java.nio.charset.StandardCharsets; | /*
* Copyright (C) 2015 Mesosphere, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mesosphere.mesos.rx.java.test.simulation;
public final class MesosServerSimulationTest {
private final MesosServerSimulation<String, String> mesosServerSimulation = new MesosServerSimulation<>(
BehaviorSubject.create(), | // Path: mesos-rxjava-test/src/main/java/com/mesosphere/mesos/rx/java/test/StringMessageCodec.java
// public final class StringMessageCodec implements MessageCodec<String> {
//
// @NotNull
// public static final MessageCodec<String> UTF8_STRING = new StringMessageCodec();
//
// private StringMessageCodec() {}
//
// @NotNull
// @Override
// public byte[] encode(@NotNull final String message) {
// return message.getBytes(StandardCharsets.UTF_8);
// }
//
// @NotNull
// @Override
// public String decode(@NotNull final byte[] bytes) {
// return new String(bytes, StandardCharsets.UTF_8);
// }
//
// @NotNull
// @Override
// public String decode(@NotNull final InputStream in) {
// try {
// final StringBuilder sb = new StringBuilder();
// final Reader reader = new InputStreamReader(in, StandardCharsets.UTF_8);
// final CharBuffer buffer = CharBuffer.allocate(0x800);// 2k chars (4k bytes)
// while (reader.read(buffer) != -1) {
// buffer.flip();
// sb.append(buffer);
// buffer.clear();
// }
// return sb.toString();
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// @NotNull
// @Override
// public String mediaType() {
// return "text/plain;charset=utf-8";
// }
//
// @NotNull
// @Override
// public String show(@NotNull final String message) {
// return message;
// }
// }
// Path: mesos-rxjava-test/src/test/java/com/mesosphere/mesos/rx/java/test/simulation/MesosServerSimulationTest.java
import static org.assertj.core.api.Assertions.assertThat;
import com.mesosphere.mesos.rx.java.test.StringMessageCodec;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.reactivex.netty.RxNetty;
import io.reactivex.netty.protocol.http.client.*;
import org.jetbrains.annotations.NotNull;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import rx.subjects.BehaviorSubject;
import java.net.URI;
import java.nio.charset.StandardCharsets;
/*
* Copyright (C) 2015 Mesosphere, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mesosphere.mesos.rx.java.test.simulation;
public final class MesosServerSimulationTest {
private final MesosServerSimulation<String, String> mesosServerSimulation = new MesosServerSimulation<>(
BehaviorSubject.create(), | StringMessageCodec.UTF8_STRING, |
mesosphere/mesos-rxjava | mesos-rxjava-protobuf-client/src/main/java/com/mesosphere/mesos/rx/java/protobuf/ProtobufMessageCodecs.java | // Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/MessageCodec.java
// public interface MessageCodec<T> {
//
// /**
// * Serialize the given {@code message} into an array of bytes.
// *
// * @param message the message to serialize
// * @return the serialized message
// */
// @NotNull
// byte[] encode(@NotNull final T message);
//
// /**
// * Deserialize the given byte array into a message.
// *
// * @param bytes the bytes to deserialize
// * @return the deserialized message
// * @throws RuntimeException If an error occurs when decoding {@code bytes}. If a checked exception is possible
// * it should be wrapped in a RuntimeException.
// */
// @NotNull
// T decode(@NotNull final byte[] bytes);
//
// /**
// * Deserialize the given byte array into a message.
// *
// * @param in The {@link InputStream} to deserialize the message from
// * @return the deserialized message
// * @throws RuntimeException If an error occurs when decoding {@code bytes}. If a checked exception is possible
// * it should be wrapped in a RuntimeException.
// */
// @NotNull
// T decode(@NotNull final InputStream in);
//
// /**
// * Returns the <a target="_blank" href="https://en.wikipedia.org/wiki/Media_type">IANA media type</a> of the serialized message
// * format handled by this object.
// * <p>
// * The value returned by this method will be used in the {@code Content-Type} and {@code Accept} headers for
// * messages sent to and received from Mesos, respectively.
// *
// * @return the media type identifier
// */
// @NotNull
// String mediaType();
//
// /**
// * Renders the given {@code message} to informative, human-readable text.
// * <p>
// * The intent of this method is to allow messages to be easily read in program logs and while debugging.
// *
// * @param message the message to render
// * @return the rendered message
// */
// @NotNull
// String show(@NotNull final T message);
//
// }
| import com.mesosphere.mesos.rx.java.util.MessageCodec;
import org.apache.mesos.v1.scheduler.Protos; | /*
* Copyright (C) 2016 Mesosphere, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mesosphere.mesos.rx.java.protobuf;
/**
* A pair of {@link MessageCodec}s for {@link org.apache.mesos.v1.scheduler.Protos.Call} and
* {@link org.apache.mesos.v1.scheduler.Protos.Event}
*/
public final class ProtobufMessageCodecs {
private ProtobufMessageCodecs() {}
/** A {@link MessageCodec} for {@link org.apache.mesos.v1.scheduler.Protos.Call Call}. */ | // Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/MessageCodec.java
// public interface MessageCodec<T> {
//
// /**
// * Serialize the given {@code message} into an array of bytes.
// *
// * @param message the message to serialize
// * @return the serialized message
// */
// @NotNull
// byte[] encode(@NotNull final T message);
//
// /**
// * Deserialize the given byte array into a message.
// *
// * @param bytes the bytes to deserialize
// * @return the deserialized message
// * @throws RuntimeException If an error occurs when decoding {@code bytes}. If a checked exception is possible
// * it should be wrapped in a RuntimeException.
// */
// @NotNull
// T decode(@NotNull final byte[] bytes);
//
// /**
// * Deserialize the given byte array into a message.
// *
// * @param in The {@link InputStream} to deserialize the message from
// * @return the deserialized message
// * @throws RuntimeException If an error occurs when decoding {@code bytes}. If a checked exception is possible
// * it should be wrapped in a RuntimeException.
// */
// @NotNull
// T decode(@NotNull final InputStream in);
//
// /**
// * Returns the <a target="_blank" href="https://en.wikipedia.org/wiki/Media_type">IANA media type</a> of the serialized message
// * format handled by this object.
// * <p>
// * The value returned by this method will be used in the {@code Content-Type} and {@code Accept} headers for
// * messages sent to and received from Mesos, respectively.
// *
// * @return the media type identifier
// */
// @NotNull
// String mediaType();
//
// /**
// * Renders the given {@code message} to informative, human-readable text.
// * <p>
// * The intent of this method is to allow messages to be easily read in program logs and while debugging.
// *
// * @param message the message to render
// * @return the rendered message
// */
// @NotNull
// String show(@NotNull final T message);
//
// }
// Path: mesos-rxjava-protobuf-client/src/main/java/com/mesosphere/mesos/rx/java/protobuf/ProtobufMessageCodecs.java
import com.mesosphere.mesos.rx.java.util.MessageCodec;
import org.apache.mesos.v1.scheduler.Protos;
/*
* Copyright (C) 2016 Mesosphere, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mesosphere.mesos.rx.java.protobuf;
/**
* A pair of {@link MessageCodec}s for {@link org.apache.mesos.v1.scheduler.Protos.Call} and
* {@link org.apache.mesos.v1.scheduler.Protos.Event}
*/
public final class ProtobufMessageCodecs {
private ProtobufMessageCodecs() {}
/** A {@link MessageCodec} for {@link org.apache.mesos.v1.scheduler.Protos.Call Call}. */ | public static final MessageCodec<Protos.Call> SCHEDULER_CALL = new ProtoCodec<>( |
mesosphere/mesos-rxjava | mesos-rxjava-util/src/test/java/com/mesosphere/mesos/rx/java/UserAgentTest.java | // Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgent.java
// public final class UserAgent {
//
// @NotNull
// private final List<UserAgentEntry> entries;
// @NotNull
// private final String toStringValue;
//
// @SafeVarargs
// public UserAgent(@NotNull final Function<Class<?>, UserAgentEntry>... entries) {
// this.entries =
// Collections.unmodifiableList(
// Arrays.asList(entries)
// .stream()
// .map(f -> f.apply(this.getClass()))
// .collect(Collectors.toList())
// );
// this.toStringValue = this.entries
// .stream()
// .map(UserAgentEntry::toString)
// .collect(Collectors.joining(" "));
// }
//
// @NotNull
// public List<UserAgentEntry> getEntries() {
// return entries;
// }
//
// @Override
// public String toString() {
// return toStringValue;
// }
//
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgentEntries.java
// @NotNull
// public static Function<Class<?>, UserAgentEntry> literal(@NotNull final String name, @NotNull final String version) {
// return (Class<?> c) -> new UserAgentEntry(name, version);
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgentEntries.java
// @NotNull
// public static Function<Class<?>, UserAgentEntry> userAgentEntryForGradleArtifact(@NotNull final String artifactId) {
// return (Class<?> c) -> {
// final Properties props = loadProperties(c, String.format("/META-INF/%s.properties", artifactId));
// return new UserAgentEntry(props.getProperty("artifactId", artifactId), props.getProperty("Implementation-Version", "unknown-version"));
// };
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgentEntries.java
// @NotNull
// public static Function<Class<?>, UserAgentEntry> userAgentEntryForMavenArtifact(@NotNull final String groupId, @NotNull final String artifactId) {
// return (Class<?> c) -> {
// final Properties props = loadProperties(c, String.format("/META-INF/maven/%s/%s/pom.properties", groupId, artifactId));
// return new UserAgentEntry(props.getProperty("artifactId", artifactId), props.getProperty("version", "unknown-version"));
// };
// }
| import com.mesosphere.mesos.rx.java.util.UserAgent;
import org.junit.Test;
import java.util.regex.Pattern;
import static com.mesosphere.mesos.rx.java.util.UserAgentEntries.literal;
import static com.mesosphere.mesos.rx.java.util.UserAgentEntries.userAgentEntryForGradleArtifact;
import static com.mesosphere.mesos.rx.java.util.UserAgentEntries.userAgentEntryForMavenArtifact;
import static org.assertj.core.api.Assertions.assertThat; | /*
* Copyright (C) 2015 Mesosphere, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mesosphere.mesos.rx.java;
public final class UserAgentTest {
@Test
public void testArtifactPropertyResolutionFunctionsCorrectly_gradle() throws Exception { | // Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgent.java
// public final class UserAgent {
//
// @NotNull
// private final List<UserAgentEntry> entries;
// @NotNull
// private final String toStringValue;
//
// @SafeVarargs
// public UserAgent(@NotNull final Function<Class<?>, UserAgentEntry>... entries) {
// this.entries =
// Collections.unmodifiableList(
// Arrays.asList(entries)
// .stream()
// .map(f -> f.apply(this.getClass()))
// .collect(Collectors.toList())
// );
// this.toStringValue = this.entries
// .stream()
// .map(UserAgentEntry::toString)
// .collect(Collectors.joining(" "));
// }
//
// @NotNull
// public List<UserAgentEntry> getEntries() {
// return entries;
// }
//
// @Override
// public String toString() {
// return toStringValue;
// }
//
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgentEntries.java
// @NotNull
// public static Function<Class<?>, UserAgentEntry> literal(@NotNull final String name, @NotNull final String version) {
// return (Class<?> c) -> new UserAgentEntry(name, version);
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgentEntries.java
// @NotNull
// public static Function<Class<?>, UserAgentEntry> userAgentEntryForGradleArtifact(@NotNull final String artifactId) {
// return (Class<?> c) -> {
// final Properties props = loadProperties(c, String.format("/META-INF/%s.properties", artifactId));
// return new UserAgentEntry(props.getProperty("artifactId", artifactId), props.getProperty("Implementation-Version", "unknown-version"));
// };
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgentEntries.java
// @NotNull
// public static Function<Class<?>, UserAgentEntry> userAgentEntryForMavenArtifact(@NotNull final String groupId, @NotNull final String artifactId) {
// return (Class<?> c) -> {
// final Properties props = loadProperties(c, String.format("/META-INF/maven/%s/%s/pom.properties", groupId, artifactId));
// return new UserAgentEntry(props.getProperty("artifactId", artifactId), props.getProperty("version", "unknown-version"));
// };
// }
// Path: mesos-rxjava-util/src/test/java/com/mesosphere/mesos/rx/java/UserAgentTest.java
import com.mesosphere.mesos.rx.java.util.UserAgent;
import org.junit.Test;
import java.util.regex.Pattern;
import static com.mesosphere.mesos.rx.java.util.UserAgentEntries.literal;
import static com.mesosphere.mesos.rx.java.util.UserAgentEntries.userAgentEntryForGradleArtifact;
import static com.mesosphere.mesos.rx.java.util.UserAgentEntries.userAgentEntryForMavenArtifact;
import static org.assertj.core.api.Assertions.assertThat;
/*
* Copyright (C) 2015 Mesosphere, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mesosphere.mesos.rx.java;
public final class UserAgentTest {
@Test
public void testArtifactPropertyResolutionFunctionsCorrectly_gradle() throws Exception { | final UserAgent agent = new UserAgent( |
mesosphere/mesos-rxjava | mesos-rxjava-util/src/test/java/com/mesosphere/mesos/rx/java/UserAgentTest.java | // Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgent.java
// public final class UserAgent {
//
// @NotNull
// private final List<UserAgentEntry> entries;
// @NotNull
// private final String toStringValue;
//
// @SafeVarargs
// public UserAgent(@NotNull final Function<Class<?>, UserAgentEntry>... entries) {
// this.entries =
// Collections.unmodifiableList(
// Arrays.asList(entries)
// .stream()
// .map(f -> f.apply(this.getClass()))
// .collect(Collectors.toList())
// );
// this.toStringValue = this.entries
// .stream()
// .map(UserAgentEntry::toString)
// .collect(Collectors.joining(" "));
// }
//
// @NotNull
// public List<UserAgentEntry> getEntries() {
// return entries;
// }
//
// @Override
// public String toString() {
// return toStringValue;
// }
//
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgentEntries.java
// @NotNull
// public static Function<Class<?>, UserAgentEntry> literal(@NotNull final String name, @NotNull final String version) {
// return (Class<?> c) -> new UserAgentEntry(name, version);
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgentEntries.java
// @NotNull
// public static Function<Class<?>, UserAgentEntry> userAgentEntryForGradleArtifact(@NotNull final String artifactId) {
// return (Class<?> c) -> {
// final Properties props = loadProperties(c, String.format("/META-INF/%s.properties", artifactId));
// return new UserAgentEntry(props.getProperty("artifactId", artifactId), props.getProperty("Implementation-Version", "unknown-version"));
// };
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgentEntries.java
// @NotNull
// public static Function<Class<?>, UserAgentEntry> userAgentEntryForMavenArtifact(@NotNull final String groupId, @NotNull final String artifactId) {
// return (Class<?> c) -> {
// final Properties props = loadProperties(c, String.format("/META-INF/maven/%s/%s/pom.properties", groupId, artifactId));
// return new UserAgentEntry(props.getProperty("artifactId", artifactId), props.getProperty("version", "unknown-version"));
// };
// }
| import com.mesosphere.mesos.rx.java.util.UserAgent;
import org.junit.Test;
import java.util.regex.Pattern;
import static com.mesosphere.mesos.rx.java.util.UserAgentEntries.literal;
import static com.mesosphere.mesos.rx.java.util.UserAgentEntries.userAgentEntryForGradleArtifact;
import static com.mesosphere.mesos.rx.java.util.UserAgentEntries.userAgentEntryForMavenArtifact;
import static org.assertj.core.api.Assertions.assertThat; | /*
* Copyright (C) 2015 Mesosphere, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mesosphere.mesos.rx.java;
public final class UserAgentTest {
@Test
public void testArtifactPropertyResolutionFunctionsCorrectly_gradle() throws Exception {
final UserAgent agent = new UserAgent( | // Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgent.java
// public final class UserAgent {
//
// @NotNull
// private final List<UserAgentEntry> entries;
// @NotNull
// private final String toStringValue;
//
// @SafeVarargs
// public UserAgent(@NotNull final Function<Class<?>, UserAgentEntry>... entries) {
// this.entries =
// Collections.unmodifiableList(
// Arrays.asList(entries)
// .stream()
// .map(f -> f.apply(this.getClass()))
// .collect(Collectors.toList())
// );
// this.toStringValue = this.entries
// .stream()
// .map(UserAgentEntry::toString)
// .collect(Collectors.joining(" "));
// }
//
// @NotNull
// public List<UserAgentEntry> getEntries() {
// return entries;
// }
//
// @Override
// public String toString() {
// return toStringValue;
// }
//
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgentEntries.java
// @NotNull
// public static Function<Class<?>, UserAgentEntry> literal(@NotNull final String name, @NotNull final String version) {
// return (Class<?> c) -> new UserAgentEntry(name, version);
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgentEntries.java
// @NotNull
// public static Function<Class<?>, UserAgentEntry> userAgentEntryForGradleArtifact(@NotNull final String artifactId) {
// return (Class<?> c) -> {
// final Properties props = loadProperties(c, String.format("/META-INF/%s.properties", artifactId));
// return new UserAgentEntry(props.getProperty("artifactId", artifactId), props.getProperty("Implementation-Version", "unknown-version"));
// };
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgentEntries.java
// @NotNull
// public static Function<Class<?>, UserAgentEntry> userAgentEntryForMavenArtifact(@NotNull final String groupId, @NotNull final String artifactId) {
// return (Class<?> c) -> {
// final Properties props = loadProperties(c, String.format("/META-INF/maven/%s/%s/pom.properties", groupId, artifactId));
// return new UserAgentEntry(props.getProperty("artifactId", artifactId), props.getProperty("version", "unknown-version"));
// };
// }
// Path: mesos-rxjava-util/src/test/java/com/mesosphere/mesos/rx/java/UserAgentTest.java
import com.mesosphere.mesos.rx.java.util.UserAgent;
import org.junit.Test;
import java.util.regex.Pattern;
import static com.mesosphere.mesos.rx.java.util.UserAgentEntries.literal;
import static com.mesosphere.mesos.rx.java.util.UserAgentEntries.userAgentEntryForGradleArtifact;
import static com.mesosphere.mesos.rx.java.util.UserAgentEntries.userAgentEntryForMavenArtifact;
import static org.assertj.core.api.Assertions.assertThat;
/*
* Copyright (C) 2015 Mesosphere, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mesosphere.mesos.rx.java;
public final class UserAgentTest {
@Test
public void testArtifactPropertyResolutionFunctionsCorrectly_gradle() throws Exception {
final UserAgent agent = new UserAgent( | userAgentEntryForGradleArtifact("rxnetty") |
mesosphere/mesos-rxjava | mesos-rxjava-util/src/test/java/com/mesosphere/mesos/rx/java/UserAgentTest.java | // Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgent.java
// public final class UserAgent {
//
// @NotNull
// private final List<UserAgentEntry> entries;
// @NotNull
// private final String toStringValue;
//
// @SafeVarargs
// public UserAgent(@NotNull final Function<Class<?>, UserAgentEntry>... entries) {
// this.entries =
// Collections.unmodifiableList(
// Arrays.asList(entries)
// .stream()
// .map(f -> f.apply(this.getClass()))
// .collect(Collectors.toList())
// );
// this.toStringValue = this.entries
// .stream()
// .map(UserAgentEntry::toString)
// .collect(Collectors.joining(" "));
// }
//
// @NotNull
// public List<UserAgentEntry> getEntries() {
// return entries;
// }
//
// @Override
// public String toString() {
// return toStringValue;
// }
//
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgentEntries.java
// @NotNull
// public static Function<Class<?>, UserAgentEntry> literal(@NotNull final String name, @NotNull final String version) {
// return (Class<?> c) -> new UserAgentEntry(name, version);
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgentEntries.java
// @NotNull
// public static Function<Class<?>, UserAgentEntry> userAgentEntryForGradleArtifact(@NotNull final String artifactId) {
// return (Class<?> c) -> {
// final Properties props = loadProperties(c, String.format("/META-INF/%s.properties", artifactId));
// return new UserAgentEntry(props.getProperty("artifactId", artifactId), props.getProperty("Implementation-Version", "unknown-version"));
// };
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgentEntries.java
// @NotNull
// public static Function<Class<?>, UserAgentEntry> userAgentEntryForMavenArtifact(@NotNull final String groupId, @NotNull final String artifactId) {
// return (Class<?> c) -> {
// final Properties props = loadProperties(c, String.format("/META-INF/maven/%s/%s/pom.properties", groupId, artifactId));
// return new UserAgentEntry(props.getProperty("artifactId", artifactId), props.getProperty("version", "unknown-version"));
// };
// }
| import com.mesosphere.mesos.rx.java.util.UserAgent;
import org.junit.Test;
import java.util.regex.Pattern;
import static com.mesosphere.mesos.rx.java.util.UserAgentEntries.literal;
import static com.mesosphere.mesos.rx.java.util.UserAgentEntries.userAgentEntryForGradleArtifact;
import static com.mesosphere.mesos.rx.java.util.UserAgentEntries.userAgentEntryForMavenArtifact;
import static org.assertj.core.api.Assertions.assertThat; | /*
* Copyright (C) 2015 Mesosphere, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mesosphere.mesos.rx.java;
public final class UserAgentTest {
@Test
public void testArtifactPropertyResolutionFunctionsCorrectly_gradle() throws Exception {
final UserAgent agent = new UserAgent(
userAgentEntryForGradleArtifact("rxnetty")
);
assertThat(agent.toString()).matches(Pattern.compile("rxnetty/\\d+\\.\\d+\\.\\d+"));
}
@Test
public void testArtifactPropertyResolutionFunctionsCorrectly_maven() throws Exception {
final UserAgent agent = new UserAgent( | // Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgent.java
// public final class UserAgent {
//
// @NotNull
// private final List<UserAgentEntry> entries;
// @NotNull
// private final String toStringValue;
//
// @SafeVarargs
// public UserAgent(@NotNull final Function<Class<?>, UserAgentEntry>... entries) {
// this.entries =
// Collections.unmodifiableList(
// Arrays.asList(entries)
// .stream()
// .map(f -> f.apply(this.getClass()))
// .collect(Collectors.toList())
// );
// this.toStringValue = this.entries
// .stream()
// .map(UserAgentEntry::toString)
// .collect(Collectors.joining(" "));
// }
//
// @NotNull
// public List<UserAgentEntry> getEntries() {
// return entries;
// }
//
// @Override
// public String toString() {
// return toStringValue;
// }
//
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgentEntries.java
// @NotNull
// public static Function<Class<?>, UserAgentEntry> literal(@NotNull final String name, @NotNull final String version) {
// return (Class<?> c) -> new UserAgentEntry(name, version);
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgentEntries.java
// @NotNull
// public static Function<Class<?>, UserAgentEntry> userAgentEntryForGradleArtifact(@NotNull final String artifactId) {
// return (Class<?> c) -> {
// final Properties props = loadProperties(c, String.format("/META-INF/%s.properties", artifactId));
// return new UserAgentEntry(props.getProperty("artifactId", artifactId), props.getProperty("Implementation-Version", "unknown-version"));
// };
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgentEntries.java
// @NotNull
// public static Function<Class<?>, UserAgentEntry> userAgentEntryForMavenArtifact(@NotNull final String groupId, @NotNull final String artifactId) {
// return (Class<?> c) -> {
// final Properties props = loadProperties(c, String.format("/META-INF/maven/%s/%s/pom.properties", groupId, artifactId));
// return new UserAgentEntry(props.getProperty("artifactId", artifactId), props.getProperty("version", "unknown-version"));
// };
// }
// Path: mesos-rxjava-util/src/test/java/com/mesosphere/mesos/rx/java/UserAgentTest.java
import com.mesosphere.mesos.rx.java.util.UserAgent;
import org.junit.Test;
import java.util.regex.Pattern;
import static com.mesosphere.mesos.rx.java.util.UserAgentEntries.literal;
import static com.mesosphere.mesos.rx.java.util.UserAgentEntries.userAgentEntryForGradleArtifact;
import static com.mesosphere.mesos.rx.java.util.UserAgentEntries.userAgentEntryForMavenArtifact;
import static org.assertj.core.api.Assertions.assertThat;
/*
* Copyright (C) 2015 Mesosphere, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mesosphere.mesos.rx.java;
public final class UserAgentTest {
@Test
public void testArtifactPropertyResolutionFunctionsCorrectly_gradle() throws Exception {
final UserAgent agent = new UserAgent(
userAgentEntryForGradleArtifact("rxnetty")
);
assertThat(agent.toString()).matches(Pattern.compile("rxnetty/\\d+\\.\\d+\\.\\d+"));
}
@Test
public void testArtifactPropertyResolutionFunctionsCorrectly_maven() throws Exception {
final UserAgent agent = new UserAgent( | userAgentEntryForMavenArtifact("org.assertj", "assertj-core") |
mesosphere/mesos-rxjava | mesos-rxjava-util/src/test/java/com/mesosphere/mesos/rx/java/UserAgentTest.java | // Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgent.java
// public final class UserAgent {
//
// @NotNull
// private final List<UserAgentEntry> entries;
// @NotNull
// private final String toStringValue;
//
// @SafeVarargs
// public UserAgent(@NotNull final Function<Class<?>, UserAgentEntry>... entries) {
// this.entries =
// Collections.unmodifiableList(
// Arrays.asList(entries)
// .stream()
// .map(f -> f.apply(this.getClass()))
// .collect(Collectors.toList())
// );
// this.toStringValue = this.entries
// .stream()
// .map(UserAgentEntry::toString)
// .collect(Collectors.joining(" "));
// }
//
// @NotNull
// public List<UserAgentEntry> getEntries() {
// return entries;
// }
//
// @Override
// public String toString() {
// return toStringValue;
// }
//
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgentEntries.java
// @NotNull
// public static Function<Class<?>, UserAgentEntry> literal(@NotNull final String name, @NotNull final String version) {
// return (Class<?> c) -> new UserAgentEntry(name, version);
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgentEntries.java
// @NotNull
// public static Function<Class<?>, UserAgentEntry> userAgentEntryForGradleArtifact(@NotNull final String artifactId) {
// return (Class<?> c) -> {
// final Properties props = loadProperties(c, String.format("/META-INF/%s.properties", artifactId));
// return new UserAgentEntry(props.getProperty("artifactId", artifactId), props.getProperty("Implementation-Version", "unknown-version"));
// };
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgentEntries.java
// @NotNull
// public static Function<Class<?>, UserAgentEntry> userAgentEntryForMavenArtifact(@NotNull final String groupId, @NotNull final String artifactId) {
// return (Class<?> c) -> {
// final Properties props = loadProperties(c, String.format("/META-INF/maven/%s/%s/pom.properties", groupId, artifactId));
// return new UserAgentEntry(props.getProperty("artifactId", artifactId), props.getProperty("version", "unknown-version"));
// };
// }
| import com.mesosphere.mesos.rx.java.util.UserAgent;
import org.junit.Test;
import java.util.regex.Pattern;
import static com.mesosphere.mesos.rx.java.util.UserAgentEntries.literal;
import static com.mesosphere.mesos.rx.java.util.UserAgentEntries.userAgentEntryForGradleArtifact;
import static com.mesosphere.mesos.rx.java.util.UserAgentEntries.userAgentEntryForMavenArtifact;
import static org.assertj.core.api.Assertions.assertThat; | /*
* Copyright (C) 2015 Mesosphere, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mesosphere.mesos.rx.java;
public final class UserAgentTest {
@Test
public void testArtifactPropertyResolutionFunctionsCorrectly_gradle() throws Exception {
final UserAgent agent = new UserAgent(
userAgentEntryForGradleArtifact("rxnetty")
);
assertThat(agent.toString()).matches(Pattern.compile("rxnetty/\\d+\\.\\d+\\.\\d+"));
}
@Test
public void testArtifactPropertyResolutionFunctionsCorrectly_maven() throws Exception {
final UserAgent agent = new UserAgent(
userAgentEntryForMavenArtifact("org.assertj", "assertj-core")
);
assertThat(agent.toString()).matches(Pattern.compile("assertj-core/\\d+\\.\\d+\\.\\d+"));
}
@Test
public void testEntriesOutputInCorrectOrder() throws Exception {
final UserAgent agent = new UserAgent( | // Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgent.java
// public final class UserAgent {
//
// @NotNull
// private final List<UserAgentEntry> entries;
// @NotNull
// private final String toStringValue;
//
// @SafeVarargs
// public UserAgent(@NotNull final Function<Class<?>, UserAgentEntry>... entries) {
// this.entries =
// Collections.unmodifiableList(
// Arrays.asList(entries)
// .stream()
// .map(f -> f.apply(this.getClass()))
// .collect(Collectors.toList())
// );
// this.toStringValue = this.entries
// .stream()
// .map(UserAgentEntry::toString)
// .collect(Collectors.joining(" "));
// }
//
// @NotNull
// public List<UserAgentEntry> getEntries() {
// return entries;
// }
//
// @Override
// public String toString() {
// return toStringValue;
// }
//
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgentEntries.java
// @NotNull
// public static Function<Class<?>, UserAgentEntry> literal(@NotNull final String name, @NotNull final String version) {
// return (Class<?> c) -> new UserAgentEntry(name, version);
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgentEntries.java
// @NotNull
// public static Function<Class<?>, UserAgentEntry> userAgentEntryForGradleArtifact(@NotNull final String artifactId) {
// return (Class<?> c) -> {
// final Properties props = loadProperties(c, String.format("/META-INF/%s.properties", artifactId));
// return new UserAgentEntry(props.getProperty("artifactId", artifactId), props.getProperty("Implementation-Version", "unknown-version"));
// };
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgentEntries.java
// @NotNull
// public static Function<Class<?>, UserAgentEntry> userAgentEntryForMavenArtifact(@NotNull final String groupId, @NotNull final String artifactId) {
// return (Class<?> c) -> {
// final Properties props = loadProperties(c, String.format("/META-INF/maven/%s/%s/pom.properties", groupId, artifactId));
// return new UserAgentEntry(props.getProperty("artifactId", artifactId), props.getProperty("version", "unknown-version"));
// };
// }
// Path: mesos-rxjava-util/src/test/java/com/mesosphere/mesos/rx/java/UserAgentTest.java
import com.mesosphere.mesos.rx.java.util.UserAgent;
import org.junit.Test;
import java.util.regex.Pattern;
import static com.mesosphere.mesos.rx.java.util.UserAgentEntries.literal;
import static com.mesosphere.mesos.rx.java.util.UserAgentEntries.userAgentEntryForGradleArtifact;
import static com.mesosphere.mesos.rx.java.util.UserAgentEntries.userAgentEntryForMavenArtifact;
import static org.assertj.core.api.Assertions.assertThat;
/*
* Copyright (C) 2015 Mesosphere, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mesosphere.mesos.rx.java;
public final class UserAgentTest {
@Test
public void testArtifactPropertyResolutionFunctionsCorrectly_gradle() throws Exception {
final UserAgent agent = new UserAgent(
userAgentEntryForGradleArtifact("rxnetty")
);
assertThat(agent.toString()).matches(Pattern.compile("rxnetty/\\d+\\.\\d+\\.\\d+"));
}
@Test
public void testArtifactPropertyResolutionFunctionsCorrectly_maven() throws Exception {
final UserAgent agent = new UserAgent(
userAgentEntryForMavenArtifact("org.assertj", "assertj-core")
);
assertThat(agent.toString()).matches(Pattern.compile("assertj-core/\\d+\\.\\d+\\.\\d+"));
}
@Test
public void testEntriesOutputInCorrectOrder() throws Exception {
final UserAgent agent = new UserAgent( | literal("first", "1"), |
mesosphere/mesos-rxjava | mesos-rxjava-client/src/main/java/com/mesosphere/mesos/rx/java/MesosClientBuilder.java | // Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/MessageCodec.java
// public interface MessageCodec<T> {
//
// /**
// * Serialize the given {@code message} into an array of bytes.
// *
// * @param message the message to serialize
// * @return the serialized message
// */
// @NotNull
// byte[] encode(@NotNull final T message);
//
// /**
// * Deserialize the given byte array into a message.
// *
// * @param bytes the bytes to deserialize
// * @return the deserialized message
// * @throws RuntimeException If an error occurs when decoding {@code bytes}. If a checked exception is possible
// * it should be wrapped in a RuntimeException.
// */
// @NotNull
// T decode(@NotNull final byte[] bytes);
//
// /**
// * Deserialize the given byte array into a message.
// *
// * @param in The {@link InputStream} to deserialize the message from
// * @return the deserialized message
// * @throws RuntimeException If an error occurs when decoding {@code bytes}. If a checked exception is possible
// * it should be wrapped in a RuntimeException.
// */
// @NotNull
// T decode(@NotNull final InputStream in);
//
// /**
// * Returns the <a target="_blank" href="https://en.wikipedia.org/wiki/Media_type">IANA media type</a> of the serialized message
// * format handled by this object.
// * <p>
// * The value returned by this method will be used in the {@code Content-Type} and {@code Accept} headers for
// * messages sent to and received from Mesos, respectively.
// *
// * @return the media type identifier
// */
// @NotNull
// String mediaType();
//
// /**
// * Renders the given {@code message} to informative, human-readable text.
// * <p>
// * The intent of this method is to allow messages to be easily read in program logs and while debugging.
// *
// * @param message the message to render
// * @return the rendered message
// */
// @NotNull
// String show(@NotNull final T message);
//
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgentEntry.java
// public final class UserAgentEntry {
// @NotNull
// private final String name;
// @NotNull
// private final String version;
// @Nullable
// private final String details;
//
// public UserAgentEntry(@NotNull final String name, @NotNull final String version) {
// this(name, version, null);
// }
//
// public UserAgentEntry(@NotNull final String name, @NotNull final String version, @Nullable final String details) {
// this.name = name;
// this.version = version;
// this.details = details;
// }
//
// @NotNull
// public String getName() {
// return name;
// }
//
// @NotNull
// public String getVersion() {
// return version;
// }
//
// @Nullable
// public String getDetails() {
// return details;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// final UserAgentEntry that = (UserAgentEntry) o;
// return Objects.equals(name, that.name) &&
// Objects.equals(version, that.version) &&
// Objects.equals(details, that.details);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(name, version, details);
// }
//
// @Override
// public String toString() {
// if (details != null) {
// return String.format("%s/%s (%s)", name, version, details);
// } else {
// return String.format("%s/%s", name, version);
// }
// }
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/Validations.java
// public static <T> T checkNotNull(@Nullable T ref) {
// return checkNotNull(ref, null);
// }
| import com.mesosphere.mesos.rx.java.util.MessageCodec;
import com.mesosphere.mesos.rx.java.util.UserAgentEntry;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import rx.BackpressureOverflow;
import rx.Observable;
import rx.functions.Action0;
import java.net.URI;
import java.util.Optional;
import java.util.function.Function;
import static com.mesosphere.mesos.rx.java.util.Validations.checkNotNull; | /*
* Copyright (C) 2015 Mesosphere, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mesosphere.mesos.rx.java;
/**
* Builder used to create a {@link MesosClient}.
* <p>
* PLEASE NOTE: All methods in this class function as "set" rather than "copy with new value"
* @param <Send> The type of objects that will be sent to Mesos
* @param <Receive> The type of objects that are expected from Mesos
*/
public final class MesosClientBuilder<Send, Receive> {
private URI mesosUri; | // Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/MessageCodec.java
// public interface MessageCodec<T> {
//
// /**
// * Serialize the given {@code message} into an array of bytes.
// *
// * @param message the message to serialize
// * @return the serialized message
// */
// @NotNull
// byte[] encode(@NotNull final T message);
//
// /**
// * Deserialize the given byte array into a message.
// *
// * @param bytes the bytes to deserialize
// * @return the deserialized message
// * @throws RuntimeException If an error occurs when decoding {@code bytes}. If a checked exception is possible
// * it should be wrapped in a RuntimeException.
// */
// @NotNull
// T decode(@NotNull final byte[] bytes);
//
// /**
// * Deserialize the given byte array into a message.
// *
// * @param in The {@link InputStream} to deserialize the message from
// * @return the deserialized message
// * @throws RuntimeException If an error occurs when decoding {@code bytes}. If a checked exception is possible
// * it should be wrapped in a RuntimeException.
// */
// @NotNull
// T decode(@NotNull final InputStream in);
//
// /**
// * Returns the <a target="_blank" href="https://en.wikipedia.org/wiki/Media_type">IANA media type</a> of the serialized message
// * format handled by this object.
// * <p>
// * The value returned by this method will be used in the {@code Content-Type} and {@code Accept} headers for
// * messages sent to and received from Mesos, respectively.
// *
// * @return the media type identifier
// */
// @NotNull
// String mediaType();
//
// /**
// * Renders the given {@code message} to informative, human-readable text.
// * <p>
// * The intent of this method is to allow messages to be easily read in program logs and while debugging.
// *
// * @param message the message to render
// * @return the rendered message
// */
// @NotNull
// String show(@NotNull final T message);
//
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgentEntry.java
// public final class UserAgentEntry {
// @NotNull
// private final String name;
// @NotNull
// private final String version;
// @Nullable
// private final String details;
//
// public UserAgentEntry(@NotNull final String name, @NotNull final String version) {
// this(name, version, null);
// }
//
// public UserAgentEntry(@NotNull final String name, @NotNull final String version, @Nullable final String details) {
// this.name = name;
// this.version = version;
// this.details = details;
// }
//
// @NotNull
// public String getName() {
// return name;
// }
//
// @NotNull
// public String getVersion() {
// return version;
// }
//
// @Nullable
// public String getDetails() {
// return details;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// final UserAgentEntry that = (UserAgentEntry) o;
// return Objects.equals(name, that.name) &&
// Objects.equals(version, that.version) &&
// Objects.equals(details, that.details);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(name, version, details);
// }
//
// @Override
// public String toString() {
// if (details != null) {
// return String.format("%s/%s (%s)", name, version, details);
// } else {
// return String.format("%s/%s", name, version);
// }
// }
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/Validations.java
// public static <T> T checkNotNull(@Nullable T ref) {
// return checkNotNull(ref, null);
// }
// Path: mesos-rxjava-client/src/main/java/com/mesosphere/mesos/rx/java/MesosClientBuilder.java
import com.mesosphere.mesos.rx.java.util.MessageCodec;
import com.mesosphere.mesos.rx.java.util.UserAgentEntry;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import rx.BackpressureOverflow;
import rx.Observable;
import rx.functions.Action0;
import java.net.URI;
import java.util.Optional;
import java.util.function.Function;
import static com.mesosphere.mesos.rx.java.util.Validations.checkNotNull;
/*
* Copyright (C) 2015 Mesosphere, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mesosphere.mesos.rx.java;
/**
* Builder used to create a {@link MesosClient}.
* <p>
* PLEASE NOTE: All methods in this class function as "set" rather than "copy with new value"
* @param <Send> The type of objects that will be sent to Mesos
* @param <Receive> The type of objects that are expected from Mesos
*/
public final class MesosClientBuilder<Send, Receive> {
private URI mesosUri; | private Function<Class<?>, UserAgentEntry> applicationUserAgentEntry; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.