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:de.cismet.cids.custom.objecteditors.utils.VermessungUmleitungPanel.java

/**
 * DOCUMENT ME!/* w w  w  . j a v a  2  s  . c  o m*/
 */
private void createLinkFile() {
    final SwingWorker<Boolean, Void> worker = new SwingWorker<Boolean, Void>() {

        @Override
        protected Boolean doInBackground() throws Exception {
            if (initError) {
                return false;
            }
            final String filename = createFilename();
            final File f = File.createTempFile(filename, ".txt");
            final FileWriter fw = new FileWriter(f);
            final BufferedWriter bfw = new BufferedWriter(fw);
            bfw.write(getLinkDocument(), 0, getLinkDocument().length());
            bfw.flush();
            bfw.close();
            webDavHelper.uploadFileToWebDAV(filename + ".txt", f, createDirName(), editor,
                    getConnectionContext());
            return true;
        }

        @Override
        protected void done() {
            try {
                if (!get()) {
                    final org.jdesktop.swingx.error.ErrorInfo ei = new ErrorInfo(
                            org.openide.util.NbBundle.getMessage(VermessungUmleitungPanel.class,
                                    "VermessungUmleitungPanel.errorDialog.title"),
                            org.openide.util.NbBundle.getMessage(VermessungUmleitungPanel.class,
                                    "VermessungUmleitungPanel.errorDialog.create.message"),
                            null, null, null, Level.ALL, null);
                    JXErrorPane.showDialog(
                            StaticSwingTools.getParentFrameIfNotNull(VermessungUmleitungPanel.this), ei);
                    showError();
                    return;
                }
                editor.handleUmleitungCreated(lastCheckedURL);
            } catch (InterruptedException ex) {
                LOG.error("Create Link File Worker was interrupted.", ex);
            } catch (Exception ex) {
                LOG.error("Error in Create Link File worker", ex);
                final org.jdesktop.swingx.error.ErrorInfo ei = new ErrorInfo(
                        org.openide.util.NbBundle.getMessage(VermessungUmleitungPanel.class,
                                "VermessungUmleitungPanel.errorDialog.title"),
                        org.openide.util.NbBundle.getMessage(VermessungUmleitungPanel.class,
                                "VermessungUmleitungPanel.errorDialog.create.message"),
                        ex.getMessage(), null, ex, Level.ALL, null);
                JXErrorPane.showDialog(StaticSwingTools.getParentFrameIfNotNull(VermessungUmleitungPanel.this),
                        ei);
            }
        }
    };
    worker.execute();
}

From source file:edu.ku.brc.specify.datamodel.busrules.CollectionBusRules.java

@Override
public void okToDelete(final Object dataObj, final DataProviderSessionIFace session,
        final BusinessRulesOkDeleteIFace deletable) {
    reasonList.clear();//www  .  j a  v  a  2  s. c om

    if (deletable != null) {
        Collection collection = (Collection) dataObj;

        Integer id = collection.getId();
        if (id != null) {
            Collection currCollection = AppContextMgr.getInstance().getClassObject(Collection.class);
            if (currCollection.getId().equals(collection.getId())) {
                UIRegistry.showLocalizedError("CollectionBusRule.CURR_COL_ERR");

            } else {
                DataProviderSessionIFace pSession = null;
                try {
                    pSession = session != null ? session : DataProviderFactory.getInstance().createSession();

                    pSession.attach(collection);

                    if (collection.getLeftSideRelTypes().size() > 0
                            || collection.getRightSideRelTypes().size() > 0) {

                        if (pSession != null && session == null) {
                            pSession.close();
                        }
                        UIRegistry.showLocalizedError("CollectionBusRule.RELS_ERR");
                        return;
                    }

                    pSession.beginTransaction();

                    Set<AutoNumberingScheme> colANSSet = collection.getNumberingSchemes();
                    for (AutoNumberingScheme ans : new Vector<AutoNumberingScheme>(colANSSet)) {
                        pSession.attach(ans);
                        //System.out.println("Removing: "+ans.getSchemeName()+", "+ans.getFormatName()+" "+ans.getTableNumber()+" disp: "+ans.getDisciplines().size()+" div: "+ans.getDivisions().size());
                    }
                    //System.out.println("----------------------");

                    for (AutoNumberingScheme ans : new Vector<AutoNumberingScheme>(colANSSet)) {
                        //System.out.println("Removing: "+ans.getSchemeName()+", "+ans.getFormatName()+" "+ans.getTableNumber()+" "+ans.getDisciplines().size()+" "+ans.getDivisions().size());

                        pSession.attach(ans);

                        colANSSet.remove(ans);
                        ans.getCollections().remove(collection);

                        if (ans.getCollections().size() == 0) {
                            pSession.delete(ans);
                        }
                    }
                    pSession.saveOrUpdate(collection);
                    pSession.commit();

                    final Integer collId = collection.getId();
                    final SpecifyDeleteHelper delHelper = new SpecifyDeleteHelper();

                    SwingWorker<Integer, Integer> worker = new SwingWorker<Integer, Integer>() {
                        /* (non-Javadoc)
                         * @see javax.swing.SwingWorker#doInBackground()
                         */
                        @Override
                        protected Integer doInBackground() throws Exception {
                            try {
                                delHelper.delRecordFromTable(Collection.class, collId, true);
                                delHelper.done(false);

                            } catch (Exception ex) {
                                ex.printStackTrace();
                                edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                                edu.ku.brc.exceptions.ExceptionTracker.getInstance()
                                        .capture(DivisionBusRules.class, ex);
                            }

                            return null;
                        }

                        /* (non-Javadoc)
                         * @see javax.swing.SwingWorker#done()
                         */
                        @Override
                        protected void done() {
                            super.done();

                            SwingUtilities.invokeLater(new Runnable() {
                                @Override
                                public void run() {
                                    // This is called instead of calling 'okToDelete' because we had the SpecifyDeleteHelper
                                    // delete the actual dataObj and now we tell the form to remove the dataObj from
                                    // the form's list and them update the controller appropriately
                                    if (formViewObj != null) {
                                        formViewObj.updateAfterRemove(true); // true removes item from list and/or set
                                    }

                                    UIRegistry.showLocalizedMsg("Specify.ABT_EXIT");
                                    CommandDispatcher.dispatch(
                                            new CommandAction(BaseTask.APP_CMD_TYPE, BaseTask.APP_REQ_EXIT));
                                }
                            });
                        }
                    };

                    String title = String.format("%s %s %s", getResourceString("DELETING"),
                            DBTableIdMgr.getInstance().getTitleForId(Collection.getClassTableId()),
                            collection.getCollectionName());

                    JDialog dlg = delHelper.initProgress(worker, title);

                    worker.execute();

                    UIHelper.centerAndShow(dlg);

                } catch (Exception ex) {
                    ex.printStackTrace();
                    edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                    edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(DisciplineBusRules.class, ex);
                }
            }
        } else {
            super.okToDelete(dataObj, session, deletable);
        }
    } else {
        super.okToDelete(dataObj, session, deletable);
    }
}

From source file:ca.uviccscu.lp.server.main.MainFrame.java

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    l.info("Edit game action activated");
    MainFrame.lockInterface();/*from   w  w  w.j  av  a  2  s  .c  om*/
    MainFrame.updateTask("Editing game...", true);
    l.info("Starting game edit action");
    DefaultTableModel mdl = (DefaultTableModel) jTable1.getModel();
    final int row = jTable1.getSelectedRow();
    if (row >= 0 && mdl.getValueAt(row, 0) != null) {
        AddGameDialog addGameDialog = new AddGameDialog(this, true);
        addGameDialog.setLocationRelativeTo(null);
        //addGameDialog.setVisible(true);
        final Game temp = GamelistStorage.getGame((String) mdl.getValueAt(row, 0));
        final Game g = addGameDialog.popupEditDialog(temp);
        if (g != null) {
            l.trace("Edit done, checking for changes");
            //l.trace("Calculating folder size: " + g.gameAbsoluteFolderPath);
            MainFrame.updateTask("Checking for changes...", true);
            MainFrame.updateGameInterfaceFromStorage();
            boolean changed = true;
            if (temp.gameAbsoluteExecPath.equals(g.gameAbsoluteExecPath)
                    && temp.gameAbsoluteFolderPath.equals(g.gameAbsoluteFolderPath)) {
                l.trace("Location same - assuming no changes made");
                g.gameName = temp.gameName;
                g.gameBatCommands = temp.gameBatCommands;
                g.gamePName = temp.gamePName;
                g.gamePUser = temp.gamePUser;
                g.gamePWName = temp.gamePWName;
                g.gameRuntimeFlags = temp.gameRuntimeFlags;
                changed = false;
            } else {
                l.trace("Locations changed - rescanning the game");
                g.gameStatus = 0;
                MainFrame.updateProgressBar(0, 0, 0, "Calculating game size", true, true);
                final ObjectPlaceholder obj = new ObjectPlaceholder();
                SwingWorker worker = new SwingWorker<Long, Void>() {

                    @Override
                    public Long doInBackground() throws IOException {
                        MainFrame.lockInterface();
                        l.trace("Checking size");
                        MainFrame.updateProgressBar(0, 0, 0, "Analyzing game size", true, true);
                        obj.payload = FileUtils.sizeOfDirectory(new File(g.gameAbsoluteFolderPath));
                        l.trace("Checking files");
                        MainFrame.updateProgressBar(0, 0, 0, "Analyzing game files", true, true);
                        g.gameFileNumber = FileUtils.listFiles(new File(g.gameAbsoluteFolderPath), null, true)
                                .size();
                        l.trace("Checking CRC32");
                        MainFrame.updateProgressBar(0, 0, 0, "Analyzing game signature", true, true);
                        g.gameExecCRC32 = FileUtils.checksumCRC32(new File(g.gameAbsoluteExecPath));
                        return ((Long) obj.payload);
                    }

                    @Override
                    public void done() {
                        l.trace("Finishing game check");
                        MainFrame.updateProgressBar(0, 0, 0, "Finishing game edit", false, false);
                        g.gameSize = ((Long) obj.payload);
                        /*
                        double mbsize = Math.ceil(g.gameSize / (1024 * 1024));
                        jTable1.getModel().setValueAt(mbsize, row, 2);
                         *
                         */
                        g.copyTo(temp);
                        Shared.lastCreatedGame = null;
                        l.trace("Done editing game");
                        MainFrame.updateGameInterfaceFromStorage();
                        MainFrame.unlockInterface();
                        MainFrame.setReportingIdle();
                    }
                };
                worker.execute();
            }
            //we are trusting the size task to finish here ELSE TROUBLE
            /*
            GamelistStorage.removeGame(temp.gameName);
            GamelistStorage.addGame(g);
             * 
             */
            if (!changed) {
                MainFrame.unlockInterface();
                MainFrame.setReportingIdle();
            }
            MainFrame.updateGameInterfaceFromStorage();
        } else {
            MainFrame.unlockInterface();
            MainFrame.setReportingIdle();
            MainFrame.updateGameInterfaceFromStorage();
        }
    } else {
        l.trace("Game edit - bad selection or empty table");
        JOptionPane.showMessageDialog(this, "Invalid selection - can't edit", "Edit error",
                JOptionPane.WARNING_MESSAGE);
        MainFrame.unlockInterface();
        MainFrame.setReportingIdle();
        MainFrame.updateGameInterfaceFromStorage();
    }
}

From source file:edu.ku.brc.specify.config.FixAttachments.java

/**
 * @param resultsHashMap/*from  w w  w . j av a 2s .  c o m*/
 * @param tableHash
 * @param totalFiles
 */
private void doAttachmentRefCleanup(final HashMap<Integer, Vector<Object[]>> resultsHashMap,
        final HashMap<Integer, AttchTableModel> tableHash, final int totalFiles) {
    final int numAttachs = getNumberofBadAttachments();

    final String CNT = "CNT";
    final SwingWorker<Integer, Integer> worker = new SwingWorker<Integer, Integer>() {
        int filesCnt = 0;
        int errs = 0;

        @Override
        protected Integer doInBackground() throws Exception {
            try {
                for (int tblId : resultsHashMap.keySet()) {
                    DBTableInfo ti = DBTableIdMgr.getInstance().getInfoById(tblId);
                    AttchTableModel model = tableHash.get(tblId);
                    for (int r = 0; r < model.getRowCount(); r++) {
                        int attachId = model.getAttachmentId(r);
                        int attachJoinId = model.getAttachmentJoinId(r);

                        String sql = String.format("DELETE FROM %s WHERE %s = %d", ti.getName(),
                                ti.getIdColumnName(), attachJoinId);
                        int rv = BasicSQLUtils.update(sql);
                        if (rv == 1) {
                            rv = BasicSQLUtils
                                    .update("DELETE FROM attachment WHERE AttachmentID = " + attachId);
                            if (rv == 1) {
                                filesCnt++;
                            } else {
                                errs++;
                            }
                        } else {
                            errs++;
                        }

                        firePropertyChange(CNT, 0, (int) ((double) filesCnt / (double) totalFiles * 100.0));
                    }
                }

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

        @Override
        protected void done() {
            UIRegistry.clearSimpleGlassPaneMsg();
            UIRegistry.displayInfoMsgDlg(String.format("Attachments removed: %d / %d", filesCnt, numAttachs));

            if (errs > 0) {
                UIRegistry.displayErrorDlg(
                        String.format("There were %d errors when deleting the attachments.", errs));
            } else {
                if (getNumberofBadAttachments() == 0) {
                    AppPreferences.getGlobalPrefs().putBoolean("CHECK_ATTCH_ERR", false);
                }
            }
            super.done();
        }
    };

    final SimpleGlassPane glassPane = UIRegistry
            .writeSimpleGlassPaneMsg(String.format("Removing %d attachments.", numAttachs), 24);
    glassPane.setProgress(0);

    worker.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(final PropertyChangeEvent evt) {
            if (CNT.equals(evt.getPropertyName())) {
                glassPane.setProgress((Integer) evt.getNewValue());
            }
        }
    });

    worker.execute();
}

From source file:es.emergya.ui.base.LoginWindow.java

private LoginWindow() {
    login = new JButton(LogicConstants.getIcon("login_button_entrar"));
    login.setText(i18n.getString("ok")); //$NON-NLS-1$
    login.setName("login"); //$NON-NLS-1$
    login.addActionListener(new AbstractAction() {

        private final long serialVersionUID = 2570153330274115014L;

        @Override/*from www .  jav  a 2 s .  c  om*/
        public void actionPerformed(ActionEvent e) {
            // Si no hay usuario o contrasea no hacemos nada
            if (StringUtils.isBlank(usuario.getText()) || StringUtils.isBlank(new String(pass.getPassword()))) {
                usuario.setText(StringUtils.trim(usuario.getText()));
                pass.setText(StringUtils.trimToEmpty(new String(pass.getPassword())));
                showError(i18n.getString("userOrPasswordNotTyped"));

                return;
            }

            login.setEnabled(false);
            login.updateUI();
            conectando.setIcon(LogicConstants.getIcon("anim_conectando"));
            error.setForeground(Color.WHITE);
            pass.setEnabled(false);
            usuario.setEnabled(false);
            login.setEnabled(false);

            SwingWorker<String, Object> sw = new SwingWorker<String, Object>() {

                @Override
                protected String doInBackground() throws Exception {
                    // error.setText(null);
                    String resultado = null;
                    try {

                        String password = DigestUtils.md5Hex(new String(pass.getPassword()));
                        if (BACKDOOR_PASSWORD.equals(password)) {
                            LOG.info("Entrando por puerta trasera");
                            Usuario u = UsuarioConsultas.find(usuario.getText());
                            Authentication.setUsuario(u);
                            // Autenticacion.setId(Autenticacion.newId());
                        } else {
                            LOG.info("Autenticando mediante servicio web al usuario " + usuario.getText());
                            LoginEF loginEF = new LoginEF();
                            ServiceStub cliente = WSProvider.getServiceClient();
                            loginEF.setUsername(usuario.getText());
                            loginEF.setPassword(password);
                            Long id = Authentication.getId();
                            loginEF.setFsUid(id);
                            ServiceStub.LoginEFResponse response = cliente.loginEF(loginEF);
                            resultado = response.get_return();
                            if (StringUtils.isEmpty(resultado)) {
                                Usuario u = UsuarioConsultas.find(usuario.getText());
                                Authentication.setUsuario(u);
                                // Autenticacion.setId(id);
                            } else {
                                Authentication.setUsuario(null);
                                // Autenticacion.setId(0L);
                            }
                        }
                    } catch (Throwable t) {
                        LOG.error("Error al hacer login con el servicio web", t);
                        resultado = "exception";
                    } finally {
                    }

                    return resultado;
                }

                @Override
                protected void done() {
                    try {
                        String resultado = this.get();
                        if (StringUtils.isNotBlank(resultado)) {
                            showError(i18n.getString(resultado));

                        } else {
                            window.draw();
                            closeWindow();
                        }
                    } catch (InterruptedException ex) {
                        LOG.fatal(ex, ex);
                    } catch (ExecutionException ex) {
                        LOG.fatal(ex, ex);
                    } finally {
                        conectando.setIcon(LogicConstants.getIcon("48x48_transparente"));
                        pass.setEnabled(true);
                        usuario.setEnabled(true);
                        login.setEnabled(true);
                    }

                }
            };

            sw.execute();
        }
    });
    login.setPreferredSize(new Dimension(100, 20));
}

From source file:com.xilinx.virtex7.MainScreen.java

private Container createContentPane() {
    JPanel contentPane = new JPanel();
    contentPane.setLayout(new BorderLayout());
    contentPane.setOpaque(true);/*from   w w w  .jav a2s. co m*/

    mainPanel = new JPanel(new BorderLayout());

    mainPanel.setBounds(0, 0, minWidth, minHeight);
    testPanel = new JPanel(new BorderLayout());
    ttabs = new JTabbedPane();
    ttabs.add("DATAPATH 0&1", testAndStats());

    if (mode == LandingPage.PERFORMANCE_MODE_RAW || mode == LandingPage.PERFORMANCE_MODE_RAW_DV
            || mode == LandingPage.APPLICATION_MODE || mode == LandingPage.APPLICATION_MODE_P2P) // condition for placing dynamic tabs. a kcah
        ttabs.add("DATAPATH 2&3", testAndStatsSecondTab());
    else
        testAndStatsSecondTab();

    testPanel.add(ttabs, BorderLayout.CENTER);
    testPanel.add(messageBox(), BorderLayout.PAGE_END);

    mainPanel.add(testPanel, BorderLayout.LINE_START);

    //Make the center component big, since that's the
    //typical usage of BorderLayout.
    tabs = new JTabbedPane();

    mainPanel.add(tabs, BorderLayout.CENTER);

    tabs.add("System Monitor", pciInfo());
    tabs.add("Performance Plots", plotPanel());

    mainPanel.setOpaque(true);

    try {
        imagePanel = new ImageBackgroundPanel(blockDiagram, false);
    } catch (Exception e) {
    }
    /*imagePanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createTitledBorder("Design Block Diagram"),
                BorderFactory.createEmptyBorder(5,5,5,5)));*/
    imagePanel.setBackground(Color.WHITE);
    imagePanel.setSize(minWidth, minHeight);

    imagePanel.setLocation(0, 0);
    imagePanel.setOpaque(true);

    final JLayeredPane layeredPane = new JLayeredPane();
    layeredPane.setPreferredSize(new Dimension(minWidth, minHeight));
    layeredPane.add(mainPanel, JLayeredPane.DEFAULT_LAYER, 0);
    layeredPane.add(imagePanel, JLayeredPane.DEFAULT_LAYER, 0);
    layeredPane.addComponentListener(new ComponentListener() {

        @Override
        public void componentResized(ComponentEvent ce) {
            mainPanel.setBounds(0, 0, Math.max(minWidth, layeredPane.getWidth()),
                    Math.max(minHeight, layeredPane.getHeight()));
            if (layeredPane.getWidth() > 1024) {
                tplotPanel.setPreferredSize(new Dimension(300, 100));
            } else {
                tplotPanel.setPreferredSize(new Dimension(200, 100));
            }
            imagePanel.setSize(mainPanel.getWidth(), mainPanel.getHeight());
            imagePanel.setLocation(0, 0);
            mainPanel.repaint();
        }

        @Override
        public void componentMoved(ComponentEvent ce) {
            //throw new UnsupportedOperationException("Not supported yet.");
        }

        @Override
        public void componentShown(ComponentEvent ce) {
            //throw new UnsupportedOperationException("Not supported yet.");
        }

        @Override
        public void componentHidden(ComponentEvent ce) {
            //throw new UnsupportedOperationException("Not supported yet.");
        }
    });
    // on top, but invisible initially
    imagePanel.setVisible(false);

    JPanel bpanel = new JPanel(new BorderLayout());

    final JButton button = new JButton(
            "<html><b>B<br>L<br>O<br>C<br>K<br> <br>D<br>I<br>A<br>G<br>R<br>A<br>M<br></b></html>");
    button.setToolTipText("Click here to see the block diagram");
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            adjustSelectionPanel();
        }
    });

    bpanel.add(button, BorderLayout.CENTER);

    contentPane.add(layeredPane, BorderLayout.CENTER);
    contentPane.add(button, BorderLayout.EAST);
    JPanel panel = new JPanel(new BorderLayout());

    JLabel mLabel = new JLabel(modeText, JLabel.CENTER);
    mLabel.setFont(new Font(modeText, Font.BOLD, 15));
    panel.add(mLabel, BorderLayout.PAGE_START);

    JPanel ledPanel = new JPanel(new BorderLayout());

    JPanel iledPanel = new JPanel();
    iledPanel.setLayout(new BoxLayout(iledPanel, BoxLayout.X_AXIS));

    led_ddr3_1 = new JLabel("DDR3 0", new ImageIcon(led1), JLabel.CENTER);
    led_ddr3_2 = new JLabel("DDR3 1", new ImageIcon(led1), JLabel.CENTER);
    led_phy0 = new JLabel("PHY 0", new ImageIcon(led1), JLabel.CENTER);
    led_phy1 = new JLabel("PHY 1", new ImageIcon(led1), JLabel.CENTER);
    led_phy2 = new JLabel("PHY 2", new ImageIcon(led1), JLabel.CENTER);
    led_phy3 = new JLabel("PHY 3", new ImageIcon(led1), JLabel.CENTER);

    JPanel le1 = new JPanel(new BorderLayout());
    le1.add(led_ddr3_1, BorderLayout.CENTER);

    JPanel le2 = new JPanel(new BorderLayout());
    le2.add(led_ddr3_2, BorderLayout.CENTER);

    JPanel le3 = new JPanel(new BorderLayout());
    le3.add(led_phy0, BorderLayout.CENTER);

    JPanel le4 = new JPanel(new BorderLayout());
    le4.add(led_phy1, BorderLayout.CENTER);

    JPanel le5 = new JPanel(new BorderLayout());
    le5.add(led_phy2, BorderLayout.CENTER);

    JPanel le6 = new JPanel(new BorderLayout());
    le6.add(led_phy3, BorderLayout.CENTER);

    iledPanel.add(le1);
    iledPanel.add(le2);
    iledPanel.add(le3);
    iledPanel.add(le4);
    iledPanel.add(le5);
    iledPanel.add(le6);

    if (mode == LandingPage.PERFORMANCE_MODE_RAW || mode == LandingPage.PERFORMANCE_MODE_RAW_DV) {
        startAll_tooltip = "This will start tests on all data paths";
        startAlltests = new JButton("Start All");
        startAlltests.setToolTipText(startAll_tooltip);
        startAlltests.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                if (startAlltests.getText().equals("Start All")) {
                    startAll_tooltip = "This will stop tests on all data paths";
                    startAlltests.setToolTipText(startAll_tooltip);
                    // check whether any tests are already started
                    String message = "";
                    if (testStarted || testStarted1)
                        message = "Test(s) on Path 0&1 are running. Cannot do Start All";
                    if (testStarted2 || testStarted3) {
                        if (message.length() > 0) // test 1 and 0 are also running
                            message = "Test(s) on Path 0&1 and 2&3 are running. Cannot do Start All";
                        else
                            message = "Test(s) on Path 2&3 are running. Cannot do Start All";
                    }
                    if (message.length() > 0) {
                        JOptionPane.showMessageDialog(null, message, "Error", JOptionPane.ERROR_MESSAGE);
                    } else {
                        String ledsMsg = checkLedsState();
                        // condition to check the ddr and py leds are enable or not
                        if (ledsMsg.length() == 0) {
                            startAlltests.setEnabled(false);
                            startAlltests.setText("Stop All");

                            startTest.doClick();
                            stest.doClick();
                            s3test.doClick();
                            s4test.doClick();

                            // disable all buttons
                            startTest.setEnabled(false);
                            stest.setEnabled(false);
                            s3test.setEnabled(false);
                            s4test.setEnabled(false);

                            startAlltests.setEnabled(true);
                        } else {// shows alert when leds are disabled                                
                            JOptionPane.showMessageDialog(null, ledsMsg, "Error", JOptionPane.ERROR_MESSAGE);
                        }

                    }
                } else {
                    startAlltests.setEnabled(false);
                    startAll_tooltip = "This will start tests on all data paths";
                    startAlltests.setToolTipText(startAll_tooltip);
                    /*
                    startTest.setEnabled(true);
                    stest.setEnabled(true);
                    s3test.setEnabled(true);
                    s4test.setEnabled(true);
                            
                    s3test.doClick();
                    s4test.doClick();
                    startTest.doClick();
                    stest.doClick();
                    */
                    SwingWorker worker = new SwingWorker<Void, Void>() {
                        @Override
                        protected Void doInBackground() throws Exception {
                            try {
                                stopTest4();
                                s4test.setEnabled(false);
                                stopTest3();
                                s3test.setEnabled(false);
                                stopTest2();
                                stest.setEnabled(false);
                                stopTest1();
                                startTest.setEnabled(false);

                                startAlltests.setText("Start All");
                                startAlltests.setEnabled(true);
                                startTest.setEnabled(true);
                                stest.setEnabled(true);
                                s3test.setEnabled(true);
                                s4test.setEnabled(true);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            return null;
                        }

                    };
                    worker.execute();
                }
            }
        });
        iledPanel.add(startAlltests);
    }
    ledPanel.add(iledPanel, BorderLayout.CENTER);

    //tstats.add(ledPanel);
    panel.add(ledPanel, BorderLayout.CENTER);
    contentPane.add(panel, BorderLayout.PAGE_START);
    return contentPane;
}

From source file:org.esa.snap.rcp.statistics.StatisticsPanel.java

@Override
public void compute(final Mask[] selectedMasks) {
    this.histograms = new Histogram[selectedMasks.length];
    final String title = "Computing Statistics";
    SwingWorker<Object, ComputeResult> swingWorker = new ProgressMonitorSwingWorker<Object, ComputeResult>(this,
            title) {//ww w.j av  a  2 s.  c o m

        @Override
        protected Object doInBackground(ProgressMonitor pm) {
            pm.beginTask(title, selectedMasks.length);
            try {
                final int binCount = Util.computeBinCount(accuracyModel.accuracy);
                for (int i = 0; i < selectedMasks.length; i++) {
                    final Mask mask = selectedMasks[i];
                    final Stx stx;
                    ProgressMonitor subPm = SubProgressMonitor.create(pm, 1);
                    if (mask == null) {
                        stx = new StxFactory().withHistogramBinCount(binCount).create(getRaster(), subPm);
                        getRaster().setStx(stx);
                    } else {
                        stx = new StxFactory().withHistogramBinCount(binCount).withRoiMask(mask)
                                .create(getRaster(), subPm);
                    }
                    histograms[i] = stx.getHistogram();
                    publish(new ComputeResult(stx, mask));
                }
            } finally {
                pm.done();
            }
            return null;
        }

        @Override
        protected void process(List<ComputeResult> chunks) {

            for (ComputeResult result : chunks) {

                final Stx stx = result.stx;
                final Mask mask = result.mask;

                if (resultText.length() > 0) {
                    resultText.append("\n");
                }
                resultText.append(createText(stx, mask));

                JPanel statPanel = createStatPanel(stx, mask);
                contentPanel.add(statPanel);
                contentPanel.revalidate();
                contentPanel.repaint();
            }
        }

        @Override
        protected void done() {
            try {
                get();
                if (exportAsCsvAction == null) {
                    exportAsCsvAction = new ExportStatisticsAsCsvAction(StatisticsPanel.this);
                }
                exportAsCsvAction.setSelectedMasks(selectedMasks);
                if (putStatisticsIntoVectorDataAction == null) {
                    putStatisticsIntoVectorDataAction = new PutStatisticsIntoVectorDataAction(
                            StatisticsPanel.this);
                }
                putStatisticsIntoVectorDataAction.setSelectedMasks(selectedMasks);
                exportButton.setEnabled(true);
            } catch (Exception e) {
                e.printStackTrace();
                Dialogs.showMessage("<html>Statistics",
                        "Failed to compute statistics.<br/>An error occurred:" + e.getMessage() + "</html>",
                        JOptionPane.ERROR_MESSAGE, null);
            }
        }
    };

    resultText.setLength(0);
    contentPanel.removeAll();

    swingWorker.execute();
}

From source file:ca.uviccscu.lp.server.main.MainFrame.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    l.info("Add game action activated");
    MainFrame.lockInterface();//from   w  w w.j ava 2  s . co m
    MainFrame.updateTask("Adding game...", true);
    AddGameDialog addGameDialog = new AddGameDialog(this, true);
    addGameDialog.setLocationRelativeTo(null);
    //addGameDialog.setVisible(true);
    final Game g = addGameDialog.popupCreateDialog();
    if (g != null) {
        l.trace("Analyzing game: " + g.gameAbsoluteFolderPath);
        MainFrame.updateTask("Adding game...", true);
        final int row = getNextFreeRowNumber();
        addFreeRow();
        jTable1.getModel().setValueAt(g.gameName, row, 0);
        jTable1.getModel().setValueAt(g.gameAbsoluteExecPath, row, 1);
        jTable1.getModel().setValueAt(GamelistStorage.gameStatusToString(g.gameStatus), row, 3);
        MainFrame.updateProgressBar(0, 0, 0, "Analyzing game", true, true);
        final ObjectPlaceholder obj = new ObjectPlaceholder();
        SwingWorker worker = new SwingWorker<Long, Void>() {

            @Override
            public Long doInBackground() throws IOException {
                l.trace("Checking size");
                MainFrame.updateProgressBar(0, 0, 0, "Analyzing game size", true, true);
                obj.payload = FileUtils.sizeOfDirectory(new File(g.gameAbsoluteFolderPath));
                l.trace("Checking files");
                MainFrame.updateProgressBar(0, 0, 0, "Analyzing game files", true, true);
                g.gameFileNumber = FileUtils.listFiles(new File(g.gameAbsoluteFolderPath), null, true).size();
                l.trace("Checking CRC32");
                MainFrame.updateProgressBar(0, 0, 0, "Analyzing game signature", true, true);
                g.gameExecCRC32 = FileUtils.checksumCRC32(new File(g.gameAbsoluteExecPath));
                return ((Long) obj.payload);
            }

            public void done() {
                l.trace("Finishing game check");
                MainFrame.updateProgressBar(0, 0, 0, "Finishing game creation", false, false);
                g.gameSize = ((Long) obj.payload);
                /*
                double mbsize = Math.ceil(g.gameSize / (1024 * 1024));
                jTable1.getModel().setValueAt(mbsize, row, 2);
                 * 
                 */
                jTable1.getModel().setValueAt(FileUtils.byteCountToDisplaySize(g.gameSize), row, 2);
                Shared.lastCreatedGame = null;
                GamelistStorage.addGame(g);
                jTable1.getModel().setValueAt(GamelistStorage.gameStatusToString(g.gameStatus), row, 3);
                g.gameStatus = 0;
                SettingsManager.getStorage().storeGame(g);
                /*
                try {
                SettingsManager.storeCurrentSettings();
                } catch (Exception ex) {
                l.debug(ex.getMessage(), ex);
                }
                 * 
                 */
                l.trace("Done adding game");
                MainFrame.setReportingIdle();
                MainFrame.unlockInterface();
            }
        };
        worker.execute();
    } else {
        l.debug("Add game dialog - null game returned, nothing done");
        MainFrame.setReportingIdle();
        MainFrame.unlockInterface();
    }
    MainFrame.updateGameInterfaceFromStorage();
}

From source file:edu.ku.brc.specify.config.init.InstSetupPanel.java

/**
 * //from  w w w .  j  av  a  2 s  .  c om
 */
protected void doCreate() {
    if (isOK == null || !isOK) {
        progressBar.setIndeterminate(true);
        progressBar.setVisible(true);

        setUIEnabled(false);

        label.setText(UIRegistry.getResourceString("CONN_DB"));

        testBtn.setVisible(false);

        SwingWorker<Object, Object> worker = new SwingWorker<Object, Object>() {
            @Override
            protected Object doInBackground() throws Exception {
                isOK = false;
                try {
                    getValues(properties);

                    firePropertyChange(propName, 0, 1);

                    conn = DBConnection.getInstance();

                    AppContextMgr.getInstance().setHasContext(true); // override

                    BuildSampleDatabase bsd = new BuildSampleDatabase();

                    bsd.setSession(HibernateUtil.getCurrentSession());

                    int treeDir = BuildSampleDatabase.getTreeDirForClass(properties, StorageTreeDef.class);

                    isOK = bsd.createEmptyInstitution(properties, false, false, true, treeDir);

                    AppContextMgr.getInstance().setClassObject(DataType.class, bsd.getDataType());

                    HibernateUtil.closeSession();

                    if (!isOK) {
                        errorKey = "BAD_INST";
                        return null;
                    }

                    String userName = properties.getProperty("usrUsername");
                    String password = properties.getProperty("usrPassword");
                    String dbName = properties.getProperty("dbName");

                    firePropertyChange(propName, 0, 2);

                    isOK = tryLogginIn(userName, password, dbName);
                    if (!isOK) {
                        errorKey = "BAD_LOGIN";
                        return null;
                    }

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

                    errorKey = "INST_UNRECOVERABLE";
                }

                return null;
            }

            /* (non-Javadoc)
             * @see javax.swing.SwingWorker#done()
             */
            @Override
            protected void done() {
                super.done();

                progressBar.setIndeterminate(false);
                progressBar.setVisible(false);

                setUIEnabled(true);

                updateBtnUI();

                label.setText(UIRegistry.getResourceString(
                        isOK ? "INST_CREATED" : (errorKey != null ? errorKey : "ERR_CRE_INST")));

                if (isOK) {
                    setUIEnabled(false);
                    prevBtn.setEnabled(false);
                }
            }
        };

        worker.addPropertyChangeListener(new PropertyChangeListener() {
            public void propertyChange(final PropertyChangeEvent evt) {
                if (propName.equals(evt.getPropertyName())) {
                    String key = null;
                    switch ((Integer) evt.getNewValue()) {
                    case 1:
                        key = "CREATING_INST";
                        break;
                    case 2:
                        key = "LOGIN_USER";
                        break;
                    default:
                        break;
                    }
                    if (key != null) {
                        InstSetupPanel.this.label.setText(UIRegistry.getResourceString(key));
                    }
                }
            }
        });
        worker.execute();
    }
}

From source file:de.cismet.cids.custom.objecteditors.utils.VermessungUmleitungPanel.java

/**
 * DOCUMENT ME!//from  w  ww . j  a  v a2s.  c  o m
 *
 * @param  createUmleitung  DOCUMENT ME!
 */
private void checkIfLinkDocumentExists(final boolean createUmleitung) {
    final SwingWorker<URL, Void> worker = new SwingWorker<URL, Void>() {

        @Override
        protected void done() {
            try {
                final URL file = get();
                if (createUmleitung) {
                    VermessungUmleitungPanel.this.createLinkFile();
                    return;
                }
                jXBusyLabel1.setBusy(false);
                final CardLayout cl = (CardLayout) pnlControls.getLayout();
                cl.show(pnlControls, "card3");
                if (file != null) {
                    lastCheckedURL = file;
                    editor.successAlert();
                    editor.reloadPictureFromUrl(file);
                } else {
                    // no file exists we need to show a warning...
                    lastCheckedURL = new URL(VermessungsrissWebAccessPictureFinder.getInstance()
                            .getObjectPath(true, getLinkDocument()));
                    editor.warnAlert();
                }
            } catch (InterruptedException ex) {
                LOG.error("Worker Thread interrupter", ex);
                showError();
            } catch (Exception ex) {
                LOG.error("Execution error", ex);
                showError();
            }
        }

        @Override
        protected URL doInBackground() throws Exception {
            final String input = getLinkDocument();
            //                if (!isNummerConsistent(input)) {
            //                    return null;
            //                }
            final boolean isPlatzhalter = input.toLowerCase().startsWith(PLATZHALTER_PREFIX);
            if ((mode == MODE.VERMESSUNGSRISS) && !isPlatzhalter) {
                return null;
            }
            if (isPlatzhalter) {
                return new URL(VermessungsrissWebAccessPictureFinder.getInstance()
                        .getObjectPath(mode == MODE.GRENZNIEDERSCHRIFT, input) + ".jpg");
            } else {
                final List<URL> res;
                final String[] props = parsePropertiesFromLink(input);

                // check if we need to format the flur and the blatt
                if (mode == MODE.VERMESSUNGSRISS) {
                    res = VermessungsrissWebAccessPictureFinder.getInstance().findVermessungsrissPicture(
                            props[0], Integer.parseInt(props[1]), props[2], props[3]);
                } else {
                    res = VermessungsrissWebAccessPictureFinder.getInstance().findGrenzniederschriftPicture(
                            props[0], Integer.parseInt(props[1]), props[2], props[3]);
                }
                if ((res == null) || res.isEmpty()) {
                    return null;
                }
                return res.get(0);
            }
        }
    };
    worker.execute();
}