Search in sources :

Example 66 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 67 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 68 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 69 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 70 with ProcessCanceledException

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

the class ForwardDependenciesBuilder method visit.

private void visit(final PsiFile file, final ProjectFileIndex fileIndex, final PsiManager psiManager, int depth) {
    final FileViewProvider viewProvider = file.getViewProvider();
    if (viewProvider.getBaseLanguage() != file.getLanguage())
        return;
    if (getScopeOfInterest() != null && !getScopeOfInterest().contains(file))
        return;
    ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
    final VirtualFile virtualFile = file.getVirtualFile();
    if (indicator != null) {
        if (indicator.isCanceled()) {
            throw new ProcessCanceledException();
        }
        indicator.setText(AnalysisScopeBundle.message("package.dependencies.progress.text"));
        if (virtualFile != null) {
            indicator.setText2(getRelativeToProjectPath(virtualFile));
        }
        if (myTotalFileCount > 0) {
            indicator.setFraction(((double) ++myFileCount) / myTotalFileCount);
        }
    }
    final boolean isInLibrary = virtualFile == null || fileIndex.isInLibrarySource(virtualFile) || fileIndex.isInLibraryClasses(virtualFile);
    final Set<PsiFile> collectedDeps = new HashSet<>();
    final HashSet<PsiFile> processed = new HashSet<>();
    collectedDeps.add(file);
    do {
        if (depth++ > getTransitiveBorder())
            return;
        for (PsiFile psiFile : new HashSet<>(collectedDeps)) {
            final VirtualFile vFile = psiFile.getVirtualFile();
            if (vFile != null) {
                if (indicator != null) {
                    indicator.setText2(getRelativeToProjectPath(vFile));
                }
                if (!isInLibrary && (fileIndex.isInLibraryClasses(vFile) || fileIndex.isInLibrarySource(vFile))) {
                    processed.add(psiFile);
                }
            }
            final Set<PsiFile> found = new HashSet<>();
            if (!processed.contains(psiFile)) {
                processed.add(psiFile);
                analyzeFileDependencies(psiFile, new DependencyProcessor() {

                    @Override
                    public void process(PsiElement place, PsiElement dependency) {
                        PsiFile dependencyFile = dependency.getContainingFile();
                        if (dependencyFile != null) {
                            if (viewProvider == dependencyFile.getViewProvider())
                                return;
                            if (dependencyFile.isPhysical()) {
                                final VirtualFile virtualFile = dependencyFile.getVirtualFile();
                                if (virtualFile != null && (fileIndex.isInContent(virtualFile) || fileIndex.isInLibraryClasses(virtualFile) || fileIndex.isInLibrarySource(virtualFile))) {
                                    final PsiElement navigationElement = dependencyFile.getNavigationElement();
                                    found.add(navigationElement instanceof PsiFile ? (PsiFile) navigationElement : dependencyFile);
                                }
                            }
                        }
                    }
                });
                Set<PsiFile> deps = getDependencies().get(file);
                if (deps == null) {
                    deps = new HashSet<>();
                    getDependencies().put(file, deps);
                }
                deps.addAll(found);
                getDirectDependencies().put(psiFile, new HashSet<>(found));
                collectedDeps.addAll(found);
                psiManager.dropResolveCaches();
                InjectedLanguageManager.getInstance(file.getProject()).dropFileCaches(file);
            }
        }
        collectedDeps.removeAll(processed);
    } while (isTransitive() && !collectedDeps.isEmpty());
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) HashSet(java.util.HashSet)

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