Commit 4c124256 authored by Matija Obreza's avatar Matija Obreza

Upgraded to scribe-java:4.2.0

parent 09ecefe3
Pipeline #2746 passed with stage
in 26 seconds
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.genesys-pgr</groupId>
......@@ -41,7 +42,6 @@
<nexus-staging-maven-plugin.version>1.6.8</nexus-staging-maven-plugin.version>
<show.deprecations>true</show.deprecations>
<scribe.version>1.3.7</scribe.version>
</properties>
......@@ -88,9 +88,9 @@
<dependencies>
<dependency>
<groupId>org.scribe</groupId>
<artifactId>scribe</artifactId>
<version>${scribe.version}</version>
<groupId>com.github.scribejava</groupId>
<artifactId>scribejava-core</artifactId>
<version>4.2.0</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
......@@ -134,6 +134,7 @@
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.6</version>
<scope>test</scope>
</dependency>
</dependencies>
......
......@@ -21,7 +21,6 @@ import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.SocketException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map.Entry;
......@@ -38,13 +37,12 @@ import com.fasterxml.jackson.databind.node.IntNode;
import com.fasterxml.jackson.databind.node.NullNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
import com.github.scribejava.core.model.Verb;
import org.apache.commons.io.IOUtils;
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.Verb;
/**
* Simple command line interface to Genesys.
......@@ -69,7 +67,7 @@ public class CLI {
private static ObjectMapper mapper = new ObjectMapper();
/** The genesys client. */
private final GenesysClient genesysClient = new GenesysClient();
private GenesysClient genesysClient;
/** The ignored fields. */
private static Set<String> ignoredFields;
......@@ -93,7 +91,7 @@ public class CLI {
_log.info("Hello World!");
final CLI cli = new CLI();
cli.loadProperties("client.properties");
cli.genesysClient = GenesysClient.build(cli.loadProperties("client.properties"));
cli.run();
}
......@@ -111,13 +109,11 @@ public class CLI {
} catch (final OAuthAuthenticationException e) {
_log.error("Failed to fetch /me", e);
authenticate();
} catch (final OAuthConnectionException e) {
if (e.getCause() != null && e.getCause() instanceof SocketException) {
_log.error("Could not connect to host");
try {
authenticate();
} catch (OAuthAuthenticationException e1) {
_log.error("Failed to authenticate", e1);
return;
} else {
_log.error(e.getMessage(), e);
}
} catch (final Throwable e) {
_log.error(e.getMessage(), e);
......@@ -566,8 +562,10 @@ public class CLI {
/**
* Authenticate.
*
* @throws OAuthAuthenticationException
*/
private void authenticate() {
private void authenticate() throws OAuthAuthenticationException {
final String authorizationUrl = genesysClient.getAuthorizationUrl();
System.out.println("Authorization URL: \n" + authorizationUrl);
......@@ -604,8 +602,9 @@ public class CLI {
* Load properties.
*
* @param propertiesFileName the properties file name
* @return
*/
private void loadProperties(final String propertiesFileName) {
private Properties loadProperties(final String propertiesFileName) {
// .properties file location
propertiesFile = new File(propertiesFileName);
......@@ -626,7 +625,7 @@ public class CLI {
IOUtils.closeQuietly(fis);
}
genesysClient.loadProperties(properties);
return properties;
}
}
......@@ -18,8 +18,9 @@ package org.genesys2.client.oauth;
import java.io.Serializable;
import com.github.scribejava.core.model.OAuth2AccessToken;
import org.apache.commons.lang.StringUtils;
import org.scribe.model.Token;
/**
* A place to keep the tokens for the session.
......@@ -36,7 +37,7 @@ public class GenesysTokens implements Serializable {
private String refreshToken = null;
/** The _access token. */
private Token _accessToken = null;
private OAuth2AccessToken _accessToken = null;
/**
* Gets the access token.
......@@ -54,7 +55,7 @@ public class GenesysTokens implements Serializable {
*/
public void setAccessToken(final String accessToken) {
this.accessToken = accessToken;
_accessToken = new Token(accessToken, "");
_accessToken = new OAuth2AccessToken(accessToken);
}
/**
......@@ -98,7 +99,7 @@ public class GenesysTokens implements Serializable {
*
* @return the token
*/
public Token accessToken() {
public OAuth2AccessToken accessToken() {
return _accessToken;
}
}
package org.genesys2.client.oauth;
public class HttpConstants {
public static final String APPLICATION_JSON_UTF8 = "application/json;charset=utf8";
public static final String LOCATION = "Location";
}
......@@ -16,64 +16,25 @@
package org.genesys2.client.oauth.api;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.HttpHeaders;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.genesys2.client.oauth.GenesysApiException;
import org.scribe.builder.api.DefaultApi20;
import org.scribe.exceptions.OAuthException;
import org.scribe.extractors.AccessTokenExtractor;
import org.scribe.extractors.JsonTokenExtractor;
import org.scribe.model.OAuthConfig;
import org.scribe.model.OAuthConstants;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.utils.OAuthEncoder;
import com.github.scribejava.core.builder.api.DefaultApi20;
import com.github.scribejava.core.builder.api.OAuth2SignatureType;
/**
* Genesys API v1.
*/
public class GenesysApi extends DefaultApi20 {
/** The Constant _log. */
private static final Logger _log = LogManager.getLogger(GenesysApi.class);
/** OAuth2 authorization endpoint that is appended to {@link #baseUrl}. */
public static final String AUTHORIZE_URL = "/oauth/authorize?client_id=%s&client_secret=%s&response_type=code&redirect_uri=%s";
public static final String AUTHORIZE_ENDPOINT = "/oauth/authorize";
/** OAuth2 access token endpoint that is appended to {@link #baseUrl}. */
private static final String TOKEN_ENDPOINT = "/oauth/token";
/** The base URL of the Genesys server (e.g. https://www.genesys-pgr.org) */
private String baseUrl;
/** The complete authorization url. */
private String authorizeUrl;
/** The scoped authorize url. */
private String scopedAuthorizeUrl;
/** The access token endpoint. */
private String accessTokenEndpoint;
private final String baseUrl;
/** The refresh token endpoint. */
private String refreshTokenEndpoint;
/**
* Sets the base url.
*
* @param baseUrl the new base url
*/
public void setBaseUrl(final String baseUrl) {
public GenesysApi(String baseUrl) {
this.baseUrl = baseUrl;
authorizeUrl = this.baseUrl + AUTHORIZE_URL;
scopedAuthorizeUrl = authorizeUrl + "&scope=%s";
refreshTokenEndpoint = this.baseUrl + TOKEN_ENDPOINT;
accessTokenEndpoint = this.baseUrl + TOKEN_ENDPOINT + "?grant_type=authorization_code";
}
/*
......@@ -83,87 +44,17 @@ public class GenesysApi extends DefaultApi20 {
*/
@Override
public String getAccessTokenEndpoint() {
return accessTokenEndpoint;
return this.baseUrl + TOKEN_ENDPOINT;
}
/**
* Gets the refresh token endpoint.
*
* @return the refresh token endpoint
*/
public String getRefreshTokenEndpoint() {
return refreshTokenEndpoint;
}
/*
* (non-Javadoc)
*
* @see org.scribe.builder.api.DefaultApi20#getAuthorizationUrl(org.scribe.model .OAuthConfig)
*/
@Override
public String getAuthorizationUrl(final OAuthConfig config) {
return config.hasScope()
? 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()));
protected String getAuthorizationBaseUrl() {
return baseUrl + AUTHORIZE_ENDPOINT;
}
/*
* (non-Javadoc)
*
* @see org.scribe.builder.api.DefaultApi20#getAccessTokenExtractor()
*/
@Override
public AccessTokenExtractor getAccessTokenExtractor() {
return new JsonTokenExtractor();
}
/**
* Gets the refresh token.
*
* @param accessToken the access token
* @return the refresh token
*/
public Token getRefreshToken(final Token accessToken) {
final Pattern refreshTokenPattern = Pattern.compile("\"refresh_token\":\\s*\"(\\S*?)\"");
final Matcher matcher = refreshTokenPattern.matcher(accessToken.getRawResponse());
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
*
* /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
* @param refreshToken the refresh token
* @return the access token
* @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(), refreshTokenEndpoint);
request.addQuerystringParameter(OAuthConstants.CLIENT_ID, apiKey);
request.addQuerystringParameter(OAuthConstants.CLIENT_SECRET, apiSecret);
request.addQuerystringParameter("grant_type", "refresh_token");
request.addQuerystringParameter("refresh_token", refreshToken);
final Response response = request.send();
_log.debug("HTTP status code " + response.getCode());
_log.debug("Redirect: " + response.getHeader(HttpHeaders.LOCATION));
if (response.getCode() >= 200 && response.getCode() < 300) {
return getAccessTokenExtractor().extract(response.getBody());
} else if (response.getCode() == 400) {
throw new OAuthException("Refresh token no longer valid.");
} else {
throw new GenesysApiException("Server responded with unexpected HTTP response code " + response.getCode());
}
public OAuth2SignatureType getSignatureType() {
return OAuth2SignatureType.BEARER_AUTHORIZATION_REQUEST_HEADER_FIELD;
}
/**
......
......@@ -16,10 +16,11 @@
package org.geneys2.client.oauth;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.*;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Matchers.anyMapOf;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.util.ArrayList;
......@@ -30,6 +31,7 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.github.scribejava.core.model.Verb;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
......@@ -48,7 +50,6 @@ import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import org.scribe.model.Verb;
// TODO: Auto-generated Javadoc
/**
......
......@@ -63,7 +63,6 @@ public class ModelTests {
final JsonNode tree = getJsonTree(aj);
System.err.println(tree.toString());
assertThat("JSON elements count mismatch", tree, JsonNodeMatchers.withSize(3));
assertThat("No INSTCODE", tree.get(Accession.INSTCODE), notNullValue());
assertThat("INSTCODE must be a text node", tree.get(Accession.INSTCODE), JsonNodeMatchers.isTextNode());
assertThat("Wrong INSTCODE", tree.get(Accession.INSTCODE).asText(), is("INS000"));
......@@ -115,7 +114,6 @@ public class ModelTests {
final JsonNode tree = getJsonTree(aj);
System.err.println(tree.toString());
assertThat("JSON elements count mismatch", tree, JsonNodeMatchers.withSize(1));
assertThat("STORAGE must be an array", tree.get(Accession.STORAGE), JsonNodeMatchers.isArrayNode());
}
}
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