Package org.scribe.model

Examples of org.scribe.model.OAuthRequest


     * @param since
     */
    private void getFitnessActivityFeed(final UpdateInfo updateInfo, final OAuthService service,
                                        final Token token, String activityFeedURL, final int pageSize,
                                        List<String> activities, long since) throws UpdateFailedException, AuthRevokedException {
        OAuthRequest request = new OAuthRequest(Verb.GET, activityFeedURL);
        request.addQuerystringParameter("pageSize", String.valueOf(pageSize));
        request.addQuerystringParameter("oauth_token", token.getToken());
        request.addHeader("Accept", "application/vnd.com.runkeeper.FitnessActivityFeed+json");
        final DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'").withZone(DateTimeZone.forID("GMT"));
        if (since>0) {
            final String sinceFormatted = dateFormatter.print(since);
            // add one day of padding to account for unknown timezone
            final String noEarlierFormatted = TimeUtils.dateFormatterUTC.print(since-DateTimeConstants.MILLIS_PER_DAY);
            request.addHeader("If-Modified-Since", sinceFormatted);
            request.addQuerystringParameter("noEarlierThan", noEarlierFormatted);
        }
        service.signRequest(token, request);
        long then = System.currentTimeMillis();
        Response response = request.send();
        final int httpResponseCode = response.getCode();
        String body = response.getBody();
        if (httpResponseCode ==200) {
            JSONObject jsonObject = JSONObject.fromObject(body);
            final JSONArray items = jsonObject.getJSONArray("items");
View Full Code Here


    private void fetchAndProcessJSON(final UpdateInfo updateInfo, final String url,
                                     final Map<String,String> parameters, ApiVersion apiVersion) throws Exception {
        long then = System.currentTimeMillis();
        int httpResponseCode = 0;
        try {
            OAuthRequest request = new OAuthRequest(Verb.GET, url);
            for (String parameterName : parameters.keySet()) {
                request.addQuerystringParameter(parameterName,
                                                parameters.get(parameterName));
            }
            OAuthService service = getOAuthService(updateInfo.apiKey);
            final String accessToken = guestService.getApiKeyAttribute(updateInfo.apiKey, "accessToken");
            final Token token = new Token(accessToken, guestService.getApiKeyAttribute(updateInfo.apiKey, "tokenSecret"));
            service.signRequest(token, request);
            Response response = request.send();
            httpResponseCode = response.getCode();
            if (httpResponseCode!=200)
                throw new UpdateFailedException("Unexpected response code: " + httpResponseCode);
            String json = response.getBody();
            JSONObject jsonObject = JSONObject.fromObject(json);
View Full Code Here

    if (accessToken == null) {
      refreshAccessToken();
    }

    for (int i = 0; i < 2; i++) {
      OAuthRequest request = new OAuthRequest(method, getApiUrl(url));

      if (queryString != null && queryString.size() > 0) {
        for (String key : queryString.keySet()) {
          request.addQuerystringParameter(key, queryString.get(key));
        }
      }

      if (_log.isDebugEnabled()) {
        _log.debug(method + " " + request.getCompleteUrl());
      }

      if (postBody != null) {
        // System.err.println("Adding data: " + data);
        request.addPayload(postBody);
        request.addHeader("Content-Type", "application/json;charset=utf-8");
      }

      service.signRequest(accessToken, request);
      request.setConnectionKeepAlive(true);
      request.setConnectTimeout(10, TimeUnit.SECONDS);
      request.setReadTimeout(30, TimeUnit.SECONDS);
      request.setCharset("UTF-8");
      Response response = null;

      try {
        response = request.send();
      } catch (OAuthConnectionException e) {
        throw e;
      }

      String responseBody = response.getBody();
      if (response.isSuccessful()) {
        return responseBody + "\n";
      } else {
        if (response.getCode() == 401) {
          _log.warn("Response error: " + response.getCode());
          System.err.println(responseBody);
          if (i == 0) {
            refreshAccessToken();
          } else {
            throw new OAuthAuthenticationException("Unauthorized");
          }
        } else {
          _log.error(method + " " + request.getCompleteUrl());
          _log.error(postBody);
          _log.error("HTTP response code: " + response.getCode());
          _log.error("Response: " + responseBody);
          if (responseBody.contains("Deadlock found when trying to get lock; try restarting transaction")
              || responseBody.contains("nested exception is org.hibernate.exception.LockAcquisitionException: could not execute statement")) {
View Full Code Here

   * mysecret&refresh_token=19698a4a-960a-4d24-a8cc-44d4b71df47b
   *
   * @throws OAuthAuthenticationException
   */
  public Token getAccessToken(String apiKey, String apiSecret, Token refreshToken) {
    OAuthRequest request = new OAuthRequest(getAccessTokenVerb(), this.refreshTokenEndpoint);
    request.addQuerystringParameter(OAuthConstants.CLIENT_ID, apiKey);
    request.addQuerystringParameter(OAuthConstants.CLIENT_SECRET, apiSecret);
    request.addQuerystringParameter("grant_type", "refresh_token");
    request.addQuerystringParameter("refresh_token", refreshToken.getToken());
    Response response = request.send();
    return getAccessTokenExtractor().extract(response.getBody());
  }
View Full Code Here

            token = new Token(oAuthToken, oAuthSecret);
        } else {
            token = new Token(oAuthToken, "");
        }

        OAuthRequest request = new OAuthRequest(Verb.valueOf(method.toUpperCase()), url);

        if (data != null) {
            request.addPayload(data);
        }

        if (requestHeaders == null) {
            requestHeaders = new ArrayList<>();
        }

        for (Header header : requestHeaders) {
            request.addHeader(header.getName(), header.getValue());
        }

        if (mediaType != null) {
            request.addHeader("Content-Type", mediaType);
        }

        oAuthService.signRequest(token, request);

        Response response = request.send();

        if (response.getCode() == 401 || response.getCode() == 403) {
            throw new InvalidCredentialsException("The OAuth Token is invalid, or has been revoked");
        } else if (response.getCode() != 200) {
            throw new IOException("Unexpected status code of " + response.getCode() + ": " + response.getBody() +
View Full Code Here

    String kmfAuthToken = props.getAuthToken();

    String url = props.getKeystoneHost() + ':' + props.getKeystonePort()
        + props.getKeystonePath() + accessToken;

    OAuthRequest oauthReq = new OAuthRequest(Verb.GET, url);
    oauthReq.addHeader(X_AUTH_HEADER, kmfAuthToken);

    return oauthReq.send();
  }
View Full Code Here

        System.out.println();
        System.out.println("********A basic user profile call********");
        //The ~ means yourself - so this should return the basic default information for your profile in XML format
        //https://developer.linkedin.com/documents/profile-api
        String url = "http://api.linkedin.com/v1/people/~";
        OAuthRequest request = new OAuthRequest(Verb.GET, url);
        service.signRequest(accessToken, request);
        Response response = request.send();
        System.out.println(response.getBody());
        System.out.println();System.out.println();

        System.out.println("********Get the profile in JSON********");
        //This basic call profile in JSON format
        //You can read more about JSON here http://json.org
        url = "http://api.linkedin.com/v1/people/~";
        request = new OAuthRequest(Verb.GET, url);
        request.addHeader("x-li-format", "json");
        service.signRequest(accessToken, request);
        response = request.send();
        System.out.println(response.getBody());
        System.out.println();System.out.println();

        System.out.println("********Get the profile in JSON using query parameter********");
        //This basic call profile in JSON format. Please note the call above is the preferred method.
        //You can read more about JSON here http://json.org
        url = "http://api.linkedin.com/v1/people/~";
        request = new OAuthRequest(Verb.GET, url);
        request.addQuerystringParameter("format", "json");
        service.signRequest(accessToken, request);
        response = request.send();
        System.out.println(response.getBody());
        System.out.println();System.out.println();


        System.out.println("********Get my connections - going into a resource********");
        //This basic call gets all your connections each one will be in a person tag with some profile information
        //https://developer.linkedin.com/documents/connections-api
        url = "http://api.linkedin.com/v1/people/~/connections";
        request = new OAuthRequest(Verb.GET, url);
        service.signRequest(accessToken, request);
        response = request.send();
        System.out.println(response.getBody());
        System.out.println();System.out.println();


        System.out.println("********Get only 10 connections - using parameters********");
        //This basic call gets only 10 connections  - each one will be in a person tag with some profile information
        //https://developer.linkedin.com/documents/connections-api
        //more basic about query strings in a URL here http://en.wikipedia.org/wiki/Query_string
        url = "http://api.linkedin.com/v1/people/~/connections";
        request = new OAuthRequest(Verb.GET, url);
        request.addQuerystringParameter("count", "10");
        service.signRequest(accessToken, request);
        response = request.send();
        System.out.println(response.getBody());
        System.out.println();System.out.println();


        System.out.println("********GET network updates that are CONN and SHAR********");
        //This basic call get connection updates from your connections
        //https://developer.linkedin.com/documents/get-network-updates-and-statistics-api
        //specifics on updates  https://developer.linkedin.com/documents/network-update-types

        url = "http://api.linkedin.com/v1/people/~/network/updates";
        request = new OAuthRequest(Verb.GET, url);
        request.addQuerystringParameter("type","SHAR");
        request.addQuerystringParameter("type","CONN");
        service.signRequest(accessToken, request);
        response = request.send();
        System.out.println(response.getBody());
        System.out.println();System.out.println();


        System.out.println("********People Search using facets and Encoding input parameters i.e. UTF8********");
        //This basic call get connection updates from your connections
        //https://developer.linkedin.com/documents/people-search-api#Facets
        //Why doesn't this look like
        //people-search?title=developer&location=fr&industry=4

        //url = "http://api.linkedin.com/v1/people-search?title=D%C3%A9veloppeur&facets=location,industry&facet=location,fr,0";
       url = "http://api.linkedin.com/v1/people-search:(people:(first-name,last-name,headline),facets:(code,buckets))";
        request = new OAuthRequest(Verb.GET, url);
        request.addQuerystringParameter("title", "Développeur");
        request.addQuerystringParameter("facet", "industry,4");
        request.addQuerystringParameter("facets", "location,industry");
        System.out.println(request.getUrl());
        service.signRequest(accessToken, request);
        response = request.send();
        System.out.println(response.getBody());
        System.out.println();System.out.println();

        /////////////////field selectors
        System.out.println("********A basic user profile call with field selectors********");
        //The ~ means yourself - so this should return the basic default information for your profile in XML format
        //https://developer.linkedin.com/documents/field-selectors
        url = "http://api.linkedin.com/v1/people/~:(first-name,last-name,positions)";
        request = new OAuthRequest(Verb.GET, url);
        service.signRequest(accessToken, request);
        response = request.send();
        System.out.println(response.getHeaders().toString());
        System.out.println(response.getBody());
        System.out.println();System.out.println();


        System.out.println("********A basic user profile call with field selectors going into a subresource********");
        //The ~ means yourself - so this should return the basic default information for your profile in XML format
        //https://developer.linkedin.com/documents/field-selectors
        url = "http://api.linkedin.com/v1/people/~:(first-name,last-name,positions:(company:(name)))";
        request = new OAuthRequest(Verb.GET, url);
        service.signRequest(accessToken, request);
        response = request.send();
        System.out.println(response.getHeaders().toString());
        System.out.println(response.getBody());
        System.out.println();System.out.println();


        System.out.println("********A basic user profile call into a subresource return data in JSON********");
        //The ~ means yourself - so this should return the basic default information for your profile
        //https://developer.linkedin.com/documents/field-selectors
        url = "https://api.linkedin.com/v1/people/~/connections:(first-name,last-name,headline)?format=json";
        request = new OAuthRequest(Verb.GET, url);
        service.signRequest(accessToken, request);
        response = request.send();
        System.out.println(response.getHeaders().toString());
        System.out.println(response.getBody());
        System.out.println();System.out.println();

        System.out.println("********A more complicated example using postings into groups********");
        //https://developer.linkedin.com/documents/field-selectors
        //https://developer.linkedin.com/documents/groups-api
        url = "http://api.linkedin.com/v1/groups/3297124/posts:(id,category,creator:(id,first-name,last-name),title,summary,creation-timestamp,site-group-post-url,comments,likes)";
        request = new OAuthRequest(Verb.GET, url);
        service.signRequest(accessToken, request);
        response = request.send();
        System.out.println(response.getHeaders().toString());
        System.out.println(response.getBody());
        System.out.println();System.out.println();



        /**************************
         *
         * Wrting to the LinkedIn API
         *
         **************************/


/*
* Commented out so we don't write into your LinkedIn/Twitter feed while you are just testing out
* some code. Uncomment if you'd like to see writes in action.
*
*
        System.out.println("********Write to the  share - using XML********");
        //This basic shares some basic information on the users activity stream
        //https://developer.linkedin.com/documents/share-api
        url = "http://api.linkedin.com/v1/people/~/shares";
        request = new OAuthRequest(Verb.POST, url);
        request.addHeader("Content-Type", "text/xml");
        //Make an XML document
        Document doc = DocumentHelper.createDocument();
        Element share = doc.addElement("share");
        share.addElement("comment").addText("Guess who is testing the LinkedIn REST APIs");
        Element content = share.addElement("content");
        content.addElement("title").addText("A title for your share");
        content.addElement("submitted-url").addText("http://developer.linkedin.com");
        share.addElement("visibility").addElement("code").addText("anyone");
        request.addPayload(doc.asXML());
        service.signRequest(accessToken, request);
        response = request.send();
        //there is no body just a header
        System.out.println(response.getBody());
        System.out.println(response.getHeaders().toString());
        System.out.println();System.out.println();


        System.out.println("********Write to the  share and to Twitter - using XML********");
        //This basic shares some basic information on the users activity stream
        //https://developer.linkedin.com/documents/share-api
        url = "http://api.linkedin.com/v1/people/~/shares";
        request = new OAuthRequest(Verb.POST, url);
        request.addQuerystringParameter("twitter-post","true");
        request.addHeader("Content-Type", "text/xml");
        //Make an XML document
        doc = DocumentHelper.createDocument();
        share = doc.addElement("share");
        share.addElement("comment").addText("Guess who is testing the LinkedIn REST APIs and sending to twitter");
        content = share.addElement("content");
        content.addElement("title").addText("A title for your share");
        content.addElement("submitted-url").addText("http://developer.linkedin.com");
        share.addElement("visibility").addElement("code").addText("anyone");
        request.addPayload(doc.asXML());
        service.signRequest(accessToken, request);
        response = request.send();
        //there is no body just a header
        System.out.println(response.getBody());
        System.out.println(response.getHeaders().toString());
        System.out.println();System.out.println();





        System.out.println("********Write to the  share and to twitter - using JSON ********");
        //This basic shares some basic information on the users activity stream
        //https://developer.linkedin.com/documents/share-api
        //NOTE - a good troubleshooting step is to validate your JSON on jsonlint.org
        url = "http://api.linkedin.com/v1/people/~/shares";
        request = new OAuthRequest(Verb.POST, url);
        //set the headers to the server knows what we are sending
        request.addHeader("Content-Type", "application/json");
        request.addHeader("x-li-format", "json");
        //make the json payload using json-simple
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        jsonMap.put("comment", "Posting from the API using JSON");
        JSONObject contentObject = new JSONObject();
        contentObject.put("title", "This is a another test post");
        contentObject.put("submitted-url","http://www.linkedin.com");
        contentObject.put("submitted-image-url", "http://press.linkedin.com/sites/all/themes/presslinkedin/images/LinkedIn_WebLogo_LowResExample.jpg");
        jsonMap.put("content", contentObject);
        JSONObject visibilityObject = new JSONObject();
        visibilityObject.put("code", "anyone");
        jsonMap.put("visibility", visibilityObject);
        request.addPayload(JSONValue.toJSONString(jsonMap));
        service.signRequest(accessToken, request);
        response = request.send();
        //again no body - just headers
        System.out.println(response.getBody());
        System.out.println(response.getHeaders().toString());
        System.out.println();System.out.println();
*/

        /**************************
         *
         * Understanding the response, creating logging, request and response headers
         *
         **************************/

        System.out.println();
        System.out.println("********A basic user profile call and response dissected********");
        //This sample is mostly to help you debug and understand some of the scaffolding around the request-response cycle
        //https://developer.linkedin.com/documents/debugging-api-calls
        url = "https://api.linkedin.com/v1/people/~";
        request = new OAuthRequest(Verb.GET, url);
        service.signRequest(accessToken, request);
        response = request.send();
        //get all the headers
        System.out.println("Request headers: " + request.getHeaders().toString());
        System.out.println("Response headers: " + response.getHeaders().toString());
        //url requested
        System.out.println("Original location is: " + request.getHeaders().get("content-location"));
        //Date of response
        System.out.println("The datetime of the response is: " + response.getHeader("Date"));
        //the format of the response
        System.out.println("Format is: " + response.getHeader("x-li-format"));
        //Content-type of the response
        System.out.println("Content type is: " + response.getHeader("Content-Type") + "\n\n");

        //get the HTTP response code - such as 200 or 404
        int responseNumber = response.getCode();

        if(responseNumber >= 199 && responseNumber < 300){
            System.out.println("HOORAY IT WORKED!!");
            System.out.println(response.getBody());
        } else if (responseNumber >= 500 && responseNumber < 600){
            //you could actually raise an exception here in your own code
            System.out.println("Ruh Roh application error of type 500: " + responseNumber);
            System.out.println(response.getBody());
        } else if (responseNumber == 403){
            System.out.println("A 403 was returned which usually means you have reached a throttle limit");
        } else if (responseNumber == 401){
            System.out.println("A 401 was returned which is a Oauth signature error");
            System.out.println(response.getBody());
        } else if (responseNumber == 405){
            System.out.println("A 405 response was received. Usually this means you used the wrong HTTP method (GET when you should POST, etc).");
        }else {
            System.out.println("We got a different response that we should add to the list: " + responseNumber + " and report it in the forums");
            System.out.println(response.getBody());
        }
        System.out.println();System.out.println();


        System.out.println("********A basic error logging function********");
        // Now demonstrate how to make a logging function which provides us the info we need to
        // properly help debug issues. Please use the logged block from here when requesting
        // help in the forums.
        url = "https://api.linkedin.com/v1/people/FOOBARBAZ";
        request = new OAuthRequest(Verb.GET, url);
        service.signRequest(accessToken, request);
        response = request.send();

        responseNumber = response.getCode();

        if(responseNumber < 200 || responseNumber >= 300){
            logDiagnostics(request, response);
View Full Code Here

     * @return info about user's account
     *
     * @see AccountInfo
     */
    public AccountInfo getAccountInfo() {
        OAuthRequest request = new OAuthRequest(Verb.GET, INFO_URL);
        service.signRequest(accessToken, request);
        String content = check(request.send()).getBody();

        return Json.parse(content, AccountInfo.class);
    }
View Full Code Here

     * @see Entry
     * @see DropboxDefaults
     */
    @SuppressWarnings({"PointlessBooleanExpression"})
    public Entry getMetadata(String path, int fileLimit, @Nullable String hash, boolean list) {
        OAuthRequest request = new OAuthRequest(Verb.GET, METADATA_URL + encode(path));

        if (fileLimit != FILE_LIMIT)
            request.addQuerystringParameter("file_limit", Integer.toString(fileLimit));

        if (hash != null) {
            request.addQuerystringParameter("hash", hash);
        }

        if (list != LIST) {
            request.addQuerystringParameter("list", Boolean.toString(list));
        }

        service.signRequest(accessToken, request);
        String content = checkMetadata(request.send()).getBody();

        return Json.parse(content, Entry.class);
    }
View Full Code Here

     * @return metadata of target file
     *
     * @see Entry
     */
    public Entry copy(String from, String to) {
        OAuthRequest request = new OAuthRequest(Verb.GET, FILE_OPS_COPY_URL);
        request.addQuerystringParameter("root", "dropbox");
        request.addQuerystringParameter("from_path", encode(from));
        request.addQuerystringParameter("to_path", encode(to));

        service.signRequest(accessToken, request);
        String content = checkCopy(request.send()).getBody();

        return Json.parse(content, Entry.class);
    }
View Full Code Here

TOP

Related Classes of org.scribe.model.OAuthRequest

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.