Merge remote-tracking branch 'origin/master'

This commit is contained in:
Roman Shevchenko
2015-07-22 18:26:08 +02:00
389 changed files with 4778 additions and 2506 deletions
@@ -25,6 +25,7 @@ import com.intellij.testFramework.fixtures.CodeInsightTestFixture;
import com.intellij.testFramework.fixtures.IdeaProjectTestFixture;
import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory;
import com.intellij.testFramework.fixtures.TestFixtureBuilder;
import org.jetbrains.annotations.NotNull;
import java.io.File;
@@ -45,7 +46,7 @@ public abstract class BaseParseTestCase extends UsefulTestCase {
new WriteCommandAction(project) {
@Override
protected void run(Result result) throws Throwable {
protected void run(@NotNull Result result) throws Throwable {
FileTypeManager.getInstance().registerFileType(RegExpFileType.INSTANCE, new String[]{"regexp"});
}
}.execute();
+1 -1
View File
@@ -238,7 +238,7 @@ def layoutFull(String home, String targetDirectory, String patchedDescriptorDir
jar("jps-model.jar") {
jpsCommonModules.each { module it }
}
jar("jps-server.jar") {
jar("jps-builders.jar") {
module("jps-builders")
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2010 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -17,7 +17,6 @@ package com.intellij.compiler.impl;
import com.intellij.compiler.impl.generic.GenericCompilerCache;
import com.intellij.compiler.impl.generic.GenericCompilerPersistentData;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.application.RunResult;
@@ -111,7 +110,7 @@ public class GenericCompilerRunner {
final Set<String> targetsToRemove = new HashSet<String>(data.getAllTargets());
new ReadAction() {
protected void run(final Result result) {
protected void run(@NotNull final Result result) {
for (T target : instance.getAllTargets()) {
targetsToRemove.remove(target.getId());
}
@@ -290,7 +289,7 @@ public class GenericCompilerRunner {
}
final RunResult runResult = new ReadAction() {
protected void run(final Result result) throws Throwable {
protected void run(@NotNull final Result result) throws Throwable {
for (Item item : processedItems) {
SourceState sourceState = sourceStates.get(item);
if (sourceState == null) {
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2010 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -22,6 +22,7 @@ import com.intellij.openapi.module.ConfigurationErrorType;
import com.intellij.openapi.project.Project;
import com.intellij.packaging.artifacts.ArtifactManager;
import com.intellij.packaging.artifacts.ModifiableArtifactModel;
import org.jetbrains.annotations.NotNull;
/**
* @author nik
@@ -42,7 +43,7 @@ public class ArtifactLoadingErrorDescription extends ConfigurationErrorDescripti
final ModifiableArtifactModel model = ArtifactManager.getInstance(myProject).createModifiableModel();
model.removeArtifact(myArtifact);
new WriteAction() {
protected void run(final Result result) {
protected void run(@NotNull final Result result) {
model.commit();
}
}.execute();
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -48,7 +48,7 @@ public class ArtifactBuildTargetScopeProvider extends BuildTargetScopeProvider {
}
final List<TargetTypeBuildScope> scopes = new ArrayList<TargetTypeBuildScope>();
new ReadAction() {
protected void run(final Result result) {
protected void run(@NotNull final Result result) {
final Set<Artifact> artifacts = ArtifactCompileScope.getArtifactsToBuild(project, baseScope, false);
if (ArtifactCompileScope.getArtifacts(baseScope) == null) {
Set<Module> modules = ArtifactUtil.getModulesIncludedInArtifacts(artifacts, project);
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2010 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -23,6 +23,7 @@ import com.intellij.openapi.util.text.StringUtil;
import com.intellij.packaging.artifacts.Artifact;
import com.intellij.packaging.artifacts.ArtifactManager;
import com.intellij.util.containers.MultiMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.jps.api.CmdlineRemoteProto.Message.ControllerMessage.ParametersMessage.TargetTypeBuildScope;
import org.jetbrains.jps.incremental.artifacts.ArtifactBuildTargetType;
@@ -48,7 +49,7 @@ public class ArtifactCompilerUtil {
public static MultiMap<String, Artifact> createOutputToArtifactMap(final Project project) {
final MultiMap<String, Artifact> result = MultiMap.create(FileUtil.PATH_HASHING_STRATEGY);
new ReadAction() {
protected void run(final Result r) {
protected void run(@NotNull final Result r) {
for (Artifact artifact : ArtifactManager.getInstance(project).getArtifacts()) {
String outputPath = artifact.getOutputFilePath();
if (!StringUtil.isEmpty(outputPath)) {
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -280,7 +280,7 @@ public class ManifestFileUtil {
ApplicationManager.getApplication().assertIsDispatchThread();
final Ref<IOException> exc = Ref.create(null);
final VirtualFile file = new WriteAction<VirtualFile>() {
protected void run(final Result<VirtualFile> result) {
protected void run(@NotNull final Result<VirtualFile> result) {
VirtualFile dir = directory;
try {
if (!dir.getName().equals(MANIFEST_DIR_NAME)) {
@@ -169,7 +169,7 @@ public class BuildArtifactsBeforeRunTaskProvider extends BeforeRunTaskProvider<B
final List<Artifact> artifacts = new ArrayList<Artifact>();
new ReadAction() {
protected void run(final Result result) {
protected void run(@NotNull final Result result) {
for (ArtifactPointer pointer : task.getArtifactPointers()) {
ContainerUtil.addIfNotNull(pointer.getArtifact(), artifacts);
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -88,7 +88,7 @@ public class PackageFileWorker {
indicator.checkCanceled();
new ReadAction() {
@Override
protected void run(final Result result) {
protected void run(@NotNull final Result result) {
try {
packageFile(file, project, artifacts, packIntoArchives);
}
@@ -1,3 +1,18 @@
/*
* Copyright 2000-2015 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.compiler;
import com.intellij.ProjectTopics;
@@ -32,9 +47,10 @@ import com.intellij.util.concurrency.Semaphore;
import com.intellij.util.io.TestFileSystemBuilder;
import com.intellij.util.ui.UIUtil;
import gnu.trove.THashSet;
import junit.framework.Assert;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.util.JpsPathUtil;
import org.junit.Assert;
import javax.swing.*;
import java.io.File;
@@ -109,7 +125,8 @@ public abstract class BaseCompilerTestCase extends ModuleTestCase {
throw new RuntimeException(e);
}
new WriteAction() {
protected void run(final Result result) {
@Override
protected void run(@NotNull final Result result) {
VirtualFile virtualDir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(target);
assertNotNull(target.getAbsolutePath() + " not found", virtualDir);
virtualDir.refresh(false, true);
@@ -124,7 +141,7 @@ public abstract class BaseCompilerTestCase extends ModuleTestCase {
protected Module addModule(final String moduleName, final @Nullable VirtualFile sourceRoot, final @Nullable VirtualFile testRoot) {
return new WriteAction<Module>() {
@Override
protected void run(final Result<Module> result) {
protected void run(@NotNull final Result<Module> result) {
final Module module = createModule(moduleName);
if (sourceRoot != null) {
PsiTestUtil.addSourceContentToRoots(module, sourceRoot, false);
@@ -285,15 +302,6 @@ public abstract class BaseCompilerTestCase extends ModuleTestCase {
return result.get();
}
private Set<String> getRelativePaths(String[] paths) {
final Set<String> set = new THashSet<String>();
final String basePath = myProject.getBaseDir().getPath();
for (String path : paths) {
set.add(StringUtil.trimStart(StringUtil.trimStart(FileUtil.toSystemIndependentName(path), basePath), "/"));
}
return set;
}
protected void changeFile(VirtualFile file) {
changeFile(file, null);
}
@@ -313,7 +321,7 @@ public abstract class BaseCompilerTestCase extends ModuleTestCase {
protected void deleteFile(final VirtualFile file) {
new WriteAction() {
@Override
protected void run(final Result result) {
protected void run(@NotNull final Result result) {
try {
file.delete(this);
}
@@ -347,7 +355,7 @@ public abstract class BaseCompilerTestCase extends ModuleTestCase {
PlatformTestCase.myFilesToDelete.add(moduleFile);
return new WriteAction<Module>() {
@Override
protected void run(Result<Module> result) throws Throwable {
protected void run(@NotNull Result<Module> result) throws Throwable {
Module module = ModuleManager.getInstance(myProject)
.newModule(FileUtil.toSystemIndependentName(moduleFile.getAbsolutePath()), getModuleType().getId());
module.getModuleFile();
@@ -408,7 +416,7 @@ public abstract class BaseCompilerTestCase extends ModuleTestCase {
}
}
protected class CompilationLog {
protected static class CompilationLog {
private final Set<String> myGeneratedPaths;
private final boolean myExternalBuildUpToDate;
private final CompilerMessage[] myErrors;
@@ -438,7 +446,7 @@ public abstract class BaseCompilerTestCase extends ModuleTestCase {
return myWarnings;
}
private void assertSet(String name, Set<String> actual, String[] expected) {
private static void assertSet(String name, Set<String> actual, String[] expected) {
for (String path : expected) {
if (!actual.remove(path)) {
Assert.fail("'" + path + "' is not " + name + ". " + name + ": " + new HashSet<String>(actual));
@@ -1,3 +1,18 @@
/*
* Copyright 2000-2015 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.compiler.artifacts;
import com.intellij.facet.Facet;
@@ -58,7 +73,7 @@ public abstract class ArtifactsTestCase extends IdeaTestCase {
protected static void commitModel(final ModifiableArtifactModel model) {
new WriteAction() {
@Override
protected void run(final Result result) {
protected void run(@NotNull final Result result) {
model.commit();
}
}.execute();
@@ -90,7 +105,7 @@ public abstract class ArtifactsTestCase extends IdeaTestCase {
public static void renameFile(final VirtualFile file, final String newName) {
new WriteAction() {
@Override
protected void run(final Result result) {
protected void run(@NotNull final Result result) {
try {
file.rename(IdeaTestCase.class, newName);
}
@@ -104,7 +119,7 @@ public abstract class ArtifactsTestCase extends IdeaTestCase {
protected Module addModule(final String moduleName, final @Nullable VirtualFile sourceRoot) {
return new WriteAction<Module>() {
@Override
protected void run(final Result<Module> result) {
protected void run(@NotNull final Result<Module> result) {
final Module module = createModule(moduleName);
if (sourceRoot != null) {
PsiTestUtil.addSourceContentToRoots(module, sourceRoot);
@@ -1,3 +1,18 @@
/*
* Copyright 2000-2015 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.compiler.artifacts;
import com.intellij.openapi.application.Result;
@@ -16,6 +31,7 @@ import com.intellij.packaging.elements.PackagingElementResolvingContext;
import com.intellij.packaging.impl.elements.ArchivePackagingElement;
import com.intellij.packaging.impl.elements.DirectoryPackagingElement;
import com.intellij.packaging.impl.elements.ManifestFileUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
@@ -86,7 +102,7 @@ public class ArtifactsTestUtil {
public static void setOutput(final Project project, final String artifactName, final String outputPath) {
new WriteAction() {
@Override
protected void run(final Result result) {
protected void run(@NotNull final Result result) {
final ModifiableArtifactModel model = ArtifactManager.getInstance(project).createModifiableModel();
model.getOrCreateModifiableArtifact(findArtifact(project, artifactName)).setOutputPath(outputPath);
model.commit();
@@ -97,7 +113,7 @@ public class ArtifactsTestUtil {
public static void addArtifactToLayout(final Project project, final Artifact parent, final Artifact toAdd) {
new WriteAction() {
@Override
protected void run(final Result result) {
protected void run(@NotNull final Result result) {
final ModifiableArtifactModel model = ArtifactManager.getInstance(project).createModifiableModel();
final PackagingElement<?> artifactElement = PackagingElementFactory.getInstance().createArtifactElement(toAdd, project);
model.getOrCreateModifiableArtifact(parent).getRootElement().addOrFindChild(artifactElement);
@@ -1,3 +1,18 @@
/*
* Copyright 2000-2015 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.compiler.artifacts;
import com.intellij.openapi.application.PathManager;
@@ -17,6 +32,7 @@ import com.intellij.packaging.artifacts.Artifact;
import com.intellij.packaging.elements.PackagingElement;
import com.intellij.testFramework.VfsTestUtil;
import com.intellij.util.PathUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
@@ -105,7 +121,7 @@ public abstract class PackagingElementsTestCase extends ArtifactsTestCase {
final VirtualFile[] jars) {
return new WriteAction<Library>() {
@Override
protected void run(final Result<Library> result) {
protected void run(@NotNull final Result<Library> result) {
final Library library = LibraryTablesRegistrar.getInstance().getLibraryTable(project).createLibrary(name);
final Library.ModifiableModel libraryModel = library.getModifiableModel();
for (VirtualFile jar : jars) {
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -34,6 +34,7 @@ import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
@@ -89,7 +90,7 @@ public class JavaWithRuntimeCastSurrounder extends JavaExpressionSurrounder {
DebuggerInvocationUtil.invokeLater(project, new Runnable() {
public void run() {
new WriteCommandAction(project, CodeInsightBundle.message("command.name.surround.with.runtime.cast")) {
protected void run(Result result) throws Throwable {
protected void run(@NotNull Result result) throws Throwable {
try {
PsiElementFactory factory = JavaPsiFacade.getInstance(myElement.getProject()).getElementFactory();
PsiParenthesizedExpression parenth =
@@ -1080,15 +1080,17 @@ public class EvaluatorBuilderImpl implements EvaluatorBuilder {
final boolean performCastToWrapperClass = shouldPerformBoxingConversion && !castingToPrimitive;
String castTypeName = castType.getCanonicalText();
if (performCastToWrapperClass) {
final PsiPrimitiveType unboxedType = PsiPrimitiveType.getUnboxedType(castType);
if (unboxedType != null) {
castTypeName = unboxedType.getCanonicalText();
if (!(PsiUtil.resolveClassInClassTypeOnly(castType) instanceof PsiTypeParameter)) {
String castTypeName = castType.getCanonicalText();
if (performCastToWrapperClass) {
final PsiPrimitiveType unboxedType = PsiPrimitiveType.getUnboxedType(castType);
if (unboxedType != null) {
castTypeName = unboxedType.getCanonicalText();
}
}
}
myResult = new TypeCastEvaluator(operandEvaluator, castTypeName, castingToPrimitive);
myResult = new TypeCastEvaluator(operandEvaluator, castTypeName, castingToPrimitive);
}
if (performCastToWrapperClass) {
myResult = new BoxingEvaluator(myResult);
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -26,5 +26,5 @@ import org.jetbrains.java.debugger.breakpoints.properties.JavaBreakpointProperti
*/
public interface JavaBreakpointType<P extends JavaBreakpointProperties> {
@NotNull
Breakpoint createJavaBreakpoint(Project project, XBreakpoint<P> breakpoint);
Breakpoint<P> createJavaBreakpoint(Project project, XBreakpoint<P> breakpoint);
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -140,7 +140,7 @@ public class JavaExceptionBreakpointType extends JavaBreakpointTypeBase<JavaExce
@NotNull
@Override
public Breakpoint createJavaBreakpoint(Project project, XBreakpoint<JavaExceptionBreakpointProperties> breakpoint) {
public Breakpoint<JavaExceptionBreakpointProperties> createJavaBreakpoint(Project project, XBreakpoint<JavaExceptionBreakpointProperties> breakpoint) {
if (!XDebuggerManager.getInstance(project).getBreakpointManager().isDefaultBreakpoint(breakpoint)) {
return new ExceptionBreakpoint(project, breakpoint);
}
@@ -41,7 +41,9 @@ import javax.swing.*;
* @author Eugene Zhuravlev
* Date: Apr 26, 2005
*/
public class JavaFieldBreakpointType extends JavaLineBreakpointTypeBase<JavaFieldBreakpointProperties> implements JavaBreakpointType {
public class JavaFieldBreakpointType extends JavaLineBreakpointTypeBase<JavaFieldBreakpointProperties>
implements JavaBreakpointType<JavaFieldBreakpointProperties> {
public JavaFieldBreakpointType() {
super("java-field", DebuggerBundle.message("field.watchpoints.tab.title"));
}
@@ -121,7 +123,7 @@ public class JavaFieldBreakpointType extends JavaLineBreakpointTypeBase<JavaFiel
@Nullable
@Override
public XLineBreakpoint<JavaFieldBreakpointProperties> addBreakpoint(final Project project, JComponent parentComponent) {
final Ref<XLineBreakpoint> result = Ref.create(null);
final Ref<XLineBreakpoint<JavaFieldBreakpointProperties>> result = Ref.create(null);
AddFieldBreakpointDialog dialog = new AddFieldBreakpointDialog(project) {
protected boolean validateData() {
final String className = getClassName();
@@ -178,7 +180,7 @@ public class JavaFieldBreakpointType extends JavaLineBreakpointTypeBase<JavaFiel
@NotNull
@Override
public Breakpoint createJavaBreakpoint(Project project, XBreakpoint breakpoint) {
public Breakpoint<JavaFieldBreakpointProperties> createJavaBreakpoint(Project project, XBreakpoint breakpoint) {
return new FieldBreakpoint(project, breakpoint);
}
@@ -44,7 +44,8 @@ import java.util.List;
* Base class for java line-connected exceptions (line, method, field)
* @author egor
*/
public class JavaLineBreakpointType extends JavaLineBreakpointTypeBase<JavaLineBreakpointProperties> implements JavaBreakpointType {
public class JavaLineBreakpointType extends JavaLineBreakpointTypeBase<JavaLineBreakpointProperties>
implements JavaBreakpointType<JavaLineBreakpointProperties> {
public JavaLineBreakpointType() {
super("java-line", DebuggerBundle.message("line.breakpoints.tab.title"));
}
@@ -78,8 +79,8 @@ public class JavaLineBreakpointType extends JavaLineBreakpointTypeBase<JavaLineB
@NotNull
@Override
public Breakpoint createJavaBreakpoint(Project project, XBreakpoint breakpoint) {
return new LineBreakpoint(project, breakpoint);
public Breakpoint<JavaLineBreakpointProperties> createJavaBreakpoint(Project project, XBreakpoint breakpoint) {
return new LineBreakpoint<JavaLineBreakpointProperties>(project, breakpoint);
}
@Override
@@ -34,7 +34,8 @@ import javax.swing.*;
* @author Eugene Zhuravlev
* Date: Apr 26, 2005
*/
public class JavaMethodBreakpointType extends JavaLineBreakpointTypeBase<JavaMethodBreakpointProperties> implements JavaBreakpointType {
public class JavaMethodBreakpointType extends JavaLineBreakpointTypeBase<JavaMethodBreakpointProperties>
implements JavaBreakpointType<JavaMethodBreakpointProperties> {
public JavaMethodBreakpointType() {
super("java-method", DebuggerBundle.message("method.breakpoints.tab.title"));
}
@@ -124,7 +125,7 @@ public class JavaMethodBreakpointType extends JavaLineBreakpointTypeBase<JavaMet
@NotNull
@Override
public Breakpoint createJavaBreakpoint(Project project, XBreakpoint breakpoint) {
public Breakpoint<JavaMethodBreakpointProperties> createJavaBreakpoint(Project project, XBreakpoint breakpoint) {
return new MethodBreakpoint(project, breakpoint);
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 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,7 +33,9 @@ import javax.swing.*;
/**
* @author Egor
*/
public class JavaWildcardMethodBreakpointType extends JavaBreakpointTypeBase<JavaMethodBreakpointProperties> implements JavaBreakpointType {
public class JavaWildcardMethodBreakpointType extends JavaBreakpointTypeBase<JavaMethodBreakpointProperties>
implements JavaBreakpointType<JavaMethodBreakpointProperties> {
public JavaWildcardMethodBreakpointType() {
super("java-wildcard-method", DebuggerBundle.message("method.breakpoints.tab.title"));
}
@@ -114,7 +116,7 @@ public class JavaWildcardMethodBreakpointType extends JavaBreakpointTypeBase<Jav
@NotNull
@Override
public Breakpoint createJavaBreakpoint(Project project, XBreakpoint breakpoint) {
public Breakpoint<JavaMethodBreakpointProperties> createJavaBreakpoint(Project project, XBreakpoint<JavaMethodBreakpointProperties> breakpoint) {
return new WildcardMethodBreakpoint(project, breakpoint);
}
}
@@ -62,6 +62,7 @@ import com.sun.jdi.request.BreakpointRequest;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.java.debugger.breakpoints.properties.JavaBreakpointProperties;
import org.jetbrains.java.debugger.breakpoints.properties.JavaLineBreakpointProperties;
import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes;
@@ -71,7 +72,7 @@ import java.util.Collection;
import java.util.List;
import java.util.regex.Pattern;
public class LineBreakpoint extends BreakpointWithHighlighter {
public class LineBreakpoint<P extends JavaBreakpointProperties> extends BreakpointWithHighlighter<P> {
private static final Logger LOG = Logger.getInstance("#com.intellij.debugger.ui.breakpoints.LineBreakpoint");
public static final @NonNls Key<LineBreakpoint> CATEGORY = BreakpointCategory.lookup("line_breakpoints");
@@ -34,7 +34,7 @@ import org.jetbrains.java.debugger.breakpoints.properties.JavaBreakpointProperti
* @author Eugene Zhuravlev
* Date: Sep 13, 2006
*/
public class RunToCursorBreakpoint extends LineBreakpoint {
public class RunToCursorBreakpoint<P extends JavaBreakpointProperties> extends LineBreakpoint<P> {
private final boolean myRestoreBreakpoints;
@NotNull
protected final SourcePosition myCustomPosition;
@@ -116,7 +116,7 @@ public class RunToCursorBreakpoint extends LineBreakpoint {
}
@Override
protected JavaBreakpointProperties getProperties() {
protected P getProperties() {
return null;
}
@@ -29,6 +29,7 @@ import com.sun.jdi.*;
import com.sun.jdi.request.BreakpointRequest;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.java.debugger.breakpoints.properties.JavaBreakpointProperties;
import java.util.*;
@@ -36,7 +37,7 @@ import java.util.*;
* @author Eugene Zhuravlev
* Date: Sep 13, 2006
*/
public class StepIntoBreakpoint extends RunToCursorBreakpoint {
public class StepIntoBreakpoint<P extends JavaBreakpointProperties> extends RunToCursorBreakpoint<P> {
private static final Logger LOG = Logger.getInstance("#com.intellij.debugger.ui.breakpoints.StepIntoBreakpoint");
@NotNull
private final BreakpointStepMethodFilter myFilter;
@@ -61,7 +61,7 @@ public class WildcardMethodBreakpoint extends Breakpoint<JavaMethodBreakpointPro
public static final String JDOM_LABEL = "wildcard_breakpoint";
public WildcardMethodBreakpoint(Project project, XBreakpoint breakpoint) {
public WildcardMethodBreakpoint(Project project, XBreakpoint<JavaMethodBreakpointProperties> breakpoint) {
super(project, breakpoint);
}
@@ -69,7 +69,7 @@ public class WildcardMethodBreakpoint extends Breakpoint<JavaMethodBreakpointPro
return MethodBreakpoint.CATEGORY;
}
protected WildcardMethodBreakpoint(Project project, @NotNull String classPattern, @NotNull String methodName, XBreakpoint breakpoint) {
protected WildcardMethodBreakpoint(Project project, @NotNull String classPattern, @NotNull String methodName, XBreakpoint<JavaMethodBreakpointProperties> breakpoint) {
super(project, breakpoint);
setClassPattern(classPattern);
setMethodName(methodName);
@@ -253,7 +253,10 @@ public class WildcardMethodBreakpoint extends Breakpoint<JavaMethodBreakpointPro
return method != null && getMethodName().equals(method.name());
}
public static WildcardMethodBreakpoint create(Project project, final String classPattern, final String methodName, XBreakpoint xBreakpoint) {
public static WildcardMethodBreakpoint create(Project project,
final String classPattern,
final String methodName,
XBreakpoint<JavaMethodBreakpointProperties> xBreakpoint) {
return new WildcardMethodBreakpoint(project, classPattern, methodName, xBreakpoint);
}
+3 -1
View File
@@ -23,7 +23,9 @@
<root url="jar://$MODULE_DIR$/../../../lib/testDiscoveryInstrumenter.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
<SOURCES>
<root url="file://$MODULE_DIR$/testDiscovery" />
</SOURCES>
</library>
</orderEntry>
</component>
@@ -219,4 +219,7 @@ public abstract class TestDiscoveryConfiguration extends JavaTestConfigurationBa
public String getChangeList() {
return myChangeList;
}
@NotNull
public abstract String getFrameworkPrefix();
}
@@ -22,6 +22,7 @@ import com.intellij.execution.actions.ConfigurationContext;
import com.intellij.execution.configurations.ConfigurationType;
import com.intellij.execution.junit.JavaRunConfigurationProducerBase;
import com.intellij.execution.testframework.TestSearchScope;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.registry.Registry;
@@ -31,6 +32,7 @@ import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.testIntegration.TestFramework;
import com.intellij.util.containers.ContainerUtil;
import java.io.IOException;
import java.util.Collection;
@@ -41,7 +43,7 @@ public abstract class TestDiscoveryConfigurationProducer extends JavaRunConfigur
}
@Override
protected boolean setupConfigurationFromContext(TestDiscoveryConfiguration configuration,
protected boolean setupConfigurationFromContext(final TestDiscoveryConfiguration configuration,
ConfigurationContext configurationContext,
Ref<PsiElement> ref) {
if (!Registry.is("testDiscovery.enabled")) {
@@ -56,7 +58,13 @@ public abstract class TestDiscoveryConfigurationProducer extends JavaRunConfigur
try {
final Collection<String> testsByMethodName = TestDiscoveryIndex
.getInstance(configuration.getProject()).getTestsByMethodName(position.first, position.second);
if (testsByMethodName == null || testsByMethodName.isEmpty()) return false;
if (testsByMethodName == null || ContainerUtil.filter(testsByMethodName, new Condition<String>() {
@Override
public boolean value(String s) {
return s.startsWith(configuration.getFrameworkPrefix());
}
}).isEmpty()) return false;
}
catch (IOException e) {
return false;
@@ -22,6 +22,7 @@ import com.intellij.execution.configurations.JavaParameters;
import com.intellij.execution.configurations.RunConfigurationBase;
import com.intellij.execution.configurations.RunnerSettings;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.testframework.JavaTestLocator;
import com.intellij.execution.testframework.sm.runner.SMTRunnerEventsAdapter;
import com.intellij.execution.testframework.sm.runner.SMTRunnerEventsListener;
import com.intellij.execution.testframework.sm.runner.SMTestProxy;
@@ -34,7 +35,9 @@ import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.Alarm;
import com.intellij.util.ArrayUtil;
import com.intellij.util.PathUtil;
import com.intellij.util.messages.MessageBusConnection;
import org.jdom.Element;
@@ -45,6 +48,8 @@ import org.jetbrains.testme.instrumentation.ProjectData;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class TestDiscoveryExtension extends RunConfigurationExtension {
private static final Logger LOG = Logger.getInstance("#" + TestDiscoveryExtension.class.getName());
@@ -73,16 +78,25 @@ public class TestDiscoveryExtension extends RunConfigurationExtension {
final Alarm processTracesAlarm = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, null);
final MessageBusConnection connection = configuration.getProject().getMessageBus().connect();
connection.subscribe(SMTRunnerEventsListener.TEST_STATUS, new SMTRunnerEventsAdapter() {
private List<String> myCompletedMethodNames = new ArrayList<String>();
@Override
public void onTestFinished(@NotNull SMTestProxy test) {
final SMTestProxy.SMRootTestProxy root = test.getRoot();
if ((root == null || root.getHandler() == handler) && processTracesAlarm.getActiveRequestCount() == 0) {
/*processTracesAlarm.addRequest(new Runnable() {
@Override
public void run() {
processAvailableTraces(configuration);
if ((root == null || root.getHandler() == handler)) {
final String fullTestName = test.getLocationUrl();
if (fullTestName != null && fullTestName.startsWith(JavaTestLocator.TEST_PROTOCOL)) {
myCompletedMethodNames.add(fullTestName.substring(JavaTestLocator.TEST_PROTOCOL.length() + 3));
if (myCompletedMethodNames.size() > 50) {
final String[] fullTestNames = ArrayUtil.toStringArray(myCompletedMethodNames);
myCompletedMethodNames.clear();
processTracesAlarm.addRequest(new Runnable() {
@Override
public void run() {
processAvailableTraces(configuration, fullTestNames);
}
}, 100);
}
}, 200);*/
}
}
}
@@ -144,6 +158,7 @@ public class TestDiscoveryExtension extends RunConfigurationExtension {
}
private static final Object ourTracesLock = new Object();
private static void processAvailableTraces(RunConfigurationBase configuration) {
final String tracesDirectory = getTracesDirectory(configuration);
final TestDiscoveryIndex coverageIndex = TestDiscoveryIndex.getInstance(configuration.getProject());
@@ -167,4 +182,28 @@ public class TestDiscoveryExtension extends RunConfigurationExtension {
}
}
}
private static void processAvailableTraces(RunConfigurationBase configuration, String[] fullTestNames) {
final String tracesDirectory = getTracesDirectory(configuration);
final TestDiscoveryIndex coverageIndex = TestDiscoveryIndex.getInstance(configuration.getProject());
synchronized (ourTracesLock) {
for (String fullTestName : fullTestNames) {
final String className = StringUtil.getPackageName(fullTestName);
final String methodName = StringUtil.getShortName(fullTestName);
if (!StringUtil.isEmptyOrSpaces(className) && !StringUtil.isEmptyOrSpaces(methodName)) {
final File testMethodTrace = new File(tracesDirectory, className + "-" + methodName + ".tr");
if (testMethodTrace.exists()) {
try {
coverageIndex.updateFromTestTrace(testMethodTrace);
FileUtil.delete(testMethodTrace);
}
catch (IOException e) {
LOG.error("Can not load " + testMethodTrace, e);
}
}
}
}
}
}
}
@@ -18,6 +18,7 @@ package com.intellij.execution.testDiscovery;
import com.intellij.codeInsight.actions.FormatChangedTextUtil;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.vcs.changes.Change;
@@ -27,6 +28,7 @@ import com.intellij.openapi.vcs.changes.LocalChangeList;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.diff.FilesTooBigForDiffException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -35,17 +37,14 @@ import java.io.IOException;
import java.util.*;
public class TestDiscoverySearchHelper {
public static Set<String> search(final Project project, final Pair<String, String> position, final String changeList) {
public static Set<String> search(final Project project,
final Pair<String, String> position,
final String changeList,
final String frameworkPrefix) {
final Set<String> patterns = new LinkedHashSet<String>();
if (position != null) {
try {
final Collection<String> testsByMethodName = TestDiscoveryIndex
.getInstance(project).getTestsByMethodName(position.first, position.second);
if (testsByMethodName != null) {
for (String pattern : testsByMethodName) {
patterns.add(pattern.replace('-', ','));
}
}
collectPatterns(project, patterns, position.first, position.second, frameworkPrefix);
}
catch (IOException ignore) {
}
@@ -73,7 +72,7 @@ public class TestDiscoverySearchHelper {
methods.add(containingMethod);
}
for (PsiMethod changedMethod : methods) {
final LinkedHashSet<String> detectedPatterns = collectPatterns(changedMethod);
final LinkedHashSet<String> detectedPatterns = collectPatterns(changedMethod, frameworkPrefix);
if (detectedPatterns != null) {
patterns.addAll(detectedPatterns);
}
@@ -90,6 +89,25 @@ public class TestDiscoverySearchHelper {
return patterns;
}
private static void collectPatterns(final Project project,
final Set<String> patterns,
final String classFQName,
final String methodName,
final String frameworkId) throws IOException {
final Collection<String> testsByMethodName = TestDiscoveryIndex
.getInstance(project).getTestsByMethodName(classFQName, methodName);
if (testsByMethodName != null) {
for (String pattern : ContainerUtil.filter(testsByMethodName, new Condition<String>() {
@Override
public boolean value(String s) {
return s.startsWith(frameworkId);
}
})) {
patterns.add(pattern.substring(frameworkId.length()).replace('-', ','));
}
}
}
@NotNull
private static List<VirtualFile> getAffectedFiles(String changeListName, Project project) {
final ChangeListManager changeListManager = ChangeListManager.getInstance(project);
@@ -115,20 +133,14 @@ public class TestDiscoverySearchHelper {
}
@Nullable
private static LinkedHashSet<String> collectPatterns(PsiMethod psiMethod) {
private static LinkedHashSet<String> collectPatterns(PsiMethod psiMethod, String frameworkId) {
LinkedHashSet<String> patterns = new LinkedHashSet<String>();
final PsiClass containingClass = psiMethod.getContainingClass();
if (containingClass != null) {
final String qualifiedName = containingClass.getQualifiedName();
if (qualifiedName != null) {
try {
final Collection<String> testsByMethodName
= TestDiscoveryIndex.getInstance(containingClass.getProject()).getTestsByMethodName(qualifiedName, psiMethod.getName());
if (testsByMethodName != null) {
for (String pattern : testsByMethodName) {
patterns.add(pattern.replace('-', ','));
}
}
collectPatterns(psiMethod.getProject(), patterns, qualifiedName, psiMethod.getName(), frameworkId);
}
catch (IOException e) {
return null;
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2015 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,7 +16,6 @@
package com.intellij.execution.ui;
import com.intellij.execution.ExecutionBundle;
import com.intellij.execution.JavaExecutionUtil;
import com.intellij.execution.configuration.BrowseModuleValueActionListener;
import com.intellij.execution.configurations.ConfigurationUtil;
import com.intellij.ide.util.ClassFilter;
@@ -33,6 +32,7 @@ import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.PsiMethodUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public abstract class ClassBrowser extends BrowseModuleValueActionListener {
@@ -96,7 +96,7 @@ public abstract class ClassBrowser extends BrowseModuleValueActionListener {
private PsiMethod findMainMethod(final PsiClass aClass) {
return new ReadAction<PsiMethod>() {
@Override
protected void run(Result<PsiMethod> result) throws Throwable {
protected void run(@NotNull Result<PsiMethod> result) throws Throwable {
result.setResult(PsiMethodUtil.findMainMethod(aClass));
}
}.execute().getResultObject();
@@ -0,0 +1,35 @@
<!--
~ 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.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<project name="Test Discovery Agent" default="all">
<dirname property="module.home" file="${ant.file}"/>
<dirname property="idea.home" file="${module.home}/../../../../"/>
<property name="idea.lib.path" value="${idea.home}/community/lib"/>
<property name="instrumenter.jar" value="${idea.lib.path}/testDiscoveryInstrumenter.jar"/>
<property name="build.rt.classes.dir" value="${idea.home}/out/classes/production"/>
<target name="all" >
<delete dir="${instrumenter.jar}"/>
<jar destfile="${instrumenter.jar}">
<manifest>
<attribute name="Premain-Class" value="org.jetbrains.testme.instrumentation.CoveragePremain"/>
</manifest>
<fileset dir="${build.rt.classes.dir}/execution-impl" includes="org/jetbrains/testme/instrumentation/**"/>
</jar>
</target>
</project>
@@ -0,0 +1,76 @@
/*
* 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.testme.instrumentation;
import java.io.File;
import java.lang.instrument.Instrumentation;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
public class CoveragePremain {
public static void premain(String argsString, Instrumentation instrumentation) throws Exception {
final File lib = new File(getArchivePath()).getParentFile();
final URL[] urls = new URL[3];
urls[0] = fileToURL(new File(lib, "testDiscoveryInstrumenter.jar"));
urls[1] = fileToURL(new File(lib, "asm-all.jar"));
urls[2] = fileToURL(new File(lib, "trove4j.jar"));
final Class instrumentator = Class.forName("org.jetbrains.testme.instrumentation.TestDiscoveryInstrumentator", true, new URLClassLoader(urls) {
protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException {
synchronized (this) {
Class result = findLoadedClass(name);
if (result == null) {
try {
result = findClass(name);
} catch (ClassNotFoundException e) {
//ignore, will try to find class in parent
}
}
if (result != null && resolve) {
resolveClass(result);
}
if (result != null) {
return result;
}
}
return getParent().loadClass(name);
}
});
final Method premainMethod = instrumentator.getDeclaredMethod("premain", new Class[]{String.class, Instrumentation.class});
premainMethod.invoke(null, new Object[] {argsString, instrumentation});
}
private static URL fileToURL(final File file) throws MalformedURLException {
return file.getAbsoluteFile().toURI().toURL();
}
private static String getArchivePath() {
final String className = CoveragePremain.class.getName().replace('.', '/') + ".class";
URL resourceURL = CoveragePremain.class.getResource("/" + className);
if (resourceURL == null) {
resourceURL = ClassLoader.getSystemResource(className);
}
return URLsUtil.extractRoot(resourceURL, "/" + className);
}
}
@@ -0,0 +1,37 @@
package org.jetbrains.testme.instrumentation;
import org.jetbrains.org.objectweb.asm.Opcodes;
public class InstrumentedMethodsFilter {
private final String myClassName;
private boolean myEnum;
public InstrumentedMethodsFilter(String className) {
myClassName = className;
}
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
myEnum = (access & Opcodes.ACC_ENUM) != 0;
}
public boolean shouldVisitMethod(final int access,
final String name,
final String desc,
final String signature,
final String[] exceptions) {
if ((access & Opcodes.ACC_BRIDGE) != 0) return false; //try to skip bridge methods
if ((access & Opcodes.ACC_ABSTRACT) != 0) return false; //skip abstracts; do not include interfaces without non-abstract methods in result
if ("<clinit>".equals(name) || "<init>".equals(name)) return false; //skip (static/instance) initializers
if (myEnum && isDefaultEnumMethod(name, desc, signature, myClassName)) {
return false;
}
return true;
}
private static boolean isDefaultEnumMethod(String name, String desc, String signature, String className) {
return name.equals("values") && desc.equals("()[L" + className + ";") ||
name.equals("valueOf") && desc.equals("(Ljava/lang/String;)L" + className + ";") ||
name.equals("<init>") && signature != null && signature.equals("()V");
}
}
@@ -0,0 +1,148 @@
/*
* 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.testme.instrumentation;
import org.jetbrains.org.objectweb.asm.ClassVisitor;
import org.jetbrains.org.objectweb.asm.Label;
import org.jetbrains.org.objectweb.asm.MethodVisitor;
import org.jetbrains.org.objectweb.asm.Opcodes;
public class Instrumenter extends ClassVisitor {
protected final ClassVisitor myClassVisitor;
private final String myClassName;
private final String myInternalClassName;
private final InstrumentedMethodsFilter myMethodFilter;
private final String[] myMethodNames;
private int myCurrentMethodCount;
private boolean myVisitedStaticBlock;
private static final String METHODS_VISITED = "__$methodsVisited$__";
private static final String METHODS_VISITED_CLASS = "[Z";
public Instrumenter(ClassVisitor classVisitor, String className, String[] methodNames) {
super(Opcodes.ASM5, classVisitor);
myClassVisitor = classVisitor;
myMethodFilter = new InstrumentedMethodsFilter(className);
myClassName = className.replace('$', '.'); // for inner classes
myInternalClassName = className.replace('.', '/');
myMethodNames = methodNames;
}
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
myMethodFilter.visit(version, access, name, signature, superName, interfaces);
super.visit(version, access, name, signature, superName, interfaces);
}
public MethodVisitor visitMethod(final int access,
final String name,
final String desc,
final String signature,
final String[] exceptions) {
final MethodVisitor mv = cv.visitMethod(access, name, desc, signature, exceptions);
if (mv == null) return mv;
if ("<clinit>".equals(name)) {
myVisitedStaticBlock = true;
return new StaticBlockMethodVisitor(mv);
}
if (!myMethodFilter.shouldVisitMethod(access, name, desc, signature, exceptions)) return mv;
assert myCurrentMethodCount < myMethodNames.length;
return new MethodVisitor(Opcodes.ASM5, mv) {
final int myMethodId = myCurrentMethodCount++;
public void visitCode() {
visitFieldInsn(Opcodes.GETSTATIC, myInternalClassName, METHODS_VISITED, METHODS_VISITED_CLASS);
pushInstruction(this, myMethodId);
visitInsn(Opcodes.ICONST_1);
visitInsn(Opcodes.BASTORE);
super.visitCode();
}
};
}
@Override
public void visitEnd() {
visitField(Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_STATIC, METHODS_VISITED,
METHODS_VISITED_CLASS, null, null);
if (!myVisitedStaticBlock) {
MethodVisitor mv = super.visitMethod(Opcodes.ACC_STATIC, "<clinit>", "()V", null, null);
mv = new StaticBlockMethodVisitor(mv);
mv.visitCode();
mv.visitInsn(Opcodes.RETURN);
mv.visitMaxs(myMethodNames.length + 2, 1);
mv.visitEnd();
}
super.visitEnd();
}
private class StaticBlockMethodVisitor extends MethodVisitor {
public StaticBlockMethodVisitor(MethodVisitor mv) {
super(Opcodes.ASM5, mv);
}
public void visitCode() {
super.visitCode();
pushInstruction(this, myMethodNames.length);
visitIntInsn(Opcodes.NEWARRAY, Opcodes.T_BOOLEAN);
visitFieldInsn(Opcodes.PUTSTATIC, myInternalClassName, METHODS_VISITED, METHODS_VISITED_CLASS);
pushInstruction(this, myMethodNames.length);
visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/String");
for(int i = 0; i < myMethodNames.length; ++i) {
visitInsn(Opcodes.DUP);
pushInstruction(this, i);
visitLdcInsn(myMethodNames[i]);
visitInsn(Opcodes.AASTORE);
}
visitVarInsn(Opcodes.ASTORE, 0);
Label startLabel = new Label();
visitLabel(startLabel);
visitLdcInsn(myClassName);
visitFieldInsn(Opcodes.GETSTATIC, myInternalClassName, METHODS_VISITED, METHODS_VISITED_CLASS);
visitVarInsn(Opcodes.ALOAD, 0);
visitMethodInsn(Opcodes.INVOKESTATIC, ProjectData.PROJECT_DATA_OWNER, "trace", "(Ljava/lang/String;[Z[Ljava/lang/String;)V", false);
Label endLabel = new Label();
visitLabel(endLabel);
visitLocalVariable("methodNames", "[Ljava/lang/String;", null, startLabel, endLabel, 0);
// no return here
}
public void visitMaxs(int maxStack, int maxLocals) {
final int ourMaxStack = myMethodNames.length + 2;
final int ourMaxLocals = 1;
super.visitMaxs(Math.max(ourMaxStack, maxStack), Math.max(ourMaxLocals, maxLocals));
}
}
private static void pushInstruction(MethodVisitor mv, int operand) {
if (operand < Byte.MAX_VALUE) mv.visitIntInsn(Opcodes.BIPUSH, operand);
else mv.visitIntInsn(Opcodes.SIPUSH, operand);
}
}
@@ -0,0 +1,158 @@
package org.jetbrains.testme.instrumentation;
import java.io.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
public class ProjectData {
public static final String PROJECT_DATA_OWNER = "org/jetbrains/testme/instrumentation/ProjectData";
public static final String TRACE_DIR = "org.jetbrains.testme.instrumentation.trace.dir";
protected static final ProjectData ourData = new ProjectData();
private String myTraceDir = System.getProperty(TRACE_DIR, "");
public void setTraceDir(String traceDir) {
myTraceDir = traceDir;
}
private ConcurrentMap<String, Set<String>> myTrace;
private final ConcurrentMap<String, boolean[]> myTrace2 = new ConcurrentHashMap<String, boolean[]>();
private final ConcurrentMap<String, String[]> myTrace3 = new ConcurrentHashMap<String, String[]>();
public static ProjectData getProjectData() {
return ourData;
}
public static void trace(String className, String methodSignature) {
ourData.traceLines(className, methodSignature);
}
// called from instrumented code during class's static init
public static void trace(String className, boolean[] methodFlags, String[] methodNames) {
ourData.traceLines(className, methodFlags, methodNames);
}
public void traceLines(String className, String methodSignature) {
if (myTrace != null) {
Set<String> methods = myTrace.get(className);
if (methods == null) {
methods = new HashSet<String>();
Set<String> previousMethods = myTrace.putIfAbsent(className, methods);
if (previousMethods != null) methods = previousMethods;
}
synchronized (methods) {
methods.add(methodSignature);
}
}
}
public synchronized void traceLines(String className, boolean[] methodFlags, String[] methodNames) {
//System.out.println("Registering " + className);
assert methodFlags.length == methodNames.length;
myTrace2.put(className, methodFlags);
myTrace3.put(className, methodNames);
}
private static volatile boolean traceDirDumped;
public synchronized void testEnded(final String name) {
//if (myTrace == null) return;
if (!traceDirDumped) {
ClassLoader classLoader = TestDiscoveryInstrumentator.class.getClassLoader();
System.out.println(ourData + "; cl: " + classLoader+ "," + classLoader.getParent());
System.out.println("Trace dir:" + myTraceDir);
traceDirDumped = true;
}
new File(myTraceDir).mkdirs();
final File traceFile = new File(myTraceDir, name + ".tr");
try {
if (!traceFile.exists()) {
traceFile.createNewFile();
}
DataOutputStream os = null;
Deflater def = new Deflater(1);
try {
os = new DataOutputStream(new DeflaterOutputStream(new BufferedOutputStream(new FileOutputStream(traceFile)), def));
//saveOldTrace(os);
Map<String, Integer> classToUsedMethods = new HashMap<String, Integer>();
for(Map.Entry<String, boolean[]> e: myTrace2.entrySet()) {
boolean[] used = e.getValue();
int usedMethodsCount = 0;
for (boolean anUsed : used) {
if (anUsed) ++usedMethodsCount;
}
if (usedMethodsCount > 0) {
classToUsedMethods.put(e.getKey(), usedMethodsCount);
}
}
os.writeInt(classToUsedMethods.size());
for(Map.Entry<String, boolean[]> e: myTrace2.entrySet()) {
final boolean[] used = e.getValue();
final String className = e.getKey();
Integer integer = classToUsedMethods.get(className);
if (integer == null) continue;;
int usedMethodsCount = integer;
os.writeUTF(className);
os.writeInt(usedMethodsCount);
String[] methodNames = myTrace3.get(className);
for (int i = 0, len = used.length; i < len; ++i) {
// we check usedMethodCount here since used was observed to change // ?
if (used[i] && usedMethodsCount-- > 0) os.writeUTF(methodNames[i]);
}
}
}
finally {
if (os != null) {
os.close();
}
def.end();
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
myTrace = null;
}
}
private void saveOldTrace(DataOutputStream os) throws IOException {
os.writeInt(myTrace.size());
for (Iterator<String> it = myTrace.keySet().iterator(); it.hasNext();) {
final String classData = it.next();
os.writeUTF(classData);
final Set<String> methods = myTrace.get(classData);
os.writeInt(methods.size());
for (Iterator<String> iterator = methods.iterator(); iterator.hasNext(); ) {
os.writeUTF(iterator.next());
}
}
}
public synchronized void testStarted(final String name) {
//clearOldTrace();
for(Map.Entry<String, boolean[]> e: myTrace2.entrySet()) {
boolean[] used = e.getValue();
for(int i = 0, len = used.length; i < len; ++i) {
if(used[i]) used[i] = false;
}
}
}
private void clearOldTrace() {
myTrace = new ConcurrentHashMap<String, Set<String>>();
}
}
@@ -0,0 +1,265 @@
/*
* Copyright 2000-2015 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.testme.instrumentation;
import org.jetbrains.org.objectweb.asm.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
public class TestDiscoveryInstrumentator {
public static void premain(String argsString, Instrumentation instrumentation) throws Exception {
instrumentation.addTransformer(new ClassFileTransformer() {
private boolean computeFrames = computeFrames();
public byte[] transform(ClassLoader loader,
String className,
Class classBeingRedefined,
ProtectionDomain protectionDomain,
byte[] classfileBuffer) throws IllegalClassFormatException {
try {
if (className == null) {
return null;
}
if (loader == null) {
// skip classes loaded by system classloader
//System.out.println("Skipping " + className);
return null;
}
if (className.endsWith(".class")) {
className = className.substring(0, className.length() - 6);
}
className = className.replace('\\', '.').replace('/', '.');
if (className.startsWith("com.intellij.rt.")
|| className.startsWith("com.intellij.util.lang.")
|| className.startsWith("com.intellij.util.containers.")
|| className.startsWith("com.intellij.openapi.util.text.")
|| className.startsWith("com.intellij.openapi.util.io.")
|| className.startsWith("java.")
|| className.startsWith("sun.")
|| className.startsWith("gnu.trove.")
|| className.startsWith("org.jetbrains.org.objectweb.asm.")
|| className.startsWith("org.apache.oro.text.regex.")
|| className.startsWith("org.jetbrains.testme.")
|| className.startsWith("org.junit.")
|| className.startsWith("com.sun.")
|| className.startsWith("junit.")
|| className.startsWith("jdk.internal.")
|| className.startsWith("com.intellij.junit3.")
|| className.startsWith("com.intellij.junit4.")) {
return null;
}
//System.out.println(className);
return instrument(classfileBuffer, className, loader, computeFrames);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
private boolean computeFrames() {
return System.getProperty("idea.coverage.no.frames") == null;
}
});
}
private final static AtomicInteger myInstrumentedClasses = new AtomicInteger();
private final static AtomicInteger myInstrumentedMethods = new AtomicInteger();
private final static AtomicLong myInstrumentedClassesTime = new AtomicLong();
private static byte[] instrument(final byte[] classfileBuffer, final String className, ClassLoader loader, boolean computeFrames) {
long started = System.nanoTime();
final ClassReader cr = new ClassReader(classfileBuffer);
final ClassWriter cw;
if (computeFrames && false) {
final int version = getClassFileVersion(cr);
cw = getClassWriter(version >= Opcodes.V1_6 && version != Opcodes.V1_1 ? ClassWriter.COMPUTE_FRAMES : ClassWriter.COMPUTE_MAXS, loader);
} else {
cw = getClassWriter(ClassWriter.COMPUTE_MAXS, loader);
}
final List<String> instrumentedMethods = new ArrayList<String>();
final ClassVisitor instrumentedMethodCounter = new ClassVisitor(Opcodes.ASM5) {
final InstrumentedMethodsFilter methodsFilter = new InstrumentedMethodsFilter(className);
@Override
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
methodsFilter.visit(version, access, name, signature, superName, interfaces);
super.visit(version, access, name, signature, superName, interfaces);
}
@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
if (methodsFilter.shouldVisitMethod(access, name, desc, signature, exceptions)) {
instrumentedMethods.add(name);
}
return super.visitMethod(access, name, desc, signature, exceptions);
}
};
cr.accept(instrumentedMethodCounter, 0);
// todo there are duplicates in array of instrumented methods
final ClassVisitor cv = new Instrumenter(cw, className, instrumentedMethods.toArray(new String[instrumentedMethods.size()]));
cr.accept(cv, 0);
byte[] bytes = cw.toByteArray();
long time = myInstrumentedClassesTime.addAndGet(System.nanoTime() - started);
int classes = myInstrumentedClasses.incrementAndGet();
int methods = myInstrumentedMethods.addAndGet(instrumentedMethods.size());
if (classes % 1000 == 0) {
System.out.println("Done instrumenting " + classes + ", methods:" + methods + " for " + (time / 1000000));
}
if (false) {
try {
FileOutputStream fileOutputStream = new FileOutputStream("transformed-" + className);
try {
fileOutputStream.write(bytes);
fileOutputStream.close();
} finally {
fileOutputStream.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return bytes;
}
private static ClassWriter getClassWriter(int flags, final ClassLoader classLoader) {
return new MyClassWriter(flags, classLoader);
}
public static int getClassFileVersion(ClassReader reader) {
final int[] classFileVersion = new int[1];
reader.accept(new ClassVisitor(Opcodes.ASM5) {
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
classFileVersion[0] = version;
}
}, 0);
return classFileVersion[0];
}
private static class MyClassWriter extends ClassWriter {
public static final String JAVA_LANG_OBJECT = "java/lang/Object";
private final ClassLoader classLoader;
public MyClassWriter(int flags, ClassLoader classLoader) {
super(flags);
this.classLoader = classLoader;
}
protected String getCommonSuperClass(String type1, String type2) {
try {
ClassReader info1 = typeInfo(type1);
ClassReader info2 = typeInfo(type2);
String
superType = checkImplementInterface(type1, type2, info1, info2);
if (superType != null) return superType;
superType = checkImplementInterface(type2, type1, info2, info1);
if (superType != null) return superType;
StringBuilder b1 = typeAncestors(type1, info1);
StringBuilder b2 = typeAncestors(type2, info2);
String result = JAVA_LANG_OBJECT;
int end1 = b1.length();
int end2 = b2.length();
while (true) {
int start1 = b1.lastIndexOf(";", end1 - 1);
int start2 = b2.lastIndexOf(";", end2 - 1);
if (start1 != -1 && start2 != -1 && end1 - start1 == end2 - start2) {
String p1 = b1.substring(start1 + 1, end1);
String p2 = b2.substring(start2 + 1, end2);
if (p1.equals(p2)) {
result = p1;
end1 = start1;
end2 = start2;
} else {
return result;
}
} else {
return result;
}
}
} catch (IOException e) {
throw new RuntimeException(e.toString());
}
}
private String checkImplementInterface(String type1, String type2, ClassReader info1, ClassReader info2) throws IOException {
if ((info1.getAccess() & Opcodes.ACC_INTERFACE) != 0) {
if (typeImplements(type2, info2, type1)) {
return type1;
}
return JAVA_LANG_OBJECT;
}
return null;
}
private StringBuilder typeAncestors(String type, ClassReader info) throws IOException {
StringBuilder b = new StringBuilder();
while (!JAVA_LANG_OBJECT.equals(type)) {
b.append(';').append(type);
type = info.getSuperName();
info = typeInfo(type);
}
return b;
}
private boolean typeImplements(String type, ClassReader classReader, String interfaceName) throws IOException {
while (!JAVA_LANG_OBJECT.equals(type)) {
String[] itfs = classReader.getInterfaces();
for (int i = 0; i < itfs.length; ++i) {
if (itfs[i].equals(interfaceName)) {
return true;
}
}
for (int i = 0; i < itfs.length; ++i) {
if (typeImplements(itfs[i], typeInfo(itfs[i]), interfaceName)) {
return true;
}
}
type = classReader.getSuperName();
classReader = typeInfo(type);
}
return false;
}
private ClassReader typeInfo(final String type) throws IOException {
InputStream is = classLoader.getResourceAsStream(type + ".class");
if (is == null) System.out.println(classLoader + "," + type + ".class");
try {
return new ClassReader(is);
} finally {
is.close();
}
}
}
}
@@ -0,0 +1,137 @@
/*
* 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.testme.instrumentation;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class URLsUtil {
public static final String FILE = "file";
public static final String PROTOCOL_DELIMITER = ":";
public static final String JAR_DELIMITER = "!";
public static boolean startsWithChar(CharSequence s, char prefix) {
return s != null && s.length() != 0 && s.charAt(0) == prefix;
}
public static String extractRoot(URL resourceURL, String resourcePath) {
if (!(startsWithChar(resourcePath, '/') || startsWithChar(resourcePath, '\\'))) {
//noinspection HardCodedStringLiteral
System.err.println("precondition failed: "+resourcePath);
return null;
}
String protocol = resourceURL.getProtocol();
String resultPath = null;
if (FILE.equals(protocol)) {
String path = resourceURL.getFile();
final String testPath = path.replace('\\', '/');
final String testResourcePath = resourcePath.replace('\\', '/');
if (endsWithIgnoreCase(testPath, testResourcePath)) {
resultPath = path.substring(0, path.length() - resourcePath.length());
}
}
else if ("jar".equals(protocol)) {
String fullPath = resourceURL.getFile();
int delimiter = fullPath.indexOf(JAR_DELIMITER);
if (delimiter >= 0) {
String archivePath = fullPath.substring(0, delimiter);
if (startsWithConcatenationOf(archivePath, FILE, PROTOCOL_DELIMITER)) {
resultPath = archivePath.substring(FILE.length() + PROTOCOL_DELIMITER.length());
}
}
}
if (resultPath == null) {
//noinspection HardCodedStringLiteral
System.err.println("cannot extract: "+resultPath + " from "+resourceURL);
return null;
}
if (resourcePath.endsWith(File.separator)) {
resultPath = resultPath.substring(0, resultPath.lastIndexOf(File.separator));
}
resultPath = unescapePercentSequences(resultPath);
return resultPath;
}
public static boolean startsWithConcatenationOf(String testee, String firstPrefix, String secondPrefix) {
int l1 = firstPrefix.length();
int l2 = secondPrefix.length();
if (testee.length() < l1 + l2) return false;
return testee.startsWith(firstPrefix) && testee.regionMatches(l1, secondPrefix, 0, l2);
}
public static boolean endsWithIgnoreCase(String str, String suffix) {
final int stringLength = str.length();
final int suffixLength = suffix.length();
return stringLength >= suffixLength && str.regionMatches(true, stringLength - suffixLength, suffix, 0, suffixLength);
}
public static String unescapePercentSequences(String s) {
if (s.indexOf('%') == -1) {
return s;
}
StringBuilder decoded = new StringBuilder();
final int len = s.length();
int i = 0;
while (i < len) {
char c = s.charAt(i);
if (c == '%') {
List bytes = new ArrayList();
while (i + 2 < len && s.charAt(i) == '%') {
final int d1 = decode(s.charAt(i + 1));
final int d2 = decode(s.charAt(i + 2));
if (d1 != -1 && d2 != -1) {
bytes.add(new Integer(((d1 & 0xf) << 4 | d2 & 0xf)));
i += 3;
} else {
break;
}
}
if (!bytes.isEmpty()) {
final byte[] bytesArray = new byte[bytes.size()];
for (int j = 0; j < bytes.size(); j++) {
bytesArray[j] = (byte) ((Integer) bytes.get(j)).intValue();
}
try {
decoded.append(new String(bytesArray, "UTF-8"));
continue;
}
catch (UnsupportedEncodingException ignored) {
}
}
}
decoded.append(c);
i++;
}
return decoded.toString();
}
private static int decode(char c) {
if ((c >= '0') && (c <= '9'))
return c - '0';
if ((c >= 'a') && (c <= 'f'))
return c - 'a' + 10;
if ((c >= 'A') && (c <= 'F'))
return c - 'A' + 10;
return -1;
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -334,7 +334,7 @@ public class LibraryOptionsPanel implements Disposable {
dialog.show();
if (item instanceof ExistingLibraryEditor) {
new WriteAction() {
protected void run(final Result result) {
protected void run(@NotNull final Result result) {
((ExistingLibraryEditor)item).commit();
}
}.execute();
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2013 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -99,7 +99,7 @@ public class AddSupportForSingleFrameworkDialog extends DialogWrapper {
}
new WriteAction() {
protected void run(final Result result) {
protected void run(@NotNull final Result result) {
myModifiableModelsProvider.commitModuleModifiableModel(modifiableModel);
}
}.execute();
@@ -116,7 +116,7 @@ public class AddSupportForSingleFrameworkDialog extends DialogWrapper {
}
new WriteAction() {
protected void run(final Result result) {
protected void run(@NotNull final Result result) {
final ModifiableRootModel rootModel = myModifiableModelsProvider.getModuleModifiableModel(myModule);
if (librarySettings != null) {
librarySettings.addLibraries(rootModel, new ArrayList<Library>(), myModel.getLibrariesContainer());
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2013 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -96,7 +96,7 @@ public class AddFrameworkSupportDialog extends DialogWrapper {
}
new WriteAction() {
protected void run(final Result result) {
protected void run(@NotNull final Result result) {
ModifiableRootModel model = ModuleRootManager.getInstance(myModule).getModifiableModel();
myAddSupportPanel.addSupport(myModule, model);
model.commit();
@@ -32,6 +32,7 @@ import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.ShowSettingsUtil;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectBundle;
import com.intellij.openapi.projectRoots.Sdk;
@@ -300,23 +301,27 @@ public class ModulesConfigurator implements ModulesProvider, ModuleEditor.Change
}
myFacetsConfigurator.applyEditors();
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
DumbService.getInstance(myProject).allowStartingDumbModeInside(DumbService.DumbModePermission.MAY_START_BACKGROUND, new Runnable() {
public void run() {
try {
final ModifiableRootModel[] rootModels = models.toArray(new ModifiableRootModel[models.size()]);
ModifiableModelCommitter.multiCommit(rootModels, myModuleModel);
myModuleModelCommitted = true;
myFacetsConfigurator.commitFacets();
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
try {
final ModifiableRootModel[] rootModels = models.toArray(new ModifiableRootModel[models.size()]);
ModifiableModelCommitter.multiCommit(rootModels, myModuleModel);
myModuleModelCommitted = true;
myFacetsConfigurator.commitFacets();
}
finally {
ModuleStructureConfigurable.getInstance(myProject).getFacetEditorFacade().clearMaps(false);
}
finally {
ModuleStructureConfigurable.getInstance(myProject).getFacetEditorFacade().clearMaps(false);
myFacetsConfigurator = createFacetsConfigurator();
myModuleModel = ModuleManager.getInstance(myProject).getModifiableModel();
myModuleModelCommitted = false;
}
myFacetsConfigurator = createFacetsConfigurator();
myModuleModel = ModuleManager.getInstance(myProject).getModifiableModel();
myModuleModelCommitted = false;
}
}
});
}
});
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -303,7 +303,7 @@ public class ArtifactsStructureConfigurable extends BaseStructureConfigurable {
if (modifiableModel != null) {
new WriteAction() {
@Override
protected void run(final Result result) {
protected void run(@NotNull final Result result) {
modifiableModel.commit();
}
}.execute();
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -39,7 +39,10 @@ import com.intellij.packaging.ui.ManifestFileConfiguration;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* @author nik
@@ -142,7 +145,7 @@ public class ArtifactsStructureConfigurableContextImpl implements ArtifactsStruc
final Artifact originalArtifact = getOriginalArtifact(artifact);
new WriteAction() {
@Override
protected void run(final Result result) {
protected void run(@NotNull final Result result) {
final ModifiableArtifact modifiableArtifact = getOrCreateModifiableArtifactModel().getOrCreateModifiableArtifact(originalArtifact);
if (modifiableArtifact.getRootElement() == originalArtifact.getRootElement()) {
modifiableArtifact.setRootElement(getOrCreateModifiableRootElement(originalArtifact));
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -167,7 +167,7 @@ public abstract class ChangeLibraryLevelActionBase extends AnAction {
new WriteAction() {
@Override
protected void run(Result result) throws Throwable {
protected void run(@NotNull Result result) throws Throwable {
for (Map.Entry<String, String> entry : copiedFiles.entrySet()) {
String fromPath = entry.getKey();
String toPath = entry.getValue();
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2010 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -92,7 +92,7 @@ public class AddCustomLibraryDialog extends DialogWrapper {
final ModifiableRootModel model = ModuleRootManager.getInstance(myModule).getModifiableModel();
new WriteAction() {
@Override
protected void run(final Result result) {
protected void run(@NotNull final Result result) {
addLibraries(model, settings);
model.commit();
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -15,7 +15,6 @@
*/
package com.intellij.openapi.roots.ui.configuration.libraryEditor;
import com.intellij.ui.ListCellRendererWrapper;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.roots.impl.libraries.LibraryEx;
@@ -25,6 +24,7 @@ import com.intellij.openapi.roots.libraries.LibraryTable;
import com.intellij.openapi.roots.libraries.LibraryType;
import com.intellij.openapi.roots.ui.configuration.projectRoot.StructureConfigurableContext;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.ui.ListCellRendererWrapper;
import com.intellij.util.ui.FormBuilder;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -77,7 +77,7 @@ public class CreateNewLibraryDialog extends LibraryEditorDialogBase {
myLibraryEditor.applyTo(model);
new WriteAction() {
@Override
protected void run(final Result result) {
protected void run(@NotNull final Result result) {
model.commit();
}
}.execute();
@@ -20,6 +20,7 @@ import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.roots.impl.OrderEntryUtil;
import com.intellij.openapi.roots.impl.libraries.LibraryEx;
import com.intellij.openapi.roots.impl.libraries.LibraryTableBase;
import com.intellij.openapi.roots.libraries.Library;
@@ -236,16 +237,7 @@ public class LibrariesContainerFactory {
if (myRootModel != null) {
return myRootModel.getModuleLibraryTable().getLibraries();
}
OrderEntry[] orderEntries = ModuleRootManager.getInstance(myModule).getOrderEntries();
List<Library> libraries = new ArrayList<Library>();
for (OrderEntry orderEntry : orderEntries) {
if (orderEntry instanceof LibraryOrderEntry) {
final LibraryOrderEntry entry = (LibraryOrderEntry)orderEntry;
if (entry.isModuleLevel()) {
libraries.add(entry.getLibrary());
}
}
}
List<Library> libraries = OrderEntryUtil.getModuleLibraries(ModuleRootManager.getInstance(myModule));
return libraries.toArray(new Library[libraries.size()]);
}
@@ -1,3 +1,18 @@
/*
* Copyright 2000-2015 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.roots.ui.configuration.projectRoot.daemon;
import com.intellij.openapi.Disposable;
@@ -57,7 +72,7 @@ public class ProjectStructureDaemonAnalyzer implements Disposable {
final ProjectStructureProblemsHolderImpl problemsHolder = new ProjectStructureProblemsHolderImpl();
new ReadAction() {
@Override
protected void run(final Result result) {
protected void run(@NotNull final Result result) {
if (myStopped.get()) return;
if (LOG.isDebugEnabled()) {
@@ -72,7 +87,7 @@ public class ProjectStructureDaemonAnalyzer implements Disposable {
private void doCollectUsages(final ProjectStructureElement element) {
final List<ProjectStructureElementUsage> usages = new ReadAction<List<ProjectStructureElementUsage>>() {
@Override
protected void run(final Result<List<ProjectStructureElementUsage>> result) {
protected void run(@NotNull final Result<List<ProjectStructureElementUsage>> result) {
if (myStopped.get()) return;
if (LOG.isDebugEnabled()) {
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2013 JetBrains s.r.o.
* Copyright 2000-2015 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,7 +20,7 @@ import com.intellij.openapi.components.PathMacroManager;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.components.impl.ComponentManagerImpl;
import com.intellij.openapi.components.impl.stores.ComponentStoreImpl;
import com.intellij.openapi.components.impl.stores.StoreUtil;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileEditor.impl.FileEditorManagerImpl;
import com.intellij.openapi.project.Project;
@@ -88,7 +88,7 @@ public class SystemFileProcessor extends ProjectTemplateFileProcessor {
Object state = ((PersistentStateComponent)component).getState();
Element element1 = XmlSerializer.serialize(state);
element.addContent(element1.cloneContent());
element.setAttribute("name", ComponentStoreImpl.getComponentName((PersistentStateComponent)component));
element.setAttribute("name", StoreUtil.getComponentName((PersistentStateComponent)component));
}
}
});
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -40,20 +40,24 @@ import java.io.IOException;
public class ConfigFileFactoryImpl extends ConfigFileFactory {
private static final Logger LOG = Logger.getInstance("#com.intellij.util.descriptors.impl.ConfigFileFactoryImpl");
@Override
public ConfigFileMetaDataProvider createMetaDataProvider(final ConfigFileMetaData... metaDatas) {
return new ConfigFileMetaDataRegistryImpl(metaDatas);
}
@Override
public ConfigFileMetaDataRegistry createMetaDataRegistry() {
return new ConfigFileMetaDataRegistryImpl();
}
@Override
public ConfigFileInfoSet createConfigFileInfoSet(final ConfigFileMetaDataProvider metaDataProvider) {
return new ConfigFileInfoSetImpl(metaDataProvider);
}
@Override
public ConfigFileContainer createConfigFileContainer(final Project project, final ConfigFileMetaDataProvider metaDataProvider,
final ConfigFileInfoSet configuration) {
final ConfigFileInfoSet configuration) {
return new ConfigFileContainerImpl(project, metaDataProvider, (ConfigFileInfoSetImpl)configuration);
}
@@ -66,6 +70,7 @@ public class ConfigFileFactoryImpl extends ConfigFileFactory {
return template.getText(templateManager.getDefaultProperties());
}
@Override
@Nullable
public VirtualFile createFile(@Nullable Project project, String url, ConfigFileVersion version, final boolean forceNew) {
return createFileFromTemplate(project, url, version.getTemplateName(), forceNew);
@@ -106,6 +111,7 @@ public class ConfigFileFactoryImpl extends ConfigFileFactory {
catch (final IOException e) {
LOG.info(e);
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
Messages.showErrorDialog(IdeBundle.message("message.text.error.creating.deployment.descriptor", e.getLocalizedMessage()),
IdeBundle.message("message.text.creating.deployment.descriptor"));
@@ -115,6 +121,7 @@ public class ConfigFileFactoryImpl extends ConfigFileFactory {
return null;
}
@Override
public ConfigFileContainer createSingleFileContainer(Project project, ConfigFileMetaData metaData) {
final ConfigFileMetaDataProvider metaDataProvider = createMetaDataProvider(metaData);
return createConfigFileContainer(project, metaDataProvider, createConfigFileInfoSet(metaDataProvider));
@@ -321,12 +321,11 @@ public class AnnotationsHighlightUtil {
}
@Nullable
static HighlightInfo checkValidAnnotationType(final PsiTypeElement typeElement) {
PsiType type = typeElement.getType();
if (type.accept(AnnotationReturnTypeVisitor.INSTANCE).booleanValue()) {
static HighlightInfo checkValidAnnotationType(PsiType type, final PsiTypeElement typeElement) {
if (type != null && type.accept(AnnotationReturnTypeVisitor.INSTANCE).booleanValue()) {
return null;
}
String description = JavaErrorMessages.message("annotation.invalid.annotation.member.type");
String description = JavaErrorMessages.message("annotation.invalid.annotation.member.type", type != null ? type.getPresentableText() : type);
return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(typeElement).descriptionAndTooltip(description).create();
}
@@ -275,7 +275,7 @@ public class HighlightVisitorImpl extends JavaElementVisitor implements Highligh
myHolder.add(AnnotationsHighlightUtil.checkMemberValueType(value, returnType));
}
myHolder.add(AnnotationsHighlightUtil.checkValidAnnotationType(method.getReturnTypeElement()));
myHolder.add(AnnotationsHighlightUtil.checkValidAnnotationType(method.getReturnType(), method.getReturnTypeElement()));
final PsiClass aClass = method.getContainingClass();
myHolder.add(AnnotationsHighlightUtil.checkCyclicMemberType(method.getReturnTypeElement(), aClass));
myHolder.add(AnnotationsHighlightUtil.checkClashesWithSuperMethods(method));
@@ -207,7 +207,7 @@ public class ExternalAnnotationsManagerImpl extends ReadableExternalAnnotationsM
}
new WriteCommandAction(project) {
@Override
protected void run(final Result result) throws Throwable {
protected void run(@NotNull final Result result) throws Throwable {
appendChosenAnnotationsRoot(entry, newRoot);
XmlFile xmlFileInRoot = findXmlFileInRoot(findExternalAnnotationsXmlFiles(listOwner), newRoot);
if (xmlFileInRoot != null) { //file already exists under appeared content root
@@ -311,7 +311,7 @@ public class ExternalAnnotationsManagerImpl extends ReadableExternalAnnotationsM
new WriteCommandAction(project) {
@Override
protected void run(final Result result) throws Throwable {
protected void run(@NotNull final Result result) throws Throwable {
if (existingXml != null) {
annotateExternally(listOwner, annotationFQName, existingXml, fromFile, value);
}
@@ -42,22 +42,30 @@ import static com.intellij.patterns.PsiJavaPatterns.psiElement;
*/
public class JavaNoVariantsDelegator extends CompletionContributor {
@Override
public void fillCompletionVariants(@NotNull final CompletionParameters parameters, @NotNull CompletionResultSet result) {
LinkedHashSet<CompletionResult> plainResults = result.runRemainingContributors(parameters, true);
final boolean empty = containsOnlyPackages(plainResults) || suggestMetaAnnotations(parameters);
public void fillCompletionVariants(@NotNull final CompletionParameters parameters, @NotNull final CompletionResultSet result) {
final InheritorsHolder holder = new InheritorsHolder(parameters.getPosition(), result);
ResultTracker tracker = new ResultTracker(result) {
@Override
public void consume(CompletionResult plainResult) {
super.consume(plainResult);
LookupElement element = plainResult.getLookupElement();
Object o = element.getObject();
if (o instanceof PsiClass) {
holder.registerClass((PsiClass)o);
}
if (element instanceof TypeArgumentCompletionProvider.TypeArgsLookupElement) {
((TypeArgumentCompletionProvider.TypeArgsLookupElement)element).registerSingleClass(holder);
}
}
};
result.runRemainingContributors(parameters, tracker);
final boolean empty = tracker.containsOnlyPackages || suggestMetaAnnotations(parameters);
if (!empty && parameters.getInvocationCount() == 0) {
result.restartCompletionWhenNothingMatches();
}
InheritorsHolder holder = new InheritorsHolder(parameters.getPosition(), result);
for (CompletionResult plainResult : plainResults) {
Object o = plainResult.getLookupElement().getObject();
if (o instanceof PsiClass) {
holder.registerClass((PsiClass)o);
}
}
if (empty) {
delegate(parameters, JavaCompletionSorting.addJavaSorting(parameters, result), holder);
} else if (Registry.is("ide.completion.show.better.matching.classes")) {
@@ -66,14 +74,7 @@ public class JavaNoVariantsDelegator extends CompletionContributor {
JavaCompletionContributor.mayStartClassName(result) &&
JavaCompletionContributor.isClassNamePossible(parameters) &&
!JavaSmartCompletionContributor.AFTER_NEW.accepts(parameters.getPosition())) {
result = result.withPrefixMatcher(new BetterPrefixMatcher(result.getPrefixMatcher(), BetterPrefixMatcher.getBestMatchingDegree(plainResults)));
for (CompletionResult plainResult : plainResults) {
LookupElement element = plainResult.getLookupElement();
if (element instanceof TypeArgumentCompletionProvider.TypeArgsLookupElement) {
((TypeArgumentCompletionProvider.TypeArgsLookupElement)element).registerSingleClass(holder);
}
}
suggestNonImportedClasses(parameters, JavaCompletionSorting.addJavaSorting(parameters, result), holder);
suggestNonImportedClasses(parameters, JavaCompletionSorting.addJavaSorting(parameters, result.withPrefixMatcher(tracker.betterMatcher)), holder);
}
}
}
@@ -84,15 +85,6 @@ public class JavaNoVariantsDelegator extends CompletionContributor {
psiElement().withSuperParent(4, psiClass().isAnnotationType()).accepts(position);
}
public static boolean containsOnlyPackages(LinkedHashSet<CompletionResult> results) {
for (CompletionResult result : results) {
if (!(CompletionUtil.getTargetElement(result.getLookupElement()) instanceof PsiPackage)) {
return false;
}
}
return true;
}
private static void delegate(CompletionParameters parameters, final CompletionResultSet result, final InheritorsHolder inheritorsHolder) {
if (parameters.getCompletionType() == CompletionType.BASIC) {
PsiElement position = parameters.getPosition();
@@ -205,4 +197,27 @@ public class JavaNoVariantsDelegator extends CompletionContributor {
}
});
}
public static class ResultTracker implements Consumer<CompletionResult> {
private final CompletionResultSet myResult;
public boolean containsOnlyPackages = true;
public BetterPrefixMatcher betterMatcher;
public ResultTracker(CompletionResultSet result) {
myResult = result;
betterMatcher = new BetterPrefixMatcher(result);
}
@Override
public void consume(CompletionResult plainResult) {
myResult.passResult(plainResult);
LookupElement element = plainResult.getLookupElement();
if (containsOnlyPackages && !(CompletionUtil.getTargetElement(element) instanceof PsiPackage)) {
containsOnlyPackages = false;
}
betterMatcher = betterMatcher.improve(plainResult);
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2013 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -67,7 +67,7 @@ public class CreateClassFromNewFix extends CreateFromUsageBaseFix {
}, getText(), getText());
new WriteCommandAction(newExpression.getProject(), getText(), getText()) {
@Override
protected void run(Result result) throws Throwable {
protected void run(@NotNull Result result) throws Throwable {
setupClassFromNewExpression(psiClass[0], newExpression);
}
}.execute();
@@ -112,7 +112,7 @@ public class CreateClassFromNewFix extends CreateFromUsageBaseFix {
public void run() {
new WriteCommandAction(project, getText(), getText()) {
@Override
protected void run(Result result) throws Throwable {
protected void run(@NotNull Result result) throws Throwable {
try {
editor.getDocument().deleteString(textRange.getStartOffset(), textRange.getEndOffset());
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -123,7 +123,7 @@ public class CreateParameterFromUsageFix extends CreateVarFromUsageFix {
JavaPsiFacade.getElementFactory(project).createExpressionFromText(newParamName, finalMethod);
new WriteCommandAction(project) {
@Override
protected void run(Result result) throws Throwable {
protected void run(@NotNull Result result) throws Throwable {
final PsiReferenceExpression[] refs =
CreateFromUsageUtils.collectExpressions(myReferenceExpression, PsiMember.class, PsiFile.class);
for (PsiReferenceExpression ref : refs) {
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -61,7 +61,7 @@ public class GenerifyFileFix implements IntentionAction, LocalQuickFix {
myFileName = file.getName();
new WriteCommandAction(project) {
@Override
protected void run(Result result) throws Throwable {
protected void run(@NotNull Result result) throws Throwable {
invoke(project, FileEditorManager.getInstance(project).getSelectedTextEditor(), file);
}
}.execute();
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2013 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -87,7 +87,7 @@ public class ImplementAbstractClassMethodsFix extends ImplementMethodsFix {
new WriteCommandAction(project, file) {
@Override
protected void run(final Result result) throws Throwable {
protected void run(@NotNull final Result result) throws Throwable {
PsiNewExpression newExpression =
(PsiNewExpression)JavaPsiFacade.getElementFactory(project).createExpressionFromText(startElement.getText() + "{}", startElement);
newExpression = (PsiNewExpression)startElement.replace(newExpression);
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 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,13 +28,17 @@ import com.intellij.openapi.application.Result;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiEnumConstant;
import com.intellij.psi.PsiFile;
import com.intellij.psi.infos.CandidateInfo;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.Collection;
import java.util.List;
public class ImplementMethodsFix extends LocalQuickFixAndIntentionActionOnPsiElement {
public ImplementMethodsFix(PsiElement aClass) {
@@ -82,7 +86,7 @@ public class ImplementMethodsFix extends LocalQuickFixAndIntentionActionOnPsiEle
new WriteCommandAction(project, file) {
@Override
protected void run(final Result result) throws Throwable {
protected void run(@NotNull final Result result) throws Throwable {
final PsiClass psiClass = ((PsiEnumConstant)myPsiElement).getOrCreateInitializingClass();
OverrideImplementUtil.overrideOrImplementMethodsInRightPlace(editor, psiClass, selectedElements, chooser.isCopyJavadoc(),
chooser.isInsertOverrideAnnotation());
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -60,7 +60,8 @@ import java.util.Collections;
import java.util.List;
import java.util.Set;
import static com.intellij.codeInsight.daemon.impl.quickfix.MissingDependencyFixUtil.*;
import static com.intellij.codeInsight.daemon.impl.quickfix.MissingDependencyFixUtil.findFixes;
import static com.intellij.codeInsight.daemon.impl.quickfix.MissingDependencyFixUtil.provideFix;
/**
* @author cdr
@@ -145,7 +146,7 @@ public abstract class OrderEntryFix implements IntentionAction, LocalQuickFix {
if (libraryPath != null) {
new WriteCommandAction(project) {
@Override
protected void run(final Result result) throws Throwable {
protected void run(@NotNull final Result result) throws Throwable {
addJarsToRootsAndImportClass(Collections.singletonList(libraryPath), null, currentModule, editor, reference,
"org.jetbrains.annotations." + referenceName);
}
@@ -363,7 +364,7 @@ public abstract class OrderEntryFix implements IntentionAction, LocalQuickFix {
if (libraryPath != null) {
new WriteCommandAction(module.getProject()) {
@Override
protected void run(final Result result) throws Throwable {
protected void run(@NotNull final Result result) throws Throwable {
addJarToRoots(libraryPath, module, null);
}
}.execute();
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -131,7 +131,7 @@ public class CreateClassOrPackageFix extends LocalQuickFixAndIntentionActionOnPs
if (isAvailable(project, null, file)) {
new WriteCommandAction(project) {
@Override
protected void run(Result result) throws Throwable {
protected void run(@NotNull Result result) throws Throwable {
final PsiDirectory directory = chooseDirectory(project, file);
if (directory == null) return;
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -103,7 +103,7 @@ public class CreateFieldOrPropertyFix implements IntentionAction, LocalQuickFix
if (editor != null) {
new WriteCommandAction(project, file) {
@Override
protected void run(Result result) throws Throwable {
protected void run(@NotNull Result result) throws Throwable {
generateMembers(project, editor, file);
}
@@ -83,7 +83,6 @@ public class MethodCallFixer implements Fixer {
endOffset = CharArrayUtil.shiftBackward(editor.getDocument().getCharsSequence(), endOffset - 1, " \t\n") + 1;
editor.getDocument().insertString(endOffset, ")");
editor.getCaretModel().moveToOffset(endOffset + 1);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2013 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -205,7 +205,7 @@ public abstract class GenerateMembersHandlerBase implements CodeInsightActionHan
public void run() {
new WriteCommandAction(myProject) {
@Override
protected void run(Result result) throws Throwable {
protected void run(@NotNull Result result) throws Throwable {
runTemplates(myProject, editor, templates, index + 1);
}
}.execute();
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -15,7 +15,10 @@
*/
package com.intellij.codeInsight.generation;
import com.intellij.codeInsight.*;
import com.intellij.codeInsight.AnnotationUtil;
import com.intellij.codeInsight.CodeInsightActionHandler;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.MethodImplementor;
import com.intellij.codeInsight.intention.AddAnnotationFix;
import com.intellij.codeInsight.intention.AddAnnotationPsiFix;
import com.intellij.featureStatistics.FeatureUsageTracker;
@@ -457,7 +460,7 @@ public class OverrideImplementUtil extends OverrideImplementExploreUtil {
LOG.assertTrue(aClass.isValid());
new WriteCommandAction(project, aClass.getContainingFile()) {
@Override
protected void run(final Result result) throws Throwable {
protected void run(@NotNull final Result result) throws Throwable {
overrideOrImplementMethodsInRightPlace(editor, aClass, selectedElements, chooser.isCopyJavadoc(), chooser.isInsertOverrideAnnotation());
}
}.execute();
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -145,7 +145,7 @@ public class CreateSubclassAction extends BaseIntentionAction {
public static void createInnerClass(final PsiClass aClass) {
new WriteCommandAction(aClass.getProject(), getTitle(aClass), getTitle(aClass)) {
@Override
protected void run(Result result) throws Throwable {
protected void run(@NotNull Result result) throws Throwable {
final PsiClass containingClass = aClass.getContainingClass();
LOG.assertTrue(containingClass != null);
@@ -197,7 +197,7 @@ public class CreateSubclassAction extends BaseIntentionAction {
final PsiClass[] targetClass = new PsiClass[1];
new WriteCommandAction(project, getTitle(psiClass), getTitle(psiClass)) {
@Override
protected void run(Result result) throws Throwable {
protected void run(@NotNull Result result) throws Throwable {
IdeDocumentHistory.getInstance(project).includeCurrentPlaceAsChangePlace();
final PsiTypeParameterList oldTypeParameterList = psiClass.getTypeParameterList();
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -164,7 +164,7 @@ public class DeannotateIntentionAction implements IntentionAction {
final PsiModifierListOwner listOwner) {
new WriteCommandAction(project, getText()) {
@Override
protected void run(final Result result) throws Throwable {
protected void run(@NotNull final Result result) throws Throwable {
final VirtualFile virtualFile = file.getVirtualFile();
String qualifiedName = annotation.getQualifiedName();
LOG.assertTrue(qualifiedName != null);
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -87,7 +87,7 @@ public class ExpandStaticImportAction extends PsiElementBaseIntentionAction {
public PopupStep onChosen(final String selectedValue, boolean finalChoice) {
new WriteCommandAction(project, ExpandStaticImportAction.this.getText()) {
@Override
protected void run(Result result) throws Throwable {
protected void run(@NotNull Result result) throws Throwable {
if (selectedValue == REPLACE_THIS_OCCURRENCE) {
expand(refExpr, staticImport);
}
@@ -43,7 +43,7 @@ import java.util.*;
public class ReplaceImplementsWithStaticImportAction extends BaseIntentionAction {
private static final Logger LOG = Logger.getInstance(ReplaceImplementsWithStaticImportAction.class);
@NonNls private static final String FIND_CONSTANT_FIELD_USAGES = "Find constant field usages...";
@NonNls private static final String FIND_CONSTANT_FIELD_USAGES = "Find Constant Field Usages...";
@Override
@NotNull
@@ -106,10 +106,9 @@ public class ReplaceImplementsWithStaticImportAction extends BaseIntentionAction
@Override
public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file) throws IncorrectOperationException {
if (!FileModificationService.getInstance().preparePsiElementForWrite(file)) return;
final int offset = editor.getCaretModel().getOffset();
final PsiReference psiReference = file.findReferenceAt(offset);
final PsiClass targetClass;
final PsiReference psiReference = TargetElementUtil.findReference(editor);
if (psiReference != null) {
final PsiElement element = psiReference.getElement();
@@ -118,155 +117,131 @@ public class ReplaceImplementsWithStaticImportAction extends BaseIntentionAction
final PsiElement target = psiReference.resolve();
LOG.assertTrue(target instanceof PsiClass);
final PsiClass targetClass = (PsiClass)target;
new WriteCommandAction(project, getText()) {
@Override
protected void run(@NotNull Result result) throws Throwable {
for (PsiField constField : targetClass.getAllFields()) {
final String fieldName = constField.getName();
final PsiClass containingClass = constField.getContainingClass();
for (PsiReference ref : ReferencesSearch.search(constField)) {
final PsiElement psiElement = ref.getElement();
if (ref instanceof PsiReferenceExpression) {
final PsiElement qualifier = ((PsiReferenceExpression)ref).getQualifier();
if (qualifier != null) {
if (qualifier instanceof PsiReferenceExpression) {
final PsiElement resolved = ((PsiReferenceExpression)qualifier).resolve();
if (resolved instanceof PsiClass && !InheritanceUtil.isInheritorOrSelf(psiClass, (PsiClass)resolved, true)) {
continue;
}
}
qualifier.putCopyableUserData(ChangeContextUtil.CAN_REMOVE_QUALIFIER_KEY,
ChangeContextUtil.canRemoveQualifier((PsiReferenceExpression)ref));
}
}
bindReference(psiElement.getContainingFile(), constField, containingClass, fieldName, ref, project);
}
}
element.delete();
JavaCodeStyleManager.getInstance(project).optimizeImports(file);
}
}.execute();
targetClass = (PsiClass)target;
}
else {
final PsiElement identifier = file.findElementAt(offset);
LOG.assertTrue(identifier instanceof PsiIdentifier);
final PsiElement element = identifier.getParent();
LOG.assertTrue(element instanceof PsiClass);
final PsiClass targetClass = (PsiClass)element;
final Map<PsiFile, Map<PsiField, Set<PsiReference>>> refs = new HashMap<PsiFile, Map<PsiField, Set<PsiReference>>>();
if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().runReadAction(new Runnable() {
@Override
public void run() {
for (PsiField field : targetClass.getAllFields()) {
final PsiClass containingClass = field.getContainingClass();
for (PsiReference reference : ReferencesSearch.search(field)) {
if (reference == null) {
continue;
}
final PsiElement refElement = reference.getElement();
if (encodeQualifier(containingClass, reference, targetClass)) continue;
final PsiFile psiFile = refElement.getContainingFile();
if (psiFile instanceof PsiJavaFile) {
Map<PsiField, Set<PsiReference>> references = refs.get(psiFile);
if (references == null) {
references = new HashMap<PsiField, Set<PsiReference>>();
refs.put(psiFile, references);
}
Set<PsiReference> fieldsRefs = references.get(field);
if (fieldsRefs == null) {
fieldsRefs = new HashSet<PsiReference>();
references.put(field, fieldsRefs);
}
fieldsRefs.add(reference);
}
}
}
}
});
}
}, FIND_CONSTANT_FIELD_USAGES, true, project)) {
return;
}
final Set<PsiJavaCodeReferenceElement> refs2Unimplement = new HashSet<PsiJavaCodeReferenceElement>();
if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().runReadAction(new Runnable() {
@Override
public void run() {
for (PsiClass psiClass : DirectClassInheritorsSearch.search(targetClass)) {
PsiFile containingFile = psiClass.getContainingFile();
if (!refs.containsKey(containingFile)) {
refs.put(containingFile, new HashMap<PsiField, Set<PsiReference>>());
}
if (collectExtendsImplements(targetClass, psiClass.getExtendsList(), refs2Unimplement)) continue;
collectExtendsImplements(targetClass, psiClass.getImplementsList(), refs2Unimplement);
}
}
});
}
}, "Find references in implement/extends lists...", true, project)) {
return;
}
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
for (PsiFile psiFile : refs.keySet()) {
final Map<PsiField, Set<PsiReference>> map = refs.get(psiFile);
for (PsiField psiField : map.keySet()) {
final PsiClass containingClass = psiField.getContainingClass();
final String fieldName = psiField.getName();
for (PsiReference reference : map.get(psiField)) {
bindReference(psiFile, psiField, containingClass, fieldName, reference, project);
}
}
}
for (PsiJavaCodeReferenceElement referenceElement : refs2Unimplement) {
referenceElement.delete();
}
}
});
final Set<SmartPsiElementPointer<PsiImportStatementBase>> redundant = new HashSet<SmartPsiElementPointer<PsiImportStatementBase>>();
final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project);
final SmartPointerManager pointerManager = SmartPointerManager.getInstance(project);
if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable(){
@Override
public void run() {
ApplicationManager.getApplication().runReadAction(new Runnable() {
@Override
public void run() {
for (PsiFile psiFile : refs.keySet()) {
final Collection<PsiImportStatementBase> red = codeStyleManager.findRedundantImports((PsiJavaFile)psiFile);
if (red != null) {
for (PsiImportStatementBase statementBase : red) {
redundant.add(pointerManager.createSmartPsiElementPointer(statementBase));
}
}
}
}
});
}
}, "Collect redundant imports...", true, project)) return;
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
for (SmartPsiElementPointer<PsiImportStatementBase> pointer : redundant) {
final PsiImportStatementBase statementBase = pointer.getElement();
if (statementBase != null) statementBase.delete();
}
}
});
targetClass = (PsiClass)element;
}
final Map<PsiFile, Map<PsiField, Set<PsiReference>>> refs = new HashMap<PsiFile, Map<PsiField, Set<PsiReference>>>();
if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().runReadAction(new Runnable() {
@Override
public void run() {
for (PsiField field : targetClass.getAllFields()) {
final PsiClass containingClass = field.getContainingClass();
for (PsiReference reference : ReferencesSearch.search(field)) {
if (reference == null) {
continue;
}
final PsiElement refElement = reference.getElement();
if (encodeQualifier(containingClass, reference, targetClass)) continue;
final PsiFile psiFile = refElement.getContainingFile();
if (psiFile instanceof PsiJavaFile) {
Map<PsiField, Set<PsiReference>> references = refs.get(psiFile);
if (references == null) {
references = new HashMap<PsiField, Set<PsiReference>>();
refs.put(psiFile, references);
}
Set<PsiReference> fieldsRefs = references.get(field);
if (fieldsRefs == null) {
fieldsRefs = new HashSet<PsiReference>();
references.put(field, fieldsRefs);
}
fieldsRefs.add(reference);
}
}
}
}
});
}
}, FIND_CONSTANT_FIELD_USAGES, true, project)) {
return;
}
final Set<PsiJavaCodeReferenceElement> refs2Unimplement = new HashSet<PsiJavaCodeReferenceElement>();
if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().runReadAction(new Runnable() {
@Override
public void run() {
for (PsiClass psiClass : DirectClassInheritorsSearch.search(targetClass)) {
PsiFile containingFile = psiClass.getContainingFile();
if (!refs.containsKey(containingFile)) {
refs.put(containingFile, new HashMap<PsiField, Set<PsiReference>>());
}
if (collectExtendsImplements(targetClass, psiClass.getExtendsList(), refs2Unimplement)) continue;
collectExtendsImplements(targetClass, psiClass.getImplementsList(), refs2Unimplement);
}
}
});
}
}, "Find References in Implement/Extends Lists...", true, project)) {
return;
}
if (!FileModificationService.getInstance().preparePsiElementsForWrite(refs.keySet())) return;
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
for (PsiFile psiFile : refs.keySet()) {
final Map<PsiField, Set<PsiReference>> map = refs.get(psiFile);
for (PsiField psiField : map.keySet()) {
final PsiClass containingClass = psiField.getContainingClass();
final String fieldName = psiField.getName();
for (PsiReference reference : map.get(psiField)) {
bindReference(psiFile, psiField, containingClass, fieldName, reference, project);
}
}
}
for (PsiJavaCodeReferenceElement referenceElement : refs2Unimplement) {
referenceElement.delete();
}
}
});
final Map<PsiJavaFile, PsiImportList> redundant = new HashMap<PsiJavaFile, PsiImportList>();
final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project);
if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable(){
@Override
public void run() {
ApplicationManager.getApplication().runReadAction(new Runnable() {
@Override
public void run() {
for (PsiFile psiFile : refs.keySet()) {
if (psiFile instanceof PsiJavaFile) {
final PsiImportList prepared = codeStyleManager.prepareOptimizeImportsResult((PsiJavaFile)psiFile);
if (prepared != null) {
redundant.put((PsiJavaFile)psiFile, prepared);
}
}
}
}
});
}
}, "Optimize Imports...", true, project)) return;
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
for (PsiJavaFile file : redundant.keySet()) {
final PsiImportList importList = redundant.get(file);
if (importList != null) {
final PsiImportList list = file.getImportList();
if (list != null) {
list.replace(importList);
}
}
}
}
});
}
private static boolean encodeQualifier(PsiClass containingClass, PsiReference reference, PsiClass targetClass) {
@@ -28,6 +28,7 @@ import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.InheritanceUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiTypesUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.MultiMap;
@@ -57,6 +58,9 @@ public class GuavaFluentIterableInspection extends BaseJavaBatchLocalInspectionT
@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
if (!PsiUtil.isLanguageLevel8OrHigher(holder.getFile())) {
return PsiElementVisitor.EMPTY_VISITOR;
}
final PsiClass fluentIterable = JavaPsiFacade.getInstance(holder.getProject())
.findClass(GUAVA_FLUENT_ITERABLE, GlobalSearchScope.allScope(holder.getProject()));
if (fluentIterable == null) {
@@ -22,6 +22,7 @@ import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.impl.PsiDiamondTypeUtil;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.*;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
@@ -103,14 +104,47 @@ class PseudoLambdaReplaceTemplate {
});
final PsiType returnType = method.getReturnType();
if (returnType instanceof PsiClassType) {
final PsiClass resolvedReturnTypeClass = ((PsiClassType)returnType).resolve();
if (!InheritanceUtil.isInheritor(resolvedReturnTypeClass, CommonClassNames.JAVA_LANG_ITERABLE)) {
if (StreamApiConstants.FAKE_FIND_MATCHED.equals(myStreamApiMethodName)) {
if (!PsiType.BOOLEAN.equals(returnType)) {
return null;
}
} else if (!(returnType instanceof PsiArrayType)) {
return null;
} else {
final PsiClass stream =
JavaPsiFacade.getInstance(method.getProject()).findClass(StreamApiConstants.JAVA_UTIL_STREAM_STREAM, method.getResolveScope());
if (stream == null) {
return null;
}
final PsiMethod[] methods = stream.findMethodsByName(myStreamApiMethodName, false);
LOG.assertTrue(methods.length != 0);
PsiMethod representative = methods[0];
final PsiType expectedReturnType = representative.getReturnType();
if (expectedReturnType instanceof PsiClassType) {
final PsiClass resolvedClass = ((PsiClassType)expectedReturnType).resolve();
if (resolvedClass == null) {
return null;
} else {
if (StreamApiConstants.JAVA_UTIL_STREAM_STREAM.equals(resolvedClass.getQualifiedName())) {
if (!(returnType instanceof PsiArrayType)) {
if (!(returnType instanceof PsiClassType)) {
return null;
}
final PsiClass methodReturnType = ((PsiClassType)returnType).resolve();
if (methodReturnType == null ||
(!InheritanceUtil.isInheritor(methodReturnType, CommonClassNames.JAVA_LANG_ITERABLE) &&
!InheritanceUtil.isInheritor(methodReturnType, CommonClassNames.JAVA_LANG_ITERABLE))) {
return null;
}
}
}
}
}
else if (PsiType.BOOLEAN.equals(expectedReturnType)) {
if (!PsiType.BOOLEAN.equals(returnType)) {
return null;
}
}
}
return validate(parameterTypes, returnType, null, method);
}
@@ -22,6 +22,7 @@ import com.intellij.openapi.util.Condition;
import com.intellij.ui.*;
import com.intellij.ui.components.JBList;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.EditableModel;
import com.intellij.util.ui.UIUtil;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
@@ -119,9 +120,7 @@ public class StaticPseudoFunctionalStyleMethodOptions {
}
public JComponent createPanel() {
final JBList list = new JBList();
list.setModel(new SettingsListModel());
final JBList list = new JBList(myElements);
list.setCellRenderer(new ColoredListCellRenderer<PipelineElement>() {
@Override
protected void customizeCellRenderer(JList list, PipelineElement element, int index, boolean selected, boolean hasFocus) {
@@ -152,26 +151,19 @@ public class StaticPseudoFunctionalStyleMethodOptions {
return;
}
myElements.add(newElement);
UIUtil.invokeLaterIfNeeded(new Runnable() {
@Override
public void run() {
list.revalidate();
list.updateUI();
}
});
((DefaultListModel)list.getModel()).addElement(newElement);
}
}
}).setRemoveAction(new AnActionButtonRunnable() {
@Override
public void run(AnActionButton button) {
myElements.remove(list.getSelectedIndex());
UIUtil.invokeLaterIfNeeded(new Runnable() {
@Override
public void run() {
list.revalidate();
list.updateUI();
}
});
final int[] indices = list.getSelectedIndices();
final List<PipelineElement> toRemove = new ArrayList<PipelineElement>(indices.length);
for (int idx : indices) {
toRemove.add(myElements.get(idx));
}
myElements.removeAll(toRemove);
ListUtil.removeSelectedItems(list);
}
}).createPanel();
}
@@ -223,26 +215,4 @@ public class StaticPseudoFunctionalStyleMethodOptions {
return result;
}
}
private class SettingsListModel implements ListModel {
@Override
public int getSize() {
return myElements.size();
}
@Override
public PipelineElement getElementAt(int index) {
return myElements.get(index);
}
@Override
public void addListDataListener(ListDataListener l) {
}
@Override
public void removeListDataListener(ListDataListener l) {
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2013 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -142,7 +142,7 @@ public class JavaDocReferenceInspection extends JavaDocReferenceInspectionBase {
if (index < 0) return;
new WriteCommandAction(project, element.getContainingFile()){
@Override
protected void run(final Result result) throws Throwable {
protected void run(@NotNull final Result result) throws Throwable {
final PsiClass psiClass = originalClasses.get(index);
if (psiClass.isValid()) {
PsiDocumentManager.getInstance(project).commitAllDocuments();
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -215,7 +215,7 @@ public class GenerateVisitorByHierarchyAction extends AnAction {
}
final int finalDetectedPrefix = detectClassPrefix(classes.keySet()).length();
new WriteCommandAction(project, PsiUtilCore.toPsiFileArray(psiFiles)) {
protected void run(final Result result) throws Throwable {
protected void run(@NotNull final Result result) throws Throwable {
if (visitorClass == null) {
final String shortClassName = PsiNameHelper.getShortClassName(visitorName);
if (directory != null) {
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2013 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -206,7 +206,7 @@ public class UsedIconsListingAction extends AnAction {
if (useScope.contains(file.getVirtualFile())) {
new WriteCommandAction<Void>(project, file) {
@Override
protected void run(Result<Void> result) throws Throwable {
protected void run(@NotNull Result<Void> result) throws Throwable {
att.setValue(replacement);
}
}.execute();
@@ -226,7 +226,7 @@ public class UsedIconsListingAction extends AnAction {
if (useScope.contains(file.getVirtualFile())) {
new WriteCommandAction(project, file) {
@Override
protected void run(Result result) throws Throwable {
protected void run(@NotNull Result result) throws Throwable {
if (call instanceof PsiLiteralExpression) {
call.replace(factory.createExpressionFromText("\"" + replacement + "\"", call));
}
@@ -255,7 +255,7 @@ public class UsedIconsListingAction extends AnAction {
if (useScope.contains(file.getVirtualFile())) {
new WriteCommandAction(project, file) {
@Override
protected void run(Result result) throws Throwable {
protected void run(@NotNull Result result) throws Throwable {
annotation.getNode();
annotation.setDeclaredAttributeValue(
"icon",
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -187,7 +187,7 @@ public class JavaChangeSignatureDetector implements LanguageChangeSignatureDetec
final int parameterIndex = method.getParameterList().getParameterIndex(parameter);
new WriteCommandAction(element.getProject(), MOVE_PARAMETER){
@Override
protected void run(Result result) throws Throwable {
protected void run(@NotNull Result result) throws Throwable {
final PsiParameterList parameterList = method.getParameterList();
final PsiParameter[] parameters = parameterList.getParameters();
final int deltaOffset = editor.getCaretModel().getOffset() - parameter.getTextRange().getStartOffset();
@@ -380,6 +380,7 @@ public class ExtractMethodSignatureSuggester {
myDuplicatesNumber = duplicatesNumber;
setTitle("Extract Parameters to Replace Duplicates");
setOKButtonText("Accept Signature Change");
setCancelButtonText("Keep Original Signature");
init();
}
@@ -139,7 +139,7 @@ public class ExtractClassProcessor extends FixableUsagesRefactoringProcessor {
}
myClass = new WriteCommandAction<PsiClass>(myProject, getCommandName()){
@Override
protected void run(Result<PsiClass> result) throws Throwable {
protected void run(@NotNull Result<PsiClass> result) throws Throwable {
result.setResult(buildClass());
}
}.execute().getResultObject();
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -41,6 +41,7 @@ import com.intellij.refactoring.util.CommonRefactoringUtil;
import com.intellij.refactoring.util.InlineUtil;
import com.intellij.refactoring.util.RefactoringMessageDialog;
import com.intellij.util.Processor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
@@ -135,7 +136,7 @@ public class InlineParameterHandler extends JavaInlineActionHandler {
if (InlineLocalHandler.checkRefsInAugmentedAssignmentOrUnaryModified(refs, def) == null) {
new WriteCommandAction(project) {
@Override
protected void run(Result result) throws Throwable {
protected void run(@NotNull Result result) throws Throwable {
for (final PsiElement ref : refs) {
InlineUtil.inlineVariable(psiParameter, rExpr, (PsiJavaCodeReferenceElement)ref);
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
* Copyright 2000-2015 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.psi.PsiJavaCodeReferenceElement;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.refactoring.listeners.RefactoringEventData;
import com.intellij.refactoring.listeners.RefactoringEventListener;
import org.jetbrains.annotations.NotNull;
import java.util.List;
@@ -59,7 +60,7 @@ public class InlineStaticImportHandler extends JavaInlineActionHandler {
new WriteCommandAction(project, REFACTORING_NAME){
@Override
protected void run(Result result) throws Throwable {
protected void run(@NotNull Result result) throws Throwable {
replaceAllAndDeleteImport(referenceElements, null, staticStatement);
}
}.execute();
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -53,6 +53,7 @@ import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.impl.source.codeStyle.CodeEditUtil;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.PsiElementProcessor;
import com.intellij.psi.util.FileTypeUtils;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.psi.util.PsiUtilCore;
@@ -61,11 +62,13 @@ import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.introduce.inplace.AbstractInplaceIntroducer;
import com.intellij.refactoring.introduceVariable.IntroduceVariableBase;
import com.intellij.refactoring.rename.RenameJavaVariableProcessor;
import com.intellij.refactoring.util.*;
import com.intellij.refactoring.util.CommonRefactoringUtil;
import com.intellij.refactoring.util.EnumConstantsUtil;
import com.intellij.refactoring.util.RefactoringChangeUtil;
import com.intellij.refactoring.util.RefactoringUtil;
import com.intellij.refactoring.util.occurrences.OccurrenceManager;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.VisibilityUtil;
import com.intellij.psi.util.FileTypeUtils;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -209,7 +212,7 @@ public abstract class BaseExpressionToFieldHandler extends IntroduceHandlerBase
new WriteCommandAction(project, getRefactoringName()){
@Override
protected void run(Result result) throws Throwable {
protected void run(@NotNull Result result) throws Throwable {
runnable.run();
}
}.execute();
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -248,7 +248,7 @@ public class InplaceIntroduceConstantPopup extends AbstractInplaceIntroduceField
myParentClass, false, false);
new WriteCommandAction(myProject, getCommandName(), getCommandName()) {
@Override
protected void run(Result result) throws Throwable {
protected void run(@NotNull Result result) throws Throwable {
if (getLocalVariable() != null) {
final LocalToFieldHandler.IntroduceFieldRunnable fieldRunnable =
new LocalToFieldHandler.IntroduceFieldRunnable(false, (PsiLocalVariable)getLocalVariable(), myParentClass, settings, true,
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -223,7 +223,7 @@ public class InplaceIntroduceFieldPopup extends AbstractInplaceIntroduceFieldPop
myParentClass, false, false);
new WriteCommandAction(myProject, getCommandName(), getCommandName()){
@Override
protected void run(Result result) throws Throwable {
protected void run(@NotNull Result result) throws Throwable {
if (getLocalVariable() != null) {
final LocalToFieldHandler.IntroduceFieldRunnable fieldRunnable =
new LocalToFieldHandler.IntroduceFieldRunnable(false, (PsiLocalVariable)getLocalVariable(), myParentClass, settings, myStatic, myOccurrences);
@@ -246,7 +246,7 @@ public class JavaVariableInplaceIntroducer extends AbstractJavaInplaceIntroducer
public void actionPerformed(ActionEvent e) {
new WriteCommandAction(myProject, getCommandName(), getCommandName()) {
@Override
protected void run(Result result) throws Throwable {
protected void run(@NotNull Result result) throws Throwable {
PsiDocumentManager.getInstance(myProject).commitDocument(myEditor.getDocument());
final PsiVariable variable = getVariable();
if (variable != null) {
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -18,8 +18,6 @@ package com.intellij.refactoring.introduceVariable;
import com.google.common.annotations.VisibleForTesting;
import com.intellij.codeInsight.template.impl.TemplateManagerImpl;
import com.intellij.codeInsight.template.impl.TemplateState;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.ui.ListCellRendererWrapper;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Editor;
@@ -30,11 +28,13 @@ import com.intellij.openapi.util.Key;
import com.intellij.psi.*;
import com.intellij.psi.scope.processor.VariablesProcessor;
import com.intellij.psi.scope.util.PsiScopesUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.refactoring.rename.inplace.InplaceRefactoring;
import com.intellij.ui.ListCellRendererWrapper;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.components.JBList;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
@@ -138,7 +138,7 @@ public class ReassignVariableUtil {
final PsiExpression initializer = var.getInitializer();
new WriteCommandAction(declaration.getProject()) {
@Override
protected void run(Result result) throws Throwable {
protected void run(@NotNull Result result) throws Throwable {
final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(variable.getProject());
final String chosenVariableName = variable.getName();
//would generate red code for final variables
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -89,7 +89,7 @@ public class JavaMoveFilesOrDirectoriesHandler extends MoveFilesOrDirectoriesHan
public PsiElement[] fun(final PsiElement[] elements) {
return new WriteCommandAction<PsiElement[]>(project, "Regrouping ...") {
@Override
protected void run(Result<PsiElement[]> result) throws Throwable {
protected void run(@NotNull Result<PsiElement[]> result) throws Throwable {
final List<PsiElement> adjustedElements = new ArrayList<PsiElement>();
for (int i = 0, length = elements.length; i < length; i++) {
PsiElement element = elements[i];
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -19,13 +19,14 @@ package com.intellij.refactoring.rename;
import com.intellij.codeInsight.daemon.impl.quickfix.RenameWrongRefFix;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiReference;
import com.intellij.psi.PsiReferenceExpression;
import org.jetbrains.annotations.NotNull;
public class RenameWrongRefHandler implements RenameHandler {
@@ -53,7 +54,7 @@ public class RenameWrongRefHandler implements RenameHandler {
if (reference instanceof PsiReferenceExpression) {
new WriteCommandAction(project){
@Override
protected void run(Result result) throws Throwable {
protected void run(@NotNull Result result) throws Throwable {
new RenameWrongRefFix((PsiReferenceExpression)reference).invoke(project, editor, file);
}
}.execute();
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2013 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -137,7 +137,7 @@ public class DuplicatesImpl {
new WriteCommandAction(project, MethodDuplicatesHandler.REFACTORING_NAME, MethodDuplicatesHandler.REFACTORING_NAME) {
@Override
protected void run(Result result) throws Throwable {
protected void run(@NotNull Result result) throws Throwable {
try {
provider.processMatch(match);
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -345,13 +345,14 @@ public class CreateTestDialog extends DialogWrapper {
}
}
});
final boolean hasTestRoots = !ModuleRootManager.getInstance(myTargetModule).getSourceRoots(JavaModuleSourceRootTypes.TESTS).isEmpty();
final List<TestFramework> attachedLibraries = new ArrayList<TestFramework>();
final String defaultLibrary = getDefaultLibraryName();
TestFramework defaultDescriptor = null;
final DefaultComboBoxModel model = (DefaultComboBoxModel)myLibrariesCombo.getModel();
for (final TestFramework descriptor : Extensions.getExtensions(TestFramework.EXTENSION_NAME)) {
model.addElement(descriptor);
if (descriptor.isLibraryAttached(myTargetModule)) {
if (hasTestRoots && descriptor.isLibraryAttached(myTargetModule)) {
attachedLibraries.add(descriptor);
}
@@ -480,7 +481,7 @@ public class CreateTestDialog extends DialogWrapper {
final PackageWrapper targetPackage = new PackageWrapper(PsiManager.getInstance(myProject), packageName);
final VirtualFile selectedRoot = new ReadAction<VirtualFile>() {
protected void run(Result<VirtualFile> result) throws Throwable {
protected void run(@NotNull Result<VirtualFile> result) throws Throwable {
final HashSet<VirtualFile> testFolders = new HashSet<VirtualFile>();
CreateTestAction.checkForTestRoots(myTargetModule, testFolders);
List<VirtualFile> roots;
@@ -504,7 +505,7 @@ public class CreateTestDialog extends DialogWrapper {
if (selectedRoot == null) return null;
return new WriteCommandAction<PsiDirectory>(myProject, CodeInsightBundle.message("create.directory.command")) {
protected void run(Result<PsiDirectory> result) throws Throwable {
protected void run(@NotNull Result<PsiDirectory> result) throws Throwable {
result.setResult(RefactoringUtil.createPackageDirectoryInSourceRoot(targetPackage, selectedRoot));
}
}.execute().getResultObject();
@@ -16,84 +16,24 @@
package com.intellij.psi.search.searches;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressIndicatorProvider;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.*;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.PsiSearchScopeUtil;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Conditions;
import com.intellij.psi.PsiClass;
import com.intellij.psi.search.SearchScope;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.reference.SoftReference;
import com.intellij.util.Processor;
import com.intellij.util.Query;
import com.intellij.util.QueryExecutor;
import com.intellij.util.containers.Stack;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.ref.Reference;
import java.util.Set;
/**
* @author max
*/
public class ClassInheritorsSearch extends ExtensibleQueryFactory<PsiClass, ClassInheritorsSearch.SearchParameters> {
public static final ExtensionPointName<QueryExecutor> EP_NAME = ExtensionPointName.create("com.intellij.classInheritorsSearch");
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.search.searches.ClassInheritorsSearch");
public static final ClassInheritorsSearch INSTANCE = new ClassInheritorsSearch();
static {
INSTANCE.registerExecutor(new QueryExecutor<PsiClass, SearchParameters>() {
@Override
public boolean execute(@NotNull final SearchParameters parameters, @NotNull final Processor<PsiClass> consumer) {
final PsiClass baseClass = parameters.getClassToProcess();
final SearchScope searchScope = parameters.getScope();
LOG.assertTrue(searchScope != null);
ProgressIndicator progress = ProgressIndicatorProvider.getGlobalProgressIndicator();
if (progress != null) {
progress.pushState();
String className = ApplicationManager.getApplication().runReadAction(new Computable<String>() {
@Override
public String compute() {
return baseClass.getName();
}
});
progress.setText(className != null ?
PsiBundle.message("psi.search.inheritors.of.class.progress", className) :
PsiBundle.message("psi.search.inheritors.progress"));
}
boolean result = processInheritors(consumer, baseClass, searchScope, parameters);
if (progress != null) {
progress.popState();
}
return result;
}
});
}
public interface InheritanceChecker {
boolean checkInheritance(@NotNull PsiClass subClass, @NotNull PsiClass parentClass);
InheritanceChecker DEFAULT = new InheritanceChecker() {
@Override
public boolean checkInheritance(@NotNull PsiClass subClass, @NotNull PsiClass parentClass) {
return subClass.isInheritor(parentClass, false);
}
};
}
public static class SearchParameters {
private final PsiClass myClass;
private final SearchScope myScope;
@@ -101,7 +41,6 @@ public class ClassInheritorsSearch extends ExtensibleQueryFactory<PsiClass, Clas
private final boolean myCheckInheritance;
private final boolean myIncludeAnonymous;
private final Condition<String> myNameCondition;
private final InheritanceChecker myInheritanceChecker;
public SearchParameters(@NotNull final PsiClass aClass, @NotNull SearchScope scope, final boolean checkDeep, final boolean checkInheritance, boolean includeAnonymous) {
this(aClass, scope, checkDeep, checkInheritance, includeAnonymous, Conditions.<String>alwaysTrue());
@@ -109,18 +48,12 @@ public class ClassInheritorsSearch extends ExtensibleQueryFactory<PsiClass, Clas
public SearchParameters(@NotNull final PsiClass aClass, @NotNull SearchScope scope, final boolean checkDeep, final boolean checkInheritance,
boolean includeAnonymous, @NotNull final Condition<String> nameCondition) {
this(aClass, scope, checkDeep, checkInheritance, includeAnonymous, nameCondition, InheritanceChecker.DEFAULT);
}
public SearchParameters(@NotNull final PsiClass aClass, @NotNull SearchScope scope, final boolean checkDeep, final boolean checkInheritance,
boolean includeAnonymous, @NotNull final Condition<String> nameCondition, @NotNull InheritanceChecker inheritanceChecker) {
myClass = aClass;
myScope = scope;
myCheckDeep = checkDeep;
myCheckInheritance = checkInheritance;
myIncludeAnonymous = includeAnonymous;
myNameCondition = nameCondition;
myInheritanceChecker = inheritanceChecker;
}
@NotNull
@@ -183,127 +116,4 @@ public class ClassInheritorsSearch extends ExtensibleQueryFactory<PsiClass, Clas
return search(aClass, true);
}
private static boolean processInheritors(@NotNull final Processor<PsiClass> consumer,
@NotNull final PsiClass baseClass,
@NotNull final SearchScope searchScope,
@NotNull final SearchParameters parameters) {
if (baseClass instanceof PsiAnonymousClass || isFinal(baseClass)) return true;
final String qname = ApplicationManager.getApplication().runReadAction(new Computable<String>() {
@Override
public String compute() {
return baseClass.getQualifiedName();
}
});
if (CommonClassNames.JAVA_LANG_OBJECT.equals(qname)) {
Project project = PsiUtilCore.getProjectInReadAction(baseClass);
return AllClassesSearch.search(searchScope, project, parameters.getNameCondition()).forEach(new Processor<PsiClass>() {
@Override
public boolean process(final PsiClass aClass) {
ProgressIndicatorProvider.checkCanceled();
final String qname1 = ApplicationManager.getApplication().runReadAction(new Computable<String>() {
@Override
@Nullable
public String compute() {
return aClass.getQualifiedName();
}
});
return CommonClassNames.JAVA_LANG_OBJECT.equals(qname1) || consumer.process(aClass);
}
});
}
final Ref<PsiClass> currentBase = Ref.create(null);
final Stack<Pair<Reference<PsiClass>, String>> stack = new Stack<Pair<Reference<PsiClass>, String>>();
// there are two sets for memory optimization: it's cheaper to hold FQN than PsiClass
final Set<String> processedFqns = new THashSet<String>(); // FQN of processed classes if the class has one
final Set<PsiClass> processed = new THashSet<PsiClass>(); // processed classes without FQN (e.g. anonymous)
final Processor<PsiClass> processor = new Processor<PsiClass>() {
@Override
public boolean process(final PsiClass candidate) {
ProgressIndicatorProvider.checkCanceled();
final Ref<Boolean> result = new Ref<Boolean>();
final String[] fqn = new String[1];
ApplicationManager.getApplication().runReadAction(new Runnable() {
@Override
public void run() {
fqn[0] = candidate.getQualifiedName();
if (parameters.isCheckInheritance() || parameters.isCheckDeep() && !(candidate instanceof PsiAnonymousClass)) {
if (!parameters.myInheritanceChecker.checkInheritance(candidate, currentBase.get())) {
result.set(true);
return;
}
}
if (PsiSearchScopeUtil.isInScope(searchScope, candidate)) {
if (candidate instanceof PsiAnonymousClass) {
result.set(consumer.process(candidate));
}
else {
final String name = candidate.getName();
if (name != null && parameters.getNameCondition().value(name) && !consumer.process(candidate)) result.set(false);
}
}
}
});
if (!result.isNull()) return result.get().booleanValue();
if (parameters.isCheckDeep() && !(candidate instanceof PsiAnonymousClass) && !isFinal(candidate)) {
Reference<PsiClass> ref = fqn[0] == null ? createHardReference(candidate) : new SoftReference<PsiClass>(candidate);
stack.push(Pair.create(ref, fqn[0]));
}
return true;
}
};
stack.push(Pair.create(createHardReference(baseClass), qname));
final GlobalSearchScope projectScope = GlobalSearchScope.allScope(PsiUtilCore.getProjectInReadAction(baseClass));
final JavaPsiFacade facade = JavaPsiFacade.getInstance(projectScope.getProject());
while (!stack.isEmpty()) {
ProgressIndicatorProvider.checkCanceled();
Pair<Reference<PsiClass>, String> pair = stack.pop();
PsiClass psiClass = pair.getFirst().get();
final String fqn = pair.getSecond();
if (psiClass == null) {
psiClass = ApplicationManager.getApplication().runReadAction(new Computable<PsiClass>() {
@Override
public PsiClass compute() {
return facade.findClass(fqn, projectScope);
}
});
if (psiClass == null) continue;
}
if (fqn == null) {
if (!processed.add(psiClass)) continue;
}
else {
if (!processedFqns.add(fqn)) continue;
}
currentBase.set(psiClass);
if (!DirectClassInheritorsSearch.search(psiClass, projectScope, parameters.isIncludeAnonymous(), false).forEach(processor)) return false;
}
return true;
}
private static Reference<PsiClass> createHardReference(final PsiClass candidate) {
return new SoftReference<PsiClass>(candidate){
@Override
public PsiClass get() {
return candidate;
}
};
}
private static boolean isFinal(@NotNull final PsiClass baseClass) {
return ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() {
@Override
public Boolean compute() {
return Boolean.valueOf(baseClass.hasModifierProperty(PsiModifier.FINAL));
}
}).booleanValue();
}
}
@@ -0,0 +1,169 @@
/*
* Copyright 2000-2015 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi.impl.search;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.QueryExecutorBase;
import com.intellij.openapi.application.ReadActionProcessor;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressIndicatorProvider;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Ref;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.PsiSearchScopeUtil;
import com.intellij.psi.search.SearchScope;
import com.intellij.psi.search.searches.AllClassesSearch;
import com.intellij.psi.search.searches.ClassInheritorsSearch;
import com.intellij.psi.search.searches.DirectClassInheritorsSearch;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.util.Processor;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.Stack;
import org.jetbrains.annotations.NotNull;
import java.util.Set;
public class JavaClassInheritorsSearcher extends QueryExecutorBase<PsiClass, ClassInheritorsSearch.SearchParameters> {
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.search.JavaClassInheritorsSearcher");
@Override
public void processQuery(@NotNull ClassInheritorsSearch.SearchParameters parameters, @NotNull Processor<PsiClass> consumer) {
final PsiClass baseClass = parameters.getClassToProcess();
final SearchScope searchScope = parameters.getScope();
LOG.assertTrue(searchScope != null);
ProgressIndicator progress = ProgressIndicatorProvider.getGlobalProgressIndicator();
if (progress != null) {
progress.pushState();
String className = ApplicationManager.getApplication().runReadAction(new Computable<String>() {
@Override
public String compute() {
return baseClass.getName();
}
});
progress.setText(className != null ?
PsiBundle.message("psi.search.inheritors.of.class.progress", className) :
PsiBundle.message("psi.search.inheritors.progress"));
}
processInheritors(consumer, baseClass, searchScope, parameters);
if (progress != null) {
progress.popState();
}
}
private static void processInheritors(@NotNull final Processor<PsiClass> consumer,
@NotNull final PsiClass baseClass,
@NotNull final SearchScope searchScope,
@NotNull final ClassInheritorsSearch.SearchParameters parameters) {
if (baseClass instanceof PsiAnonymousClass || isFinal(baseClass)) return;
Project project = PsiUtilCore.getProjectInReadAction(baseClass);
if (isJavaLangObject(baseClass)) {
AllClassesSearch.search(searchScope, project, parameters.getNameCondition()).forEach(new Processor<PsiClass>() {
@Override
public boolean process(final PsiClass aClass) {
ProgressIndicatorProvider.checkCanceled();
return isJavaLangObject(aClass) || consumer.process(aClass);
}
});
return;
}
final Ref<PsiClass> currentBase = Ref.create(null);
final Stack<PsiAnchor> stack = new Stack<PsiAnchor>();
final Set<PsiAnchor> processed = ContainerUtil.newTroveSet();
final Processor<PsiClass> processor = new ReadActionProcessor<PsiClass>() {
@Override
public boolean processInReadAction(PsiClass candidate) {
ProgressIndicatorProvider.checkCanceled();
if (parameters.isCheckInheritance() || parameters.isCheckDeep() && !(candidate instanceof PsiAnonymousClass)) {
if (!candidate.isInheritor(currentBase.get(), false)) {
return true;
}
}
if (PsiSearchScopeUtil.isInScope(searchScope, candidate)) {
if (candidate instanceof PsiAnonymousClass) {
return consumer.process(candidate);
}
final String name = candidate.getName();
if (name != null && parameters.getNameCondition().value(name) && !consumer.process(candidate)) {
return false;
}
}
if (parameters.isCheckDeep() && !(candidate instanceof PsiAnonymousClass) && !isFinal(candidate)) {
stack.push(PsiAnchor.create(candidate));
}
return true;
}
};
ApplicationManager.getApplication().runReadAction(new Runnable() {
@Override
public void run() {
stack.push(PsiAnchor.create(baseClass));
}
});
final GlobalSearchScope projectScope = GlobalSearchScope.allScope(project);
while (!stack.isEmpty()) {
ProgressIndicatorProvider.checkCanceled();
final PsiAnchor anchor = stack.pop();
if (!processed.add(anchor)) continue;
PsiClass psiClass = ApplicationManager.getApplication().runReadAction(new Computable<PsiClass>() {
@Override
public PsiClass compute() {
return (PsiClass)anchor.retrieve();
}
});
if (psiClass == null) continue;
currentBase.set(psiClass);
if (!DirectClassInheritorsSearch.search(psiClass, projectScope, parameters.isIncludeAnonymous(), false).forEach(processor)) return;
}
}
private static boolean isJavaLangObject(@NotNull final PsiClass baseClass) {
return ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() {
@Override
public Boolean compute() {
return baseClass.isValid() && CommonClassNames.JAVA_LANG_OBJECT.equals(baseClass.getQualifiedName());
}
});
}
private static boolean isFinal(@NotNull final PsiClass baseClass) {
return ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() {
@Override
public Boolean compute() {
return Boolean.valueOf(baseClass.hasModifierProperty(PsiModifier.FINAL));
}
}).booleanValue();
}
}
@@ -73,7 +73,12 @@ public class SPIReferencesSearcher extends QueryExecutorBase<PsiReference, Refer
} else if (element instanceof PsiPackage) {
final String qualifiedName = ((PsiPackage)element).getQualifiedName();
final Project project = element.getProject();
final String[] filenames = FilenameIndex.getAllFilenames(project);
final String[] filenames = ApplicationManager.getApplication().runReadAction(new Computable<String[]>() {
@Override
public String[] compute() {
return FilenameIndex.getAllFilenames(project);
}
});
for (final String filename : filenames) {
if (filename.startsWith(qualifiedName + ".")) {
final PsiFile[] files = ApplicationManager.getApplication().runReadAction(new Computable<PsiFile[]>() {
@@ -233,7 +233,14 @@ public class InferenceSession {
private static PsiType getParameterType(PsiParameter[] parameters, int i, @Nullable PsiSubstitutor substitutor, boolean varargs) {
if (substitutor == null) return null;
PsiType parameterType = substitutor.substitute(parameters[i < parameters.length ? i : parameters.length - 1].getType());
final PsiParameter parameter = parameters[i < parameters.length ? i : parameters.length - 1];
final PsiType type = parameter.getType();
if (!type.isValid()) {
PsiUtil.ensureValidType(type, "Invalid type of parameter " + parameter + " of " + parameter.getClass());
}
PsiType parameterType = substitutor.substitute(type);
if (parameterType instanceof PsiEllipsisType && varargs) {
parameterType = ((PsiEllipsisType)parameterType).getComponentType();
}
@@ -1231,7 +1238,9 @@ public class InferenceSession {
final PsiMethodReferenceUtil.QualifierResolveResult qualifierResolveResult = PsiMethodReferenceUtil.getQualifierResolveResult(reference);
final PsiClass containingClass = qualifierResolveResult.getContainingClass();
LOG.assertTrue(containingClass != null, myContext);
if (containingClass == null) {
return resolveSubset(myInferenceVariables, mySiteSubstitutor);
}
final PsiParameter[] functionalMethodParameters = interfaceMethod.getParameterList().getParameters();
final PsiParameter[] parameters = method.getParameterList().getParameters();
@@ -11,7 +11,7 @@ annotation.not.applicable=''@{0}'' not applicable to {1}
annotation.non.constant.attribute.value=Attribute value must be constant
annotation.non.class.literal.attribute.value=Attribute value must be a class literal
annotation.non.enum.constant.attribute.value=Attribute value must be an enum constant
annotation.invalid.annotation.member.type=Invalid type for annotation member
annotation.invalid.annotation.member.type=Invalid type ''{0}'' for annotation member
annotation.cyclic.element.type=Cyclic annotation element type
annotation.annotation.type.expected=Annotation type expected
annotation.members.may.not.have.throws.list=@interface members may not have throws list
@@ -17,10 +17,11 @@ package com.intellij.execution;
import java.lang.reflect.Method;
public class TestDiscoveryListener {
public abstract class TestDiscoveryListener {
public abstract String getFrameworkId();
public void testStarted(String className, String methodName) {
final Object data = getData();
try {
final Object data = getData();
Method testStarted = data.getClass().getMethod("testStarted", new Class[] {String.class});
testStarted.invoke(data, new Object[] {className + "-" + methodName});
} catch (Throwable t) {
@@ -29,23 +30,22 @@ public class TestDiscoveryListener {
}
public void testFinished(String className, String methodName) {
final Object data = getData();
try {
final Object data = getData();
Method testEnded = data.getClass().getMethod("testEnded", new Class[] {String.class});
testEnded.invoke(data, new Object[] {className + "-" + methodName});
testEnded.invoke(data, new Object[] {getFrameworkId() + className + "-" + methodName});
} catch (Throwable t) {
t.printStackTrace();
}
}
protected Object getData() {
try {
return Class.forName("org.jetbrains.testme.instrumentation.ProjectData")
protected Object getData() throws Exception {
return Class.forName("org.jetbrains.testme.instrumentation.ProjectData")
.getMethod("getProjectData", new Class[0])
.invoke(null, new Object[0]);
} catch (Exception e) {
return null; //should not happen
}
}
public void testRunStarted(String name) {}
public void testRunFinished(String name) {}
}
@@ -67,13 +67,14 @@ public class ComparisonFailureData {
Map attrs,
Throwable throwable) {
final int failureIdx = failureMessage != null ? trace.indexOf(failureMessage) : -1;
final int failureMessageLength = failureMessage != null ? failureMessage.length() : 0;
attrs.put("details", failureIdx > -1 ? trace.substring(failureIdx + failureMessageLength) : trace);
if (notification != null) {
attrs.put("expected", notification.getExpected());
attrs.put("actual", notification.getActual());
final int failureIdx = failureMessage != null ? trace.indexOf(failureMessage) : -1;
final int failureMessageLength = failureMessage != null ? failureMessage.length() : 0;
attrs.put("details", failureIdx > -1 ? trace.substring(failureIdx + failureMessageLength) : trace);
final String filePath = notification.getFilePath();
if (filePath != null) {
attrs.put("expectedFile", filePath);
@@ -89,8 +90,6 @@ public class ComparisonFailureData {
attrs.put("message", comparisonFailureMessage);
}
else {
attrs.put("details", trace);
Throwable throwableCause = null;
try {
throwableCause = throwable.getCause();
@@ -3,7 +3,7 @@
Class <error descr="@interface member clashes with 'annotationType()' in java.lang.annotation.Annotation">annotationType</error>();
int value();
boolean equals();
<error descr="Invalid type for annotation member">void</error> <error descr="@interface member clashes with 'finalize()' in java.lang.Object">finalize</error>();
<error descr="Invalid type for annotation member">void</error> registerNatives();
<error descr="Invalid type 'void' for annotation member">void</error> <error descr="@interface member clashes with 'finalize()' in java.lang.Object">finalize</error>();
<error descr="Invalid type 'void' for annotation member">void</error> registerNatives();
}
@@ -1,8 +1,9 @@
class Clazz {}
@interface Ann {
<error descr="Invalid type for annotation member">Clazz</error> i ();
<error descr="Invalid type 'Clazz' for annotation member">Clazz</error> i ();
<error descr="Cyclic annotation element type">Ann</error> j ();
<error descr="Invalid type for annotation member">void</error> f();
<error descr="Invalid type 'void' for annotation member">void</error> f();
<error descr="Invalid type 'int[][]' for annotation member">int[]</error> intDblArray()[];
}
@@ -0,0 +1,12 @@
import java.util.function.Function;
class Test {
{
foo(s -> {
foo(s::concat);
return s;
});
}
<S,<error descr="'>' expected."><error descr="Type parameter expected"> </error></error> void foo(Function<String, String> f){}
}

Some files were not shown because too many files have changed in this diff Show More