Jan 20, 2014

Twitter OAuth API Integration

 you can download jar from www.twitter4j.org and then follow bellow Steps
1. first register your application in twitter.com, there you will get consumerKey and consumerSecret
2. then include the above jar in your classpath,
3. write the following servlet to get authenticate by the user.


package com.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;


@WebServlet("/twitter")
public class TwitterLogin  extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
     
        try {
            String CALLBACKURL = "http://localhost:8080/connect/twitter";
            HttpSession session = req.getSession(true);
            if(req.getParameter("oauth_verifier")== null){
                Twitter twitter = new TwitterFactory().getInstance();
                twitter.setOAuthConsumer("ConsumerKey", "ConsumerSecret");
                RequestToken requestToken = twitter.getOAuthRequestToken(CALLBACKURL);
               // String authUrl = requestToken.getAuthorizationURL();        
                session.setAttribute("twitter", twitter);
                session.setAttribute("requestToken", requestToken);
                resp.sendRedirect(requestToken.getAuthorizationURL());
                return;
            }else{
                AccessToken accessToken = null;
                Twitter twitter = (Twitter)session.getAttribute("twitter");
                RequestToken requestToken = (RequestToken)session.getAttribute("requestToken");
                accessToken = twitter.getOAuthAccessToken(requestToken, req.getParameter("oauth_verifier"));
                System.out.println("Got request token.");
                System.out.println("accessToken : " + accessToken.getToken());
                System.out.println("accessToken  secret: " + accessToken.getTokenSecret());
                System.out.println("screenname:" + accessToken.getScreenName());
            }           
        } catch (TwitterException te) {
            te.printStackTrace();         
        } catch (IOException ioe) {
            ioe.printStackTrace();         
        }   
    }
       
}

Jan 18, 2014

Linkedin OAuth API Integration In Java with Example

you can download linked4j.jar file from http://code.google.com/p/linkedin-j/ and then follow bellow code:
steps:
1. first register your application in linkedin.com, there you will get consumerKey and consumerSecret
2. then include the above jar in your classpath,
3. write the following servlet to get authenticate by the user.

import java.io.IOException;
import java.util.EnumSet;

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

import com.cs.liveebiz.server.common.ui.ImportLinkedInProfile;
import com.cs.liveebiz.server.common.util.UserContextHolder;
import com.google.code.linkedinapi.client.LinkedInApiClient;
import com.google.code.linkedinapi.client.LinkedInApiClientFactory;
import com.google.code.linkedinapi.client.enumeration.ProfileField;
import com.google.code.linkedinapi.client.oauth.LinkedInAccessToken;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthService;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthServiceFactory;
import com.google.code.linkedinapi.client.oauth.LinkedInRequestToken;
import com.google.code.linkedinapi.schema.Education;
import com.google.code.linkedinapi.schema.Person;
import com.google.code.linkedinapi.schema.Position;

@SuppressWarnings("serial")
public class LogonServlet extends HttpServlet {
private static final String AUTH_TOKEN_PARAMETER = "oauth_token";
private static final String AUTH_TOKEN_VERIFIER_PARAMETER = "oauth_verifier";
/**
* Consumer Key you can get this from linked in by adding your application at (https://www.linkedin.com/secure/developer)
*/
private static final String CONSUMER_KEY_OPTION = "consumerKey";

/**
* Consumer Secret you can get this from linked in by adding your application
*/
private static final String CONSUMER_SECRET_OPTION = "consumerSecret";

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
         String oauthToken = req.getParameter(AUTH_TOKEN_PARAMETER);
         String oauthVerifier = req.getParameter(AUTH_TOKEN_VERIFIER_PARAMETER);
         final String consumerKeyValue = CONSUMER_KEY_OPTION;
         final String consumerSecretValue = CONSUMER_SECRET_OPTION;
         HttpSession session = req.getSession();

         final LinkedInOAuthService oauthService = LinkedInOAuthServiceFactory.getInstance().createLinkedInOAuthService(consumerKeyValue, consumerSecretValue);
         if (oauthToken == null && oauthVerifier == null ) {
         LinkedInRequestToken requestToken = oauthService.getOAuthRequestToken("same servlet reqpath");
         System.out.println("Fetching request token from LinkedIn..."
+ requestToken);
         session.setAttribute("requestToken", requestToken);
         String authUrl = requestToken.getAuthorizationUrl();
         resp.sendRedirect(authUrl);
} else {
         String sVerifier = req.getParameter("oauth_verifier");
         LinkedInRequestToken requestToken = (LinkedInRequestToken)                          
         session.getAttribute("requestToken");
         LinkedInAccessToken accessToken = oauthService.getOAuthAccessToken(requestToken,sVerifier);
         System.out.println("Access token: " + accessToken.getToken());
         System.out.println("Token secret: " + accessToken.getTokenSecret());
         final LinkedInApiClientFactory factory = LinkedInApiClientFactory.newInstance(consumerKeyValue,                   consumerSecretValue);
         final LinkedInApiClient client = factory.createLinkedInApiClient(accessToken);
         System.out.println("Fetching profile for current user.");
         Person profile = client.getProfileForCurrentUser(EnumSet.of(ProfileField.ID));
         Person profile2 = client.getProfileById(profile.getId());
         printResult(profile2);
         resp.sendRedirect("page to which you want to redirect after processing the result");
  }
} catch (Throwable ex) {
      ex.printStackTrace();
}
}
}
}

What is the use of the finally block?


Finally is the block of code that executes always. The code in finally block will execute even if an exception is occurred. 

finally will not execute when the user calls System.exit().
Example:

try{

       statements1;

}catch(Exception e){

      statements2;

}finally{       

  //    statements3; code will execute weather exception is occurred or not.

}