Java tutorial
/* * 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. */ package Twitter; import com.mongodb.MongoClient; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.util.Timer; import java.util.TimerTask; import org.bson.Document; import twitter4j.Query; import twitter4j.QueryResult; import twitter4j.Status; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.TwitterFactory; import twitter4j.conf.ConfigurationBuilder; /** * * @author itza */ public class Frame extends javax.swing.JFrame { MongoClient mongo; ConfigurationBuilder cb; TwitterFactory tf; Query query; QueryResult result; Twitter twitter; String squery; String collection; String database; Timer timer; boolean flag; /** * Creates new form Frame */ public Frame() { initComponents(); squery = "#YOLO";//Este es el hashtag a buscar flag = true; //Nos conectamos a Mongo DB database = "twitter";//nombre de la base de datos collection = "twitts";//colleccion mongo = new MongoClient("localhost"); //Aqui van las llaves, las quite para que no se vieran publicas cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey("").setOAuthConsumerSecret("").setOAuthAccessToken("") .setOAuthAccessTokenSecret(""); tf = new TwitterFactory(cb.build()); twitter = tf.getInstance(); timer = new Timer(); //Colecctamos twiits cada 10 segundos para que no se repitan timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { if (flag) getTwitters(); } }, 100, 10000); this.addWindowListener(new WindowListener() { @Override public void windowOpened(WindowEvent e) { } @Override public void windowClosing(WindowEvent e) { mongo.close();//cerramos la conexion al cerrar la ventana } @Override public void windowClosed(WindowEvent e) { } @Override public void windowIconified(WindowEvent e) { } @Override public void windowDeiconified(WindowEvent e) { } @Override public void windowActivated(WindowEvent e) { } @Override public void windowDeactivated(WindowEvent e) { } }); } public void init() { } public void insertTwitt(Document doc) { //insertamos un objeto documnto en la coleccion mongo.getDatabase(database).getCollection(collection).insertOne(doc); } //Esta funcion convierte un estatus que es un objeto tweets a un Document que es el objeto para insertar en mongo public Document statustoJSON(Status status) { Document doc = new Document(); if (status.getText() != null) doc.append("tweet", status.getText()); if (status.getUser().getName() != null) doc.append("name", status.getUser().getName()); if (status.getPlace() != null) doc.append("place", status.getPlace().toString()); if (status.getUser().getScreenName() != null) doc.append("nick", status.getUser().getScreenName()); if (status.getGeoLocation() != null) doc.append("gloc", status.getGeoLocation().toString()); doc.append("fcont", status.getFavoriteCount()); doc.append("rcunt", status.getRetweetCount()); if (status.getRetweetedStatus() != null) doc.append("rstate", status.getRetweetedStatus().getText()); tacol.setText(tacol.getText() + doc.toJson() + "\n");//imprimimos el tweet en el frame return doc; } //Ejecutamos la query, convertimos e insertamos el resultado //la bandera evita que el timer alcanze a el procesamiento de tweets public void getTwitters() { flag = false; query = new Query(squery); try { result = twitter.search(query); tacol.setText(""); for (Status status : result.getTweets()) { insertTwitt(statustoJSON(status)); } } catch (TwitterException ex) { ex.printStackTrace(); } flag = true; } /** * 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() { jLabel1 = new javax.swing.JLabel(); contador = new javax.swing.JButton(); jTabbedPane1 = new javax.swing.JTabbedPane(); jPanel1 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); tacol = new javax.swing.JTextArea(); jPanel2 = new javax.swing.JPanel(); jScrollPane2 = new javax.swing.JScrollPane(); taerr = new javax.swing.JTextArea(); jPanel3 = new javax.swing.JPanel(); bsalir = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setText("Contador:"); contador.setText("0"); contador.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { contadorActionPerformed(evt); } }); tacol.setColumns(20); tacol.setRows(5); jScrollPane1.setViewportView(tacol); 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() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 344, Short.MAX_VALUE) .addContainerGap())); jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup().addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE) .addContainerGap())); jTabbedPane1.addTab("Colector", jPanel1); taerr.setColumns(20); taerr.setRows(5); jScrollPane2.setViewportView(taerr); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup(jPanel2Layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup().addContainerGap() .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 344, Short.MAX_VALUE) .addContainerGap())); jPanel2Layout.setVerticalGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup().addContainerGap() .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE) .addContainerGap())); jTabbedPane1.addTab("Error", jPanel2); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup(jPanel3Layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 368, Short.MAX_VALUE)); jPanel3Layout.setVerticalGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 204, Short.MAX_VALUE)); jTabbedPane1.addTab("Info", jPanel3); bsalir.setText("Salir"); bsalir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bsalirActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTabbedPane1) .addGroup(layout.createSequentialGroup().addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(contador, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(bsalir, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap())); layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1).addComponent(contador).addComponent(bsalir)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTabbedPane1).addContainerGap())); pack(); }// </editor-fold>//GEN-END:initComponents private void contadorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_contadorActionPerformed contador.setText("" + mongo.getDatabase(database).getCollection(collection).count()); //este boton muestr el contador de tweets }//GEN-LAST:event_contadorActionPerformed private void bsalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bsalirActionPerformed mongo.close(); System.exit(0); }//GEN-LAST:event_bsalirActionPerformed /** * @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(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Frame.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 Frame().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton bsalir; private javax.swing.JButton contador; private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTabbedPane jTabbedPane1; private javax.swing.JTextArea tacol; private javax.swing.JTextArea taerr; // End of variables declaration//GEN-END:variables }