static List<String> findAnnotations(PsiModifierListOwner element, boolean nullable) { if (overridesSuper(element)) { return Collections.emptyList(); } List<String> annotations = new ArrayList<>(); Project project = element.getProject(); PsiModifierList modifierList = element.getModifierList(); List<String> nullabilityAnnotations = nullable ? NullableNotNullManager.getInstance(project).getNullables() : NullableNotNullManager.getInstance(project).getNotNulls(); for (String notNullAnnotationFqn : nullabilityAnnotations) { PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); PsiAnnotation annotation = factory.createAnnotationFromText("@" + notNullAnnotationFqn, null); PsiAnnotation.TargetType[] targetTypes = getTargetsForLocation(modifierList); if (isNullabilityAnnotationForTypeQualifierDefault(annotation, nullable, targetTypes)) { annotations.add(annotation.getQualifiedName()); } } return annotations; }
@Override public void visitClass(UClass uClass) { //only check interface if(!uClass.isInterface()){ return; } Set<PropInfo> infos = getPropInfoWithSupers(uClass); if(infos.isEmpty()){ return; } //check method is relative of any field for(UMethod method: uClass.getMethods()){ PsiModifierList list = method.getModifierList(); PsiAnnotation pa_keep = list.findAnnotation(NAME_KEEP); PsiAnnotation pa_impl = list.findAnnotation(NAME_IMPL_METHOD); if (pa_keep == null && pa_impl == null) { if(!hasPropInfo(infos, method.getName())){ report(method); } } } }
public static PsiElement find( PsiModifierListOwner resolve, ManifoldPsiClass facade ) { PsiModifierList modifierList = resolve.getModifierList(); if( modifierList == null ) { return null; } PsiAnnotation[] annotations = modifierList.getAnnotations(); if( annotations.length > 0 && Objects.equals( annotations[0].getQualifiedName(), SourcePosition.class.getName() ) ) { return findTargetFeature( annotations[0], facade ); } if( !facade.getRawFiles().isEmpty() && DarkJavaTypeManifold.FILE_EXTENSIONS.stream() .anyMatch( ext -> ext.equalsIgnoreCase( facade.getRawFiles().get( 0 ).getVirtualFile().getExtension() ) ) ) { // DarkJava is Java return facade.getRawFiles().get( 0 ).findElementAt( resolve.getTextOffset() ); } return null; }
private void errrantThisOrExtension( PsiElement element, AnnotationHolder holder ) { if( element instanceof PsiModifierList ) { PsiModifierList mods = (PsiModifierList)element; PsiAnnotation annotation; if( (annotation = mods.findAnnotation( Extension.class.getName() )) != null || (annotation = mods.findAnnotation( This.class.getName() )) != null) { TextRange range = new TextRange( annotation.getTextRange().getStartOffset(), annotation.getTextRange().getEndOffset() ); //noinspection ConstantConditions holder.createErrorAnnotation( range, ExtIssueMsg.MSG_NOT_IN_EXTENSION_CLASS.get( ClassUtil.extractClassName( annotation.getQualifiedName() ) ) ); } } }
static PsiAnnotation findAnnotation(PsiElement element, String annotationName) { if (element instanceof PsiModifierListOwner) { PsiModifierListOwner listOwner = (PsiModifierListOwner) element; PsiModifierList modifierList = listOwner.getModifierList(); if (modifierList != null) { for (PsiAnnotation psiAnnotation : modifierList.getAnnotations()) { if (annotationName.equals(psiAnnotation.getQualifiedName())) { return psiAnnotation; } } } } return null; }
@Override protected String showDialog() { Project project = getProject(); final JavaPsiFacade facade = JavaPsiFacade.getInstance(project); Module module = myModuleSelector.getModule(); if (module == null) { Messages.showErrorDialog(project, ExecutionBundle.message("module.not.specified.error.text"), CommonBundle.getErrorTitle()); return null; } GlobalSearchScope scope = myIncludeLibraryClasses ? module.getModuleWithDependenciesAndLibrariesScope(true) : module.getModuleWithDependenciesScope(); PsiClass initialSelection = facade.findClass(getText(), scope); TreeClassChooser chooser = createTreeClassChooser(project, scope, initialSelection, new ClassFilter() { @Override public boolean isAccepted(PsiClass aClass) { if (aClass.isInterface()) return false; final PsiModifierList modifierList = aClass.getModifierList(); return modifierList == null || !modifierList.hasModifierProperty(PsiModifier.ABSTRACT); } }); if (chooser == null) return null; chooser.showDialog(); PsiClass selClass = chooser.getSelected(); return selClass != null ? selClass.getQualifiedName() : null; }
@Override protected void doFix(final Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { final PsiMethod method = PsiTreeUtil.getParentOfType(descriptor.getPsiElement(), PsiMethod.class); if (method != null) { final PsiModifierList modifierList = method.getModifierList(); if (!modifierList.hasModifierProperty(PsiModifier.PUBLIC)) { modifierList.setModifierProperty(PsiModifier.PUBLIC, true); } if (!modifierList.hasModifierProperty(PsiModifier.STATIC)) { modifierList.setModifierProperty(PsiModifier.STATIC, true); } if (method.getReturnType() != PsiType.VOID) { ChangeSignatureProcessor csp = new ChangeSignatureProcessor(project, method, false, PsiModifier.PUBLIC, method.getName(), PsiType.VOID, new ParameterInfoImpl[0]); csp.run(); } } }
@Override protected void doFix(Project project, ProblemDescriptor descriptor) { final PsiElement psiElement = descriptor.getPsiElement(); final Iterable<String> ids; if (psiElement instanceof PsiAnnotation) { ids = JavaSuppressionUtil.getInspectionIdsSuppressedInAnnotation((PsiModifierList)psiElement.getParent()); } else { final String suppressedIds = JavaSuppressionUtil.getSuppressedInspectionIdsIn(psiElement); if (suppressedIds == null) { return; } ids = StringUtil.tokenize(suppressedIds, ","); } for (String id : ids) { if (!myAllowedSuppressions.contains(id)) { myAllowedSuppressions.add(id); } } saveProfile(project); }
@Override public void visitAnnotation(GrAnnotation annotation) { super.visitAnnotation(annotation); PsiElement parent = annotation.getParent().getParent(); if (parent == null || !(parent instanceof GrTypeDefinition)) return; if (SINGLETON.equals(annotation.getQualifiedName())) { GrTypeDefinition typeDefinition = (GrTypeDefinition)parent; PsiMethod[] methods = typeDefinition.getMethods(); for (PsiMethod method : methods) { if (method.isConstructor()) { PsiModifierList modifierList = method.getModifierList(); if (modifierList.hasModifierProperty(PsiModifier.PUBLIC)) { registerClassError(typeDefinition); } } } } }
@Override public boolean checkApplicability(@NotNull AnnotationHolder holder, @NotNull GrAnnotation annotation) { final String qname = annotation.getQualifiedName(); if (!GroovyCommonClassNames.GROOVY_TRANSFORM_FIELD.equals(qname)) return false; checkScriptField(holder, annotation); PsiElement annoParent = annotation.getParent(); PsiElement ownerToUse = annoParent instanceof PsiModifierList ? annoParent.getParent() : annoParent; if (!(ownerToUse instanceof GrVariableDeclaration) || !PsiUtil.isLocalVariable(((GrVariableDeclaration)ownerToUse).getVariables()[0])) { return false; } if (!GrAnnotationImpl.isAnnotationApplicableTo(annotation, PsiAnnotation.TargetType.LOCAL_VARIABLE)) { GrCodeReferenceElement ref = annotation.getClassReference(); String target = JavaErrorMessages.message("annotation.target.LOCAL_VARIABLE"); String description = JavaErrorMessages.message("annotation.not.applicable", ref.getText(), target); holder.createErrorAnnotation(ref, description); } return true; }
public static boolean writeModifiers(StringBuilder builder, PsiModifierList modifierList, String[] modifiers, boolean writeAnnotations) { boolean wasAddedModifiers = false; if (writeAnnotations && modifierList instanceof GrModifierList) { GrAnnotation[] annotations = ((GrModifierList)modifierList).getAnnotations(); AnnotationGenerator annotationGenerator = new AnnotationGenerator(builder, new ExpressionContext(modifierList.getProject(), GroovyFile.EMPTY_ARRAY)); wasAddedModifiers = annotations.length > 0; for (GrAnnotation annotation : annotations) { annotation.accept(annotationGenerator); builder.append(' '); } } for (String modifierType : modifiers) { if (modifierList.hasModifierProperty(modifierType)) { builder.append(modifierType); builder.append(' '); wasAddedModifiers = true; } } return wasAddedModifiers; }
public static void writeClassModifiers(StringBuilder text, @Nullable PsiModifierList modifierList, boolean isInterface, boolean isEnum, boolean toplevel, boolean generateAnnotations) { if (modifierList == null) { text.append("public "); return; } List<String> allowedModifiers = new ArrayList<String>(); allowedModifiers.add(PsiModifier.PUBLIC); if (!isEnum) allowedModifiers.add(PsiModifier.FINAL); if (!toplevel) { allowedModifiers.addAll(Arrays.asList(PsiModifier.PROTECTED, PsiModifier.PRIVATE, PsiModifier.STATIC)); } if (!isInterface && !isEnum) { allowedModifiers.add(PsiModifier.ABSTRACT); } writeModifiers(text, modifierList, ArrayUtil.toStringArray(allowedModifiers), generateAnnotations); }
private boolean hasParameterName(PsiParameter psiParameter) { PsiModifierList modifierList = psiParameter.getModifierList(); if (modifierList == null) { return false; } PsiAnnotation annotation = modifierList.findAnnotation("javax.inject.Named"); if (annotation != null) { return true; } annotation = modifierList.findAnnotation(GctConstants.APP_ENGINE_ANNOTATION_NAMED); if (annotation != null) { return true; } return false; }
/** Checks if the supplied method is a public constructor with no parameters. */ public static boolean isPublicNullaryConstructor(PsiMethod method) { if (!method.isConstructor()) { return false; } if (method.getParameterList().getParametersCount() > 0) { return false; } PsiModifierList modifierList = method.getModifierList(); if (modifierList.hasModifierProperty(PsiModifier.PUBLIC)) { return true; } return false; }
private void initializePsiMethod(String methodName, String httpMethodValue, String pathValue) { PsiAnnotationMemberValue mockAnnotationMemberValue1 = mock(PsiAnnotationMemberValue.class); when(mockAnnotationMemberValue1.getText()).thenReturn(httpMethodValue); PsiAnnotationMemberValue mockAnnotationMemberValue2 = mock(PsiAnnotationMemberValue.class); when(mockAnnotationMemberValue2.getText()).thenReturn(pathValue); PsiAnnotation mockAnnotation = mock(PsiAnnotation.class); when(mockAnnotation.getQualifiedName()) .thenReturn(GctConstants.APP_ENGINE_ANNOTATION_API_METHOD); when(mockAnnotation.findAttributeValue("httpMethod")).thenReturn(mockAnnotationMemberValue1); when(mockAnnotation.findAttributeValue("path")).thenReturn(mockAnnotationMemberValue2); PsiAnnotation[] mockAnnotationsArray = {mockAnnotation}; PsiModifierList mockModifierList = mock(PsiModifierList.class); when(mockModifierList.getAnnotations()).thenReturn(mockAnnotationsArray); mockPsiMethod = mock(PsiMethod.class); when(mockPsiMethod.getModifierList()).thenReturn(mockModifierList); when(mockPsiMethod.getName()).thenReturn(methodName); when(mockPsiMethod.getContainingClass()).thenReturn(mockPsiClass); PsiParameterList mockParameterList = mock(PsiParameterList.class); when(mockParameterList.getParameters()).thenReturn(new PsiParameter[0]); when(mockPsiMethod.getParameterList()).thenReturn(mockParameterList); }
private void initializePsiClass(String apiResource, String apiClassResource) { PsiAnnotationMemberValue mockAnnotationMemberValue1 = mock(PsiAnnotationMemberValue.class); when(mockAnnotationMemberValue1.getText()).thenReturn(apiResource); PsiAnnotationMemberValue mockAnnotationMemberValue2 = mock(PsiAnnotationMemberValue.class); when(mockAnnotationMemberValue2.getText()).thenReturn(apiClassResource); // Mock @Api(resource = "") PsiAnnotation mockAnnotation1 = mock(PsiAnnotation.class); when(mockAnnotation1.getQualifiedName()).thenReturn(GctConstants.APP_ENGINE_ANNOTATION_API); when(mockAnnotation1.findAttributeValue("resource")).thenReturn(mockAnnotationMemberValue1); // Mock @ApiClass(resource = "") PsiAnnotation mockAnnotation2 = mock(PsiAnnotation.class); when(mockAnnotation2.getQualifiedName()) .thenReturn(GctConstants.APP_ENGINE_ANNOTATION_API_CLASS); when(mockAnnotation2.findAttributeValue("resource")).thenReturn(mockAnnotationMemberValue2); PsiAnnotation[] mockAnnotationsArray = {mockAnnotation1, mockAnnotation2}; PsiModifierList mockModifierList = mock(PsiModifierList.class); when(mockModifierList.getAnnotations()).thenReturn(mockAnnotationsArray); mockPsiClass = mock(PsiClass.class); when(mockPsiClass.getModifierList()).thenReturn(mockModifierList); }
@Override public final void invoke(@NotNull final Project project, final Editor editor, final PsiFile file) throws IncorrectOperationException { final PsiModifierList modifierList = element.getModifierList(); if(modifierList == null) { return; } for(final PsiAnnotation annotation : modifierList.getAnnotations()) { if(isAnnotation(annotation)) { annotation.delete(); } } }
@Override public boolean checkApplicability(@NotNull AnnotationHolder holder, @NotNull GrAnnotation annotation) { final String qname = annotation.getQualifiedName(); if (!GroovyCommonClassNames.GROOVY_TRANSFORM_FIELD.equals(qname)) return false; checkScriptField(holder, annotation); PsiElement annoParent = annotation.getParent(); PsiElement ownerToUse = annoParent instanceof PsiModifierList ? annoParent.getParent() : annoParent; if (!(ownerToUse instanceof GrVariableDeclaration) || !GroovyRefactoringUtil.isLocalVariable(((GrVariableDeclaration)ownerToUse).getVariables()[0])) { return false; } if (!GrAnnotationImpl.isAnnotationApplicableTo(annotation, PsiAnnotation.TargetType.LOCAL_VARIABLE)) { GrCodeReferenceElement ref = annotation.getClassReference(); String target = JavaErrorMessages.message("annotation.target.LOCAL_VARIABLE"); String description = JavaErrorMessages.message("annotation.not.applicable", ref.getText(), target); holder.createErrorAnnotation(ref, description); } return true; }
public void visitAnnotation(GrAnnotation annotation) { super.visitAnnotation(annotation); PsiElement parent = annotation.getParent().getParent(); if (parent == null || !(parent instanceof GrTypeDefinition)) return; if (SINGLETON.equals(annotation.getQualifiedName())) { GrTypeDefinition typeDefinition = (GrTypeDefinition)parent; PsiMethod[] methods = typeDefinition.getMethods(); for (PsiMethod method : methods) { if (method.isConstructor()) { PsiModifierList modifierList = method.getModifierList(); if (modifierList.hasModifierProperty(PsiModifier.PUBLIC)) { registerClassError(typeDefinition); } } } } }
@Override public void transformModifiers(@NotNull PsiModifierList modifierList, @NotNull final Set<String> modifiers) { final PsiModifierListOwner parentElement = PsiTreeUtil.getParentOfType(modifierList, PsiModifierListOwner.class, false); if (null != parentElement) { // FINAL if (!PsiAnnotationSearchUtil.isAnnotatedWith(parentElement, lombok.experimental.NonFinal.class)) { modifiers.add(PsiModifier.FINAL); } // PRIVATE if (modifierList.getParent() instanceof PsiField && // Visibility is only changed for package private fields hasPackagePrivateModifier(modifierList) && // except they are annotated with @PackagePrivate !PsiAnnotationSearchUtil.isAnnotatedWith(parentElement, lombok.experimental.PackagePrivate.class)) { modifiers.add(PsiModifier.PRIVATE); // IDEA _right now_ checks if other modifiers are set, and ignores PACKAGE_LOCAL but may as well clean it up modifiers.remove(PsiModifier.PACKAGE_LOCAL); } } }
@Override public boolean isSupported(@NotNull PsiModifierList modifierList) { PsiElement modifierListParent = modifierList.getParent(); if (modifierListParent instanceof PsiClass) { PsiClass parentClass = (PsiClass) modifierListParent; if (PsiAnnotationSearchUtil.isAnnotatedWith(parentClass, UtilityClass.class)) { return UtilityClassProcessor.validateOnRightType(parentClass, new ProblemNewBuilder()); } } if (!isElementFieldMethodOrInnerClass(modifierListParent)) { return false; } PsiClass searchableClass = PsiTreeUtil.getParentOfType(modifierListParent, PsiClass.class, true); return null != searchableClass && PsiAnnotationSearchUtil.isAnnotatedWith(searchableClass, UtilityClass.class) && UtilityClassProcessor.validateOnRightType(searchableClass, new ProblemNewBuilder()); }
@Override public void transformModifiers(@NotNull PsiModifierList modifierList, @NotNull final Set<String> modifiers) { final PsiElement parent = modifierList.getParent(); // FINAL if (parent instanceof PsiClass) { PsiClass psiClass = (PsiClass) parent; if (PsiAnnotationSearchUtil.isAnnotatedWith(psiClass, UtilityClass.class)) { modifiers.add(PsiModifier.FINAL); } } // STATIC if (isElementFieldMethodOrInnerClass(parent)) { modifiers.add(PsiModifier.STATIC); } }
@NotNull @SuppressWarnings("deprecation") protected Collection<PsiField> getAllNotInitializedAndNotStaticFields(@NotNull PsiClass psiClass) { Collection<PsiField> allNotInitializedNotStaticFields = new ArrayList<PsiField>(); final boolean classAnnotatedWithValue = PsiAnnotationSearchUtil.isAnnotatedWith(psiClass, Value.class, lombok.experimental.Value.class); for (PsiField psiField : psiClass.getFields()) { // skip fields named $ boolean addField = !psiField.getName().startsWith(LombokUtils.LOMBOK_INTERN_FIELD_MARKER); final PsiModifierList modifierList = psiField.getModifierList(); if (null != modifierList) { // skip static fields addField &= !modifierList.hasModifierProperty(PsiModifier.STATIC); boolean isFinal = isFieldFinal(psiField, modifierList, classAnnotatedWithValue); // skip initialized final fields addField &= (!isFinal || null == psiField.getInitializer()); } if (addField) { allNotInitializedNotStaticFields.add(psiField); } } return allNotInitializedNotStaticFields; }
@NotNull @SuppressWarnings("deprecation") public Collection<PsiField> getRequiredFields(@NotNull PsiClass psiClass) { Collection<PsiField> result = new ArrayList<PsiField>(); final boolean classAnnotatedWithValue = PsiAnnotationSearchUtil.isAnnotatedWith(psiClass, Value.class, lombok.experimental.Value.class); for (PsiField psiField : getAllNotInitializedAndNotStaticFields(psiClass)) { final PsiModifierList modifierList = psiField.getModifierList(); if (null != modifierList) { final boolean isFinal = isFieldFinal(psiField, modifierList, classAnnotatedWithValue); final boolean isNonNull = PsiAnnotationSearchUtil.isAnnotatedWith(psiField, LombokUtils.NON_NULL_PATTERN); // accept initialized final or nonnull fields if ((isFinal || isNonNull) && null == psiField.getInitializer()) { result.add(psiField); } } } return result; }
@NotNull public PsiMethod createGetterMethod(@NotNull PsiField psiField, @NotNull PsiClass psiClass, @NotNull String methodModifier) { final String methodName = getGetterName(psiField); LombokLightMethodBuilder method = new LombokLightMethodBuilder(psiField.getManager(), methodName) .withMethodReturnType(psiField.getType()) .withContainingClass(psiClass) .withNavigationElement(psiField); if (StringUtil.isNotEmpty(methodModifier)) { method.withModifier(methodModifier); } boolean isStatic = psiField.hasModifierProperty(PsiModifier.STATIC); if (isStatic) { method.withModifier(PsiModifier.STATIC); } method.withBody(PsiMethodUtil.createCodeBlockFromText(String.format("return %s.%s;", isStatic ? psiClass.getName() : "this", psiField.getName()), psiClass)); PsiModifierList modifierList = method.getModifierList(); copyAnnotations(psiField, modifierList, LombokUtils.NON_NULL_PATTERN, LombokUtils.NULLABLE_PATTERN, LombokUtils.DEPRECATED_PATTERN); addOnXAnnotations(PsiAnnotationSearchUtil.findAnnotation(psiField, Getter.class), modifierList, "onMethod"); return method; }
@NotNull public static Collection<String> collectAnnotationsToCopy(@NotNull PsiField psiField, final Pattern... patterns) { Collection<String> annotationsToCopy = new ArrayList<String>(); PsiModifierList modifierList = psiField.getModifierList(); if (null != modifierList) { for (PsiAnnotation psiAnnotation : modifierList.getAnnotations()) { final String annotationName = PsiAnnotationSearchUtil.getSimpleNameOf(psiAnnotation); for (Pattern pattern : patterns) { if (pattern.matcher(annotationName).matches()) { annotationsToCopy.add(psiAnnotation.getQualifiedName()); } } } } return annotationsToCopy; }
@Override protected void process(List<ClassMember> classMembers) { for (ClassMember classMember : classMembers) { final PsiElementClassMember elementClassMember = (PsiElementClassMember) classMember; PsiField psiField = (PsiField) elementClassMember.getPsiElement(); PsiMethod psiMethod = PropertyUtil.findPropertySetter(psiField.getContainingClass(), psiField.getName(), false, false); if (null != psiMethod) { PsiModifierList modifierList = psiField.getModifierList(); if (null != modifierList) { PsiAnnotation psiAnnotation = modifierList.addAnnotation(Setter.class.getName()); psiMethod.delete(); } } } }
private void addAnnotation(@NotNull PsiModifierListOwner targetElement, @NotNull PsiAnnotation newPsiAnnotation, @NotNull Class<? extends Annotation> annotationClass) { final PsiAnnotation presentAnnotation = PsiAnnotationSearchUtil.findAnnotation(targetElement, annotationClass); final Project project = targetElement.getProject(); final JavaCodeStyleManager javaCodeStyleManager = JavaCodeStyleManager.getInstance(project); javaCodeStyleManager.shortenClassReferences(newPsiAnnotation); if (null == presentAnnotation) { PsiModifierList modifierList = targetElement.getModifierList(); if (null != modifierList) { modifierList.addAfter(newPsiAnnotation, null); } } else { presentAnnotation.setDeclaredAttributeValue(PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME, newPsiAnnotation.findDeclaredAttributeValue(PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME)); } }
@Override protected void process(List<ClassMember> classMembers) { for (ClassMember classMember : classMembers) { final PsiElementClassMember elementClassMember = (PsiElementClassMember) classMember; PsiField psiField = (PsiField) elementClassMember.getPsiElement(); PsiMethod psiMethod = PropertyUtil.findPropertyGetter(psiField.getContainingClass(), psiField.getName(), false, false); if (null != psiMethod) { PsiModifierList modifierList = psiField.getModifierList(); if (null != modifierList) { PsiAnnotation psiAnnotation = modifierList.addAnnotation(Getter.class.getName()); // psiAnnotation.setDeclaredAttributeValue("value", ) psiMethod.delete(); } } } }
@Test public void findClass() throws Exception { final PsiClass psiBaseClass = mock(PsiClass.class); when(javaFileManager.findClass(BASE_CLASS, scope)).thenReturn(psiBaseClass); final PsiModifierList psiModifierList = mock(PsiModifierList.class); when(psiBaseClass.getModifierList()).thenReturn(psiModifierList); final PsiAnnotation psiAnnotation = mock(PsiAnnotation.class); when(psiModifierList.getAnnotations()).thenReturn(new PsiAnnotation[]{psiAnnotation}); when(psiAnnotation.getQualifiedName()).thenReturn(Builder.class.getName()); final PsiJavaCodeReferenceElement referenceElement = mock(PsiJavaCodeReferenceElement.class); when(psiAnnotation.getNameReferenceElement()).thenReturn(referenceElement); when(referenceElement.getReferenceName()).thenReturn(Builder.class.getSimpleName()); final PsiClass psiBuilderClass = mock(PsiClass.class); when(psiBaseClass.findInnerClassByName(eq(SOME_CLASS_BUILDER.substring(1)), anyBoolean())).thenReturn(psiBuilderClass); when(psiBuilderClass.getName()).thenReturn(SOME_CLASS_BUILDER.substring(1)); final PsiClass psiClass = elementFinder.findClass(BASE_CLASS + SOME_CLASS_BUILDER, scope); assertNotNull(psiClass); verify(javaFileManager).findClass(BASE_CLASS, scope); }
private void compareFields(PsiClass beforeClass, PsiClass afterClass) { PsiField[] beforeClassFields = beforeClass.getFields(); PsiField[] afterClassFields = afterClass.getFields(); LOG.debug("IntelliJ fields for class " + beforeClass.getName() + ": " + Arrays.toString(beforeClassFields)); LOG.debug("Theirs fields for class " + afterClass.getName() + ": " + Arrays.toString(afterClassFields)); assertEquals("Field counts are different for Class " + beforeClass.getName(), afterClassFields.length, beforeClassFields.length); for (PsiField afterField : afterClassFields) { boolean compared = false; final PsiModifierList afterFieldModifierList = afterField.getModifierList(); for (PsiField beforeField : beforeClassFields) { if (Objects.equal(afterField.getName(), beforeField.getName())) { final PsiModifierList beforeFieldModifierList = beforeField.getModifierList(); compareModifiers(beforeFieldModifierList, afterFieldModifierList); compareType(beforeField.getType(), afterField.getType(), afterField); compareInitializers(beforeField.getInitializer(), afterField.getInitializer()); compared = true; } } assertTrue("Fieldnames are not equal, Field (" + afterField.getName() + ") not found", compared); } }
private void compareModifiers(PsiModifierList beforeModifierList, PsiModifierList afterModifierList) { assertNotNull(beforeModifierList); assertNotNull(afterModifierList); if (shouldCompareModifiers()) { for (String modifier : PsiModifier.MODIFIERS) { boolean haveSameModifiers = afterModifierList.hasModifierProperty(modifier) == beforeModifierList.hasModifierProperty(modifier); final PsiMethod afterModifierListParent = PsiTreeUtil.getParentOfType(afterModifierList, PsiMethod.class); assertTrue(modifier + " Modifier is not equal for " + (null == afterModifierListParent ? "..." : afterModifierListParent.getText()), haveSameModifiers); } } if (shouldCompareAnnotations()) { Collection<String> beforeAnnotations = Lists.newArrayList(Collections2.transform(Arrays.asList(beforeModifierList.getAnnotations()), new QualifiedNameFunction())); Collection<String> afterAnnotations = Lists.newArrayList(Collections2.transform(Arrays.asList(afterModifierList.getAnnotations()), new QualifiedNameFunction())); Iterables.removeIf(beforeAnnotations, Predicates.containsPattern("lombok.*")); assertThat("Annotations are different", beforeAnnotations, equalTo(afterAnnotations)); } }
public static Set<String> getQualifierAnnotations(PsiElement element) { Set<String> qualifiedClasses = new HashSet<String>(); if (element instanceof PsiModifierListOwner) { PsiModifierListOwner listOwner = (PsiModifierListOwner) element; PsiModifierList modifierList = listOwner.getModifierList(); if (modifierList != null) { for (PsiAnnotation psiAnnotation : modifierList.getAnnotations()) { if (psiAnnotation != null && psiAnnotation.getQualifiedName() != null) { JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(element.getProject()); PsiClass psiClass = psiFacade.findClass(psiAnnotation.getQualifiedName(), GlobalSearchScope.projectScope(element.getProject())); if (hasAnnotation(psiClass, CLASS_QUALIFIER)) { qualifiedClasses.add(psiAnnotation.getQualifiedName()); } } } } } return qualifiedClasses; }
@PsiModifier.ModifierConstant public static String getVisibilityModifier(PsiModifierList list) { if(list == null) { return PsiModifier.PACKAGE_LOCAL; } for(@PsiModifier.ModifierConstant String modifier : visibilityModifiers) { if(list.hasModifierProperty(modifier)) { return modifier; } } return PsiModifier.PACKAGE_LOCAL; }
private static void analyzeConflictsOnUsages(UsageInfo[] usages, Set<PsiMember> membersToMove, String newVisibility, @NotNull PsiClass targetClass, Map<PsiMember, PsiModifierList> modifierListCopies, MultiMap<PsiElement, String> conflicts) { for(UsageInfo usage : usages) { if(!(usage instanceof MoveMembersUsageInfo)) { continue; } final MoveMembersUsageInfo usageInfo = (MoveMembersUsageInfo) usage; final PsiMember member = usageInfo.member; final MoveMemberHandler handler = MoveMemberHandler.EP_NAME.forLanguage(member.getLanguage()); if(handler != null) { handler.checkConflictsOnUsage(usageInfo, newVisibility, modifierListCopies.get(member), targetClass, membersToMove, conflicts); } } }
@Override protected String buildMethod(PsiClass psiClass, boolean isOverride, boolean needAll) { StringBuilder sb = new StringBuilder(); sb.append("public ").append(getMethodType()).append(mMethodName).append("(){"); PsiField[] fields; if (isOverride && !needAll) { sb.append(getMethodType()).append(mFieldName).append("=super.").append(mMethodName).append("();"); fields = psiClass.getFields(); } else { sb.append(getMethodType()).append(mFieldName).append("=new ").append(getParamsType()).append("();"); fields = psiClass.getAllFields(); } for (PsiField field : fields) { PsiModifierList modifiers = field.getModifierList(); if (!findIgnore(modifiers)) { if (findPostFiles(modifiers)) { sb.append("if (").append(field.getName()).append("!=null&&").append(field.getName()).append(".size()>0){"); sb.append("for (FileInput file : ").append(field.getName()).append(") {"); sb.append(mFieldName).append(".put(file.key + \"\\\"; filename=\\\"\" + file.filename,") .append(getValueType()).append(".create(").append(getMediaType()).append(".parse(guessMimeType(file.filename)), file.file));}}"); } else if (findPostFile(modifiers)) { sb.append("if (").append(field.getName()).append("!=null){"); sb.append(mFieldName).append(".put(").append(field.getName()).append(".key + \"\\\"; filename=\\\"\" + ").append(field.getName()) .append(".filename, ").append(getValueType()).append(".create(").append(getMediaType()).append(".parse(guessMimeType(") .append(field.getName()).append(".filename)),").append(field.getName()).append(".file));}"); } else { sb.append(mFieldName).append(".put(").append("\"").append(field.getName()).append("\", ").append(getValueType()) .append(".create(").append(getMediaType()).append(".parse(\"text/plain\"), String.valueOf(").append(field.getName()).append(")));"); } } } sb.append("return ").append(mFieldName).append(";}"); return sb.toString(); }
@Override protected String buildMethod(PsiClass psiClass, boolean isOverride, boolean needAll) { StringBuilder sb = new StringBuilder(); sb.append("public ").append(getMethodType()).append(mMethodName).append("(){"); PsiField[] fields; if (isOverride && !needAll) { sb.append(getMethodType()).append(mFieldName).append("=super.").append(mMethodName).append("();"); fields = psiClass.getFields(); } else { sb.append(getMethodType()).append(mFieldName).append("=new ").append(getMethodType()).append("().setType(MultipartBody.FORM);"); fields = psiClass.getAllFields(); } for (PsiField field : fields) { PsiModifierList modifiers = field.getModifierList(); if (!findIgnore(modifiers)) { if (findPostFiles(modifiers)) { sb.append("if (").append(field.getName()).append("!=null&&").append(field.getName()).append(".size()>0){"); sb.append("for (FileInput file : ").append(field.getName()).append(") {"); sb.append(mFieldName).append(".addFormDataPart(file.key, file.filename, ") .append(getValueType()).append(".create(").append(getMediaType()).append(".parse(guessMimeType(file.filename)), file.file));}}"); } else if (findPostFile(modifiers)) { sb.append("if (").append(field.getName()).append("!=null){"); sb.append(mFieldName).append(".addFormDataPart(").append(field.getName()).append(".key,") .append(field.getName()).append(".filename,").append(getValueType()).append(".create(").append(getMediaType()).append(".parse(guessMimeType(") .append(field.getName()).append(".filename)),").append(field.getName()).append(".file));}"); } else { sb.append(mFieldName).append(".addFormDataPart(\"").append(field.getName()).append("\", String.valueOf(").append(field.getName()).append("));"); } } } sb.append("return ").append(mFieldName).append(";}"); return sb.toString(); }