mydropbox.MyDropboxSwing.java Source code

Java tutorial

Introduction

Here is the source code for mydropbox.MyDropboxSwing.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 mydropbox;

import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Properties;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JOptionPane;
import javax.swing.text.DefaultCaret;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import model.Constants;
import model.FileAttr;
import model.FileChange;
import model.FileCursor;
import model.XmlFactory;

import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.restlet.ext.xml.DomRepresentation;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import service.AutoSyncService;
import service.DownloadService;
import controller.AddNodeTree;
import controller.AppConfig;
import controller.FileWatcher;
import controller.LoginForm;
import frame.ShowFileDelete;
import frame.ShowFileVersion;

/**
 *
 * @author Bunny
 */
public class MyDropboxSwing extends javax.swing.JFrame implements WindowListener {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    DefaultMutableTreeNode root;
    public static File url;
    public static String urls = "/home/nhuan/Dropbox";
    public static final int userId = 1;
    public static ArrayList<FileAttr> list;
    public static ArrayList<FileAttr> diffList;
    public static Properties prop;
    public static DomRepresentation dom;
    public static BlockingQueue<FileChange> lstCommit;
    public static FileAlterationMonitor watcher;
    public static String protocol;
    public static String address;
    public static String port;
    public static String tmpFolder;
    public static String trashFolder;
    public static Thread timer;

    public static FileCursor cursor;
    public static AppConfig config;

    /**
     * Creates new form MyDropboxSwing
     */
    public MyDropboxSwing() {
        initComponents();
        config = new AppConfig();
        prop = config.getProperties();
        loadFileConfig();
        addWindowListener(this);
        lstCommit = new LinkedBlockingQueue<>();
        timer = new Thread(new AutoSyncService());
    }

    /**
     * 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"
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        sign_in = new javax.swing.JButton();
        log_out = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTree1 = new javax.swing.JTree(root);
        jProgressBar1 = new javax.swing.JProgressBar();
        sync = new javax.swing.JButton();
        username = new javax.swing.JTextField();
        password = new javax.swing.JPasswordField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        reload = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jLabel3 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("My Dropbox");

        sign_in.setText("Login");
        sign_in.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sign_inActionPerformed(evt);
            }
        });

        log_out.setText("Watcher");
        log_out.setToolTipText("");
        log_out.setEnabled(false);
        log_out.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                log_outActionPerformed(evt);
            }
        });

        jScrollPane1.setEnabled(false);

        jTree1.setEnabled(false);
        javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("root");
        jTree1.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));
        jScrollPane1.setViewportView(jTree1);

        jProgressBar1.setEnabled(false);

        sync.setEnabled(false);
        sync.setText("Sync");

        password.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                passwordActionPerformed(evt);
            }
        });

        jLabel1.setText("Username");

        jLabel2.setText("Password");

        reload.setEnabled(false);
        reload.setText("Reload");
        reload.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                reloadActionPerformed(evt);
            }
        });
        reload.setVisible(false);
        sync.setVisible(false);
        jTextArea1.setEnabled(false);
        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        DefaultCaret defaultCaret = (DefaultCaret) jTextArea1.getCaret();
        defaultCaret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);

        jScrollPane2.setViewportView(jTextArea1);

        jLabel3.setText("History");

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

        jButton2.setText("Show File Revision");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                .addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout
                        .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup().addGroup(layout
                                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 60,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(167, 167, 167).addComponent(jLabel2,
                                                javax.swing.GroupLayout.PREFERRED_SIZE, 58,
                                                javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(layout.createSequentialGroup()
                                        .addComponent(username, javax.swing.GroupLayout.PREFERRED_SIZE, 202,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(25, 25, 25)
                                        .addComponent(password, javax.swing.GroupLayout.PREFERRED_SIZE, 134,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18)
                                        .addComponent(sign_in, javax.swing.GroupLayout.PREFERRED_SIZE, 66,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18).addComponent(log_out).addGap(44, 44, 44)
                                        .addComponent(reload, javax.swing.GroupLayout.PREFERRED_SIZE, 73,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18).addComponent(sync,
                                                javax.swing.GroupLayout.PREFERRED_SIZE, 73,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addGap(39, 39, 39)
                                .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 152,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(62, 89, Short.MAX_VALUE))
                        .addGroup(
                                layout.createSequentialGroup().addComponent(jLabel3).addGap(0, 0, Short.MAX_VALUE))
                        .addComponent(jScrollPane2).addComponent(jScrollPane1)))
                .addGroup(layout.createSequentialGroup()
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton1).addGap(18, 18, 18).addComponent(jButton2).addGap(142, 142, 142)));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addGroup(layout
                        .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(jLabel1).addComponent(jLabel2))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(username, 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)
                                        .addComponent(sign_in).addComponent(log_out)
                                        .addComponent(reload, javax.swing.GroupLayout.PREFERRED_SIZE, 33,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(sync, javax.swing.GroupLayout.PREFERRED_SIZE, 33,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGroup(layout.createSequentialGroup().addGap(34, 34, 34).addComponent(jProgressBar1,
                                javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
                                javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 99,
                                javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 259,
                                javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jButton1).addComponent(jButton2))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));

        setBounds(0, 0, 900, 534);
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        ShowFileDelete d = new ShowFileDelete();
        d.setVisible(true);
    }

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        ShowFileVersion s = new ShowFileVersion();
        s.setVisible(true);
    }

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

        list = new ArrayList<>();
        diffList = new ArrayList<>();
        sign_in.setEnabled(false);
        jScrollPane1.setEnabled(true);
        jTree1.setEnabled(true);
        sync.setEnabled(true);
        reload.setEnabled(true);
        jTextArea1.setEnabled(true);
        jProgressBar1.setEnabled(true);
        log_out.setEnabled(true);
        username.setEnabled(false);
        password.setEnabled(false);
        File file = new File(urls);
        //Kiem tra dang nhap
        DomRepresentation login = null;
        try {
            login = LoginForm.result(username.getText(), password.getText());
            if (login == null) {
                JOptionPane.showMessageDialog(null, "Retry to login");
                return;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        //Load setting tu file

        //      userId = Integer.parseInt(login.getText("/User/UserId"));
        root = new DefaultMutableTreeNode("Dropbox");
        DefaultTreeModel defaultTreeModel = new DefaultTreeModel(root);
        jTree1.setModel(defaultTreeModel);

        AddNodeTree tree = new AddNodeTree();
        tree.addNode(file, root);
        //Init observer
        FileAlterationObserver fao = new FileAlterationObserver(file);
        fao.addListener(new FileWatcher());
        watcher = new FileAlterationMonitor(Constants.TIME_MONITOR);
        //Watch Dropbox folder
        watcher.addObserver(fao);
        System.out.println("Starting monitor. Ctrc - C to stop");
        try {
            //addAttr(urls);
            watcher.start();
        } catch (Exception ex) {
            Logger.getLogger(MyDropboxSwing.class.getName()).log(Level.SEVERE, null, ex);
        }

        loadXMLDoc();
    }

    private void log_outActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_log_outActionPerformed
        // TODO add your handling code here:
        timer.start();
        //       executor.execute(download);
        //       executor.execute(upload);

    }// GEN-LAST:event_log_outActionPerformed

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

    private void reloadActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_reloadActionPerformed
        // TODO add your handling code here:

        //      root = new DefaultMutableTreeNode("Root");
        //      DefaultTreeModel defaultTreeModel = new DefaultTreeModel(root);
        //      jTree1.setModel(defaultTreeModel);
        //
        //      addNode(file, root);
    }// GEN-LAST:event_reloadActionPerformed

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

        // </editor-fold>

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

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    public static javax.swing.JProgressBar jProgressBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    public static javax.swing.JTextArea jTextArea1;
    public static javax.swing.JTree jTree1;
    private javax.swing.JButton log_out;
    private javax.swing.JPasswordField password;
    private javax.swing.JButton reload;
    private javax.swing.JButton sign_in;
    private javax.swing.JButton sync;
    private javax.swing.JTextField username;

    // End of variables declaration                   

    @Override
    public void windowActivated(WindowEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void windowClosed(WindowEvent e) {
        // TODO Auto-generated method stub
        System.out.println("Closed");
    }

    @Override
    public void windowClosing(WindowEvent e) {
        // TODO Auto-generated method stub
        XmlFactory xmlFactory = new XmlFactory(dom);
        try {
            Document doc = xmlFactory.dom.getDocument();
            xmlFactory.saveFileXml(doc);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        config = new AppConfig();
        config.write("tid", Integer.toString(cursor.getTid()));
        config.write("index", Integer.toString(cursor.getIndex()));
    }

    @Override
    public void windowDeactivated(WindowEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void windowDeiconified(WindowEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void windowIconified(WindowEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void windowOpened(WindowEvent e) {
        // TODO Auto-generated method stub

    }

    public void loadXMLDoc() {
        if (cursor.getTid() * cursor.getIndex() == 0) {

            DownloadService download = new DownloadService();
            XmlFactory xmlFactory = new XmlFactory();
            try {
                Document doc = download.getServer();
                xmlFactory.saveFileXml(doc, Constants.INDEXXML);
                dom = new DomRepresentation();
                dom.setDocument(doc);
            } catch (IllegalStateException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (IOException ex) {
                Logger.getLogger(MyDropboxSwing.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            File index = new File(Constants.INDEXXML);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            //Load file index
            try {
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document doc = builder.parse(index);
                dom = new DomRepresentation();
                dom.setDocument(doc);

            } catch (ParserConfigurationException | SAXException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                DownloadService download = new DownloadService();
                try {
                    Document doc = download.getServer();
                    dom = new DomRepresentation();
                    dom.setDocument(doc);
                } catch (IllegalStateException | IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
            //Kiem tra thu muc moi, them cac file moi, file bi xoa vao list commit
        }
    }

    public void loadFileConfig() {

        String tid = prop.getProperty("tid");
        protocol = prop.getProperty("protocol");
        address = prop.getProperty("address");
        port = prop.getProperty("port");
        urls = prop.getProperty("urls");
        tmpFolder = prop.getProperty("tmp");
        trashFolder = prop.getProperty("trash");
        String index = prop.getProperty("index");
        cursor = new FileCursor(tid, index);
    }
}