Package twitterjavagt

Source Code of twitterjavagt.AutorizacionVentana

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

import java.awt.Desktop;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.logging.Level;
import java.util.logging.Logger;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.ConfigurationBuilder;

/**
*
* @author mario
*/
public class AutorizacionVentana extends javax.swing.JFrame {

    /**
* Creates new form AutorizacionVentana
*/
   
            RequestToken requestToken = null;
        AccessToken accessToken = null;
        String url = null;
        Twitter OAuthTwitter;
    public AutorizacionVentana() throws TwitterException, URISyntaxException, IOException {
        initComponents();
        setTitle("Ventana de autorización");
        setVisible(true);
        jLabel2.setText("El archivo 'auth_file.txt' se generará en la ruta: "+System.getProperty("user.home")+"/auth_file.txt");
       
       
        ConfigurationBuilder configBuilder = new ConfigurationBuilder();
            configBuilder.setDebugEnabled(true)
                    .setOAuthConsumerKey(new Tokens().OAuthConsumerKey)
                    .setOAuthConsumerSecret(new Tokens().OAuthConsumerSecret);
        OAuthTwitter = new TwitterFactory(configBuilder.build()).getInstance();
           
       
        try {
                requestToken = OAuthTwitter.getOAuthRequestToken();
                System.out.println("Request Tokens obtenidos con éxito.");
                /*System.out.println("Request Token: " + requestToken.getToken());
System.out.println("Request Token secret: " + requestToken.getTokenSecret());*/
                url = requestToken.getAuthorizationURL();
            } catch (TwitterException ex) {
                Logger.getLogger(TwitterJavaGT.class.getName()).log(Level.SEVERE, null, ex);
            }
            BufferedReader lectorTeclado = new BufferedReader(new InputStreamReader(System.in));
            //Abro el navegador.
           
            Desktop.getDesktop().browse(new URI(url));

            /*Runtime runtime = Runtime.getRuntime();
try {
runtime.exec("firefox " + url);
} catch (Exception e) {
}*/
            //Nos avisa de que introduciremos el PIN a continuación
            System.out.print("Introduce el PIN del navegador y pulsa intro.\n\n PIN: ");
            //Leemos el PIN
           
       
        System.out.println("\n\nAccess Tokens obtenidos con éxito.");
        /*System.out.println("Access Token: " + accessToken.getToken());
System.out.println("Access Token secret: " + accessToken.getTokenSecret());*/

   
   
    }

    /**
* 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">
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("PIN: ");

        jButton1.setText("VALIDAR");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Ubuntu", 0, 12)); // NOI18N
        jLabel2.setText("jLabel2");

        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()
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 468, Short.MAX_VALUE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton1)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(32, 32, 32)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jButton1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addContainerGap(15, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        String pin = jTextField1.getText();

        if (pin.length() > 0) {
            try {
                accessToken = OAuthTwitter.getOAuthAccessToken(requestToken, pin);
            } catch (TwitterException ex) {
                Logger.getLogger(AutorizacionVentana.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            try {
                accessToken = OAuthTwitter.getOAuthAccessToken(requestToken);
            } catch (TwitterException ex) {
                Logger.getLogger(AutorizacionVentana.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
       
        if(accessToken!=null){
                    FileOutputStream fileOS = null;
        File file;
        String content = accessToken.getToken() + "\n" + accessToken.getTokenSecret();
        try {
            file = new File(System.getProperty("user.home")+"/auth_file.txt".replace("\\","/"));
            fileOS = new FileOutputStream(file);
            //Si el archivo no existe, se crea
            if (!file.exists()) {
                file.createNewFile();
            }
            //Se obtiene el contenido en Bytes
            byte[] contentInBytes = content.getBytes();
            fileOS.write(contentInBytes);
            fileOS.flush();
            fileOS.close();
            System.out.println("Escritura realizada con éxito.");
        } catch (IOException e) {
        } finally {
            try {
                if (fileOS != null) {
                    fileOS.close();
                }
            } catch (IOException e) {
            }
                try {
                try {
                    TwitterJavaGT cliente=new TwitterJavaGT();
                } catch (MalformedURLException ex) {
                    Logger.getLogger(AutorizacionVentana.class.getName()).log(Level.SEVERE, null, ex);
                }
                    dispose();
                } catch (TwitterException ex) {
                    Logger.getLogger(AutorizacionVentana.class.getName()).log(Level.SEVERE, null, ex);
                }
        }
        } else {
            jTextField1.setText("");
        }

    }

    /**
* @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(AutorizacionVentana.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AutorizacionVentana.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AutorizacionVentana.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AutorizacionVentana.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
               
                    try {
                        new AutorizacionVentana().setVisible(true);
                    } catch ( TwitterException | URISyntaxException | IOException ex) {
                        Logger.getLogger(AutorizacionVentana.class.getName()).log(Level.SEVERE, null, ex);
                    }
              
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration
}
TOP

Related Classes of twitterjavagt.AutorizacionVentana

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.