edu.synth.SynthHelper.java Source code

Java tutorial

Introduction

Here is the source code for edu.synth.SynthHelper.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 edu.synth;

import java.io.File;
import java.io.IOException;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

import org.apache.commons.io.FileUtils;

import edu.synth.gui.*;
import edu.synth.logging.LogPublisher;
import edu.synth.logging.Messager;
import edu.synth.state.*;
import edu.synth.state.threads.*;
import edu.synth.utils.Constants;
import edu.synth.settings.SettingsBuilder;

import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JSeparator;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import javax.swing.GroupLayout.Alignment;
import javax.swing.GroupLayout;

public class SynthHelper extends JFrame {
    private static final long serialVersionUID = 2953026546965833308L;

    private static SyntHelper instance;
    private SyntHelperState state = SyntHelperState.getInstance();

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTabbedPane tabbedPane;
    private GeneralSynthPanel synthPanel;
    private AbundancesPanel abundancesPanel;
    private JMenuBar menuBar;
    private JMenu mnFile;
    private JMenu mnOperations;
    private JMenu mnHelp;
    private JMenuItem mntmOpenWorkspace;
    private JMenuItem mntmLogWindow;
    private JMenuItem mntmHelp;
    private JMenuItem mntmAbout;
    private JMenuItem mntmViewObs;
    private JMenuItem mntmRunSynth;
    private JMenuItem mntmRunSynthForObs;
    private JMenuItem mntmApplyChanges;
    private JMenuItem mntmExportConfFiles;
    private JMenuItem mntmExit;
    private StatusBar statusBar;

    // End of variables declaration//GEN-END:variables
    /**
     * Creates new form MainPage
     */

    public static SyntHelper getInstance() {
        return instance;
    }

    public SynthHelper() {
        try {
            FileUtils.copyFile(new File(Constants.DEF_SOLAR_ABN), new File(Constants.ABN_PATH));
            FileUtils.copyFile(new File(Constants.DEF_CONV_CONF), new File(Constants.CONV_PATH));
            FileUtils.copyFile(new File(Constants.DEF_SYNTH_INP), new File(Constants.SYNTH_PATH));
        } catch (IOException e) {
            e.printStackTrace();
            ;
        }
        clear();
        initSettings();
        menu();
        controls();
        Messager.publish("Welcome to  SYNTHelper! Logging started...");
        instance = this;
    }

    private void clear() {
        new File(Constants.SYNTH_RES).delete();
        new File(Constants.CONV_RES).delete();
        new File(Constants.DIV_RES).delete();
        new File(Constants.OBS_DATA).delete();
        new File(Constants.MODEL_PATH).delete();
    }

    public void initSettings() {
        try {
            state.setSynthSettings(SettingsBuilder.buildSettings(Constants.SYNTH_PATH, state.getSynthSettings()));
        } catch (Exception e) {
            Messager.publish("Parsing and initializing of SYNTH Settings", e);
        }
        try {
            state.setConvolveSettings(
                    SettingsBuilder.buildSettings(Constants.CONV_PATH, state.getConvolveSettings()));
        } catch (Exception e) {
            Messager.publish("Parsing and initializing of CONV Settings", e);
        }
        try {
            state.setAbundanceSettings(
                    SettingsBuilder.buildSettings(Constants.ABN_PATH, state.getAbundanceSettings()));
        } catch (Exception e) {
            Messager.publish("Parsing and initializing of ABN Settings", e);
        }

        if (new File(Constants.OBS_DATA).exists())
            try {
                state.handleObsData();
            } catch (Exception e) {
                Messager.publish("SYNTHelper - prepare OBS DATA", e);
            }
        try {
            state.resetLinePathList();
            state.getSynthSettings().saveSettings(new File(Constants.SYNTH_PATH));
        } catch (IOException e) {
            Messager.publish("SYNTHelper - initSettings", e);
        }

    }

    public void setValues() {
        statusBar.setMainMessage(state.getWorkspacePath());
        synthPanel.setValues();
        abundancesPanel.setValues();
    }

    private void menu() {
        menuBar = new JMenuBar();
        setJMenuBar(menuBar);

        mnFile = new JMenu("File");
        menuBar.add(mnFile);

        mntmOpenWorkspace = new JMenuItem("Open Workspace...");
        mntmOpenWorkspace.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        clear();
                        String path = SyntHelper.getInstance().openDialogFileChooser(state.getWorkspacePath(), true,
                                "Choose Workspace", "Choose", null);
                        try {
                            state.setWorkspacePath(path);
                        } catch (IOException e) {
                            Messager.publish("Set Workspace", e);
                        }
                        initSettings();
                        setValues();
                    }
                }).start();
            }
        });
        mnFile.add(mntmOpenWorkspace);

        mntmApplyChanges = new JMenuItem("Save Changes...");
        mntmApplyChanges.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            state.saveSettings();
                        } catch (IOException e) {
                            Messager.publish("Save Settings Files", e);
                        }
                    }
                }).start();
            }
        });
        mnFile.add(mntmApplyChanges);

        mntmExportConfFiles = new JMenuItem("Export Settings Files to Workspace...");
        mntmExportConfFiles.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            state.saveSettings();
                        } catch (IOException e) {
                            Messager.publish("Save Settings Files", e);
                        }
                        if (!state.getWorkspacePath().isEmpty())
                            try {
                                state.copySettingsFilesToWorkspace();
                            } catch (IOException e) {
                                Messager.publish("Export Settings Files to Workspace", e);
                            }
                        else
                            Messager.publish("Export Settings Files to Workspace",
                                    "Files have not been copied. Workspace has not been selected!");
                    }
                }).start();
            }
        });
        mnFile.add(mntmExportConfFiles);

        mnFile.add(new JSeparator());
        mntmExit = new JMenuItem("Exit");
        mntmExit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                System.exit(0);
            }
        });
        mnFile.add(mntmExit);

        mnOperations = new JMenu("Operations");
        menuBar.add(mnOperations);

        mntmViewObs = new JMenuItem("View Observed Data (1.obs)");
        mntmViewObs.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            new DataViewWindow("Observed Data Viewer", new File(Constants.OBS_DATA));
                        } catch (IOException e) {
                            Messager.publish("Observed Data Viewer error", e);
                        }
                    }
                }).start();
            }
        });
        mnOperations.add(mntmViewObs);

        mnOperations.add(new JSeparator());

        mntmRunSynth = new JMenuItem("Run Synth");
        mntmRunSynth.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                new Thread(new ExecuteSynthConvThread()).start();
            }
        });
        mnOperations.add(mntmRunSynth);

        mntmRunSynthForObs = new JMenuItem("Run Synth for Observed Data");
        mntmRunSynthForObs.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                final Thread main = new Thread(new ExecuteSynthConvDivThread());
                main.start();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        while (main.isAlive()) {
                        }
                        ;
                        try {
                            new SyntHelperChartWindow("Result of synthesis and dividing");
                        } catch (IOException e) {
                            Messager.publish("Charting result error", e);
                        }
                    }
                }).start();
            }
        });
        mnOperations.add(mntmRunSynthForObs);

        mnHelp = new JMenu("Help");
        menuBar.add(mnHelp);

        mntmLogWindow = new JMenuItem("Log Window");
        mntmLogWindow.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                LogPublisher.getInstance().openWindow();
            }
        });
        mnHelp.add(mntmLogWindow);

        mnHelp.add(new JSeparator());

        mntmAbout = new JMenuItem("About SYNTHelper");
        mnHelp.add(mntmAbout);

        mntmHelp = new JMenuItem("Help Content");
        mnHelp.add(mntmHelp);
    }

    private void controls() {
        tabbedPane = new javax.swing.JTabbedPane();
        synthPanel = new GeneralSynthPanel();
        abundancesPanel = new AbundancesPanel();
        statusBar = new StatusBar("Workspace is not selected...");
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("SYNTHelper v. 1.0");
        tabbedPane.setToolTipText("SYNTH Settings");
        tabbedPane.addTab("Synthesis", synthPanel);
        tabbedPane.addTab("Abundances", abundancesPanel);
        GroupLayout layout = new GroupLayout(getContentPane());
        layout.setHorizontalGroup(layout.createParallelGroup(Alignment.LEADING)
                .addComponent(tabbedPane, GroupLayout.DEFAULT_SIZE, 640, Short.MAX_VALUE)
                .addComponent(statusBar, GroupLayout.DEFAULT_SIZE, 640, Short.MAX_VALUE));
        layout.setVerticalGroup(layout.createParallelGroup(Alignment.TRAILING)
                .addGroup(layout.createSequentialGroup().addContainerGap()
                        .addComponent(tabbedPane, GroupLayout.DEFAULT_SIZE, 357, Short.MAX_VALUE)
                        .addComponent(statusBar, GroupLayout.PREFERRED_SIZE, 25, GroupLayout.PREFERRED_SIZE)));
        getContentPane().setLayout(layout);
        tabbedPane.getAccessibleContext().setAccessibleDescription("");
        pack();
    }

    public String openDialogFileChooser(String path, boolean dirOnly, String name, String button,
            String filterType) {
        JFileChooser fileOpen = new JFileChooser();
        if (!path.isEmpty())
            fileOpen.setCurrentDirectory(new File(path));
        else
            fileOpen.setCurrentDirectory(new File("."));
        if (dirOnly)
            fileOpen.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        else {
            fileOpen.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            switch (filterType) {
            case "abn":
                FileFilter filter = new FileNameExtensionFilter("*.abn - Abundances file", "abn");
                fileOpen.setFileFilter(filter);
                break;
            case "model":
                filter = new FileNameExtensionFilter("*.atl - Kurucz's format model file", "atl");
                fileOpen.setFileFilter(filter);
                break;
            case "lns":
                filter = new FileNameExtensionFilter("*.lns - Lines file", "lns");
                fileOpen.setFileFilter(filter);
                break;
            }
        }
        fileOpen.setDialogTitle(name);
        fileOpen.setApproveButtonText(button);
        int returnVal = fileOpen.showOpenDialog(fileOpen);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File selectedPath = fileOpen.getSelectedFile();
            if (selectedPath != null)
                return selectedPath.getAbsolutePath();
        }
        return "";
    }

    /**
     * @param args
     *            the command line arguments
     */
    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            Messager.publish("SYNTHelper - main", ex);
        } catch (InstantiationException ex) {
            Messager.publish("SYNTHelper - main", ex);
        } catch (IllegalAccessException ex) {
            Messager.publish("SYNTHelper - main", ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            Messager.publish("SYNTHelper - main", ex);
        }
        // </editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                SyntHelper app = new SyntHelper();
                app.setVisible(true);
                app.setExtendedState(app.getExtendedState() | JFrame.MAXIMIZED_BOTH);
                ;
            }
        });
    }
}