org.rimudb.editor.RimuDBEditor.java Source code

Java tutorial

Introduction

Here is the source code for org.rimudb.editor.RimuDBEditor.java

Source

/*
 * Copyright (c) 2008-2011 Simon Ritchie.
 * All rights reserved. 
 * 
 * This program is free software: you can redistribute it and/or modify 
 * it under the terms of the GNU Lesser General Public License as published 
 * by the Free Software Foundation, either version 3 of the License, or 
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
 * See the GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License 
 * along with this program.  If not, see http://www.gnu.org/licenses/>.
 */
package org.rimudb.editor;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.sql.*;
import java.util.*;
import java.util.List;

import javax.swing.*;

import org.apache.commons.logging.*;
import org.rimudb.configuration.DescriptorModel;
import org.rimudb.configuration.FieldEntry;
import org.rimudb.editor.actions.*;
import org.rimudb.editor.exporter.*;
import org.rimudb.editor.importwizard.*;
import org.rimudb.editor.swing.*;

public class RimuDBEditor extends JFrame {
    private Log log = LogFactory.getLog(RimuDBEditor.class);
    private static final long serialVersionUID = -3159920088749329786L;
    private static final String TITLE = "RimuDB Editor";
    private JComboBox urlCB = null;

    private JMenuItem exitMenuItem = null;
    private JMenuItem openMenuItem = null;
    private JMenuItem saveMenuItem = null;
    private JMenuItem saveAsMenuItem = null;
    private JMenuItem dbImportMenuItem = null;
    private JMenuItem clearMenuItem = null;
    private JMenuItem createClassesMenuItem = null;

    private JButton createBtn = null;
    private JButton clearBtn = null;
    private JButton openBtn = null;
    private JButton saveBtn = null;
    private JButton saveAsBtn = null;

    private File file = null;

    private DescriptorEditor editor = null;

    // Properties stored locally in user.home
    private RimuDBPreferences preferences = null;
    private JMenuItem ddsExportMenuItem;
    private JMenuItem sqlExportMenuItem;
    private DescriptorFileController descriptorFileController;
    private Map<String, DriverEntry> driverMap = new TreeMap<String, DriverEntry>();
    private ToolbarButton importBtn;
    private JMenuItem aboutMenuItem;
    private JMenuItem preferencesMenuItem;
    private JMenuItem propertyRenameMenuItem;
    private JMenuItem copyCodeMenuItem;
    private JMenuItem convertFinderMenuItem;
    private JMenuItem convertCDBMenuItem;

    /**
     * DataObjectEditor
     */
    public RimuDBEditor() {
        super(TITLE);

        log.debug(System.getProperties());
        logMemory();

        // Create a preferences object
        preferences = new RimuDBPreferences(this.getClass().getName());

        // Use the system l&f
        try {
            String plaf = UIManager.getSystemLookAndFeelClassName();
            UIManager.setLookAndFeel(plaf);
        } catch (Exception e) {
        }

        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                if (getDescriptorEditor().hasChanged()) {
                    log.debug("windowClosing() Save changes to table descriptor?");
                    int option = JOptionPane.showConfirmDialog(RimuDBEditor.this,
                            "Save changes to Table Descriptor?", "RimuDB Editor", JOptionPane.YES_NO_CANCEL_OPTION);
                    // Cancel the close operation
                    if (option == JOptionPane.CANCEL_OPTION) {
                        // setVisible(true);
                        return;
                    }
                    // Save the file
                    if (option == JOptionPane.YES_OPTION) {
                        log.debug("windowClosing() saving data");
                        getDescriptorFileContoller().save();
                    }
                }
                log.debug("System.exit(0)");
                System.exit(0);
            }
        });

        setIconImage(loadIcon("/images/rimudb_logo.gif").getImage());

        descriptorFileController = new DescriptorFileController(this);

        setJMenuBar(buildJMenuBar());
        JToolBar toolbar = createToolbar();

        editor = new DescriptorEditor(this);

        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.add(toolbar, BorderLayout.NORTH);
        panel.add(new JSeparator());
        panel.add(editor, BorderLayout.CENTER);

        setContentPane(panel);

        pack();

        editor.requestPackageFocus();

        // Center in the screen
        setLocationRelativeTo(null);

        startDriverCheck();
    }

    /**
     * 
     */
    private void logMemory() {
        log.debug("total memory=" + Runtime.getRuntime().totalMemory() + " max memory="
                + Runtime.getRuntime().maxMemory() + " free memory=" + Runtime.getRuntime().freeMemory());
    }

    /**
     * Check which drivers are in the classpath
     */
    public void startDriverCheck() {
        log.debug("startDriverCheck()");

        dbImportMenuItem.setEnabled(false);
        importBtn.setEnabled(false);
        preferencesMenuItem.setEnabled(false);

        Thread runner = new Thread() {

            public void run() {
                driverCheck();

                // Change the GUI on the EDT
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        log.debug("startDriverCheck() - enabling controls");
                        dbImportMenuItem.setEnabled(true);
                        importBtn.setEnabled(true);
                        preferencesMenuItem.setEnabled(true);
                    }
                });
            }
        };

        runner.start();
    }

    public JMenuBar buildJMenuBar() {
        log.debug("buildJMenuBar()");
        JMenuBar menuBar = new JMenuBar();

        // File menu
        JMenu menu = new JMenu("File");
        menu.setMnemonic(KeyEvent.VK_F);

        openMenuItem = new JMenuItem(
                new OpenDescriptorAction(this, "Open...", loadIcon("/images/famfamfam/folder.png")));
        openMenuItem.setName("OpenMenuItem");
        openMenuItem.setMnemonic(KeyEvent.VK_O);
        openMenuItem.setAccelerator(
                KeyStroke.getKeyStroke('O', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), false));
        menu.add(openMenuItem);

        saveMenuItem = new JMenuItem(
                new SaveDescriptorAction(this, "Save", loadIcon("/images/famfamfam/disk.png")));
        saveMenuItem.setName("SaveMenuItem");
        saveMenuItem.setMnemonic(KeyEvent.VK_S);
        saveMenuItem.setAccelerator(
                KeyStroke.getKeyStroke('S', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), false));
        menu.add(saveMenuItem);

        saveAsMenuItem = new JMenuItem(new SaveAsDescriptorAction(this, "Save as..."));
        saveAsMenuItem.setName("SaveAsMenuItem");
        menu.add(saveAsMenuItem);

        menu.addSeparator();

        clearMenuItem = new JMenuItem(
                new ClearTableAction(this, "Clear...", loadIcon("/images/famfamfam/bin_closed.png")));
        clearMenuItem.setName("ClearMenuItem");
        clearMenuItem.setMnemonic(KeyEvent.VK_C);
        menu.add(clearMenuItem);

        preferencesMenuItem = new JMenuItem(
                new PreferencesAction(this, "Preferences...", loadIcon("/images/famfamfam/text_list_bullets.png")));
        preferencesMenuItem.setName("PreferencesMenuItem");
        preferencesMenuItem.setEnabled(false);
        preferencesMenuItem.setMnemonic(KeyEvent.VK_P);
        menu.add(preferencesMenuItem);

        menu.addSeparator();

        exitMenuItem = new JMenuItem(new ExitAction(this, "Exit"));
        exitMenuItem.setName("ExitMenuItem");
        exitMenuItem.setMnemonic(KeyEvent.VK_E);
        menu.add(exitMenuItem);

        menuBar.add(menu);

        JMenu toolsMenu = new JMenu("Tools");
        toolsMenu.setMnemonic(KeyEvent.VK_T);

        dbImportMenuItem = new JMenuItem(
                new ImportAction(this, "Import from database...", loadIcon("/images/famfamfam/database_go.png")));
        dbImportMenuItem.setName("DbImportMenuItem");
        dbImportMenuItem.setEnabled(false);
        dbImportMenuItem.setMnemonic(KeyEvent.VK_I);
        dbImportMenuItem.setAccelerator(
                KeyStroke.getKeyStroke('I', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), false));
        toolsMenu.add(dbImportMenuItem);

        createClassesMenuItem = new JMenuItem(new GenerateJavaAction(this, "Create classes...",
                loadIcon("/images/famfamfam/page_white_cup.png")));
        createClassesMenuItem.setName("CreateClassesMenuItem");
        createClassesMenuItem.setMnemonic(KeyEvent.VK_C);
        toolsMenu.add(createClassesMenuItem);

        ddsExportMenuItem = new JMenuItem("Export as DDS...");
        ddsExportMenuItem.setName("DdsExportMenuItem");
        ddsExportMenuItem.setMnemonic(KeyEvent.VK_D);
        ddsExportMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionExportToDDS();
            }
        });
        toolsMenu.add(ddsExportMenuItem);

        sqlExportMenuItem = new JMenuItem("Export as SQL...");
        sqlExportMenuItem.setIcon(loadIcon("/images/famfamfam/page_white_database.png"));
        sqlExportMenuItem.setName("SqlExportMenuItem");
        sqlExportMenuItem.setMnemonic(KeyEvent.VK_Q);
        sqlExportMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionExportToSQL();
            }
        });
        toolsMenu.add(sqlExportMenuItem);

        toolsMenu.addSeparator();

        propertyRenameMenuItem = new JMenuItem("Rename Properties...");
        propertyRenameMenuItem.setName("PropertyRenameMenuItem");
        propertyRenameMenuItem.setMnemonic(KeyEvent.VK_R);
        propertyRenameMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionRenameProperties();
            }
        });
        toolsMenu.add(propertyRenameMenuItem);

        copyCodeMenuItem = new JMenuItem(new GenerateCopyCodeAction(this, "Create Java DO Copy Code...", null));
        copyCodeMenuItem.setName("CopyCodeMenuItem");
        toolsMenu.add(copyCodeMenuItem);

        convertFinderMenuItem = new JMenuItem(new ConvertFinderAction(this, "Convert Finders (pre 1.1)...", null));
        convertFinderMenuItem.setName("ConvertFinderMenuItem");
        toolsMenu.add(convertFinderMenuItem);

        convertCDBMenuItem = new JMenuItem(new ConvertCDBAction(this, "Convert CDB Configs (pre 1.2)...", null));
        convertCDBMenuItem.setName("ConvertCDBMenuItem");
        toolsMenu.add(convertCDBMenuItem);

        menuBar.add(toolsMenu);

        JMenu helpMenu = new JMenu("Help");
        helpMenu.setMnemonic(KeyEvent.VK_H);

        aboutMenuItem = new JMenuItem(new AboutAction(this, "About..."));
        aboutMenuItem.setName("AboutMenuItem");
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        return menuBar;
    }

    /**
     * Handle the Rename Properties item on the tools menu
     */
    protected void actionRenameProperties() {
        log.debug("actionRenameProperties()");
        PropertyRenameDialog dialog = new PropertyRenameDialog(this, editor.getPropertyModel());
    }

    protected void actionExportToDDS() {
        log.debug("actionExportToDDS()");
        // If the filename has been chosen and it follows the iSeries file
        // naming
        // convention then deduce the record name.
        String recordname = "RECORD";
        if (file != null) {
            String filename = file.getName();
            int pos = filename.indexOf(".");
            if (pos == 8) {
                recordname = filename.substring(0, 6) + "R1";
            }
        }
        DescriptorModel descriptorModel = editor.createDescriptorModel();
        DDSExporter exporter = new DDSExporter(descriptorModel, recordname);
        String text = exporter.build();
        Font font = new Font("Monospaced", Font.PLAIN, 12);
        TextPadFrame frame = new TextPadFrame(text, font);
        frame.setPreferredSize(new Dimension(500, 300));
        frame.pack();
        frame.setLocationRelativeTo(this);
        frame.setVisible(true);
    }

    protected void actionExportToSQL() {
        log.debug("actionExportToSQL()");
        SQLExporterDialog dialog = new SQLExporterDialog(this, getDescriptorEditor().getTableName());
        if (dialog.getUserAction() == SQLExporterDialog.OK) {
            DescriptorModel descriptorModel = editor.createDescriptorModel();
            // Assume version 10 for Oracle
            int databaseMajorVersion = 0;
            if (dialog.getDatabaseName().equals("Oracle")) {
                databaseMajorVersion = 10;
            }
            SQLExporter exporter = new SQLExporter(descriptorModel, dialog.getTableName(), dialog.getDatabaseName(),
                    databaseMajorVersion, dialog.getUseQuotes());
            String text = exporter.build();
            Font font = new Font("Monospaced", Font.PLAIN, 12);
            TextPadFrame frame = new TextPadFrame(text, font);
            frame.setPreferredSize(new Dimension(500, 300));
            frame.pack();
            frame.setLocationRelativeTo(this);
            frame.setVisible(true);
        }
    }

    /**
     * Create and return a toolbar.
     */
    protected JToolBar createToolbar() {
        log.debug("createToolbar()");
        JToolBar toolbar = new JToolBar();

        // Open
        openBtn = new ToolbarButton(new OpenDescriptorAction(this, loadIcon("/images/famfamfam/folder.png")),
                "Open Table Descriptor");
        openBtn.setText("Open");
        openBtn.setName("openBtn");
        toolbar.add(openBtn);

        // Save
        saveBtn = new ToolbarButton(new SaveDescriptorAction(this, loadIcon("/images/famfamfam/disk.png")),
                "Save Table Descriptor");
        saveBtn.setText("Save");
        saveBtn.setName("saveBtn");
        toolbar.add(saveBtn);

        // A space
        //      toolbar.add(Box.createHorizontalStrut(5));

        // Clear
        clearBtn = new ToolbarButton(new ClearTableAction(this, loadIcon("/images/famfamfam/bin_closed.png")),
                "Clear");
        clearBtn.setText("Clear");
        clearBtn.setName("clearBtn");
        toolbar.add(clearBtn);

        // Save as
        //      saveAsBtn = new ToolbarButton(new SaveAsDescriptorAction(this, loadIcon("/images/sun/SaveAs24.gif")), "Save Table Descriptor as");
        //      saveAsBtn.setName("saveAsBtn");
        //      toolbar.add(saveAsBtn);

        // A space
        toolbar.addSeparator();

        // Import from a database
        importBtn = new ToolbarButton(new ImportAction(this, loadIcon("/images/famfamfam/database_go.png")),
                "Import from database");
        importBtn.setText("Import");
        importBtn.setName("importBtn");
        importBtn.setEnabled(false);
        toolbar.add(importBtn);

        // A space
        toolbar.add(Box.createHorizontalStrut(5));

        // Create classes
        createBtn = new ToolbarButton(
                new GenerateJavaAction(this, loadIcon("/images/famfamfam/page_white_cup.png")), "Create classes");
        createBtn.setText("Create");
        createBtn.setName("createBtn");
        toolbar.add(createBtn);

        // Finish up the tool bar
        toolbar.add(Box.createHorizontalGlue());
        toolbar.setFloatable(false);

        return toolbar;
    }

    public String getDatabaseURL() {
        return (String) urlCB.getSelectedItem();
    }

    /**
     * Starts the application.
     * 
     * @param args
     *            an array of command-line arguments
     */
    public static void main(java.lang.String[] args) {
        // Start the application
        RimuDBEditor wizard = new RimuDBEditor();
        wizard.setVisible(true);
    }

    /**
     * 
     */
    public void clearDisplay() {
        editor.clearData();
        file = null;
        updateTitle();
    }

    public DescriptorEditor getDescriptorEditor() {
        return editor;
    }

    public File getFile() {
        return file;
    }

    /**
     * Return the DescriptorFileController
     * 
     * @return DescriptorFileController
     */
    public DescriptorFileController getDescriptorFileContoller() {
        return descriptorFileController;
    }

    /**
     * Set the file.
     * 
     * @param file
     *            File
     */
    public void setFile(File file) {
        this.file = file;

        // Update the title with the new file name
        updateTitle();

        // Save the directory chosen
        preferences.setLastDescriptorDirectory(file.getParent());
    }

    /**
     * Return the JDBC driver names.
     * 
     * @return String[]
     */
    public Map<String, DriverEntry> getDriverMap() {
        return driverMap;
    }

    /**
     * Looks up and returns an icon for the specified filename suffix.
     */
    public static ImageIcon loadIcon(String filename) {
        URL url = RimuDBEditor.class.getResource(filename);
        if (url != null) {
            return new ImageIcon(url);
        } else {
            return null;
        }
    }

    /**
     * Load the editor from data imported from a database.
     * 
     * @param importData
     *            ImportData
     */
    public void loadImportData(ImportData importData) {
        log.debug("loadImportData()");
        file = null;

        getDescriptorEditor().clearData();

        String tableName = importData.getTableName();

        getDescriptorEditor().setTableName(tableName);

        String dataObjectName = importData.reformatToDataObjectName();

        getDescriptorEditor().setDataObjectName(dataObjectName);

        List<FieldEntry> list = importData.getList();
        for (FieldEntry fieldEntry : list) {
            getDescriptorEditor().addFieldEntry(fieldEntry);
        }

        List<String> primaryKeyList = importData.getPrimaryKeyList();
        for (String primaryKeyColumn : primaryKeyList) {
            getDescriptorEditor().addPrimaryKey(primaryKeyColumn);
        }

        updateTitle();
    }

    /**
     * Update the title
     */
    public void updateTitle() {
        if (file != null) {
            String changedText = getDescriptorEditor().hasChanged() ? " *" : "";
            setTitle(TITLE + " - " + file.getName() + changedText);
        } else {
            setTitle(TITLE);
        }
    }

    public RimuDBPreferences getPreferences() {
        return preferences;
    }

    protected void driverCheck() {
        driverMap = getPreferences().getDrivers();
        if (driverMap != null) {
            Set<String> keyset = driverMap.keySet();
            for (String driverName : keyset) {

                DriverEntry driverEntry = driverMap.get(driverName);

                boolean found = false;
                try {
                    Class.forName(driverEntry.getJdbcDriver());
                    found = true;
                } catch (Exception e) {
                    log.info("driverCheck() Could not find driverClass", e);
                }

                driverEntry.setFound(found);
            }

            List<Driver> drivers = Collections.list(DriverManager.getDrivers());
            for (int i = 0; i < drivers.size(); i++) {
                Driver driver = (Driver) drivers.get(i);

                // Find the driver in the map and add the version to the DriverEntry
                Collection<DriverEntry> values = driverMap.values();
                for (DriverEntry driverEntry : values) {
                    if (driverEntry.getJdbcDriver().trim().equals(driver.getClass().getName())) {
                        driverEntry.setDriverVersion(driver.getMajorVersion() + "." + driver.getMinorVersion());
                    }
                }

            }

        }
    }
}