org.scribe.model.Response Java Examples

The following examples show how to use org.scribe.model.Response. 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: ResourceClient.java    From jerseyoauth2 with MIT License 7 votes vote down vote up
public SampleEntity retrieveEntitySample1(Token accessToken) throws ClientException
{
	OAuthService service = getOAuthService(scopes, null);
	
	OAuthRequest request = new OAuthRequest(Verb.GET,
			"http://localhost:9998/testsuite/rest/sample/1");
	service.signRequest(accessToken, request);
	Response response = request.send();
	if (response.getCode()!=200)
		throwClientException(response);
	
	ObjectMapper mapper = new ObjectMapper();
	try {
		SampleEntity entity = mapper.readValue(response.getBody(), SampleEntity.class);
		return entity;
	} catch (IOException e) {
		throw new ClientException(response.getBody());
	}
}
 
Example #2
Source File: SmugMugInterface.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
private <T> SmugMugResponse<T> makeRequest(
    String url, TypeReference<SmugMugResponse<T>> typeReference) throws IOException {
  // Note: there are no request params that need to go here, because smugmug fully specifies
  // which resource to get in the URL of a request, without using query params.
  String fullUrl;
  if (!url.contains("https://")) {
    fullUrl = BASE_URL + url;
  } else {
    fullUrl = url;
  }
  OAuthRequest request = new OAuthRequest(Verb.GET, fullUrl + "?_accept=application%2Fjson");
  oAuthService.signRequest(accessToken, request);
  final Response response = request.send();

  if (response.getCode() < 200 || response.getCode() >= 300) {
    throw new IOException(
        String.format("Error occurred in request for %s : %s", url, response.getMessage()));
  }

  return mapper.readValue(response.getBody(), typeReference);
}
 
Example #3
Source File: SliApi.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
public TokenResponse getAccessToken(Token requestToken, Verifier verifier, Token t) {
    TokenResponse tokenResponse = new TokenResponse();

    OAuthRequest request = new OAuthRequest(myApi.getAccessTokenVerb(), myApi.getAccessTokenEndpoint());
    request.addQuerystringParameter(OAuthConstants.CLIENT_ID, myConfig.getApiKey());
    request.addQuerystringParameter(OAuthConstants.CLIENT_SECRET, myConfig.getApiSecret());
    request.addQuerystringParameter(OAuthConstants.CODE, verifier.getValue());
    request.addQuerystringParameter(OAuthConstants.REDIRECT_URI, myConfig.getCallback());
    if (myConfig.hasScope()) {
        request.addQuerystringParameter(OAuthConstants.SCOPE, myConfig.getScope());
    }

    Response response = request.send();

    tokenResponse.oauthResponse = response;
    tokenResponse.token = myApi.getAccessTokenExtractor().extract(response.getBody());
    return tokenResponse;
}
 
Example #4
Source File: RequestBuilder.java    From jumblr with Apache License 2.0 6 votes vote down vote up
ResponseWrapper clear(Response response) {
    if (response.getCode() == 200 || response.getCode() == 201) {
        String json = response.getBody();
        try {
            Gson gson = new GsonBuilder().
                    registerTypeAdapter(JsonElement.class, new JsonElementDeserializer()).
                    create();
            ResponseWrapper wrapper = gson.fromJson(json, ResponseWrapper.class);
            if (wrapper == null) {
                throw new JumblrException(response);
            }
            wrapper.setClient(client);
            return wrapper;
        } catch (JsonSyntaxException ex) {
            throw new JumblrException(response);
        }
    } else {
        throw new JumblrException(response);
    }
}
 
Example #5
Source File: RequestBuilder.java    From jumblr with Apache License 2.0 6 votes vote down vote up
private Token parseXAuthResponse(final Response response) {
    String responseStr = response.getBody();
    if (responseStr != null) {
        // Response is received in the format "oauth_token=value&oauth_token_secret=value".
        String extractedToken = null, extractedSecret = null;
        final String[] values = responseStr.split("&");
        for (String value : values) {
            final String[] kvp = value.split("=");
            if (kvp != null && kvp.length == 2) {
                if (kvp[0].equals("oauth_token")) {
                    extractedToken = kvp[1];
                } else if (kvp[0].equals("oauth_token_secret")) {
                    extractedSecret = kvp[1];
                }
            }
        }
        if (extractedToken != null && extractedSecret != null) {
            return new Token(extractedToken, extractedSecret);
        }
    }
    // No good
    throw new JumblrException(response);
}
 
Example #6
Source File: XeroClient.java    From xero-java-client with Apache License 2.0 6 votes vote down vote up
protected com.connectifier.xeroclient.models.Response get(String endPoint, Date modifiedAfter, Map<String,String> params) {
  OAuthRequest request = new OAuthRequest(Verb.GET, BASE_URL + endPoint);
  if (modifiedAfter != null) {
    request.addHeader("If-Modified-Since", utcFormatter.format(modifiedAfter));
  }
  if (params != null) {
    for (Map.Entry<String,String> param : params.entrySet()) {
      request.addQuerystringParameter(param.getKey(), param.getValue());
    }
  }
  service.signRequest(token, request);
  Response response = request.send();
  if (response.getCode() != 200) {
    throw newApiException(response);
  }
  return unmarshallResponse(response.getBody(), com.connectifier.xeroclient.models.Response.class);
}
 
Example #7
Source File: XeroClient.java    From xero-java-client with Apache License 2.0 6 votes vote down vote up
protected XeroApiException newApiException(Response response) {
  ApiException exception = null;
  try {
    exception = unmarshallResponse(response.getBody(), ApiException.class);
  } catch (Exception e) {
  }
  // Jibx doesn't support xsi:type, so we pull out errors this somewhat-hacky way
  Matcher matcher = MESSAGE_PATTERN.matcher(response.getBody());
  StringBuilder messages = new StringBuilder();
  while (matcher.find()) {
    if (messages.length() > 0) {
      messages.append(", ");
    }
    messages.append(matcher.group(1));
  }
  if (exception == null) {
    if (messages.length() > 0) {
      return new XeroApiException(response.getCode(), messages.toString());
    }
    return new XeroApiException(response.getCode());
  }
  return new XeroApiException(response.getCode(), "Error number " + exception.getErrorNumber() + ". " + messages);
}
 
Example #8
Source File: JumblrException.java    From jumblr with Apache License 2.0 6 votes vote down vote up
/**
 * Instantiate a new JumblrException given a bad response to wrap
 * @param response the response to wrap
 */
public JumblrException(Response response) {
    this.responseCode = response.getCode();
    String body = response.getBody();

    JsonParser parser = new JsonParser();
    try {
        final JsonElement element = parser.parse(body);
        if (element.isJsonObject()) {
            JsonObject object = element.getAsJsonObject();
            this.extractMessage(object);
            this.extractErrors(object);
        } else {
            this.message = body;
        }
    } catch (JsonParseException ex) {
        this.message = body;
    }
}
 
Example #9
Source File: HubicOAuth20ServiceImpl.java    From swift-explorer with Apache License 2.0 6 votes vote down vote up
public Token refreshAccessToken (Token expiredToken)
{
	if (expiredToken == null)
		return null ;
	
	OAuthRequest request = new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint());
	
	String authenticationCode = config.getApiKey() + ":" + config.getApiSecret() ;
	byte[] bytesEncodedAuthenticationCode = Base64.encodeBase64(authenticationCode.getBytes()); 
	request.addHeader ("Authorization", "Basic " + bytesEncodedAuthenticationCode) ;
	
	String charset = "UTF-8";
	
	request.setCharset(charset);
	request.setFollowRedirects(false);
	
	AccessToken at = new HubicTokenExtractorImpl ().getAccessToken(expiredToken.getRawResponse()) ;
	
	try
	{
		request.addBodyParameter("refresh_token", at.getRefreshToken());
		//request.addBodyParameter("refresh_token", URLEncoder.encode(at.getRefreshToken(), charset));
		request.addBodyParameter("grant_type", "refresh_token");
		request.addBodyParameter(OAuthConstants.CLIENT_ID, URLEncoder.encode(config.getApiKey(), charset));
		request.addBodyParameter(OAuthConstants.CLIENT_SECRET, URLEncoder.encode(config.getApiSecret(), charset));
	} 
	catch (UnsupportedEncodingException e) 
	{			
		logger.error("Error occurred while refreshing the access token", e);
	}
	
	Response response = request.send();
	Token newToken = api.getAccessTokenExtractor().extract(response.getBody());		
	// We need to keep the initial RowResponse because it contains the refresh token
	return new Token (newToken.getToken(), newToken.getSecret(), expiredToken.getRawResponse()) ;
}
 
Example #10
Source File: HubicSwift.java    From swift-explorer with Apache License 2.0 6 votes vote down vote up
private static SwiftAccess getSwiftAccess (HubicOAuth20ServiceImpl service, Token accessToken)
{
	String urlCredential = HubicApi.CREDENTIALS_URL;
	
    OAuthRequest request = new OAuthRequest(Verb.GET, urlCredential);
    request.setConnectionKeepAlive(false);
    service.signRequest(accessToken, request);
    Response responseReq = request.send();
    
    SwiftAccess ret = gson.fromJson(responseReq.getBody(), SwiftAccess.class) ;
    ret.setAccessToken(accessToken);
    
    logger.info("Swift access token expiry date: " + ret.getExpires());
    
	return ret ;
}
 
Example #11
Source File: Google2Api.java    From jpa-invoicer with The Unlicense 6 votes vote down vote up
@Override
public Token getAccessToken(Token requestToken, Verifier verifier) {
    OAuthRequest request = new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint());
    switch (api.getAccessTokenVerb()) {
    case POST:
        request.addBodyParameter(OAuthConstants.CLIENT_ID, config.getApiKey());
        request.addBodyParameter(OAuthConstants.CLIENT_SECRET, config.getApiSecret());
        request.addBodyParameter(OAuthConstants.CODE, verifier.getValue());
        request.addBodyParameter(OAuthConstants.REDIRECT_URI, config.getCallback());
        request.addBodyParameter(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE);
        break;
    case GET:
    default:
        request.addQuerystringParameter(OAuthConstants.CLIENT_ID, config.getApiKey());
        request.addQuerystringParameter(OAuthConstants.CLIENT_SECRET, config.getApiSecret());
        request.addQuerystringParameter(OAuthConstants.CODE, verifier.getValue());
        request.addQuerystringParameter(OAuthConstants.REDIRECT_URI, config.getCallback());
        if(config.hasScope()) request.addQuerystringParameter(OAuthConstants.SCOPE, config.getScope());
    }
    Response response = request.send();
    return api.getAccessTokenExtractor().extract(response.getBody());
}
 
Example #12
Source File: RequestBuilderTest.java    From jumblr with Apache License 2.0 5 votes vote down vote up
@Test
public void testXauthForbidden() {
    Response r = mock(Response.class);
    when(r.getCode()).thenReturn(403);
    when(r.getBody()).thenReturn("");

    thrown.expect(JumblrException.class);
    rb.clearXAuth(r);
}
 
Example #13
Source File: RequestBuilderTest.java    From jumblr with Apache License 2.0 5 votes vote down vote up
@Test
public void testXauthSuccess() {
    Response r = mock(Response.class);
    when(r.getCode()).thenReturn(200);
    when(r.getBody()).thenReturn("oauth_token=valueForToken&oauth_token_secret=valueForSecret");

    Token token = rb.clearXAuth(r);
    assertEquals(token.getToken(), "valueForToken");
    assertEquals(token.getSecret(), "valueForSecret");
}
 
Example #14
Source File: RequestBuilderTest.java    From jumblr with Apache License 2.0 5 votes vote down vote up
@Test
public void testClearEmptyJson() {
    Response r = mock(Response.class);
    when(r.getCode()).thenReturn(200);
    when(r.getBody()).thenReturn("");

    thrown.expect(JumblrException.class);
    ResponseWrapper got = rb.clear(r);
}
 
Example #15
Source File: RequestBuilderTest.java    From jumblr with Apache License 2.0 5 votes vote down vote up
@Test
public void testXauthSuccessWithExtra() {
    Response r = mock(Response.class);
    when(r.getCode()).thenReturn(201);
    when(r.getBody()).thenReturn("oauth_token=valueForToken&oauth_token_secret=valueForSecret&other=paramisokay");

    Token token = rb.clearXAuth(r);
    assertEquals(token.getToken(), "valueForToken");
    assertEquals(token.getSecret(), "valueForSecret");
}
 
Example #16
Source File: RequestBuilderTest.java    From jumblr with Apache License 2.0 5 votes vote down vote up
@Test
public void testXauthBadResponseGoodCode() {
    Response r = mock(Response.class);
    when(r.getCode()).thenReturn(200);
    when(r.getBody()).thenReturn("");

    thrown.expect(JumblrException.class);
    rb.clearXAuth(r);
}
 
Example #17
Source File: RequestBuilder.java    From jumblr with Apache License 2.0 5 votes vote down vote up
Token clearXAuth(Response response) {
    if (response.getCode() == 200 || response.getCode() == 201) {
        return parseXAuthResponse(response);
    } else {
        throw new JumblrException(response);
    }
}
 
Example #18
Source File: ResourceClient.java    From jerseyoauth2 with MIT License 5 votes vote down vote up
public String sendTestRequestSample1(Token accessToken) throws ClientException
{
	OAuthService service = getOAuthService(scopes, null);
	
	OAuthRequest request = new OAuthRequest(Verb.GET,
			"http://localhost:9998/testsuite/rest/sample/1");
	service.signRequest(accessToken, request);
	Response response = request.send();
	if (response.getCode()!=200)
		throwClientException(response);
	return response.getBody();
}
 
Example #19
Source File: ResourceClient.java    From jerseyoauth2 with MIT License 5 votes vote down vote up
public String sendTestRequestSample2(Token accessToken) throws ClientException
{
	OAuthService service = getOAuthService(null, null);
	
	OAuthRequest request = new OAuthRequest(Verb.GET,
			"http://localhost:9998/testsuite/rest/sample2/1");
	service.signRequest(accessToken, request);
	Response response = request.send();
	if (response.getCode()!=200)
		throwClientException(response);
	return response.getBody();
}
 
Example #20
Source File: RequestBuilder.java    From jumblr with Apache License 2.0 5 votes vote down vote up
public String getRedirectUrl(String path) {
    OAuthRequest request = this.constructGet(path, null);
    sign(request);
    boolean presetVal = HttpURLConnection.getFollowRedirects();
    HttpURLConnection.setFollowRedirects(false);
    Response response = request.send();
    HttpURLConnection.setFollowRedirects(presetVal);
    if (response.getCode() == 301 || response.getCode() == 302) {
        return response.getHeader("Location");
    } else {
        throw new JumblrException(response);
    }
}
 
Example #21
Source File: OAuth2ServiceWrapper.java    From jerseyoauth2 with MIT License 5 votes vote down vote up
@Override
public Token refreshToken(OAuth2Token token) {
    OAuthRequest request = new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint());
    request.addQuerystringParameter(OAuthConstants.CLIENT_ID, config.getApiKey());
    request.addQuerystringParameter(OAuthConstants.CLIENT_SECRET, config.getApiSecret());
    request.addQuerystringParameter(OAuthConstants.REDIRECT_URI, config.getCallback());
    request.addQuerystringParameter("refresh_token", token.getRefreshToken());
    if(config.hasScope()) 
    	request.addQuerystringParameter(OAuthConstants.SCOPE, config.getScope());
    Response response = request.send();
    return api.getAccessTokenExtractor().extract(response.getBody());
}
 
Example #22
Source File: ScribeJavaSampleActivity.java    From android-opensource-library-56 with Apache License 2.0 5 votes vote down vote up
private void tweet() {
    final Button button = (Button) findViewById(R.id.tweet_button);
    button.setEnabled(false);
    new Thread() {
        public void run() {
            OAuthRequest request = new OAuthRequest(Verb.POST,
                    "https://api.twitter.com/1.1/statuses/update.json");
            request.addBodyParameter("status", "hello scribe java!");
            mService.signRequest(mAccessToken, request);
            final Response response = request.send();
            final int status = response.getCode();
            final String body = response.getBody();
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    if (status == 200) {
                        Toast.makeText(This(), "tweet success!",
                                Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(This(), "tweet failed!:" + body,
                                Toast.LENGTH_SHORT).show();
                    }
                    button.setEnabled(true);
                }
            });
        };
    }.start();
}
 
Example #23
Source File: TestOAuthRequestFactory.java    From open with GNU General Public License v3.0 5 votes vote down vote up
@Override
public OAuthRequest getPermissionsRequest() {
    OAuthRequest mockRequest = Mockito.spy(super.getPermissionsRequest());
    Response responseMock = mock(Response.class);
    doReturn(responseMock).when(mockRequest).send();
    doReturn(true).when(responseMock).isSuccessful();
    return mockRequest;
}
 
Example #24
Source File: TestOAuthRequestFactory.java    From open with GNU General Public License v3.0 5 votes vote down vote up
@Override
public OAuthRequest getOAuthRequest() {
    OAuthRequest mockRequest = Mockito.spy(super.getOAuthRequest());
    Response responseMock = mock(Response.class);
    doReturn(responseMock).when(mockRequest).send();
    doReturn(true).when(responseMock).isSuccessful();
    return mockRequest;
}
 
Example #25
Source File: DataUploadService.java    From open with GNU General Public License v3.0 5 votes vote down vote up
public String getPermissionResponse() {
    try {
        OAuthRequest request = requestFactory.getPermissionsRequest();
        app.getOsmOauthService().signRequest(app.getAccessToken(), request);
        Response response = request.send();
        return response.getBody();
    } catch (Exception e) {
        Logger.d("Unable to get permissions");
    }
    return null;
}
 
Example #26
Source File: XeroClient.java    From xero-java-client with Apache License 2.0 5 votes vote down vote up
protected com.connectifier.xeroclient.models.Response post(String endPoint, JAXBElement<?> object) {
  OAuthRequest request = new OAuthRequest(Verb.POST, BASE_URL + endPoint);
  String contents = marshallRequest(object);
  request.setCharset("UTF-8");
  request.addBodyParameter("xml", contents);
  service.signRequest(token, request);
  Response response = request.send();
  if (response.getCode() != 200) {
    throw newApiException(response);
  }
  return unmarshallResponse(response.getBody(), com.connectifier.xeroclient.models.Response.class);
}
 
Example #27
Source File: XeroClient.java    From xero-java-client with Apache License 2.0 5 votes vote down vote up
protected com.connectifier.xeroclient.models.Response put(String endPoint, JAXBElement<?> object) {
  OAuthRequest request = new OAuthRequest(Verb.PUT, BASE_URL + endPoint);
  String contents = marshallRequest(object);
  request.setCharset("UTF-8");
  request.addBodyParameter("xml", contents);
  service.signRequest(token, request);
  Response response = request.send();
  if (response.getCode() != 200) {
    throw newApiException(response);
  }
  return unmarshallResponse(response.getBody(), com.connectifier.xeroclient.models.Response.class);
}
 
Example #28
Source File: MainActivity.java    From FitbitAndroidSample with Apache License 2.0 5 votes vote down vote up
public void btnRetrieveData(View view) {
	EditText etPIN = (EditText) findViewById(R.id.etPIN);
	String gotPIN = etPIN.getText().toString();

	final Verifier v = new Verifier(gotPIN);

	// network operation shouldn't run on main thread
	new Thread(new Runnable() {
		public void run() {
			Token accessToken = service.getAccessToken(requestToken, v);

			OAuthRequest request = new OAuthRequest(Verb.GET,
					"http://api.fitbit.com/1/user/-/profile.json");
			service.signRequest(accessToken, request); // the access token from step
														// 4
			final Response response = request.send();
			final TextView tvOutput = (TextView) findViewById(R.id.tvOutput);

			// Visual output should run on main thread again...
			tvOutput.post(new Runnable() {
				@Override
				public void run() {
					tvOutput.setText(response.getBody());
				}
			});
		}
	}).start();
}
 
Example #29
Source File: HubicOAuth20ServiceImpl.java    From swift-explorer with Apache License 2.0 5 votes vote down vote up
@Override
public Token getAccessToken(Token requestToken, Verifier verifier) {

	OAuthRequest request = new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint());
	
	String authenticationCode = config.getApiKey() + ":" + config.getApiSecret() ;
	byte[] bytesEncodedAuthenticationCode = Base64.encodeBase64(authenticationCode.getBytes()); 
	request.addHeader ("Authorization", "Basic " + bytesEncodedAuthenticationCode) ;
	
	String charset = "UTF-8";
	
	request.setCharset(charset);
	request.setFollowRedirects(false);
	
	try
	{
		request.addBodyParameter(OAuthConstants.CODE, URLEncoder.encode(verifier.getValue(), charset));
		request.addBodyParameter(OAuthConstants.REDIRECT_URI, URLEncoder.encode(config.getCallback(), charset));
		request.addBodyParameter("grant_type", "authorization_code");
		request.addBodyParameter(OAuthConstants.CLIENT_ID, URLEncoder.encode(config.getApiKey(), charset));
		request.addBodyParameter(OAuthConstants.CLIENT_SECRET, URLEncoder.encode(config.getApiSecret(), charset));
	} 
	catch (UnsupportedEncodingException e) 
	{
		logger.error("Error occurred while getting the access token", e);
	}
	
	Response response = request.send();
	return api.getAccessTokenExtractor().extract(response.getBody());
}
 
Example #30
Source File: WeiXinOAuth20ServiceImpl.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
/**
 * 获取account_token的http请求参数添加
 */
@Override
public Token getAccessToken(final Token requestToken, final Verifier verifier) {
    final OAuthRequest request = new ProxyOAuthRequest(this.api.getAccessTokenVerb(),
            this.api.getAccessTokenEndpoint(), this.connectTimeout,
            this.readTimeout, this.proxyHost, this.proxyPort);
    request.addBodyParameter("appid", this.config.getApiKey());
    request.addBodyParameter("secret", this.config.getApiSecret());
    request.addBodyParameter(OAuthConstants.CODE, verifier.getValue());
    request.addBodyParameter(OAuthConstants.REDIRECT_URI, this.config.getCallback());
    request.addBodyParameter("grant_type", "authorization_code");
    final Response response = request.send();
    return this.api.getAccessTokenExtractor().extract(response.getBody());
}