Search in sources :

Example 1 with Cancellable

use of org.openide.util.Cancellable in project syncope by apache.

the class ResourceExplorerTopComponent method componentOpened.

// End of variables declaration//GEN-END:variables
@Override
public void componentOpened() {
    // look for connection preferences
    Preferences prefs = NbPreferences.forModule(ResourceExplorerTopComponent.class);
    if (StringUtils.isBlank(prefs.get("scheme", null)) || StringUtils.isBlank(prefs.get("host", null)) || StringUtils.isBlank(prefs.get("port", null)) || StringUtils.isBlank(prefs.get("username", null)) || StringUtils.isBlank(prefs.get("password", null))) {
        new ServerDetailsView(null, true).setVisible(true);
    }
    try {
        mailTemplateManagerService = ResourceConnector.getMailTemplateManagerService();
        reportTemplateManagerService = ResourceConnector.getReportTemplateManagerService();
        // init tree, because on close it is reset
        initTemplatesTree();
        // Load templates
        LOG.info("Loading Apache Syncope templates...");
        Runnable tsk = new Runnable() {

            @Override
            public void run() {
                final ProgressHandle progr = ProgressHandle.createHandle("Loading Templates", new Cancellable() {

                    @Override
                    public boolean cancel() {
                        return true;
                    }
                });
                progr.start();
                progr.progress("Loading Templates.");
                addMailTemplates();
                addReportXslts();
                progr.finish();
            }
        };
        REQUEST_PROCESSOR.post(tsk);
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e.getMessage(), "Generic Error", JOptionPane.ERROR_MESSAGE);
        ServerDetailsView serverDetails = getRefreshServerDetails();
    }
    Runnable tsk = new Runnable() {

        @Override
        public void run() {
            final ProgressHandle progr = ProgressHandle.createHandle("Loading Templates", new Cancellable() {

                @Override
                public boolean cancel() {
                    return true;
                }
            });
            progr.start();
            progr.progress("Loading Templates.");
            addMailTemplates();
            addReportXslts();
            progr.finish();
        }
    };
    RequestProcessor.getDefault().post(tsk);
}
Also used : ProgressHandle(org.netbeans.api.progress.ProgressHandle) Cancellable(org.openide.util.Cancellable) NbPreferences(org.openide.util.NbPreferences) Preferences(java.util.prefs.Preferences) SyncopeClientException(org.apache.syncope.common.lib.SyncopeClientException) BadLocationException(javax.swing.text.BadLocationException) IOException(java.io.IOException)

Example 2 with Cancellable

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

the class RequestProcessor180386Test method testInvokeAllCancellation.

public void testInvokeAllCancellation() throws Exception {
    int count = 20;
    final CountDownLatch waitAll = new CountDownLatch(count);
    final RequestProcessor rp = new RequestProcessor("TestRP", count);
    class C implements Callable<String>, Cancellable {

        private final String result;

        volatile boolean cancelCalled;

        C(String result) {
            this.result = result;
        }

        @Override
        public String call() throws Exception {
            waitAll.countDown();
            return cancelCalled ? null : result;
        }

        @Override
        public boolean cancel() {
            cancelCalled = true;
            return false;
        }
    }
    List<C> l = new ArrayList<C>(count);
    List<Future<String>> fs;
    Set<String> names = new HashSet<String>(count);
    for (int i = 0; i < count; i++) {
        String name = "R" + i;
        names.add(name);
        C c = new C(name);
        l.add(c);
    }
    fs = rp.invokeAll(l);
    assertNotNull(fs);
    Set<String> s = new HashSet<String>(count);
    for (Future<String> f : fs) {
        s.add(f.get());
    }
    assertEquals(names, s);
}
Also used : Cancellable(org.openide.util.Cancellable) ArrayList(java.util.ArrayList) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) CountDownLatch(java.util.concurrent.CountDownLatch) Callable(java.util.concurrent.Callable) ScheduledFuture(java.util.concurrent.ScheduledFuture) Future(java.util.concurrent.Future) RequestProcessor(org.openide.util.RequestProcessor) HashSet(java.util.HashSet)

Example 3 with Cancellable

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

the class InstallStep method handleValidation.

private Installer handleValidation(Validator v, final InstallSupport support) {
    if (canceled) {
        log.fine("Quit handleValidation() because an previous installation was canceled.");
        return null;
    }
    component.setHeadAndContent(getBundle(HEAD_VERIFY), getBundle(CONTENT_VERIFY));
    ProgressHandle handle = ProgressHandleFactory.createHandle(getBundle("InstallStep_Validate_ValidatingPlugins"));
    JComponent progressComponent = ProgressHandleFactory.createProgressComponent(handle);
    JLabel mainLabel = ProgressHandleFactory.createMainLabelComponent(handle);
    JLabel detailLabel = ProgressHandleFactory.createDetailLabelComponent(handle);
    if (runInBackground()) {
        systemHandle = ProgressHandleFactory.createHandle(getBundle("InstallStep_Validate_ValidatingPlugins"), new Cancellable() {

            @Override
            public boolean cancel() {
                handleCancel();
                return true;
            }
        });
        handle = systemHandle;
    } else {
        spareHandle = ProgressHandleFactory.createHandle(getBundle("InstallStep_Validate_ValidatingPlugins"), new Cancellable() {

            @Override
            public boolean cancel() {
                handleCancel();
                return true;
            }
        });
        totalUnits = model.getInstallContainer().listAll().size();
        processedUnits = 0;
        if (indeterminateProgress) {
            detailLabel.addPropertyChangeListener(TEXT_PROPERTY, new PropertyChangeListener() {

                @Override
                public void propertyChange(PropertyChangeEvent evt) {
                    assert TEXT_PROPERTY.equals(evt.getPropertyName()) : "Listens onlo on " + TEXT_PROPERTY + " but was " + evt;
                    if (evt.getOldValue() != evt.getNewValue()) {
                        processedUnits++;
                        if (indeterminateProgress && spareHandleStarted) {
                            if (processedUnits < totalUnits - 1) {
                                totalUnits = totalUnits - processedUnits;
                                spareHandle.switchToDeterminate(totalUnits);
                                indeterminateProgress = false;
                            }
                        }
                        if (!indeterminateProgress) {
                            spareHandle.progress(((JLabel) evt.getSource()).getText(), processedUnits < totalUnits - 1 ? processedUnits : totalUnits - 1);
                        }
                    }
                }
            });
        }
    }
    handle.setInitialDelay(0);
    panel.waitAndSetProgressComponents(mainLabel, progressComponent, detailLabel);
    if (spareHandle != null && spareHandleStarted) {
        spareHandle.finish();
    }
    Installer tmpInst;
    try {
        tmpInst = support.doValidate(v, handle);
        if (tmpInst == null)
            return null;
    } catch (OperationException ex) {
        log.log(Level.INFO, ex.getMessage(), ex);
        ProblemPanel problem = new ProblemPanel(ex, detailLabel.getText(), false);
        if (ex.getErrorType() == OperationException.ERROR_TYPE.MODIFIED) {
            problem.showModifiedProblemDialog(detailLabel.getText());
        } else {
            problem.showNetworkProblemDialog();
        }
        handleCancel();
        return null;
    }
    final Installer inst = tmpInst;
    List<UpdateElement> signedVerified = new ArrayList<UpdateElement>();
    List<UpdateElement> signedUnverified = new ArrayList<UpdateElement>();
    List<UpdateElement> unsigned = new ArrayList<UpdateElement>();
    List<UpdateElement> modified = new ArrayList<UpdateElement>();
    int trustedCount = 0;
    Map<Object, String> certs = new HashMap<>();
    for (UpdateElement el : model.getAllUpdateElements()) {
        boolean writeCert = false;
        if (support.isContentModified(inst, el)) {
            modified.add(el);
            continue;
        } else if (support.isTrusted(inst, el)) {
            trustedCount++;
            continue;
        } else if (support.isSignedVerified(inst, el)) {
            signedVerified.add(el);
            writeCert = true;
        } else if (support.isSignedUnverified(inst, el)) {
            signedUnverified.add(el);
            writeCert = true;
        } else {
            unsigned.add(el);
        }
        if (writeCert) {
            String cert = support.getCertificate(inst, el);
            if (cert != null && cert.length() > 0) {
                certs.put(el.getDisplayName(), cert);
            }
        }
    }
    if (signedVerified.size() > 0 || signedUnverified.size() > 0 || unsigned.size() > 0 || modified.size() > 0 && !runInBackground()) {
        int total = trustedCount + signedVerified.size() + signedUnverified.size() + unsigned.size();
        final ValidationWarningPanel p = new ValidationWarningPanel(signedVerified, signedUnverified, unsigned, modified, total);
        final boolean verifyCertificate = (!signedVerified.isEmpty() || !signedUnverified.isEmpty()) && !certs.isEmpty();
        JButton[] options;
        JButton[] closeOptions;
        final JButton cancel = model.getCancelButton(wd);
        DialogDescriptor dd = new DialogDescriptor(p, verifyCertificate ? getBundle("ValidationWarningPanel_VerifyCertificate_Title") : getBundle("ValidationWarningPanel_Title"));
        JButton canContinue = new JButton();
        canContinue.setDefaultCapable(false);
        if (modified.isEmpty()) {
            final JButton showDetails = new JButton();
            Mnemonics.setLocalizedText(showDetails, getBundle("ValidationWarningPanel_ShowDetailsButton"));
            final Map<Object, String> certsMap = certs;
            showDetails.setEnabled(false);
            p.addSelectionListener(new TreeSelectionListener() {

                @Override
                public void valueChanged(TreeSelectionEvent e) {
                    if (e.getNewLeadSelectionPath().getPathCount() == 3 && certsMap.containsKey(p.getSelectedNode())) {
                        showDetails.setEnabled(true);
                    } else {
                        showDetails.setEnabled(false);
                    }
                }
            });
            showDetails.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    if (showDetails.equals(e.getSource())) {
                        Object node = p.getSelectedNode();
                        if (certsMap.containsKey(node)) {
                            JTextArea ta = new JTextArea(certsMap.get(node));
                            ta.setEditable(false);
                            DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(ta));
                        }
                    }
                }
            });
            Mnemonics.setLocalizedText(canContinue, getBundle("ValidationWarningPanel_ContinueButton"));
            if (verifyCertificate) {
                dd.setAdditionalOptions(new JButton[] { showDetails });
            }
            options = new JButton[] { canContinue, cancel };
            closeOptions = new JButton[] { canContinue, cancel };
        } else {
            options = new JButton[] { cancel };
            closeOptions = new JButton[] { cancel };
        }
        dd.setOptions(options);
        dd.setClosingOptions(closeOptions);
        dd.setMessageType(NotifyDescriptor.WARNING_MESSAGE);
        final Dialog dlg = DialogDisplayer.getDefault().createDialog(dd);
        JDialog jdlg = (JDialog) dlg;
        jdlg.getRootPane().setDefaultButton(cancel);
        try {
            SwingUtilities.invokeAndWait(new Runnable() {

                @Override
                public void run() {
                    dlg.setVisible(true);
                }
            });
        } catch (InterruptedException ex) {
            log.log(Level.INFO, ex.getLocalizedMessage(), ex);
            return null;
        } catch (InvocationTargetException ex) {
            log.log(Level.INFO, ex.getLocalizedMessage(), ex);
            return null;
        }
        if (!canContinue.equals(dd.getValue())) {
            if (!cancel.equals(dd.getValue())) {
                cancel.doClick();
            }
            return null;
        }
        assert canContinue.equals(dd.getValue());
    }
    panel.waitAndSetProgressComponents(mainLabel, progressComponent, new JLabel(getBundle("InstallStep_Done")));
    return inst;
}
Also used : JTextArea(javax.swing.JTextArea) PropertyChangeListener(java.beans.PropertyChangeListener) UpdateElement(org.netbeans.api.autoupdate.UpdateElement) Installer(org.netbeans.api.autoupdate.InstallSupport.Installer) HashMap(java.util.HashMap) Cancellable(org.openide.util.Cancellable) ActionEvent(java.awt.event.ActionEvent) ArrayList(java.util.ArrayList) JButton(javax.swing.JButton) ProblemPanel(org.netbeans.modules.autoupdate.ui.ProblemPanel) TreeSelectionListener(javax.swing.event.TreeSelectionListener) JDialog(javax.swing.JDialog) Dialog(java.awt.Dialog) OperationException(org.netbeans.api.autoupdate.OperationException) PropertyChangeEvent(java.beans.PropertyChangeEvent) JComponent(javax.swing.JComponent) JLabel(javax.swing.JLabel) InvocationTargetException(java.lang.reflect.InvocationTargetException) ProgressHandle(org.netbeans.api.progress.ProgressHandle) ActionListener(java.awt.event.ActionListener) DialogDescriptor(org.openide.DialogDescriptor) TreeSelectionEvent(javax.swing.event.TreeSelectionEvent) JDialog(javax.swing.JDialog)

Example 4 with Cancellable

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

the class RequestProcessor180386Test method testCancellablesThatSayTheyCantBeCancelledAreNotCancelledViaFutureDotCancel.

public void testCancellablesThatSayTheyCantBeCancelledAreNotCancelledViaFutureDotCancel() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    final CountDownLatch exit = new CountDownLatch(1);
    class C implements Runnable, Cancellable {

        volatile boolean hasRun;

        volatile boolean interrupted;

        volatile boolean cancelCalled;

        @Override
        public void run() {
            try {
                try {
                    latch.await();
                } catch (InterruptedException e) {
                    interrupted = true;
                    throw new AssertionError(e);
                }
                if (Thread.interrupted()) {
                    interrupted = true;
                    throw new AssertionError("Thread should not have been interrupted");
                }
                hasRun = true;
            } finally {
                exit.countDown();
            }
        }

        @Override
        public boolean cancel() {
            cancelCalled = true;
            return false;
        }
    }
    C c = new C();
    Future<?> f = RequestProcessor.getDefault().submit(c);
    f.cancel(true);
    assertFalse(f.isCancelled());
    assertTrue(c.cancelCalled);
    latch.countDown();
    exit.await();
    f.get();
    assertFalse(f.isCancelled());
    assertTrue(c.hasRun);
}
Also used : Cancellable(org.openide.util.Cancellable) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 5 with Cancellable

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

the class RequestProcessor180386Test method testCancellablesGetCancelInvokedWithCallable.

public void testCancellablesGetCancelInvokedWithCallable() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    final CountDownLatch exit = new CountDownLatch(1);
    class C implements Callable<String>, Cancellable {

        volatile boolean hasRun;

        volatile boolean interrupted;

        volatile boolean cancelled;

        @Override
        public String call() throws Exception {
            try {
                try {
                    latch.await();
                } catch (InterruptedException e) {
                    interrupted = true;
                    return null;
                }
                if (Thread.interrupted()) {
                    interrupted = true;
                    return null;
                }
                if (cancelled) {
                    return null;
                }
                hasRun = true;
                return "Hello";
            } finally {
                exit.countDown();
            }
        }

        @Override
        public boolean cancel() {
            cancelled = true;
            exit.countDown();
            return true;
        }
    }
    C c = new C();
    Future<String> f = RequestProcessor.getDefault().submit(c);
    f.cancel(true);
    assertTrue(c.cancelled);
    latch.countDown();
    exit.await();
    String s = null;
    try {
        s = f.get();
        fail("Should have gotten cancellation exception");
    } catch (CancellationException e) {
    }
}
Also used : CancellationException(java.util.concurrent.CancellationException) Cancellable(org.openide.util.Cancellable) CountDownLatch(java.util.concurrent.CountDownLatch) Callable(java.util.concurrent.Callable)

Aggregations

Cancellable (org.openide.util.Cancellable)7 CountDownLatch (java.util.concurrent.CountDownLatch)4 ProgressHandle (org.netbeans.api.progress.ProgressHandle)3 PropertyChangeEvent (java.beans.PropertyChangeEvent)2 PropertyChangeListener (java.beans.PropertyChangeListener)2 ArrayList (java.util.ArrayList)2 Callable (java.util.concurrent.Callable)2 CancellationException (java.util.concurrent.CancellationException)2 JButton (javax.swing.JButton)2 JComponent (javax.swing.JComponent)2 JLabel (javax.swing.JLabel)2 OperationException (org.netbeans.api.autoupdate.OperationException)2 UpdateElement (org.netbeans.api.autoupdate.UpdateElement)2 ProblemPanel (org.netbeans.modules.autoupdate.ui.ProblemPanel)2 Dialog (java.awt.Dialog)1 ActionEvent (java.awt.event.ActionEvent)1 ActionListener (java.awt.event.ActionListener)1 IOException (java.io.IOException)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 HashMap (java.util.HashMap)1