Creating a Graphical Client for Twitter

download Creating a Graphical Client for Twitter

of 35

Transcript of Creating a Graphical Client for Twitter

  • 8/2/2019 Creating a Graphical Client for Twitter

    1/35

    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.

    If you do not have a Twitter account, go totwitter.comand create an account before proceeding with

    this tutorial.

    A complete sample of this application is available for download. Clickhereto download the sample.

    Contents

    Designing the JFrame Showing Your User Status Getting OAuth Keys from Twitter Running the Project Calling Multiple Serviceso Adding services and combining calls to one class

    http://twitter.com/http://twitter.com/http://twitter.com/http://netbeans.org/projects/samples/downloads/download/Samples%252FWeb%2520Services%252FTwitterSwingClient.ziphttp://netbeans.org/projects/samples/downloads/download/Samples%252FWeb%2520Services%252FTwitterSwingClient.ziphttp://netbeans.org/projects/samples/downloads/download/Samples%252FWeb%2520Services%252FTwitterSwingClient.ziphttp://netbeans.org/kb/docs/websvc/twitter-swing.html#jframehttp://netbeans.org/kb/docs/websvc/twitter-swing.html#jframehttp://netbeans.org/kb/docs/websvc/twitter-swing.html#show-statushttp://netbeans.org/kb/docs/websvc/twitter-swing.html#show-statushttp://netbeans.org/kb/docs/websvc/twitter-swing.html#authenticationhttp://netbeans.org/kb/docs/websvc/twitter-swing.html#authenticationhttp://netbeans.org/kb/docs/websvc/twitter-swing.html#runhttp://netbeans.org/kb/docs/websvc/twitter-swing.html#runhttp://netbeans.org/kb/docs/websvc/twitter-swing.html#multiservishttp://netbeans.org/kb/docs/websvc/twitter-swing.html#multiservishttp://netbeans.org/kb/docs/websvc/twitter-swing.html#add-serviceshttp://netbeans.org/kb/docs/websvc/twitter-swing.html#add-serviceshttp://netbeans.org/kb/docs/websvc/twitter-swing.html#add-serviceshttp://netbeans.org/kb/docs/websvc/twitter-swing.html#multiservishttp://netbeans.org/kb/docs/websvc/twitter-swing.html#runhttp://netbeans.org/kb/docs/websvc/twitter-swing.html#authenticationhttp://netbeans.org/kb/docs/websvc/twitter-swing.html#show-statushttp://netbeans.org/kb/docs/websvc/twitter-swing.html#jframehttp://netbeans.org/projects/samples/downloads/download/Samples%252FWeb%2520Services%252FTwitterSwingClient.ziphttp://twitter.com/
  • 8/2/2019 Creating a Graphical Client for Twitter

    2/35

    o Modifying the resource paths Adding an Update Status Action Displaying Usernames and Statuses in the JFrameo Creating a TimerTasko Adding a run Method With the getFriendsTimeline Operationo Creating a List Cell Rendering Componento Displaying the Component in TwitterJFrame Connecting Through a ProxyTo 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 aTwitteraccount

    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 aJFrame. 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, thena Java Application project. Click Next.

    http://netbeans.org/kb/docs/websvc/twitter-swing.html#add-serviceshttp://netbeans.org/kb/docs/websvc/twitter-swing.html#add-serviceshttp://netbeans.org/kb/docs/websvc/twitter-swing.html#modify-pathshttp://netbeans.org/kb/docs/websvc/twitter-swing.html#modify-pathshttp://netbeans.org/kb/docs/websvc/twitter-swing.html#update-statushttp://netbeans.org/kb/docs/websvc/twitter-swing.html#update-statushttp://netbeans.org/kb/docs/websvc/twitter-swing.html#public-timeline-autoupdatehttp://netbeans.org/kb/docs/websvc/twitter-swing.html#public-timeline-autoupdatehttp://netbeans.org/kb/docs/websvc/twitter-swing.html#timer-taskhttp://netbeans.org/kb/docs/websvc/twitter-swing.html#timer-taskhttp://netbeans.org/kb/docs/websvc/twitter-swing.html#add-runhttp://netbeans.org/kb/docs/websvc/twitter-swing.html#add-runhttp://netbeans.org/kb/docs/websvc/twitter-swing.html#listcellrendererhttp://netbeans.org/kb/docs/websvc/twitter-swing.html#listcellrendererhttp://netbeans.org/kb/docs/websvc/twitter-swing.html#display-componenthttp://netbeans.org/kb/docs/websvc/twitter-swing.html#display-componenthttp://netbeans.org/kb/docs/websvc/twitter-swing.html#connecting-proxyhttp://netbeans.org/kb/docs/websvc/twitter-swing.html#connecting-proxyhttp://www.netbeans.org/downloads/index.htmlhttp://www.oracle.com/technetwork/java/javase/downloads/index.htmlhttp://www.twitter.com/http://www.twitter.com/http://www.twitter.com/http://java.sun.com/javase/6/docs/api/http://java.sun.com/javase/6/docs/api/http://java.sun.com/javase/6/docs/api/http://java.sun.com/javase/6/docs/api/http://www.twitter.com/http://www.oracle.com/technetwork/java/javase/downloads/index.htmlhttp://www.netbeans.org/downloads/index.htmlhttp://netbeans.org/kb/docs/websvc/twitter-swing.html#connecting-proxyhttp://netbeans.org/kb/docs/websvc/twitter-swing.html#display-componenthttp://netbeans.org/kb/docs/websvc/twitter-swing.html#listcellrendererhttp://netbeans.org/kb/docs/websvc/twitter-swing.html#add-runhttp://netbeans.org/kb/docs/websvc/twitter-swing.html#timer-taskhttp://netbeans.org/kb/docs/websvc/twitter-swing.html#public-timeline-autoupdatehttp://netbeans.org/kb/docs/websvc/twitter-swing.html#update-statushttp://netbeans.org/kb/docs/websvc/twitter-swing.html#modify-paths
  • 8/2/2019 Creating a Graphical Client for Twitter

    3/35

    2. Name the project TwitterSwingClient. Select a Project Location. UnselectCreate MainClass. (The JFrame will be the main class.) Click Finish.

    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.

  • 8/2/2019 Creating a Graphical Client for Twitter

    4/35

    4. Name the form TwitterJFrame and create a package for it called twitterclient. ClickFinish.

  • 8/2/2019 Creating a Graphical Client for Twitter

    5/35

    5. The IDE opens TwitterJFrame in the editor, in the Design view. Here you have a palette ofall the Swing components you can drag and drop into the JFrame.

    6. Click on the Button icon under Swing Controls in the Palette. Drag and drop it into thebottom right corner of the JFrame. Note that the button displays jButton1, which is the

  • 8/2/2019 Creating a Graphical Client for Twitter

    6/35

    name of this JButton object.

    7. Right-click jButton1 and select Edit Text from the context menu. Change the display textto "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 itsdisplay 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 jLabel1Properties dialog opens. Set the labelFor property to point to jTextField1. (This increases

    accessibility.)

  • 8/2/2019 Creating a Graphical Client for Twitter

    7/35

    11. Find the properties Maximum Size, Minimum Size, and Preferred Size. Set each of theseproperties to [48,48], to match the 48px X 48px dimensions of Twitter icons.

    12. Drag and drop a Scroll Pane into the upper part of the JFrame. Drag its borders to expandit 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 thesample.)

    http://netbeans.org/projects/samples/downloads/download/Samples%252FWeb%2520Services%252FTwitterSwingClient.ziphttp://netbeans.org/projects/samples/downloads/download/Samples%252FWeb%2520Services%252FTwitterSwingClient.ziphttp://netbeans.org/projects/samples/downloads/download/Samples%252FWeb%2520Services%252FTwitterSwingClient.ziphttp://netbeans.org/projects/samples/downloads/download/Samples%252FWeb%2520Services%252FTwitterSwingClient.zip
  • 8/2/2019 Creating a Graphical Client for Twitter

    8/35

    13. Drag and drop a List into the Scroll Pane. A sample list of items appears. SaveTwitterJFrame. The JFrame should look like the following image:

    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.

  • 8/2/2019 Creating a Graphical Client for Twitter

    9/35

    2. Press Alt-Insert, or right-click and select Insert Code from the context menu. A menu ofcode to insert opens.

    3. Click Generate REST Client. The Available REST Resources dialog opens.

  • 8/2/2019 Creating a Graphical Client for Twitter

    10/35

    4. Select the IDE Registered radio button and click Browse. Navigate to Twitter > TwitterOAuth > [statuses] > [user_timeline.{format}]. Click OK.

  • 8/2/2019 Creating a Graphical Client for Twitter

    11/35

    5. The Available REST Resources dialog now shows the selected Twitter OAuth user_timelineresource, the corresponding class name, and OAuth authentication type. Click OK.

    6. A dialog opens asking if you want to generate Java objects from the XML schemareferences in the WADL file. Click Yes.

    7. At the end of the TwitterJFrame class, the IDE generates an internal class calledTwitter_OAuth_user_timeline__format_JerseyClient.

    The internal class is complex and contains the following fields, methods and inner

    classes:

    o CONSUMER_KEY: Consumer Key stringo CONSUMER_SECRET: Consumer Sectret stringo initOAuth(): method for OAuh intitializationo getUserTimeline(): method corresponding to HTTP method: getUserTimeline (from

    the REST resource)

    o makeOAuthRequestUnique(): useful for multiple API calls in one sessiono 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.

  • 8/2/2019 Creating a Graphical Client for Twitter

    12/35

    8. In TwitterJFrame immediately above the internalTwitter_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;

    9. Locate the main method in TwitterJFrame. Above this method, create a new methodcalled initUserInfo that throws a MalformedURLException and an IOException.

    10.private void initUserInfo() throws MalformedURLException,IOException {

    11.

  • 8/2/2019 Creating a Graphical Client for Twitter

    13/35

    12.13.

    }

    14. Insert the following code into the method body ofinitUserInfo. Comments in the codeexplain what the code does.

    15.private void initUserInfo() throws MalformedURLException,IOException {

    16.

    17. //Create an instance of the internal service class18. client = new

    Twitter_OAuth_user_timeline__format_JerseyClient("xml");

    19.

    20. //Log in, get tokens, and append the tokens to the consumer andsecret

    21. //keys22. client.login();23. client.initOAuth();24.

    25. //Call getUserTimeline, get a list of statuses, pass the mostrecent

    26. //status as a StatusType object, and display the text of thatobject

    27. //in the JTextField28. Statuses statuses = client.getUserTimeline(Statuses.class,

    null, null, null, "1");

    29. StatusType st = statuses.getStatus().get(0);30. jTextField1.setText(st.getText().trim());31.

    32. //Get a UserType object from the StatusType object, get the URLof that

    33. //user's icon, and display that icon in the JLabel34. UserType user = st.getUser();

  • 8/2/2019 Creating a Graphical Client for Twitter

    14/35

  • 8/2/2019 Creating a Graphical Client for Twitter

    15/35

    After youget 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 theTwitter > Applicationspage and clickRegister a newapplication . 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 User Timeline Application in the Application Name text field.

    3. Type a description into the Description field. This is required. You can type somethinglike "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 theapplication 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 whereCONSUMER_KEY is set. Paste the value of the consumer key between the quotation

    http://netbeans.org/kb/docs/websvc/twitter-swing.html#authenticationhttp://netbeans.org/kb/docs/websvc/twitter-swing.html#authenticationhttp://netbeans.org/kb/docs/websvc/twitter-swing.html#authenticationhttp://twitter.com/appshttp://twitter.com/appshttp://twitter.com/appshttp://twitter.com/apps/newhttp://twitter.com/apps/newhttp://twitter.com/apps/newhttp://twitter.com/apps/newhttp://twitter.com/apps/newhttp://twitter.com/apps/newhttp://twitter.com/appshttp://netbeans.org/kb/docs/websvc/twitter-swing.html#authentication
  • 8/2/2019 Creating a Graphical Client for Twitter

    16/35

    marks.

    9. Copy and paste the Consumer secret key from the browser into TwitterSwingClient. Saveyour 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. If TwitterSwingClient is your main project, press F6. Otherwise, right-click theTwitterSwingClient project node and select Run from the context menu.

    2. A browser window opens asking if you want to allow your registered application to accessyour 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.

  • 8/2/2019 Creating a Graphical Client for Twitter

    17/35

    5. The desktop client opens, displaying your latest Twitter status message.

    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 classAdding 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.

  • 8/2/2019 Creating a Graphical Client for Twitter

    18/35

    2. Follow the same procedure to generate a REST client that you followed in the sectionShowing 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.

    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_JerseyClientclass. 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

    http://netbeans.org/kb/docs/websvc/twitter-swing.html#show-statushttp://netbeans.org/kb/docs/websvc/twitter-swing.html#show-statushttp://netbeans.org/kb/docs/websvc/twitter-swing.html#show-status
  • 8/2/2019 Creating a Graphical Client for Twitter

    19/35

    the new name TwitterClient.

    5. Click Refactor. The IDE replaces all instances of the class name.

    6. In the Navigator window, locate theTwitter_Oauth_friends_timeline__format_JerseyClient class. In that class, locate and

    double-click the getFriendsTimeline method.

  • 8/2/2019 Creating a Graphical Client for Twitter

    20/35

    7. The cursor in the Editor moves to the getFriendsTimeline method. Cut that method(reproduced below).

    8. public T getFriendsTimeline(Class responseType, Stringsince, String since_id, String page, String count) throws

    UniformInterfaceException {

    9. String[] queryParamNames = new String[]{"since", "since_id","page", "count"};

    10. String[] queryParamValues = new String[]{since, since_id,page, count};

    11. returnwebResource.queryParams(getQueryOrFormParams(queryParamNames,

    queryParamValues)).accept(javax.ws.rs.core.MediaType.TEXT_XML).get(

    responseType);

    }

    12. Paste the getFriendsTimeline method into the TwitterClient internal class, below thegetUserTimeline method.

    13. Cut and paste the updateStatus method fromTwitter_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 classare 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.

    2. A red error bar appears in the right margin. Click it, and you go to the line ininitUserInfo that instantiates the TwitterClient class. This line is client = new

  • 8/2/2019 Creating a Graphical Client for Twitter

    21/35

    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 thefollowing 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(getQueryOrFormPar

    ams(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(getQueryOrForm

    Params(queryParamNames,

    queryParamValues)).accept(javax.ws.rs.core.MediaType.TEXT_XML).get(

    responseType);

    6. Navigate to the updateStatus method. Locate the return line:

  • 8/2/2019 Creating a Graphical Client for Twitter

    22/35

    return

    webResource.type(javax.ws.rs.core.MediaType.APPLICATION_FORM_URLENC

    ODED)...

    Append path information to the beginning of the call.

    return

    webResource.path("update.xml").type(javax.ws.rs.core.MediaType.APPL

    ICATION_FORM_URLENCODED).post(responseType,

    getQueryOrFormParams(formParamNames, formParamValues));

    7. Locate and comment out the TwitterClient's setResourcePath method. It is not evercalled, but this is a precaution.

    8. Delete the classes Twitter_OAuth_update__format_JerseyClient andTwitter_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 theJFrame. The editor switches back to the Source view, in the body of the

    jButton1ActionPerformed method, which the IDE just created for you.

    2. Fill in the jButton1ActionPerformed method body as follows:

  • 8/2/2019 Creating a Graphical Client for Twitter

    23/35

    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 TwittergetFriendsTimeline operation when the application runs. To set this up,create a new run

    methodthat overrides the run method in main. Insert calls to getFriendsTimeline into this

    method.

    To have the display update automatically,wrap the run methodcontaining thegetFriendsTimeline operation in ajava.util.TimerTaskthat executes the run method

    every 75 seconds.

    http://netbeans.org/kb/docs/websvc/twitter-swing.html#add-runhttp://netbeans.org/kb/docs/websvc/twitter-swing.html#add-runhttp://netbeans.org/kb/docs/websvc/twitter-swing.html#add-runhttp://netbeans.org/kb/docs/websvc/twitter-swing.html#add-runhttp://netbeans.org/kb/docs/websvc/twitter-swing.html#timer-taskhttp://netbeans.org/kb/docs/websvc/twitter-swing.html#timer-taskhttp://netbeans.org/kb/docs/websvc/twitter-swing.html#timer-taskhttp://java.sun.com/javase/6/docs/api/java/util/TimerTask.htmlhttp://java.sun.com/javase/6/docs/api/java/util/TimerTask.htmlhttp://java.sun.com/javase/6/docs/api/java/util/TimerTask.htmlhttp://java.sun.com/javase/6/docs/api/java/util/TimerTask.htmlhttp://netbeans.org/kb/docs/websvc/twitter-swing.html#timer-taskhttp://netbeans.org/kb/docs/websvc/twitter-swing.html#add-runhttp://netbeans.org/kb/docs/websvc/twitter-swing.html#add-run
  • 8/2/2019 Creating a Graphical Client for Twitter

    24/35

    The application displays the data as cells in a list. You need to pass the data into GUI componentsthat 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 JPanelthat implementsjavax.swing.ListCellRenderer. This

    JPanel returns ajava.awt.Componentobject with the username and status passed in JLabels.

    Tweak the format of the JPanel.

    In TwitterJFrame,set up the JListto 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.3. public class TwitterJFrame extends javax.swing.JFrame {4.5. /** Creates new form TwitterJFrame */6. public TwitterJFrame() {7. initComponents();8. try {9. initUserInfo();10. } catch (IOException ex) {11.

    Logger.getLogger(TwitterJFrame.class.getName()).log(Level.SEVERE,

    null, ex);

    12. }}

    13. In the method body of the constructor, above initComponents();, instantiate thejava.util.Timerclass. The parameters name the Timer thread "Twitter Updater" and

    specify that it cannot be run as a daemon.

    14.public class TwitterJFrame extends javax.swing.JFrame {15.16. /** Creates new form TwitterJFrame */17. public TwitterJFrame() {18. Timer t = new Timer("Twitter Updater`", false);19. initComponents();

    http://netbeans.org/kb/docs/websvc/twitter-swing.html#listcellrendererhttp://netbeans.org/kb/docs/websvc/twitter-swing.html#listcellrendererhttp://netbeans.org/kb/docs/websvc/twitter-swing.html#listcellrendererhttp://java.sun.com/javase/6/docs/api/javax/swing/ListCellRenderer.htmlhttp://java.sun.com/javase/6/docs/api/javax/swing/ListCellRenderer.htmlhttp://java.sun.com/javase/6/docs/api/javax/swing/ListCellRenderer.htmlhttp://java.sun.com/javase/6/docs/api/java/awt/Component.htmlhttp://java.sun.com/javase/6/docs/api/java/awt/Component.htmlhttp://java.sun.com/javase/6/docs/api/java/awt/Component.htmlhttp://netbeans.org/kb/docs/websvc/twitter-swing.html#display-componenthttp://netbeans.org/kb/docs/websvc/twitter-swing.html#display-componenthttp://netbeans.org/kb/docs/websvc/twitter-swing.html#display-componenthttp://java.sun.com/javase/6/docs/api/java/util/Timer.htmlhttp://java.sun.com/javase/6/docs/api/java/util/Timer.htmlhttp://java.sun.com/javase/6/docs/api/java/util/Timer.htmlhttp://netbeans.org/kb/docs/websvc/twitter-swing.html#display-componenthttp://java.sun.com/javase/6/docs/api/java/awt/Component.htmlhttp://java.sun.com/javase/6/docs/api/javax/swing/ListCellRenderer.htmlhttp://netbeans.org/kb/docs/websvc/twitter-swing.html#listcellrenderer
  • 8/2/2019 Creating a Graphical Client for Twitter

    25/35

    20. try {21. initUserInfo();22. } catch (IOException ex) {23.

    Logger.getLogger(TwitterJFrame.class.getName()).log(Level.SEVERE,

    null, ex);

    24. }25. }

    26. Right-click anywhere in the editor and select Fix Imports from the context menu, or pressCtrl/-Shift-I. A dialog opens and gives you a choice of classes to import. Add an import

    statement for java.util.Timer.

    27. Below the instantiation ofTimer, 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.

    28.public class TwitterJFrame extends javax.swing.JFrame {29.30. /** Creates new form TwitterJFrame */31. public TwitterJFrame() {32. Timer t = new Timer("Twitter Updater`", false);33. t.scheduleAtFixedRate(new TimerTask() {

    34. }, 30000, 75000);35. initComponents();36. try {37. initUserInfo();38. } catch (IOException ex) {39.

    Logger.getLogger(TwitterJFrame.class.getName()).log(Level.SEVERE,

    null, ex);

    40. }

  • 8/2/2019 Creating a Graphical Client for Twitter

    26/35

  • 8/2/2019 Creating a Graphical Client for Twitter

    27/35

    18. Timer t = new Timer("Twitter Updater`", false);t.scheduleAtFixedRate(new TimerTask() {

    @Override

    public void run(){

    }

    }, 1500, 75000);

    initComponents();

    19. try {20. initUserInfo();21. } catch (IOException ex) {22.

    Logger.getLogger(TwitterJFrame.class.getName()).log(Level.SEVERE,

    null, ex);

    23. }

    24. Insert the following code into the body of the run [email protected] void run() {27. System.out.println("Timer Task is running");28. try {29. client.initOAuth();30. Statuses response =

    client.getFriendsTimeline(Statuses.class, null, null, null, "10");

    31. // Clear the list model so it does not replicate thecontents from the last run

    32. statusesListModel.clear();33. // Create a Status Type object for every status in the

    Status list, and add an element

    34. // to the list model for every status type object35. for (final StatusType st : response.getStatus()) {36. SwingUtilities.invokeLater(new Runnable() {37. public void run() {38. statusesListModel.addElement(st);39. }40. });

  • 8/2/2019 Creating a Graphical Client for Twitter

    28/35

    41. }42. } catch (UniformInterfaceException ex) {43. System.out.println("Exception when calling getFriendsTimeline =

    " + ex.getResponse().getEntity(String.class));

    44. }}

    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 ajava.awt.Componentobject 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 Formwizard opens.

    2. Name the JPanel Item and place it in the twitterclient package.

    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.

    http://java.sun.com/javase/6/docs/api/javax/swing/ListCellRenderer.htmlhttp://java.sun.com/javase/6/docs/api/javax/swing/ListCellRenderer.htmlhttp://java.sun.com/javase/6/docs/api/java/awt/Component.htmlhttp://java.sun.com/javase/6/docs/api/java/awt/Component.htmlhttp://java.sun.com/javase/6/docs/api/java/awt/Component.htmlhttp://java.sun.com/javase/6/docs/api/java/awt/Component.htmlhttp://java.sun.com/javase/6/docs/api/javax/swing/ListCellRenderer.html
  • 8/2/2019 Creating a Graphical Client for Twitter

    29/35

    5. Position the Label and the Text Pane to match how you want the data to be displayed. Inthe following image, the username is on the left top while the status text is below and

    slightly indented. Thesampleproject 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.

    6. Right-click on the JLabel element and select Properties from the context menu. In theProperties, 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

    http://netbeans.org/projects/samples/downloads/download/Samples%252FWeb%2520Services%252FTwitterSwingClient.ziphttp://netbeans.org/projects/samples/downloads/download/Samples%252FWeb%2520Services%252FTwitterSwingClient.ziphttp://netbeans.org/projects/samples/downloads/download/Samples%252FWeb%2520Services%252FTwitterSwingClient.ziphttp://netbeans.org/projects/samples/downloads/download/Samples%252FWeb%2520Services%252FTwitterSwingClient.zip
  • 8/2/2019 Creating a Graphical Client for Twitter

    30/35

    color is set to blue in the Foreground property.

    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?

  • 8/2/2019 Creating a Graphical Client for Twitter

    31/35

    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 forjavax.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.

    12.public Component getListCellRendererComponent(JList list, Objectvalue, int index, boolean sel, boolean focus) {

    13. StatusType st = (StatusType) value;14. jTextPane1.setText(st.getText());15. jLabel1.setText("" + st.getUser().getScreenName() +

    "");

    16. return this;}

  • 8/2/2019 Creating a Graphical Client for Twitter

    32/35

  • 8/2/2019 Creating a Graphical Client for Twitter

    33/35

    2. Select the model property. Press Ctrl-Space. The custom property editor opens, showingthe default text displayed in the list.

    3. In the "Set jLlist1's model property using:" drop-down menu, select Custom Code. A textfield appears where you type in the properties for jLabel1.setModel. Type

    statusesListModel in the field and click OK.

    4. In the Properties dialog, select cellRenderer and press Ctrl-Space. The custom propertyeditor 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

  • 8/2/2019 Creating a Graphical Client for Twitter

    34/35

    new Item() and click OK.

    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.

    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.

  • 8/2/2019 Creating a Graphical Client for Twitter

    35/35

    For the TwitterSwingClient project, you need to specify the proxy that the HTTP protocol handler uses.

    This is described inJava 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 selectProperties. 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!

    http://java.sun.com/javase/6/docs/technotes/guides/net/proxies.htmlhttp://java.sun.com/javase/6/docs/technotes/guides/net/proxies.htmlhttp://java.sun.com/javase/6/docs/technotes/guides/net/proxies.htmlhttp://java.sun.com/javase/6/docs/technotes/guides/net/proxies.html