Thursday Jun 14, 2012

Twitter API for Java - Hello Twitter Servlet (TOTD #179)


There are a few Twitter APIs for Java that allow you to integrate Twitter functionality in a Java application. This is yet another API, built using JAX-RS and Jersey stack. I started this effort earlier this year and kept delaying to share because wanted to provide a more comprehensive API. But I've delayed enough and releasing it as a work-in-progress.

I'm happy to take contributions in order to evolve this API and make it complete, useful, and robust. Drop a comment on the blog if you are interested or ping me at @arungupta.

How do you get started ? Just add the following to your "pom.xml":

<dependency>
<groupId>org.glassfish.samples</groupId>
<artifactId>twitter-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>

The implementation of this API uses Jersey OAuth Filters for authentication with Twitter and so the following dependencies are required if any API that requires authentication, which is pretty much all the APIs ;-)
<dependency>
<groupId>com.sun.jersey.contribs.jersey-oauth</groupId>
    <artifactId>oauth-client</artifactId>
    <version>${jersey.version}</version>
</dependency>
<dependency>
    <groupId>com.sun.jersey.contribs.jersey-oauth</groupId>
    <artifactId>oauth-signature</artifactId>
    <version>${jersey.version}</version>
</dependency> 
Once the dependencies are added to your project, inject Twitter  API in your Servlet (or any other Java EE component) as:

@Inject Twitter twitter;

Here is a simple non-secure invocation of the API to get you started:

SearchResults result = twitter.search("glassfish", SearchResults.class);
for (SearchResultsTweet t : result.getResults()) {
out.println(t.getText() + "<br/>");
}
This code returns the tweets that matches the query "glassfish".

The source code for the complete project can be downloaded here. Download it, unzip, and mvn package will build the .war file. And then deploy it on GlassFish or any other Java EE 6 compliant application server!

The source code for the API also acts as the javadocs and can be checked out from here.

Read README.txt for complete details on how to get started.

A more detailed sample using security and several other API from this library is coming soon!

Saturday Jul 09, 2011

GlassFish Everywhere - Share your pictures on Facebook page!


There are several social media channels to reach the GlassFish team:
And of course we have our usual GlassFish Forum.

The growth in all these channels has been very consistent, especially the GlassFishVideos@youtube and @glassfish have shown exponential growth in the past few months. Thank you very much for that!

I've created a new album on our facebook page - GlassFish Everywhere! These are creative, funny, passionate, and all kinds of pictures of GlassFish that you've taken all around the world. Please share a link by posting a comment on the page and then we'll consolidate them it into the album.

Monday Jan 03, 2011

Happy New Year 2011!

2010 is over and 2011 is here ... wishing you a very happy & prosperous new year folks!

Here are some statistics from 2010 (missed 2009 and now lazy, similar reports from 2008 and 2007) ...

  • 126 blog entries, 523 comments
  • Blog visited 282,972 times from 13,296 cities (thanks a lot!)
  • 237,054 flight miles
  • About 1320 running miles
  • 4155 tweets
  • Crossed 2000 followers (thank you for that as well!)
  • 2 marathons (Silicon Valley Marathon 2010 and San Francisco 1/2 Marathon 2010)
  • Some of the conferences visited: JavaOne Latin America, CEJUG, DevIgnition, Rich Web Experience, Oredev, Cloud Computing Expo, OTN Developer Days, Silicon Valley Code Camp, Java2Days, JavaOne San Francsico, JAX London, London JUG, IndicThreads Cloud Computing, Java EE 6 Hands-on workshop @ San Francsico JUG, Dallas Tech Fest, UberConf, Jazoon, Tech Days Hyderabad, Ruby Conf India, Spark IT, DevNexus, EclipseCon, . . .

And now some data reported by Google Analytics for this blog ...

Here is a comparison with 2009 ...

Majority of searches are still organic ...

Firefox, IE, Chrome, and Safari are the top browsers ...

And Windows remain to be the dominant OS ...

Here is the geo spread ...

Somebody read this blog once even from Greenland :-)

And here are the top 25 blog entries ...

The decline in blogs traffic is most likely because of the increase in micro-blogging traffic as shown by twitter stats:

Do you know of any tools that allow to measure tweets/followers over a period of dates ? Google Analytics for Twitter would be nice :-)

Onward to 2011, Miles to go ...

Technorati: milestogo happynewyear 2010 2011 blogs bsc googleanalytics twitter stats

Tuesday Sep 21, 2010

Java EE 6 Twitter Demo @ JavaOne 2010 Technical General Session Keynote

This blog explains a typical 3-tier Java EE 6 application that lets the user monitor twitter trends for pre-defined hashtags. The following diagram explains the application's architecture.

Java EE 6 is a complete stack that provides support for all three tiers. This application uses a Java Server Faces front-end and uses PrimeFaces widget library to generate the monitoring charts. The widget library provides 100+ rich set of components and uses JSF 2.0 APIs and Servlet 3.0 features like self-registration. The "backing bean" for the JSF front-end is an EJB packaged in the WAR - yet another ease-of-use feature in Java EE 6. This EJB uses JPA for persistence query the stored tweets in a database. There is another EJB in the middle tier that triggers a method every 3 minutes, specified using the simplified cron-like @Schedule syntax, and uses Jersey Client API to get data from Twitter. And this EJB also uses JPA to store the queried tweets in the database.

A live version of this demo is available at glassfish.org/twitter-demo. An earlier snapshot of the trends is shown below:

The source code for this application can be downloaded as a Maven project here. This code comes with a "readme.txt" that explains how to create schema for a pre-defined JDBC resource in GlassFish, deploy, and run the application.

This application demonstrates the following features of Java EE 6:

  • Facelets as templating language using JSF 2.0
  • Composite components using JSF 2.0 - enables abstraction and reusable code
  • Third-party open source widget library based upon JSF 2.0
  • Simplified EJB packaging in a WAR file
  • CDI bean as the "backing bean" for JSF 2.0 and other dependency injection
  • Simplified cron-like timer syntax in EJB 3.1 using @Schedule
  • Jersey Client API to invoke RESTful endpoints
  • Simplified usage of JPA for persistence

Currently this application uses a pre-defined set of hashtags. A future version will allow the users to specify their own set of hashtags and then monitor them.

How about using this application for a tweet-a-thon for your next conference ?

Technorati: conf javaone javaee6 glassfish twitter 3tier architecture primefaces

Wednesday Aug 04, 2010

TOTD #143: Retrieve Twitter user timeline using using Jersey and OAuth

The Basic Authentication for authorizing with Twitter API will be turned off on Aug 16th. After that OAuth will be the only way to invoke the API.

Beginner's guide to OAuth provide an excellent explanation to OAuth. The typical analogy for OAuth is a "valet key" to the car which is a stripped down version of your regular key. These keys are meant for valet drivers who don't need to open trunk or glove compartment and don't need to drive the car for longer distance. So even though they have access to the entire car but are restricted to the limited functionality.

OAuth is used to share your resources (photos, videos, bank accounts, etc) stored on one site with another site without having to share your username and password. The site storing the resources is "Service Provider", the site requesting the access is "Consumer", you are the "User", "Tokens" are "valet key" that provide required access to the resources.

This Tip Of The Day (TOTD) explains how Jersey, the Reference Implementation for JAX-RS, provides seamless support for OAuth by creating a simple desktop application that retrieves user timeline on Twitter using OAuth. This blog is going to combine the instructions outlined in Understanding the guts of Twitter's OAuth for client apps and Using Jersey client OAuth support with Smugmug to achieve that.

Lets get started!

  1. Create a Maven project as:
    mvn -DarchetypeVersion=1.0 -DgroupId=org.glassfish.samples -DarchetypeArtifactId=maven-archetype-quickstart -Dversion=1.0-SNAPSHOT -DarchetypeGroupId=org.apache.maven.archetypes -Dpackage=org.glassfish.samples.twitter -DartifactId=twitter
    
  2. Update the generated "pom.xml" with the following fragments:
    <repositories>
      <repository>
        <id>glassfish-repository</id>
        <name>Java.net Repository for Glassfish</name>
        <url>http://download.java.net/maven/2/</url>
      </repository>
    </repositories>
    <dependencies>
      <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
      </dependency>
      <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-client</artifactId>
        <version>1.1.3-SNAPSHOT</version>
      </dependency>
      <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-json</artifactId>
        <version>1.1.3-SNAPSHOT</version>
      </dependency>
      <dependency>
        <groupId>com.sun.jersey.oauth</groupId>
        <artifactId>oauth-signature</artifactId>
        <version>1.1.2-ea-SNAPSHOT</version>
      </dependency>
      <dependency>
        <groupId>com.sun.jersey.oauth</groupId>
        <artifactId>oauth-client</artifactId>
        <version>1.1.2-ea-SNAPSHOT</version>
       </dependency>
    </dependencies>
    <build>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>2.0.2</version>
          <configuration>
            <source>1.6</source>
            <target>1.6</target>
          </configuration>
        </plugin>
      </plugins>
     </build>
    

    The Jersey dependencies add the core Jersey libraries and OAuth functionality in Jersey.
  3. Register your app with Twitter - Register your application with Twitter by clicking on Register a new application >>. The complete list of registered applications can be seen at Applications using Twitter. Select "Client" as the app type, select "Yes, use Twitter for login" and leave the "Callback URL" empty. The registration gives you "consumer key" and "consumer secret". These are used to obtain temporary credentials (or request tokens) from Twitter.
  4. Obtain Twitter OAuth credentials - Each OAuth request is an HTTP request with "Authorization" header specifying the information by OAuth service provider. Jersey provides a OAuthClientFilter to add this header to the outbound client request. Twitter API Wiki explains the authentication as multiple step process for desktop applications. Each step involves sending some parameters to twitter and getting a result back and the intent of each method/request is clearly explained in Understanding the guts of Twitter's OAuth for client apps. In our case, each request is created by using Jersey Client API and attaching OAuthClientFilter and is explained next.
    1. Request temporary credentials, a.k.a request token, from Twitter using oauth/request_token.
      1. In "App.java", create an instance of Jersey client in the constructor and attach a LoggingFilter to dump inbound/outbound messages as:
        public App() {
            // Create a Jersey client
            client = Client.create();
        
            client.addFilter(new LoggingFilter());
        }
        
      2. Request temporary credentials by adding the following method:
        public void getRequestToken() {
            client.removeAllFilters();
        
            // Create a resource to be used to make Twitter API calls
            WebResource resource = client.resource(REQUEST_TOKEN_URL);
        
            // Set the OAuth parameters
            OAuthSecrets secrets = new OAuthSecrets().consumerSecret(CONSUMER_SECRET);
            OAuthParameters params = new OAuthParameters().consumerKey(CONSUMER_KEY).
                    signatureMethod("HMAC-SHA1").version("1.0");
            // Create the OAuth client filter
            OAuthClientFilter oauthFilter =
                    new OAuthClientFilter(client.getProviders(), params, secrets);
        
            // Add the filter to the resource
            resource.addFilter(oauthFilter);
        
            // make the request and print out the result
            System.out.println(resource.get(String.class));
        }
        
        
        Note, "OAuthClientFilter" is used to populate the "Authorization" header instead of handcrafting it. The REQUEST_TOKEN_URL is "http://twitter.com/oauth/request_token", CONSUMER_SECRET and CONSUMER_KEY are the values obtained from registering your application.
      3. Edit "AppTest.java" and change "testApp" method such that it looks like:
        public void testApp() {
            App app = new App();
            app.getRequestToken();
        }
        
      4. Obtain the temporary credentials by running this application as:
        mvn test
        

        and see an output as:
        oauth_token=REQUEST_OAUTH_TOKEN&oauth_token_secret=REQUEST_OAUTH_TOKEN_SECRET&oauth_callback_confirmed=true
        

        REQUEST_OAUTH_TOKEN, a temporary token, is used to authorize on twitter.com.
    2. Authorize the user and obtain PIN
      1. Go to "https://twitter.com/oauth/authorize?oauth_token=REQUEST_OAUTH_TOKEN" in a browser window.
      2. If not already logged in, enter your twitter credentials and click "Allow".
      3. Copy the PIN.
    3. Request permanent credentials, a.k.a access token, from Twitter using oauth/access_token.
      1. Request permanent credentials by adding the following method in "App.java"
        public void getAccessToken() {
                client.removeAllFilters();
        
                // Set the OAuth parameters
                OAuthSecrets secrets = new OAuthSecrets().consumerSecret(CONSUMER_SECRET);
                OAuthParameters params = new OAuthParameters().consumerKey(CONSUMER_KEY).
                        signatureMethod("HMAC-SHA1").
                        version("1.0").
                        token(REQUEST_OAUTH_TOKEN).
                        verifier(PIN);
                // Create the OAuth client filter
                OAuthClientFilter oauthFilter =
                        new OAuthClientFilter(client.getProviders(), params, secrets);
        
                // Create a resource to be used to make Twitter API calls
                WebResource resource = client.resource(ACCESS_TOKEN_URL);
        
                // Add the filter to the resource
                resource.addFilter(oauthFilter);
        
                // make the request and print out the result
                System.out.println(resource.get(String.class));
            }
        
        REQUEST_OAUTH_TOKEN is the temporary token obtained earlier, ACCESS_TOKEN_URL is "https://twitter.com/oauth/access_token".

        Notice, REQUEST_OAUTH_TOKEN and PIN are now added to the OAuthClientFilter.
      2. Invoke this method by editing "AppTest.java" as:
        public void testApp() {
             App app = new App();
        //     app.getRequestToken();
             app.getAccessToken();
        }
        
      3. Obtain the permanent credentials by running this application as:
        mvn test
        

        and see an output as:
        oauth_token=ACCESS_OAUTH_TOKEN&oauth_token_secret=ACCESS_OAUTH_TOKEN_SECRET&user_id=USER_ID&screen_name=USER_NAME
        

        ACCESS_OAUTH_TOKEN is the authorized token that can be used for making any future requests, USER_ID and USER_NAME are identifiers for the user who signed in on twitter.com. 
  5. Get the last 20 status messages for the user from Twitter
    1. Add the following method in "App.java:
      public void getUserTimeline() {
          client.removeAllFilters();
      
          // Set the OAuth parameters
          OAuthSecrets secrets = new OAuthSecrets().consumerSecret(CONSUMER_SECRET);
          OAuthParameters params = new OAuthParameters().consumerKey(CONSUMER_KEY).
                  signatureMethod("HMAC-SHA1").
                  version("1.0").
                  token(ACCESS_OAUTH_TOKEN);
          // Create the OAuth client filter
          OAuthClientFilter oauthFilter =
                  new OAuthClientFilter(client.getProviders(), params, secrets);
      
          // Create a resource to be used to make Twitter API calls
          WebResource resource = client.resource(USER_TIMELINE_URL);
      
          // Add the filter to the resource
          resource.addFilter(oauthFilter);
      
         // Parse the JSON array
          JSONArray jsonArray = resource.get(JSONArray.class);
          List<String> statuses = new ArrayList<String>();
      
          try {
              for (int i = 0; i < jsonArray.length(); i++) {
                  JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                  StringBuilder builder = new StringBuilder();
                  builder.append(jsonObject.getString("text")).
                          append(jsonObject.getString("created_at"));
                  statuses.add(builder.toString());
              }
          } catch (JSONException ex) {
              Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
          }
      } 
      USER_TIMELINE_URL is "http://api.twitter.com/1/statuses/user_timeline.json". The "getTimelineElements" method can be updated to pick other elements from the return JSON object. The complete JSON schema for the response is described here.
    2. Edit "AppTest.java" as:
      public void testApp() {
          App app = new App();
      //    app.getRequestToken();
      //    app.getAccessToken();
          app.getUserTimeline();
      }
      
    3. Finally get the last 20 status updates by giving the command:

      mvn test
      


      and see the output similar to:
      Running org.glassfish.samples.twitter.AppTest
      [Developing OSGi-Enabled Java EE Applications- http://bit.ly/aOim34 (via 
      @JavaOneConf) #javaone10Wed Aug 04 23:53:13 +0000 2010, Google Wave goes
       bye bye (via @google:)Update on Google Wave http://bit.ly/bIoDWAWed Aug
       04 21:16:07 +0000 2010, @gdaniels Yeah, I expected #wave to bye bye as
       well, but this is fairly quick!Wed Aug 04 21:15:41 +0000 2010,
      

And that's it!

This Tip Of The Day explained how to use Jersey to retrieve last 20 status messages that a user posted on twitter. Here are some other future possible additions:

  • POST status update
  • Integrate Search API using OAuth (is it possible ?)
  • Integrate Streaming API (need more investigation)
  • Create a web-base client that automatically redirects the user from application to twitter.com and then back to the application.

Jersey and OAuth wiki provides more details about how to use OAuth with Jersey.

Technorati: totd jaxrs jersey restful webservices oauth twitter glassfish

Monday Apr 20, 2009

GlassFish in Twitterverse - Oracle buying Sun


Oracle has entered a definitive agreement to acquire Sun for $9.50 per share in cash. Read more details in Sun's PR and Oracle's PR.

Here are some tweets captured from the Twitterverse on GlassFish:



























And there is certainly buzz at MySQL Users Conference about the announcement. Only time will tell the future and fate of this blog!

It seems there is only one other entry tagged Oracle on this blog ;-)

Technorati: glassfish twitter oracle sun

Thursday Jan 08, 2009

Twitter.com - 500 Internal Server Error



And even the JavaScript widget is asking to login as:

Sunday Jan 04, 2009

TOTD #59: How to add Twitter feeds to blogs.sun.com ? + Other Twitter Tools


Twitter is a micro-blogging service that allows its users to send and read other users's updates which are text-based posts upto 140 characters in length. This Tip Of The Day will show how to add Twitter feeds to your blog but first some facts about Twitter:

The State of Twittersphere Q4 2008 was released recently (generated using Tweet Grader) and shows:
  • Total of 4-5 million users
  • 70% users joined in 2008, 20% joined in past 60 days, 5-10 new accounts/day (so mostly noobies)
  • Only 5% have 250 or more followers
  • Only 0.8% have 1000 or more followers
  • 35% tweeters have 10 or fewer followers
  • 9% tweeters follow no one at all
Here are Tweet Grader statistics generated for @arungupta:



Lets add twitter feeds to your blog:
  1. Go to twitter.com/widgets and select Other as shown below:



    It allows you to create Flash and HTML widgets for any web page. Twitter feeds can be directly added to some other popular social networking websites by selecting their option.
  2. Click on "Continue" and choose between Flash or HTML widget as shown below:


  3. Click on "Continue" and feel free to customize as shown below:



    "Number of updates" is the number of tweets that will be shown and title can be changed as well.
  4. For blogs.sun.com, this obtained code fragment can be easily added to "_sideColumn" template.
Here are some other nifty tools to manage your Twitter account:
  1. Twitterfeed: Twitter your blog entries
  2. Twitterank: Page rank for Tweeters (85.01 as of this writing, live here)
  3. Twinfluence: Combined influence of twitterers and followers (as of Jan 2)
  4. TwitterCounter: Widget that shows twitterer follower
  5. TwitterFox: Firefox extension that notifies of tweets (really sweet and lots of other related plugins)
  6. SocialToo: Manage online interactions of Twitter (surveys, auto-follow/unfollow, Direct Messages to new followers)
  7. TweetStats: Trends and analysis as shown below:



    Live stats for @arungupta are available here.
  8. TweetLater: Schedule tweets for a particular time/day and some other features similar to SocialToo (auto-follow/unfollow and DM to new followers)
  9. Easy Tweets: Schedule tweets in future, automatically post RSS feeds and other similar features
There are numerous other tools available to manage your Twitter account! What is your favorite ?

Please leave suggestions on other TOTD (Tip Of The Day) that you'd like to see. An archive of all the tips is available here.

Technorati: twitter microblogging blogs bsc milestogo
About

profile image
Arun Gupta is a technology enthusiast, a passionate runner, author, and a community guy who works for Oracle Corp.


Java EE 7 Samples

Stay Connected

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today