Example usage for javax.swing SwingWorker execute

List of usage examples for javax.swing SwingWorker execute

Introduction

In this page you can find the example usage for javax.swing SwingWorker execute.

Prototype

public final void execute() 

Source Link

Document

Schedules this SwingWorker for execution on a worker thread.

Usage

From source file:com.mirth.connect.client.ui.SettingsPanelServer.java

public void doBackup() {
    if (isSaveEnabled()) {
        int option = JOptionPane.showConfirmDialog(this, "Would you like to save the settings first?");

        if (option == JOptionPane.YES_OPTION) {
            if (!doSave()) {
                return;
            }//  w  w w.j a  v a2  s . com
        } else if (option == JOptionPane.CANCEL_OPTION || option == JOptionPane.CLOSED_OPTION) {
            return;
        }
    }

    final String backupDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    final File exportFile = getFrame().createFileForExport(backupDate.substring(0, 10) + " Mirth Backup.xml",
            "XML");

    if (exportFile != null) {
        final String workingId = getFrame().startWorking("Exporting server config...");

        SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {

            public Void doInBackground() {
                ServerConfiguration configuration = null;

                try {
                    configuration = getFrame().mirthClient.getServerConfiguration();
                } catch (ClientException e) {
                    getFrame().alertThrowable(SettingsPanelServer.this, e);
                    return null;
                }

                // Update resource names
                for (Channel channel : configuration.getChannels()) {
                    getFrame().updateResourceNames(channel, configuration.getResourceProperties().getList());
                }

                configuration.setDate(backupDate);
                String backupXML = ObjectXMLSerializer.getInstance().serialize(configuration);

                getFrame().exportFile(backupXML, exportFile, "Server Configuration");
                return null;
            }

            public void done() {
                getFrame().stopWorking(workingId);
            }
        };

        worker.execute();
    }
}

From source file:mainGUI.TrainingJFrame.java

private void loadMNISTButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadMNISTButtonActionPerformed
    mnistProgressBar.setMaximum(60000);//from   www . ja  va  2  s . co  m

    SwingWorker<TrainingDataSet, Integer> worker = new SwingWorker<TrainingDataSet, Integer>() {
        @Override
        protected TrainingDataSet doInBackground() throws Exception {
            MNISTDatasetLoader.setOnDataitemLoadListener(new OnDataitemLoadListener() {
                @Override
                public void onDataitemLoadListener(int currentProgress) {
                    publish(currentProgress);
                }
            });
            return MNISTDatasetLoader.loadMNISTDataset("MNIST/train-images.idx3-ubyte",
                    "MNIST/train-labels.idx1-ubyte");
        }

        @Override
        protected void process(List<Integer> chunks) {
            mnistProgressBar.setValue(chunks.get(chunks.size() - 1));
            mnistProgressBar.setString(chunks.get(chunks.size() - 1) + " of 60000");
        }

        protected void done() {
            try {
                trainingDataSet = get();
                loadNetPanel.setEnabled(true);
                System.out.println("MNIST Dataset Loaded");
            } catch (InterruptedException ex) {
                ex.printStackTrace();
                Logger.getLogger(TrainingJFrame.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ExecutionException ex) {
                ex.printStackTrace();
                Logger.getLogger(TrainingJFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    };
    worker.execute();
}

From source file:dbseer.gui.actions.ExplainChartAction.java

private void explain() {
    try {/*from  w  ww  . ja  v  a2 s. co  m*/
        if (panel.getAnomalyRegion().isEmpty()) {
            JOptionPane.showMessageDialog(null, "Please select an anomaly region.", "Warning",
                    JOptionPane.WARNING_MESSAGE);
            return;
        }

        //         console.setText("Analyzing data for explanation... ");
        DBSeerGUI.explainStatus.setText("Analyzing data for explanation...");

        final StatisticalPackageRunner runner = DBSeerGUI.runner;
        final DBSeerExplainChartPanel explainPanel = this.panel;
        final String causalModelPath = this.causalModelPath;
        final JTextArea console = this.console;
        final ExplainChartAction action = this;

        SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
            String normalIdx = "";
            String anomalyIdx = "";

            HashSet<Integer> normalRegion = new HashSet<Integer>();
            HashSet<Integer> anomalyRegion = new HashSet<Integer>();

            @Override
            protected Void doInBackground() throws Exception {
                for (Double d : explainPanel.getNormalRegion()) {
                    normalRegion.add(d.intValue());
                }
                for (Double d : explainPanel.getAnomalyRegion()) {
                    anomalyRegion.add(d.intValue());
                }

                for (Integer i : normalRegion) {
                    normalIdx = normalIdx + i.toString() + " ";
                }
                for (Integer i : anomalyRegion) {
                    anomalyIdx = anomalyIdx + i.toString() + " ";
                }

                runner.eval("normal_idx = [" + normalIdx + "];");
                runner.eval("anomaly_idx = [" + anomalyIdx + "];");
                runner.eval(
                        "[predicates explanations] = explainPerformance(plotter.mv, anomaly_idx, normal_idx, '"
                                + causalModelPath + "', 500, 0.2, 10);");

                return null;
            }

            @Override
            protected void done() {
                try {
                    DBSeerGUI.explainStatus.setText("");
                    printExplanations();
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                    e.printStackTrace();
                }
            }
        };
        worker.execute();
    } catch (Exception e) {
        DBSeerExceptionHandler.handleException(e);
    }
}

From source file:com.mirth.connect.client.ui.SettingsPanelResources.java

public void doReloadResource() {
    final int selectedRow = resourceTable.getSelectedRow();

    if (selectedRow >= 0) {
        if (getFrame().isSaveEnabled()) {
            getFrame().alertWarning(getFrame(), "You must save before reloading any resources.");
            return;
        }/*from  ww w  .j ava 2 s  .c o  m*/

        if (!getFrame().alertOption(getFrame(),
                "<html>Libraries associated with this resource will be reloaded.<br/>Any channels / connectors using those libraries will be<br/>affected. Also, a maximum of 1000 files may be loaded into<br/>a directory resource, with additional files being skipped.<br/>Are you sure you wish to continue?</html>")) {
            return;
        }

        final String workingId = getFrame().startWorking("Reloading resource...");
        final String resourceId = ((ResourceProperties) resourceTable.getModel().getValueAt(selectedRow,
                PROPERTIES_COLUMN)).getId();

        SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {

            @Override
            public Void doInBackground() throws ClientException {
                getFrame().mirthClient.reloadResource(resourceId);
                return null;
            }

            @Override
            public void done() {
                try {
                    get();

                    if (resourceTable.getSelectedRow() == selectedRow && currentPropertiesPanel != null) {
                        ResourceProperties properties = (ResourceProperties) resourceTable.getModel()
                                .getValueAt(selectedRow, PROPERTIES_COLUMN);
                        properties.setName(
                                (String) resourceTable.getModel().getValueAt(selectedRow, NAME_COLUMN));
                        properties.setIncludeWithGlobalScripts((Boolean) resourceTable.getModel()
                                .getValueAt(selectedRow, GLOBAL_SCRIPTS_COLUMN));
                        currentPropertiesPanel.fillProperties(properties);
                        currentPropertiesPanel.setProperties(properties);
                    }
                } catch (Throwable t) {
                    if (t instanceof ExecutionException) {
                        t = t.getCause();
                    }
                    getFrame().alertThrowable(getFrame(), t, "Error reloading resource: " + t.toString());
                } finally {
                    getFrame().stopWorking(workingId);
                }
            }
        };

        worker.execute();
    }
}

From source file:com.mirth.connect.client.ui.SettingsPanelServer.java

private void testEmailButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_testEmailButtonActionPerformed
    resetInvalidSettings();/*from   ww  w .  j  a  v a 2  s . co m*/
    ServerSettings serverSettings = getServerSettings();
    StringBuilder invalidFields = new StringBuilder();

    if (StringUtils.isBlank(serverSettings.getSmtpHost())) {
        smtpHostField.setBackground(UIConstants.INVALID_COLOR);
        invalidFields.append("\"SMTP Host\" is required\n");
    }

    if (StringUtils.isBlank(serverSettings.getSmtpPort())) {
        smtpPortField.setBackground(UIConstants.INVALID_COLOR);
        invalidFields.append("\"SMTP Port\" is required\n");
    }

    if (StringUtils.isBlank(serverSettings.getSmtpTimeout())) {
        smtpTimeoutField.setBackground(UIConstants.INVALID_COLOR);
        invalidFields.append("\"Send Timeout\" is required\n");
    }

    if (StringUtils.isBlank(serverSettings.getSmtpFrom())) {
        defaultFromAddressField.setBackground(UIConstants.INVALID_COLOR);
        invalidFields.append("\"Default From Address\" is required\n");
    }

    if (serverSettings.getSmtpAuth()) {
        if (StringUtils.isBlank(serverSettings.getSmtpUsername())) {
            usernameField.setBackground(UIConstants.INVALID_COLOR);
            invalidFields.append("\"Username\" is required\n");
        }

        if (StringUtils.isBlank(serverSettings.getSmtpPassword())) {
            passwordField.setBackground(UIConstants.INVALID_COLOR);
            invalidFields.append("\"Password\" is required\n");
        }
    }

    String errors = invalidFields.toString();
    if (StringUtils.isNotBlank(errors)) {
        PlatformUI.MIRTH_FRAME.alertCustomError(PlatformUI.MIRTH_FRAME, errors,
                "Please fix the following errors before sending a test email:");
        return;
    }

    String sendToEmail = (String) JOptionPane.showInputDialog(PlatformUI.MIRTH_FRAME, "Send test email to:",
            "Send Test Email", JOptionPane.INFORMATION_MESSAGE, null, null, serverSettings.getSmtpFrom());

    if (StringUtils.isNotBlank(sendToEmail)) {
        try {
            new InternetAddress(sendToEmail).validate();
        } catch (Exception error) {
            PlatformUI.MIRTH_FRAME.alertWarning(PlatformUI.MIRTH_FRAME,
                    "The Send To Address is invalid: " + error.getMessage());
            return;
        }

        final Properties properties = new Properties();
        properties.put("port", serverSettings.getSmtpPort());
        properties.put("encryption", serverSettings.getSmtpSecure());
        properties.put("host", serverSettings.getSmtpHost());
        properties.put("timeout", serverSettings.getSmtpTimeout());
        properties.put("authentication", String.valueOf(serverSettings.getSmtpAuth()));
        properties.put("username", serverSettings.getSmtpUsername());
        properties.put("password", serverSettings.getSmtpPassword());
        properties.put("toAddress", sendToEmail);
        properties.put("fromAddress", serverSettings.getSmtpFrom());

        final String workingId = PlatformUI.MIRTH_FRAME.startWorking("Sending test email...");

        SwingWorker worker = new SwingWorker<Void, Void>() {

            public Void doInBackground() {

                try {
                    ConnectionTestResponse response = (ConnectionTestResponse) PlatformUI.MIRTH_FRAME.mirthClient
                            .sendTestEmail(properties);

                    if (response == null) {
                        PlatformUI.MIRTH_FRAME.alertError(PlatformUI.MIRTH_FRAME, "Failed to send email.");
                    } else if (response.getType().equals(ConnectionTestResponse.Type.SUCCESS)) {
                        PlatformUI.MIRTH_FRAME.alertInformation(PlatformUI.MIRTH_FRAME, response.getMessage());
                    } else {
                        PlatformUI.MIRTH_FRAME.alertWarning(PlatformUI.MIRTH_FRAME, response.getMessage());
                    }

                    return null;
                } catch (Exception e) {
                    PlatformUI.MIRTH_FRAME.alertThrowable(PlatformUI.MIRTH_FRAME, e);
                    return null;
                }
            }

            public void done() {
                PlatformUI.MIRTH_FRAME.stopWorking(workingId);
            }
        };

        worker.execute();
    }
}

From source file:edu.ku.brc.ui.UIRegistry.java

/**
 * Fades screen and writes message to screen
 * @param localizedMsg the already localized message
 * @param milliseconds the number of milliseconds to pause showing the message
 * @param textColor the color of the text
 * @param pointSize the point size to draw the text
 * @param yTextPos set the the 'y' position of the text
 *//* ww  w .  jav  a 2  s  .  c om*/
public static void writeTimedSimpleGlassPaneMsg(final String localizedMsg, final Integer milliseconds,
        final Color textColor, final Integer pointSize, final boolean doHideOnClick, final Integer yTextPos) {
    final SimpleGlassPane sgp = UIRegistry.writeSimpleGlassPaneMsg(localizedMsg,
            pointSize == null ? STD_FONT_SIZE : pointSize);
    if (sgp != null) {
        sgp.setTextColor(textColor);
        sgp.setHideOnClick(doHideOnClick);
        sgp.setTextYPos(yTextPos);
    }

    SwingWorker<Integer, Integer> msgWorker = new SwingWorker<Integer, Integer>() {
        /* (non-Javadoc)
         * @see javax.swing.SwingWorker#doInBackground()
         */
        @Override
        protected Integer doInBackground() throws Exception {
            try {
                Thread.sleep(milliseconds != null ? milliseconds : STD_WAIT_TIME);

            } catch (Exception ex) {
                ex.printStackTrace();
            }

            return null;
        }

        @Override
        protected void done() {
            super.done();

            if (sgp != null) {
                sgp.setTextColor(null);
            }

            UIRegistry.clearSimpleGlassPaneMsg();

            if (textColor == Color.RED) {
                getStatusBar().setErrorMessage(localizedMsg);
            } else {
                displayStatusBarText(localizedMsg);
            }
        }
    };

    msgWorker.execute();
}

From source file:edu.ku.brc.af.core.db.MySQLBackupService.java

/**
 * @param newFilePath//from w  w w  .  ja va 2 s  . c  o  m
 * @param isMonthly
 */
public void doCompareBeforeRestore(final String restoreFilePath, final SimpleGlassPane glassPane) {
    SwingWorker<Integer, Integer> backupWorker = new SwingWorker<Integer, Integer>() {
        protected Vector<Object[]> rowData = null;

        /* (non-Javadoc)
         * @see javax.swing.SwingWorker#doInBackground()
         */
        @Override
        protected Integer doInBackground() throws Exception {
            rowData = doCompare(MySQLBackupService.this.getTableNames(), restoreFilePath);
            return null;
        }

        @Override
        protected void done() {
            super.done();

            if (rowData != null && rowData.size() > 0) {
                UIRegistry.getStatusBar().setProgressDone(STATUSBAR_NAME);

                BackupCompareDlg dlg = new BackupCompareDlg(rowData);
                dlg.setVisible(true);
                if (!dlg.isCancelled()) {
                    doActualRestore(restoreFilePath, glassPane);
                } else {
                    UIRegistry.clearSimpleGlassPaneMsg();
                }
            } else {
                doActualRestore(restoreFilePath, glassPane);
            }
        }
    };
    backupWorker.execute();
}

From source file:net.sourceforge.atunes.kernel.modules.repository.RepositoryHandler.java

/**
 * Adds the given files to repository and refresh.
 * //from  www.  java 2s .c  o  m
 * @param files
 *            the files
 */
public void addFilesAndRefresh(final List<File> files) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            VisualHandler.getInstance().showProgressBar(true,
                    StringUtils.getString(LanguageTool.getString("REFRESHING"), "..."));
        }
    });
    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
        @Override
        protected Void doInBackground() throws Exception {
            RepositoryLoader.addToRepository(repository, files);
            return null;
        }

        @Override
        protected void done() {
            super.done();
            // Persist
            ApplicationStateHandler.getInstance().persistRepositoryCache(repository, false);

            VisualHandler.getInstance().showProgressBar(false, null);
            VisualHandler.getInstance().showRepositoryAudioFileNumber(getAudioFiles().size(),
                    getRepositoryTotalSize(), repository.getTotalDurationInSeconds());
            if (ControllerProxy.getInstance().getNavigationController() != null) {
                ControllerProxy.getInstance().getNavigationController().notifyReload();
            }
            getLogger().info(LogCategories.REPOSITORY, "Repository refresh done");
        }
    };
    worker.execute();
}

From source file:de.tntinteractive.portalsammler.gui.MainDialog.java

private void poll(final Gui gui) {

    this.pollButton.setEnabled(false);

    final Settings settings = this.getStore().getSettings().deepClone();
    final ProgressMonitor progress = new ProgressMonitor(this, "Sammle Daten aus den Quell-Portalen...", "...",
            0, settings.getSize());/*from  w w  w . jav  a 2 s .c  o m*/
    progress.setMillisToDecideToPopup(0);
    progress.setMillisToPopup(0);
    progress.setProgress(0);

    final SwingWorker<String, String> task = new SwingWorker<String, String>() {

        @Override
        protected String doInBackground() throws Exception {
            final StringBuilder summary = new StringBuilder();
            int cnt = 0;
            for (final String id : settings.getAllSettingIds()) {
                if (this.isCancelled()) {
                    break;
                }
                cnt++;
                this.publish(cnt + ": " + id);
                final Pair<Integer, Integer> counts = MainDialog.this.pollSingleSource(settings, id);
                summary.append(id).append(": ");
                if (counts != null) {
                    summary.append(counts.getLeft()).append(" neu, ").append(counts.getRight())
                            .append(" schon bekannt\n");
                } else {
                    summary.append("Fehler!\n");
                }
                this.setProgress(cnt);
            }
            MainDialog.this.getStore().writeMetadata();
            return summary.toString();
        }

        @Override
        protected void process(final List<String> ids) {
            progress.setNote(ids.get(ids.size() - 1));
        }

        @Override
        public void done() {
            MainDialog.this.pollButton.setEnabled(true);
            MainDialog.this.table.refreshContents();
            try {
                final String summary = this.get();
                JOptionPane.showMessageDialog(MainDialog.this, summary, "Abruf-Zusammenfassung",
                        JOptionPane.INFORMATION_MESSAGE);
            } catch (final Exception e) {
                gui.showError(e);
            }
        }

    };

    task.addPropertyChangeListener(new PropertyChangeListener() {
        @Override
        public void propertyChange(final PropertyChangeEvent evt) {
            if ("progress".equals(evt.getPropertyName())) {
                progress.setProgress((Integer) evt.getNewValue());
            }
            if (progress.isCanceled()) {
                task.cancel(true);
            }
        }
    });

    task.execute();
}

From source file:edu.ku.brc.specify.tools.l10nios.StrLocalizerAppForiOS.java

private void scanSources() {
    scanMI.setEnabled(false);// www . j av a 2s. c  o  m

    final String STATUSBAR_NAME = "STATUS";
    final JStatusBar statusBar = UIRegistry.getStatusBar();
    statusBar.setProgressRange(STATUSBAR_NAME, 0, 100);

    SwingWorker<Integer, Integer> translator = new SwingWorker<Integer, Integer>() {
        @Override
        protected Integer doInBackground() throws Exception {
            doScanSources();
            return null;
        }

        @Override
        protected void done() {
            scanMI.setEnabled(false);
        }
    };

    translator.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(final PropertyChangeEvent evt) {
            if ("progress".equals(evt.getPropertyName())) {
                statusBar.setText(String.format("%d / 100 ", (Integer) evt.getNewValue()) + "%");
            }
        }
    });
    translator.execute();
}