Java Code Examples for oauth.signpost.OAuthConsumer#setTokenWithSecret()

The following examples show how to use oauth.signpost.OAuthConsumer#setTokenWithSecret() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: OsmConnection.java    From osmapi with GNU Lesser General Public License v3.0 6 votes vote down vote up
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;
	}
}
 
Example 2
Source File: BurpExtender.java    From burp-oauth with MIT License 6 votes vote down vote up
@Override
public void processHttpMessage(int toolFlag, boolean messageIsRequest, IHttpRequestResponse messageInfo)
{
	if (messageIsRequest && shouldSign(messageInfo))
	{
		HttpRequest req = new BurpHttpRequestWrapper(messageInfo);
		OAuthConsumer consumer = new DefaultOAuthConsumer(
				OAuthConfig.getConsumerKey(),
				OAuthConfig.getConsumerSecret());
		consumer.setTokenWithSecret(OAuthConfig.getToken(),
				OAuthConfig.getTokenSecret());
		try {
			consumer.sign(req);
		} catch (OAuthException oae) {
			oae.printStackTrace();
		}
	}
}
 
Example 3
Source File: OAuth.java    From AndroidApp with Mozilla Public License 2.0 5 votes vote down vote up
public static OAuthConsumer loadConsumer(SharedPreferences prefs) {
    OAuthConsumer result = createConsumer();
    String accessToken = prefs.getString(Prefs.OAUTH_ACCESS_TOKEN, null);
    String accessTokenSecret = prefs.getString(Prefs.OAUTH_ACCESS_TOKEN_SECRET, null);
    result.setTokenWithSecret(accessToken, accessTokenSecret);
    return result;
}
 
Example 4
Source File: Authenticator.java    From AndroidApp with Mozilla Public License 2.0 5 votes vote down vote up
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;
}
 
Example 5
Source File: ConnectionTestFactory.java    From osmapi with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static OAuthConsumer createConsumerThatProhibitsEverything()
{
	OAuthConsumer result = new DefaultOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
	result.setTokenWithSecret(
			"RCamNf4TT7uNeFjmigvOUWhajp5ERFZmcN1qvi7a",
			"72dzmAvuNBEOVKkif3JSYdzMlAq2dw5OnIG75dtX");
	return result;
}
 
Example 6
Source File: ConnectionTestFactory.java    From osmapi with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static OAuthConsumer createConsumerThatAllowsEverything()
{
	OAuthConsumer result = new DefaultOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
	result.setTokenWithSecret(
			"2C4LiOQBOn96kXHyal7uzMJiqpCsiyDBvb8pomyX",
			"1bFMIQpgmu5yjywt3kknopQpcRmwJ6snDDGF7kdr");
	return result;
}
 
Example 7
Source File: RestTask.java    From android-discourse with Apache License 2.0 5 votes vote down vote up
@Override
protected RestResult doInBackground(String... args) {
    try {
        request = createRequest();
        if (isCancelled())
            throw new InterruptedException();
        OAuthConsumer consumer = Session.getInstance().getOAuthConsumer();
        if (consumer != null) {
            AccessToken accessToken = Session.getInstance().getAccessToken();
            if (accessToken != null) {
                consumer.setTokenWithSecret(accessToken.getKey(), accessToken.getSecret());
            }
            consumer.sign(request);
        }
        request.setHeader("Accept-Language", Locale.getDefault().getLanguage());
        request.setHeader("API-Client", String.format("uservoice-android-%s", UserVoice.getVersion()));
        AndroidHttpClient client = AndroidHttpClient.newInstance(String.format("uservoice-android-%s", UserVoice.getVersion()), Session.getInstance().getContext());
        if (isCancelled())
            throw new InterruptedException();
        // TODO it would be nice to find a way to abort the request on cancellation
        HttpResponse response = client.execute(request);
        if (isCancelled())
            throw new InterruptedException();
        HttpEntity responseEntity = response.getEntity();
        StatusLine responseStatus = response.getStatusLine();
        int statusCode = responseStatus != null ? responseStatus.getStatusCode() : 0;
        String body = responseEntity != null ? EntityUtils.toString(responseEntity) : null;
        client.close();
        if (isCancelled())
            throw new InterruptedException();
        return new RestResult(statusCode, new JSONObject(body));
    } catch (Exception e) {
        return new RestResult(e);
    }
}
 
Example 8
Source File: WSUrlFetch.java    From restcommander with Apache License 2.0 5 votes vote down vote up
private HttpURLConnection prepare(URL url, String method) {
    if (this.username != null && this.password != null && this.scheme != null) {
        String authString = null;
        switch (this.scheme) {
        case BASIC: authString = basicAuthHeader(); break;
        default: throw new RuntimeException("Scheme " + this.scheme + " not supported by the UrlFetch WS backend.");
        }
        this.headers.put("Authorization", authString);
    }
    try {
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod(method);
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(this.followRedirects);
        connection.setReadTimeout(this.timeout * 1000);
        for (String key: this.headers.keySet()) {
            connection.setRequestProperty(key, headers.get(key));
        }
        checkFileBody(connection);
        if (this.oauthToken != null && this.oauthSecret != null) {
            OAuthConsumer consumer = new DefaultOAuthConsumer(oauthInfo.consumerKey, oauthInfo.consumerSecret);
            consumer.setTokenWithSecret(oauthToken, oauthSecret);
            consumer.sign(connection);
        }
        return connection;
    } catch(Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 9
Source File: OAuth.java    From restcommander with Apache License 2.0 5 votes vote down vote up
/**
 * Exchange a request token for an access token.
 * @param token the token obtained from a previous call
 * @param secret your application secret
 * @return a Response object holding either the result in case of a success or the error
 */
public Response retrieveAccessToken(String token, String secret) {
     OAuthConsumer consumer = new DefaultOAuthConsumer(info.consumerKey, info.consumerSecret);
    consumer.setTokenWithSecret(token, secret);
    String verifier = Params.current().get("oauth_verifier");
    try {
        provider.retrieveAccessToken(consumer, verifier);
    } catch (OAuthException e) {
        return Response.error(new Error(e));
    }
    return Response.success(consumer.getToken(), consumer.getTokenSecret());
}
 
Example 10
Source File: OAuthTest.java    From burp-oauth with MIT License 5 votes vote down vote up
@Test
public void testSignature() throws Exception {
	HttpRequest hr = reqWrapForTestInput(1);
	OAuthConsumer consumer = new DefaultOAuthConsumer("1234", "5678");
	consumer.setTokenWithSecret("9ABC", "DEF0");
	consumer.sign(hr);
}
 
Example 11
Source File: RestTask.java    From uservoice-android-sdk with MIT License 5 votes vote down vote up
@Override
protected RestResult doInBackground(String... args) {
    try {
        Request request = createRequest();
        if (isCancelled())
            throw new InterruptedException();
        OkHttpClient client = new OkHttpClient();
        OAuthConsumer consumer = Session.getInstance().getOAuthConsumer(context);
        if (consumer != null) {
            AccessToken accessToken = Session.getInstance().getAccessToken();
            if (accessToken != null) {
                consumer.setTokenWithSecret(accessToken.getKey(), accessToken.getSecret());
            }
            request = (Request) consumer.sign(request).unwrap();
        }
        Log.d("UV", urlPath);
        if (isCancelled())
            throw new InterruptedException();
        // TODO it would be nice to find a way to abort the request on cancellation
        Response response = client.newCall(request).execute();
        if (isCancelled())
            throw new InterruptedException();
        int statusCode = response.code();
        String body = response.body().string();
        if (statusCode >= 400) {
            Log.d("UV", body);
        }
        if (isCancelled())
            throw new InterruptedException();
        return new RestResult(statusCode, new JSONObject(body));
    } catch (Exception e) {
        return new RestResult(e);
    }
}
 
Example 12
Source File: KAAPIAdapter.java    From android-viewer-for-khan-academy with GNU General Public License v3.0 5 votes vote down vote up
public OAuthConsumer getConsumer(User user) {
	OAuthConsumer consumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
	if (user != null) {
		String token = user.getToken();
		String secret = user.getSecret();
		if (token != null && secret != null) {
			consumer.setTokenWithSecret(token, secret);
		}
	}
	return consumer;
}
 
Example 13
Source File: KAAPIAdapter.java    From android-viewer-for-khan-academy with GNU General Public License v3.0 5 votes vote down vote up
public void login(final String token, final String secret, final UserLoginHandler handler) {
	OAuthConsumer consumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
	consumer.setTokenWithSecret(token, secret);
	fetchUser(consumer, new EntityCallback<User>() {
		@Override
		public void call(User returnedUser) {
			
			if (returnedUser != null) {
				returnedUser.setToken(token);
				returnedUser.setSecret(secret);
				try {
					Dao<User, String> userDao = dataService.getHelper().getUserDao();
					if (userDao.getConnectionSource().isOpen()) {
						userDao.createOrUpdate(returnedUser);
					}
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			handler.onUserLogin(returnedUser);
			currentUser = returnedUser;
			setCurrentUser(returnedUser);
			doUserUpdate(returnedUser);
		}
	});
}
 
Example 14
Source File: TestTwitterSocket.java    From albert with MIT License 4 votes vote down vote up
public static void main(String[] args) throws Exception {
	  OAuthConsumer consumer = new CommonsHttpOAuthConsumer(
				Constants.ConsumerKey,
				Constants.ConsumerSecret);
	  consumer.setTokenWithSecret(Constants.AccessToken, Constants.AccessSecret);
	  
	  
    HttpParams params = new BasicHttpParams();
    // HTTP 协议的版本,1.1/1.0/0.9
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    // 字符集
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    // 伪装的浏览器类型
    // IE7 是 
    // Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 6.0)
    //
    // Firefox3.03
    // Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3
    //
    HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
    HttpProtocolParams.setUseExpectContinue(params, true);
    BasicHttpProcessor httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new RequestContent());
    httpproc.addInterceptor(new RequestTargetHost());
    httpproc.addInterceptor(new RequestConnControl());
    httpproc.addInterceptor(new RequestUserAgent());
    httpproc.addInterceptor(new RequestExpectContinue());
    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
    HttpContext context = new BasicHttpContext(null);
    HttpHost host = new HttpHost("127.0.0.1", 1080);
    DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
    ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();
    context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
    try {
      String[] targets = { "https://www.twitter.com"};
      for (int i = 0; i < targets.length; i++) {
        if (!conn.isOpen()) {
          Socket socket = new Socket(host.getHostName(), host.getPort());
          conn.bind(socket, params);
        }
        
	  
        BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]);
//        consumer.sign(request);
        
        System.out.println(">> Request URI: " + request.getRequestLine().getUri());
        context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
        request.setParams(params);
        httpexecutor.preProcess(request, httpproc, context);
        HttpResponse response = httpexecutor.execute(request, conn, context);
        response.setParams(params);
        httpexecutor.postProcess(response, httpproc, context);
        // 返回码
        System.out.println("<< Response: " + response.getStatusLine());
        // 返回的文件头信息
//        Header[] hs = response.getAllHeaders();
//        for (Header h : hs) {
//          System.out.println(h.getName() + ":" + h.getValue());
//        }
        // 输出主体信息
//        System.out.println(EntityUtils.toString(response.getEntity()));
        
        HttpEntity entry = response.getEntity();
        StringBuffer sb = new StringBuffer();
  	  if(entry != null)
  	  {
  	    InputStreamReader is = new InputStreamReader(entry.getContent());
  	    BufferedReader br = new BufferedReader(is);
  	    String str = null;
  	    while((str = br.readLine()) != null)
  	    {
  	     sb.append(str.trim());
  	    }
  	    br.close();
  	  }
  	  System.out.println(sb.toString());
  	  
        System.out.println("==============");
        if (!connStrategy.keepAlive(response, context)) {
          conn.close();
        } else {
          System.out.println("Connection kept alive...");
        }
      }
    } finally {
      conn.close();
    }
  }