archive_v1.Archive_Form.java Source code

Java tutorial

Introduction

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

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.sql.*;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
/*
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
*/
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot3D;
import org.jfree.data.general.DefaultPieDataset;

/**
 *
 * @author root
 */
public class Archive_Form extends javax.swing.JFrame {

    /**
     * Creates new form Archive_Form
     */
    public Archive_Form() {
        initComponents();
    }

    public Archive_Form(String username) {
        this.username = username;
        initComponents();
    }

    Connection conn_archive = null;
    CallableStatement stored_pro = null;
    PreparedStatement ps = null;
    Statement statement1 = null;
    ResultSet rs = null;
    String filename = null, tape_id = null;
    float size = 0;
    String username = "";

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

        jButton1 = new javax.swing.JButton();
        compressArchive = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        verboseArchive = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        tape_id_textfield = new javax.swing.JTextField();
        archive_size_panel = new javax.swing.JPanel();
        jButton2 = new javax.swing.JButton();
        user_label = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

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

        compressArchive.setText("Start Compress Archive");
        compressArchive.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                compressArchiveActionPerformed(evt);
            }
        });

        jButton3.setText("Erase Tape");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        verboseArchive.setText("Start Verbose Archive");
        verboseArchive.setEnabled(false);
        verboseArchive.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                verboseArchiveActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel1.setText("Tape ID");

        tape_id_textfield.setBackground(new java.awt.Color(51, 51, 51));
        tape_id_textfield.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        tape_id_textfield.setForeground(new java.awt.Color(255, 255, 51));

        archive_size_panel.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        javax.swing.GroupLayout archive_size_panelLayout = new javax.swing.GroupLayout(archive_size_panel);
        archive_size_panel.setLayout(archive_size_panelLayout);
        archive_size_panelLayout.setHorizontalGroup(archive_size_panelLayout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 280, Short.MAX_VALUE));
        archive_size_panelLayout.setVerticalGroup(archive_size_panelLayout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 178, Short.MAX_VALUE));

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

        user_label.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        user_label.setForeground(new java.awt.Color(0, 255, 102));

        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)
                        .addGroup(layout.createSequentialGroup().addGap(0, 0, Short.MAX_VALUE).addComponent(
                                user_label, javax.swing.GroupLayout.PREFERRED_SIZE, 73,
                                javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(compressArchive, javax.swing.GroupLayout.DEFAULT_SIZE, 155,
                                                Short.MAX_VALUE)
                                        .addComponent(verboseArchive, javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(jButton3, javax.swing.GroupLayout.Alignment.TRAILING,
                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addGap(39, 39, 39)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout
                                                .createSequentialGroup()
                                                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 68,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addGap(18, 18, 18).addComponent(tape_id_textfield,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE, 198,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addComponent(archive_size_panel,
                                                javax.swing.GroupLayout.Alignment.TRAILING,
                                                javax.swing.GroupLayout.PREFERRED_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addGap(25, 25, 25)));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addGroup(layout.createSequentialGroup()
                                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(compressArchive, javax.swing.GroupLayout.PREFERRED_SIZE, 33,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(verboseArchive, javax.swing.GroupLayout.PREFERRED_SIZE, 41,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 34,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 36,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(
                                                jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 34,
                                                javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(layout.createSequentialGroup()
                                        .addComponent(user_label, javax.swing.GroupLayout.PREFERRED_SIZE, 23,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18)
                                        .addGroup(layout
                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 28,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addComponent(tape_id_textfield))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(archive_size_panel, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(24, 24, 24)));

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

    public void CreateConnection() {
        conn_archive = ConnectDB_test.connectDb();
    }

    public void StoreDatabase() {
        File[] folder = new File("/u01/archive").listFiles();
        for (File vid : folder) {
            filename = vid.getName();
            size = getFileSize("/u01/archive/" + filename);
            tape_id = generateTapeId();
            insertArchive(filename, size, tape_id, username);

        }
    }

    public float folderSize(String fileLocation) {
        float size = 0;
        File[] folder = new File(fileLocation).listFiles();
        for (File file : folder) {
            if (!file.exists() || !file.isFile()) {
                size = size + 0;
            }
            size = size + file.length();
        }

        return ((size / 1024) / 1024) / 1024;
    }

    public String generateTapeId() {
        String id = "";
        DateFormat dateFormat = new SimpleDateFormat("ddMMyyyy");
        Date date = new Date();
        //System.out.println(dateFormat.format(date)); //2014/08/06 15:59:48
        id = dateFormat.format(date);
        return id;
    }

    public long getFileSize(String filename) {
        File file = new File(filename);
        if (!file.exists() || !file.isFile()) {
            return 0;
        }
        return file.length();
    }

    public void insertArchive(String filename, float size, String tape_id, String username) {
        System.out.println(filename);
        System.out.println(size);
        System.out.println(tape_id);
        try {
            ps = conn_archive.prepareStatement(
                    "insert into archive (program_name,tape_id,size,archiver_name) values(?,?,?,?)");
            ps.setString(1, filename);
            ps.setString(2, tape_id);
            ps.setString(3, String.valueOf(size));
            ps.setString(4, username);
            ps.executeUpdate();

        } catch (Exception e) {

        }
    }

    public void execArchive(int compress) {
        String execArchiveCommand = null;
        if (compress == 0) {
            execArchiveCommand = "cd /u01 && tar cvf /dev/st0 archive";
        } else {
            execArchiveCommand = "cd /u01 && tar czf /dev/st0 archive";
        }
        Process proc = null;
        String output = null;
        try {

            ProcessBuilder builder = new ProcessBuilder("/bin/sh", "-c", execArchiveCommand);
            builder.redirectErrorStream(true);
            proc = builder.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));

            output = reader.readLine();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void DeleteFiles(String FileLocation) {
        File[] folder = new File(FileLocation).listFiles();
        for (File file : folder) {
            file.delete();
        }
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        CreateConnection();
        JFileChooser jfc = new JFileChooser();
        jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int a = jfc.showOpenDialog(this);
        if (a == JFileChooser.APPROVE_OPTION) {
            File file = jfc.getSelectedFile();
            try {
                // What to do with the file, e.g. display it in a TextArea
                System.out.println(file.getAbsolutePath());
            } catch (Exception ex) {
                System.out.println("problem accessing file" + file.getAbsolutePath());
            }
            File[] folder = new File(file.getAbsolutePath()).listFiles();
            for (File vid : folder) {
                filename = vid.getName();
                size = getFileSize(file.getAbsolutePath() + "\\" + filename);
                tape_id = generateTapeId();
                insertArchive(filename, size, tape_id, username);

            }
        } else {
            System.out.println("File access cancelled by user.");
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void compressArchiveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_compressArchiveActionPerformed
        // TODO add your handling code here:
        String tape_id = generateTapeId();
        tape_id_textfield.setText(tape_id);
        execArchive(1);
        CreateConnection();
        StoreDatabase();
        JOptionPane.showMessageDialog(null, "All videos will be deleted after you OK this option");
        DeleteFiles("/u01/archive");
    }//GEN-LAST:event_compressArchiveActionPerformed

    private void verboseArchiveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_verboseArchiveActionPerformed
        // TODO add your handling code here:
        execArchive(0);
    }//GEN-LAST:event_verboseArchiveActionPerformed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        user_label.setText(username);
        /*
            
        float folderSize = folderSize("/u01/archive");
        System.out.println(folderSize);
        float usedSize  = (100*folderSize)/6000;
        DefaultPieDataset dataset = new DefaultPieDataset();
        dataset.setValue("Used", usedSize);
        dataset.setValue("UnUsed", (100-usedSize));
            
            
        JFreeChart chart3 = ChartFactory.createPieChart3D("Archive drive status", dataset, true, true, true);
        PiePlot3D plot3 = (PiePlot3D) chart3.getPlot();
        plot3.setForegroundAlpha(0.6f);
        plot3.setCircular(true);
            
        ChartPanel p = new ChartPanel(chart3);
        archive_size_panel.add(p);
        p.setSize(300,180);
        p.setVisible(true);
        */
    }//GEN-LAST:event_formWindowOpened

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

    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        this.dispose();
        Retrieve retrieve = new Retrieve(username);
        retrieve.setDefaultCloseOperation(retrieve.DISPOSE_ON_CLOSE);
        retrieve.setResizable(false);
        retrieve.pack();
        retrieve.setLocationRelativeTo(null);
        retrieve.setLocation(350, 150);
        retrieve.setVisible(true);
    }//GEN-LAST:event_jButton2ActionPerformed

    /**
     * @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()) {
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Archive_Form.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Archive_Form.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Archive_Form.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Archive_Form.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 Archive_Form().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel archive_size_panel;
    private javax.swing.JButton compressArchive;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JTextField tape_id_textfield;
    private javax.swing.JLabel user_label;
    private javax.swing.JButton verboseArchive;
    // End of variables declaration//GEN-END:variables
}