Example usage for javax.swing SwingWorker SwingWorker

List of usage examples for javax.swing SwingWorker SwingWorker

Introduction

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

Prototype

public SwingWorker() 

Source Link

Document

Constructs this SwingWorker .

Usage

From source file:ZipTest.java

/**
 * Scans the contents of the ZIP archive and populates the combo box.
 *///from  w w w .j a va2s .  co  m
public void scanZipFile() {
    new SwingWorker<Void, String>() {
        protected Void doInBackground() throws Exception {
            ZipInputStream zin = new ZipInputStream(new FileInputStream(zipname));
            ZipEntry entry;
            while ((entry = zin.getNextEntry()) != null) {
                publish(entry.getName());
                zin.closeEntry();
            }
            zin.close();
            return null;
        }

        protected void process(List<String> names) {
            for (String name : names)
                fileCombo.addItem(name);

        }
    }.execute();
}

From source file:DOMTreeTest.java

/**
     * Open a file and load the document.
     *///from   w ww  . ja  v  a2 s .c o m
    public void openFile() {
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new File("."));

        chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
            public boolean accept(File f) {
                return f.isDirectory() || f.getName().toLowerCase().endsWith(".xml");
            }

            public String getDescription() {
                return "XML files";
            }
        });
        int r = chooser.showOpenDialog(this);
        if (r != JFileChooser.APPROVE_OPTION)
            return;
        final File file = chooser.getSelectedFile();

        new SwingWorker<Document, Void>() {
            protected Document doInBackground() throws Exception {
                if (builder == null) {
                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                    builder = factory.newDocumentBuilder();
                }
                return builder.parse(file);
            }

            protected void done() {
                try {
                    Document doc = get();
                    JTree tree = new JTree(new DOMTreeModel(doc));
                    tree.setCellRenderer(new DOMTreeCellRenderer());

                    setContentPane(new JScrollPane(tree));
                    validate();
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(DOMTreeFrame.this, e);
                }
            }
        }.execute();
    }

From source file:it.unibas.spicygui.controllo.spicy.ActionFindMappings.java

@Override
public void performAction() {
    Properties config = new Properties();
    config.setProperty(IComputeQuality.class.getSimpleName(),
            "it.unibas.spicy.findmappings.strategies.computequality.ComputeQualityStructuralAnalysis");
    Application.reset(config);/* ww w . j  a  v a 2s .  com*/
    executeInjection();
    mappingFinder.cleanUp();
    Scenario scenario = (Scenario) modello.getBean(Costanti.CURRENT_SCENARIO);
    MappingTask mappingTask = scenario.getMappingTask();
    if (mappingTask.getTargetProxy().getInstances().isEmpty()) {
        NotifyDescriptor nd = new NotifyDescriptor.Message(
                NbBundle.getMessage(Costanti.class, Costanti.WARNING_NOT_TARGET_INSTANCES),
                DialogDescriptor.WARNING_MESSAGE);
        DialogDisplayer.getDefault().notify(nd);
        return;
    }
    checkValueCorrespondenceInMappingTask(mappingTask);
    SwingWorker swingWorker = new SwingWorker() {

        private Scenario scenario;

        @Override
        protected Object doInBackground() throws Exception {
            scenario = (Scenario) modello.getBean(Costanti.CURRENT_SCENARIO);
            MappingTask mappingTask = scenario.getMappingTask();

            List<AnnotatedMappingTask> bestMappingTasks = mappingFinder.findBestMappings(mappingTask);
            modello.putBean(Costanti.BEST_MAPPING_TASKS, bestMappingTasks);
            IOProvider.getDefault().getIO(Costanti.FLUSSO_SPICY, false).select();
            return true;
        }

        @Override
        protected void done() {
            try {
                if ((Boolean) get() && !isCancelled()) {
                    actionViewSpicy.performActionWithScenario(this.scenario);
                    actionViewBestMappings.performActionWithScenario(this.scenario);
                }
            } catch (InterruptedException ex) {
                logger.error(ex);
            } catch (ExecutionException ex) {
                logger.error(ex);
            }
        }
    };
    swingWorker.execute();

}

From source file:ProgressMonitorInputStreamTest.java

/**
 * Prompts the user to select a file, loads the file into a text area, and sets it as the content
 * pane of the frame.//from  www  .  ja va  2 s . co  m
 */
public void openFile() throws IOException {
    int r = chooser.showOpenDialog(this);
    if (r != JFileChooser.APPROVE_OPTION)
        return;
    final File f = chooser.getSelectedFile();

    // set up stream and reader filter sequence

    FileInputStream fileIn = new FileInputStream(f);
    ProgressMonitorInputStream progressIn = new ProgressMonitorInputStream(this, "Reading " + f.getName(),
            fileIn);
    final Scanner in = new Scanner(progressIn);

    textArea.setText("");

    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
        protected Void doInBackground() throws Exception {
            while (in.hasNextLine()) {
                String line = in.nextLine();
                textArea.append(line);
                textArea.append("\n");
            }
            in.close();
            return null;
        }
    };
    worker.execute();
}

From source file:it.unibas.spicygui.controllo.spicy.ActionRankTransformations.java

@Override
public void performAction() {
    executeInjection();/*from   w  w w .ja  v  a 2s  .  c om*/
    Scenario scenario = (Scenario) modello.getBean(Costanti.CURRENT_SCENARIO);
    MappingTask mappingTask = scenario.getMappingTask();
    if (mappingTask.getTargetProxy().getInstances().isEmpty()) {
        DialogDisplayer.getDefault()
                .notify(new NotifyDescriptor.Message(
                        NbBundle.getMessage(Costanti.class, Costanti.WARNING_NOT_TARGET_INSTANCES),
                        DialogDescriptor.INFORMATION_MESSAGE));
        return;
    }
    //        MappingTaskInfo mappingTaskInfo = (MappingTaskInfo) modello.getBean(Costanti.MAPPINGTASK_INFO);
    if (mappingTask.getMappingData() == null) {
        DialogDisplayer.getDefault()
                .notify(new NotifyDescriptor.Message(NbBundle.getMessage(Costanti.class, Costanti.NOT_MAPPED),
                        DialogDescriptor.INFORMATION_MESSAGE));
        return;
    }
    // TODO: check
    //        if (mappingTaskInfo.getTransformations().size() == 1) {
    //            DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(NbBundle.getMessage(Costanti.class, Costanti.SINGLE_TRANSFORMATION), DialogDescriptor.INFORMATION_MESSAGE));
    //            return;
    //        }
    SwingWorker swingWorker = new SwingWorker() {

        private Scenario scenario;

        @Override
        protected Object doInBackground() throws Exception {
            scenario = (Scenario) modello.getBean(Costanti.CURRENT_SCENARIO);
            MappingTask mappingTask = scenario.getMappingTask();
            List<Transformation> rankedTransformations = tranformationRanker.rankTransformations(mappingTask);
            modello.putBean(Costanti.RANKED_TRANSFORMATIONS, rankedTransformations);
            return true;
        }

        @Override
        protected void done() {
            try {
                if ((Boolean) get() && !isCancelled()) {
                    actionViewRankedTranformations.performActionWithScenario(scenario);
                }
            } catch (InterruptedException ex) {
                logger.error(ex);
            } catch (ExecutionException ex) {
                logger.error(ex);
            }
        }
    };
    swingWorker.execute();

}

From source file:it.unibas.spicygui.controllo.spicy.ActionFindConfidenceMappings.java

@Override
public void performAction() {
    Properties config = new Properties();
    config.setProperty(IComputeQuality.class.getSimpleName(),
            "it.unibas.spicy.findmappings.strategies.computequality.ComputeQualityMatchAverage");
    Application.reset(config);/*from w  w w .ja va 2  s .c  o m*/
    executeInjection();
    mappingFinder.cleanUp();
    Scenario scenario = (Scenario) modello.getBean(Costanti.CURRENT_SCENARIO);
    MappingTask mappingTask = scenario.getMappingTask();
    if (mappingTask.getTargetProxy().getInstances().isEmpty()) {
        NotifyDescriptor nd = new NotifyDescriptor.Message(
                NbBundle.getMessage(Costanti.class, Costanti.WARNING_NOT_TARGET_INSTANCES),
                DialogDescriptor.WARNING_MESSAGE);
        DialogDisplayer.getDefault().notify(nd);
        return;
    }
    checkValueCorrespondenceInMappingTask(mappingTask);
    SwingWorker swingWorker = new SwingWorker() {

        private Scenario scenario;

        @Override
        protected Object doInBackground() throws Exception {
            scenario = (Scenario) modello.getBean(Costanti.CURRENT_SCENARIO);
            MappingTask mappingTask = scenario.getMappingTask();
            List<AnnotatedMappingTask> bestMappingTasks = mappingFinder.findBestMappings(mappingTask);
            modello.putBean(Costanti.BEST_MAPPING_TASKS, bestMappingTasks);
            IOProvider.getDefault().getIO(Costanti.FLUSSO_SPICY, false).select();
            return true;
        }

        @Override
        protected void done() {
            try {
                if ((Boolean) get() && !isCancelled()) {
                    actionViewSpicy.performActionWithScenario(this.scenario);
                    actionViewBestMappings.performActionWithScenario(this.scenario);
                }
            } catch (InterruptedException ex) {
                logger.error(ex);
            } catch (ExecutionException ex) {
                logger.error(ex);
            }
        }
    };
    swingWorker.execute();

}

From source file:com.github.rholder.gradle.ui.DependencyViewerStandalone.java

private void refresh() {
    if (gradleBaseDir != null) {
        updateView(null, null);/*w ww .  j av a  2 s . c  o  m*/

        new SwingWorker<Void, Void>() {
            protected Void doInBackground() throws Exception {

                try {
                    Map<String, GradleNode> dependencyMap = loadProjectDependenciesFromModel(gradleBaseDir,
                            toolingLogger);
                    GradleNode tree = dependencyMap.get("root");

                    GradleNode target = dependencyCellRenderer.selectedGradleNode;
                    GradleNode dependency;
                    if (target != null && target.group != null) {
                        dependency = target;
                    } else {
                        dependency = new GradleNode("No dependency selected");
                    }

                    updateView(tree, dependency);
                    return null;
                } catch (Exception e) {
                    e.printStackTrace();
                    toolingLogger.log(ExceptionUtils.getFullStackTrace(e));
                    throw new RuntimeException(e);
                }
            }
        }.execute();
    }
}

From source file:fr.crnan.videso3d.ihm.PLNSPanel.java

/**
 * /*from w w w  . ja  v a 2  s  .co  m*/
 * @param path
 *            Chemin vers la base de donnes
 */
public PLNSPanel(final String path) {
    this.setLayout(new BorderLayout());

    this.add(createToolbar(), BorderLayout.NORTH);

    desktop = new TilingDesktopPane();
    desktop.setPreferredSize(new Dimension(800, 600));
    this.add(desktop);

    chartPanels = new ArrayList<ChartPanel>();

    final ProgressMonitor progressMonitorT = new ProgressMonitor(this, "Extraction des donnes", "", 0, 100,
            false, true, false);
    progressMonitorT.setMillisToDecideToPopup(0);
    progressMonitorT.setMillisToPopup(0);
    progressMonitorT.setNote("Extraction des fichiers compresss...");

    plnsAnalyzer = new PLNSAnalyzer();

    //au cas o il faille importer les donnes, on coute le ProgressSupport et on ne lance la cration de la fentre qu' la fin
    plnsAnalyzer.addPropertyChangeListener(new PropertyChangeListener() {

        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            if (evt.getPropertyName().equals(ProgressSupport.TASK_STARTS)) {

            } else if (evt.getPropertyName().equals(ProgressSupport.TASK_PROGRESS)) {
                progressMonitorT.setProgress((Integer) evt.getNewValue());
            } else if (evt.getPropertyName().equals(ProgressSupport.TASK_INFO)) {
                progressMonitorT.setNote((String) evt.getNewValue());
            } else if (evt.getPropertyName().equals(ProgressSupport.TASK_ENDS)) {
                createIHM();
            }
        }
    });

    new SwingWorker<Void, Void>() {

        @Override
        protected Void doInBackground() throws Exception {
            plnsAnalyzer.setPath(path);
            return null;
        }
    }.execute();
}

From source file:edu.ku.brc.specify.tasks.subpane.wb.SGRResultsForForm.java

public void refresh() {
    if (currentIndex < 0)
        return;//from  w w w  .j  av  a 2s. c o m

    removeAll();
    repaint();

    if (!sgrPlugin.isReady()) {
        showMessage("SGR_NO_MATCHER");
        return;
    }

    setCursor(new Cursor(Cursor.WAIT_CURSOR));
    new SwingWorker<MatchResults, Void>() {
        private int index = currentIndex;

        @Override
        protected MatchResults doInBackground() throws Exception {
            int modelIndex = workbenchPaneSS.getSpreadSheet().convertRowIndexToModel(index);
            WorkbenchRow row = workbench.getRow(modelIndex);
            return isEmpty(row) ? null : sgrPlugin.doQuery(row);
        }

        @Override
        protected void done() {
            // if we changed indexes in the meantime, don't show this result.
            if (index != currentIndex)
                return;
            //removeAll();

            try {
                results = get();
            } catch (CancellationException e) {
                return;
            } catch (InterruptedException e) {
                return;
            } catch (ExecutionException e) {
                sgrFailed(e);
                setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                return;
            }

            setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
            if (results == null || results.matches.size() < 1) {
                showMessage("SGR_NO_RESULTS");
                return;
            }

            float maxScore = sgrPlugin.getColorizer().getMaxScore();
            if (maxScore == 0.0f)
                maxScore = 22.0f;

            StringBuilder columns = new StringBuilder("right:max(50dlu;p)");
            for (Match result : results) {
                columns.append(", 4dlu, 150dlu:grow");
            }

            String[] fields = columnOrdering.getFields();
            StringBuilder rows = new StringBuilder();
            for (int i = 0; i < fields.length - 1; i++) {
                rows.append("p, 4dlu,");
            }
            rows.append("p");

            FormLayout layout = new FormLayout(columns.toString(), rows.toString());
            PanelBuilder builder = new PanelBuilder(layout, SGRResultsForForm.this);
            CellConstraints cc = new CellConstraints();

            int y = 1;
            for (String heading : columnOrdering.getHeadings()) {
                builder.addLabel(heading + ":", cc.xy(1, y));
                y += 2;
            }

            int x = 3;
            for (Match result : results) {
                y = 1;
                for (String field : fields) {
                    String value;
                    Color color;
                    if (field.equals("id")) {
                        value = result.match.id;
                        color = SGRColors.colorForScore(result.score, maxScore);
                    } else if (field.equals("score")) {
                        value = String.format("%1$.2f", result.score);
                        color = SGRColors.colorForScore(result.score, maxScore);
                    } else {
                        value = StringUtils.join(result.match.getFieldValues(field).toArray(), "; ");
                        Float fieldContribution = result.fieldScoreContributions().get(field);
                        color = SGRColors.colorForScore(result.score, maxScore, fieldContribution);
                    }

                    JTextField textField = new JTextField(value);
                    textField.setBackground(color);
                    textField.setEditable(false);
                    textField.setCaretPosition(0);
                    builder.add(textField, cc.xy(x, y));
                    y += 2;
                }
                x += 2;
            }
            getParent().validate();
        }
    }.execute();
    UsageTracker.incrUsageCount("SGR.MatchRow");
}

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   ww w  .j  av  a  2s .  c o  m*/
    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();

}