Search in sources :

Example 36 with ProcessCanceledException

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

the class AbstractExternalFilter method doBuildFromStream.

protected void doBuildFromStream(final String url, Reader input, final StringBuilder data, boolean searchForEncoding, boolean matchStart) throws IOException {
    ParseSettings settings = getParseSettings(url);
    @NonNls Pattern startSection = settings.startPattern;
    @NonNls Pattern endSection = settings.endPattern;
    boolean useDt = settings.useDt;
    data.append(HTML);
    URL baseUrl = VfsUtilCore.convertToURL(url);
    if (baseUrl != null) {
        data.append("<base href=\"").append(baseUrl).append("\">");
    }
    data.append("<style type=\"text/css\">" + "  ul.inheritance {\n" + "      margin:0;\n" + "      padding:0;\n" + "  }\n" + "  ul.inheritance li {\n" + "       display:inline;\n" + "       list-style:none;\n" + "  }\n" + "  ul.inheritance li ul.inheritance {\n" + "    margin-left:15px;\n" + "    padding-left:15px;\n" + "    padding-top:1px;\n" + "  }\n" + "</style>");
    String read;
    String contentEncoding = null;
    @SuppressWarnings("IOResourceOpenedButNotSafelyClosed") BufferedReader buf = new BufferedReader(input);
    do {
        read = buf.readLine();
        if (read != null && searchForEncoding && read.contains("charset")) {
            String foundEncoding = parseContentEncoding(read);
            if (foundEncoding != null) {
                contentEncoding = foundEncoding;
            }
        }
    } while (read != null && matchStart && !startSection.matcher(StringUtil.toUpperCase(read)).find());
    if (input instanceof MyReader && contentEncoding != null && !contentEncoding.equalsIgnoreCase(CharsetToolkit.UTF8) && !contentEncoding.equals(((MyReader) input).getEncoding())) {
        //restart page parsing with correct encoding
        try {
            data.setLength(0);
            doBuildFromStream(url, new MyReader(((MyReader) input).myInputStream, contentEncoding), data, false, true);
        } catch (ProcessCanceledException e) {
            return;
        }
        return;
    }
    if (read == null) {
        data.setLength(0);
        if (matchStart && !settings.forcePatternSearch && input instanceof MyReader) {
            try {
                final MyReader reader = contentEncoding != null ? new MyReader(((MyReader) input).myInputStream, contentEncoding) : new MyReader(((MyReader) input).myInputStream, ((MyReader) input).getEncoding());
                doBuildFromStream(url, reader, data, false, false);
            } catch (ProcessCanceledException ignored) {
            }
        }
        return;
    }
    if (useDt) {
        boolean skip = false;
        do {
            if (StringUtil.toUpperCase(read).contains(H2) && !read.toUpperCase(Locale.ENGLISH).contains("H2")) {
                // read=class name in <H2>
                data.append(H2);
                skip = true;
            } else if (endSection.matcher(read).find() || StringUtil.indexOfIgnoreCase(read, GREATEST_END_SECTION, 0) != -1) {
                data.append(HTML_CLOSE);
                return;
            } else if (!skip) {
                appendLine(data, read);
            }
        } while (((read = buf.readLine()) != null) && !StringUtil.toUpperCase(read).trim().equals(DL) && !StringUtil.containsIgnoreCase(read, "<div class=\"description\""));
        data.append(DL);
        StringBuilder classDetails = new StringBuilder();
        while (((read = buf.readLine()) != null) && !StringUtil.toUpperCase(read).equals(HR) && !StringUtil.toUpperCase(read).equals(P)) {
            if (reachTheEnd(data, read, classDetails, endSection))
                return;
            appendLine(classDetails, read);
        }
        while (((read = buf.readLine()) != null) && !StringUtil.toUpperCase(read).equals(P) && !StringUtil.toUpperCase(read).equals(HR)) {
            if (reachTheEnd(data, read, classDetails, endSection))
                return;
            appendLine(data, read.replaceAll(DT, DT + BR));
        }
        data.append(classDetails);
        data.append(P);
    } else {
        appendLine(data, read);
    }
    while (((read = buf.readLine()) != null) && !endSection.matcher(read).find() && StringUtil.indexOfIgnoreCase(read, GREATEST_END_SECTION, 0) == -1) {
        if (!StringUtil.toUpperCase(read).contains(HR) && !StringUtil.containsIgnoreCase(read, "<ul class=\"blockList\">") && !StringUtil.containsIgnoreCase(read, "<li class=\"blockList\">")) {
            appendLine(data, read);
        }
    }
    data.append(HTML_CLOSE);
}
Also used : NonNls(org.jetbrains.annotations.NonNls) Pattern(java.util.regex.Pattern) URL(java.net.URL) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException)

Example 37 with ProcessCanceledException

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

the class ViewOfflineResultsAction method actionPerformed.

@Override
public void actionPerformed(AnActionEvent event) {
    final Project project = event.getData(CommonDataKeys.PROJECT);
    LOG.assertTrue(project != null);
    final FileChooserDescriptor descriptor = new FileChooserDescriptor(false, true, false, false, false, false) {

        @Override
        public Icon getIcon(VirtualFile file) {
            if (file.isDirectory()) {
                if (file.findChild(InspectionApplication.DESCRIPTIONS + "." + StdFileTypes.XML.getDefaultExtension()) != null) {
                    return AllIcons.Nodes.InspectionResults;
                }
            }
            return super.getIcon(file);
        }
    };
    descriptor.setTitle("Select Path");
    descriptor.setDescription("Select directory which contains exported inspections results");
    final VirtualFile virtualFile = FileChooser.chooseFile(descriptor, project, null);
    if (virtualFile == null || !virtualFile.isDirectory())
        return;
    final Map<String, Map<String, Set<OfflineProblemDescriptor>>> resMap = new HashMap<>();
    final String[] profileName = new String[1];
    ProgressManager.getInstance().run(new Task.Backgroundable(project, InspectionsBundle.message("parsing.inspections.dump.progress.title"), true, new PerformAnalysisInBackgroundOption(project)) {

        @Override
        public void run(@NotNull ProgressIndicator indicator) {
            final VirtualFile[] files = virtualFile.getChildren();
            try {
                for (final VirtualFile inspectionFile : files) {
                    if (inspectionFile.isDirectory())
                        continue;
                    final String shortName = inspectionFile.getNameWithoutExtension();
                    final String extension = inspectionFile.getExtension();
                    if (shortName.equals(InspectionApplication.DESCRIPTIONS)) {
                        profileName[0] = ReadAction.compute(() -> OfflineViewParseUtil.parseProfileName(LoadTextUtil.loadText(inspectionFile).toString()));
                    } else if (XML_EXTENSION.equals(extension)) {
                        resMap.put(shortName, ReadAction.compute(() -> OfflineViewParseUtil.parse(LoadTextUtil.loadText(inspectionFile).toString())));
                    }
                }
            } catch (final Exception e) {
                //all parse exceptions
                ApplicationManager.getApplication().invokeLater(() -> Messages.showInfoMessage(e.getMessage(), InspectionsBundle.message("offline.view.parse.exception.title")));
                //cancel process
                throw new ProcessCanceledException();
            }
        }

        @Override
        public void onSuccess() {
            ApplicationManager.getApplication().invokeLater(() -> {
                final String name = profileName[0];
                showOfflineView(project, name, resMap, InspectionsBundle.message("offline.view.title") + " (" + (name != null ? name : InspectionsBundle.message("offline.view.editor.settings.title")) + ")");
            });
        }
    });
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) Task(com.intellij.openapi.progress.Task) HashMap(java.util.HashMap) FileChooserDescriptor(com.intellij.openapi.fileChooser.FileChooserDescriptor) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) OfflineProblemDescriptor(com.intellij.codeInspection.offline.OfflineProblemDescriptor) Project(com.intellij.openapi.project.Project) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) PerformAnalysisInBackgroundOption(com.intellij.analysis.PerformAnalysisInBackgroundOption) HashMap(java.util.HashMap) Map(java.util.Map) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException)

Example 38 with ProcessCanceledException

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

the class ExecutionManagerImpl method startRunProfile.

@Override
public void startRunProfile(@NotNull final RunProfileStarter starter, @NotNull final RunProfileState state, @NotNull final ExecutionEnvironment environment) {
    final Project project = environment.getProject();
    RunContentDescriptor reuseContent = getContentManager().getReuseContent(environment);
    if (reuseContent != null) {
        reuseContent.setExecutionId(environment.getExecutionId());
        environment.setContentToReuse(reuseContent);
    }
    final Executor executor = environment.getExecutor();
    project.getMessageBus().syncPublisher(EXECUTION_TOPIC).processStartScheduled(executor.getId(), environment);
    Runnable startRunnable;
    startRunnable = () -> {
        if (project.isDisposed()) {
            return;
        }
        RunProfile profile = environment.getRunProfile();
        project.getMessageBus().syncPublisher(EXECUTION_TOPIC).processStarting(executor.getId(), environment);
        starter.executeAsync(state, environment).done(descriptor -> {
            AppUIUtil.invokeOnEdt(() -> {
                if (descriptor != null) {
                    final Trinity<RunContentDescriptor, RunnerAndConfigurationSettings, Executor> trinity = Trinity.create(descriptor, environment.getRunnerAndConfigurationSettings(), executor);
                    myRunningConfigurations.add(trinity);
                    Disposer.register(descriptor, () -> myRunningConfigurations.remove(trinity));
                    getContentManager().showRunContent(executor, descriptor, environment.getContentToReuse());
                    final ProcessHandler processHandler = descriptor.getProcessHandler();
                    if (processHandler != null) {
                        if (!processHandler.isStartNotified()) {
                            processHandler.startNotify();
                        }
                        project.getMessageBus().syncPublisher(EXECUTION_TOPIC).processStarted(executor.getId(), environment, processHandler);
                        ProcessExecutionListener listener = new ProcessExecutionListener(project, executor.getId(), environment, processHandler, descriptor);
                        processHandler.addProcessListener(listener);
                        boolean terminating = processHandler.isProcessTerminating();
                        boolean terminated = processHandler.isProcessTerminated();
                        if (terminating || terminated) {
                            listener.processWillTerminate(new ProcessEvent(processHandler), false);
                            if (terminated) {
                                int exitCode = processHandler.isStartNotified() ? processHandler.getExitCode() : -1;
                                listener.processTerminated(new ProcessEvent(processHandler, exitCode));
                            }
                        }
                    }
                    environment.setContentToReuse(descriptor);
                } else {
                    project.getMessageBus().syncPublisher(EXECUTION_TOPIC).processNotStarted(executor.getId(), environment);
                }
            }, o -> project.isDisposed());
        }).rejected(e -> {
            if (!(e instanceof ProcessCanceledException)) {
                ExecutionException error = e instanceof ExecutionException ? (ExecutionException) e : new ExecutionException(e);
                ExecutionUtil.handleExecutionError(project, ExecutionManager.getInstance(project).getContentManager().getToolWindowIdByEnvironment(environment), profile, error);
            }
            LOG.info(e);
            project.getMessageBus().syncPublisher(EXECUTION_TOPIC).processNotStarted(executor.getId(), environment);
        });
    };
    if (ApplicationManager.getApplication().isUnitTestMode() && !myForceCompilationInTests) {
        startRunnable.run();
    } else {
        compileAndRun(() -> TransactionGuard.submitTransaction(project, startRunnable), environment, state, () -> {
            if (!project.isDisposed()) {
                project.getMessageBus().syncPublisher(EXECUTION_TOPIC).processNotStarted(executor.getId(), environment);
            }
        });
    }
}
Also used : Trinity(com.intellij.openapi.util.Trinity) ModalityState(com.intellij.openapi.application.ModalityState) ProcessAdapter(com.intellij.execution.process.ProcessAdapter) RunProfileState(com.intellij.execution.configurations.RunProfileState) ExecutionEnvironment(com.intellij.execution.runners.ExecutionEnvironment) SmartList(com.intellij.util.SmartList) SaveAndSyncHandler(com.intellij.ide.SaveAndSyncHandler) Disposer(com.intellij.openapi.util.Disposer) Messages(com.intellij.openapi.ui.Messages) Logger(com.intellij.openapi.diagnostic.Logger) RunnerLayoutUi(com.intellij.execution.ui.RunnerLayoutUi) DumbService(com.intellij.openapi.project.DumbService) AppUIUtil(com.intellij.ui.AppUIUtil) IndexNotReadyException(com.intellij.openapi.project.IndexNotReadyException) ExecutionEnvironmentBuilder(com.intellij.execution.runners.ExecutionEnvironmentBuilder) Nullable(org.jetbrains.annotations.Nullable) ServiceManager(com.intellij.openapi.components.ServiceManager) RunContentDescriptor(com.intellij.execution.ui.RunContentDescriptor) ApplicationManager(com.intellij.openapi.application.ApplicationManager) ProcessEvent(com.intellij.execution.process.ProcessEvent) ExecutionUtil(com.intellij.execution.runners.ExecutionUtil) Registry(com.intellij.openapi.util.registry.Registry) NotNull(org.jetbrains.annotations.NotNull) java.util(java.util) RunConfiguration(com.intellij.execution.configurations.RunConfiguration) DataContext(com.intellij.openapi.actionSystem.DataContext) RunContentManager(com.intellij.execution.ui.RunContentManager) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) RunContentManagerImpl(com.intellij.execution.ui.RunContentManagerImpl) ContainerUtil(com.intellij.util.containers.ContainerUtil) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) DialogWrapper(com.intellij.openapi.ui.DialogWrapper) CommonBundle(com.intellij.CommonBundle) Project(com.intellij.openapi.project.Project) ProgramRunner(com.intellij.execution.runners.ProgramRunner) StringUtil(com.intellij.openapi.util.text.StringUtil) Key(com.intellij.openapi.util.Key) RunProfile(com.intellij.execution.configurations.RunProfile) Disposable(com.intellij.openapi.Disposable) ProcessHandler(com.intellij.execution.process.ProcessHandler) com.intellij.execution(com.intellij.execution) TestOnly(org.jetbrains.annotations.TestOnly) DockManager(com.intellij.ui.docking.DockManager) CompatibilityAwareRunProfile(com.intellij.execution.configuration.CompatibilityAwareRunProfile) SimpleDataContext(com.intellij.openapi.actionSystem.impl.SimpleDataContext) TransactionGuard(com.intellij.openapi.application.TransactionGuard) Condition(com.intellij.openapi.util.Condition) Alarm(com.intellij.util.Alarm) javax.swing(javax.swing) Project(com.intellij.openapi.project.Project) RunContentDescriptor(com.intellij.execution.ui.RunContentDescriptor) Trinity(com.intellij.openapi.util.Trinity) ProcessEvent(com.intellij.execution.process.ProcessEvent) ProcessHandler(com.intellij.execution.process.ProcessHandler) RunProfile(com.intellij.execution.configurations.RunProfile) CompatibilityAwareRunProfile(com.intellij.execution.configuration.CompatibilityAwareRunProfile) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException)

Example 39 with ProcessCanceledException

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

the class RunManagerImpl method loadState.

@Override
public void loadState(Element parentNode) {
    clear(false);
    List<Element> children = parentNode.getChildren(CONFIGURATION);
    Element[] sortedElements = children.toArray(new Element[children.size()]);
    // ensure templates are loaded first
    Arrays.sort(sortedElements, (a, b) -> {
        final boolean aDefault = Boolean.valueOf(a.getAttributeValue("default", "false"));
        final boolean bDefault = Boolean.valueOf(b.getAttributeValue("default", "false"));
        return aDefault == bDefault ? 0 : aDefault ? -1 : 1;
    });
    //noinspection ForLoopReplaceableByForEach
    for (int i = 0, length = sortedElements.length; i < length; i++) {
        Element element = sortedElements[i];
        RunnerAndConfigurationSettings configurationSettings;
        try {
            configurationSettings = loadConfiguration(element, false);
        } catch (ProcessCanceledException e) {
            configurationSettings = null;
        } catch (Throwable e) {
            LOG.error(e);
            continue;
        }
        if (configurationSettings == null) {
            if (myUnknownElements == null) {
                myUnknownElements = new SmartList<>();
            }
            myUnknownElements.add((Element) element.detach());
        }
    }
    myOrder.readExternal(parentNode);
    // migration (old ids to UUIDs)
    readList(myOrder);
    myRecentlyUsedTemporaries.clear();
    Element recentNode = parentNode.getChild(RECENT);
    if (recentNode != null) {
        JDOMExternalizableStringList list = new JDOMExternalizableStringList();
        list.readExternal(recentNode);
        readList(list);
        for (String name : list) {
            RunnerAndConfigurationSettings settings = myConfigurations.get(name);
            if (settings != null) {
                myRecentlyUsedTemporaries.add(settings.getConfiguration());
            }
        }
    }
    myOrdered = false;
    myLoadedSelectedConfigurationUniqueName = parentNode.getAttributeValue(SELECTED_ATTR);
    setSelectedConfigurationId(myLoadedSelectedConfigurationUniqueName);
    fireBeforeRunTasksUpdated();
    fireRunConfigurationSelected();
}
Also used : Element(org.jdom.Element) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException)

Example 40 with ProcessCanceledException

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

the class MultiHostRegistrarImpl method doneInjecting.

@Override
public void doneInjecting() {
    try {
        if (shreds.isEmpty()) {
            throw new IllegalStateException("Seems you haven't called addPlace()");
        }
        if (myReferenceInjector != null) {
            addToResults(new Place(shreds), null);
            return;
        }
        PsiDocumentManagerBase documentManager = (PsiDocumentManagerBase) PsiDocumentManager.getInstance(myProject);
        Place place = new Place(shreds);
        DocumentWindowImpl documentWindow = new DocumentWindowImpl(myHostDocument, isOneLineEditor, place);
        String fileName = PathUtil.makeFileName(myHostVirtualFile.getName(), fileExtension);
        VirtualFileWindowImpl virtualFile = new VirtualFileWindowImpl(fileName, myHostVirtualFile, documentWindow, myLanguage, outChars);
        Language forcedLanguage = myContextElement.getUserData(InjectedFileViewProvider.LANGUAGE_FOR_INJECTED_COPY_KEY);
        myLanguage = forcedLanguage == null ? LanguageSubstitutors.INSTANCE.substituteLanguage(myLanguage, virtualFile, myProject) : forcedLanguage;
        createDocument(virtualFile);
        InjectedFileViewProvider viewProvider = new InjectedFileViewProvider(myPsiManager, virtualFile, documentWindow, myLanguage);
        ParserDefinition parserDefinition = LanguageParserDefinitions.INSTANCE.forLanguage(myLanguage);
        assert parserDefinition != null : "Parser definition for language " + myLanguage + " is null";
        PsiFile psiFile = parserDefinition.createFile(viewProvider);
        SmartPsiElementPointer<PsiLanguageInjectionHost> pointer = ((ShredImpl) shreds.get(0)).getSmartPointer();
        synchronized (InjectedLanguageManagerImpl.ourInjectionPsiLock) {
            final ASTNode parsedNode = keepTreeFromChameleoningBack(psiFile);
            assert parsedNode instanceof FileElement : "Parsed to " + parsedNode + " instead of FileElement";
            String documentText = documentManager.getLastCommittedDocument(documentWindow).getText();
            assert ((FileElement) parsedNode).textMatches(outChars) : exceptionContext("Before patch: doc:\n'" + documentText + "'\n---PSI:\n'" + parsedNode.getText() + "'\n---chars:\n'" + outChars + "'");
            viewProvider.setPatchingLeaves(true);
            try {
                patchLeaves(parsedNode, escapers, place);
            } catch (ProcessCanceledException e) {
                throw e;
            } catch (RuntimeException e) {
                throw new RuntimeException(exceptionContext("Patch error"), e);
            } finally {
                viewProvider.setPatchingLeaves(false);
            }
            if (!((FileElement) parsedNode).textMatches(documentText)) {
                throw new AssertionError(exceptionContext("After patch: doc:\n'" + documentText + "'\n---PSI:\n'" + parsedNode.getText() + "'\n---chars:\n'" + outChars + "'"));
            }
            virtualFile.setContent(null, documentWindow.getText(), false);
            virtualFile.setWritable(virtualFile.getDelegate().isWritable());
            cacheEverything(place, documentWindow, viewProvider, psiFile, pointer);
            PsiFile cachedPsiFile = documentManager.getCachedPsiFile(documentWindow);
            assert cachedPsiFile == psiFile : "Cached psi :" + cachedPsiFile + " instead of " + psiFile;
            assert place.isValid();
            assert viewProvider.isValid();
            PsiFile newFile = registerDocument(documentWindow, psiFile, place, myHostPsiFile, documentManager);
            boolean mergeHappened = newFile != psiFile;
            if (mergeHappened) {
                InjectedLanguageUtil.clearCaches(psiFile, documentWindow);
                psiFile = newFile;
                viewProvider = (InjectedFileViewProvider) psiFile.getViewProvider();
                documentWindow = (DocumentWindowImpl) viewProvider.getDocument();
                virtualFile = (VirtualFileWindowImpl) viewProvider.getVirtualFile();
                boolean shredsRewritten = cacheEverything(place, documentWindow, viewProvider, psiFile, pointer);
                if (!shredsRewritten) {
                    place.dispose();
                    place = documentWindow.getShreds();
                }
            }
            assert psiFile.isValid();
            assert place.isValid();
            assert viewProvider.isValid();
            try {
                List<Trinity<IElementType, SmartPsiElementPointer<PsiLanguageInjectionHost>, TextRange>> tokens = obtainHighlightTokensFromLexer(myLanguage, outChars, escapers, place, virtualFile, myProject);
                psiFile.putUserData(InjectedLanguageUtil.HIGHLIGHT_TOKENS, tokens);
            } catch (ProcessCanceledException e) {
                throw e;
            } catch (RuntimeException e) {
                throw new RuntimeException(exceptionContext("Obtaining tokens error"), e);
            }
            addToResults(place, psiFile);
            assertEverythingIsAllright(documentManager, documentWindow, psiFile);
        }
    } finally {
        clear();
    }
}
Also used : VirtualFileWindowImpl(com.intellij.injected.editor.VirtualFileWindowImpl) PsiDocumentManagerBase(com.intellij.psi.impl.PsiDocumentManagerBase) ParserDefinition(com.intellij.lang.ParserDefinition) DocumentWindowImpl(com.intellij.injected.editor.DocumentWindowImpl) Language(com.intellij.lang.Language) ASTNode(com.intellij.lang.ASTNode) FileElement(com.intellij.psi.impl.source.tree.FileElement) 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