com.foresee.api.sdk.AuthClient Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of public-api-sdk Show documentation
Show all versions of public-api-sdk Show documentation
SDK to access Foresee data over Public API
package com.foresee.api.sdk;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.http.HttpClient;
import com.amazonaws.http.HttpRequest;
import com.amazonaws.http.HttpResponse;
import com.amazonaws.http.UrlHttpClient;
import com.foresee.api.sdk.clients.BaseApiClient;
import com.foresee.api.sdk.common.Environment;
import com.foresee.api.sdk.exceptions.ApiAuthenticationException;
import com.foresee.api.sdk.model.OAuth2TokenResponse;
import com.google.common.base.Strings;
import com.google.common.io.BaseEncoding;
import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
public final class AuthClient extends BaseApiClient {
/** Version 1 of the token URL */
private static final String V1_TOKEN_URL = "/v1/token";
/**
* Initialize the client with the environment
* @param environment
*/
public AuthClient(Environment environment) {
super(environment);
}
/**
* Perform the authentication using Client Credentials Flow
* @param consumerKey The Consumer Key
* @param consumerSecret The consumer secret
* @param scope The scope
* @Deprecated @param xdebugEnabled Whether you want this request to have additional debugging
* @return The OAuth2 Access Token
* @throws ApiAuthenticationException Any exception encountered during authentication
*/
public String authenticateUsingClientCredentials(String consumerKey, String consumerSecret,
String scope, @Deprecated boolean xdebugEnabled) throws ApiAuthenticationException {
if (Strings.isNullOrEmpty(consumerKey) || Strings.isNullOrEmpty(consumerSecret)) {
throw new IllegalArgumentException("Passed consumer credentials cannot be null or empty");
}
if (Strings.isNullOrEmpty(scope)) {
throw new IllegalArgumentException("Passed scope cannot be null or empty");
}
/** Build the Authorization header which is essentially a Base64 encoded value of consumer key: consumer secret pair */
String combinedCredentials = consumerKey + ":" + consumerSecret;
String base64EncodedHeader = BaseEncoding.base64().encode(combinedCredentials.getBytes());
String authHeader = AUTHORIZATION_HEADER_PREFIX_BASIC + base64EncodedHeader;
/** Build the Url - The Token URL is https://api.foresee.com/v1/token */
String baseUrl = buildTokenUrl();
String url = new StringBuilder(baseUrl).append("?grant_type=").
append(GRANT_TYPE_CLIENT_CREDENTIALS).
append("&scope=").
append(scope).
toString();
/** Add the headers needed to set the media type and Authorization */
Map headers = new HashMap();
headers.put(ACCEPT_HEADER, CONTENT_TYPE_JSON);
headers.put(CONTENT_TYPE_HEADER, CONTENT_TYPE_JSON);
headers.put(AUTHORIZATION_HEADER, authHeader);
/** Make the HTTP Request */
HttpClient client = new UrlHttpClient(new ClientConfiguration());
try {
HttpRequest httpRequest = new HttpRequest("POST",
new URI(url),
headers, (InputStream)null);
HttpResponse httpResponse = client.execute(httpRequest);
/** If status code is 200 then your call was successful */
if (httpResponse.getStatusCode() == 200) {
/** Use a convenient JSON marshalling / unmarshalling library to marshal from Json to Java */
Gson gson = new Gson();
JsonReader reader = new JsonReader(new InputStreamReader(httpResponse.getContent()));
reader.setLenient(true);
OAuth2TokenResponse tokenResponse = gson.fromJson(reader,OAuth2TokenResponse.class);
String accessToken = tokenResponse.getAccessToken();
return accessToken;
} else {
throw ApiAuthenticationException.builder().
message("Encountered an exception performing authentication").build();
}
} catch (URISyntaxException e) {
throw ApiAuthenticationException.builder().
message("Encountered an exception performing authentication due to malformed URL").
cause(e).
build();
} catch (IOException e) {
throw ApiAuthenticationException.builder().
message("Encountered an exception performing authentication due to lower level network I/O").
cause(e).
build();
}
}
/**
* Build the Token URL
* @return
*/
protected String buildTokenUrl() {
return getEnvironment().getGatewayBaseUrl() + V1_TOKEN_URL;
}
}