The Artima Developer Community
Sponsored Link

Java Buzz Forum
500px API and OAuth using Jersey and Struts

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Cal Holman

Posts: 18
Nickname: holmanc
Registered: Aug, 2003

Cal Holman is Manager for Web Applications at Paymentech
500px API and OAuth using Jersey and Struts Posted: Dec 31, 2011 12:31 AM
Reply to this message Reply

This post originated from an RSS feed registered with Java Buzz by Cal Holman.
Original Post: 500px API and OAuth using Jersey and Struts
Feed Title: Cal Holman's Blog
Feed URL: http://www.calandva.com/holmansite/do/rss/CreateRssFile?type=blog
Feed Description: CalAndVA.com is built on many Java Open Source projects - this is a blog on the site progress
Latest Java Buzz Posts
Latest Java Buzz Posts by Cal Holman
Latest Posts From Cal Holman's Blog

Advertisement

This is an example of the three steps used to establish the authentication for OAuth with the 500px site. And an example of using the API to access a photo's information.

 

package com.holmansite;

import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.ws.rs.core.MultivaluedMap;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.json.JSONException;
import org.json.JSONObject;


import com.holmansite.model.FiveHundredPxData;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.core.util.MultivaluedMapImpl;
import com.sun.jersey.oauth.client.OAuthClientFilter;
import com.sun.jersey.oauth.signature.OAuthParameters;
import com.sun.jersey.oauth.signature.OAuthSecrets;

public class OAuthExample {

 
    /*
     * Used for the OAuth token process
     */

    public void getSecurity(HttpServletRequest request)
    {

        // Create a Jersey client
        Client client = Client.create();

        // Create a resource to be used to make  API calls
        WebResource resource = client.resource(URL_REQUEST_TOKEN);

        // Set the OAuth parameters
        OAuthSecrets secrets = new OAuthSecrets().consumerSecret(CONSUMER_SECRET);
        OAuthParameters params = new OAuthParameters().consumerKey(CONSUMER_KEY).signatureMethod("HMAC-SHA1").version(
                "1.0").timestamp().nonce();

        // Create the OAuth client filter
        OAuthClientFilter filter = new OAuthClientFilter(client.getProviders(), params, secrets);

        // Add the filter to the resource
        resource.addFilter(filter);

        // make the request
        String tokenResponse = resource.get(String.class);
       
        cat.debug("Response - " + tokenResponse);

        int oauth_token_index_start = 12;
        int oauth_token_index_end = tokenResponse.indexOf("oauth_token_secret=") - 1;
        String oauth_token = tokenResponse.substring(oauth_token_index_start, oauth_token_index_end);

        int oauth_token_secret_start = tokenResponse.indexOf("oauth_token_secret=") + 19;
        int oauth_token_secret_end = oauth_token_secret_start + 64;
        String oauth_token_secret = tokenResponse.substring(oauth_token_secret_start, oauth_token_secret_end);


        cat.debug("Request token:" + oauth_token);
        cat.debug("Request token secret:" + oauth_token_secret);
       
        request.getSession().setAttribute("token_secret", oauth_token_secret);

        // open the browser at the authorization URL to let user authorize
        // Call Back URL loaded into Control Panel API Keys in "oauth callback url" field
        // Once user has accepted the terms the user will be forwarded to the "oauth callback url"
        try
        {
            Desktop.getDesktop().browse(new URI(URL_AUTHORIZE + "?oauth_token=" + oauth_token));
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        catch (URISyntaxException e)
        {
            e.printStackTrace();
        }

        return;
    }

    /** Category definition for this class to log to log4j.  */
    protected Logger cat = Logger.getLogger(this.getClass());
   
    String CONSUMER_KEY = "<your API key>";
    String CONSUMER_SECRET = "<your API secret>";

    // URL for Oauth user step - second step
    String URL_AUTHORIZE =  "https://api.500px.com/v1/oauth/authorize";  

    // Reuest Token URL first step
    String URL_REQUEST_TOKEN =  "https://api.500px.com/v1/oauth/request_token";
 
}

/**
 * This Action is to respond to a call back request from user authentication during the OAuth
 * process.
 *
 * @author  Cal Holman
 */
public class OAuthCallBackAction extends Action
{
    /**
     * Action called on call back from user auth step in OAuth process
     */
    public ActionForward doPerform(ActionMapping       mapping,
                                   ActionForm          form,
                                   HttpServletRequest  request,
                                   HttpServletResponse response) throws Exception
    {
        // Return the session
        HttpSession session = request.getSession();
        String tokenSecret = (String) session.getAttribute("token_secret");
     cat.debug("back from Auth page - token secret:" + tokenSecret );

     // Token and Verifier code returned from user authentication step
        String oauth_token = request.getParameter("oauth_token");
        String oauth_verifier = request.getParameter("oauth_verifier");

     cat.debug("back from Auth page - auth token:" + oauth_token );
     cat.debug("back from Auth page - auth verifier:" + oauth_verifier);
        // Create a Jersey client
        Client client = Client.create();
 
        // make an API call to request the access token/secret
        WebResource resource = client.resource(URL_ACCESS_TOKEN);
      
        // Add the token secret to the secrets object
        OAuthSecrets secrets = new OAuthSecrets().consumerSecret(CONSUMER_SECRET).tokenSecret(tokenSecret);
       
        // Set the OAuth parameters - timestamp and nonce are managed by Jersey filter
        // Add the auth token and verifier to parameters
        OAuthParameters params = new OAuthParameters().consumerKey(CONSUMER_KEY).
                signatureMethod("HMAC-SHA1").version("1.0").token(oauth_token).verifier(oauth_verifier);

        // Create the OAuth client filter
        OAuthClientFilter filter =
                new OAuthClientFilter(client.getProviders(), params, secrets);

        // Add the filter to the resource
        resource.addFilter(filter);
 
        // make the request and print out the resulting OAuth Keys
        String oauthAccessKeySecret = resource.get(String.class);
       
        cat.debug(oauthAccessKeySecret);
       
        // Forward control to the specified success URI
        return (mapping.findForward("success"));
    }

    // Access token URL
    String URL_ACCESS_TOKEN =  "https://api.500px.com/v1/oauth/access_token";
   
    String CONSUMER_KEY = "<your API key>";
    String CONSUMER_SECRET = "<your API secret>";


    /** Category definition for this class to log to log4j.  */
    protected Logger cat = Logger.getLogger(this.getClass());

}

public class FiveHundredDAO
{
/*
 * Example method using the credentials
 */
 public  FiveHundredPxData getFiveHundredPxInfo(Integer photo)
 {
        // Create a Jersey client
        Client client = Client.create();
 
        // Create a resource to be used to make  API calls
        WebResource resource = client.resource(URL_API);
 
        // Set the OAuth parameters
        OAuthSecrets secrets = new OAuthSecrets().consumerSecret(CONSUMER_SECRET).tokenSecret(OAUTH_TOKEN_SECRET);
        OAuthParameters params = new OAuthParameters().consumerKey(CONSUMER_KEY).
                signatureMethod("HMAC-SHA1").version("1.0").token(OAUTH_TOKEN);
        // Create the OAuth client filter
        OAuthClientFilter filter =
                new OAuthClientFilter(client.getProviders(), params, secrets);
        // Add the filter to the resource
        resource.addFilter(filter);
       
        ClientResponse response =  resource.path("photos/" + photo).get(ClientResponse.class);
 
     String responseBody = response.getEntity(String.class);

     cat.debug("back from 500px:\n" + responseBody + "\n");
    
 
   
     FiveHundredPxData theFiveHundredPxData = new FiveHundredPxData();
     // Extract the date from the Json string
     // Code not present for extracting data

     return theFiveHundredPxData;
   
   }


 /** Category definition for this class to log to log4j.  */
 protected Logger cat = Logger.getLogger(this.getClass());
 
 String CONSUMER_KEY = "<your API key>";
 String CONSUMER_SECRET = "<your API secret>";
 
 String OAUTH_TOKEN = "<your oauth token>";
 String OAUTH_TOKEN_SECRET = "<your oauth secret>";
 
 // base URL for the API calls
 String URL_API =   "https://api.500px.com/v1/";
   
}

 

Read: 500px API and OAuth using Jersey and Struts

Topic: The Microsoft Ecosystem Previous Topic   Next Topic Topic: Performance Reviews: A Guide for the Borderline Clinically Depressed

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use