Example usage for javax.swing SwingUtilities invokeAndWait

List of usage examples for javax.swing SwingUtilities invokeAndWait

Introduction

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

Prototype

public static void invokeAndWait(final Runnable doRun) throws InterruptedException, InvocationTargetException 

Source Link

Document

Causes doRun.run() to be executed synchronously on the AWT event dispatching thread.

Usage

From source file:net.sourceforge.atunes.kernel.modules.repository.RepositoryHandler.java

/**
 * Imports folders passed as argument to repository
 * //from  w  w w  .  j av a 2s  . c  o m
 * @param folders
 * @param path
 */
private void importFolders(final List<File> folders, final String path) {
    SwingWorker<List<AudioFile>, Void> worker = new SwingWorker<List<AudioFile>, Void>() {
        @Override
        protected List<AudioFile> doInBackground() throws Exception {
            VisualHandler.getInstance().showIndeterminateProgressDialog(
                    StringUtils.getString(LanguageTool.getString("READING_FILES_TO_IMPORT"), "..."));
            return RepositoryLoader.getSongsForFolders(folders);
        }

        @Override
        protected void done() {
            super.done();
            VisualHandler.getInstance().hideIndeterminateProgressDialog();

            try {
                final List<AudioFile> filesToLoad = get();

                TagAttributesReviewed tagAttributesReviewed = null;
                // Review tags if selected in settings
                if (ApplicationState.getInstance().isReviewTagsBeforeImport()) {
                    ReviewImportDialog reviewImportDialog = VisualHandler.getInstance().getReviewImportDialog();
                    reviewImportDialog.show(folders, filesToLoad);
                    if (reviewImportDialog.isDialogCancelled()) {
                        return;
                    }
                    tagAttributesReviewed = reviewImportDialog.getResult();
                }

                final ImportFilesProcess process = new ImportFilesProcess(filesToLoad, folders, path,
                        tagAttributesReviewed);
                process.addProcessListener(new ProcessListener() {
                    @Override
                    public void processCanceled() {
                        // Nothing to do, files copied will be removed before calling this method 
                    }

                    @Override
                    public void processFinished(final boolean ok) {
                        if (!ok) {
                            try {
                                SwingUtilities.invokeAndWait(new Runnable() {
                                    @Override
                                    public void run() {
                                        VisualHandler.getInstance().showErrorDialog(
                                                LanguageTool.getString("ERRORS_IN_IMPORT_PROCESS"));
                                    }
                                });
                            } catch (InterruptedException e) {
                                // Do nothing
                            } catch (InvocationTargetException e) {
                                // Do nothing
                            }
                        } else {
                            // If import is ok then add files to repository
                            addFilesAndRefresh(process.getFilesTransferred());
                        }
                    }
                });
                process.execute();

            } catch (InterruptedException e) {
                getLogger().error(LogCategories.REPOSITORY, e);
            } catch (ExecutionException e) {
                getLogger().error(LogCategories.REPOSITORY, e);
            }
        }
    };
    worker.execute();
}

From source file:com.igormaznitsa.jhexed.swing.editor.ui.MainForm.java

@Override
public HexLayer makeHexLayer(final String name, final String comment) {
    if (name == null) {
        throw new NullPointerException("Name must not be null");
    }//from  w  w w  .jav  a2  s  .  co m
    if (comment == null) {
        throw new NullPointerException("Comments must not be null");
    }

    final AtomicReference<HexLayer> result = new AtomicReference<HexLayer>();

    final Runnable run = new Runnable() {
        @Override
        public void run() {
            result.set(layers.addLayer(layers.makeNewLayerField(name, comment)));
        }
    };

    if (SwingUtilities.isEventDispatchThread()) {
        run.run();
    } else {
        try {
            SwingUtilities.invokeAndWait(run);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
    return result.get();
}

From source file:gda.plots.SimplePlot.java

/**
 * Temporary main for speed testing purposes only
 * /*from  ww  w  .j ava 2s .co m*/
 * @param args
 */
public static void main(String args[]) {
    JFrame jf = new JFrame();
    final SimplePlot sp = new SimplePlot();
    jf.getContentPane().add(sp);
    jf.pack();
    jf.setVisible(true);

    sp.setXAxisAutoScaling(false);
    sp.setXAxisLimits(0.0, 300.0);
    sp.setYAxisLimits(0.0, 1.0);
    sp.initializeLine(0);
    final double x[] = new double[1000];
    final double y[] = new double[1000];
    final double[] numbers = new double[10];
    final double[] timesOne = new double[10];
    final double[] timesTwo = new double[10];
    for (int i = 0; i < 1000; i++)
        x[i] = i;

    try {
        SwingUtilities.invokeAndWait(new Runnable() {

            @Override
            public void run() {
                long timeOne;
                long timeTwo;
                for (int j = 0; j < 10; j++) {
                    sp.initializeLine(j);
                    timeOne = System.currentTimeMillis();
                    for (int k = 0; k < 300; k++) {
                        y[k] = Math.random();
                        sp.addPointToLine(j, x[k], y[k]);
                    }
                    timeTwo = System.currentTimeMillis();
                    numbers[j] = j;
                    timesOne[j] = timeTwo - timeOne;
                    System.out.println("LINE " + j + " " + timesOne[j]);
                }

            }
        });

        SwingUtilities.invokeAndWait(new Runnable() {

            @Override
            public void run() {
                sp.deleteAllLines();

            }
        });

        SwingUtilities.invokeAndWait(new Runnable() {

            @Override
            public void run() {
                long timeOne;
                long timeTwo;
                // SimpleXYSeries[] lines = new SimpleXYSeries[10];
                // sp.setBatchingRepaints(true);

                for (int j = 0; j < 10; j++) {
                    sp.initializeLine(j);
                    // lines[j] = sp.getActualLine(j);
                    timeOne = System.currentTimeMillis();
                    for (int k = 0; k < 300; k++) {
                        y[k] = Math.random();
                    }
                    // lines[j].setPoints(x, y);
                    sp.setLinePoints(j, x, y);
                    timeTwo = System.currentTimeMillis();
                    timesTwo[j] = timeTwo - timeOne;
                    System.out.println("LINE " + j + " " + (timeTwo - timeOne));
                }

            }
        });

        SwingUtilities.invokeAndWait(new Runnable() {

            @Override
            public void run() {
                sp.deleteAllLines();
            }
        });

        SwingUtilities.invokeAndWait(new Runnable() {

            @Override
            public void run() {
                sp.initializeLine(0);
                sp.setLinePoints(0, numbers, timesOne);

                sp.initializeLine(1);
                sp.setLinePoints(1, numbers, timesTwo);
            }
        });

    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
}

From source file:JNLPAppletLauncher.java

private void checkNoDDrawAndUpdateDeploymentProperties() {
    if (!getBooleanParameter("noddraw.check"))
        return;/*from   www.  j  ava  2 s.  c  om*/
    if (System.getProperty("os.name").toLowerCase().startsWith("windows")
            && !"true".equalsIgnoreCase(System.getProperty("sun.java2d.noddraw"))) {
        if (!SwingUtilities.isEventDispatchThread()) {
            try {
                SwingUtilities.invokeAndWait(new Runnable() {
                    public void run() {
                        updateDeploymentPropertiesImpl();
                    }
                });
            } catch (Exception e) {
            }
        } else {
            updateDeploymentPropertiesImpl();
        }
    }
}

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

private void initComponents() {
    splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
    splitPane.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
    splitPane.setOneTouchExpandable(true);

    topPanel = new JPanel();

    List<String> columns = new ArrayList<String>();

    for (ChannelColumnPlugin plugin : LoadedExtensions.getInstance().getChannelColumnPlugins().values()) {
        if (plugin.isDisplayFirst()) {
            columns.add(plugin.getColumnHeader());
        }//  w w w . j a  va 2 s. c  o  m
    }

    columns.addAll(Arrays.asList(DEFAULT_COLUMNS));

    for (ChannelColumnPlugin plugin : LoadedExtensions.getInstance().getChannelColumnPlugins().values()) {
        if (!plugin.isDisplayFirst()) {
            columns.add(plugin.getColumnHeader());
        }
    }

    channelTable = new MirthTreeTable("channelPanel", new LinkedHashSet<String>(columns));

    channelTable.setColumnFactory(new ChannelTableColumnFactory());

    ChannelTreeTableModel model = new ChannelTreeTableModel();
    model.setColumnIdentifiers(columns);
    model.setNodeFactory(new DefaultChannelTableNodeFactory());
    channelTable.setTreeTableModel(model);

    channelTable.setDoubleBuffered(true);
    channelTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    channelTable.getTreeSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    channelTable.setHorizontalScrollEnabled(true);
    channelTable.packTable(UIConstants.COL_MARGIN);
    channelTable.setRowHeight(UIConstants.ROW_HEIGHT);
    channelTable.setOpaque(true);
    channelTable.setRowSelectionAllowed(true);
    channelTable.setSortable(true);
    channelTable.putClientProperty("JTree.lineStyle", "Horizontal");
    channelTable.setAutoCreateColumnsFromModel(false);
    channelTable.setShowGrid(true, true);
    channelTable.restoreColumnPreferences();
    channelTable.setMirthColumnControlEnabled(true);

    channelTable.setDragEnabled(true);
    channelTable.setDropMode(DropMode.ON);
    channelTable.setTransferHandler(new ChannelTableTransferHandler() {
        @Override
        public boolean canImport(TransferSupport support) {
            // Don't allow files to be imported when the save task is enabled 
            if (support.isDataFlavorSupported(DataFlavor.javaFileListFlavor) && isSaveEnabled()) {
                return false;
            }
            return super.canImport(support);
        }

        @Override
        public void importFile(final File file, final boolean showAlerts) {
            try {
                SwingUtilities.invokeAndWait(new Runnable() {
                    @Override
                    public void run() {
                        String fileString = StringUtils.trim(parent.readFileToString(file));

                        try {
                            // If the table is in channel view, don't allow groups to be imported
                            ChannelGroup group = ObjectXMLSerializer.getInstance().deserialize(fileString,
                                    ChannelGroup.class);
                            if (group != null && !((ChannelTreeTableModel) channelTable.getTreeTableModel())
                                    .isGroupModeEnabled()) {
                                return;
                            }
                        } catch (Exception e) {
                        }

                        if (showAlerts && !parent.promptObjectMigration(fileString, "channel or group")) {
                            return;
                        }

                        try {
                            importChannel(
                                    ObjectXMLSerializer.getInstance().deserialize(fileString, Channel.class),
                                    showAlerts);
                        } catch (Exception e) {
                            try {
                                importGroup(ObjectXMLSerializer.getInstance().deserialize(fileString,
                                        ChannelGroup.class), showAlerts, !showAlerts);
                            } catch (Exception e2) {
                                if (showAlerts) {
                                    parent.alertThrowable(parent, e,
                                            "Invalid channel or group file:\n" + e.getMessage());
                                }
                            }
                        }
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public boolean canMoveChannels(List<Channel> channels, int row) {
            if (row >= 0) {
                TreePath path = channelTable.getPathForRow(row);
                if (path != null) {
                    AbstractChannelTableNode node = (AbstractChannelTableNode) path.getLastPathComponent();

                    if (node.isGroupNode()) {
                        Set<String> currentChannelIds = new HashSet<String>();
                        for (Enumeration<? extends MutableTreeTableNode> channelNodes = node
                                .children(); channelNodes.hasMoreElements();) {
                            currentChannelIds.add(((AbstractChannelTableNode) channelNodes.nextElement())
                                    .getChannelStatus().getChannel().getId());
                        }

                        for (Iterator<Channel> it = channels.iterator(); it.hasNext();) {
                            if (currentChannelIds.contains(it.next().getId())) {
                                it.remove();
                            }
                        }

                        return !channels.isEmpty();
                    }
                }
            }

            return false;
        }

        @Override
        public boolean moveChannels(List<Channel> channels, int row) {
            if (row >= 0) {
                TreePath path = channelTable.getPathForRow(row);
                if (path != null) {
                    AbstractChannelTableNode node = (AbstractChannelTableNode) path.getLastPathComponent();

                    if (node.isGroupNode()) {
                        Set<String> currentChannelIds = new HashSet<String>();
                        for (Enumeration<? extends MutableTreeTableNode> channelNodes = node
                                .children(); channelNodes.hasMoreElements();) {
                            currentChannelIds.add(((AbstractChannelTableNode) channelNodes.nextElement())
                                    .getChannelStatus().getChannel().getId());
                        }

                        for (Iterator<Channel> it = channels.iterator(); it.hasNext();) {
                            if (currentChannelIds.contains(it.next().getId())) {
                                it.remove();
                            }
                        }

                        if (!channels.isEmpty()) {
                            ListSelectionListener[] listeners = ((DefaultListSelectionModel) channelTable
                                    .getSelectionModel()).getListSelectionListeners();
                            for (ListSelectionListener listener : listeners) {
                                channelTable.getSelectionModel().removeListSelectionListener(listener);
                            }

                            try {
                                ChannelTreeTableModel model = (ChannelTreeTableModel) channelTable
                                        .getTreeTableModel();
                                Set<String> channelIds = new HashSet<String>();
                                for (Channel channel : channels) {
                                    model.addChannelToGroup(node, channel.getId());
                                    channelIds.add(channel.getId());
                                }

                                List<TreePath> selectionPaths = new ArrayList<TreePath>();
                                for (Enumeration<? extends MutableTreeTableNode> channelNodes = node
                                        .children(); channelNodes.hasMoreElements();) {
                                    AbstractChannelTableNode channelNode = (AbstractChannelTableNode) channelNodes
                                            .nextElement();
                                    if (channelIds
                                            .contains(channelNode.getChannelStatus().getChannel().getId())) {
                                        selectionPaths.add(new TreePath(
                                                new Object[] { model.getRoot(), node, channelNode }));
                                    }
                                }

                                parent.setSaveEnabled(true);
                                channelTable.expandPath(new TreePath(
                                        new Object[] { channelTable.getTreeTableModel().getRoot(), node }));
                                channelTable.getTreeSelectionModel().setSelectionPaths(
                                        selectionPaths.toArray(new TreePath[selectionPaths.size()]));
                                return true;
                            } finally {
                                for (ListSelectionListener listener : listeners) {
                                    channelTable.getSelectionModel().addListSelectionListener(listener);
                                }
                            }
                        }
                    }
                }
            }

            return false;
        }
    });

    channelTable.setTreeCellRenderer(new DefaultTreeCellRenderer() {
        @Override
        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded,
                boolean leaf, int row, boolean hasFocus) {
            JLabel label = (JLabel) super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row,
                    hasFocus);

            TreePath path = channelTable.getPathForRow(row);
            if (path != null && ((AbstractChannelTableNode) path.getLastPathComponent()).isGroupNode()) {
                setIcon(UIConstants.ICON_GROUP);
            }

            return label;
        }
    });
    channelTable.setLeafIcon(UIConstants.ICON_CHANNEL);
    channelTable.setOpenIcon(UIConstants.ICON_GROUP);
    channelTable.setClosedIcon(UIConstants.ICON_GROUP);

    channelTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent evt) {
            channelListSelected(evt);
        }
    });

    // listen for trigger button and double click to edit channel.
    channelTable.addMouseListener(new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent evt) {
            checkSelectionAndPopupMenu(evt);
        }

        @Override
        public void mouseReleased(MouseEvent evt) {
            checkSelectionAndPopupMenu(evt);
        }

        @Override
        public void mouseClicked(MouseEvent evt) {
            int row = channelTable.rowAtPoint(new Point(evt.getX(), evt.getY()));
            if (row == -1) {
                return;
            }

            if (evt.getClickCount() >= 2 && channelTable.getSelectedRowCount() == 1
                    && channelTable.getSelectedRow() == row) {
                AbstractChannelTableNode node = (AbstractChannelTableNode) channelTable.getPathForRow(row)
                        .getLastPathComponent();
                if (node.isGroupNode()) {
                    doEditGroupDetails();
                } else {
                    doEditChannel();
                }
            }
        }
    });

    // Key Listener trigger for DEL
    channelTable.addKeyListener(new KeyListener() {
        @Override
        public void keyPressed(KeyEvent evt) {
            if (evt.getKeyCode() == KeyEvent.VK_DELETE) {
                if (channelTable.getSelectedModelRows().length == 0) {
                    return;
                }

                boolean allGroups = true;
                boolean allChannels = true;
                for (int row : channelTable.getSelectedModelRows()) {
                    AbstractChannelTableNode node = (AbstractChannelTableNode) channelTable.getPathForRow(row)
                            .getLastPathComponent();
                    if (node.isGroupNode()) {
                        allChannels = false;
                    } else {
                        allGroups = false;
                    }
                }

                if (allChannels) {
                    doDeleteChannel();
                } else if (allGroups) {
                    doDeleteGroup();
                }
            }
        }

        @Override
        public void keyReleased(KeyEvent evt) {
        }

        @Override
        public void keyTyped(KeyEvent evt) {
        }
    });

    // MIRTH-2301
    // Since we are using addHighlighter here instead of using setHighlighters, we need to remove the old ones first.
    channelTable.setHighlighters();

    // Set highlighter.
    if (Preferences.userNodeForPackage(Mirth.class).getBoolean("highlightRows", true)) {
        Highlighter highlighter = HighlighterFactory.createAlternateStriping(UIConstants.HIGHLIGHTER_COLOR,
                UIConstants.BACKGROUND_COLOR);
        channelTable.addHighlighter(highlighter);
    }

    HighlightPredicate revisionDeltaHighlighterPredicate = new HighlightPredicate() {
        @Override
        public boolean isHighlighted(Component renderer, ComponentAdapter adapter) {
            if (adapter.column == channelTable.convertColumnIndexToView(
                    channelTable.getColumnExt(DEPLOYED_REVISION_DELTA_COLUMN_NAME).getModelIndex())) {
                if (channelTable.getValueAt(adapter.row, adapter.column) != null
                        && ((Integer) channelTable.getValueAt(adapter.row, adapter.column)).intValue() > 0) {
                    return true;
                }

                if (channelStatuses != null) {
                    String channelId = (String) channelTable.getModel()
                            .getValueAt(channelTable.convertRowIndexToModel(adapter.row), ID_COLUMN_NUMBER);
                    ChannelStatus status = channelStatuses.get(channelId);
                    if (status != null && status.isCodeTemplatesChanged()) {
                        return true;
                    }
                }
            }
            return false;
        }
    };
    channelTable.addHighlighter(new ColorHighlighter(revisionDeltaHighlighterPredicate, new Color(255, 204, 0),
            Color.BLACK, new Color(255, 204, 0), Color.BLACK));

    HighlightPredicate lastDeployedHighlighterPredicate = new HighlightPredicate() {
        @Override
        public boolean isHighlighted(Component renderer, ComponentAdapter adapter) {
            if (adapter.column == channelTable.convertColumnIndexToView(
                    channelTable.getColumnExt(LAST_DEPLOYED_COLUMN_NAME).getModelIndex())) {
                Calendar checkAfter = Calendar.getInstance();
                checkAfter.add(Calendar.MINUTE, -2);

                if (channelTable.getValueAt(adapter.row, adapter.column) != null
                        && ((Calendar) channelTable.getValueAt(adapter.row, adapter.column))
                                .after(checkAfter)) {
                    return true;
                }
            }
            return false;
        }
    };
    channelTable.addHighlighter(new ColorHighlighter(lastDeployedHighlighterPredicate, new Color(240, 230, 140),
            Color.BLACK, new Color(240, 230, 140), Color.BLACK));

    channelScrollPane = new JScrollPane(channelTable);
    channelScrollPane.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));

    filterPanel = new JPanel();
    filterPanel.setBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, new Color(164, 164, 164)));

    tagsFilterButton = new IconButton();
    tagsFilterButton
            .setIcon(new ImageIcon(getClass().getResource("/com/mirth/connect/client/ui/images/wrench.png")));
    tagsFilterButton.setToolTipText("Show Channel Filter");
    tagsFilterButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            tagsFilterButtonActionPerformed();
        }
    });

    tagsLabel = new JLabel();

    ButtonGroup tableModeButtonGroup = new ButtonGroup();

    tableModeGroupsButton = new IconToggleButton(UIConstants.ICON_GROUP);
    tableModeGroupsButton.setToolTipText("Groups");
    tableModeGroupsButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            if (!switchTableMode(true)) {
                tableModeChannelsButton.setSelected(true);
            }
        }
    });
    tableModeButtonGroup.add(tableModeGroupsButton);

    tableModeChannelsButton = new IconToggleButton(UIConstants.ICON_CHANNEL);
    tableModeChannelsButton.setToolTipText("Channels");
    tableModeChannelsButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            if (!switchTableMode(false)) {
                tableModeGroupsButton.setSelected(true);
            }
        }
    });
    tableModeButtonGroup.add(tableModeChannelsButton);

    tabPane = new JTabbedPane();

    splitPane.setTopComponent(topPanel);
    splitPane.setBottomComponent(tabPane);
}

From source file:com.hexidec.ekit.EkitCore.java

/**
 * Convenience method for setting the document text
 *///from ww  w. jav  a2  s .  co m
public void setDocumentText(final String sText) {

    // log.debug("> setDocumentText");
    // log.debug("> setDocumentText(\"" + sText + "\")");

    if (SwingUtilities.isEventDispatchThread()) {
        jtpMain.setText(sText);
    } else {
        // Evita deadlock
        try {
            SwingUtilities.invokeAndWait(new Runnable() {

                @Override
                public void run() {
                    jtpMain.setText(sText);
                }

            });
        } catch (Exception e) {
            log.error("Falha ao aplicar texto ao editor.", e);
        }
    }

    purgeUndos();

    htmlDoc.resetDirty();

    // log.debug("< setDocumentText");

}

From source file:edu.ku.brc.specify.tasks.WorkbenchTask.java

/**
 * @param workbenchNames//from  ww  w  .  ja  v a  2 s .c o m
 */
public void uploadWorkbenches(final List<Integer> workbenchIds) {
    /* !!!!!!!!!!!!!! for batch upload hack!!
     * testingJUNK = false;
     */

    javax.swing.SwingWorker<Object, Object> worker = new javax.swing.SwingWorker<Object, Object>() {

        /**
         * @param wbId
         * @return
         */
        protected RecordSet bldRS(Integer wbId) {
            RecordSet result = new RecordSet();
            result.initialize();
            result.addItem(wbId);
            return result;
        }

        /**
         * @param wb
         * @return
         */
        protected WorkbenchPaneSS getWbSS(Workbench wb) {
            WorkbenchPaneSS wbSS = null;
            for (SubPaneIFace sb : SubPaneMgr.getInstance().getSubPanes()) {
                if (sb instanceof WorkbenchPaneSS) {
                    Workbench pwb = ((WorkbenchPaneSS) sb).getWorkbench();
                    if (pwb == wb) {
                        wbSS = (WorkbenchPaneSS) sb;
                        break;
                    }
                }
            }
            return wbSS;
        }

        /*
         * (non-Javadoc)
         * 
         * @see javax.swing.SwingWorker#doInBackground()
         */
        @Override
        protected Object doInBackground() throws Exception {
            for (Integer wbId : workbenchIds) {
                try {
                    RecordSet rs = bldRS(wbId);
                    final Workbench wb = loadWorkbench(rs);
                    if (wb != null) {
                        System.out.println("loaded " + wb.getName());
                        SwingUtilities.invokeAndWait(new Runnable() {

                            /* (non-Javadoc)
                             * @see java.lang.Runnable#run()
                             */
                            @Override
                            public void run() {
                                createEditorForWorkbench(wb, null, false, false);
                            }

                        });
                        final WorkbenchPaneSS wbSS = getWbSS(wb);
                        if (wbSS != null) {
                            SwingUtilities.invokeAndWait(new Runnable() {
                                /* (non-Javadoc)
                                 * @see java.lang.Runnable#run()
                                 */
                                @Override
                                public void run() {
                                    wbSS.doDatasetUpload();
                                    System.out.println("opened uploader for " + wb.getName());
                                }

                            });

                            //                        SwingUtilities.invokeLater(new Runnable(){
                            //                           /* (non-Javadoc)
                            //                            * @see java.lang.Runnable#run()
                            //                            */
                            //                           @Override
                            //                           public void run() {
                            boolean validated = Uploader.getCurrentUpload().validateData(false);
                            //                           }
                            //                           
                            //                        });
                            if (validated) {
                                System.out.println("validated uploader for " + wb.getName());
                                Uploader.getCurrentUpload().uploadIt(false);
                                if (Uploader.getCurrentUpload().getCurrentOp() != Uploader.SUCCESS) {
                                    System.out.println("upload failed for " + wb.getName());
                                } else {
                                    System.out.println("uploaded " + wb.getName());
                                    // NOT saving recordsets of uploaded
                                    // objects or setting isUploaded status for wb rows.
                                }
                            }
                            SwingUtilities.invokeLater(new Runnable() {

                                /* (non-Javadoc)
                                 * @see java.lang.Runnable#run()
                                 */
                                @Override
                                public void run() {
                                    Uploader.getCurrentUpload().closeMainForm(true);
                                    SubPaneMgr.getInstance().removePane(wbSS);
                                }

                            });
                            System.out.println("closed uploader for " + wb.getName());
                        }
                    } else {
                        System.out.println("No workbench with id = " + wbId);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            return null;
        }
    };
    worker.execute();
}

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

/**
 * Undoes the most recent upload./*from  w  w  w .j  av  a  2 s  . c  o  m*/
 * 
 * Called in response to undo command from user, and by the program when an upload is cancelled
 * or fails.
 */
public void undoUpload(final boolean isUserCmd, final boolean shuttingDown, final boolean completeUndo) {
    setOpKiller(null);

    final UploaderTask undoTask = new UploaderTask(false, "") {
        boolean success = false;
        boolean removeObjects = completeUndo;
        Vector<UploadTable> undone = new Vector<UploadTable>();

        @Override
        public Object doInBackground() {
            start();
            if (removeObjects) {
                try {
                    if (isUserCmd) {
                        SwingUtilities.invokeAndWait(new Runnable() {
                            public void run() {
                                initProgressBar(0, getUploadedObjects(), true,
                                        getResourceString("WB_UPLOAD_UNDOING") + " "
                                                + getResourceString("WB_UPLOAD_OBJECT"),
                                        shuttingDown);
                            }
                        });
                    } else {
                        SwingUtilities.invokeLater(new Runnable() {
                            public void run() {
                                initProgressBar(0, getUploadedObjects(), true,
                                        getResourceString("WB_UPLOAD_CLEANING_UP") + " "
                                                + getResourceString("WB_UPLOAD_OBJECT"),
                                        shuttingDown);
                            }
                        });
                    }
                    List<UploadTable> fixedUp = reorderUploadTablesForUndo();
                    boolean isEmbeddedCE = AppContextMgr.getInstance().getClassObject(Collection.class)
                            .getIsEmbeddedCollectingEvent();
                    undoAttachments();
                    try {
                        AppContextMgr.getInstance().getClassObject(Collection.class)
                                .setIsEmbeddedCollectingEvent(false);
                        for (int ut = fixedUp.size() - 1; ut >= 0; ut--) {
                            // setCurrentOpProgress(fixedUp.size() - ut, false);
                            logDebug("undoing " + fixedUp.get(ut).getTable().getName());
                            fixedUp.get(ut).undoUpload(true);
                            undone.add(fixedUp.get(ut));
                        }
                        success = true;
                        return success;
                    } finally {
                        AppContextMgr.getInstance().getClassObject(Collection.class)
                                .setIsEmbeddedCollectingEvent(isEmbeddedCE);
                    }
                } catch (Exception ex) {
                    setOpKiller(ex);
                    return false;
                }
            }
            //else
            success = true;
            return success;
        }

        @Override
        public void done() {
            if (removeObjects) {
                try {
                    for (UploadTable ut : undone) {
                        ut.finishUndoUpload();
                    }
                } catch (Exception ex) {
                    setOpKiller(ex);
                    success = false;
                }
            }

            super.done();

            if (removeObjects) {
                for (WorkbenchRow wbRow : theWb.getWorkbenchRows()) {
                    wbRow.setUploadStatus(WorkbenchRow.UPLD_NONE);
                }
                wbSS.setChanged(false);
            }

            statusBar.setText("");
            statusBar.setProgressDone("UPLOADER");
            if (shuttingDown) {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        UIRegistry.clearSimpleGlassPaneMsg();

                    }
                });
            }
            if (getOpKiller() != null) {
                JOptionPane.showMessageDialog(UIRegistry.getTopWindow(), String.format(
                        getResourceString("WB_UPLOAD_CLEANUP_FAILED"),
                        new Object[] {
                                getResourceString((isUserCmd ? "WB_UPLOAD_UNDO_BTN" : "WB_UPLOAD_CLEANUP")),
                                theWb.getName(), theWb.getName() }),
                        getResourceString("WARNING"), JOptionPane.WARNING_MESSAGE);

            }
            if (mainPanel != null) {
                mainPanel.clearObjectsCreated();
                if (success) {
                    if (removeObjects) {
                        setCurrentOp(Uploader.READY_TO_UPLOAD);
                    } else {
                        setCurrentOp(Uploader.SUCCESS_PARTIAL);
                    }
                } else {
                    setCurrentOp(Uploader.FAILURE);
                }
            }
            if (shuttingDown && !isUserCmd) {
                wbSS.decShutdownLock();
                wbSS.shutdown();
            }
        }

    };
    if (recordSets != null) {
        recordSets.clear();
        recordSets = null;
    }
    UIRegistry.displayStatusBarText(
            getResourceString((isUserCmd ? Uploader.UNDOING_UPLOAD : Uploader.CLEANING_UP)));
    if (shuttingDown) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                UIRegistry.writeSimpleGlassPaneMsg(
                        String.format(getResourceString("WB_UPLOAD_CLEANING_UP") + "...", theWb.getName()),
                        WorkbenchTask.GLASSPANE_FONT_SIZE);

            }
        });
    }
    if (shuttingDown && !isUserCmd) {
        wbSS.incShutdownLock();
    }
    undoTask.execute();
    setCurrentOp(isUserCmd ? Uploader.UNDOING_UPLOAD : Uploader.CLEANING_UP);
}

From source file:lcmc.gui.resources.ServiceInfo.java

/** Returns existing service manu item. */
private MyMenu getExistingServiceMenuItem(final String name, final boolean enableForNew,
        final boolean testOnly) {
    final ServiceInfo thisClass = this;
    return new MyMenu(name, new AccessMode(ConfigData.AccessType.ADMIN, false),
            new AccessMode(ConfigData.AccessType.OP, false)) {
        private static final long serialVersionUID = 1L;
        private final Lock mUpdateLock = new ReentrantLock();

        @Override/*ww w  .  ja v  a 2  s.c  o m*/
        public String enablePredicate() {
            if (getBrowser().clStatusFailed()) {
                return ClusterBrowser.UNKNOWN_CLUSTER_STATUS_STRING;
            } else if (getService().isRemoved()) {
                return IS_BEING_REMOVED_STRING;
            } else if (getService().isOrphaned()) {
                return IS_ORPHANED_STRING;
            } else if (!enableForNew && getService().isNew()) {
                return IS_NEW_STRING;
            }
            if (getBrowser().getExistingServiceList(thisClass).size() == 0) {
                return "&lt;&lt;empty;&gt;&gt;";
            }
            return null;
        }

        @Override
        public void update() {
            final Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    if (mUpdateLock.tryLock()) {
                        try {
                            updateThread();
                        } finally {
                            mUpdateLock.unlock();
                        }
                    }
                }
            });
            t.start();
        }

        private void updateThread() {
            final JCheckBox colocationWi = new JCheckBox("Colo", true);
            final JCheckBox orderWi = new JCheckBox("Order", true);
            colocationWi.setBackground(ClusterBrowser.STATUS_BACKGROUND);
            colocationWi.setPreferredSize(colocationWi.getMinimumSize());
            orderWi.setBackground(ClusterBrowser.STATUS_BACKGROUND);
            orderWi.setPreferredSize(orderWi.getMinimumSize());
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    setEnabled(false);
                }
            });
            Tools.invokeAndWait(new Runnable() {
                @Override
                public void run() {
                    removeAll();
                }
            });

            final MyListModel<MyMenuItem> dlm = new MyListModel<MyMenuItem>();
            final Map<MyMenuItem, ButtonCallback> callbackHash = new HashMap<MyMenuItem, ButtonCallback>();
            final MyList<MyMenuItem> list = new MyList<MyMenuItem>(dlm, getBackground());

            final List<JDialog> popups = new ArrayList<JDialog>();
            for (final ServiceInfo asi : getBrowser().getExistingServiceList(thisClass)) {
                if (asi.isConstraintPH() && isConstraintPH()) {
                    continue;
                }
                if (asi.getCloneInfo() != null || asi.getGroupInfo() != null) {
                    /* skip services that are clones or in groups. */
                    continue;
                }
                addExistingServiceMenuItem(asi.toString(), asi, dlm, callbackHash, list, colocationWi, orderWi,
                        popups, testOnly);
                asi.addExistingGroupServiceMenuItems(thisClass, dlm, callbackHash, list, colocationWi, orderWi,
                        popups, testOnly);
            }
            final JPanel colOrdPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
            colOrdPanel.setBackground(ClusterBrowser.STATUS_BACKGROUND);
            colOrdPanel.add(colocationWi);
            colOrdPanel.add(orderWi);
            final MyMenu thisM = this;
            try {
                SwingUtilities.invokeAndWait(new Runnable() {
                    @Override
                    public void run() {
                        final boolean ret = Tools.getScrollingMenu(name, colOrdPanel, thisM, dlm, list,
                                thisClass, popups, callbackHash);
                        if (!ret) {
                            setEnabled(false);
                        }
                    }
                });
            } catch (final InterruptedException ix) {
                Thread.currentThread().interrupt();
            } catch (final InvocationTargetException x) {
                Tools.printStackTrace();
            }
            super.update();
        }
    };
}

From source file:lcmc.gui.resources.ServiceInfo.java

/** Adds new Service and dependence. */
private MyMenu getAddServiceMenuItem(final boolean testOnly, final String name) {
    final ServiceInfo thisClass = this;
    return new MyMenu(name, new AccessMode(ConfigData.AccessType.ADMIN, false),
            new AccessMode(ConfigData.AccessType.OP, false)) {
        private static final long serialVersionUID = 1L;
        private final Lock mUpdateLock = new ReentrantLock();

        @Override//w  w  w . j  ava 2  s . c  o m
        public String enablePredicate() {
            if (getBrowser().clStatusFailed()) {
                return ClusterBrowser.UNKNOWN_CLUSTER_STATUS_STRING;
            } else if (getService().isRemoved()) {
                return IS_BEING_REMOVED_STRING;
            } else if (getService().isOrphaned()) {
                return IS_ORPHANED_STRING;
            } else if (getService().isNew()) {
                return IS_NEW_STRING;
            }
            return null;
        }

        @Override
        public void update() {
            final Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    if (mUpdateLock.tryLock()) {
                        try {
                            updateThread();
                        } finally {
                            mUpdateLock.unlock();
                        }
                    }
                }
            });
            t.start();
        }

        private void updateThread() {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    setEnabled(false);
                }
            });
            Tools.invokeAndWait(new Runnable() {
                @Override
                public void run() {
                    removeAll();
                }
            });
            final Point2D pos = getPos();
            final CRMXML crmXML = getBrowser().getCRMXML();
            final ResourceAgent fsService = crmXML.getResourceAgent("Filesystem",
                    ResourceAgent.HEARTBEAT_PROVIDER, ResourceAgent.OCF_CLASS);
            final MyMenu thisMenu = this;
            if (crmXML.isLinbitDrbdPresent()) { /* just skip it, if it
                                                   is not */
                final ResourceAgent linbitDrbdService = crmXML.getHbLinbitDrbd();
                /* Linbit:DRBD */
                try {
                    SwingUtilities.invokeAndWait(new Runnable() {
                        @Override
                        public void run() {
                            addDrbdLinbitMenu(thisMenu, crmXML, pos, fsService, testOnly);
                        }
                    });
                } catch (final InterruptedException ix) {
                    Thread.currentThread().interrupt();
                } catch (final InvocationTargetException x) {
                    Tools.printStackTrace();
                }

            }
            if (crmXML.isDrbddiskPresent()) { /* just skip it,
                                                 if it is not */
                /* drbddisk */
                try {
                    SwingUtilities.invokeAndWait(new Runnable() {
                        @Override
                        public void run() {
                            addDrbddiskMenu(thisMenu, crmXML, pos, fsService, testOnly);
                        }
                    });
                } catch (final InterruptedException ix) {
                    Thread.currentThread().interrupt();
                } catch (final InvocationTargetException x) {
                    Tools.printStackTrace();
                }
            }
            final ResourceAgent ipService = crmXML.getResourceAgent("IPaddr2", ResourceAgent.HEARTBEAT_PROVIDER,
                    ResourceAgent.OCF_CLASS);
            if (ipService != null) { /* just skip it, if it is not*/
                /* ipaddr */
                try {
                    SwingUtilities.invokeAndWait(new Runnable() {
                        @Override
                        public void run() {
                            addIpMenu(thisMenu, pos, ipService, testOnly);
                        }
                    });
                } catch (final InterruptedException ix) {
                    Thread.currentThread().interrupt();
                } catch (final InvocationTargetException x) {
                    Tools.printStackTrace();
                }
            }
            if (fsService != null) { /* just skip it, if it is not*/
                /* Filesystem */
                try {
                    SwingUtilities.invokeAndWait(new Runnable() {
                        @Override
                        public void run() {
                            addFilesystemMenu(thisMenu, pos, fsService, testOnly);
                        }
                    });
                } catch (final InterruptedException ix) {
                    Thread.currentThread().interrupt();
                } catch (final InvocationTargetException x) {
                    Tools.printStackTrace();
                }
            }
            final List<JDialog> popups = new ArrayList<JDialog>();
            for (final String cl : ClusterBrowser.HB_CLASSES) {
                final List<ResourceAgent> services = getAddServiceList(cl);
                if (services.size() == 0) {
                    /* no services, don't show */
                    continue;
                }
                final JCheckBox colocationWi = new JCheckBox("Colo", true);
                final JCheckBox orderWi = new JCheckBox("Order", true);
                colocationWi.setBackground(ClusterBrowser.STATUS_BACKGROUND);
                colocationWi.setPreferredSize(colocationWi.getMinimumSize());
                orderWi.setBackground(ClusterBrowser.STATUS_BACKGROUND);
                orderWi.setPreferredSize(orderWi.getMinimumSize());
                final JPanel colOrdPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
                colOrdPanel.setBackground(ClusterBrowser.STATUS_BACKGROUND);
                colOrdPanel.add(colocationWi);
                colOrdPanel.add(orderWi);
                boolean mode = !AccessMode.ADVANCED;
                if (ResourceAgent.UPSTART_CLASS.equals(cl) || ResourceAgent.SYSTEMD_CLASS.equals(cl)) {
                    mode = AccessMode.ADVANCED;
                }
                if (ResourceAgent.LSB_CLASS.equals(cl)
                        && !getAddServiceList(ResourceAgent.SERVICE_CLASS).isEmpty()) {
                    mode = AccessMode.ADVANCED;
                }
                final MyMenu classItem = new MyMenu(ClusterBrowser.getClassMenu(cl),
                        new AccessMode(ConfigData.AccessType.ADMIN, mode),
                        new AccessMode(ConfigData.AccessType.OP, mode));
                final MyListModel<MyMenuItem> dlm = new MyListModel<MyMenuItem>();
                for (final ResourceAgent ra : services) {
                    try {
                        SwingUtilities.invokeAndWait(new Runnable() {
                            @Override
                            public void run() {
                                addResourceAgentMenu(ra, dlm, pos, popups, colocationWi, orderWi, testOnly);
                            }
                        });
                    } catch (final InterruptedException ix) {
                        Thread.currentThread().interrupt();
                    } catch (final InvocationTargetException x) {
                        Tools.printStackTrace();
                    }
                }
                try {
                    SwingUtilities.invokeAndWait(new Runnable() {
                        @Override
                        public void run() {
                            final boolean ret = Tools.getScrollingMenu(ClusterBrowser.getClassMenu(cl),
                                    colOrdPanel, classItem, dlm, new MyList<MyMenuItem>(dlm, getBackground()),
                                    thisClass, popups, null);
                            if (!ret) {
                                classItem.setEnabled(false);
                            }
                            thisMenu.add(classItem);
                        }
                    });
                } catch (final InterruptedException ix) {
                    Thread.currentThread().interrupt();
                } catch (final InvocationTargetException x) {
                    Tools.printStackTrace();
                }
            }
            super.update();
        }
    };
}