ventanas.parqueadero.NewimportContract.java Source code

Java tutorial

Introduction

Here is the source code for ventanas.parqueadero.NewimportContract.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 ventanas.parqueadero;

import controllers.ClientProviderJpaController;
import controllers.ContractsJpaController;
import controllers.PersonJpaController;
import controllers.UserContractJpaController;
import entities.ClientProvider;
import entities.Contracts;
import entities.Person;
import entities.UserContract;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.Query;
import javax.swing.JOptionPane;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 *
 * @author macbookpro
 */
public class NewimportContract extends javax.swing.JDialog {

    PersonJpaController personController;
    ContractsJpaController contractsController;
    UserContractJpaController usercontractController;
    ClientProviderJpaController clientProviderController;
    File file = null;

    /**
     * Creates new form importContract
     *
     * @param parent
     * @param modal
     */
    public NewimportContract(java.awt.Frame parent, boolean modal) {
        super(parent, modal);

        personController = new PersonJpaController();
        contractsController = new ContractsJpaController();
        usercontractController = new UserContractJpaController();
        clientProviderController = new ClientProviderJpaController();

        initComponents();
        Calendar now = Calendar.getInstance();
        now.set(Calendar.DAY_OF_MONTH, 1);

        dateDesde.setDate(now.getTime());

        now.set(Calendar.DAY_OF_MONTH, now.getActualMaximum(Calendar.DATE));

        dateHasta.setDate(now.getTime());
    }

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

        selector = new javax.swing.JFileChooser();
        jPanel1 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel8 = new javax.swing.JLabel();
        pathFile = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        dateDesde = new com.toedter.calendar.JDateChooser();
        dateDesde.setDate(new Date());
        jLabel9 = new javax.swing.JLabel();
        dateHasta = new com.toedter.calendar.JDateChooser();
        dateHasta.setDate(new Date());
        importbtn = new javax.swing.JButton();
        progressBar = new javax.swing.JProgressBar();

        selector.setFileFilter(new MyCustomFilter());

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));

        jLabel5.setFont(new java.awt.Font("Arial", 1, 24)); // NOI18N
        jLabel5.setText("Cargar contratos");

        jLabel8.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        jLabel8.setText("Cargar archivo: ");

        pathFile.setEditable(false);

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

        jLabel7.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel7.setText("Desde:");

        jLabel9.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        jLabel9.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel9.setText("Hasta:");

        importbtn.setText("Importar");
        importbtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                importbtnActionPerformed(evt);
            }
        });

        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().addGroup(jPanel1Layout
                        .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup().addComponent(jLabel5).addGap(18, 18, 18)
                                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 408,
                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(jPanel1Layout.createSequentialGroup().addComponent(jLabel8)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(pathFile, javax.swing.GroupLayout.PREFERRED_SIZE, 284,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 154,
                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(jPanel1Layout.createSequentialGroup().addGroup(jPanel1Layout
                                .createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 106,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(dateDesde, javax.swing.GroupLayout.PREFERRED_SIZE, 174,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 94,
                                                javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, 215,
                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(jPanel1Layout
                                        .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addComponent(importbtn, javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(dateHasta, javax.swing.GroupLayout.DEFAULT_SIZE, 159,
                                                Short.MAX_VALUE))))
                        .addContainerGap(9, Short.MAX_VALUE)));
        jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup().addGroup(jPanel1Layout
                        .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup().addGap(17, 17, 17).addComponent(jLabel5))
                        .addGroup(jPanel1Layout.createSequentialGroup().addGap(25, 25, 25).addComponent(jSeparator1,
                                javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
                                javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 29,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(pathFile, javax.swing.GroupLayout.PREFERRED_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jButton1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 30,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(dateDesde, javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout
                                        .createSequentialGroup().addGap(0, 0, Short.MAX_VALUE)
                                        .addGroup(jPanel1Layout
                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                .addComponent(jLabel9, javax.swing.GroupLayout.Alignment.TRAILING,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE, 30,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addComponent(dateHasta, javax.swing.GroupLayout.Alignment.TRAILING,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(jPanel1Layout.createSequentialGroup().addGap(18, 18, 18)
                                        .addComponent(importbtn))
                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
                                        jPanel1Layout.createSequentialGroup().addGap(27, 27, 27).addComponent(
                                                progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, 20,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addContainerGap(22, Short.MAX_VALUE)));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
                        Short.MAX_VALUE));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(
                jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
                Short.MAX_VALUE));

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

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

        //validar las fechas
        Date from = dateDesde.getDate();
        Date until = dateHasta.getDate();
        boolean isValid = datesValidation(from, until);
        if (!isValid) {
            JOptionPane.showMessageDialog(this, "Ya existe contratos en las fechas" + " indicadas", "Error",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }

        //Crear un nuevo periodo de contrato
        Contracts contract = new Contracts();
        contract.setDateStart(from);
        contract.setDateEnd(until);
        contractsController.create(contract);

        //barra de progreso
        progressBar.setMinimum(0);
        try {
            //leer el archivo
            FileInputStream fis = new FileInputStream(this.file);
            XSSFWorkbook workbook = new XSSFWorkbook(fis);

            //Get first sheet from the workbook
            XSSFSheet sheet = workbook.getSheetAt(0);

            //Get iterator to all the rows in current sheet
            Iterator<Row> rowIterator = sheet.iterator();
            int cont = 0;
            while (rowIterator.hasNext()) {

                Row row = rowIterator.next();
                if (row.getCell(0) != null) {
                    cont++;
                }

            }

            progressBar.setMaximum(cont);
            cont = 0;

            rowIterator = sheet.iterator();
            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();

                if (row.getCell(0) == null) {
                    continue;
                }
                //buscar o crear la persona
                Person person = findPerson(row);
                //buscar o crear el client
                ClientProvider client = findClient(person);

                UserContract usercontract = new UserContract();
                usercontract.setClient(client);
                usercontract.setContract(contract);
                usercontract.setLicensePlate(row.getCell(2).getStringCellValue());
                usercontractController.create(usercontract);

                cont++;
                progressBar.setValue(cont);
            }
            fis.close();

            JOptionPane.showMessageDialog(this, "Importacin realizada con " + "xito", "Informacin",
                    JOptionPane.INFORMATION_MESSAGE, null);
            this.dispose();
            ImportContracts.verTabla();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(NewimportContract.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this, "Error en la importacin", "Error", JOptionPane.ERROR_MESSAGE,
                    null);
            Logger.getLogger(NewimportContract.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_importbtnActionPerformed

    /**
     * 
     * @param from Date
     * @param until Date
     * @return boolean
     */
    private boolean datesValidation(Date from, Date until) {

        if (from.after(until)) {
            return false;
        }

        Query q = contractsController.getEm().createNamedQuery("Contracts.findByDates");
        q.setParameter("start", from);
        q.setParameter("end", until);
        List<Contracts> contracts = q.getResultList();
        return (contracts.isEmpty()) ? true : false;
    }

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

        int returnVal = selector.showOpenDialog(this);
        if (returnVal == selector.APPROVE_OPTION) {
            this.file = selector.getSelectedFile();
            pathFile.setText(file.getAbsolutePath());
            Boolean isCSV = file.getAbsolutePath().endsWith(".xlsx");
            if (!isCSV) {
                importbtn.setEnabled(false);
                JOptionPane.showMessageDialog(this, "Solo puede importar archivos con extensin .xlsx", "Error",
                        JOptionPane.ERROR_MESSAGE);
            } else {
                importbtn.setEnabled(true);
            }
        } else {
            System.out.println("File access cancelled by user.");
        }

    }//GEN-LAST:event_jButton1ActionPerformed

    /**
     *
     * @param row Row
     * @return Person
     */
    private Person findPerson(Row row) {
        //For each row, iterate through each columns
        Cell passport = row.getCell(0); //passport
        Cell names = row.getCell(1); //names

        //buscar en la base de datos
        Query q = personController.getEntityManager().createNamedQuery(Person.FIND_BY_PASSPORT);
        //        q.setParameter("passport", names.getNumericCellValue()+"");
        q.setParameter("passport", passport.getStringCellValue());
        List<Person> persons = q.getResultList();
        Person person = null;
        if (persons.isEmpty()) {
            person = new Person();
            person.setNames(names.getStringCellValue());
            person.setAddress("S/N");
            person.setSex("S/N");
            person.setEmail("");
            person.setPassport(passport.getStringCellValue());
            personController.create(person);
        } else {
            person = persons.get(0);
            System.out.println("Encontrada" + person.getPassport() + " " + person.getNames());
        }
        return person;
    }

    /**
     *
     * @param person
     * @return
     */
    private ClientProvider findClient(Person person) {

        Query q = clientProviderController.getEm().createNamedQuery("ClientProvider.findByPerson");
        q.setParameter("personId", person);
        List<ClientProvider> clients = q.getResultList();
        ClientProvider client = null;
        if (clients.isEmpty()) {
            //crear cliente
            client = new ClientProvider();
            client.setPersonId(person);
            client.setActiveclient(Boolean.TRUE);
            client.setClient(Boolean.TRUE);
            clientProviderController.create(client);
        } else {
            client = clients.get(0);
        }

        return client;
    }

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

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                NewimportContract dialog = new NewimportContract(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    class MyCustomFilter extends javax.swing.filechooser.FileFilter {

        @Override
        public boolean accept(File file) {
            //files with ".csv" extension
            return file.getAbsolutePath().endsWith(".xlsx");
        }

        @Override
        public String getDescription() {
            // This description will be displayed in the dialog,
            // hard-coded = ugly, should be done via I18N
            return "xlsx documents (*.xlsx)";
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private com.toedter.calendar.JDateChooser dateDesde;
    private com.toedter.calendar.JDateChooser dateHasta;
    private javax.swing.JButton importbtn;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextField pathFile;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JFileChooser selector;
    // End of variables declaration//GEN-END:variables
}