my.swingconnect.SwingConnectUI.java Source code

Java tutorial

Introduction

Here is the source code for my.swingconnect.SwingConnectUI.java

Source

/*
 * 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 my.swingconnect;

import java.io.File;
//import java.lang.Object;
import java.net.URL;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.io.DataOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.JFileChooser;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.params.HttpMethodParams;
import sun.security.util.Password;

/**
 *
 * @author alicegeorge
 */
public class SwingConnectUI extends javax.swing.JFrame {

    private File targetFile, targetFile1;
    static String filename = "";
    static File[] files;
    static int count = 0;
    static ArrayList<String> results = new ArrayList<String>();

    /**
     * Creates new form SwingConnectUI
     */
    public SwingConnectUI() {
        initComponents();
        jButton3.setEnabled(false);
        jButton2.setEnabled(false);
        jButton4.setEnabled(false);
    }

    /**
     * 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() {

        jDialog1 = new javax.swing.JDialog();
        jDialog2 = new javax.swing.JDialog();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jTextField3 = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jTextField4 = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        jCheckBox1 = new javax.swing.JCheckBox();
        jPasswordField1 = new javax.swing.JPasswordField();
        jSeparator1 = new javax.swing.JSeparator();
        jButton3 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextArea2 = new javax.swing.JTextArea();
        jLabel6 = new javax.swing.JLabel();
        jButton4 = new javax.swing.JButton();
        jCheckBox2 = new javax.swing.JCheckBox();
        jCheckBox3 = new javax.swing.JCheckBox();
        jCheckBox4 = new javax.swing.JCheckBox();
        jLabel5 = new javax.swing.JLabel();
        jOptionPane1 = new javax.swing.JOptionPane();

        javax.swing.GroupLayout jDialog1Layout = new javax.swing.GroupLayout(jDialog1.getContentPane());
        jDialog1.getContentPane().setLayout(jDialog1Layout);
        jDialog1Layout.setHorizontalGroup(jDialog1Layout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 400, Short.MAX_VALUE));
        jDialog1Layout.setVerticalGroup(jDialog1Layout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 300, Short.MAX_VALUE));

        javax.swing.GroupLayout jDialog2Layout = new javax.swing.GroupLayout(jDialog2.getContentPane());
        jDialog2.getContentPane().setLayout(jDialog2Layout);
        jDialog2Layout.setHorizontalGroup(jDialog2Layout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 400, Short.MAX_VALUE));
        jDialog2Layout.setVerticalGroup(jDialog2Layout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 300, Short.MAX_VALUE));

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

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Welcome to Photo-drop !!!");
        getContentPane().setLayout(null);

        jLabel1.setFont(new java.awt.Font("Lucida Handwriting", 3, 14)); // NOI18N
        jLabel1.setText("Enter the Username :");
        getContentPane().add(jLabel1);
        jLabel1.setBounds(70, 120, 170, 25);

        jTextField1.setFont(new java.awt.Font("Lucida Handwriting", 3, 14)); // NOI18N
        jTextField1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED,
                new java.awt.Color(255, 153, 153), java.awt.Color.lightGray, new java.awt.Color(255, 204, 204),
                new java.awt.Color(204, 255, 255)));
        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });
        getContentPane().add(jTextField1);
        jTextField1.setBounds(250, 120, 180, 30);

        jLabel2.setFont(new java.awt.Font("Lucida Handwriting", 1, 14)); // NOI18N
        jLabel2.setText("Password : ");
        getContentPane().add(jLabel2);
        jLabel2.setBounds(450, 120, 90, 20);

        jButton1.setFont(new java.awt.Font("Lucida Handwriting", 3, 13)); // NOI18N
        jButton1.setText("Login");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton1);
        jButton1.setBounds(750, 120, 86, 30);

        jLabel3.setFont(new java.awt.Font("Lucida Handwriting", 3, 14)); // NOI18N
        jLabel3.setText("URL: ");
        getContentPane().add(jLabel3);
        jLabel3.setBounds(90, 240, 50, 20);

        jTextField3.setFont(new java.awt.Font("Lucida Handwriting", 3, 14)); // NOI18N
        jTextField3.setText("http://photo-drop.com/uploader.php");
        jTextField3.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED,
                new java.awt.Color(255, 153, 153), new java.awt.Color(204, 204, 204),
                new java.awt.Color(255, 204, 204), new java.awt.Color(153, 255, 255)));
        jTextField3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField3ActionPerformed(evt);
            }
        });
        getContentPane().add(jTextField3);
        jTextField3.setBounds(250, 230, 340, 30);

        jLabel4.setFont(new java.awt.Font("Lucida Handwriting", 3, 14)); // NOI18N
        jLabel4.setText("Select a directory:");
        getContentPane().add(jLabel4);
        jLabel4.setBounds(70, 280, 150, 26);

        jTextField4.setFont(new java.awt.Font("Lucida Handwriting", 3, 13)); // NOI18N
        jTextField4.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED,
                new java.awt.Color(255, 204, 204), new java.awt.Color(204, 204, 204),
                new java.awt.Color(255, 204, 204), new java.awt.Color(153, 255, 255)));
        jTextField4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField4ActionPerformed(evt);
            }
        });
        getContentPane().add(jTextField4);
        jTextField4.setBounds(250, 280, 340, 30);

        jButton2.setFont(new java.awt.Font("Lucida Handwriting", 3, 13)); // NOI18N
        jButton2.setText("Select a directory...");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton2);
        jButton2.setBounds(610, 280, 182, 29);

        jCheckBox1.setFont(new java.awt.Font("Lucida Handwriting", 3, 13)); // NOI18N
        jCheckBox1.setText("Use Expect Header");
        jCheckBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBox1ActionPerformed(evt);
            }
        });
        getContentPane().add(jCheckBox1);
        jCheckBox1.setBounds(420, 320, 180, 24);

        jPasswordField1.setFont(new java.awt.Font("Lucida Handwriting", 3, 14)); // NOI18N
        jPasswordField1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED,
                new java.awt.Color(255, 153, 153), new java.awt.Color(204, 204, 204),
                new java.awt.Color(255, 204, 204), new java.awt.Color(153, 255, 255)));
        getContentPane().add(jPasswordField1);
        jPasswordField1.setBounds(550, 120, 180, 30);

        jSeparator1.setBackground(new java.awt.Color(204, 204, 204));
        jSeparator1.setForeground(new java.awt.Color(0, 0, 0));
        jSeparator1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        getContentPane().add(jSeparator1);
        jSeparator1.setBounds(10, 202, 850, 10);

        jButton3.setFont(new java.awt.Font("Lucida Handwriting", 3, 14)); // NOI18N
        jButton3.setText("Upload");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton3);
        jButton3.setBounds(310, 320, 102, 29);
        jButton3.getAccessibleContext().setAccessibleName("jButton3");

        jTextArea2.setColumns(20);
        jTextArea2.setFont(new java.awt.Font("Lucida Handwriting", 3, 13)); // NOI18N
        jTextArea2.setRows(5);
        jTextArea2.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        jScrollPane2.setViewportView(jTextArea2);

        getContentPane().add(jScrollPane2);
        jScrollPane2.setBounds(80, 500, 680, 90);

        jLabel6.setBackground(new java.awt.Color(255, 51, 0));
        jLabel6.setFont(new java.awt.Font("Lucida Handwriting", 3, 13)); // NOI18N
        jLabel6.setText("Messages :");
        getContentPane().add(jLabel6);
        jLabel6.setBounds(90, 480, 80, 19);

        jButton4.setFont(new java.awt.Font("Lucida Handwriting", 3, 14)); // NOI18N
        jButton4.setText("Share via Email");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton4);
        jButton4.setBounds(290, 450, 160, 30);

        jCheckBox2.setFont(new java.awt.Font("Lucida Handwriting", 3, 14)); // NOI18N
        jCheckBox2.setText("My Team");
        getContentPane().add(jCheckBox2);
        jCheckBox2.setBounds(310, 360, 120, 23);

        jCheckBox3.setFont(new java.awt.Font("Lucida Handwriting", 3, 14)); // NOI18N
        jCheckBox3.setText("Friends");
        getContentPane().add(jCheckBox3);
        jCheckBox3.setBounds(310, 390, 120, 25);

        jCheckBox4.setFont(new java.awt.Font("Lucida Handwriting", 3, 14)); // NOI18N
        jCheckBox4.setText("Family");
        getContentPane().add(jCheckBox4);
        jCheckBox4.setBounds(310, 420, 87, 25);

        jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/my/swingconnect/Backgroundtemp.jpg"))); // NOI18N
        jLabel5.setText("jLabel5");
        getContentPane().add(jLabel5);
        jLabel5.setBounds(0, 0, 860, 660);

        jOptionPane1.setBackground(new java.awt.Color(0, 0, 255));
        jOptionPane1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        jOptionPane1.setForeground(new java.awt.Color(255, 0, 0));
        getContentPane().add(jOptionPane1);
        jOptionPane1.setBounds(30, 70, 20, 20);

        setBounds(0, 0, 861, 673);
    }// </editor-fold>//GEN-END:initComponents

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
        // TODO add your handling codehere:
    }//GEN-LAST:event_jTextField1ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        //private void sendPost() throws Exception 
        String upLoadServerUri = null;
        int serverResponseCode = 0;
        String Username = jTextField1.getText();
        char[] Password = jPasswordField1.getPassword();
        String passstring = new String(Password);
        System.out.println("Username:" + Username);
        System.out.println("Password:" + passstring);
        int result = uploadFile(Username, passstring);
        if (result == 1) {
            jOptionPane1.showMessageDialog(null, "Login Successfull !!!");
            jButton3.setEnabled(true);
            jButton2.setEnabled(true);
            jButton4.setEnabled(true);
        } else {
            jOptionPane1.showMessageDialog(null, "Login Failed...Please try again !!!");
            jButton3.setEnabled(false);
            jButton2.setEnabled(false);
        }

    }

    public int uploadFile(String User, String Pass) {
        int set = 0;
        String upLoadServerUri = null;
        upLoadServerUri = "http://photo-drop.com/clientlogin.php";
        final String USER_AGENT = "Mozilla/5.0";
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;

        if (User.isEmpty() && Pass.isEmpty()) {

            System.out.println("Please enter the valid User and Pass :");

            return set;
        } else {

            try {
                //String upLoadServerUri = null;
                int serverResponseCode = 0;

                URL url = new URL(upLoadServerUri); //Passing the server complete URL

                // Open a HTTP connection to the URL
                conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true); // Allow Inputs
                conn.setDoOutput(true); // Allow Outputs
                conn.setUseCaches(false); // Don't use a Cached Copy
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("User-Agent", USER_AGENT);
                conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
                //conn.setRequestProperty("Cookie", "Username=Mavericks;");
                String urlParameters = "Username=" + User + "&Password=" + Pass + "&submit=Login";
                dos = new DataOutputStream(conn.getOutputStream());

                dos.writeBytes(urlParameters);
                dos.flush();
                dos.close();

                System.out.println("\nSending 'POST' request to URL : " + url);
                System.out.println("Post parameters : " + urlParameters);
                serverResponseCode = conn.getResponseCode();

                String serverResponseMessage = conn.getResponseMessage();

                System.out.println("HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);

                if (serverResponseCode == 200) {

                    System.out.println("Posted success");
                    set = 1;
                } else if (serverResponseCode == 401) {
                    System.out.println("Invalid Login");

                } else {
                    System.out.println("Error check");
                }

            } catch (MalformedURLException ex) {

                ex.printStackTrace();
                System.out.println("Error");

            } catch (Exception e) {

                e.printStackTrace();
                System.out.println("Error");

            }

            return set;

        }

    }//GEN-LAST:event_jButton1ActionPerformed

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

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed

        //To BROWSE A FILE FROM THE DIRECTORY
        JFileChooser chooser = new JFileChooser();
        //To enable showing hidden file
        chooser.setFileHidingEnabled(false);
        //To Enable selecting directory or files
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        //To enable multiple file selections
        chooser.setMultiSelectionEnabled(true);
        //Choice of user to save or open a file
        chooser.setDialogType(JFileChooser.OPEN_DIALOG);
        chooser.setDialogTitle("Choose a file...");

        //To user to select a file
        if (chooser.showOpenDialog(SwingConnectUI.this) == JFileChooser.APPROVE_OPTION) {
            targetFile = chooser.getSelectedFile();
            String directory = targetFile.getPath();
            jTextField4.setText(targetFile.toString());

            //                       files = new File("/Users/pradil90/Desktop/207dropbox").listFiles();

            files = new File(directory).listFiles();
            for (File file : files) {
                if (file.isFile()) {
                    results.add(file.getAbsolutePath());

                    //                           results.add(file.getName());

                    System.out.println(file);

                    count++;

                    System.out.println(count);

                }

            }

            results.remove(0);
            jButton3.setEnabled(true);

        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        {

            int i = 0;
            while (i < results.size()) {
                String path = results.get(i);
                System.out.println("Printing path" + path);
                targetFile1 = new File(path);

                //                    String targetURL = jTextField3.getSelectedItem().toString();
                //                String targetURL = jTextField3.getSelectedText();
                String targetURL = "http://photo-drop.com/uploader.php";

                //                    if (!targetURL
                //
                //                            .equals(
                //
                //                            cmbURLModel.getElementAt(
                //
                //                            cmbURL.getSelectedIndex()))) {
                //
                //                        cmbURLModel.addElement(targetURL);
                //
                //                    }

                System.out.println(targetURL);
                //From the apache package: the class that implements POST method

                PostMethod filePost = new PostMethod(targetURL);

                filePost.getParams().setBooleanParameter(

                        HttpMethodParams.USE_EXPECT_CONTINUE,

                        jCheckBox1.isSelected());
                try {

                    System.out.println("Uploading " + targetFile1.getName() + " to " + targetURL);
                    jTextArea2.append("Uploading " + targetFile1.getName() + " to " + targetURL);
                    filename = targetFile1.toString();
                    System.out.println(filename);
                    javapostmethod f = new javapostmethod();
                    f.sendPost(filename);

                    Part[] parts = {

                            new FilePart(targetFile1.getName(), targetFile1)

                    };

                    filePost.setRequestEntity(

                            new MultipartRequestEntity(parts,

                                    filePost.getParams())

                    );

                    HttpClient client = new HttpClient();

                    client.getHttpConnectionManager().

                            getParams().setConnectionTimeout(5000);

                    int status = client.executeMethod(filePost);
                    if (status == HttpStatus.SC_OK) {
                        jTextArea2.append("Upload complete, response=" + filePost.getResponseBodyAsString());
                        jTextArea2.append("Uploaded from:" + filename);
                    } else {
                        jTextArea2.append("Upload failed, response=" + HttpStatus.getStatusText(status));
                    }
                } catch (Exception ex) {
                    jTextArea2.append("Error: " + ex.getMessage());
                    ex.printStackTrace();
                } finally {
                    filePost.releaseConnection();
                }

                i++;

            }

            //

        }

    }//GEN-LAST:event_jButton3ActionPerformed

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

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        System.out.println("Share button clicked");
        SendEmail.Mail();
    }//GEN-LAST:event_jButton4ActionPerformed

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

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

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JCheckBox jCheckBox2;
    private javax.swing.JCheckBox jCheckBox3;
    private javax.swing.JCheckBox jCheckBox4;
    private javax.swing.JDialog jDialog1;
    private javax.swing.JDialog jDialog2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JOptionPane jOptionPane1;
    private javax.swing.JPasswordField jPasswordField1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextArea jTextArea2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    // End of variables declaration//GEN-END:variables
}