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:pl.otros.vfs.browser.VfsBrowser.java

License:asdf

public void goToUrl(final FileObject fileObject) {

    if (taskContext != null) {
        taskContext.setStop(true);/*from   w w w . ja v  a 2s .  c o  m*/
    }

    try {
        final FileObject[] files = VFSUtils.getFiles(fileObject);
        LOGGER.info("Have {} files in {}", files.length, fileObject.getName().getFriendlyURI());
        this.currentLocation = fileObject;

        taskContext = new TaskContext(Messages.getMessage("browser.checkingSFtpLinksTask"), files.length);
        taskContext.setIndeterminate(false);
        SwingWorker<Void, Void> refreshWorker = new SwingWorker<Void, Void>() {
            int icon = 0;
            Icon[] icons = new Icon[] { Icons.getInstance().getNetworkStatusOnline(),
                    Icons.getInstance().getNetworkStatusAway(), Icons.getInstance().getNetworkStatusOffline() };

            @Override
            protected void process(List<Void> chunks) {
                loadingProgressBar.setIndeterminate(taskContext.isIndeterminate());
                loadingProgressBar.setMaximum(taskContext.getMax());
                loadingProgressBar.setValue(taskContext.getCurrentProgress());
                loadingProgressBar.setString(String.format("%s [%d of %d]", taskContext.getName(),
                        taskContext.getCurrentProgress(), taskContext.getMax()));
                loadingIconLabel.setIcon(icons[++icon % icons.length]);
            }

            @Override
            protected Void doInBackground() throws Exception {
                try {
                    while (!taskContext.isStop()) {
                        publish();
                        Thread.sleep(300);
                    }
                } catch (InterruptedException ignore) {
                    //ignore
                }
                return null;
            }
        };
        new Thread(refreshWorker).start();

        if (!skipCheckingLinksButton.isSelected()) {
            VFSUtils.checkForSftpLinks(files, taskContext);
        }
        taskContext.setStop(true);

        final FileObject[] fileObjectsWithParent = addParentToFiles(files);
        Runnable r = new

        Runnable() {

            @Override
            public void run() {
                vfsTableModel.setContent(fileObjectsWithParent);
                try {
                    pathField.setText(fileObject.getURL().toString());
                } catch (FileSystemException e) {
                    LOGGER.error("Can't get URL", e);
                }
                if (tableFiles.getRowCount() > 0) {
                    tableFiles.getSelectionModel().setSelectionInterval(0, 0);
                }
                updateStatusText();
            }
        };
        SwingUtils.runInEdt(r);
    } catch (Exception e) {
        LOGGER.error("Can't go to URL for " + fileObject, e);
        final String message = ExceptionsUtils.getRootCause(e).getClass().getName() + ": "
                + ExceptionsUtils.getRootCause(e).getLocalizedMessage();

        Runnable runnable = new Runnable() {
            public void run() {
                JOptionPane.showMessageDialog(VfsBrowser.this, message,
                        Messages.getMessage("browser.badlocation"), JOptionPane.ERROR_MESSAGE);
            }
        };
        SwingUtils.runInEdt(runnable);
    }
}

From source file:pt.lsts.neptus.console.plugins.ImageLayers.java

private Future<ImageLayer> addLayer(final File f) {
    final SwingWorker<ImageLayer, Object> worker = new SwingWorker<ImageLayer, Object>() {
        @Override//from ww  w .  jav a 2s .c o  m
        protected ImageLayer doInBackground() throws Exception {
            note = "loading layer in " + f.getAbsolutePath();
            ImageLayer il = ImageLayer.read(f);
            layers.add(il);
            files.add(f);
            note = "";
            layerFiles = StringUtils.join(files, ",");
            rebuildControls();
            return il;
        }
    };
    worker.execute();
    return worker;
}

From source file:pt.lsts.neptus.mra.MRAFilesHandler.java

/**
 * Generates PDF report from log file.//from w ww . j  a  v a2 s.co  m
 */
public void generatePDFReport(final File f) {

    SwingWorker<Boolean, Void> worker = new SwingWorker<Boolean, Void>() {
        @Override
        protected Boolean doInBackground() throws Exception {
            //                GuiUtils.infoMessage(mra, I18n.text("Generating PDF Report..."), I18n.text("Generating PDF Report..."));
            mra.getMRAMenuBar().getReportMenuItem().setEnabled(false);
            LsfReportProperties.generatingReport = true;
            mra.getMraPanel().addStatusBarMsg("Generating Report...");
            return LsfReport.generateReport(mra.getMraPanel().getSource(), f, mra.getMraPanel());
        }

        @Override
        protected void done() {
            super.done();
            try {
                get();
            } catch (Exception e) {
                NeptusLog.pub().error(e);
            }
            try {
                if (get()) {
                    GuiUtils.infoMessage(mra, I18n.text("Generate PDF Report"),
                            I18n.text("File saved to") + " " + f.getAbsolutePath());
                    final String pdfF = f.getAbsolutePath();
                    int resp = GuiUtils.confirmDialog(mra, I18n.text("Open PDF Report"),
                            I18n.text("Do you want to open PDF Report file?"));
                    if (resp == JOptionPane.YES_OPTION) {
                        new Thread() {
                            @Override
                            public void run() {
                                openPDFInExternalViewer(pdfF);
                            };
                        }.start();
                    }
                }
            } catch (Exception e) {
                GuiUtils.errorMessage(mra, I18n.text("PDF Creation Process"),
                        "<html>" + I18n.text("PDF <b>was not</b> saved to file.") + "<br>" + I18n.text("Error")
                                + ": " + e.getMessage() + "</html>");
                e.printStackTrace();
            } finally {
                mra.getBgp().block(false);
                mra.getMRAMenuBar().getReportMenuItem().setEnabled(true);
                LsfReportProperties.generatingReport = false;
                mra.getMraPanel().reDrawStatusBar();
            }
        }
    };
    worker.execute();
}

From source file:put.semantic.fcanew.ui.MainWindow.java

private void addNew(final String uri) {
    if (uri == null || uri.isEmpty()) {
        return;/*from  w  ww  .  ja  va  2s . co  m*/
    }
    new SwingWorker<Object, Object>() {

        @Override
        protected Object doInBackground() throws Exception {
            OWLOntologyManager m = kb.getManager();
            OWLDataFactory f = m.getOWLDataFactory();
            OWLNamedIndividual ind = f.getOWLNamedIndividual(IRI.create(uri));
            if (!mlExpert.getCurrentImplication().getPremises().isEmpty()) {
                for (Attribute a : mlExpert.getCurrentImplication().getPremises()) {
                    m.addAxiom(kb.getAbox(),
                            f.getOWLClassAssertionAxiom(((ClassAttribute) a).getOntClass(), ind));
                }
            } else {
                m.addAxiom(kb.getAbox(), f.getOWLClassAssertionAxiom(
                        kb.getReasoner().getTopClassNode().getRepresentativeElement(), ind));
            }
            extendPartialContext(uri, getUsedAttributes());
            kb.getReasoner().flush();
            context.updateContext();
            return null;
        }

        @Override
        protected void done() {
            ((ContextDataModel) contextTable.getModel()).fireTableDataChanged();
        }
    }.execute();
}

From source file:put.semantic.fcanew.ui.MainWindow.java

private void continueStart() {
    final List<Attribute> forced = getAttributes(2);
    if (forced.isEmpty()) {
        forced.addAll(getAttributes(1));
    }//from w w w  . ja v a2 s . c  om
    logger.trace("START");
    for (Attribute a : getUsedAttributes()) {
        logger.trace("ATTR: {}", a);
    }
    context = new PartialContext(new SimpleSetOfAttributes(getUsedAttributes()), kb);
    context.addProgressListener(progressListener);
    context.updateContext();
    contextTable.setRowSorter(new TableRowSorter<>());
    contextTable.setModel(new ContextDataModel(context));
    contextTable.setDefaultRenderer(Object.class, new PODCellRenderer(kb.getReasoner()));
    Enumeration<TableColumn> e = contextTable.getColumnModel().getColumns();
    JComboBox comboBox = new JComboBox(new Object[] { "+", "-", " " });
    while (e.hasMoreElements()) {
        TableColumn col = e.nextElement();
        col.setHeaderRenderer(new VerticalTableHeaderCellRenderer());
        col.setCellEditor(new DefaultCellEditor(comboBox));
        if (col.getModelIndex() >= 1) {
            col.setPreferredWidth(20);
        }
    }
    List<? extends FeatureCalculator> calculators = availableCalculatorsModel.getChecked();
    for (FeatureCalculator calc : calculators) {
        if (calc instanceof EndpointCalculator) {
            ((EndpointCalculator) calc).setMappings(mappingsPanel1.getMappings());
        }
    }
    Classifier classifier = (Classifier) classifierToUse.getSelectedItem();
    classifier.setRejectedWeight((Double) rejectedWeight.getValue());
    mlExpert = new MLExpert(classifier, (Integer) credibilityTreshold.getValue(), calculators,
            getIgnoreTreshold(), context, getAutoAcceptTreshold());
    mlExpert.addEventListener(new MLExpertEventListener() {

        @Override
        public void implicationAccepted(ImplicationDescription i, boolean autoDecision) {
            logger.trace("ACCEPT");
            setButtonsEnabled(false);
            ((ConfusionMatrix) confusionMatrix.getModel()).add(i.getSuggestion(), Expert.Decision.ACCEPT);
            registerImplication(i.getImplication(), i.getClassificationOutcome(), Expert.Decision.ACCEPT);
        }

        @Override
        public void implicationRejected(ImplicationDescription i, boolean autoDecision) {
            logger.trace("REJECT");
            setButtonsEnabled(false);
            ((ConfusionMatrix) confusionMatrix.getModel()).add(i.getSuggestion(), Expert.Decision.REJECT);
            registerImplication(i.getImplication(), i.getClassificationOutcome(), Expert.Decision.REJECT);
        }

        private TableModel getFeaturesTableModel(Map<String, Double> features) {
            DefaultTableModel model = new DefaultTableModel(new String[] { "feature", "value" }, 0);
            for (Map.Entry<String, Double> f : features.entrySet()) {
                model.addRow(new Object[] { f.getKey(), f.getValue() });
            }
            return model;
        }

        @Override
        public void ask(ImplicationDescription i, String justification) {
            logger.trace("ASK: {}", i.getImplication());
            highlightButton(i.getSuggestion());
            ((ContextDataModel) contextTable.getModel()).setCurrentImplication(i.getImplication());
            justificationText.setText(justification);
            implicationText.setText(String.format("<html>%s</html>", i.getImplication().toString()));
            {
                Map<String, String> desc = i.getImplication().describe(kb);
                String s = "<html><table border=\"1\">";
                s += "<tr><th>Attribute</th><th>Label</th></tr>";
                for (Map.Entry<String, String> e : desc.entrySet()) {
                    s += String.format("<tr><td>%s</td><td><pre>%s</pre></td></tr>", e.getKey(), e.getValue());
                }
                s += "</table></html>";
                implicationText.setToolTipText(s);
            }
            setButtonsEnabled(true);
            featuresTable.setModel(getFeaturesTableModel(i.getFeatures()));
        }
    });
    learningExamplesTable.setModel(classifier.getExamplesTableModel());
    fca = new FCA();
    fca.setContext(context);
    fca.setExpert(mlExpert);
    new SwingWorker() {
        @Override
        protected Object doInBackground() throws Exception {
            fca.reset(forced);
            fca.run();
            return null;
        }

        @Override
        protected void done() {
            try {
                get();
                logger.trace("FINISHED");
                if (script != null) {
                    String name = JOptionPane.showInputDialog(MainWindow.this,
                            "Jeeli chcesz otrzyma punkty z TSiSS, podaj swoje imi, nazwisko i nr indeksu",
                            "TSiSS", JOptionPane.QUESTION_MESSAGE);
                    if (name != null) {
                        logger.trace("NAME: {}", name);
                    }
                    script.submitLog(new File("fca.log"));
                }
                implicationText.setText("Bye-bye");
            } catch (InterruptedException | ExecutionException ex) {
                implicationText.setText(ex.getLocalizedMessage());
                ex.printStackTrace();
            }
        }
    }.execute();
}

From source file:put.semantic.fcanew.ui.MainWindow.java

private void startActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startActionPerformed
    jTabbedPane1.setEnabledAt(jTabbedPane1.indexOfComponent(setupTab), false);
    jTabbedPane1.setEnabledAt(jTabbedPane1.indexOfComponent(fcaTab), true);
    jTabbedPane1.setSelectedComponent(fcaTab);
    final List<Attribute> attrs = getUsedAttributes();
    downloader = new ARQDownloader(mappingsPanel1.getMappings());
    new SwingWorker() {

        @Override//from  ww  w. j  a  v a 2  s.c o  m
        protected Object doInBackground() throws Exception {
            seedKB(attrs);
            return null;
        }

        @Override
        protected void done() {
            continueStart();
        }

    }.execute();
}

From source file:put.semantic.fcanew.ui.MainWindow.java

private void downloadSomethingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_downloadSomethingActionPerformed
    final Implication impl = mlExpert.getCurrentImplication();
    new SwingWorker<List<String>, Object>() {

        @Override//w w w . j  av a2 s .c  o  m
        protected List<String> doInBackground() throws Exception {
            List<String> result = downloader.select(0, toArray(impl.getPremises().iterator()));
            removeKnown(result);
            return result;
        }

        @Override
        protected void done() {
            try {
                List<String> uris = get();
                if (uris.isEmpty()) {
                    JOptionPane.showMessageDialog(MainWindow.this,
                            "There are no objects fulifying premises and not available in considered context");
                    return;
                }
                Object result = JOptionPane.showInputDialog(MainWindow.this, "Select URI",
                        "Downloaded something", JOptionPane.PLAIN_MESSAGE, null, uris.toArray(new String[0]),
                        uris.get(0));
                addNew((String) result);
            } catch (InterruptedException | ExecutionException ex) {
                //should never happen
                ex.printStackTrace();
            }
        }

    }.execute();
}

From source file:richtercloud.document.scanner.components.OCRResultPanel.java

private void startOCR() {
    String oCRResult = null;//from  ww w .j ava 2  s. c o m
    if (!cancelable) {
        oCRResult = this.oCRResultPanelFetcher.fetch();
    } else {
        showProgressMonitor();
        final SwingWorker<String, String> oCRThread = new SwingWorker<String, String>() {
            private final OCRResultPanelFetcherProgressListener progressListener = new OCRResultPanelFetcherProgressListener() {
                @Override
                public void onProgressUpdate(OCRResultPanelFetcherProgressEvent progressEvent) {
                    int progress = (int) (progressEvent.getProgress() * 100);
                    if (progressMonitor != null) {
                        //might be null if the panel isn't displayed yet
                        progressMonitor.setProgress(progress);
                    }
                }
            };

            @Override
            public String doInBackground() {
                oCRResultPanelFetcher.addProgressListener(progressListener);
                try {
                    Thread thread1 = new Thread() {
                        @Override
                        public void run() {
                            while (!isDone()) {
                                if (progressMonitor != null && progressMonitor.isCanceled()) {
                                    oCRResultPanelFetcher.cancelFetch();
                                    break;
                                }
                                try {
                                    Thread.sleep(100);
                                } catch (InterruptedException ex) {
                                    throw new RuntimeException(ex);
                                }
                            }
                        }
                    };
                    thread1.start();
                    String retValue = oCRResultPanelFetcher.fetch();
                    return retValue;
                } catch (Exception ex) {
                    progressMonitor.setProgress(101);
                    messageHandler.handle(new Message(
                            String.format("An exception during fetching OCR result occured: %s",
                                    ExceptionUtils.getRootCauseMessage(ex)),
                            JOptionPane.ERROR_MESSAGE, "Exception occured"));
                }
                return null;
            }

            @Override
            protected void done() {
                oCRResultPanelFetcher.removeProgressListener(progressListener);
                progressMonitor.setProgress(101);
            }
        };
        oCRThread.execute();
        try {
            oCRResult = oCRThread.get();
        } catch (InterruptedException | ExecutionException ex) {
            throw new RuntimeException(ex);
        }
    }
    if (oCRResult != null) {
        //might be null if fetch has been canceled (this check is
        //unnecessary for non-cancelable processing, but don't care
        this.oCRResultTextArea.setText(oCRResult);
    }
}

From source file:richtercloud.document.scanner.gui.MainPanel.java

/**
 * Uses a modal dialog in order to display the progress of the retrieval and
 * make the operation cancelable.//from w ww .j av a  2  s .c  o m
 * @param documentFile
 * @return the retrieved images or {@code null} if the retrieval has been
 * canceled (in dialog)
 * @throws DocumentAddException
 * @throws InterruptedException
 * @throws ExecutionException
 */
/*
internal implementation notes:
- can't use ProgressMonitor without blocking EVT instead of a model dialog
when using SwingWorker.get
*/
public List<BufferedImage> retrieveImages(final File documentFile)
        throws DocumentAddException, InterruptedException, ExecutionException {
    if (documentFile == null) {
        throw new IllegalArgumentException("documentFile mustn't be null");
    }
    final SwingWorkerGetWaitDialog dialog = new SwingWorkerGetWaitDialog(SwingUtilities.getWindowAncestor(this), //owner
            DocumentScanner.generateApplicationWindowTitle("Wait", APP_NAME, APP_VERSION), //dialogTitle
            "Retrieving image data", //labelText
            null //progressBarText
    );
    final SwingWorker<List<BufferedImage>, Void> worker = new SwingWorker<List<BufferedImage>, Void>() {
        @Override
        protected List<BufferedImage> doInBackground() throws Exception {
            List<BufferedImage> retValue = new LinkedList<>();
            try {
                InputStream pdfInputStream = new FileInputStream(documentFile);
                PDDocument document = PDDocument.load(pdfInputStream);
                @SuppressWarnings("unchecked")
                List<PDPage> pages = document.getDocumentCatalog().getAllPages();
                for (PDPage page : pages) {
                    if (dialog.isCanceled()) {
                        document.close();
                        MainPanel.LOGGER.debug("tab generation aborted");
                        return null;
                    }
                    BufferedImage image = page.convertToImage();
                    retValue.add(image);
                }
                document.close();
            } catch (IOException ex) {
                throw new DocumentAddException(ex);
            }
            return retValue;
        }

        @Override
        protected void done() {
        }
    };
    worker.addPropertyChangeListener(new SwingWorkerCompletionWaiter(dialog));
    worker.execute();
    //the dialog will be visible until the SwingWorker is done
    dialog.setVisible(true);
    List<BufferedImage> retValue = worker.get();
    return retValue;
}

From source file:richtercloud.document.scanner.gui.MainPanel.java

/**
 *
 * @param images images to be transformed into a {@link OCRSelectPanelPanel}
 * or {@code null} indicating that no scan data was persisted when opening a
 * persisted entry//from  ww  w  .  j  a  va  2 s .c  o m
 * @param documentFile The {@link File} the document is stored in.
 * {@code null} indicates that the document has not been saved yet (e.g. if
 * the {@link OCRSelectComponent} represents scan data).
 * @throws DocumentAddException
 */
public void addDocument(final List<BufferedImage> images, final File documentFile, final Object entityToEdit)
        throws DocumentAddException {
    if (ADD_DOCUMENT_ASYNC) {
        final ProgressMonitor progressMonitor = new ProgressMonitor(this, //parent
                "Generating new document tab", //message
                null, //note
                0, //min
                100 //max
        );
        progressMonitor.setMillisToPopup(0);
        progressMonitor.setMillisToDecideToPopup(0);
        final SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
            private OCRSelectComponent createdOCRSelectComponentScrollPane;

            @Override
            protected Void doInBackground() throws Exception {
                try {
                    this.createdOCRSelectComponentScrollPane = addDocumentRoutine(images, documentFile,
                            entityToEdit, progressMonitor);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                return null;
            }

            @Override
            protected void done() {
                progressMonitor.close();
                addDocumentDone(this.createdOCRSelectComponentScrollPane);
            }
        };
        worker.execute();
        progressMonitor.setProgress(1); //ProgressMonitor dialog blocks until SwingWorker.done
        //is invoked
    } else {
        OCRSelectComponent oCRSelectComponentScrollPane = addDocumentRoutine(images, documentFile, entityToEdit,
                null //progressMonitor
        );
        addDocumentDone(oCRSelectComponentScrollPane);
    }
}