Minggu, 23 September 2012

Introduction to Web Services

Introduction to Web Services

This document provides an overview of web service concepts and technologies supported by NetBeans IDE. It is meant to help newcomers to web services before they use any tutorials.
Web services are distributed application components that are externally available. You can use them to integrate computer applications that are written in different languages and run on different platforms. Web services are language and platform independent because vendors have agreed on common web service standards.
Oracle is developing a java.net project called Metro. Metro is a complete web services stack, covering all of a developer's needs from simple "Hello, World!" demonstrations to reliable, secured, and transacted web services. For more information, see the Metro home page.
Metro includes Web Services Interoperability Technologies (WSIT). WSIT supports enterprise features such as security, reliability, and message optimization. WSIT ensures that Metro services with these features are interoperable with Microsoft .NET services. Within Metro, Project Tango develops and evolves the codebase for WSIT. To see how WSIT works, use the Advanced Web Service Interoperability tutorial.
Several programming models are available to web service developers. These models fall into two categories, both supported by the IDE:
  • REST-based. REpresentational State Transfer is a new way to create and communicate with web services. In REST, resources have URIs and are manipulated through HTTP header operations. For more details, see RESTful Web Services.
  • SOAP/WSDL-based. In traditional web service models, web service interfaces are exposed through WSDL documents (a type of XML), which have URLs. Subsequent message exchange is in SOAP, another type of XML document. For more details, see SOAP-based Web Services.

RESTful Web Services

REST-based ("RESTful") web services are collections of web resources identified by URIs. Every document and every process is modeled as a web resource with a unique URI. These web resources are manipulated by the actions that can be specified in an HTTP header. Neither SOAP, nor WSDL, nor WS-* standards are used. Instead, message exchange can be conducted in any format—XML, JSON, HTML, etc. In many cases a web browser can serve as the client.
HTTP is the protocol in REST. Only four methods are available: GET, PUT, POST, and DELETE. Requests can be bookmarked and responses can be cached. A network administrator can easily follow what is going on with a RESTful service just by looking at the HTTP headers.
REST is a suitable technology for applications that do not require security beyond what is available in the HTTP infrastructure and where HTTP is the appropriate protocol. REST services can still deliver sophisticated functionality. Flickr, Google Maps and Amazon all provide RESTful web services. NetBeans IDE Software as a Service (SaaS) functionality lets you use Facebook, Zillow, and other third-party-provided services in your own applications.
Project Jersey is the open source reference implementation for building RESTful web services. The Jersey APIs are available as the "RESTful Web Services" plugin for NetBeans IDE.
The following tutorials involve creating and consuming REST services:

SOAP-based Web Services

In SOAP-based web services, Java utilites create a WSDL file based on the Java code in the web service. The WSDL is exposed on the net. Parties interested in using the web service create a Java client based on the WSDL. Messages are exchanged in SOAP format. The range of operations that can be passed in SOAP is much broader than what is available in REST, especially in security.
SOAP-based web services are suitable for heavyweight applications using complicated operations and for applications requiring sophisticated security, reliability or other WS-* standards-supported features. They are also suitable when a transport protocol other than HTTP has to be used. Many of Amazon's web services, particularly those involving commercial transactions, and the web services used by banks and government agencies are SOAP-based.
The Java API for XML Web Services (JAX-WS) is the current model for SOAP-based web services in Metro. JAX-WS is built on the earlier JAX-RPC model but uses specific Java EE 5 features, such as annotations, to simplify the task of developing web services. Because it uses SOAP for messaging, JAX-WS is transport neutral. It also supports a wide range of modular WS-* specifications, such as WS-Security and WS-ReliableMessaging.
Note: Although we strongly recommend using the JAX-WS model for creating SOAP services, the IDE continues to support JAX-RPC web services for legacy reasons. Install the "JAX-RPC Web Services" plug-in to develop them.
When you create a web service client, you have the option of using either the JAX-WS or JAX-RPC model. This is because some older JAX-RPC services use a binding style that is not supported by JAX-WS. These services can only be consumed by JAX-RPC clients.
The following tutorials involve creating and consuming JAX-WS SOAP-based web services:

Creating a Graphical Client for Twitter

Creating a Graphical Client for Twitter

In this tutorial, you use the NetBeans IDE to create a simple, graphical, REST-based client that displays Twitter friends timeline messages and lets you view and update your Twitter status. The application uses Swing and NetBeans IDE's support for Twitter's SaaS operations.
Running client displaying Twitter messages If you do not have a Twitter account, go to twitter.com and create an account before proceeding with this tutorial.
A complete sample of this application is available for download. Click here to download the sample.
Contents
Content on this page applies to NetBeans IDE 6.9-7.1 To complete this tutorial, you need the following software and resources.
Software or Resource Version Required
NetBeans IDE Java EE download bundle
Java Development Kit (JDK) Version 6 or version 7
User name and password for a Twitter account

Designing the JFrame

In this step you create the GUI elements that will display the Twitter friends timeline, your user icon, and where you read and update your status. The GUI elements are all wrapped in a JFrame. You do not have to lay out the GUI elements exactly as described in this section. This layout is a suggestion only. For example, you may add more functionality. However you need to create at least all the elements described in this tutorial.
To design the JFrame:
  1. Choose File > New Project. The New Project wizard opens. Select the Java category, then a Java Application project. Click Next.
  2. Name the project TwitterSwingClient. Select a Project Location. Unselect Create Main Class. (The JFrame will be the main class.) Click Finish.
    New Project wizard showing fields for creating the TwitterSwingClient project
  3. The IDE creates the TwitterSwingClient project, which appears in the Projects window. Right-click the TwitterSwingClient project node and choose New > JFrame Form (or New > Other > Swing GUI Forms > JFrame Form). The New JFrame Form wizard opens.
  4. Name the form TwitterJFrame and create a package for it called twitterclient. Click Finish.
    New JFrame Form wizard showing fields for creating TwitterJFrame
  5. The IDE opens TwitterJFrame in the editor, in the Design view. Here you have a palette of all the Swing components you can drag and drop into the JFrame.
    Twitter J Frame in the Design view of the Editor
  6. Click on the Button icon under Swing Controls in the Palette. Drag and drop it into the bottom right corner of the JFrame. Note that the button displays jButton1, which is the name of this JButton object.
    JFrame showing newly added jButton1
  7. Right-click jButton1 and select Edit Text from the context menu. Change the display text to "Update."
  8. Drag and drop a Label (jLabel1) to the bottom left corner of the JFrame. Change its display text to "Icon." Your user icon will be displayed in this label.
  9. Drag and drop a Text Field (jTextField1) between the Label and the Button. Change its display text to "Status." Click on the right border of the text field and stretch it across towards the button. Blue guidelines appear showing you suggested distances from the button.
  10. Right-click on jLabel1 and select Properties from the context menu. The jLabel1 Properties dialog opens. Set the labelFor property to point to jTextField1. (This increases accessibility.)
  11. Find the properties Maximum Size, Minimum Size, and Preferred Size. Set each of these properties to [48,48], to match the 48px X 48px dimensions of Twitter icons.
    Properties of j Label 1 in Twitter J Frame, showing Maximum, Minimum, and Preferred sizes set to 48, 48
  12. Drag and drop a Scroll Pane into the upper part of the JFrame. Drag its borders to expand it to fill most or all of the space above the text field and button. (You may leave a margin if you want to add more functionality later, such as the menu in the sample.)
  13. Drag and drop a List into the Scroll Pane. A sample list of items appears. Save TwitterJFrame. The JFrame should look like the following image:
    Twitter J Frame in the Design view, with all basic GUI elements
You now have all the basic GUI components for the Swing client. It is time to add the first Twitter SaaS (Software as a Service) operation.

Showing Your User Status

In this section you create a new method and add the Twitter getUserTimeline operation to this method. The getUserTimeline operation gets your user icon and your current status. You then add code to the method to display your icon and status in jLabel1 and jTextField, respectively. Finally you add a line to the JFrame's constructor to initialize the method.
To show your user status:
  1. Switch to the Source view of TwitterJFrame.
  2. Press Alt-Insert, or right-click and select Insert Code from the context menu. A menu of code to insert opens.
    Important: If the Generate REST Client option does not appear, Java EE support is either not installed or not activated. Go to Tools > Plugins, open the Installed tab, and check that Java Web and EE support is present and activated. If Java Web and EE support is not listed, open the Available Plugins tab and install it. If you do not want to install or activate all Java Web and EE support, you can install and activate only RESTful Web Services support.
    Menu of code to insert in initUserInfo method
  3. Click Generate REST Client. The Available REST Resources dialog opens.
    Available REST Resources dialog
  4. Select the IDE Registered radio button and click Browse. Navigate to Twitter > Twitter OAuth > [statuses] > [user_timeline.{format}]. Click OK.
    Services window with Web Services tree showing Twitter getUserTimelineById operation chosen
  5. The Available REST Resources dialog now shows the selected Twitter OAuth user_timeline resource, the corresponding class name, and OAuth authentication type. Click OK.
    Filled out Available REST Resource dialog
  6. A dialog opens asking if you want to generate Java objects from the XML schema references in the WADL file. Click Yes.
  7. At the end of the TwitterJFrame class, the IDE generates an internal class called Twitter_OAuth_user_timeline__format_JerseyClient. The internal class is complex and contains the following fields, methods and inner classes:
    • CONSUMER_KEY: Consumer Key string
    • CONSUMER_SECRET: Consumer Sectret string
    • initOAuth(): method for OAuh intitialization
    • getUserTimeline(): method corresponding to HTTP method: getUserTimeline (from the REST resource)
    • makeOAuthRequestUnique(): useful for multiple API calls in one session
    • login: used to login to the Twitter Application (forces the authorization). This method calls two more generated methods, getOAuthAccessToken and getOAuthRequestToken.
    Here is the class structure as shown in the Navigator window.
    Navigator window showing Twitter_OAuth_user_timeline__format_JerseyClient class
  8. In TwitterJFrame immediately above the internal Twitter_OAuth_user_timeline__format_JerseyClient class, insert the following line of code. This code creates a variable called client to represent an instance of the internal class.
    private Twitter_OAuth_user_timeline__format_JerseyClient client;
    Code snippet showing client variable immediately above internal class
  9. Locate the main method in TwitterJFrame. Above this method, create a new method called initUserInfo that throws a MalformedURLException and an IOException.
    private void initUserInfo() throws MalformedURLException, IOException {
    
    
    
    }
  10. Insert the following code into the method body of initUserInfo. Comments in the code explain what the code does.
    private void initUserInfo() throws MalformedURLException, IOException {
    
    
        //Create an instance of the internal service class
        client = new Twitter_OAuth_user_timeline__format_JerseyClient("xml");
    
    
        //Log in, get tokens, and append the tokens to the consumer and secret
        //keys
        client.login();
        client.initOAuth();
    
    
        //Call getUserTimeline, get a list of statuses, pass the most recent
        //status as a StatusType object, and display the text of that object
        //in the JTextField
        Statuses statuses = client.getUserTimeline(Statuses.class, null, null, null, "1");
        StatusType st = statuses.getStatus().get(0);
        jTextField1.setText(st.getText().trim());
    
    
        //Get a UserType object from the StatusType object, get the URL of that
        //user's icon, and display that icon in the JLabel
        UserType user = st.getUser();
        String iconSrc = user.getProfileImageUrl();
        URL iconUrl = new URL(iconSrc);
        ImageIcon icon = new ImageIcon(iconUrl, user.getScreenName());
        jLabel1.setIcon(icon);
    }
  11. Open the Fix Imports dialog (Ctrl/⌘-Shift-I, or from context menu). In the dialog, select twitter.twitteroauth.twitterresponse.StatusType and not the default Java StatusType class.
    Fix Imports dialog after completing initUserInfo method
  12. Add a try/catch block to the TwitterJForm constructor to call initUserInfo when the application runs. Fix Imports after adding the try/catch block.
    public TwitterJFrame() {
        initComponents();
    
        try {
            initUserInfo();
        } catch (IOException ex) {
            Logger.getLogger(TwitterJFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
     }
After you get OAuth keys from Twitter, you can run the project. Right-click the project node and select Run from the context menu. An application opens showing your user icon and status.

Getting OAuth Keys from Twitter

In order for the Java application to access Twitter data, you need to get CUSTOMER and CUSTOMER_SECRET keys, along with a verification string, from Twitter. Twitter uses OAuth authorization, which requires these keys. However, OAuth is set up with the expectation that it will be called by a web application on a server. In order to get the authorization keys, you register a "dummy" web application.
To get the OAuth keys from Twitter:
  1. Open a browser. Go to the Twitter > Applications page and click Register a new application. You need to be logged into a Twitter account. Make sure you are logged into the correct account, if you have multiple accounts.
  2. Type an arbitrary name in the Application Name text field. Application names need to be unique across Twitter.
  3. Type a description into the Description field. This is required. You can type something like "Java application created in NetBeans IDE calling the user_timeline operation."
  4. Type an arbitrary URL into the Application Website field.
  5. In the Application Type option, select the Client radio button.
  6. In the Default Access Type section, select the Read & Write button.
    Caution: Be certain you select Read & Write. Although you can go back and edit your settings later, this does not seem to affect your application's access privileges.
  7. Leave other options default and press Save. A browser page opens with the details of the application you registered. The important details are the Consumer key and Consumer secret.
  8. Copy the Consumer key from the browser. In the IDE, locate the line where CONSUMER_KEY is set. Paste the value of the consumer key between the quotation marks.
    TwitterClient showing CONSUMER_KEY and CONSUMER_SECRET location
  9. Copy and paste the Consumer secret key from the browser into TwitterSwingClient. Save your changes.

Running the Project

Now that you have the Consumer key and Consumer secret key, you can run the project. The application calls Twitter, which opens a browser window for you to allow the application to access data.
To run the project:
  1. Right-click the TwitterSwingClient project node and select Run from the context menu.
  2. A browser window opens asking if you want to allow your registered application to access your Twitter data. Click Allow.
  3. The browser window updates to a new window showing you a PIN. Copy this PIN.
  4. In the IDE, the output window shows a request that you type the oauth_verifier string. Paste the PIN after the colon : and press Enter.
    Output window in IDE asking for verifier string, which has not yet been pasted
  5. The desktop client opens, displaying your latest Twitter status message.
    Running application, showing user icon and status

Calling Multiple Services

The final design of the application requires calls to three Twitter services: user_timeline{format} (already called), update{format}, and friends_timeline{format}. The calls to these services need to share one login. For the calls to share the same login, they must be in the same client class. Calling multiple services from one client requires two steps:
  • Add multiple services to one client class.
  • Modify the resource paths in the client class

Adding services and combining calls to one class

In this section you first add clients for the other services and merge them into one general client.
To add multiple services:
  1. Press Alt-Insert and select Generate REST Client.
    Menu of code to insert in initUserInfo method
  2. Follow the same procedure to generate a REST client that you followed in the section Showing Your User Status, but select the [statuses] > [update.{format}] service. The IDE generates the internal class Twitter_OAuth_update__format_JerseyClient, which is similar to the Twitter_OAuth_user_timeline__format_JerseyClient class.
    The Available REST Resources dialog showing the update format service
  3. Repeat steps 1 and 2 above, but add a client for the [friends_timeline.{format}] service.
  4. Change the name of the original Twitter_OAuth_user_timeline__format_JerseyClient class. You will make this the general client class that calls all 3 services. Select an instance of the name Twitter_OAuth_user_timeline__format_JerseyClient and press Ctrl-R, or right-click and select Refactor > Rename. The Rename Class dialog opens. Type in the new name TwitterClient.
    Rename Class dialog with new name TwitterClient
  5. Click Refactor. The IDE replaces all instances of the class name.
    Class name changed in multiple places
  6. In the Navigator window, locate the Twitter_Oauth_friends_timeline__format_JerseyClient class. In that class, locate and double-click the getFriendsTimeline method.
    Navigator window showing the getPublicTimeline method
  7. The cursor in the Editor moves to the getFriendsTimeline method. Cut that method (reproduced below).
    public <T> T getFriendsTimeline(Class<T> responseType, String since, String since_id, String page, String count) throws UniformInterfaceException {
          String[] queryParamNames = new String[]{"since", "since_id", "page", "count"};
          String[] queryParamValues = new String[]{since, since_id, page, count};
          return webResource.queryParams(getQueryOrFormParams(queryParamNames, queryParamValues)).accept(javax.ws.rs.core.MediaType.TEXT_XML).get(responseType);
    }
  8. Paste the getFriendsTimeline method into the TwitterClient internal class, below the getUserTimeline method.
  9. Cut and paste the updateStatus method from Twitter_OAuth_update__format_JerseyClient into TwitterClient, below the getFriendsTimeline method.

Modifying the resource paths

All the Twitter service calls are now in one client class. However, the resource paths in that client class are not constructed correctly. The IDE generated resource paths specific for the user_timeline service when it originally generated the class. You need to modify the class so that at the class level, the resource path is generic, and specific paths are assigned by the service call methods.
To modify the resource paths:
  1. Locate the TwitterClient constructor and remove the String format parameter.
    Before and after view of removing parameter from constructor
  2. A red error bar appears in the right margin. Click it, and you go to the line in initUserInfo that instantiates the TwitterClient class. This line is client = new TwitterClient("xml");. Delete the parameter "xml", because the TwitterClient constructor no longer takes it. The line now is client = new TwitterClient();. The error icons disappear.
  3. Return to the TwitterClient constructor. (The Navigator window can help you.) Locate the following line:
    String resourcePath = java.text.MessageFormat.format("statuses/user_timeline.{0}", new Object[]{format}); 
    This line sets the resourcePath for the entire class. Change the line so that resourcePath points to the parent statuses directory. The line now reads:
    String resourcePath = "statuses";
  4. Navigate to the getUserTimeline method. Locate the return line:
    return webResource.queryParams(getQueryOrFormParams(queryParamNames, queryParamValues))...;
    Append path information (in boldface, below) to the beginning of the call.
    return webResource.path("user_timeline.xml").queryParams(getQueryOrFormParams(queryParamNames, queryParamValues)).accept(javax.ws.rs.core.MediaType.TEXT_XML).get(responseType);
  5. Navigate to the getFriendsTimeline method. Locate the return line:
    return webResource.queryParams(getQueryOrFormParams(queryParamNames, queryParamValues)).accept(javax.ws.rs.core.MediaType.TEXT_XML).get(responseType);
    Append path information to the beginning of the call.
    return webResource.path("friends_timeline.xml").queryParams(getQueryOrFormParams(queryParamNames, queryParamValues)).accept(javax.ws.rs.core.MediaType.TEXT_XML).get(responseType);
    
                  
  6. Navigate to the updateStatus method. Locate the return line:
    return webResource.type(javax.ws.rs.core.MediaType.APPLICATION_FORM_URLENCODED)...
    Append path information to the beginning of the call.
    return webResource.path("update.xml").type(javax.ws.rs.core.MediaType.APPLICATION_FORM_URLENCODED).post(responseType, getQueryOrFormParams(formParamNames, formParamValues));
  7. Locate and comment out the TwitterClient's setResourcePath method. It is not ever called, but this is a precaution.
  8. Delete the classes Twitter_OAuth_update__format_JerseyClient and Twitter_Oauth_friends_timeline__format_JerseyClient.
You now have all three services available from the JerseyClient class.
Important: You change three return statements in three methods in the procedure above. Make sure you change all three!

Adding an Update Status Action

  1. Return to the Design view of TwitterJFrame. Double-click the Update button in the JFrame. The editor switches back to the Source view, in the body of the jButton1ActionPerformed method, which the IDE just created for you.
    TwitterJFrame in Source view, with cursor in middle of newly created jButton1ActionPerformed method
  2. Fill in the jButton1ActionPerformed method body as follows:
    Caution: When you update your status, it will appear UTF-8-encoded, with spaces either as + signs or %21 symbols, etc. However, if you do not convert the text field contents to UTF-8, the application will fail with "Invalid signature" if you type any spaces in your status message! If anyone finds a way around this, please use the Feedback link at the bottom of the tutorial to contact us.
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        String rawStatus = jTextField1.getText().trim();
        String status = URLEncoder.encode(rawStatus, "UTF-8");
        client.makeOAuthRequestUnique();
        try {
        client.updateStatus(String.class, status, null);
        } catch(UniformInterfaceException ex) {
            System.out.println("Exception when calling updateStatus = " + ex.getResponse().getEntity(String.class));
        }
    
    }    
This code gets the text from the text field and passes it to the updateStatus class. Note the call to makeOAuthRequestUnique. The code calls this method because the application is already logged in and authenticated by the calls to login and initOAuth from initUserInfo when the application initialized. The makeOAuthRequestUnique method increases existing OAuth nonce and timestamp parameters to make each request unique.
Caution: It is not entirely clear if it is better to call makeOAuthRequestUnique or initOAuth here. If you experience authentication issues, please experiment with both forms.
Also note that the call to updateStatus is wrapped in a try/catch block. This helps you debug any issues that could arise when you call updateStatus.

Displaying Usernames and Statuses in the JFrame

Now you set up the application to display the usernames and statuses of your Twitter friends.
  • To get the usernames and statuses from Twitter, the application calls the Twitter getFriendsTimeline operation when the application runs. To set this up, create a new run method that overrides the run method in main. Insert calls to getFriendsTimeline into this method.
  • To have the display update automatically, wrap the run method containing the getFriendsTimeline operation in a java.util.TimerTask that executes the run method every 75 seconds.
  • The application displays the data as cells in a list. You need to pass the data into GUI components that can be rendered as cells in the list, and you also want to format the display of the data. To accomplish this, create a new JPanel that implements javax.swing.ListCellRenderer. This JPanel returns a java.awt.Component object with the username and status passed in JLabels. Tweak the format of the JPanel.
  • In TwitterJFrame, set up the JList to display the Component objects returned by the JPanel.

Creating a TimerTask

To update the display of the Twitter friends timeline automatically, wrap the execution code in a TimerTask. Write the TimerTask wrapper first and then fill it in with execution code. Otherwise your code will be full of error warnings.
To create the TimerTask:
  1. Open TwitterJFrame in the Sources view of the editor.
  2. Find the class declaration and the constructor.
    public class TwitterJFrame extends javax.swing.JFrame {
    
        /** Creates new form TwitterJFrame */
        public TwitterJFrame() {
            initComponents();
            try {
                initUserInfo();
            } catch (IOException ex) {
                Logger.getLogger(TwitterJFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
  3. In the method body of the constructor, above initComponents();, instantiate the java.util.Timer class. The parameters name the Timer thread "Twitter Updater" and specify that it cannot be run as a daemon.
    public class TwitterJFrame extends javax.swing.JFrame {
    
        /** Creates new form TwitterJFrame */
        public TwitterJFrame() {
            Timer t = new Timer("Twitter Updater`", false);
            initComponents();
            try {
                initUserInfo();
            } catch (IOException ex) {
                Logger.getLogger(TwitterJFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
                        
  4. Right-click anywhere in the editor and select Fix Imports from the context menu, or press Ctrl/⌘-Shift-I. A dialog opens and gives you a choice of classes to import. Add an import statement for java.util.Timer.
  5. Below the instantiation of Timer, create a new Timer.scheduleAtFixedRate method. The method's parameters are a TimerTask object, the delay before it first runs the task, and the frequency with which it runs the task. Set the method to wait 30 seconds before running the first time and run again every 75 seconds. (The long initial delay is to give you time to log in.) The exact code follows, in bold. An empty line is left where you put the execution code. Note that you have to add an import statement for java.util.TimerTask.
    public class TwitterJFrame extends javax.swing.JFrame {
    
        /** Creates new form TwitterJFrame */
        public TwitterJFrame() {
            Timer t = new Timer("Twitter Updater`", false);
            t.scheduleAtFixedRate(new TimerTask() {
    
    
            }, 30000, 75000);
            initComponents();
            try {
                initUserInfo();
            } catch (IOException ex) {
                Logger.getLogger(TwitterJFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
         }
The TimerTask wrapper code is now complete. Next you add the execution code.

Adding a run Method With the getFriendsTimeline Operation

To display usernames and statuses, the application first gets this data from Twitter. Twitter SaaS provides the getFriendsTimeline operation for getting usernames and statuses. To execute the getFriendsTimeline operation when the application runs, the operation needs to be inside a run method. Finally, because the application displays the usernames and statuses in a JList, the application needs to add the results of getFriendsTimeline as elements of a DefaultListModel object.
To add a run method with the getFriendsTimeline operation:
  1. Above the TwitterJFrame constructor, create a DefaultListModel object named statusesListModel.
    public class TwitterJFrame extends javax.swing.JFrame {
    
        private DefaultListModel statusesListModel = new DefaultListModel();
    
    
        /** Creates new form TwitterJFrame */
        public TwitterJFrame() {
                        
  2. Right-click anywhere in the editor and select Fix Imports from the context menu, or press Ctrl/⌘-Shift-I. This action adds an import statement for DefaultListModel.
  3. In the body of the TimerTask object, create a new run method. Use the @Override annotation to override the run method in main.
    public class TwitterJFrame extends javax.swing.JFrame {
    
        private DefaultListModel statuses = new DefaultListModel();
    
    
    
    
    
        /** Creates new form TwitterJFrame */
        public TwitterJFrame() {
            Timer t = new Timer("Twitter Updater`", false);
            t.scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run(){
                 
                }
            }, 1500, 75000);
            initComponents();
            try {
                initUserInfo();
            } catch (IOException ex) {
                Logger.getLogger(TwitterJFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        
  4. Insert the following code into the body of the run method.
    @Override
    public void run() {
        System.out.println("Timer Task is running");
        try {
            client.initOAuth();
            Statuses response = client.getFriendsTimeline(Statuses.class, null, null, null, "10");
            // Clear the list model so it does not replicate the contents from the last run
            statusesListModel.clear();
            // Create a Status Type object for every status in the Status list, and add an element
            // to the list model for every status type object
            for (final StatusType st : response.getStatus()) {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        statusesListModel.addElement(st);
                    }
                });
            }
        } catch (UniformInterfaceException ex) {
        System.out.println("Exception when calling getFriendsTimeline = " + ex.getResponse().getEntity(String.class));
        }
    }
The code for getting statuses from the Twitter friends timeline is now complete. Next you write a new class that returns a Component with list elements rendered in GUI components.

Creating a List Cell Rendering Component

Now you have code that gets Status objects from the Twitter Friends Timeline and creates a list element for each status. However, you cannot display these raw list elements in a JList. You need to pass the data into GUI components . To accomplish this, create a new JPanel that implements javax.swing.ListCellRenderer. This JPanel returns a java.awt.Component object with the username and status passed in JLabels. You can customize the appearance of the JLabels in the JPanel.
To add a list cell rendering Component:
  1. Right-click the project's node and choose New > JPanel Form. The New JPanel Form wizard opens.
  2. Name the JPanel Item and place it in the twitterclient package.
    New JPanel Form wizard showing panel named Item and package twitterclient
  3. Click Finish. Item.java opens in the Design view of the editor.
  4. Drag and drop a Label and a Text Pane into the JPanel. The Label will display the username and the Text Pane will display that user's status message.
  5. Position the Label and the Text Pane to match how you want the data to be displayed. In the following image, the username is on the left top while the status text is below and slightly indented. The sample project has the data on the top left and the username on the bottom right. Leave enough empty space in the JPanel below the Text Pane for the Text Pane to expand when it contains longer text.
    Layout of jlabels displaying username and status text
  6. Right-click on the JLabel element and select Properties from the context menu. In the Properties, you can change the font, the color, the alignment and other qualities. Set the labelFor property to point to jTextPane1. This improves accessibility. Experiment with the properties of the label until you like the appearance. In the following image, the font color is set to blue in the Foreground property.
    JLabel properties dialog with Foreground set to blue
  7. Open the Properties dialog of the JTextPane and experiment with its appearance.
  8. Change to the Source view for Item.java. Find the Generated Code block and expand it. This shows you the code generated by the IDE when you set the properties of the JLabel and JTextPane. In the following image, note the blue color setting for JLabel1. Can you see what properties are set for the JTextPane?
    Code generated in Item.java by setting JLabel properties in the Design view
  9. Find the class declaration and add the code implements ListCellRenderer.
    public class Item extends javax.swing.JPanel implements ListCellRenderer {
  10. Press Ctrl-Shift-I (⌘-Shift-I on MacOS). This action adds an import statement for javax.swing.ListCellRenderer. A warning appears saying that you need to implement all abstract methods.
  11. Add a few empty lines between the generated code block and the variable declarations. Into that space, add the following code, which implements the abstract method getListCellRendererComponent. (You can copy and paste the code, or you can try to reproduce it with code completion.) This code replaces the default label texts "username" and "text" with the Text, User, and ScreenName objects you get with the twitteroauth StatusType class. The code then returns an instance of Component with these new JLabel text values.
    public Component getListCellRendererComponent(JList list, Object value, int index, boolean sel, boolean focus) {
            StatusType st = (StatusType) value;
            jTextPane1.setText(st.getText());
            jLabel1.setText("<html>" + st.getUser().getScreenName() + "</html>");
            return this;
    }
  12. Press Ctrl-Shift-I (⌘-Shift-I on MacOS). This adds import statements for the StatusType and Component classes. Select the twitteroauth version of StatusType. Save Item.java.
Now you have an Item class that returns a Component object with username and status displayed in a JLabel and a JTextPane. Next you modify TwitterJFrame to use this Component.

Displaying the Component in TwitterJFrame

In order to display the Component object created in Item.java, the JList in TwitterJFrame has to use Item.java as its cell renderer.
  1. Return to TwitterJFrame. In the Design view, select the JList. Right-click and open its Properties.
    Properties dialog for the JList element in TwitterJFrame
  2. Select the model property. Press Ctrl-Space. The custom property editor opens, showing the default text displayed in the list.
    J list custom property editor
  3. In the "Set jLlist1's model property using:" drop-down menu, select Custom Code. A text field appears where you type in the properties for jLabel1.setModel. Type statusesListModel in the field and click OK.
    jList custom property editor showing setModel(statuses) chosen in the cusom code editor
  4. In the Properties dialog, select cellRenderer and press Ctrl-Space. The custom property editor opens.
  5. In the "Set jList1's cellRenderer property using:" drop-down menu, select Custom Code. A text field appears where you type in the properties for jList1.cellRenderer. Type new Item() and click OK.
    J List custom cell renderer properties editor showing new Item chosen
Your client application is now complete! Save all files and run the application. (Right-click project node and select Run.) The application opens, showing a list of timeline messages and a field with your own status.
Running client displaying Twitter messages

Connecting Through a Proxy;

If you are connected to the Internet through a proxy, you need to configure both the IDE and your TwitterSwingClient project to use the proxy settings.
To configure the IDE, open Tools > Options > General. Locate the Proxy Settings section. You have the options of using no proxy settings, using the system proxy settings, or using manual proxy settings. The IDE gets your system proxy settings from your default system web browser.
For the TwitterSwingClient project, you need to specify the proxy that the HTTP protocol handler uses. This is described in Java SE 6 documentation. You specify the proxy in options passed to the virtual machine. With the NetBeans IDE, these options are set in the Properties dialog.
To specify the proxy for the TwitterSwingClient project:
  1. In the Projects window, right-click your TwitterSwingClient project node and select Properties. The Properties dialog opens.
  2. In the Categories tree, select Run. The Run properties display.
  3. In the VM Options field, enter -Dhttp.proxyHost=server -Dhttp.proxyPort=port. Replace "server" and "port" with the host name and port of your proxy server!
    Proxy settings in VM options in Project properties dialog

More Exercises

Here are a few more ideas for you to explore:
  • Change your Twitter user icon (in a browser) and run the client again. Does the new icon appear?
  • Add a toolbar with some functions to the JFrame.

See Also

For more information about using NetBeans IDE to create and consume web services and to design GUIs, see the following resources:
To send comments and suggestions, get support, and keep informed about the latest developments on the NetBeans IDE Java EE development features, join  the nbj2ee@netbeans.org mailing list.

Creating RESTful Service Clients in NetBeans Modules

Creating RESTful Service Clients in NetBeans Modules

Starting in NetBeans IDE 6.9, native REST support is available in NetBeans Module projects. You can now directly generate RESTful client code in a NetBeans module. You can also insert Jersey RESTful client code in a Java or Java Web application.
In this tutorial, you create a NetBeans platform application that consumes the Twitter What Are You Doing service, displaying a list of your Twitter friends' status messages. First you create the platform application. You select the libraries needed in the application. Then you create a NetBeans module. Finally, you add a RESTful client and some basic display elements to the module. The client uses OAuth authorization.
Note: To use the procedure described in this tutorial with a Java or Java Web project, skip the section on Creating a Platform Application and create a Java or Java Web application instead of a NetBeans Module. Ignore any directions that are specific to NetBeans modules. If you are creating a Java application, you can use most of the design in Designing the Window in a JFrame + JPanel. If you are using a Java Web application, you have to design your own JSP or JSF.
Note: You can follow the procedure in this tutorial with another RESTful web service than the Twitter service, if you have the URL for that service's WADL. You only need to register the service in the IDE. To register a service, open the Services window, right-click the Web Services node, and select Add Web Service.
Contents
Content on this page applies to NetBeans IDE 6.9-7.1 To follow this tutorial, you need the following software and resources.
Software or Resource Version Required
NetBeans IDE Java EE download bundle
Java Development Kit (JDK) version 6 or version 7

Creating the Platform Application

You can add NetBeans IDE libraries to a NetBeans Platform Application. In this section, you create the platform application and add the necessary libraries.

To create the module suite:
  1. Click New Project (Ctrl-Shift-N on Linux and Windows, ⌘-Shift-N on MacOS). The New Project wizard opens.
  2. Select the NetBeans Modules category. Then select the NetBeans Platform Application project. Click Next.
  3. Name the project RestfulClientPlatformApp. Choose a location for the project. Accept the other default settings and click Finish. The RestfulClientPlatformApp project appears in the Projects window.
  4. In the Projects window, right-click the RestfulClientPlatformApp project node and select Properties. The Properties dialog opens.
  5. In the Properties dialog, select the Libraries category. Note that only the Platform libraries are included.
  6. Expand the node for the Enterprise libraries. Tick the Included box for the RESTful Web Service Libraries.
    Suite properties showing RESTful WS Libraries selected for inclusion
  7. The Resolve button is highlighted in red, because the RESTful Web Service Libraries depend on other libraries that are not included in the suite. Click the Resolve button to include those libraries.
  8. Click OK. The platform application is ready for you to create the client module.

Creating the Client Module

In just a few steps, you create a module that serves as a client for the Twitter What Are You Doing service. Twitter services are registered "out of the box" in the NetBeans IDE web service manager. You can add additional
To create the module and the client functionality:
  1. In the Projects window, right-click the Modules subnode of the RestfulClientPlatformApp and select Add New... The New Module Project wizard opens.
  2. Name the module TwitterClientModule. Accept the default settings in the other fields and click Next. The Basic Module Configuration panel opens.
  3. Give the code name base an arbitrary name, such as org.my.twitter.friends. Accept the default settings in the other fields and click Finish. TwitterClientModule now appears in the Projects window, under the Modules node of the platform application.
  4. Right-click the TwitterClientModule node and select Open Project. A TwitterClientModule node now appears at the root level of the Projects window.
    Projects window showing TwitterClientModule root node
  5. Select the new, root-level TwitterClientModule node. Launch the New File wizard (Ctrl-N/⌘-N, or New File icon, or context menu of the node).
  6. In the New File wizard, select the Web Services category and the RESTful Java Client file type. Click Next. The New RESTful Java Client panel opens.
  7. Name the class TwitterClient and give it an arbitrary package name, or select the code name base you previously created.
    New RESTful Client wizard showing class and package name
  8. Under Select the REST resource, select IDE Registered. Click Browse and browse for Twitter > Twitter OAuth > [statuses] > [friends_timeline.{format}]. Select this resource and click OK.
    The friends_timeline rest resource selected in the Available REST Resources dialog
    Note: You can register additional web services in the IDE. Go to the Services window, right-click the Web Services node, and choose Add Web Service. You can add a local file or a RESTful URL.
    Add Web Service option for Web Services manager, Services window
  9. OAuth is automatically selected as the authentication type. Accept all defaults and click Finish.
    Completed new RESTful Client wizard
  10. A warning dialog opens. The dialog asks if you want to generate java artifacts from XML schema references in the WADL file. Click Yes.
  11. Another warning may appear asking you to add modules to the classpath. Click OK.
    Warning dialog about missing dependencies
  12. If you need to add modules to the classpath, right-click the TwitterClientModule node and open its Project Properties. Go to the Libraries section, and add the modules with the Add Dependency button. This button opens a list of module dependencies to browse.
    Twitter Client Module properties window, Libraries section
The TwitterClient class is generated and opens in the editor. TheTwitterClient class is complex and contains the following fields, methods and 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
  • login: used to login to the Twitter Application (forces the authorization). This method calls two more generated methods, getOAuthAccessToken and getOAuthRequestToken.
Next you get OAuth keys from Twitter and add them to TwitterClient.

Getting OAuth Keys from Twitter

In order for the NetBeans Platform application to access Twitter data, you need to get CUSTOMER and CUSTOMER_SECRET keys, along with a verification string, from Twitter. Twitter uses OAuth authorization, which requires these keys. However, OAuth is set up with the expectation that it will be called by a web application on a server. In order to get the authorization keys, you register a "dummy" web application.
To get the OAuth keys from Twitter:
  1. Open a browser. Go to the Twitter > Applications page and click Register a new application . You need to be logged into a Twitter account. Make sure you are logged into the correct account, if you have multiple accounts.
  2. Type NB Platform Friends Application in the Application Name text field.
  3. Type a description into the Description field. This is required. You can type something like "NetBeans Platform application calling the friends_timeline operation."
  4. Type an arbitrary URL into the Application Website field.
  5. In the Application Type option, select the Client radio button.
  6. In the Default Access Type option, select the Read and Write radio button.
  7. Leave other options default and press Save. A browser page opens with the details of the application you registered. The important details are the Consumer key and Consumer secret.
  8. Copy the Consumer key from the browser. In the IDE, locate the line where CONSUMER_KEY is set. Paste the value of the consumer key between the quotation marks.
    TwitterClient showing CONSUMER_KEY and CONSUMER_SECRET location
  9. Copy and paste the Consumer secret key from the browser into TwitterClient. Save your changes.

Designing the Window

To complete the project, add a window. Populate the window with UI components and add actions so that clicking a button, for example, will show a list of friends' statuses.
To design the window:
  1. In the Projects window, right-click the module's node and select New > Window. The New Window wizard opens with the Basic Settings panel.
  2. In the Basic Settings panel, select the editor window position, select Open on Application Start, and click Next. The Name, Icon and Location panel opens.
  3. In the Class Name Prefix field, type twitterFriendsStatus. Select the org.my.twitter.friends package. Click Finish.
    Name, Icon and Location panel of New Window wizard, showing class name prefix and package name
  4. The twitterFriendsStatusTopComponent file opens in the Design view. A palette of Swing UI components opens on the right.
    Design view of new window and Palette of swing components, with no components added yet
  5. Drag the following GUI elements into the design area:
    Component Display text Settings
    Button Get Friends' Statuses Change variable name to getStatusesButton.
    Unselect "enabled" property
    Unselected 'enabled' property
    Button Log in Change variable name to loginButton
    Scroll pane --  
    Text area -- Drag into scroll pane
    Resize the text area/scroll pane and align the buttons as you like.
    Design view of new window showing completed window
  6. Double-click the Login button. The IDE generates an action method for the button, and the editor switches to the Source view with the action method focused.
  7. Type or copy the following code into the body of the login button action method. This code launches the method for logging the application into Twitter, enables the getStatuses button, and disables the login button. The application only needs to log in once. Note that TwitterClient does not need to be instantiated to call its login method.
    private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {                                   
       TwitterClient.login();
       getStatusesButton.setEnabled(true);
       loginButton.setEnabled(false);
    } 
  8. Double-click the getStatuses button. The IDE generates an action method for the button, and the editor switches to the Source view with the action method focused.
  9. Paste or type the following handling code into the body of the getStatuses button action method. This code instantiates the TwitterClient and initializes OAuth, using the tokens that the login method created. The code then calls getFriendsTimeline, gets a list of Statuses, adds a line with the username and text for each status to a String, and passes the String to the text area.
    private void getStatusesButtonActionPerformed(java.awt.event.ActionEvent evt) {                                         
        TwitterClient client = new TwitterClient("xml");
        client.initOAuth();
        Statuses response = client.getFriendsTimeline(Statuses.class, null, null, null, "10");
        response.getStatus().size();
        String text = "";
        for (StatusType st : response.getStatus()) {
            text += st.getUser().getName() + ":  " + st.getText() + "\n";
        }
        jTextArea1.setText(text);
    }     
  10. The code has some warning icons for classes that aren't found. Press Ctrl-Shift-I (⌘-Shift-I on MacOS). The Fix All Imports dialog opens. Select the twitter.twitteroauth.twitterresponse classes. Click OK.
    Fix All Imports dialog showing the correct classes to import
The application is now complete. Run the RestfulClientPlatformApp, and a NetBeans platform appears with your designed window in the Output section. Click Log In, and a dialog opens with a link to click for you to authorize the application to access data.
Dialog for authorizing OAuth to pass data to application
Click the link, and a browser page opens with Twitter asking if you want to allow your application to access Twitter data. Click Allow, and the page refreshes with a PIN. Copy the PIN and paste it into the authentication dialog's verifier string field. Click OK.
The Log In button is now disabled, and the Get Friends' Statuses button is enabled. Click Get Friends' Statuses , and a list of your Twitter friends' latest status messages appears.
Running application showing status messages

More Exercises

Here are a few more ideas for you to explore:
  • Add another window to the module, using other methods in the friends_timeline API.
  • Add another module to the project, using a different Twitter resource.
  • Explore the Facebook Module Sample at New Project > Samples > NetBeans Modules > Facebook Module Sample

See Also

For more information about using NetBeans IDE to develop Java EE applications, see the following resources:
To send comments and suggestions, get support, and keep informed about the latest developments on the NetBeans IDE Java EE development features, join the nbj2ee@netbeans.org mailing list.
To send comments and suggestions, get support, and keep informed on topics connected with developing RCP applications on the NetBeans platform, join the dev@platform.netbeans.org mailing list.