Programa em Java para criar Chaves

16/11/2018

7

Olá pessoal nesse feriado resolvi criar um programa que gera chaves. Segue abaixo:

package principal;

import java.util.ArrayList;
import java.util.Random;

/**
 *
 * @author Nelson Anjos - (71)996116119 - nelson.contatos@gmail.com - Canal Ti de Plantão no Youtube
 * @version 1.0
 */
public class Metodos {

    private ArrayList<Object> alfaNum = new ArrayList();
    private String chave = "";
    private ArrayList<String> lista = new ArrayList();

    public ArrayList<String> getLista() {
        return lista;
    }

    public void listaParaSorteio(boolean c, boolean n, boolean s) {
        if (c == true) {
            for (char ch = ''A''; ch <= ''Z''; ch++) {
                alfaNum.add(ch);
            }
        }
        if (n == true) {
            for (int i = 1; i < 10; i++) {
                alfaNum.add(i);
            }
        }
        if (s == true) {
            alfaNum.add(''$'');
            alfaNum.add(''%'');
            alfaNum.add(''*'');
            alfaNum.add(''#'');
            alfaNum.add(''!'');
            alfaNum.add(''@'');
        }
    }

    public void gerarChave(int qtd, boolean c, boolean n, boolean s) {
        listaParaSorteio(c, n, s);
        Random r = new Random();
        for (int a = 0; a < qtd; a++) {

            for (int i = 0; i < 15; i++) { //Gera 15 caracteres
                if (i % 5 == 0 && i != 0) {
                    chave += " - ";
                }
                Object car = alfaNum.get(r.nextInt(alfaNum.size()));
                chave += car;

            }
            lista.add(chave);
            chave = "";
        }

    }
}


[code=java]
package principal;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JOptionPane;

public class ConexaoUtil {

String caminho = JOptionPane.showInputDialog(null, "Digite o caminho do Servidor:");
String porta = JOptionPane.showInputDialog(null, "Digite a porta do Servidor:");
String nome = JOptionPane.showInputDialog(null, "Digite o nome do Servidor:");
String usuario = JOptionPane.showInputDialog(null, "Digite o usuario do Servidor:");
String senha = JOptionPane.showInputDialog(null, "Digite a senha do Servidor:");

public static ConexaoUtil getInstanec() {
if (conexaoUtil == null) {
conexaoUtil = new ConexaoUtil();
}
return conexaoUtil;
}

private final String URL = "jdbc:mysql://" + caminho + ":" + porta + "/" + nome;
private final String USER = usuario;
private final String PASS = senha;
private static ConexaoUtil conexaoUtil;

public Connection getConnection() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection(URL, USER, PASS);
}
Responder

Post mais votado

16/11/2018

package principal;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Nelson Anjos - (71)996116119 - nelson.contatos@gmail.com - Canal Ti de Plantão no Youtube
 * @version 1.0
 */
public class View extends javax.swing.JFrame {

    public View() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        quantidade = new javax.swing.JSpinner();
        exportarParaTxt = new javax.swing.JButton();
        exportarParaBD = new javax.swing.JButton();
        letrasChk = new javax.swing.JCheckBox();
        simbolosChk = new javax.swing.JCheckBox();
        numerosChk = new javax.swing.JCheckBox();
        gerar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        listaTbl = new javax.swing.JTable();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(new java.awt.Color(255, 255, 255));

        jLabel1.setFont(new java.awt.Font("sansserif", 0, 14)); // NOI18N
        jLabel1.setText("Digite a quantidade de chaves: ");

        quantidade.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        quantidade.setValue(1);

        exportarParaTxt.setText("Exportar para arquivo de texto");
        exportarParaTxt.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        exportarParaTxt.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exportarParaTxtActionPerformed(evt);
            }
        });

        exportarParaBD.setText("Exportar para banco");
        exportarParaBD.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        exportarParaBD.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exportarParaBDActionPerformed(evt);
            }
        });

        letrasChk.setSelected(true);
        letrasChk.setText("Letras");
        letrasChk.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        letrasChk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                letrasChkActionPerformed(evt);
            }
        });

        simbolosChk.setText("Simbolos");
        simbolosChk.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));

        numerosChk.setText("Números");
        numerosChk.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));

        gerar.setText("Gerar Chave(s) com: ");
        gerar.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        gerar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                gerarActionPerformed(evt);
            }
        });

        listaTbl.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "#", "Chave"
            }
        ));
        jScrollPane1.setViewportView(listaTbl);
        if (listaTbl.getColumnModel().getColumnCount() > 0) {
            listaTbl.getColumnModel().getColumn(0).setMinWidth(50);
            listaTbl.getColumnModel().getColumn(0).setPreferredWidth(50);
            listaTbl.getColumnModel().getColumn(0).setMaxWidth(50);
        }

        jLabel2.setFont(new java.awt.Font("sansserif", 1, 18)); // NOI18N
        jLabel2.setText("Gerador de Chaves");

        jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/principal/chave-logo_1.png"))); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(gerar)
                            .addGap(14, 14, 14)
                            .addComponent(letrasChk)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(simbolosChk)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(numerosChk))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addGap(14, 14, 14)
                            .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 198, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(94, 94, 94)
                            .addComponent(jLabel3)))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(quantidade, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addComponent(exportarParaTxt)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 35, Short.MAX_VALUE)
                                .addComponent(exportarParaBD, javax.swing.GroupLayout.PREFERRED_SIZE, 162, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
        );
Responder

Mais Posts

16/11/2018

Nelson Anjos

 layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(31, 31, 31)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(quantidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(gerar)
                    .addComponent(letrasChk)
                    .addComponent(simbolosChk)
                    .addComponent(numerosChk))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(exportarParaBD)
                    .addComponent(exportarParaTxt))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 218, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>                        

    private void letrasChkActionPerformed(java.awt.event.ActionEvent evt) {                                          
        // TODO add your handling code here:
    }                                         

    private Metodos metodos;
    private ArrayList<String> lista;
    private void gerarActionPerformed(java.awt.event.ActionEvent evt) {                                      
        metodos = new Metodos();
        lista = metodos.getLista();
        boolean c = letrasChk.isSelected();
        boolean n = numerosChk.isSelected();
        boolean s = simbolosChk.isSelected();
        try {
            metodos.gerarChave(quantidade.getValue().hashCode(), c, n, s);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Você precisa selecionar pelo menos um tipo de caracter!");
        }

        DefaultTableModel modelo = (DefaultTableModel) listaTbl.getModel();
        try {
            modelo.setNumRows(0);
            lista.forEach((ch) -> {
                modelo.addRow(new Object[]{
                    lista.indexOf(ch) + 1,
                    ch
                });
            });
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }                                     
    private String nomeDaTabela = "Erro";
    private String dia = "Erro";
    private int mes = 0;
    private int ano = 0;
    private void exportarParaBDActionPerformed(java.awt.event.ActionEvent evt) {                                               
        nomeDaTabela = JOptionPane.showInputDialog(null, "Digite a tabela do Servidor:");
        dia = JOptionPane.showInputDialog(null, "Qual dia de vencimento?");
        mes = Integer.parseInt(JOptionPane.showInputDialog(null, "A partir de qual mês contar?"));
        ano = Integer.parseInt(JOptionPane.showInputDialog(null, "A partir de qual ano contar?"));
        ConexaoUtil conexaoUtil = new ConexaoUtil();

        for (int i = 0; i < quantidade.getValue().hashCode(); i++) {
            try {
                Connection con = conexaoUtil.getInstanec().getConnection();
                String chave = lista.get(i);
                String query = "INSERT INTO " + nomeDaTabela + " (id_Chave, chave, dia, mes, ano, situacao) VALUES ( ?, ?, ?, ?, ?, ?)";
                PreparedStatement stmt = con.prepareStatement(query);
                stmt.setString(1, null);
                stmt.setString(2, chave);
                stmt.setString(3, dia);
                stmt.setInt(4, mes);
                stmt.setInt(5, ano);
                stmt.setString(6, "ativo");
                stmt.execute();
                mes++;
                if (mes == 12) {
                    mes = 1;
                    ano++;
                }
                con.close();
            } catch (Exception e) {
                System.err.println(e.getMessage());
            }
        }
    }                                              

    private void exportarParaTxtActionPerformed(java.awt.event.ActionEvent evt) {                                                
        BufferedWriter buffWrite;
        File file = new File("C:/tmp");
        file.mkdirs();
        try {
            buffWrite = new BufferedWriter(new FileWriter(file.getAbsolutePath()+"/script.txt"));
            nomeDaTabela = JOptionPane.showInputDialog(null, "Digite a tabela do Servidor:");
            dia = JOptionPane.showInputDialog(null, "Qual dia de vencimento?");
            mes = Integer.parseInt(JOptionPane.showInputDialog(null, "A partir de qual mês contar?"));
            ano = Integer.parseInt(JOptionPane.showInputDialog(null, "A partir de qual ano contar?"));

            for (int i = 0; i < quantidade.getValue().hashCode(); i++) {
                String chave = lista.get(i);
                String query = "INSERT INTO " + nomeDaTabela + " (id_Chave, chave, dia, mes, ano, situacao) "
                        + "VALUES (null, " + chave + ", " + dia + ", " + mes + ", " + ano + ", ativo)";
                buffWrite.append(query + "\\r\\n");
                mes++;
                if(mes >= 12){
                    mes = 1;
                    ano++;
                }
                
            }
            buffWrite.close();

        } catch (IOException ex) {
            Logger.getLogger(View.class.getName()).log(Level.SEVERE, null, ex);
        }

    }                                               

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

16/11/2018

Nelson Anjos

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

// Variables declaration - do not modify
private javax.swing.JButton exportarParaBD;
private javax.swing.JButton exportarParaTxt;
private javax.swing.JButton gerar;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JCheckBox letrasChk;
private javax.swing.JTable listaTbl;
private javax.swing.JCheckBox numerosChk;
private javax.swing.JSpinner quantidade;
private javax.swing.JCheckBox simbolosChk;
// End of variables declaration
}
[/code]
Responder

16/11/2018

Nelson Anjos

Tive que ir mandando aos poucos por conta da limitação.<br />
Enfim, quem quiser contribuir agradeço, ou só copiar e colar também fique a vontade.<br />
Vlw
Responder
×
+1 DevUP
Acesso diário, +1 DevUP
Parabéns, você está investindo na sua carreira