Java Code Examples for org.openide.util.RequestProcessor#Task

The following examples show how to use org.openide.util.RequestProcessor#Task . 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: WhiteListTaskProvider.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static void cancelAllCurrent() {
    synchronized (TASKS) {
        clearing = true;
        try {
            for (final Iterator<Map.Entry<RequestProcessor.Task,Work>> it =  TASKS.entrySet().iterator();
                 it.hasNext();) {
                final Map.Entry<RequestProcessor.Task,Work> t = it.next();
                t.getKey().cancel();
                t.getValue().cancel();
                it.remove();
            }
        } finally {
            clearing = false;
        }
    }
    synchronized (root2FilesWithAttachedErrors) {
        root2FilesWithAttachedErrors.clear();
    }
}
 
Example 2
Source File: InteceptorTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void deleteCreateChangeCase_issue_157373 () throws Exception {
    // init
    final File fileA = new File(wc, "file");
    FileUtil.toFileObject(wc).createData(fileA.getName());
    assertCachedStatus(fileA, FileInformation.STATUS_NOTVERSIONED_NEWLOCALLY);
    commit(wc);
    assertEquals(FileInformation.STATUS_VERSIONED_UPTODATE, getStatus(fileA));

    // rename
    fileA.delete();
    Handler h = new SVNInterceptor();
    Subversion.LOG.addHandler(h);
    RequestProcessor.Task r = Subversion.getInstance().getParallelRequestProcessor().create(new Runnable() {
        public void run() {
            FileUtil.refreshFor(fileA);
        }
    });
    r.run();
    assertFalse(fileA.exists());
    final File fileB = new File(wc, fileA.getName().toUpperCase());
    fileB.createNewFile();
    Thread.sleep(3000);
    assertTrue(fileB.exists());
    assertEquals(FileInformation.STATUS_NOTVERSIONED_NEWLOCALLY, getStatus(fileB));
    Subversion.LOG.removeHandler(h);
}
 
Example 3
Source File: PluginManagerUI.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static RequestProcessor.Task getRunningTask (Runnable onCancel) {
    if (runningTask != null) {
        if (runOnCancel == null) {
            runOnCancel = new HashSet<Runnable>();
        }
        runOnCancel.add(onCancel);
    }
    return runningTask;
}
 
Example 4
Source File: FolderChildrenGCRaceConditionTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@RandomlyFails // NB-Core-Build #1087
public void testChildrenCanBeSetToNullIfGCKicksIn () throws Exception {
    FileObject f = FileUtil.createData(FileUtil.getConfigRoot(), "folder/node.txt");
    
    DataFolder df = DataFolder.findFolder(f.getParent());
    Node n = df.getNodeDelegate();
    
    Node[] arr = n.getChildren().getNodes(true);
    assertEquals("Ok, one", 1, arr.length);
    final Reference<?> ref = new WeakReference<Node>(arr[0]);
    arr = null;
    
    class R implements Runnable {
        @Override
        public void run() {
            LOG.info("Ready to GC");
            assertGC("Node can go away in the worst possible moment", ref);
            LOG.info("Gone");
        }
    }
    R r = new R();
    RequestProcessor.Task t = new RequestProcessor("Inter", 1, true).post(r);
    
    Log.controlFlow(Logger.getLogger("org.openide.loaders"), null,
        "THREAD:FolderChildren_Refresh MSG:Children computed" +
        "THREAD:FolderChildren_Refresh MSG:notifyFinished.*" +
        "THREAD:Inter MSG:Gone.*" +
        "THREAD:Finalizer MSG:RMV.*" +
        "THREAD:FolderChildren_Refresh MSG:Clearing the ref.*" +
        "", 200);
    
    LOG.info("Before getNodes(true");
    int cnt = n.getChildren().getNodes(true).length;
    LOG.info("Children are here: " + cnt);
    t.cancel();
    LOG.info("Cancel done");
    assertEquals("Count is really one", 1, cnt);
}
 
Example 5
Source File: CommonServerSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public ServerState getServerState() {
    if (serverState == ServerState.UNKNOWN) {
        RequestProcessor.Task task = refresh();
        if (task != null) {
            task.waitFinished();
        }
    }
    return serverState;
}
 
Example 6
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 testWaitFinishedOnNotStartedTask () throws Exception {
    Counter x = new Counter ();
    final RequestProcessor.Task task = RequestProcessor.getDefault().create (x);
    
    //
    // Following code tests whether the RP.create().waitFinished really blocks
    // until somebody schedules the task.
    //
    class WaitThread extends Thread {
        public boolean finished;
        
        @Override
        public void run () {
            task.waitFinished ();
            synchronized (this) {
                finished = true;
                notifyAll ();
            }
        }
        
        public synchronized void w (int timeOut) throws Exception {
            if (!finished) {
                wait (timeOut);
            }
        }
    }
    WaitThread wt = new WaitThread ();
    wt.start ();
    wt.w (100);
    assertTrue ("The waitFinished has not ended, because the task has not been planned", !wt.finished);
    task.schedule (0);
    wt.w (0);
    assertTrue ("The waitFinished finished, as the task is now planned", wt.finished);
    x.assertCnt ("The task has been executed", 1);
}
 
Example 7
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 8
Source File: RequestProcessorTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testWhenWaitingForAlreadyFinishedTaskWithTimeOutTheResultIsGood () throws Exception {
    Counter x = new Counter ();
    RequestProcessor rp = new RequestProcessor ("testWaitFinishedOnStartedTaskFromRPThread");
    final RequestProcessor.Task task = rp.post (x);
    task.waitFinished ();
    x.assertCnt ("The task has been executed before", 1);
    
    class WaitTask implements Runnable {
        public boolean finished;
        
        public synchronized void run () {
            notifyAll ();
            try {
                assertTrue ("The task has been already finished", task.waitFinished (1000));
            } catch (InterruptedException ex) {
                ex.printStackTrace();
                fail ("Should not happen");
            }
            finished = true;
        }
        
    }
    WaitTask wt = new WaitTask ();
    synchronized (wt) {
        rp.post (wt);
        wt.wait ();
    }
    assertTrue ("The task.waitFinished has to finish", wt.finished);
}
 
Example 9
Source File: TransactionView.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
    * Open the transaction nodes (i.e. first level children of the root).
    */
   void openTransactionNodes() {

// Post the request for later in case there are timing issues
// going on here. 

OpenTransactionNodesRequest req = new
    OpenTransactionNodesRequest();

RequestProcessor.Task t = 
    RequestProcessor.postRequest(req, 500); // wait a sec...
   }
 
Example 10
Source File: OpenConfigurationAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected RequestProcessor.Task performAction (File repository, File[] roots, VCSContext context) {
    File config = new File(GitUtils.getGitFolderForRoot(repository), "config"); //NOI18N
    if (config.canRead()) {
        Utils.openFile(config);
    }
    return null;
}
 
Example 11
Source File: NbStartStop.java    From netbeans with Apache License 2.0 5 votes vote down vote up
void initialize() {
    for (Lookup.Item<Runnable> item : onStart().allItems()) {
        synchronized (onStart) {
            RequestProcessor.Task already = onStart.get(item.getId());
            if (already == null) {
                Runnable r = item.getInstance();
                if (r != null) {
                    onStart.put(item.getId(), RP.post(r));
                }
            }
        }
    }
    
}
 
Example 12
Source File: UndoRedoSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void componentAdded(ContainerEvent e) {
    Component c = e.getChild();
    while(((c = c.getParent()) != null)) {
        if(c instanceof TopComponent) {
            RequestProcessor.Task t = (RequestProcessor.Task) ((TopComponent)c).getClientProperty(REGISTER_TASK);
            if(t != null) {
                t.schedule(1000);
            } 
            break;
        }
    }
}
 
Example 13
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);
                }
        }
    });
}
 
Example 14
Source File: DatabaseTablesSelectorPanel.java    From jeddict with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isValid() {

    // TODO: RETOUCHE
    //            if (JavaMetamodel.getManager().isScanInProgress()) {
    if (false) {
        if (!waitingForScan) {
            waitingForScan = true;
            RequestProcessor.Task task = RequestProcessor.getDefault().create(() -> {
                // TODO: RETOUCHE
                //                            JavaMetamodel.getManager().waitScanFinished();
                waitingForScan = false;
                changeSupport.fireChange();
            });
            setErrorMessage(NbBundle.getMessage(DatabaseTablesSelectorPanel.class, "scanning-in-progress"));
            task.schedule(0);
        }
        return false;
    }
    Sources sources = ProjectUtils.getSources(project);
    SourceGroup groups[] = sources.getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
    if (groups == null || groups.length == 0) {
        setErrorMessage(NbBundle.getMessage(DatabaseTablesSelectorPanel.class, "ERR_JavaSourceGroup")); //NOI18N
        getComponent().datasourceComboBox.setEnabled(false);
        getComponent().dbschemaComboBox.setEnabled(false);
        return false;
    }

    if (!cmp && SourceLevelChecker.isSourceLevel14orLower(project)) {
        setErrorMessage(NbBundle.getMessage(DatabaseTablesSelectorPanel.class, "ERR_NeedProperSourceLevel"));
        return false;
    }

    if (getComponent().getSourceSchemaElement() == null) {
        setErrorMessage(NbBundle.getMessage(DatabaseTablesSelectorPanel.class, "ERR_SelectTableSource"));
        return false;
    }

    if (getComponent().getTableClosure().getSelectedTables().size() <= 0) {
        setErrorMessage(NbBundle.getMessage(DatabaseTablesSelectorPanel.class, "ERR_SelectTables"));
        return false;
    }

    // any view among selected tables?
    for (Table table : getComponent().getTableClosure().getSelectedTables()) {
        if (!table.isTable()) {
            setWarningMessage(NbBundle.getMessage(DatabaseTablesSelectorPanel.class, "MSG_ViewSelected"));
            return true;
        }
    }
    setErrorMessage(" "); // NOI18N
    return true;
}
 
Example 15
Source File: LSPBindings.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void scheduleBackgroundTask(RequestProcessor.Task req) {
    WORKER.post(req, DELAY);
}
 
Example 16
Source File: PushToUpstreamAction.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
protected RequestProcessor.Task performAction (File repository, File[] roots, VCSContext context) {
    return push(repository, GitUtils.getRepositoryRoots(context));
}
 
Example 17
Source File: BookmarksPersistence.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Provides access to the bookmarks load/save RP.
 */
RequestProcessor.Task createTask(Runnable r) {
    return RP.create(r, true);
}
 
Example 18
Source File: RunEGTask.java    From BART with MIT License 4 votes vote down vote up
@Override
    public void runEGTask() {
        log.setLevel(Level.INFO);
        log.fine("Load DataObject from CentralLookup");
        DataObject dObj = CentralLookup.getDefLookup().lookup(DataObject.class);
        if(dObj == null)return;
        EGTaskDataObjectDataObject dto = (EGTaskDataObjectDataObject)dObj;
        if(dto.isRun() == true)   {
            System.out.println("EGTask is runnig....");
            DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(Bundle.MSG_RunEGTask_IS_RUN()
                                                    , NotifyDescriptor.INFORMATION_MESSAGE));
            return;
        }
        if(dto.getEgtask() == null)   {
                log.log(Level.SEVERE, "EGTASK NULL IN DATAOBJECT");
                System.err.println("EGTASK NULL IN DATAOBJECT");
                DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(Bundle.MSG_RunEGTask_NO_DataObj()
                                                    , NotifyDescriptor.INFORMATION_MESSAGE));
                return;
        }
        
        
        if((dto.getEgtask().getTarget() == null) || (dto.getEgtask().getTarget() instanceof EmptyDB))  {
            log.fine("DB Target is not in correct state");
                DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(Bundle.MSG_RunEGTask_NO_DB_Target()
                                                    , NotifyDescriptor.INFORMATION_MESSAGE));
                return;
        }
//        if((dto.getDependencies() == null) || dto.getDependencies().isEmpty())  {
//            log.fine("No Dependencies");
//                DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(Bundle.MSG_RunEGTask_NO_DEPendencies()
//                                                    , NotifyDescriptor.INFORMATION_MESSAGE));
//                return;
//        }
        
        generator = new APrioriGenerator();
        
        final Dialog d = BusyDialog.getBusyDialog();
        RequestProcessor.Task T =  RequestProcessor.getDefault().post(new RunEGTaskRunnable(dto));
        T.addTaskListener(new TaskListener() {
            @Override
            public void taskFinished(Task task) {
//                d.setVisible(false);
                if(esito)   {
                    log.fine("RUN Executed OK");
                    DataBaseConfigurationNotifier.fire();
                    StatusBar.setStatus(Bundle.MSG_STATUS_RUN_OK(), 10, 3000);                    
                }else{
                    log.fine("RUN NOT Executed correctly");
                    StatusBar.setStatus(Bundle.MSG_STATUS_RUN_NO(), 10, 3000);
                }
            }
        });
//        d.setVisible(true);
    }
 
Example 19
Source File: RequestProcessorTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/** A test to check that objects are executed in the right order.
     */
    public void testOrder () throws Exception {
        final int[] count = new int[1];
        final String[] fail = new String[1];
        
        class X extends Object 
        implements Runnable, Comparable {
            public int order;
            
            public void run () {
                if (order != count[0]++) {
                    if (fail[0] == null) {
                        fail[0] = "Executing task " + order + " instead of " + count[0];
                    }
                }
            }
            
            public int compareTo (Object o) {
                X x = (X)o;
                
                return System.identityHashCode (x) - System.identityHashCode (this);
            }
            
            @Override
            public String toString () {
                return "O: " + order;
            }
        }
        
        // prepare the tasks 
        X[] arr = new X[10];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = new X ();
        }
        
        // sort it
//        Arrays.sort (arr);
        
        for (int i = 0; i < arr.length; i++) {
            arr[i].order = i;
        }
        
        // execute the task as quickly as possible (only those with the same time
        // can have wrong order
        RequestProcessor.Task[] wait = new RequestProcessor.Task[arr.length];
        for (int i = 0; i < arr.length; i++) {
            wait[i] = RequestProcessor.postRequest (arr[i]);
        }
        
        // wait to all tasks to finish
        for (int i = 0; i < arr.length; i++) {
            wait[i].waitFinished ();
        }
        
        if (fail[0] != null) {
            fail (fail[0]);
        }
            
    }
 
Example 20
Source File: FeatureManager.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public RequestProcessor.Task create(Runnable r) {
    return RP.create(r);
}