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

The following examples show how to use org.openide.util.RequestProcessor#create() . 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: RequestProcessorTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testStopAndSchedule() throws Exception {
    final boolean executed[] = { false };
    class R implements Runnable {
        @Override
        public void run() {
            executed[0] = true;
        }
    }
    
    RequestProcessor rp = new RequestProcessor("stopped");
    RequestProcessor.Task task = rp.create(new R());
    assertTrue("No runnables", rp.shutdownNow().isEmpty());
    task.schedule(0);
    task.waitFinished(500);
    assertFalse("Not executed at all", executed[0]);
}
 
Example 2
Source File: RequestProcessorTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void doCheckFinished(boolean usefalse) {
        RequestProcessor rp = new RequestProcessor ("Finish");

class R extends Object implements Runnable {
    RequestProcessor.Task t;
    
    public void run () {
        if (t.isFinished ()) {
            fail ("Finished when running");
        }
    }
}
        
        R r = new R ();
        RequestProcessor.Task task = usefalse ? rp.create(r, false) : rp.create (r);
        r.t = task;

        if (task.isFinished ()) {
            fail ("Finished after creation");
        }
     
        doCommonTestWithScheduling(task);
    }
 
Example 3
Source File: RequestProcessorTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testCheckFinishedWithTrue () {
    RequestProcessor rp = new RequestProcessor ("Finish");
    
    class R extends Object implements Runnable {
        RequestProcessor.Task t;
        
        public void run () {
            if (t.isFinished ()) {
                fail ("Finished when running");
            }
        }
    }
    
    R r = new R ();
    RequestProcessor.Task task = rp.create(r, true);
    r.t = task;

    assertTrue("It has to be finished after creation", task.isFinished());

    task.waitFinished();

    // rest is the same
    doCommonTestWithScheduling(task);
}
 
Example 4
Source File: Annotations.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private JMenu createMenu(BaseKit kit, int line, boolean backgroundInit){
    final DelayedMenu pm = new DelayedMenu(NbBundle.getBundle(BaseKit.class).getString("generate-gutter-popup"));
    final BaseKit fKit = kit;
    final int fLine = line;

    if (backgroundInit){
        RequestProcessor rp = RequestProcessor.getDefault();
        RequestProcessor.Task task = rp.create(new Runnable(){
            public void run(){
                initMenu(pm, fKit, fLine);
                pm.clearTask(); // clear the finished task reference to avoid leaking
            }
        });
        pm.setTask(task); // set before task execution so that always cleaned properly
        task.schedule(0);
    }else{
        initMenu(pm, fKit, fLine);
    }

    return pm;
}
 
Example 5
Source File: ProjectChooserAccessory.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** Creates new form ProjectChooserAccessory */
public ProjectChooserAccessory(JFileChooser chooser, boolean isOpenSubprojects) {
    initComponents();

    modelUpdater = new ModelUpdater();
    //#98080
    RP = new RequestProcessor(ModelUpdater.class.getName(), 1);
    RP2 = new RequestProcessor(ModelUpdater.class.getName(), 1);
    updateSubprojectsTask = RP.create(modelUpdater);
    updateSubprojectsTask.setPriority( Thread.MIN_PRIORITY );

    // Listen on the subproject checkbox to change the option accordingly
    jCheckBoxSubprojects.setSelected( isOpenSubprojects );
    jCheckBoxSubprojects.addActionListener( this );

    // Listen on the chooser to update the Accessory
    chooser.addPropertyChangeListener( this );

    // Set default list model for the subprojects list
    jListSubprojects.setModel( new DefaultListModel() );

    // Disable the Accessory. JFileChooser does not select a file
    // by default
    setAccessoryEnablement( false, 0 );
}
 
Example 6
Source File: TestMethodDebuggerAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void performAction(final Node[] activatedNodes) {
    final Collection<? extends TestMethodDebuggerProvider> providers = Lookup.getDefault().lookupAll(TestMethodDebuggerProvider.class);
    RequestProcessor RP = new RequestProcessor("TestMethodDebuggerAction", 1, true);   // NOI18N
    debugMethodTask = RP.create(new Runnable() {
        @Override
        public void run() {
            for (TestMethodDebuggerProvider provider : providers) {
                if (provider.canHandle(activatedNodes[0])) {
                    debugMethodProvider = provider;
                    break;
                }
            }
        }
    });
    final ProgressHandle ph = ProgressHandleFactory.createHandle(Bundle.Search_For_Provider(), debugMethodTask);
    debugMethodTask.addTaskListener(new TaskListener() {
        @Override
        public void taskFinished(org.openide.util.Task task) {
            ph.finish();
            if (debugMethodProvider == null) {
                StatusDisplayer.getDefault().setStatusText(Bundle.No_Provider_Found());
            } else {
                debugMethodProvider.debugTestMethod(activatedNodes[0]);
            }
        }
    });
    ph.start();
    debugMethodTask.schedule(0);
}
 
Example 7
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 8
Source File: RequestProcessorTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testTheCancelOfFutureTask() {
    Counter x = new Counter ();
    RequestProcessor rp = new RequestProcessor ("testTheCancelOfFutureTask");
    final RequestProcessor.Task task = rp.create (x);
    task.schedule(20000);
    assertTrue("Sure, that one can be cancelled", task.cancel());
    assertTrue("After cancle we are finished", task.isFinished());
    assertFalse("Can be cancelled only once", task.cancel());
}
 
Example 9
Source File: RequestProcessorTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testWhenWaitingForALimitedTimeFromTheSameProcessorThenInterruptedExceptionIsThrownImmediatelly () throws Exception {
    Counter x = new Counter ();
    RequestProcessor rp = new RequestProcessor ("testWaitFinishedOnNotStartedTaskFromRPThread");
    final RequestProcessor.Task task = rp.create (x);
    
    class WaitTask implements Runnable {
        public boolean finished;
        
        public synchronized void run () {
            long time = System.currentTimeMillis ();
            try {
                task.waitFinished (1000);
                fail ("This should throw an exception. Btw time was: " + (System.currentTimeMillis () - time));
            } catch (InterruptedException ex) {
                // ok, this is expected
            } finally {
                time = System.currentTimeMillis () - time;
                notifyAll ();
            }
            if (time > 100) {
                fail ("Exception should be thrown quickly. Was: " + time);
            }
            finished = true;
        }
        
    }
    WaitTask wt = new WaitTask ();
    synchronized (wt) {
        rp.post (wt);
        wt.wait ();
    }
    assertTrue ("The task.waitFinished has to finish", wt.finished);
    x.assertCnt ("The task has NOT been executed", 0);
}
 
Example 10
Source File: DocumentModel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
DocumentModel(Document doc, DocumentModelProvider provider) throws DocumentModelException {
    this.doc = (BaseDocument)doc; //type changed in DocumentModel.getDocumentModel(document);
    this.provider = provider;
    
    //init RP & RP task
    requestProcessor = new RequestProcessor(DocumentModel.class.getName());
    task = requestProcessor.create(new Runnable() {
        public void run() {
            updateModel();
        }
    });
    
    //create a new root element - this element comprises the entire document
    addRootElement();
    
    /*create a sorted set which sorts its elements according to their
    startoffsets and endoffsets.
    - lets have elements E1 and E2:
     
    if E1.startOffset > E2.startOffset then the E1 is before E2.
    if E1.startOffset == E2.startOffset then
       if E1.endOffset > E2.endOffset then the E1 is before E2
     */
    initDocumentModel();
    
    this.changesWatcher = new DocumentChangesWatcher();
    getDocument().addDocumentListener(WeakListeners.document(changesWatcher, doc));
    
}
 
Example 11
Source File: NotificationsManager.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private NotificationsManager () {
    files = new HashSet<File>();
    rp = new RequestProcessor("SubversionNotifications", 1, true);  //NOI18N
    notificationTask = rp.create(new NotificationTask());
    cache = Subversion.getInstance().getStatusCache();
    kenaiAccessor = SvnKenaiAccessor.getInstance();
}
 
Example 12
Source File: RequestProcessorMemoryTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testRunOutOfMemory() throws Exception {
    RequestProcessor rp = new RequestProcessor("testRunOutOfMemory", 1, false, false);
    final int[] cnt = { 0 };
    RequestProcessor.Task task = rp.create(new Runnable() {
        @Override
        public void run() {
            cnt[0]++;
        }
    });
    for (int i = 0; i < 10000000; i++) {
        task.schedule(2000000);
    }
    assertEquals("Still zero", 0, cnt[0]);
}
 
Example 13
Source File: HintsTests.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected void waitHintsShown(FileObject fileToTest, int size) {
    final int delay = 1000;
    int repeat = 20;
    final Object lock = new Object();
    Runnable posted = new Runnable() {

        public void run() {
            synchronized (lock) {
                lock.notifyAll();
            }
        }
    };
    RequestProcessor RP = new RequestProcessor("TEST REQUEST PROCESSOR");
    final RequestProcessor.Task task = RP.create(posted);
    HintsHandler handl = new HintsHandler(delay, task);
    Logger logger = Logger.getLogger(AnnotationHolder.class.getName());
    logger.setLevel(Level.FINE);
    try {
        do {
            synchronized (lock) {
                task.schedule(delay);
                logger.addHandler(handl);
                lock.wait(repeat * delay);
            }
        } while ((repeat-- > 0) && (getFixes(fileToTest).size() < size));
    } catch (InterruptedException intExc) {
        throw new JemmyException("REFRESH DID NOT FINISHED IN " + repeat * delay + " SECONDS", intExc);
    } finally {
        logger.removeHandler(handl);
    }
}
 
Example 14
Source File: HudsonInstanceImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private HudsonInstanceImpl(HudsonInstanceProperties properties, boolean interactive, BuilderConnector builderConnector, Persistence persistence) {
    this.builderConnector = builderConnector;
    this.properties = properties;
    this.persistence = persistence != null ? persistence : Persistence.persistent();

    RP = new RequestProcessor(getUrl(), 1, true);
    final AtomicBoolean firstSynch = new AtomicBoolean(interactive); // #200643
    synchronization = RP.create(new Runnable() {
        private boolean firstRun = true;

        @Override
        public void run() {
            String s = getProperties().get(INSTANCE_SYNC);
            int pause = Integer.parseInt(s) * 60 * 1000;
            if (pause > 0 || firstSynch.compareAndSet(true, false)) {
                doSynchronize(false, firstRun);
                firstRun = false;
            }
            if (pause > 0) {
                synchronization.schedule(pause);
            }
        }
    });
    synchronization.schedule(0);
    this.properties.addPropertyChangeListener(new PropertyChangeListener() {
        @Override public void propertyChange(PropertyChangeEvent evt) {
            if (evt.getPropertyName().equals(INSTANCE_SYNC)) {
                synchronization.schedule(0);
            }
        }
    });
}
 
Example 15
Source File: RequestProcessorTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@RandomlyFails // NB-Core-Build #1211
public void testInterruptedStatusWorksInInversedTasksWhenInterruptedSoon() throws Exception {
    log.info("starting testInterruptedStatusWorksInInversedTasksWhenInterruptedSoon");
    RequestProcessor rp = new RequestProcessor ("testInterruptedStatusWorksInInversedTasksWhenInterruptedSoon", 1, true);
    log.info("rp created: " + rp);
    class Fail implements Runnable {
        public Fail(String n) {
            name = n;
        }
        
        private String name;
        public RequestProcessor.Task wait;
        public Object lock;
        
        public boolean checkBefore;
        public boolean checkAfter;
        
        public volatile boolean alreadyCanceled;
        
        public void run () {
            synchronized (this) {
                checkBefore = Thread.interrupted();
                log.info(name + " checkBefore: " + checkBefore);
                notifyAll();
            }
            if (lock != null) {
                synchronized (lock) {
                    lock.notify();
                }
            }
            
            if (wait != null) {
                // we cannot call Thread.sleep, so lets slow things own 
                // in other way

                log(name + " do waitFinished");
                wait.waitFinished();
                log(name + " waitFinished in task is over");
                
                log.info(name + " slowing by using System.gc");
                while (!alreadyCanceled) {
                    System.gc ();
                }
                log.info(name + " ended slowing");
                
            }
            
            synchronized (this) {
                checkAfter = Thread.interrupted();
                log.info(name + " checkAfter: " + checkAfter);
                notifyAll();
            }
        }
    }
    
    Object initLock = new Object();
    
    Fail smaller = new Fail("smaller");
    Fail bigger = new Fail("bigger");
    RequestProcessor.Task smallerTask, biggerTask;
    
    
    smallerTask = rp.create (smaller);
    biggerTask = rp.create (bigger);
    log.info("tasks created. small: " + smallerTask + " big: " + biggerTask);
    
    bigger.lock = initLock;
    bigger.wait = smallerTask;
    
    synchronized (initLock) {
        log.info("Do schedule");
        biggerTask.schedule(0);
        initLock.wait();
        log.info("do cancel");
        assertFalse ("Already running", biggerTask.cancel());
        bigger.alreadyCanceled = true;
        log.info("cancel done");
    }

    biggerTask.waitFinished();
    log.info("waitFinished is over");
    
    assertFalse("bigger not interrupted at begining", bigger.checkBefore);
    assertFalse("smaller not interrupted at all", smaller.checkBefore);
    assertFalse("smaller not interrupted at all2", smaller.checkAfter);
    assertTrue("bigger interrupted at end", bigger.checkAfter);
}
 
Example 16
Source File: TestMethodDebuggerProvider.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
    * Handle/Debug the selected test method
    * @param activatedNode the selected node
    */
   public final void debugTestMethod(Node activatedNode) {
       final Node activeNode = activatedNode;
       final Document doc;
       final int caret;

       final EditorCookie ec = activeNode.getLookup().lookup(EditorCookie.class);
       if (ec != null) {
           JEditorPane pane = Mutex.EVENT.readAccess(new Mutex.Action<JEditorPane>() {
	@Override
	public JEditorPane run() {
	    return NbDocument.findRecentEditorPane(ec);
	}
    });
           if (pane != null) {
               doc = pane.getDocument();
               caret = pane.getCaret().getDot();
           } else {
               doc = null;
               caret = -1;
           }
       } else {
           doc = null;
           caret = -1;
       }

       singleMethod = activeNode.getLookup().lookup(SingleMethod.class);
if (singleMethod == null) {
    RequestProcessor RP = new RequestProcessor("TestMethodDebuggerProvider", 1, true);   // NOI18N
    singleMethodTask = RP.create(new Runnable() {
	@Override
	public void run() {
	    singleMethod = getTestMethod(doc, caret);
	}
    });
    final ProgressHandle ph = ProgressHandleFactory.createHandle(Bundle.Search_For_Test_Method(), singleMethodTask);
    singleMethodTask.addTaskListener(new TaskListener() {
	@Override
	public void taskFinished(org.openide.util.Task task) {
	    ph.finish();
	    if (singleMethod == null) {
		StatusDisplayer.getDefault().setStatusText(Bundle.No_Test_Method_Found());
	    } else {
		Mutex.EVENT.readAccess(new Runnable() {
		    @Override
		    public void run() {
			ActionProvider ap = CommonUtils.getInstance().getActionProvider(singleMethod.getFile());
			if (ap != null) {
			    if (Arrays.asList(ap.getSupportedActions()).contains(command) && ap.isActionEnabled(command, Lookups.singleton(singleMethod))) {
				ap.invokeAction(command, Lookups.singleton(singleMethod));
			    }
			}
		    }
		});
	    }
	}
    });
    ph.start();
    singleMethodTask.schedule(0);
}
   }
 
Example 17
Source File: Utils.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public static Task createParallelTask (Runnable runnable) {
    RequestProcessor rp = getParallelRequestProcessor();
    return rp.create(runnable);
}
 
Example 18
Source File: RequestProcessorTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testInterruptedStatusWorksInInversedTasks() throws Exception {
    RequestProcessor rp = new RequestProcessor ("testInterruptedStatusWorksInInversedTasks", 1, true);
    
    class Fail implements Runnable {
        public Fail (String n) {
            name = n;
        }
        
        private String name;
        public RequestProcessor.Task wait;
        public Object lock;
        public Exception ex;

        public volatile boolean executed;
        public volatile boolean checkBefore;
        public volatile boolean checkAfter;
        
        @Override
        public void run () {
            synchronized (this) {
                executed = true;
                checkBefore = Thread.interrupted();
                log("checkBefore: " + checkBefore);
                notifyAll();
            }
            if (lock != null) {
                synchronized (lock) {
                    lock.notify();
                    try {
                        lock.wait();
                    } catch (InterruptedException interrex) {
                        this.ex = interrex;
                        interrex.printStackTrace();
                        fail ("No InterruptedException");
                    }
                    log.info("wait for lock over");
                }
            }
            
            if (wait != null) {
                wait.schedule(100);
                wait.waitFinished();
            }
            
            synchronized (this) {
                checkAfter = Thread.interrupted();
                log.info("checkAfter: " + checkAfter);
                notifyAll();
            }
        }
        
        @Override
        public String toString () {
            return name;
        }
    }
    
    Object initLock = new Object();
    
    Fail smaller = new Fail("smaller");
    smaller.lock = initLock;
    Fail bigger = new Fail("BIGGER");
    RequestProcessor.Task smallerTask, biggerTask;
    
    
    smallerTask = rp.create (smaller);
    biggerTask = rp.create (bigger);
    
    bigger.wait = smallerTask;
    
    synchronized (initLock) {
        log.info("schedule 0");
        biggerTask.schedule(0);
        initLock.wait();
        initLock.notifyAll();
        log.info("doing cancel");
        assertFalse ("Already running", biggerTask.cancel());
        log.info("biggerTask cancelled");
    }

    biggerTask.waitFinished();
    log.info("waitFinished over");
    
    assertTrue("Bigger executed", bigger.executed);
    assertTrue("Smaller executed", smaller.executed);
    
    assertFalse("bigger not interrupted at begining", bigger.checkBefore);
    assertFalse("smaller not interrupted at all", smaller.checkBefore);
    assertFalse("smaller not interrupted at all2", smaller.checkAfter);
    assertTrue("bigger interrupted at end", bigger.checkAfter);
    
}
 
Example 19
Source File: VisibilitySupport.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private VisibilitySupport(
        @NonNull final RepositoryUpdater ru,
        @NonNull final RequestProcessor worker) {
    this.visibilityTask = new SlidingTask(ru);
    this.visibilityChanged = worker.create(this.visibilityTask);
}
 
Example 20
Source File: NbMavenProject.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Messages({
    "Progress_Download=Downloading Maven dependencies", 
    "# {0} - error message",
    "MSG_Failed=Failed to download - {0}", 
    "MSG_Done=Finished retrieving dependencies from remote repositories."})
private RequestProcessor.Task createBinaryDownloadTask(RequestProcessor rp) {
    return rp.create(new Runnable() {
        @Override
        public void run() {
                //#146171 try the hardest to avoid NPE for files/directories that
                // seemed to have been deleted while the task was scheduled.
                FileObject fo = project.getProjectDirectory();
                if (fo == null || !fo.isValid()) {
                    return;
                }
                fo = fo.getFileObject("pom.xml"); //NOI18N
                if (fo == null) {
                    return;
                }
                File pomFile = FileUtil.toFile(fo);
                if (pomFile == null) {
                    return;
                }
                MavenEmbedder online = EmbedderFactory.getOnlineEmbedder();
                AggregateProgressHandle hndl = AggregateProgressFactory.createHandle(Progress_Download(),
                        new ProgressContributor[] {
                            AggregateProgressFactory.createProgressContributor("zaloha") },  //NOI18N
                        ProgressTransferListener.cancellable(), null);

                boolean ok = true;
                try {
                    ProgressTransferListener.setAggregateHandle(hndl);
                    hndl.start();
                    MavenExecutionRequest req = online.createMavenExecutionRequest();
                    req.setPom(pomFile);
                    req.setTransferListener(ProgressTransferListener.activeListener());
                    MavenExecutionResult res = online.readProjectWithDependencies(req, false); //NOI18N
                    if (res.hasExceptions()) {
                        ok = false;
                        Exception ex = (Exception)res.getExceptions().get(0);
                        StatusDisplayer.getDefault().setStatusText(MSG_Failed(ex.getLocalizedMessage()));
                    }
                } catch (ThreadDeath d) { // download interrupted
                } catch (IllegalStateException x) {
                    if (x.getCause() instanceof ThreadDeath) {
                        // #197261: download interrupted
                    } else {
                        throw x;
                    }
                } catch (RuntimeException exc) {
                    //guard against exceptions that are not processed by the embedder
                    //#136184 NumberFormatException, #214152 InvalidArtifactRTException
                    StatusDisplayer.getDefault().setStatusText(MSG_Failed(exc.getLocalizedMessage()));
                } finally {
                    hndl.finish();
                    ProgressTransferListener.clearAggregateHandle();
                }
                if (ok) {
                    StatusDisplayer.getDefault().setStatusText(MSG_Done());
                }
                if (support.hasListeners(NbMavenProject.PROP_PROJECT)) {
                    NbMavenProject.fireMavenProjectReload(project);
                }
        }
    });
}