oauth.signpost.commonshttp.CommonsHttpOAuthConsumer Java Examples

The following examples show how to use oauth.signpost.commonshttp.CommonsHttpOAuthConsumer. 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: LtiOauthSigner.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public HttpRequest sign(HttpRequest request, String key, String secret) throws LtiSigningException {
    CommonsHttpOAuthConsumer signer = new CommonsHttpOAuthConsumer(key, secret);
    try {
        String body = getRequestBody(request);
        String bodyHash = new String(Base64.encodeBase64(md.digest(body.getBytes())));

        HttpParameters params = new HttpParameters();
        params.put("oauth_body_hash", URLEncoder.encode(bodyHash, "UTF-8"));
        signer.setAdditionalParameters(params);

        signer.sign(request);
    } catch (OAuthMessageSignerException|OAuthExpectationFailedException|OAuthCommunicationException|IOException e) {
        throw new LtiSigningException("Exception encountered while singing Lti request...", e);
    }
    return request;
}
 
Example #2
Source File: IMSPOXRequest.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public static HttpPost buildReplaceResult(String url, String key, String secret, String sourcedid, String score, String resultData, Boolean isUrl) throws IOException, OAuthException, GeneralSecurityException {
	String dataXml = "";
	if (resultData != null) {
		String format = isUrl ? resultDataUrl : resultDataText;
		dataXml = String.format(format, StringEscapeUtils.escapeXml(resultData));
	}
	//*LAMS* the following line was added by LAMS and also messageIdentifier was added to the line after it
	String messageIdentifier = UUID.randomUUID().toString();
	String xml = String.format(replaceResultMessage, messageIdentifier, StringEscapeUtils.escapeXml(sourcedid),
			StringEscapeUtils.escapeXml(score), dataXml);

	HttpParameters parameters = new HttpParameters();
	String hash = getBodyHash(xml);
	parameters.put("oauth_body_hash", URLEncoder.encode(hash, "UTF-8"));

	CommonsHttpOAuthConsumer signer = new CommonsHttpOAuthConsumer(key, secret);
	HttpPost request = new HttpPost(url);
	request.setHeader("Content-Type", "application/xml");
	request.setEntity(new StringEntity(xml, "UTF-8"));
	signer.setAdditionalParameters(parameters);
	signer.sign(request);
	return request;
}
 
Example #3
Source File: OAuthClientTest.java    From java-upwork with Apache License 2.0 6 votes vote down vote up
private OAuthClient getMockedClient() throws Exception {
	when(properties.getProperty("consumerKey")).thenReturn("key");
	when(properties.getProperty("consumerSecret")).thenReturn("secret");
	
	final FileInputStream fileInputStreamMock = PowerMockito.mock(FileInputStream.class);
       PowerMockito.whenNew(FileInputStream.class).withArguments(Matchers.anyString())
                           .thenReturn(fileInputStreamMock);
	
	PowerMockito.whenNew(CommonsHttpOAuthConsumer.class).withArguments(Matchers.anyString(), Matchers.anyString())
                           .thenReturn(CommonsHttpOAuthConsumerMock);
       
       PowerMockito.whenNew(CommonsHttpOAuthProvider.class).withArguments(Matchers.anyString(), Matchers.anyString(), Matchers.anyString())
       					.thenReturn(CommonsHttpOAuthProviderMock);
       
       Config config = new Config(properties);
	
	OAuthClient client = new OAuthClient(config);
	
	return client;
}
 
Example #4
Source File: LtiOauthSigner.java    From basiclti-util-java with Apache License 2.0 6 votes vote down vote up
@Override
public HttpRequest sign(HttpRequest request, String key, String secret) throws LtiSigningException {
    CommonsHttpOAuthConsumer signer = new CommonsHttpOAuthConsumer(key, secret);
    try {
        String body = getRequestBody(request);
        String bodyHash = new String(Base64.encodeBase64(md.digest(body.getBytes())));

        HttpParameters params = new HttpParameters();
        params.put("oauth_body_hash", URLEncoder.encode(bodyHash, "UTF-8"));
        signer.setAdditionalParameters(params);

        signer.sign(request);
    } catch (OAuthMessageSignerException|OAuthExpectationFailedException|OAuthCommunicationException|IOException e) {
        throw new LtiSigningException("Exception encountered while singing Lti request...", e);
    }
    return request;
}
 
Example #5
Source File: OAuthClient.java    From java-upwork with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor
 * 
 * @param	properties Config properties
 * */
public OAuthClient(Config properties) {
	if (properties == null) {
		properties = new Config(null);  
	}
	
	consumerKey = properties.getProperty("consumerKey");
	consumerSecret = properties.getProperty("consumerSecret");

	mOAuthConsumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
}
 
Example #6
Source File: IMSPOXRequest.java    From basiclti-util-java with Apache License 2.0 5 votes vote down vote up
public static HttpPost buildReplaceResult(String url, String key, String secret, String sourcedid,
	String score, String resultData, Boolean isUrl, String messageId) throws IOException, OAuthException, GeneralSecurityException
{
	String dataXml = "";
	if (resultData != null) {
		String format = isUrl ? resultDataUrl : resultDataText;
		dataXml = String.format(format, StringEscapeUtils.escapeXml(resultData));
	}

	String messageIdentifier = StringUtils.isBlank(messageId) ? String.valueOf(new Date().getTime()) : messageId;
	String xml = String.format(ReplaceResultMessageTemplate,
		StringEscapeUtils.escapeXml(messageIdentifier),
		StringEscapeUtils.escapeXml(sourcedid),
		StringEscapeUtils.escapeXml(score),
		dataXml);

	HttpParameters parameters = new HttpParameters();
	String hash = getBodyHash(xml);
	parameters.put("oauth_body_hash", URLEncoder.encode(hash, "UTF-8"));

	CommonsHttpOAuthConsumer signer = new CommonsHttpOAuthConsumer(key, secret);
	HttpPost request = new HttpPost(url);
	request.setHeader("Content-Type", "application/xml");
	request.setEntity(new StringEntity(xml, "UTF-8"));
	signer.setAdditionalParameters(parameters);
	signer.sign(request);
	return request;
}
 
Example #7
Source File: OAuth1Utils.java    From shimmer with Apache License 2.0 5 votes vote down vote up
/**
 * Signs an HTTP post request for cases where OAuth 1.0 posts are
 * required instead of GET.
 *
 * @param unsignedUrl     - The unsigned URL
 * @param clientId        - The external provider assigned client id
 * @param clientSecret    - The external provider assigned client secret
 * @param token           - The access token
 * @param tokenSecret     - The 'secret' parameter to be used (Note: token secret != client secret)
 * @param oAuthParameters - Any additional parameters
 * @return The request to be signed and sent to external data provider.
 */
public static HttpRequestBase getSignedRequest(HttpMethod method,
                                               String unsignedUrl,
                                               String clientId,
                                               String clientSecret,
                                               String token,
                                               String tokenSecret,
                                               Map<String, String> oAuthParameters) throws ShimException {

    URL requestUrl = buildSignedUrl(unsignedUrl, clientId, clientSecret, token, tokenSecret, oAuthParameters);
    String[] signedParams = requestUrl.toString().split("\\?")[1].split("&");

    HttpRequestBase postRequest = method == HttpMethod.GET ?
        new HttpGet(unsignedUrl) : new HttpPost(unsignedUrl);
    String oauthHeader = "";
    for (String signedParam : signedParams) {
        String[] parts = signedParam.split("=");
        oauthHeader += parts[0] + "=\"" + parts[1] + "\",";
    }
    oauthHeader = "OAuth " + oauthHeader.substring(0, oauthHeader.length() - 1);
    postRequest.setHeader("Authorization", oauthHeader);
    CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer(clientId, clientSecret);
    consumer.setSendEmptyTokens(false);
    if (token != null) {
        consumer.setTokenWithSecret(token, tokenSecret);
    }
    try {
        consumer.sign(postRequest);
        return postRequest;
    } catch (
        OAuthMessageSignerException
            | OAuthExpectationFailedException
            | OAuthCommunicationException e) {
        e.printStackTrace();
        throw new ShimException("Could not sign POST request, cannot continue");
    }
}
 
Example #8
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 #9
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 #10
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();
    }
  }
 
Example #11
Source File: ToopherAPI.java    From oxAuth with MIT License 3 votes vote down vote up
/**
 * Create an API object with the supplied credentials
 * 
 * @param consumerKey
 *            The consumer key for a requester (obtained from the developer portal)
 * @param consumerSecret
 *            The consumer secret for a requester (obtained from the developer portal)
 */
public ToopherAPI(String consumerKey, String consumerSecret) {
    httpClient = new DefaultHttpClient();
    HttpProtocolParams.setUserAgent(httpClient.getParams(),
                                    String.format("ToopherJava/%s", VERSION));

    consumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
}