{{ !articles[0].partner.isSponsoringArticle ? "Platinum" : "Portal" }} Partner

OAuth Support in NetBeans IDE 6.9

OAuth is a security protocol that enables users to authorize client applications to access their web resources. OAuth has quickly become the industry standard for web-based access delegation. There are many well known (REST) service providers, like Yahoo services, Delicious, Twitter and SmugMug, that have already applied the OAuth protocol.

NetBeans IDE provides a mechanism where an OAuth protected REST resource can be registered in the IDE, and an application client can be generated for such a resource. The IDE, by default, registers OAuth REST resources for Twiter and Delicious services.

See the screenshot for details:


In this article, I demonstrate how the Twitter client, using the OAuth protocol, can be created in a web application:

Create the Twitter Client Class

 Take the following steps to create a Twitter Client class in the IDE:

  1. Choose File > New Project. Under Categories, select Java Web. Under Projects, select Web Application and click Next.

  2. In the Project Name field, type TwitterWebApp. Choose a location for the project. Click Next.

  3. Select the GlassFish and Java EE 6 or EE 5. Accept the default setting of the other options and click Finish.

  4. In the Projects window, right-click the TwitterWebApp node and select New > Other. The New File wizard opens, select the Web Services category. Select the RESTful Java Client file type, click Next...

  5. In the Class Name field, type TwitterClient. In the Package field, type twitter.

  6. In the Select the REST Resource section, select the IDE Registered radio button and click Browse:

  7. The Available REST Resources dialog opens. Browse for Twitter > Twitter OAuth > statuses > [friends_timeline.{format}] and click OK.

  8. The New RESTful Java Client dialog is now complete. Note that the Authentication field is automatically filled in with OAuth, which is an option for OAuth protocol. Click Finish.

  9. A dialog opens asking if you want to generate Java artifacts from XML Schema references in the WADL. Click Yes.

The TwitterClient class is generated and opens in editor. TheTwitterClient class is pretty complex and contain the followith fields, methods or inner classes:

  • CONSUMER_KEY : Consumer Key string
  • CONSUMER_SECRET : Consumer Sectret string
  • initOAuth(): method for OAuh intitialization
  • getFriendsTimeline(): method corresponding to HTTP method: getFriendsTimeline (from the REST resource) 
  • makeOAuthRequestUnique(): useful for multiple API calls in one session
  • OAuthLoginServlet: used to login to the Twitter Application (forces the authorization)
  • OAuthCallbackServlet:used by callback mechannism to redirect back the application flow after authorization

Register the New Twitter Application

If you want the web application to access Twitter data, you need to register the application in Twitter:

  1. Go to the Twitter > Applications page and click Register a new application » link to register a new Twitter Application.

  2. Type My First Web Application for Application Name text field.

  3. Type http://netbeans.org/OAuthCallback.php?callback_url=http://localhost:8080/TwitterWebApp/OAuthCallback for Callback URL field. 

  4. Type this URL: http://netbeans.org/OAuthCallback.php?callback_url=http://localhost:8080/TwitterWebApp for Application Website field.

  5. Make sure that the Browser radio button is selected for the Application Type option

  6. Leave other options default and press Save

Note: The http://netbeans.org/OAuthCallback.php is a workaround for the Twitter limitation, where the callback page can not be located at localhost. (http://localhost:8080/TwitterWebApp/OAuthCallback). The php simply redirects the output, together with all query parameters, to the URL specified by callback_url parameter. In real world you can setup the Callback URL to a real callback page (the page where the application flow should be redirected after authorization).

Copy the Consumer Key and Consumer Secret to your Application

After you successfully register your Twitter application you need to copy the Consumer Key and Consumer Secret keys from the Application Details page to your TwitterClient class. Edit the TwitterClient class and replace the CONSUMER_KEY and CONSUMER_SECRET fields with the values assigned for your Twitter application.


* Please, specify the consumer_key string obtained from service API pages
private static final String CONSUMER_KEY = "ABCDKPPOEOFMSrtB1r1kxQ";
* Please, specify the consumer_secret string obtained from service API pages
private static final String CONSUMER_SECRET = "ABCDi9Rf1JRwxeGnjPt6mo4UMoQESUUYjyukx58";

Write the Client Code

This is the client code written in index.jsp file :

<%@page contentType="text/html" pageEncoding="UTF-8" 
com.sun.jersey.api.client.UniformInterfaceException" %>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<h2>Friends Statuses</h2>
if (session.getAttribute("oauth_token") == null) {
} else {
TwitterClient twitter = new TwitterClient("xml");
twitter.initOAuth(request, response);
try {
Statuses resp =
Statuses.class, null, null, null, 100);
int i=0;
for (StatusType status : resp.getStatus()) {
out.println("<p>author: <b>"+status.getUser().getName()+
} catch (UniformInterfaceException ex) {
"Error = "+ex.getResponse().getEntity(String.class));
Note: The client code takes the oauth_token string from HTTP session, and checks it on null.
If null the response is redirected to OAuthLogin servlet, that forces the authorization. If not the oauth_token string is used to send the authorized request to Twitter API to get last 100 statuses (of your friends) from Twitter.

You may also modify the TwitterClient$OAuthCallbackServlet and append a link to the application root (index.jsp), when the application is successfully authorized:

if (uiEx == null) {
out.println("Now, you have successfully authorized this application to access your data.<br><br>");
out.println("Usage: <p><pre>");
out.println(" TwitterClient client = new TwitterClient(...);");
out.println(" client.initOAuth(httpServletRequest, httpServletResponse);");
out.println(" // call any method");
out.println(" client.close();");
out.println("<a href="/TwitterWebApp/">Go Home</a>");
} else {
out.println("Problem to get access token: " + uiEx.getResponse() + ": " + uiEx.getResponse().getEntity(String.class));

Run the Project

To run the project:

  1. Right-click the project's node in the Projects window. Select Deploy from the context menu. The IDE builds your project, starts the application server, and deploys the project to the application server.

  2. Right-click the project's node again and select Run, which should result in the following:


{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks