private static void processCallerMethod(
      JavaChangeInfo changeInfo,
      PsiMethod caller,
      PsiMethod baseMethod,
      boolean toInsertParams,
      boolean toInsertThrows)
      throws IncorrectOperationException {
    LOG.assertTrue(toInsertParams || toInsertThrows);
    if (toInsertParams) {
      List<PsiParameter> newParameters = new ArrayList<PsiParameter>();
      ContainerUtil.addAll(newParameters, caller.getParameterList().getParameters());
      final JavaParameterInfo[] primaryNewParms = changeInfo.getNewParameters();
      PsiSubstitutor substitutor =
          baseMethod == null
              ? PsiSubstitutor.EMPTY
              : ChangeSignatureProcessor.calculateSubstitutor(caller, baseMethod);
      for (JavaParameterInfo info : primaryNewParms) {
        if (info.getOldIndex() < 0)
          newParameters.add(createNewParameter(changeInfo, info, substitutor));
      }
      PsiParameter[] arrayed = newParameters.toArray(new PsiParameter[newParameters.size()]);
      boolean[] toRemoveParm = new boolean[arrayed.length];
      Arrays.fill(toRemoveParm, false);
      resolveParameterVsFieldsConflicts(arrayed, caller, caller.getParameterList(), toRemoveParm);
    }

    if (toInsertThrows) {
      List<PsiJavaCodeReferenceElement> newThrowns = new ArrayList<PsiJavaCodeReferenceElement>();
      final PsiReferenceList throwsList = caller.getThrowsList();
      ContainerUtil.addAll(newThrowns, throwsList.getReferenceElements());
      final ThrownExceptionInfo[] primaryNewExns = changeInfo.getNewExceptions();
      for (ThrownExceptionInfo thrownExceptionInfo : primaryNewExns) {
        if (thrownExceptionInfo.getOldIndex() < 0) {
          final PsiClassType type =
              (PsiClassType) thrownExceptionInfo.createType(caller, caller.getManager());
          final PsiJavaCodeReferenceElement ref =
              JavaPsiFacade.getInstance(caller.getProject())
                  .getElementFactory()
                  .createReferenceElementByType(type);
          newThrowns.add(ref);
        }
      }
      PsiJavaCodeReferenceElement[] arrayed =
          newThrowns.toArray(new PsiJavaCodeReferenceElement[newThrowns.size()]);
      boolean[] toRemoveParm = new boolean[arrayed.length];
      Arrays.fill(toRemoveParm, false);
      ChangeSignatureUtil.synchronizeList(
          throwsList, Arrays.asList(arrayed), ThrowsList.INSTANCE, toRemoveParm);
    }
  }
 @NotNull
 private XmlAttribute[] calculateAttributes(final Map<String, String> attributesValueMap) {
   final List<XmlAttribute> result = new ArrayList<XmlAttribute>(10);
   processChildren(
       new PsiElementProcessor() {
         public boolean execute(@NotNull PsiElement element) {
           if (element instanceof XmlAttribute) {
             XmlAttribute attribute = (XmlAttribute) element;
             result.add(attribute);
             cacheOneAttributeValue(attribute.getName(), attribute.getValue(), attributesValueMap);
             myHaveNamespaceDeclarations =
                 myHaveNamespaceDeclarations || attribute.isNamespaceDeclaration();
           } else if (element instanceof XmlToken
               && ((XmlToken) element).getTokenType() == XmlTokenType.XML_TAG_END) {
             return false;
           }
           return true;
         }
       });
   if (result.isEmpty()) {
     return XmlAttribute.EMPTY_ARRAY;
   } else {
     return ContainerUtil.toArray(result, new XmlAttribute[result.size()]);
   }
 }
  @NotNull
  public PsiReference[] getReferences() {
    ProgressManager.checkCanceled();
    final ASTNode startTagName = XmlChildRole.START_TAG_NAME_FINDER.findChild(this);
    if (startTagName == null) return PsiReference.EMPTY_ARRAY;
    final ASTNode endTagName = XmlChildRole.CLOSING_TAG_NAME_FINDER.findChild(this);
    List<PsiReference> refs = new ArrayList<PsiReference>();
    String prefix = getNamespacePrefix();

    TagNameReference startTagRef =
        TagNameReference.createTagNameReference(this, startTagName, true);
    refs.add(startTagRef);
    if (prefix.length() > 0) {
      refs.add(createPrefixReference(startTagName, prefix, startTagRef));
    }
    if (endTagName != null) {
      TagNameReference endTagRef = TagNameReference.createTagNameReference(this, endTagName, false);
      refs.add(endTagRef);
      prefix = XmlUtil.findPrefixByQualifiedName(endTagName.getText());
      if (StringUtil.isNotEmpty(prefix)) {
        refs.add(createPrefixReference(endTagName, prefix, endTagRef));
      }
    }

    // ArrayList.addAll() makes a clone of the collection
    //noinspection ManualArrayToCollectionCopy
    for (PsiReference ref :
        ReferenceProvidersRegistry.getReferencesFromProviders(this, XmlTag.class)) {
      refs.add(ref);
    }

    return ContainerUtil.toArray(refs, new PsiReference[refs.size()]);
  }
  @NotNull
  private static PsiSubstitutor replaceVariables(Collection<InferenceVariable> inferenceVariables) {
    final List<InferenceVariable> targetVars = new ArrayList<InferenceVariable>();
    PsiSubstitutor substitutor = PsiSubstitutor.EMPTY;
    final InferenceVariable[] oldVars =
        inferenceVariables.toArray(new InferenceVariable[inferenceVariables.size()]);
    for (InferenceVariable variable : oldVars) {
      final InferenceVariable newVariable =
          new InferenceVariable(
              variable.getCallContext(), variable.getParameter(), variable.getName());
      substitutor =
          substitutor.put(
              variable,
              JavaPsiFacade.getElementFactory(variable.getProject()).createType(newVariable));
      targetVars.add(newVariable);
      if (variable.isThrownBound()) {
        newVariable.setThrownBound();
      }
    }

    for (int i = 0; i < targetVars.size(); i++) {
      InferenceVariable var = targetVars.get(i);
      for (InferenceBound boundType : InferenceBound.values()) {
        for (PsiType bound : oldVars[i].getBounds(boundType)) {
          var.addBound(substitutor.substitute(bound), boundType, null);
        }
      }
    }
    return substitutor;
  }
  private void processUsagesPerFile(UsageInfo[] usages) {
    Map<PsiFile, List<EncapsulateFieldUsageInfo>> usagesInFiles =
        new HashMap<PsiFile, List<EncapsulateFieldUsageInfo>>();
    for (UsageInfo usage : usages) {
      PsiElement element = usage.getElement();
      if (element == null) continue;
      final PsiFile file = element.getContainingFile();
      List<EncapsulateFieldUsageInfo> usagesInFile = usagesInFiles.get(file);
      if (usagesInFile == null) {
        usagesInFile = new ArrayList<EncapsulateFieldUsageInfo>();
        usagesInFiles.put(file, usagesInFile);
      }
      usagesInFile.add(((EncapsulateFieldUsageInfo) usage));
    }

    for (List<EncapsulateFieldUsageInfo> usageInfos : usagesInFiles.values()) {
      // this is to avoid elements to become invalid as a result of processUsage
      final EncapsulateFieldUsageInfo[] infos =
          usageInfos.toArray(new EncapsulateFieldUsageInfo[usageInfos.size()]);
      CommonRefactoringUtil.sortDepthFirstRightLeftOrder(infos);

      for (EncapsulateFieldUsageInfo info : infos) {
        EncapsulateFieldHelper helper =
            EncapsulateFieldHelper.getHelper(info.getElement().getLanguage());
        helper.processUsage(
            info,
            myDescriptor,
            myNameToSetter.get(info.getFieldDescriptor().getSetterName()),
            myNameToGetter.get(info.getFieldDescriptor().getGetterName()));
      }
    }
  }
 private static PsiClassType[] filterCheckedExceptions(PsiClassType[] exceptions) {
   List<PsiClassType> result = new ArrayList<PsiClassType>();
   for (PsiClassType exceptionType : exceptions) {
     if (!ExceptionUtil.isUncheckedException(exceptionType)) result.add(exceptionType);
   }
   return result.toArray(new PsiClassType[result.size()]);
 }
  public void updateThrowsList(PsiClassType exceptionType) {
    if (!getSuperMethods().isEmpty()) {
      for (RefMethod refSuper : getSuperMethods()) {
        ((RefMethodImpl) refSuper).updateThrowsList(exceptionType);
      }
    } else if (myUnThrownExceptions != null) {
      if (exceptionType == null) {
        myUnThrownExceptions = null;
        return;
      }
      PsiClass exceptionClass = exceptionType.resolve();
      JavaPsiFacade facade = JavaPsiFacade.getInstance(myManager.getProject());
      for (int i = myUnThrownExceptions.size() - 1; i >= 0; i--) {
        String exceptionFqn = myUnThrownExceptions.get(i);
        PsiClass classType =
            facade.findClass(
                exceptionFqn, GlobalSearchScope.allScope(getRefManager().getProject()));
        if (InheritanceUtil.isInheritorOrSelf(exceptionClass, classType, true)
            || InheritanceUtil.isInheritorOrSelf(classType, exceptionClass, true)) {
          myUnThrownExceptions.remove(i);
        }
      }

      if (myUnThrownExceptions.isEmpty()) myUnThrownExceptions = null;
    }
  }
 @NotNull
 public static PsiClassType[] getImplementsListTypes(GrTypeDefinition grType) {
   Set<PsiClass> visited = new HashSet<PsiClass>();
   List<PsiClassType> result = new ArrayList<PsiClassType>();
   getImplementListsInner(grType, result, visited);
   return result.toArray(new PsiClassType[result.size()]);
 }
  private static PsiAnnotationMemberValue[] readFromClass(
      @NonNls String attributeName, @NotNull PsiAnnotation magic, PsiType type) {
    PsiAnnotationMemberValue fromClassAttr = magic.findAttributeValue(attributeName);
    PsiType fromClassType =
        fromClassAttr instanceof PsiClassObjectAccessExpression
            ? ((PsiClassObjectAccessExpression) fromClassAttr).getOperand().getType()
            : null;
    PsiClass fromClass =
        fromClassType instanceof PsiClassType ? ((PsiClassType) fromClassType).resolve() : null;
    if (fromClass == null) return null;
    String fqn = fromClass.getQualifiedName();
    if (fqn == null) return null;
    List<PsiAnnotationMemberValue> constants = new ArrayList<PsiAnnotationMemberValue>();
    for (PsiField field : fromClass.getFields()) {
      if (!field.hasModifierProperty(PsiModifier.PUBLIC)
          || !field.hasModifierProperty(PsiModifier.STATIC)
          || !field.hasModifierProperty(PsiModifier.FINAL)) continue;
      PsiType fieldType = field.getType();
      if (!Comparing.equal(fieldType, type)) continue;
      PsiAssignmentExpression e =
          (PsiAssignmentExpression)
              JavaPsiFacade.getElementFactory(field.getProject())
                  .createExpressionFromText("x=" + fqn + "." + field.getName(), field);
      PsiReferenceExpression refToField = (PsiReferenceExpression) e.getRExpression();
      constants.add(refToField);
    }
    if (constants.isEmpty()) return null;

    return constants.toArray(new PsiAnnotationMemberValue[constants.size()]);
  }
 @Override
 @Nullable
 public PsiClass[] getUnThrownExceptions() {
   if (getRefManager().isOfflineView()) {
     LOG.debug("Should not traverse graph offline");
   }
   if (myUnThrownExceptions == null) return null;
   JavaPsiFacade facade = JavaPsiFacade.getInstance(myManager.getProject());
   List<PsiClass> result = new ArrayList<PsiClass>(myUnThrownExceptions.size());
   for (String exception : myUnThrownExceptions) {
     PsiClass element =
         facade.findClass(exception, GlobalSearchScope.allScope(myManager.getProject()));
     if (element != null) result.add(element);
   }
   return result.toArray(new PsiClass[result.size()]);
 }
 @NotNull
 public static PsiMethod[] findMethodsByName(
     @NotNull PsiClass aClass, String name, boolean checkBases) {
   List<PsiMember> methods = findByMap(aClass, name, checkBases, MemberType.METHOD);
   //noinspection SuspiciousToArrayCall
   return methods.toArray(new PsiMethod[methods.size()]);
 }
Exemple #12
0
 @NotNull
 public static PsiElement[] findSuperElements(@NotNull PsiElement element) {
   if (element instanceof PsiClass) {
     PsiClass aClass = (PsiClass) element;
     List<PsiClass> allSupers = new ArrayList<>(Arrays.asList(aClass.getSupers()));
     for (Iterator<PsiClass> iterator = allSupers.iterator(); iterator.hasNext(); ) {
       PsiClass superClass = iterator.next();
       if (CommonClassNames.JAVA_LANG_OBJECT.equals(superClass.getQualifiedName()))
         iterator.remove();
     }
     return allSupers.toArray(new PsiClass[allSupers.size()]);
   }
   if (element instanceof PsiMethod) {
     PsiMethod method = (PsiMethod) element;
     if (method.isConstructor()) {
       PsiMethod constructorInSuper = PsiSuperMethodUtil.findConstructorInSuper(method);
       if (constructorInSuper != null) {
         return new PsiMethod[] {constructorInSuper};
       }
     } else {
       PsiMethod[] superMethods = method.findSuperMethods(false);
       if (superMethods.length == 0) {
         PsiMethod superMethod = getSiblingInheritedViaSubClass(method);
         if (superMethod != null) {
           superMethods = new PsiMethod[] {superMethod};
         }
       }
       return superMethods;
     }
   }
   return PsiElement.EMPTY_ARRAY;
 }
 private static PsiClassType[] filterUnhandledExceptions(
     PsiClassType[] exceptions, PsiElement place) {
   List<PsiClassType> result = new ArrayList<PsiClassType>();
   for (PsiClassType exception : exceptions) {
     if (!ExceptionUtil.isHandled(exception, place)) result.add(exception);
   }
   return result.toArray(new PsiClassType[result.size()]);
 }
 public static PsiClass[] getInterfaces(GrTypeDefinition grType) {
   final PsiClassType[] implementsListTypes = grType.getImplementsListTypes();
   List<PsiClass> result = new ArrayList<PsiClass>(implementsListTypes.length);
   for (PsiClassType type : implementsListTypes) {
     final PsiClass psiClass = type.resolve();
     if (psiClass != null) result.add(psiClass);
   }
   return result.toArray(new PsiClass[result.size()]);
 }
 @Nullable
 static MethodSignature getFunction(PsiClass psiClass) {
   if (psiClass == null) return null;
   final List<MethodSignature> functions = findFunctionCandidates(psiClass);
   if (functions != null && functions.size() == 1) {
     return functions.get(0);
   }
   return null;
 }
 @Override
 @NotNull
 public Collection<RefMethod> getSuperMethods() {
   if (mySuperMethods == null) return EMPTY_METHOD_LIST;
   if (mySuperMethods.size() > 10) {
     LOG.info("method: " + getName() + " owner:" + getOwnerClass().getQualifiedName());
   }
   if (getRefManager().isOfflineView()) {
     LOG.debug("Should not traverse graph offline");
   }
   return mySuperMethods;
 }
 private PsiElement[] getElements() {
   final List<PsiElement> elements = new ArrayList<PsiElement>();
   processElements(
       new PsiElementProcessor() {
         public boolean execute(@NotNull PsiElement psiElement) {
           elements.add(psiElement);
           return true;
         }
       },
       this);
   return ContainerUtil.toArray(elements, new PsiElement[elements.size()]);
 }
  @Override
  public List<RefEntity> getChildren() {
    List<RefEntity> superChildren = super.getChildren();
    if (myParameters == null) return superChildren;
    if (superChildren == null || superChildren.isEmpty())
      return Arrays.<RefEntity>asList(myParameters);

    List<RefEntity> allChildren =
        new ArrayList<RefEntity>(superChildren.size() + myParameters.length);
    allChildren.addAll(superChildren);
    Collections.addAll(allChildren, myParameters);
    return allChildren;
  }
  @NotNull
  public static PsiClass[] getSupers(GrTypeDefinition grType) {
    PsiClassType[] superTypes = grType.getSuperTypes();
    List<PsiClass> result = new ArrayList<PsiClass>();
    for (PsiClassType superType : superTypes) {
      PsiClass superClass = superType.resolve();
      if (superClass != null) {
        result.add(superClass);
      }
    }

    return result.toArray(new PsiClass[result.size()]);
  }
 @NotNull
 public XmlTag[] findSubTags(final String name, final String namespace) {
   final XmlTag[] subTags = getSubTags();
   final List<XmlTag> result = new ArrayList<XmlTag>();
   for (final XmlTag subTag : subTags) {
     if (namespace == null) {
       if (name.equals(subTag.getName())) result.add(subTag);
     } else if (name.equals(subTag.getLocalName()) && namespace.equals(subTag.getNamespace())) {
       result.add(subTag);
     }
   }
   return ContainerUtil.toArray(result, new XmlTag[result.size()]);
 }
 @Nullable
 private String extractReturnType() {
   final String ARROW = "->";
   final StructuredDocString structuredDocString = getStructuredDocString();
   if (structuredDocString != null) {
     return structuredDocString.getReturnType();
   }
   final String docString = getDocStringValue();
   if (docString != null && docString.contains(ARROW)) {
     final List<String> lines = StringUtil.split(docString, "\n");
     while (lines.size() > 0 && lines.get(0).trim().length() == 0) {
       lines.remove(0);
     }
     if (lines.size() > 1 && lines.get(1).trim().length() == 0) {
       String firstLine = lines.get(0);
       int pos = firstLine.lastIndexOf(ARROW);
       if (pos >= 0) {
         return firstLine.substring(pos + 2).trim();
       }
     }
   }
   return null;
 }
 @NotNull
 public static PsiClass[] getInterfaces(@NotNull PsiTypeParameter typeParameter) {
   final PsiClassType[] referencedTypes = typeParameter.getExtendsListTypes();
   if (referencedTypes.length == 0) {
     return PsiClass.EMPTY_ARRAY;
   }
   final List<PsiClass> result = new ArrayList<PsiClass>(referencedTypes.length);
   for (PsiClassType referencedType : referencedTypes) {
     final PsiClass psiClass = referencedType.resolve();
     if (psiClass != null && psiClass.isInterface()) {
       result.add(psiClass);
     }
   }
   return result.toArray(new PsiClass[result.size()]);
 }
  private static PsiMethod[] findMethodsByName(
      GrTypeDefinition grType, String name, boolean checkBases, boolean includeSyntheticAccessors) {
    if (!checkBases) {
      List<PsiMethod> result = new ArrayList<PsiMethod>();
      for (PsiMethod method :
          CollectClassMembersUtil.getMethods(grType, includeSyntheticAccessors)) {
        if (name.equals(method.getName())) result.add(method);
      }

      return result.toArray(new PsiMethod[result.size()]);
    }

    Map<String, List<CandidateInfo>> methodsMap =
        CollectClassMembersUtil.getAllMethods(grType, includeSyntheticAccessors);
    return PsiImplUtil.mapToMethods(methodsMap.get(name));
  }
  private static void insertGenerationInfos(
      InsertionContext context, List<PsiGenerationInfo<PsiMethod>> infos) {
    List<PsiGenerationInfo<PsiMethod>> newInfos =
        GenerateMembersUtil.insertMembersAtOffset(
            context.getFile(), context.getStartOffset(), infos);
    if (!newInfos.isEmpty()) {
      final List<PsiElement> elements = new ArrayList<PsiElement>();
      for (GenerationInfo member : newInfos) {
        if (!(member instanceof TemplateGenerationInfo)) {
          final PsiMember psiMember = member.getPsiMember();
          if (psiMember != null) {
            elements.add(psiMember);
          }
        }
      }

      GlobalInspectionContextBase.cleanupElements(
          context.getProject(), null, elements.toArray(new PsiElement[elements.size()]));
      newInfos.get(0).positionCaret(context.getEditor(), true);
    }
  }
  @NotNull
  public XmlTagValue getValue() {
    XmlTagValue tagValue = myValue;
    if (tagValue == null) {
      final PsiElement[] elements = getElements();
      final List<XmlTagChild> bodyElements = new ArrayList<XmlTagChild>(elements.length);

      boolean insideBody = false;
      for (final PsiElement element : elements) {
        final ASTNode treeElement = element.getNode();
        if (insideBody) {
          if (treeElement.getElementType() == XmlTokenType.XML_END_TAG_START) break;
          if (!(element instanceof XmlTagChild)) continue;
          bodyElements.add((XmlTagChild) element);
        } else if (treeElement.getElementType() == XmlTokenType.XML_TAG_END) insideBody = true;
      }

      XmlTagChild[] tagChildren =
          ContainerUtil.toArray(bodyElements, new XmlTagChild[bodyElements.size()]);
      myValue = tagValue = new XmlTagValueImpl(tagChildren, this);
    }
    return tagValue;
  }
 @Nullable
 private Modifier getWrappersFromStub() {
   final StubElement parentStub = getStub().getParentStub();
   final List childrenStubs = parentStub.getChildrenStubs();
   int index = childrenStubs.indexOf(getStub());
   if (index >= 0 && index < childrenStubs.size() - 1) {
     StubElement nextStub = (StubElement) childrenStubs.get(index + 1);
     if (nextStub instanceof PyTargetExpressionStub) {
       final PyTargetExpressionStub targetExpressionStub = (PyTargetExpressionStub) nextStub;
       if (targetExpressionStub.getInitializerType()
           == PyTargetExpressionStub.InitializerType.CallExpression) {
         final QualifiedName qualifiedName = targetExpressionStub.getInitializer();
         if (QualifiedName.fromComponents(PyNames.CLASSMETHOD).equals(qualifiedName)) {
           return CLASSMETHOD;
         }
         if (QualifiedName.fromComponents(PyNames.STATICMETHOD).equals(qualifiedName)) {
           return STATICMETHOD;
         }
       }
     }
   }
   return null;
 }
 @NotNull
 public static PsiClass[] getAllInnerClasses(@NotNull PsiClass aClass) {
   List<PsiClass> classes = getAllByMap(aClass, MemberType.CLASS);
   return classes.toArray(new PsiClass[classes.size()]);
 }
  // uses hierarchy signature tree if available, traverses class structure by itself otherwise
  public static boolean isSuperMethodSmart(
      @NotNull PsiMethod method, @NotNull PsiMethod superMethod) {
    // boolean old = PsiSuperMethodUtil.isSuperMethod(method, superMethod);

    if (method == superMethod) return false;
    PsiClass aClass = method.getContainingClass();
    PsiClass superClass = superMethod.getContainingClass();

    if (aClass == null || superClass == null || superClass == aClass) return false;

    if (!canHaveSuperMethod(method, true, false)) return false;

    PsiMethod[] superMethods = null;
    Map<MethodSignature, HierarchicalMethodSignature> cachedMap =
        SIGNATURES_KEY.getCachedValueOrNull(aClass);
    if (cachedMap != null) {
      HierarchicalMethodSignature signature =
          cachedMap.get(method.getSignature(PsiSubstitutor.EMPTY));
      if (signature != null) {
        superMethods =
            MethodSignatureUtil.convertMethodSignaturesToMethods(signature.getSuperSignatures());
      }
    }
    if (superMethods == null) {
      PsiClassType[] directSupers = aClass.getSuperTypes();
      List<PsiMethod> found = null;
      boolean canceled = false;
      for (PsiClassType directSuper : directSupers) {
        PsiClassType.ClassResolveResult resolveResult = directSuper.resolveGenerics();
        if (resolveResult.getSubstitutor() != PsiSubstitutor.EMPTY) {
          // generics
          canceled = true;
          break;
        }
        PsiClass directSuperClass = resolveResult.getElement();
        if (directSuperClass == null) continue;
        PsiMethod[] candidates = directSuperClass.findMethodsBySignature(method, false);
        if (candidates.length != 0) {
          if (found == null) found = new ArrayList<PsiMethod>();
          for (PsiMethod candidate : candidates) {
            if (PsiUtil.canBeOverriden(candidate)) found.add(candidate);
          }
        }
      }
      superMethods =
          canceled
              ? null
              : found == null ? PsiMethod.EMPTY_ARRAY : found.toArray(new PsiMethod[found.size()]);
    }
    if (superMethods == null) {
      superMethods =
          MethodSignatureUtil.convertMethodSignaturesToMethods(
              method.getHierarchicalMethodSignature().getSuperSignatures());
    }

    for (PsiMethod superCandidate : superMethods) {
      if (superMethod.equals(superCandidate) || isSuperMethodSmart(superCandidate, superMethod))
        return true;
    }
    return false;
  }
  private static AllowedValues parseBeanInfo(@NotNull PsiModifierListOwner owner) {
    PsiMethod method = null;
    if (owner instanceof PsiParameter) {
      PsiParameter parameter = (PsiParameter) owner;
      PsiElement scope = parameter.getDeclarationScope();
      if (!(scope instanceof PsiMethod)) return null;
      PsiElement nav = scope.getNavigationElement();
      if (!(nav instanceof PsiMethod)) return null;
      method = (PsiMethod) nav;
      if (method.isConstructor()) {
        // not a property, try the @ConstructorProperties({"prop"})
        PsiAnnotation annotation =
            AnnotationUtil.findAnnotation(method, "java.beans.ConstructorProperties");
        if (annotation == null) return null;
        PsiAnnotationMemberValue value = annotation.findAttributeValue("value");
        if (!(value instanceof PsiArrayInitializerMemberValue)) return null;
        PsiAnnotationMemberValue[] initializers =
            ((PsiArrayInitializerMemberValue) value).getInitializers();
        PsiElement parent = parameter.getParent();
        if (!(parent instanceof PsiParameterList)) return null;
        int index = ((PsiParameterList) parent).getParameterIndex(parameter);
        if (index >= initializers.length) return null;
        PsiAnnotationMemberValue initializer = initializers[index];
        if (!(initializer instanceof PsiLiteralExpression)) return null;
        Object val = ((PsiLiteralExpression) initializer).getValue();
        if (!(val instanceof String)) return null;
        PsiMethod setter =
            PropertyUtil.findPropertySetter(
                method.getContainingClass(), (String) val, false, false);
        if (setter == null) return null;
        // try the @beaninfo of the corresponding setter
        method = (PsiMethod) setter.getNavigationElement();
      }
    } else if (owner instanceof PsiMethod) {
      PsiElement nav = owner.getNavigationElement();
      if (!(nav instanceof PsiMethod)) return null;
      method = (PsiMethod) nav;
    }
    if (method == null) return null;

    PsiClass aClass = method.getContainingClass();
    if (aClass == null) return null;
    if (PropertyUtil.isSimplePropertyGetter(method)) {
      List<PsiMethod> setters =
          PropertyUtil.getSetters(aClass, PropertyUtil.getPropertyNameByGetter(method));
      if (setters.size() != 1) return null;
      method = setters.get(0);
    }
    if (!PropertyUtil.isSimplePropertySetter(method)) return null;
    PsiDocComment doc = method.getDocComment();
    if (doc == null) return null;
    PsiDocTag beaninfo = doc.findTagByName("beaninfo");
    if (beaninfo == null) return null;
    String data =
        StringUtil.join(
            beaninfo.getDataElements(),
            new Function<PsiElement, String>() {
              @Override
              public String fun(PsiElement element) {
                return element.getText();
              }
            },
            "\n");
    int enumIndex = StringUtil.indexOfSubstringEnd(data, "enum:");
    if (enumIndex == -1) return null;
    data = data.substring(enumIndex);
    int colon = data.indexOf(":");
    int last = colon == -1 ? data.length() : data.substring(0, colon).lastIndexOf("\n");
    data = data.substring(0, last);

    List<PsiAnnotationMemberValue> values = new ArrayList<PsiAnnotationMemberValue>();
    for (String line : StringUtil.splitByLines(data)) {
      List<String> words = StringUtil.split(line, " ", true, true);
      if (words.size() != 2) continue;
      String ref = words.get(1);
      PsiExpression constRef =
          JavaPsiFacade.getElementFactory(aClass.getProject())
              .createExpressionFromText(ref, aClass);
      if (!(constRef instanceof PsiReferenceExpression)) continue;
      PsiReferenceExpression expr = (PsiReferenceExpression) constRef;
      values.add(expr);
    }
    if (values.isEmpty()) return null;
    PsiAnnotationMemberValue[] array = values.toArray(new PsiAnnotationMemberValue[values.size()]);
    return new AllowedValues(array, false);
  }
Exemple #30
0
 public static boolean addStaticImport(
     @NotNull String qualifierClass,
     @NonNls @NotNull String memberName,
     @NotNull PsiElement context) {
   if (!nameCanBeStaticallyImported(qualifierClass, memberName, context)) {
     return false;
   }
   final PsiClass containingClass = PsiTreeUtil.getParentOfType(context, PsiClass.class);
   if (InheritanceUtil.isInheritor(containingClass, qualifierClass)) {
     return true;
   }
   final PsiFile psiFile = context.getContainingFile();
   if (!(psiFile instanceof PsiJavaFile)) {
     return false;
   }
   final PsiJavaFile javaFile = (PsiJavaFile) psiFile;
   final PsiImportList importList = javaFile.getImportList();
   if (importList == null) {
     return false;
   }
   final PsiImportStatementBase existingImportStatement =
       importList.findSingleImportStatement(memberName);
   if (existingImportStatement != null) {
     if (existingImportStatement instanceof PsiImportStaticStatement) {
       final PsiImportStaticStatement importStaticStatement =
           (PsiImportStaticStatement) existingImportStatement;
       if (!memberName.equals(importStaticStatement.getReferenceName())) {
         return false;
       }
       final PsiClass targetClass = importStaticStatement.resolveTargetClass();
       return targetClass != null && qualifierClass.equals(targetClass.getQualifiedName());
     }
     return false;
   }
   final PsiImportStaticStatement onDemandImportStatement =
       findOnDemandImportStaticStatement(importList, qualifierClass);
   if (onDemandImportStatement != null
       && !hasOnDemandImportStaticConflict(qualifierClass, memberName, context)) {
     return true;
   }
   final Project project = context.getProject();
   final GlobalSearchScope scope = context.getResolveScope();
   final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project);
   final PsiClass aClass = psiFacade.findClass(qualifierClass, scope);
   if (aClass == null) {
     return false;
   }
   final String qualifiedName = aClass.getQualifiedName();
   if (qualifiedName == null) {
     return false;
   }
   final List<PsiImportStaticStatement> imports = getMatchingImports(importList, qualifiedName);
   final int onDemandCount =
       JavaCodeStyleSettingsFacade.getInstance(project).getNamesCountToUseImportOnDemand();
   final PsiElementFactory elementFactory = psiFacade.getElementFactory();
   if (imports.size() < onDemandCount) {
     importList.add(elementFactory.createImportStaticStatement(aClass, memberName));
   } else {
     for (PsiImportStaticStatement importStatement : imports) {
       importStatement.delete();
     }
     importList.add(elementFactory.createImportStaticStatement(aClass, "*"));
   }
   return true;
 }