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:org.pmedv.blackboard.dialogs.PartDialog.java

@Override
protected void initializeComponents() {

    partPanel = new PartPanel();
    partBusyPanel = new JBusyComponent<PartPanel>(partPanel);

    setSize(new Dimension(900, 750));

    textArea = new RSyntaxTextArea();
    textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_XML);
    RTextScrollPane textScrollPane = new RTextScrollPane(textArea);

    CompletionProvider provider = createCompletionProvider();
    AutoCompletion ac = new AutoCompletion(provider);
    ac.install(textArea);//  ww w .  ja  v  a 2  s  . c  om

    JPopupMenu popup = textArea.getPopupMenu();
    popup.addSeparator();
    popup.add(new JMenuItem(new SaveAction()));

    tabbedPane = new JTabbedPane(JTabbedPane.BOTTOM);
    tabbedPane.addTab("Parts", partBusyPanel);
    tabbedPane.addTab("Part Editor", textScrollPane);
    tabbedPane.setEnabledAt(1, false);
    getContentPanel().add(tabbedPane);

    tablePopupMenu = new JPopupMenu();

    // We do the part loading in background and display a busy panel while loading

    SwingWorker<ArrayList<Part>, Void> w = new SwingWorker<ArrayList<Part>, Void>() {

        @Override
        protected ArrayList<Part> doInBackground() {
            partBusyPanel.setBusy(true);
            try {
                return AppContext.getContext().getBean(PartFactory.class).getAvailableParts();
            } catch (Exception e) {
                ErrorUtils.showErrorDialog(e);
                return new ArrayList<Part>();
            }
        }

        @Override
        protected void done() {
            log.info("Done loading parts.");
            try {
                model = new PartTableModel(get());
                partPanel.getPartTable().setModel(model);
            } catch (Exception e) {
                ErrorUtils.showErrorDialog(e);
            }
            partBusyPanel.setBusy(false);
            partPanel.transferFocus();
        }
    };

    getOkButton().addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JXTable table = partPanel.getPartTable();
            result = OPTION_OK;
            selectedParts = new ArrayList<Part>();
            int rows[] = partPanel.getPartTable().getSelectedRows();
            try {
                for (int i = 0; i < rows.length; i++) {
                    selectedParts.add(AppContext.getContext().getBean(PartFactory.class).createPart(
                            model.getParts().get(table.convertRowIndexToModel(rows[i])).getFilename()));
                }
            } catch (Exception e1) {
                ErrorUtils.showErrorDialog(e1);
            }
            setVisible(false);
        }
    });

    getCancelButton().addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            result = OPTION_CANCEL;
            setVisible(false);
        }
    });

    getNewButton().addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            AppContext.getContext().getBean(CreatePartCommand.class).execute(e);
        }
    });

    partPanel.getPartTable().getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            JXTable table = partPanel.getPartTable();
            int[] rows = table.getSelectedRows();
            if (rows.length == 1) {
                if (model == null)
                    return;
                Part selectedPart = model.getParts().get(table.convertRowIndexToModel(rows[0]));
                currentPart = selectedPart;
                selectedRow = table.convertRowIndexToModel(rows[0]);
                partPanel.getImageLabel().setIcon(new ImageIcon(selectedPart.getImage()));
                partPanel.getImageLabel().setText(null);
                partPanel.getPartNameField().setText(selectedPart.getName());
                partPanel.getDescriptionPane().setText(selectedPart.getDescription());
                partPanel.getPackageTypeField().setText(selectedPart.getPackageType());
                partPanel.getAuthorField().setText(selectedPart.getAuthor());
                partPanel.getLicenseField().setText(selectedPart.getLicense());
                tabbedPane.setEnabledAt(1, true);
                textArea.setText(selectedPart.getXmlContent());
            } else {
                currentPart = null;
                partPanel.getImageLabel().setText(resources.getResourceByKey("PartDialog.selectmsg"));
                partPanel.getImageLabel().setIcon(null);
                tabbedPane.setEnabledAt(1, false);
                textArea.setText("");
            }
        }
    });

    tabbedPane.addChangeListener(new ChangeListener() {
        // This method is called whenever the selected tab changes
        public void stateChanged(ChangeEvent evt) {
            JTabbedPane pane = (JTabbedPane) evt.getSource();
            int index = pane.getSelectedIndex();
            if (index == 0) {
                getTitleLabel().setText(title);
                getSubTitleLabel().setText(subTitle);
            } else {
                getTitleLabel().setText(editTitle);
                getSubTitleLabel().setText(editSubTitle + " : " + currentPart.getName());
            }
        }
    });

    partPanel.getPartTable().addMouseListener(new MouseAdapter() {

        @Override
        public void mousePressed(MouseEvent e) {
            handlePopupTrigger(e);
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            handlePopupTrigger(e);
        }
    });

    tablePopupMenu.add(ctx.getBean(DeletePartCommand.class));

    // this is the filter configuration for the filter text box on the top
    PartFilter filter = new PartFilter(partPanel.getPartTable());
    BindingGroup filterGroup = new BindingGroup();
    // bind filter JTextBox's text attribute to part tables filterString
    // attribute
    filterGroup.addBinding(Bindings.createAutoBinding(READ, partPanel.getFilterPanel().getFilterTextField(),
            BeanProperty.create("text"), filter, BeanProperty.create("filterString")));
    filterGroup.bind();
    w.execute();

}

From source file:org.ut.biolab.medsavant.client.region.RegionWizard.java

private AbstractWizardPage getGenesPage() {
    return new DefaultWizardPage(PAGENAME_GENES) {
        private static final int GENE_SELECTION_PANE_WIDTH = 350;
        private JPanel leftSide;
        private GeneSelectionPanel geneManiaResultsPanel;
        private Set<String> geneManiaGeneNames = null;

        {/*www  .j  a  va  2s.  com*/
            selectedGenesPanel = new GeneSelectionPanel(true, true);
            sourceGenesPanel = new GeneSelectionPanel(true, true);
            geneManiaResultsPanel = new GeneSelectionPanel(true, true) {
                @Override
                protected void dragAndDropAddGenes(Set<Gene> geneSet) {
                    Set<Object> genesToMoveToGeneManiaPanel = new HashSet<Object>(geneManiaGeneNames);
                    genesToMoveToGeneManiaPanel.retainAll(selectedGenesPanel.getSelectedKeys());
                    selectedGenesPanel.copyItems(geneManiaResultsPanel, genesToMoveToGeneManiaPanel);
                    selectedGenesPanel.moveSelectedItems(sourceGenesPanel);
                }

                @Override
                protected void dragAndDropRemoveKeys(Set<Object> keySet) {
                    Set<Object> keys = geneManiaResultsPanel.getSelectedKeys();
                    geneManiaResultsPanel.removeRows(keys);
                    sourceGenesPanel.removeRows(keys);
                }
            };
            geneManiaResultsPanel.setOddRowColor(new Color(242, 249, 245));

            runGeneManiaButton = new JButton("Run GeneMANIA");
            runGeneManiaButton.setEnabled(!DirectorySettings.isGeneManiaInstalled());

            ListSelectionListener selectionListener = new ListSelectionListener() {
                @Override
                public void valueChanged(ListSelectionEvent lse) {
                    int numSel = sourceGenesPanel.getNumSelected() + selectedGenesPanel.getNumSelected();
                    if (geneManiaGeneNames != null) {
                        numSel += geneManiaResultsPanel.getNumSelected();
                    }
                    if (GenemaniaInfoRetriever.isGeneManiaDownloading()) {
                        runGeneManiaButton.setEnabled(false);
                    } else {
                        runGeneManiaButton.setEnabled(numSel > 0 || !DirectorySettings.isGeneManiaInstalled());
                    }
                }
            };

            sourceGenesPanel.getTable().getSelectionModel().addListSelectionListener(selectionListener);
            selectedGenesPanel.getTable().getSelectionModel().addListSelectionListener(selectionListener);
            selectedGenesPanel.getTable().getModel().addTableModelListener(new TableModelListener() {
                @Override
                public void tableChanged(TableModelEvent tme) {
                    if (selectedGenesPanel.getData().length > 0) {
                        fireButtonEvent(ButtonEvent.ENABLE_BUTTON, ButtonNames.NEXT);
                    } else {
                        fireButtonEvent(ButtonEvent.DISABLE_BUTTON, ButtonNames.NEXT);
                    }
                }
            });

            selectedGenesPanel.setPreferredSize(
                    new Dimension(GENE_SELECTION_PANE_WIDTH, selectedGenesPanel.getPreferredSize().height));

            final JPanel outerLeftSide = new JPanel();
            outerLeftSide.setLayout(new BoxLayout(outerLeftSide, BoxLayout.X_AXIS));

            leftSide = new JPanel();
            leftSide.setLayout(new BoxLayout(leftSide, BoxLayout.Y_AXIS));
            leftSide.add(sourceGenesPanel);
            outerLeftSide.add(leftSide);
            final JPanel bg = new JPanel();
            bg.setLayout(new BoxLayout(bg, BoxLayout.Y_AXIS));

            JButton addButton = new JButton("Add ");
            JButton removeButton = new JButton("? Remove");

            sourceGenesPanel.getTable().addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent me) {
                    if (me.getClickCount() == 2) {
                        sourceGenesPanel.moveSelectedItems(selectedGenesPanel);
                    }
                }
            });

            selectedGenesPanel.getTable().addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent me) {
                    if (me.getClickCount() == 2) {
                        if (geneManiaGeneNames != null) {
                            Set<Object> genesToMoveToGeneManiaPanel = new HashSet<Object>(geneManiaGeneNames);
                            genesToMoveToGeneManiaPanel.retainAll(selectedGenesPanel.getSelectedKeys());
                            selectedGenesPanel.copyItems(geneManiaResultsPanel, genesToMoveToGeneManiaPanel);
                        }
                        selectedGenesPanel.moveSelectedItems(sourceGenesPanel);
                    }
                }
            });

            geneManiaResultsPanel.getTable().addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent me) {
                    if (me.getClickCount() == 2) {
                        Set<Object> keys = geneManiaResultsPanel.getSelectedKeys();
                        geneManiaResultsPanel.moveSelectedItems(selectedGenesPanel);
                        sourceGenesPanel.moveItems(selectedGenesPanel, keys);
                    }
                }
            });

            addButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent ae) {
                    if (geneManiaGeneNames != null) {
                        Set<Object> keys = geneManiaResultsPanel.getSelectedKeys();
                        geneManiaResultsPanel.moveSelectedItems(selectedGenesPanel);
                        sourceGenesPanel.moveItems(selectedGenesPanel, keys);
                    } else {
                        sourceGenesPanel.moveSelectedItems(selectedGenesPanel);
                    }
                }
            });

            removeButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent ae) {
                    if (geneManiaGeneNames != null) {
                        Set<Object> genesToMoveToGeneManiaPanel = new HashSet<Object>(geneManiaGeneNames);
                        genesToMoveToGeneManiaPanel.retainAll(selectedGenesPanel.getSelectedKeys());
                        selectedGenesPanel.copyItems(geneManiaResultsPanel, genesToMoveToGeneManiaPanel);
                    }
                    selectedGenesPanel.moveSelectedItems(sourceGenesPanel);
                }
            });

            bg.add(Box.createVerticalGlue());
            bg.add(addButton);
            bg.add(removeButton);
            bg.add(Box.createVerticalGlue());
            outerLeftSide.add(bg);

            JPanel rightSide = new JPanel();
            rightSide.setLayout(new BoxLayout(rightSide, BoxLayout.Y_AXIS));
            rightSide.add(selectedGenesPanel);
            rightSide.add(runGeneManiaButton);

            final JSplitPane hsplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, outerLeftSide, rightSide);
            hsplitPane.setResizeWeight(1);
            addComponent(hsplitPane, true);

            if (!DirectorySettings.isGeneManiaInstalled()) {
                runGeneManiaButton.setText("Download GeneMANIA");
                if (GenemaniaInfoRetriever.isGeneManiaDownloading()) {
                    runGeneManiaButton.setEnabled(false);
                    registerDownloadListener();
                }
            }

            runGeneManiaButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent ae) {

                    if (!DirectorySettings.isGeneManiaInstalled()) {
                        int response = DialogUtils.askYesNo("Download GeneMANIA?",
                                "GeneMANIA is not yet installed.  Do you want to download and install it now?");
                        try {
                            if (response == DialogUtils.OK) {
                                runGeneManiaButton.setText("Run GeneMANIA");
                                runGeneManiaButton.setEnabled(false);
                                registerDownloadListener();

                                /*
                                 DownloadTask dt = GenemaniaInfoRetriever.getGeneManiaDownloadTask();
                                 dt.addPropertyChangeListener(new PropertyChangeListener() {
                                 @Override
                                 public void propertyChange(PropertyChangeEvent evt) {
                                 if (evt.getPropertyName().equals("downloadState")) {
                                 DownloadTask.DownloadState ds = (DownloadTask.DownloadState) evt.getNewValue();
                                 if (ds == DownloadTask.DownloadState.CANCELLED
                                 || ds == DownloadTask.DownloadState.FINISHED) {
                                        
                                 runGeneManiaButton.setEnabled(
                                 (selectedGenesPanel.getNumSelected() + sourceGenesPanel.getNumSelected()) > 0);
                                 }
                                 }
                                 }
                                 });
                                 */
                                GenemaniaInfoRetriever.getGeneManiaDownloadTask().execute();
                            }
                        } catch (IOException e) {
                            DialogUtils.displayMessage("Error downloading GeneMANIA files");
                            LOG.error(e);
                        }
                    } else {

                        final List<String> selectedGenes = new LinkedList<String>();
                        for (Gene g : selectedGenesPanel.getSelectedGenes()) {
                            selectedGenes.add(g.getName());
                        }
                        for (Gene g : sourceGenesPanel.getSelectedGenes()) {
                            selectedGenes.add(g.getName());
                        }
                        if (geneManiaGeneNames != null) {
                            for (Gene g : geneManiaResultsPanel.getSelectedGenes()) {
                                selectedGenes.add(g.getName());
                            }
                        }
                        final JButton closeGeneManiaButton = new JButton("? Close GeneMANIA results");
                        closeGeneManiaButton.setEnabled(false);
                        final JPanel geneManiaContainingPanel = new JPanel();
                        geneManiaContainingPanel
                                .setLayout(new BoxLayout(geneManiaContainingPanel, BoxLayout.Y_AXIS));

                        final SwingWorker geneManiaWorker = new SwingWorker() {
                            private List<Object[]> results;

                            @Override
                            public void done() {
                                Object[][] newdata = new Object[results.size()][4];
                                results.toArray(newdata);
                                geneManiaResultsPanel.updateData(newdata);
                                geneManiaResultsPanel.updateView();
                                geneManiaContainingPanel.removeAll();
                                geneManiaContainingPanel.add(geneManiaResultsPanel);
                                geneManiaContainingPanel.revalidate();
                                geneManiaContainingPanel.repaint();
                                closeGeneManiaButton.setEnabled(true);
                            }

                            @Override
                            public Object doInBackground() {
                                try {
                                    GenemaniaInfoRetriever genemania = new GenemaniaInfoRetriever();
                                    genemania.setGenes(selectedGenes);
                                    List<String> geneNameList = genemania.getRelatedGeneNamesByScore();
                                    geneManiaGeneNames = new HashSet<String>();
                                    geneManiaGeneNames.addAll(geneNameList);
                                    LOG.debug("Found " + geneNameList.size() + " related genes");

                                    results = new ArrayList<Object[]>(geneNameList.size());

                                    int i = 0;
                                    for (String gene : geneNameList) {
                                        if (isCancelled()) {
                                            return null;
                                        }
                                        Gene g = GeneSetFetcher.getInstance().getGeneDictionary().get(gene);
                                        if (g == null) {
                                            LOG.warn("No gene found for " + gene);
                                        } else if (!selectedGenesPanel.hasKey(g.getName())) {
                                            results.add(new Object[] { g.getName(), g.getChrom(), g.getStart(),
                                                    g.getEnd() });
                                        }
                                    }
                                } catch (IOException e) {
                                    LOG.error(e);
                                } catch (ApplicationException e) {
                                    LOG.error(e);
                                } catch (DataStoreException e) {
                                    LOG.error(e);
                                } catch (NoRelatedGenesInfoException e) {
                                    LOG.error(e);
                                }
                                return null;
                            }
                        };

                        leftSide.removeAll();

                        closeGeneManiaButton.addActionListener(new ActionListener() {
                            @Override
                            public void actionPerformed(ActionEvent ae) {
                                try {
                                    geneManiaWorker.cancel(true);
                                } catch (Exception e) {
                                    //genemania throws exceptions when cancelled
                                }
                                leftSide.removeAll();
                                leftSide.add(sourceGenesPanel);
                                leftSide.validate();
                                leftSide.repaint();
                                geneManiaGeneNames = null;
                            }
                        });

                        JPanel closeButtonPanel = new JPanel();
                        closeButtonPanel.setLayout(new BoxLayout(closeButtonPanel, BoxLayout.X_AXIS));
                        closeButtonPanel.add(closeGeneManiaButton);
                        closeButtonPanel.add(Box.createHorizontalGlue());

                        leftSide.add(closeButtonPanel);

                        geneManiaContainingPanel.add(new WaitPanel("Querying GeneMANIA for related genes"));

                        leftSide.add(geneManiaContainingPanel);
                        leftSide.validate();
                        leftSide.repaint();
                        geneManiaWorker.execute();

                    } //end else
                }//end actionPerformed
            });//end ActionListener
        }

        @Override
        public void setupWizardButtons() {
            fireButtonEvent(ButtonEvent.HIDE_BUTTON, ButtonNames.FINISH);
            fireButtonEvent(ButtonEvent.SHOW_BUTTON, ButtonNames.BACK);

            if (selectedGenesPanel.getNumSelected() > 0) {
                fireButtonEvent(ButtonEvent.ENABLE_BUTTON, ButtonNames.NEXT);
            } else {
                fireButtonEvent(ButtonEvent.DISABLE_BUTTON, ButtonNames.NEXT);
            }
        }
    };
}

From source file:org.yccheok.jstock.gui.JStock.java

public void saveToCloud() {
    jMenu3.setEnabled(false);/*from  w  w  w. j  a  v  a  2 s  .c o m*/

    SwingWorker swingWorker = new SwingWorker<Pair<Pair<Credential, String>, Boolean>, Void>() {

        @Override
        protected Pair<Pair<Credential, String>, Boolean> doInBackground() throws Exception {
            final Pair<Pair<Credential, String>, Boolean> pair = org.yccheok.jstock.google.Utils
                    .authorizeDrive();
            return pair;
        }

        @Override
        public void done() {
            jMenu3.setEnabled(true);

            Pair<Pair<Credential, String>, Boolean> pair = null;

            try {
                pair = this.get();
            } catch (InterruptedException ex) {
                JOptionPane.showMessageDialog(JStock.this, ex.getMessage(),
                        GUIBundle.getString("SaveToCloudJDialog_Title"), JOptionPane.ERROR_MESSAGE);
                log.error(null, ex);
            } catch (ExecutionException ex) {
                org.yccheok.jstock.google.Utils.logoutDrive();

                JOptionPane.showMessageDialog(JStock.this, ex.getMessage(),
                        GUIBundle.getString("SaveToCloudJDialog_Title"), JOptionPane.ERROR_MESSAGE);
                log.error(null, ex);
            }

            if (pair == null) {
                return;
            }

            SaveToCloudJDialog saveToCloudJDialog = new SaveToCloudJDialog(JStock.this, true, pair.first,
                    pair.second);
            saveToCloudJDialog.setVisible(true);
        }
    };

    swingWorker.execute();
}

From source file:org.yccheok.jstock.gui.JStock.java

public void loadFromCloud() {
    jMenu3.setEnabled(false);//from   w w w .ja  va 2s.co  m

    SwingWorker swingWorker = new SwingWorker<Pair<Pair<Credential, String>, Boolean>, Void>() {

        @Override
        protected Pair<Pair<Credential, String>, Boolean> doInBackground() throws Exception {
            final Pair<Pair<Credential, String>, Boolean> pair = org.yccheok.jstock.google.Utils
                    .authorizeDrive();
            if (pair == null) {
                return null;
            }
            return pair;
        }

        @Override
        public void done() {
            jMenu3.setEnabled(true);

            Pair<Pair<Credential, String>, Boolean> pair = null;

            try {
                pair = this.get();
            } catch (InterruptedException ex) {
                JOptionPane.showMessageDialog(JStock.this, ex.getMessage(),
                        GUIBundle.getString("LoadFromCloudJDialog_Title"), JOptionPane.ERROR_MESSAGE);
                log.error(null, ex);
            } catch (ExecutionException ex) {
                org.yccheok.jstock.google.Utils.logoutDrive();

                JOptionPane.showMessageDialog(JStock.this, ex.getMessage(),
                        GUIBundle.getString("LoadFromCloudJDialog_Title"), JOptionPane.ERROR_MESSAGE);
                log.error(null, ex);
            }

            if (pair == null) {
                return;
            }

            LoadFromCloudJDialog loadFromCloudJDialog = new LoadFromCloudJDialog(JStock.this, true, pair.first,
                    pair.second);
            loadFromCloudJDialog.setVisible(true);
        }
    };

    swingWorker.execute();
}

From source file:org.yccheok.jstock.gui.OptionsAlertJPanel.java

private void signIn() {
    jCheckBox2.setEnabled(false);/*from   ww  w  .  ja v a 2 s.  c o m*/

    SwingWorker swingWorker = new SwingWorker<Pair<Pair<Credential, String>, Boolean>, Void>() {

        @Override
        protected Pair<Pair<Credential, String>, Boolean> doInBackground() throws Exception {
            final Pair<Pair<Credential, String>, Boolean> pair = org.yccheok.jstock.google.Utils
                    .authorizeGmail();
            return pair;
        }

        @Override
        public void done() {
            Pair<Pair<Credential, String>, Boolean> pair = null;

            try {
                pair = this.get();
            } catch (InterruptedException ex) {
                JOptionPane.showMessageDialog(OptionsAlertJPanel.this, ex.getMessage(),
                        GUIBundle.getString("OptionsAlertJPanel_Alert"), JOptionPane.ERROR_MESSAGE);
                log.error(null, ex);
            } catch (ExecutionException ex) {
                Throwable throwable = ex.getCause();
                if (throwable instanceof com.google.api.client.googleapis.json.GoogleJsonResponseException) {
                    com.google.api.client.googleapis.json.GoogleJsonResponseException ge = (com.google.api.client.googleapis.json.GoogleJsonResponseException) throwable;
                    for (GoogleJsonError.ErrorInfo errorInfo : ge.getDetails().getErrors()) {
                        if ("insufficientPermissions".equals(errorInfo.getReason())) {
                            org.yccheok.jstock.google.Utils.logoutGmail();
                            break;
                        }
                    }
                }

                JOptionPane.showMessageDialog(OptionsAlertJPanel.this, ex.getMessage(),
                        GUIBundle.getString("OptionsAlertJPanel_Alert"), JOptionPane.ERROR_MESSAGE);
                log.error(null, ex);
            }

            if (pair != null) {
                credentialEx = pair.first;
            } else {
                jCheckBox2.setSelected(false);
                JStock.instance().getJStockOptions().setSendEmail(jCheckBox2.isSelected());
            }

            updateGUIState();
        }
    };

    swingWorker.execute();
}

From source file:org.yccheok.jstock.gui.OptionsAlertJPanel.java

private void initCredentialEx() {
    SwingWorker swingWorker = new SwingWorker<Pair<Credential, String>, Void>() {

        @Override/*w  ww  . j  a v a  2  s  .  c  om*/
        protected Pair<Credential, String> doInBackground() throws Exception {
            final Pair<Credential, String> pair = org.yccheok.jstock.google.Utils.authorizeGmailOffline();
            return pair;
        }

        @Override
        public void done() {
            Pair<Credential, String> pair = null;

            try {
                pair = this.get();
            } catch (InterruptedException ex) {
                log.error(null, ex);
            } catch (ExecutionException ex) {
                Throwable throwable = ex.getCause();
                if (throwable instanceof com.google.api.client.googleapis.json.GoogleJsonResponseException) {
                    com.google.api.client.googleapis.json.GoogleJsonResponseException ge = (com.google.api.client.googleapis.json.GoogleJsonResponseException) throwable;
                    for (GoogleJsonError.ErrorInfo errorInfo : ge.getDetails().getErrors()) {
                        if ("insufficientPermissions".equals(errorInfo.getReason())) {
                            org.yccheok.jstock.google.Utils.logoutGmail();
                            break;
                        }
                    }

                }

                log.error(null, ex);
            }

            if (pair != null) {
                credentialEx = pair;
                jCheckBox2.setSelected(JStock.instance().getJStockOptions().isSendEmail());
            }

            updateGUIState();
        }
    };

    swingWorker.execute();
}

From source file:org.yccheok.jstock.gui.StockServerFactoryJRadioButton.java

private void initSwingWorker() {
    SwingWorker worker = new SwingWorker<Health, Void>() {
        @Override/*from   w  w w .j  a  v a 2s.  c o m*/
        public Health doInBackground() {
            return getServerHealth();
        }

        @Override
        public void done() {
            // The done Method: When you are informed that the SwingWorker
            // is done via a property change or via the SwingWorker object's
            // done method, you need to be aware that the get methods can
            // throw a CancellationException. A CancellationException is a
            // RuntimeException, which means you do not need to declare it
            // thrown and you do not need to catch it. Instead, you should
            // test the SwingWorker using the isCancelled method before you
            // use the get method.
            if (this.isCancelled()) {
                return;
            }

            Health health = null;
            try {
                health = get();
            } catch (InterruptedException ex) {
                log.error(null, ex);
            } catch (ExecutionException ex) {
                log.error(null, ex);
            } catch (CancellationException ex) {
                // Some developers suggest to catch this exception, instead of 
                // checking on isCancelled. As I am not confident by merely 
                // isCancelled check can prevent CancellationException (What 
                // if cancellation is happen just after isCancelled check?),
                // I will apply both techniques.
                log.error(null, ex);
            }

            if (health == null || health.isGood() == false) {
                StockServerFactoryJRadioButton.this.setStatus(Status.Failed);
            } else {
                StockServerFactoryJRadioButton.this.setStatus(Status.Success);
            }
            StockServerFactoryJRadioButton.this.setToolTipText(toHTML(health));
        }
    };

    worker.execute();
}

From source file:org.zaproxy.zap.extension.autoupdate.ExtensionAutoUpdate.java

boolean uninstallAddOnsWithView(final Window caller, final Set<AddOn> addOns, final boolean updates,
        final Set<AddOn> failedUninstallations) {
    if (addOns == null || addOns.isEmpty()) {
        return true;
    }/*from  w w  w .  j  av a  2 s  . c  o m*/

    if (!EventQueue.isDispatchThread()) {
        try {
            EventQueue.invokeAndWait(new Runnable() {

                @Override
                public void run() {
                    uninstallAddOnsWithView(caller, addOns, updates, failedUninstallations);
                }
            });
        } catch (InvocationTargetException | InterruptedException e) {
            logger.error("Failed to uninstall add-ons:", e);
            return false;
        }
        return failedUninstallations.isEmpty();
    }

    final Window parent = getWindowParent(caller);

    final UninstallationProgressDialogue waitDialogue = new UninstallationProgressDialogue(parent, addOns);
    waitDialogue.addAddOnUninstallListener(new AddOnUninstallListener() {

        @Override
        public void uninstallingAddOn(AddOn addOn, boolean updating) {
            if (updating) {
                String message = MessageFormat.format(
                        Constant.messages.getString("cfu.output.replacing") + "\n", addOn.getName(),
                        Integer.valueOf(addOn.getFileVersion()));
                getView().getOutputPanel().append(message);
            }
        }

        @Override
        public void addOnUninstalled(AddOn addOn, boolean update, boolean uninstalled) {
            if (uninstalled) {
                if (!update && addonsDialog != null) {
                    addonsDialog.notifyAddOnUninstalled(addOn);
                }

                String message = MessageFormat.format(
                        Constant.messages.getString("cfu.output.uninstalled") + "\n", addOn.getName(),
                        Integer.valueOf(addOn.getFileVersion()));
                getView().getOutputPanel().append(message);
            } else {
                if (addonsDialog != null) {
                    addonsDialog.notifyAddOnFailedUninstallation(addOn);
                }

                String message;
                if (update) {
                    message = MessageFormat.format(
                            Constant.messages.getString("cfu.output.replace.failed") + "\n", addOn.getName(),
                            Integer.valueOf(addOn.getFileVersion()));
                } else {
                    message = MessageFormat.format(
                            Constant.messages.getString("cfu.output.uninstall.failed") + "\n", addOn.getName(),
                            Integer.valueOf(addOn.getFileVersion()));
                }
                getView().getOutputPanel().append(message);
            }
        }

    });

    SwingWorker<Void, UninstallationProgressEvent> a = new SwingWorker<Void, UninstallationProgressEvent>() {

        @Override
        protected void process(List<UninstallationProgressEvent> events) {
            waitDialogue.update(events);
        }

        @Override
        protected Void doInBackground() {
            UninstallationProgressHandler progressHandler = new UninstallationProgressHandler() {

                @Override
                protected void publishEvent(UninstallationProgressEvent event) {
                    publish(event);
                }
            };

            for (AddOn addOn : addOns) {
                if (!uninstall(addOn, updates, progressHandler)) {
                    failedUninstallations.add(addOn);
                }
            }

            if (!failedUninstallations.isEmpty()) {
                logger.warn("Not all add-ons were successfully uninstalled: " + failedUninstallations);
            }

            return null;
        }
    };

    waitDialogue.bind(a);
    a.execute();
    waitDialogue.setSynchronous(updates);
    waitDialogue.setVisible(true);

    return failedUninstallations.isEmpty();
}

From source file:org.zaproxy.zap.extension.plugnhack.MonitoredPagesManager.java

protected void setMonitorFlags() {
    // Do in a background thread in case the tree is huge ;)
    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
        @Override/*from w  ww  .jav  a  2  s.c o  m*/
        protected Void doInBackground() throws Exception {
            logger.debug("Refreshing tree with monitor client flags");
            setMonitorFlags((SiteNode) Model.getSingleton().getSession().getSiteTree().getRoot(), false);
            return null;
        }
    };
    worker.execute();
}

From source file:pcgui.SetupParametersPanel.java

private void runModel() {

    //retrieve master configuration
    ArrayList<ArrayList<Object>> mod = model.getData();
    //create a new list and check for dependencies
    ArrayList<Symbol> list = new ArrayList<Symbol>();
    //independent variable list
    ArrayList<Symbol> ivList = new ArrayList<Symbol>();
    //step variable list
    ArrayList<Symbol> stepList = new ArrayList<Symbol>();
    //dependent list
    ArrayList<Symbol> depList = new ArrayList<Symbol>();
    //output tracking
    ArrayList<Symbol> trackedSymbols = new ArrayList<Symbol>();
    Symbol tempSym = null;// w w w  .j  a v a  2  s  .c o  m
    //step variable counter to be used for making combinations
    int stepVarCount = 0;
    long stepCombinations = 1;
    TextParser textParser = new TextParser();
    compileSuccess = true;
    for (ArrayList<Object> rowData : mod) {
        tempSym = paramList.get(mod.indexOf(rowData));
        if ("Manual".equals((String) rowData.get(2))) {
            System.out.println("Found Customized Symbol : " + rowData.get(0));
            System.out.println("Value : " + rowData.get(3) + ": type=" + rowData.get(3).getClass());

            tempSym.mode = "Manual";
            String data = (String) rowData.get(3);

            //checking dependent variables
            if (data != null && !data.isEmpty()) {
                //dependent
                if (hashTable.containsKey(data)) {
                    tempSym.setDependent(true);
                    depList.add(tempSym);
                } else {
                    //independents
                    tempSym.setDependent(false);
                    tempSym.set(data);
                    ivList.add(tempSym);
                }
            }
        } else if ("External".equals((String) rowData.get(2))) {
            System.out.println("Found External Symbol : " + rowData.get(0));
            System.out.println("External : " + rowData.get(3) + ": type=" + rowData.get(3).getClass());

            if (!(((String) rowData.get(4)).isEmpty())) {

                tempSym.externalFile = (String) rowData.get(4);
                tempSym.set(tempSym.externalFile);
                tempSym.mode = "External";
                if (tempSym.externalFile.endsWith(".xls") || tempSym.externalFile.endsWith(".xlsx")) {

                    if (tempSym.excelFileRange.isEmpty()) {
                        // TODO show an error dialog
                        System.err.println("Error user missed excel range arguments");
                        JOptionPane.showMessageDialog(new JFrame(), "Error user missed excel range arguments");
                        return;
                    } else {
                        tempSym.excelFileRange = (String) rowData.get(5);
                        //'[Daten_10$B'+(i)+':B'+(5+n)+']'
                        //user has to add quote before the 1st + and after the last +
                        //the data file used should be inside Models/Data folder
                        tempSym.set("Models//Data//" + tempSym.externalFile + "::" + tempSym.excelFileRange);

                    }
                } else {
                    //for non excel files
                    tempSym.set("Models//Data//" + tempSym.externalFile);

                }
            } else {
                System.err.println("Error user missed excel file");
                JOptionPane.showMessageDialog(new JFrame(),
                        "Please enter external file for variable : " + tempSym.name);
                return;
            }
            ivList.add(tempSym);
            list.add(tempSym);
        } else if ("Randomized".equals((String) rowData.get(2))) {
            System.out.println("Found Randomized Symbol : " + rowData.get(0));
            System.out.println("Value : " + rowData.get(6));

            boolean isValid = textParser.validate((String) rowData.get(6));
            if (isValid) {

                //saving the array declaration parameters
                if (((String) rowData.get(1)).trim().startsWith("array")) {
                    System.out.println("Found randomized array : " + tempSym.name);
                    //found an array
                    tempSym.isArray = true;
                    List<String> arrayParams = parseArrayParam((String) rowData.get(1));
                    tempSym.arrayParams = arrayParams;
                    System.out.println("Param list : ");
                    for (Object obj : tempSym.arrayParams) {
                        //check if any of the param is symbol
                        if (hashTable.containsKey((String) obj)) {
                            tempSym.isDependentDimension = true;
                            depList.add(tempSym);
                            break;
                        }
                        System.out.println((String) obj);
                    }
                    //add to independent variable list if none of the dimension is based on variable
                    if (!tempSym.isDependentDimension) {
                        ivList.add(tempSym);
                    }

                }
                Distribution dist = textParser.getDistribution((String) rowData.get(6));
                if ("Step".equalsIgnoreCase(dist.getDistribution())) {
                    System.err.println("Error: User entered step distribution in Randomized variable");
                    JOptionPane.showMessageDialog(new JFrame(),
                            "Please enter random distribution only" + " for variable : " + tempSym.name);
                    return;
                }
                tempSym.setDistribution(dist);
                tempSym.mode = "Randomized";
                //check dependent variables
                List<String> distParamList = dist.getParamList();
                for (String param : distParamList) {
                    //TODO: if .contains work on Symbol
                    if (hashTable.containsKey(param) && !depList.contains(tempSym)) {
                        tempSym.setDependent(true);
                        depList.add(tempSym);
                        break;
                    }
                }
                //generate apache distribution object for independent vars
                if (!tempSym.isDependent()) {
                    Object apacheDist = generateDistribution(tempSym);
                    tempSym.setApacheDist(apacheDist);
                    if ("StepDistribution".equals(apacheDist.getClass().getSimpleName())) {
                        stepVarCount++;
                        StepDistribution stepDist = (StepDistribution) apacheDist;
                        stepCombinations *= stepDist.getStepCount();

                        tempSym.isStepDist = true;
                        tempSym.setStepDist(stepDist);
                        stepList.add(tempSym);
                    } else if (!ivList.contains(tempSym) && !tempSym.isDependentDimension) {
                        ivList.add(tempSym);
                    }
                }
                list.add(tempSym);
            } else {
                System.err.println("Error: User entered unknown distribution for randomized variable");
                JOptionPane.showMessageDialog(new JFrame(),
                        "Please enter random distribution only" + " for variable : " + tempSym.name);
                return;
            }
        } else if ("Step".equals((String) rowData.get(2))) {
            System.out.println("Found Step Symbol : " + rowData.get(0));
            System.out.println("Value : " + rowData.get(6));
            Distribution dist = textParser.getStepDistribution((String) rowData.get(6));
            if (dist == null || !"Step".equalsIgnoreCase(dist.getDistribution())) {
                System.err.println("Error: User entered unknown distribution for step variable");
                JOptionPane.showMessageDialog(new JFrame(),
                        "Please enter random distribution only" + " for variable : " + tempSym.name);
                return;
            }

            boolean isValid = textParser.validateStepDist((String) rowData.get(6));
            if (isValid) {

                //saving the array declaration parameters
                if (((String) rowData.get(1)).trim().startsWith("array")) {
                    //TODO: if this can work for step arrays
                    System.out.println("Found step array : " + tempSym.name);
                    //found an array
                    tempSym.isArray = true;
                    List<String> arrayParams = parseArrayParam((String) rowData.get(1));
                    tempSym.arrayParams = arrayParams;
                    System.out.println("Param list : ");
                    for (Object obj : tempSym.arrayParams) {
                        //check if any of the param is symbol
                        if (hashTable.containsKey((String) obj)) {
                            tempSym.isDependentDimension = true;
                            depList.add(tempSym);
                            break;
                        }
                        System.out.println((String) obj);
                    }
                    //add to independent variable list if none of the dimension is based on variable
                    if (!tempSym.isDependentDimension) {
                        ivList.add(tempSym);
                    }

                }
                tempSym.setDistribution(dist);
                tempSym.mode = "Randomized";
                //check dependent variables
                List<String> distParamList = dist.getParamList();
                for (String param : distParamList) {
                    if (hashTable.containsKey(param) && !depList.contains(tempSym)) {
                        tempSym.setDependent(true);
                        depList.add(tempSym);
                        break;
                    }
                }
                //generate apache distribution object for independent vars
                if (!tempSym.isDependent()) {
                    Object apacheDist = generateDistribution(tempSym);
                    tempSym.setApacheDist(apacheDist);
                    //dual safe check
                    if ("StepDistribution".equals(apacheDist.getClass().getSimpleName())) {
                        stepVarCount++;
                        StepDistribution stepDist = (StepDistribution) apacheDist;
                        stepCombinations *= stepDist.getStepCount();

                        tempSym.isStepDist = true;
                        tempSym.setStepDist(stepDist);
                        stepList.add(tempSym);
                    } else if (!ivList.contains(tempSym) && !tempSym.isDependentDimension) {
                        ivList.add(tempSym);
                    }
                }
                list.add(tempSym);
            } else {
                System.err.println("Error: User entered unknown distribution for randomized variable");
                JOptionPane.showMessageDialog(new JFrame(),
                        "Please enter random distribution only" + " for variable : " + tempSym.name);
                return;
            }
        }
        //add symbol to trackedSymbol list for output tracking
        if (tempSym != null && rowData.get(7) != null && (boolean) rowData.get(7)) {
            trackedSymbols.add(tempSym);
        }

    }

    System.out.println("Total step distribution variables =" + stepVarCount);
    System.out.println("Total step combinations =" + stepCombinations);
    System.out.println("====STEP VARIABLES====");
    for (Symbol sym : stepList) {
        System.out.println(sym.name);
    }

    //resolve dependencies and generate random distributions object
    //list for an instance of execution

    HashMap<String, Integer> map = new HashMap<String, Integer>();
    for (int i = 0; i < stepList.size(); i++) {
        map.put(stepList.get(i).name, getSteppingCount(stepList, i));
        System.out.println(stepList.get(i).name + " has stepping count =" + map.get(stepList.get(i).name));
    }
    int repeatitions = 0;
    try {
        repeatitions = Integer.parseInt(repeatCount.getText());
    } catch (NumberFormatException e) {
        System.err.println("Invalid repeat count");
        JOptionPane.showMessageDialog(new JFrame(), "Please enter integer value for repeat count");
        return;
    }
    //generate instances

    showProgressBar();

    final long totalIterations = repeatitions * stepCombinations;
    final long repeatitionsFinal = repeatitions;
    final long combinations = stepCombinations;

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

        @Override
        protected Void doInBackground() throws Exception {

            long itNum = 1;
            int itCount = 1;

            System.out.println("Total iterations: " + totalIterations);
            // TODO Auto-generated method stub
            for (int c = 1; c <= repeatitionsFinal; c++) {
                for (int i = 1; i <= combinations; i++) {

                    setProgress((int) (itNum * 100 / totalIterations));
                    //step variables first
                    for (Symbol sym : stepList) {
                        if (map.get(sym.name) == 1 || i % map.get(sym.name) - 1 == 0 || i == 1) {
                            sym.set(sym.getStepDist().sample());
                            hashTable.put(sym.name, sym);
                        }
                        //System.out.println(sym.name+" = "+sym.get());

                    }
                    //independent randomized variables
                    for (Symbol sym : ivList) {
                        if (sym.mode.equals("Randomized")) {
                            Object distObj = sym.getApacheDist();
                            switch (sym.getApacheDist().getClass().getSimpleName()) {
                            case "UniformIntegerDistribution":

                                //case "GeometricDistribution" :

                                //   case "BinomialDistribution"://not implemented yet
                                IntegerDistribution intDist = (IntegerDistribution) distObj;
                                if (sym.isArray) {
                                    //generate Stringified array
                                    String val = generateIndependentArray(sym, intDist);
                                    sym.set(val);
                                    hashTable.put(sym.name, sym);

                                }

                                break;

                            case "LogisticDistribution":

                            case "UniformRealDistribution":

                            case "ExponentialDistribution":

                            case "GammaDistribution":

                            case "NormalDistribution":
                                RealDistribution realDist = (RealDistribution) distObj;
                                if (sym.isArray) {
                                    //generate Stringified array
                                    String val = generateIndependentArray(sym, realDist);
                                    sym.set(val);
                                    hashTable.put(sym.name, sym);

                                }

                                break;

                            default:

                                System.err.println("Unknown distribution");
                                JOptionPane.showMessageDialog(new JFrame(),
                                        "Error occurred : Unknown distribution");
                                return null;
                            }

                        }
                        //System.out.println(sym.name+" = "+sym.get());
                        //other types of independent variable already have values
                    }

                    for (Symbol sym : depList) {

                        if (sym.mode != null && "Manual".equals(sym.mode)) {
                            //value depends on some other value
                            String ref = (String) sym.get();
                            Object val = (Object) hashTable.get(ref);
                            sym.set(val);
                            hashTable.put(sym.name, sym);

                        } else if (sym.mode != null && "Randomized".equals(sym.mode)) {

                            Object distObj = null;
                            //when a random distribution depends on another variable
                            Distribution dist = sym.getDistribution();
                            StringBuilder sb = new StringBuilder();
                            sb.append(dist.getDistribution());
                            sb.append("(");
                            for (String s : dist.getParamList()) {
                                //replacing a dependency by actual value of that variable
                                if (hashTable.containsKey(s)) {
                                    Symbol val = (Symbol) hashTable.get(s);
                                    sb.append((String) val.get());
                                } else {
                                    //this param is a number itself
                                    sb.append(s);
                                }
                                sb.append(",");
                            }
                            //check if param list length = 0
                            if (dist.getParamList() != null && dist.getParamList().size() >= 1) {
                                sb.deleteCharAt(sb.length() - 1);
                            }
                            sb.append(")");
                            if (sym.typeString != null && sym.typeString.contains("integer")) {
                                try {
                                    distObj = textParser.parseText(sb.toString(), TextParser.INTEGER);

                                    sym.setApacheDist(distObj);
                                } catch (Exception e) {
                                    System.err.println(
                                            "Exception occured when trying to get Random distribution for variable"
                                                    + sym.name + "\n" + e.getMessage());
                                    e.printStackTrace();
                                    JOptionPane.showMessageDialog(new JFrame(),
                                            "Error occurred : " + e.getMessage());
                                    return null;
                                }
                            } else {
                                try {
                                    distObj = textParser.parseText(sb.toString(), TextParser.REAL);
                                    sym.setApacheDist(distObj);
                                } catch (Exception e) {
                                    System.err.println(
                                            "Exception occured when trying to get Random distribution for variable"
                                                    + sym.name + "\n" + e.getMessage());
                                    e.printStackTrace();
                                    JOptionPane.showMessageDialog(new JFrame(),
                                            "Error occurred : " + e.getMessage());
                                    return null;
                                }
                            }
                            //generation of actual apache distribution objects

                            switch (distObj.getClass().getSimpleName()) {
                            case "UniformIntegerDistribution":

                                //case "GeometricDistribution" :

                                //case "BinomialDistribution":
                                IntegerDistribution intDist = (IntegerDistribution) distObj;
                                if (sym.isArray) {
                                    //generate Stringified array
                                    String val = generateDependentArray(sym, intDist);
                                    sym.set(val);
                                    hashTable.put(sym.name, sym);

                                }
                                break;

                            case "LogisticDistribution":

                            case "UniformRealDistribution":

                            case "ExponentialDistribution":

                            case "GammaDistribution":

                            case "NormalDistribution":
                                RealDistribution realDist = (RealDistribution) distObj;
                                if (sym.isArray) {
                                    //generate Stringified array
                                    String val = generateDependentArray(sym, realDist);
                                    sym.set(val);
                                    hashTable.put(sym.name, sym);

                                }
                                break;

                            default:

                                System.err.println("Unknown distribution");
                                JOptionPane.showMessageDialog(new JFrame(),
                                        "Error occurred : Unknown distribution");
                            }
                        }

                        //System.out.println(sym.name+" = "+sym.get());

                    }
                    ArrayList<Symbol> instanceList = new ArrayList<Symbol>();
                    instanceList.addAll(stepList);
                    instanceList.addAll(ivList);
                    instanceList.addAll(depList);
                    System.out.println("=======ITERATION " + itCount++ + "=======");
                    System.out.println("=======instanceList.size =" + instanceList.size() + " =======");
                    for (Symbol sym : instanceList) {
                        System.out.println(sym.name + " = " + sym.get());
                    }
                    //runModel here
                    try {

                        //TODO anshul: pass output variables to be written to excel
                        System.out.println("Tracked output symbols");
                        for (Symbol sym : trackedSymbols) {
                            System.out.println(sym.name);
                        }
                        HashMap<String, OutputParams> l = parser.changeModel(instanceList, trackedSymbols,
                                itNum);

                        if (l == null) {
                            compileSuccess = false;
                            break;
                        }
                    } catch (/*XPRMCompileException | */XPRMLicenseError | IOException e) {
                        e.printStackTrace();
                        JOptionPane.showMessageDialog(new JFrame(), "Error occurred : " + e.getMessage());
                        compileSuccess = false;
                        break;
                    }
                    itNum++;
                }
            }
            this.notifyAll();
            done();
            return null;
        }

        @Override
        protected void done() {

            super.done();
            //check if compilation was successful
            if (compileSuccess) {
                ModelSaver.saveModelResult();
                visPanel.setTrackedVariables(trackedSymbols);
                mapVisPanel.setTrackedVariables(trackedSymbols);
                JOptionPane.showMessageDialog(new JFrame("Success"),
                        "Model execution completed.\nOutput written to excel file : " + outputFile);

            } else {
                //Error popup should have been shown by ModelParser
                System.err.println("There was an error while running the model.");
                return;
            }
            if (progressFrame != null) {
                progressFrame.dispose();
            }
        }

    };

    executionTask.addPropertyChangeListener(new PropertyChangeListener() {

        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            if ("progress" == evt.getPropertyName()) {
                int progress = (Integer) evt.getNewValue();
                if (pbar != null)
                    pbar.setValue(progress);
                if (taskOutput != null)
                    taskOutput.append(String.format("Completed %d%% of task.\n", executionTask.getProgress()));
            }
        }
    });
    executionTask.execute();

}