public void testCreateConfiguration() throws IOException, ExecutionException {
    Module module1 = getModule1();
    PsiClass psiClass = findTestA(module1);
    JUnitConfiguration configuration = createConfiguration(psiClass);
    assertEquals(
        Collections.singleton(module1), ContainerUtilRt.newHashSet(configuration.getModules()));
    checkClassName(psiClass.getQualifiedName(), configuration);
    assertEquals(psiClass.getName(), configuration.getName());
    checkTestObject(JUnitConfiguration.TEST_CLASS, configuration);
    Module module2 = getModule2();
    Assertion.compareUnordered(new Module[] {module1, module2}, configuration.getValidModules());

    PsiClass innerTest = findClass(module1, INNER_TEST_NAME);
    configuration =
        createJUnitConfiguration(
            innerTest, TestClassConfigurationProducer.class, new MapDataContext());
    checkClassName(RT_INNER_TEST_NAME, configuration);
    checkCanRun(configuration);

    PsiMethod[] testMethod = innerTest.findMethodsByName("test", false);
    assertEquals(1, testMethod.length);
    configuration = createConfiguration(testMethod[0]);
    checkClassName(RT_INNER_TEST_NAME, configuration);
    checkMethodName("test", configuration);
    checkTestObject(JUnitConfiguration.TEST_METHOD, configuration);
    checkCanRun(configuration);

    PsiMethod mainMethod = innerTest.findMethodsByName("main", false)[0];
    ApplicationConfiguration appConfiguration = createConfiguration(mainMethod);
    assertEquals(RT_INNER_TEST_NAME, appConfiguration.MAIN_CLASS_NAME);
    checkCanRun(configuration);
  }
 @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;
 }
Exemplo n.º 3
0
  private void checkCompoundIds(Class<?> javaClass) throws IOException {
    String javaClassName = javaClass.getCanonicalName();
    PsiClass psiClass =
        myJavaPsiFacade.findClass(
            javaClassName, GlobalSearchScope.moduleWithLibrariesScope(myModule));
    assertNotNull(psiClass);

    for (java.lang.reflect.Method javaMethod : javaClass.getDeclaredMethods()) {
      Method method =
          new Method(
              Type.getType(javaClass).getInternalName(),
              javaMethod.getName(),
              Type.getMethodDescriptor(javaMethod));
      boolean noKey = javaMethod.getAnnotation(ExpectNoPsiKey.class) != null;
      PsiMethod psiMethod = psiClass.findMethodsByName(javaMethod.getName(), false)[0];
      checkCompoundId(method, psiMethod, noKey);
    }

    for (Constructor<?> constructor : javaClass.getDeclaredConstructors()) {
      Method method =
          new Method(
              Type.getType(javaClass).getInternalName(),
              "<init>",
              Type.getConstructorDescriptor(constructor));
      boolean noKey = constructor.getAnnotation(ExpectNoPsiKey.class) != null;
      PsiMethod[] constructors = psiClass.getConstructors();
      PsiMethod psiMethod = constructors[0];
      checkCompoundId(method, psiMethod, noKey);
    }
  }
 public void testPropagateParameter() throws Exception {
   String basePath = "/refactoring/changeSignature/" + getTestName(false);
   @NonNls final String filePath = basePath + ".java";
   configureByFile(filePath);
   final PsiElement targetElement =
       TargetElementUtilBase.findTargetElement(
           getEditor(), TargetElementUtilBase.ELEMENT_NAME_ACCEPTED);
   assertTrue("<caret> is not on method name", targetElement instanceof PsiMethod);
   PsiMethod method = (PsiMethod) targetElement;
   final PsiClass containingClass = method.getContainingClass();
   assertTrue(containingClass != null);
   final PsiMethod[] callers = containingClass.findMethodsByName("caller", false);
   assertTrue(callers.length > 0);
   final PsiMethod caller = callers[0];
   final HashSet<PsiMethod> propagateParametersMethods = new HashSet<PsiMethod>();
   propagateParametersMethods.add(caller);
   final PsiParameter[] parameters = method.getParameterList().getParameters();
   new ChangeSignatureProcessor(
           getProject(),
           method,
           false,
           null,
           method.getName(),
           CanonicalTypes.createTypeWrapper(PsiType.VOID),
           new ParameterInfoImpl[] {
             new ParameterInfoImpl(0, parameters[0].getName(), parameters[0].getType()),
             new ParameterInfoImpl(-1, "b", PsiType.BOOLEAN)
           },
           null,
           propagateParametersMethods,
           null)
       .run();
   @NonNls String after = basePath + "_after.java";
   checkResultByFile(after);
 }
  @Nullable
  private static PsiMethod doFindMethodInSuperClassBySignatureInDerived(
      @NotNull PsiClass superClass,
      @NotNull PsiSubstitutor superSubstitutor,
      @NotNull MethodSignature signature,
      final boolean checkDeep) {
    final String name = signature.getName();
    final PsiMethod[] methods = superClass.findMethodsByName(name, false);
    for (final PsiMethod method : methods) {
      if (isSubsignature(method.getSignature(superSubstitutor), signature)) {
        return method;
      }
    }

    if (checkDeep) {
      final PsiClass clazz = superClass.getSuperClass();
      if (clazz != null && clazz != superClass) {
        PsiSubstitutor substitutor1 =
            TypeConversionUtil.getSuperClassSubstitutor(clazz, superClass, superSubstitutor);
        return doFindMethodInSuperClassBySignatureInDerived(clazz, substitutor1, signature, true);
      }
    }

    return null;
  }
  @Nullable
  private static PsiElement doResolveMember(PsiClass aClass, String memberName) {
    PsiMember member = aClass.findFieldByName(memberName, true);
    if (member != null) return member;

    PsiMethod[] methods = aClass.findMethodsByName(memberName, true);
    return methods.length == 0 ? null : methods[0];
  }
Exemplo n.º 7
0
 /**
  * get initView method
  *
  * @return
  */
 private PsiMethod getInitView() {
   PsiMethod[] methods = mClass.findMethodsByName("initView", true);
   for (PsiMethod method : methods) {
     if (method.getReturnType().equals(PsiType.VOID)) {
       return method;
     }
   }
   return null;
 }
  @Nullable
  private static String computeConstantReturnValue(PsiClass languagePsiClass, String methodName) {
    final PsiMethod[] methods = languagePsiClass.findMethodsByName(methodName, false);
    if (methods.length != 1) {
      return null;
    }

    return getStringConstantExpression(methods[0]);
  }
 public boolean isMethodSignatureExists() {
   PsiClass target = myTargetMethod.getContainingClass();
   LOG.assertTrue(target != null);
   PsiMethod[] methods = target.findMethodsByName(myTargetMethod.getName(), false);
   for (PsiMethod method : methods) {
     if (PsiUtil.isApplicable(method, PsiSubstitutor.EMPTY, myExpressions)) return true;
   }
   return false;
 }
Exemplo n.º 10
0
 /** Add the initView() after onCreate() */
 private void addInitViewAfterOnCreate() {
   String initViewStatement = "initView();";
   PsiMethod createMethod = mClass.findMethodsByName("onCreate", false)[0];
   for (PsiStatement statement : createMethod.getBody().getStatements()) {
     if (statement.getText().equals(initViewStatement)) {
       return;
     }
   }
   createMethod.getBody().add(mFactory.createStatementFromText(initViewStatement, mClass));
 }
Exemplo n.º 11
0
  public static Map<String, PsiElement> prepareDefaultNameToDeclaration(
      Project project, KotlinCoreEnvironment environment) {
    Map<String, PsiElement> nameToDeclaration = new HashMap<String, PsiElement>();

    PsiClass java_util_Collections = findClass("java.util.Collections", project, environment);
    nameToDeclaration.put(
        "java::java.util.Collections.emptyList()", findMethod(java_util_Collections, "emptyList"));
    nameToDeclaration.put("java::java.util.Collections", java_util_Collections);
    PsiClass java_util_List = findClass("java.util.ArrayList", project, environment);
    nameToDeclaration.put(
        "java::java.util.List", findClass("java.util.List", project, environment));
    nameToDeclaration.put("java::java.util.ArrayList", java_util_List);
    nameToDeclaration.put(
        "java::java.util.ArrayList.set()", java_util_List.findMethodsByName("set", true)[0]);
    nameToDeclaration.put(
        "java::java.util.ArrayList.get()", java_util_List.findMethodsByName("get", true)[0]);
    nameToDeclaration.put("java::java", findPackage("java", project));
    nameToDeclaration.put("java::java.util", findPackage("java.util", project));
    nameToDeclaration.put("java::java.lang", findPackage("java.lang", project));
    nameToDeclaration.put(
        "java::java.lang.Object", findClass("java.lang.Object", project, environment));
    nameToDeclaration.put(
        "java::java.lang.Comparable", findClass("java.lang.Comparable", project, environment));
    PsiClass java_lang_System = findClass("java.lang.System", project, environment);
    nameToDeclaration.put("java::java.lang.System", java_lang_System);
    PsiMethod[] methods =
        findClass("java.io.PrintStream", project, environment).findMethodsByName("print", true);
    nameToDeclaration.put("java::java.io.PrintStream.print(Object)", methods[8]);
    nameToDeclaration.put("java::java.io.PrintStream.print(Int)", methods[2]);
    nameToDeclaration.put("java::java.io.PrintStream.print(char[])", methods[6]);
    nameToDeclaration.put("java::java.io.PrintStream.print(Double)", methods[5]);
    PsiField outField = java_lang_System.findFieldByName("out", true);
    assertNotNull("'out' property wasn't found", outField);
    nameToDeclaration.put("java::java.lang.System.out", outField);
    PsiClass java_lang_Number = findClass("java.lang.Number", project, environment);
    nameToDeclaration.put("java::java.lang.Number", java_lang_Number);
    nameToDeclaration.put(
        "java::java.lang.Number.intValue()",
        java_lang_Number.findMethodsByName("intValue", true)[0]);

    return nameToDeclaration;
  }
  private static boolean areMissingMethodsDeclared(GrReferenceExpression ref) {
    PsiType qualifierType = GrReferenceResolveUtil.getQualifierType(ref);
    if (!(qualifierType instanceof PsiClassType)) return false;

    PsiClass resolved = ((PsiClassType) qualifierType).resolve();
    if (resolved == null) return false;

    if (ref.getParent() instanceof GrCall) {
      PsiMethod[] found = resolved.findMethodsByName("methodMissing", true);
      for (PsiMethod method : found) {
        if (MissingMethodAndPropertyUtil.isMethodMissing(method)) return true;
      }
    } else {
      PsiMethod[] found = resolved.findMethodsByName("propertyMissing", true);
      for (PsiMethod method : found) {
        if (MissingMethodAndPropertyUtil.isPropertyMissing(method)) return true;
      }
    }

    return false;
  }
Exemplo n.º 13
0
 @Nullable
 private static PsiMethod getMethod(PsiClass psiClass, MethodSignature methodSignature) {
   final PsiMethod[] methodsByName = psiClass.findMethodsByName(methodSignature.getName(), true);
   for (PsiMethod psiMethod : methodsByName) {
     if (MethodSignatureUtil.areSignaturesEqual(
         getMethodSignature(psiMethod, psiClass, psiMethod.getContainingClass()),
         methodSignature)) {
       return psiMethod;
     }
   }
   return null;
 }
 @Nullable
 static PsiMethod findExistingImplementation(final PsiClass aClass, PsiMethod method) {
   final PsiMethod[] methods = aClass.findMethodsByName(method.getName(), false);
   for (PsiMethod candidate : methods) {
     final PsiMethod[] superMethods = candidate.findSuperMethods(false);
     for (PsiMethod superMethod : superMethods) {
       if (superMethod.equals(method)) {
         return candidate;
       }
     }
   }
   return null;
 }
 @Nullable
 private PsiType extractListTypeFromContainingClass(
   PsiElement element) {
   PsiClass listClass = PsiTreeUtil.getParentOfType(element,
                                                    PsiClass.class);
   if (listClass == null) {
     return null;
   }
   final PsiMethod[] getMethods =
     listClass.findMethodsByName("get", true);
   if (getMethods.length == 0) {
     return null;
   }
   final PsiType type = getMethods[0].getReturnType();
   if (!(type instanceof PsiClassType)) {
     return null;
   }
   final PsiClassType classType = (PsiClassType)type;
   final PsiClass parameterClass = classType.resolve();
   if (parameterClass == null) {
     return null;
   }
   PsiClass subClass = null;
   while (listClass != null && !listClass.hasTypeParameters()) {
     subClass = listClass;
     listClass = listClass.getSuperClass();
   }
   if (listClass == null || subClass == null) {
     return TypeUtils.getObjectType(element);
   }
   final PsiTypeParameter[] typeParameters =
     listClass.getTypeParameters();
   if (!parameterClass.equals(typeParameters[0])) {
     return TypeUtils.getObjectType(element);
   }
   final PsiReferenceList extendsList = subClass.getExtendsList();
   if (extendsList == null) {
     return null;
   }
   final PsiJavaCodeReferenceElement[] referenceElements =
     extendsList.getReferenceElements();
   if (referenceElements.length == 0) {
     return null;
   }
   final PsiType[] types =
     referenceElements[0].getTypeParameters();
   if (types.length == 0) {
     return TypeUtils.getObjectType(element);
   }
   return types[0];
 }
    @Override
    public void visitAnnotationNameValuePair(GrAnnotationNameValuePair nameValuePair) {
      if (myExpression.equals(nameValuePair.getValue())) {
        final PsiClass annot = ResolveUtil.resolveAnnotation(nameValuePair.getParent());
        if (annot != null) {
          final String name = nameValuePair.getName();
          if (name != null) {
            final PsiMethod[] attrs = annot.findMethodsByName(name, false);
            if (attrs.length > 0) {
              PsiType type = attrs[0].getReturnType();
              while (type instanceof PsiArrayType) type = ((PsiArrayType) type).getComponentType();
              if (type != null && isAcceptableAnnotationValueType(type)) {
                myResult = createSimpleSubTypeResult(type);
              }
            }
          } else {
            final PsiMethod[] valueAttr = annot.findMethodsByName("value", false);
            boolean canHaveSimpleExpr = valueAttr.length > 0;
            final PsiMethod[] methods = annot.getMethods();
            for (PsiMethod method : methods) {
              if (!("value".equals(method.getName())
                  || method instanceof PsiAnnotationMethod
                      && ((PsiAnnotationMethod) method).getDefaultValue() != null)) {
                canHaveSimpleExpr = false;
              }
            }

            if (canHaveSimpleExpr) {
              PsiType type = valueAttr[0].getReturnType();
              while (type instanceof PsiArrayType) type = ((PsiArrayType) type).getComponentType();
              if (type != null && isAcceptableAnnotationValueType(type)) {
                myResult = createSimpleSubTypeResult(type);
              }
            }
          }
        }
      }
    }
Exemplo n.º 17
0
 @NotNull
 public static List<PsiMethod> getSetters(
     @NotNull final PsiClass psiClass, final String propertyName) {
   final String setterName = suggestSetterName(propertyName);
   final PsiMethod[] psiMethods = psiClass.findMethodsByName(setterName, true);
   final ArrayList<PsiMethod> list = new ArrayList<PsiMethod>(psiMethods.length);
   for (PsiMethod method : psiMethods) {
     if (filterMethods(method)) continue;
     if (PropertyUtil.isSimplePropertySetter(method)) {
       list.add(method);
     }
   }
   return list;
 }
Exemplo n.º 18
0
  private void checkAnnotations(Class<?> javaClass) {
    PsiClass psiClass =
        myJavaPsiFacade.findClass(
            javaClass.getName(), GlobalSearchScope.moduleWithLibrariesScope(myModule));
    assertNotNull(psiClass);

    for (java.lang.reflect.Method javaMethod : javaClass.getDeclaredMethods()) {
      PsiMethod psiMethod = psiClass.findMethodsByName(javaMethod.getName(), false)[0];
      Annotation[][] annotations = javaMethod.getParameterAnnotations();

      // not-null parameters
      params:
      for (int i = 0; i < annotations.length; i++) {
        Annotation[] parameterAnnotations = annotations[i];
        PsiParameter psiParameter = psiMethod.getParameterList().getParameters()[i];
        PsiAnnotation inferredAnnotation =
            myInferredAnnotationsManager.findInferredAnnotation(
                psiParameter, AnnotationUtil.NOT_NULL);
        for (Annotation parameterAnnotation : parameterAnnotations) {
          if (parameterAnnotation.annotationType() == ExpectNotNull.class) {
            assertNotNull(javaMethod.toString() + " " + i, inferredAnnotation);
            continue params;
          }
        }
        assertNull(javaMethod.toString() + " " + i, inferredAnnotation);
      }

      // not-null result
      ExpectNotNull expectedAnnotation = javaMethod.getAnnotation(ExpectNotNull.class);
      PsiAnnotation actualAnnotation =
          myInferredAnnotationsManager.findInferredAnnotation(psiMethod, AnnotationUtil.NOT_NULL);
      assertEquals(javaMethod.toString(), expectedAnnotation == null, actualAnnotation == null);

      // contracts
      ExpectContract expectedContract = javaMethod.getAnnotation(ExpectContract.class);
      PsiAnnotation actualContractAnnotation =
          myInferredAnnotationsManager.findInferredAnnotation(
              psiMethod, ORG_JETBRAINS_ANNOTATIONS_CONTRACT);

      assertEquals(expectedContract == null, actualContractAnnotation == null);

      if (expectedContract != null) {
        String expectedContractValue = expectedContract.value();
        String actualContractValue =
            AnnotationUtil.getStringAttributeValue(actualContractAnnotation, null);
        assertEquals(javaMethod.toString(), expectedContractValue, actualContractValue);
      }
    }
  }
  @NotNull
  private static ExpectedTypeMatching preferByMemberName(
      @Nullable String expectedMemberName, @Nullable PsiType itemType) {
    if (expectedMemberName != null) {
      PsiClass itemClass = PsiUtil.resolveClassInClassTypeOnly(itemType);
      if (itemClass != null) {
        if (itemClass.findMethodsByName(expectedMemberName, true).length > 0
            || itemClass.findFieldByName(expectedMemberName, true) != null
            || itemClass.findInnerClassByName(expectedMemberName, true) != null) {
          return ExpectedTypeMatching.expected;
        }
      }
    }

    return ExpectedTypeMatching.normal;
  }
    @Override
    public void visitAnnotationArrayInitializer(GrAnnotationArrayInitializer arrayInitializer) {
      final GrAnnotationNameValuePair nameValuePair =
          PsiTreeUtil.getParentOfType(
              arrayInitializer,
              GrAnnotationNameValuePair.class,
              true,
              GrDefaultAnnotationValue.class);
      if (nameValuePair != null) {

        final PsiClass annot = ResolveUtil.resolveAnnotation(arrayInitializer);
        if (annot == null) return;

        final String name = nameValuePair.getName();
        if (name == null) return;

        final PsiMethod[] attrs = annot.findMethodsByName(name, false);
        if (attrs.length > 0) {
          PsiType type = attrs[0].getReturnType();
          while (type instanceof PsiArrayType) type = ((PsiArrayType) type).getComponentType();
          if (type != null && isAcceptableAnnotationValueType(type)) {
            myResult = createSimpleSubTypeResult(type);
          }
        }
      } else {
        final GrAnnotationMethod method =
            PsiTreeUtil.getParentOfType(arrayInitializer, GrAnnotationMethod.class);
        assert method != null;

        PsiType type = method.getReturnType();

        int count = 1;
        PsiElement parent = arrayInitializer.getParent();
        while (parent instanceof GrAnnotationArrayInitializer) {
          count++;
          parent = parent.getParent();
        }

        while (type instanceof PsiArrayType && count > 0) {
          type = ((PsiArrayType) type).getComponentType();
          count--;
        }
        if (type != null && isAcceptableAnnotationValueType(type)) {
          myResult = createSimpleSubTypeResult(type);
        }
      }
    }
  private static void checkAnnotationsJarAttached(@NotNull LocalInspectionToolSession session) {
    PsiFile file = session.getFile();
    final Project project = file.getProject();
    PsiClass event =
        JavaPsiFacade.getInstance(project)
            .findClass("java.awt.event.InputEvent", GlobalSearchScope.allScope(project));
    if (event == null) return; // no jdk to attach
    PsiMethod[] methods = event.findMethodsByName("getModifiers", false);
    if (methods.length != 1) return; // no jdk to attach
    PsiMethod getModifiers = methods[0];
    PsiAnnotation annotation =
        ExternalAnnotationsManager.getInstance(project)
            .findExternalAnnotation(getModifiers, MagicConstant.class.getName());
    if (annotation != null) return;
    final VirtualFile virtualFile = PsiUtilCore.getVirtualFile(getModifiers);
    if (virtualFile == null) return; // no jdk to attach
    final List<OrderEntry> entries =
        ProjectRootManager.getInstance(project).getFileIndex().getOrderEntriesForFile(virtualFile);
    Sdk jdk = null;
    for (OrderEntry orderEntry : entries) {
      if (orderEntry instanceof JdkOrderEntry) {
        jdk = ((JdkOrderEntry) orderEntry).getJdk();
        if (jdk != null) break;
      }
    }
    if (jdk == null) return; // no jdk to attach

    if (!ApplicationManager.getApplication().isUnitTestMode()) {
      final Sdk finalJdk = jdk;
      ApplicationManager.getApplication()
          .invokeLater(
              new Runnable() {
                @Override
                public void run() {
                  ApplicationManager.getApplication()
                      .runWriteAction(
                          new Runnable() {
                            public void run() {
                              attachJdkAnnotations(finalJdk);
                            }
                          });
                }
              },
              ModalityState.NON_MODAL,
              project.getDisposed());
    }
  }
  @Nullable
  private static String doCheckRepeatableAnnotation(@NotNull PsiAnnotation annotation) {
    PsiAnnotationOwner owner = annotation.getOwner();
    if (!(owner instanceof PsiModifierList)) return null;
    PsiElement target = ((PsiModifierList) owner).getParent();
    if (!(target instanceof PsiClass) || !((PsiClass) target).isAnnotationType()) return null;
    PsiClass container = getRepeatableContainer(annotation);
    if (container == null) return null;

    PsiMethod[] methods = container.findMethodsByName("value", false);
    if (methods.length == 0) {
      return JavaErrorMessages.message(
          "annotation.container.no.value", container.getQualifiedName());
    }

    if (methods.length == 1) {
      PsiType expected =
          new PsiImmediateClassType((PsiClass) target, PsiSubstitutor.EMPTY).createArrayType();
      if (!expected.equals(methods[0].getReturnType())) {
        return JavaErrorMessages.message(
            "annotation.container.bad.type",
            container.getQualifiedName(),
            JavaHighlightUtil.formatType(expected));
      }
    }

    RetentionPolicy targetPolicy = getRetentionPolicy((PsiClass) target);
    if (targetPolicy != null) {
      RetentionPolicy containerPolicy = getRetentionPolicy(container);
      if (containerPolicy != null && targetPolicy.compareTo(containerPolicy) > 0) {
        return JavaErrorMessages.message(
            "annotation.container.low.retention", container.getQualifiedName(), containerPolicy);
      }
    }

    Set<PsiAnnotation.TargetType> repeatableTargets =
        PsiImplUtil.getAnnotationTargets((PsiClass) target);
    if (repeatableTargets != null) {
      Set<PsiAnnotation.TargetType> containerTargets = PsiImplUtil.getAnnotationTargets(container);
      if (containerTargets != null && !repeatableTargets.containsAll(containerTargets)) {
        return JavaErrorMessages.message(
            "annotation.container.wide.target", container.getQualifiedName());
      }
    }

    return null;
  }
  // returns contained element
  private static PsiClass contained(PsiClass annotationType) {
    if (!annotationType.isAnnotationType()) return null;
    PsiMethod[] values = annotationType.findMethodsByName("value", false);
    if (values.length != 1) return null;
    PsiMethod value = values[0];
    PsiType returnType = value.getReturnType();
    if (!(returnType instanceof PsiArrayType)) return null;
    PsiType type = ((PsiArrayType) returnType).getComponentType();
    if (!(type instanceof PsiClassType)) return null;
    PsiClass contained = ((PsiClassType) type).resolve();
    if (contained == null || !contained.isAnnotationType()) return null;
    if (PsiImplUtil.findAnnotation(
            contained.getModifierList(), CommonClassNames.JAVA_LANG_ANNOTATION_REPEATABLE)
        == null) return null;

    return contained;
  }
 private boolean hasGoodToString(PsiClass aClass) {
   final PsiMethod[] methods =
       aClass.findMethodsByName(HardcodedMethodConstants.TO_STRING, true);
   for (PsiMethod method : methods) {
     final PsiClass containingClass = method.getContainingClass();
     if (containingClass == null) {
       continue;
     }
     final String name = containingClass.getQualifiedName();
     if (CommonClassNames.JAVA_LANG_OBJECT.equals(name)) {
       continue;
     }
     final PsiParameterList parameterList = method.getParameterList();
     if (parameterList.getParametersCount() == 0) {
       return true;
     }
   }
   return false;
 }
 @NotNull
 public static List<Pair<PsiMethod, PsiSubstitutor>> findMethodsAndTheirSubstitutorsByName(
     @NotNull PsiClass psiClass, String name, boolean checkBases) {
   if (!checkBases) {
     final PsiMethod[] methodsByName = psiClass.findMethodsByName(name, false);
     final List<Pair<PsiMethod, PsiSubstitutor>> ret =
         new ArrayList<Pair<PsiMethod, PsiSubstitutor>>(methodsByName.length);
     for (final PsiMethod method : methodsByName) {
       ret.add(new Pair<PsiMethod, PsiSubstitutor>(method, PsiSubstitutor.EMPTY));
     }
     return ret;
   }
   Map<String, List<Pair<PsiMember, PsiSubstitutor>>> map = getMap(psiClass, MemberType.METHOD);
   @SuppressWarnings("unchecked")
   List<Pair<PsiMethod, PsiSubstitutor>> list = (List) map.get(name);
   return list == null
       ? Collections.<Pair<PsiMethod, PsiSubstitutor>>emptyList()
       : Collections.unmodifiableList(list);
 }
 private static boolean usesDefaultClone(PsiClass aClass) {
   final Project project = aClass.getProject();
   final PsiManager manager = aClass.getManager();
   final GlobalSearchScope scope = GlobalSearchScope.allScope(project);
   final PsiClass cloneable =
       JavaPsiFacade.getInstance(manager.getProject()).findClass("java.lang.Cloneable", scope);
   if (!InheritanceUtil.isInheritorOrSelf(aClass, cloneable, true)) {
     return false;
   }
   final PsiMethod[] methods = aClass.findMethodsByName("clone", false);
   for (PsiMethod method : methods) {
     final PsiParameterList parameterList = method.getParameterList();
     final PsiParameter[] parameters = parameterList.getParameters();
     if (parameters.length == 0) {
       return false;
     }
   }
   return true;
 }
Exemplo n.º 27
0
 private static boolean nameCanBeStaticallyImported(
     @NotNull String fqName, @NotNull String memberName, @NotNull PsiElement context) {
   final PsiClass containingClass = PsiTreeUtil.getParentOfType(context, PsiClass.class);
   if (containingClass == null) {
     return false;
   }
   if (InheritanceUtil.isInheritor(containingClass, fqName)) {
     return true;
   }
   final PsiField field = containingClass.findFieldByName(memberName, true);
   if (field != null) {
     return false;
   }
   final PsiMethod[] methods = containingClass.findMethodsByName(memberName, true);
   if (methods.length > 0) {
     return false;
   }
   return !hasOnDemandImportStaticConflict(fqName, memberName, context, true)
       && !hasExactImportStaticConflict(fqName, memberName, context);
 }
Exemplo n.º 28
0
    @Nullable
    private SiblingInfo findSibling(PsiClass inheritor, PsiClass anInterface, PsiMethod method) {
      for (PsiMethod superMethod : anInterface.findMethodsByName(method.getName(), true)) {
        PsiElement navigationElement = superMethod.getNavigationElement();
        if (!(navigationElement instanceof PsiMethod)) continue; // Kotlin
        superMethod = (PsiMethod) navigationElement;
        ProgressManager.checkCanceled();
        PsiClass superInterface = superMethod.getContainingClass();
        if (superInterface == null || myContainingClass.isInheritor(superInterface, true)) {
          // if containingClass implements the superInterface then it's not a sibling inheritance
          // but a pretty boring the usual one
          continue;
        }

        if (isOverridden(inheritor, method, superMethod, superInterface)) {
          return new SiblingInfo(superMethod, inheritor);
        }
      }
      return null;
    }
 private static boolean usesDefaultSerialization(PsiClass aClass) {
   final Project project = aClass.getProject();
   final PsiManager manager = aClass.getManager();
   final GlobalSearchScope scope = GlobalSearchScope.allScope(project);
   final PsiClass serializable =
       JavaPsiFacade.getInstance(manager.getProject()).findClass("java.io.Serializable", scope);
   if (!InheritanceUtil.isInheritorOrSelf(aClass, serializable, true)) {
     return false;
   }
   final PsiMethod[] methods = aClass.findMethodsByName("writeObject", false);
   for (PsiMethod method : methods) {
     final PsiParameterList parameterList = method.getParameterList();
     final PsiParameter[] parameters = parameterList.getParameters();
     if (parameters.length == 1) {
       final PsiType type = parameters[0].getType();
       final String text = type.getCanonicalText();
       if ("java.io.DataOutputStream".equals(text)) {
         return false;
       }
     }
   }
   return true;
 }
 public void testOverloadConstructors() throws Exception {
   PsiClass aClass = myJavaFacade.findClass("B", GlobalSearchScope.allScope(myProject));
   PsiMethod constructor;
   //    constructor = myJavaFacade.getElementFactory().createConstructor();
   //    constructor = aClass.findMethodBySignature(constructor, false);
   constructor = aClass.findMethodsByName("B", false)[0];
   PsiMethodCallExpression superCall =
       (PsiMethodCallExpression) constructor.getBody().getStatements()[0].getFirstChild();
   PsiReferenceExpression superExpr = superCall.getMethodExpression();
   String[] fileNames = new String[] {"B.java", "A.java", "A.java", "B.java"};
   int[] starts = new int[] {};
   int[] ends = new int[] {};
   final ArrayList<PsiFile> filesList = new ArrayList<PsiFile>();
   final IntArrayList startsList = new IntArrayList();
   final IntArrayList endsList = new IntArrayList();
   PsiReference[] refs =
       MethodReferencesSearch.search(
               (PsiMethod) superExpr.resolve(), GlobalSearchScope.projectScope(myProject), false)
           .toArray(PsiReference.EMPTY_ARRAY);
   for (PsiReference ref : refs) {
     addReference(ref, filesList, startsList, endsList);
   }
   checkResult(fileNames, filesList, starts, startsList, ends, endsList);
 }