public static boolean fieldOrMethodIsAnnotated(PsiElement element, String annotationType) {
    final PsiElement e = findFieldOrMethod(element);

    if (e instanceof PsiField) {
      final PsiModifierList modifierList = ((PsiField) e).getModifierList();

      if (modifierList != null) {
        for (PsiAnnotation psiAnnotation : modifierList.getAnnotations()) {
          final String qualifiedName = psiAnnotation.getQualifiedName();
          if (qualifiedName != null && qualifiedName.equals(annotationType)) {
            return true;
          }
        }
      }
    } else if (e instanceof PsiMethod) {
      for (PsiAnnotation psiAnnotation : ((PsiMethod) e).getModifierList().getAnnotations()) {
        final String qualifiedName = psiAnnotation.getQualifiedName();
        if (qualifiedName != null && qualifiedName.equals(annotationType)) {
          return true;
        }
      }
    }

    return false;
  }
  @Override
  public void actionPerformed(AnActionEvent e) {
    final Project project = e.getProject();
    assert project != null;

    final PsiAnnotation annotation =
        KotlinSignatureUtil.findKotlinSignatureAnnotation(annotationOwner);
    assert annotation != null;

    if (annotation.getContainingFile() != annotationOwner.getContainingFile()) {
      // external annotation
      new WriteCommandAction(project) {
        @Override
        protected void run(@NotNull Result result) throws Throwable {
          ExternalAnnotationsManager.getInstance(project)
              .deannotate(annotationOwner, KOTLIN_SIGNATURE.asString());
          ExternalAnnotationsManager.getInstance(project)
              .deannotate(annotationOwner, OLD_KOTLIN_SIGNATURE.asString());
        }
      }.execute();
    } else {
      new WriteCommandAction(project) {
        @Override
        protected void run(@NotNull Result result) throws Throwable {
          annotation.delete();
        }
      }.execute();
    }

    KotlinSignatureUtil.refreshMarkers(project);
  }
  public static void fillCompletionVariants(
      CompletionParameters parameters, CompletionResultSet result) {
    if (parameters.getCompletionType() != CompletionType.BASIC
        && parameters.getCompletionType() != CompletionType.SMART) {
      return;
    }

    PsiElement position = parameters.getPosition();
    if (psiElement(PsiIdentifier.class)
        .withParents(PsiJavaCodeReferenceElement.class, PsiTypeElement.class, PsiClass.class)
        .andNot(JavaCompletionData.AFTER_DOT)
        .andNot(psiElement().afterLeaf(psiElement().inside(PsiModifierList.class)))
        .accepts(position)) {
      suggestGeneratedMethods(result, position);
    } else if (psiElement(PsiIdentifier.class)
        .withParents(
            PsiJavaCodeReferenceElement.class,
            PsiAnnotation.class,
            PsiModifierList.class,
            PsiClass.class)
        .accepts(position)) {
      PsiAnnotation annotation =
          ObjectUtils.assertNotNull(PsiTreeUtil.getParentOfType(position, PsiAnnotation.class));
      int annoStart = annotation.getTextRange().getStartOffset();
      suggestGeneratedMethods(
          result.withPrefixMatcher(
              annotation.getText().substring(0, parameters.getOffset() - annoStart)),
          position);
    }
  }
 private static void addSuppressAnnotation(
     final Project project, final GrModifierList modifierList, final String id)
     throws IncorrectOperationException {
   PsiAnnotation annotation =
       modifierList.findAnnotation(BatchSuppressManager.SUPPRESS_INSPECTIONS_ANNOTATION_NAME);
   final GrExpression toAdd =
       GroovyPsiElementFactory.getInstance(project).createExpressionFromText("\"" + id + "\"");
   if (annotation != null) {
     final PsiAnnotationMemberValue value = annotation.findDeclaredAttributeValue(null);
     if (value instanceof GrAnnotationArrayInitializer) {
       value.add(toAdd);
     } else if (value != null) {
       GrAnnotation anno =
           GroovyPsiElementFactory.getInstance(project).createAnnotationFromText("@A([])");
       final GrAnnotationArrayInitializer list =
           (GrAnnotationArrayInitializer) anno.findDeclaredAttributeValue(null);
       list.add(value);
       list.add(toAdd);
       annotation.setDeclaredAttributeValue(null, list);
     }
   } else {
     modifierList
         .addAnnotation(BatchSuppressManager.SUPPRESS_INSPECTIONS_ANNOTATION_NAME)
         .setDeclaredAttributeValue(null, toAdd);
   }
 }
  private static PsiField createField(
      PsiLocalVariable local, PsiType forcedType, String fieldName, boolean includeInitializer) {
    @NonNls StringBuilder pattern = new StringBuilder();
    pattern.append("private int ");
    pattern.append(fieldName);
    if (local.getInitializer() == null) {
      includeInitializer = false;
    }
    if (includeInitializer) {
      pattern.append("=0");
    }
    pattern.append(";");
    final Project project = local.getProject();
    PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
    try {
      PsiField field = factory.createFieldFromText(pattern.toString(), null);

      field.getTypeElement().replace(factory.createTypeElement(forcedType));
      if (includeInitializer) {
        PsiExpression initializer =
            RefactoringUtil.convertInitializerToNormalExpression(
                local.getInitializer(), forcedType);
        field.getInitializer().replace(initializer);
      }

      for (PsiAnnotation annotation : local.getModifierList().getAnnotations()) {
        field.getModifierList().add(annotation.copy());
      }
      return field;
    } catch (IncorrectOperationException e) {
      LOG.error(e);
      return null;
    }
  }
 /**
  * The parameter <code>allowIndirect</code> determines if the method should look for indirect
  * annotations, i.e. annotations which have themselves been annotated by the supplied annotation
  * name. Currently, this only allows one level of indirection and returns an array of
  * [base-annotation, indirect annotation]
  *
  * <p>The <code>annotationName</code> parameter is a pair of the target annotation class' fully
  * qualified name as a String and as a Set. This is done for performance reasons because the Set
  * is required by the {@link com.intellij.codeInsight.AnnotationUtil} utility class and allows to
  * avoid unnecessary object constructions.
  */
 public static PsiAnnotation[] getAnnotationsFromImpl(
     PsiModifierListOwner owner,
     Pair<String, ? extends Set<String>> annotationName,
     boolean allowIndirect,
     boolean inHierarchy) {
   final PsiAnnotation directAnnotation =
       inHierarchy
           ? AnnotationUtil.findAnnotationInHierarchy(owner, annotationName.second)
           : AnnotationUtil.findAnnotation(owner, annotationName.second);
   if (directAnnotation != null) {
     return new PsiAnnotation[] {directAnnotation};
   }
   if (allowIndirect) {
     final PsiAnnotation[] annotations = getAnnotations(owner, inHierarchy);
     for (PsiAnnotation annotation : annotations) {
       PsiJavaCodeReferenceElement nameReference = annotation.getNameReferenceElement();
       if (nameReference == null) continue;
       PsiElement resolved = nameReference.resolve();
       if (resolved instanceof PsiClass) {
         final PsiAnnotation psiAnnotation =
             AnnotationUtil.findAnnotationInHierarchy(
                 (PsiModifierListOwner) resolved, annotationName.second);
         if (psiAnnotation != null) {
           return new PsiAnnotation[] {psiAnnotation, annotation};
         }
       }
     }
   }
   return PsiAnnotation.EMPTY_ARRAY;
 }
 private static void deleteOverrideAnnotationIfFound(PsiMethod oMethod) {
   final PsiAnnotation annotation =
       AnnotationUtil.findAnnotation(oMethod, Override.class.getName());
   if (annotation != null) {
     annotation.delete();
   }
 }
 private static String buildAnnotationText(PsiAnnotation annotation) {
   final StringBuilder out = new StringBuilder("@");
   final PsiJavaCodeReferenceElement nameReferenceElement = annotation.getNameReferenceElement();
   assert nameReferenceElement != null;
   out.append(nameReferenceElement.getText());
   final PsiAnnotationParameterList parameterList = annotation.getParameterList();
   final PsiNameValuePair[] attributes = parameterList.getAttributes();
   if (attributes.length == 0) {
     return out.toString();
   }
   out.append('(');
   if (attributes.length == 1) {
     final PsiNameValuePair attribute = attributes[0];
     @NonNls final String name = attribute.getName();
     if (name != null && !PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME.equals(name)) {
       out.append(name).append('=');
     }
     buildAttributeValueText(attribute.getValue(), out);
   } else {
     for (int i = 0; i < attributes.length; i++) {
       final PsiNameValuePair attribute = attributes[i];
       if (i > 0) {
         out.append(',');
       }
       out.append(attribute.getName()).append('=');
       buildAttributeValueText(attribute.getValue(), out);
     }
   }
   out.append(')');
   return out.toString();
 }
  @Override
  public void computeUsages(List<PsiLiteralExpression> targets) {
    final Project project = myTarget.getProject();
    final PsiElement parent = myTarget.getParent().getParent();
    final LocalInspectionsPass pass =
        new LocalInspectionsPass(
            myFile,
            myFile.getViewProvider().getDocument(),
            parent.getTextRange().getStartOffset(),
            parent.getTextRange().getEndOffset(),
            LocalInspectionsPass.EMPTY_PRIORITY_RANGE,
            false,
            HighlightInfoProcessor.getEmpty());
    final InspectionProfile inspectionProfile =
        InspectionProjectProfileManager.getInstance(project).getInspectionProfile();
    for (PsiLiteralExpression target : targets) {
      final Object value = target.getValue();
      if (!(value instanceof String)) {
        continue;
      }
      InspectionToolWrapper toolWrapperById =
          ((InspectionProfileImpl) inspectionProfile).getToolById((String) value, target);
      if (!(toolWrapperById instanceof LocalInspectionToolWrapper)) {
        continue;
      }
      final LocalInspectionToolWrapper toolWrapper =
          ((LocalInspectionToolWrapper) toolWrapperById).createCopy();
      final InspectionManagerEx managerEx =
          (InspectionManagerEx) InspectionManager.getInstance(project);
      final GlobalInspectionContextImpl context = managerEx.createNewGlobalContext(false);
      toolWrapper.initialize(context);
      ((RefManagerImpl) context.getRefManager()).inspectionReadActionStarted();
      ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
      Runnable inspect =
          new Runnable() {
            @Override
            public void run() {
              pass.doInspectInBatch(
                  context,
                  managerEx,
                  Collections.<LocalInspectionToolWrapper>singletonList(toolWrapper));
            }
          };
      if (indicator == null) {
        ProgressManager.getInstance()
            .executeProcessUnderProgress(inspect, new ProgressIndicatorBase());
      } else {
        inspect.run();
      }

      for (HighlightInfo info : pass.getInfos()) {
        final PsiElement element =
            CollectHighlightsUtil.findCommonParent(myFile, info.startOffset, info.endOffset);
        if (element != null) {
          addOccurrence(element);
        }
      }
    }
  }
  public static HighlightInfo checkForeignInnerClassesUsed(final PsiAnnotation annotation) {
    final HighlightInfo[] infos = new HighlightInfo[1];
    final PsiAnnotationOwner owner = annotation.getOwner();
    if (owner instanceof PsiModifierList) {
      final PsiElement parent = ((PsiModifierList) owner).getParent();
      if (parent instanceof PsiClass) {
        annotation.accept(
            new JavaRecursiveElementWalkingVisitor() {
              @Override
              public void visitElement(PsiElement element) {
                if (infos[0] != null) return;
                super.visitElement(element);
              }

              @Override
              public void visitClassObjectAccessExpression(
                  PsiClassObjectAccessExpression expression) {
                super.visitClassObjectAccessExpression(expression);
                final PsiTypeElement operand = expression.getOperand();
                final PsiClass classType = PsiUtil.resolveClassInType(operand.getType());
                if (classType != null) {
                  checkAccessibility(expression, classType, HighlightUtil.formatClass(classType));
                }
              }

              @Override
              public void visitReferenceExpression(PsiReferenceExpression expression) {
                super.visitReferenceExpression(expression);
                final PsiElement resolve = expression.resolve();
                if (resolve instanceof PsiField) {
                  checkAccessibility(
                      expression,
                      (PsiMember) resolve,
                      HighlightUtil.formatField((PsiField) resolve));
                }
              }

              private void checkAccessibility(
                  PsiExpression expression, PsiMember resolve, String memberString) {
                if (resolve.hasModifierProperty(PsiModifier.PRIVATE)
                    && PsiTreeUtil.isAncestor(parent, resolve, true)) {
                  String description =
                      JavaErrorMessages.message(
                          "private.symbol",
                          memberString,
                          HighlightUtil.formatClass((PsiClass) parent));
                  infos[0] =
                      HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR)
                          .range(expression)
                          .descriptionAndTooltip(description)
                          .create();
                }
              }
            });
      }
    }
    return infos[0];
  }
 static PsiAnnotation findAnnotationOnMethod(PsiMethod psiMethod, String annotationName) {
   PsiModifierList modifierList = psiMethod.getModifierList();
   for (PsiAnnotation psiAnnotation : modifierList.getAnnotations()) {
     if (annotationName.equals(psiAnnotation.getQualifiedName())) {
       return psiAnnotation;
     }
   }
   return null;
 }
  public void setMirror(@NotNull TreeElement element) {
    setMirrorCheckingType(element, null);

    PsiAnnotation mirror = (PsiAnnotation) SourceTreeToPsiMap.treeElementToPsi(element);
    ((ClsElementImpl) getParameterList())
        .setMirror((TreeElement) SourceTreeToPsiMap.psiElementToTree(mirror.getParameterList()));
    ((ClsElementImpl) getNameReferenceElement())
        .setMirror(
            (TreeElement) SourceTreeToPsiMap.psiElementToTree(mirror.getNameReferenceElement()));
  }
 public static void deleteTypeAnnotations(@NotNull PsiTypeElement typeElement) {
   PsiElement left =
       PsiTreeUtil.skipSiblingsBackward(
           typeElement, PsiComment.class, PsiWhiteSpace.class, PsiTypeParameterList.class);
   if (left instanceof PsiModifierList) {
     for (PsiAnnotation annotation : ((PsiModifierList) left).getAnnotations()) {
       if (TYPE_ANNO_MARK.get(annotation) == Boolean.TRUE) {
         annotation.delete();
       }
     }
   }
 }
 public static void markTypeAnnotations(@NotNull PsiTypeElement typeElement) {
   PsiElement left =
       PsiTreeUtil.skipSiblingsBackward(
           typeElement, PsiComment.class, PsiWhiteSpace.class, PsiTypeParameterList.class);
   if (left instanceof PsiModifierList) {
     for (PsiAnnotation annotation : ((PsiModifierList) left).getAnnotations()) {
       if (AnnotationTargetUtil.isTypeAnnotation(annotation)) {
         annotation.putUserData(TYPE_ANNO_MARK, Boolean.TRUE);
       }
     }
   }
 }
    private static boolean containsError(PsiAnnotation annotation) {
      final PsiJavaCodeReferenceElement nameRef = annotation.getNameReferenceElement();
      if (nameRef == null) {
        return true;
      }
      final PsiClass aClass = (PsiClass) nameRef.resolve();
      if (aClass == null || !aClass.isAnnotationType()) {
        return true;
      }
      final Set<String> names = new HashSet<String>();
      final PsiAnnotationParameterList annotationParameterList = annotation.getParameterList();
      if (PsiUtilCore.hasErrorElementChild(annotationParameterList)) {
        return true;
      }
      final PsiNameValuePair[] attributes = annotationParameterList.getAttributes();
      for (PsiNameValuePair attribute : attributes) {
        final PsiReference reference = attribute.getReference();
        if (reference == null) {
          return true;
        }
        final PsiMethod method = (PsiMethod) reference.resolve();
        if (method == null) {
          return true;
        }
        final PsiAnnotationMemberValue value = attribute.getValue();
        if (value == null || PsiUtilCore.hasErrorElementChild(value)) {
          return true;
        }
        if (value instanceof PsiAnnotation && containsError((PsiAnnotation) value)) {
          return true;
        }
        if (!hasCorrectType(value, method.getReturnType())) {
          return true;
        }
        final String name = attribute.getName();
        if (!names.add(name != null ? name : PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME)) {
          return true;
        }
      }

      for (PsiMethod method : aClass.getMethods()) {
        if (!(method instanceof PsiAnnotationMethod)) {
          continue;
        }
        final PsiAnnotationMethod annotationMethod = (PsiAnnotationMethod) method;
        if (annotationMethod.getDefaultValue() == null
            && !names.contains(annotationMethod.getName())) {
          return true; // missing a required argument
        }
      }
      return false;
    }
 public static PsiAnnotation getAnnotationFromElement(PsiElement element, String annotationType) {
   if (element instanceof PsiModifierListOwner) {
     final PsiModifierList modifierList = ((PsiModifierListOwner) element).getModifierList();
     if (modifierList != null) {
       for (PsiAnnotation annotation : modifierList.getAnnotations()) {
         if (annotationType.equals(annotation.getQualifiedName())) {
           return annotation;
         }
       }
     }
   }
   return null;
 }
 private void makeStatic(PsiMethod member) {
   final PsiAnnotation overrideAnnotation =
       AnnotationUtil.findAnnotation(member, CommonClassNames.JAVA_LANG_OVERRIDE);
   if (overrideAnnotation != null) {
     overrideAnnotation.delete();
   }
   setupTypeParameterList(member);
   // Add static modifier
   final PsiModifierList modifierList = member.getModifierList();
   modifierList.setModifierProperty(PsiModifier.STATIC, true);
   modifierList.setModifierProperty(PsiModifier.FINAL, false);
   modifierList.setModifierProperty(PsiModifier.DEFAULT, false);
 }
  public static PsiAnnotation findAnnotation(
      @NotNull PsiAnnotationOwner modifierList, @NotNull String qualifiedName) {
    final String shortName = StringUtil.getShortName(qualifiedName);
    PsiAnnotation[] annotations = modifierList.getAnnotations();
    for (PsiAnnotation annotation : annotations) {
      final PsiJavaCodeReferenceElement referenceElement = annotation.getNameReferenceElement();
      if (referenceElement != null && shortName.equals(referenceElement.getReferenceName())) {
        if (qualifiedName.equals(annotation.getQualifiedName())) return annotation;
      }
    }

    return null;
  }
  public static boolean typeIsAnnotated(PsiClass psiClass, String annotationType) {
    final PsiModifierList modifierList = psiClass.getModifierList();

    if (modifierList != null) {
      for (PsiAnnotation psiAnnotation : modifierList.getAnnotations()) {
        final String qualifiedName = psiAnnotation.getQualifiedName();
        if (qualifiedName != null && qualifiedName.equals(annotationType)) {
          return true;
        }
      }
    }
    return false;
  }
 private static void deleteOverrideAnnotationIfFound(PsiMethod oMethod) {
   final PsiAnnotation annotation =
       AnnotationUtil.findAnnotation(oMethod, CommonClassNames.JAVA_LANG_OVERRIDE);
   if (annotation != null) {
     PsiElement prev = annotation.getPrevSibling();
     PsiElement next = annotation.getNextSibling();
     if ((prev == null || org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil.isLineFeed(prev))
         && org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil.isLineFeed(next)) {
       next.delete();
     }
     annotation.delete();
   }
 }
Example #21
0
  /**
   * Returns a set of targets where the given annotation may be applied, or {@code null} when the
   * type is not a valid annotation.
   */
  @Nullable
  public static Set<TargetType> getAnnotationTargets(@NotNull PsiClass annotationType) {
    if (!annotationType.isAnnotationType()) return null;
    PsiModifierList modifierList = annotationType.getModifierList();
    if (modifierList == null) return null;
    PsiAnnotation target =
        modifierList.findAnnotation(CommonClassNames.JAVA_LANG_ANNOTATION_TARGET);
    if (target == null)
      return DEFAULT_TARGETS; // if omitted it is applicable to all but Java 8
                              // TYPE_USE/TYPE_PARAMETERS targets

    return extractRequiredAnnotationTargets(target.findAttributeValue(null));
  }
Example #22
0
 static boolean isAnnotationEditable(@NotNull PsiElement element) {
   PsiModifierListOwner annotationOwner = getAnnotationOwner(element);
   PsiAnnotation annotation = findKotlinSignatureAnnotation(element);
   assert annotation != null;
   if (annotation.getContainingFile() == annotationOwner.getContainingFile()) {
     return annotation.isWritable();
   } else {
     ExternalAnnotationsManager annotationsManager =
         ExternalAnnotationsManager.getInstance(element.getProject());
     return annotationsManager.isExternalAnnotationWritable(
         annotationOwner, KOTLIN_SIGNATURE_ANNOTATION);
   }
 }
 @Override
 protected void doFix(Project project, ProblemDescriptor descriptor)
     throws IncorrectOperationException {
   final PsiElement element = descriptor.getPsiElement();
   final PsiAnnotation annotation = PsiTreeUtil.getParentOfType(element, PsiAnnotation.class);
   if (annotation == null) {
     return;
   }
   final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
   final String annotationText = buildAnnotationText(annotation);
   final PsiAnnotation newAnnotation = factory.createAnnotationFromText(annotationText, element);
   annotation.replace(newAnnotation);
 }
  @Nullable
  public static List<String> findTestDataFiles(@NotNull DataContext context) {
    final PsiMethod method = findTargetMethod(context);
    if (method == null) {
      return null;
    }
    final String name = method.getName();

    if (name.startsWith("test")) {
      String testDataPath =
          TestDataLineMarkerProvider.getTestDataBasePath(method.getContainingClass());
      final TestDataReferenceCollector collector =
          new TestDataReferenceCollector(testDataPath, name.substring(4));
      return collector.collectTestDataReferences(method);
    }

    final Location<?> location = Location.DATA_KEY.getData(context);
    if (location instanceof PsiMemberParameterizedLocation) {
      PsiClass containingClass = ((PsiMemberParameterizedLocation) location).getContainingClass();
      if (containingClass == null) {
        containingClass =
            PsiTreeUtil.getParentOfType(location.getPsiElement(), PsiClass.class, false);
      }
      if (containingClass != null) {
        final PsiAnnotation annotation =
            AnnotationUtil.findAnnotationInHierarchy(
                containingClass, Collections.singleton(JUnitUtil.RUN_WITH));
        if (annotation != null) {
          final PsiAnnotationMemberValue memberValue = annotation.findAttributeValue("value");
          if (memberValue instanceof PsiClassObjectAccessExpression) {
            final PsiTypeElement operand =
                ((PsiClassObjectAccessExpression) memberValue).getOperand();
            if (operand.getType().equalsToText(Parameterized.class.getName())) {
              final String testDataPath =
                  TestDataLineMarkerProvider.getTestDataBasePath(containingClass);
              final String paramSetName =
                  ((PsiMemberParameterizedLocation) location).getParamSetName();
              final String baseFileName =
                  StringUtil.trimEnd(StringUtil.trimStart(paramSetName, "["), "]");
              final ProjectFileIndex fileIndex =
                  ProjectRootManager.getInstance(containingClass.getProject()).getFileIndex();
              return TestDataGuessByExistingFilesUtil.suggestTestDataFiles(
                  fileIndex, baseFileName, testDataPath, containingClass);
            }
          }
        }
      }
    }

    return null;
  }
  private static PsiAnnotation createNewAnnotation(
      final Project project,
      final Editor editor,
      final PsiElement container,
      @Nullable final PsiAnnotation annotation,
      final String id) {

    if (annotation != null) {
      final String currentSuppressedId = "\"" + id + "\"";
      if (!annotation.getText().contains("{")) {
        final PsiNameValuePair[] attributes = annotation.getParameterList().getAttributes();
        if (attributes.length == 1) {
          final String suppressedWarnings = attributes[0].getText();
          if (suppressedWarnings.contains(currentSuppressedId)) return null;
          return JavaPsiFacade.getInstance(project)
              .getElementFactory()
              .createAnnotationFromText(
                  "@"
                      + SuppressManager.SUPPRESS_INSPECTIONS_ANNOTATION_NAME
                      + "({"
                      + suppressedWarnings
                      + ", "
                      + currentSuppressedId
                      + "})",
                  container);
        }
      } else {
        final int curlyBraceIndex = annotation.getText().lastIndexOf("}");
        if (curlyBraceIndex > 0) {
          final String oldSuppressWarning = annotation.getText().substring(0, curlyBraceIndex);
          if (oldSuppressWarning.contains(currentSuppressedId)) return null;
          return JavaPsiFacade.getInstance(project)
              .getElementFactory()
              .createAnnotationFromText(
                  oldSuppressWarning + ", " + currentSuppressedId + "})", container);
        } else if (!ApplicationManager.getApplication().isUnitTestMode() && editor != null) {
          Messages.showErrorDialog(
              editor.getComponent(),
              InspectionsBundle.message(
                  "suppress.inspection.annotation.syntax.error", annotation.getText()));
        }
      }
    } else {
      return JavaPsiFacade.getInstance(project)
          .getElementFactory()
          .createAnnotationFromText(
              "@" + SuppressManager.SUPPRESS_INSPECTIONS_ANNOTATION_NAME + "(\"" + id + "\")",
              container);
    }
    return null;
  }
 private static boolean hasAnnotation(
     PsiModifierListOwner modifierListOwner, String qualifiedName) {
   PsiModifierList modifierList = modifierListOwner.getModifierList();
   if (modifierList != null) {
     for (PsiAnnotation annotation : modifierList.getAnnotations()) {
       if (annotation instanceof ClsAnnotationImpl) {
         if (qualifiedName.equals(annotation.getQualifiedName())) {
           return true;
         }
       }
     }
   }
   return false;
 }
 private static boolean isAnnotationRepeatedTwice(
     @NotNull PsiAnnotationOwner owner, @NotNull String qualifiedName) {
   int count = 0;
   for (PsiAnnotation annotation : owner.getAnnotations()) {
     PsiJavaCodeReferenceElement nameRef = annotation.getNameReferenceElement();
     if (nameRef == null) continue;
     PsiElement resolved = nameRef.resolve();
     if (!(resolved instanceof PsiClass)
         || !qualifiedName.equals(((PsiClass) resolved).getQualifiedName())) continue;
     count++;
     if (count == 2) return true;
   }
   return false;
 }
 private static Collection<PsiClass> getClassesByAnnotation(
     String annotationName, Project project, GlobalSearchScope scope) {
   Collection<PsiClass> classes = Sets.newHashSet();
   Collection<PsiAnnotation> annotations =
       JavaAnnotationIndex.getInstance().get(annotationName, project, scope);
   for (PsiAnnotation annotation : annotations) {
     PsiModifierList modifierList = (PsiModifierList) annotation.getParent();
     PsiElement owner = modifierList.getParent();
     if (owner instanceof PsiClass) {
       classes.add((PsiClass) owner);
     }
   }
   return classes;
 }
Example #29
0
 @Nullable
 static PsiAnnotation findKotlinSignatureAnnotation(@NotNull PsiElement element) {
   if (!(element instanceof PsiModifierListOwner)) return null;
   PsiModifierListOwner annotationOwner = getAnnotationOwner(element);
   PsiAnnotation ownAnnotation =
       PsiBasedExternalAnnotationResolver.findOwnAnnotation(annotationOwner, KOTLIN_SIGNATURE);
   PsiAnnotation annotation =
       ownAnnotation != null
           ? ownAnnotation
           : PsiBasedExternalAnnotationResolver.findExternalAnnotation(
               annotationOwner, KOTLIN_SIGNATURE.getFqName());
   if (annotation == null) return null;
   if (annotation.getParameterList().getAttributes().length == 0) return null;
   return annotation;
 }
 public static PsiClass getProviderClass(final PsiElement element, final PsiClass topLevelClass) {
   final PsiAnnotation annotation = PsiTreeUtil.getParentOfType(element, PsiAnnotation.class);
   if (annotation != null) {
     final PsiAnnotationMemberValue value =
         annotation.findDeclaredAttributeValue("dataProviderClass");
     if (value instanceof PsiClassObjectAccessExpression) {
       final PsiTypeElement operand = ((PsiClassObjectAccessExpression) value).getOperand();
       final PsiClass psiClass = PsiUtil.resolveClassInType(operand.getType());
       if (psiClass != null) {
         return psiClass;
       }
     }
   }
   return topLevelClass;
 }