se.trixon.toolbox.rsync.RsyncTopComponent.java Source code

Java tutorial

Introduction

Here is the source code for se.trixon.toolbox.rsync.RsyncTopComponent.java

Source

/*
 * Copyright 2015 Patrik Karlsson.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package se.trixon.toolbox.rsync;

import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import org.apache.commons.io.FileUtils;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.DialogDescriptor;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import se.trixon.almond.CircularInt;
import se.trixon.almond.dialogs.SimpleDialog;
import se.trixon.almond.dictionary.Dict;
import se.trixon.almond.icon.Pict;
import se.trixon.toolbox.core.base.ToolTopComponent;
import se.trixon.toolbox.rsync.editor.EditorPanel;
import se.trixon.toolbox.rsync.job.Job;
import se.trixon.toolbox.rsync.job.JobManager;
import se.trixon.toolbox.rsync.speeddial.SpeedDialButton;
import se.trixon.toolbox.rsync.speeddial.SpeedDialPanel;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(dtd = "-//se.trixon.toolbox.rsync//Rsync//EN", autostore = false)
@TopComponent.Description(preferredID = "RsyncTopComponent",
        //iconBase="SET/PATH/TO/ICON/HERE",
        persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(mode = "editor", openAtStartup = false)
@TopComponent.OpenActionRegistration(displayName = "#Tool-Name", preferredID = "RsyncTopComponent")
public final class RsyncTopComponent extends ToolTopComponent
        implements JobManager.JobListener, SpeedDialPanel.SpeedDialListener, JotaRunner.JotaListener {

    private static final String PROGRESS_PANEL = "progressPanel";
    private static final String DASHBOARD_PANEL = "dashboardPanel";
    private static final int STATES = 3;
    private static final int STARTABLE = 0;
    private static final int STOPPABLE = 1;
    private static final int CLOSEABLE = 2;
    private static final int ICON_SIZE = 32;
    private final RsyncController mController;
    private JotaRunner mJotaRunner;
    private ProgressPanel mProgressPanel;
    private SpeedDialPanel mSpeedDialPanel;
    private DialogDescriptor mDialogDescriptor;
    private CardLayout mCardLayout;
    private Job mSelectedJob;
    private boolean mSimulate;
    private final CircularInt mState = new CircularInt(0, 2);
    private ImageIcon[] mStateIcons;
    private String[] mStateTexts;

    public RsyncTopComponent() {
        mBundle = NbBundle.getBundle(RsyncTopComponent.class);
        mToolName = mBundle.getString("Tool-Name");
        initComponents();
        setName(mToolName);
        mController = new RsyncController(this);
        init();
    }

    @Override
    public void onJobSave() {
        DefaultComboBoxModel model = JobManager.INSTANCE
                .populateModel((DefaultComboBoxModel) jobsComboBox.getModel());
        boolean hasJob = model.getSize() > 0;
        jobsComboBox.setModel(model);
        jobsComboBox.setVisible(hasJob);
        stateButton.setVisible(hasJob);
        mSpeedDialPanel.setButtonsVisibility(hasJob);

        if (mSelectedJob != null) {
            jobsComboBox.setSelectedItem(mSelectedJob);

            for (int i = 0; i < model.getSize(); i++) {
                Job job = (Job) model.getElementAt(i);

                if (job.getId() == mSelectedJob.getId()) {
                    jobsComboBox.setSelectedIndex(i);
                    break;
                }
            }
        }
    }

    @Override
    public void onJotaFinished(Job job, int exitValue) {
        mProgressPanel.stop();
        setState(CLOSEABLE);
        mSelectedJob.setLastRun(System.currentTimeMillis());
        JobManager.INSTANCE.notifyDataListeners();
        try {
            JotaManager.INSTANCE.save();
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
        stateButton.requestFocus();
    }

    @Override
    public void onJotaStarted(Job job) {
        jobEditorButton.setVisible(false);
        jobsComboBox.setEnabled(false);
        mCardLayout.show(mainPanel, PROGRESS_PANEL);
        setState(STOPPABLE);
    }

    @Override
    public void onJotaStopped(Job job) {
        mProgressPanel.stop();
        setState(CLOSEABLE);
        stateButton.requestFocus();
    }

    @Override
    public void onSpeedDialButtonClicked(SpeedDialButton speedDialButton) {
        requestJobStart(speedDialButton.getJob());
    }

    @Override
    public boolean canClose() {
        return true;// mState.get() != STOPPABLE;
    }

    private void debug(String string) {
        System.out.println(string);
        mProgressPanel.launcherLog(string);
    }

    private void init() {
        JobManager.INSTANCE.addJobListener(this);
        mCardLayout = (CardLayout) (mainPanel.getLayout());
        mSpeedDialPanel = new SpeedDialPanel();
        mProgressPanel = new ProgressPanel();

        mainPanel.add(mSpeedDialPanel, DASHBOARD_PANEL);
        mainPanel.add(mProgressPanel, PROGRESS_PANEL);

        mSpeedDialPanel.addSpeedDialListener(this);
        JobManager.INSTANCE.notifyDataListeners();

        mStateTexts = new String[STATES];
        mStateTexts[STARTABLE] = Dict.START.getString();
        mStateTexts[STOPPABLE] = Dict.STOP.getString();
        mStateTexts[CLOSEABLE] = Dict.CLOSE.getString();

        mStateIcons = new ImageIcon[STATES];
        mStateIcons[STARTABLE] = Pict.Actions.ARROW_RIGHT.get(ICON_SIZE);
        mStateIcons[STOPPABLE] = Pict.Actions.PROCESS_STOP.get(ICON_SIZE);
        mStateIcons[CLOSEABLE] = Pict.Actions.WINDOW_CLOSE.get(ICON_SIZE);

        setState(mState.get());
    }

    private boolean requestJobStart(Job job) {
        mSelectedJob = job;
        mProgressPanel.setProgressString(job.getName());
        String start = Dict.START.getString();
        String simulate = "Simulate";
        String cancel = Dict.CANCEL.getString();
        String[] options = new String[] { simulate, start };
        String title = "Confirm";
        String message = String.format("<html>Start job <b>%s</b>?</html>", job.getName());

        NotifyDescriptor d = new NotifyDescriptor(message, title, NotifyDescriptor.DEFAULT_OPTION,
                NotifyDescriptor.QUESTION_MESSAGE, options, start);
        d.setAdditionalOptions(new String[] { cancel });

        //        Object retval = DialogDisplayer.getDefault().notify(d);
        //        mSimulate = retval == simulate;
        //        if (retval == start || retval == simulate) {
        mJotaRunner = new JotaRunner(mProgressPanel);
        mJotaRunner.addJotaListener(this);
        mJotaRunner.start(job, mSimulate);
        //        }

        return false;
    }

    private void requestJobStop() {
        mJotaRunner.stop();
        setState(CLOSEABLE);
    }

    private void setState(int state) {
        mState.set(state);
        stateButton.setToolTipText(mStateTexts[state]);
        stateButton.setIcon(mStateIcons[state]);
        saveButton.setVisible(state == CLOSEABLE);
    }

    private void showEditor() {
        mSelectedJob = (Job) jobsComboBox.getSelectedItem();

        String title = NbBundle.getMessage(this.getClass(), "RsyncTopComponent.jobEditorButton.toolTipText");
        EditorPanel mEditorPanel = new EditorPanel();
        DialogDescriptor dialogDescriptor = new DialogDescriptor(mEditorPanel, title, true, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
            }
        });

        dialogDescriptor.setAdditionalOptions(new JButton[] { new JButton(Dict.EXPORT.getString()) });
        Object retval = DialogDisplayer.getDefault().notify(dialogDescriptor);
        if (retval == DialogDescriptor.OK_OPTION) {
            mEditorPanel.save();
            try {
                JotaManager.INSTANCE.save();
            } catch (IOException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    }

    /**
     * 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.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        toolBar = new javax.swing.JToolBar();
        jobsComboBox = new javax.swing.JComboBox();
        stateButton = new javax.swing.JButton();
        saveButton = new javax.swing.JButton();
        filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0),
                new java.awt.Dimension(32767, 0));
        jobEditorButton = new javax.swing.JButton();
        mainPanel = new javax.swing.JPanel();

        toolBar.setFloatable(false);
        toolBar.setRollover(true);

        jobsComboBox.setMaximumSize(new java.awt.Dimension(200, 32767));
        toolBar.add(jobsComboBox);

        stateButton.setBorderPainted(false);
        stateButton.setFocusable(false);
        stateButton.setHorizontalAlignment(javax.swing.SwingConstants.LEADING);
        stateButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        stateButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        stateButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                stateButtonActionPerformed(evt);
            }
        });
        toolBar.add(stateButton);

        saveButton.setIcon(Pict.Actions.DOCUMENT_SAVE_AS.get(ICON_SIZE));
        saveButton.setToolTipText(Dict.SAVE_AS.getString());
        saveButton.setBorderPainted(false);
        saveButton.setFocusable(false);
        saveButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        saveButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });
        toolBar.add(saveButton);
        toolBar.add(filler1);

        jobEditorButton.setIcon(Pict.Actions.CONFIGURE.get(ICON_SIZE));
        jobEditorButton.setToolTipText(org.openide.util.NbBundle.getMessage(RsyncTopComponent.class,
                "RsyncTopComponent.jobEditorButton.toolTipText")); // NOI18N
        jobEditorButton.setBorderPainted(false);
        jobEditorButton.setFocusable(false);
        jobEditorButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jobEditorButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jobEditorButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jobEditorButtonActionPerformed(evt);
            }
        });
        toolBar.add(jobEditorButton);

        mainPanel.setLayout(new java.awt.CardLayout());

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(toolBar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
                        Short.MAX_VALUE)
                .addComponent(mainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 0, Short.MAX_VALUE));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                        .addComponent(toolBar, javax.swing.GroupLayout.DEFAULT_SIZE,
                                javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, 0)
                        .addComponent(mainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 231, Short.MAX_VALUE)));
    }// </editor-fold>//GEN-END:initComponents

    private void jobEditorButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jobEditorButtonActionPerformed
        showEditor();
    }//GEN-LAST:event_jobEditorButtonActionPerformed

    private void stateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stateButtonActionPerformed
        if (mState.get() == STARTABLE) {
            mSelectedJob = (Job) jobsComboBox.getSelectedItem();
            requestJobStart(mSelectedJob);
        } else if (mState.get() == STOPPABLE) {
            requestJobStop();
        } else if (mState.get() == CLOSEABLE) {
            jobsComboBox.setEnabled(true);
            jobEditorButton.setEnabled(true);
            jobEditorButton.setVisible(true);
            mCardLayout.show(mainPanel, DASHBOARD_PANEL);
            setState(STARTABLE);
            mProgressPanel.reset();
        }
    }//GEN-LAST:event_stateButtonActionPerformed

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        String dateTime = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date(mSelectedJob.getLastRun()));
        File logFile = new File(Options.INSTANCE.getLogDirectory(),
                String.format("%s_%s.log", mSelectedJob.getName(), dateTime));

        SimpleDialog.setParent(saveButton.getTopLevelAncestor());
        SimpleDialog.setTitle(Dict.SAVE_AS.getString());
        SimpleDialog.setPath(logFile);
        SimpleDialog.setPath(Options.INSTANCE.getLogDirectory());

        if (SimpleDialog.saveFile()) {
            try {
                FileUtils.writeStringToFile(SimpleDialog.getPath(), mProgressPanel.getText());
            } catch (IOException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    }//GEN-LAST:event_saveButtonActionPerformed

    @Override
    public void componentOpened() {
        Job job = JobManager.INSTANCE.getJobById(Options.INSTANCE.getJobId());
        jobsComboBox.setSelectedItem(job);
    }

    @Override
    public void componentClosed() {
        mSelectedJob = (Job) jobsComboBox.getSelectedItem();
        Options.INSTANCE.setJobId(mSelectedJob.getId());
    }

    void writeProperties(java.util.Properties p) {
        p.setProperty("version", "1.0");
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.Box.Filler filler1;
    private javax.swing.JButton jobEditorButton;
    private javax.swing.JComboBox jobsComboBox;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JButton saveButton;
    private javax.swing.JButton stateButton;
    private javax.swing.JToolBar toolBar;
    // End of variables declaration//GEN-END:variables

}