javaapplication2.NewJFrame.java Source code

Java tutorial

Introduction

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

import java.io.IOException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;

/**
 *
 * @author alves
 */
public class NewJFrame extends javax.swing.JFrame {

    /**
     * Creates new form NewJFrame
     */
    public NewJFrame() {
        initComponents();
        group.add(jRadioButton1);
        group.add(jRadioButton2);
        group.add(jRadioButton3);
        group.add(jRadioButton4);
        group.add(jRadioButton5);
        group.add(jRadioButton6);
        group.add(jRadioButton7);
        group.add(jRadioButton8);
        group.add(jRadioButton9);
        group.add(jRadioButton10);

        hm.put("Cantina 1 Campus 1", "cantina1_campus1_pt");
        hm.put("Restaurante Campus 1", "restaurante_campus1_pt");

        hm.put("Cantina 2 Campus 2", "cantina2_campus2_pt");
        hm.put("Cantina 3 Campus 2", "cantina3_campus2_pt");
        hm.put("Restaurante Campus 2", "restaurante_campus2_pt");
        hm.put("Snack Bar Campus 2", "snack_campus2_pt");
        hm.put("Bar ESSLei Campus 2", "bar_campus2_pt");

        hm.put("Cantina 4 Campus 3", "cantina4_campus3_pt");

        hm.put("Cantina 5 Campus 4", "cantina5_campus4_pt");

        hm.put("Bar Sede Leiria", "bar_sede_pt");
    }

    /**
     * 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();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jRadioButton1 = new javax.swing.JRadioButton();
        jRadioButton2 = new javax.swing.JRadioButton();
        jRadioButton3 = new javax.swing.JRadioButton();
        jRadioButton4 = new javax.swing.JRadioButton();
        jRadioButton5 = new javax.swing.JRadioButton();
        jRadioButton6 = new javax.swing.JRadioButton();
        jRadioButton7 = new javax.swing.JRadioButton();
        jRadioButton8 = new javax.swing.JRadioButton();
        jRadioButton9 = new javax.swing.JRadioButton();
        jRadioButton10 = new javax.swing.JRadioButton();
        jButton2 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(451, 376));

        jButton1.setText("Importar para BD");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton1MouseClicked(evt);
            }
        });
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        jRadioButton1.setSelected(true);
        jRadioButton1.setText("Cantina 1 Campus 1");

        jRadioButton2.setText("Cantina 2 Campus 2");

        jRadioButton3.setText("Restaurante Campus 2");

        jRadioButton4.setText("Bar ESSLei Campus 2");

        jRadioButton5.setText("Cantina 5 Campus 4");

        jRadioButton6.setText("Restaurante Campus 1");

        jRadioButton7.setText("Cantina 3 Campus 2");

        jRadioButton8.setText("Snack Bar Campus 2");

        jRadioButton9.setText("Cantina 4 Campus 3");

        jRadioButton10.setText("Bar Sede Leiria");

        jButton2.setText("Escolher Ficheiro");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(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)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 464, Short.MAX_VALUE)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
                                layout.createSequentialGroup().addComponent(jTextField1)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jButton2))
                        .addGroup(layout.createSequentialGroup().addGroup(layout
                                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup().addGroup(layout
                                        .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
                                                layout.createSequentialGroup().addGroup(layout
                                                        .createParallelGroup(
                                                                javax.swing.GroupLayout.Alignment.TRAILING)
                                                        .addComponent(jRadioButton1).addComponent(jRadioButton2))
                                                        .addGap(39, 39, 39))
                                        .addGroup(layout.createSequentialGroup().addGroup(layout
                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                .addComponent(jRadioButton3).addComponent(jRadioButton4))
                                                .addGap(25, 25, 25)))
                                        .addGroup(layout
                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                .addComponent(jRadioButton7).addComponent(jRadioButton6)
                                                .addComponent(jRadioButton8).addComponent(jRadioButton9)
                                                .addComponent(jRadioButton10)))
                                .addComponent(jRadioButton5))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,
                                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jButton1)))
                        .addContainerGap()));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout
                        .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(jButton2)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE,
                                javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(10, 10, 10)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jRadioButton6).addComponent(jRadioButton1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jRadioButton2).addComponent(jRadioButton7))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jRadioButton3).addComponent(jRadioButton8))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jRadioButton4).addComponent(jRadioButton9))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jRadioButton5).addComponent(jRadioButton10).addComponent(jButton1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 206, Short.MAX_VALUE)
                        .addContainerGap()));

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

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked
        /* JFileChooser chooser = new JFileChooser();
         FileNameExtensionFilter filter = new FileNameExtensionFilter(
        "ficheiros PDF", "pdf");
         chooser.setFileFilter(filter);
         int returnVal;
         returnVal = chooser.showOpenDialog(getParent());
         if(returnVal == JFileChooser.APPROVE_OPTION) {*/
        if (!jTextField1.getText().isEmpty()) {

            System.out.println("You chose to open this file: " + jTextField1.getText());
            String text = null;
            String[] linhas = null;

            try {
                PDDocument doc = PDDocument.load(jTextField1.getText());
                PDFTextStripper stripper = new PDFTextStripper();
                text = stripper.getText(doc);
                doc.close();
            } catch (IOException ex) {
                Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
            linhas = text.split("\n", -1);

            ArrayList<Dia> dias = new ArrayList<>();
            Refeicao r = null;
            Dia d = null;
            Boolean almoco = false;
            Boolean ignorarDia = false; //dias sem refeio ex. feriados
            for (String linha : linhas) {
                if (linha.contains("Segunda-feira") || linha.contains("Tera-feira")
                        || linha.contains("Quarta-feira") || linha.contains("Quinta-feira")
                        || linha.contains("Sexta-feira")) {
                    if (d != null) {// && !ignorarDia){
                        dias.add(d);
                        // ignorarDia=false;
                    }
                    d = new Dia();
                    almoco = true;
                    r = new Refeicao();
                    jTextArea1.setText(jTextArea1.getText() + linha.trim() + " --NOVO DIA \n");
                }
                /* else if(linha.contains("ENCERRADO")){
                ignorarDia=true;
                 }*/
                else if (isValidDate(linha)) {
                    DateFormat format = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
                    try {
                        d.setDia(format.parse(linha));
                    } catch (ParseException ex) {
                        Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    jTextArea1.setText(jTextArea1.getText() + linha.trim() + " --DATA \n");
                } else if (linha.contains("Sopa")) {

                    if (almoco)
                        jTextArea1.setText(jTextArea1.getText() + " ALMOO \n");
                    else
                        jTextArea1.setText(jTextArea1.getText() + " JANTAR \n");

                    r.setSopa(linha);
                    jTextArea1.setText(jTextArea1.getText() + linha.trim() + " --SOPA \n");
                }

                else if (linha.contains("Carne")) {
                    r.setCarne(linha);
                    jTextArea1.setText(jTextArea1.getText() + linha.trim() + " --CARNE \n");
                }

                else if (linha.contains("Peixe")) {
                    r.setPeixe(linha);
                    jTextArea1.setText(jTextArea1.getText() + linha.trim() + " --PEIXE \n");
                }

                else if (linha.contains("Sobremesa")) {

                    jTextArea1.setText(jTextArea1.getText() + linha.trim() + " --SOBREMESA \n");
                    r.setSobremesa(linha);
                    if (almoco) {
                        d.setAlmoco(r);
                        r = new Refeicao();
                        almoco = false;
                    } else {
                        d.setJantar(r);
                        r = new Refeicao();
                        almoco = true;
                    }

                } else {
                    jTextArea1.setText(jTextArea1.getText() + linha.trim() + " --Ignorado \n");
                }

                // jTextArea1.setText(jTextArea1.getText()+t+" a testar\n ");
            }

            if (d != null)
                dias.add(d);

            jTextArea1.setText(" ");
            System.out.println("nmero de dias: " + dias.size());
            getSelectedButtonText();
            getConnection();
            for (Dia dia : dias) {
                //if(dia.dia.compareTo(new Date(2015, 06, 12))==0){
                if (dia.dia != null) {
                    System.out.println("dia: " + dia.dia);
                    jTextArea1.setText(jTextArea1.getText() + "\n" + dia.dia);
                    jTextArea1.setText(jTextArea1.getText() + "\n" + "-----ALMOO-----\n");
                    if (dia.almoco != null)
                        jTextArea1
                                .setText(jTextArea1.getText() + dia.almoco.getSopa() + "\n" + dia.almoco.getCarne()
                                        + "\n" + dia.almoco.getPeixe() + "\n" + dia.almoco.getSobremesa() + "\n");
                    else
                        jTextArea1.setText(jTextArea1.getText() + "Nao definido" + "\n");

                    jTextArea1.setText(jTextArea1.getText() + "\n" + "-----JANTAR-----\n");
                    if (dia.jantar != null)
                        jTextArea1
                                .setText(jTextArea1.getText() + dia.jantar.getSopa() + "\n" + dia.jantar.getCarne()
                                        + "\n" + dia.jantar.getPeixe() + "\n" + dia.jantar.getSobremesa() + "\n");
                    else
                        jTextArea1.setText(jTextArea1.getText() + "Nao definido" + "\n");

                    try {
                        String query = " insert into " + getSelectedButtonText()
                                + " (data,temAlmoco,almoco_sopa,almoco_carne,almoco_peixe,almoco_sobremesa,temJantar,jantar_sopa,jantar_carne,jantar_peixe,jantar_sobremesa)"
                                + " values (?,?,?,?,?,?,?,?,?,?,?)";

                        // create the mysql insert preparedstatement
                        PreparedStatement preparedStmt = conexao.prepareStatement(query);
                        java.sql.Date sqldate = new Date(dia.dia.getTime());
                        preparedStmt.setDate(1, sqldate);
                        if (dia.almoco != null) {
                            preparedStmt.setInt(2, 1);
                            preparedStmt.setString(3, dia.almoco.getSopa());
                            preparedStmt.setString(4, dia.almoco.getCarne());
                            preparedStmt.setString(5, dia.almoco.getPeixe());
                            preparedStmt.setString(6, dia.almoco.getSobremesa());
                        } else {
                            preparedStmt.setInt(2, 0);
                            preparedStmt.setString(3, "No Definido");
                            preparedStmt.setString(4, "No Definido");
                            preparedStmt.setString(5, "No Definido");
                            preparedStmt.setString(6, "No Definido");
                        }
                        if (dia.jantar != null) {
                            preparedStmt.setInt(7, 1);
                            preparedStmt.setString(8, dia.jantar.getSopa());
                            preparedStmt.setString(9, dia.jantar.getCarne());
                            preparedStmt.setString(10, dia.jantar.getPeixe());
                            preparedStmt.setString(11, dia.jantar.getSobremesa());
                        } else {
                            preparedStmt.setInt(7, 0);
                            preparedStmt.setString(8, "No Definido");
                            preparedStmt.setString(9, "No Definido");
                            preparedStmt.setString(10, "No Definido");
                            preparedStmt.setString(11, "No Definido");
                        }
                        // execute the preparedstatement
                        preparedStmt.execute();
                        //System.out.println(text);
                        //jTextArea1.setText(text);

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

        }
    }//GEN-LAST:event_jButton1MouseClicked

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

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        JFileChooser chooser = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter("ficheiros PDF", "pdf");
        chooser.setFileFilter(filter);
        int returnVal;
        returnVal = chooser.showOpenDialog(getParent());
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            jTextField1.setText(chooser.getSelectedFile().getAbsolutePath());
        } // TODO add your handling code here:
    }//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()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.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 NewJFrame().setVisible(true);
            }
        });
    }

    public boolean isValidDate(String dateString) {

        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        try {
            df.parse(dateString);
            return true;
        } catch (ParseException e) {
            return false;
        }
    }

    private static String usuario = "ementa15_ementa1";
    private static String senha = "qwerty1q";
    private static String banco = "ementa15_ementa";
    private static String ip = "johnny.heliohost.org";
    private static String driver = "com.mysql.jdbc.Driver";
    private static Connection conexao = null;
    ButtonGroup group = new ButtonGroup();
    HashMap hm = new HashMap();

    //padrao singleton
    public static Connection getConnection() {
        System.out.println(">>Conectando ao banco");
        try {
            Class.forName(driver);
            if (conexao == null || conexao.isClosed()) {
                conexao = DriverManager.getConnection("jdbc:mysql://" + ip + "/" + banco + "", usuario, senha);
            }
            return conexao;
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {

            //closeConnection();
            throw new RuntimeException(e);
        }
    }

    public String getSelectedButtonText() {
        for (AbstractButton b : Collections.list(group.getElements())) {
            if (b.isSelected()) {
                System.out.println("este: " + hm.get(b.getText()));
                return (String) hm.get(b.getText());
            }
        }

        return null;
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JRadioButton jRadioButton1;
    private javax.swing.JRadioButton jRadioButton10;
    private javax.swing.JRadioButton jRadioButton2;
    private javax.swing.JRadioButton jRadioButton3;
    private javax.swing.JRadioButton jRadioButton4;
    private javax.swing.JRadioButton jRadioButton5;
    private javax.swing.JRadioButton jRadioButton6;
    private javax.swing.JRadioButton jRadioButton7;
    private javax.swing.JRadioButton jRadioButton8;
    private javax.swing.JRadioButton jRadioButton9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
}