Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.paypal.base.rest;
  
  import java.util.Date;
  import java.util.HashMap;
  import java.util.Map;
  
OAuthTokenCredential is used for generation of OAuth Token used by PayPal REST API service. ClientID and ClientSecret are required by the class to generate OAuth Token, the resulting token is of the form "Bearer xxxxxx". The class has two constructors, one of it taking an additional configuration map used for dynamic configuration. When using the constructor with out configuration map the endpoint is fetched from the configuration that is used during initialization. See PayPalResource for configuring the system. When using a configuration map the class expects an entry by the name "oauth.EndPoint" or "service.EndPoint" to retrieve the value of the endpoint for the OAuth Service. If either are not present the configuration should have a entry by the name "mode" with values sandbox or live wherein the corresponding endpoints are default to PayPal endpoints.

Author(s):
kjayakumar
 
 public final class OAuthTokenCredential implements ICredential {

OAuth URI path parameter
 
 	private static String OAUTH_TOKEN_PATH = "/v1/oauth2/token";

Client ID for OAuth
 
 	private String clientID;

Client Secret for OAuth
 
 	private String clientSecret;

Access Token that is generated
 
 	private String accessToken;

Lifetime in seconds of the access token
 
 	private long expires = 0;

Map used for dynamic configuration
 
 
 	private SDKVersion sdkVersion;

Sets the URI path for the OAuth Token service. If not set it defaults to "/v1/oauth2/token"

Parameters:
oauthTokenPath the URI part to set
 
 	public static void setOAUTH_TOKEN_PATH(String oauthTokenPath) {
 		 = oauthTokenPath;
 	}

Parameters:
clientID Client ID for the OAuth
clientSecret Client Secret for OAuth
 
 	public OAuthTokenCredential(String clientIDString clientSecret) {
 		super();
 		this. = clientID;
 		this. = clientSecret;
 		this. = SDKUtil.combineDefaultMap(ConfigManager
 		this. = new SDKVersionImpl();
	}

Configuration Constructor for dynamic configuration

Parameters:
clientID Client ID for the OAuth
clientSecret Client Secret for OAuth
configurationMap Dynamic configuration map which should have an entry for 'oauth.EndPoint' or 'service.EndPoint'. If either are not present then there should be entry for 'mode' with values sandbox/live, wherein PayPals endpoints are used.
	public OAuthTokenCredential(String clientIDString clientSecret,
			Map<StringStringconfigurationMap) {
		super();
		this. = clientID;
		this. = clientSecret;
		this. = SDKUtil.combineDefaultMap(configurationMap);
		this. = new SDKVersionImpl();
	}

Computes Access Token by placing a call to OAuth server using ClientID and ClientSecret. The token is appended to the token type (Bearer).

Returns:
the accessToken
Throws:
PayPalRESTException
		if ( == null) {
		}
		return ;
	}

Computes Access Token by doing a Base64 encoding on the ClientID and ClientSecret. The token is appended to the String "Basic ".

Returns:
the accessToken
Throws:
PayPalRESTException
		String base64EncodedString = generateBase64String( + ":"
		return "Basic " + base64EncodedString;
	}

Specifies how long this token can be used for placing API calls. The remaining lifetime is given in seconds.

Returns:
remaining lifetime of this access token in seconds
	public long expiresIn() {
		return  - new java.util.Date().getTime() / 1000;
	}
		String generatedToken = null;
		String base64ClientID = generateBase64String( + ":"
		generatedToken = generateOAuthToken(base64ClientID);
		return generatedToken;
	}
	/*
	 * Generate a Base64 encoded String from clientID & clientSecret
	 */
	private String generateBase64String(String clientCredentials)
		String base64ClientID = null;
		byte[] encoded = null;
		try {
			encoded = Base64.encodeBase64(clientCredentials.getBytes("UTF-8"));
			base64ClientID = new String(encoded"UTF-8");
			throw new PayPalRESTException(e.getMessage(), e);
		}
		return base64ClientID;
	}
	/*
	 * Generate OAuth type token from Base64Client ID
	 */
	private String generateOAuthToken(String base64ClientID)
		HttpConnection connection = null;
		HttpConfiguration httpConfiguration = null;
		String generatedToken = null;
		try {
			connection = ConnectionManager.getInstance().getConnection();
			httpConfiguration = getOAuthHttpConfiguration();
			connection.createAndconfigureHttpConnection(httpConfiguration);
			Map<StringStringheaders = new HashMap<StringString>();
base64ClientID);
			// Accept only json output
			UserAgentHeader userAgentHeader = new UserAgentHeader(
					 != null ? .getSDKId() : null,
					 != null ? .getSDKVersion() : null);
			headers.putAll(userAgentHeader.getHeader());
			String postRequest = getRequestPayload();
			String jsonResponse = connection.execute(""postRequestheaders);
			JsonParser parser = new JsonParser();
			JsonElement jsonElement = parser.parse(jsonResponse);
			generatedToken = jsonElement.getAsJsonObject().get("token_type")
" "
jsonElement.getAsJsonObject().get("access_token")
			// Save expiry date
			long tokenLifeTime = jsonElement.getAsJsonObject()
					.get("expires_in").getAsLong();
			 = new Date().getTime() / 1000 + tokenLifeTime;
catch (Exception e) {
			throw new PayPalRESTException(e.getMessage(), e);
		}
		return generatedToken;
	}

Returns the request payload for OAuth Service. Override this method to alter the payload

Returns:
Payload as String
	protected String getRequestPayload() {
		return "grant_type=client_credentials";
	}
	/*
	 * Get HttpConfiguration object for OAuth server
	 */
		HttpConfiguration httpConfiguration = new HttpConfiguration();
		httpConfiguration
		if (endPointUrl == null || endPointUrl.trim().length() <= 0) {
else if (..equalsIgnoreCase(mode)) {
			}
		}
		if (Boolean
			httpConfiguration.setProxySet(true);
			httpConfiguration.setProxyPort(Integer.parseInt(
			String proxyUserName = 
			String proxyPassword = 
			if (proxyUserName != null && proxyPassword != null) {
				httpConfiguration.setProxyUserName(proxyUserName);
				httpConfiguration.setProxyPassword(proxyPassword);
			}
		}
		endPointUrl = (endPointUrl.endsWith("/")) ? endPointUrl.substring(0,
				endPointUrl.length() - 1) : endPointUrl;
		endPointUrl += ;
		httpConfiguration.setEndPointUrl(endPointUrl);
		httpConfiguration
		return httpConfiguration;
	}
New to GrepCode? Check out our FAQ X