@Nullable public Script getScriptSync(@NotNull final String isolateId, @NotNull final String scriptId) { assertSyncRequestAllowed(); final Semaphore semaphore = new Semaphore(); semaphore.down(); final Ref<Script> resultRef = Ref.create(); addRequest( () -> myVmService.getObject( isolateId, scriptId, new GetObjectConsumer() { @Override public void received(Obj script) { resultRef.set((Script) script); semaphore.up(); } @Override public void received(Sentinel response) { semaphore.up(); } @Override public void onError(RPCError error) { semaphore.up(); } })); semaphore.waitFor(RESPONSE_WAIT_TIMEOUT); return resultRef.get(); }
public synchronized void stop() { if (myOriginal.isRunning()) { myOriginal.stop(); } else { myStartupAlarm.cancelAllRequests(); } // needed only for correct assertion of !progress.isRunning() in // ApplicationImpl.runProcessWithProgressSynchroniously final Semaphore semaphore = new Semaphore(); semaphore.down(); SwingUtilities.invokeLater( new Runnable() { public void run() { semaphore.waitFor(); if (myDialog != null) { // System.out.println("myDialog.destroyProcess()"); myDialog.close(DialogWrapper.OK_EXIT_CODE); myDialog = null; } } }); super.stop(); // should be last to not leaveModal before closing the dialog semaphore.up(); }
private List<String> runCompiler(final Consumer<ErrorReportingCallback> runnable) { final Semaphore semaphore = new Semaphore(); semaphore.down(); final ErrorReportingCallback callback = new ErrorReportingCallback(semaphore); UIUtil.invokeAndWaitIfNeeded( new Runnable() { @Override public void run() { try { if (useJps()) { getProject().save(); CompilerTestUtil.saveSdkTable(); File ioFile = VfsUtil.virtualToIoFile(myModule.getModuleFile()); if (!ioFile.exists()) { getProject().save(); assert ioFile.exists() : "File does not exist: " + ioFile.getPath(); } } runnable.consume(callback); } catch (Exception e) { throw new RuntimeException(e); } } }); // tests run in awt while (!semaphore.waitFor(100)) { if (SwingUtilities.isEventDispatchThread()) { UIUtil.dispatchAllInvocationEvents(); } } callback.throwException(); return callback.getMessages(); }
public static List<GitCommit> history( final Project project, @NotNull VirtualFile root, String... parameters) throws VcsException { final List<GitCommit> commits = new ArrayList<GitCommit>(); final Semaphore semaphore = new Semaphore(); semaphore.down(); historyWithLinks( project, new FilePathImpl(root), null, new AsynchConsumer<GitCommit>() { @Override public void finished() { semaphore.up(); } @Override public void consume(GitCommit gitCommit) { commits.add(gitCommit); } }, null, null, parameters); semaphore.waitFor(); return commits; }
static void invokeAndWait( @NotNull final Runnable runnable, @NotNull ModalityState modalityState) { LOG.assertTrue(!isDispatchThread()); final Semaphore semaphore = new Semaphore(); semaphore.down(); final Ref<Throwable> exception = Ref.create(); Runnable runnable1 = new Runnable() { @Override public void run() { try { runnable.run(); } catch (Throwable e) { exception.set(e); } finally { semaphore.up(); } } @Override @NonNls public String toString() { return "InvokeAndWait[" + runnable + "]"; } }; invokeLater(runnable1, modalityState); semaphore.waitFor(); if (!exception.isNull()) { throw new RuntimeException(exception.get()); } }
@Override public void commitAndRunReadAction(@NotNull final Runnable runnable) { final Application application = ApplicationManager.getApplication(); if (SwingUtilities.isEventDispatchThread()) { commitAllDocuments(); runnable.run(); } else { LOG.assertTrue( !ApplicationManager.getApplication().isReadAccessAllowed(), "Don't call commitAndRunReadAction inside ReadAction, it will cause a deadlock otherwise."); final Semaphore s1 = new Semaphore(); final Semaphore s2 = new Semaphore(); final boolean[] committed = {false}; application.runReadAction( new Runnable() { @Override public void run() { if (myUncommittedDocuments.isEmpty()) { runnable.run(); committed[0] = true; } else { s1.down(); s2.down(); final Runnable commitRunnable = new Runnable() { @Override public void run() { commitAllDocuments(); s1.up(); s2.waitFor(); } }; final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator(); if (progressIndicator == null) { ApplicationManager.getApplication().invokeLater(commitRunnable); } else { ApplicationManager.getApplication() .invokeLater(commitRunnable, progressIndicator.getModalityState()); } } } }); if (!committed[0]) { s1.waitFor(); application.runReadAction( new Runnable() { @Override public void run() { s2.up(); runnable.run(); } }); } } }
@Override public boolean executeTask( DataContext context, RunConfiguration configuration, ExecutionEnvironment env, final BuildArtifactsBeforeRunTask task) { final Ref<Boolean> result = Ref.create(false); final Semaphore finished = new Semaphore(); final List<Artifact> artifacts = new ArrayList<Artifact>(); new ReadAction() { @Override protected void run(final Result result) { for (ArtifactPointer pointer : task.getArtifactPointers()) { ContainerUtil.addIfNotNull(pointer.get(), artifacts); } } }.execute(); final CompileStatusNotification callback = new CompileStatusNotification() { @Override public void finished( boolean aborted, int errors, int warnings, CompileContext compileContext) { result.set(!aborted && errors == 0); finished.up(); } }; final Condition<Compiler> compilerFilter = new Condition<Compiler>() { @Override public boolean value(com.intellij.openapi.compiler.Compiler compiler) { return compiler instanceof ArtifactsCompiler || compiler instanceof ArtifactAwareCompiler && ((ArtifactAwareCompiler) compiler).shouldRun(artifacts); } }; ApplicationManager.getApplication() .invokeAndWait( new Runnable() { @Override public void run() { final CompilerManager manager = CompilerManager.getInstance(myProject); finished.down(); manager.make( ArtifactCompileScope.createArtifactsScope(myProject, artifacts), compilerFilter, callback); } }, ModalityState.NON_MODAL); finished.waitFor(); return result.get(); }
public static void invokeAndWaitInterruptedWhenClosing( final Project project, final Runnable runnable, final ModalityState modalityState) { final Ref<Boolean> start = new Ref<Boolean>(Boolean.TRUE); final Application application = ApplicationManager.getApplication(); LOG.assertTrue(!application.isDispatchThread()); final Semaphore semaphore = new Semaphore(); semaphore.down(); Runnable runnable1 = new Runnable() { public void run() { try { runnable.run(); } finally { semaphore.up(); } } @NonNls public String toString() { return "PeriodicalTaskCloser's invoke and wait [" + runnable.toString() + "]"; } }; LaterInvocator.invokeLater( runnable1, modalityState, new Condition<Object>() { public boolean value(Object o) { synchronized (start) { return !start.get(); } } }); while (true) { if (semaphore.waitFor(1000)) { return; } final Ref<Boolean> fire = new Ref<Boolean>(); synchronized (ourLock) { final Boolean state = myStates.get(project); if (!Boolean.TRUE.equals(state)) { fire.set(Boolean.TRUE); } if (Boolean.TRUE.equals(fire.get())) { synchronized (start) { start.set(Boolean.FALSE); return; } } } } }
// blocks until all elements in the queue are processed public void waitFor() { final Semaphore semaphore = new Semaphore(); semaphore.down(); schedule( new Runnable() { @Override public void run() { semaphore.up(); } }); semaphore.waitFor(); }
private void waitForProcess(Application application) { myWaitSemaphore = new Semaphore(); myWaitSemaphore.down(); myWaitForThreadFuture = application.executeOnPooledThread( () -> { try { myProcess.waitFor(); } catch (InterruptedException ignored) { } finally { myWaitSemaphore.up(); } }); }
private CompilationLog compile(final ParameterizedRunnable<CompileStatusNotification> action) { final Ref<CompilationLog> result = Ref.create(null); final Semaphore semaphore = new Semaphore(); UIUtil.invokeAndWaitIfNeeded( new Runnable() { @Override public void run() { semaphore.down(); CompilerManagerImpl.testSetup(); final CompileStatusNotification callback = new CompileStatusNotification() { @Override public void finished( boolean aborted, int errors, int warnings, CompileContext compileContext) { try { if (aborted) { Assert.fail("compilation aborted"); } result.set( new CompilationLog( CompilerManagerImpl.getPathsToRecompile(), CompilerManagerImpl.getPathsToDelete(), compileContext.getMessages(CompilerMessageCategory.ERROR), compileContext.getMessages(CompilerMessageCategory.WARNING))); } finally { semaphore.up(); } } }; if (useExternalCompiler()) { myProject.save(); CompilerTestUtil.saveSdkTable(); CompilerTestUtil.scanSourceRootsToRecompile(myProject); } action.run(callback); } }); long start = System.currentTimeMillis(); while (!semaphore.waitFor(10)) { if (System.currentTimeMillis() - start > 60 * 1000) { throw new RuntimeException("timeout"); } UIUtil.dispatchAllInvocationEvents(); } UIUtil.dispatchAllInvocationEvents(); return result.get(); }
protected ProcessHandler runProcess( String className, Module module, final Class<? extends Executor> executorClass, final ProcessListener listener, final ProgramRunner runner) throws ExecutionException { final ApplicationConfiguration configuration = new ApplicationConfiguration( "app", getProject(), ApplicationConfigurationType.getInstance()); configuration.setModule(module); configuration.setMainClassName(className); final Executor executor = Executor.EXECUTOR_EXTENSION_NAME.findExtension(executorClass); final ExecutionEnvironment environment = new ExecutionEnvironment( configuration, getProject(), new RunnerSettings<JDOMExternalizable>(null, null), null, null); final Semaphore semaphore = new Semaphore(); semaphore.down(); final AtomicReference<ProcessHandler> processHandler = new AtomicReference<ProcessHandler>(); runner.execute( executor, environment, new ProgramRunner.Callback() { @Override public void processStarted(final RunContentDescriptor descriptor) { disposeOnTearDown( new Disposable() { @Override public void dispose() { Disposer.dispose(descriptor); } }); final ProcessHandler handler = descriptor.getProcessHandler(); assert handler != null; handler.addProcessListener(listener); processHandler.set(handler); semaphore.up(); } }); semaphore.waitFor(); return processHandler.get(); }
private void openAndWait(VirtualFile file, @Nullable String relativePath) throws InterruptedException, IOException { semaphore.down(); DesignerApplicationManager.getInstance() .renderDocument(myModule, Tests.virtualToPsi(myProject, file)); await(); }
public void stop() { super.stop(); myQueue.cancelAllUpdates(); myFreezeSemaphore.up(); ApplicationManager.getApplication() .invokeLater( new Runnable() { public void run() { final CompletionPhase phase = CompletionServiceImpl.getCompletionPhase(); if (!(phase instanceof CompletionPhase.BgCalculation) || phase.indicator != CompletionProgressIndicator.this) return; LOG.assertTrue(!getProject().isDisposed(), "project disposed"); if (myEditor.isDisposed()) { LookupManager.getInstance(getProject()).hideActiveLookup(); CompletionServiceImpl.setCompletionPhase(CompletionPhase.NoCompletion); return; } if (myEditor instanceof EditorWindow) { LOG.assertTrue( ((EditorWindow) myEditor).getInjectedFile().isValid(), "injected file !valid"); LOG.assertTrue( ((DocumentWindow) myEditor.getDocument()).isValid(), "docWindow !valid"); } PsiFile file = myLookup.getPsiFile(); LOG.assertTrue(file == null || file.isValid(), "file !valid"); myLookup.setCalculating(false); if (hideAutopopupIfMeaningless()) { return; } if (myCount == 0) { if (!isAutopopupCompletion()) { LookupManager.getInstance(getProject()).hideActiveLookup(); final CompletionProgressIndicator current = CompletionServiceImpl.getCompletionService().getCurrentCompletion(); LOG.assertTrue( current == null, current + "!=" + CompletionProgressIndicator.this); handleEmptyLookup(!((CompletionPhase.BgCalculation) phase).modifiersChanged); } } else { CompletionServiceImpl.setCompletionPhase( new CompletionPhase.ItemsCalculated(CompletionProgressIndicator.this)); updateLookup(); } } }, myQueue.getModalityState()); }
protected void performRemoteGitTask(final GitLineHandler handler, String title) throws ServerRuntimeException { final GitTask task = new GitTask(myProject, handler, title); task.setProgressAnalyzer(new GitStandardProgressAnalyzer()); final Semaphore semaphore = new Semaphore(); semaphore.down(); final Ref<ServerRuntimeException> errorRef = new Ref<ServerRuntimeException>(); ApplicationManager.getApplication() .invokeLater( new Runnable() { @Override public void run() { task.execute( false, false, new GitTaskResultHandlerAdapter() { @Override protected void run(GitTaskResult result) { super.run(result); semaphore.up(); } @Override protected void onFailure() { for (VcsException error : handler.errors()) { myLoggingHandler.println(error.toString()); if (errorRef.isNull()) { errorRef.set(new ServerRuntimeException(error)); } } } }); } }); semaphore.waitFor(); if (!errorRef.isNull()) { throw errorRef.get(); } }
public Waiter( @NotNull Project project, @NotNull Runnable runnable, String title, boolean cancellable) { super( project, VcsBundle.message("change.list.manager.wait.lists.synchronization", title), cancellable); myRunnable = runnable; mySemaphore.down(); setCancelText("Skip"); }
public void run(@NotNull ProgressIndicator indicator) { indicator.setIndeterminate(true); indicator.setText2(VcsBundle.message("commit.wait.util.synched.text")); if (!myStarted.compareAndSet(false, true)) { LOG.error("Waiter running under progress being started again."); } else { while (!mySemaphore.waitFor(500)) { indicator.checkCanceled(); } } }
@Nullable private String evaluateExpression( final @NotNull String isolateId, final @Nullable Frame vmTopFrame, final @Nullable XExpression xExpression) { final String evalText = xExpression == null ? null : xExpression.getExpression(); if (vmTopFrame == null || StringUtil.isEmptyOrSpaces(evalText)) return null; final Ref<String> evalResult = new Ref<>(); final Semaphore semaphore = new Semaphore(); semaphore.down(); myDebugProcess .getVmServiceWrapper() .evaluateInFrame( isolateId, vmTopFrame, evalText, new XDebuggerEvaluator.XEvaluationCallback() { @Override public void evaluated(@NotNull final XValue result) { if (result instanceof DartVmServiceValue) { evalResult.set( getSimpleStringPresentation(((DartVmServiceValue) result).getInstanceRef())); } semaphore.up(); } @Override public void errorOccurred(@NotNull final String errorMessage) { evalResult.set( "Failed to evaluate log expression [" + evalText + "]: " + errorMessage); semaphore.up(); } }, true); semaphore.waitFor(1000); return evalResult.get(); }
public synchronized void close() throws IOException { if (myWaitForThreadFuture != null) { myWaitForThreadFuture.cancel(true); } if (myWaitSemaphore != null) { myWaitSemaphore.up(); } try { if (myInputStream != null && !myContainsError) { myInputStream.close(); try { Thread.sleep(10); } catch (InterruptedException e) { // ignore } } } finally { try { if (myOutputStream != null && !myContainsError) { myOutputStream.close(); try { Thread.sleep(10); } catch (InterruptedException e) { // ignore } } try { if (myErrThread != null) { myErrThread.setProcessTerminated(true); } if (myStdErrFuture != null) { myStdErrFuture.get(); } } catch (InterruptedException e) { // } catch (ExecutionException e) { LOG.error(e); } } finally { try { if (myProcess != null) { myProcess.destroy(); } } finally { myInputStream = null; myOutputStream = null; myProcess = null; } } } }
@Override public synchronized void stop() { if (myOriginal.isRunning()) { myOriginal.stop(); } else { myStartupAlarm.cancelAllRequests(); if (!myOriginalStarted && myOriginal instanceof Disposable) { // dispose original because start & stop were not called so original progress might not have // released its resources Disposer.dispose(((Disposable) myOriginal)); } } // needed only for correct assertion of !progress.isRunning() in // ApplicationImpl.runProcessWithProgressSynchroniously final Semaphore semaphore = new Semaphore(); semaphore.down(); SwingUtilities.invokeLater( new Runnable() { @Override public void run() { semaphore.waitFor(); if (myDialog != null) { // System.out.println("myDialog.destroyProcess()"); myDialog.close(DialogWrapper.OK_EXIT_CODE); myDialog = null; } } }); try { super.stop(); // should be last to not leaveModal before closing the dialog } finally { semaphore.up(); } }
@Override public void waitForSmartMode() { final Application application = ApplicationManager.getApplication(); if (!application.isUnitTestMode()) { assert !application.isDispatchThread(); assert !application.isReadAccessAllowed(); } if (!isDumb()) { return; } final Semaphore semaphore = new Semaphore(); semaphore.down(); runWhenSmart( new Runnable() { @Override public void run() { semaphore.up(); } }); semaphore.waitFor(); }
private void execute(final MavenRunnerParameters params) { final Semaphore sema = new Semaphore(); sema.down(); UIUtil.invokeLaterIfNeeded( new Runnable() { @Override public void run() { MavenRunConfigurationType.runConfiguration( myProject, params, getMavenGeneralSettings(), new MavenRunnerSettings(), new ProgramRunner.Callback() { @Override public void processStarted(final RunContentDescriptor descriptor) { descriptor .getProcessHandler() .addProcessListener( new ProcessAdapter() { @Override public void processTerminated(ProcessEvent event) { sema.up(); UIUtil.invokeLaterIfNeeded( new Runnable() { @Override public void run() { Disposer.dispose(descriptor); } }); } }); } }); } }); sema.waitFor(); }
private void insertString(VirtualFile file, int offset, @NotNull CharSequence s) throws InterruptedException { final Document document = FileDocumentManager.getInstance().getDocument(file); assertNotNull(document); AccessToken token = WriteAction.start(); try { document.insertString(offset, s); } finally { token.finish(); } semaphore.down(); PsiDocumentManager.getInstance(myProject).commitAllDocuments(); FileDocumentManager.getInstance().saveAllDocuments(); await(); }
private void renderAndWait(VirtualFile file) throws InterruptedException { semaphore.down(); AsyncResult<DocumentInfo> result = DesignerApplicationManager.getInstance() .renderDocument(myModule, Tests.virtualToPsi(myProject, file)); result.doWhenProcessed( new Runnable() { @Override public void run() { semaphore.up(); } }); await(); }
private void callClientAssert(VirtualFile file) throws IOException, InterruptedException { semaphore.down(); ActionCallback callback = client.test( null, DocumentFactoryManager.getInstance().getId(file), getTestName(false), APP_TEST_CLASS_ID); callback.doWhenProcessed( new Runnable() { @Override public void run() { semaphore.up(); } }); await(); }
public void fireEvents(boolean hasWriteAction) { try { if (!iHaveEventsToFire) return; if (hasWriteAction) { fireEventsInWriteAction(); } else { ApplicationManager.getApplication() .runWriteAction( new Runnable() { @Override public void run() { fireEventsInWriteAction(); } }); } } finally { mySemaphore.up(); } }
@Override protected void processCommand(int command) throws IOException { boolean result = true; try { super.processCommand(command); } catch (Throwable e) { //noinspection InstanceofCatchParameter if (!(e instanceof SocketException)) { result = false; fail.set(true); try { LOG.error(e); } catch (AssertionError ignored) { } } } finally { if (!result) { semaphore.up(); } } }
@Override public void finished( boolean aborted, int errors, int warnings, final CompileContext compileContext) { try { for (CompilerMessageCategory category : CompilerMessageCategory.values()) { for (CompilerMessage message : compileContext.getMessages(category)) { final String msg = message.getMessage(); if (category != CompilerMessageCategory.INFORMATION || !msg.startsWith("Compilation completed successfully")) { myMessages.add(category + ": " + msg); } } } if (errors > 0) { fail("Compiler errors occurred! " + StringUtil.join(myMessages, "\n")); } assertFalse("Code did not compile!", aborted); } catch (Throwable t) { myError = t; } finally { mySemaphore.up(); } }
@CalledInAwt public void execute() { FileDocumentManager.getInstance().saveAllDocuments(); mySemaphore.down(); runInEdt( () -> { if (areInSameHierarchy( createUrl(myMergeContext.getSourceUrl()), myMergeContext.getWcInfo().getUrl())) { end("Cannot merge from self", true); } else if (!hasSwitchedRoots() || myInteraction.shouldContinueSwitchedRootFound()) { runInBackground( "Checking repository capabilities", indicator -> { if (supportsMergeInfo()) { runInEdt(this::selectMergeVariant); } else { mergeAll(false); } }); } }); }
private static boolean checkPort(final InetSocketAddress remoteAddress) { final ClientBootstrap bootstrap = new ClientBootstrap(new OioClientSocketChannelFactory(new PooledThreadExecutor())); bootstrap.setOption("child.tcpNoDelay", true); final AtomicBoolean result = new AtomicBoolean(false); final Semaphore semaphore = new Semaphore(); semaphore.down(); // must call to down() here to ensure that down was called _before_ up() bootstrap.setPipeline( pipeline( new HttpResponseDecoder(), new HttpRequestEncoder(), new SimpleChannelUpstreamHandler() { @Override public void messageReceived(ChannelHandlerContext context, MessageEvent e) throws Exception { try { if (e.getMessage() instanceof HttpResponse) { HttpResponse response = (HttpResponse) e.getMessage(); if (response.getStatus().equals(OK) && response .getContent() .toString(CharsetUtil.US_ASCII) .equals(getApplicationStartTime())) { LOG.info("port check: current OS must be marked as normal"); result.set(true); } } } finally { semaphore.up(); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { try { LOG.error(e.getCause()); } finally { semaphore.up(); } } })); ChannelFuture connectFuture = null; try { connectFuture = bootstrap.connect(remoteAddress); if (!waitComplete(connectFuture, "connect")) { return false; } ChannelFuture writeFuture = connectFuture .getChannel() .write(new DefaultHttpRequest(HTTP_1_1, HttpMethod.GET, START_TIME_PATH)); if (!waitComplete(writeFuture, "write")) { return false; } try { // yes, 30 seconds. I always get timeout in Linux in Parallels if I set to 2 seconds. // In any case all work is done in pooled thread (IDE init time isn't affected) if (!semaphore.waitForUnsafe(30000)) { LOG.info("port check: semaphore down timeout"); } } catch (InterruptedException e) { LOG.info("port check: semaphore interrupted", e); } } finally { if (connectFuture != null) { connectFuture.getChannel().close().awaitUninterruptibly(); } bootstrap.releaseExternalResources(); } return result.get(); }