OAuth Support in NetBeans IDE 6.9
Join the DZone community and get the full member experience.
Join For FreeOAuth 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:
- Choose File > New Project. Under Categories, select Java Web. Under Projects, select Web Application and click Next.
- In the Project Name field, type TwitterWebApp. Choose a location for the project. Click Next.
- Select the GlassFish and Java EE 6 or EE 5. Accept the default setting of the other options and click Finish.
- 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...
- In the Class Name field, type TwitterClient. In the Package field, type twitter.
- In the Select the REST Resource section, select the IDE Registered radio button and click Browse:
The Available REST Resources dialog opens. Browse for Twitter > Twitter OAuth > statuses > [friends_timeline.{format}] and click OK.
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.
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:
- Go to the Twitter > Applications page and click Register a new application » link to register a new Twitter Application.
- Type My First Web Application for Application Name text field.
- Type http://netbeans.org/OAuthCallback.php?callback_url=http://localhost:8080/TwitterWebApp/OAuthCallback for Callback URL field.
- Type this URL: http://netbeans.org/OAuthCallback.php?callback_url=http://localhost:8080/TwitterWebApp for Application Website field.
- Make sure that the Browser radio button is selected for the Application Type option
- 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.
Example:
/**
* 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"Note: The client code takes the oauth_token string from HTTP session, and checks it on null.
import="twitter.TwitterClient,
twitter.twitteroauth.twitterresponse.*,
com.sun.jersey.api.client.UniformInterfaceException" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h2>Friends Statuses</h2>
<%
if (session.getAttribute("oauth_token") == null) {
response.sendRedirect("OAuthLogin");
} else {
TwitterClient twitter = new TwitterClient("xml");
twitter.initOAuth(request, response);
try {
Statuses resp =
twitter.getFriendsTimeline(
Statuses.class, null, null, null, 100);
int i=0;
for (StatusType status : resp.getStatus()) {
out.println("<p>author: <b>"+status.getUser().getName()+
"</b>("+status.getCreatedAt()+")</p>"+
"<p><tt>"+status.getText()+"</tt></p>");
}
} catch (UniformInterfaceException ex) {
System.out.println(
"Error = "+ex.getResponse().getEntity(String.class));
}
twitter.close();
}
%>
</body>
</html>
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("</pre></p>");
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:
- 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.
- Right-click the project's node again and select Run, which should result in the following:
Opinions expressed by DZone contributors are their own.
Trending
-
Five Java Books Beginners and Professionals Should Read
-
DevOps Midwest: A Community Event Full of DevSecOps Best Practices
-
Database Integration Tests With Spring Boot and Testcontainers
-
Building the World's Most Resilient To-Do List Application With Node.js, K8s, and Distributed SQL
Comments