From 74bfdbf15c0d0c4bd4faa5264a76adc484152e65 Mon Sep 17 00:00:00 2001 From: Alexey Kudravtsev Date: Wed, 16 Apr 2014 13:18:18 +0400 Subject: [PATCH] simplify, introduce runWriteCommandAction(ThrowableComputable) --- .../intellij/compiler/impl/CompileDriver.java | 62 ++++---- .../impl/TranslatingCompilerFilesMonitor.java | 15 +- .../javaCompiler/api/CompilerAPICompiler.java | 27 ++-- .../javaCompiler/eclipse/EclipseCompiler.java | 20 +-- .../eclipse/EclipseEmbeddedCompiler.java | 25 ++-- .../javaCompiler/jikes/JikesCompiler.java | 20 +-- .../intellij/compiler/make/CacheUtils.java | 68 ++++----- .../ui/configuration/ModulesConfigurator.java | 28 ++-- .../intellij/debugger/impl/OutputChecker.java | 134 ++++++++---------- .../openapi/command/WriteCommandAction.java | 61 ++++---- .../src/com/intellij/util/ActionRunner.java | 121 ++++------------ .../editorActions/PasteHandler.java | 2 + .../openapi/options/SchemesManagerImpl.java | 20 +-- .../vfs/impl/local/LocalFileSystemImpl.java | 7 +- .../LightPlatformCodeInsightTestCase.java | 51 +++---- .../impl/CodeInsightTestFixtureImpl.java | 35 +++-- .../impl/patch/formove/PathsVerifier.java | 18 +-- .../importWizard/EclipseImportBuilder.java | 20 +-- .../references/I18nizeQuickFixDialog.java | 40 ++++-- .../treeConflict/MergeFromTheirsResolver.java | 90 ++++++------ .../plugins/relaxNG/HighlightingTestBase.java | 9 +- 21 files changed, 366 insertions(+), 507 deletions(-) diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java b/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java index ce5a6072ca43..342ff2efdfea 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -1216,7 +1216,7 @@ public class CompileDriver { private void clearAffectedOutputPathsIfPossible(final CompileContextEx context) { final List scopeOutputs = new ReadAction>() { - protected void run(final Result> result) { + protected void run(@NotNull final Result> result) { final MultiMap outputToModulesMap = new MultiMap(); for (Module module : ModuleManager.getInstance(myProject).getModules()) { final CompilerModuleExtension compilerModuleExtension = CompilerModuleExtension.getInstance(module); @@ -1900,40 +1900,33 @@ public class CompileDriver { final Set pathsToRemove = new HashSet(cache.getUrls()); final Map itemToOutputPathMap = new HashMap(); - final IOException[] ex = {null}; - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { + ApplicationManager.getApplication().runReadAction(new ThrowableComputable() { + @Override + public Void compute() throws IOException { for (final GeneratingCompiler.GenerationItem item : allItems) { + final Module itemModule = item.getModule(); final String outputDirPath = CompilerPaths.getGenerationOutputPath(compiler, itemModule, item.isTestSource()); final String outputPath = outputDirPath + "/" + item.getPath(); itemToOutputPathMap.put(item, outputPath); + final ValidityState savedState = cache.getState(outputPath); - try { - final ValidityState savedState = cache.getState(outputPath); - - if (forceGenerate || savedState == null || !savedState.equalsTo(item.getValidityState())) { - final String outputPathUrl = VirtualFileManager.constructUrl(LocalFileSystem.PROTOCOL, outputPath); - if (context.getCompileScope().belongs(outputPathUrl)) { - toGenerate.add(item); - } - else { - pathsToRemove.remove(outputPath); - } + if (forceGenerate || savedState == null || !savedState.equalsTo(item.getValidityState())) { + final String outputPathUrl = VirtualFileManager.constructUrl(LocalFileSystem.PROTOCOL, outputPath); + if (context.getCompileScope().belongs(outputPathUrl)) { + toGenerate.add(item); } else { pathsToRemove.remove(outputPath); } } - catch (IOException e) { - ex[0] = e; + else { + pathsToRemove.remove(outputPath); } } + return null; } }); - if (ex[0] != null) { - throw ex[0]; - } if (onlyCheckStatus) { if (toGenerate.isEmpty() && pathsToRemove.isEmpty()) { @@ -2514,7 +2507,7 @@ public class CompileDriver { final Boolean refreshSuccess = new WriteAction() { @Override - protected void run(Result result) throws Throwable { + protected void run(@NotNull Result result) throws Throwable { LocalFileSystem.getInstance().refreshIoFiles(nonExistingOutputPaths); Boolean res = Boolean.TRUE; for (File file : nonExistingOutputPaths) { @@ -2740,26 +2733,19 @@ public class CompileDriver { list.add(new Pair(cache, item)); } - public void doUpdate() throws IOException{ - final IOException[] ex = {null}; - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - try { - for (Map.Entry>> entry : myData.entrySet()) { - for (Pair pair : entry.getValue()) { - final FileProcessingCompiler.ProcessingItem item = pair.getSecond(); - pair.getFirst().update(entry.getKey(), item.getValidityState()); - } + public void doUpdate() throws IOException { + ApplicationManager.getApplication().runReadAction(new ThrowableComputable() { + @Override + public Void compute() throws IOException { + for (Map.Entry>> entry : myData.entrySet()) { + for (Pair pair : entry.getValue()) { + final FileProcessingCompiler.ProcessingItem item = pair.getSecond(); + pair.getFirst().update(entry.getKey(), item.getValidityState()); } } - catch (IOException e) { - ex[0] = e; - } + return null; } }); - if (ex[0] != null) { - throw ex[0]; - } } } diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/TranslatingCompilerFilesMonitor.java b/java/compiler/impl/src/com/intellij/compiler/impl/TranslatingCompilerFilesMonitor.java index 3ee643e170cd..c82e7bd13707 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/TranslatingCompilerFilesMonitor.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/TranslatingCompilerFilesMonitor.java @@ -405,11 +405,10 @@ public class TranslatingCompilerFilesMonitor implements ApplicationComponent { final int projectId = getProjectId(project); if (!successfullyCompiled.isEmpty()) { final LocalFileSystem lfs = LocalFileSystem.getInstance(); - final IOException[] exceptions = {null}; // need read action here to ensure that no modifications were made to VFS while updating file attributes - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - try { + ApplicationManager.getApplication().runReadAction(new ThrowableComputable() { + @Override + public Void compute() throws IOException { final Map compiledSources = new HashMap(); final Set forceRecompile = new HashSet(); @@ -477,15 +476,9 @@ public class TranslatingCompilerFilesMonitor implements ApplicationComponent { addSourceForRecompilation(projectId, file, info); } } - } - catch (IOException e) { - exceptions[0] = e; - } + return null; } }); - if (exceptions[0] != null) { - throw exceptions[0]; - } } if (filesToRecompile.length > 0) { diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/api/CompilerAPICompiler.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/api/CompilerAPICompiler.java index c29b5c515aa2..19e2a0bf6fbf 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/api/CompilerAPICompiler.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/api/CompilerAPICompiler.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,7 +30,7 @@ import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.JavaSdkVersion; -import com.intellij.openapi.util.Computable; +import com.intellij.openapi.util.ThrowableComputable; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; @@ -101,27 +101,20 @@ public class CompilerAPICompiler implements BackendCompiler { @NotNull public Process launchProcess(@NotNull final ModuleChunk chunk, @NotNull final String outputDir, @NotNull final CompileContext compileContext) throws IOException { - final IOException[] ex = {null}; - @NonNls final List commandLine = ApplicationManager.getApplication().runReadAction(new Computable>() { - public List compute() { - try { + @NonNls final List commandLine = + ApplicationManager.getApplication().runReadAction(new ThrowableComputable, IOException>() { + @Override + public List compute() throws IOException { List commandLine = new ArrayList(); final List additionalOptions = - JavacCompiler.addAdditionalSettings(commandLine, CompilerAPIConfiguration.getOptions(myProject, CompilerAPIConfiguration.class), false, JavaSdkVersion.JDK_1_6, chunk, compileContext.isAnnotationProcessorsEnabled()); + JavacCompiler.addAdditionalSettings(commandLine, CompilerAPIConfiguration .getOptions(myProject, CompilerAPIConfiguration.class), false, + JavaSdkVersion.JDK_1_6, chunk, compileContext.isAnnotationProcessorsEnabled()); - JavacCompiler.addCommandLineOptions(chunk, commandLine, outputDir, chunk.getJdk(), false,false, null, false, false, false); + JavacCompiler.addCommandLineOptions(chunk, commandLine, outputDir, chunk.getJdk(), false, false, null, false, false, false); commandLine.addAll(additionalOptions); return commandLine; } - catch (IOException e) { - ex[0] = e; - } - return null; - } - }); - if (ex[0] != null) { - throw ex[0]; - } + }); return new MyProcess(commandLine, chunk, outputDir, compileContext); } diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/eclipse/EclipseCompiler.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/eclipse/EclipseCompiler.java index 615315dd8f8a..d9a7c303494f 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/eclipse/EclipseCompiler.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/eclipse/EclipseCompiler.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,6 +31,7 @@ import com.intellij.openapi.projectRoots.JavaSdkType; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.projectRoots.impl.JavaAwareProjectJdkTableImpl; import com.intellij.openapi.ui.Messages; +import com.intellij.openapi.util.ThrowableComputable; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; @@ -130,20 +131,13 @@ public class EclipseCompiler extends ExternalCompiler { throws IOException { final ArrayList commandLine = new ArrayList(); - final IOException[] ex = {null}; - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - try { - createStartupCommand(chunk, commandLine, outputPath, true); - } - catch (IOException e) { - ex[0] = e; - } + ApplicationManager.getApplication().runReadAction(new ThrowableComputable() { + @Override + public Void compute() throws IOException { + createStartupCommand(chunk, commandLine, outputPath, true); + return null; } }); - if (ex[0] != null) { - throw ex[0]; - } return ArrayUtil.toStringArray(commandLine); } diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/eclipse/EclipseEmbeddedCompiler.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/eclipse/EclipseEmbeddedCompiler.java index 77aa2a162ea1..ed6c03a451be 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/eclipse/EclipseEmbeddedCompiler.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/eclipse/EclipseEmbeddedCompiler.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,6 +28,7 @@ import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.ThrowableComputable; import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; @@ -104,21 +105,15 @@ public class EclipseEmbeddedCompiler implements BackendCompiler { @NotNull public Process launchProcess(@NotNull final ModuleChunk chunk, @NotNull final String outputDir, @NotNull final CompileContext compileContext) throws IOException { @NonNls final ArrayList commandLine = new ArrayList(); - final IOException[] ex = {null}; - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - try { - final EclipseCompilerOptions options = EclipseCompilerConfiguration.getOptions(myProject, EclipseEmbeddedCompilerConfiguration.class); - myEclipseExternalCompiler.addCommandLineOptions(commandLine, chunk, outputDir, options, false, false); - } - catch (IOException e) { - ex[0] = e; - } + ApplicationManager.getApplication().runReadAction(new ThrowableComputable() { + @Override + public Void compute() throws IOException { + final EclipseCompilerOptions options = + EclipseCompilerConfiguration.getOptions(myProject, EclipseEmbeddedCompilerConfiguration.class); + myEclipseExternalCompiler.addCommandLineOptions(commandLine, chunk, outputDir, options, false, false); + return null; } }); - if (ex[0] != null) { - throw ex[0]; - } return new Process() { public OutputStream getOutputStream() { @@ -140,7 +135,7 @@ public class EclipseEmbeddedCompiler implements BackendCompiler { try { commandLine.remove("-verbose"); String[] finalCmds = ArrayUtil.toStringArray(commandLine); - myEclipseCompilerDriver.parseCommandLineAndCompile(finalCmds,compileContext); + myEclipseCompilerDriver.parseCommandLineAndCompile(finalCmds, compileContext); myExitCode = 0; return myExitCode; } diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/jikes/JikesCompiler.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/jikes/JikesCompiler.java index fb4eed3a4927..fb0246fa0fa7 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/jikes/JikesCompiler.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/jikes/JikesCompiler.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,6 +33,7 @@ import com.intellij.openapi.options.ShowSettingsUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.ui.Messages; +import com.intellij.openapi.util.ThrowableComputable; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; @@ -140,20 +141,13 @@ public class JikesCompiler extends ExternalCompiler { throws IOException { final ArrayList commandLine = new ArrayList(); - final IOException[] ex = {null}; - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - try { - _createStartupCommand(chunk, commandLine, outputPath); - } - catch (IOException e) { - ex[0] = e; - } + ApplicationManager.getApplication().runReadAction(new ThrowableComputable() { + @Override + public Void compute() throws IOException { + _createStartupCommand(chunk, commandLine, outputPath); + return null; } }); - if (ex[0] != null) { - throw ex[0]; - } return ArrayUtil.toStringArray(commandLine); } diff --git a/java/compiler/impl/src/com/intellij/compiler/make/CacheUtils.java b/java/compiler/impl/src/com/intellij/compiler/make/CacheUtils.java index bf2a58e74133..51cb953e9935 100644 --- a/java/compiler/impl/src/com/intellij/compiler/make/CacheUtils.java +++ b/java/compiler/impl/src/com/intellij/compiler/make/CacheUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,6 +27,7 @@ import com.intellij.openapi.compiler.CompilerMessageCategory; import com.intellij.openapi.compiler.ex.CompileContextEx; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Pair; +import com.intellij.openapi.util.ThrowableComputable; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.ArrayUtil; @@ -134,7 +135,7 @@ public class CacheUtils { final Set compiledWithErrors, final @Nullable Function>, Pair>> filter) throws CacheCorruptedException, ExitException { - + if (!CompilerConfiguration.MAKE_ENABLED) { return Collections.emptyList(); } @@ -143,51 +144,44 @@ public class CacheUtils { final DependencyCache dependencyCache = context.getDependencyCache(); final Pair> deps = dependencyCache.findDependentClasses(context, context.getProject(), compiledWithErrors); - final Pair> filteredDeps = filter != null? filter.fun(deps) : deps; + final Pair> filteredDeps = filter != null ? filter.fun(deps) : deps; final Set dependentFiles = new HashSet(); - final CacheCorruptedException[] _ex = {null}; - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - try { - CompilerConfiguration compilerConfiguration = CompilerConfiguration.getInstance(context.getProject()); - SourceFileFinder sourceFileFinder = new SourceFileFinder(context.getProject(), context); - final Cache cache = dependencyCache.getCache(); - for (final int infoQName : filteredDeps.getFirst()) { - final String qualifiedName = dependencyCache.resolve(infoQName); - final String sourceFileName = cache.getSourceFileName(infoQName); - final VirtualFile file = sourceFileFinder.findSourceFile(qualifiedName, sourceFileName, true); - if (file != null) { - dependentFiles.add(file); - if (ApplicationManager.getApplication().isUnitTestMode()) { - LOG.assertTrue(file.isValid()); - CompilerManagerImpl.addRecompiledPath(file.getPath()); - } - } - else { - LOG.info("No source file for " + dependencyCache.resolve(infoQName) + " found; source file name=" + sourceFileName); + ApplicationManager.getApplication().runReadAction(new ThrowableComputable() { + @Override + public Void compute() throws CacheCorruptedException { + CompilerConfiguration compilerConfiguration = CompilerConfiguration.getInstance(context.getProject()); + SourceFileFinder sourceFileFinder = new SourceFileFinder(context.getProject(), context); + final Cache cache = dependencyCache.getCache(); + for (final int infoQName : filteredDeps.getFirst()) { + final String qualifiedName = dependencyCache.resolve(infoQName); + final String sourceFileName = cache.getSourceFileName(infoQName); + final VirtualFile file = sourceFileFinder.findSourceFile(qualifiedName, sourceFileName, true); + if (file != null) { + dependentFiles.add(file); + if (ApplicationManager.getApplication().isUnitTestMode()) { + LOG.assertTrue(file.isValid()); + CompilerManagerImpl.addRecompiledPath(file.getPath()); } } - for (final VirtualFile file : filteredDeps.getSecond()) { - if (!compilerConfiguration.isExcludedFromCompilation(file)) { - dependentFiles.add(file); - if (ApplicationManager.getApplication().isUnitTestMode()) { - LOG.assertTrue(file.isValid()); - CompilerManagerImpl.addRecompiledPath(file.getPath()); - } + else { + LOG.info("No source file for " + dependencyCache.resolve(infoQName) + " found; source file name=" + sourceFileName); + } + } + for (final VirtualFile file : filteredDeps.getSecond()) { + if (!compilerConfiguration.isExcludedFromCompilation(file)) { + dependentFiles.add(file); + if (ApplicationManager.getApplication().isUnitTestMode()) { + LOG.assertTrue(file.isValid()); + CompilerManagerImpl.addRecompiledPath(file.getPath()); } } } - catch (CacheCorruptedException e) { - _ex[0] = e; - } + return null; } }); - if (_ex[0] != null) { - throw _ex[0]; - } context.getProgressIndicator().setText( - dependentFiles.size() > 0? CompilerBundle.message("progress.found.dependent.files", dependentFiles.size()) : "" + dependentFiles.size() > 0 ? CompilerBundle.message("progress.found.dependent.files", dependentFiles.size()) : "" ); return dependentFiles; diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ModulesConfigurator.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ModulesConfigurator.java index f553168de429..7edad1ddc1e3 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ModulesConfigurator.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ModulesConfigurator.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,8 +47,8 @@ import com.intellij.openapi.roots.ui.configuration.projectRoot.StructureConfigur import com.intellij.openapi.roots.ui.configuration.projectRoot.daemon.ModuleProjectStructureElement; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Comparing; -import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Disposer; +import com.intellij.openapi.util.ThrowableComputable; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.packaging.artifacts.Artifact; @@ -392,25 +392,19 @@ public class ModulesConfigurator implements ModulesProvider, ModuleEditor.Change } private Module createModule(final ModuleBuilder builder) { - final Exception[] ex = new Exception[]{null}; - final Module module = ApplicationManager.getApplication().runWriteAction(new Computable() { - @Override - @SuppressWarnings({"ConstantConditions"}) - public Module compute() { - try { + try { + return ApplicationManager.getApplication().runWriteAction(new ThrowableComputable() { + @Override + public Module compute() throws Exception { return builder.createModule(myModuleModel); } - catch (Exception e) { - ex[0] = e; - return null; - } - } - }); - if (ex[0] != null) { - Messages.showErrorDialog(ProjectBundle.message("module.add.error.message", ex[0].getMessage()), + }); + } + catch (Exception e) { + Messages.showErrorDialog(ProjectBundle.message("module.add.error.message", e.getMessage()), ProjectBundle.message("module.add.error.title")); + return null; } - return module; } @Nullable diff --git a/java/testFramework/src/com/intellij/debugger/impl/OutputChecker.java b/java/testFramework/src/com/intellij/debugger/impl/OutputChecker.java index df5817e226c9..113587fe0ec4 100644 --- a/java/testFramework/src/com/intellij/debugger/impl/OutputChecker.java +++ b/java/testFramework/src/com/intellij/debugger/impl/OutputChecker.java @@ -24,9 +24,9 @@ import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.projectRoots.ex.JavaSdkUtil; import com.intellij.openapi.projectRoots.impl.JavaAwareProjectJdkTableImpl; -import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.SystemInfo; +import com.intellij.openapi.util.ThrowableComputable; import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.util.text.StringUtilRt; @@ -37,6 +37,7 @@ import org.junit.Assert; import java.io.File; import java.io.FileOutputStream; import java.net.InetAddress; +import java.net.UnknownHostException; import java.util.Arrays; import java.util.Map; import java.util.regex.Matcher; @@ -172,91 +173,78 @@ public class OutputChecker { if (application == null) return buffer; - final Exception[] ex = new Exception[]{null}; - - String actual = application.runReadAction(new Computable() { + return application.runReadAction(new ThrowableComputable() { @Override - public String compute() { - try { - String internalJdkHome = JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk().getHomeDirectory().getPath(); - //System.out.println("internalJdkHome = " + internalJdkHome); + public String compute() throws UnknownHostException { + String internalJdkHome = JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk().getHomeDirectory().getPath(); + //System.out.println("internalJdkHome = " + internalJdkHome); - String result = buffer; - //System.out.println("Original Output = " + result); - final boolean shouldIgnoreCase = !SystemInfo.isFileSystemCaseSensitive; + String result = buffer; + //System.out.println("Original Output = " + result); + final boolean shouldIgnoreCase = !SystemInfo.isFileSystemCaseSensitive; - result = StringUtil.replace(result, "\r\n", "\n"); - result = StringUtil.replace(result, "\r", "\n"); - result = replaceAdditionalInOutput(result); - result = StringUtil.replace(result, testJdk.getHomePath(), "!TEST_JDK!", shouldIgnoreCase); - result = StringUtil.replace(result, myAppPath, "!APP_PATH!", shouldIgnoreCase); - result = StringUtil.replace(result, myAppPath.replace(File.separatorChar, '/'), "!APP_PATH!", shouldIgnoreCase); - result = StringUtil.replace(result, JavaSdkUtil.getIdeaRtJarPath(), "!RT_JAR!", shouldIgnoreCase); - result = StringUtil.replace(result, JavaSdkUtil.getJunit4JarPath(), "!JUNIT4_JAR!", shouldIgnoreCase); - result = StringUtil.replace(result, InetAddress.getLocalHost().getCanonicalHostName(), "!HOST_NAME!", shouldIgnoreCase); - result = StringUtil.replace(result, InetAddress.getLocalHost().getHostName(), "!HOST_NAME!", shouldIgnoreCase); - result = StringUtil.replace(result, "127.0.0.1", "!HOST_NAME!", shouldIgnoreCase); - result = StringUtil.replace(result, JavaSdkUtil.getIdeaRtJarPath().replace('/', File.separatorChar), "!RT_JAR!", shouldIgnoreCase); - result = StringUtil.replace(result, internalJdkHome.replace('/', File.separatorChar), "!JDK_HOME!", shouldIgnoreCase); - result = StringUtil.replace(result, internalJdkHome, "!JDK_HOME!", shouldIgnoreCase); - result = StringUtil.replace(result, PathManager.getHomePath(), "!IDEA_HOME!", shouldIgnoreCase); - result = StringUtil.replace(result, "Process finished with exit code 255", "Process finished with exit code -1"); + result = StringUtil.replace(result, "\r\n", "\n"); + result = StringUtil.replace(result, "\r", "\n"); + result = replaceAdditionalInOutput(result); + result = StringUtil.replace(result, testJdk.getHomePath(), "!TEST_JDK!", shouldIgnoreCase); + result = StringUtil.replace(result, myAppPath, "!APP_PATH!", shouldIgnoreCase); + result = StringUtil.replace(result, myAppPath.replace(File.separatorChar, '/'), "!APP_PATH!", shouldIgnoreCase); + result = StringUtil.replace(result, JavaSdkUtil.getIdeaRtJarPath(), "!RT_JAR!", shouldIgnoreCase); + result = StringUtil.replace(result, JavaSdkUtil.getJunit4JarPath(), "!JUNIT4_JAR!", shouldIgnoreCase); + result = StringUtil.replace(result, InetAddress.getLocalHost().getCanonicalHostName(), "!HOST_NAME!", shouldIgnoreCase); + result = StringUtil.replace(result, InetAddress.getLocalHost().getHostName(), "!HOST_NAME!", shouldIgnoreCase); + result = StringUtil.replace(result, "127.0.0.1", "!HOST_NAME!", shouldIgnoreCase); + result = StringUtil.replace(result, JavaSdkUtil.getIdeaRtJarPath().replace('/', File.separatorChar), "!RT_JAR!", shouldIgnoreCase); + result = StringUtil.replace(result, internalJdkHome.replace('/', File.separatorChar), "!JDK_HOME!", shouldIgnoreCase); + result = StringUtil.replace(result, internalJdkHome, "!JDK_HOME!", shouldIgnoreCase); + result = StringUtil.replace(result, PathManager.getHomePath(), "!IDEA_HOME!", shouldIgnoreCase); + result = StringUtil.replace(result, "Process finished with exit code 255", "Process finished with exit code -1"); -// result = result.replaceAll(" +\n", "\n"); - result = result.replaceAll("!HOST_NAME!:\\d*", "!HOST_NAME!:!HOST_PORT!"); - result = result.replaceAll("at \\'.*?\\'", "at '!HOST_NAME!:PORT_NAME!'"); - result = result.replaceAll("address: \\'.*?\\'", "address: '!HOST_NAME!:PORT_NAME!'"); - result = result.replaceAll("file.*AppletPage.*\\.html", "file:/!APPLET_HTML!"); - result = result.replaceAll("\"(!JDK_HOME!.*?)\"", "$1"); - result = result.replaceAll("\"(!APP_PATH!.*?)\"", "$1"); + // result = result.replaceAll(" +\n", "\n"); + result = result.replaceAll("!HOST_NAME!:\\d*", "!HOST_NAME!:!HOST_PORT!"); + result = result.replaceAll("at \\'.*?\\'", "at '!HOST_NAME!:PORT_NAME!'"); + result = result.replaceAll("address: \\'.*?\\'", "address: '!HOST_NAME!:PORT_NAME!'"); + result = result.replaceAll("file.*AppletPage.*\\.html", "file:/!APPLET_HTML!"); + result = result.replaceAll("\"(!JDK_HOME!.*?)\"", "$1"); + result = result.replaceAll("\"(!APP_PATH!.*?)\"", "$1"); - result = result.replaceAll("-Didea.launcher.port=\\d*", "-Didea.launcher.port=!IDEA_LAUNCHER_PORT!"); - result = result.replaceAll("-Dfile.encoding=[\\w\\d-]*", "-Dfile.encoding=!FILE_ENCODING!"); - result = result.replaceAll("\\((.*)\\:\\d+\\)", "($1:!LINE_NUMBER!)"); + result = result.replaceAll("-Didea.launcher.port=\\d*", "-Didea.launcher.port=!IDEA_LAUNCHER_PORT!"); + result = result.replaceAll("-Dfile.encoding=[\\w\\d-]*", "-Dfile.encoding=!FILE_ENCODING!"); + result = result.replaceAll("\\((.*)\\:\\d+\\)", "($1:!LINE_NUMBER!)"); - int commandLineStart = result.indexOf("!JDK_HOME!"); - while (commandLineStart != -1) { - final StringBuilder builder = new StringBuilder(result); - int i = commandLineStart + 1; - while (i < builder.length()) { - char c = builder.charAt(i); - if (c == '\n') break; - else if (c == File.separatorChar) builder.setCharAt(i, '\\'); - i++; - } - result = builder.toString(); - commandLineStart = result.indexOf("!JDK_HOME!", commandLineStart + 1); + int commandLineStart = result.indexOf("!JDK_HOME!"); + while (commandLineStart != -1) { + final StringBuilder builder = new StringBuilder(result); + int i = commandLineStart + 1; + while (i < builder.length()) { + char c = builder.charAt(i); + if (c == '\n') break; + else if (c == File.separatorChar) builder.setCharAt(i, '\\'); + i++; } + result = builder.toString(); + commandLineStart = result.indexOf("!JDK_HOME!", commandLineStart + 1); + } - result = stripQuotesAroundClasspath(result); + result = stripQuotesAroundClasspath(result); - final Matcher matcher = Pattern.compile("-classpath\\s+(\\S+)\\s+").matcher(result); - while (matcher.find()) { - final String classPath = matcher.group(1); - final String[] classPathElements = classPath.split(File.pathSeparator); - if (sortClassPath) { - Arrays.sort(classPathElements); - } - final String sortedPath = StringUtil.join(classPathElements, ";"); - result = StringUtil.replace(result, classPath, sortedPath); + final Matcher matcher = Pattern.compile("-classpath\\s+(\\S+)\\s+").matcher(result); + while (matcher.find()) { + final String classPath = matcher.group(1); + final String[] classPathElements = classPath.split(File.pathSeparator); + if (sortClassPath) { + Arrays.sort(classPathElements); } - - result = JDI_BUG_OUTPUT_PATTERN_1.matcher(result).replaceAll(""); - result = JDI_BUG_OUTPUT_PATTERN_2.matcher(result).replaceAll(""); - - return result; - } - catch (Exception exception) { - ex[0] = exception; - return null; + final String sortedPath = StringUtil.join(classPathElements, ";"); + result = StringUtil.replace(result, classPath, sortedPath); } + + result = JDI_BUG_OUTPUT_PATTERN_1.matcher(result).replaceAll(""); + result = JDI_BUG_OUTPUT_PATTERN_2.matcher(result).replaceAll(""); + + return result; } }); - - - if (ex[0] != null) throw ex[0]; - - return actual; } protected String replaceAdditionalInOutput(String str) { diff --git a/platform/core-api/src/com/intellij/openapi/command/WriteCommandAction.java b/platform/core-api/src/com/intellij/openapi/command/WriteCommandAction.java index f2e891dafbdf..ecc61358f0d0 100644 --- a/platform/core-api/src/com/intellij/openapi/command/WriteCommandAction.java +++ b/platform/core-api/src/com/intellij/openapi/command/WriteCommandAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,6 +20,8 @@ import com.intellij.openapi.application.*; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Computable; +import com.intellij.openapi.util.Ref; +import com.intellij.openapi.util.ThrowableComputable; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; @@ -32,7 +34,7 @@ import java.util.Collection; public abstract class WriteCommandAction extends BaseActionRunnable { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.command.WriteCommandAction"); - private final String myName; + private final String myCommandName; private final String myGroupID; private final Project myProject; private final PsiFile[] myPsiFiles; @@ -45,8 +47,8 @@ public abstract class WriteCommandAction extends BaseActionRunnable { this(project, commandName, null, files); } - protected WriteCommandAction(@Nullable final Project project, @Nullable final String name, @Nullable final String groupID, PsiFile... files) { - myName = name; + protected WriteCommandAction(@Nullable final Project project, @Nullable final String commandName, @Nullable final String groupID, PsiFile... files) { + myCommandName = commandName; myGroupID = groupID; myProject = project; myPsiFiles = files == null || files.length == 0 ? PsiFile.EMPTY_ARRAY : files; @@ -57,7 +59,7 @@ public abstract class WriteCommandAction extends BaseActionRunnable { } public final String getCommandName() { - return myName; + return myCommandName; } public String getGroupID() { @@ -67,28 +69,23 @@ public abstract class WriteCommandAction extends BaseActionRunnable { @NotNull @Override public RunResult execute() { - if (!ApplicationManager.getApplication().isDispatchThread() && ApplicationManager.getApplication().isReadAccessAllowed()) { + Application application = ApplicationManager.getApplication(); + if (!application.isDispatchThread() && application.isReadAccessAllowed()) { LOG.error("Must not start write action from within read action in the other thread - deadlock is coming"); } - final RunResult result = new RunResult(this); try { - Runnable runnable = new Runnable() { - @Override - public void run() { - performWriteCommandAction(result); - } - }; - Application application = ApplicationManager.getApplication(); if (application.isDispatchThread()) { - runnable.run(); - } - else if (application.isReadAccessAllowed()) { - LOG.error("Calling write command from read-action leads to deadlock."); + performWriteCommandAction(result); } else { - SwingUtilities.invokeAndWait(runnable); + SwingUtilities.invokeAndWait(new Runnable() { + @Override + public void run() { + performWriteCommandAction(result); + } + }); } } catch (InvocationTargetException e) { @@ -102,11 +99,10 @@ public abstract class WriteCommandAction extends BaseActionRunnable { return FileModificationService.getInstance().preparePsiElementsForWrite(psiFiles); } - private void performWriteCommandAction(final RunResult result) { + private void performWriteCommandAction(@NotNull final RunResult result) { if (!FileModificationService.getInstance().preparePsiElementsForWrite(Arrays.asList(myPsiFiles))) return; - //this is needed to prevent memory leak, since command - // is put into undo queue + // this is needed to prevent memory leak, since the command is put into undo queue final RunResult[] results = {result}; CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() { @@ -131,21 +127,23 @@ public abstract class WriteCommandAction extends BaseActionRunnable { return UndoConfirmationPolicy.DO_NOT_REQUEST_CONFIRMATION; } - protected RunResult executeCommand(RunResult result) { + public void performCommand() throws Throwable { //this is needed to prevent memory leak, since command // is put into undo queue - final RunResult[] results = {result}; + final RunResult[] results = {new RunResult(this)}; + final Ref exception = new Ref(); CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { @Override public void run() { if (isGlobalUndoAction()) CommandProcessor.getInstance().markCurrentCommandAsGlobal(myProject); - results[0].run(); + exception.set(results[0].run().getThrowable()); results[0] = null; } }, getCommandName(), getGroupID(), getUndoConfirmationPolicy()); - return result; + Throwable throwable = exception.get(); + if (throwable != null) throw throwable; } /** @@ -188,5 +186,16 @@ public abstract class WriteCommandAction extends BaseActionRunnable { } }.execute().getResultObject(); } + + public static T runWriteCommandAction(Project project, @NotNull final ThrowableComputable computable) throws E { + RunResult result = new WriteCommandAction(project,"") { + @Override + protected void run(@NotNull Result result) throws Throwable { + result.setResult(computable.compute()); + } + }.execute(); + if (result.getThrowable() instanceof Throwable) throw (E)result.getThrowable(); + return result.throwException().getResultObject(); + } } diff --git a/platform/lang-api/src/com/intellij/util/ActionRunner.java b/platform/lang-api/src/com/intellij/util/ActionRunner.java index 4a0993953250..75e5179d522a 100644 --- a/platform/lang-api/src/com/intellij/util/ActionRunner.java +++ b/platform/lang-api/src/com/intellij/util/ActionRunner.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,109 +16,50 @@ package com.intellij.util; import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.application.ModalityState; -import com.intellij.openapi.util.Computable; - -import javax.swing.*; +import com.intellij.openapi.application.Result; +import com.intellij.openapi.application.RunResult; +import com.intellij.openapi.application.WriteAction; +import com.intellij.openapi.util.ThrowableComputable; +import org.jetbrains.annotations.NotNull; public abstract class ActionRunner { - public static void runInsideWriteAction(final InterruptibleRunnable runnable) throws Exception { - final Exception[] exception = new Exception[1]; - Runnable swingRunnable = new Runnable() { + public static void runInsideWriteAction(@NotNull final InterruptibleRunnable runnable) throws Exception { + RunResult result = new WriteAction() { @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - runnable.run(); - } - catch (Exception e) { - exception[0] = e; - } - } - }); + protected void run(@NotNull Result result) throws Throwable { + runnable.run(); } - }; - if (SwingUtilities.isEventDispatchThread()) { - swingRunnable.run(); - } - else { - ApplicationManager.getApplication().invokeAndWait(swingRunnable, ModalityState.NON_MODAL); - } - Exception e = exception[0]; - if (e != null) { - if (e instanceof RuntimeException) throw (RuntimeException)e; - throw new Exception(e); - } - } - //public static void runInsideWriteAction(final InterruptibleRunnable runnable) throws E { - // runInsideWriteAction(new InterruptibleRunnableWithResult(){ - // public Object run() throws E { - // runnable.run(); - // return null; - // } - // }); - //} - public static T runInsideWriteAction(final InterruptibleRunnableWithResult runnable) throws Exception { - final Throwable[] exception = new Throwable[]{null}; - final T[] result = (T[])new Object[1]; - Runnable swingRunnable = new Runnable() { - @Override - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - try { - result[0] = runnable.run(); - } - catch (Exception e) { - exception[0] = e; - } - } - }); - } - }; - if (SwingUtilities.isEventDispatchThread()) { - swingRunnable.run(); - } - else { - ApplicationManager.getApplication().invokeAndWait(swingRunnable, ModalityState.NON_MODAL); - } - Throwable e = exception[0]; - if (e != null) { - if (e instanceof Exception) throw (Exception)e; - throw new Exception(e); - } - return result[0]; + }.execute(); + if (result.getThrowable() instanceof Exception) throw (Exception)result.getThrowable(); + result.throwException(); } - public static void runInsideReadAction(final InterruptibleRunnable runnable) throws Exception { - Throwable exception = ApplicationManager.getApplication().runReadAction(new Computable() { + public static T runInsideWriteAction(@NotNull final InterruptibleRunnableWithResult runnable) throws Exception { + RunResult result = new WriteAction() { @Override - public Throwable compute() { - try { - runnable.run(); - return null; - } - catch (Throwable e) { - return e; - } + protected void run(@NotNull Result result) throws Throwable { + result.setResult(runnable.run()); + } + }.execute(); + if (result.getThrowable() instanceof Exception) throw (Exception)result.getThrowable(); + return result.throwException().getResultObject(); + } + + public static void runInsideReadAction(@NotNull final InterruptibleRunnable runnable) throws Exception { + ApplicationManager.getApplication().runReadAction(new ThrowableComputable() { + @Override + public Void compute() throws Exception { + runnable.run(); + return null; } }); - if (exception != null) { - if (exception instanceof RuntimeException) { - throw (RuntimeException)exception; - } - throw new Exception(exception); - } } - public static interface InterruptibleRunnable { + public interface InterruptibleRunnable { void run() throws Exception; } - public static interface InterruptibleRunnableWithResult { + public interface InterruptibleRunnableWithResult { T run() throws Exception; } } \ No newline at end of file diff --git a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/PasteHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/PasteHandler.java index 0296e8e139dc..ef7772502adb 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/PasteHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/PasteHandler.java @@ -229,6 +229,8 @@ public class PasteHandler extends EditorActionHandler implements EditorTextInser VirtualFile virtualFile = file.getVirtualFile(); if (!pastedTextContainsWhiteSpacesOnly && (virtualFile == null || !SingleRootFileViewProvider.isTooLargeForIntelligence(virtualFile))) { final int indentOptions1 = indentOptions; + PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(document); + ApplicationManager.getApplication().runWriteAction( new Runnable() { @Override diff --git a/platform/platform-impl/src/com/intellij/openapi/options/SchemesManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/options/SchemesManagerImpl.java index 5ca7ea0a7aac..1c7e768c7d83 100644 --- a/platform/platform-impl/src/com/intellij/openapi/options/SchemesManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/options/SchemesManagerImpl.java @@ -334,27 +334,17 @@ public class SchemesManagerImpl() { + return ApplicationManager.getApplication().runWriteAction(new ThrowableComputable() { @Override - public VirtualFile compute() { + public VirtualFile compute() throws IOException { VirtualFile file = myVFSBaseDir.findChild(fileName); - try { - if (file == null) file = myVFSBaseDir.createChildData(SchemesManagerImpl.this, fileName); - if (!Arrays.equals(file.contentsToByteArray(), text)) { - file.setBinaryContent(text); - } + if (file == null) file = myVFSBaseDir.createChildData(SchemesManagerImpl.this, fileName); + if (!Arrays.equals(file.contentsToByteArray(), text)) { + file.setBinaryContent(text); } - catch (IOException e) { - ex[0] = e; - } - return file; } }); - - if (ex[0] != null) throw ex[0]; - return _file; } private String checkFileNameIsFree(final String subPath, final String schemeName) { diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/local/LocalFileSystemImpl.java b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/local/LocalFileSystemImpl.java index 94f9420ecb23..2cc4254b7155 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/local/LocalFileSystemImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/local/LocalFileSystemImpl.java @@ -529,12 +529,7 @@ public final class LocalFileSystemImpl extends LocalFileSystemBase implements Ap @TestOnly public void cleanupForNextTest() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - @Override - public void run() { - FileDocumentManager.getInstance().saveAllDocuments(); - } - }); + FileDocumentManager.getInstance().saveAllDocuments(); PersistentFS.getInstance().clearIdCache(); myRootsToWatch.clear(); } diff --git a/platform/testFramework/src/com/intellij/testFramework/LightPlatformCodeInsightTestCase.java b/platform/testFramework/src/com/intellij/testFramework/LightPlatformCodeInsightTestCase.java index 3a5f104d9802..01e0a7a09fb5 100644 --- a/platform/testFramework/src/com/intellij/testFramework/LightPlatformCodeInsightTestCase.java +++ b/platform/testFramework/src/com/intellij/testFramework/LightPlatformCodeInsightTestCase.java @@ -42,6 +42,7 @@ import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.fileEditor.impl.TrailingSpacesStripper; import com.intellij.openapi.project.ProjectManager; +import com.intellij.openapi.util.ThrowableComputable; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.openapi.util.text.StringUtil; @@ -78,33 +79,22 @@ public abstract class LightPlatformCodeInsightTestCase extends LightPlatformTest @Override protected void runTest() throws Throwable { - final Throwable[] throwable = {null}; - Runnable action = new Runnable() { - @Override - public void run() { - CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() { - @Override - public void run() { - - try { - doRunTest(); - } - catch (Throwable t) { - throwable[0] = t; - } - } - }, "", null); - } - }; if (isRunInWriteAction()) { - ApplicationManager.getApplication().runWriteAction(action); + WriteCommandAction.runWriteCommandAction(getProject(), new ThrowableComputable() { + @Override + public Void compute() throws Throwable { + doRunTest(); + return null; + } + }); } else { - action.run(); - } - - if (throwable[0] != null) { - throw throwable[0]; + new WriteCommandAction.Simple(getProject()){ + @Override + protected void run() throws Throwable { + doRunTest(); + } + }.performCommand(); } } @@ -230,16 +220,13 @@ public abstract class LightPlatformCodeInsightTestCase extends LightPlatformTest } } - private static void deleteVFile() { + private static void deleteVFile() throws IOException { if (myVFile != null) { - ApplicationManager.getApplication().runWriteAction(new Runnable() { + ApplicationManager.getApplication().runWriteAction(new ThrowableComputable() { @Override - public void run() { - try { - myVFile.delete(this); - } catch (IOException e) { - LOG.error(e); - } + public Void compute() throws IOException { + myVFile.delete(this); + return null; } }); } diff --git a/platform/testFramework/src/com/intellij/testFramework/fixtures/impl/CodeInsightTestFixtureImpl.java b/platform/testFramework/src/com/intellij/testFramework/fixtures/impl/CodeInsightTestFixtureImpl.java index dfebd8577864..1096c84de094 100644 --- a/platform/testFramework/src/com/intellij/testFramework/fixtures/impl/CodeInsightTestFixtureImpl.java +++ b/platform/testFramework/src/com/intellij/testFramework/fixtures/impl/CodeInsightTestFixtureImpl.java @@ -90,7 +90,6 @@ import com.intellij.psi.impl.PsiManagerImpl; import com.intellij.psi.impl.PsiModificationTrackerImpl; import com.intellij.psi.impl.cache.CacheManager; import com.intellij.psi.impl.cache.impl.todo.TodoIndex; -import com.intellij.psi.impl.source.PostprocessReformattingAspect; import com.intellij.psi.impl.source.PsiFileImpl; import com.intellij.psi.impl.source.tree.FileElement; import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil; @@ -110,11 +109,11 @@ import com.intellij.util.containers.ContainerUtil; import com.intellij.util.indexing.FileBasedIndex; import com.intellij.util.ui.UIUtil; import gnu.trove.THashMap; -import org.junit.Assert; import junit.framework.ComparisonFailure; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.junit.Assert; import javax.swing.*; import java.io.File; @@ -1061,23 +1060,26 @@ public class CodeInsightTestFixtureImpl extends BaseFixture implements CodeInsig @Override public void checkResultByFile(final String expectedFile, final boolean ignoreTrailingWhitespaces) { assertInitialized(); - new WriteCommandAction.Simple(getProject()) { - + UIUtil.invokeAndWaitIfNeeded(new Runnable() { @Override - protected void run() throws Exception { - checkResultByFile(expectedFile, getHostFile(), ignoreTrailingWhitespaces); + public void run() { + try { + checkResultByFile(expectedFile, getHostFile(), ignoreTrailingWhitespaces); + } + catch (IOException e) { + throw new RuntimeException(e); + } } - }.execute().throwException(); + }); } @Override public void checkResultByFile(final String filePath, final String expectedFile, final boolean ignoreTrailingWhitespaces) { assertInitialized(); - new WriteCommandAction.Simple(getProject()) { - + UIUtil.invokeAndWaitIfNeeded(new Runnable() { @Override - protected void run() throws Exception { + public void run() { final String path = filePath.replace(File.separatorChar, '/'); final VirtualFile copy = findFileInTempDir(path); if (copy == null) { @@ -1085,9 +1087,14 @@ public class CodeInsightTestFixtureImpl extends BaseFixture implements CodeInsig } final PsiFile psiFile = myPsiManager.findFile(copy); assert psiFile != null; - checkResultByFile(expectedFile, psiFile, ignoreTrailingWhitespaces); + try { + checkResultByFile(expectedFile, psiFile, ignoreTrailingWhitespaces); + } + catch (IOException e) { + throw new RuntimeException(e); + } } - }.execute().throwException(); + }); } @Override @@ -1674,14 +1681,12 @@ public class CodeInsightTestFixtureImpl extends BaseFixture implements CodeInsig String actualText) { assertInitialized(); Project project = getProject(); - PsiFile file = getFile(); Editor editor = getEditor(); if (editor instanceof EditorWindow) { editor = ((EditorWindow)editor).getDelegate(); - file = InjectedLanguageUtil.getTopLevelFile(file); } - project.getComponent(PostprocessReformattingAspect.class).doPostponedFormatting(); + UsefulTestCase.doPostponedFormatting(getProject()); if (stripTrailingSpaces) { actualText = stripTrailingSpaces(actualText); } diff --git a/platform/vcs-impl/src/com/intellij/openapi/diff/impl/patch/formove/PathsVerifier.java b/platform/vcs-impl/src/com/intellij/openapi/diff/impl/patch/formove/PathsVerifier.java index 39b73342df26..618264ca07d9 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/diff/impl/patch/formove/PathsVerifier.java +++ b/platform/vcs-impl/src/com/intellij/openapi/diff/impl/patch/formove/PathsVerifier.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,7 @@ import com.intellij.openapi.diff.impl.patch.apply.ApplyTextFilePatch; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Pair; +import com.intellij.openapi.util.ThrowableComputable; import com.intellij.openapi.vcs.*; import com.intellij.openapi.vcs.changes.patch.RelativePathCalculator; import com.intellij.openapi.vcs.changes.shelf.ShelveChangesManager; @@ -475,21 +476,12 @@ public class PathsVerifier { final MovedFileData movedFile = myMovedFiles.get(file); if (movedFile != null) { myBeforePaths.add(new FilePathImpl(file.getParent(), file.getName(), file.isDirectory())); - final IOException[] exc = new IOException[1]; - ApplicationManager.getApplication().runWriteAction(new Runnable() { + ApplicationManager.getApplication().runWriteAction(new ThrowableComputable() { @Override - public void run() { - try { - final VirtualFile moveResult = movedFile.doMove(); - } - catch (IOException e) { - exc[0] = e; - } + public VirtualFile compute() throws IOException { + return movedFile.doMove(); } }); - if (exc[0] != null) { - throw exc[0]; - } } } diff --git a/plugins/eclipse/src/org/jetbrains/idea/eclipse/importWizard/EclipseImportBuilder.java b/plugins/eclipse/src/org/jetbrains/idea/eclipse/importWizard/EclipseImportBuilder.java index f1157a1e3ae1..74c46b28a151 100644 --- a/plugins/eclipse/src/org/jetbrains/idea/eclipse/importWizard/EclipseImportBuilder.java +++ b/plugins/eclipse/src/org/jetbrains/idea/eclipse/importWizard/EclipseImportBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,6 +47,7 @@ import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.JDOMUtil; import com.intellij.openapi.util.Ref; +import com.intellij.openapi.util.ThrowableComputable; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.LocalFileSystem; @@ -280,20 +281,13 @@ public class EclipseImportBuilder extends ProjectImportBuilder implement for (File file : files) { final VirtualFile virtualFile = localFileSystem.findFileByIoFile(file); if (virtualFile != null) { - final IOException[] ex = new IOException[1]; - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - try { - virtualFile.delete(this); - } - catch (IOException e) { - ex[0] = e; - } + ApplicationManager.getApplication().runWriteAction(new ThrowableComputable() { + @Override + public Void compute() throws IOException { + virtualFile.delete(this); + return null; } }); - if (ex[0] != null) { - throw ex[0]; - } } else { FileUtil.delete(file); diff --git a/plugins/properties/src/com/intellij/lang/properties/references/I18nizeQuickFixDialog.java b/plugins/properties/src/com/intellij/lang/properties/references/I18nizeQuickFixDialog.java index 03a72a8ca811..b19510be034b 100644 --- a/plugins/properties/src/com/intellij/lang/properties/references/I18nizeQuickFixDialog.java +++ b/plugins/properties/src/com/intellij/lang/properties/references/I18nizeQuickFixDialog.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,7 +36,7 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Comparing; -import com.intellij.openapi.util.Computable; +import com.intellij.openapi.util.ThrowableComputable; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.LocalFileSystem; @@ -131,6 +131,7 @@ public class I18nizeQuickFixDialog extends DialogWrapper implements I18nizeQuick myPropertiesFile = new TextFieldWithHistory(); myPropertiesFile.setHistorySize(-1); myPropertiesFilePanel.add(GuiUtils.constructFieldWithBrowseButton(myPropertiesFile, new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { TreeFileChooserFactory chooserFactory = TreeFileChooserFactory.getInstance(myProject); final PropertiesFile propertiesFile = getPropertiesFile(); @@ -144,6 +145,7 @@ public class I18nizeQuickFixDialog extends DialogWrapper implements I18nizeQuick }), BorderLayout.CENTER); myPropertiesFile.addDocumentListener(new DocumentAdapter() { + @Override protected void textChanged(DocumentEvent e) { propertiesFileChanged(); somethingChanged(); @@ -151,12 +153,14 @@ public class I18nizeQuickFixDialog extends DialogWrapper implements I18nizeQuick }); getKeyTextField().getDocument().addDocumentListener(new DocumentAdapter() { + @Override protected void textChanged(DocumentEvent e) { somethingChanged(); } }); myValue.getDocument().addDocumentListener(new DocumentAdapter() { + @Override protected void textChanged(DocumentEvent e) { somethingChanged(); } @@ -168,6 +172,7 @@ public class I18nizeQuickFixDialog extends DialogWrapper implements I18nizeQuick !PropertiesComponent.getInstance().isValueSet(KEY) || PropertiesComponent.getInstance().isTrueValue(KEY); myUseResourceBundle.setSelected(useBundleByDefault); myUseResourceBundle.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { PropertiesComponent.getInstance().setValue(KEY, Boolean.valueOf(myUseResourceBundle.isSelected()).toString()); } @@ -300,6 +305,7 @@ public class I18nizeQuickFixDialog extends DialogWrapper implements I18nizeQuick final String lastUrl = suggestSelectedFileUrl(paths); final String lastPath = lastUrl == null ? null : FileUtil.toSystemDependentName(VfsUtil.urlToPath(lastUrl)); Collections.sort(paths, new Comparator() { + @Override public int compare(final String path1, final String path2) { if (lastPath != null && lastPath.equals(path1)) return -1; if (lastPath != null && lastPath.equals(path2)) return 1; @@ -388,23 +394,16 @@ public class I18nizeQuickFixDialog extends DialogWrapper implements I18nizeQuick try { final File file = new File(path).getCanonicalFile(); FileUtil.createParentDirs(file); - final IOException[] e = new IOException[1]; - virtualFile = ApplicationManager.getApplication().runWriteAction(new Computable() { - public VirtualFile compute() { + virtualFile = ApplicationManager.getApplication().runWriteAction(new ThrowableComputable() { + @Override + public VirtualFile compute() throws IOException { VirtualFile dir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file.getParentFile()); - try { - if (dir == null) { - throw new IOException("Error creating directory structure for file '" + path + "'"); - } - return dir.createChildData(this, file.getName()); + if (dir == null) { + throw new IOException("Error creating directory structure for file '" + path + "'"); } - catch (IOException e1) { - e[0] = e1; - } - return null; + return dir.createChildData(this, file.getName()); } }); - if (e[0] != null) throw e[0]; } catch (IOException e) { Messages.showErrorDialog(myProject, e.getLocalizedMessage(), CodeInsightBundle.message("i18nize.error.creating.properties.file")); @@ -415,19 +414,23 @@ public class I18nizeQuickFixDialog extends DialogWrapper implements I18nizeQuick return psiFile instanceof PropertiesFile; } + @Override protected JComponent createCenterPanel() { return myPanel; } + @Override public JComponent getPreferredFocusedComponent() { return myCustomization.focusValueComponent ? myValue:myKey; } + @Override public void dispose() { saveLastSelectedFile(); super.dispose(); } + @Override protected void doOKAction() { if (!createPropertiesFileIfNotExists()) return; Collection propertiesFiles = getAllPropertiesFiles(); @@ -445,11 +448,13 @@ public class I18nizeQuickFixDialog extends DialogWrapper implements I18nizeQuick super.doOKAction(); } + @Override @NotNull protected Action[] createActions() { return new Action[]{getOKAction(), getCancelAction(), getHelpAction()}; } + @Override public void doHelpAction() { HelpManager.getInstance().invokeHelp("editing.propertyFile.i18nInspection"); } @@ -459,14 +464,17 @@ public class I18nizeQuickFixDialog extends DialogWrapper implements I18nizeQuick return myValue; } + @Override public String getValue() { return myValue.getText(); } + @Override public String getKey() { return getKeyTextField().getText(); } + @Override public boolean hasValidData() { assert !ApplicationManager.getApplication().isUnitTestMode(); show(); @@ -478,10 +486,12 @@ public class I18nizeQuickFixDialog extends DialogWrapper implements I18nizeQuick return myUseResourceBundle.isEnabled() && myUseResourceBundle.isSelected(); } + @Override protected String getDimensionServiceKey() { return "#com.intellij.codeInsight.i18n.I18nizeQuickFixDialog"; } + @Override public Collection getAllPropertiesFiles() { PropertiesFile propertiesFile = getPropertiesFile(); if (propertiesFile == null) return Collections.emptySet(); diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/treeConflict/MergeFromTheirsResolver.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/treeConflict/MergeFromTheirsResolver.java index 31b040cd98dd..967c6e5908e6 100644 --- a/plugins/svn4idea/src/org/jetbrains/idea/svn/treeConflict/MergeFromTheirsResolver.java +++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/treeConflict/MergeFromTheirsResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,6 +27,7 @@ import com.intellij.openapi.ui.MessageDialogBuilder; import com.intellij.openapi.ui.MessageType; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Comparing; +import com.intellij.openapi.util.ThrowableComputable; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vcs.*; import com.intellij.openapi.vcs.changes.*; @@ -355,55 +356,56 @@ public class MergeFromTheirsResolver { public void run(final ContinuationContext context) { if (myTheirsBinaryChanges.isEmpty()) return; final Application application = ApplicationManager.getApplication(); - final VcsException[] exc = new VcsException[1]; final List dirtyPaths = new ArrayList(); for (final Change change : myTheirsBinaryChanges) { - application.runWriteAction(new Runnable() { - public void run() { - try { - if (change.getAfterRevision() != null) { - final FilePath file = change.getAfterRevision().getFile(); - dirtyPaths.add(file); - final String parentPath = file.getParentPath().getPath(); - final VirtualFile parentFile = VfsUtil.createDirectoryIfMissing(parentPath); - if (parentFile == null) { - context.handleException(new VcsException("Can not create directory: " + parentPath, true), false); - return; + try { + application.runWriteAction(new ThrowableComputable() { + @Override + public Void compute() throws VcsException { + try { + if (change.getAfterRevision() == null) { + final FilePath path = change.getBeforeRevision().getFile(); + dirtyPaths.add(path); + final VirtualFile file = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(path.getIOFile()); + if (file == null) { + context.handleException(new VcsException("Can not delete file: " + file.getPath(), true), false); + return null; + } + file.delete(TreeConflictRefreshablePanel.class); } - final VirtualFile child = parentFile.createChildData(TreeConflictRefreshablePanel.class, file.getName()); - if (child == null) { - context.handleException(new VcsException("Can not create file: " + file.getPath(), true), false); - return; + else { + final FilePath file = change.getAfterRevision().getFile(); + dirtyPaths.add(file); + final String parentPath = file.getParentPath().getPath(); + final VirtualFile parentFile = VfsUtil.createDirectoryIfMissing(parentPath); + if (parentFile == null) { + context.handleException(new VcsException("Can not create directory: " + parentPath, true), false); + return null; + } + final VirtualFile child = parentFile.createChildData(TreeConflictRefreshablePanel.class, file.getName()); + if (child == null) { + context.handleException(new VcsException("Can not create file: " + file.getPath(), true), false); + return null; + } + final BinaryContentRevision revision = (BinaryContentRevision)change.getAfterRevision(); + final byte[] content = revision.getBinaryContent(); + // actually it was the fix for IDEA-91572 Error saving merged data: Argument 0 for @NotNull parameter of > com/intellij/ + if (content == null) { + context.handleException(new VcsException("Can not load Theirs content for file " + file.getPath()), false); + return null; + } + child.setBinaryContent(content); } - final BinaryContentRevision revision = (BinaryContentRevision)change.getAfterRevision(); - final byte[] content = revision.getBinaryContent(); - // actually it was the fix for IDEA-91572 Error saving merged data: Argument 0 for @NotNull parameter of > com/intellij/ - if (content == null) { - context.handleException(new VcsException("Can not load Theirs content for file " + file.getPath()), false); - return; - } - child.setBinaryContent(content); - } else { - final FilePath path = change.getBeforeRevision().getFile(); - dirtyPaths.add(path); - final VirtualFile file = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(path.getIOFile()); - if (file == null) { - context.handleException(new VcsException("Can not delete file: " + file.getPath(), true), false); - return; - } - file.delete(TreeConflictRefreshablePanel.class); } + catch (IOException e) { + throw new VcsException(e); + } + return null; } - catch (IOException e) { - exc[0] = new VcsException(e); - } - catch (VcsException e) { - exc[0] = e; - } - } - }); - if (exc[0] != null) { - context.handleException(exc[0], true); + }); + } + catch (VcsException e) { + context.handleException(e, true); return; } } diff --git a/xml/relaxng/test/org/intellij/plugins/relaxNG/HighlightingTestBase.java b/xml/relaxng/test/org/intellij/plugins/relaxNG/HighlightingTestBase.java index 65bae6b51b9a..53558fe2dbe1 100644 --- a/xml/relaxng/test/org/intellij/plugins/relaxNG/HighlightingTestBase.java +++ b/xml/relaxng/test/org/intellij/plugins/relaxNG/HighlightingTestBase.java @@ -215,13 +215,14 @@ public abstract class HighlightingTestBase extends UsefulTestCase implements Ide assertTrue("One action expected", fixes != null && fixes.length == 1); final Project project = myTestFixture.getProject(); + final ProblemDescriptor problemDescriptor = InspectionManager.getInstance(project).createProblemDescriptor(psiReference.getElement(), + "foo", + fixes, + ProblemHighlightType.GENERIC_ERROR_OR_WARNING, + true); new WriteCommandAction.Simple(project, myTestFixture.getFile()) { @Override protected void run() throws Throwable { - ProblemDescriptor problemDescriptor = InspectionManager.getInstance(project).createProblemDescriptor(psiReference.getElement(), "foo", - fixes, - ProblemHighlightType.GENERIC_ERROR_OR_WARNING, - true); fixes[0].applyFix(project, problemDescriptor); } }.execute();