Pages

Showing posts with label LinkedIn Java. Show all posts
Showing posts with label LinkedIn Java. Show all posts

Tuesday, May 31, 2011

Simple Java Program using LinkedIn API

The below program will helps you to fetch & view linkedIn data in a short time.

Follow this link to download the jars & to get token, secret to work with LinkedIn API

Simple Java Program. To get the LinkedIn details about the current user [Who created the token & secret key]


public static void main(String[] args) {

String linkedinKey = "C2E7PG.."; //Your LinkedIn key
String linkedinSecret = "9hyC6.. ";//Your LinkedIn Secret
OAuthConsumer consumer = new DefaultOAuthConsumer( linkedinKey,linkedinSecret);

OAuthProvider provider = new DefaultOAuthProvider("https://api.linkedin.com/uas/oauth/requestToken",
"https://api.linkedin.com/uas/oauth/accessToken",
"https://api.linkedin.com/uas/oauth/authorize");

System.out.println("Fetching request token from LinkedIn...");
String authUrl;
try {
authUrl = provider.retrieveRequestToken(consumer, OAuth.OUT_OF_BAND);
System.out.println("Check the below link and grant this app authorization -You will get Pin Number.Copy it\n" + authUrl );
System.out.println("Enter the PIN code and hit ENTER when you're done:");
} catch (OAuthMessageSignerException e1) {
e1.printStackTrace();
} catch (OAuthNotAuthorizedException e1) {
e1.printStackTrace();
} catch (OAuthExpectationFailedException e1) {
e1.printStackTrace();
} catch (OAuthCommunicationException e1) {
e1.printStackTrace();
}
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String pin;
try {
pin = br.readLine();
System.out.println("Fetching access token from LinkedIn...");
provider.retrieveAccessToken(consumer, pin);
System.out.println("Access token: " + consumer.getToken());
System.out.println("Token secret: " + consumer.getTokenSecret());
URL url = new URL("http://api.linkedin.com/v1/people/~:(id,first-name,last-name,picture-url,headline)");

HttpURLConnection request = (HttpURLConnection) url.openConnection();
consumer.sign(request);
request.connect();
System.out.println("Sending request to LinkedIn...");
String responseBody = convertStreamToString(request.getInputStream());
System.out.println("Response: " + request.getResponseCode() + " "
+ request.getResponseMessage() + "\n" + responseBody);

} catch (OAuthMessageSignerException e) {
e.printStackTrace();
} catch (OAuthNotAuthorizedException e) {
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
e.printStackTrace();
} catch (OAuthCommunicationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static String convertStreamToString(InputStream is) {

BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}


Output

Fetching request token from LinkedIn...
Check the below link and grant this app authorization -You will get Pin Number.Copy it
https://api.linkedin.com/uas/oauth/authorize?oauth_token=dcb835667-a5d7-4e95-91f9-fde4b9b47e3a
Enter the PIN code and hit ENTER when you're done:
59278
Fetching access token from LinkedIn...
Access token: f0f94b3d-50b9-4549-bd96-5d1ea3ba7a9c
Token secret: f2b13c99-f206-4612-bf9e-2afc1387bc1a
Sending request to LinkedIn...
Response: 200 OK



GtYKzPiNkX
Sundari Shree
Gunasekaran
Software Engineer at Vision Tech Solutions


Note: By passing the different URL’s as parameter You can check all the available information in LinkedIn .

URL url = new URL("http://api.linkedin.com/v1/people/~:(id,first-name,last-name,picture-url,headline)");

This URL is to get about the people information.

Thursday, June 24, 2010

LinkedIn API

I have just started to work in this API with Java .bcoz am basically a Java developer.

Step-up LinkedIn API

To start your work with LinkedIn API, You need to get the
Consumer key \ API key & Consumer Secret \Secret Key.
Go for this link to get your Consumer key & Consumer Secret for your application
https://www.linkedin.com/secure/developer
You have to give application name & some regular fields you have to fill up.

IDE & JDK Version
Working with IBM Rational Application Developer-Version: 7.0.0
jdk used is 1.6 version.
You can work on Eclipse also.

Download 3 Jars

1.commons-codec-1.3.jar
http://code.google.com/p/linkedin-j/source/browse/#svn/trunk/linkedin-j/lib

2.linkedin-j.jar - http://code.google.com/p/linkedin-j/source/browse/#svn/trunk/linkedin-j/dist [version downloaded is May24]

3.signpost-core-1.2.1.1.jar - http://code.google.com/p/linkedin-j/source/browse/#svn/trunk/linkedin-j/lib

Included the jar in the class path and try to access the class in the jar

Got :( Error bcoz I tried out downloading snapshot version of linkedIn.jar ,
Not able to get the authService object.

final LinkedInOAuthService oauthService = LinkedInOAuthServiceFactory.getInstance().createLinkedInOAuthService(consumerKeyValue, consumerSecretValue);

Error got
Exception in thread "main" java.lang.NoClassDefFoundError: oauth/signpost/signature/OAuthMessageSigner
With the support of Linked Forum got rid from this issue.
http://developer.linkedin.com/message/5585#5585

Lets start coding ....
How to get LinkedIn –token, token secret & Authorization URL using consumer key & consumer secret?


final LinkedInOAuthService oauthService = LinkedInOAuthServiceFactory.getInstance().createLinkedInOAuthService(consumerKeyValue, consumerSecretValue);
LinkedInRequestToken requestToken = oauthService.getOAuthRequestToken("your application url");
String token = requestToken.getToken();
String tokenSecret = requestToken.getTokenSecret();
String authUrl = requestToken.getAuthorizationUrl();


Set all this objects in session.Inorder to proceed with the functions.

session.setAttribute("LINKEDIN_TOKEN", token);
session.setAttribute("LINKEDIN_TOKEN_SECRET", tokenSecret);
session.setAttribute("LINKEDIN_REQUEST_TOKEN", requestToken );
session.setAttribute("LINKEDIN_AUTH_URL", authUrl );

After execution of these codes, the service will be verfied .

Place this authorized url as a link in a jsp page.
When the link is clicked it asks for your LinkedIn username & Password.

How to get the LinkedIn –Access Token?

Once your application ,username& password are verified you will get a auth_verifier with the url.

String oauthVerifier = request.getParameter("oauth_verifier");
//Pass the requestToken[session.getAttribute("LINKEDIN_REQUEST_TOKEN")] & oauthVerifier to get accesstoken
LinkedInAccessToken accessToken = oauthService.getOAuthAccessToken(requestToken, oauthVerifier);

Set the access token in a session

session.setAttribute("LINKEDIN_ACCESS_TOKEN", accessToken);


How to create the Client Object?

Create the factory object by passing consumerKeyValue & consumerSecretValue

final LinkedInApiClientFactory factory = LinkedInApiClientFactory.newInstance(consumerKeyValue, consumerSecretValue);

Pass the access token to get the client object .

final LinkedInApiClient client = factory.createLinkedInApiClient(accessToken);


Functions in Linked-Id

Check out all the functions available in the LinedIn API

I have given some of the main functions with example code ,Here it goes...

To get the Current user Profile

Person profile = client.getProfileForCurrentUser(EnumSet.of(ProfileField.ID));
System.out.print("CurrentUsers Profile-Id >>"+profile.getId());

To get specific information of the Current User

Set the fields which you need .

Person userprofile = client.getProfileById(profile.getId(), EnumSet.of(ProfileField.FIRST_NAME,ProfileField.LAST_NAME,ProfileField.HEADLINE,ProfileField.INDUSTRY,ProfileField.API_STANDARD_PROFILE_REQUEST, ProfileField.PICTURE_URL, ProfileField.PUBLIC_PROFILE_URL));
System.out.println("PersonID:" + userprofile.getId());
System.out.println("Name:"+ userprofile.getFirstName()+ " " + userprofile.getLastName());
System.out.println("Headline:" + userprofile.getHeadline());
System.out.println("API Request:" + userprofile.getApiStandardProfileRequest());
System.out.println("Industry:" + userprofile.getIndustry());
System.out.println("Picture:" + userprofile.getPictureUrl());
System.out.println("Public URL:" + userprofile.getPublicProfileUrl());


To get the connections of the Current User
Set the fields which you need .

final Set connectionFields = EnumSet.of(ProfileField.ID, ProfileField.FIRST_NAME, ProfileField.LAST_NAME, ProfileField.HEADLINE, ProfileField.INDUSTRY, ProfileField.CURRENT_STATUS, ProfileField.CURRENT_STATUS_TIMESTAMP,ProfileField.API_STANDARD_PROFILE_REQUEST, ProfileField.EDUCATIONS,ProfileField.PUBLIC_PROFILE_URL, ProfileField.POSITIONS, ProfileField.LOCATION, ProfileField.PICTURE_URL);

Pass the connection fields & get the connection object

Connections tryconnections = client.getConnectionsForCurrentUser(connectionFields);


Iterate the Person object from the person list.

for (Person person : connections.getPersonList()) {
System.out.println( "PersonId :"+ person.getId());
System.out.println("Name:" + person.getFirstName() + " " + person.getLastName());
System.out.println("Headline:" + person.getHeadline());
System.out.println("Industry:" + person.getIndustry());
System.out.println("Picture:" + person.getPictureUrl());

//To get the Location details

Location location = person.getLocation();
System.out.println("Location:" +location.getName()+" - "+location.getCountry().getCode());
System.out.println("API Request:" + person.getApiStandardProfileRequest());
System.out.println("Public URL:" + person.getPublicProfileUrl());

//To get the Header information

ApiStandardProfileRequest apiStandardProfileRequest=person.getApiStandardProfileRequest();
System.out.println("Header:" + apiStandardProfileRequest.getHeaders());
}


To get Profile ID by using public url

Pass the public URL of a person & connection fields

Person checkPerson = client.getProfileByUrl("public url of a person,connectionFields);
System.out.println("PersonID:" + checkPerson.getId());
System.out.println("Name:" + checkPerson.getFirstName() + " " + checkPerson.getLastName());
.
.

You can get all the data of a person for whatever fields mentioned in the connection field.

To get Profile ID by using Person ID

Pass the PersonID & required fields
Person othersProfile = client.getProfileById(userID, EnumSet.of(ProfileField.FIRST_NAME,ProfileField.LAST_NAME,ProfileField.HEADLINE,ProfileField.INDUSTRY,ProfileField.API_STANDARD_PROFILE_REQUEST, ProfileField.PICTURE_URL, ProfileField.PUBLIC_PROFILE_URL));

To invite by using E-mail
Pass the client object,emailId of the person you want to invite,firsname,lastname,subject & message.

inviteByEmailID(client,emailID, firstName, lastName,subject,msg);

Note:e-mail,first name & last name should not be passed Empty.Null Pointer Exception will be thrown.

To invite by using PersonId

Pass the header token value ,userId,subject & message.

Code to take the header token value

String tokenValue=authHeader.getHttpHeaderList().get(0).getValue();
System.out.println("tokenValue "+tokenValue);
client.sendInviteById("PersonID", subject, msg,tokenValue);


To send message to specific group of people

You have to pass the id’s of the people in a list whom you want to send message

Iterate the list in a for loop

client.sendMessage(Arrays.asList(((String) list.get(i)).split(",")), subj, message);

To Search within Linked In

We can search by passing company name,keyword,title,CountryCode
…etc

Example code is given for searching connection based on particular company

Function to put the search parameters [Company name is set]

private static Map getSearchParameters() {
Map searchParameters = new EnumMap(SearchParameter.class);
searchParameters.put(SearchParameter.COMPANY, "Kyyba");
return searchParameters;
}
Map SearchParameter, String searchParameters = getSearchParameters();


Pass the search Parameters to find the people based on search

People people = client.searchPeople(searchParameters);


To get the people information

for (Person person : people.getPersonList()) {
System.out.println(person.getId() + ":" + person.getFirstName() + " " + person.getLastName() + ":" + person.getHeadline());
}


We can't get the connections of connections

Connections otherscon = client.getConnectionsById("ProfielID");

Error will be thrown as Access to other member's connections denied.

In Linkedin forum they have mentioned as currently they not support getting other people's connections.

http://developer.linkedin.com/thread/1329
http://developer.linkedin.com/message/3706;jsessionid=3E26C276AF047188942CDE50F562B638.node0