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 doRefresh() {
    if (PlatformUI.MIRTH_FRAME.alertRefresh()) {
        return;//from  w ww  . jav a 2  s  . co  m
    }

    final String workingId = getFrame().startWorking("Loading " + getTabName() + " settings...");

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

        ServerSettings serverSettings = null;
        UpdateSettings updateSettings = null;

        public Void doInBackground() {
            try {
                serverSettings = getFrame().mirthClient.getServerSettings();
                updateSettings = getFrame().mirthClient.getUpdateSettings();
            } catch (ClientException e) {
                getFrame().alertThrowable(getFrame(), e);
            }

            return null;
        }

        @Override
        public void done() {
            // null if it failed to get the server/update settings or if confirmLeave returned false
            if (serverSettings != null && updateSettings != null) {
                setServerSettings(serverSettings);
                setUpdateSettings(updateSettings);
            }
            getFrame().stopWorking(workingId);
        }
    };

    worker.execute();
}

From source file:de.atomfrede.tools.evalutation.tools.plot.ui.wizard.simple.SimplePlotWizard.java

@Override
public void onFinished(List<WizardPage> arg0, WizardSettings arg1) {
    this.setVisible(false);

    busyDialog = new BusyDialog("Please wait while plots are generated...");
    busyDialog.setLocationRelativeTo(DialogUtil.getInstance().getFrame());
    DialogUtil.getInstance().showStandardDialog(busyDialog);

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

        @Override// w  ww  .j  a  v a  2 s.c om
        protected Object doInBackground() throws Exception {
            StringBuilder fileNameBuilder = new StringBuilder();
            // first collect all datasets
            List<XYDatasetWrapper> wrappers = ((DatasetSelectionWizardPage) pages.get(1)).getDatasetWrappers();
            XYDatasetWrapper[] wrappersArray = new XYDatasetWrapper[wrappers.size()];

            int width = ((FileSelectionWizardPage) pages.get(0)).getEnteredWidth();
            int height = ((FileSelectionWizardPage) pages.get(0)).getEnteredHeight();

            int i = 0;
            for (XYDatasetWrapper wrapper : wrappers) {
                wrappersArray[i] = wrapper;
                if (i == 0)
                    fileNameBuilder.append(wrapper.getSeriesName());
                else
                    fileNameBuilder.append("-" + wrapper.getSeriesName());
                i++;
            }

            String date = DateFormat.getDateInstance().format(new Date());

            String fileName = date + "-" + fileNameBuilder.toString();
            CustomSimplePlot timePlot = new CustomSimplePlot(dataFile, fileName, width, height, wrappersArray);
            try {
                timePlot.plot();
            } catch (Exception e) {
                log.error("The requested data could not be plotted", e);
            }
            try {
                Desktop.getDesktop().open(new File(Options.getOutputFolder(), fileName + ".pdf"));
            } catch (IOException e) {
                log.error("Generated file could not be opened.", e);
            }

            return null;
        }

        @Override
        protected void done() {
            busyDialog.dispose();
            dispose();
        }

    };

    worker.execute();

}

From source file:de.atomfrede.tools.evalutation.tools.plot.ui.wizard.time.TimePlotWizard.java

@Override
public void onFinished(List<WizardPage> arg0, WizardSettings arg1) {
    this.setVisible(false);

    busyDialog = new BusyDialog("Please wait while plots are generated...");
    busyDialog.setLocationRelativeTo(DialogUtil.getInstance().getFrame());
    DialogUtil.getInstance().showStandardDialog(busyDialog);

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

        @Override//  w  w  w.j  a  va 2s.co  m
        protected Object doInBackground() throws Exception {
            StringBuilder fileNameBuilder = new StringBuilder();
            // first collect all datasets
            List<TimeDatasetWrapper> wrappers = ((DatasetSelectionWizardPage) pages.get(1))
                    .getTimeDatasetWrappers();
            TimeDatasetWrapper[] wrappersArray = new TimeDatasetWrapper[wrappers.size()];

            int width = ((TimeFileSelectionPage) pages.get(0)).getEnteredWidth();
            int height = ((TimeFileSelectionPage) pages.get(0)).getEnteredHeight();

            int i = 0;
            for (TimeDatasetWrapper wrapper : wrappers) {
                wrappersArray[i] = wrapper;
                if (i == 0)
                    fileNameBuilder.append(wrapper.getSeriesName());
                else
                    fileNameBuilder.append("-" + wrapper.getSeriesName());
                i++;
            }

            String date = DateFormat.getDateInstance().format(new Date());

            String fileName = date + "-" + fileNameBuilder.toString();
            CustomTimePlot timePlot = new CustomTimePlot(dataFile, fileName, width, height, wrappersArray);
            try {
                timePlot.plot();
            } catch (Exception e) {
                log.error("The requested data could not be plotted", e);
            }
            try {
                Desktop.getDesktop().open(new File(Options.getOutputFolder(), fileName + ".pdf"));
            } catch (IOException e) {
                log.error("Generated file could not be opened.", e);
            }

            return null;
        }

        @Override
        protected void done() {
            busyDialog.dispose();
            dispose();
        }

    };

    worker.execute();
}

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

@Override
public void doRefresh() {
    final String workingId = getFrame().startWorking("Loading database tasks...");
    final int selectedRow = taskTable.getSelectedRow();

    SwingWorker<Map<String, DatabaseTask>, Void> worker = new SwingWorker<Map<String, DatabaseTask>, Void>() {

        @Override//from www .j ava2  s  .  co m
        public Map<String, DatabaseTask> doInBackground() throws ClientException {
            return getFrame().mirthClient.getDatabaseTasks();
        }

        @Override
        public void done() {
            try {
                Map<String, DatabaseTask> databaseTasks = get();
                if (databaseTasks == null) {
                    databaseTasks = new HashMap<String, DatabaseTask>();
                }

                Object[][] data = new Object[databaseTasks.size()][4];
                int i = 0;

                for (DatabaseTask databaseTask : databaseTasks.values()) {
                    Status status = databaseTask.getStatus();
                    data[i][0] = new CellData(status == Status.IDLE ? UIConstants.ICON_BULLET_YELLOW
                            : UIConstants.ICON_BULLET_GREEN, status.toString());
                    data[i][1] = databaseTask;
                    data[i][2] = databaseTask.getDescription();
                    data[i][3] = databaseTask.getStartDateTime();
                    i++;
                }

                ((RefreshTableModel) taskTable.getModel()).refreshDataVector(data);

                if (selectedRow > -1 && selectedRow < taskTable.getRowCount()) {
                    taskTable.setRowSelectionInterval(selectedRow, selectedRow);
                }
            } catch (Throwable t) {
                if (t instanceof ExecutionException) {
                    t = t.getCause();
                }
                getFrame().alertThrowable(getFrame(), t, "Error loading database tasks: " + t.toString());
            } finally {
                getFrame().stopWorking(workingId);
            }
        }
    };

    worker.execute();
}

From source file:gui.sqlmap.SqlmapUi.java

private void startSqlmap() {
    String python = textfieldPython.getText();
    String workingDir = textfieldWorkingdir.getText();
    String sqlmap = textfieldSqlmap.getText();

    // Do some basic tests
    File f;//from w w  w  .  j a v  a 2s.c  om
    f = new File(python);
    if (!f.exists()) {
        JOptionPane.showMessageDialog(this, "Python path does not exist: " + python);
        return;
    }
    f = new File(workingDir);
    if (!f.exists()) {
        JOptionPane.showMessageDialog(this, "workingDir path does not exist: " + workingDir);
        return;
    }
    f = new File(sqlmap);
    if (!f.exists()) {
        JOptionPane.showMessageDialog(this, "sqlmap path does not exist: " + sqlmap);
        return;
    }

    // Write request file
    String requestFile = workingDir + "request.txt";
    try {
        FileOutputStream fos = new FileOutputStream(requestFile);
        fos.write(httpMessage.getRequest());
        fos.close();
    } catch (IOException e) {
        JOptionPane.showMessageDialog(this, "could not write request: " + workingDir + "request.txt");
        BurpCallbacks.getInstance().print("Error: " + e.getMessage());
    }

    // Start sqlmap
    args = new ArrayList<String>();
    args.add(python);
    args.add(sqlmap);
    args.add("-r");
    args.add(requestFile);
    args.add("--batch");

    args.add("-p");
    args.add(attackParam.getName());

    String sessionFile = workingDir + "sessionlog.txt";
    args.add("-s");
    args.add(sessionFile);
    args.add("--flush-session");

    String traceFile = workingDir + "tracelog.txt";
    args.add("-t");
    args.add(traceFile);

    args.add("--disable-coloring");
    args.add("--cleanup");

    textareaCommand.setText(StringUtils.join(args, " "));

    SwingWorker worker = new SwingWorker<String, Void>() {
        @Override
        public String doInBackground() {
            ProcessBuilder pb = new ProcessBuilder(args);
            //BurpCallbacks.getInstance().print(pb.command().toString());
            pb.redirectErrorStream(true);
            Process proc;
            try {
                proc = pb.start();

                InputStream is = proc.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);

                String line;
                int exit = -1;

                while ((line = br.readLine()) != null) {
                    // Outputs your process execution
                    addLine(line);
                    try {
                        exit = proc.exitValue();
                        if (exit == 0) {
                            // Process finished
                        }
                    } catch (IllegalThreadStateException t) {
                        // The process has not yet finished. 
                        // Should we stop it?
                        //if (processMustStop()) // processMustStop can return true 
                        // after time out, for example.
                        //{
                        //    proc.destroy();
                        //}
                    }
                }
            } catch (IOException ex) {
                BurpCallbacks.getInstance().print(ex.getLocalizedMessage());
            }
            return "";
        }

        @Override
        public void done() {
        }
    };

    worker.execute();

}

From source file:it.illinois.adsc.ema.softgrid.monitoring.ui.SPMainFrame.java

private void startPRXs() {
    SwingWorker iedWorker = new SwingWorker() {
        @Override/*w w w.  java 2s.c o m*/
        protected Object doInBackground() throws Exception {
            resultTabbedPane.add(logAreaScrollPane, "Gateway Log");
            stateTextArea.setEnabled(false);
            stateTextArea.setDisabledTextColor(Color.blue);
            queryScrolPane.getViewport().add(stateTextArea, null);
            stateTextArea.setText("Initializing Proxy gateway...");
            if (!ConfigUtil.PW_TO_SCL_MAPPING.isEmpty()) {
                it.illinois.adsc.ema.control.conf.generator.ConfigGenerator.generateConfigXml(
                        ConfigUtil.SCL_PATH, ConfigUtil.CONFIG_PEROPERTY_FILE, ConfigUtil.IP);
            }
            if (ConfigUtil.SERVER_TYPE.equals("PRX")) {
                String[] args = { "-f", ConfigUtil.CONFIG_PEROPERTY_FILE, ConfigUtil.SERVER_TYPE, "local" };
                SoftGridController.setPRXLogEventListener(SPMainFrame.this);
                SoftGridController.initiate(args);
            } else if (ConfigUtil.SERVER_TYPE.equals("ACM")) {
                String[] args = { ConfigUtil.SERVER_TYPE };
                //                    IEC60870104Server.main(args);
            }
            stateTextArea.setText("Gateway Started..!" + "\nGateway Server Protocol : IEC 60870-5-104 "
                    + "\nIED Protocol : IEC 61850");
            return null;
        }
    };
    iedWorker.execute();
}

From source file:net.openbyte.gui.WorkFrame.java

private void menuItem1ActionPerformed(ActionEvent e) {
    if (this.api == ModificationAPI.BUKKIT) {
        showBukkitIncompatibleFeature();
        return;//ww  w  . j  a v a  2  s  . co  m
    }
    System.out.println("Starting client...");
    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
        @Override
        protected Void doInBackground() throws Exception {
            GradleConnector.newConnector().forProjectDirectory(workDirectory).connect().newBuild()
                    .forTasks("runClient").run();
            return null;
        }
    };
    if (this.api == ModificationAPI.MCP) {
        worker = new SwingWorker<Void, Void>() {
            @Override
            protected Void doInBackground() throws Exception {
                if (System.getProperty("os.name").startsWith("Windows")) {
                    Runtime.getRuntime().exec("cmd /c startclient.bat", null, workDirectory);
                    return null;
                }
                try {
                    CommandLine startClient = CommandLine.parse("python "
                            + new File(new File(workDirectory, "runtime"), "startclient.py").getAbsolutePath()
                            + " $@");
                    CommandLine authClient = CommandLine.parse("chmod 755 "
                            + new File(new File(workDirectory, "runtime"), "startclient.py").getAbsolutePath());
                    DefaultExecutor executor = new DefaultExecutor();
                    executor.setWorkingDirectory(workDirectory);
                    executor.execute(authClient);
                    executor.execute(startClient);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        };
    }
    worker.execute();
}

From source file:net.openbyte.gui.WorkFrame.java

private void menuItem2ActionPerformed(ActionEvent e) {
    if (this.api == ModificationAPI.BUKKIT) {
        showBukkitIncompatibleFeature();
        return;/*from  w ww .j a  v a2 s  . c om*/
    }
    System.out.println("Starting server...");
    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
        @Override
        protected Void doInBackground() throws Exception {
            GradleConnector.newConnector().forProjectDirectory(workDirectory).connect().newBuild()
                    .forTasks("runServer").run();
            return null;
        }
    };
    if (this.api == ModificationAPI.MCP) {
        worker = new SwingWorker<Void, Void>() {
            @Override
            protected Void doInBackground() throws Exception {
                if (System.getProperty("os.name").startsWith("Windows")) {
                    Runtime.getRuntime().exec("cmd /c startserver.bat", null, workDirectory);
                    return null;
                }
                try {
                    CommandLine startServer = CommandLine.parse("python "
                            + new File(new File(workDirectory, "runtime"), "startserver.py").getAbsolutePath()
                            + " $@");
                    CommandLine authServer = CommandLine.parse("chmod 755 "
                            + new File(new File(workDirectory, "runtime"), "startserver.py").getAbsolutePath());
                    DefaultExecutor executor = new DefaultExecutor();
                    executor.setWorkingDirectory(workDirectory);
                    executor.execute(authServer);
                    executor.execute(startServer);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        };
    }
    worker.execute();
}

From source file:edu.ku.brc.specify.tasks.subpane.lm.LifeMapperPane.java

/**
 * @param genusSpecies/*  w w  w  .ja  v  a  2s. c  o  m*/
 */
private void doSearchSpecifyData(final String genusSpecies) {
    UsageTracker.incrUsageCount("LM.MyDataSearch");

    myDataTaxa = genusSpecies;

    final SimpleGlassPane glassPane = writeSimpleGlassPaneMsg(getLocalizedMessage("LM_SEARCH_SPECIFY"),
            GLASS_FONT_SIZE);
    glassPane.setTextYPos((int) ((double) getSize().height * 0.25));

    SwingWorker<Integer, Integer> worker = new SwingWorker<Integer, Integer>() {
        @Override
        protected Integer doInBackground() throws Exception {

            return addLocalData(genusSpecies);
        }

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

            Integer cnt = null;
            try {
                cnt = get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            if (cnt == null || cnt == 0) {
                writeTimedSimpleGlassPaneMsg(getResourceString("LM_NO_LOCAL_DATA"), null, Color.RED,
                        GLASS_FONT_SIZE, true, (int) ((double) getSize().height * 0.25));
                UsageTracker.incrUsageCount("LM.NoMyData");
            } else {
                String msg = UIRegistry.getFormattedResStr("LM_MYDATA_FND", cnt, myDataTaxa);
                writeTimedSimpleGlassPaneMsg(msg, null, null, GLASS_FONT_SIZE, true,
                        (int) ((double) getSize().height * 0.25));
            }
        }
    };
    worker.execute();

}

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

public void doExportMap() {
    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.  ja  va  2  s  .  c  o m*/
        } else if (option == JOptionPane.CANCEL_OPTION || option == JOptionPane.CLOSED_OPTION) {
            return;
        }
    }

    final String workingId = getFrame().startWorking("Exporting " + getTabName() + " settings...");

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

        private Map<String, ConfigurationProperty> configurationMap;

        public Void doInBackground() {
            try {
                File file = getFrame().createFileForExport(null, "PROPERTIES");
                if (file != null) {
                    PropertiesConfiguration properties = new PropertiesConfiguration();
                    properties.setDelimiterParsingDisabled(true);
                    properties.setListDelimiter((char) 0);
                    properties.clear();
                    PropertiesConfigurationLayout layout = properties.getLayout();

                    configurationMap = getFrame().mirthClient.getConfigurationMap();
                    Map<String, ConfigurationProperty> sortedMap = new TreeMap<String, ConfigurationProperty>(
                            String.CASE_INSENSITIVE_ORDER);
                    sortedMap.putAll(configurationMap);

                    for (Entry<String, ConfigurationProperty> entry : sortedMap.entrySet()) {
                        String key = entry.getKey();
                        String value = entry.getValue().getValue();
                        String comment = entry.getValue().getComment();

                        if (StringUtils.isNotBlank(key)) {
                            properties.setProperty(key, value);
                            layout.setComment(key, StringUtils.isBlank(comment) ? null : comment);
                        }
                    }

                    properties.save(file);
                }
            } catch (Exception e) {
                getFrame().alertThrowable(getFrame(), e);
            }

            return null;
        }

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

    worker.execute();
}