migrationextraction.MainWindowUI.java Source code

Java tutorial

Introduction

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

import auxiliar.OleObject;
import java.awt.Color;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
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.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jdom2.Content;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet;

/**
 *
 * @author Carlos Cortina
 */
public class MainWindowUI extends javax.swing.JFrame {
    private static File ROOT_DIRECTORY = null;

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

        fileChooser = new javax.swing.JFileChooser();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        subfolderChkbx = new javax.swing.JCheckBox();
        folderPathTxtField = new javax.swing.JTextField();
        chooseRootFolderBtn = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        outputJtxtPane = new javax.swing.JTextPane();
        extractBtn = new javax.swing.JButton();

        fileChooser.setFileSelectionMode(javax.swing.JFileChooser.DIRECTORIES_ONLY);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel2.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
        jPanel2.setToolTipText("");
        jPanel2.setName("MainPanel"); // NOI18N

        jLabel1.setText("Select folder:");

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel2.setText("Migration Extraction Tool");

        subfolderChkbx.setText("Include subfolders");
        subfolderChkbx.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                subfolderChkbxActionPerformed(evt);
            }
        });

        folderPathTxtField.setEditable(false);

        chooseRootFolderBtn.setText("Choose Folder");
        chooseRootFolderBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chooseRootFolderBtnActionPerformed(evt);
            }
        });

        outputJtxtPane.setEditable(false);
        jScrollPane2.setViewportView(outputJtxtPane);

        extractBtn.setText("Extract");
        extractBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                extractBtnActionPerformed(evt);
            }
        });

        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(jScrollPane2)
                        .addGroup(jPanel2Layout.createSequentialGroup().addGroup(jPanel2Layout
                                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(jPanel2Layout.createSequentialGroup().addGroup(jPanel2Layout
                                        .createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 207,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGroup(jPanel2Layout.createSequentialGroup().addComponent(jLabel1)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addGroup(jPanel2Layout
                                                        .createParallelGroup(
                                                                javax.swing.GroupLayout.Alignment.LEADING)
                                                        .addComponent(subfolderChkbx)
                                                        .addComponent(folderPathTxtField,
                                                                javax.swing.GroupLayout.PREFERRED_SIZE, 303,
                                                                javax.swing.GroupLayout.PREFERRED_SIZE))))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(chooseRootFolderBtn))
                                .addComponent(extractBtn)).addGap(0, 55, Short.MAX_VALUE)))
                        .addContainerGap()));
        jPanel2Layout.setVerticalGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel2Layout.createSequentialGroup().addContainerGap().addComponent(jLabel2)
                        .addGap(29, 29, 29)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel1)
                                .addComponent(folderPathTxtField, javax.swing.GroupLayout.PREFERRED_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(chooseRootFolderBtn))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(subfolderChkbx)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 237,
                                javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(extractBtn)
                        .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)
                .addGroup(layout.createSequentialGroup().addContainerGap().addComponent(jPanel2,
                        javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap()));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addContainerGap().addComponent(jPanel2,
                        javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap()));

        jPanel2.getAccessibleContext().setAccessibleName("");

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

    //Open File Chooser and select a folder wich contains the folders for all suplier sites
    private void chooseRootFolderBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chooseRootFolderBtnActionPerformed
        int returnVal = fileChooser.showOpenDialog(this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            ROOT_DIRECTORY = fileChooser.getSelectedFile();
            if (ROOT_DIRECTORY.exists() && ROOT_DIRECTORY.isDirectory()) {
                folderPathTxtField.setText(ROOT_DIRECTORY.getPath());

                try {
                    appendTextToPane(2, ROOT_DIRECTORY.getName() + " sucsessfully loaded ...\n");
                } catch (BadLocationException ex) {
                    Logger.getLogger(MainWindowUI.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else {
                try {
                    appendTextToPane(1, ROOT_DIRECTORY.getName() + " is not a valid directory\n");
                } catch (BadLocationException ex) {
                    Logger.getLogger(MainWindowUI.class.getName()).log(Level.SEVERE, null, ex);
                }
                errorDisplay("The selected directory doesnt exist or is not a valid directory");
            }
        }
    }//GEN-LAST:event_chooseRootFolderBtnActionPerformed

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

    private void extractBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_extractBtnActionPerformed
        if (ROOT_DIRECTORY != null) {
            //check for subfolders
            if (subfolderChkbx.getSelectedObjects() != null) {
                for (File subfolder : ROOT_DIRECTORY.listFiles()) {

                }
            } else {
                try {
                    appendTextToPane(3, "Processing... " + ROOT_DIRECTORY.getName() + "\n");
                } catch (BadLocationException ex) {
                    Logger.getLogger(MainWindowUI.class.getName()).log(Level.SEVERE, null, ex);
                }
                //Process Excel File
                for (File file : ROOT_DIRECTORY.listFiles()) {
                    String filename = file.getName();
                    String extension = filename.substring(filename.lastIndexOf(".") + 1, filename.length());

                    /*List<String> sheetsToCheck = new ArrayList<String>(){{ //Sheets with documents required
                                                add("1. Supplier Basic Info");
                                                add("6. Test Data");
                                                add("5. Kosher Declaration");
                                            }};*/
                    //There must be only one Excel file per folder                            
                    if (extension.equalsIgnoreCase("xlsx") || extension.equalsIgnoreCase("xlsm")) {
                        try {
                            //Initialize excel file as POI Object
                            Workbook wb = new XSSFWorkbook(file);

                            //Sheet 1
                            processBasicInfoSheet((XSSFWorkbook) wb);

                            break; //End for cycle as excel file has been found
                        } catch (IOException | InvalidFormatException ex) {
                            Logger.getLogger(MainWindowUI.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }
            }

        } else {
            errorDisplay("No directory has been selected");
            try {
                appendTextToPane(1, ROOT_DIRECTORY.getName() + " no directory selected\n");
            } catch (BadLocationException ex) {
                Logger.getLogger(MainWindowUI.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_extractBtnActionPerformed

    //Display Error Messages
    private void errorDisplay(String msg) {
        JOptionPane.showMessageDialog(this, msg, "Error", JOptionPane.ERROR_MESSAGE);
    }

    //Appends text to the textpane
    private void appendTextToPane(int type, String text) throws BadLocationException {
        SimpleAttributeSet set = new SimpleAttributeSet();
        outputJtxtPane.setCharacterAttributes(set, true);
        Document doc = outputJtxtPane.getStyledDocument();

        switch (type) {
        case 1: //Error
            StyleConstants.setForeground(set, Color.red);
            doc.insertString(doc.getLength(), text, set);
            break;
        case 2: //Success
            StyleConstants.setForeground(set, new Color(71, 175, 81));
            doc.insertString(doc.getLength(), text, set);
            break;
        default: //Log
            doc.insertString(doc.getLength(), text, set);
            break;
        }
    }

    //Process sheet - 1. Supplier Basic Info
    private void processBasicInfoSheet(XSSFWorkbook wb) throws InvalidFormatException {
        try {
            XSSFSheet sheet = wb.getSheet("1. Supplier Basic Info");
            CTWorksheet ctws = sheet.getCTWorksheet();
            /*String xml10pattern = "[^"
                + "\u0009\r\n"
                + "\u0020-\uD7FF"
                + "\uE000-\uFFFD"
                + "\ud800\udc00-\udbff\udfff"
                + "]";
            String xml = ctws.toString().replaceAll(xml10pattern, "");*/
            //Get embedded objects positions.
            SAXBuilder saxB = new SAXBuilder();
            org.jdom2.Document doc = saxB.build(new StringReader(ctws.toString()));

            List<OleObject> oleObjects = new ArrayList<>();
            List<Element> elements = doc.getRootElement().getChildren();
            elements.stream().forEach((element) -> {
                if (element.getName().equals("oleObjects")) {
                    element.getChildren();
                    getXMLUntilOle(element.getContent(), 0);
                    //Get content
                    System.out.println("");
                    //for(Content content:element.getContent())
                }
            });
        } catch (JDOMException | IOException ex) {
            Logger.getLogger(MainWindowUI.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private OleObject getXMLUntilOle(List<Content> contentList, int nextLvl) {
        List<String> contentPath = Arrays.asList("AlternateContent", "Choice", "oleObject", "objectPr", "anchor");
        for (Iterator<Content> it = contentList.iterator(); it.hasNext();) {
            Content content = it.next();
            if (nextLvl < contentPath.size() - 1 && content.getCType().toString().equals("Element")
                    && ((Element) content).getName().equals(contentPath.get(nextLvl))) {
                getXMLUntilOle(((Element) content).getContent(), nextLvl++);
            }
            System.out.println(content);
        }

        return null;
    }

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

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton chooseRootFolderBtn;
    private javax.swing.JButton extractBtn;
    private javax.swing.JFileChooser fileChooser;
    private javax.swing.JTextField folderPathTxtField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextPane outputJtxtPane;
    private javax.swing.JCheckBox subfolderChkbx;
    // End of variables declaration//GEN-END:variables
}