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);
}
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 & with &
detailUrl = detailUrl.replace("&", "&");
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
// <groupId>org.apache.log4j</groupId>
// <artifactId>com.springsource.org.apache.log4j</artifactId>
// <version>1.2.15</version>
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);
}
}
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();
}
}
}
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();
}
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();
}
Aggregations