dbms.ANTGui.java Source code

Java tutorial

Introduction

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

//import antlr4.programLexer;
//import antlr4.programParser;
import antlr.sqlLexer;
import antlr.sqlParser;
import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import static javafx.scene.input.DataFormat.IMAGE;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import org.antlr.v4.gui.Trees;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.tree.ParseTree;

/**
 *
 * @author Pablo
 */
public class ANTGui extends javax.swing.JFrame {

    private File inputFile;
    private File inputGrammar;
    public static String[] ruleNames;
    private sqlParser parser;
    private sqlParser.Sql2003ParserContext contexto;
    public static boolean selected = false;
    public static String bdActual = "";
    private TextPanel jTextArea2;
    private DefaultTreeModel model;
    private boolean runSelected = false;

    //    
    /**
     * Creates new form ANTGui
     */
    public ANTGui() {
        initComponents();
        toolbar();
        lines();
        actualizarJTree();
    }

    private void actualizarJTree() {
        jTree1.clearSelection();
        model = null;

        model = (DefaultTreeModel) this.jTree1.getModel();

        DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
        root.removeAllChildren();
        DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) jTree1.getCellRenderer();
        Icon icon1 = new ImageIcon("src/resources/db-git.png");
        Icon icon2 = new ImageIcon("src/resources/dbfile-git.png");

        renderer.setClosedIcon(icon1);
        renderer.setOpenIcon(icon1);
        renderer.setLeafIcon(icon2);

        File[] files = new File("DB").listFiles();
        //If this pathname does not denote a directory, then listFiles() returns null. 
        int count = 0;
        for (File file : files) {
            if (file.isDirectory()) {
                DefaultMutableTreeNode child = new DefaultMutableTreeNode(file.getName());
                model.insertNodeInto(child, root, count);
                File[] files2 = new File("DB/" + file.getName()).listFiles();
                int count2 = 0;
                for (File innerFile : files2) {
                    model.insertNodeInto(new DefaultMutableTreeNode(innerFile.getName()), child, count2++);
                }
                count++;
            }
        }

        model.reload(root);

    }

    private void lines() {

        jTextArea2 = new TextPanel();
        this.jTabbedPane1.add(jTextArea2);
        this.jTabbedPane1.setTitleAt(0, "SQL Editor");

    }

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

        jTabbedPane1 = new javax.swing.JTabbedPane();
        jToolBar1 = new javax.swing.JToolBar();
        jTabbedPane2 = new javax.swing.JTabbedPane();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane4 = new javax.swing.JScrollPane();
        jTextArea3 = new javax.swing.JTextPane();
        jPanel5 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTree1 = new javax.swing.JTree();
        jLabel2 = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu2 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jToolBar1.setBackground(new java.awt.Color(204, 204, 204));
        jToolBar1.setForeground(new java.awt.Color(204, 204, 204));
        jToolBar1.setRollover(true);
        jToolBar1.setToolTipText("ToolBar");

        jScrollPane4.setViewportView(jTextArea3);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout
                .setHorizontalGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
                                jPanel3Layout.createSequentialGroup().addContainerGap().addComponent(jScrollPane4,
                                        javax.swing.GroupLayout.DEFAULT_SIZE, 1074, Short.MAX_VALUE)));
        jPanel3Layout.setVerticalGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jScrollPane4, javax.swing.GroupLayout.Alignment.TRAILING,
                        javax.swing.GroupLayout.DEFAULT_SIZE, 196, Short.MAX_VALUE));

        jTabbedPane2.addTab("Log", jPanel3);

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

        }, new String[] {

        }));
        jScrollPane1.setViewportView(jTable1);

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(jPanel5Layout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel5Layout.createSequentialGroup().addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 1068, Short.MAX_VALUE)
                        .addContainerGap()));
        jPanel5Layout.setVerticalGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel5Layout.createSequentialGroup().addContainerGap().addComponent(jScrollPane1,
                        javax.swing.GroupLayout.DEFAULT_SIZE, 190, Short.MAX_VALUE)));

        jTabbedPane2.addTab("Data Output", jPanel5);

        javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode(
                "Bases de datos");
        jTree1.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));
        jScrollPane3.setViewportView(jTree1);

        jLabel2.setText("F5 run query F6 run selected query");

        jMenu2.setText("Acciones");
        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        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)
                        .addGroup(layout.createSequentialGroup()
                                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 145,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jTabbedPane1)
                                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout
                                                .createSequentialGroup().addGap(0, 0, Short.MAX_VALUE)
                                                .addGroup(layout
                                                        .createParallelGroup(
                                                                javax.swing.GroupLayout.Alignment.TRAILING)
                                                        .addComponent(jLabel2).addComponent(jToolBar1,
                                                                javax.swing.GroupLayout.PREFERRED_SIZE, 604,
                                                                javax.swing.GroupLayout.PREFERRED_SIZE))
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 145,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addGap(208, 208, 208))
                        .addGroup(layout.createSequentialGroup().addComponent(jTabbedPane2).addGap(59, 59, 59)))));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 33,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 14,
                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 21, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jTabbedPane1).addComponent(jScrollPane3,
                                        javax.swing.GroupLayout.PREFERRED_SIZE, 359,
                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18).addComponent(jTabbedPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 242,
                                javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap()));

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

    private void toolbar() {

        //************************ Actions ************************
        Action newFileButton = new AbstractAction("Nuevo", new ImageIcon("src/resources/new-git.png")) {
            public void actionPerformed(ActionEvent e) {
                nuevoArchivo();
            }
        };

        Action openFileAction = new AbstractAction("Abrir", new ImageIcon("src/resources/open-git.png")) {
            public void actionPerformed(ActionEvent e) {
                abrirArchivo();
            }
        };
        Action deleteAction = new AbstractAction("Delete", new ImageIcon("src/resources/delete-git.png")) {
            public void actionPerformed(ActionEvent e) {
                limpiarEditor();
            }
        };

        Action saveAction = new AbstractAction("Guardar", new ImageIcon("src/resources/update-git.png")) {
            public void actionPerformed(ActionEvent e) {
                guardarArchivo();
            }
        };
        Action updateTree = new AbstractAction("Update Tree", new ImageIcon("src/resources/updatetree-git.png")) {
            public void actionPerformed(ActionEvent e) {
                actualizarJTree();
            }
        };

        Action compileAction = new AbstractAction("Run Query", new ImageIcon("src/resources/query-git.png")) {
            public void actionPerformed(ActionEvent e) {
                compilar();
            }
        };

        Action runQuery = new AbstractAction("Run Selected Query", new ImageIcon("src/resources/compile.png")) {
            @Override
            public void actionPerformed(ActionEvent e) {
                runSelected = true;
                compilar();
                runSelected = false;
            }
        };

        Action showTree;
        showTree = new AbstractAction("Arbol", new ImageIcon("src/resources/tree-git.png")) {
            public void actionPerformed(ActionEvent e) {
                mostrarArbol();
            }
        };

        Action debugAction = new AbstractAction("Debug", new ImageIcon("src/resources/bug-git.png")) {

            @Override
            public void actionPerformed(ActionEvent e) {
                selected = !selected;
                if (selected) {
                    jLabel1.setText("Debug activado");
                } else {
                    jLabel1.setText("Debug desactivado");
                }

            }
        };

        jMenu2.setMnemonic('R');
        JMenuItem item = jMenu2.add(compileAction);
        jMenu2.add(item);
        item.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F5, 0));
        item = jMenu2.add(runQuery);
        jMenu2.add(item);
        item.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F6, 0));
        jMenu2.setMnemonic('O');
        item = jMenu2.add(openFileAction);
        jMenu2.add(item);
        item.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, 0));
        item.setAccelerator(
                (javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, ActionEvent.CTRL_MASK)));
        jMenu2.setMnemonic('T');
        item = jMenu2.add(showTree);
        jMenu2.add(item);
        item.setAccelerator(
                (javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_T, ActionEvent.CTRL_MASK)));
        jMenu2.setMnemonic('S');
        item = jMenu2.add(saveAction);
        jMenu2.add(item);
        item.setAccelerator(
                (javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, ActionEvent.CTRL_MASK)));
        item = jMenu2.add(updateTree);
        jMenu2.add(item);
        item.setAccelerator(
                (javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_U, ActionEvent.CTRL_MASK)));

        JButton btnNew = this.jToolBar1.add(newFileButton);
        btnNew.setToolTipText("Nuevo archivo");

        this.jToolBar1.add(openFileAction).setToolTipText("Abrir archivo");
        this.jToolBar1.add(deleteAction).setToolTipText("Limpiar editor");
        this.jToolBar1.add(saveAction).setToolTipText("Guardar");
        this.jToolBar1.addSeparator();
        this.jToolBar1.addSeparator();
        this.jToolBar1.addSeparator();
        this.jToolBar1.addSeparator();
        this.jToolBar1.addSeparator();
        this.jToolBar1.addSeparator();
        this.jToolBar1.addSeparator();
        this.jToolBar1.addSeparator();
        this.jToolBar1.addSeparator();
        this.jToolBar1.addSeparator();
        this.jToolBar1.addSeparator();
        this.jToolBar1.addSeparator();
        this.jToolBar1.addSeparator();

        this.jToolBar1.add(showTree).setToolTipText("Mostrar Arbol");
        this.jToolBar1.add(compileAction).setToolTipText("RUN Query");
        this.jToolBar1.add(runQuery).setToolTipText("RUN SELECTED QUERY");

        this.jToolBar1.add((debugAction));

    }

    public void nuevoArchivo() {

    }

    public void limpiarEditor() {
        this.jTextArea2.setText("");
    }

    public void guardarArchivo() {
        crearArchivo(this.jTextArea2.getText(), inputFile);
    }

    public void abrirArchivo() {
        JFileChooser fc = new JFileChooser();
        int returnVal = fc.showOpenDialog(null);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            inputFile = fc.getSelectedFile();
            //This is where a real application would open the file.
            String dir = inputFile.toString();
            String input = "";
            try {
                BufferedReader br = new BufferedReader(new FileReader(inputFile.getAbsoluteFile()));
                String sCurrentLine;

                while ((sCurrentLine = br.readLine()) != null) {

                    input += sCurrentLine + "\n";

                }
                compilar2(input);
            } catch (Exception e) {
            }

            //this.jTextArea2.setText(input);

        } else {
            System.out.println("Error al abrir el archivo");
        }

    }

    public void compilar2(String in) {
        try {

            jTextArea3.setText("");

            CharStream cs = new ANTLRInputStream(in);

            sqlLexer lexer = new sqlLexer(cs);
            lexer.removeErrorListeners();
            lexer.addErrorListener(DescriptiveErrorListener.INSTANCE);
            CommonTokenStream tokens = new CommonTokenStream(lexer);
            parser = new sqlParser(tokens);
            parser.removeErrorListeners();
            parser.addErrorListener(DescriptiveErrorListener.INSTANCE);
            contexto = parser.sql2003Parser();
            ParseTree tree = contexto;

            // Specify our entry point

            ruleNames = parser.getRuleNames();

            int errorsCount = parser.getNumberOfSyntaxErrors();
            System.out.println(errorsCount);
            if (errorsCount == 0) {
                System.out.println("Parseo Exitoso");

                JOptionPane.showMessageDialog(this, "Parseo Exitoso!");
                Visitor vistor = new Visitor();
                VisitorAdolfo vistorAdolfo = new VisitorAdolfo();
                VisitorChuso vistorChuso = new VisitorChuso();
                vistor.visit(tree);
                vistorAdolfo.visit(tree);
                vistorChuso.visit(tree);
                System.out.println("visited");
            } else {
                JOptionPane.showMessageDialog(this, "Parseo Fallido!");
            }

        } catch (RecognitionException e) {
            System.out.println("ERROR");

        }
        // insertarTablaIDE();

    }

    public void compilar() {
        try {

            jTextArea3.setText("");
            String in = "";

            if (!this.runSelected) {
                in = this.jTextArea2.getText();
            } else {
                if (this.jTextArea2.getStringSelected().isEmpty()) {
                    DBMS.throwMessage("No hay nada seleccionado");
                } else {
                    in = this.jTextArea2.getStringSelected();
                }
                this.jTextArea2.setStringSelected("");
            }

            CharStream cs = new ANTLRInputStream(in);

            sqlLexer lexer = new sqlLexer(cs);
            lexer.removeErrorListeners();
            lexer.addErrorListener(DescriptiveErrorListener.INSTANCE);
            CommonTokenStream tokens = new CommonTokenStream(lexer);
            parser = new sqlParser(tokens);
            parser.removeErrorListeners();
            parser.addErrorListener(DescriptiveErrorListener.INSTANCE);
            contexto = parser.sql2003Parser();
            ParseTree tree = contexto;

            // Specify our entry point

            ruleNames = parser.getRuleNames();

            int errorsCount = parser.getNumberOfSyntaxErrors();
            System.out.println(errorsCount);
            if (errorsCount == 0) {
                System.out.println("Parseo Exitoso");

                JOptionPane.showMessageDialog(this, "Parseo Exitoso!");
                Visitor vistor = new Visitor();
                VisitorAdolfo vistorAdolfo = new VisitorAdolfo();
                VisitorChuso vistorChuso = new VisitorChuso();
                vistor.visit(tree);
                vistorAdolfo.visit(tree);
                vistorChuso.visit(tree);

            } else {
                JOptionPane.showMessageDialog(this, "Parseo Fallido!");
            }

        } catch (RecognitionException e) {
            System.out.println("ERROR");

        }

    }

    public void mostrarArbol() {
        Trees.inspect(contexto, parser);

    }

public static String leerArchivo(File inputFile){
      
    int contador=0;
    int tamao=0;
    String input=" ";
    BufferedReader br = null;
 
    try {

            String sCurrentLine;
                
            br = new BufferedReader(new FileReader(inputFile.getAbsoluteFile()));

               
               
           while ((sCurrentLine = br.readLine()) != null) {
                    
                input+=sCurrentLine+"\n";
                
            }
             
                
    input+="\n";
              
    return input;
    } catch (IOException e) {
               
    } finally {
            try {
                    if (br != null)br.close();
            } catch (IOException ex) {
                    ex.printStackTrace();
            }
    }
    return null;
        
}

    public void crearArchivo(String output, File archivo) {
        try {

            FileWriter fw = new FileWriter(archivo);
            BufferedWriter bw = new BufferedWriter(fw);

            bw.write(output);

            bw.close();

            System.out.println("Se ha guardado el archivo exitosamente");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void debug(String str, boolean debug) {
        if (debug) {
            System.out.println(str);
        }
    }

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

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

    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel5;
    public static javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTabbedPane jTabbedPane2;
    public static javax.swing.JTable jTable1;
    public static javax.swing.JTextPane jTextArea3;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JTree jTree1;
    // End of variables declaration//GEN-END:variables
}