Search in sources :

Example 11 with ProcessCanceledException

use of com.intellij.openapi.progress.ProcessCanceledException in project intellij-community by JetBrains.

the class TaskManagerImpl method testConnection.

@Override
public boolean testConnection(final TaskRepository repository) {
    TestConnectionTask task = new TestConnectionTask("Test connection") {

        public void run(@NotNull ProgressIndicator indicator) {
            indicator.setText("Connecting to " + repository.getUrl() + "...");
            indicator.setFraction(0);
            indicator.setIndeterminate(true);
            try {
                myConnection = repository.createCancellableConnection();
                if (myConnection != null) {
                    Future<Exception> future = ApplicationManager.getApplication().executeOnPooledThread(myConnection);
                    while (true) {
                        try {
                            myException = future.get(100, TimeUnit.MILLISECONDS);
                            return;
                        } catch (TimeoutException ignore) {
                            try {
                                indicator.checkCanceled();
                            } catch (ProcessCanceledException e) {
                                myException = e;
                                myConnection.cancel();
                                return;
                            }
                        } catch (Exception e) {
                            myException = e;
                            return;
                        }
                    }
                } else {
                    try {
                        repository.testConnection();
                    } catch (Exception e) {
                        LOG.info(e);
                        myException = e;
                    }
                }
            } catch (Exception e) {
                myException = e;
            }
        }
    };
    ProgressManager.getInstance().run(task);
    Exception e = task.myException;
    if (e == null) {
        myBadRepositories.remove(repository);
        Messages.showMessageDialog(myProject, "Connection is successful", "Connection", Messages.getInformationIcon());
    } else if (!(e instanceof ProcessCanceledException)) {
        String message = e.getMessage();
        if (e instanceof UnknownHostException) {
            message = "Unknown host: " + message;
        }
        if (message == null) {
            LOG.error(e);
            message = "Unknown error";
        }
        Messages.showErrorDialog(myProject, StringUtil.capitalize(message), "Error");
    }
    return e == null;
}
Also used : UnknownHostException(java.net.UnknownHostException) EmptyProgressIndicator(com.intellij.openapi.progress.EmptyProgressIndicator) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) NotNull(org.jetbrains.annotations.NotNull) TimeoutException(java.util.concurrent.TimeoutException) XmlSerializationException(com.intellij.util.xmlb.XmlSerializationException) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) SocketTimeoutException(java.net.SocketTimeoutException) UnknownHostException(java.net.UnknownHostException) TimeoutException(java.util.concurrent.TimeoutException) SocketTimeoutException(java.net.SocketTimeoutException) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException)

Example 12 with ProcessCanceledException

use of com.intellij.openapi.progress.ProcessCanceledException in project intellij-community by JetBrains.

the class ExternalDocumentValidator method runJaxpValidation.

private void runJaxpValidation(final XmlElement element, Validator.ValidationHost host) {
    final PsiFile file = element.getContainingFile();
    if (myFile == file && file != null && myModificationStamp == file.getModificationStamp() && !ValidateXmlActionHandler.isValidationDependentFilesOutOfDate((XmlFile) file) && // we have validated before
    SoftReference.dereference(myInfos) != null) {
        addAllInfos(host, myInfos.get());
        return;
    }
    if (myHandler == null)
        myHandler = new ValidateXmlActionHandler(false);
    final Project project = element.getProject();
    final Document document = PsiDocumentManager.getInstance(project).getDocument(file);
    if (document == null)
        return;
    final List<ValidationInfo> results = new LinkedList<>();
    myHost = new Validator.ValidationHost() {

        @Override
        public void addMessage(PsiElement context, String message, int type) {
            addMessage(context, message, type == ERROR ? ErrorType.ERROR : type == WARNING ? ErrorType.WARNING : ErrorType.INFO);
        }

        @Override
        public void addMessage(final PsiElement context, final String message, @NotNull final ErrorType type) {
            final ValidationInfo o = new ValidationInfo(context, message, type);
            results.add(o);
        }
    };
    myHandler.setErrorReporter(new ErrorReporter(myHandler) {

        @Override
        public boolean isStopOnUndeclaredResource() {
            return true;
        }

        @Override
        public void processError(final SAXParseException e, final ValidateXmlActionHandler.ProblemType warning) {
            try {
                ApplicationManager.getApplication().runReadAction(() -> {
                    if (e.getPublicId() != null) {
                        return;
                    }
                    final VirtualFile errorFile = myHandler.getProblemFile(e);
                    if (!Comparing.equal(errorFile, file.getVirtualFile()) && errorFile != null) {
                        // error in attached schema
                        return;
                    }
                    if (document.getLineCount() < e.getLineNumber() || e.getLineNumber() <= 0) {
                        return;
                    }
                    Validator.ValidationHost.ErrorType problemType = getProblemType(warning);
                    int offset = Math.max(0, document.getLineStartOffset(e.getLineNumber() - 1) + e.getColumnNumber() - 2);
                    if (offset >= document.getTextLength())
                        return;
                    PsiElement currentElement = PsiDocumentManager.getInstance(project).getPsiFile(document).findElementAt(offset);
                    PsiElement originalElement = currentElement;
                    final String elementText = currentElement.getText();
                    if (elementText.equals("</")) {
                        currentElement = currentElement.getNextSibling();
                    } else if (elementText.equals(">") || elementText.equals("=")) {
                        currentElement = currentElement.getPrevSibling();
                    }
                    // Cannot find the declaration of element
                    String localizedMessage = e.getLocalizedMessage();
                    // Ideally would be to switch one messageIds
                    int endIndex = localizedMessage.indexOf(':');
                    if (endIndex < localizedMessage.length() - 1 && localizedMessage.charAt(endIndex + 1) == '/') {
                        // ignore : in http://
                        endIndex = -1;
                    }
                    String messageId = endIndex != -1 ? localizedMessage.substring(0, endIndex) : "";
                    localizedMessage = localizedMessage.substring(endIndex + 1).trim();
                    if (localizedMessage.startsWith(CANNOT_FIND_DECLARATION_ERROR_PREFIX) || localizedMessage.startsWith(ELEMENT_ERROR_PREFIX) || localizedMessage.startsWith(ROOT_ELEMENT_ERROR_PREFIX) || localizedMessage.startsWith(CONTENT_OF_ELEMENT_TYPE_ERROR_PREFIX)) {
                        addProblemToTagName(currentElement, originalElement, localizedMessage, warning);
                    //return;
                    } else if (localizedMessage.startsWith(VALUE_ERROR_PREFIX)) {
                        addProblemToTagName(currentElement, originalElement, localizedMessage, warning);
                    } else {
                        if (messageId.startsWith(ATTRIBUTE_MESSAGE_PREFIX)) {
                            @NonNls String prefix = "of attribute ";
                            final int i = localizedMessage.indexOf(prefix);
                            if (i != -1) {
                                int messagePrefixLength = prefix.length() + i;
                                final int nextQuoteIndex = localizedMessage.indexOf(localizedMessage.charAt(messagePrefixLength), messagePrefixLength + 1);
                                String attrName = nextQuoteIndex == -1 ? null : localizedMessage.substring(messagePrefixLength + 1, nextQuoteIndex);
                                XmlTag parent = PsiTreeUtil.getParentOfType(originalElement, XmlTag.class);
                                currentElement = parent.getAttribute(attrName, null);
                                if (currentElement != null) {
                                    currentElement = ((XmlAttribute) currentElement).getValueElement();
                                }
                            }
                            if (currentElement != null) {
                                assertValidElement(currentElement, originalElement, localizedMessage);
                                myHost.addMessage(currentElement, localizedMessage, problemType);
                            } else {
                                addProblemToTagName(originalElement, originalElement, localizedMessage, warning);
                            }
                        } else if (localizedMessage.startsWith(ATTRIBUTE_ERROR_PREFIX)) {
                            final int messagePrefixLength = ATTRIBUTE_ERROR_PREFIX.length();
                            if (localizedMessage.charAt(messagePrefixLength) == '"' || localizedMessage.charAt(messagePrefixLength) == '\'') {
                                // extract the attribute name from message and get it from tag!
                                final int nextQuoteIndex = localizedMessage.indexOf(localizedMessage.charAt(messagePrefixLength), messagePrefixLength + 1);
                                String attrName = nextQuoteIndex == -1 ? null : localizedMessage.substring(messagePrefixLength + 1, nextQuoteIndex);
                                XmlTag parent = PsiTreeUtil.getParentOfType(originalElement, XmlTag.class);
                                currentElement = parent.getAttribute(attrName, null);
                                if (currentElement != null) {
                                    currentElement = SourceTreeToPsiMap.treeElementToPsi(XmlChildRole.ATTRIBUTE_NAME_FINDER.findChild(SourceTreeToPsiMap.psiElementToTree(currentElement)));
                                }
                            } else {
                                currentElement = PsiTreeUtil.getParentOfType(currentElement, XmlTag.class, false);
                            }
                            if (currentElement != null) {
                                assertValidElement(currentElement, originalElement, localizedMessage);
                                myHost.addMessage(currentElement, localizedMessage, problemType);
                            } else {
                                addProblemToTagName(originalElement, originalElement, localizedMessage, warning);
                            }
                        } else if (localizedMessage.startsWith(STRING_ERROR_PREFIX)) {
                            if (currentElement != null) {
                                myHost.addMessage(currentElement, localizedMessage, Validator.ValidationHost.ErrorType.WARNING);
                            }
                        } else {
                            currentElement = getNodeForMessage(currentElement != null ? currentElement : originalElement);
                            assertValidElement(currentElement, originalElement, localizedMessage);
                            if (currentElement != null) {
                                myHost.addMessage(currentElement, localizedMessage, problemType);
                            }
                        }
                    }
                });
            } catch (Exception ex) {
                if (ex instanceof ProcessCanceledException)
                    throw (ProcessCanceledException) ex;
                if (ex instanceof XmlResourceResolver.IgnoredResourceException)
                    throw (XmlResourceResolver.IgnoredResourceException) ex;
                LOG.error(ex);
            }
        }
    });
    myHandler.doValidate((XmlFile) element.getContainingFile());
    myFile = file;
    myModificationStamp = myFile.getModificationStamp();
    myInfos = new WeakReference<>(results);
    addAllInfos(host, results);
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) Document(com.intellij.openapi.editor.Document) XmlResourceResolver(com.intellij.xml.util.XmlResourceResolver) ErrorReporter(com.intellij.xml.actions.validate.ErrorReporter) SAXParseException(org.xml.sax.SAXParseException) PsiFile(com.intellij.psi.PsiFile) ValidateXmlActionHandler(com.intellij.xml.actions.validate.ValidateXmlActionHandler) PsiElement(com.intellij.psi.PsiElement) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) NonNls(org.jetbrains.annotations.NonNls) LinkedList(java.util.LinkedList) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) SAXParseException(org.xml.sax.SAXParseException) Project(com.intellij.openapi.project.Project) Validator(com.intellij.codeInsight.daemon.Validator)

Example 13 with ProcessCanceledException

use of com.intellij.openapi.progress.ProcessCanceledException in project intellij-community by JetBrains.

the class CheckRegExpForm method isMatchingText.

static RegExpMatchResult isMatchingText(@NotNull final PsiFile regexpFile, @NotNull String sampleText) {
    final String regExp = regexpFile.getText();
    final Language regexpFileLanguage = regexpFile.getLanguage();
    final RegExpMatcherProvider matcherProvider = RegExpMatcherProvider.EP.forLanguage(regexpFileLanguage);
    if (matcherProvider != null) {
        final RegExpMatchResult result = ReadAction.compute(() -> {
            final PsiLanguageInjectionHost host = InjectedLanguageUtil.findInjectionHost(regexpFile);
            if (host != null) {
                return matcherProvider.matches(regExp, regexpFile, host, sampleText, 1000L);
            }
            return null;
        });
        if (result != null) {
            return result;
        }
    }
    final Integer patternFlags = ReadAction.compute(() -> {
        final PsiLanguageInjectionHost host = InjectedLanguageUtil.findInjectionHost(regexpFile);
        int flags = 0;
        if (host != null) {
            for (RegExpModifierProvider provider : RegExpModifierProvider.EP.allForLanguage(host.getLanguage())) {
                flags = provider.getFlags(host, regexpFile);
                if (flags > 0)
                    break;
            }
        }
        return flags;
    });
    try {
        //noinspection MagicConstant
        return Pattern.compile(regExp, patternFlags).matcher(StringUtil.newBombedCharSequence(sampleText, 1000)).matches() ? RegExpMatchResult.MATCHES : RegExpMatchResult.NO_MATCH;
    } catch (ProcessCanceledException pc) {
        return RegExpMatchResult.TIMEOUT;
    } catch (Exception ignore) {
    }
    return RegExpMatchResult.BAD_REGEXP;
}
Also used : Language(com.intellij.lang.Language) PsiLanguageInjectionHost(com.intellij.psi.PsiLanguageInjectionHost) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException)

Example 14 with ProcessCanceledException

use of com.intellij.openapi.progress.ProcessCanceledException in project intellij-community by JetBrains.

the class CompileDriver method executeCompileTask.

public void executeCompileTask(final CompileTask task, final CompileScope scope, final String contentName, final Runnable onTaskFinished) {
    final CompilerTask progressManagerTask = new CompilerTask(myProject, contentName, false, false, true, isCompilationStartedAutomatically(scope));
    final CompileContextImpl compileContext = new CompileContextImpl(myProject, progressManagerTask, scope, false, false);
    FileDocumentManager.getInstance().saveAllDocuments();
    progressManagerTask.start(() -> {
        try {
            task.execute(compileContext);
        } catch (ProcessCanceledException ex) {
        // suppressed
        } finally {
            if (onTaskFinished != null) {
                onTaskFinished.run();
            }
        }
    }, null);
}
Also used : CompilerTask(com.intellij.compiler.progress.CompilerTask) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException)

Example 15 with ProcessCanceledException

use of com.intellij.openapi.progress.ProcessCanceledException in project intellij-community by JetBrains.

the class CompileDriver method startup.

private void startup(final CompileScope scope, final boolean isRebuild, final boolean forceCompile, final CompileStatusNotification callback, final CompilerMessage message) {
    ApplicationManager.getApplication().assertIsDispatchThread();
    final String contentName = CompilerBundle.message(forceCompile ? "compiler.content.name.compile" : "compiler.content.name.make");
    final boolean isUnitTestMode = ApplicationManager.getApplication().isUnitTestMode();
    final CompilerTask compileTask = new CompilerTask(myProject, contentName, isUnitTestMode, true, true, isCompilationStartedAutomatically(scope));
    StatusBar.Info.set("", myProject, "Compiler");
    // ensure the project model seen by build process is up-to-date
    myProject.save();
    if (!isUnitTestMode) {
        ApplicationManager.getApplication().saveSettings();
    }
    PsiDocumentManager.getInstance(myProject).commitAllDocuments();
    FileDocumentManager.getInstance().saveAllDocuments();
    final CompileContextImpl compileContext = new CompileContextImpl(myProject, compileTask, scope, !isRebuild && !forceCompile, isRebuild);
    final Runnable compileWork = () -> {
        final ProgressIndicator indicator = compileContext.getProgressIndicator();
        if (indicator.isCanceled() || myProject.isDisposed()) {
            if (callback != null) {
                callback.finished(true, 0, 0, compileContext);
            }
            return;
        }
        CompilerCacheManager compilerCacheManager = CompilerCacheManager.getInstance(myProject);
        try {
            LOG.info("COMPILATION STARTED (BUILD PROCESS)");
            if (message != null) {
                compileContext.addMessage(message);
            }
            if (isRebuild) {
                CompilerUtil.runInContext(compileContext, "Clearing build system data...", (ThrowableRunnable<Throwable>) () -> compilerCacheManager.clearCaches(compileContext));
            }
            final boolean beforeTasksOk = executeCompileTasks(compileContext, true);
            final int errorCount = compileContext.getMessageCount(CompilerMessageCategory.ERROR);
            if (!beforeTasksOk || errorCount > 0) {
                COMPILE_SERVER_BUILD_STATUS.set(compileContext, errorCount > 0 ? ExitStatus.ERRORS : ExitStatus.CANCELLED);
                return;
            }
            final TaskFuture future = compileInExternalProcess(compileContext, false);
            if (future != null) {
                while (!future.waitFor(200L, TimeUnit.MILLISECONDS)) {
                    if (indicator.isCanceled()) {
                        future.cancel(false);
                    }
                }
                if (!executeCompileTasks(compileContext, false)) {
                    COMPILE_SERVER_BUILD_STATUS.set(compileContext, ExitStatus.CANCELLED);
                }
                if (compileContext.getMessageCount(CompilerMessageCategory.ERROR) > 0) {
                    COMPILE_SERVER_BUILD_STATUS.set(compileContext, ExitStatus.ERRORS);
                }
            }
        } catch (ProcessCanceledException ignored) {
            compileContext.putUserDataIfAbsent(COMPILE_SERVER_BUILD_STATUS, ExitStatus.CANCELLED);
        } catch (Throwable e) {
            // todo
            LOG.error(e);
        } finally {
            compilerCacheManager.flushCaches();
            final long duration = notifyCompilationCompleted(compileContext, callback, COMPILE_SERVER_BUILD_STATUS.get(compileContext));
            CompilerUtil.logDuration("\tCOMPILATION FINISHED (BUILD PROCESS); Errors: " + compileContext.getMessageCount(CompilerMessageCategory.ERROR) + "; warnings: " + compileContext.getMessageCount(CompilerMessageCategory.WARNING), duration);
        }
    };
    compileTask.start(compileWork, () -> {
        if (isRebuild) {
            final int rv = Messages.showOkCancelDialog(myProject, "You are about to rebuild the whole project.\nRun 'Build Project' instead?", "Confirm Project Rebuild", "Build", "Rebuild", Messages.getQuestionIcon());
            if (rv == Messages.OK) /*yes, please, do run make*/
            {
                startup(scope, false, false, callback, null);
                return;
            }
        }
        startup(scope, isRebuild, forceCompile, callback, message);
    });
}
Also used : CompilerTask(com.intellij.compiler.progress.CompilerTask) ThrowableRunnable(com.intellij.util.ThrowableRunnable) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) ThrowableRunnable(com.intellij.util.ThrowableRunnable) TaskFuture(org.jetbrains.jps.api.TaskFuture) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException)

Aggregations

ProcessCanceledException (com.intellij.openapi.progress.ProcessCanceledException)175 NotNull (org.jetbrains.annotations.NotNull)45 ProgressIndicator (com.intellij.openapi.progress.ProgressIndicator)41 VirtualFile (com.intellij.openapi.vfs.VirtualFile)38 Project (com.intellij.openapi.project.Project)28 Nullable (org.jetbrains.annotations.Nullable)23 IOException (java.io.IOException)20 Task (com.intellij.openapi.progress.Task)16 File (java.io.File)16 Document (com.intellij.openapi.editor.Document)14 Ref (com.intellij.openapi.util.Ref)13 PsiFile (com.intellij.psi.PsiFile)12 IndexNotReadyException (com.intellij.openapi.project.IndexNotReadyException)11 Logger (com.intellij.openapi.diagnostic.Logger)10 StringUtil (com.intellij.openapi.util.text.StringUtil)9 ContainerUtil (com.intellij.util.containers.ContainerUtil)9 ArrayList (java.util.ArrayList)9 NonNls (org.jetbrains.annotations.NonNls)9 ProgressManager (com.intellij.openapi.progress.ProgressManager)8 java.util (java.util)8