FindMyPhrase / src / UI / Interfaz.java
Interfaz.java
Raw
/*
 * 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 UI;

import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;
import java.awt.Desktop;
import java.awt.Image;
import java.awt.Point;
import java.awt.Toolkit;
import static java.awt.image.ImageObserver.WIDTH;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.text.Normalizer;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import javax.swing.DefaultListModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 *
 * @author Josh
 */
public class Interfaz extends javax.swing.JFrame {

 
  private final ArrayList<File> documentos;

  protected JProgressBar progressBar;

  
  private File carpeta;
 
  private JFileChooser fileChooser;
  
  private JList<String> listaViewDocumentos = new JList<>();
  
  private JList<String> listaViewEncriptados = new JList<>();
  
  private final DefaultListModel<String> modelolistaDoc = new DefaultListModel<>();
  
  private final DefaultListModel<String> modelolistaEnc = new DefaultListModel<>();
  Icon icon;
    /**
     * Creates new form Interfaz
     */
    public Interfaz() {
       
    initComponents();
    listaViewDocumentos = this.listadoDoc;
    listaViewEncriptados = this.listadoEncrip;
    documentos = new ArrayList<>();
    icon = new ImageIcon("Images/log.png");
            

    }
    

    
    public ArrayList<File> getDocumentos() {
        return documentos;
    }
    public Image getIconImage(){
        Image retValue = Toolkit.getDefaultToolkit().getImage(ClassLoader.getSystemResource("Images/logo1.png"));
        return retValue;
    }

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

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        listadoDoc = new javax.swing.JList<>();
        jScrollPane2 = new javax.swing.JScrollPane();
        listadoEncrip = new javax.swing.JList<>();
        jTextField1 = new javax.swing.JTextField();
        selccionar = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        buscar = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        totalDoc = new javax.swing.JLabel();
        totalDocEncr = new javax.swing.JLabel();
        fondo = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setIconImage(getIconImage());
        setResizable(false);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel1.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(255, 255, 255));
        jLabel1.setText("Escriba la frase/palabra que desee buscar:");
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 50, -1, -1));

        jLabel2.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(255, 255, 255));
        jLabel2.setText("Listado de documentos que contienen la frase/palabra:");
        getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(470, 50, 390, -1));

        listadoDoc.setBackground(new java.awt.Color(51, 51, 51));
        listadoDoc.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 1, 1, 1, new java.awt.Color(0, 255, 255)));
        listadoDoc.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        listadoDoc.setForeground(new java.awt.Color(255, 255, 255));
        listadoDoc.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                listadoDocMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(listadoDoc);

        getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(470, 80, 440, 630));

        listadoEncrip.setBackground(new java.awt.Color(51, 51, 51));
        listadoEncrip.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 1, 1, 1, new java.awt.Color(0, 255, 255)));
        listadoEncrip.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        listadoEncrip.setForeground(new java.awt.Color(255, 255, 255));
        listadoEncrip.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                listadoEncripMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(listadoEncrip);

        getContentPane().add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(32, 444, 410, 267));

        jTextField1.setBackground(new java.awt.Color(51, 51, 51));
        jTextField1.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        jTextField1.setForeground(new java.awt.Color(255, 255, 255));
        jTextField1.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 1, 1, 1, new java.awt.Color(0, 255, 255)));
        getContentPane().add(jTextField1, new org.netbeans.lib.awtextra.AbsoluteConstraints(36, 308, 400, 30));

        selccionar.setBackground(new java.awt.Color(0, 102, 102));
        selccionar.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        selccionar.setForeground(new java.awt.Color(255, 255, 255));
        selccionar.setText("Seleccionar");
        selccionar.setBorder(null);
        selccionar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                selccionarMouseClicked(evt);
            }
        });
        getContentPane().add(selccionar, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 360, 120, 39));

        jTextArea1.setBackground(new java.awt.Color(51, 51, 51));
        jTextArea1.setColumns(20);
        jTextArea1.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        jTextArea1.setForeground(new java.awt.Color(255, 255, 255));
        jTextArea1.setRows(5);
        jTextArea1.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 1, 1, 1, new java.awt.Color(0, 255, 255)));
        jScrollPane3.setViewportView(jTextArea1);

        getContentPane().add(jScrollPane3, new org.netbeans.lib.awtextra.AbsoluteConstraints(36, 81, 400, 116));

        buscar.setBackground(new java.awt.Color(0, 102, 102));
        buscar.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        buscar.setForeground(new java.awt.Color(255, 255, 255));
        buscar.setText("Buscar");
        buscar.setBorder(null);
        buscar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                buscarMouseClicked(evt);
            }
        });
        getContentPane().add(buscar, new org.netbeans.lib.awtextra.AbsoluteConstraints(319, 220, 120, 39));

        jLabel3.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(255, 255, 255));
        jLabel3.setText("Listado de documentos encriptados:");
        getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 410, -1, -1));

        jLabel4.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        jLabel4.setForeground(new java.awt.Color(255, 255, 255));
        jLabel4.setText("Ruta de acceso a los documentos:");
        getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 270, -1, -1));

        totalDoc.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        totalDoc.setForeground(new java.awt.Color(255, 255, 255));
        getContentPane().add(totalDoc, new org.netbeans.lib.awtextra.AbsoluteConstraints(870, 50, 50, 16));

        totalDocEncr.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        totalDocEncr.setForeground(new java.awt.Color(255, 255, 255));
        getContentPane().add(totalDocEncr, new org.netbeans.lib.awtextra.AbsoluteConstraints(310, 410, 60, 19));

        fondo.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        fondo.setForeground(new java.awt.Color(255, 255, 255));
        fondo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/fondo.jpg"))); // NOI18N
        getContentPane().add(fondo, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 940, 740));

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

    private void selccionarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_selccionarMouseClicked
 
    fileChooser = new JFileChooser(this.jTextField1.getText());
    fileChooser.setMultiSelectionEnabled(false);
    fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    fileChooser.setAcceptAllFileFilterUsed(false);
    fileChooser.setDialogTitle("Seleccione documentos");
    FileNameExtensionFilter filter = new FileNameExtensionFilter("*.PDF", new String[] { "pdf" });
    fileChooser.setFileFilter(filter);
    int selection = fileChooser.showOpenDialog(this);
    documentos.clear();
    switch (selection) {
      case 0:
        if (fileChooser.getSelectedFile().isDirectory()) {
        try {
            buscarHijos(carpeta);
        } catch (IOException | InterruptedException ex) {
            Logger.getLogger(Interfaz.class.getName()).log(Level.SEVERE, null, ex);
        }
        if(!documentos.isEmpty()){
         jTextField1.setText(fileChooser.getSelectedFile().getPath());
         }else{
              JOptionPane.showMessageDialog(Interfaz.this, "La carpeta seleccionada no contiene documentos", "Error", HEIGHT, icon );
          }
          
        }else{
            documentos.add(fileChooser.getSelectedFile());
            jTextField1.setText(fileChooser.getSelectedFile().getParent());
        }   
        break;
      case JFileChooser.CANCEL_OPTION:
          
        System.out.println("No se han seleccionado archivos");
        break;
      case JFileChooser.ERROR:
        System.err.println("Error seleccionando archivos");
        break;
    }
  
    
    }//GEN-LAST:event_selccionarMouseClicked

    private void buscarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_buscarMouseClicked
     
   if (this.jTextArea1.getText().equals("")) {
      JOptionPane.showMessageDialog(this, "Escriba una frase", "Error", 2);
    } else if (this.documentos.isEmpty()) {
      JOptionPane.showMessageDialog(this, "No han seleccionado documentos", "Error", 2);
    } else {
 
      Runnable runnable1 = new Runnable() {
          public void run() {
            Loading l = new Loading();
           
            l.setLocationRelativeTo(Interfaz.this);
            l.setVisible(true);
            Interfaz.this.setEnabled(false);
            encontrarFrase();
            totalDoc.setText(""+modelolistaDoc.size());
            totalDocEncr.setText(""+modelolistaEnc.size());
            Interfaz.this.setEnabled(true);
            l.setVisible(false);
          }
        };
      Thread t1 = new Thread(runnable1);
      t1.start();
    } 
    this.listaViewDocumentos.setModel(this.modelolistaDoc);
    this.listaViewEncriptados.setModel(this.modelolistaEnc);
    }//GEN-LAST:event_buscarMouseClicked


    private void listadoDocMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listadoDocMouseClicked
        if (!this.modelolistaDoc.isEmpty()) {
      String fileName = this.listaViewDocumentos.getSelectedValue();
      if (evt.getClickCount() == 2) {
        for (File documento : this.documentos) {
          if (fileName.equals(documento.getName()))
            abrirDocumento(documento); 
        } 
      } else {
        System.out.println(fileName);
      } 
    } else {
      System.err.println("lista vacia");
    } 
    }//GEN-LAST:event_listadoDocMouseClicked

    private void listadoEncripMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listadoEncripMouseClicked
        if (!this.modelolistaEnc.isEmpty()) {
      String fileName = this.listaViewEncriptados.getSelectedValue();
      if (evt.getClickCount() == 2) {
        for (File documento : this.documentos) {
          if (fileName.equals(documento.getName()))
            abrirDocumento(documento); 
        } 
      } else {
        System.out.println("Usted ha seleccionado " + fileName);
      } 
    } else {
      System.err.println("Lista vacia");
    } 
    }//GEN-LAST:event_listadoEncripMouseClicked

    
    
 public void abrirDocumento(File file) {
    try {
      Desktop.getDesktop().open(file);
    } catch (IOException e) {
      e.getMessage();
    } 
  }
  
 public void encontrarFrase() {

         
    String title = "";
    String pdfText = "";
    this.modelolistaDoc.removeAllElements();
    this.modelolistaEnc.removeAllElements();
    for (File documento : this.documentos) {
      try {
        PdfReader.unethicalreading = true;
        PdfReader reader = new PdfReader(documento.getAbsolutePath());
        if (reader.isEncrypted()) {
          System.out.println("Esta encriptado");
          if (!this.modelolistaEnc.contains(documento.getName())) {
            this.modelolistaEnc.addElement(documento.getName());
            continue;
          } 
          System.out.println("Ya existe el archivo " + documento.getName());
          continue;
        } 
        int pages = reader.getNumberOfPages();
        while (pages > 0) {
          pdfText = pdfText + PdfTextExtractor.getTextFromPage(reader, pages);
          pages--;
        } 
        if (quitarSimbolos(pdfText).toLowerCase().contains(quitarSimbolos(this.jTextArea1.getText()).toLowerCase())) {
          title = title + documento.getName() + "\n";
          if (!this.modelolistaDoc.contains(documento.getName())) {
            this.modelolistaDoc.addElement(documento.getName());
          } else {
            System.out.println("Ya existe el archivo " + documento.getName());
          } 
          System.out.println("Encontrado" + documento.getName());
          pdfText = "";
          continue;
        } 
        System.out.println("Error");
        pdfText = "";
      } catch (IOException ex) {
        Logger.getLogger(Interfaz.class.getName()).log(Level.SEVERE, (String)null, ex);
      } 
    } 
    if (this.modelolistaDoc.isEmpty() && this.modelolistaEnc.isEmpty()){
      JOptionPane.showMessageDialog(this, "No hay resultados","Error",WIDTH, icon); 
  }
  }
  
  
  

  
  
  
  
  public void buscarHijos(File file) throws IOException, InterruptedException {
       file = fileChooser.getSelectedFile();
    if(file.listFiles().length == 0 || file.listFiles() == null){
        System.out.println("vacio");
    }else{  
    final Path rootDir = Paths.get(file.getAbsolutePath(), new String[0]);
    Files.walkFileTree(rootDir, new FileVisitor<Path>() {
          private Pattern pattern = Pattern.compile("^(.*?)");
          
          @Override
          public FileVisitResult preVisitDirectory(Path path, BasicFileAttributes atts) throws IOException {
            boolean matches = this.pattern.matcher(path.toString()).matches();
            return matches ? FileVisitResult.CONTINUE : FileVisitResult.SKIP_SUBTREE;
          }
          
          @Override
          public FileVisitResult visitFile(Path path, BasicFileAttributes mainAtts) throws IOException {
              
            boolean matches = (path.toFile().getName().endsWith(".pdf") || path.toFile().getName().endsWith(".PDF"));
            if (matches) {
              documentos.add(path.toFile());
            }
         
            return FileVisitResult.CONTINUE;
          }
          
          @Override
          public FileVisitResult postVisitDirectory(Path path, IOException exc) throws IOException {
            return FileVisitResult.CONTINUE;
          }
          
          @Override
          public FileVisitResult visitFileFailed(Path path, IOException exc) throws IOException {
            exc.getMessage();
            return path.equals(rootDir) ? FileVisitResult.TERMINATE : FileVisitResult.CONTINUE;
          }

         
        });
    }
  }
  
  public String quitarSimbolos(String cadena) {
    String cadenaNormalize = Normalizer.normalize(cadena, Normalizer.Form.NFD);
    String cadenaSinAcentos = cadenaNormalize.replaceAll("[^\\p{ASCII}]", "");
    String cadenaSinSimbolos = cadenaSinAcentos.replaceAll("[, . : ; < > / _ ? ! + ) ( } { ~ ']", "");
    return cadenaSinSimbolos;
  }
    /**
     * @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 (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if("Nimbus".equals(info.getName())){
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
                
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Interfaz.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Interfaz.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Interfaz.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Interfaz.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 Interfaz().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buscar;
    private javax.swing.JLabel fondo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JList<String> listadoDoc;
    private javax.swing.JList<String> listadoEncrip;
    private javax.swing.JButton selccionar;
    private javax.swing.JLabel totalDoc;
    private javax.swing.JLabel totalDocEncr;
    // End of variables declaration//GEN-END:variables
}