br.com.gsoftwares.util.ImportClient.java Source code

Java tutorial

Introduction

Here is the source code for br.com.gsoftwares.util.ImportClient.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 br.com.gsoftwares.util;

import br.com.gsoftwares.LerArqXML;
import br.com.gsoftwares.dao.ClienteDao;
import br.com.gsoftwares.model.Cliente;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

/**
 *
 * @author Gustavo Steinhoefel
 */
public class ImportClient extends javax.swing.JDialog {

    private String CPF = "";
    private String Tipo = "";
    private String Nome = "";
    private String Apelido = "";
    private String Rua = "";
    private String Bairro = "";
    private String Cod_Mun = "";
    private String Cidade = "";
    private String Estado = "";
    private String Cep = "";
    private String Telefone = "";
    private String Tipo_ins = "9";
    private String Ins = "";
    private String Comp = "";
    private String numero = "";
    private String email = "";

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

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

        jFileChooser1 = new javax.swing.JFileChooser();
        jTextField1 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Importar Clientes para o Sistema");

        jLabel1.setText("Caminho do arquivo:");

        jButton1.setIcon(new javax.swing.ImageIcon(
                getClass().getResource("/br/com/gsoftwares/imagens/1480357371_free-01.png"))); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton4.setIcon(new javax.swing.ImageIcon(
                getClass().getResource("/br/com/gsoftwares/imagens/1480357534_free-05.png"))); // NOI18N
        jButton4.setText("Import");
        jButton4.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton4.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
        jButton4.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton4.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                jButton4FocusGained(evt);
            }
        });
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jButton5.setIcon(new javax.swing.ImageIcon(
                getClass().getResource("/br/com/gsoftwares/imagens/1480357355_free-09.png"))); // NOI18N
        jButton5.setText("Fechar");
        jButton5.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton5.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
        jButton5.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton5.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                jButton5FocusGained(evt);
            }
        });
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        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()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 634,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jButton1))
                                .addComponent(jLabel1))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
                        layout.createSequentialGroup()
                                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 75,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 75,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addContainerGap()));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addContainerGap().addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jTextField1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jButton5, javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(jButton4, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));

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

    private void jButton4FocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jButton4FocusGained
        try {
            Botao j = new Botao();
            j.BotaoEnter(jButton4);
        } catch (Exception ex) {
            //Logger.getLogger(CadNfe.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButton4FocusGained

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        if ((!jTextField1.getText().isEmpty() || (!jTextField1.getText().equals("")))) {
            try {
                lerarq(jTextField1.getText());
                //Salvar();
            } catch (Exception ex) {
                Logger.getLogger(ImportClient.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            JOptionPane.showMessageDialog(null, "Favor Procurar arquivo a ser Importado!");
            jTextField1.requestFocusInWindow();
        }
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton5FocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jButton5FocusGained
        try {
            Botao j = new Botao();
            j.BotaoEnter(jButton5);
        } catch (Exception ex) {
            //Logger.getLogger(CadNfe.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButton5FocusGained

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        dispose();
    }//GEN-LAST:event_jButton5ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        JFileChooser abrir = new JFileChooser();
        int retorno = abrir.showOpenDialog(null);
        abrir.setFileFilter(new FileNameExtensionFilter("Image files", "xml", "XML"));
        abrir.setAcceptAllFileFilterUsed(false);
        if (retorno == JFileChooser.APPROVE_OPTION) {
            jTextField1.setText(abrir.getSelectedFile().getAbsolutePath());
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
     * @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(ImportClient.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        }
        //</editor-fold>

        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(() -> {
            ImportClient dialog = new ImportClient(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);
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JFileChooser jFileChooser1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables

    private void lerarq(String caminho) throws Exception {
        //Aqui voc informa o nome do arquivo XML.  
        File f = new File(caminho);
        File[] arquivos = f.listFiles();
        //Criamos uma classe SAXBuilder que vai processar o XML  
        for (File fileTmp : arquivos) {

            SAXBuilder sb = new SAXBuilder();

            //Este documento agora possui toda a estrutura do arquivo.  
            Document d;
            try {
                d = sb.build(fileTmp);
                //Recuperamos o elemento root  
                Element nfe = d.getRootElement();

                //Recuperamos os atributos filhos (Attributes)  
                List atributes = nfe.getAttributes();
                Iterator i_atr = atributes.iterator();

                //Iteramos com os atributos filhos  
                while (i_atr.hasNext()) {
                    Attribute atrib = (Attribute) i_atr.next();
                    //System.out.println("\nattribute de (" + nfe.getName() + "):" + atrib.getName() + " - valor: " + atrib.getValue());
                }
                //Recuperamos os elementos filhos (children)  
                List elements = nfe.getChildren();
                Iterator i = elements.iterator();

                //Iteramos com os elementos filhos, e filhos do dos filhos  
                while (i.hasNext()) {
                    Element element = (Element) i.next();
                    //System.out.println("element:" + element.getName());
                    trataElement(element);
                }
                Salvar();
            } catch (JDOMException | IOException ex) {
                Logger.getLogger(LerArqXML.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        JOptionPane.showMessageDialog(null, "Cadastro efetuado com sucesso!", "", JOptionPane.INFORMATION_MESSAGE);
    }

    private void trataElement(Element element) throws Exception {

        //Recuperamos os atributos filhos (Attributes)  
        List atributes = element.getAttributes();
        Iterator i_atr = atributes.iterator();

        //Iteramos com os atributos filhos  
        while (i_atr.hasNext()) {
            Attribute atrib = (Attribute) i_atr.next();
            //System.out.println("\nattribute de (" + element.getName() + "):" + atrib.getName() + " - valor: " + atrib.getValue());
        }
        //Recuperamos os elementos filhos (children)  
        List elements = element.getChildren();
        Iterator it = elements.iterator();

        //Iteramos com os elementos filhos, e filhos do dos filhos  
        while (it.hasNext()) {
            Element el = (Element) it.next();
            //System.out.println(el.getName() + " - " + el.getText());
            switch (el.getName()) {
            case "CPF":
                CPF = el.getText();
                Tipo = "F";
                break;
            case "CNPJ":
                CPF = el.getText();
                Tipo = "J";
                break;
            case "xNome":
                Nome = el.getText();
                Apelido = "";
                break;
            case "xLgr":
                Rua = el.getText();
                break;
            case "nro":
                numero = el.getText();
                break;
            case "xCpl":
                Comp = el.getText();
                break;
            case "xBairro":
                Bairro = el.getText();
                break;
            case "cMun":
                Cod_Mun = el.getText();
                break;
            case "xMun":
                Cidade = el.getText();
                break;
            case "UF":
                Estado = el.getText();
                break;
            case "CEP":
                Cep = el.getText();
                break;
            case "fone":
                Telefone = el.getText();
                break;
            case "IE":
                if (el.getText().equals("ISENTO")) {
                    Tipo_ins = "2";
                    Ins = "ISENTO";
                } else {
                    if (el.getText().contains("^[0-9]*$")) {
                        Tipo_ins = "1";
                        Ins = el.getText();
                    } else {
                        Tipo_ins = "9";
                        Ins = "";
                    }
                    break;
                }
            case "email":
                email = el.getText();
                break;
            }

            trataElement(el);
        }
    }

    public void Salvar() throws Exception {
        ClienteDao dao = new ClienteDao();
        Cliente s = new Cliente();
        s.setNome(Nome);
        s.setApelido(Apelido);
        s.setCpf(CPF);
        s.setTipo_pessoa(Tipo);
        s.setLogradouro(Rua);
        s.setNumero(numero);
        s.setComplemento(Comp);
        s.setBairro(Bairro);
        s.setCidade(Cidade);
        s.setCep(Cep);
        s.setEstado(Estado);
        s.setCod_municipio(Cod_Mun);
        if (Tipo_ins.equals("")) {
            s.setTipo_inscricao("3");
        } else {
            s.setTipo_inscricao(Tipo_ins);
        }
        s.setInscricao_estadual(Ins);
        if (!Telefone.equals("")) {
            s.setTelefone("51" + Telefone);
        } else {
            s.setTelefone(Telefone);
        }
        s.setContato("");
        s.setEmail(email);
        s.setStatus("0");
        s.setDel("0");
        dao.salvar_cliente(s);
        limpaDados();
    }

    private void limpaDados() {
        jTextField1.setText("");
        CPF = "";
        Tipo = "";
        Nome = "";
        Apelido = "";
        Rua = "";
        Bairro = "";
        Cod_Mun = "";
        Cidade = "";
        Estado = "";
        Cep = "";
        Telefone = "";
        Tipo_ins = "9";
        Ins = "";
        Comp = "";
        numero = "";
        email = "";
    }
}