Twitte API for Java - Hello Twitter Servlet (TOTD #178)

Posted by arungupta on Oracle Blogs See other posts from Oracle Blogs or by arungupta
Published on Thu, 14 Jun 2012 17:38:19 +0000 Indexed on 2012/06/15 15:23 UTC
Read the original article Hit count: 440

Filed under:

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.

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

© Oracle Blogs or respective owner

Related posts about /General