Commit 9aceab50 authored by Matija Obreza's avatar Matija Obreza

GenesysTokens

parent 05a5dea2
...@@ -34,7 +34,6 @@ import org.apache.commons.lang.StringUtils; ...@@ -34,7 +34,6 @@ import org.apache.commons.lang.StringUtils;
import org.apache.log4j.LogManager; import org.apache.log4j.LogManager;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.scribe.exceptions.OAuthConnectionException; import org.scribe.exceptions.OAuthConnectionException;
import org.scribe.model.Token;
import org.scribe.model.Verb; import org.scribe.model.Verb;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
...@@ -91,8 +90,7 @@ public class CLI { ...@@ -91,8 +90,7 @@ public class CLI {
try { try {
System.out.println("/me: " + genesysClient.query("/me")); System.out.println("/me: " + genesysClient.query("/me"));
Token accessToken = genesysClient.getAccessToken(); this.properties.put("access.token", genesysClient.getTokens().getAccessToken());
this.properties.put("access.token", accessToken.getToken());
saveProperties(); saveProperties();
} catch (OAuthAuthenticationException e) { } catch (OAuthAuthenticationException e) {
...@@ -281,7 +279,8 @@ public class CLI { ...@@ -281,7 +279,8 @@ public class CLI {
System.out.println(arr.toString()); System.out.println(arr.toString());
// make a crop // make a crop
System.out.println("New rules: " + genesysClient.query(Verb.POST, "/crops/" + shortName + "/rules", null, arr.toString())); System.out.println("New rules: "
+ genesysClient.query(Verb.POST, "/crops/" + shortName + "/rules", null, arr.toString()));
} }
private void updateCrop() throws GenesysApiException { private void updateCrop() throws GenesysApiException {
...@@ -425,7 +424,8 @@ public class CLI { ...@@ -425,7 +424,8 @@ public class CLI {
System.err.println(datasetJson.toString()); System.err.println(datasetJson.toString());
// make a dataset // make a dataset
System.out.println("Put dataset: " + genesysClient.query(Verb.PUT, "/datasets/" + datasetId + "/data", null, datasetJson.toString())); System.out.println("Put dataset: "
+ genesysClient.query(Verb.PUT, "/datasets/" + datasetId + "/data", null, datasetJson.toString()));
} }
private void addDatasetRaw() throws GenesysApiException { private void addDatasetRaw() throws GenesysApiException {
...@@ -438,7 +438,8 @@ public class CLI { ...@@ -438,7 +438,8 @@ public class CLI {
System.err.println(json); System.err.println(json);
// make a dataset // make a dataset
System.out.println("Put dataset: " + genesysClient.query(Verb.PUT, "/datasets/" + datasetId + "/data", null, json)); System.out.println("Put dataset: "
+ genesysClient.query(Verb.PUT, "/datasets/" + datasetId + "/data", null, json));
} }
private void checkPreconditions() { private void checkPreconditions() {
...@@ -469,7 +470,7 @@ public class CLI { ...@@ -469,7 +470,7 @@ public class CLI {
} }
private void authenticate() { private void authenticate() {
String authorizationUrl = genesysClient.getAuthorizationUrl(GenesysClient.EMPTY_TOKEN); String authorizationUrl = genesysClient.getAuthorizationUrl();
System.out.println("Authorization URL: \n" + authorizationUrl); System.out.println("Authorization URL: \n" + authorizationUrl);
System.out.print("\nVerifier: "); System.out.print("\nVerifier: ");
...@@ -478,17 +479,10 @@ public class CLI { ...@@ -478,17 +479,10 @@ public class CLI {
// Trade the Request Token and Verifier for the Access Token // Trade the Request Token and Verifier for the Access Token
genesysClient.authenticate(verifierCode); genesysClient.authenticate(verifierCode);
Token accessToken = genesysClient.getAccessToken(); this.properties.put("access.token", genesysClient.getTokens().getAccessToken());
this.properties.put("access.token", accessToken.getToken());
// Get refresh token () // Get refresh token ()
this.properties.put("refresh.token", genesysClient.getTokens().getRefreshToken());
Token refreshToken = genesysClient.getRefreshToken();
if (refreshToken != null) {
this.properties.put("refresh.token", refreshToken.getToken());
} else {
this.properties.remove("refresh.token");
}
saveProperties(); saveProperties();
} }
......
...@@ -57,9 +57,6 @@ public class GenesysClient { ...@@ -57,9 +57,6 @@ public class GenesysClient {
/** The Constant _log. */ /** The Constant _log. */
private static final Logger _log = LogManager.getLogger(GenesysClient.class); private static final Logger _log = LogManager.getLogger(GenesysClient.class);
/** The Constant EMPTY_TOKEN. */
public static final Token EMPTY_TOKEN = null;
/** The Constant SCOPE. */ /** The Constant SCOPE. */
private static final String SCOPE = "read,write"; private static final String SCOPE = "read,write";
...@@ -69,11 +66,8 @@ public class GenesysClient { ...@@ -69,11 +66,8 @@ public class GenesysClient {
/** The service. */ /** The service. */
private OAuthService service; private OAuthService service;
/** The access token. */ /** GenesysTokens: access- and refreshToken */
private Token accessToken; private GenesysTokens tokens = new GenesysTokens();
/** The refresh token. */
private Token refreshToken;
/** The genesys api. */ /** The genesys api. */
private GenesysApi genesysApi; private GenesysApi genesysApi;
...@@ -83,10 +77,10 @@ public class GenesysClient { ...@@ -83,10 +77,10 @@ public class GenesysClient {
/** The api secret. */ /** The api secret. */
private String apiSecret; private String apiSecret;
/** Socket connect timeout */ /** Socket connect timeout */
private int connectTimeout = 20; private int connectTimeout = 20;
/** Socket read timeout */ /** Socket read timeout */
private int readTimeout = 120; private int readTimeout = 120;
...@@ -106,19 +100,19 @@ public class GenesysClient { ...@@ -106,19 +100,19 @@ public class GenesysClient {
public void setReadTimeout(int readTimeout) { public void setReadTimeout(int readTimeout) {
this.readTimeout = readTimeout; this.readTimeout = readTimeout;
} }
public int getReadTimeout() { public int getReadTimeout() {
return readTimeout; return readTimeout;
} }
public void setConnectTimeout(int connectTimeout) { public void setConnectTimeout(int connectTimeout) {
this.connectTimeout = connectTimeout; this.connectTimeout = connectTimeout;
} }
public int getConnectTimeout() { public int getConnectTimeout() {
return connectTimeout; return connectTimeout;
} }
/** /**
* Sets the base url. * Sets the base url.
* *
...@@ -171,8 +165,9 @@ public class GenesysClient { ...@@ -171,8 +165,9 @@ public class GenesysClient {
}); });
} }
setAccessToken(properties.getProperty("access.token")); tokens = new GenesysTokens();
setRefreshToken(properties.getProperty("refresh.token")); tokens.setAccessToken(properties.getProperty("access.token"));
tokens.setRefreshToken(properties.getProperty("refresh.token"));
// CropHub auth service // CropHub auth service
connect(properties.getProperty("client.key"), properties.getProperty("client.secret"), connect(properties.getProperty("client.key"), properties.getProperty("client.secret"),
...@@ -193,26 +188,12 @@ public class GenesysClient { ...@@ -193,26 +188,12 @@ public class GenesysClient {
.callback(callback).scope(SCOPE).build(); .callback(callback).scope(SCOPE).build();
} }
/** public void setTokens(GenesysTokens tokens) {
* Sets the access token. this.tokens = tokens;
*
* @param tokenKey the token key
* @return the genesys client
*/
public GenesysClient setAccessToken(String tokenKey) {
accessToken = new Token(tokenKey, "");
return this;
} }
/** public GenesysTokens getTokens() {
* Sets the refresh token. return tokens;
*
* @param tokenKey the token key
* @return the genesys client
*/
public GenesysClient setRefreshToken(String tokenKey) {
refreshToken = new Token(tokenKey, "");
return this;
} }
/** /**
...@@ -243,7 +224,7 @@ public class GenesysClient { ...@@ -243,7 +224,7 @@ public class GenesysClient {
public String query(Verb method, String url, Map<String, String> queryString, String postBody) public String query(Verb method, String url, Map<String, String> queryString, String postBody)
throws OAuthAuthenticationException, PleaseRetryException, HttpRedirectException, GenesysApiException { throws OAuthAuthenticationException, PleaseRetryException, HttpRedirectException, GenesysApiException {
if (accessToken == null) { if (!tokens.hasAccessToken()) {
refreshAccessToken(); refreshAccessToken();
} }
...@@ -266,7 +247,7 @@ public class GenesysClient { ...@@ -266,7 +247,7 @@ public class GenesysClient {
request.addHeader("Content-Type", "application/json;charset=utf-8"); request.addHeader("Content-Type", "application/json;charset=utf-8");
} }
service.signRequest(accessToken, request); service.signRequest(tokens.accessToken(), request);
request.setConnectionKeepAlive(true); request.setConnectionKeepAlive(true);
request.setConnectTimeout(this.connectTimeout, TimeUnit.SECONDS); request.setConnectTimeout(this.connectTimeout, TimeUnit.SECONDS);
request.setReadTimeout(this.readTimeout, TimeUnit.SECONDS); request.setReadTimeout(this.readTimeout, TimeUnit.SECONDS);
...@@ -305,8 +286,10 @@ public class GenesysClient { ...@@ -305,8 +286,10 @@ public class GenesysClient {
_log.error("HTTP response code: " + response.getCode()); _log.error("HTTP response code: " + response.getCode());
_log.error("Response: " + responseBody); _log.error("Response: " + responseBody);
if (responseBody.contains("Deadlock found when trying to get lock; try restarting transaction") 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
|| responseBody.contains("nested exception is org.hibernate.exception.LockTimeoutException: could not execute statement")) { .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")) {
throw new PleaseRetryException(responseBody); throw new PleaseRetryException(responseBody);
} else } else
throw new GenesysApiException("Unexpected error: " + responseBody); throw new GenesysApiException("Unexpected error: " + responseBody);
...@@ -332,10 +315,12 @@ public class GenesysClient { ...@@ -332,10 +315,12 @@ public class GenesysClient {
* @throws GenesysApiException * @throws GenesysApiException
*/ */
public void refreshAccessToken() throws GenesysApiException { public void refreshAccessToken() throws GenesysApiException {
if (this.refreshToken != null && !this.refreshToken.isEmpty()) { if (tokens.hasRefreshToken()) {
_log.info("Using Refresh Token to get new access token"); _log.info("Using Refresh Token to get new access token");
try { try {
accessToken = genesysApi.getAccessToken(this.apiKey, this.apiSecret, this.refreshToken); Token accessToken = genesysApi.getAccessToken(this.apiKey, this.apiSecret, tokens.getRefreshToken());
tokens.setAccessToken(accessToken.getToken());
_log.info("Got new Access Token!"); _log.info("Got new Access Token!");
} catch (OAuthException e) { } catch (OAuthException e) {
_log.info("Refresh token didn't work: " + e.getMessage()); _log.info("Refresh token didn't work: " + e.getMessage());
...@@ -557,11 +542,10 @@ public class GenesysClient { ...@@ -557,11 +542,10 @@ public class GenesysClient {
/** /**
* Gets the authorization url. * Gets the authorization url.
* *
* @param accessToken the access token
* @return the authorization url * @return the authorization url
*/ */
public String getAuthorizationUrl(Token accessToken) { public String getAuthorizationUrl() {
return this.service.getAuthorizationUrl(accessToken); return this.service.getAuthorizationUrl(null);
} }
/** /**
...@@ -571,32 +555,17 @@ public class GenesysClient { ...@@ -571,32 +555,17 @@ public class GenesysClient {
*/ */
public void authenticate(String verifierCode) { public void authenticate(String verifierCode) {
Verifier verifier = new Verifier(verifierCode); Verifier verifier = new Verifier(verifierCode);
accessToken = service.getAccessToken(GenesysClient.EMPTY_TOKEN, verifier); Token accessToken = service.getAccessToken(null, verifier);
_log.info("ACCESS TOKEN: " + accessToken.getToken() + " sec=" + accessToken.getSecret() + " raw=" _log.info("ACCESS TOKEN: " + accessToken.getToken() + " sec=" + accessToken.getSecret() + " raw="
+ accessToken.getRawResponse()); + accessToken.getRawResponse());
refreshToken = genesysApi.getRefreshToken(accessToken); Token refreshToken = genesysApi.getRefreshToken(accessToken);
_log.info("REFRESH TOKEN: " + refreshToken.getToken() + " sec=" + refreshToken.getSecret() + " raw=" _log.info("REFRESH TOKEN: " + refreshToken.getToken() + " sec=" + refreshToken.getSecret() + " raw="
+ refreshToken.getRawResponse()); + refreshToken.getRawResponse());
}
/**
* Gets the access token.
*
* @return the access token
*/
public Token getAccessToken() {
return accessToken;
}
/** tokens.setAccessToken(accessToken.getToken());
* Gets the refresh token. tokens.setRefreshToken(refreshToken.getToken());
*
* @return the refresh token
*/
public Token getRefreshToken() {
return refreshToken;
} }
/** /**
......
/**
* Copyright 2014 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.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package org.genesys2.client.oauth;
import java.io.Serializable;
import org.apache.commons.lang.StringUtils;
import org.scribe.model.Token;
/**
* A place to keep the tokens for the session.
*/
public class GenesysTokens implements Serializable {
private static final long serialVersionUID = 3022586353518887500L;
private String accessToken = null;
private String refreshToken = null;
private Token _accessToken = null;
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
this._accessToken = new Token(accessToken, "");
}
public String getRefreshToken() {
return refreshToken;
}
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
}
public boolean hasRefreshToken() {
return StringUtils.isNotBlank(this.refreshToken);
}
public boolean hasAccessToken() {
return StringUtils.isNotBlank(this.accessToken);
}
public Token accessToken() {
return this._accessToken;
}
}
...@@ -149,12 +149,12 @@ public class GenesysApi extends DefaultApi20 { ...@@ -149,12 +149,12 @@ public class GenesysApi extends DefaultApi20 {
* @return the access token * @return the access token
* @throws GenesysApiException * @throws GenesysApiException
*/ */
public Token getAccessToken(String apiKey, String apiSecret, Token refreshToken) throws GenesysApiException { public Token getAccessToken(String apiKey, String apiSecret, String refreshToken) throws GenesysApiException {
OAuthRequest request = new OAuthRequest(getAccessTokenVerb(), this.refreshTokenEndpoint); OAuthRequest request = new OAuthRequest(getAccessTokenVerb(), this.refreshTokenEndpoint);
request.addQuerystringParameter(OAuthConstants.CLIENT_ID, apiKey); request.addQuerystringParameter(OAuthConstants.CLIENT_ID, apiKey);
request.addQuerystringParameter(OAuthConstants.CLIENT_SECRET, apiSecret); request.addQuerystringParameter(OAuthConstants.CLIENT_SECRET, apiSecret);
request.addQuerystringParameter("grant_type", "refresh_token"); request.addQuerystringParameter("grant_type", "refresh_token");
request.addQuerystringParameter("refresh_token", refreshToken.getToken()); request.addQuerystringParameter("refresh_token", refreshToken);
Response response = request.send(); Response response = request.send();
_log.debug("HTTP status code " + response.getCode()); _log.debug("HTTP status code " + response.getCode());
_log.debug("Redirect: " + response.getHeader(HttpHeaders.LOCATION)); _log.debug("Redirect: " + response.getHeader(HttpHeaders.LOCATION));
......
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