Cleanup (duplication; correct light test setup; formatting; typos)

This commit is contained in:
Roman Shevchenko
2015-11-16 18:24:00 +01:00
parent b6106c5cda
commit 8e62c0f4ef
11 changed files with 265 additions and 268 deletions
@@ -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.
@@ -126,11 +126,11 @@ public class CreateConstructorParameterFromFieldFix implements IntentionAction {
}
});
final List<PsiElement> cleanupElements = new ArrayList<PsiElement>();
final ArrayList<PsiMethod> constrs = filterConstructorsIfFieldAlreadyAssigned(constructors, getField());
if (constrs.size() > 1) {
final PsiMethodMember[] members = new PsiMethodMember[constrs.size()];
final List<PsiMethod> filtered = filterConstructorsIfFieldAlreadyAssigned(constructors, getField());
if (filtered.size() > 1) {
final PsiMethodMember[] members = new PsiMethodMember[filtered.size()];
int i = 0;
for (PsiMethod constructor : constrs) {
for (PsiMethod constructor : filtered) {
members[i++] = new PsiMethodMember(constructor);
}
final List<PsiMethodMember> elements;
@@ -138,7 +138,7 @@ public class CreateConstructorParameterFromFieldFix implements IntentionAction {
elements = Arrays.asList(members);
} else {
final MemberChooser<PsiMethodMember> chooser = new MemberChooser<PsiMethodMember>(members, false, true, project);
chooser.setTitle("Choose constructors to add parameter to");
chooser.setTitle("Choose Constructors to Add Parameter to");
chooser.show();
elements = chooser.getSelectedElements();
if (elements == null) return;
@@ -149,11 +149,11 @@ public class CreateConstructorParameterFromFieldFix implements IntentionAction {
break;
}
}
} else if (!constrs.isEmpty()) {
}
else if (!filtered.isEmpty()) {
final Collection<SmartPsiElementPointer<PsiField>> fieldsToFix = getFieldsToFix();
try {
final PsiMethod constructor = constrs.get(0);
final PsiMethod constructor = filtered.get(0);
final LinkedHashSet<PsiField> fields = new LinkedHashSet<PsiField>();
getFieldsToFix().add(myField);
for (SmartPsiElementPointer<PsiField> elementPointer : fieldsToFix) {
@@ -162,7 +162,7 @@ public class CreateConstructorParameterFromFieldFix implements IntentionAction {
fields.add(field);
}
}
if (constrs.size() == constructors.length && fields.size() > 1 && !ApplicationManager.getApplication().isUnitTestMode()) {
if (filtered.size() == constructors.length && fields.size() > 1 && !ApplicationManager.getApplication().isUnitTestMode()) {
PsiFieldMember[] members = new PsiFieldMember[fields.size()];
int i = 0;
for (PsiField field : fields) {
@@ -180,7 +180,7 @@ public class CreateConstructorParameterFromFieldFix implements IntentionAction {
}
}
addParameterToConstructor(project, file, editor, constructor, constrs.size() == constructors.length
addParameterToConstructor(project, file, editor, constructor, filtered.size() == constructors.length
? fields.toArray(new PsiField[fields.size()])
: new PsiField[]{getField()}, cleanupElements);
}
@@ -222,8 +222,8 @@ public class CreateConstructorParameterFromFieldFix implements IntentionAction {
};
}
private static ArrayList<PsiMethod> filterConstructorsIfFieldAlreadyAssigned(PsiMethod[] constructors, PsiField field) {
final ArrayList<PsiMethod> result = new ArrayList<PsiMethod>(Arrays.asList(constructors));
private static List<PsiMethod> filterConstructorsIfFieldAlreadyAssigned(PsiMethod[] constructors, PsiField field) {
final List<PsiMethod> result = new ArrayList<PsiMethod>(Arrays.asList(constructors));
for (PsiReference reference : ReferencesSearch.search(field, new LocalSearchScope(constructors))) {
final PsiElement element = reference.getElement();
if (element instanceof PsiReferenceExpression && PsiUtil.isOnAssignmentLeftHand((PsiExpression)element)) {
@@ -246,7 +246,7 @@ public class CreateConstructorParameterFromFieldFix implements IntentionAction {
Collections.sort(params, new FieldParameterComparator(parameterList));
int i = 0;
final HashMap<PsiField, String> usedFields = new HashMap<PsiField, String>();
final Map<PsiField, String> usedFields = new HashMap<PsiField, String>();
final MultiMap<PsiType, PsiVariable> types = new MultiMap<PsiType, PsiVariable>();
for (PsiVariable param : params) {
types.putValue(param.getType(), param);
@@ -299,12 +299,12 @@ public class CreateConstructorParameterFromFieldFix implements IntentionAction {
}, ", ") + "){}";
}
private static String getUniqueParameterName(PsiParameter[] parameters, PsiVariable variable, HashMap<PsiField, String> usedNames) {
final JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(variable.getProject());
final SuggestedNameInfo nameInfo = styleManager
.suggestVariableName(VariableKind.PARAMETER,
styleManager.variableNameToPropertyName(variable.getName(), VariableKind.FIELD),
null, variable.getType());
private static String getUniqueParameterName(PsiParameter[] parameters, PsiVariable variable, Map<PsiField, String> usedNames) {
String name = variable.getName();
assert name != null : variable;
JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(variable.getProject());
name = styleManager.variableNameToPropertyName(name, VariableKind.FIELD);
SuggestedNameInfo nameInfo = styleManager.suggestVariableName(VariableKind.PARAMETER, name, null, variable.getType());
String newName = nameInfo.names[0];
int n = 1;
while (true) {
@@ -317,7 +317,7 @@ public class CreateConstructorParameterFromFieldFix implements IntentionAction {
return newName;
}
private static boolean isUnique(PsiParameter[] params, String newName, HashMap<PsiField, String> usedNames) {
private static boolean isUnique(PsiParameter[] params, String newName, Map<PsiField, String> usedNames) {
if (usedNames.containsValue(newName)) return false;
for (PsiParameter parameter : params) {
if (Comparing.strEqual(parameter.getName(), newName)) {
@@ -328,12 +328,12 @@ public class CreateConstructorParameterFromFieldFix implements IntentionAction {
}
private static boolean doCreate(Project project, Editor editor, PsiParameter[] parameters, SmartPsiElementPointer constructorPointer,
ParameterInfoImpl[] parameterInfos, HashMap<PsiField, String> fields, List<PsiElement> cleanupElements) {
ParameterInfoImpl[] parameterInfos, Map<PsiField, String> fields, List<PsiElement> cleanupElements) {
PsiMethod constructor = (PsiMethod)constructorPointer.getElement();
assert constructor != null;
PsiParameter[] newParameters = constructor.getParameterList().getParameters();
if (newParameters == parameters) return false; //user must have canceled dialog
// do not introduce assignment in chanined constructor
// do not introduce assignment in chained constructor
if (JavaHighlightUtil.getChainedConstructors(constructor) == null) {
boolean created = false;
for (PsiField field : fields.keySet()) {
@@ -359,6 +359,7 @@ public class CreateConstructorParameterFromFieldFix implements IntentionAction {
private static void notNull(PsiField field, PsiParameter parameter) {
final PsiAnnotation notNull = NullableNotNullManager.getInstance(field.getProject()).copyNotNullAnnotation(field);
if (notNull != null) {
//noinspection ConstantConditions
parameter.getModifierList().addBefore(notNull, 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.
@@ -33,7 +33,6 @@ import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.util.Function;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -43,6 +42,7 @@ import java.util.List;
public class GenerateConstructorHandler extends GenerateMembersHandlerBase {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.generation.GenerateConstructorHandler");
private boolean myCopyJavadoc;
public GenerateConstructorHandler() {
@@ -54,12 +54,13 @@ public class GenerateConstructorHandler extends GenerateMembersHandlerBase {
PsiField[] fields = aClass.getFields();
ArrayList<ClassMember> array = new ArrayList<ClassMember>();
ImplicitUsageProvider[] implicitUsageProviders = Extensions.getExtensions(ImplicitUsageProvider.EP_NAME);
fieldLoop: for (PsiField field : fields) {
fieldLoop:
for (PsiField field : fields) {
if (field.hasModifierProperty(PsiModifier.STATIC)) continue;
if (field.hasModifierProperty(PsiModifier.FINAL) && field.getInitializer() != null) continue;
for(ImplicitUsageProvider provider: implicitUsageProviders) {
for (ImplicitUsageProvider provider : implicitUsageProviders) {
if (provider.isImplicitWrite(field)) continue fieldLoop;
}
array.add(new PsiFieldMember(field));
@@ -70,7 +71,7 @@ public class GenerateConstructorHandler extends GenerateMembersHandlerBase {
@Override
@Nullable
protected ClassMember[] chooseOriginalMembers(PsiClass aClass, Project project) {
if (aClass instanceof PsiAnonymousClass){
if (aClass instanceof PsiAnonymousClass) {
Messages.showMessageDialog(project,
CodeInsightBundle.message("error.attempt.to.generate.constructor.for.anonymous.class"),
CommonBundle.getErrorTitle(),
@@ -81,18 +82,18 @@ public class GenerateConstructorHandler extends GenerateMembersHandlerBase {
myCopyJavadoc = false;
PsiMethod[] baseConstructors = null;
PsiClass baseClass = aClass.getSuperClass();
if (baseClass != null){
ArrayList<PsiMethod> array = new ArrayList<PsiMethod>();
if (baseClass != null) {
List<PsiMethod> array = new ArrayList<PsiMethod>();
for (PsiMethod method : baseClass.getConstructors()) {
if (JavaPsiFacade.getInstance(method.getProject()).getResolveHelper().isAccessible(method, aClass, null)) {
array.add(method);
}
}
if (!array.isEmpty()){
if (array.size() == 1){
if (!array.isEmpty()) {
if (array.size() == 1) {
baseConstructors = new PsiMethod[]{array.get(0)};
}
else{
else {
final PsiSubstitutor substitutor = TypeConversionUtil.getSuperClassSubstitutor(baseClass, aClass, PsiSubstitutor.EMPTY);
PsiMethodMember[] constructors = ContainerUtil.map2Array(array, PsiMethodMember.class, new Function<PsiMethod, PsiMethodMember>() {
@Override
@@ -106,7 +107,7 @@ public class GenerateConstructorHandler extends GenerateMembersHandlerBase {
List<PsiMethodMember> elements = chooser.getSelectedElements();
if (elements == null || elements.isEmpty()) return null;
baseConstructors = new PsiMethod[elements.size()];
for(int i = 0; i < elements.size(); i++){
for (int i = 0; i < elements.size(); i++) {
final ClassMember member = elements.get(i);
baseConstructors[i] = ((PsiMethodMember)member).getElement();
}
@@ -120,12 +121,13 @@ public class GenerateConstructorHandler extends GenerateMembersHandlerBase {
if (allMembers.length == 0) {
members = ClassMember.EMPTY_ARRAY;
}
else{
else {
members = chooseMembers(allMembers, true, false, project, null);
if (members == null) return null;
}
if (baseConstructors != null) {
ArrayList<ClassMember> array = new ArrayList<ClassMember>();
List<ClassMember> array = new ArrayList<ClassMember>();
for (PsiMethod baseConstructor : baseConstructors) {
array.add(new PsiMethodMember(baseConstructor));
}
@@ -210,81 +212,94 @@ public class GenerateConstructorHandler extends GenerateMembersHandlerBase {
return "Constructor already exist";
}
public static PsiMethod generateConstructorPrototype(PsiClass aClass, PsiMethod baseConstructor, boolean copyJavaDoc, PsiField[] fields) throws IncorrectOperationException {
public static PsiMethod generateConstructorPrototype(PsiClass aClass,
PsiMethod baseConstructor,
boolean copyJavaDoc,
PsiField[] fields) throws IncorrectOperationException {
PsiManager manager = aClass.getManager();
JVMElementFactory factory = JVMElementFactories.requireFactory(aClass.getLanguage(), aClass.getProject());
Project project = aClass.getProject();
JVMElementFactory factory = JVMElementFactories.requireFactory(aClass.getLanguage(), project);
CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(manager.getProject());
PsiMethod constructor = factory.createConstructor(aClass.getName(), aClass);
String className = aClass.getName();
assert className != null : aClass;
PsiMethod constructor = factory.createConstructor(className, aClass);
GenerateMembersUtil.setVisibility(aClass, constructor);
if (baseConstructor != null){
if (baseConstructor != null) {
PsiJavaCodeReferenceElement[] throwRefs = baseConstructor.getThrowsList().getReferenceElements();
for (PsiJavaCodeReferenceElement ref : throwRefs) {
constructor.getThrowsList().add(ref);
}
if(copyJavaDoc) {
if (copyJavaDoc) {
final PsiDocComment docComment = ((PsiMethod)baseConstructor.getNavigationElement()).getDocComment();
if(docComment != null) {
if (docComment != null) {
constructor.addAfter(docComment, null);
}
}
}
boolean isNotEnum = false;
if (baseConstructor != null){
if (baseConstructor != null) {
PsiClass superClass = aClass.getSuperClass();
LOG.assertTrue(superClass != null);
if (!CommonClassNames.JAVA_LANG_ENUM.equals(superClass.getQualifiedName())) {
isNotEnum = true;
if (baseConstructor instanceof PsiCompiledElement){ // to get some parameter names
PsiClass dummyClass = JVMElementFactories.requireFactory(baseConstructor.getLanguage(), baseConstructor.getProject()).createClass("Dummy");
if (baseConstructor instanceof PsiCompiledElement) { // to get some parameter names
PsiClass dummyClass = JVMElementFactories.requireFactory(baseConstructor.getLanguage(), project).createClass("Dummy");
baseConstructor = (PsiMethod)dummyClass.add(baseConstructor);
}
PsiParameter[] params = baseConstructor.getParameterList().getParameters();
for (PsiParameter param : params) {
PsiParameter newParam = factory.createParameter(param.getName(), param.getType(), aClass);
String name = param.getName();
assert name != null : param;
PsiParameter newParam = factory.createParameter(name, param.getType(), aClass);
GenerateMembersUtil.copyOrReplaceModifierList(param, newParam);
constructor.getParameterList().add(newParam);
}
}
}
JavaCodeStyleManager javaStyle = JavaCodeStyleManager.getInstance(aClass.getProject());
JavaCodeStyleManager javaStyle = JavaCodeStyleManager.getInstance(project);
final PsiMethod dummyConstructor = factory.createConstructor(aClass.getName());
final PsiMethod dummyConstructor = factory.createConstructor(className);
dummyConstructor.getParameterList().replace(constructor.getParameterList().copy());
List<PsiParameter> fieldParams = new ArrayList<PsiParameter>();
for (PsiField field : fields) {
String fieldName = field.getName();
assert fieldName != null : field;
String name = javaStyle.variableNameToPropertyName(fieldName, VariableKind.FIELD);
String parmName = javaStyle.propertyNameToVariableName(name, VariableKind.PARAMETER);
parmName = javaStyle.suggestUniqueVariableName(parmName, dummyConstructor, true);
PsiParameter parm = factory.createParameter(parmName, field.getType(), aClass);
final NullableNotNullManager nullableManager = NullableNotNullManager.getInstance(field.getProject());
final PsiAnnotation notNull = nullableManager.copyNotNullAnnotation(field);
PsiAnnotation notNull = NullableNotNullManager.getInstance(project).copyNotNullAnnotation(field);
if (notNull != null) {
parm.getModifierList().addAfter(notNull, null);
PsiModifierList modifierList = parm.getModifierList();
if (modifierList != null) {
modifierList.addAfter(notNull, null);
}
}
if (constructor.isVarArgs()) {
final PsiParameterList parameterList = constructor.getParameterList();
parameterList.addBefore(parm, parameterList.getParameters()[parameterList.getParametersCount() - 1]);
final PsiParameterList dummyParameterlist = dummyConstructor.getParameterList();
dummyParameterlist.addBefore(parm.copy(), dummyParameterlist.getParameters()[dummyParameterlist.getParametersCount() - 1]);
} else {
final PsiParameterList dummyParameterList = dummyConstructor.getParameterList();
dummyParameterList.addBefore(parm.copy(), dummyParameterList.getParameters()[dummyParameterList.getParametersCount() - 1]);
}
else {
constructor.getParameterList().add(parm);
dummyConstructor.getParameterList().add(parm.copy());
}
fieldParams.add(parm);
}
ConstructorBodyGenerator generator = ConstructorBodyGenerator.INSTANCE.forLanguage(aClass.getLanguage());
if (generator != null) {
@NonNls StringBuilder buffer = new StringBuilder();
StringBuilder buffer = new StringBuilder();
generator.start(buffer, constructor.getName(), PsiParameter.EMPTY_ARRAY);
if (isNotEnum) {
generator.generateSuperCallIfNeeded(buffer, baseConstructor.getParameterList().getParameters());
@@ -292,7 +307,10 @@ public class GenerateConstructorHandler extends GenerateMembersHandlerBase {
generator.generateFieldInitialization(buffer, fields, fieldParams.toArray(new PsiParameter[fieldParams.size()]));
generator.finish(buffer);
PsiMethod stub = factory.createMethodFromText(buffer.toString(), aClass);
constructor.getBody().replace(stub.getBody());
PsiCodeBlock original = constructor.getBody(), replacement = stub.getBody();
assert original != null : constructor;
assert replacement != null : stub;
original.replace(replacement);
}
constructor = (PsiMethod)codeStyleManager.reformat(constructor);
@@ -304,4 +322,4 @@ public class GenerateConstructorHandler extends GenerateMembersHandlerBase {
LOG.assertTrue(false);
return 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.
@@ -37,6 +37,7 @@ import org.jetbrains.annotations.Nullable;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* @author Danila Ponomarenko
@@ -75,7 +76,8 @@ public final class FieldFromParameterUtils {
final PsiClassType.ClassResolveResult result = PsiUtil.resolveGenericsClassInType(type);
final PsiClass psiClass = result.getElement();
if (psiClass == null) return type;
final HashSet<PsiTypeParameter> usedTypeParameters = new HashSet<PsiTypeParameter>();
final Set<PsiTypeParameter> usedTypeParameters = new HashSet<PsiTypeParameter>();
RefactoringUtil.collectTypeParameters(usedTypeParameters, parameter);
for (Iterator<PsiTypeParameter> iterator = usedTypeParameters.iterator(); iterator.hasNext(); ) {
PsiTypeParameter usedTypeParameter = iterator.next();
@@ -83,18 +85,25 @@ public final class FieldFromParameterUtils {
iterator.remove();
}
}
final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(parameter.getProject());
PsiSubstitutor subst = PsiSubstitutor.EMPTY;
for (PsiTypeParameter usedTypeParameter : usedTypeParameters) {
subst = subst.put(usedTypeParameter, TypeConversionUtil.typeParameterErasure(usedTypeParameter));
}
PsiSubstitutor substitutor = PsiSubstitutor.EMPTY;
final Map<PsiTypeParameter, PsiType> typeMap = result.getSubstitutor().getSubstitutionMap();
for (PsiTypeParameter typeParameter : typeMap.keySet()) {
final PsiType psiType = typeMap.get(typeParameter);
substitutor = substitutor.put(typeParameter, psiType != null ? subst.substitute(psiType) : null);
}
return psiClass instanceof PsiTypeParameter ? subst.substitute((PsiTypeParameter)psiClass) : elementFactory.createType(psiClass, substitutor);
if (psiClass instanceof PsiTypeParameter) {
return subst.substitute((PsiTypeParameter)psiClass);
}
else {
return JavaPsiFacade.getElementFactory(parameter.getProject()).createType(psiClass, substitutor);
}
}
@Nullable
@@ -127,8 +136,7 @@ public final class FieldFromParameterUtils {
if (expression instanceof PsiMethodCallExpression) {
PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)expression;
@NonNls String text = methodCallExpression.getMethodExpression().getText();
String text = methodCallExpression.getMethodExpression().getText();
if (text.equals("super") || text.equals("this")) {
continue;
}
@@ -173,9 +181,10 @@ public final class FieldFromParameterUtils {
final @NotNull PsiClass targetClass,
final @NotNull PsiMethod method,
final @NotNull PsiParameter parameter,
final @NotNull PsiType fieldType, final @NotNull String fieldName,
final boolean isStatic, final boolean isFinal) throws IncorrectOperationException {
final @NotNull PsiType fieldType,
final @NotNull String fieldName,
final boolean isStatic,
final boolean isFinal) throws IncorrectOperationException {
PsiManager psiManager = PsiManager.getInstance(project);
PsiElementFactory factory = JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory();
@@ -227,16 +236,7 @@ public final class FieldFromParameterUtils {
psiVariable.normalizeDeclaration();
}
boolean found = false;
final PsiField[] fields = targetClass.getFields();
for (PsiField f : fields) {
if (f.getName().equals(field.getName())) {
found = true;
break;
}
}
if (!found) {
if (targetClass.findFieldByName(fieldName, false) == null) {
if (fieldAnchor != null) {
Boolean insertBefore = fieldAnchor.getSecond();
PsiField inField = fieldAnchor.getFirst();
@@ -253,9 +253,7 @@ public final class FieldFromParameterUtils {
}
}
public static boolean isAvailable(@Nullable PsiParameter myParameter,
@Nullable PsiType type,
@Nullable PsiClass targetClass){
public static boolean isAvailable(@Nullable PsiParameter myParameter, @Nullable PsiType type, @Nullable PsiClass targetClass) {
return myParameter != null
&& myParameter.isValid()
&& myParameter.getManager().isInProject(myParameter)
@@ -267,6 +265,6 @@ public final class FieldFromParameterUtils {
&& !targetClass.isInterface()
&& getParameterAssignedToField(myParameter) == null;
}
private FieldFromParameterUtils() {
}
private FieldFromParameterUtils() { }
}
@@ -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,16 +33,16 @@ import org.jetbrains.annotations.Nullable;
import java.util.*;
/**
* User: anna
* Date: 1/25/11
* @author anna
* @since 25.01.2011
*/
public abstract class NullableNotNullManager implements PersistentStateComponent<Element> {
private static final Logger LOG = Logger.getInstance("#" + NullableNotNullManager.class.getName());
public String myDefaultNullable = AnnotationUtil.NULLABLE;
public String myDefaultNotNull = AnnotationUtil.NOT_NULL;
public final JDOMExternalizableStringList myNullables = new JDOMExternalizableStringList();
public final JDOMExternalizableStringList myNotNulls = new JDOMExternalizableStringList();
@SuppressWarnings("deprecation") public final JDOMExternalizableStringList myNullables = new JDOMExternalizableStringList();
@SuppressWarnings("deprecation") public final JDOMExternalizableStringList myNotNulls = new JDOMExternalizableStringList();
private static final String JAVAX_ANNOTATION_NULLABLE = "javax.annotation.Nullable";
private static final String JAVAX_ANNOTATION_NONNULL = "javax.annotation.Nonnull";
@@ -106,12 +106,10 @@ public abstract class NullableNotNullManager implements PersistentStateComponent
if (annotation == null) {
return null;
}
else {
if (!acceptContainer && isContainerAnnotation(annotation)) {
return null;
}
return annotation.getQualifiedName();
if (!acceptContainer && isContainerAnnotation(annotation)) {
return null;
}
return annotation.getQualifiedName();
}
@Nullable
@@ -147,13 +145,9 @@ public abstract class NullableNotNullManager implements PersistentStateComponent
return copyAnnotation(owner, getNullableAnnotation(owner, false));
}
private PsiAnnotation copyAnnotation(PsiModifierListOwner owner,
PsiAnnotation annotation) {
final String notNull = checkContainer(annotation, false);
if (notNull != null) {
return JavaPsiFacade.getElementFactory(owner.getProject()).createAnnotationFromText("@" + notNull, owner);
}
return null;
private PsiAnnotation copyAnnotation(PsiModifierListOwner owner, PsiAnnotation annotation) {
String notNull = checkContainer(annotation, false);
return notNull != null ? JavaPsiFacade.getElementFactory(owner.getProject()).createAnnotationFromText("@" + notNull, owner) : null;
}
@Nullable
@@ -308,6 +302,7 @@ public abstract class NullableNotNullManager implements PersistentStateComponent
return true;
}
@SuppressWarnings("deprecation")
@Override
public Element getState() {
final Element component = new Element("component");
@@ -325,6 +320,7 @@ public abstract class NullableNotNullManager implements PersistentStateComponent
return component;
}
@SuppressWarnings("deprecation")
@Override
public void loadState(Element state) {
try {
@@ -348,4 +344,4 @@ public abstract class NullableNotNullManager implements PersistentStateComponent
public static boolean isNotNull(@NotNull PsiModifierListOwner owner) {
return getInstance(owner.getProject()).isNotNull(owner, true);
}
}
}
@@ -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.
@@ -30,55 +30,49 @@ import java.util.List;
* @author ven
*/
public class GenerateConstructorTest extends LightCodeInsightTestCase {
public void testAbstractClass() throws Exception { doTest(); }
public void testPackageLocalClass() throws Exception { doTest(); }
public void testPrivateClass() throws Exception { doTest(); }
public void testBoundComments() throws Exception { doTest(); }
public void testSameNamedFields() throws Exception { doTest(); }
public void testEnumWithAbstractMethod() throws Exception { doTest(); }
public void testNoMoreConstructorsCanBeGenerated() throws Exception { doTest(); }
public void testBaseVarargs() throws Exception { doTest(); }
public void testAbstractClass() { doTest(); }
public void testPackageLocalClass() { doTest(); }
public void testPrivateClass() { doTest(); }
public void testBoundComments() { doTest(); }
public void testSameNamedFields() { doTest(); }
public void testEnumWithAbstractMethod() { doTest(); }
public void testNoMoreConstructorsCanBeGenerated() { doTest(); }
public void testBaseVarargs() { doTest(); }
public void testFinalFieldPreselection() { doTest(true); }
public void testSubstitution() { doTest(true); }
public void testImmediatelyAfterRBrace() throws Exception { // IDEADEV-28811
public void testImmediatelyAfterRBrace() { // IDEADEV-28811
CodeStyleSettingsManager.getInstance(getProject()).getCurrentSettings().CLASS_BRACE_STYLE = CommonCodeStyleSettings.NEXT_LINE;
doTest();
}
public void testBoundCommentsKeepsBlankLine() throws Exception {
CommonCodeStyleSettings javaSettings =
CodeStyleSettingsManager.getInstance(getProject()).getCurrentSettings().getCommonSettings(JavaLanguage.INSTANCE);
javaSettings.BLANK_LINES_AFTER_CLASS_HEADER = 1;
public void testBoundCommentsKeepsBlankLine() {
CodeStyleSettingsManager.getInstance(getProject()).getCurrentSettings().getCommonSettings(JavaLanguage.INSTANCE).BLANK_LINES_AFTER_CLASS_HEADER = 1;
doTest();
}
public void testFinalFieldPreselection() throws Exception { doTest(true); }
public void testSubstitution() throws Exception { doTest(true); }
public void testFieldPrefixCoincidence() throws Exception {
public void testFieldPrefixCoincidence() {
CodeStyleSettingsManager.getInstance(getProject()).getCurrentSettings().FIELD_NAME_PREFIX = "m";
doTest();
}
public void testFieldPrefixCoincidence1() throws Exception {
public void testFieldPrefixCoincidence1() {
CodeStyleSettingsManager.getInstance(getProject()).getCurrentSettings().FIELD_NAME_PREFIX = "_";
doTest();
}
private void doTest() throws Exception {
private void doTest() {
doTest(false);
}
private void doTest(final boolean preSelect) throws Exception {
private void doTest(boolean preSelect) {
String name = getTestName(false);
configureByFile("/codeInsight/generateConstructor/before" + name + ".java");
new GenerateConstructorHandler() {
@Override
protected ClassMember[] chooseMembers(ClassMember[] members,
boolean allowEmptySelection,
boolean copyJavadocCheckbox,
Project project, Editor editor) {
protected ClassMember[] chooseMembers(ClassMember[] members, boolean allowEmpty, boolean copyJavadoc, Project project, Editor editor) {
if (preSelect) {
final List<ClassMember> preselection = GenerateConstructorHandler.preselect(members);
List<ClassMember> preselection = GenerateConstructorHandler.preselect(members);
return preselection.toArray(new ClassMember[preselection.size()]);
}
else {
@@ -88,4 +82,4 @@ public class GenerateConstructorTest extends LightCodeInsightTestCase {
}.invoke(getProject(), getEditor(), getFile());
checkResultByFile("/codeInsight/generateConstructor/after" + name + ".java");
}
}
}
@@ -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,13 +20,12 @@ import com.intellij.codeInsight.NullableNotNullManager;
import com.intellij.codeInspection.dataFlow.DataFlowInspection;
import com.intellij.openapi.util.Disposer;
import com.intellij.testFramework.LightProjectDescriptor;
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase;
import org.jetbrains.annotations.NotNull;
/**
* @author peter
*/
public class DataFlowInspection8Test extends LightCodeInsightFixtureTestCase {
public class DataFlowInspection8Test extends DataFlowInspectionTestCase {
@NotNull
@Override
protected LightProjectDescriptor getProjectDescriptor() {
@@ -38,39 +37,40 @@ public class DataFlowInspection8Test extends LightCodeInsightFixtureTestCase {
return JavaTestUtil.getJavaTestDataPath() + "/inspection/dataFlow/fixture/";
}
private void doTest() {
final DataFlowInspection inspection = new DataFlowInspection();
inspection.SUGGEST_NULLABLE_ANNOTATIONS = true;
inspection.REPORT_CONSTANT_REFERENCE_VALUES = false;
public void testAnnotatedTypeParameters() { doTestWithCustomAnnotations(); }
public void testReturnNullInLambdaExpression() { doTest(); }
public void testReturnNullInLambdaStatement() { doTest(); }
public void testUnboxingBoxingInLambdaReturn() { doTest(); }
public void testUnboxingInMethodReferences() { doTest(); }
public void testMethodReferenceOnNullable() { doTest(); }
public void testNullableVoidLambda() { doTest(); }
public void testNullableForeachVariable() { doTestWithCustomAnnotations(); }
public void testOptionalOfNullable() { doTest(); }
public void testPrimitiveInVoidLambda() { doTest(); }
public void testNullableArrayComponent() {
setupCustomAnnotations();
DataFlowInspection inspection = new DataFlowInspection();
inspection.IGNORE_ASSERT_STATEMENTS = true;
myFixture.enableInspections(inspection);
myFixture.testHighlighting(true, false, true, getTestName(false) + ".java");
}
public void testAnnotatedTypeParameters() throws Throwable {
public void testLambdaParametersWithDefaultNullability() {
DataFlowInspectionTest.addJavaxNullabilityAnnotations(myFixture);
DataFlowInspectionTest.addJavaxDefaultNullabilityAnnotations(myFixture);
doTest();
}
private void doTestWithCustomAnnotations() {
setupCustomAnnotations();
doTest();
}
public void testReturnNullInLambdaExpression() throws Exception {
doTest();
}
public void testReturnNullInLambdaStatement() throws Exception {
doTest();
}
public void testUnboxingBoxingInLambdaReturn() throws Exception {
doTest();
}
public void testUnboxingInMethodReferences() throws Exception {
doTest();
}
private void setupCustomAnnotations() {
myFixture.addClass("package foo;\n\nimport java.lang.annotation.*;\n\n@Target({ElementType.TYPE_USE}) public @interface Nullable { }");
myFixture.addClass("package foo;\n\nimport java.lang.annotation.*;\n\n@Target({ElementType.TYPE_USE}) public @interface NotNull { }");
final NullableNotNullManager nnnManager = NullableNotNullManager.getInstance(getProject());
NullableNotNullManager nnnManager = NullableNotNullManager.getInstance(getProject());
nnnManager.setNotNulls("foo.NotNull");
nnnManager.setNullables("foo.Nullable");
Disposer.register(myTestRootDisposable, () -> {
@@ -78,32 +78,4 @@ public class DataFlowInspection8Test extends LightCodeInsightFixtureTestCase {
nnnManager.setNullables();
});
}
public void testMethodReferenceOnNullable() { doTest(); }
public void testNullableVoidLambda() { doTest(); }
public void testNullableForeachVariable() {
setupCustomAnnotations();
doTest();
}
public void testNullableArrayComponent() {
setupCustomAnnotations();
final DataFlowInspection inspection = new DataFlowInspection();
inspection.IGNORE_ASSERT_STATEMENTS = true;
myFixture.enableInspections(inspection);
myFixture.testHighlighting(true, false, true, getTestName(false) + ".java");
}
public void testOptionalOfNullable() { doTest(); }
public void testLambdaParametersWithDefaultNullability() {
DataFlowInspectionTest.addJavaxNullabilityAnnotations(myFixture);
DataFlowInspectionTest.addJavaxDefaultNullabilityAnnotations(myFixture);
doTest();
}
public void testPrimitiveInVoidLambda() { doTest(); }
}
}
@@ -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.
@@ -19,14 +19,12 @@ import com.intellij.JavaTestUtil;
import com.intellij.codeInspection.dataFlow.DataFlowInspection;
import com.intellij.testFramework.LightProjectDescriptor;
import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture;
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase;
import org.jetbrains.annotations.NotNull;
/**
* @author peter
*/
public class DataFlowInspectionTest extends LightCodeInsightFixtureTestCase {
public class DataFlowInspectionTest extends DataFlowInspectionTestCase {
@NotNull
@Override
protected LightProjectDescriptor getProjectDescriptor() {
@@ -38,14 +36,6 @@ public class DataFlowInspectionTest extends LightCodeInsightFixtureTestCase {
return JavaTestUtil.getJavaTestDataPath() + "/inspection/dataFlow/fixture/";
}
private void doTest() {
final DataFlowInspection inspection = new DataFlowInspection();
inspection.SUGGEST_NULLABLE_ANNOTATIONS = true;
inspection.REPORT_CONSTANT_REFERENCE_VALUES = false;
myFixture.enableInspections(inspection);
myFixture.testHighlighting(true, false, true, getTestName(false) + ".java");
}
public void testTryInAnonymous() throws Throwable { doTest(); }
public void testNullableAnonymousMethod() throws Throwable { doTest(); }
public void testNullableAnonymousParameter() throws Throwable { doTest(); }
@@ -0,0 +1,29 @@
/*
* 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.codeInspection;
import com.intellij.codeInspection.dataFlow.DataFlowInspection;
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase;
public abstract class DataFlowInspectionTestCase extends LightCodeInsightFixtureTestCase {
protected void doTest() {
DataFlowInspection inspection = new DataFlowInspection();
inspection.SUGGEST_NULLABLE_ANNOTATIONS = true;
inspection.REPORT_CONSTANT_REFERENCE_VALUES = false;
myFixture.enableInspections(inspection);
myFixture.testHighlighting(true, false, true, getTestName(false) + ".java");
}
}
@@ -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.
@@ -16,30 +16,30 @@
package com.intellij.codeInspection.bytecodeAnalysis;
import com.intellij.JavaTestUtil;
import com.intellij.codeInspection.dataFlow.DataFlowInspection;
import com.intellij.codeInspection.DataFlowInspectionTestCase;
import com.intellij.openapi.application.ex.PathManagerEx;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.roots.ContentEntry;
import com.intellij.openapi.roots.ModifiableRootModel;
import com.intellij.testFramework.LightProjectDescriptor;
import com.intellij.testFramework.PsiTestUtil;
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase;
import com.intellij.testFramework.fixtures.DefaultLightProjectDescriptor;
import org.jetbrains.annotations.NotNull;
/**
* @author lambdamix
*/
public class BytecodeAnalysisResultsHighlightingTest extends LightCodeInsightFixtureTestCase {
@Override
protected void setUp() throws Exception {
super.setUp();
setUpLibraries();
}
public class BytecodeAnalysisResultsHighlightingTest extends DataFlowInspectionTestCase {
@NotNull
@Override
protected LightProjectDescriptor getProjectDescriptor() {
return JAVA_1_7;
return new DefaultLightProjectDescriptor() {
@Override
public void configureModule(@NotNull Module module, @NotNull ModifiableRootModel model, @NotNull ContentEntry contentEntry) {
super.configureModule(module, model, contentEntry);
PsiTestUtil.addLibrary(module, model, "velocity", PathManagerEx.getCommunityHomePath() + "/lib", "velocity.jar");
}
};
}
@Override
@@ -47,21 +47,5 @@ public class BytecodeAnalysisResultsHighlightingTest extends LightCodeInsightFix
return JavaTestUtil.getJavaTestDataPath() + "/codeInspection/bytecodeAnalysis/src/";
}
private void doTest() {
final DataFlowInspection inspection = new DataFlowInspection();
inspection.SUGGEST_NULLABLE_ANNOTATIONS = true;
inspection.REPORT_CONSTANT_REFERENCE_VALUES = false;
myFixture.enableInspections(inspection);
myFixture.testHighlighting(true, false, true, getTestName(false) + ".java");
}
public void testExample() {
doTest();
}
private void setUpLibraries() {
VirtualFile lib = LocalFileSystem.getInstance().refreshAndFindFileByPath(PathManagerEx.getTestDataPath() + "/../../../lib");
assertNotNull(lib);
PsiTestUtil.addLibrary(myModule, "velocity", lib.getPath(), new String[]{"/velocity.jar!/"}, new String[]{});
}
}
public void testExample() { doTest(); }
}
@@ -1,10 +1,24 @@
/*
* 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.refactoring;
import com.intellij.JavaTestUtil;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiExpression;
import com.intellij.psi.PsiPrimitiveType;
import com.intellij.psi.PsiType;
import com.intellij.refactoring.introduceField.BaseExpressionToFieldHandler;
import com.intellij.refactoring.util.CommonRefactoringUtil;
@@ -23,15 +37,15 @@ public class IntroduceFieldInSameClassTest extends LightCodeInsightTestCase {
return JavaTestUtil.getJavaTestDataPath();
}
public void testInClassInitializer () throws Exception {
public void testInClassInitializer() {
configureByFile("/refactoring/introduceField/before1.java");
performRefactoring(BaseExpressionToFieldHandler.InitializationPlace.IN_FIELD_DECLARATION, true);
checkResultByFile("/refactoring/introduceField/after1.java");
}
public void testConflictingFieldInContainingClass () throws Exception {
public void testConflictingFieldInContainingClass() {
configureByFile("/refactoring/introduceField/beforeConflictingFieldInContainingClass.java");
new MockIntroduceFieldHandler(BaseExpressionToFieldHandler.InitializationPlace.IN_FIELD_DECLARATION, false){
new MockIntroduceFieldHandler(BaseExpressionToFieldHandler.InitializationPlace.IN_FIELD_DECLARATION, false) {
@Override
protected String getNewName(Project project, PsiExpression expr, PsiType type) {
return "aField";
@@ -40,9 +54,9 @@ public class IntroduceFieldInSameClassTest extends LightCodeInsightTestCase {
checkResultByFile("/refactoring/introduceField/afterConflictingFieldInContainingClass.java");
}
public void testConflictingFieldInContainingClassLocal () throws Exception {
public void testConflictingFieldInContainingClassLocal() {
configureByFile("/refactoring/introduceField/beforeConflictingFieldInContainingClassLocal.java");
new MockIntroduceFieldHandler(BaseExpressionToFieldHandler.InitializationPlace.IN_FIELD_DECLARATION, false){
new MockIntroduceFieldHandler(BaseExpressionToFieldHandler.InitializationPlace.IN_FIELD_DECLARATION, false) {
@Override
protected String getNewName(Project project, PsiExpression expr, PsiType type) {
return "aField";
@@ -56,109 +70,105 @@ public class IntroduceFieldInSameClassTest extends LightCodeInsightTestCase {
checkResultByFile("/refactoring/introduceField/afterConflictingFieldInContainingClassLocal.java");
}
public void testInElseClause() throws Exception {
public void testInElseClause() {
configureByFile("/refactoring/introduceField/beforeElseClause.java");
performRefactoring(BaseExpressionToFieldHandler.InitializationPlace.IN_CURRENT_METHOD, true);
checkResultByFile("/refactoring/introduceField/afterElseClause.java");
}
public void testOuterClass() throws Exception {
public void testOuterClass() {
configureByFile("/refactoring/introduceField/beforeOuterClass.java");
performRefactoring(BaseExpressionToFieldHandler.InitializationPlace.IN_CONSTRUCTOR, false);
checkResultByFile("/refactoring/introduceField/afterOuterClass.java");
}
public void testOnClassLevelNoDuplicates() throws Exception {
public void testOnClassLevelNoDuplicates() {
configureByFile("/refactoring/introduceField/beforeOnClassLevelNoDuplicates.java");
performRefactoring(BaseExpressionToFieldHandler.InitializationPlace.IN_FIELD_DECLARATION, false);
checkResultByFile("/refactoring/introduceField/afterOnClassLevelNoDuplicates.java");
}
public void testOnClassLevelDuplicates() throws Exception {
public void testOnClassLevelDuplicates() {
configureByFile("/refactoring/introduceField/beforeOnClassLevelDuplicates.java");
performRefactoring(BaseExpressionToFieldHandler.InitializationPlace.IN_FIELD_DECLARATION, false);
checkResultByFile("/refactoring/introduceField/afterOnClassLevelDuplicates.java");
}
public void testOnClassLevelDuplicates1() throws Exception {
public void testOnClassLevelDuplicates1() {
configureByFile("/refactoring/introduceField/beforeOnClassLevelDuplicates1.java");
performRefactoring(BaseExpressionToFieldHandler.InitializationPlace.IN_FIELD_DECLARATION, false);
checkResultByFile("/refactoring/introduceField/afterOnClassLevelDuplicates1.java");
}
public void testOnClassLevelBinary() throws Exception {
public void testOnClassLevelBinary() {
configureByFile("/refactoring/introduceField/beforeOnClassLevelBinary.java");
performRefactoring(BaseExpressionToFieldHandler.InitializationPlace.IN_FIELD_DECLARATION, false);
checkResultByFile("/refactoring/introduceField/afterOnClassLevelBinary.java");
}
//multiple error elements on class level corresponding to the extracted fragment ------------------
public void testOnClassLevelNewExpression() throws Exception {
public void testOnClassLevelNewExpression() {
configureByFile("/refactoring/introduceField/beforeOnClassLevelNewExpression.java");
performRefactoring(BaseExpressionToFieldHandler.InitializationPlace.IN_FIELD_DECLARATION, false);
checkResultByFile("/refactoring/introduceField/afterOnClassLevelNewExpression.java");
}
public void testOnClassLevelClassForName() throws Exception {
public void testOnClassLevelClassForName() {
configureByFile("/refactoring/introduceField/beforeOnClassLevelClassForName.java");
performRefactoring(BaseExpressionToFieldHandler.InitializationPlace.IN_FIELD_DECLARATION, false);
checkResultByFile("/refactoring/introduceField/afterOnClassLevelClassForName.java");
}
//-------------------------------------------------------------------------------------------------
public void testUnresolvedReferenceToLocalVar() throws Exception {
public void testUnresolvedReferenceToLocalVar() {
configureByFile("/refactoring/introduceField/beforeUnresolvedReferenceToLocalVar.java");
performRefactoring(BaseExpressionToFieldHandler.InitializationPlace.IN_CURRENT_METHOD, false);
checkResultByFile("/refactoring/introduceField/afterUnresolvedReferenceToLocalVar.java");
}
private static void performRefactoring(final BaseExpressionToFieldHandler.InitializationPlace initializationPlace, final boolean declareStatic) {
new MockIntroduceFieldHandler(initializationPlace, declareStatic).invoke(getProject(), myEditor, myFile, null);
}
public void testForcedFieldType() throws Exception {
public void testForcedFieldType() {
configureByFile("/refactoring/introduceField/beforeForcedFieldType.java");
new MockIntroduceFieldHandler(BaseExpressionToFieldHandler.InitializationPlace.IN_CURRENT_METHOD, false){
new MockIntroduceFieldHandler(BaseExpressionToFieldHandler.InitializationPlace.IN_CURRENT_METHOD, false) {
@Override
protected PsiType getFieldType(PsiType type) {
return PsiPrimitiveType.INT;
return PsiType.INT;
}
}.invoke(getProject(), myEditor, myFile, null);
checkResultByFile("/refactoring/introduceField/afterForcedFieldType.java");
}
public void testRejectIntroduceFieldFromExprInThisCall() throws Exception {
public void testRejectIntroduceFieldFromExprInThisCall() {
configureByFile("/refactoring/introduceField/beforeRejectIntroduceFieldFromExprInThisCall.java");
try {
performRefactoring(BaseExpressionToFieldHandler.InitializationPlace.IN_FIELD_DECLARATION, false);
fail("Should not proceed");
}
catch (CommonRefactoringUtil.RefactoringErrorHintException e) {
assertEquals("Cannot perform refactoring.\n" +
"Invalid expression context.", e.getMessage());
assertEquals("Cannot perform refactoring.\nInvalid expression context.", e.getMessage());
}
}
public void testInConstructorEnclosingAnonymous() throws Exception {
public void testInConstructorEnclosingAnonymous() {
configureByFile("/refactoring/introduceField/beforeEnclosingAnonymous.java");
performRefactoring(BaseExpressionToFieldHandler.InitializationPlace.IN_CONSTRUCTOR, false);
checkResultByFile("/refactoring/introduceField/afterEnclosingAnonymous.java");
}
public void testLocalVarAnnotations() throws Exception {
public void testLocalVarAnnotations() {
configureByFile("/refactoring/introduceField/beforeLocalVarAnnotations.java");
performRefactoring(BaseExpressionToFieldHandler.InitializationPlace.IN_FIELD_DECLARATION, false);
checkResultByFile("/refactoring/introduceField/afterLocalVarAnnotations.java");
}
public void testFromLambdaExpr() throws Exception {
public void testFromLambdaExpr() {
configureByFile("/refactoring/introduceField/beforeFromLambdaExpr.java");
performRefactoring(BaseExpressionToFieldHandler.InitializationPlace.IN_FIELD_DECLARATION, false);
checkResultByFile("/refactoring/introduceField/afterFromLambdaExpr.java");
}
public void testStaticFieldInInnerClass() throws Exception {
public void testStaticFieldInInnerClass() {
configureByFile("/refactoring/introduceField/beforeStaticFieldInInnerClass.java");
new MockIntroduceFieldHandler(BaseExpressionToFieldHandler.InitializationPlace.IN_CURRENT_METHOD, false){
new MockIntroduceFieldHandler(BaseExpressionToFieldHandler.InitializationPlace.IN_CURRENT_METHOD, false) {
@Override
protected int getChosenClassIndex(List<PsiClass> classes) {
return 0;
@@ -166,5 +176,8 @@ public class IntroduceFieldInSameClassTest extends LightCodeInsightTestCase {
}.invoke(getProject(), myEditor, myFile, null);
checkResultByFile("/refactoring/introduceField/afterStaticFieldInInnerClass.java");
}
private static void performRefactoring(BaseExpressionToFieldHandler.InitializationPlace initializationPlace, boolean declareStatic) {
new MockIntroduceFieldHandler(initializationPlace, declareStatic).invoke(getProject(), myEditor, myFile, null);
}
}
@@ -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.
@@ -30,6 +30,7 @@ import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.JDOMUtil;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.testFramework.Parameterized;
import com.intellij.testFramework.TestRunnerUtil;
import com.intellij.util.PathUtil;
import com.intellij.util.containers.ContainerUtil;
@@ -38,6 +39,7 @@ import junit.framework.TestCase;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.model.serialization.JDomSerializationUtil;
@@ -68,13 +70,11 @@ public class PathManagerEx {
/**
* Caches test data lookup strategy by class.
*/
private static final ConcurrentMap<Class, TestDataLookupStrategy> CLASS_STRATEGY_CACHE =
ContainerUtil.newConcurrentMap();
private static final ConcurrentMap<Class, TestDataLookupStrategy> CLASS_STRATEGY_CACHE = ContainerUtil.newConcurrentMap();
private static final ConcurrentMap<String, Class> CLASS_CACHE = ContainerUtil.newConcurrentMap();
private static Set<String> ourCommunityModules;
private PathManagerEx() {
}
private PathManagerEx() { }
/**
* Enumerates possible strategies of test data lookup.
@@ -175,7 +175,8 @@ public class PathManagerEx {
/**
* @return path to 'community' project home irrespective of current project
*/
private static String getCommunityHomePath() {
@NotNull
public static String getCommunityHomePath() {
String path = PathManager.getHomePath();
return isLocatedInCommunity() ? path : path + File.separator + "community";
}
@@ -202,8 +203,8 @@ public class PathManagerEx {
}
/**
* Find file by its path relative to project home directory (the 'commmunity' project if {@code testClass} is located in the community project
* and the 'ultimate' project otherwise)
* Find file by its path relative to project home directory (the 'community' project if {@code testClass} is located
* in the community project, and the 'ultimate' project otherwise)
*/
public static File findFileUnderProjectHome(String relativePath, Class<? extends TestCase> testClass) {
String homePath = getHomePath(testClass);
@@ -340,8 +341,9 @@ public class PathManagerEx {
}
}
@SuppressWarnings("TestOnlyProblems")
private static boolean isJUnitClass(Class<?> clazz) {
return TestCase.class.isAssignableFrom(clazz) || TestRunnerUtil.isJUnit4TestClass(clazz) || com.intellij.testFramework.Parameterized.class.isAssignableFrom(clazz);
return TestCase.class.isAssignableFrom(clazz) || TestRunnerUtil.isJUnit4TestClass(clazz) || Parameterized.class.isAssignableFrom(clazz);
}
@Nullable
@@ -404,9 +406,9 @@ public class PathManagerEx {
}
try {
Element componentRoot = JDomSerializationUtil
.findComponent(JDOMUtil.loadDocument(modulesXml).getRootElement(), ModuleManagerImpl.COMPONENT_NAME);
ModuleManagerImpl.ModulePath[] files = ModuleManagerImpl.getPathsToModuleFiles(componentRoot);
Element element = JDomSerializationUtil.findComponent(JDOMUtil.loadDocument(modulesXml).getRootElement(), ModuleManagerImpl.COMPONENT_NAME);
assert element != null;
ModuleManagerImpl.ModulePath[] files = ModuleManagerImpl.getPathsToModuleFiles(element);
for (ModuleManagerImpl.ModulePath file : files) {
String name = FileUtil.getNameWithoutExtension(PathUtil.getFileName(file.getPath()));
ourCommunityModules.add(name);