Search in sources :

Example 66 with Semaphore

use of com.intellij.util.concurrency.Semaphore in project intellij-community by JetBrains.

the class SvnTestCase method refreshSvnMappingsSynchronously.

protected void refreshSvnMappingsSynchronously() {
    final SvnVcs vcs = SvnVcs.getInstance(myProject);
    if (!myInitChangeListManager) {
        return;
    }
    final Semaphore semaphore = new Semaphore();
    semaphore.down();
    ((SvnFileUrlMappingImpl) vcs.getSvnFileUrlMapping()).realRefresh(() -> semaphore.up());
    semaphore.waitFor();
}
Also used : SvnFileUrlMappingImpl(org.jetbrains.idea.svn.SvnFileUrlMappingImpl) Semaphore(com.intellij.util.concurrency.Semaphore) SvnVcs(org.jetbrains.idea.svn.SvnVcs)

Example 67 with Semaphore

use of com.intellij.util.concurrency.Semaphore in project intellij-community by JetBrains.

the class SvnCachingRepositoryPoolTest method testCancel.

@Test
public void testCancel() throws Exception {
    final SvnIdeaRepositoryPoolManager poolManager = new SvnIdeaRepositoryPoolManager(true, null, null, 1, 1);
    final SVNURL url = SVNURL.parseURIEncoded("http://a.b.c");
    poolManager.setCreator(svnurl -> new MockSvnRepository(svnurl, ISVNSession.DEFAULT));
    final MockSvnRepository repository1 = (MockSvnRepository) poolManager.createRepository(url, true);
    final Semaphore semaphore = new Semaphore();
    semaphore.down();
    poolManager.setCreator(svnurl -> {
        semaphore.waitFor();
        return new MockSvnRepository(svnurl, ISVNSession.DEFAULT);
    });
    final SVNException[] exc = new SVNException[1];
    final Runnable target = () -> {
        try {
            final MockSvnRepository repository = (MockSvnRepository) poolManager.createRepository(url, true);
            repository.fireConnectionClosed();
        } catch (SVNException e) {
            e.printStackTrace();
            exc[0] = e;
        }
    };
    final EmptyProgressIndicator indicator = new EmptyProgressIndicator();
    Thread thread = new Thread(() -> ((ProgressManagerImpl) ProgressManager.getInstance()).executeProcessUnderProgress(target, indicator), "svn cache repo");
    thread.start();
    TimeoutUtil.sleep(10);
    Assert.assertTrue(thread.isAlive());
    indicator.cancel();
    final Object obj = new Object();
    while (!timeout(System.currentTimeMillis()) && thread.isAlive()) {
        synchronized (obj) {
            try {
                obj.wait(300);
            } catch (InterruptedException e) {
            //
            }
        }
    }
    Assert.assertTrue(!thread.isAlive());
    thread.join();
    Assert.assertNotNull(exc[0]);
    //repository1.fireConnectionClosed(); // also test that used are also closed.. in dispose
    poolManager.dispose();
    checkAfterDispose(poolManager);
}
Also used : EmptyProgressIndicator(com.intellij.openapi.progress.EmptyProgressIndicator) SVNURL(org.tmatesoft.svn.core.SVNURL) SvnIdeaRepositoryPoolManager(org.jetbrains.idea.svn.svnkit.lowLevel.SvnIdeaRepositoryPoolManager) Semaphore(com.intellij.util.concurrency.Semaphore) SVNException(org.tmatesoft.svn.core.SVNException) FileBasedTest(com.intellij.testFramework.vcs.FileBasedTest) Test(org.junit.Test)

Example 68 with Semaphore

use of com.intellij.util.concurrency.Semaphore in project intellij-community by JetBrains.

the class SvnAuthenticationTest method synchronousBackground.

private static void synchronousBackground(final Runnable runnable) throws InterruptedException {
    final Semaphore semaphore = new Semaphore();
    semaphore.down();
    ApplicationManager.getApplication().executeOnPooledThread(() -> {
        try {
            runnable.run();
        } finally {
            semaphore.up();
        }
    });
    semaphore.waitFor();
}
Also used : Semaphore(com.intellij.util.concurrency.Semaphore)

Example 69 with Semaphore

use of com.intellij.util.concurrency.Semaphore in project intellij-community by JetBrains.

the class GitHistoryUtils method history.

public static void history(@NotNull Project project, @NotNull FilePath path, @Nullable VirtualFile root, @NotNull VcsRevisionNumber startingRevision, @NotNull Consumer<GitFileRevision> consumer, @NotNull Consumer<VcsException> exceptionConsumer, String... parameters) {
    // adjust path using change manager
    final FilePath filePath = getLastCommitName(project, path);
    final VirtualFile finalRoot;
    try {
        finalRoot = (root == null ? GitUtil.getGitRoot(filePath) : root);
    } catch (VcsException e) {
        exceptionConsumer.consume(e);
        return;
    }
    final GitLogParser logParser = new GitLogParser(project, GitLogParser.NameStatus.STATUS, HASH, COMMIT_TIME, AUTHOR_NAME, AUTHOR_EMAIL, COMMITTER_NAME, COMMITTER_EMAIL, PARENTS, SUBJECT, BODY, RAW_BODY, AUTHOR_TIME);
    final AtomicReference<String> firstCommit = new AtomicReference<>(startingRevision.asString());
    final AtomicReference<String> firstCommitParent = new AtomicReference<>(firstCommit.get());
    final AtomicReference<FilePath> currentPath = new AtomicReference<>(filePath);
    final AtomicReference<GitLineHandler> logHandler = new AtomicReference<>();
    final AtomicBoolean skipFurtherOutput = new AtomicBoolean();
    final Consumer<GitLogRecord> resultAdapter = record -> {
        if (skipFurtherOutput.get()) {
            return;
        }
        if (record == null) {
            exceptionConsumer.consume(new VcsException("revision details are null."));
            return;
        }
        record.setUsedHandler(logHandler.get());
        final GitRevisionNumber revision = new GitRevisionNumber(record.getHash(), record.getDate());
        firstCommit.set(record.getHash());
        final String[] parentHashes = record.getParentsHashes();
        if (parentHashes.length < 1) {
            firstCommitParent.set(null);
        } else {
            firstCommitParent.set(parentHashes[0]);
        }
        final String message = record.getFullMessage();
        FilePath revisionPath;
        try {
            final List<FilePath> paths = record.getFilePaths(finalRoot);
            if (paths.size() > 0) {
                revisionPath = paths.get(0);
            } else {
                revisionPath = currentPath.get();
            }
            Couple<String> authorPair = Couple.of(record.getAuthorName(), record.getAuthorEmail());
            Couple<String> committerPair = Couple.of(record.getCommitterName(), record.getCommitterEmail());
            Collection<String> parents = Arrays.asList(parentHashes);
            consumer.consume(new GitFileRevision(project, finalRoot, revisionPath, revision, Couple.of(authorPair, committerPair), message, null, new Date(record.getAuthorTimeStamp()), parents));
            List<GitLogStatusInfo> statusInfos = record.getStatusInfos();
            if (statusInfos.isEmpty()) {
                return;
            }
            if (statusInfos.get(0).getType() == GitChangeType.ADDED && !filePath.isDirectory()) {
                skipFurtherOutput.set(true);
            }
        } catch (VcsException e) {
            exceptionConsumer.consume(e);
        }
    };
    GitVcs vcs = GitVcs.getInstance(project);
    GitVersion version = vcs != null ? vcs.getVersion() : GitVersion.NULL;
    final AtomicBoolean criticalFailure = new AtomicBoolean();
    while (currentPath.get() != null && firstCommitParent.get() != null) {
        logHandler.set(getLogHandler(project, version, finalRoot, logParser, currentPath.get(), firstCommitParent.get(), parameters));
        final MyTokenAccumulator accumulator = new MyTokenAccumulator(logParser);
        final Semaphore semaphore = new Semaphore();
        logHandler.get().addLineListener(new GitLineHandlerAdapter() {

            @Override
            public void onLineAvailable(String line, Key outputType) {
                final GitLogRecord record = accumulator.acceptLine(line);
                if (record != null) {
                    resultAdapter.consume(record);
                }
            }

            @Override
            public void startFailed(Throwable exception) {
                //noinspection ThrowableInstanceNeverThrown
                try {
                    exceptionConsumer.consume(new VcsException(exception));
                } finally {
                    criticalFailure.set(true);
                    semaphore.up();
                }
            }

            @Override
            public void processTerminated(int exitCode) {
                try {
                    super.processTerminated(exitCode);
                    final GitLogRecord record = accumulator.processLast();
                    if (record != null) {
                        resultAdapter.consume(record);
                    }
                } catch (ProcessCanceledException ignored) {
                } catch (Throwable t) {
                    LOG.error(t);
                    exceptionConsumer.consume(new VcsException("Internal error " + t.getMessage(), t));
                    criticalFailure.set(true);
                } finally {
                    semaphore.up();
                }
            }
        });
        semaphore.down();
        logHandler.get().start();
        semaphore.waitFor();
        if (criticalFailure.get()) {
            return;
        }
        try {
            Pair<String, FilePath> firstCommitParentAndPath = getFirstCommitParentAndPathIfRename(project, finalRoot, firstCommit.get(), currentPath.get(), version);
            currentPath.set(firstCommitParentAndPath == null ? null : firstCommitParentAndPath.second);
            firstCommitParent.set(firstCommitParentAndPath == null ? null : firstCommitParentAndPath.first);
            skipFurtherOutput.set(false);
        } catch (VcsException e) {
            LOG.warn("Tried to get first commit rename path", e);
            exceptionConsumer.consume(e);
            return;
        }
    }
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) com.intellij.openapi.util(com.intellij.openapi.util) VcsRevisionNumber(com.intellij.openapi.vcs.history.VcsRevisionNumber) Change(com.intellij.openapi.vcs.changes.Change) git4idea.commands(git4idea.commands) ObjectUtils.notNull(com.intellij.util.ObjectUtils.notNull) VirtualFile(com.intellij.openapi.vfs.VirtualFile) GitLogProvider(git4idea.log.GitLogProvider) GitVersionSpecialty(git4idea.config.GitVersionSpecialty) ReadAction(com.intellij.openapi.application.ReadAction) VcsRevisionDescriptionImpl(com.intellij.openapi.vcs.history.VcsRevisionDescriptionImpl) SmartList(com.intellij.util.SmartList) Semaphore(com.intellij.util.concurrency.Semaphore) GitVersion(git4idea.config.GitVersion) GitHeavyCommit(git4idea.history.browser.GitHeavyCommit) Logger(com.intellij.openapi.diagnostic.Logger) VcsException(com.intellij.openapi.vcs.VcsException) FilePath(com.intellij.openapi.vcs.FilePath) git4idea(git4idea) ChangeListManager(com.intellij.openapi.vcs.changes.ChangeListManager) GitBundle(git4idea.i18n.GitBundle) NullableFunction(com.intellij.util.NullableFunction) com.intellij.vcs.log(com.intellij.vcs.log) AbstractHash(git4idea.history.wholeTree.AbstractHash) Nullable(org.jetbrains.annotations.Nullable) ServiceManager(com.intellij.openapi.components.ServiceManager) HashImpl(com.intellij.vcs.log.impl.HashImpl) StopWatch(com.intellij.vcs.log.util.StopWatch) Registry(com.intellij.openapi.util.registry.Registry) GitLogOption(git4idea.history.GitLogParser.GitLogOption) NotNull(org.jetbrains.annotations.NotNull) Consumer(com.intellij.util.Consumer) SHAHash(git4idea.history.browser.SHAHash) ItemLatestState(com.intellij.openapi.vcs.diff.ItemLatestState) FileStatus(com.intellij.openapi.vcs.FileStatus) java.util(java.util) ArrayUtil(com.intellij.util.ArrayUtil) VcsRevisionDescription(com.intellij.openapi.vcs.history.VcsRevisionDescription) SymbolicRefsI(git4idea.history.browser.SymbolicRefsI) LogDataImpl(com.intellij.vcs.log.impl.LogDataImpl) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ContainerUtil(com.intellij.util.containers.ContainerUtil) GitBranchUtil(git4idea.branch.GitBranchUtil) AtomicReference(java.util.concurrent.atomic.AtomicReference) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) Project(com.intellij.openapi.project.Project) SymbolicRefs(git4idea.history.browser.SymbolicRefs) ProcessOutputTypes(com.intellij.execution.process.ProcessOutputTypes) StringUtil(com.intellij.openapi.util.text.StringUtil) VcsFileRevision(com.intellij.openapi.vcs.history.VcsFileRevision) OpenTHashSet(com.intellij.util.containers.OpenTHashSet) GitRefManager(git4idea.log.GitRefManager) Semaphore(com.intellij.util.concurrency.Semaphore) SmartList(com.intellij.util.SmartList) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) FilePath(com.intellij.openapi.vcs.FilePath) GitVersion(git4idea.config.GitVersion) AtomicReference(java.util.concurrent.atomic.AtomicReference) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) VcsException(com.intellij.openapi.vcs.VcsException)

Example 70 with Semaphore

use of com.intellij.util.concurrency.Semaphore in project intellij-community by JetBrains.

the class ReloadClassesWorker method reloadClasses.

public void reloadClasses(final Map<String, HotSwapFile> modifiedClasses) {
    DebuggerManagerThreadImpl.assertIsManagerThread();
    if (modifiedClasses == null || modifiedClasses.size() == 0) {
        myProgress.addMessage(myDebuggerSession, MessageCategory.INFORMATION, DebuggerBundle.message("status.hotswap.loaded.classes.up.to.date"));
        return;
    }
    final DebugProcessImpl debugProcess = getDebugProcess();
    final VirtualMachineProxyImpl virtualMachineProxy = debugProcess.getVirtualMachineProxy();
    final Project project = debugProcess.getProject();
    final BreakpointManager breakpointManager = (DebuggerManagerEx.getInstanceEx(project)).getBreakpointManager();
    breakpointManager.disableBreakpoints(debugProcess);
    try {
        RedefineProcessor redefineProcessor = new RedefineProcessor(virtualMachineProxy);
        int processedEntriesCount = 0;
        for (final Map.Entry<String, HotSwapFile> entry : modifiedClasses.entrySet()) {
            // stop if process is finished already
            if (debugProcess.isDetached() || debugProcess.isDetaching()) {
                break;
            }
            if (redefineProcessor.getProcessedClassesCount() == 0 && myProgress.isCancelled()) {
                // once at least one class has been actually reloaded, do not interrupt the whole process
                break;
            }
            processedEntriesCount++;
            final String qualifiedName = entry.getKey();
            if (qualifiedName != null) {
                myProgress.setText(qualifiedName);
                myProgress.setFraction(processedEntriesCount / (double) modifiedClasses.size());
            }
            try {
                redefineProcessor.processClass(qualifiedName, entry.getValue().file);
            } catch (IOException e) {
                reportProblem(qualifiedName, e);
            }
        }
        if (redefineProcessor.getProcessedClassesCount() == 0 && myProgress.isCancelled()) {
            // once at least one class has been actually reloaded, do not interrupt the whole process
            return;
        }
        redefineProcessor.processPending();
        myProgress.setFraction(1);
        final int partiallyRedefinedClassesCount = redefineProcessor.getPartiallyRedefinedClassesCount();
        if (partiallyRedefinedClassesCount == 0) {
            myProgress.addMessage(myDebuggerSession, MessageCategory.INFORMATION, DebuggerBundle.message("status.classes.reloaded", redefineProcessor.getProcessedClassesCount()));
        } else {
            final String message = DebuggerBundle.message("status.classes.not.all.versions.reloaded", partiallyRedefinedClassesCount, redefineProcessor.getProcessedClassesCount());
            myProgress.addMessage(myDebuggerSession, MessageCategory.WARNING, message);
        }
        LOG.debug("classes reloaded");
    } catch (Throwable e) {
        processException(e);
    }
    debugProcess.onHotSwapFinished();
    DebuggerContextImpl context = myDebuggerSession.getContextManager().getContext();
    SuspendContextImpl suspendContext = context.getSuspendContext();
    if (suspendContext != null) {
        XExecutionStack stack = suspendContext.getActiveExecutionStack();
        if (stack != null) {
            ((JavaExecutionStack) stack).initTopFrame();
        }
    }
    final Semaphore waitSemaphore = new Semaphore();
    waitSemaphore.down();
    //noinspection SSBasedInspection
    SwingUtilities.invokeLater(() -> {
        try {
            if (!project.isDisposed()) {
                breakpointManager.reloadBreakpoints();
                debugProcess.getRequestsManager().clearWarnings();
                if (LOG.isDebugEnabled()) {
                    LOG.debug("requests updated");
                    LOG.debug("time stamp set");
                }
                myDebuggerSession.refresh(false);
                XDebugSession session = myDebuggerSession.getXDebugSession();
                if (session != null) {
                    session.rebuildViews();
                }
            }
        } catch (Throwable e) {
            LOG.error(e);
        } finally {
            waitSemaphore.up();
        }
    });
    waitSemaphore.waitFor();
    if (!project.isDisposed()) {
        try {
            breakpointManager.enableBreakpoints(debugProcess);
        } catch (Exception e) {
            processException(e);
        }
    }
}
Also used : XDebugSession(com.intellij.xdebugger.XDebugSession) VirtualMachineProxyImpl(com.intellij.debugger.jdi.VirtualMachineProxyImpl) IOException(java.io.IOException) Semaphore(com.intellij.util.concurrency.Semaphore) BreakpointManager(com.intellij.debugger.ui.breakpoints.BreakpointManager) XExecutionStack(com.intellij.xdebugger.frame.XExecutionStack) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) IOException(java.io.IOException) Project(com.intellij.openapi.project.Project) JavaExecutionStack(com.intellij.debugger.engine.JavaExecutionStack) DebugProcessImpl(com.intellij.debugger.engine.DebugProcessImpl) SuspendContextImpl(com.intellij.debugger.engine.SuspendContextImpl) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

Semaphore (com.intellij.util.concurrency.Semaphore)74 Ref (com.intellij.openapi.util.Ref)10 Project (com.intellij.openapi.project.Project)8 IOException (java.io.IOException)8 Nullable (org.jetbrains.annotations.Nullable)8 ProgressIndicator (com.intellij.openapi.progress.ProgressIndicator)7 NotNull (org.jetbrains.annotations.NotNull)7 Test (org.junit.Test)7 VcsFileRevision (com.intellij.openapi.vcs.history.VcsFileRevision)6 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)6 ProcessEvent (com.intellij.execution.process.ProcessEvent)5 File (java.io.File)5 ProcessAdapter (com.intellij.execution.process.ProcessAdapter)4 ExecutionEnvironment (com.intellij.execution.runners.ExecutionEnvironment)4 Disposable (com.intellij.openapi.Disposable)4 Application (com.intellij.openapi.application.Application)4 Task (com.intellij.openapi.progress.Task)4 VcsAbstractHistorySession (com.intellij.openapi.vcs.history.VcsAbstractHistorySession)4 VcsAppendableHistorySessionPartner (com.intellij.openapi.vcs.history.VcsAppendableHistorySessionPartner)4 VcsHistoryProvider (com.intellij.openapi.vcs.history.VcsHistoryProvider)4