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);
}
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")) + ")");
});
}
});
}
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);
}
});
}
}
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();
}
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();
}
}
Aggregations