com.tngtech.archunit.core.domain.JavaMethod Java Examples

The following examples show how to use com.tngtech.archunit.core.domain.JavaMethod. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Module.java    From moduliths with Apache License 2.0 6 votes vote down vote up
private static Classes filterSpringBeans(JavaPackage source) {

		Map<Boolean, List<JavaClass>> collect = source.that(isConfiguration()).stream() //
				.flatMap(it -> it.getMethods().stream()) //
				.filter(SpringTypes::isAtBeanMethod) //
				.map(JavaMethod::getRawReturnType) //
				.collect(Collectors.groupingBy(it -> source.contains(it)));

		Classes repositories = source.that(isSpringDataRepository());
		Classes coreComponents = source.that(not(INTERFACES).and(isComponent()));

		return coreComponents //
				.and(repositories) //
				.and(collect.getOrDefault(true, Collections.emptyList())) //
				.and(collect.getOrDefault(false, Collections.emptyList()));
	}
 
Example #2
Source File: PublicAPIRules.java    From ArchUnit with Apache License 2.0 6 votes vote down vote up
private static ArchCondition<? super JavaCodeUnit> haveContravariantPredicateParameterTypes() {
    return new ArchCondition<JavaCodeUnit>("have contravariant predicate parameter types") {
        @Override
        public void check(JavaCodeUnit javaCodeUnit, ConditionEvents events) {
            Type[] parameterTypes = javaCodeUnit.isConstructor()
                    ? ((JavaConstructor) javaCodeUnit).reflect().getGenericParameterTypes()
                    : ((JavaMethod) javaCodeUnit).reflect().getGenericParameterTypes();

            stream(parameterTypes)
                    .filter(type -> type instanceof ParameterizedType)
                    .map(type -> (ParameterizedType) type)
                    .filter(type -> type.getRawType().equals(DescribedPredicate.class))
                    .map(predicateType -> predicateType.getActualTypeArguments()[0])
                    .filter(predicateTypeParameter -> !(predicateTypeParameter instanceof WildcardType)
                            || ((WildcardType) predicateTypeParameter).getLowerBounds().length == 0)
                    .forEach(type -> {
                        String message = String.format("%s has a parameter %s<%s> instead of a contravariant type parameter in %s",
                                javaCodeUnit.getDescription(), DescribedPredicate.class.getSimpleName(), type.getTypeName(), javaCodeUnit.getSourceCodeLocation());
                        events.add(violated(javaCodeUnit, message));
                    });
        }
    };
}
 
Example #3
Source File: ArchConditionsTest.java    From ArchUnit with Apache License 2.0 6 votes vote down vote up
@Test
public void never_call_method_where_target_owner_is_assignable_to() {
    JavaClass callingClass = importClassWithContext(CallingClass.class);
    AccessesSimulator simulateCall = simulateCall();
    JavaClass someClass = importClassWithContext(SomeClass.class);
    JavaMethod doNotCallMe = someClass.getMethod("doNotCallMe");
    JavaMethodCall callTodoNotCallMe = simulateCall.from(callingClass.getMethod("call"), 0).to(doNotCallMe);

    ArchCondition<JavaClass> condition = never(callMethodWhere(target(name("doNotCallMe"))
            .and(target(owner(assignableTo(SomeSuperClass.class))))));
    assertThat(condition).checking(callingClass)
            .containViolations(callTodoNotCallMe.getDescription());

    condition = never(callMethodWhere(target(name("doNotCallMe")).and(target(owner(type(SomeSuperClass.class))))));
    assertThat(condition).checking(callingClass)
            .containNoViolation();
}
 
Example #4
Source File: ClassFileImporterTest.java    From ArchUnit with Apache License 2.0 6 votes vote down vote up
@Test
public void imports_methods_with_two_annotations_correctly() throws Exception {
    JavaClass clazz = classesIn("testexamples/annotationmethodimport").get(ClassWithAnnotatedMethods.class);

    JavaMethod method = findAnyByName(clazz.getMethods(), stringAndIntAnnotatedMethod);
    Set<JavaAnnotation<JavaMethod>> annotations = method.getAnnotations();
    assertThat(annotations).hasSize(2);
    assertThat(annotations).extractingResultOf("getOwner").containsOnly(method);
    assertThat(annotations).extractingResultOf("getAnnotatedElement").containsOnly(method);

    JavaAnnotation<?> annotationWithString = method.getAnnotationOfType(MethodAnnotationWithStringValue.class.getName());
    assertThat(annotationWithString.get("value").get()).isEqualTo("otherThing");

    JavaAnnotation<?> annotationWithInt = method.getAnnotationOfType(MethodAnnotationWithIntValue.class.getName());
    assertThat(annotationWithInt.get("otherValue").get()).isEqualTo("overridden");

    assertThat(method).isEquivalentTo(ClassWithAnnotatedMethods.class.getMethod(stringAndIntAnnotatedMethod));
}
 
Example #5
Source File: ClassFileImporterTest.java    From ArchUnit with Apache License 2.0 6 votes vote down vote up
@Test
public void imports_enclosing_classes() throws Exception {
    ImportedClasses classes = classesIn("testexamples/innerclassimport");
    JavaClass classWithInnerClass = classes.get(ClassWithInnerClass.class);
    JavaClass innerClass = classes.get(ClassWithInnerClass.Inner.class);
    JavaClass anonymousClass = classes.get(ClassWithInnerClass.class.getName() + "$1");
    JavaClass localClass = classes.get(ClassWithInnerClass.class.getName() + "$1LocalCaller");
    JavaMethod calledTarget = getOnlyElement(classes.get(CalledClass.class).getMethods());

    assertThat(innerClass.getEnclosingClass()).contains(classWithInnerClass);
    assertThat(anonymousClass.getEnclosingClass()).contains(classWithInnerClass);
    assertThat(localClass.getEnclosingClass()).contains(classWithInnerClass);

    JavaMethodCall call = getOnlyElement(innerClass.getCodeUnitWithParameterTypes("call").getMethodCallsFromSelf());
    assertThatCall(call).isFrom("call").isTo(calledTarget).inLineNumber(31);

    call = getOnlyElement(anonymousClass.getCodeUnitWithParameterTypes("call").getMethodCallsFromSelf());
    assertThatCall(call).isFrom("call").isTo(calledTarget).inLineNumber(11);

    call = getOnlyElement(localClass.getCodeUnitWithParameterTypes("call").getMethodCallsFromSelf());
    assertThatCall(call).isFrom("call").isTo(calledTarget).inLineNumber(21);
}
 
Example #6
Source File: ApplicationComponentsTest.java    From archunit-examples with MIT License 6 votes vote down vote up
@Override
public void check(JavaClass clazz, ConditionEvents events) {
  Set<JavaMethod> methods = clazz.getMethods();
  Predicate<JavaMethod> hasMethodNamedInvoke = method -> method.getName().equals("invoke");
  if (methods.stream().filter(hasMethodNamedInvoke).count() != 1) {
    events.add(SimpleConditionEvent.violated(clazz, "${clazz.simpleName} does not have a single 'invoke' method"));
    return;
  }
  methods.stream().filter(hasMethodNamedInvoke).findFirst().ifPresent(invokeMethod -> {
    JavaClassList parameters = invokeMethod.getRawParameterTypes();
    if (parameters.size() != 1 || parameters.stream().noneMatch(it -> it.isInnerClass() && it.getSimpleName().equals("Request"))) {
      events.add(SimpleConditionEvent.violated(invokeMethod, "${clazz.simpleName}: method 'invoke' does not have a single parameter that is named 'request' and of inner-class type 'Request'"));
    }
    JavaClass returnType = invokeMethod.getRawReturnType();
    if (!returnType.isInnerClass() || !returnType.getSimpleName().equals("Response")) {
      events.add(SimpleConditionEvent.violated(invokeMethod, "${clazz.simpleName}: method 'invoke' does not have a return type that is of inner-class type 'Response'"));
    }
  });
}
 
Example #7
Source File: ArchRuleDefinition.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@PublicAPI(usage = ACCESS)
public GivenMethods noMethods() {
    return new GivenMethodsInternal(
            priority,
            Transformers.methods().as("no " + Transformers.methods().getDescription()),
            ArchRuleDefinition.<JavaMethod>negateCondition());
}
 
Example #8
Source File: JavaClassProcessor.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
private Optional<Class<?>> determineComponentType(ClassesByTypeName importedClasses) {
    if (derivedComponentType != null) {
        return Optional.<Class<?>>of(derivedComponentType);
    }

    JavaClass annotationType = importedClasses.get(annotationArrayContext.getDeclaringAnnotationTypeName());
    Optional<JavaMethod> method = annotationType
            .tryGetMethod(annotationArrayContext.getDeclaringAnnotationMemberName());

    return method.isPresent() ?
            determineComponentTypeFromReturnValue(method.get()) :
            Optional.<Class<?>>absent();
}
 
Example #9
Source File: MethodsShouldInternal.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
MethodsShouldInternal(
        ClassesTransformer<? extends JavaMethod> classesTransformer,
        Priority priority,
        ArchCondition<JavaMethod> condition,
        Function<ArchCondition<JavaMethod>, ArchCondition<JavaMethod>> prepareCondition) {

    super(classesTransformer, priority, condition, prepareCondition);
}
 
Example #10
Source File: MethodsShouldInternal.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
MethodsShouldInternal(
        ClassesTransformer<? extends JavaMethod> classesTransformer,
        Priority priority,
        Function<ArchCondition<JavaMethod>, ArchCondition<JavaMethod>> prepareCondition) {

    super(classesTransformer, priority, prepareCondition);
}
 
Example #11
Source File: GivenMethodsInternal.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Override
public GivenMethodsInternal create(
        Priority priority,
        ClassesTransformer<JavaMethod> classesTransformer,
        Function<ArchCondition<JavaMethod>, ArchCondition<JavaMethod>> prepareCondition,
        PredicateAggregator<JavaMethod> relevantObjectsPredicates,
        Optional<String> overriddenDescription) {

    return new GivenMethodsInternal(this,
            priority, classesTransformer, prepareCondition, relevantObjectsPredicates, overriddenDescription);
}
 
Example #12
Source File: ClassFileImporterTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void imports_own_set_field_access() throws Exception {
    JavaClass classWithOwnFieldAccess = classesIn("testexamples/fieldaccessimport").get(OwnFieldAccess.class);

    JavaMethod setStringValue = classWithOwnFieldAccess.getMethod("setStringValue", String.class);

    JavaFieldAccess access = getOnlyElement(setStringValue.getFieldAccesses());
    assertThatAccess(access)
            .isOfType(SET)
            .isFrom(setStringValue)
            .isTo(classWithOwnFieldAccess.getField("stringValue"))
            .inLineNumber(12);
}
 
Example #13
Source File: ImportTestUtils.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
public static JavaFieldAccess newFieldAccess(JavaMethod origin, JavaField target, int lineNumber, JavaFieldAccess.AccessType accessType) {
    return new DomainBuilders.JavaFieldAccessBuilder()
            .withOrigin(origin)
            .withTarget(targetFrom(target))
            .withLineNumber(lineNumber)
            .withAccessType(accessType)
            .build();
}
 
Example #14
Source File: ClassFileImporterTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void imports_methods_with_one_annotation_correctly() throws Exception {
    JavaClass clazz = classesIn("testexamples/annotationmethodimport").get(ClassWithAnnotatedMethods.class);

    JavaMethod method = findAnyByName(clazz.getMethods(), stringAnnotatedMethod);
    JavaAnnotation<JavaMethod> annotation = method.getAnnotationOfType(MethodAnnotationWithStringValue.class.getName());
    assertThat(annotation.getRawType()).matches(MethodAnnotationWithStringValue.class);
    assertThat(annotation.getOwner()).isEqualTo(method);
    assertThat(annotation.get("value").get()).isEqualTo("something");

    assertThat(method).isEquivalentTo(ClassWithAnnotatedMethods.class.getMethod(stringAnnotatedMethod));
}
 
Example #15
Source File: ClassFileImporterTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void methods_handle_optional_annotation_correctly() throws Exception {
    Set<JavaMethod> methods = classesIn("testexamples/annotationmethodimport").getMethods();

    JavaMethod method = findAnyByName(methods, "stringAnnotatedMethod");
    assertThat(method.tryGetAnnotationOfType(MethodAnnotationWithStringValue.class)).isPresent();
    assertThat(method.tryGetAnnotationOfType(MethodAnnotationWithEnumAndArrayValue.class)).isAbsent();

    Optional<JavaAnnotation<JavaMethod>> optionalAnnotation = method.tryGetAnnotationOfType(MethodAnnotationWithStringValue.class.getName());
    assertThat(optionalAnnotation.get().getOwner()).as("owner of optional annotation").isEqualTo(method);
    assertThat(method.tryGetAnnotationOfType(MethodAnnotationWithEnumAndArrayValue.class.getName())).isAbsent();
}
 
Example #16
Source File: ClassFileImporterTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void imports_methods_with_complex_annotations_correctly() throws Exception {
    JavaClass clazz = classesIn("testexamples/annotationmethodimport").get(ClassWithAnnotatedMethods.class);

    JavaMethod method = findAnyByName(clazz.getMethods(), enumAndArrayAnnotatedMethod);

    JavaAnnotation<?> annotation = method.getAnnotationOfType(MethodAnnotationWithEnumAndArrayValue.class.getName());
    assertThat((JavaEnumConstant) annotation.get("value").get()).isEquivalentTo(OTHER_VALUE);
    assertThat((JavaEnumConstant) annotation.get("valueWithDefault").get()).isEquivalentTo(SOME_VALUE);
    assertThat(((JavaEnumConstant[]) annotation.get("enumArray").get())).matches(SOME_VALUE, OTHER_VALUE);
    assertThat(((JavaEnumConstant[]) annotation.get("enumArrayWithDefault").get())).matches(OTHER_VALUE);
    JavaAnnotation<?> subAnnotation = (JavaAnnotation<?>) annotation.get("subAnnotation").get();
    assertThat(subAnnotation.get("value").get()).isEqualTo("changed");
    assertThat(subAnnotation.getOwner()).isEqualTo(annotation);
    assertThat(subAnnotation.getAnnotatedElement()).isEqualTo(method);
    assertThat(((JavaAnnotation<?>) annotation.get("subAnnotationWithDefault").get()).get("value").get())
            .isEqualTo("default");
    JavaAnnotation<?>[] subAnnotationArray = (JavaAnnotation<?>[]) annotation.get("subAnnotationArray").get();
    assertThat(subAnnotationArray[0].get("value").get()).isEqualTo("another");
    assertThat(subAnnotationArray[0].getOwner()).isEqualTo(annotation);
    assertThat(subAnnotationArray[0].getAnnotatedElement()).isEqualTo(method);
    assertThat(((JavaAnnotation<?>[]) annotation.get("subAnnotationArrayWithDefault").get())[0].get("value").get())
            .isEqualTo("first");
    assertThat((JavaClass) annotation.get("clazz").get()).matches(Map.class);
    assertThat((JavaClass) annotation.get("clazzWithDefault").get()).matches(String.class);
    assertThat((JavaClass[]) annotation.get("classes").get()).matchExactly(Object.class, Serializable.class);
    assertThat((JavaClass[]) annotation.get("classesWithDefault").get()).matchExactly(Serializable.class, List.class);

    assertThat(method).isEquivalentTo(ClassWithAnnotatedMethods.class.getMethod(enumAndArrayAnnotatedMethod));
}
 
Example #17
Source File: ClassFileImporterTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void imports_own_get_field_access() throws Exception {
    JavaClass classWithOwnFieldAccess = classesIn("testexamples/fieldaccessimport").get(OwnFieldAccess.class);

    JavaMethod getStringValue = classWithOwnFieldAccess.getMethod("getStringValue");

    JavaFieldAccess access = getOnlyElement(getStringValue.getFieldAccesses());
    assertThatAccess(access)
            .isOfType(GET)
            .isFrom(getStringValue)
            .isTo("stringValue")
            .inLineNumber(8);
}
 
Example #18
Source File: Module.java    From moduliths with Apache License 2.0 5 votes vote down vote up
private static String getDescriptionFor(JavaMember member) {

			if (JavaConstructor.class.isInstance(member)) {
				return "constructor";
			} else if (JavaMethod.class.isInstance(member)) {
				return "injection method";
			} else if (JavaField.class.isInstance(member)) {
				return "injected field";
			}

			throw new IllegalArgumentException(String.format("Invalid member type %s!", member.toString()));
		}
 
Example #19
Source File: JavaClassProcessor.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
private Optional<Class<?>> determineComponentTypeFromReturnValue(JavaMethod method) {
    if (method.getRawReturnType().isEquivalentTo(Class[].class)) {
        return Optional.<Class<?>>of(JavaClass.class);
    }

    return resolveComponentTypeFrom(method.getRawReturnType().getName());
}
 
Example #20
Source File: ImportTestUtils.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
public static MethodCallTarget targetFrom(JavaMethod target, Supplier<Set<JavaMethod>> resolveSupplier) {
    return new DomainBuilders.MethodCallTargetBuilder()
            .withOwner(target.getOwner())
            .withName(target.getName())
            .withParameters(target.getRawParameterTypes())
            .withReturnType(target.getRawReturnType())
            .withMethods(resolveSupplier)
            .build();
}
 
Example #21
Source File: ClassGraphCreator.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
void registerMethods(Set<JavaMethod> methods) {
    for (JavaMethod method : methods) {
        for (JavaClass parameter : method.getRawParameterTypes()) {
            methodParameterTypeDependencies.put(parameter, method);
        }
        methodReturnTypeDependencies.put(method.getRawReturnType(), method);
        for (ThrowsDeclaration<JavaMethod> throwsDeclaration : method.getThrowsClause()) {
            methodsThrowsDeclarationDependencies.put(throwsDeclaration.getRawType(), throwsDeclaration);
        }
    }
}
 
Example #22
Source File: MethodsShouldInternal.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
private MethodsShouldInternal(
        ClassesTransformer<? extends JavaMethod> classesTransformer,
        Priority priority,
        ConditionAggregator<JavaMethod> conditionAggregator,
        Function<ArchCondition<JavaMethod>, ArchCondition<JavaMethod>> prepareCondition) {

    super(classesTransformer, priority, conditionAggregator, prepareCondition);
}
 
Example #23
Source File: AccessRecord.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Override
public MethodCallTarget getTarget() {
    Supplier<Set<JavaMethod>> methodsSupplier = new MethodTargetSupplier(targetOwner.getAllMethods(), record.target);
    JavaClassList parameters = getArgumentTypesFrom(record.target.desc, classes);
    JavaClass returnType = classes.getOrResolve(JavaTypeImporter.importAsmMethodReturnType(record.target.desc).getName());
    return new MethodCallTargetBuilder()
            .withOwner(targetOwner)
            .withName(record.target.name)
            .withParameters(parameters)
            .withReturnType(returnType)
            .withMethods(methodsSupplier)
            .build();
}
 
Example #24
Source File: ImportTestUtils.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
private static Set<DomainBuilders.BuilderWithBuildParameter<JavaClass, JavaMethod>> methodBuildersFor(Class<?> inputClass,
        ClassesByTypeName importedClasses) {
    final Set<DomainBuilders.BuilderWithBuildParameter<JavaClass, JavaMethod>> methodBuilders = new HashSet<>();
    for (Method method : inputClass.getDeclaredMethods()) {
        methodBuilders.add(new DomainBuilders.JavaMethodBuilder()
                .withReturnType(JavaType.From.name(method.getReturnType().getName()))
                .withParameters(typesFrom(method.getParameterTypes()))
                .withName(method.getName())
                .withDescriptor(Type.getMethodDescriptor(method))
                .withAnnotations(javaAnnotationBuildersFrom(method.getAnnotations(), inputClass, importedClasses))
                .withModifiers(JavaModifier.getModifiersForMethod(method.getModifiers()))
                .withThrowsClause(typesFrom(method.getExceptionTypes())));
    }
    return methodBuilders;
}
 
Example #25
Source File: RawAccessRecord.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean signatureExistsIn(JavaClass javaClass) {
    for (JavaMethod method : javaClass.getMethods()) {
        if (hasMatchingSignatureTo(method)) {
            return true;
        }
    }
    return false;
}
 
Example #26
Source File: DomainBuilders.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Override
JavaMethod construct(JavaMethodBuilder builder, final ClassesByTypeName importedClasses) {
    if (annotationDefaultValueBuilder.isPresent()) {
        annotationDefaultValue = Suppliers.memoize(new DefaultValueSupplier(getOwner(), annotationDefaultValueBuilder.get(), importedClasses));
    }
    return DomainObjectCreationContext.createJavaMethod(builder);
}
 
Example #27
Source File: DomainBuilders.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
private void addDefaultValues(ImmutableMap.Builder<String, Object> result, ClassesByTypeName importedClasses) {
    for (JavaMethod method : importedClasses.get(type.getName()).getMethods()) {
        if (!values.containsKey(method.getName()) && method.getDefaultValue().isPresent()) {
            result.put(method.getName(), method.getDefaultValue().get());
        }
    }
}
 
Example #28
Source File: SlicesTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Test
public void slices_of_dependencies() {
    JavaMethod methodThatCallsJavaUtil = TestUtils.importClassWithContext(Object.class).getMethod("toString");
    JavaMethod methodThatCallsJavaLang = TestUtils.importClassWithContext(Map.class).getMethod("put", Object.class, Object.class);
    simulateCall().from(methodThatCallsJavaUtil, 5).to(methodThatCallsJavaLang);
    simulateCall().from(methodThatCallsJavaLang, 1).to(methodThatCallsJavaUtil);

    Dependency first = dependencyFrom(getOnlyElement(methodThatCallsJavaUtil.getMethodCallsFromSelf()));
    Dependency second = dependencyFrom(getOnlyElement(methodThatCallsJavaLang.getMethodCallsFromSelf()));

    Slices slices = Slices.matching("java.(*)..").transform(ImmutableSet.of(first, second));

    assertThat(slices).extractingResultOf("getDescription").containsOnly("Slice lang", "Slice util");
}
 
Example #29
Source File: GivenThatIsTestedConsistentlyTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
private void assertAccessFrom(JavaClass test, JavaMethod method) {
    for (JavaMethodCall call : method.getAccessesToSelf()) {
        if (call.getOriginOwner().equals(test)) {
            return;
        }
    }
    Assert.fail("Method " + method.getFullName() + " is not called by " + test.getName());
}
 
Example #30
Source File: JavaMethodsAssertion.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
private boolean contains(Class<?> owner, String name, Class<?>[] parameterTypes) {
    for (JavaMethod method : actual) {
        if (method.getOwner().isEquivalentTo(owner) && method.getName().equals(name) && rawParameterTypes(parameterTypes).apply(method)) {
            return true;
        }
    }
    return false;
}