com.intellij.codeInsight.AnnotationUtil Java Examples

The following examples show how to use com.intellij.codeInsight.AnnotationUtil. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PsiMethodExtractorUtils.java    From litho with Apache License 2.0 6 votes vote down vote up
private static List<AnnotationSpec> getExternalAnnotations(PsiParameter param) {
  PsiAnnotation[] annotationsOnParam = AnnotationUtil.getAllAnnotations(param, false, null);
  final List<AnnotationSpec> annotations = new ArrayList<>();

  for (PsiAnnotation annotationOnParam : annotationsOnParam) {
    if (annotationOnParam.getQualifiedName().startsWith(COMPONENTS_PACKAGE)) {
      continue;
    }

    final AnnotationSpec.Builder annotationSpec =
        AnnotationSpec.builder(PsiTypeUtils.guessClassName(annotationOnParam.getQualifiedName()));

    PsiNameValuePair[] paramAttributes = annotationOnParam.getParameterList().getAttributes();
    for (PsiNameValuePair attribute : paramAttributes) {
      annotationSpec.addMember(attribute.getName(), attribute.getDetachedValue().getText());
    }

    annotations.add(annotationSpec.build());
  }

  return annotations;
}
 
Example #2
Source File: PsiEventDeclarationsExtractor.java    From litho with Apache License 2.0 6 votes vote down vote up
public static ImmutableList<EventDeclarationModel> getEventDeclarations(PsiClass psiClass) {
  final PsiAnnotation layoutSpecAnnotation =
      AnnotationUtil.findAnnotation(psiClass, LayoutSpec.class.getName());
  if (layoutSpecAnnotation == null) {
    throw new RuntimeException("LayoutSpec annotation not found on class");
  }

  PsiAnnotationMemberValue psiAnnotationMemberValue =
      layoutSpecAnnotation.findAttributeValue("events");

  ArrayList<EventDeclarationModel> eventDeclarationModels = new ArrayList<>();
  if (psiAnnotationMemberValue instanceof PsiArrayInitializerMemberValue) {
    PsiArrayInitializerMemberValue value =
        (PsiArrayInitializerMemberValue) psiAnnotationMemberValue;
    for (PsiAnnotationMemberValue annotationMemberValue : value.getInitializers()) {
      PsiClassObjectAccessExpression accessExpression =
          (PsiClassObjectAccessExpression) annotationMemberValue;
      eventDeclarationModels.add(getEventDeclarationModel(accessExpression));
    }
  } else if (psiAnnotationMemberValue instanceof PsiClassObjectAccessExpression) {
    eventDeclarationModels.add(
        getEventDeclarationModel((PsiClassObjectAccessExpression) psiAnnotationMemberValue));
  }

  return ImmutableList.copyOf(eventDeclarationModels);
}
 
Example #3
Source File: ProducerUtils.java    From intellij with Apache License 2.0 6 votes vote down vote up
private static boolean isJUnit4Class(PsiClass psiClass) {
  String qualifiedName = JUnitUtil.RUN_WITH;
  if (AnnotationUtil.isAnnotated(psiClass, qualifiedName, true)) {
    return true;
  }
  // handle the case where RunWith and/or the current class isn't indexed
  PsiModifierList modifierList = psiClass.getModifierList();
  if (modifierList == null) {
    return false;
  }
  if (modifierList.hasAnnotation(qualifiedName)) {
    return true;
  }
  String shortName = StringUtil.getShortName(qualifiedName);
  return modifierList.hasAnnotation(shortName) && hasImport(psiClass, qualifiedName);
}
 
Example #4
Source File: PsiAnnotationProxyUtils.java    From litho with Apache License 2.0 6 votes vote down vote up
@Nullable
public static <T extends Annotation> T findAnnotationInHierarchy(
    PsiModifierListOwner listOwner, Class<T> annotationClass) {
  T basicProxy = AnnotationUtil.findAnnotationInHierarchy(listOwner, annotationClass);
  if (basicProxy == null) {
    return null;
  }

  T biggerProxy =
      (T)
          Proxy.newProxyInstance(
              annotationClass.getClassLoader(),
              new Class[] {annotationClass},
              new AnnotationProxyInvocationHandler(basicProxy, listOwner, annotationClass));

  return biggerProxy;
}
 
Example #5
Source File: PsiAnnotationProxyUtils.java    From litho with Apache License 2.0 6 votes vote down vote up
private Object invoke(Method method, Object[] args) throws IllegalAccessException {
  Class<?> returnType = method.getReturnType();
  if (returnType.isEnum()) {
    PsiAnnotation currentAnnotation =
        AnnotationUtil.findAnnotationInHierarchy(
            mListOwner, Collections.singleton(mAnnotationClass.getCanonicalName()));
    PsiReferenceExpression declaredValue =
        (PsiReferenceExpression) currentAnnotation.findAttributeValue(method.getName());
    if (declaredValue == null) {
      return method.getDefaultValue();
    }
    PsiIdentifier identifier = PsiTreeUtil.getChildOfType(declaredValue, PsiIdentifier.class);
    return Enum.valueOf((Class<Enum>) returnType, identifier.getText());
  }

  try {
    if (args == null) {
      return method.invoke(mStubbed);
    }
    return method.invoke(mStubbed, args);
  } catch (InvocationTargetException e) {
    return method.getDefaultValue();
  }
}
 
Example #6
Source File: SuggestionServiceImpl.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
private Optional<Suggestion> fromAction(final PsiAnnotation action, final String defaultFamily) {

        final String actionType = ofNullable(action.getNameReferenceElement())
                .map(PsiReference::resolve)
                .filter(PsiClass.class::isInstance)
                .map(e -> (PsiClass) e)
                .map(e -> AnnotationUtil.findAnnotation(e, true, ACTION_TYPE))
                .map(e -> e.findAttributeValue("value"))
                .map(v -> removeQuotes(v.getText()))
                .orElse("");

        return ofNullable(action.findAttributeValue("value"))
                .map(t -> removeQuotes(t.getText()))
                .map(actionId -> new Suggestion(
                        defaultFamily + ".actions." + actionType + "." + actionId + "." + DISPLAY_NAME,
                        Suggestion.Type.Action));
    }
 
Example #7
Source File: SuggestionServiceImpl.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
private Stream<Suggestion> fromComponent(final PsiClass clazz, final String defaultFamily) {
    final PsiAnnotation componentAnnotation =
            AnnotationUtil.findAnnotation(clazz, PARTITION_MAPPER, PROCESSOR, EMITTER);
    final PsiAnnotationMemberValue name = componentAnnotation.findAttributeValue("name");
    if (name == null || "\"\"".equals(name.getText())) {
        return Stream.empty();
    }

    final PsiAnnotationMemberValue familyValue = componentAnnotation.findAttributeValue("family");
    final String componentFamily = (familyValue == null || removeQuotes(familyValue.getText()).isEmpty()) ? null
            : removeQuotes(familyValue.getText());

    final String family = ofNullable(componentFamily).orElseGet(() -> ofNullable(defaultFamily).orElse(null));
    if (family == null) {
        return Stream.empty();
    }

    return Stream
            .of(new Suggestion(family + "." + DISPLAY_NAME, Suggestion.Type.Family), new Suggestion(
                    family + "." + removeQuotes(name.getText()) + "." + DISPLAY_NAME, Suggestion.Type.Component));
}
 
Example #8
Source File: PsiHelper.java    From android-butterknife-zelezny with Apache License 2.0 5 votes vote down vote up
@Nullable
public static PsiAnnotation getAnnotation(@NotNull final PsiElement element, @NotNull final String annotation) {
    if (element instanceof PsiModifierListOwner) {
        final PsiAnnotation[] annotations = AnnotationUtil.getAllAnnotations((PsiModifierListOwner) element, false, null);
        for (PsiAnnotation psiAnnotation : annotations) {
            if (annotation.equals(psiAnnotation.getQualifiedName())) {
                return psiAnnotation;
            }
        }
    }

    return null;
}
 
Example #9
Source File: CodeGenerator.java    From ParcelablePlease with Apache License 2.0 5 votes vote down vote up
/**
 * Add the @Parcelable annotation if not already annotated
 */
private void addAnnotation(PsiElementFactory elementFactory, JavaCodeStyleManager styleManager) {

  boolean annotated = AnnotationUtil.isAnnotated(psiClass, ANNOTATION_PACKAGE+"."+ANNOTATION_NAME, false);

  if (!annotated) {
    styleManager.shortenClassReferences(psiClass.getModifierList().addAnnotation(
        ANNOTATION_NAME));
  }
}
 
Example #10
Source File: BlazeJUnitTestFilterFlags.java    From intellij with Apache License 2.0 5 votes vote down vote up
private static String methodFilter(PsiMethod method, @Nullable String testSuffixRegex) {
  if (testSuffixRegex != null) {
    return method.getName() + testSuffixRegex;
  } else if (AnnotationUtil.findAnnotation(method, "Parameters") != null) {
    // Supports @junitparams.Parameters, an annotation that applies to an individual test method
    return method.getName() + JUnitParameterizedClassHeuristic.STANDARD_JUNIT_TEST_SUFFIX;
  } else {
    return method.getName();
  }
}
 
Example #11
Source File: BlazeJavaAbstractTestCaseConfigurationProducer.java    From intellij with Apache License 2.0 5 votes vote down vote up
private static PsiMethod getTestMethod(ConfigurationContext context) {
  PsiElement psi = context.getPsiLocation();
  if (psi instanceof PsiMethod
      && AnnotationUtil.isAnnotated((PsiMethod) psi, JUnitUtil.TEST_ANNOTATION, false)) {
    return (PsiMethod) psi;
  }
  List<PsiMethod> selectedMethods = TestMethodSelectionUtil.getSelectedMethods(context);
  return selectedMethods != null && selectedMethods.size() == 1 ? selectedMethods.get(0) : null;
}
 
Example #12
Source File: SqliteMagicImplicitUsageProvider.java    From sqlitemagic with Apache License 2.0 5 votes vote down vote up
private boolean checkAnnotations(PsiModifierListOwner element, Collection<String> annotations) {
  boolean result;
  result = AnnotationUtil.isAnnotated(element, annotations);
  if (!result) {
    final PsiClass containingClass = ((PsiMember) element).getContainingClass();
    if (null != containingClass) {
      result = AnnotationUtil.isAnnotated(containingClass, CLASS_ANNOTATIONS);
    }
  }
  return result;
}
 
Example #13
Source File: SuggestionServiceImpl.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
private Stream<Suggestion> fromConfiguration(final String family, final String configurationName,
        final PsiClass configClazz) {
    return Stream
            .concat(of(configClazz.getAllFields())
                    .filter(field -> AnnotationUtil.findAnnotation(field, OPTION) != null)
                    .flatMap(field -> {
                        final PsiAnnotation fOption = AnnotationUtil.findAnnotation(field, OPTION);
                        final PsiAnnotationMemberValue fOptionValue = fOption.findAttributeValue("value");

                        String fieldName = removeQuotes(fOptionValue.getText());
                        if (fieldName.isEmpty()) {
                            fieldName = field.getName();
                        }

                        final Suggestion displayNameSuggestion =
                                new Suggestion(configurationName + "." + fieldName + "." + DISPLAY_NAME,
                                        Suggestion.Type.Configuration);
                        final PsiType type = field.getType();
                        if ("java.lang.String".equals(type.getCanonicalText())) {
                            return Stream
                                    .of(displayNameSuggestion,
                                            new Suggestion(configurationName + "." + fieldName + "." + PLACEHOLDER,
                                                    Suggestion.Type.Configuration));
                        }
                        final PsiClass clazz = findClass(type);
                        if (clazz != null && clazz.isEnum()) {
                            return Stream
                                    .concat(Stream.of(displayNameSuggestion),
                                            Stream
                                                    .of(clazz.getFields())
                                                    .filter(PsiEnumConstant.class::isInstance)
                                                    .map(f -> clazz
                                                            .getName()
                                                            .substring(clazz.getName().lastIndexOf('.') + 1) + '.'
                                                            + f.getName() + "._displayName")
                                                    .map(v -> new Suggestion(v, Suggestion.Type.Configuration)));
                        }
                        return Stream.of(displayNameSuggestion);
                    }), extractConfigTypes(family, configClazz));
}
 
Example #14
Source File: SuggestionServiceImpl.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
private Stream<Suggestion> extractConfigTypes(final String family, final PsiClass configClass) {
    return Stream
            .of(DATA_STORE, DATA_SET)
            .map(a -> AnnotationUtil.findAnnotation(configClass, a))
            .filter(Objects::nonNull)
            .map(a -> new Suggestion(family + '.'
                    + a.getQualifiedName().substring(a.getQualifiedName().lastIndexOf('.') + 1).toLowerCase(ROOT)
                    + '.' + removeQuotes(a.findAttributeValue("value").getText()) + '.' + DISPLAY_NAME,
                    Suggestion.Type.Configuration));
}
 
Example #15
Source File: PsiEventDeclarationsExtractor.java    From litho with Apache License 2.0 5 votes vote down vote up
public static PsiType getReturnPsiType(@Nullable PsiClass eventClass) {
  return Optional.ofNullable(eventClass)
      .map(cls -> AnnotationUtil.findAnnotation(eventClass, Event.class.getTypeName()))
      .map(psiAnnotation -> psiAnnotation.findAttributeValue("returnType"))
      .filter(PsiClassObjectAccessExpression.class::isInstance)
      .map(PsiClassObjectAccessExpression.class::cast)
      .map(PsiClassObjectAccessExpression::getOperand)
      .map(PsiTypeElement::getType)
      .orElse(PsiType.VOID);
}
 
Example #16
Source File: PsiWorkingRangesMethodExtractor.java    From litho with Apache License 2.0 5 votes vote down vote up
private static SpecMethodModel<EventMethod, WorkingRangeDeclarationModel>
    generateWorkingRangeMethod(
        PsiMethod psiMethod,
        List<Class<? extends Annotation>> permittedInterStageInputAnnotations,
        String annotationQualifiedName) {
  final List<MethodParamModel> methodParams =
      getMethodParams(
          psiMethod,
          getPermittedMethodParamAnnotations(permittedInterStageInputAnnotations),
          permittedInterStageInputAnnotations,
          ImmutableList.of());

  PsiAnnotation psiAnnotation = AnnotationUtil.findAnnotation(psiMethod, annotationQualifiedName);
  PsiNameValuePair valuePair = AnnotationUtil.findDeclaredAttribute(psiAnnotation, "name");

  return SpecMethodModel.<EventMethod, WorkingRangeDeclarationModel>builder()
      .annotations(ImmutableList.of())
      .modifiers(PsiModifierExtractor.extractModifiers(psiMethod.getModifierList()))
      .name(psiMethod.getName())
      .returnTypeSpec(PsiTypeUtils.generateTypeSpec(psiMethod.getReturnType()))
      .typeVariables(ImmutableList.copyOf(getTypeVariables(psiMethod)))
      .methodParams(ImmutableList.copyOf(methodParams))
      .representedObject(psiMethod)
      .typeModel(
          new WorkingRangeDeclarationModel(
              valuePair.getLiteralValue(), valuePair.getNameIdentifier()))
      .build();
}
 
Example #17
Source File: PsiEventMethodExtractor.java    From litho with Apache License 2.0 5 votes vote down vote up
static ImmutableList<SpecMethodModel<EventMethod, EventDeclarationModel>> getOnEventMethods(
    PsiClass psiClass, List<Class<? extends Annotation>> permittedInterStageInputAnnotations) {
  final List<SpecMethodModel<EventMethod, EventDeclarationModel>> delegateMethods =
      new ArrayList<>();

  for (PsiMethod psiMethod : psiClass.getMethods()) {
    final PsiAnnotation onEventAnnotation =
        AnnotationUtil.findAnnotation(psiMethod, OnEvent.class.getName());
    if (onEventAnnotation == null) {
      continue;
    }

    PsiClassObjectAccessExpression accessExpression =
        (PsiClassObjectAccessExpression) onEventAnnotation.findAttributeValue("value");
    final List<MethodParamModel> methodParams =
        getMethodParams(
            psiMethod,
            EventMethodExtractor.getPermittedMethodParamAnnotations(
                permittedInterStageInputAnnotations),
            permittedInterStageInputAnnotations,
            ImmutableList.of());

    final SpecMethodModel<EventMethod, EventDeclarationModel> eventMethod =
        new SpecMethodModel<>(
            ImmutableList.of(),
            PsiModifierExtractor.extractModifiers(psiMethod.getModifierList()),
            psiMethod.getName(),
            PsiTypeUtils.generateTypeSpec(psiMethod.getReturnType()),
            ImmutableList.copyOf(getTypeVariables(psiMethod)),
            ImmutableList.copyOf(methodParams),
            psiMethod,
            PsiEventDeclarationsExtractor.getEventDeclarationModel(accessExpression));
    delegateMethods.add(eventMethod);
  }

  return ImmutableList.copyOf(delegateMethods);
}
 
Example #18
Source File: SuggestionServiceImpl.java    From component-runtime with Apache License 2.0 4 votes vote down vote up
@Override
public List<LookupElement> computeKeySuggestions(final Project project, final Module module,
        final String packageName, final List<String> containerElements, final String query) {
    final JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(project);
    final PsiPackage pkg = javaPsiFacade.findPackage(packageName);
    if (pkg == null) {
        return Collections.emptyList();
    }

    final String defaultFamily = getFamilyFromPackageInfo(pkg, module);
    return Stream
            .concat(Stream
                    .concat(of(pkg.getClasses())
                            .flatMap(this::unwrapInnerClasses)
                            .filter(c -> AnnotationUtil
                                    .findAnnotation(c, PARTITION_MAPPER, PROCESSOR, EMITTER) != null)
                            .flatMap(clazz -> fromComponent(clazz, defaultFamily)),
                            of(pkg.getClasses())
                                    .flatMap(this::unwrapInnerClasses)
                                    .filter(c -> of(c.getAllFields())
                                            .anyMatch(f -> AnnotationUtil.findAnnotation(f, OPTION) != null))
                                    .flatMap(c -> fromConfiguration(defaultFamily, c.getName(), c))),
                    of(pkg.getClasses())
                            .flatMap(this::unwrapInnerClasses)
                            .flatMap(c -> of(c.getMethods())
                                    .filter(m -> ACTIONS
                                            .stream()
                                            .anyMatch(action -> AnnotationUtil.findAnnotation(m, action) != null)))
                            .map(m -> ACTIONS
                                    .stream()
                                    .map(action -> AnnotationUtil.findAnnotation(m, action))
                                    .filter(Objects::nonNull)
                                    .findFirst()
                                    .get())
                            .map(action -> fromAction(action, defaultFamily))
                            .filter(Optional::isPresent)
                            .map(Optional::get))
            .filter(s -> containerElements.isEmpty() || !containerElements.contains(s.getKey()))
            .filter(s -> query == null || query.isEmpty() || s.getKey().startsWith(query))
            .map(s -> s.newLookupElement(withPriority(s.getType())))
            .collect(toList());
}
 
Example #19
Source File: PsiTriggerMethodExtractor.java    From litho with Apache License 2.0 4 votes vote down vote up
public static ImmutableList<SpecMethodModel<EventMethod, EventDeclarationModel>>
    getOnTriggerMethods(
        PsiClass psiClass,
        List<Class<? extends Annotation>> permittedInterStageInputAnnotations) {
  final List<SpecMethodModel<EventMethod, EventDeclarationModel>> delegateMethods =
      new ArrayList<>();

  for (PsiMethod psiMethod : psiClass.getMethods()) {
    final OnTrigger onTriggerAnnotation =
        PsiAnnotationProxyUtils.findAnnotationInHierarchy(psiMethod, OnTrigger.class);
    if (onTriggerAnnotation != null) {
      final List<MethodParamModel> methodParams =
          getMethodParams(
              psiMethod,
              TriggerMethodExtractor.getPermittedMethodParamAnnotations(
                  permittedInterStageInputAnnotations),
              permittedInterStageInputAnnotations,
              ImmutableList.<Class<? extends Annotation>>of());

      PsiAnnotation psiOnTriggerAnnotation =
          AnnotationUtil.findAnnotation(psiMethod, OnTrigger.class.getName());
      PsiNameValuePair valuePair =
          AnnotationUtil.findDeclaredAttribute(psiOnTriggerAnnotation, "value");
      PsiClassObjectAccessExpression valueClassExpression =
          (PsiClassObjectAccessExpression) valuePair.getValue();

      // Reuse EventMethodModel and EventDeclarationModel because we are capturing the same info
      TypeSpec returnTypeSpec = PsiTypeUtils.generateTypeSpec(psiMethod.getReturnType());
      final SpecMethodModel<EventMethod, EventDeclarationModel> eventMethod =
          new SpecMethodModel<EventMethod, EventDeclarationModel>(
              ImmutableList.<Annotation>of(),
              PsiModifierExtractor.extractModifiers(psiMethod.getModifierList()),
              psiMethod.getName(),
              returnTypeSpec,
              ImmutableList.copyOf(getTypeVariables(psiMethod)),
              ImmutableList.copyOf(methodParams),
              psiMethod,
              PsiEventDeclarationsExtractor.getEventDeclarationModel(valueClassExpression));
      delegateMethods.add(eventMethod);
    }
  }

  return ImmutableList.copyOf(delegateMethods);
}
 
Example #20
Source File: PsiAnnotationUtil.java    From sqlitemagic with Apache License 2.0 4 votes vote down vote up
public static boolean isAnnotatedWith(@NotNull PsiModifierListOwner psiModifierListOwner, @NotNull String qualifiedName) {
  return AnnotationUtil.isAnnotated(psiModifierListOwner, qualifiedName, false, true);
}
 
Example #21
Source File: HaxePullUpHelper.java    From intellij-haxe with Apache License 2.0 4 votes vote down vote up
private static void deleteOverrideAnnotationIfFound(PsiMethod oMethod) {
  final PsiAnnotation annotation = AnnotationUtil.findAnnotation(oMethod, Override.class.getName());
  if (annotation != null) {
    annotation.delete();
  }
}
 
Example #22
Source File: ProjectInfo.java    From IntelliJDeodorant with MIT License 4 votes vote down vote up
public boolean overridesMethod(final @NotNull PsiMethod psiMethod) {
    return AnnotationUtil.findAnnotation(psiMethod, "Override") == null &&
            psiMethod.findSuperMethods().length == 0;
}
 
Example #23
Source File: MethodObject.java    From IntelliJDeodorant with MIT License 4 votes vote down vote up
public boolean overridesMethod() {
    PsiMethod methodBinding = getMethodDeclaration();
    return !(AnnotationUtil.findAnnotation(methodBinding, "Override") == null &&
            methodBinding.findSuperMethods().length == 0);
}