Search in sources :

Example 26 with RequestProcessor

use of org.openide.util.RequestProcessor in project netbeans-rcp-lite by outersky.

the class RequestProcessor180386Test method testAwaitTermination.

public void testAwaitTermination() throws Exception {
    int count = 20;
    final Object lock = new Object();
    final CountDownLatch waitAllLaunched = new CountDownLatch(count);
    final CountDownLatch waitAll = new CountDownLatch(count);
    final RequestProcessor rp = new RequestProcessor("TestRP", count);
    class R implements Runnable {

        volatile boolean hasStarted;

        volatile boolean hasFinished;

        @Override
        public void run() {
            hasStarted = true;
            waitAllLaunched.countDown();
            synchronized (lock) {
                try {
                    lock.wait();
                    if (Thread.interrupted()) {
                        return;
                    }
                } catch (InterruptedException ex) {
                    return;
                } finally {
                    hasFinished = true;
                    waitAll.countDown();
                }
            }
        }
    }
    Set<Future<String>> s = new HashSet<Future<String>>();
    Set<R> rs = new HashSet<R>();
    for (int i = 0; i < count; i++) {
        String currName = "Runnable " + i;
        R r = new R();
        rs.add(r);
        s.add(rp.submit(r, currName));
    }
    waitAllLaunched.await();
    synchronized (lock) {
        // Notify just one thread
        lock.notifyAll();
    }
    rp.shutdown();
    boolean awaitTermination = rp.awaitTermination(1, TimeUnit.DAYS);
    assertTrue(awaitTermination);
    assertTrue(rp.isShutdown());
    assertTrue(rp.isTerminated());
}
Also used : CountDownLatch(java.util.concurrent.CountDownLatch) ScheduledFuture(java.util.concurrent.ScheduledFuture) Future(java.util.concurrent.Future) RequestProcessor(org.openide.util.RequestProcessor) HashSet(java.util.HashSet)

Example 27 with RequestProcessor

use of org.openide.util.RequestProcessor in project netbeans-rcp-lite by outersky.

the class RequestProcessor180386Test method testScheduleOneShot.

public void testScheduleOneShot() throws Exception {
    RequestProcessor rp = new RequestProcessor("testScheduleOneShot", 5, true, true);
    try {
        class C implements Callable<String> {

            volatile long start = System.currentTimeMillis();

            private volatile long end;

            @Override
            public String call() throws Exception {
                synchronized (this) {
                    end = System.currentTimeMillis();
                }
                return "Hello";
            }

            synchronized long elapsed() {
                return end - start;
            }
        }
        C c = new C();
        long delay = 5000;
        // Use a 20 second timeout to have a reasonable chance of accuracy
        ScheduledFuture<String> f = rp.schedule(c, delay * 1000, TimeUnit.MICROSECONDS);
        assertEquals(5000, f.getDelay(TimeUnit.MILLISECONDS));
        assertNotNull(f.get());
        // Allow 4 seconds fudge-factor
        assertTrue(c.elapsed() > 4600);
        assertTrue(f.isDone());
    } finally {
        rp.stop();
    }
}
Also used : RequestProcessor(org.openide.util.RequestProcessor) Callable(java.util.concurrent.Callable)

Example 28 with RequestProcessor

use of org.openide.util.RequestProcessor in project netbeans-rcp-lite by outersky.

the class OptionsChooserPanel method showExportDialog.

/**
 * Shows panel for export of options.
 */
@NbBundle.Messages({ "ProgressHandle_Export_DisplayName=Exporting Options", "# {0} - path where the exported options are saved", "Export_Notification_DetailsText=File saved at {0}" })
public static void showExportDialog() {
    if (exportTask != null && !exportTask.isFinished()) {
        return;
    }
    // NOI18N
    LOGGER.fine("showExportDialog");
    File sourceUserdir = Places.getUserDirectory();
    final OptionsChooserPanel optionsChooserPanel = new OptionsChooserPanel();
    optionsChooserPanel.panelType = PanelType.EXPORT;
    optionsChooserPanel.setOptionsExportModel(new OptionsExportModel(sourceUserdir));
    optionsChooserPanel.loadOptions();
    optionsChooserPanel.txtFile.setText(getDefaultUserdirRoot().concat(File.separator));
    optionsChooserPanel.txtFile.getDocument().addDocumentListener(new DocumentListener() {

        public void insertUpdate(DocumentEvent e) {
            optionsChooserPanel.dialogDescriptor.setValid(optionsChooserPanel.isPanelValid());
        }

        public void removeUpdate(DocumentEvent e) {
            optionsChooserPanel.dialogDescriptor.setValid(optionsChooserPanel.isPanelValid());
        }

        public void changedUpdate(DocumentEvent e) {
            optionsChooserPanel.dialogDescriptor.setValid(optionsChooserPanel.isPanelValid());
        }
    });
    DialogDescriptor dd = new DialogDescriptor(optionsChooserPanel, NbBundle.getMessage(OptionsChooserPanel.class, "OptionsChooserPanel.export.title"), true, new Object[] { DialogDescriptor.OK_OPTION, DialogDescriptor.CANCEL_OPTION }, DialogDescriptor.OK_OPTION, DialogDescriptor.DEFAULT_ALIGN, null, null);
    // add bottom user notification area
    dd.createNotificationLineSupport();
    dd.setValid(false);
    ExportConfirmationPanel exportConfirmationPanel = null;
    if (!ExportConfirmationPanel.getSkipOption()) {
        exportConfirmationPanel = new ExportConfirmationPanel();
        final ExportConfirmationPanel finalExportConfirmationPanel = exportConfirmationPanel;
        dd.setButtonListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                if (e.getSource() == DialogDescriptor.OK_OPTION) {
                    String passwords = NbBundle.getMessage(OptionsChooserPanel.class, "OptionsChooserPanel.export.passwords.displayName");
                    Enumeration dfs = ((DefaultMutableTreeNode) treeModel.getRoot()).depthFirstEnumeration();
                    while (dfs.hasMoreElements()) {
                        Object nodeObj = dfs.nextElement();
                        DefaultMutableTreeNode node = (DefaultMutableTreeNode) nodeObj;
                        Object userObject = node.getUserObject();
                        if (userObject instanceof OptionsExportModel.Item) {
                            if (((OptionsExportModel.Item) userObject).getDisplayName().equals(passwords)) {
                                if (treeDataProvider.isSelected(nodeObj)) {
                                    // show confirmation dialog when user click OK and All/Passwords/Passwords item is selected
                                    finalExportConfirmationPanel.showConfirmation();
                                }
                            }
                        }
                    }
                }
            }
        });
    }
    optionsChooserPanel.setDialogDescriptor(dd);
    DialogDisplayer.getDefault().createDialog(dd).setVisible(true);
    if (DialogDescriptor.OK_OPTION.equals(dd.getValue())) {
        if (exportConfirmationPanel != null && !exportConfirmationPanel.confirmed()) {
            // NOI18N
            LOGGER.fine("Export canceled.");
            return;
        }
        // NOI18N
        Action save = Actions.forID("Window", "org.netbeans.core.windows.actions.SaveWindowsAction");
        if (save != null) {
            save.actionPerformed(new ActionEvent(optionsChooserPanel, 0, ""));
        }
        String selectedFilePath = optionsChooserPanel.getSelectedFilePath();
        if (selectedFilePath.endsWith("/")) {
            // NOI18N
            // name zip file after last folder
            // NOI18N
            selectedFilePath = selectedFilePath.substring(0, selectedFilePath.lastIndexOf("/"));
            // NOI18N
            String zipName = selectedFilePath.substring(selectedFilePath.lastIndexOf("/") + 1);
            // NOI18N
            selectedFilePath = selectedFilePath.concat("/").concat(zipName).concat(".zip");
        }
        if (!selectedFilePath.endsWith(".zip")) {
            // NOI18N
            // NOI18N
            selectedFilePath = selectedFilePath.concat(".zip");
        }
        final String targetPath = selectedFilePath;
        // NOI18N
        RequestProcessor RP = new RequestProcessor("OptionsChooserPanel Export", 1);
        Runnable runnable = new Runnable() {

            @Override
            public void run() {
                // to avoid false possitives during import, find the items that are explicitly selected by the user for export
                Enumeration dfs = ((DefaultMutableTreeNode) treeModel.getRoot()).depthFirstEnumeration();
                ArrayList<String> enabledItems = new ArrayList<String>();
                while (dfs.hasMoreElements()) {
                    Object userObject = ((DefaultMutableTreeNode) dfs.nextElement()).getUserObject();
                    if (userObject instanceof OptionsExportModel.Category) {
                        OptionsExportModel.Category category = (OptionsExportModel.Category) userObject;
                        if (!category.getState().equals(OptionsExportModel.State.DISABLED)) {
                            List<OptionsExportModel.Item> items = ((OptionsExportModel.Category) userObject).getItems();
                            for (OptionsExportModel.Item item : items) {
                                if (item.isEnabled()) {
                                    enabledItems.add(category.getDisplayName().concat(item.getDisplayName()));
                                }
                            }
                        }
                    }
                }
                optionsChooserPanel.getOptionsExportModel().doExport(new File(targetPath), enabledItems);
                NotificationDisplayer.getDefault().notify(// NOI18N
                NbBundle.getMessage(OptionsChooserPanel.class, "OptionsChooserPanel.export.status.text"), OPTIONS_ICON, Bundle.Export_Notification_DetailsText(targetPath), null);
                // NOI18N
                LOGGER.fine("Export finished.");
            }
        };
        exportTask = RP.create(runnable);
        final ProgressHandle ph = ProgressHandleFactory.createHandle(Bundle.ProgressHandle_Export_DisplayName(), exportTask);
        exportTask.addTaskListener(new TaskListener() {

            @Override
            public void taskFinished(org.openide.util.Task task) {
                ph.finish();
            }
        });
        ph.start();
        exportTask.schedule(0);
    }
}
Also used : DocumentListener(javax.swing.event.DocumentListener) Action(javax.swing.Action) DefaultMutableTreeNode(javax.swing.tree.DefaultMutableTreeNode) ActionEvent(java.awt.event.ActionEvent) ArrayList(java.util.ArrayList) TaskListener(org.openide.util.TaskListener) Enumeration(java.util.Enumeration) DocumentEvent(javax.swing.event.DocumentEvent) ActionListener(java.awt.event.ActionListener) ProgressHandle(org.netbeans.api.progress.ProgressHandle) DialogDescriptor(org.openide.DialogDescriptor) File(java.io.File) RequestProcessor(org.openide.util.RequestProcessor)

Example 29 with RequestProcessor

use of org.openide.util.RequestProcessor in project netbeans-rcp-lite by outersky.

the class RequestProcessor226051Test method testAwaitTermination.

@Test
public void testAwaitTermination() throws InterruptedException {
    if (true)
        return;
    int count = 5;
    RequestProcessor rp = new RequestProcessor(getClass().getSimpleName(), count + 1, false);
    CountDownLatch latch = new CountDownLatch(count);
    List<R> rs = new LinkedList<R>();
    for (int i = 0; i < count; i++) {
        R r = new R(latch);
        rs.add(r);
        rp.post(r);
    }
    rp.shutdown();
    boolean res = rp.awaitTermination(DELAY * (count + 1), TimeUnit.MILLISECONDS);
    for (R r : rs) {
        assertTrue(r.ran.get());
    }
    assertTrue(res);
}
Also used : CountDownLatch(java.util.concurrent.CountDownLatch) RequestProcessor(org.openide.util.RequestProcessor) LinkedList(java.util.LinkedList) Test(org.junit.Test)

Example 30 with RequestProcessor

use of org.openide.util.RequestProcessor in project netbeans-rcp-lite by outersky.

the class RequestProcessorParallelTest method testParallelExecutionOnOwnRequestProcessorAllowed.

public void testParallelExecutionOnOwnRequestProcessorAllowed() {
    final RequestProcessor rp = new RequestProcessor("Mine", 32);
    Para p = new Para(rp, 28);
    CharSequence log = Log.enable("org.openide.util.RequestProcessor", Level.WARNING);
    rp.post(p).waitFinished();
    if (log.length() > 0) {
        fail("There shall be no warnings:\n" + log);
    }
}
Also used : RequestProcessor(org.openide.util.RequestProcessor)

Aggregations

RequestProcessor (org.openide.util.RequestProcessor)56 CountDownLatch (java.util.concurrent.CountDownLatch)20 Task (org.openide.util.Task)13 HashSet (java.util.HashSet)12 ArrayList (java.util.ArrayList)8 Callable (java.util.concurrent.Callable)8 CopyOnWriteArrayList (java.util.concurrent.CopyOnWriteArrayList)8 RandomlyFails (org.netbeans.junit.RandomlyFails)7 Future (java.util.concurrent.Future)6 ScheduledFuture (java.util.concurrent.ScheduledFuture)6 CancellationException (java.util.concurrent.CancellationException)3 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 Logger (java.util.logging.Logger)2 TaskListener (org.openide.util.TaskListener)2 ActionEvent (java.awt.event.ActionEvent)1 ActionListener (java.awt.event.ActionListener)1 File (java.io.File)1 Enumeration (java.util.Enumeration)1 LinkedList (java.util.LinkedList)1