Commit 1e19babb authored by Matija Obreza's avatar Matija Obreza

Cleanup

parent d533b35b
......@@ -54,8 +54,7 @@ import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
public class GenesysClient {
private static final Logger _log = LogManager
.getLogger(GenesysClient.class);
private static final Logger _log = LogManager.getLogger(GenesysClient.class);
private static final Token EMPTY_TOKEN = null;
private static final String SCOPE = "read,write";
......@@ -107,9 +106,7 @@ public class GenesysClient {
}
final String baseUrl = this.properties.getProperty("base.url");
this.genesysApi = new GenesysApi(baseUrl,
properties.getProperty("client.key"),
properties.getProperty("client.secret"));
this.genesysApi = new GenesysApi(baseUrl, properties.getProperty("client.key"), properties.getProperty("client.secret"));
this.apiUrl = baseUrl + this.properties.getProperty("api.url");
final String httpAuth = this.properties.getProperty("http.auth");
......@@ -117,25 +114,20 @@ public class GenesysClient {
if (StringUtils.isNotBlank(httpAuth) && httpAuth.contains(":")) {
_log.warn("Using HTTP AUTH " + httpAuth);
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
httpAuth.split(":", 2)[0],
httpAuth.split(":", 2)[1].toCharArray());
return new PasswordAuthentication(httpAuth.split(":", 2)[0], httpAuth.split(":", 2)[1].toCharArray());
}
});
}
// CropHub auth service
this.service = new ServiceBuilder().provider(this.genesysApi)
.apiKey(properties.getProperty("client.key"))
.apiSecret(properties.getProperty("client.secret"))
.callback(OOB_CALLBACK).scope(SCOPE).build();
this.service = new ServiceBuilder().provider(this.genesysApi).apiKey(properties.getProperty("client.key")).apiSecret(properties.getProperty("client.secret")).callback(OOB_CALLBACK)
.scope(SCOPE).build();
this.accessToken = makeToken(this.properties
.getProperty("access.token"));
this.accessToken = makeToken(this.properties.getProperty("access.token"));
this.refreshToken = makeToken(this.properties
.getProperty("refresh.token"));
this.refreshToken = makeToken(this.properties.getProperty("refresh.token"));
}
private Token makeToken(String tokenKey) {
......@@ -184,8 +176,7 @@ public class GenesysClient {
String data = StringUtils.defaultIfBlank(in.nextLine(), null);
// Exec
System.out.println("Put dataset: "
+ query(Verb.valueOf(method), url, null, data));
System.out.println("Put dataset: " + query(Verb.valueOf(method), url, null, data));
}
private void doTraits() throws OAuthAuthenticationException {
......@@ -240,12 +231,10 @@ public class GenesysClient {
datasetJson.put("description", in.nextLine());
System.out.println("UOM: ");
datasetJson
.put("unit", StringUtils.defaultIfBlank(in.nextLine(), null));
datasetJson.put("unit", StringUtils.defaultIfBlank(in.nextLine(), null));
System.out.println("Field name: ");
datasetJson.put("fieldName",
StringUtils.defaultIfBlank(in.nextLine(), null));
datasetJson.put("fieldName", StringUtils.defaultIfBlank(in.nextLine(), null));
System.out.println("Field type: (0=String, 1=Double, 2=Long)");
int fieldType = Integer.parseInt(in.nextLine());
......@@ -257,18 +246,15 @@ public class GenesysClient {
}
System.out.println("Options: ");
datasetJson.put("options",
StringUtils.defaultIfBlank(in.nextLine(), null));
datasetJson.put("options", StringUtils.defaultIfBlank(in.nextLine(), null));
System.out.println("Range: ");
datasetJson.put("range",
StringUtils.defaultIfBlank(in.nextLine(), null));
datasetJson.put("range", StringUtils.defaultIfBlank(in.nextLine(), null));
System.err.println(datasetJson.toString());
// make a dataset
System.out.println("Put method: "
+ query(Verb.PUT, "/methods", null, datasetJson.toString()));
System.out.println("Put method: " + query(Verb.PUT, "/methods", null, datasetJson.toString()));
}
......@@ -286,8 +272,7 @@ public class GenesysClient {
System.err.println(datasetJson.toString());
// make a dataset
System.out.println("Put dataset: "
+ query(Verb.PUT, "/datasets", null, datasetJson.toString()));
System.out.println("Put dataset: " + query(Verb.PUT, "/datasets", null, datasetJson.toString()));
}
......@@ -305,9 +290,7 @@ public class GenesysClient {
System.err.println(datasetJson.toString());
// make a dataset
System.out.println("Put dataset: "
+ query(Verb.PUT, "/datasets/" + datasetId + "/data", null,
datasetJson.toString()));
System.out.println("Put dataset: " + query(Verb.PUT, "/datasets/" + datasetId + "/data", null, datasetJson.toString()));
}
private void addDatasetRaw() throws OAuthAuthenticationException {
......@@ -320,9 +303,7 @@ public class GenesysClient {
System.err.println(json);
// make a dataset
System.out.println("Put dataset: "
+ query(Verb.PUT, "/datasets/" + datasetId + "/data", null,
json));
System.out.println("Put dataset: " + query(Verb.PUT, "/datasets/" + datasetId + "/data", null, json));
}
private void authenticate() {
......@@ -336,9 +317,7 @@ public class GenesysClient {
// Trade the Request Token and Verfier for the Access Token
accessToken = service.getAccessToken(EMPTY_TOKEN, verifier);
_log.info("ACCESS TOKEN: " + accessToken.getToken() + " sec="
+ accessToken.getSecret() + " raw="
+ accessToken.getRawResponse());
_log.info("ACCESS TOKEN: " + accessToken.getToken() + " sec=" + accessToken.getSecret() + " raw=" + accessToken.getRawResponse());
this.properties.put("access.token", accessToken.getToken());
......@@ -393,14 +372,11 @@ public class GenesysClient {
}
}
private String query(String url) throws OAuthAuthenticationException,
PleaseRetryException {
private String query(String url) throws OAuthAuthenticationException, PleaseRetryException {
return query(Verb.GET, url, null, null);
}
private String query(Verb method, String url,
Map<String, String> queryString, String postBody)
throws OAuthAuthenticationException, PleaseRetryException {
private String query(Verb method, String url, Map<String, String> queryString, String postBody) throws OAuthAuthenticationException, PleaseRetryException {
if (accessToken == null) {
refreshAccessToken();
......@@ -460,14 +436,11 @@ public class GenesysClient {
_log.error(postBody);
_log.error("HTTP response code: " + response.getCode());
_log.error("Response: " + responseBody);
if (responseBody
.contains("Deadlock found when trying to get lock; try restarting transaction")
|| responseBody
.contains("nested exception is org.hibernate.exception.LockAcquisitionException: could not execute statement")) {
if (responseBody.contains("Deadlock found when trying to get lock; try restarting transaction")
|| responseBody.contains("nested exception is org.hibernate.exception.LockAcquisitionException: could not execute statement")) {
throw new PleaseRetryException(responseBody);
} else
throw new RuntimeException("Unexpected error: "
+ responseBody);
throw new RuntimeException("Unexpected error: " + responseBody);
}
}
}
......@@ -491,24 +464,20 @@ public class GenesysClient {
}
}
public String accessionExists(String instCode, String acceNumb, String genus)
throws OAuthAuthenticationException {
public String accessionExists(String instCode, String acceNumb, String genus) throws OAuthAuthenticationException {
try {
HashMap<String, String> queryString = new HashMap<String, String>();
queryString.put("acceNumb", acceNumb);
return query(Verb.GET, new URI(null, null, "/acn/exists/"
+ instCode + "/" + genus, null).toString(), queryString,
null);
return query(Verb.GET, new URI(null, null, "/acn/exists/" + instCode + "/" + genus, null).toString(), queryString, null);
} catch (URISyntaxException e) {
e.printStackTrace();
return null;
}
}
public static ObjectNode makeAid3(String instCode, String genus,
String acceNumb) {
public static ObjectNode makeAid3(String instCode, String genus, String acceNumb) {
ObjectNode json = mapper.createObjectNode();
json.put("instCode", instCode);
json.put("acceNumb", acceNumb);
......@@ -516,8 +485,7 @@ public class GenesysClient {
return json;
}
public String updateMLS(String instCode, Collection<ObjectNode> accns)
throws OAuthAuthenticationException {
public String updateMLS(String instCode, Collection<ObjectNode> accns) throws OAuthAuthenticationException {
ArrayNode arr = mapper.createArrayNode();
for (ObjectNode accn : accns) {
......@@ -525,24 +493,20 @@ public class GenesysClient {
}
_log.debug("Sending: " + arr);
return query(Verb.PUT, "/acn/" + instCode + "/update", null,
arr.toString());
return query(Verb.PUT, "/acn/" + instCode + "/update", null, arr.toString());
}
public String accessionExists(String instCode, Collection<ObjectNode> accns)
throws OAuthAuthenticationException {
public String accessionExists(String instCode, Collection<ObjectNode> accns) throws OAuthAuthenticationException {
ArrayNode arr = mapper.createArrayNode();
for (ObjectNode accn : accns) {
arr.add(accn);
}
_log.debug("Sending: " + arr);
return query(Verb.PUT, "/acn/" + instCode + "/check", null,
arr.toString());
return query(Verb.PUT, "/acn/" + instCode + "/check", null, arr.toString());
}
public String updateAccessions(String instCode, Collection<ObjectNode> accns)
throws OAuthAuthenticationException {
public String updateAccessions(String instCode, Collection<ObjectNode> accns) throws OAuthAuthenticationException {
if (accns == null || accns.size() == 0) {
return null;
......@@ -557,11 +521,9 @@ public class GenesysClient {
for (int retry = 0; retry < 5; retry++) {
try {
return query(Verb.PUT, "/acn/" + instCode + "/upsert", null,
arr.toString());
return query(Verb.PUT, "/acn/" + instCode + "/upsert", null, arr.toString());
} catch (PleaseRetryException e) {
long sleepTime = (long) (Math.pow(2, retry) * 100 + Math.pow(2,
retry) * 2500 * Math.random());
long sleepTime = (long) (Math.pow(2, retry) * 100 + Math.pow(2, retry) * 2500 * Math.random());
_log.warn("Retrying PUT after " + sleepTime + " ms.");
try {
Thread.sleep(sleepTime);
......@@ -573,12 +535,10 @@ public class GenesysClient {
throw new RuntimeException("All retries failed");
}
public String updateOrganizationMembers(String organizationSlug,
ArrayNode institutes) throws OAuthAuthenticationException {
public String updateOrganizationMembers(String organizationSlug, ArrayNode institutes) throws OAuthAuthenticationException {
_log.debug("Sending: " + institutes);
try {
return query(Verb.PUT, "/org/" + organizationSlug
+ "/set-institutes", null, institutes.toString());
return query(Verb.PUT, "/org/" + organizationSlug + "/set-institutes", null, institutes.toString());
} catch (PleaseRetryException e) {
_log.warn("Retrying PUT after some time...");
try {
......@@ -586,17 +546,14 @@ public class GenesysClient {
} catch (InterruptedException e1) {
e1.printStackTrace();
}
return query(Verb.PUT, "/org/" + organizationSlug
+ "/set-institutes", null, institutes.toString());
return query(Verb.PUT, "/org/" + organizationSlug + "/set-institutes", null, institutes.toString());
}
}
public String updateAccessionNames(String instCode,
Collection<ObjectNode> batch) throws OAuthAuthenticationException {
public String updateAccessionNames(String instCode, Collection<ObjectNode> batch) throws OAuthAuthenticationException {
_log.debug("Sending: " + batch);
try {
return query(Verb.PUT, "/acn/" + instCode + "/names", null,
batch.toString());
return query(Verb.PUT, "/acn/" + instCode + "/names", null, batch.toString());
} catch (PleaseRetryException e) {
_log.warn("Retrying PUT after some time...");
try {
......@@ -605,14 +562,11 @@ public class GenesysClient {
e1.printStackTrace();
}
_log.warn("Retrying PUT");
return query(Verb.PUT, "/acn/" + instCode + "/names", null,
batch.toString());
return query(Verb.PUT, "/acn/" + instCode + "/names", null, batch.toString());
}
}
public String deleteAccessions(String instCode, ArrayNode array)
throws OAuthAuthenticationException {
return query(Verb.PUT, "/acn/" + instCode + "/delete", null,
array.toString());
public String deleteAccessions(String instCode, ArrayNode array) throws OAuthAuthenticationException {
return query(Verb.PUT, "/acn/" + instCode + "/delete", null, array.toString());
}
}
......@@ -48,8 +48,7 @@ public class GenesysApi extends DefaultApi20 {
this.authorizeUrl = this.baseUrl + AUTHORIZE_URL;
this.scopedAuthorizeUrl = this.authorizeUrl + "&scope=%s";
this.refreshTokenEndpoint = this.baseUrl + TOKEN_ENDPOINT;
this.accessTokenEndpoint = this.baseUrl + TOKEN_ENDPOINT
+ "?grant_type=authorization_code";
this.accessTokenEndpoint = this.baseUrl + TOKEN_ENDPOINT + "?grant_type=authorization_code";
this.clientKey = clientKey;
this.clientSecret = clientSecret;
}
......@@ -66,12 +65,8 @@ public class GenesysApi extends DefaultApi20 {
@Override
public String getAuthorizationUrl(OAuthConfig config) {
return config.hasScope() ? String.format(this.scopedAuthorizeUrl,
config.getApiKey(), config.getApiSecret(),
OAuthEncoder.encode(config.getCallback()),
OAuthEncoder.encode(config.getScope())) : String.format(
this.authorizeUrl, config.getApiKey(), config.getApiSecret(),
OAuthEncoder.encode(config.getCallback()));
return config.hasScope() ? String.format(this.scopedAuthorizeUrl, config.getApiKey(), config.getApiSecret(), OAuthEncoder.encode(config.getCallback()), OAuthEncoder.encode(config.getScope()))
: String.format(this.authorizeUrl, config.getApiKey(), config.getApiSecret(), OAuthEncoder.encode(config.getCallback()));
}
@Override
......@@ -80,11 +75,9 @@ public class GenesysApi extends DefaultApi20 {
}
public Token getRefreshToken(Token accessToken) {
Pattern refreshTokenPattern = Pattern
.compile("\"refresh_token\":\\s*\"(\\S*?)\"");
Pattern refreshTokenPattern = Pattern.compile("\"refresh_token\":\\s*\"(\\S*?)\"");
Matcher matcher = refreshTokenPattern.matcher(accessToken
.getRawResponse());
Matcher matcher = refreshTokenPattern.matcher(accessToken.getRawResponse());
if (matcher.find()) {
return new Token(matcher.group(1), "", accessToken.getRawResponse());
}
......@@ -102,14 +95,11 @@ public class GenesysApi extends DefaultApi20 {
* @throws OAuthAuthenticationException
*/
public Token getAccessToken(Token refreshToken) {
OAuthRequest request = new OAuthRequest(getAccessTokenVerb(),
this.refreshTokenEndpoint);
OAuthRequest request = new OAuthRequest(getAccessTokenVerb(), this.refreshTokenEndpoint);
request.addQuerystringParameter(OAuthConstants.CLIENT_ID, clientKey);
request.addQuerystringParameter(OAuthConstants.CLIENT_SECRET,
clientSecret);
request.addQuerystringParameter(OAuthConstants.CLIENT_SECRET, clientSecret);
request.addQuerystringParameter("grant_type", "refresh_token");
request.addQuerystringParameter("refresh_token",
refreshToken.getToken());
request.addQuerystringParameter("refresh_token", refreshToken.getToken());
Response response = request.send();
return getAccessTokenExtractor().extract(response.getBody());
}
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment