The Artima Developer Community
Sponsored Link

Java Buzz Forum
Smugmug API 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
Smugmug API using Jersey and Struts Posted: Dec 29, 2011 8:33 PM
Reply to this message Reply

This post originated from an RSS feed registered with Java Buzz by Cal Holman.
Original Post: Smugmug API 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

Three classes are examples on how to go through the OAuth process and obtain the credentials - then how to access Smugmug for data.


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 com.holmansite.model.SmugmugData;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientHandlerException;
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 = "http://api.smugmug.com/services/oauth/authorize.mg";

    // Reuest Token URL first step
    String URL_REQUEST_TOKEN = "http://api.smugmug.com/services/oauth/getRequestToken.mg";
}

/**
 * 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 returned from user authentication step
        String oauth_token = request.getParameter("oauth_token");
     cat.debug("back from Auth page - auth token:" + oauth_token );
 
        // 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 to parameters
        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);
 
        // 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 =  "http://api.smugmug.com/services/oauth/getAccessToken.mg";
   
    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 SmugmugDAO
{
/*
 * Example method using the Smugmug credentials
 */
public SmugmugData getSmugmugInfo(String photoId)
{
 //Deconstruct the key from two parts - stored as a string id_key
 String smugmugId = "";
 String smugmugKey = "";
 
 int dash = photoId.indexOf("_");
 
 smugmugId = photoId.substring(0, dash);
 smugmugKey = photoId.substring(dash + 1);

 // 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);

    // Create parame for URL
    MultivaluedMap<String, String> requestParams = new MultivaluedMapImpl();
    requestParams.add("ImageID", smugmugId);
    requestParams.add("ImageKey", smugmugKey);  
    requestParams.add("method", "smugmug.images.getInfo");
 
    String response =  resource.queryParams(requestParams).get(String.class);

    cat.debug("GET response:\n" + response.toString() + "\n");

    // Extract the date from the Json string - into
    // a java POJO
    SmugmugData smugmugPhotoData = new SmugmugData();
   // code omitted to extract data from Json response
   
    // Now get comments
    requestParams = new MultivaluedMapImpl();
    requestParams.add("ImageID", smugmugId);
    requestParams.add("ImageKey", smugmugKey);  
    requestParams.add("method", "smugmug.images.comments.get");
 
    //Need to refresh nonce explicitly - timestamp will be rolled forward by Jersey but not a new nonce
    params.setNonce();

    response =  resource.queryParams(requestParams).get(String.class);

    cat.debug("GET response:\n" + response.toString() + "\n");

    // Extract the date from the Json string
    // Populate data object with comment info
    // code omited to extract data from Json response
 
 return smugmugPhotoData;
}

 /** 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 API_VERSION = "1.3.0";
 String URL_API = "http://api.smugmug.com/services/api/json/1.3.0/";
}

 

Read: Smugmug API using Jersey and Struts

Topic: A book at breakfast Previous Topic   Next Topic Topic: Try it out

Sponsored Links



Google
  Web Artima.com   

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