The Artima Developer Community
Sponsored Link

Java Buzz Forum
Flickr API using OAuth - 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
Flickr API using OAuth - Jersey and Struts Posted: Dec 31, 2011 8:32 AM
Reply to this message Reply

This post originated from an RSS feed registered with Java Buzz by Cal Holman.
Original Post: Flickr API using OAuth - 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 Flickr site. And an example of using the API to access a photo's information.

First an Action class to use for the OAuth communication and call back - and then a DAO used for OAuth communication and upload

For the struts-config.xml - use this URL for initiating the OAuth process and call back URL on the second step

<action path="/OAuth"
 type="com.holmansite.util.OAuth"
scope="request"
validate="false">
<forward name="success" path="/do/home/home"/>
</action>

Classes


package com.holmansite.util;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.holmansite.controller.HolmanSiteAction;
import com.holmansite.dao.FlickrOAuthDAO;


 public class OAuth extends HolmanSiteAction
 {

     public ActionForward doPerform(ActionMapping       mapping,
                                    ActionForm          form,
                                    HttpServletRequest  request,
                                    HttpServletResponse response) throws Exception
     {
         // Return the session
         HttpSession session = request.getSession();
        
         // Add the DAO object for the OAuth needed
         // Individual security methods are in respective DAO
         FlickrOAuthDAO theDAO = new FlickrOAuthDAO();
        
         String tokenSecret = (String) session.getAttribute("token_secret");
      cat.debug("back from Auth page - toke_secret:" + tokenSecret );
     
         if( tokenSecret == null ) 
         {
          // If no token secret we are in the initial step of three
          //  This method will perform step 1 and step 2
          
          cat.debug("starting step 1 and 2");
          
          tokenSecret = theDAO.getRequestToken();
          session.setAttribute("token_secret", tokenSecret);
         }
         else
         {
          // Third and last step
          
          cat.debug("Starting step 3");
          
          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);
      
          theDAO.performAuthStep(tokenSecret, oauth_token, oauth_verifier);
         }       
        
         // Forward control to the specified success URI
         return (mapping.findForward("success"));
 }

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

 

package com.holmansite.dao;

import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;

import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;

import com.holmansite.model.Picture;
import com.holmansite.model.PictureCategory;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.core.util.MultivaluedMapImpl;
import com.sun.jersey.multipart.FormDataBodyPart;
import com.sun.jersey.multipart.FormDataMultiPart;
import com.sun.jersey.multipart.file.FileDataBodyPart;
import com.sun.jersey.oauth.client.OAuthClientFilter;
import com.sun.jersey.oauth.signature.OAuthParameters;
import com.sun.jersey.oauth.signature.OAuthSecrets;


public class FlickrOAuthDAO
{
    /**
     * Creates a new FlickrDAO object.
     */
    public FlickrOAuthDAO()
    {
 
    }

    public String addPhoto( Picture thePicture,
       InputStream instream) throws JSONException
{

 //Turn the keywords into an array for display
 String         thePhotoKeywords    = thePicture.getKeywords();
 String keywords = "";
 
 // initialize by skipping the first *
 int    pos        = thePhotoKeywords.indexOf("*", 1);
 int    oldpos     = 1;
 String theKeyword = "";
 
 while (pos > -1)    //loop through the keywords - separated by *
 {
  if (oldpos !=1)
  {
   keywords = keywords + ",";
  }
  theKeyword = "\"" + thePhotoKeywords.substring(oldpos, pos) + "\"";
  keywords = keywords + theKeyword;
  
  oldpos = pos + 1;
  pos    = thePhotoKeywords.indexOf("*", pos + 1);
 }
 
 PictureCategory item     = null;
 Iterator<PictureCategory>  theItems = thePicture.getCategory().iterator();
 
 while (theItems.hasNext())
 {
  item = (PictureCategory)theItems.next();
 
  keywords = keywords + "," + item.getName();
 }
 keywords = keywords + "," + thePicture.getLocation();
 
 // Create a Jersey client
 Client client = Client.create();
 
 // Create a resource to be used to make  API calls     
 WebResource resource = client.resource("http://api.flickr.com/services/upload/");
 
 // 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); 
 
    File thePhotoFile = new File("F:/Pictures/for_site/" + thePicture.getFilename());

 FormDataMultiPart form = new FormDataMultiPart();
 FormDataBodyPart formBody = new FileDataBodyPart("photo", thePhotoFile, MediaType.MULTIPART_FORM_DATA_TYPE);
 form.bodyPart(formBody);
 form.field("title", thePicture.getTitle());
 form.field("description", thePicture.getDescription());
 form.field("tags", keywords);
 
 // Flickr wants signature to have the parameters in signature except for photo
 // Jersey will not add form data to signature - so we trick it
 // by adding the same parameters to the reuest parms - so Jersey will
 // calculate the correct signature - but Flickr will ignore
 // the parameters
 MultivaluedMapImpl requestParams = new MultivaluedMapImpl();
    requestParams.add("title", thePicture.getTitle());
    requestParams.add("description", thePicture.getDescription());
    requestParams.add("tags", keywords);
   
    ClientResponse response = resource.queryParams(requestParams)
      .type("multipart/form-data").post(ClientResponse.class, form);


 String responseBody = response.getEntity(String.class);
 
 cat.debug("POST response:\n" + response.toString() + "\n");
 cat.debug("POST body:\n" + responseBody + "\n");
 
    int oauth_token_index_start = responseBody.indexOf("<photoid>") + 9;
    int oauth_token_index_end = responseBody.indexOf("</photoid>");
    String photoId = responseBody.substring(oauth_token_index_start, oauth_token_index_end);
 
 return photoId;
}
 
 public  void getFlickrInfo(String photo) throws JSONException
 {
        // 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);
    
     Date today = new Date();
  SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd");
  String todayParsed = format.format(today);
       
     MultivaluedMap<String, String> requestParams = new MultivaluedMapImpl();
     requestParams.add("format", "json");
     requestParams.add("method", "flickr.stats.getPhotoStats");
     requestParams.add("date", todayParsed);
     requestParams.add("photo_id", photo);

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

     cat.debug("back from flickr:\n" + response.toString() + "\n");
     cat.debug("back from flickr:\n" + responseBody + "\n");
 }

 
 public String  getRequestToken() {
 
         // 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")
                 .callback("http://www.calandva.test/holmansite/do/OAuth");
        
         // 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 response = resource.get(String.class);

      cat.debug("back from request token:" + response );

      // hacked to extract the reuest_token and request_secret from response
      int oauth_token_index_start = 42;
         int oauth_token_index_end = response.indexOf("oauth_token_secret=") - 1;
         String oauth_token = response.substring(oauth_token_index_start, oauth_token_index_end);
 
         int oauth_token_secret_start = response.indexOf("oauth_token_secret=")+ 19;
         String oauth_token_secret = response.substring(oauth_token_secret_start);
        
        
      cat.debug("reuest token:" + oauth_token );
      cat.debug("reuest token secret:" + oauth_token_secret);
 
         // open the browser at the authorization URL to let user authorize
         try {
    Desktop.getDesktop().browse(new URI(URL_AUTHORIZE + "?oauth_token=" + oauth_token + "&perms=write"));
   } catch (IOException e) {
    cat.fatal("Desktop failure");
    e.printStackTrace();
   } catch (URISyntaxException e) {
    cat.fatal("Desktop failure");
    e.printStackTrace();
   }
        
         return oauth_token_secret;
 }
 
 public void performAuthStep(String tokenSecret, String oauth_token, String oauth_verifier)
 {
        // Create a Jersey client
        Client client = Client.create();
 
        // make an API call to request the access token
        WebResource resource = client.resource(URL_ACCESS_TOKEN);
 
      
        // Set the OAuth parameters
        OAuthSecrets secrets = new OAuthSecrets().consumerSecret(CONSUMER_SECRET).tokenSecret(tokenSecret);
        OAuthParameters params = new OAuthParameters().consumerKey(CONSUMER_KEY).
                signatureMethod("HMAC-SHA1").version("1.0");

        // use the request token id and secret to create the request
      
        params.setVerifier(oauth_verifier);
        params.setToken(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
        String response = resource.get(String.class);
       
        // Print out the result
        // Key and secret will be in this message - copy the message and store the keys
        cat.debug("Access Credentials: " + response);
       
        return;
 }

    // base URL for the API calls
 private static String URL_API =   "http://api.flickr.com/services/rest/";

    // authorization URL
 private static String URL_REQUEST_TOKEN =  "http://www.flickr.com/services/oauth/request_token";
 private static String URL_ACCESS_TOKEN =  "http://www.flickr.com/services/oauth/access_token";
 private static String URL_AUTHORIZE =  "http://www.flickr.com/services/oauth/authorize";
 
 
    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>";

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

Read: Flickr API using OAuth - Jersey and Struts

Topic: IntelliJ IDEA 11.0.1 Release Candidate 2 Previous Topic   Next Topic Topic: The Microsoft Ecosystem

Sponsored Links



Google
  Web Artima.com   

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