31
Jul/09
2

One Way Tweet a Java App

One way tweet is a sending application for twitter. In this tutorial you will see/learn how to send stuff to twitter by writing a java desktop UI. You will create a new project in NetBeans and choose java application, and create a new package called org.me.owt.

Then, create a new java source file and call it main.java, and another called tweet.java. Two simple classes and you’ve got yourself a twitter client. The end result will look like this:
One Way Tweet

/*
 * Main.java
 *
 * Created on 23-Jul-2009, 11:57:04
 */
package org.me.owt;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 *
 * @author Siriquelle
 */
public class Main extends javax.swing.JFrame {

    private JButton button;

    /** Creates new form Main*/
    public Main() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // 
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        usernamelabel = new java.awt.Label();
        username = new java.awt.TextField();
        passwordlabel = new java.awt.Label();
        password = new java.awt.TextField();
        status = new java.awt.TextArea();
        tweet = new java.awt.Button();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("One Way Tweet");
        setBackground(new java.awt.Color(204, 255, 255));
        setBounds(new java.awt.Rectangle(0, 0, 0, 0));
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setForeground(new java.awt.Color(204, 255, 255));
        setName("One Way Tweet"); // NOI18N
        setResizable(false);

        jPanel1.setBackground(new java.awt.Color(204, 255, 255));
        jPanel1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        jPanel1.setAlignmentX(getWidth() / 2);
        jPanel1.setAlignmentY(getHeight() / 2);

        usernamelabel.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N
        usernamelabel.setForeground(new java.awt.Color(0, 102, 102));
        usernamelabel.setName("usernameLabel"); // NOI18N
        usernamelabel.setText("Username");

        username.setForeground(new java.awt.Color(51, 51, 51));
        username.setName("username"); // NOI18N
        username.addFocusListener(new java.awt.event.FocusAdapter() {

            public void focusGained(java.awt.event.FocusEvent evt) {
                Main.this.focusGained(evt);
            }

            public void focusLost(java.awt.event.FocusEvent evt) {
                Main.this.focusLost(evt);
            }
        });

        passwordlabel.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N
        passwordlabel.setForeground(new java.awt.Color(0, 102, 102));
        passwordlabel.setName("passwordLabel"); // NOI18N
        passwordlabel.setText("Password");

        password.setEchoChar('*');
        password.setForeground(new java.awt.Color(51, 51, 51));
        password.setName("password"); // NOI18N
        password.addFocusListener(new java.awt.event.FocusAdapter() {

            public void focusGained(java.awt.event.FocusEvent evt) {
                Main.this.focusGained(evt);
            }

            public void focusLost(java.awt.event.FocusEvent evt) {
                Main.this.focusLost(evt);
            }
        });

        status.setForeground(new java.awt.Color(51, 51, 51));
        status.setName("status"); // NOI18N
        status.addFocusListener(new java.awt.event.FocusAdapter() {

            @Override
            public void focusGained(java.awt.event.FocusEvent evt) {
                Main.this.focusGained(evt);
            }

            @Override
            public void focusLost(java.awt.event.FocusEvent evt) {
                Main.this.focusLost(evt);
            }
        });

        tweet.setActionCommand("tweet");
        tweet.setBackground(new java.awt.Color(153, 255, 255));
        tweet.setFont(new java.awt.Font("Impact", 1, 48)); // NOI18N
        tweet.setForeground(new java.awt.Color(0, 102, 102));
        tweet.setLabel("tweet");
        tweet.setName("tweet"); // NOI18N
        tweet.addMouseListener(new java.awt.event.MouseAdapter() {

            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tweetMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(jPanel1Layout.createSequentialGroup().addContainerGap().addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(status, javax.swing.GroupLayout.PREFERRED_SIZE, 266, javax.swing.GroupLayout.PREFERRED_SIZE).addGroup(jPanel1Layout.createSequentialGroup().addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false).addComponent(passwordlabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(usernamelabel, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(username, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(password, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE))).addComponent(tweet, javax.swing.GroupLayout.PREFERRED_SIZE, 266, javax.swing.GroupLayout.PREFERRED_SIZE)).addContainerGap()));
        jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(jPanel1Layout.createSequentialGroup().addContainerGap().addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING).addComponent(usernamelabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(username, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(passwordlabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(password, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(status, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(tweet, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE).addContainerGap()));

        usernamelabel.getAccessibleContext().setAccessibleName("usernameLabel");
        username.getAccessibleContext().setAccessibleName("username");
        password.getAccessibleContext().setAccessibleName("password");
        status.getAccessibleContext().setAccessibleName("status");
        tweet.getAccessibleContext().setAccessibleName("tweet");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE));
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE));

        getAccessibleContext().setAccessibleName("One Way Tweet");
        getAccessibleContext().setAccessibleDescription("One Way Tweet");

        pack();
    }// 

    private void tweetMouseClicked(java.awt.event.MouseEvent evt) {
        Tweet tw = new Tweet(username.getText(), password.getText(), status.getText());
        if (tw.sendTweet())
        {
            this.ShowMessageDialog("Tweet Win");
        } else
        {
            this.ShowMessageDialog("Tweet Fail");
        }
    }

    private void focusGained(java.awt.event.FocusEvent evt) {
        evt.getComponent().setBackground(new java.awt.Color(255, 255, 215));
    }

    private void focusLost(java.awt.event.FocusEvent evt) {
        evt.getComponent().setBackground(new java.awt.Color(255, 255, 255));
    }

    public void ShowMessageDialog(String msg) {
        final JFrame frame = new JFrame(msg);
        button = new JButton("OK");
        button.addMouseListener(new java.awt.event.MouseAdapter() {

            public void mouseClicked(java.awt.event.MouseEvent evt) {
                frame.dispose();
            }
        });

        JPanel panel = new JPanel();
        panel.add(button);
        panel.add(button);
        frame.add(panel);
        frame.setSize(220, 80);
        frame.setLocation(220, 80);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Main().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JPanel jPanel1;
    private java.awt.TextField password;
    private java.awt.Label passwordlabel;
    private java.awt.TextArea status;
    private java.awt.Button tweet;
    private java.awt.TextField username;
    private java.awt.Label usernamelabel;
    // End of variables declaration
}

The following code is a class that handles the tweet. create a new java source file in the org.me.owt package and call it tweet.java. It’s methods are used to create and send the tweet and handle the response from the twitter api:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.me.owt;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

/**
 *
 * @author Siriquelle
 */
public class Tweet {

    private String twitteruser;
    private String twitterpass;
    private String status;
    private String response;

    public Tweet(String u, String p, String s) {
        twitteruser = u;
        twitterpass = p;
        status = s;
    }

    public boolean sendTweet() {
        try
        {
            String encodedData = URLEncoder.encode(status, "UTF-8");

            String credentials = twitteruser + ":" + twitterpass;
            String encodecredentials = new sun.misc.BASE64Encoder().encode(credentials.getBytes());

            URLConnection connection = null;
            URL url = new URL("http://twitter.com/statuses/update.xml");
            connection = url.openConnection();
            connection.setRequestProperty("Authorization", "Basic " + encodecredentials);
            connection.setDoOutput(true);

            OutputStreamWriter output = new OutputStreamWriter(connection.getOutputStream());
            output.write("status=" + encodedData);
            output.close();

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String decodedString;
            while ((decodedString = in.readLine()) != null)
            {
                response = decodedString;
            }
            in.close();
            return true;
        } catch (Exception e)
        {
            response = e.toString();
            return false;
        }
    }
}

And thats the code, right click your project and choose run. After you examine this code you’ll discover how, with a little parsing you can turn this application into a fully fledged thwirl competitor. :) If you’ve any questions I’d love a go at answering.

This application was created in netbeans using the swing UI builder. In a future post I will describe the process to building an application using the NetBeans IDE and it’s UI builders in design view.

Comments (2) Trackbacks (0)
  1. aaaaaaaa
    9:35 am on July 31st, 2009

    That’s a whole lot of code :P I’ll stick with Flex thanks :) But nice job.

  2. Siriquelle
    9:12 pm on August 1st, 2009

    most of that code was auto-generated by NetBeans you should give it a try,

Leave a comment

No trackbacks yet.