Commit 44ad36bf authored by Matija Obreza's avatar Matija Obreza

Updated javadoc and code cleanup

parent 9cab9d3a
/*
* Copyright 2016 Global Crop Diversity Trust
*
*
* 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.
......@@ -106,7 +106,7 @@ public class CLI {
try {
System.out.println("/me: " + genesysClient.query("/me"));
this.properties.put("access.token", genesysClient.getTokens().getAccessToken());
properties.put("access.token", genesysClient.getTokens().getAccessToken());
saveProperties();
} catch (final OAuthAuthenticationException e) {
......@@ -302,9 +302,10 @@ public class CLI {
updateCropRules();
} else if ("9".equals(line)) {
System.out.println("/methods: " + genesysClient.query("/methods"));
} else if ("0".equalsIgnoreCase(line))
} else if ("0".equalsIgnoreCase(line)) {
return;
} while (!("0".equalsIgnoreCase(line)));
}
} while (!"0".equalsIgnoreCase(line));
}
/**
......@@ -397,9 +398,10 @@ public class CLI {
addMethod();
} else if ("9".equals(line)) {
System.out.println("/methods: " + genesysClient.query("/methods"));
} else if ("0".equalsIgnoreCase(line))
} else if ("0".equalsIgnoreCase(line)) {
return;
} while (!("0".equalsIgnoreCase(line)));
}
} while (!"0".equalsIgnoreCase(line));
}
/**
......@@ -425,9 +427,10 @@ public class CLI {
addDatasetData();
} else if ("4".equals(line)) {
addDatasetRaw();
} else if ("0".equalsIgnoreCase(line))
} else if ("0".equalsIgnoreCase(line)) {
return;
} while (!("0".equalsIgnoreCase(line)));
}
} while (!"0".equalsIgnoreCase(line));
}
/**
......@@ -574,10 +577,10 @@ public class CLI {
// Trade the Request Token and Verifier for the Access Token
genesysClient.authenticate(verifierCode);
this.properties.put("access.token", genesysClient.getTokens().getAccessToken());
properties.put("access.token", genesysClient.getTokens().getAccessToken());
// Get refresh token ()
this.properties.put("refresh.token", genesysClient.getTokens().getRefreshToken());
properties.put("refresh.token", genesysClient.getTokens().getRefreshToken());
saveProperties();
}
......@@ -589,7 +592,7 @@ public class CLI {
FileOutputStream fis = null;
try {
fis = new FileOutputStream(propertiesFile);
this.properties.store(fis, "OAuth client properties");
properties.store(fis, "OAuth client properties");
} catch (final IOException e) {
_log.error(e);
} finally {
......
/*
* Copyright 2016 Global Crop Diversity Trust
*
*
* 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.
......
/*
* Copyright 2016 Global Crop Diversity Trust
*
*
* 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.
......@@ -101,8 +101,6 @@ public class GenesysClient {
/** UTF8 charset */
private static Charset CHARSET_UTF8 = Charset.forName("UTF8");
static {
objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true);
......@@ -217,12 +215,13 @@ public class GenesysClient {
*
* @param clientId the client id
* @param clientSecret the client secret
* @param callbackUrl the callback URL for web-based clients. Use "oob" for out-of-band authentication.
* @param callbackUrl the callback URL for web-based clients. Use "oob" for out-of-band
* authentication.
*/
public void connect(final String clientId, final String clientSecret, final String callbackUrl) {
this.apiKey = clientId;
this.apiSecret = clientSecret;
this.service = new ServiceBuilder().provider(this.genesysApi).apiKey(clientId).apiSecret(clientSecret).callback(callbackUrl).scope(SCOPE).build();
apiKey = clientId;
apiSecret = clientSecret;
service = new ServiceBuilder().provider(genesysApi).apiKey(clientId).apiSecret(clientSecret).callback(callbackUrl).scope(SCOPE).build();
}
/**
......@@ -286,10 +285,11 @@ public class GenesysClient {
public String query(final Verb method, final String url, final Map<String, String> queryString, final String postBody)
throws OAuthAuthenticationException, PleaseRetryException, HttpRedirectException, GenesysApiException {
if (StringUtils.isBlank(postBody))
if (StringUtils.isBlank(postBody)) {
return query(method, url, queryString, null, null);
else
} else {
return query(method, url, queryString, ContentType.APPLICATION_JSON.withCharset(CHARSET_UTF8).getMimeType(), postBody.getBytes(CHARSET_UTF8));
}
}
/**
......@@ -337,8 +337,8 @@ public class GenesysClient {
service.signRequest(tokens.accessToken(), request);
request.setConnectionKeepAlive(true);
request.setConnectTimeout(this.connectTimeout, TimeUnit.SECONDS);
request.setReadTimeout(this.readTimeout, TimeUnit.SECONDS);
request.setConnectTimeout(connectTimeout, TimeUnit.SECONDS);
request.setReadTimeout(readTimeout, TimeUnit.SECONDS);
request.setCharset("UTF-8");
Response response = null;
......@@ -365,8 +365,9 @@ public class GenesysClient {
System.err.println(responseBody);
if (i == 0) {
refreshAccessToken();
} else
} else {
throw new OAuthAuthenticationException("Unauthorized");
}
} else {
_log.error(method + " " + request.getCompleteUrl());
_log.error(postBody);
......@@ -374,10 +375,11 @@ public class GenesysClient {
_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")
|| responseBody.contains("nested exception is org.hibernate.exception.LockTimeoutException: could not execute statement"))
|| responseBody.contains("nested exception is org.hibernate.exception.LockTimeoutException: could not execute statement")) {
throw new PleaseRetryException(responseBody);
else
} else {
throw new GenesysApiException("Unexpected error: " + responseBody);
}
}
}
}
......@@ -403,7 +405,7 @@ public class GenesysClient {
if (tokens.hasRefreshToken()) {
_log.info("Using Refresh Token to get new access token");
try {
final Token accessToken = genesysApi.getAccessToken(this.apiKey, this.apiSecret, tokens.getRefreshToken());
final Token accessToken = genesysApi.getAccessToken(apiKey, apiSecret, tokens.getRefreshToken());
tokens.setAccessToken(accessToken.getToken());
_log.info("Got new Access Token!");
......@@ -411,8 +413,9 @@ public class GenesysClient {
_log.info("Refresh token didn't work: " + e.getMessage());
throw new OAuthAuthenticationException("Refresh token not valid, please re-authenticate");
}
} else
} else {
throw new OAuthAuthenticationException("No refresh token, please re-authenticate");
}
}
/**
......@@ -462,21 +465,24 @@ public class GenesysClient {
* @throws GenesysApiException the genesys api exception
* @throws PleaseRetryException the please retry exception
* @throws JsonProcessingException the json processing exception
* @deprecated Please use {@link #updateAccessions(String, Collection)} with only the instCode, acceNumb, (genus, ) and mlsStat provided.
* @deprecated Please use {@link #updateAccessions(String, Collection)} with only the instCode,
* acceNumb, (genus, ) and mlsStat provided.
*/
@Deprecated
public String updateMLS(final String instCode, final Collection<ObjectNode> accns) throws GenesysApiException, PleaseRetryException, JsonProcessingException {
if (accns == null || accns.size() == 0)
if (accns == null || accns.size() == 0) {
return null;
}
_log.debug("Sending: " + accns);
return query(Verb.PUT, "/acn/" + instCode + "/update", null, objectMapper.writeValueAsString(accns));
}
/**
* Update accession information with new values provided in the JSON string. In case of {@link PleaseRetryException}, this method will attempt to re-send the data 5 times
* before giving up.
* Update accession information with new values provided in the JSON string. In case of
* {@link PleaseRetryException}, this method will attempt to re-send the data 5 times before
* giving up.
*
* @param instCode the WIEWS institute code
* @param jsonAccessionList the JSON array of accessions
......@@ -512,8 +518,9 @@ public class GenesysClient {
*/
public String updateAccessions(final String instCode, final Collection<AccessionJson> accns) throws GenesysApiException, InterruptedException, JsonProcessingException {
if (accns == null || accns.size() == 0)
if (accns == null || accns.size() == 0) {
return null;
}
final String data = objectMapper.writeValueAsString(accns);
......@@ -641,7 +648,7 @@ public class GenesysClient {
* @return the authorization url
*/
public String getAuthorizationUrl() {
return this.service.getAuthorizationUrl(null);
return service.getAuthorizationUrl(null);
}
/**
......@@ -684,8 +691,9 @@ public class GenesysClient {
* @throws GenesysApiException the genesys api exception
*/
public String getCrop(final String shortName) throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException {
if (!shortName.matches("^\\w+$"))
if (!shortName.matches("^\\w+$")) {
throw new GenesysApiException("Crop shortname can only contain characters");
}
return query("/crops/" + shortName);
}
......@@ -1091,14 +1099,16 @@ public class GenesysClient {
}
/**
* List existing image galleries for INSTCODE. The response is paginated, provide <code>page</page> argument to request a specific page.
* List existing image galleries for INSTCODE. The response is paginated, provide
* <code>page</code> argument to request a specific page.
*
* @param instCode institute code (MCPD INSTCODE)
* @param page 1 for first page
* @throws GenesysApiException
* @throws HttpRedirectException
* @throws PleaseRetryException
* @throws OAuthAuthenticationException
* @return the string
* @throws OAuthAuthenticationException the o auth authentication exception
* @throws PleaseRetryException the please retry exception
* @throws HttpRedirectException the http redirect exception
* @throws GenesysApiException the genesys api exception
*/
public String listGalleries(final String instCode, final int page) throws OAuthAuthenticationException, PleaseRetryException, HttpRedirectException, GenesysApiException {
return query(Verb.GET, String.format("/img/%1$s/_galleries", instCode), Collections.singletonMap("page", Integer.toString(page)), null);
......@@ -1108,11 +1118,14 @@ public class GenesysClient {
* List UUIDs of images in an existing accession gallery.
*
* @param instCode institute code (MCPD INSTCODE)
* @param page 1 for first page
* @throws GenesysApiException
* @throws HttpRedirectException
* @throws PleaseRetryException
* @throws OAuthAuthenticationException
* @param acceNumb the acce numb
* @return the list
* @throws OAuthAuthenticationException the o auth authentication exception
* @throws PleaseRetryException the please retry exception
* @throws GenesysApiException the genesys api exception
* @throws JsonParseException the json parse exception
* @throws JsonMappingException the json mapping exception
* @throws IOException Signals that an I/O exception has occurred.
*/
public List<UUID> listGalleryImages(final String instCode, final String acceNumb)
throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException, JsonParseException, JsonMappingException, IOException {
......@@ -1121,23 +1134,25 @@ public class GenesysClient {
return objectMapper.readValue(json, new TypeReference<List<UUID>>() {
});
}
/**
* Add image to accession
* Add image to accession.
*
* @param instCode institute code (MCPD INSTCODE)
* @param acceNumb accession number (MCPD ACCENUMB)
* @param file image to upload
*
* @param contentType the content type
* @return the repository image
* @throws GenesysApiException the genesys api exception
* @throws IOException if file cannot be read
* @throws GenesysApiException
*/
public RepositoryImage uploadImage(final String instCode, final String acceNumb, final File file, final String contentType) throws GenesysApiException, IOException {
if (StringUtils.isBlank(contentType))
if (StringUtils.isBlank(contentType)) {
throw new GenesysApiException("Content-Type must be provided for the file " + file.getAbsolutePath());
}
_log.debug("Image content type: " + contentType);
// PUT file on server
final String json = query(Verb.PUT, String.format("/img/%1$s/acn/%2$s/", instCode, acceNumb), Collections.singletonMap("originalFilename", file.getName()), contentType,
FileUtils.readFileToByteArray(file));
......@@ -1148,28 +1163,29 @@ public class GenesysClient {
}
/**
* Remove image from accession gallery by UUID. URL template: <code>/img/{instCode}/acn/{acceNumb:.+}/{uuid}/_metadata</code>
* Remove image from accession gallery by UUID. URL template:
* <code>/img/{instCode}/acn/{acceNumb:.+}/{uuid}/_metadata</code>
*
* @param instCode institute code (MCPD INSTCODE)
* @param acceNumb accession number (MCPD ACCENUMB)
* @param uuid Repository image UUID as assigned by Genesys
* @throws GenesysApiException
* @throws PleaseRetryException
* @throws OAuthAuthenticationException
* @throws OAuthAuthenticationException the o auth authentication exception
* @throws PleaseRetryException the please retry exception
* @throws GenesysApiException the genesys api exception
*/
public void deleteImage(final String instCode, final String acceNumb, final UUID uuid) throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException {
query(Verb.DELETE, String.format("/img/%1$s/acn/%2$s/%3$s", instCode, acceNumb, uuid));
}
/**
* Get image metadata from Genesys
* Get image metadata from Genesys.
*
* @param instCode institute code (MCPD INSTCODE)
* @param acceNumb accession number (MCPD ACCENUMB)
* @param uuid Repository image UUID as assigned by Genesys
* @return the metadata
* @throws GenesysApiException
* @throws IOException
* @throws GenesysApiException the genesys api exception
* @throws IOException Signals that an I/O exception has occurred.
*/
public RepositoryImage getImageMetadata(final String instCode, final String acceNumb, final UUID uuid) throws GenesysApiException, IOException {
// PUT file on server
......@@ -1180,14 +1196,16 @@ public class GenesysClient {
}
/**
* Set image metadata. Endpoint <b>PUT</b> <code>/img/{instCode}/acn/{acceNumb:.+}/{uuid}/_metadata</code>
* Set image metadata. Endpoint <b>PUT</b>
* <code>/img/{instCode}/acn/{acceNumb:.+}/{uuid}/_metadata</code>
*
* @param instCode institute code (MCPD INSTCODE)
* @param acceNumb accession number (MCPD ACCENUMB)
* @param uuid Repository image UUID as assigned by Genesys
* @param imageData the image data
* @return the metadata
* @throws GenesysApiException
* @throws IOException
* @throws GenesysApiException the genesys api exception
* @throws IOException Signals that an I/O exception has occurred.
*/
public RepositoryImage putImageMetadata(final String instCode, final String acceNumb, final UUID uuid, final RepositoryImage imageData)
throws GenesysApiException, IOException {
......
/*
* Copyright 2016 Global Crop Diversity Trust
*
*
* 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.
......@@ -54,7 +54,7 @@ public class GenesysTokens implements Serializable {
*/
public void setAccessToken(final String accessToken) {
this.accessToken = accessToken;
this._accessToken = new Token(accessToken, "");
_accessToken = new Token(accessToken, "");
}
/**
......@@ -81,7 +81,7 @@ public class GenesysTokens implements Serializable {
* @return true, if successful
*/
public boolean hasRefreshToken() {
return StringUtils.isNotBlank(this.refreshToken);
return StringUtils.isNotBlank(refreshToken);
}
/**
......@@ -90,7 +90,7 @@ public class GenesysTokens implements Serializable {
* @return true, if successful
*/
public boolean hasAccessToken() {
return StringUtils.isNotBlank(this.accessToken);
return StringUtils.isNotBlank(accessToken);
}
/**
......@@ -99,6 +99,6 @@ public class GenesysTokens implements Serializable {
* @return the token
*/
public Token accessToken() {
return this._accessToken;
return _accessToken;
}
}
/*
* Copyright 2016 Global Crop Diversity Trust
*
*
* 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.
......
/*
* Copyright 2016 Global Crop Diversity Trust
*
*
* 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.
......
/*
* Copyright 2016 Global Crop Diversity Trust
*
*
* 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.
......@@ -16,9 +16,9 @@
package org.genesys2.client.oauth;
// TODO: Auto-generated Javadoc
/**
* API exception indicating that the operation failed due to concurrency issues and should be retried by the client.
* API exception indicating that the operation failed due to concurrency issues and should be
* retried by the client.
*/
public class PleaseRetryException extends GenesysApiException {
......
/*
* Copyright 2016 Global Crop Diversity Trust
*
*
* 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.
......@@ -70,10 +70,10 @@ public class GenesysApi extends DefaultApi20 {
*/
public void setBaseUrl(final String baseUrl) {
this.baseUrl = baseUrl;
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";
authorizeUrl = this.baseUrl + AUTHORIZE_URL;
scopedAuthorizeUrl = authorizeUrl + "&scope=%s";
refreshTokenEndpoint = this.baseUrl + TOKEN_ENDPOINT;
accessTokenEndpoint = this.baseUrl + TOKEN_ENDPOINT + "?grant_type=authorization_code";
}
/*
......@@ -83,7 +83,7 @@ public class GenesysApi extends DefaultApi20 {
*/
@Override
public String getAccessTokenEndpoint() {
return this.accessTokenEndpoint;
return accessTokenEndpoint;
}
/**
......@@ -92,7 +92,7 @@ public class GenesysApi extends DefaultApi20 {
* @return the refresh token endpoint
*/
public String getRefreshTokenEndpoint() {
return this.refreshTokenEndpoint;
return refreshTokenEndpoint;
}
/*
......@@ -104,9 +104,8 @@ public class GenesysApi extends DefaultApi20 {
public String getAuthorizationUrl(final 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()));
? String.format(scopedAuthorizeUrl, config.getApiKey(), config.getApiSecret(), OAuthEncoder.encode(config.getCallback()), OAuthEncoder.encode(config.getScope()))
: String.format(authorizeUrl, config.getApiKey(), config.getApiSecret(), OAuthEncoder.encode(config.getCallback()));
}
/*
......@@ -129,16 +128,19 @@ public class GenesysApi extends DefaultApi20 {
final Pattern refreshTokenPattern = Pattern.compile("\"refresh_token\":\\s*\"(\\S*?)\"");
final Matcher matcher = refreshTokenPattern.matcher(accessToken.getRawResponse());
if (matcher.find())
if (matcher.find()) {
return new Token(matcher.group(1), "", accessToken.getRawResponse());
}
return null;
}
/**
* http://stackoverflow.com/questions/20044222/spring-security-oauth-2- implicit-grant-no-support-for-refresh-token
* http://stackoverflow.com/questions/20044222/spring-security-oauth-2-
* implicit-grant-no-support-for-refresh-token
*
* /oauth/token?client_id=MyClient&amp;grant_type=refresh_token&amp; client_secret= mysecret&amp;refresh_token=19698a4a-960a-4d24-a8cc-44d4b71df47b
* /oauth/token?client_id=MyClient&amp;grant_type=refresh_token&amp; client_secret=
* mysecret&amp;refresh_token=19698a4a-960a-4d24-a8cc-44d4b71df47b
*
* @param apiKey the api key
* @param apiSecret the api secret
......@@ -147,7 +149,7 @@ public class GenesysApi extends DefaultApi20 {
* @throws GenesysApiException the genesys api exception
*/
public Token getAccessToken(final String apiKey, final String apiSecret, final String refreshToken) throws GenesysApiException {
final OAuthRequest request = new OAuthRequest(getAccessTokenVerb(), this.refreshTokenEndpoint);
final OAuthRequest request = new OAuthRequest(getAccessTokenVerb(), refreshTokenEndpoint);
request.addQuerystringParameter(OAuthConstants.CLIENT_ID, apiKey);
request.addQuerystringParameter(OAuthConstants.CLIENT_SECRET, apiSecret);
request.addQuerystringParameter("grant_type", "refresh_token");
......@@ -155,12 +157,13 @@ public class GenesysApi extends DefaultApi20 {
final Response response = request.send();
_log.debug("HTTP status code " + response.getCode());