示例#1
0
 @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()]);
   }
 }
 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()]);
 }
示例#3
0
    @Override
    public Result<PsiModifierList> compute() {
      List<PsiModifierList> list = new ArrayList<PsiModifierList>();
      for (PsiDirectory directory : getDirectories()) {
        PsiFile file = directory.findFile(PACKAGE_INFO_FILE);
        if (file != null) {
          PsiPackageStatement stmt = PsiTreeUtil.getChildOfType(file, PsiPackageStatement.class);
          if (stmt != null) {
            final PsiModifierList modifierList = stmt.getAnnotationList();
            if (modifierList != null) {
              list.add(modifierList);
            }
          }
        }
      }

      final JavaPsiFacade facade = getFacade();
      final GlobalSearchScope scope = allScope();
      for (PsiClass aClass : facade.findClasses(getQualifiedName() + ".package-info", scope)) {
        ContainerUtil.addIfNotNull(aClass.getModifierList(), list);
      }

      return new Result<PsiModifierList>(
          list.isEmpty() ? null : new PsiCompositeModifierList(getManager(), list),
          OOCB_DEPENDENCY);
    }
  @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;
  }
 @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()]);
 }
示例#6
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;
 }
 @NotNull
 private static List<PsiMethod> findMethodsBySignature(
     @NotNull PsiClass aClass,
     @NotNull PsiMethod patternMethod,
     boolean checkBases,
     boolean stopOnFirst) {
   final PsiMethod[] methodsByName = aClass.findMethodsByName(patternMethod.getName(), checkBases);
   if (methodsByName.length == 0) return Collections.emptyList();
   final List<PsiMethod> methods = new SmartList<PsiMethod>();
   final MethodSignature patternSignature = patternMethod.getSignature(PsiSubstitutor.EMPTY);
   for (final PsiMethod method : methodsByName) {
     final PsiClass superClass = method.getContainingClass();
     final PsiSubstitutor substitutor;
     if (checkBases && !aClass.equals(superClass)) {
       substitutor =
           TypeConversionUtil.getSuperClassSubstitutor(superClass, aClass, PsiSubstitutor.EMPTY);
     } else {
       substitutor = PsiSubstitutor.EMPTY;
     }
     final MethodSignature signature = method.getSignature(substitutor);
     if (signature.equals(patternSignature)) {
       methods.add(method);
       if (stopOnFirst) {
         break;
       }
     }
   }
   return methods;
 }
  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()]);
  }
示例#11
0
  public String getAttributeValue(String _name, String namespace) {
    if (namespace == null) {
      return getAttributeValue(_name);
    }

    XmlTagImpl current = this;
    PsiElement parent = getParent();

    while (current != null) {
      BidirectionalMap<String, String> map = current.initNamespaceMaps(parent);
      if (map != null) {
        List<String> keysByValue = map.getKeysByValue(namespace);
        if (keysByValue != null && !keysByValue.isEmpty()) {

          for (String prefix : keysByValue) {
            if (prefix != null && prefix.length() > 0) {
              final String value = getAttributeValue(prefix + ":" + _name);
              if (value != null) return value;
            }
          }
        }
      }

      current = parent instanceof XmlTag ? (XmlTagImpl) parent : null;
      parent = parent.getParent();
    }

    if (namespace.length() == 0 || getNamespace().equals(namespace)) {
      return getAttributeValue(_name);
    }
    return null;
  }
  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()));
      }
    }
  }
示例#13
0
  private static String[] getSuggestionsByValue(final String stringValue) {
    List<String> result = new ArrayList<String>();
    StringBuffer currentWord = new StringBuffer();

    boolean prevIsUpperCase = false;

    for (int i = 0; i < stringValue.length(); i++) {
      final char c = stringValue.charAt(i);
      if (Character.isUpperCase(c)) {
        if (currentWord.length() > 0 && !prevIsUpperCase) {
          result.add(currentWord.toString());
          currentWord = new StringBuffer();
        }
        currentWord.append(c);
      } else if (Character.isLowerCase(c)) {
        currentWord.append(Character.toUpperCase(c));
      } else if (Character.isJavaIdentifierPart(c) && c != '_') {
        if (Character.isJavaIdentifierStart(c) || currentWord.length() > 0 || !result.isEmpty()) {
          currentWord.append(c);
        }
      } else {
        if (currentWord.length() > 0) {
          result.add(currentWord.toString());
          currentWord = new StringBuffer();
        }
      }

      prevIsUpperCase = Character.isUpperCase(c);
    }

    if (currentWord.length() > 0) {
      result.add(currentWord.toString());
    }
    return ArrayUtil.toStringArray(result);
  }
 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()]);
 }
示例#15
0
 @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;
 }
 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()]);
 }
 public static void addExpandingReflectedMethods(List<PsiMethod> result, PsiMethod method) {
   if (method instanceof GrMethod) {
     final GrReflectedMethod[] reflectedMethods = ((GrMethod) method).getReflectedMethods();
     if (reflectedMethods.length > 0) {
       result.addAll(Arrays.asList(reflectedMethods));
       return;
     }
   }
   result.add(method);
 }
 @Nullable
 @Override
 protected RefactoringEventData getBeforeData() {
   RefactoringEventData data = new RefactoringEventData();
   final List<PsiElement> fields = new ArrayList<PsiElement>();
   for (FieldDescriptor fieldDescriptor : myFieldDescriptors) {
     fields.add(fieldDescriptor.getField());
   }
   data.addElements(fields);
   return data;
 }
示例#19
0
 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()]);
 }
  @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()]);
  }
示例#21
0
 @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()]);
 }
  @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;
  }
示例#23
0
 public String getPrefixByNamespace(String namespace) {
   final PsiElement parent = getParent();
   BidirectionalMap<String, String> map = initNamespaceMaps(parent);
   if (map != null) {
     List<String> keysByValue = map.getKeysByValue(namespace);
     final String ns = keysByValue == null || keysByValue.isEmpty() ? null : keysByValue.get(0);
     if (ns != null) return ns;
   }
   if (parent instanceof XmlTag) return ((XmlTag) parent).getPrefixByNamespace(namespace);
   // The prefix 'xml' is by definition bound to the namespace name
   // http://www.w3.org/XML/1998/namespace. It MAY, but need not, be declared
   if (XmlUtil.XML_NAMESPACE_URI.equals(namespace)) return XML_NS_PREFIX;
   return null;
 }
 @Nullable
 @Override
 protected RefactoringEventData getAfterData(UsageInfo[] usages) {
   RefactoringEventData data = new RefactoringEventData();
   List<PsiElement> elements = new ArrayList<PsiElement>();
   if (myNameToGetter != null) {
     elements.addAll(myNameToGetter.values());
   }
   if (myNameToSetter != null) {
     elements.addAll(myNameToSetter.values());
   }
   data.addElements(elements);
   return data;
 }
示例#25
0
 public static List<PsiExpression> getReturnExpressions(PsiLambdaExpression lambdaExpression) {
   final PsiElement body = lambdaExpression.getBody();
   if (body instanceof PsiExpression) {
     // if (((PsiExpression)body).getType() != PsiType.VOID) return Collections.emptyList();
     return Collections.singletonList((PsiExpression) body);
   }
   final List<PsiExpression> result = new ArrayList<PsiExpression>();
   for (PsiReturnStatement returnStatement : getReturnStatements(lambdaExpression)) {
     final PsiExpression returnValue = returnStatement.getReturnValue();
     if (returnValue != null) {
       result.add(returnValue);
     }
   }
   return result;
 }
示例#26
0
 private static List<PsiImportStaticStatement> getMatchingImports(
     @NotNull PsiImportList importList, @NotNull String className) {
   final List<PsiImportStaticStatement> imports = new ArrayList();
   for (PsiImportStaticStatement staticStatement : importList.getImportStaticStatements()) {
     final PsiClass psiClass = staticStatement.resolveTargetClass();
     if (psiClass == null) {
       continue;
     }
     if (!className.equals(psiClass.getQualifiedName())) {
       continue;
     }
     imports.add(staticStatement);
   }
   return imports;
 }
  @NotNull
  private static <T extends PsiMember> List<T> getAllByMap(
      @NotNull PsiClass aClass, @NotNull MemberType type) {
    List<Pair<T, PsiSubstitutor>> pairs = getAllWithSubstitutorsByMap(aClass, type);

    final List<T> ret = new ArrayList<T>(pairs.size());
    //noinspection ForLoopReplaceableByForEach
    for (int i = 0; i < pairs.size(); i++) {
      Pair<T, PsiSubstitutor> pair = pairs.get(i);
      T t = pair.getFirst();
      LOG.assertTrue(t != null, aClass);
      ret.add(t);
    }
    return ret;
  }
 @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));
  }
 @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()]);
 }