Milan has posted 4 posts at DZone. View Full User Profile

OAuth Support in NetBeans IDE 6.9

  • submit to reddit

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 for Callback URL field. 

  4. Type this URL: 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 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:


Published at DZone with permission of its author, Milan Kuchtiak.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)


Umer Farooq replied on Tue, 2010/06/01 - 4:58am

really nice tutorial will it support PHP in netbeans also or only java

Milan Kuchtiak replied on Tue, 2010/06/01 - 5:22am in response to: Umer Farooq

 Now only Java clients. The support is based on Jersey Client and Jersey OAuth, which are Java libraries.

Pascal Fares replied on Thu, 2010/06/03 - 3:54pm

What about Google Apps OAth?

Milan Kuchtiak replied on Tue, 2010/06/08 - 9:05am


Theoretically - if Google supports OAuth1.0 it should be possible to register Google Apps in IDE, but I haven't tested.  I haven't tested Google Apps.

Kartheek Reddy replied on Fri, 2010/08/27 - 12:21am

gud 1 . . very helpful . .

Toni Epple replied on Wed, 2010/10/13 - 11:00am

I'm trying to write a NB Platform based client. Registered it as an aplication with read/write access.

ReadingTimelines works fine, but when I'm trying tosend a status update I get through sometimes (twice so far, but most of the time the Basic authenticator pops up asking for my credentials. Any idea why that happens, or what I can do about it?


My calls look like this:

UpdateStatusClient client = new UpdateStatusClient("xml");
client.updateStatus(Object.class, "Testing my NetBeans based Twitter client", null); 



Dan Becker replied on Thu, 2010/12/09 - 3:30am

Excellent & very helpful article! Thanks!

One tip - line 11 in TwitterClient$OAuthCallbackServlet needs to have the two double quotes in the a href tag escaped out by preceding them with a \ (backslash).

Instead of a href="/TwitterWebApp/" it needs to be a href=\"/TwitterWebApp/\"

Username Koko replied on Sat, 2011/01/01 - 10:20pm

I have a problem in using statuses/friends

My code is the same as in the tutorial but using the statuses/friends resource:

Statuses statuses = twitter.getFriendsStatuses(Statuses.class, null, null); 
for (StatusType statusType : statuses.getStatus()) {
  UserType userType = statusType.getUser();
  out.println("<p>" + userType.getName() + "</p>");
but i get this error :
javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"users"). 
Expected elements are <{}statuses> 

Username Koko replied on Sun, 2011/01/02 - 4:19am

there is a mistake in the statuses/friends in the twitter restful class client:

String resourcePath = java.text.MessageFormat.format("statuses/friends.{0}", new Object[]{format});

The format should be something like  :

String resourcePath = java.text.MessageFormat.format("users/friends.{0}", new Object[]{format});

because the default return type of this method in twitter returns an array of users

So you will always get this error:

javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"user"). Expected elements are <{}statuses>
Any suggestions? 


Carla Brian replied on Sun, 2012/04/08 - 6:14pm

OAuth is an authentication protocol that allows users to approve application to act on their behalf without sharing their password. - Paul Perito

Carla Brian replied on Sun, 2012/04/08 - 6:16pm

I love their new features. It is really good. I need more practice on this. - Marla Ahlgrimm

Matt Coleman replied on Thu, 2012/04/26 - 12:45am

graphic artist buffalo hase benefited using netbeans

Mateo Gomez replied on Fri, 2012/04/27 - 2:01am in response to: Carla Brian

mexican dessert loves it too..we need to practice more

Chege Kinuthia replied on Thu, 2013/03/14 - 2:13pm

 Am getting the following error

OAuth Login Servlet at /twitterwebapp Problem to get request token: GET returned a response status of 301 Moved Permanently:

what could be the problem?

Cata Nic replied on Tue, 2013/09/03 - 3:26am

 Is it safe enough this application? I mean... I have some doubts that my twitter account can be accessed by a hacker via this authentication access. 

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.