Wednesday, June 30, 2010
linkedin profile api
Sample Program
website get linkedin profile using java
You get the jar file signpost-core-1.1-SNAPSHOT.jar then save inside WEB-INF/lib
First create the website profile to LinkedIn.com
click the link --->https://www.linkedin.com/secure/developer
You get API key and security key
You put the key below the program 1
package test;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.security.SignatureException;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import com.lowagie.text.pdf.codec.Base64;
public class Oauthprofile {
public static void main(String[] args) throws GeneralSecurityException, HttpException, IOException {
String baseUrl = "http://api.linkedin.com/v1/people/~";
String Consumer_key = "API Key";
//add one "&" after the access_token_secret;
String token_secret = "Security Key";// add your consumer secret(application secret) and access token secret
String token = "lookforshan@gmail.com";
long time = System.currentTimeMillis() / 1000;
String oauth_nonce = Md5(Long.toString(time));
String oauth_timestamp = Long.toString(time);
String base = "GET&" + URLEncoder.encode(baseUrl).replace("%7E", "~")+ "&";
String ParamerterString = "";
ParamerterString += "oauth_consumer_key="+Consumer_key+"&";
ParamerterString += "oauth_nonce="+oauth_nonce+"&";
ParamerterString += "oauth_signature_method=HMAC-SHA1&";
ParamerterString += "oauth_timestamp="+oauth_timestamp+"&";
ParamerterString += "oauth_token="+"lookforshan@gmail.com"+"&";
ParamerterString += "oauth_version=1.0";
base = base+ URLEncoder.encode(ParamerterString).replace("%7E", "~");
String signature = URLEncoder.encode(computeSignature(base,token_secret));
ParamerterString += "&oauth_signature="+signature;
String[] parameters = ParamerterString.split("&");
StringBuilder sb = new StringBuilder("OAuth realm=\"http://api.linkedin.com/\",");
for (int i = 0; i < authorization =" new" client =" new" getmethod =" new" hh =" getMethod.getRequestHeaders();" secretkey =" null;" keybytes =" keyString.getBytes();" secretkey =" new" mac =" Mac.getInstance(" text =" baseString.getBytes();" defaultbytes =" pass.getBytes();" algorithm =" MessageDigest.getInstance(" hexstring =" new" i="0;i"> 0 && isAuthenticationComplete();
}
public boolean isAuthenticationComplete() {
Object completeFlag = httpSession.getAttribute(AUTHENTICATION_COMPLETE_FLAG);
return null != completeFlag && completeFlag instanceof Boolean && ((Boolean) completeFlag).booleanValue();
}
public void setAuthenticationComplete(boolean isComplete) {
httpSession.setAttribute(AUTHENTICATION_COMPLETE_FLAG, new Boolean(isComplete));
}
public String getConsumerKey() {
return underlyingConsumer.getConsumerKey();
}
public String getConsumerSecret() {
return underlyingConsumer.getConsumerSecret();
}
public String getToken() {
return underlyingConsumer.getToken();
}
public String getTokenSecret() {
return underlyingConsumer.getTokenSecret();
}
public void setTokenWithSecret(String token, String secret) {
underlyingConsumer.setTokenWithSecret(token, secret);
// TBD: encrypt secret in the session?
if (token != null && secret != null) {
httpSession.setAttribute(TOKEN_KEY, token);
httpSession.setAttribute(TOKEN_SECRET_KEY, secret);
}
else {
httpSession.removeAttribute(TOKEN_KEY);
httpSession.removeAttribute(TOKEN_SECRET_KEY);
}
}
public HttpRequest sign(HttpRequest request)
throws OAuthMessageSignerException, OAuthExpectationFailedException {
return underlyingConsumer.sign(request);
}
public HttpRequest sign(Object obj) throws OAuthMessageSignerException,
OAuthExpectationFailedException {
return underlyingConsumer.sign(obj);
}
}
third Program 2
--------------------
package test;
import com.google.code.linkedinapi.schema.ApiStandardProfileRequest;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.servlet.RequestDispatcher;
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 resume.bean.Register;
@SuppressWarnings("serial")
public class LinkedInAPIProxyServlet extends HttpServlet {
private String constructLinkedInAPIURL(String baseURL, HttpServletRequest request) {
//
// This constructs a LinkedIN API URL using the base URL and information from the path and request to this servlet
//
// Example:
// If this servlet is deployed to http://localhost:8080/api
// and a request is received at "http://localhost:8080/api/v1/people/~/connections?count=1"
// If this function is called with the baseURL is "http://api.linkedin.com"
// the resulting URL is "http://api.linkedin.com/v1/people/~/connections?count=1"
//
StringBuilder apiURL = new StringBuilder(baseURL);
String pathInfo = request.getPathInfo();
if (pathInfo != null && pathInfo.length() > 0) {
apiURL.append(pathInfo);
}
String queryString = request.getQueryString();
if (queryString != null && queryString.length() > 0) {
apiURL.append("?");
apiURL.append(queryString);
}
return apiURL.toString();
}
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
OAuthSession authSession = LinkedInAuthentication.GetConsumer(req.getSession());
HttpSession session=req.getSession();
Register user=new Register();
user=(Register)session.getAttribute("userbean");
if (!authSession.isAuthenticated()) {
//
// redirect back to logon to re-authenticate, passing all of the parameters.
// These parameters will be passed back in once authentication succeeds.
//
String relativeLogonURL = constructLinkedInAPIURL("/logon", req);
URL reloginPage = new URL(new URL(req.getRequestURL().toString()), relativeLogonURL);
resp.sendRedirect(reloginPage.toString());
return;
}
String apiURL = constructLinkedInAPIURL("http://api.linkedin.com", req);
URL connectionsURL = new URL(apiURL);
HttpURLConnection apiRequest = (HttpURLConnection) connectionsURL.openConnection();
authSession.sign(apiRequest);
apiRequest.connect();
//
// Forward the API response
//
resp.setStatus(apiRequest.getResponseCode());
resp.setContentType(apiRequest.getContentType());
java.io.OutputStream out = resp.getOutputStream();
java.io.InputStream in = apiRequest.getInputStream();
byte[] data = new byte[4048];
int length = 0;
while ((length = in.read(data)) > 0) {
out.write(data, 0, length);
}
// resp.sendRedirect("http://localhost:8080/linkedInProfile.do");
//RequestDispatcher rd=req.getRequestDispatcher("/inde.jsp");
//rd.forward(req, resp);
in.close();
out.close();
}
catch (Throwable ex) {
//resp.setContentType("text/plain");
//ex.printStackTrace(resp.getWriter());
}
}
}
the 3rd program get the linked in profile.
fourth program
----------------
package test;
import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
@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";
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
if (null != req.getParameter("logoff")) {
req.getSession().invalidate();
URL rootURL = new URL(new URL(req.getRequestURL().toString()), "/");
resp.sendRedirect(rootURL.toString());
return;
}
//
// The OAuthConsumer automatically stores the LinkedIn token and secret in the HTTP session
//
OAuthSession consumer = LinkedInAuthentication.GetConsumer(req.getSession());
OAuthProvider provider = LinkedInAuthentication.GetProvider(consumer);
String oauthToken = req.getParameter(AUTH_TOKEN_PARAMETER);
String oauthVerifier = req.getParameter(AUTH_TOKEN_VERIFIER_PARAMETER);
if (oauthToken != null && oauthVerifier != null) {
//
// This is the oauth callback - process the verifier to complete the authentication
//
// This writes the secret and token back to the consumer
//
provider.retrieveAccessToken(oauthVerifier);
consumer.setAuthenticationComplete(true);
StringBuilder relativeURL = new StringBuilder("/api");
String pathInfo = req.getPathInfo();
if (pathInfo != null) {
//
// Pass the requested LinkedIn API parameters to the "api" servlet
// if they were provided as part of logon. See the comments in LinkedInAPIProxyServlet.java
// for how the parameters are used.
//
relativeURL.append(pathInfo);
StringBuilder additionalParameters = new StringBuilder();
Enumeration parameterNames = req.getParameterNames();
boolean isFirstParameter = true;
while (parameterNames.hasMoreElements()) {
String parameterName = (String) parameterNames.nextElement();
if (!parameterName.equals(AUTH_TOKEN_PARAMETER) && !parameterName.equals(AUTH_TOKEN_VERIFIER_PARAMETER)) {
if (!isFirstParameter) {
additionalParameters.append("&");
}
additionalParameters.append(URLEncoder.encode(parameterName, "UTF-8"));
additionalParameters.append("=");
additionalParameters.append(URLEncoder.encode(req.getParameter(parameterName), "UTF-8"));
isFirstParameter = false;
}
}
if (additionalParameters.length() > 0) {
relativeURL.append("?");
relativeURL.append(additionalParameters.toString());
}
}
else {
//
// If no API parameters were requested, default to the current person's profile
//http://www.linkedin.com/connections?trk=hb_tab_cnts
///v1/people/~/connections?count=700
relativeURL.append("/v1/people/~/connections?count=1");
}
URL apiURL = new URL(new URL(req.getRequestURL().toString()), relativeURL.toString());
resp.sendRedirect(apiURL.toString());
}
else {
//
// This is the initial logon.
//
// The callback URL redirects to this servlet once authentication is complete.
//
StringBuffer requestURL = req.getRequestURL();
//
// embed any parameters passed in to logon. These will be used post-logon.
//
String queryString = req.getQueryString();
if (queryString != null && queryString.length() > 0) {
requestURL.append("?");
requestURL.append(queryString);
}
consumer.setAuthenticationComplete(false);
//
// Start the oauth process, redirecting to LinkedIn for authentication.
//
String authUrl = provider.retrieveRequestToken(requestURL.toString());
if(authUrl !=null){
// RequestDispatcher rd=req.getRequestDispatcher("/onlineprofile.jsp");
// rd.forward(req, resp);
}
resp.sendRedirect(authUrl);
}
}
catch (Throwable ex) {
// TODO
//resp.setContentType("text/plain");
//ex.printStackTrace(resp.getWriter());
}
}
}
web.xml
----------
Logon
test.LogonServlet
Logon
/logon/*
Logon
/logon
APIProxy
test.LinkedInAPIProxyServlet
APIProxy
/api/*
you give the url http://localhost:8080/logon
automatically redirect the linked login page . then you give the linkedin userid and password.
finally get the the profile (xml format)
Aspire latest java interview question
2. Difference between java and object?
3. where is store the preparedstatement object?
4. Thead and synchronization
5. exception (throws and try,catch,finally)
6. exception program try{
}catch(Exception e){}
catch(NullPointerException n){}
Is it correct . Explain.
7. exception program try{
}catch(IoException i){}
catch(FileNotFoundException f){}
catch(Exception e){}
Is it correct . Explain.
Accenture latest interview question:
========
1.How will you handle Runtimeexceptions without using try catch.?
2.How will you handle custom validations in struts 3.Struts flow?
4.What are all the sunchronized classes in collections?
5.the replacement for remove Hashtable coding?
6.scalability 7.performance enhancement?
8.jboss issues 9.configuration management techniques 10.Designs?
Adventnet latest interview question:
=========
1.which is efficient and tell the reason,”in” condition query and simple join ?
2.What is the output ?
String str1="aa";
String str2="aa";
if(str1==str2){
System.out.println("inside if");
}
3.Write code for binarySearch?
4.what is the reason the Public static final modifier for variables in interface.?
CMC latest interview question
====
1.When will you use procedure? when will you use functions?
2.We have array , then what is the purpose of ArrayList?
3.purpose of clone method?
4.jsp lifcycle.
5.when client disabled the cookies the how will you maintain session?
6.Database Connection object creation in which layer?
Tech Mahindra latest interview question
==============
1.purpose of div tag
2.dhtml ,dom object how to create tables in dhtml dynamically.
3.
Bahwan Cybertech latest interview question
=================
1.set of classes,all have method with same signature(i.e public int aa();)
how execute the method in all the classes by passing classname to one class method ?
2.if i have one action and call add,delete,update methods from bo's,how to get connection objects,where will you create the con objects?
3.how to create table column to support i18n
ATOS Origin latest interview question
1.What is monitor?
2.What is synchronization
3.Any other way other than callablestatement to call procedure in java program.
4.how to execute procedure in sql command prompt.
5.what is the purpose of generics in arraylist.
6.diff between abstract factory pattern and factory pattern
7.what is transfer object pattern and how will you implement
8. what is materialized view?
9.can you update views?
10.how will you get custom sort?
11.what is the RandomAccess interface.
12.name the two classes implements the RandomAccess Interface?
13.what is DispatchAction
14.how will you develop custom tags
15.how will you validate in struts?
16.Can you change the name of the struts-config.xml file.
17.Can you declare more than on struts-config files?
18.what is LLD&HLD?
19.can you call functions in views?
20.what is cursor?
21.what is referential cursor?
22.what is inner join and outer join?
Thirdware technology sol latest interview question
1.How will you handle server side exceptions in struts?
2.how will to achieve module to module communication in struts?
3.how will you implement SwitchAction?
4.how will you access java class in your scriptlet code?
5.why will you go for jsp:useBean instead of scriplet bean usage?
6.Generic method sample code?
Tcs latest interview question
How will you get part of the records from resultset(i.e rs having 10 records I want 5 records only to fetch)?
String to Integer conversion?
Integer to string conversion?
How will you read as binary from file?
How will you write files?
JSP life cycle?
Diff b/w formbean and value object?
String vs STringBuffer which one is better?
What is synchronous and asynchronous?
Struts flow?
How will you handle exception in struts action class?
Website get LinkedIn profile

You get the jar file signpost-core-1.1-SNAPSHOT.jar then save inside WEB-INF/lib
First create the website profile to LinkedIn.com
click the link --->https://www.linkedin.com/secure/developer
You get API key and security key
package test;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.security.SignatureException;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import com.lowagie.text.pdf.codec.Base64;
public class Oauthprofile {
public static void main(String[] args) throws GeneralSecurityException, HttpException, IOException {
String baseUrl = "http://api.linkedin.com/v1/people/~";
String Consumer_key = "API Key";
//add one "&" after the access_token_secret;
String token_secret = "Security Key";// add your consumer secret(application secret) and access token secret
String token = "lookforshan@gmail.com";
long time = System.currentTimeMillis() / 1000;
String oauth_nonce = Md5(Long.toString(time));
String oauth_timestamp = Long.toString(time);
String base = "GET&" + URLEncoder.encode(baseUrl).replace("%7E", "~")+ "&";
String ParamerterString = "";
ParamerterString += "oauth_consumer_key="+Consumer_key+"&";
ParamerterString += "oauth_nonce="+oauth_nonce+"&";
ParamerterString += "oauth_signature_method=HMAC-SHA1&";
ParamerterString += "oauth_timestamp="+oauth_timestamp+"&";
ParamerterString += "oauth_token="+"lookforshan@gmail.com"+"&";
ParamerterString += "oauth_version=1.0";
base = base+ URLEncoder.encode(ParamerterString).replace("%7E", "~");
String signature = URLEncoder.encode(computeSignature(base,token_secret));
ParamerterString += "&oauth_signature="+signature;
String[] parameters = ParamerterString.split("&");
StringBuilder sb = new StringBuilder("OAuth realm=\"http://api.linkedin.com/\",");
for (int i = 0; i < authorization =" new" client =" new" getmethod =" new" hh =" getMethod.getRequestHeaders();" secretkey =" null;" keybytes =" keyString.getBytes();" secretkey =" new" mac =" Mac.getInstance(" text =" baseString.getBytes();" defaultbytes =" pass.getBytes();" algorithm =" MessageDigest.getInstance(" hexstring =" new" i="0;i
}
public boolean isAuthenticationComplete() {
Object completeFlag = httpSession.getAttribute(AUTHENTICATION_COMPLETE_FLAG);
return null != completeFlag && completeFlag instanceof Boolean && ((Boolean) completeFlag).booleanValue();
}
public void setAuthenticationComplete(boolean isComplete) {
httpSession.setAttribute(AUTHENTICATION_COMPLETE_FLAG, new Boolean(isComplete));
}
public String getConsumerKey() {
return underlyingConsumer.getConsumerKey();
}
public String getConsumerSecret() {
return underlyingConsumer.getConsumerSecret();
}
public String getToken() {
return underlyingConsumer.getToken();
}
public String getTokenSecret() {
return underlyingConsumer.getTokenSecret();
}
public void setTokenWithSecret(String token, String secret) {
underlyingConsumer.setTokenWithSecret(token, secret);
// TBD: encrypt secret in the session?
if (token != null && secret != null) {
httpSession.setAttribute(TOKEN_KEY, token);
httpSession.setAttribute(TOKEN_SECRET_KEY, secret);
}
else {
httpSession.removeAttribute(TOKEN_KEY);
httpSession.removeAttribute(TOKEN_SECRET_KEY);
}
}
public HttpRequest sign(HttpRequest request)
throws OAuthMessageSignerException, OAuthExpectationFailedException {
return underlyingConsumer.sign(request);
}
public HttpRequest sign(Object obj) throws OAuthMessageSignerException,
OAuthExpectationFailedException {
return underlyingConsumer.sign(obj);
}
}
Program 2
--------------------
package test;
import com.google.code.linkedinapi.schema.ApiStandardProfileRequest;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.servlet.RequestDispatcher;
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 resume.bean.Register;
@SuppressWarnings("serial")
public class LinkedInAPIProxyServlet extends HttpServlet {
private String constructLinkedInAPIURL(String baseURL, HttpServletRequest request) {
//
// This constructs a LinkedIN API URL using the base URL and information from the path and request to this servlet
//
// Example:
// If this servlet is deployed to http://localhost:8080/api
// and a request is received at "http://localhost:8080/api/v1/people/~/connections?count=1"
// If this function is called with the baseURL is "http://api.linkedin.com"
// the resulting URL is "http://api.linkedin.com/v1/people/~/connections?count=1"
//
StringBuilder apiURL = new StringBuilder(baseURL);
String pathInfo = request.getPathInfo();
if (pathInfo != null && pathInfo.length() > 0) {
apiURL.append(pathInfo);
}
String queryString = request.getQueryString();
if (queryString != null && queryString.length() > 0) {
apiURL.append("?");
apiURL.append(queryString);
}
return apiURL.toString();
}
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
OAuthSession authSession = LinkedInAuthentication.GetConsumer(req.getSession());
HttpSession session=req.getSession();
Register user=new Register();
user=(Register)session.getAttribute("userbean");
if (!authSession.isAuthenticated()) {
//
// redirect back to logon to re-authenticate, passing all of the parameters.
// These parameters will be passed back in once authentication succeeds.
//
String relativeLogonURL = constructLinkedInAPIURL("/logon", req);
URL reloginPage = new URL(new URL(req.getRequestURL().toString()), relativeLogonURL);
resp.sendRedirect(reloginPage.toString());
return;
}
String apiURL = constructLinkedInAPIURL("http://api.linkedin.com", req);
URL connectionsURL = new URL(apiURL);
HttpURLConnection apiRequest = (HttpURLConnection) connectionsURL.openConnection();
authSession.sign(apiRequest);
apiRequest.connect();
//
// Forward the API response
//
resp.setStatus(apiRequest.getResponseCode());
resp.setContentType(apiRequest.getContentType());
java.io.OutputStream out = resp.getOutputStream();
java.io.InputStream in = apiRequest.getInputStream();
byte[] data = new byte[4048];
int length = 0;
while ((length = in.read(data)) > 0) {
out.write(data, 0, length);
}
// resp.sendRedirect("http://localhost:8080/linkedInProfile.do");
//RequestDispatcher rd=req.getRequestDispatcher("/inde.jsp");
//rd.forward(req, resp);
in.close();
out.close();
}
catch (Throwable ex) {
//resp.setContentType("text/plain");
//ex.printStackTrace(resp.getWriter());
}
}
}
the 3rd program get the linked in profile.
----------------
package test;
import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
@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";
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
if (null != req.getParameter("logoff")) {
req.getSession().invalidate();
URL rootURL = new URL(new URL(req.getRequestURL().toString()), "/");
resp.sendRedirect(rootURL.toString());
return;
}
//
// The OAuthConsumer automatically stores the LinkedIn token and secret in the HTTP session
//
OAuthSession consumer = LinkedInAuthentication.GetConsumer(req.getSession());
OAuthProvider provider = LinkedInAuthentication.GetProvider(consumer);
String oauthToken = req.getParameter(AUTH_TOKEN_PARAMETER);
String oauthVerifier = req.getParameter(AUTH_TOKEN_VERIFIER_PARAMETER);
if (oauthToken != null && oauthVerifier != null) {
//
// This is the oauth callback - process the verifier to complete the authentication
//
// This writes the secret and token back to the consumer
//
provider.retrieveAccessToken(oauthVerifier);
consumer.setAuthenticationComplete(true);
StringBuilder relativeURL = new StringBuilder("/api");
String pathInfo = req.getPathInfo();
if (pathInfo != null) {
//
// Pass the requested LinkedIn API parameters to the "api" servlet
// if they were provided as part of logon. See the comments in LinkedInAPIProxyServlet.java
// for how the parameters are used.
//
relativeURL.append(pathInfo);
StringBuilder additionalParameters = new StringBuilder();
Enumeration parameterNames = req.getParameterNames();
boolean isFirstParameter = true;
while (parameterNames.hasMoreElements()) {
String parameterName = (String) parameterNames.nextElement();
if (!parameterName.equals(AUTH_TOKEN_PARAMETER) && !parameterName.equals(AUTH_TOKEN_VERIFIER_PARAMETER)) {
if (!isFirstParameter) {
additionalParameters.append("&");
}
additionalParameters.append(URLEncoder.encode(parameterName, "UTF-8"));
additionalParameters.append("=");
additionalParameters.append(URLEncoder.encode(req.getParameter(parameterName), "UTF-8"));
isFirstParameter = false;
}
}
if (additionalParameters.length() > 0) {
relativeURL.append("?");
relativeURL.append(additionalParameters.toString());
}
}
else {
//
// If no API parameters were requested, default to the current person's profile
//http://www.linkedin.com/connections?trk=hb_tab_cnts
///v1/people/~/connections?count=700
relativeURL.append("/v1/people/~/connections?count=1");
}
URL apiURL = new URL(new URL(req.getRequestURL().toString()), relativeURL.toString());
resp.sendRedirect(apiURL.toString());
}
else {
//
// This is the initial logon.
//
// The callback URL redirects to this servlet once authentication is complete.
//
StringBuffer requestURL = req.getRequestURL();
//
// embed any parameters passed in to logon. These will be used post-logon.
//
String queryString = req.getQueryString();
if (queryString != null && queryString.length() > 0) {
requestURL.append("?");
requestURL.append(queryString);
}
consumer.setAuthenticationComplete(false);
//
// Start the oauth process, redirecting to LinkedIn for authentication.
//
String authUrl = provider.retrieveRequestToken(requestURL.toString());
if(authUrl !=null){
// RequestDispatcher rd=req.getRequestDispatcher("/onlineprofile.jsp");
// rd.forward(req, resp);
}
resp.sendRedirect(authUrl);
}
}
catch (Throwable ex) {
// TODO
//resp.setContentType("text/plain");
//ex.printStackTrace(resp.getWriter());
}
}
}
web.xml
----------
you give the url http://localhost:8080/logon
automatically redirect the linked login page . then you give the linkedin userid and password.
finally get the the profile (xml format)
Monday, June 28, 2010
java exception
An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error.
2. What is a Java Exception ?
A Java exception is an object that describes an exceptional condition i.e., an error condition that has occurred in a piece of code. When this type of condition arises, an object representing that exception is created and thrown in the method that caused the error by the Java Runtime. That method may choose to handle the exception itself, or pass it on. Either way, at some point, the exception is caught and processed.
3.Where does Exception stand in the Java tree hierarchy ?
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.Error
4.What are checked exceptions ?
Checked exception are those which the Java compiler forces you to catch. e.g. IOException are checked Exceptions.
5.What are runtime exceptions ?
Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time.
6.What is the difference between error and an exception ?
An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.).
7.How to create custom exceptions ?
Your class should extend class Exception, or some more specific type thereof.
8.If I want an object of my class to be thrown as an exception object, what should I do ?
The class should extend from Exception class. Or you can extend your class from some more precise exception type also.
9.If my class already extends from some other class what should I do if I want an instance of my class to be thrown as an exception object ?
One can not do anytihng in this scenarion. Because Java does not allow multiple inheritance and does not provide any exception interface as well.
10.How does an exception permeate through the code ?
An unhandled exception moves up the method stack in search of a matching When an exception is thrown from a code which is wrapped in a try block followed by one or more catch blocks, a search is made for matching catch block. If a matching type is found then that block will be invoked. If a matching type is not found then the exception moves up the method stack and reaches the caller method. Same procedure is repeated if the caller method is included in a try catch block. This process continues until a catch block handling the appropriate type of exception is found. If it does not find such a block then finally the program terminates.
11.What are the different ways to handle exceptions ?
There are two ways to handle exceptions,
1. By wrapping the desired code in a try block followed by a catch block to catch the exceptions. and
2. List the desired exceptions in the throws clause of the method and let the caller of the method hadle those exceptions.
2 specifying the candidate exceptions in the throws clause ?
In the first approach as a programmer of the method, you urself are dealing with the exception. This is fine if you are in a best position to decide should be done in case of an exception. Whereas if it is not the responsibility of the method to deal with it’s own exceptions, then do not use this approach. In this case use the second approach. In the second approach we are forcing the caller of the method to catch the exceptions, that the method is likely to throw. This is often the approach library creators use. They list the exception in the throws clause and we must catch them. You will find the same approach throughout the java libraries we use.
throw ThrowableInstance; ThrowableInstance must be an object of type Throwable or a subclass of Throwable.
throw new NullPointerException(“thrownException”);
16.What is the use of throws keyword ?
If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception. You do this by including a throws clause in the method’s declaration. A throws clause lists the types of exceptions that a method might throw.
type method-name(parameter-list) throws exception-list {
// body of method
}
Here, exception-list is a comma-separated list of the exceptions that a method can throw.
static void throwOne() throws IllegalAccessException {
System.out.println(“Inside throwOne.”);
Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream’s read() method·
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn’t force client programmers either to catch the
exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String’s charAt() method· Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.
ArithmeticException
ArrayIndexOutOfBoundsException
ClassCastException
IndexOutOfBoundsException
IllegalStateException
NullPointerException
SecurityException
Checked Exception
ClassNotFoundException
CloneNotSupportedException
IllegalAccessException
InstantiationException
InterruptedException
NoSuchFieldException
NoSuchMethodException
Throwable getCause( )
Throwable initCause(Throwable causeExc)
Sunday, June 20, 2010
Friday, June 18, 2010
read .cvs file sturts
html:file size="25" property="contactFile" styleId="contactFile" name="contactForm" onchange="javascript:checkFileType(this.value)"
javascript check the only.cvs format
--------------------------------------
function checkFileType(fName){
var isValid=true;
fullName = fName;
shortName = fullName.match(/[^\/\\]+$/);
splitName = fullName.split(".");
fileType = splitName[1];
fileType = fileType.toLowerCase();
if (fileType == 'cvs' )
{
document.contactForm.action="address.do";
document.contactForm.submit();
}
else {
alert("File formats must be .cvs ");
isValid=false;
}
}
What is the difference between sendRedirect & forward methods
What is the difference between sendRedirect & forward methods?
Forward( ) : javax.Servlet.RequestDispatcher interface.
- RequestDispatcher.forward( ) works on the Server.
- The forward( ) works inside the WebContainer.
- The forward( ) restricts you to redirect only to a resource in the same web-Application.
- After executing the forward( ), the control will return back to the same method from where the forward method was called.
- The forward( ) will redirect in the application server itself, it does'n come back to the client.
- The forward( ) is faster than Sendredirect( ) .
To use the forward( ) of the requestDispatcher interface, the first thing to do is to obtain RequestDispatcher Object. The Servlet technology provides in three ways.
1. By using the getRequestDispatcher( ) of the javax.Servlet.ServletContext interface , passing a String containing the path of the other resources, path is relative to the root of the ServletContext.
RequestDispatcher rd=request.getRequestDispatcher ("secondServlet");
Rd.forward(request, response);
2. getRequestDispatcher( ) of the javax.Servlet.Request interface , the path is relative to current HtpRequest.
RequestDispatcher rd=getServletContext( ).getRequestDispatcher("servlet/secondServlet");
Rd.forward(request, response);
3. By using the getNameDispatcher( ) of the javax.Servlet.ServletContext interface.
RequestDispatcher rd=getServletContext( ).getNameDispatcher("secondServlet");
Rd.forward(request, response);
Sendredirect( ) : javax.Servlet.Http.HttpServletResponce interface
- RequestDispatcher.SendRedirect( ) works on the browser.
- The SendRedirect( ) allows you to redirect trip to the Client.
- The SendRedirect( ) allows you to redirect to any URL.
- After executing the SendRedirect( ) the control will not return back to same method.
- The Client receives the Http response code 302 indicating that temporarly the client is being redirected to the specified location , if the specified location is relative , this method converts it into an absolute URL before redirecting.
- The SendRedirect( ) will come to the Client and go back,.. ie URL appending will happen.
Response. SendRedirect( "absolute path");
Absolutepath – other than application , relative path - same application.
When you invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completely with in the web container. When a sendRedirtect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completely new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.
OR
forward
Control can be forward to resources available within the server from where the call is made. This transfer of control is done by the container internally and browser / client is not involved. This is the major difference between forward and sendRedirect. When the forward is done, the original request and response objects are transfered along with additional parameters if needed.
redirect
Control can be redirect to resources to different servers or domains. This transfer of control task is delegated to the browser by the container. That is, the redirect sends a header back to the browser / client. This header contains the resource url to be redirected by the browser. Then the browser initiates a new request to the given url. Since it is a new request, the old request and response object is lost.
For example, sendRedirect can transfer control from http://javapapers.com to http://anydomain.com but forward cannot do this.
’session’ is not lost in both forward and redirect.
To feel the difference between forward and sendRedirect visually see the address bar of your browser,
in forward, you will not see the forwarded address (since the browser is not involved)
in redirect, you can see the redirected address.
Thursday, June 10, 2010
read .vcf files in java
html:file size="25" property="contactFile" styleId="contactFile" name="contactForm" onchange="javascript:checkFileType(this.value)"
javascript check the only.vcf format
--------------------------------------
function checkFileType(fName){
var isValid=true;
fullName = fName;
shortName = fullName.match(/[^\/\\]+$/);
splitName = fullName.split(".");
fileType = splitName[1];
fileType = fileType.toLowerCase();
if (fileType == 'vcf' )
{
document.contactForm.action="address.do";
document.contactForm.submit();
}
else {
alert("File formats must be .vcf ");
isValid=false;
}
}
action class
------------------
ContactForm contact=(ContactForm)form;
FormFile myFile=contact.getContactFile();
String fileType=null;
//HttpSession session = request.getSession(true);
//Register reg=(Register)session.getAttribute("userbean");
if(myFile.getFileSize() != 0 || myFile.getFileName().equals(""))
{
try
{
String fileName = myFile.getFileName();
fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
if(fileType.equals("vcf")){
InputStream fis = myFile.getInputStream();
byte buf[] = new byte[2048];
int n = 0;
String newFile = "contact.vcf";
if(!fileName.equals(""))
{
// FileOutputStream fos = new FileOutputStream((new StringBuilder("C:/Users/CIM Services 4/Desktop/folder/2sellback/")).append(newFile).toString());
FileOutputStream fos = new FileOutputStream((new StringBuilder("/home/resum0/public_html/importfile/")).append(newFile).toString());
while((n = fis.read(buf)) != -1)
{
fos.write(buf);
}
fis.close();
fos.flush();
fos.close();
}
the above code is upload
File f = new File("/home/resum0/public_html/importfile/contact.vcf");
BufferedReader input = new BufferedReader(new FileReader(f));
StringBuffer mail = new StringBuffer();
StringBuffer fname = new StringBuffer();
while((line = input.readLine()) != null)
{
Address address = new Address();
Contact fAddress = new Contact();
StringTokenizer st = new StringTokenizer(line, ":");
int i = 1;
int k = 1;
String check = "no";
while(st.hasMoreTokens())
{
if(i % 2 == 0)
{
if(check.equals("mail"))
{
address.setEmailId(st.nextToken());
check = "no";
}
if(check.equals("fname"))
{
String name = st.nextToken();
if(name.equals("null"))
{
fAddress.setfName("no");
} else
{
fAddress.setfName(name);
}
check = "no";
}
} else
{
String str = st.nextToken();
if(str.equals("EMAIL;TYPE=INTERNET"))
{
check = "mail";
}
if(str.equals("FN"))
{
check = "fname";
}
}
i++;
}
if(fAddress.getfName() != null)
{
fNameList.add(fAddress);
}
if(address.getEmailId() != null)
{
contacList.add(address);
}
}
System.out.println(mail.toString());
System.out.println(fname.toString());
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
contact.setContactList(contacList);
contact.setfNameList(fNameList);
return mapping.findForward("success");
}
Friday, June 4, 2010
captcha source code servlet jsp struts
More details about the captcha code below the link so you see the catcha source code and servet code ..
Captcha using java program . mainly graphics and awt package is very useful the captha servlet
catcha java and captha struts
See the Link
dynamic change letter java
public class alphanumber {
private static Random rand = new Random();
public static String generate(String characters, int n) {
char[] array = characters.toCharArray();
shuffle(array);
char[] temp = new char[n];
System.arraycopy(array, 0, temp, 0, n);
return new String(temp);
}
public static void shuffle(char[] array) {
int N = (100 + rand.nextInt(1000)) * array.length;
for(int i = 0; i < N; i++) {
int idx1 = rand.nextInt(array.length);
int idx2 = rand.nextInt(array.length);
char temp = array[idx1];
array[idx1] = array[idx2];
array[idx2] = temp;
}
}
public static void main(String[] args) {
for(int i = 0; i < 1000; i++) {
StringBuffer sb=new StringBuffer();
String s = generate("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 7);
char data[]=s.toCharArray();
sb.append("{'").append(data[0]).append("','").append(data[1]).append("','").append(data[2]).append("','");
sb.append(data[3]).append("','");
sb.append(data[4]).append("','");
sb.append(data[5]).append("','");
sb.append(data[6]).append("'},");
System.out.println(sb.toString());
}
}
}
struts captcha

what is captcha : Captcha is verify the code
below the sample code for the captch
Captcha.jsp
=------------
Refresh<% String captcha = (String) session.getAttribute("captcha"); String code = (String) request.getParameter("code"); if (captcha != null && code != null) { if (captcha.equalsIgnoreCase(code)) { String url="#"; RequestDispatcher rd=request.getRequestDispatcher(url); rd.forward(request,response); } else { out.print("
The characters you entered didn't match the word verification. Please try again.
");}
}
%>

the above code include in our jsp and change .
------------------------
package captchas;
import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.*;
import javax.servlet.http.*;
public class CaptchaServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
int width = 150;
int height = 50;
char data[][] = {
{'g','y','7','0','N','n','1'},
{'G','v','V','t','Y','O','J'},
{'p','z','t','c','f','1','H'},
{'r','u','6','K','f','d','C'},
{'L','1','E','i','x','0','7'},
{'j','c','r','n','u','f','N'},
{'w','v','P','O','K','Y','I'},
{'f','D','J','p','i','x','h'},
{'p','1','3','T','Q','g','k'},
{'t','c','B','C','n','e','x'},
{'1','p','x','T','W','k','v'},
{'E','i','N','I','S','e','r'},
{'0','I','Q','W','c','n','h'},
{'c','C','d','W','K','F','V'},
{'e','8','M','A','J','7','1'},
{'9','A','t','h','o','f','7'},
{'r','j','v','P','S','d','R'},
{'p','J','X','F','v','M','w'},
{'p','W','m','4','1','7','y'},
{'N','a','s','H','U','w','7'},
{'X','f','V','C','J','P','e'},
{'d','K','4','V','l','F','9'},
{'K','Z','G','i','q','O','N'},
{'l','G','V','F','R','o','1'},
{'I','A','a','7','b','2','p'},
{'k','D','r','5','s','I','P'},
{'P','x','H','0','6','M','q'},
{'X','j','q','L','3','K','z'},
{'3','j','V','J','B','1','D'},
{'R','K','l','I','j','E','B'},
{'a','o','7','F','D','X','4'},
{'T','A','l','N','h','0','x'},
{'3','2','G','E','4','j','D'},
{'8','i','E','y','a','t','B'},
{'S','k','s','8','o','A','K'},
{'q','a','z','N','Q','T','m'},
{'d','H','c','r','o','J','U'},
{'B','A','p','H','9','O','M'},
{'8','j','Q','I','d','H','7'},
{'7','t','i','5','V','M','o'},
{'L','A','0','a','w','6','7'},
{'s','L','E','h','M','o','b'},
{'t','q','r','V','N','x','5'}
};
BufferedImage bufferedImage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = bufferedImage.createGraphics();
Font font = new Font("Georgia", Font.BOLD, 18);
g2d.setFont(font);
RenderingHints rh = new RenderingHints(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
rh.put(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHints(rh);
GradientPaint gp = new GradientPaint(0, 0,
Color.magenta, 0, height/2, Color.black, true);
g2d.setPaint(gp);
g2d.fillRect(0, 0, width, height);
g2d.setColor(new Color(221, 233, 55));
Random r = new Random();
// int index1 = Math.abs(r.nextInt());
// int index=index1%10;
Random randomGenerator = new Random();
int index = randomGenerator.nextInt(999);
System.out.println("index1");
String captcha = String.copyValueOf(data[index]);
System.out.println("capta"+captcha);
request.getSession().setAttribute("captcha", captcha );
int x = 0;
int y = 0;
for (int i=0; i
x += 10 + (Math.abs(r.nextInt()) % 15);
y = 20 + Math.abs(r.nextInt()) % 20;
g2d.drawChars(data[index], i, 1, x, y);
}
g2d.dispose();
response.setContentType("image/png");
OutputStream os = response.getOutputStream();
ImageIO.write(bufferedImage, "png", os);
os.close();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
the above captchaservlet and change the struts code
Thursday, June 3, 2010
latest xml interview question
If we need to find a node and doesnt need to insert or delete we can go with SAX itself otherwise DOM provided we have more memory.
SAX Parser:
SAX (Simple API for XML) parser does not create any internal structure. Instead, it takes the occurrences of components of an input document as events, and tells the client what it reads as it reads through the input document.
A SAX parser serves the client application always only with pieces of the document at any given time.
SAX parser, however, is much more space efficient in case of a big input document (because it creates no internal structure). What's more, it runs faster and is easier to learn than DOM parser because its API is really simple. But from the functionality point of view, it provides a fewer functions, which means that the users themselves have to take care of more, such as creating their own data structures.
DOM Parser:
A DOM (Document Object Model) parser creates a tree structure in memory from an input document and then waits for requests from client.
A DOM parser always serves the client application with the entire document no matter how much is actually needed by the client.
DOM parser is rich in functionality. It creates a DOM tree in memory and allows you to access any part of the document repeatedly and allows you to modify the DOM tree. But it is space inefficient when the document is huge, and it takes a little bit longer to learn how to work with it.
Parsers are fundamental xml components, a bridge between XML documents and applications that process that XML. The parser is responsible for handling xml syntax, checking the contents of the document against constraints established in a DTD or Schema.
DOM
1. Tree of nodes
2. Memory: Occupies more memory, preffered for small XML documents
3. Slower at runtime
4. Stored as objects
5. Programmatically easy
6. Ease of navigation
SAX
1. Sequence of events
2. Doesn't use any memory preferred for large documents
3. Faster at runtime
4. Objects are to be created
5. Need to write code for creating objects
6. Backward navigation is not possible as it sequentially processes the document
XML interview question
1. sax is an event based parser and raise and event, while dom is not
2. sax is forward only where as dom can acess both was forward as well as backwards.
3. sax parses the file as it reads where as the dom loads the file into memory to parse the file.
4. Sax does not have memory constraints where as the dom has momory constraints as xml file is loaded into the momory to parse the file.
5. sax is read only , dom is read and write both.
6. if you have to parse and use the content only once , consider using sax if the xml file and content are used extensively then consider using dom
Wednesday, June 2, 2010
Captcha using java
What is captcha
Captcha is verify the image code..
see the coding
Creating a captcha in a Struts
see the coding