Search in sources :

Example 81 with ProcessCanceledException

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

the class EditorHighlighterFactoryImpl method createEditorHighlighter.

@NotNull
@Override
public EditorHighlighter createEditorHighlighter(@NotNull VirtualFile vFile, @NotNull EditorColorsScheme settings, @Nullable Project project) {
    FileType fileType = vFile.getFileType();
    if (fileType instanceof LanguageFileType) {
        LanguageFileType substFileType = substituteFileType(((LanguageFileType) fileType).getLanguage(), vFile, project);
        if (substFileType != null) {
            EditorHighlighterProvider provider = FileTypeEditorHighlighterProviders.INSTANCE.forFileType(substFileType);
            EditorHighlighter editorHighlighter = provider.getEditorHighlighter(project, substFileType, vFile, settings);
            boolean isPlain = editorHighlighter.getClass() == LexerEditorHighlighter.class && ((LexerEditorHighlighter) editorHighlighter).isPlain();
            if (!isPlain) {
                return editorHighlighter;
            }
        }
        try {
            return FileTypeEditorHighlighterProviders.INSTANCE.forFileType(fileType).getEditorHighlighter(project, fileType, vFile, settings);
        } catch (ProcessCanceledException e) {
            throw e;
        } catch (Exception e) {
            LOG.error(e);
        }
    }
    SyntaxHighlighter highlighter = SyntaxHighlighterFactory.getSyntaxHighlighter(fileType, project, vFile);
    return createEditorHighlighter(highlighter, settings);
}
Also used : LexerEditorHighlighter(com.intellij.openapi.editor.ex.util.LexerEditorHighlighter) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) LexerEditorHighlighter(com.intellij.openapi.editor.ex.util.LexerEditorHighlighter) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) NotNull(org.jetbrains.annotations.NotNull)

Example 82 with ProcessCanceledException

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

the class SpringSourceObr method queryForMavenArtifact.

@NotNull
public ObrMavenResult[] queryForMavenArtifact(@NotNull String queryString, @NotNull ProgressIndicator indicator) throws IOException {
    try {
        // TODO: make this more robust against URL changes.
        List<ObrMavenResult> result = new ArrayList<>();
        indicator.setText("Connecting to " + getDisplayName() + "...");
        // http://www.springsource.com/repository/app/search?query=log4j
        // http://www.springsource.com/repository/app/bundle/version/detail?name=com.springsource.org.apache.log4j&version=1.2.15&searchType=bundlesByName&searchQuery=log4j
        String url = "http://www.springsource.com/repository/app/search?query=" + URLEncoder.encode(queryString, "utf-8");
        String contents = HttpRequests.request(url).readString(indicator);
        indicator.setText("Search completed. Getting results.");
        indicator.checkCanceled();
        // now it's happy regexp-parsing
        // first, get the results fragment, it's a single div
        // <div id="results_fragment"> ... content ... </div> and no divs inbetween.
        // we can do this with cheap indexof
        int start = contents.indexOf("<div id=\"results-fragment\">");
        int end = contents.indexOf("</div>", start);
        contents = contents.substring(start, end);
        // next up, we extract all links in there which leads us to the search results
        // <li>*whitespace*<a href="url">Package Name</a>Package Version*whitespace*</li>
        // on multiple lines. We in fact only care for the URLs.
        Matcher m = RESULT_PARSING_PATTERN.matcher(contents);
        while (m.find()) {
            String detailUrl = m.group(1);
            // cut out the session id.
            detailUrl = detailUrl.replaceAll(";jsessionid.*?\\?", "?");
            // replace &amp; with &
            detailUrl = detailUrl.replace("&amp;", "&");
            String packageName = m.group(2);
            indicator.setText("Loading details for result " + packageName + "...");
            // read the detail page.
            // the detail url always starts with a / so we can just concatenate it
            String detail = HttpRequests.request("http://www.springsource.com" + detailUrl).readString(indicator);
            indicator.checkCanceled();
            indicator.setText("Details retrieved. Getting detail information...");
            // we have the maven dependency in some nice html gibberish in there
            // &lt;groupId&gt;org.apache.log4j&lt;/groupId&gt;
            // &lt;artifactId&gt;com.springsource.org.apache.log4j&lt;/artifactId&gt;
            // &lt;version&gt;1.2.15&lt;/version&gt;
            String groupId;
            String artifactId;
            String version;
            String classifier = null;
            Matcher groupMatcher = GROUP_ID_PATTERN.matcher(detail);
            if (groupMatcher.find()) {
                groupId = groupMatcher.group(1);
            } else {
                continue;
            }
            Matcher artifactMatcher = ARTIFACT_ID_PATTERN.matcher(detail);
            if (artifactMatcher.find()) {
                artifactId = artifactMatcher.group(1);
            } else {
                continue;
            }
            Matcher versionMatcher = VERSION_PATTERN.matcher(detail);
            if (versionMatcher.find()) {
                version = versionMatcher.group(1);
            } else {
                continue;
            }
            Matcher classifierMatcher = CLASSIFIER_PATTERN.matcher(detail);
            if (classifierMatcher.find()) {
                classifier = classifierMatcher.group(1);
            }
            // no else here ,since the classifier is optional
            // finally add the result to the list
            result.add(new ObrMavenResult(groupId, artifactId, version, classifier, this));
        }
        indicator.setText("Done. " + result.size() + " artifacts found.");
        return result.toArray(new ObrMavenResult[result.size()]);
    } catch (ProcessCanceledException ignored) {
        indicator.setText("Canceled.");
        return new ObrMavenResult[0];
    } finally {
        indicator.setIndeterminate(false);
    }
}
Also used : Matcher(java.util.regex.Matcher) ArrayList(java.util.ArrayList) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) NotNull(org.jetbrains.annotations.NotNull)

Example 83 with ProcessCanceledException

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

the class DebugInfoAnnotator method annotate.

@Override
public void annotate(@NotNull PsiElement element, @NotNull final AnnotationHolder holder) {
    if (!isDebugInfoEnabled() || !ProjectRootsUtil.isInProjectOrLibSource(element)) {
        return;
    }
    if (element instanceof KtFile && !(element instanceof KtCodeFragment)) {
        KtFile file = (KtFile) element;
        try {
            BindingContext bindingContext = ResolutionUtils.analyzeFully(file);
            DebugInfoUtil.markDebugAnnotations(file, bindingContext, new DebugInfoUtil.DebugInfoReporter() {

                @Override
                public void reportElementWithErrorType(@NotNull KtReferenceExpression expression) {
                    holder.createErrorAnnotation(expression, "[DEBUG] Resolved to error element").setTextAttributes(KotlinHighlightingColors.RESOLVED_TO_ERROR);
                }

                @Override
                public void reportMissingUnresolved(@NotNull KtReferenceExpression expression) {
                    holder.createErrorAnnotation(expression, "[DEBUG] Reference is not resolved to anything, but is not marked unresolved").setTextAttributes(KotlinHighlightingColors.DEBUG_INFO);
                }

                @Override
                public void reportUnresolvedWithTarget(@NotNull KtReferenceExpression expression, @NotNull String target) {
                    holder.createErrorAnnotation(expression, "[DEBUG] Reference marked as unresolved is actually resolved to " + target).setTextAttributes(KotlinHighlightingColors.DEBUG_INFO);
                }
            });
        } catch (ProcessCanceledException e) {
            throw e;
        } catch (Throwable e) {
            // TODO
            holder.createErrorAnnotation(element, e.getClass().getCanonicalName() + ": " + e.getMessage());
            e.printStackTrace();
        }
    }
}
Also used : KtReferenceExpression(org.jetbrains.kotlin.psi.KtReferenceExpression) KtCodeFragment(org.jetbrains.kotlin.psi.KtCodeFragment) KtFile(org.jetbrains.kotlin.psi.KtFile) BindingContext(org.jetbrains.kotlin.resolve.BindingContext) DebugInfoUtil(org.jetbrains.kotlin.checkers.DebugInfoUtil) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException)

Example 84 with ProcessCanceledException

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

the class ResolveAction method actionPerformed.

@Override
public void actionPerformed(@NotNull AnActionEvent event) {
    VirtualFile virtualFile = event.getData(CommonDataKeys.VIRTUAL_FILE);
    Project project = event.getProject();
    if (virtualFile == null || project == null)
        return;
    Document document = FileDocumentManager.getInstance().getDocument(virtualFile);
    if (document == null)
        return;
    FileDocumentManager.getInstance().saveAllDocuments();
    new Task.Backgroundable(project, message("bnd.resolve.requirements.title"), true) {

        private Map<Resource, List<Wire>> resolveResult;

        private String updatedText;

        @Override
        public void run(@NotNull ProgressIndicator indicator) {
            indicator.setIndeterminate(true);
            File file = new File(virtualFile.getPath());
            try (Workspace workspace = Workspace.findWorkspace(file);
                Run run = Run.createRun(workspace, file);
                ProjectResolver projectResolver = new ProjectResolver(run)) {
                resolveResult = projectResolver.resolve();
                List<VersionedClause> versionedClauses = projectResolver.getRunBundles().stream().map(c -> {
                    Attrs attrs = new Attrs();
                    attrs.put(Constants.VERSION_ATTRIBUTE, c.getVersion());
                    return new VersionedClause(c.getBundleSymbolicName(), attrs);
                }).sorted(Comparator.comparing(VersionedClause::getName)).collect(Collectors.toList());
                BndEditModel editModel = new BndEditModel();
                IDocument bndDocument = new aQute.bnd.properties.Document(document.getImmutableCharSequence().toString());
                editModel.loadFrom(bndDocument);
                editModel.setRunBundles(versionedClauses);
                editModel.saveChangesTo(bndDocument);
                updatedText = bndDocument.get();
            } catch (ProcessCanceledException e) {
                throw e;
            } catch (Exception e) {
                throw new WrappingException(e);
            }
            indicator.checkCanceled();
        }

        @Override
        public void onSuccess() {
            if (new ResolutionSucceedDialog(project, resolveResult).showAndGet() && FileModificationService.getInstance().prepareVirtualFilesForWrite(project, Collections.singleton(virtualFile))) {
                writeCommandAction(project).withName("Bndrun Resolve").run(() -> document.setText(updatedText));
            }
        }

        @Override
        public void onThrowable(@NotNull Throwable t) {
            Throwable cause = t instanceof WrappingException ? t.getCause() : t;
            LOG.warn("Resolution failed", cause);
            if (cause instanceof ResolutionException) {
                new ResolutionFailedDialog(project, (ResolutionException) cause).show();
            } else {
                OsmorcBundle.notification(message("bnd.resolve.failed.title"), cause.getMessage(), NotificationType.ERROR).notify(project);
            }
        }
    }.queue();
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) WriteCommandAction.writeCommandAction(com.intellij.openapi.command.WriteCommandAction.writeCommandAction) Constants(aQute.bnd.osgi.Constants) VirtualFile(com.intellij.openapi.vfs.VirtualFile) Document(com.intellij.openapi.editor.Document) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) Task(com.intellij.openapi.progress.Task) Workspace(aQute.bnd.build.Workspace) DialogWrapper(com.intellij.openapi.ui.DialogWrapper) Map(java.util.Map) Project(com.intellij.openapi.project.Project) CommonDataKeys(com.intellij.openapi.actionSystem.CommonDataKeys) Logger(com.intellij.openapi.diagnostic.Logger) OsmorcBundle.message(org.osmorc.i18n.OsmorcBundle.message) BndEditModel(aQute.bnd.build.model.BndEditModel) OsmorcBundle(org.osmorc.i18n.OsmorcBundle) ProjectResolver(biz.aQute.resolve.ProjectResolver) FileModificationService(com.intellij.codeInsight.FileModificationService) Resource(org.osgi.resource.Resource) AnAction(com.intellij.openapi.actionSystem.AnAction) FileDocumentManager(com.intellij.openapi.fileEditor.FileDocumentManager) Run(aQute.bnd.build.Run) Collectors(java.util.stream.Collectors) File(java.io.File) NotificationType(com.intellij.notification.NotificationType) BndFileType(org.jetbrains.osgi.bnd.BndFileType) Nullable(org.jetbrains.annotations.Nullable) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) List(java.util.List) IDocument(aQute.bnd.properties.IDocument) VersionedClause(aQute.bnd.build.model.clauses.VersionedClause) Attrs(aQute.bnd.header.Attrs) Wire(org.osgi.resource.Wire) AnActionEvent(com.intellij.openapi.actionSystem.AnActionEvent) ResolutionException(org.osgi.service.resolver.ResolutionException) NotNull(org.jetbrains.annotations.NotNull) Comparator(java.util.Comparator) Collections(java.util.Collections) javax.swing(javax.swing) Task(com.intellij.openapi.progress.Task) VersionedClause(aQute.bnd.build.model.clauses.VersionedClause) ProjectResolver(biz.aQute.resolve.ProjectResolver) Attrs(aQute.bnd.header.Attrs) Document(com.intellij.openapi.editor.Document) IDocument(aQute.bnd.properties.IDocument) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) List(java.util.List) BndEditModel(aQute.bnd.build.model.BndEditModel) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) Resource(org.osgi.resource.Resource) Run(aQute.bnd.build.Run) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) ResolutionException(org.osgi.service.resolver.ResolutionException) ResolutionException(org.osgi.service.resolver.ResolutionException) Project(com.intellij.openapi.project.Project) VirtualFile(com.intellij.openapi.vfs.VirtualFile) File(java.io.File) IDocument(aQute.bnd.properties.IDocument) Workspace(aQute.bnd.build.Workspace)

Example 85 with ProcessCanceledException

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

the class ManifestInfo method getMergedManifest.

@NotNull
static MergingReport getMergedManifest(@NotNull AndroidFacet facet, @NotNull VirtualFile primaryManifestFile, @NotNull List<VirtualFile> flavorAndBuildTypeManifests, @NotNull List<VirtualFile> libManifests) throws ManifestMerger2.MergeFailureException {
    ApplicationManager.getApplication().assertReadAccessAllowed();
    final File mainManifestFile = VfsUtilCore.virtualToIoFile(primaryManifestFile);
    ILogger logger = NullLogger.getLogger();
    ManifestMerger2.MergeType mergeType = facet.isAppProject() ? ManifestMerger2.MergeType.APPLICATION : ManifestMerger2.MergeType.LIBRARY;
    AndroidModel androidModel = facet.getAndroidModel();
    AndroidModuleModel gradleModel = AndroidModuleModel.get(facet);
    ManifestMerger2.Invoker manifestMergerInvoker = ManifestMerger2.newMerger(mainManifestFile, logger, mergeType);
    manifestMergerInvoker.withFeatures(ManifestMerger2.Invoker.Feature.SKIP_BLAME, ManifestMerger2.Invoker.Feature.SKIP_XML_STRING);
    manifestMergerInvoker.addFlavorAndBuildTypeManifests(VfsUtilCore.virtualToIoFiles(flavorAndBuildTypeManifests).toArray(new File[0]));
    List<Pair<String, File>> libraryManifests = new ArrayList<>();
    for (VirtualFile file : libManifests) {
        libraryManifests.add(Pair.of(file.getName(), VfsUtilCore.virtualToIoFile(file)));
    }
    manifestMergerInvoker.addBundleManifests(libraryManifests);
    if (androidModel != null) {
        AndroidVersion minSdkVersion = androidModel.getMinSdkVersion();
        if (minSdkVersion != null) {
            manifestMergerInvoker.setOverride(ManifestSystemProperty.MIN_SDK_VERSION, minSdkVersion.getApiString());
        }
        AndroidVersion targetSdkVersion = androidModel.getTargetSdkVersion();
        if (targetSdkVersion != null) {
            manifestMergerInvoker.setOverride(ManifestSystemProperty.TARGET_SDK_VERSION, targetSdkVersion.getApiString());
        }
        Integer versionCode = androidModel.getVersionCode();
        if (versionCode != null && versionCode > 0) {
            manifestMergerInvoker.setOverride(ManifestSystemProperty.VERSION_CODE, String.valueOf(versionCode));
        }
        String packageOverride = androidModel.getApplicationId();
        if (!Strings.isNullOrEmpty(packageOverride)) {
            manifestMergerInvoker.setOverride(ManifestSystemProperty.PACKAGE, packageOverride);
        }
    }
    if (gradleModel != null) {
        BuildTypeContainer buildTypeContainer = gradleModel.findBuildType(gradleModel.getSelectedVariant().getBuildType());
        assert buildTypeContainer != null;
        BuildType buildType = buildTypeContainer.getBuildType();
        ProductFlavor mergedProductFlavor = gradleModel.getSelectedVariant().getMergedFlavor();
        // copy-paste from {@link VariantConfiguration#getManifestPlaceholders()}
        Map<String, Object> placeHolders = new HashMap<>(mergedProductFlavor.getManifestPlaceholders());
        placeHolders.putAll(buildType.getManifestPlaceholders());
        manifestMergerInvoker.setPlaceHolderValues(placeHolders);
        // @deprecated maxSdkVersion has been ignored since Android 2.1 (API level 7)
        Integer maxSdkVersion = mergedProductFlavor.getMaxSdkVersion();
        if (maxSdkVersion != null) {
            manifestMergerInvoker.setOverride(ManifestSystemProperty.MAX_SDK_VERSION, maxSdkVersion.toString());
        }
        // TODO we should have version Name for non-gradle projects
        // copy-paste from {@link VariantConfiguration#getVersionName()}
        String versionName = mergedProductFlavor.getVersionName();
        String flavorVersionNameSuffix = null;
        if (gradleModel.getFeatures().isProductFlavorVersionSuffixSupported()) {
            flavorVersionNameSuffix = getVersionNameSuffix(mergedProductFlavor);
        }
        String versionNameSuffix = Joiner.on("").skipNulls().join(flavorVersionNameSuffix, getVersionNameSuffix(buildType));
        if (!Strings.isNullOrEmpty(versionName) || !Strings.isNullOrEmpty(versionNameSuffix)) {
            if (Strings.isNullOrEmpty(versionName)) {
                Manifest manifest = facet.getManifest();
                if (manifest != null) {
                    versionName = manifest.getXmlTag().getAttributeValue(SdkConstants.ATTR_VERSION_NAME, ANDROID_URI);
                }
            }
            if (!Strings.isNullOrEmpty(versionNameSuffix)) {
                versionName = Strings.nullToEmpty(versionName) + versionNameSuffix;
            }
            manifestMergerInvoker.setOverride(ManifestSystemProperty.VERSION_NAME, versionName);
        }
    }
    if (mergeType == ManifestMerger2.MergeType.APPLICATION) {
        manifestMergerInvoker.withFeatures(ManifestMerger2.Invoker.Feature.REMOVE_TOOLS_DECLARATIONS);
    }
    final Module module = facet.getModule();
    final Project project = module.getProject();
    manifestMergerInvoker.withFileStreamProvider(new ManifestMerger2.FileStreamProvider() {

        @Override
        protected InputStream getInputStream(@NotNull File file) throws FileNotFoundException {
            VirtualFile vFile;
            if (file == mainManifestFile) {
                // Some tests use VirtualFile files (e.g. temp:///src/AndroidManifest.xml) for the main manifest
                vFile = primaryManifestFile;
            } else {
                vFile = VfsUtil.findFileByIoFile(file, false);
            }
            assert vFile != null : file;
            // findModuleForFile does not work for other build systems (e.g. bazel)
            if (!libManifests.isEmpty()) {
                Module moduleContainingManifest = getAndroidModuleForManifest(vFile);
                if (moduleContainingManifest != null && !module.equals(moduleContainingManifest)) {
                    MergedManifest manifest = MergedManifest.get(moduleContainingManifest);
                    Document document = manifest.getDocument();
                    if (document != null) {
                        // normally the case, but can fail on merge fail
                        // This is not very efficient. Consider enhancing the manifest merger API
                        // such that I can pass back a fully merged DOM document instead of
                        // an XML string since it will need to turn around and parse it anyway.
                        String text = XmlUtils.toXml(document);
                        return new ByteArrayInputStream(text.getBytes(Charsets.UTF_8));
                    }
                }
            }
            try {
                PsiFile psiFile = PsiManager.getInstance(project).findFile(vFile);
                if (psiFile != null) {
                    String text = psiFile.getText();
                    return new ByteArrayInputStream(text.getBytes(Charsets.UTF_8));
                }
            } catch (ProcessCanceledException ignore) {
            // During startup we may receive a progress canceled exception here,
            // but we don't *need* to read from PSI; we can read directly from
            // disk. PSI is useful when the file has been modified, but that's not
            // the case in the typical scenario where we hit process canceled.
            }
            return super.getInputStream(file);
        }

        @Nullable
        private Module getAndroidModuleForManifest(@NotNull VirtualFile vFile) {
            // project and look at their source providers
            for (Module m : ModuleManager.getInstance(project).getModules()) {
                AndroidFacet androidFacet = AndroidFacet.getInstance(m);
                if (androidFacet == null) {
                    continue;
                }
                List<VirtualFile> manifestFiles = IdeaSourceProvider.getManifestFiles(androidFacet);
                for (VirtualFile manifestFile : manifestFiles) {
                    if (vFile.equals(manifestFile)) {
                        return m;
                    }
                }
            }
            return null;
        }
    });
    return manifestMergerInvoker.merge();
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) FileNotFoundException(java.io.FileNotFoundException) Document(org.w3c.dom.Document) ILogger(com.android.utils.ILogger) PsiFile(com.intellij.psi.PsiFile) ImmutableList(com.google.common.collect.ImmutableList) Pair(com.android.utils.Pair) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) AndroidVersion(com.android.sdklib.AndroidVersion) Manifest(org.jetbrains.android.dom.manifest.Manifest) AndroidFacet(org.jetbrains.android.facet.AndroidFacet) Project(com.intellij.openapi.project.Project) ByteArrayInputStream(java.io.ByteArrayInputStream) AndroidModuleModel(com.android.tools.idea.gradle.project.model.AndroidModuleModel) Module(com.intellij.openapi.module.Module) VirtualFile(com.intellij.openapi.vfs.VirtualFile) PsiFile(com.intellij.psi.PsiFile) File(java.io.File) Nullable(org.jetbrains.annotations.Nullable) NotNull(org.jetbrains.annotations.NotNull)

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