protected void handleUnexpectedResponse(int statusCode, HttpResponse response) throws Exception { if (response == null) { return; } BufferedReader reader = new BufferedReader(new InputStreamReader(response.getContent())); StringBuilder responseBody = new StringBuilder(); String line = reader.readLine(); while (line != null) { responseBody.append(line); line = reader.readLine(); } switch (statusCode) { case 401: throw new OAuthNotAuthorizedException(responseBody.toString()); default: throw new OAuthCommunicationException("Service provider responded in error: " + statusCode + " (" + response.getReasonPhrase() + ")", responseBody.toString()); } }
@Override public String sign(HttpRequest request, HttpParameters requestParams) throws OAuthMessageSignerException { try { String keyString = OAuth.percentEncode(getConsumerSecret()) + '&' + OAuth.percentEncode(getTokenSecret()); byte[] keyBytes = keyString.getBytes(OAuth.ENCODING); SecretKey key = new SecretKeySpec(keyBytes, MAC_NAME); Mac mac = Mac.getInstance(MAC_NAME); mac.init(key); String sbs = new SignatureBaseString(request, requestParams).generate(); OAuth.debugOut("SBS", sbs); byte[] text = sbs.getBytes(OAuth.ENCODING); return base64Encode(mac.doFinal(text)).trim(); } catch (GeneralSecurityException e) { throw new OAuthMessageSignerException(e); } catch (UnsupportedEncodingException e) { throw new OAuthMessageSignerException(e); } } }
/** * Return {@link OAuthConsumer} of the client for the current authorization. * * @return {@link OAuthConsumer} instance of the client * @throws OAuthNotAuthorizedException if the client is not authorized */ public final OAuthConsumer getAuthConsumer() throws OAuthNotAuthorizedException { if (oAuthConsumer == null) throw new OAuthNotAuthorizedException(); return oAuthConsumer; }
public synchronized HttpRequest sign(HttpRequest request) throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException { if (consumerKey == null) { throw new OAuthExpectationFailedException("consumer key not set"); } if (consumerSecret == null) { throw new OAuthExpectationFailedException("consumer secret not set"); } requestParameters = new HttpParameters(); try { if (additionalParameters != null) { requestParameters.putAll(additionalParameters, false); } collectHeaderParameters(request, requestParameters); collectQueryParameters(request, requestParameters); collectBodyParameters(request, requestParameters); // add any OAuth params that haven't already been set completeOAuthParameters(requestParameters); requestParameters.remove(OAuth.OAUTH_SIGNATURE); } catch (IOException e) { throw new OAuthCommunicationException(e); } String signature = messageSigner.sign(request, requestParameters); OAuth.debugOut("signature", signature); signingStrategy.writeSignature(signature, request, requestParameters); OAuth.debugOut("Request URL", request.getRequestUrl()); return request; }
public synchronized void retrieveAccessToken(OAuthConsumer consumer, String oauthVerifier, String... customOAuthParams) throws OAuthMessageSignerException, OAuthNotAuthorizedException, OAuthExpectationFailedException, OAuthCommunicationException { if (consumer.getToken() == null || consumer.getTokenSecret() == null) { throw new OAuthExpectationFailedException( "Authorized request token or token secret not set. " + "Did you retrieve an authorized request token before?"); } HttpParameters params = new HttpParameters(); params.putAll(customOAuthParams, true); if (isOAuth10a && oauthVerifier != null) { params.put(OAuth.OAUTH_VERIFIER, oauthVerifier, true); } retrieveToken(consumer, accessTokenEndpointUrl, params); }
@Override public void run() { String response = ""; try { response = httpClient.executeOAuthRequest(finalUrlString, method, jsonPayload, new SimpleGeoHandler()); } catch (OAuthMessageSignerException e) { callback.onError(e.getMessage()); } catch (OAuthExpectationFailedException e) { callback.onError(e.getMessage()); } catch (OAuthCommunicationException e) { callback.onError(e.getMessage()); } catch (IOException e) { callback.onError(e.getMessage()); } callback.onSuccess(response); } });
private Error(OAuthException exception) { this.exception = exception; if (this.exception instanceof OAuthMessageSignerException) { this.type = Type.MESSAGE_SIGNER; } else if (this.exception instanceof OAuthNotAuthorizedException) { this.type = Type.NOT_AUTHORIZED; } else if (this.exception instanceof OAuthExpectationFailedException) { this.type = Type.EXPECTATION_FAILED; } else if (this.exception instanceof OAuthCommunicationException) { this.type = Type.COMMUNICATION; } else { this.type = Type.OTHER; } this.details = exception.getMessage(); }
public void signRequest(HttpRequest request) { int retries = 3; if (consumer == null) { buildConsumer(); } while (retries-- > 0) { try { if (consumer != null) { // We need to remove the previous Authorization header // because signpost fails to sign a second time otherwise. request.removeHeaders("Authorization"); consumer.sign(request); return; } } catch (OAuthException e) { e.printStackTrace(); } login(); } }
throw new OAuthExpectationFailedException("Consumer key or secret not set"); throw new OAuthExpectationFailedException( "Request token or token secret not set in server reply. " + "The service provider you use is probably buggy."); throw e; } catch (Exception e) { throw new OAuthCommunicationException(e); } finally { try { closeConnection(request, response); } catch (Exception e) { throw new OAuthCommunicationException(e);
public static OAuthConsumer createOAuthConsumer(OAuthConsumer oauth) throws OAuthExpectationFailedException { if (oauth == null) { throw new OAuthExpectationFailedException( "This class has been initialized without a OAuthConsumer. Only API calls " + "that do not require authentication can be made."); } // "clone" the original consumer every time because the consumer is documented to be not // thread safe and maybe multiple threads are making calls to this class OAuthConsumer consumer = new DefaultOAuthConsumer( oauth.getConsumerKey(), oauth.getConsumerSecret()); consumer.setTokenWithSecret(oauth.getToken(), oauth.getTokenSecret()); return consumer; } }
@Override public String sign(HttpRequest request, HttpParameters requestParams) throws OAuthMessageSignerException { try { String keyString = OAuth.percentEncode(getConsumerSecret()) + '&' + OAuth.percentEncode(getTokenSecret()); byte[] keyBytes = keyString.getBytes(OAuth.ENCODING); SecretKey key = new SecretKeySpec(keyBytes, MAC_NAME); Mac mac = Mac.getInstance(MAC_NAME); mac.init(key); String sbs = new SignatureBaseString(request, requestParams).generate(); OAuth.debugOut("SBS", sbs); byte[] text = sbs.getBytes(OAuth.ENCODING); return base64Encode(mac.doFinal(text)).trim(); } catch (GeneralSecurityException e) { throw new OAuthMessageSignerException(e); } catch (UnsupportedEncodingException e) { throw new OAuthMessageSignerException(e); } } }
protected void handleUnexpectedResponse(int statusCode, HttpResponse response) throws Exception { if (response == null) { return; } BufferedReader reader = new BufferedReader(new InputStreamReader(response.getContent())); StringBuilder responseBody = new StringBuilder(); String line = reader.readLine(); while (line != null) { responseBody.append(line); line = reader.readLine(); } switch (statusCode) { case 401: throw new OAuthNotAuthorizedException(responseBody.toString()); default: throw new OAuthCommunicationException("Service provider responded in error: " + statusCode + " (" + response.getReasonPhrase() + ")", responseBody.toString()); } }
HttpURLConnection sign( HttpURLConnection request, final HttpEntity body ) throws IOException { try { // OAuth Sign. // Note that the request body must be repeatable even though it is an input stream. if ( body == null ) return (HttpURLConnection)oauth.sign( request ).unwrap(); else return (HttpURLConnection)oauth.sign( new HttpURLConnectionRequestAdapter(request) { /* @Override */ public InputStream getMessagePayload() throws IOException { return body.getContent(); } }).unwrap(); } catch ( final OAuthException ex ) { // throw new IOException( "OAuth signing error", ex ); // 1.6 only! throw new IOException( "OAuth signing error: " + ex.getMessage() ) { private static final long serialVersionUID = -13848840190384656L; /* @Override */ public Throwable getCause() { return ex; } }; } } }
/** * Return {@link OAuthProvider} of the client for the current authorization. * * @return {@link OAuthProvider} instance of the client * @throws OAuthNotAuthorizedException if the client is not authorized */ public final OAuthProvider getAuthProvider() throws OAuthNotAuthorizedException { if (oAuthProvider == null) throw new OAuthNotAuthorizedException(); return oAuthProvider; }
public synchronized HttpRequest sign(HttpRequest request) throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException { if (consumerKey == null) { throw new OAuthExpectationFailedException("consumer key not set"); } if (consumerSecret == null) { throw new OAuthExpectationFailedException("consumer secret not set"); } requestParameters = new HttpParameters(); try { if (additionalParameters != null) { requestParameters.putAll(additionalParameters, false); } collectHeaderParameters(request, requestParameters); collectQueryParameters(request, requestParameters); collectBodyParameters(request, requestParameters); // add any OAuth params that haven't already been set completeOAuthParameters(requestParameters); requestParameters.remove(OAuth.OAUTH_SIGNATURE); } catch (IOException e) { throw new OAuthCommunicationException(e); } String signature = messageSigner.sign(request, requestParameters); OAuth.debugOut("signature", signature); signingStrategy.writeSignature(signature, request, requestParameters); OAuth.debugOut("Request URL", request.getRequestUrl()); return request; }
private OAuthConsumer createOAuthConsumer() throws OAuthExpectationFailedException { synchronized(oauthLock) { if(oauth == null) { throw new OAuthExpectationFailedException( "This class has been initialized without a OAuthConsumer. Only API calls " + "that do not require authentication can be made."); } // "clone" the original consumer every time because the consumer is documented to be not // thread safe and maybe multiple threads are making calls to this class OAuthConsumer consumer = new DefaultOAuthConsumer( oauth.getConsumerKey(), oauth.getConsumerSecret()); consumer.setTokenWithSecret(oauth.getToken(), oauth.getTokenSecret()); return consumer; } }
/** * Builds the signature base string from the data this instance was * configured with. * * @return the signature base string * @throws OAuthMessageSignerException */ public String generate() throws OAuthMessageSignerException { try { String normalizedUrl = normalizeRequestUrl(); String normalizedParams = normalizeRequestParameters(); return request.getMethod() + '&' + OAuth.percentEncode(normalizedUrl) + '&' + OAuth.percentEncode(normalizedParams); } catch (Exception e) { throw new OAuthMessageSignerException(e); } }
HttpURLConnection sign( HttpURLConnection request, final HttpEntity body ) throws IOException { try { // OAuth Sign. // Note that the request body must be repeatable even though it is an input stream. if ( body == null ) return (HttpURLConnection)oauth.sign( request ).unwrap(); else return (HttpURLConnection)oauth.sign( new HttpURLConnectionRequestAdapter(request) { /* @Override */ public InputStream getMessagePayload() throws IOException { return body.getContent(); } }).unwrap(); } catch ( final OAuthException ex ) { // throw new IOException( "OAuth signing error", ex ); // 1.6 only! throw new IOException( "OAuth signing error: " + ex.getMessage() ) { private static final long serialVersionUID = -13848840190384656L; /* @Override */ public Throwable getCause() { return ex; } }; } } }
public synchronized void retrieveAccessToken(OAuthConsumer consumer, String oauthVerifier, String... customOAuthParams) throws OAuthMessageSignerException, OAuthNotAuthorizedException, OAuthExpectationFailedException, OAuthCommunicationException { if (consumer.getToken() == null || consumer.getTokenSecret() == null) { throw new OAuthExpectationFailedException( "Authorized request token or token secret not set. " + "Did you retrieve an authorized request token before?"); } HttpParameters params = new HttpParameters(); params.putAll(customOAuthParams, true); if (isOAuth10a && oauthVerifier != null) { params.put(OAuth.OAUTH_VERIFIER, oauthVerifier, true); } retrieveToken(consumer, accessTokenEndpointUrl, params); }
/** * Builds the signature base string from the data this instance was * configured with. * * @return the signature base string * @throws OAuthMessageSignerException */ public String generate() throws OAuthMessageSignerException { try { String normalizedUrl = normalizeRequestUrl(); String normalizedParams = normalizeRequestParameters(); return request.getMethod() + '&' + OAuth.percentEncode(normalizedUrl) + '&' + OAuth.percentEncode(normalizedParams); } catch (Exception e) { throw new OAuthMessageSignerException(e); } }