Pages
Saturday, December 18, 2010
Links for Twitpals
http://www.twitlonger.com
To Tweet URL
http://bit.ly/
http://tinyurl.com/
http://twitpwr.com/
http://www.urltwit.com/
To Tweet Image/Video
http://twitpic.com/
http://yfrog.com/
http://plixi.com
http://www.twitvid.com/
http://twitgoo.com/
To Tweet Audio[Songs...]
http://twitlens.com/
http://tweetmic.com/
http://twt.fm/
To Update the Background of Tweet Page
http://twitrounds.com/
http://www.twitrbackgrounds.com/
To Increase the Twitter Followers
http://www.tweetwhistle.com/
Tuesday, September 7, 2010
Create Android Applications in Eclipse
Android is one of the most useful, innovative mobile platform.
Android 2.2. Codenamed Froyo (for frozen yogurt), this is the seventh update to the Android platform brings some great new functionality to users (things like making your handset a portable hotspot and support for Adobe Flash within the browser)
, along with new tools for developers.
To know more about Android check out this links
www.android.com/
http://android-developers.blogspot.com
Steps to set the environment for creating Android applications with Eclipse
It is based on Eclipse 3.5 & above, Java 1.6 and Android 2.2 (Froyo).
Step- 1 Install Eclipse Galileo (3.5)
Step- 2 Download the Android SDK from the Android homepage under Android SDK download .The download contains a zip file which you can extract to any place in your file system.
e.g. place it under "c:\android-sdk-windows"
Step-3 Open the Help -> Install new software .To install all available plugins for the Android Development Tools (ADT) from the URL https://dl-ssl.google.com/android/eclipse/
Step-3.1 Add the Name as Android & Location of the site as https://dl-ssl.google.com/android/eclipse/
Step-3.2 Select the packages & click Next
Step-3.3 Select the agree option & click finish
Step-4 To Configure in Eclipse - Open the Preferences dialog via Windows -> Preferences.Select Android and maintain the installation path of the Android SDK.
Step-4.1 Select now Window -> Android SDK and AVD Manager from the menu.
Step-4.2 Select the following available packages and select the latest version of the SDK.
-Documentation for Android SDK,API8 ,revision 1
-SDK Platform Android2.2,API8,revision 2
-Samples for SDK API8 ,revision 1h
Step-4.3 Press "Install selected" and confirm the license for all package.Installation will be started.After the installation restart Eclipse.
Step-5 We need to define a device which can be used for emulation.Select now Window -> Android SDK and AVD Manager from the menu -> Select Virtual Devices .Press "New" and maintain the following.
Step-5.1 Press "Create AVD".This will create the device. To test if you setup is correct, select your device and press "Start".
Step-5.2Device is ready .
Now the environment is ready for developing android application.
Thursday, August 26, 2010
Shortening URL in Java using Bitly
Shortening any url in Java using bitly API .
We need to get API key first using bit.ly account
In two ways we can do
1. By calling the bit.ly's REST API.
2. By using bitly core methods.
1. By calling the bit.ly's REST API
We need the following jars to work on
bitlyj-2[1].0.0
commons-httpclient-3.1
commons-codec-1.2
logging-1.0.4
Code to shorten the url
HttpClient httpclient = new HttpClient();
HttpMethod method = new GetMethod("http://api.bit.ly/shorten");
NameValuePair[] valuePair=new NameValuePair[]{new NameValuePair("longUrl","http://www.sundarishree.blogspot.com/"),
new NameValuePair("version","2.0.1"),
new NameValuePair("login","YourUsername"),
new NameValuePair("apiKey","YourApikey"),
new NameValuePair("format","xml"),
new NameValuePair("history","1")
};
method.setQueryString(valuePair);
try {
httpclient.executeMethod(method);
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String responseXml =null;
try {
responseXml = method.getResponseBodyAsString();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(responseXml);
When the above code is excuted we will get the output in following XML format
<bitly>
<errorCode>0</errorCode>
<errorMessage></errorMessage>
<results>
<nodeKeyVal>
<shortKeywordUrl></shortKeywordUrl>
<hash>bzXiN2</hash>
<userHash>ceCaRl</userHash>
<nodeKey><![CDATA[http://www.sundarishree.blogspot.com/]]></nodeKey>
<shortUrl>http://bit.ly/ceCaRl</shortUrl>
<shortCNAMEUrl>http://bit.ly/ceCaRl</shortCNAMEUrl>
</nodeKeyVal>
</results>
<statusCode>OK</statusCode>
</bitly>
Code to get the short url from XML output
if(responseXml != null) {
// parse the XML
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;
try {
db = dbf.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
StringReader st = new StringReader(responseXml);
Document d = null;
String retVal=null;
try {
d = db.parse(new InputSource(st));
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
NodeList nl = d.getElementsByTagName("shortUrl");
if(nl != null) {
Node n = nl.item(0);
retVal = n.getTextContent();
System.out.println("Short URL >> "+retVal);
}
}
We can get the output as Short URL >>http://bit.ly/ceCaRl
2. By using bitly core methods
bitlyj-2[1].0.0 and commons-httpclient-3.1 jars are enough to use bitly core methods
Code to shorten the url
While importing Bitly mention as static
import static com.rosaloves.bitlyj.Bitly.*;
....
Provider bitly = Bitly.as("YourUserName", "YourApiKey");
ShortenedUrl info =bitly.call(shorten("http://www.visiontss.com/"));
System.out.println("Shorten URL "+info.getShortUrl());
output : Shorten URL http://bit.ly/ahyvK0
Bulk Methods
Some bitly methods support multiple arguments.info and clicks for example can take an arbitrary number of hash
or shortUrl arguments. You can do this in bitlyj just like you'd expect:
for(UrlInfo info1 : bitly.call(info("http://bit.ly/ceCaRl","http://bit.ly/ahyvK0"))) {
System.out.println("Created by :"
+info1.getCreatedBy());
System.out.println("ShortUrl :"
+info1.getUrl());
System.out.println("Title of the page :"
+info1.getTitle());
}
output :
Created by :sundarishree
ShortUrl :Url [shortBase=http://bit.ly/, globalHash=7haiBr, longUrl=, shortUrl=http://bit.ly/ahyvK0, userHash=ahyvK0]
Title of the page :Vision Tech Solutions - Software Product Development Company
Created by :sundarishree
ShortUrl :Url [shortBase=http://bit.ly/, globalHash=bzXiN2, longUrl=, shortUrl=http://bit.ly/ceCaRl, userHash=ceCaRl]
Title of the page :TECH.BLOG
You can know more in QuickStart
Wednesday, August 11, 2010
A Comfortable Online HTML Editor
A powerful Web-based WYSIWYG HTML editor that is designed for easy integration into our custom web applications
We can use this link for designing blog content HTML editor
Friday, August 6, 2010
rake aborted! Mysql::Error
|
Rails Application with MySQL DB
|
Friday, July 16, 2010
Google Map in Rails
http://code.google.com/apis/maps/signup.html
Signing up a key for http://yourdomain.com is usually the best practice, as it will work for all sub domains and directories.
Steps to include Google Map in an application
1. Generate an application geomap with latitude:decimal ,longitude:decimal,location
name:string and place description:string using scaffold.
2. We have to show this data in the map.Map we will get from the google server.
3. Download the file at http://tinyurl.com/hfrailsmap .Its a partial file save it as _map.html.erb and place in the app/views/geomaps/ like app/views/geomaps/_map.html.erb
4. We have the update the google_key in the _map.html.erb file with the key we got from google api link.
5. Copy the generated code from the show.html.erb & paste in new file called
show_map.html.erb.place it in app/view/geomaps/show_map.html.erb
6. In the app\controllers\geomaps_controller.rb place the following code
def show_map
@geomap=Geomap.find(params[:id])
end
7. Include the following code in the route.rb located in config folder.
map.connect 'geomaps/map/:id',:action=>'show_map',:controller=>'geomaps'
8. Place a test.xml data file in the public folder.This to check the map with static data.
<data>
<description>Vision Tech Solutions Description: Vision Tech Solutions is a Software Product and Outsourced Software Product Development firm, dedicated to provide custom made software services to customer's need of any size within global reach.</description>
<latitude>10.784745 </latitude>
<longitude>78.689575 </longitude>
<title>Vision Tech Solutions</title>
</data>
9. We have to now include the _map.html.erb partial code in the display page show_map.html.erb
<%=render(:partial=>'map',:local=>{:data=>'test.xml'}) %>
We need to pass a local variable called data containing the path to
the map data /test.xml
10. Check the display of map in http://yourdomain:3000/geomaps/map/1
Thursday, July 15, 2010
Ruby On Rails for Beginners
Rails is a collection ruby script. It’s better to have basic idea of ruby language before entering into Rails.
Rails has the following things
1. An Application framework /Action Pack that will help us to
generate data-driven, interactive pages.
2. Rails comes with one build in WebServer -We can run the web
application
3. Database-Rails creates application that are configured to
work with an integrated SQLite3 database
4. Active Record-Rails provides for object-relational mapping
library. This makes the database like a collection of Ruby objects.
5. Rails also provide the collection of tool scripts that helps
to manage the application.
Principle in Rails: Don’t Repeat Yourself
[If we tell Rails something once,its not required to say it again]
Install Ruby on Rails or RoR version2.1 & SQLite3 for database
http://www.rubyonrails.org/down
Getting started with Application
I - Steps to create a new application in Rails
1. At a Command Prompt –type >rails Application name
Ex: C:\ >rails MyApp
A New Folder names MyApp will be created with basic structure of the
application.
The basic Structure has the following folders &files
App,Config,Db,Doc,Lib,Log,Public,Script, test, tmp, vendor ,Rake files & readme
file
2.In that command prompt change into MyApp folder C:\MyApp>.
Type ruby script/server –To run the web server.
Ex: C:\MyApp>ruby script/server
3.Check this link http://localhost:3000/ to
confirm whether the webserver running Rails starts its webserver on port 3000 by default.
II -Start developing the Application
CRUD operation
CRUD operation/ Scaffolding –Basic operation of an application
Create,Read,Update & Delete.
Type scaffold command _Will generate the code for doing CRUD
operation in a database and also in the presentation layer .
Ex: C:\MyApp\>ruby script/generate scaffold employee employee_name:string
address:text
Creates employee.rb file in models & create_employees.rb
file in Db -migrate
[Note: We have to give the db name in singular form like
Employee,Shop..etc., and the table name will be in plural like
employees,Shops..etc.,]
To create the Tables in the database
We have to run the migration script using another rails tool called Rake.This
migration ruby script is generated by the scaffolding.
Type rake db:migrate at the command prompt –Which runs the
migration code& creates the table.[Db files are location the db folder]
Ex:C:\MyApp\>rake db:migrate
Run the employees.rb file in Db –migrate & create the table.
Go for link http://localhost:3000/employees In a couple of minutes we
can enter few records & perform the CRUD operations.
In app folder we will have Model, Controller & View folders .
To changes the display of the page
We can make the changes in the labels by changing the four .html.erb files in
the views folder.
To append a column after creating the Table.
Rails understand the migration Add..To..=>Add particular column
to a particular table.
Ex:If we want to include Phone Number column in employees table.
C:\MyApp\>ruby script/generate migration
AddPhoneToEmployees phone:string
Rails write the migration code.
After this command we have to give Rake db:migrate to make the
reflection of new column in the table.
Go for link http://localhost:3000/employees to conifrm the addition of
one more column in the table.
We can check the changes whenever we update the code.No need for publish & deploy
operations.
Without Scaffolding
We are in some time need of writing the code by our self for some application.Instead of having the same basic CRUD functions.We might be in need of genearating our own models & controllers
Command to create own model
ruby script/generate model table name in singular form column name:type
> rake db:migrate
This command will create magic columns
Id – Generated Primary Key.
Created_at and updated_at – record when data is entered or updated
Command to create own controller
> ruby script/generate controller
A Controller file will be created in the controller folder.
III- Routes
Route tells Tails where the web pages are located.
Routes are defined in a ruby program in config/routes.rb
By default this two line swill be the routes.rb
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
We can specify our own routes.
Ex:map.connect '/employees/:id',:controller=>'employees',:action=>'show'
The controller by using the finder method in the model sends the employees to the view
employees_controller.rb file
Class employeesController < ApplicationController
Def show
@employee=Employee.find(params[:id])
end
end
Rails Layout
Super-template exists in Rails is called Layout. one Single
template that will control how a group of other templates will look.
We have to place the html.erb file in the app/views/layouts.
To Add the style-sheet in the
Style sheet, images & javascripts will resides in the public folder.Which has all the static files.
Include the following code in the head tag of the html template.
<%=stylesheet_link_tag 'style sheet name(css)'>
Redirect
A redirect tells the browser to go to a different URL for output.
redirect_to "/---/# {---}"
# -symbol and {} inserts the value of the variable into a string.
Ex: While creating a new sample .We have to redirect to the currently
created sample.
def create
@sample = Sample.new(params[:sample])
@sample.save
redirect_to "/samples/#{@sample.id}"
end
Restricting access to a function
Rails will use special kind of web security called HTTP Authenticating .This type of security will pops up a dialog box and asks for a username and password when someone tries to enter a secure area of a website.
In the controller we have to specify the following code to make the filtration before doing security applied functions.
before_filter :function name to be called before executing particular function,;only=>[:security applied operation name]
function name to be called before particular operations
def functionname
authenticate_or_request_with_http_basic("The name of the secured area of the website-domain") do |username,password|
username == "username "&& password =="password"
end
end
Ex:
class SampleController <ApplicationController before_filter check_logged_in,:only=>[:edit]
def check_logged_in
authenticate_or_request_with_http_basic("Samples") do |username,password|
username == 'admin' && password =="XY2HYS8"
end
end
end
Thursday, July 8, 2010
Execute RUBY program on Command Prompt
Download Ruby -One-Click Installer (old) - ruby186-27_rc2.exe
Know about Ruby by having a look at the below links
http://www.ruby-lang.org/en/about/
http://www.techotopia.com/index.php/What_is_Ruby%3F
Simple steps for executing a tiny ruby program in command prompt.
1. Write a simple program & save the file as “welcome.rb”
Code: puts "Welcome ==> RUBY !"
2. Set Ruby on Path as follows :
C:\ruby\prg>set path=%path%;c:\ruby\bin
3.To excute the program give the filename with .rb extension suffix to the word ruby
C:\ruby\prg>ruby welcome.rb
4.Add .rb to the PATHEXT environment variable as follows:
C:\ruby\prg>set PATHEXT=.rb;%PATHEXT%
5.Once the above settings are configured simply run the program by typing the filename at the command prompt (the .rb filename extension is not required):
C:\ruby\prg> welcome
Command Prompt code
Wednesday, July 7, 2010
PostGres Vs MySQL Database
PROPERTY | POSTGRES | MYSQL |
License | BSD | GPL or Commercial |
OS Support | Windows, Unix, Linux, Mac OS. | Windows, Unix, Linux, Mac OS, Symbiyan. |
Fundamental Futures | ACID, Referential Integrity, Transactions, Unicode, Interface – GUI & SQL | ACID, Referential Integrity, Transactions, Unicode, Interface – GUI & SQL |
Max DB Size | Unlimited | Unlimited |
Max Table Size | 32 TB | 256 TB |
Max Row Size | 1.6 TB | 64 KB |
Max Columns per row | 250 – 1600 Depending on type | 4096 |
Max BLOB Size | 2 GB | 4 GB |
Max Char Size | 1 GB | 64 KB |
Max Number Size | Unlimited | 64 bits |
Min Date Value | -4713 | 1000 |
Max Date Value | 5874897 | 9999 |
Max Column Name | 63 | 64 |
Database Capability | Union, Inner join, Intersect, Except, Inner join, Outer join, Inner Selects, Merge join, Windowing Functions, Common Table Expressions. | |
Objects | Data Domain, Cursor, Trigger, Function, Procedure, External Routine. | Cursor, Trigger, Function, Procedure, External Routine. |
Facebook API
DownLoad Facebook jar
To work in JAVA Download - facebook-java-api-3.0.2-bin.zip
Inlcuded the jar in the class path and try to access the class in the jar
IDE
Eclipse - Version: 3.4.0
Get the API key & Application Secret
To start your work with Facebook API, You need to get the
API key & Application Key.
You need to get register your applications in this page http://www.facebook.com/developers/apps.php using Facebook account.
Necessary fields to be entered as follows
In Basic - Include the developers name .Who will be involving in developing the application.
In Canvas –Give the callback url of your application
We can start coding the application now.
Create the Twitter object & get the request token by passing the application Consumer key & secret.
To get the user client
FacebookJsonRestClient class is used for getting user client returns the object in JSON format.
FacebookJsonRestClient userClient =getUserClientsession);
public static FacebookJsonRestClient.getUserClient(HttpSession session) {
return (FacebookJsonRestClient)session.getAttribute(FACEBOOK_USER_CLIENT);
}
User session doesn't have a Facebook API client setup yet.
Pass the API key & Application secret to get the valid userclient
And store it in a session.
userClient = new FacebookJsonRestClient(api_key, secret);
session.setAttribute(FACEBOOK_USER_CLIENT, userClient);
Pass the Facebook url with your api key & required permission redirect the call.
You can check the permission available in Facebook .
facebook = new FacebookWebappHelper(req, res, api_key, secret);
nextPage = req.getRequestURI();
nextPage = nextPage.substring(nextPage.indexOf("/", 1) + 1);
//cut out the first /, the context path and the 2nd /
System.out.println(nextPage);
boolean redirectOccurred = facebook.requireLogin(nextPage);
if(redirectOccurred){
res.sendRedirect("http://www.facebook.com/login.php?api_key=dbfc65d0e72f5c103gg0gfgd8c5&connect_display=popup&v=1.0&next=http://www.facebook.com/connect/login_success.html&cancel_url=http://www.facebook.com/connect/login_failure.html&fbconnect=true&return_session=true&session_key_only=true&req_perms=read_stream,publish_stream,offline_access,sms,email,user_location");
return;
}
After execution of the above code.It request you enter the Facebook username & password.
Get the auth_token
String authToken=request.getParameter("auth_token");
By passing this authToken to the client you can start working on the functionalities like getting friends ,knowing user details etc.,
You can check the functionalities available in the FacebookJsonRestClient in this link
http://developers.facebook.com/docs/reference/rest/
Functions
To know the current user id
Long facebookUserID = userClient.users_getLoggedInUser();
To get friends Id’s
JSONArray arrayObj = (JSONArray)userClient.friends_get();
Get the id’s from Array & store it in a list
List userIds = new ArrayList();
for(int i=0;itry {
userIds.add((arrayObj.getString(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
Set the necessary fields in the ProfileField,that you need from a
User.
EnumSetfields = EnumSet.of ( com.google.code.facebookapi.ProfileField.NAME, com.google.code.facebookapi.ProfileField.PIC, com.google.code.facebookapi.ProfileField.CURRENT_LOCATION, com.google.code.facebookapi.ProfileField.FIRST_NAME, com.google.code.facebookapi.ProfileField.LAST_NAME);
To get the user details
JSONArray userArray = null;
try {
userArray = client.users_getInfo(userIds, fields);
} catch (FacebookException e1) {
e1.printStackTrace();
}
for(int i=0;i< userArray.length();i++){
try {
for (int j = 0; j < userArray.length(); j++) {
JSONObject obj = userArray.getJSONObject(j);
System.out.println("User Id"+obj.getString("uid"));
System.out.println("Pic url "+obj.getString("pic"));
System.out.println("Name"+obj.getString("first_name")
+" "+obj.getString "last_name"));
}
} catch (JSONException e) {
e.printStackTrace();}
}
To update the status of the current user
Check whether the user having the permissions & than try the functions
if (userClient.users_hasAppPermission(Permission.STATUS_UPDATE)){
userClient.users_setStatus("Status-Developing Facebook apps in Java!", false);
}
To Publish the stream for the current user
if(userClient.users_hasAppPermission(Permission.PUBLISH_STREAM)){
userClient.stream_publish("Stream-Publish-Wall written using Facebook API !", null, null, null, null);
}
To post the link to single /Group of user
userClient.links_post(Long.parseLong("Give the UserID"), "www.kyyba.com", "IT Recruitment");
Sunday, July 4, 2010
Twitter API
With Twitter4J, We can easily integrate our Java application with the Twitter service.
Step-up Twitter4j API
Get the Consumer key \ API key & Consumer Secret \Secret Key.
To start your work with Twitter4j API, You need to get the
Consumer key \ API key & Consumer Secret \Secret Key.
You need to get register your applications in this page http://twitter.com/apps
using Twitter account.
Download Twitter4j jar
Download - twitter4j-core-2.1.3-SNAPSHOT.jar
Inlcuded the jar in the class path and try to access the class in the jar
We can start coding the application now.
Create the Twitter object & get the request token by passing the application Consumer key & secret.
Code
Twitter twitter = new Twitter();
twitter.setOAuthConsumer("consumer key",”consumer secret” );
RequestToken requestToken = twitter.getOAuthRequestToken();
Get the Access Token & Secret
By using the request token you need to get the access token & token secret.
Code
String token = requestToken.getToken();
String tokenSecret = requestToken.getTokenSecret();
Authorized URL for accessing the Application
Store the requestToken & Authorized URl in a session.
String authUrl = requestToken.getAuthorizationURL();
session.setAttribute("authUrl", authUrl);
session.setAttribute("requestToken", requestToken);
Example Authorized Application URL
https://twitter.com/oauth/authorize?auth_token=LJyavdddrrrreddddy3sfpm8bTHg3H3Bddddm4
Once you click the authorized link it will ask for you twitter username & password.Once user details verfied it redirect to your application.
Functions in Twitter4j
Tweet Message
This function is to tweet a text message in his/her twitter.
Status status = twitter.updateStatus(“Tweet Message .”);
Delete the Tweeted message
We can delete the tweeted message by passing the TweetId
destroyTweet(twitter,tweetId);
User details
This function is used to get the user details.We need to pass the user’s id .
User user = twitter.showUser(twitter.getId());
From the user object we can get the details of the user profile,description …
user.getProfileImageURL();
user.getScreenName();
user.getName();
user.getDescription();
user.getURL();
user.getLocation();
user.getProfileBackgroundColor();
user.getProfileBackgroundImageUrl();
Search Tweet
We can search for tweets by using this method
String searchTweet ="TieCon MidWest"
Query query = new Query("searchTweet");
QueryResult result = twitter.search(query);
System.out.println("hits:" + result.getTotal());
for (Tweet tweet : result.getTweets()) {
System.out.println(tweet.getFromUser() + ":" + tweet.getText());
}
To get the friends tweets & details
/* All the Tweets in the first page will be displayed*/
Liststatuses = twitter.getFriendsTimeline();
for (Status status : statuses) {
System.out.println(status.getUser().getName() + ":" +
status.getText());
}
/** Four tweets in the first page will be displayed*/
Paging paging = new Paging(1, 4);
Liststatuses = twitter.getFriendsTimeline(paging);
Sending / Receiving Direct Messages
Twitter sender= new TwitterFactory().getInstance(senderID,senderPassword);
sender.sendDirectMessage(recipientId,message);
Twitter receiver = new TwitterFactory().getInstance(recipientId,recipientPassword);
Listmessages = receiver.getDirectMessages();
for (DirectMessage message : messages) {
System.out.println("Sender:" + message.getSenderScreenName());
System.out.println("Text:" + message.getText());
}
Method's avaialabe in the Twitter API
http://apiwiki.twitter.com/Twitter-API-Documentation
Thursday, June 24, 2010
LinkedIn API
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 SetconnectionFields = 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 MapgetSearchParameters() {
MapsearchParameters = 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
Monday, May 31, 2010
About Twitter API
With Twitter4J, We can easily integrate our Java application with the Twitter service.
Click to Download Twitter API
example :Code to update Tweets
............
..........
public static void main(String[] args)throws TwitterException{
Twitter twitter = new TwitterFactory().getInstance(username,password);
Status status = null;
try {
status = twitter.updateStatus(statusInput);
} catch (TwitterException e) {
System.out.println("Exception while updating the status to [" + status.getText() + "].");
e.printStackTrace();
}
System.out.println("Successfully updated the status to [" + status.getText() + "].");
Saturday, May 15, 2010
Links for Jquery Learners
http://www.ajaxdaddy.com/javascript-tooltip-jtip.html
Marquee
http://www.seangw.com/wordpress/index.php/2009/01/basic-ajax-tutorial-smooth-scrolling-text-marquee-with-a-jquery-plugin/
Floating Box
http://www.phpletter.com/Demo/Jquery-Floating-Box-Plugin/
Paging
http://rikrikrik.com/jquery/pager/#examples
Slide Show
http://malsup.com/jquery/cycle/
Image Zooming
http://dynamicdrive.com/dynamicindex4/imagepanner.htm
JScrollPane
http://www.kelvinluck.com/assets/jquery/jScrollPane/jScrollPane.html
My first try in Jquery .... :)
Include the Script & Style within Head tag
$(document).ready(function(){
$('.showAnswer').click(function(){
var htmlStr = $("li.theAnswer").html();
$("li.theAnswer").html($("li.theAnswer").text().replace(htmlStr,''+htmlStr+''));
$(this).text($(this).text() == 'Hide Answer' ? 'Show Answer' : 'Hide Answer');
});
});
Include the code in Body tag
A list with one alone with class for example
.. class="theAnswer"(C) 6 to 7..
Have A hyperlink with class class="showAnswer"
View Demo