twitterswingclient.TwitterClient.java Source code

Java tutorial

Introduction

Here is the source code for twitterswingclient.TwitterClient.java

Source

package twitterswingclient;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author HASNA
 */

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.logging.Level;
import twitter4j.*;
import twitter4j.auth.AccessToken;

public class TwitterClient extends javax.swing.JFrame {

    /**
     * Creates new form TwitterClient
     */
    public TwitterClient() {
        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")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        update = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        status = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        textArea = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        update.setText("Update");
        update.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                updateActionPerformed(evt);
            }
        });

        jLabel1.setText("Icon");
        jLabel1.setPreferredSize(new java.awt.Dimension(48, 48));

        status.setText("Status");
        status.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                statusActionPerformed(evt);
            }
        });

        textArea.setColumns(20);
        textArea.setRows(5);
        jScrollPane1.setViewportView(textArea);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
                javax.swing.GroupLayout.Alignment.TRAILING,
                layout.createSequentialGroup().addContainerGap().addGroup(layout
                        .createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING).addComponent(jScrollPane1)
                        .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 47,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(status, javax.swing.GroupLayout.DEFAULT_SIZE, 244, Short.MAX_VALUE)
                                .addGap(18, 18, 18).addComponent(update)))
                        .addContainerGap()));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 226, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
                                        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                .addComponent(update).addComponent(jLabel1,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE, 46,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addComponent(status, javax.swing.GroupLayout.Alignment.TRAILING,
                                        javax.swing.GroupLayout.PREFERRED_SIZE, 36,
                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap()));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void statusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_statusActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_statusActionPerformed

    private void updateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateActionPerformed
        // TODO add your handling code here:
        String consKey = "Your key";
        String consSecret = "Your secret";
        String accToken = "Your key";
        String accSecret = "Your secret";
        try {

            TwitterFactory twitterFactory = new TwitterFactory();

            Twitter twitter = twitterFactory.getInstance();

            twitter.setOAuthConsumer(consKey, consSecret);

            twitter.setOAuthAccessToken(new AccessToken(accToken, accSecret));

            StatusUpdate statusUpdate = new StatusUpdate(status.getText());

            statusUpdate.setMedia("Feeling great",
                    new URL("http://media3.giphy.com/media/el1tH0BzEWm4w/giphy.gif").openStream());

            Status stat = twitter.updateStatus(statusUpdate);

            textArea.append("status.toString() = " + stat.toString());
            textArea.append("status.getInReplyToScreenName() = " + stat.getInReplyToScreenName());
            textArea.append("status.getSource() = " + stat.getSource());
            textArea.append("status.getText() = " + stat.getText());
            textArea.append("status.getContributors() = " + Arrays.toString(stat.getContributors()));
            textArea.append("status.getCreatedAt() = " + stat.getCreatedAt());
            textArea.append("status.getCurrentUserRetweetId() = " + stat.getCurrentUserRetweetId());
            textArea.append("status.getGeoLocation() = " + stat.getGeoLocation());
            textArea.append("status.getId() = " + stat.getId());
            textArea.append("status.getInReplyToStatusId() = " + stat.getInReplyToStatusId());
            textArea.append("status.getInReplyToUserId() = " + stat.getInReplyToUserId());
            textArea.append("status.getPlace() = " + stat.getPlace());
            textArea.append("status.getRetweetCount() = " + stat.getRetweetCount());
            textArea.append("status.getRetweetedStatus() = " + stat.getRetweetedStatus());
            textArea.append("status.getUser() = " + stat.getUser());
            textArea.append("status.getAccessLevel() = " + stat.getAccessLevel());
            textArea.append("status.getHashtagEntities() = " + Arrays.toString(stat.getHashtagEntities()));
            textArea.append("status.getMediaEntities() = " + Arrays.toString(stat.getMediaEntities()));

            if (stat.getRateLimitStatus() != null) {
                textArea.append("status.getRateLimitStatus().getLimit() = " + stat.getRateLimitStatus().getLimit());
                textArea.append(
                        "status.getRateLimitStatus().getRemaining() = " + stat.getRateLimitStatus().getRemaining());
                textArea.append("status.getRateLimitStatus().getResetTimeInSeconds() = "
                        + stat.getRateLimitStatus().getResetTimeInSeconds());
                textArea.append("status.getRateLimitStatus().getSecondsUntilReset() = "
                        + stat.getRateLimitStatus().getSecondsUntilReset());
                textArea.append("status.getRateLimitStatus().getRemainingHits() = "
                        + stat.getRateLimitStatus().getRemaining());
            }
            textArea.append("status.getURLEntities() = " + Arrays.toString(stat.getURLEntities()));
            textArea.append("status.getUserMentionEntities() = " + Arrays.toString(stat.getUserMentionEntities()));

        } catch (IOException ex) {
            textArea.append("IO Exception");
        } catch (TwitterException tw) {
            textArea.append("Twitter Exception");
        }
    }//GEN-LAST:event_updateActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TwitterClient.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TwitterClient.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TwitterClient.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TwitterClient.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TwitterClient().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField status;
    private javax.swing.JTextArea textArea;
    private javax.swing.JButton update;
    // End of variables declaration//GEN-END:variables
}