carolina.pegaLatLong.LatLong.java Source code

Java tutorial

Introduction

Here is the source code for carolina.pegaLatLong.LatLong.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 carolina.pegaLatLong;

import java.awt.Color;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ButtonGroup;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.ParseException;

/**
 *
 * @author c01015
 */
public class LatLong extends javax.swing.JFrame {

    private List<InformacoesTxt> listaNaoEncontrados = new ArrayList<>();
    private List<InformacaoGerada> listaResultado = new ArrayList<>();
    private List<InformacoesTxt> listaMaisDeUm = new ArrayList<>();
    private List<InformacoesTxt> listaBadRequest = new ArrayList<>();
    private boolean parar = false;

    /**
     * Creates new form LatLong
     */
    public LatLong() {
        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() {

        painelPai = new javax.swing.JPanel();
        edtTxt = new javax.swing.JTextField();
        btnCarregaTxt = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        edtProcessados = new javax.swing.JLabel();
        edtEncontrados = new javax.swing.JLabel();
        edtMaisDeUm = new javax.swing.JLabel();
        edtNaoEncontrados = new javax.swing.JLabel();
        edtStatus = new javax.swing.JLabel();
        btnGerar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                parar(evt);
            }
        });

        painelPai.setBackground(new java.awt.Color(0, 102, 255));

        edtTxt.setEditable(false);
        edtTxt.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                edtTxtActionPerformed(evt);
            }
        });

        btnCarregaTxt.setText("Carregar TXT");
        btnCarregaTxt.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCarregaTxtActionPerformed(evt);
            }
        });

        edtProcessados.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N

        edtEncontrados.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N

        edtMaisDeUm.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N

        edtNaoEncontrados.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N

        edtStatus.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(jPanel2Layout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel2Layout.createSequentialGroup().addContainerGap()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(edtNaoEncontrados, javax.swing.GroupLayout.Alignment.TRAILING,
                                        javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
                                        Short.MAX_VALUE)
                                .addComponent(edtMaisDeUm, javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(edtEncontrados, javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(edtProcessados, javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addContainerGap())
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
                        jPanel2Layout.createSequentialGroup().addGap(0, 73, Short.MAX_VALUE).addComponent(edtStatus,
                                javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(55, 55, 55)));
        jPanel2Layout.setVerticalGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel2Layout.createSequentialGroup().addGap(6, 6, 6)
                        .addComponent(edtStatus, javax.swing.GroupLayout.DEFAULT_SIZE, 32, Short.MAX_VALUE)
                        .addGap(18, 18, 18)
                        .addComponent(edtProcessados, javax.swing.GroupLayout.PREFERRED_SIZE, 24,
                                javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(edtEncontrados, javax.swing.GroupLayout.PREFERRED_SIZE, 25,
                                javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(edtMaisDeUm, javax.swing.GroupLayout.PREFERRED_SIZE, 25,
                                javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(edtNaoEncontrados, javax.swing.GroupLayout.PREFERRED_SIZE, 27,
                                javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap()));

        btnGerar.setText("Gerar CSV");
        btnGerar.setEnabled(false);
        btnGerar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGerarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout painelPaiLayout = new javax.swing.GroupLayout(painelPai);
        painelPai.setLayout(painelPaiLayout);
        painelPaiLayout.setHorizontalGroup(painelPaiLayout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(painelPaiLayout.createSequentialGroup().addContainerGap().addGroup(painelPaiLayout
                        .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(painelPaiLayout.createSequentialGroup().addComponent(btnCarregaTxt)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(edtTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 199,
                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE,
                                javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(painelPaiLayout.createSequentialGroup().addGap(108, 108, 108)
                                .addComponent(btnGerar)))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
        painelPaiLayout.setVerticalGroup(painelPaiLayout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(painelPaiLayout.createSequentialGroup().addContainerGap().addGroup(painelPaiLayout
                        .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(btnCarregaTxt)
                        .addComponent(edtTxt, javax.swing.GroupLayout.PREFERRED_SIZE,
                                javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE,
                                javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(btnGerar)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, 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(painelPai, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
                        Short.MAX_VALUE));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(
                painelPai, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
                Short.MAX_VALUE));

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

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

    private void btnCarregaTxtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCarregaTxtActionPerformed
        // TODO add your handling code here
        JFileChooser escolhe = new JFileChooser();
        //        escolhe.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        //        escolhe.setAcceptAllFileFilterUsed(false);
        int i = escolhe.showOpenDialog(null);
        if (i != 1) {
            String caminho = escolhe.getSelectedFile().getPath();
            edtTxt.setText(escolhe.getSelectedFile().getName());
            btnCarregaTxt.setEnabled(false);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        buscaLtLong(carregaRetorna(caminho));
                    } catch (IOException ex) {
                        Logger.getLogger(LatLong.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (ParseException ex) {
                        Logger.getLogger(LatLong.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }).start();

        }

    }//GEN-LAST:event_btnCarregaTxtActionPerformed

    private void btnGerarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGerarActionPerformed
        // TODO add your handling code here:
        List<JRadioButton> radios = new ArrayList<>();
        JPanel painel = new JPanel();
        JRadioButton btnEncontrados = new JRadioButton("Encontrados \n");
        JRadioButton btnNaoEncontrados = new JRadioButton("No encontrados");
        JRadioButton btnEncontradosMais = new JRadioButton("Mais de um encontrados");
        JRadioButton btnTudo = new JRadioButton("Tudo");
        ButtonGroup btnGroup = new ButtonGroup();
        btnGroup.add(btnTudo);
        btnGroup.add(btnEncontrados);
        btnGroup.add(btnNaoEncontrados);
        btnGroup.add(btnEncontradosMais);

        //painel.add(btnTudo);
        painel.add(btnEncontrados);
        painel.add(btnNaoEncontrados);
        painel.add(btnEncontradosMais);
        JOptionPane.showMessageDialog(null, painel, "Escolha uma opo:", JOptionPane.QUESTION_MESSAGE);
        if (btnTudo.isSelected()) {
            System.err.println("Tudo selecionado!");
        } else if (btnNaoEncontrados.isSelected()) {
            System.err.println("No encontrados!");
        } else if (btnEncontrados.isSelected()) {
            try {
                geraCsv(listaResultado);
            } catch (IOException ex) {
                Logger.getLogger(LatLong.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else if (btnEncontradosMais.isSelected()) {
            System.err.println("Encontrados mais");
        }

    }//GEN-LAST:event_btnGerarActionPerformed

    private void parar(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_parar
        // TODO add your handling code here:
        parar = true;

    }//GEN-LAST:event_parar

    private List<InformacoesTxt> carregaRetorna(String path) throws FileNotFoundException, IOException {
        List<InformacoesTxt> listaInfo = new ArrayList<>();

        //String caminho = "externfiles\\emitente3.txt";
        FileInputStream file = new FileInputStream(path);
        InputStreamReader input = new InputStreamReader(file, java.nio.charset.StandardCharsets.ISO_8859_1);
        BufferedReader br = new BufferedReader(input);
        String pega;
        String mostra = "";
        System.err.println(mostra);
        int cont = 0;
        // Nome do Emitente,CNPJ,IE,Endereo,Bairro,CEP,Cidade,UF,Pais,
        while ((pega = br.readLine()) != null) {
            if (cont > 0) {
                String neew = LatLong.removerAcentos(pega.toLowerCase());
                String vet[] = neew.split(";");
                InformacoesTxt info = new InformacoesTxt();
                info.setEndereco(vet[0]);
                info.setCep(vet[1]);
                info.setBairro(vet[2]);
                info.setCidade(vet[3]);
                info.setUf(vet[4]);
                info.setPais(vet[5]);
                listaInfo.add(info);
            }
            cont++;
        }

        return listaInfo;
    }

    private void buscaLtLong(List<InformacoesTxt> lista) throws MalformedURLException, IOException, ParseException {
        String status = "Processando...";
        edtEncontrados.setText("Encontrados:");
        edtNaoEncontrados.setText("No encontrados:");
        edtMaisDeUm.setText("Mais de um encontrados:");
        edtProcessados.setText("Processados:");
        edtStatus.setText(status);
        int processados = 1;

        URL ul;

        for (InformacoesTxt in : lista) {
            if (processados == 2499) {
                break;
            }
            edtProcessados.setText("Processados: " + processados);
            String resto = "";
            String vet[] = in.getEndereco().split(" ");

            for (String vet1 : vet) {
                resto += vet1 + "+";
            }

            //            String vet2[] = in.getBairro().split(" ");
            //            for (String vet21 : vet2) {
            //                resto += vet21 + "+";
            //            }
            //
            //            String vet3[] = in.getCep().split(" ");
            //            for (String vet31 : vet3) {
            //                resto += vet31 + "+";
            //            }
            String vet4[] = in.getCidade().split(" ");
            for (String vet41 : vet4) {
                resto += vet41 + "+";
            }

            ul = new URL("https://maps.googleapis.com/maps/api/geocode/json?address=" + resto
                    + "&key=AIzaSyDFg9GJIbgHKbZP3b5H2qRV_cAhhvlBaoE");
            //System.err.println("URL: " + ul);
            HttpURLConnection conn = (HttpURLConnection) ul.openConnection();
            // conn.setRequestMethod("GET");
            //conn.setRequestProperty("Accept", "application/json");

            if (conn.getResponseCode() != 200) {
                listaBadRequest.add(in);
                System.err.println("Codigo: " + conn.getResponseMessage());
                //System.err.println("URL: " + ul);
                //JOptionPane.showMessageDialog(null, "Falha ao obter a localizao!");
                //break;
            } else {
                BufferedReader bf = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String pega = "";
                String result = "";
                while ((pega = bf.readLine()) != null) {
                    result += pega;
                }
                System.err.println(result);

                org.json.simple.parser.JSONParser parser = new org.json.simple.parser.JSONParser();
                Object obj = parser.parse(result);

                JSONObject tudo = (JSONObject) obj;

                JSONArray arrayResultado = (JSONArray) tudo.get("results");
                if (arrayResultado.isEmpty()) {
                    listaNaoEncontrados.add(in);
                    edtNaoEncontrados.setText("No encontrados: " + listaNaoEncontrados.size());
                } else if (arrayResultado.size() == 1) {
                    JSONObject primeiro = (JSONObject) arrayResultado.get(0);
                    JSONObject jsonObject3 = (JSONObject) primeiro.get("geometry");
                    JSONObject location = (JSONObject) jsonObject3.get("location");
                    InformacaoGerada gerado = new InformacaoGerada();
                    gerado.setEnderecoFormatado(primeiro.get("formatted_address").toString());
                    String latitude = location.get("lat").toString().replace(".", ",");
                    gerado.setLatitude(latitude);
                    String longitude = location.get("lng").toString().replace(".", ",");
                    gerado.setLongitude(longitude);
                    listaResultado.add(gerado);
                    edtEncontrados.setText("Encontrados: " + listaResultado.size());
                } else {
                    listaMaisDeUm.add(in);
                    edtMaisDeUm.setText("Mais de um encontrados: " + listaMaisDeUm.size());
                }

                //                System.err.println("Endereo Formatado: " + primeiro.get("formatted_address"));
                //                System.out.println("Lat = " + location.get("lat"));
                //                System.out.println("Lng = " + location.get("lng"));
            }

            processados++;
        }

        edtStatus.setForeground(Color.GREEN);
        edtStatus.setText("Concludo");
        btnGerar.setEnabled(true);

    }

    private void geraCsv(List<InformacaoGerada> gerados) throws IOException {
        JFileChooser escolha = new JFileChooser();
        escolha.setAcceptAllFileFilterUsed(false);
        escolha.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int i = escolha.showSaveDialog(null);
        if (i != 1) {
            System.err.println(escolha.getSelectedFile().getPath() + "\\teste.txt");
            String caminho = escolha.getSelectedFile().getPath();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(caminho + "\\teste.csv"), StandardCharsets.ISO_8859_1));
            //FileWriter arquivo = new FileWriter(caminho + "\\teste.csv");
            //PrintWriter writer = new PrintWriter(arquivo);
            writer.write("Endereco;Latitude;Longitude");
            writer.newLine();

            gerados.stream().forEach((gerado) -> {
                try {
                    System.err.println(gerado.getEnderecoFormatado() + ";" + gerado.getLatitude() + ";"
                            + gerado.getLongitude() + "\n");
                    writer.write(gerado.getEnderecoFormatado() + ";" + gerado.getLatitude() + ";"
                            + gerado.getLongitude());
                    writer.newLine();
                } catch (IOException ex) {
                    System.err.println("Erro");
                }
            });

            writer.close();
            JOptionPane.showMessageDialog(null, "Finalizado!");

        }

    }

    public static String removerAcentos(String palavra) {
        palavra = palavra.replaceAll("[]", "a");
        return palavra;
    }

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

        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(LatLong.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);

        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(LatLong.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);

        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(LatLong.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 LatLong().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCarregaTxt;
    private javax.swing.JButton btnGerar;
    private javax.swing.JLabel edtEncontrados;
    private javax.swing.JLabel edtMaisDeUm;
    private javax.swing.JLabel edtNaoEncontrados;
    private javax.swing.JLabel edtProcessados;
    private javax.swing.JLabel edtStatus;
    private javax.swing.JTextField edtTxt;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel painelPai;
    // End of variables declaration//GEN-END:variables
}