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

GenesysTokens

parent 05a5dea2
......@@ -34,7 +34,6 @@ import org.apache.commons.lang.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.scribe.exceptions.OAuthConnectionException;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import com.fasterxml.jackson.core.JsonProcessingException;
......@@ -91,8 +90,7 @@ public class CLI {
try {
System.out.println("/me: " + genesysClient.query("/me"));
Token accessToken = genesysClient.getAccessToken();
this.properties.put("access.token", accessToken.getToken());
this.properties.put("access.token", genesysClient.getTokens().getAccessToken());
saveProperties();
} catch (OAuthAuthenticationException e) {
......@@ -281,7 +279,8 @@ public class CLI {
System.out.println(arr.toString());
// 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 {
......@@ -425,7 +424,8 @@ public class CLI {
System.err.println(datasetJson.toString());
// 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 {
......@@ -438,7 +438,8 @@ public class CLI {
System.err.println(json);
// 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() {
......@@ -469,7 +470,7 @@ public class CLI {
}
private void authenticate() {
String authorizationUrl = genesysClient.getAuthorizationUrl(GenesysClient.EMPTY_TOKEN);
String authorizationUrl = genesysClient.getAuthorizationUrl();
System.out.println("Authorization URL: \n" + authorizationUrl);
System.out.print("\nVerifier: ");
......@@ -478,17 +479,10 @@ public class CLI {
// Trade the Request Token and Verifier for the Access Token
genesysClient.authenticate(verifierCode);
Token accessToken = genesysClient.getAccessToken();
this.properties.put("access.token", accessToken.getToken());
this.properties.put("access.token", genesysClient.getTokens().getAccessToken());
// Get refresh token ()
Token refreshToken = genesysClient.getRefreshToken();
if (refreshToken != null) {
this.properties.put("refresh.token", refreshToken.getToken());
} else {
this.properties.remove("refresh.token");
}
this.properties.put("refresh.token", genesysClient.getTokens().getRefreshToken());
saveProperties();
}
......
......@@ -57,9 +57,6 @@ public class GenesysClient {
/** The Constant _log. */
private static final Logger _log = LogManager.getLogger(GenesysClient.class);
/** The Constant EMPTY_TOKEN. */
public static final Token EMPTY_TOKEN = null;
/** The Constant SCOPE. */
private static final String SCOPE = "read,write";
......@@ -69,11 +66,8 @@ public class GenesysClient {
/** The service. */
private OAuthService service;
/** The access token. */
private Token accessToken;
/** The refresh token. */
private Token refreshToken;
/** GenesysTokens: access- and refreshToken */
private GenesysTokens tokens = new GenesysTokens();
/** The genesys api. */
private GenesysApi genesysApi;
......@@ -83,10 +77,10 @@ public class GenesysClient {
/** The api secret. */
private String apiSecret;
/** Socket connect timeout */
private int connectTimeout = 20;
/** Socket read timeout */
private int readTimeout = 120;
......@@ -106,19 +100,19 @@ public class GenesysClient {
public void setReadTimeout(int readTimeout) {
this.readTimeout = readTimeout;
}
public int getReadTimeout() {
return readTimeout;
}
public void setConnectTimeout(int connectTimeout) {
this.connectTimeout = connectTimeout;
}
public int getConnectTimeout() {
return connectTimeout;
}
/**
* Sets the base url.
*
......@@ -171,8 +165,9 @@ public class GenesysClient {
});
}
setAccessToken(properties.getProperty("access.token"));
setRefreshToken(properties.getProperty("refresh.token"));
tokens = new GenesysTokens();
tokens.setAccessToken(properties.getProperty("access.token"));
tokens.setRefreshToken(properties.getProperty("refresh.token"));
// CropHub auth service
connect(properties.getProperty("client.key"), properties.getProperty("client.secret"),
......@@ -193,26 +188,12 @@ public class GenesysClient {
.callback(callback).scope(SCOPE).build();
}
/**
* Sets the access token.
*
* @param tokenKey the token key
* @return the genesys client
*/
public GenesysClient setAccessToken(String tokenKey) {
accessToken = new Token(tokenKey, "");
return this;
public void setTokens(GenesysTokens tokens) {
this.tokens = tokens;
}
/**
* Sets the refresh token.
*
* @param tokenKey the token key
* @return the genesys client
*/
public GenesysClient setRefreshToken(String tokenKey) {
refreshToken = new Token(tokenKey, "");
return this;
public GenesysTokens getTokens() {
return tokens;
}
/**
......@@ -243,7 +224,7 @@ public class GenesysClient {
public String query(Verb method, String url, Map<String, String> queryString, String postBody)
throws OAuthAuthenticationException, PleaseRetryException, HttpRedirectException, GenesysApiException {
if (accessToken == null) {
if (!tokens.hasAccessToken()) {
refreshAccessToken();
}
......@@ -266,7 +247,7 @@ public class GenesysClient {
request.addHeader("Content-Type", "application/json;charset=utf-8");
}
service.signRequest(accessToken, request);
service.signRequest(tokens.accessToken(), request);
request.setConnectionKeepAlive(true);
request.setConnectTimeout(this.connectTimeout, TimeUnit.SECONDS);
request.setReadTimeout(this.readTimeout, TimeUnit.SECONDS);
......@@ -305,8 +286,10 @@ public class GenesysClient {
_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")
|| responseBody.contains("nested exception is org.hibernate.exception.LockTimeoutException: could not execute statement")) {
|| 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")) {
throw new PleaseRetryException(responseBody);
} else
throw new GenesysApiException("Unexpected error: " + responseBody);
......@@ -332,10 +315,12 @@ public class GenesysClient {
* @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");
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!");
} catch (OAuthException e) {
_log.info("Refresh token didn't work: " + e.getMessage());
......@@ -557,11 +542,10 @@ public class GenesysClient {
/**
* Gets the authorization url.
*
* @param accessToken the access token
* @return the authorization url
*/
public String getAuthorizationUrl(Token accessToken) {
return this.service.getAuthorizationUrl(accessToken);
public String getAuthorizationUrl() {
return this.service.getAuthorizationUrl(null);
}
/**
......@@ -571,32 +555,17 @@ public class GenesysClient {
*/
public void authenticate(String 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="
+ accessToken.getRawResponse());
refreshToken = genesysApi.getRefreshToken(accessToken);
Token refreshToken = genesysApi.getRefreshToken(accessToken);
_log.info("REFRESH TOKEN: " + refreshToken.getToken() + " sec=" + refreshToken.getSecret() + " raw="
+ refreshToken.getRawResponse());
}
/**
* Gets the access token.
*
* @return the access token
*/
public Token getAccessToken() {
return accessToken;
}
/**
* Gets the refresh token.
*
* @return the refresh token
*/
public Token getRefreshToken() {
return refreshToken;
tokens.setAccessToken(accessToken.getToken());
tokens.setRefreshToken(refreshToken.getToken());
}
/**
......
/**
* 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 {
* @return the access token
* @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);
request.addQuerystringParameter(OAuthConstants.CLIENT_ID, apiKey);
request.addQuerystringParameter(OAuthConstants.CLIENT_SECRET, apiSecret);
request.addQuerystringParameter("grant_type", "refresh_token");
request.addQuerystringParameter("refresh_token", refreshToken.getToken());
request.addQuerystringParameter("refresh_token", refreshToken);
Response response = request.send();
_log.debug("HTTP status code " + response.getCode());
_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