Java Code Examples for org.openide.util.RequestProcessor#post()

The following examples show how to use org.openide.util.RequestProcessor#post() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ClickableIcon.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void invokeAction() {
    final boolean suspended = isThreadSupended;
    RequestProcessor rp;
    try {
        Session s = dvThread.getDVSupport().getSession();
        rp = s.lookupFirst(null, RequestProcessor.class);
    } catch (Exception e) {
        Exceptions.printStackTrace(e);
        return ;
    }
    if (rp == null) {
        // debugger finishing?
        rp = RequestProcessor.getDefault();
    }
    rp.post(new Runnable() {
        public void run() {
            if (suspended) {
                dvThread.resume();
            } else {
                dvThread.suspend();
            }
        }
    });
    isThreadSupended = !isThreadSupended;
}
 
Example 2
Source File: InfoPanel.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void stepBrkpIgnoreButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stepBrkpIgnoreButtonActionPerformed
    if (stepBrkpDVSupportRef != null) {
        final DVSupport ds = stepBrkpDVSupportRef.get();
        if (ds != null) {
            RequestProcessor rp = getRP(ds);
            if (rp == null) {
                return ;
            }
            rp.post(new Runnable() {
                @Override
                public void run() {
                    try {
                        ds.resume();
                    } catch (Exception ex) {
                        Exceptions.printStackTrace(ex);
                    }
                }
            });
        }
    }
}
 
Example 3
Source File: Mercurial.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void asyncInit() {
    gotVersion = false;
    RequestProcessor rp = getRequestProcessor();
    if (LOG.isLoggable(Level.FINEST)) {
        LOG.log(Level.FINEST, "Mercurial subsystem initialized", new Exception()); //NOI18N
    }
    Runnable init = new Runnable() {
        @Override
        public void run() {
            HgKenaiAccessor.getInstance().registerVCSNoficationListener();
            synchronized(Mercurial.this) {
                checkVersionIntern();
            }
        }

    };
    rp.post(init);
}
 
Example 4
Source File: JmxHeartbeat.java    From visualvm with GNU General Public License v2.0 6 votes vote down vote up
protected final void pingApps(Collection<JmxApplication> applications) {
        int count = applications.size();
        
//        System.err.println(">>> " + id + " Heartbeat for " + count + " targets at " + java.time.LocalTime.now() + ": " + applications);
        
        final AtomicInteger counter = new AtomicInteger(count);
        final Collection<JmxApplication> unresolved = Collections.synchronizedList(new ArrayList());
        RequestProcessor processor = new RequestProcessor("JMX " + id + " Heartbeat Processor", Math.min(count, MAX_HEARTBEAT_THREADS)); // NOI18N
        
        for (final JmxApplication app : applications) {
            processor.post(new Runnable() {
                @Override
                public void run() {
                    try {
                        if (!app.tryConnect()) unresolved.add(app);
                    } finally {
                        if (counter.decrementAndGet() == 0) pingFinished(unresolved.toArray(new JmxApplication[0]));
                    }
                }
            }, delay);
        }
    }
 
Example 5
Source File: InfoPanel.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void resumeDebuggerDeadlockButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_resumeDebuggerDeadlockButtonActionPerformed
    //final List<DVThread> threadsToResume = debuggerDeadlockThreads;
    final DVThread blockedThread = debuggerDeadlockThread;
    RequestProcessor rp;
    try {
        DVSupport debugger = blockedThread.getDVSupport();
        rp = getRP(debugger);
        if (rp == null) {
            return ;
        }
    } catch (Exception e) {
        Exceptions.printStackTrace(e);
        return ;
    }
    rp.post(new Runnable() {
        public void run() {
            blockedThread.resumeBlockingThreads();
            //resumeThreadToFreeMonitor(blockedThread);
        }
    });
    hideDebuggerDeadlockPanel();
}
 
Example 6
Source File: MavenTestNGSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@NbBundle.Messages("remove_junit3_when_adding_testng=Removing JUnit 3.x dependency as TestNG has transitive dependency to JUnit 4.x.")
public void configureProject(FileObject createdFile) {
    ClassPath cp = ClassPath.getClassPath(createdFile, ClassPath.COMPILE);
    FileObject ng = cp.findResource("org.testng.annotations.Test"); //NOI18N
    if (ng == null) {
        final Project p = FileOwnerQuery.getOwner(createdFile);
        FileObject pom = p.getProjectDirectory().getFileObject("pom.xml"); //NOI18N
        ModelOperation<POMModel> operation = new ModelOperation<POMModel>() {
            public @Override
            void performOperation(POMModel model) {
                String groupID = "org.testng"; //NOI18N
                String artifactID = "testng"; //NOI18N
                if (!hasEffectiveDependency(groupID, artifactID, p.getLookup().lookup(NbMavenProject.class))) {
                    fixJUnitDependency(model, p.getLookup().lookup(NbMavenProject.class));
                    Dependency dep = ModelUtils.checkModelDependency(model, groupID, artifactID, true);
                    dep.setVersion("6.8.1"); //NOI18N
                    dep.setScope("test"); //NOI18N
                }
            }
        };
        Utilities.performPOMModelOperations(pom, Collections.singletonList(operation));
        RequestProcessor RP = new RequestProcessor("Configure TestNG project task", 1, true); //NOI18N
        RP.post(new Runnable() {

            public void run() {
                p.getLookup().lookup(NbMavenProject.class).downloadDependencyAndJavadocSource(true);
            }
        });
    }
}
 
Example 7
Source File: JavaViewHierarchyRandomTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testParralelMods() throws Exception {
        loggingOn();
        RandomTestContainer container = createContainer();
        JEditorPane pane = container.getInstance(JEditorPane.class);
        final Document doc = pane.getDocument();
        doc.putProperty("mimeType", "text/x-java");
        final RandomTestContainer.Context context = container.context();
        DocumentTesting.setSameThreadInvoke(context, true); // Do not post to EDT
        // (Done automatically) Logger.getLogger("org.netbeans.editor.BaseDocument.EDT").setLevel(Level.OFF);
//        ViewHierarchyRandomTesting.disableHighlighting(container);
        int opCount = 100;
        final int throughput = 5; // How many truly parallel invocations
        RequestProcessor rp = new RequestProcessor("Doc-Mod", throughput, false, false);
        Task task = null;
        for (int i = opCount - 1; i >= 0; i--) {
            task = rp.post(new Runnable() {
                @Override
                public void run() {
                    // make sure insert won't fail for multiple threads
                    int offset = Math.max(doc.getLength() - throughput, 0);
                    try {
                        DocumentTesting.insert(context, offset, "ab");
                        DocumentTesting.remove(context, offset, 1);
                    } catch (Exception ex) {
                        throw new IllegalStateException(ex);
                    }
                }
            });
        }
        task.waitFinished();
    }
 
Example 8
Source File: Hk2WSChildren.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void updateKeys(){
    setKeys(new Object[] { WAIT_NODE });
    
    RequestProcessor t = new RequestProcessor("ws-child-updater"); // NOI18N
    t.post(new Runnable() {
        Vector<Object> keys = new Vector<Object>();
        
        @Override
        public void run() {
            CommonServerSupport commonSupport = lookup.lookup(
                    CommonServerSupport.class);
            if(commonSupport != null) {
                try {
                    List<WSDesc> wsList
                            = WSDesc.getWebServices(commonSupport.getInstance());
                    for(WSDesc ws: wsList) {
                        keys.add(new Hk2WSNode(lookup, ws, Hk2ItemNode.WS_ENDPOINT));
                    }
                } catch (Exception ex) {
                    Logger.getLogger("payara").log(Level.INFO, ex.getLocalizedMessage(), ex); // NOI18N
                }
                
                setKeys(keys);
            }
        }
    }, 0);
}
 
Example 9
Source File: GitProgressSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public RequestProcessor.Task start (RequestProcessor rp, File repositoryRoot, String displayName) {
    this.error = false;
    this.originalDisplayName = displayName;
    setDisplayName(displayName);
    this.repositoryRoot = repositoryRoot;
    startProgress();
    setProgressQueued();
    task = rp.post(this);
    return task;
}
 
Example 10
Source File: RequestProcessorTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testUseAsInCND() throws Exception {
    final RequestProcessor processor = new RequestProcessor("testUseAsInCND");
    final AtomicReference<String> threadName = new AtomicReference<String>();
    final Runnable task = new Runnable() {
        @Override
        public void run() {
            threadName.set(Thread.currentThread().getName());
        }
    };
    final String taskName = "MyTask";
    final RequestProcessor.Task rpTask = processor.create(new Runnable() {
        @Override
        public void run() {
            String oldName = Thread.currentThread().getName();
            Thread.currentThread().setName(taskName);
            try {
                task.run();
            } finally {
                Thread.currentThread().setName(oldName);
            }
        }
    });
    processor.post(rpTask);
    rpTask.waitFinished();
    
    assertEquals("Executed and named OK", taskName, threadName.get());
}
 
Example 11
Source File: ExportAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void performExport(final Export export, final RequestProcessor rp, final Node[] nodes, final File[] roots) {
    rp.post(new Runnable() {
        @Override
        public void run() {
            ContextAction.ProgressSupport support = new ContextAction.ProgressSupport(ExportAction.this, nodes) {
                @Override
                public void perform() {
                    File fromFile = export.getFromFile();
                    File toFile = export.getToFile();
                    toFile.mkdir();
                    if(isCanceled()) {
                        return;
                    }

                    SvnClient client;
                    try {
                        client = Subversion.getInstance().getClient(fromFile);
                        client.doExport (fromFile, toFile, true);
                    } catch (SVNClientException ex) {
                        SvnClientExceptionHandler.notifyException(ex, true, true); // should not happen
                        return;
                    }
                    if(export.getScanAfterExport()) {
                        CheckoutCompleted cc = new CheckoutCompleted(toFile, new String[] {"."});
                        if (isCanceled()) {
                            return;
                        }
                        cc.scanForProjects(this, CheckoutCompleted.Type.EXPORT);
                    }
                }
            };
            support.start(rp);
        }
    });
}
 
Example 12
Source File: Hk2ApplicationsChildren.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void updateKeys(){
    setKeys(new Object[] { WAIT_NODE });
    
    RequestProcessor t = new RequestProcessor("app-child-updater");
    t.post(new Runnable() {
        Vector<Object> keys = new Vector<Object>();
        
        @Override
        public void run() {
            CommonServerSupport commonSupport = lookup.lookup(
                    CommonServerSupport.class);
            if(commonSupport != null) {
                try {
                    java.util.Map<String, List<AppDesc>> appMap
                            = commonSupport.getApplications(null);
                    for(Entry<String, List<AppDesc>> entry: appMap.entrySet()) {
                        List<AppDesc> apps = entry.getValue();
                        for(AppDesc app: apps) {
                            keys.add(new Hk2ApplicationNode(lookup, app, DecoratorManager.findDecorator(entry.getKey(), Hk2ItemNode.J2EE_APPLICATION, app.getEnabled())));
                        }
                    }
                } catch (Exception ex) {
                    Logger.getLogger("payara").log(Level.INFO, ex.getLocalizedMessage(), ex);
                }
                
                setKeys(keys);
            }
        }
    }, 0);
}
 
Example 13
Source File: RequestProcessorTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testTheCancelOfRunningTask() throws InterruptedException {
    final CountDownLatch started = new CountDownLatch(1);
    final CountDownLatch allowedToFinish = new CountDownLatch(1);
    Counter x = new Counter () {
        @Override
        public void run() {
            started.countDown();
            super.run();
            for (;;) try {
                allowedToFinish.await();
                break;
            } catch (InterruptedException ex) {
                continue;
            }
        }
    };
    RequestProcessor rp = new RequestProcessor ("testTheCancelOfRunningTask");
    final RequestProcessor.Task task = rp.post(x);
    started.await();
    assertFalse("Finished", task.isFinished());
    assertFalse("Too late to cancel", task.cancel());
    allowedToFinish.countDown();
    assertFalse("nothing to cancel", task.cancel());
    task.waitFinished();
    assertTrue("Now it is finished", task.isFinished());
    assertFalse("Still nothing to cancel", task.cancel());
}
 
Example 14
Source File: RequestProcessorTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Test to check the waiting in request processor.
*/
public void testWaitFinishedOnNotStartedTaskFromRPThread () throws Exception {
    Counter x = new Counter ();
    RequestProcessor rp = new RequestProcessor ("testWaitFinishedOnNotStartedTaskFromRPThread");
    final RequestProcessor.Task task = rp.post(x, Integer.MAX_VALUE);
    
    //
    // Following code tests whether the RP.create().waitFinished really blocks
    // until somebody schedules the task.
    //
    class WaitTask implements Runnable {
        public boolean finished;
        
        public synchronized void run () {
            task.waitFinished ();
            finished = true;
            notifyAll ();
        }
        
        public synchronized void w (int timeOut) throws Exception {
            if (!finished) {
                wait (timeOut);
            }
        }
    }
    WaitTask wt = new WaitTask ();
    rp.post (wt);
    wt.w (0);
    assertTrue ("The task.waitFinished has to finish, otherwise the RequestProcessor thread will stay occupied forever", wt.finished);
    x.assertCnt ("The task has been executed - wait from RP made it start", 1);
}
 
Example 15
Source File: SingleThreadLoadsDeadlockTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testOSGiCanRequireBundleOnNetBeans() throws Throwable {
    MockModuleInstaller installer = new MockModuleInstaller();
    MockEvents ev = new MockEvents();
    ModuleManager mgr = new ModuleManager(installer, ev);
    
    
    mgr.mutexPrivileged().enterWriteAccess();
    HashSet<Module> all = null;
    try {
        Module mBottom = mgr.create(bottom, null, false, false, false);
        Module mMiddle = mgr.create(middle, null, false, false, false);
        final Module mTop = mgr.create(top, null, false, false, false);
        
        HashSet<Module> b = new HashSet<Module>(Arrays.asList(mBottom, mMiddle, mTop));
        mgr.enable(b);
        all = b;
        
        String order = 
            "THREAD: Load3 MSG: Loaded.*org/load3/Load.class\n"
          + "THREAD: Test Watch Dog: testOSGiCanRequireBundleOnNetBeans MSG: Loading 2\n";
        
        Logger messages = Logger.getLogger("org.netbeans.modules.netbinox");
        Log.controlFlow(messages, LOG, order, 500);
        
        final Throwable[] exArr = { null };
        final Class[] classTop = { null };
        RequestProcessor RP = new RequestProcessor("Load3");
        
        Task task = RP.post(new Runnable() {
                 @Override
                 public void run() {
                     LOG.info("Loading 3");
                     try {
                         classTop[0] = Class.forName("org.load3.Load", true, mTop.getClassLoader());
                     } catch (Throwable ex) {
                         exArr[0] = ex;
                         LOG.info("ClassNotFoundException while loading 3");
                     }
                     LOG.info("Loading 3 done");
                 }
             });

        Thread.yield();
        
        LOG.info("Loading 2");
        Class<?> classMiddle = Class.forName("org.load2.Load", true, mMiddle.getClassLoader());
        LOG.info("Loading 2 is done");
        
        task.waitFinished();
        if (exArr[0] != null) {
            throw exArr[0];
        }
        assertNotNull("All classes loaded", classTop[0]);
    } finally {
        if (all != null) {
            mgr.disable(all);
        }
        mgr.mutexPrivileged().exitWriteAccess();
    }
}
 
Example 16
Source File: RequestProcessorHrebejkBugTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testBug() throws Exception {
    RequestProcessor rp = new RequestProcessor("TestProcessor", 3, true); 
    
    R1 r1 = new R1();
    R2 r2 = new R2(r1);
    
    r1.submit(rp);

    r1.in.await();
    
    RequestProcessor.Task t = rp.post(r2);
    
    r1.goOn.countDown();
    
    t.waitFinished(); 
    
    if (r1.count != 1) {
        throw r1.wrong;
    }
}
 
Example 17
Source File: AbstractJSToolTipAnnotation.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public String getShortDescription () {
    final Session session = DebuggerManager.getDebuggerManager ().getCurrentSession();
    if (session == null) {
        return null;
    }
    final DebuggerEngine engine = session.getCurrentEngine();
    if (engine == null) {
        return null;
    }

    final Line.Part lp = (Line.Part) getAttachedAnnotatable();
    if (lp == null) {
        return null;
    }
    Line line = lp.getLine ();
    DataObject dob = DataEditorSupport.findDataObject (line);
    if (dob == null) {
        return null;
    }
    final EditorCookie ec = dob.getLookup().lookup(EditorCookie.class);
    if (ec == null) {
        return null;
        // Only for editable dataobjects
    }

    Runnable runnable = new Runnable() {

        @Override
        public void run() {
            evaluate(session, engine/*, dbg*/, lp, ec);
        }
    };
    RequestProcessor rp = engine.lookupFirst(null, RequestProcessor.class);
    if (rp == null) {
        // Debugger is likely finishing...
        rp = RP;
    }
    rp.post(runnable);
    return null;
}
 
Example 18
Source File: Utils.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public static Task postParallel (Runnable runnable) {
    RequestProcessor rp = getParallelRequestProcessor();
    return rp.post(runnable);
}
 
Example 19
Source File: RequestProcessorTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testInterruptedStatusIsClearedBetweenTwoTaskExecution () throws Exception {
    RequestProcessor rp = new RequestProcessor ("testInterruptedStatusIsClearedBetweenTwoTaskExecution", 1, true);
    
    final RequestProcessor.Task[] task = new RequestProcessor.Task[1];
    // test interrupted status is cleared after task ends
    class Fail implements Runnable {
        public boolean checkBefore;
        public Thread runIn;
        public boolean goodThread;
        
        public synchronized void run () {
            if (runIn == null) {
                runIn = Thread.currentThread();
                task[0].schedule (0);
                
                // wait to make sure the task is scheduled
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            } else {
                goodThread = Thread.currentThread () == runIn;
            }
                
            checkBefore = runIn.isInterrupted();
            // set the flag for next execution
            runIn.interrupt();
            
            notifyAll ();
        }
    }
    
    Fail f = new Fail ();
    synchronized (f) {
        task[0] = rp.post (f);
        
        // wait for the first execution
        f.wait ();
    }
    // wait for the second
    task[0].waitFinished ();
    
    /* Shall be true, but sometimes the threads get GCed, so we cannot really check that.
    assertTrue ("This shall be always true, but if not, than it does not mean too much"
        + " just that the tasks were not executed in the same thread. In such case it "
        + " this test does not do anything useful as it needs to execute the task twice "
        + " in the same thread", f.goodThread);
    */
    
    if (f.goodThread) {
        assertTrue ("Interrupted state has been cleared between two executions of the task", !f.checkBefore);
    }
}
 
Example 20
Source File: CurrentThreadAnnotationListener.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Annotates current thread or removes annotations.
 */
private void annotate () {
    // 1) no current thread => remove annotations
    final JPDADebugger debugger;
    final SourcePath sourcePath;
    final JPDAThread thread;
    synchronized (this) {
        debugger = currentDebugger;
        if ( (currentThread == null) ||
             (debugger.getState () != JPDADebugger.STATE_STOPPED) ) {
            synchronized (currentPCLock) {
                currentPCSet = false; // The annotation is goint to be removed
            }
            removeAnnotations ();
            return;
        }

        sourcePath = currentSourcePath;
        thread = currentThread;
    }
    Session s;
    try {
        s = (Session) debugger.getClass().getMethod("getSession").invoke(debugger);
    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
        s = null;
    }
    RequestProcessor rProcessor = null;
    if (s != null) {
        rProcessor = s.lookupFirst(null, RequestProcessor.class);
    }
    if (rProcessor == null) {
        rProcessor = this.rp;
    }
    rProcessor.post(new Runnable() {
        @Override
        public void run() {
            annotate(debugger, thread, sourcePath);
        }
    });
}