void signWithSignpost( HttpUriRequest hcRequest, String consumerKey0, String consumerSecret0, String token, String tokenSecret) throws IndivoClientException { logger.info("in signWithSignpost"); String consumerKey = null; String consumerSecret = null; if (consumerKey0 == null) { consumerKey = defaultConsumerKey; consumerSecret = defaultConsumerSecret; } else { consumerKey = consumerKey0; consumerSecret = consumerSecret0; } logger.info( "in signWithSignpost pre new DefaultOAuthConsumer " + consumerKey + " " + consumerSecret); OAuthConsumer oauthConsumer = new DefaultOAuthConsumer(consumerKey, consumerSecret); logger.info("in signWithSignpost post new DefaultOAuthConsumer"); oauth.signpost.http.HttpRequest spRequest = new HttpRequestAdapter(hcRequest); logger.info("in signWithSignpost post new HttpRequestAdapter"); if (token == null) { oauthConsumer.setTokenWithSecret(null, ""); } else { oauthConsumer.setTokenWithSecret(token, tokenSecret); } try { String whatDebugWas = null; /* un-comment to get SBS */ // whatDebugWas = System.setProperty("debug", "true"); logger.info("in signWithSignpost pre sign"); oauthConsumer.sign(spRequest); logger.info("in signWithSignpost post sign"); /* un-comment this also when un-commenting the above */ // if (whatDebugWas == null) { System.clearProperty("debug"); } else { // System.setProperty("debug", whatDebugWas); } } catch (OAuthMessageSignerException omse) { throw new IndivoClientException(omse); } catch (OAuthExpectationFailedException oefe) { throw new IndivoClientException(oefe); } catch (oauth.signpost.exception.OAuthCommunicationException oce) { throw new IndivoClientException(oce); } }
/** * Retrieve the oauth_verifier, and store the oauth and oauth_token_secret for future API calls. */ @Override protected Void doInBackground(Uri... params) { final Uri uri = params[0]; final String oauth_verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER); try { provider.retrieveAccessToken(consumer, oauth_verifier); final Editor edit = prefs.edit(); edit.putString(OAuth.OAUTH_TOKEN, consumer.getToken()); edit.putString(OAuth.OAUTH_TOKEN_SECRET, consumer.getTokenSecret()); edit.commit(); String token = prefs.getString(OAuth.OAUTH_TOKEN, ""); String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, ""); consumer.setTokenWithSecret(token, secret); context.startActivity(new Intent(context, TwitterActivity.class)); executeAfterAccessTokenRetrieval(); Log.i(TAG, "OAuth - Access Token Retrieved"); } catch (Exception e) { Log.e(TAG, "OAuth - Access Token Retrieval Error", e); } return null; }
public String makeServiceCall(String url) { OAuthConsumer oAuthConsumer = new CommonsHttpOAuthConsumer(consumerKeyStr, consumerSecretStr); oAuthConsumer.setTokenWithSecret(accessTokenStr, accessTokenSecretStr); HttpGet httpGet = new HttpGet(url); try { oAuthConsumer.sign(httpGet); HttpClient httpClient = new DefaultHttpClient(); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); String jsonResponse = EntityUtils.toString(httpEntity); return jsonResponse; } catch (OAuthMessageSignerException e) { e.printStackTrace(); return null; } catch (OAuthExpectationFailedException e) { e.printStackTrace(); return null; } catch (OAuthCommunicationException e) { e.printStackTrace(); return null; } catch (ClientProtocolException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } }
@Override protected String doInBackground(String... urls) { HttpClient httpClient = new DefaultHttpClient(); Log.d("inbgactivity", urls[0]); if (networkStatus() == NETWORK_STATUS_OK) { if (method.equalsIgnoreCase("POST")) { try { HttpPost request = new HttpPost(urls[0]); Log.d("asd", this.params); StringEntity parameters = new StringEntity(params); request.addHeader("content-type", "application/json"); request.setEntity(parameters); HttpResponse response = httpClient.execute(request); return EntityUtils.toString(response.getEntity()); } catch (Exception e) { e.printStackTrace(); Log.d("bg exception", e.toString()); return null; } } else if (method.equalsIgnoreCase("GET")) { try { HttpGet request = new HttpGet(urls[0]); HttpResponse response = httpClient.execute(request); return EntityUtils.toString(response.getEntity()); } catch (Exception e) { e.printStackTrace(); Log.d("bg exception", e.toString()); return null; } } else if (method.equalsIgnoreCase("OAUTH_GET")) { try { OAuthConsumer consumer = new DefaultOAuthConsumer(LINKEDIN_API_KEY, LINKEDIN_SECRET_KEY); consumer.setTokenWithSecret(urls[1], urls[2]); URL url = new URL(urls[0]); HttpURLConnection request = (HttpURLConnection) url.openConnection(); request.setRequestMethod("GET"); request.setUseCaches(true); consumer.sign(request); request.connect(); BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); Log.d("as", sb.toString()); return sb.toString(); } catch (Exception e) { e.printStackTrace(); Log.d("bg exception", e.toString()); return null; } } else return null; } else { return null; } }
/** Loads saved keys token and configure consumer with provider tokens */ private void loadSavedKeys() { if (getPreferences().contains(OAuth.OAUTH_TOKEN) && getPreferences().contains(OAuth.OAUTH_TOKEN_SECRET)) { mToken = getPreferences().getString(OAuth.OAUTH_TOKEN, null); mSecret = getPreferences().getString(OAuth.OAUTH_TOKEN_SECRET, null); if (mToken != null && mSecret != null) { mConsumer.setTokenWithSecret(mToken, mSecret); } } }
public static void test1() throws OAuthMessageSignerException, OAuthNotAuthorizedException, OAuthExpectationFailedException, OAuthCommunicationException, IOException { Properties prop = new Properties(); InputStream in = KivaApiExampleWithSignPost.class.getResourceAsStream("/signpost.properties"); prop.load(in); String consumerKey = prop.getProperty("oauth.consumer.key"); String consumerSecret = prop.getProperty("oauth.consumer.secret"); in.close(); System.setProperty("debug", "true"); OAuthConsumer consumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret); // Note: we have to add the consumer key in the authorization URL to make it work OAuthProvider provider = new CommonsHttpOAuthProvider( REQUEST_TOKEN_URL, ACCESS_TOKEN_URL, AUTHORIZATION_URL + "&client_id=" + consumerKey); /* * This has to be done once to get request token */ provider.setOAuth10a(true); // for some reason, SignPost does not append oauth_callback so I // added it directly into the AUTHORIZATION_URL String requestUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL); System.out.println("Copy/Paste the following URL in your browser: " + requestUrl); System.out.print("Enter your token: "); // read authorization code Scanner scanner = new Scanner(System.in); String authorizationCode = scanner.nextLine().trim(); provider.retrieveAccessToken(consumer, authorizationCode); String accessToken = consumer.getToken(); String tokenSecret = consumer.getTokenSecret(); System.out.println("Token: " + accessToken + ". Secret: " + tokenSecret); // store token and secret somewhere in a database or in a file // so that it can be used later /* * To be done whenever you use the Kiva API */ OAuthConsumer newConsumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret); newConsumer.setTokenWithSecret(accessToken, tokenSecret); HttpGet request = new HttpGet(RESOURCE_URL); consumer.sign(request); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(request); // send request and get content String content = IOUtil.toString(response.getEntity().getContent()); System.out.println(content); }
private JSONObject OAuthGet(String url) throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException, ClientProtocolException, IOException, IllegalStateException, JSONException { String[] oauth_tokens = getOAuthTokens(); consumer.setTokenWithSecret(oauth_tokens[0], oauth_tokens[1]); HttpGet req = new HttpGet(url); consumer.sign(req); HttpResponse response = client.execute(req); JSONObject result = new JSONObject(convertToString(response.getEntity().getContent())); return result; }
OAuthConsumer setupConsumer(ApiKey apiKey) { String api_key = guestService.getApiKeyAttribute(apiKey, "bodymediaConsumerKey"); String bodymediaConsumerSecret = guestService.getApiKeyAttribute(apiKey, "bodymediaConsumerSecret"); OAuthConsumer consumer = new CommonsHttpOAuthConsumer(api_key, bodymediaConsumerSecret); String accessToken = guestService.getApiKeyAttribute(apiKey, "accessToken"); String tokenSecret = guestService.getApiKeyAttribute(apiKey, "tokenSecret"); consumer.setTokenWithSecret(accessToken, tokenSecret); return consumer; }
/** * This method takes into account the Indivo specificities when obtaining a request token, which * are detailed in this class description. It has the same signature as the standard * retrieveRequestToken() method except it takes an extra parameter recordId. * * @param consumer the OAuthConsumer to be used for OAuth processing * @param callbackUrl an optional alternative OAuth callback URL * @param recordId an optional record ID to be used when it is received by the start URL * @return the received request token as a String * @throws OAuthMessageSignerException * @throws OAuthNotAuthorizedException * @throws OAuthExpectationFailedException * @throws OAuthCommunicationException */ public String retrieveRequestToken(OAuthConsumer consumer, String callbackUrl, RecordId recordId) throws OAuthMessageSignerException, OAuthNotAuthorizedException, OAuthExpectationFailedException, OAuthCommunicationException { // invalidate current credentials, if any consumer.setTokenWithSecret(null, null); // if a recordId is present, it has to be used only at request sending (another method in this // class) ... if (recordId != null) { // ... therefore we create a protected block to guarantee the shared recordId we set is not // overwritten synchronized (this) { // set the shared recordId to be used by method sendRequest() this.sharedRecordId = recordId; // 1.0a expects the callback to be sent while getting the request token. // 1.0 service providers would simply ignore this parameter. this.retrieveToken( consumer, super.getRequestTokenEndpointUrl(), OAuth.OAUTH_CALLBACK, callbackUrl); // unset the shared recordId this.sharedRecordId = null; } } else { this.retrieveToken( consumer, super.getRequestTokenEndpointUrl(), OAuth.OAUTH_CALLBACK, callbackUrl); } /// Indivo does not send OAUTH_CALLBACK_CONFIRMED for now /// this is why the following lines are commented /* String callbackConfirmed = super.getResponseParameters().getFirst(OAuth.OAUTH_CALLBACK_CONFIRMED); super.getResponseParameters().remove(OAuth.OAUTH_CALLBACK_CONFIRMED); isOAuth10a = Boolean.TRUE.toString().equals(callbackConfirmed); */ // 1.0 service providers expect the callback as part of the auth URL, // Do not send when 1.0a. if (super.isOAuth10a()) { return OAuth.addQueryParameters( super.getAuthorizationWebsiteUrl(), OAuth.OAUTH_TOKEN, consumer.getToken()); } else { return OAuth.addQueryParameters( super.getAuthorizationWebsiteUrl(), OAuth.OAUTH_TOKEN, consumer.getToken(), OAuth.OAUTH_CALLBACK, callbackUrl); } }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle extras = getIntent().getExtras(); if (extras != null) { oauthToken = extras.getString("oauth_token"); oauthTokenSecret = extras.getString("oauth_token_secret"); consumer = new DefaultOAuthConsumer(FEOauth.CONSUMER_KEY, FEOauth.CONSUMER_SECRET); consumer.setTokenWithSecret(oauthToken, oauthTokenSecret); Intent myIntent = new Intent(this, FileBrowserActivity.class); myIntent.putExtra(FileBrowserActivity.EXTRA_DEFAULT_ROOT, AMEnv.DEFAULT_ROOT_PATH); myIntent.putExtra(FileBrowserActivity.EXTRA_FILE_EXTENSIONS, ".db"); startActivityForResult(myIntent, FILE_BROWSER); } }
/** * Creates a connection to the Streaming Filter API * * @param baseUrl the URL for Twitter Filter API * @param outFilePath Location to place the exported file */ private InputStream CreateStreamingConnection(String baseUrl) { HttpClient httpClient = new DefaultHttpClient(); httpClient .getParams() .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer(90000)); // Step 1: Initialize OAuth Consumer OAuthConsumer consumer = new CommonsHttpOAuthConsumer(OAuthUtils.CONSUMER_KEY, OAuthUtils.CONSUMER_SECRET); consumer.setTokenWithSecret(OAuthToken.getAccessToken(), OAuthToken.getAccessSecret()); // Step 2: Create a new HTTP POST request and set parameters HttpPost httppost = new HttpPost(baseUrl); try { httppost.setEntity(new UrlEncodedFormEntity(CreateRequestBody(), "UTF-8")); } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); } try { // Step 3: Sign the request consumer.sign(httppost); } catch (OAuthMessageSignerException ex) { ex.printStackTrace(); } catch (OAuthExpectationFailedException ex) { ex.printStackTrace(); } catch (OAuthCommunicationException ex) { ex.printStackTrace(); } HttpResponse response; InputStream is = null; try { // Step 4: Connect to the API response = httpClient.execute(httppost); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new IOException("Got status " + response.getStatusLine().getStatusCode()); } else { System.out.println(OAuthToken.getAccessToken() + ": Processing from " + baseUrl); HttpEntity entity = response.getEntity(); try { is = entity.getContent(); } catch (IOException ex) { ex.printStackTrace(); } catch (IllegalStateException ex) { ex.printStackTrace(); } } } catch (IOException ex) { ex.printStackTrace(); } return is; }
public static OAuthConsumer getOAuthConsumer(Context context) { if (!isLoggedIn(context)) { return null; } SharedPreferences prefs = getSharedPreferences("oauth"); OAuthConsumer consumer = new CommonsHttpOAuthConsumer( prefs.getString(context.getString(R.string.setting_oauth_consumer_key), null), prefs.getString(context.getString(R.string.setting_oauth_consumer_secret), null)); consumer.setTokenWithSecret( prefs.getString(context.getString(R.string.setting_oauth_token), null), prefs.getString(context.getString(R.string.setting_oauth_token_secret), null)); return consumer; }
/** * Signs the connection with an OAuth authentication header * * @param connection the connection * @throws OsmTransferException thrown if there is currently no OAuth Access Token configured * @throws OsmTransferException thrown if signing fails */ protected void addOAuthAuthorizationHeader(HttpURLConnection connection) throws OsmTransferException { if (oauthParameters == null) { oauthParameters = OAuthParameters.createFromPreferences(Main.pref); } OAuthConsumer consumer = oauthParameters.buildConsumer(); OAuthAccessTokenHolder holder = OAuthAccessTokenHolder.getInstance(); if (!holder.containsAccessToken()) throw new MissingOAuthAccessTokenException(); consumer.setTokenWithSecret(holder.getAccessTokenKey(), holder.getAccessTokenSecret()); try { consumer.sign(connection); } catch (OAuthException e) { throw new OsmTransferException( tr("Failed to sign a HTTP connection with an OAuth Authentication header"), e); } }
private HttpGet connect(Authentication app) { OAuthConsumer consumer = new CommonsHttpOAuthConsumer(app.getConsumerKey(), app.getConsumerSecret()); consumer.setTokenWithSecret(app.getAccessToken(), app.getAccessSecret()); HttpGet request = new HttpGet("https://stream.twitter.com/1.1/statuses/sample.json"); try { consumer.sign(request); } catch (OAuthMessageSignerException e) { e.printStackTrace(); } catch (OAuthExpectationFailedException e) { e.printStackTrace(); } catch (OAuthCommunicationException e) { e.printStackTrace(); } return request; }
private static String getUpdatedWikiContents(UserPreferences prefs) throws IOException, OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException { final OAuthConsumer consumer = new DefaultOAuthConsumer( AppCredentials.INSTANCE.getKey(), AppCredentials.INSTANCE.getSecret()); consumer.setTokenWithSecret(prefs.getOauthTokenKey(), prefs.getOauthTokenSecret()); final URL url = new URL(DropboxWikiClient.FILE_BASE_URL + prefs.getWikiPath()); final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("GET"); consumer.sign(connection); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { String contents = extractString(connection.getInputStream()); return contents; } LOG.error("Error getting wiki. Got response {}", connection.getResponseCode()); throw new IOException(); }
/** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // mConsumer = new DefaultOAuthConsumer(OAUTH_KEY, OAUTH_SECRET); mConsumer = new CommonsHttpOAuthConsumer(OAUTH_KEY, OAUTH_SECRET); mProvider = new DefaultOAuthProvider( "https://api.twitter.com/oauth/request_token", "https://api.twitter.com/oauth/access_token", "https://api.twitter.com/oauth/authorize"); // Read the prefs to see if we have token prefs = PreferenceManager.getDefaultSharedPreferences(this); String token = prefs.getString("token", null); String tokenSecret = prefs.getString("tokenSecret", null); if (token != null && tokenSecret != null) { // We have token, use it mConsumer.setTokenWithSecret(token, tokenSecret); // Make a Twitter object oauthClient = new OAuthSignpostClient(OAUTH_KEY, OAUTH_SECRET, token, tokenSecret); twitter = new Twitter(TWITTER_USER, oauthClient); } }
public OAuthConsumer loadConsumer(OAuthConsumer consumer) { consumer.setTokenWithSecret(p.getString("token", ""), p.getString("token_secret", "")); return consumer; }
private void setAccessToken(String token, String tokenSecret) { consumer.setTokenWithSecret(token, tokenSecret); }
public void onCreate(OAuthObject oauthData) { consumer2 = new CommonsHttpOAuthConsumer( oauthData.getConsumerKey(), oauthData.getConsumerSecret(), SignatureMethod.HMAC_SHA1); consumer2.setTokenWithSecret(oauthData.getToken(), oauthData.getTokenSecret()); }
public EdaciousOauthImpl getImplementation( Long userId, String token, String tokenSecret, String comment) { OAuthConsumer consumer = getConsumer(); consumer.setTokenWithSecret(token, tokenSecret); return new EdaciousOauthImpl(userId, consumer, comment); }
public void setOAuthTokens(String token, String secret) { consumer.setTokenWithSecret(token, secret); }