public @Override void outputLineAction(OutputEvent ev) { HudsonSCMHelper.noteWillShowDiff(path); RequestProcessor.getDefault().post(new Runnable() { public @Override void run() { String repo = findRepo(module); if (repo == null) { return; } try { final StreamSource before = makeSource(repo, path, startRev); final StreamSource after = makeSource(repo, path, endRev); HudsonSCMHelper.showDiff(before, after, path); } catch (IOException x) { LOG.log(Level.INFO, null, x); } } }); }
/** * Gets the badge * @return badge or null if badge icon does not exist */ @NullUnknown private Image getJFXBadge() { Image img = badgeCache.get(); if (img == null) { if(!EventQueue.isDispatchThread()) { img = ImageUtilities.loadImage(JFX_BADGE_PATH); badgeCache.set(img); } else { final Runnable runLoadIcon = new Runnable() { @Override public void run() { badgeCache.set(ImageUtilities.loadImage(JFX_BADGE_PATH)); cs.fireChange(); } }; final RequestProcessor RP = new RequestProcessor(JFXProjectIconAnnotator.class.getName()); RP.post(runLoadIcon); } } return img; }
private void startRename() throws Exception { synchronized (BIG_MDR_LOCK) { RequestProcessor.getDefault ().post (new Runnable () { public void run () { synchronized (BIG_MDR_LOCK) { try { called = true; BIG_MDR_LOCK.notify(); BIG_MDR_LOCK.wait(); // for notification // in some thread try to rename some object while holding mdr lock anotherObj.rename ("mynewname" + cnt++); ok = true; } catch (Exception ex) { assigned = ex; } finally { // end this all BIG_MDR_LOCK.notifyAll(); } } } }); BIG_MDR_LOCK.wait(); } }
private void updatePackages() { final Object item = createdLocationComboBox.getSelectedItem(); if (!(item instanceof SourceGroupSupport.SourceGroupProxy)) { return; } WAIT_MODEL.setSelectedItem(createdPackageComboBox.getEditor().getItem()); createdPackageComboBox.setModel(WAIT_MODEL); if (updatePackagesTask != null) { updatePackagesTask.cancel(); } updatePackagesTask = new RequestProcessor("ComboUpdatePackages").post(new Runnable() { // NOI18N @Override public void run() { final ComboBoxModel model = ((SourceGroupSupport.SourceGroupProxy) item).getPackagesComboBoxModel(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { model.setSelectedItem(createdPackageComboBox.getEditor().getItem()); createdPackageComboBox.setModel(model); } }); } }); }
@Override protected Entry createPrimaryEntry(MultiDataObject obj, FileObject primaryFile) { return new FileEntry(obj, primaryFile) { @Override public FileObject move(FileObject f, String suffix) throws IOException { try { Teaser.WAIT = new CountDownLatch(1); Teaser.WAITING = new CountDownLatch(1); FileObject fo; synchronized (DataObjectPool.getPOOL()) { Teaser.task = RequestProcessor.getDefault().post(new Teaser()); Teaser.WAITING.await(300, TimeUnit.MILLISECONDS); fo = super.move(f, suffix); } Teaser.WAITING.await(); Teaser.WAIT.countDown(); return fo; } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } }; }
protected void projectOpened() { assertFalse("Running", OpenProjects.getDefault().openProjects().isDone()); // now verify that other threads do not see results from the Future RequestProcessor.getDefault().post(this).waitFinished(); assertNull("TimeoutException thrown", arr); if (toWaitOn != null) { try { toWaitOn.await(); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } opened++; toOpen.countDown(); throw new NullPointerException("Throwing Null pointer from projectOpened()"); }
public static void revert(final VCSContext ctx) { final File files[] = HgUtils.getActionRoots(ctx); if (files == null || files.length == 0) return; final File repository = Mercurial.getInstance().getRepositoryRoot(files[0]); final RevertModifications revertModifications = new RevertModifications(repository, Arrays.asList(files).contains(repository) ? null : files); // this is much faster when getting revisions if (!revertModifications.showDialog()) { return; } final String revStr = revertModifications.getSelectionRevision(); final boolean doBackup = revertModifications.isBackupRequested(); final boolean removeNewFiles = revertModifications.isRemoveNewFilesRequested(); HgModuleConfig.getDefault().setRemoveNewFilesOnRevertModifications(removeNewFiles); HgModuleConfig.getDefault().setBackupOnRevertModifications(doBackup); RequestProcessor rp = Mercurial.getInstance().getRequestProcessor(repository); HgProgressSupport support = new HgProgressSupport() { @Override public void perform() { performRevert(repository, revStr, files, doBackup, removeNewFiles, this.getLogger()); } }; support.start(rp, repository, org.openide.util.NbBundle.getMessage(UpdateAction.class, "MSG_Revert_Progress")); // NOI18N }
public RequestProcessor.Task start(RequestProcessor rp) { runningName = ActionUtils.cutAmpersand(action.getRunningName(nodes)); SVNUrl url = null; try { Context actionContext = ctx == null ? action.getContext(nodes) : ctx; // reuse already created context if possible if (actionContext.getRootFiles().length == 0) { LOG.log(Level.INFO, "Running a task with an empty context."); //NOI18N if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "Running a task with an empty context.", new Exception()); //NOI18N } } url = getSvnUrl(actionContext); } catch (SVNClientException ex) { SvnClientExceptionHandler.notifyException(ex, false, false); } return start(rp, url, runningName); }
public void testDiffSame () throws Exception { // init File folder = new File(wc, "folder"); File file = new File(folder, "file"); folder.mkdirs(); file.createNewFile(); add(folder); commit(folder); RepositoryFile left = new RepositoryFile(repoUrl, wc.getName() + "/folder", SVNRevision.HEAD); RepositoryFile right = new RepositoryFile(repoUrl, wc.getName() + "/folder", SVNRevision.HEAD); final RevisionSetupsSupport revSupp = new RevisionSetupsSupport(left, right, repoUrl, new Context(folder)); final AtomicReference<Setup[]> ref = new AtomicReference<>(); new SvnProgressSupport() { @Override protected void perform () { ref.set(revSupp.computeSetupsBetweenRevisions(this)); } }.start(RequestProcessor.getDefault(), repoUrl, "bbb").waitFinished(); Setup[] setups = ref.get(); assertNotNull(setups); assertEquals(0, setups.length); }
protected void performAction2(final Node[] activatedNodes) { final DatabaseConnection connection = activatedNodes[0].getLookup().lookup(DatabaseConnection.class); if (connection != null) { RequestProcessor.getDefault().post( new Runnable() { @Override public void run() { String expression = null; ProcedureNode pn = activatedNodes[0].getLookup().lookup(ProcedureNode.class); try { expression = pn.getSource(); SQLEditorSupport.openSQLEditor(connection.getDatabaseConnection(), expression, false); } catch (Exception exc) { Logger.getLogger(ViewSourceCodeAction.class.getName()).log(Level.INFO, exc.getLocalizedMessage() + " while executing expression " + expression, exc); // NOI18N } } }); } }
private void checkServicesModel() { if (SaasServicesModel.getInstance().getState() != State.READY) { setErrorMessage(NbBundle.getMessage(AddWebServiceDlg.class, "INIT_WEB_SERVICES_MANAGER")); disableAllControls(); RequestProcessor.getDefault().post(new Runnable() { @Override public void run() { SaasServicesModel.getInstance().initRootGroup(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { enableAllControls(); enableControls(); checkValues(); } }); } }); } }
private static void cancelAllCurrent() { synchronized (TASKS) { clearing = true; try { for (Map.Entry<RequestProcessor.Task,Work> t : TASKS.entrySet()) { t.getKey().cancel(); t.getValue().cancel(); } TASKS.clear(); } finally { clearing = false; } } synchronized (TaskProvider.class) { root2FilesWithAttachedErrors.clear(); } }
public void next() throws InterruptedException { final WizardDescriptor.AsynchronousValidatingPanel<?> avp = (WizardDescriptor.AsynchronousValidatingPanel<?>) RunTCK.this.current(); if (RunTCK.this.prepareValidation()) { RequestProcessor.Task task = rp.post(new Runnable() { @Override public void run() { try { avp.validate(); RunTCK.this.nextPanel(); } catch (WizardValidationException ex) { Exceptions.printStackTrace(ex); } finally { lastTask = null; } } }); lastTask = task; } else { if (RunTCK.this.isValid()) { RunTCK.this.nextPanel(); } } }
@Override public final void scanSourceDirs() { RequestProcessor.getDefault().execute(() -> { List<Future<List<Photo>>> futures = new ArrayList<>(); sourceDirs.stream() .map(d -> new SourceDirScanner(d)) .forEach(sds -> futures.add((Future<List<Photo>>) executorService.submit(sds))); futures.forEach(f -> { try { final List<Photo> list = f.get(); processPhotos(list); } catch (InterruptedException | ExecutionException ex) { Exceptions.printStackTrace(ex); } }); instanceContent.add(new ReloadCookie()); }); }
static void revert(final RepositoryRevision [] revisions, final RepositoryRevision.Event [] events) { File root; if(revisions == null || revisions.length == 0){ if(events == null || events.length == 0 || events[0].getLogInfoHeader() == null) return; root = events[0].getLogInfoHeader().getRepositoryRoot(); }else{ root = revisions[0].getRepositoryRoot(); } RequestProcessor rp = Mercurial.getInstance().getRequestProcessor(root); HgProgressSupport support = new HgProgressSupport() { @Override public void perform() { revertImpl(revisions, events, this); } }; support.start(rp, root, NbBundle.getMessage(SummaryView.class, "MSG_Revert_Progress")); // NOI18N }
@Override public void ancestorAdded(AncestorEvent event) { //need to move fill into EDT but also direct call cause lock //this way code is called after panel is initialized and is added //see also 204327 RequestProcessor.getDefault().post(new Runnable() { @Override public void run() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { fillDatabaseTable(); } }); } }); removeAncestorListener(this); }
@NbBundle.Messages({ "MSG_Detecting_Wait=Detecting installations, please wait..." }) private void initList() { installationList.setListData(new Object[]{ Bundle.MSG_Detecting_Wait() }); installationList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); installationList.setEnabled(false); RequestProcessor.getDefault().post(new Runnable() { @Override public void run() { final List<Installation> installations = InstallationManager.detectAllInstallations(); EventQueue.invokeLater(new Runnable() { @Override public void run() { updateListForDetectedInstallations(installations); } }); } }); }
public WsdlData addWsdlData(String wsdlUrl, String packageName) { final WsdlDataImpl wsData = new WsdlDataImpl(wsdlUrl); wsData.setStatus(WsdlData.Status.WSDL_UNRETRIEVED); Runnable addWsRunnable = new Runnable() { public void run() { try { WebServiceManager.getInstance().addWebService(wsData, true); } catch (IOException ex) { handleException(ex); } } }; RequestProcessor.getDefault().post(addWsRunnable); return wsData; }
@Test public void testAsynchronous() { JTextComponent c = new JEditorPane(); final MyAction a = new MyAction(SIMPLE_ATTRS); ActionEvent evt = new ActionEvent(c, 0, ""); a.actionPerformed(evt); assertSame(Thread.currentThread(), a.actionPerformedThread); a.putValue(AbstractEditorAction.ASYNCHRONOUS_KEY, true); a.actionPerformedThread = null; a.actionPerformed(evt); // Add new task to the same RP to verify threading correctness RequestProcessor.getDefault().post(new Runnable() { public void run() { assertNotNull(a.actionPerformedThread); assertNotSame(Thread.currentThread(), a.actionPerformedThread); } }); }
/** 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 ); }
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]); }
private void cbPluginsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbPluginsActionPerformed // This is designed on purpose to make the user feel that // license do refresh when new plugin is selected taLicense.setText(""); final int delay = 100; RequestProcessor.getDefault().post(new Runnable() { @Override public void run() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { UpdateElement el = license4plugins.get(cbPlugins.getSelectedIndex()); taLicense.setText(el.getLicence()); taLicense.setCaretPosition(0); } }); } }, delay); }
private static void start () { RequestProcessor.getDefault ().post (new Runnable () { public void run () { Map<String,WeakReference> cs = new HashMap<String,WeakReference> (collections); Iterator<String> it = cs.keySet ().iterator (); while (it.hasNext ()) { String name = it.next (); Object o = cs.get (name).get (); if (o == null) collections.remove (name); else System.out.println (":" + name + " " + size (o)); } start (); } }, 5000); }
public Executor asynchronous(Executor original, CALL asynchCall, Object node) throws UnknownTypeException { RequestProcessor rp = (RequestProcessor) rps.get(asynchCall); if (rp != null) { return rp; } else { return AsynchronousModelFilter.CURRENT_THREAD; } }
private boolean collectMacroActions(MimePath mimePath, Map<String, MacroDescription> macros) { if (storage == null) { storage = EditorSettingsStorage.<String, MacroDescription>find(MacrosStorage.ID); if (storage == null) { synchronized (this) { if (delayed != null) { return false; } if (retryCount++ < MAX_RETRY_COUNT) { delayed = RequestProcessor.getDefault().post(new Runnable() { public void run() { synchronized (MacroShortcutsInjector.this) { delayed = null; } refreshShortcuts(); } }, 500); } else { LOG.warning("Could not create macro shortcuts, editor settings storage not initialized yet."); } } return false; } storage.addPropertyChangeListener(WeakListeners.propertyChange(this, storage)); } try { macros.putAll(storage.load(mimePath, null, false)); } catch (IOException ioe) { LOG.log(Level.WARNING, null, ioe); } return true; }
private void coalescedLookupChanged() { CoalescedChange cc = lookupCoalescedChange.get(); if (cc == null) { cc = new CoalescedChange(); lookupCoalescedChange.set(cc); } Collection<? extends FileObject> fos = null; boolean doCoalescing = cc.isCoalescing(); if (!doCoalescing) { if (SwingUtilities.isEventDispatchThread()) { if (type == FileObject.class) { fos = resFileObject.allInstances(); if (fos.size() > 1) { // Do not call an expensive DataObject.find(fo) in AWT thread. doCoalescing = true; } } } } if (doCoalescing) { RequestProcessor.Task task; synchronized (this) { if (cctask == null) { cctask = ccrp.create(new Runnable() { @Override public void run() { lookupChanged(true); } }); } task = cctask; } task.schedule(2); } else { lookupChanged(true, fos); } cc.done(); }
protected void projectOpened() { assertFalse("Running", OpenProjects.getDefault().openProjects().isDone()); // now verify that other threads do not see results from the Future RequestProcessor.getDefault().post(this).waitFinished(); assertNull("TimeoutException thrown", arr); opened++; toOpen.countDown(); }
@Override public void actionPerformed(ActionEvent e) { setEnabled(false); RequestProcessor.getDefault().post(new Runnable() { @Override public void run() { exec.cancel(); } }); }
@Messages({ "run_single_method_disabled=Surefire 2.8+ with JUnit 4.8+ or TestNG needed to run a single test method.", "TIT_RequiresUpdateOfPOM=Feature requires update of POM", "TXT_Run_Single_method=<html>Executing single test method requires Surefire 2.8+ and JUnit in version 4.8 and bigger. <br/><br/>Update your pom.xml?</html>" }) private boolean checkSurefire(final String action) { if (action.equals(SingleMethod.COMMAND_RUN_SINGLE_METHOD) || action.equals(SingleMethod.COMMAND_DEBUG_SINGLE_METHOD)) { if (!runSingleMethodEnabled()) { if (NbPreferences.forModule(ActionProviderImpl.class).getBoolean(SHOW_SUREFIRE_WARNING, true)) { WarnPanel pnl = new WarnPanel(TXT_Run_Single_method()); Object o = DialogDisplayer.getDefault().notify(new NotifyDescriptor.Confirmation(pnl, TIT_RequiresUpdateOfPOM(), NotifyDescriptor.YES_NO_OPTION)); if (pnl.disabledWarning()) { NbPreferences.forModule(ActionProviderImpl.class).putBoolean(SHOW_SUREFIRE_WARNING, false); } if (o == NotifyDescriptor.YES_OPTION) { RequestProcessor.getDefault().post(new Runnable() { @Override public void run() { Utilities.performPOMModelOperations( proj.getProjectDirectory().getFileObject("pom.xml"), Collections.singletonList(new UpdateSurefireOperation(usingSurefire28() ? null : SUREFIRE_VERSION_SAFE, usingJUnit4() || usingTestNG() ? null : JUNIT_VERSION_SAFE))); //this appears to run too fast, before the resolved model is updated. // SwingUtilities.invokeLater(new Runnable() { // @Override // public void run() { // invokeAction(action, lookup); // } // }); } }); return false; } } StatusDisplayer.getDefault().setStatusText(run_single_method_disabled()); return false; } } return true; }
public void actionPerformed (ActionEvent ignore) { // #21355 similar to fix of #16720 - don't do this in the event thread... RequestProcessor.getDefault().post(new Runnable() { public void run() { TargetExecutor exec = new TargetExecutor (proj, null); try { exec.execute (); } catch (IOException ioe) { AntModule.err.notify (ioe); } } }); }
public void testAIsBlockedButBCanBeCreated() throws Exception { final SlowND objA = (SlowND) DataObject.find(a); SlowND objB = (SlowND) DataObject.find(b); final RequestProcessor RP = new RequestProcessor("Node for A"); final Node[] nodeA = { null }; RequestProcessor.Task task = RP.post(new Runnable() { @Override public void run() { nodeA[0] = objA.getNodeDelegate(); } }); assertFalse("Did not finish yet", task.waitFinished(500)); assertNull("Node not yet created", nodeA[0]); Node nodeB = objB.getNodeDelegate(); assertNotNull("Meanwhile other nodes can be created", nodeB); assertNull("Node A still not created", nodeA[0]); synchronized (objA) { objA.notifyAll(); } task.waitFinished(); assertNotNull("Node A also created", nodeA[0]); }
/** Creates new form AddPropertyDialog */ public AddPropertyDialog(NbMavenProjectImpl prj, String goalsText) { initComponents(); manager = new ExplorerManager(); //project can be null when invoked from Tools/Options project = prj; okbutton = new JButton(NbBundle.getMessage(AddPropertyDialog.class, "BTN_OK")); manager.setRootContext(Node.EMPTY); tpDesc.setEditorKit(new HTMLEditorKit()); tpDesc.putClientProperty( JTextPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE ); manager.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { Node[] nds = getExplorerManager().getSelectedNodes(); if (nds.length != 1) { okbutton.setEnabled(false); } else { PluginIndexManager.ParameterDetail plg = nds[0].getLookup().lookup(PluginIndexManager.ParameterDetail.class); if (plg != null) { okbutton.setEnabled(true); tpDesc.setText(plg.getHtmlDetails(false)); } else { okbutton.setEnabled(false); tpDesc.setText(""); } } } }); ((BeanTreeView)tvExpressions).setRootVisible(false); ((BeanTreeView)tvExpressions).setSelectionMode(ListSelectionModel.SINGLE_SELECTION); this.goalsText = goalsText; RequestProcessor.getDefault().post(new Loader()); }
@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); }
public void testNeverSharePropertyEditorBetweenTwoThreads() { final Node.Property p = new PropertySupport.ReadOnly<String>("name", String.class, "display", "short") { @Override public String getValue() throws IllegalAccessException, InvocationTargetException { return "Hello"; } }; PropertyEditor p1 = p.getPropertyEditor(); class R implements Runnable { PropertyEditor p2; @Override public void run() { p2 = p.getPropertyEditor(); } } R r = new R(); RequestProcessor.getDefault().post(r).waitFinished(); assertNotNull("Find 1", p1); assertNotNull("Find 2", r.p2); if (p1 == r.p2) { fail("Editors obtained from different threads should be different! was " + p1 + " and " + r.p2); } }
/** Check all selected nodes. */ protected void performAction (Node[] nodes) { if (nodes == null) return; RequestProcessor.getDefault().post( new ValidateAction.RunAction (nodes) ); }
/** cancel the scheduled request task */ public void cancel() { RequestProcessor.Task t = task; if (t == null) return ; if (isRunning()) { t.waitFinished(); } else { synchronized (this) { t.cancel(); counter = 0; releaseResources(); } } }
@Override public void propertyChange(PropertyChangeEvent evt) { final JTextComponent component = EditorRegistry.focusedComponent(); FileObject fo = component != null ? NbEditorUtilities.getFileObject(component.getDocument()) : null; if (target == null || target != fo) { return; } EditorRegistry.removePropertyChangeListener(this); RequestProcessor.getDefault().post(new Runnable() { @Override public void run() { try { JavaSource js = JavaSource.forDocument(component.getDocument()); js.runModificationTask(new Task<WorkingCopy>() { @Override public void run(WorkingCopy parameter) throws Exception { parameter.toPhase(JavaSource.Phase.RESOLVED); CompilationUnitTree cut = parameter.getCompilationUnit(); if (!cut.getTypeDecls().isEmpty()) { TreePath path = TreePath.getPath(cut, cut.getTypeDecls().get(0)); if (isAbstract) { GeneratorUtils.generateAllAbstractMethodImplementations(parameter, path); } if (hasNonDefaultConstructor) { ConstructorGenerator.Factory factory = new ConstructorGenerator.Factory(); Iterator<? extends CodeGenerator> generators = factory.create(Lookups.fixed(component, parameter, path)).iterator(); if (generators.hasNext()) { generators.next().invoke(); } } } } }).commit(); } catch (IOException ioe) { } } }); }
public void testDisabledActionDoesNotCauseAnInfiniteLoop() { List<ProgressSupport.Action> actions = new ArrayList<ProgressSupport.Action>(); final CountDownLatch sync = new CountDownLatch(1); final AtomicBoolean ran = new AtomicBoolean(); actions.add(new ProgressSupport.EventThreadAction() { public void run(ProgressSupport.Context actionContext) { synchronized (sync) { ran.set(true); sync.countDown(); } } public boolean isEnabled() { return false; } }); RequestProcessor.getDefault().post(new Runnable() { public void run() { try { sync.await(10, TimeUnit.SECONDS); } catch (InterruptedException e) {} if (!ran.get()) { // hmm, anything better? System.exit(1); } } }); ProgressSupport.invoke(actions); }
/** * Save default options to persistent storage, in background. */ public static void storeDefault() { if (saveScheduled.compareAndSet(false, true)) { RequestProcessor.getDefault().post(new Runnable() { @Override public void run() { OutputOptions.getDefault().saveTo( NbPreferences.forModule(Controller.class)); saveScheduled.set(false); } }, 100); } }