Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: Resolve annotation headers + Multiple AsyncListener/AsyncPublisher annotation #139

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import io.github.stavshamir.springwolf.asyncapi.types.channel.operation.message.header.AsyncHeaderSchema;
import io.github.stavshamir.springwolf.asyncapi.types.channel.operation.message.header.AsyncHeaders;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.StringValueResolver;

import java.lang.reflect.Method;
import java.util.Arrays;
Expand All @@ -18,7 +19,7 @@
import static java.util.stream.Collectors.groupingBy;

class AsyncAnnotationScannerUtil {
public static AsyncHeaders getAsyncHeaders(AsyncOperation op) {
public static AsyncHeaders getAsyncHeaders(AsyncOperation op, StringValueResolver resolver) {
if (op.headers().values().length == 0) {
return AsyncHeaders.NOT_DOCUMENTED;
}
Expand All @@ -27,13 +28,13 @@ public static AsyncHeaders getAsyncHeaders(AsyncOperation op) {
Arrays.stream(op.headers().values())
.collect(groupingBy(AsyncOperation.Headers.Header::name))
.forEach((headerName, headers) -> {
List<String> values = getHeaderValues(headers);
List<String> values = getHeaderValues(headers, resolver);
String exampleValue = values.stream().findFirst().orElse(null);
asyncHeaders.addHeader(
AsyncHeaderSchema
.headerBuilder()
.headerName(headerName)
.description(getDescription(headers))
.headerName(resolver.resolveStringValue(headerName))
.description(getDescription(headers, resolver))
.enumValue(values)
.example(exampleValue)
.build()
Expand All @@ -43,18 +44,20 @@ public static AsyncHeaders getAsyncHeaders(AsyncOperation op) {
return asyncHeaders;
}

private static List<String> getHeaderValues(List<AsyncOperation.Headers.Header> value) {
private static List<String> getHeaderValues(List<AsyncOperation.Headers.Header> value, StringValueResolver resolver) {
return value
.stream()
.map(AsyncOperation.Headers.Header::value)
.map(resolver::resolveStringValue)
.sorted()
.collect(Collectors.toList());
}

private static String getDescription(List<AsyncOperation.Headers.Header> value) {
private static String getDescription(List<AsyncOperation.Headers.Header> value, StringValueResolver resolver) {
return value
.stream()
.map(AsyncOperation.Headers.Header::description)
.map(resolver::resolveStringValue)
.filter(StringUtils::isNotBlank)
.sorted()
.findFirst()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import io.github.stavshamir.springwolf.asyncapi.types.OperationData;

import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
Expand Down Expand Up @@ -30,6 +31,7 @@
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(value = {ElementType.METHOD})
@Repeatable(AsyncListeners.class)
public @interface AsyncListener {
/**
* Mapped to {@link OperationData}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,11 @@
import org.springframework.util.StringValueResolver;

import java.lang.reflect.Method;
import java.util.*;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toSet;
import java.util.stream.Stream;

@Slf4j
@RequiredArgsConstructor
Expand Down Expand Up @@ -48,38 +49,40 @@ protected SchemasService getSchemaService() {
@Override
protected List<OperationData> getOperationData() {
return componentClassScanner.scan().stream()
.map(this::getAnnotatedMethods)
.flatMap(Collection::stream)
.map(this::mapMethodToOperationData)
.flatMap(this::getAnnotatedMethods)
.flatMap(this::toOperationData)
.collect(Collectors.toList());
}

private Set<Method> getAnnotatedMethods(Class<?> type) {
private Stream<Method> getAnnotatedMethods(Class<?> type) {
Class<AsyncListener> annotationClass = AsyncListener.class;
Class<AsyncListeners> annotationClassRepeatable = AsyncListeners.class;
log.debug("Scanning class \"{}\" for @\"{}\" annotated methods", type.getName(), annotationClass.getName());

return Arrays.stream(type.getDeclaredMethods())
.filter(method -> method.isAnnotationPresent(annotationClass))
.collect(toSet());
.filter(method -> method.isAnnotationPresent(annotationClass) || method.isAnnotationPresent(annotationClassRepeatable));
}

private OperationData mapMethodToOperationData(Method method) {
private Stream<OperationData> toOperationData(Method method) {
log.debug("Mapping method \"{}\" to channels", method.getName());

Map<String, OperationBinding> operationBindings = AsyncAnnotationScannerUtil.processOperationBindingFromAnnotation(method, operationBindingProcessors);
Map<String, MessageBinding> messageBindings = AsyncAnnotationScannerUtil.processMessageBindingFromAnnotation(method, messageBindingProcessors);

Class<AsyncListener> annotationClass = AsyncListener.class;
AsyncListener annotation = Optional.of(method.getAnnotation(annotationClass))
.orElseThrow(() -> new IllegalArgumentException("Method must be annotated with " + annotationClass.getName()));
return Arrays
.stream(method.getAnnotationsByType(annotationClass))
.map(annotation -> toConsumerData(method, operationBindings, messageBindings, annotation));
}

private ConsumerData toConsumerData(Method method, Map<String, OperationBinding> operationBindings, Map<String, MessageBinding> messageBindings, AsyncListener annotation) {
AsyncOperation op = annotation.operation();
Class<?> payloadType = op.payloadType() != Object.class ? op.payloadType() :
SpringPayloadAnnotationTypeExtractor.getPayloadType(method);
return ConsumerData.builder()
.channelName(resolver.resolveStringValue(op.channelName()))
.description(resolver.resolveStringValue(op.description()))
.headers(AsyncAnnotationScannerUtil.getAsyncHeaders(op))
.headers(AsyncAnnotationScannerUtil.getAsyncHeaders(op, resolver))
.payloadType(payloadType)
.operationBinding(operationBindings)
.messageBinding(messageBindings)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package io.github.stavshamir.springwolf.asyncapi.scanners.channels.operationdata.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(value = {ElementType.METHOD})
@interface AsyncListeners {
AsyncListener[] value();
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import io.github.stavshamir.springwolf.asyncapi.types.OperationData;

import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
Expand All @@ -29,6 +30,7 @@
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(value = {ElementType.METHOD})
@Repeatable(AsyncPublishers.class)
public @interface AsyncPublisher {
/**
* Mapped to {@link OperationData}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,11 @@
import org.springframework.util.StringValueResolver;

import java.lang.reflect.Method;
import java.util.*;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toSet;
import java.util.stream.Stream;

@Slf4j
@RequiredArgsConstructor
Expand Down Expand Up @@ -48,38 +49,40 @@ protected SchemasService getSchemaService() {
@Override
protected List<OperationData> getOperationData() {
return componentClassScanner.scan().stream()
.map(this::getAnnotatedMethods)
.flatMap(Collection::stream)
.map(this::mapMethodToOperationData)
.flatMap(this::getAnnotatedMethods)
.flatMap(this::toOperationData)
.collect(Collectors.toList());
}

private Set<Method> getAnnotatedMethods(Class<?> type) {
private Stream<Method> getAnnotatedMethods(Class<?> type) {
Class<AsyncPublisher> annotationClass = AsyncPublisher.class;
Class<AsyncPublishers> annotationClassRepeatable = AsyncPublishers.class;
log.debug("Scanning class \"{}\" for @\"{}\" annotated methods", type.getName(), annotationClass.getName());

return Arrays.stream(type.getDeclaredMethods())
.filter(method -> method.isAnnotationPresent(annotationClass))
.collect(toSet());
.filter(method -> method.isAnnotationPresent(annotationClass) || method.isAnnotationPresent(annotationClassRepeatable));
}

private OperationData mapMethodToOperationData(Method method) {
private Stream<OperationData> toOperationData(Method method) {
log.debug("Mapping method \"{}\" to channels", method.getName());

Map<String, OperationBinding> operationBindings = AsyncAnnotationScannerUtil.processOperationBindingFromAnnotation(method, operationBindingProcessors);
Map<String, MessageBinding> messageBindings = AsyncAnnotationScannerUtil.processMessageBindingFromAnnotation(method, messageBindingProcessors);

Class<AsyncPublisher> annotationClass = AsyncPublisher.class;
AsyncPublisher annotation = Optional.of(method.getAnnotation(annotationClass))
.orElseThrow(() -> new IllegalArgumentException("Method must be annotated with " + annotationClass.getName()));
return Arrays
.stream(method.getAnnotationsByType(annotationClass))
.map(annotation -> toConsumerData(method, operationBindings, messageBindings, annotation));
}

private ProducerData toConsumerData(Method method, Map<String, OperationBinding> operationBindings, Map<String, MessageBinding> messageBindings, AsyncPublisher annotation) {
AsyncOperation op = annotation.operation();
Class<?> payloadType = op.payloadType() != Object.class ? op.payloadType() :
SpringPayloadAnnotationTypeExtractor.getPayloadType(method);
return ProducerData.builder()
.channelName(resolver.resolveStringValue(op.channelName()))
.description(resolver.resolveStringValue(op.description()))
.headers(AsyncAnnotationScannerUtil.getAsyncHeaders(op))
.headers(AsyncAnnotationScannerUtil.getAsyncHeaders(op, resolver))
.payloadType(payloadType)
.operationBinding(operationBindings)
.messageBinding(messageBindings)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package io.github.stavshamir.springwolf.asyncapi.scanners.channels.operationdata.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(value = {ElementType.METHOD})
@interface AsyncPublishers {
AsyncPublisher[] value();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package io.github.stavshamir.springwolf.asyncapi.scanners.channels.operationdata.annotation;

import com.asyncapi.v2.binding.OperationBinding;
import io.github.stavshamir.springwolf.asyncapi.types.channel.operation.message.header.AsyncHeaders;
import org.assertj.core.util.Maps;
import org.junit.jupiter.api.Test;
import org.springframework.util.StringValueResolver;

import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Map;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

class AsyncAnnotationScannerUtilTest {

@Test
void getAsyncHeaders() throws NoSuchMethodException {
// given
Method m = ClassWithOperationBindingProcessor.class.getDeclaredMethod("methodWithAnnotation", String.class);
AsyncOperation operation = m.getAnnotation(AsyncListener.class).operation();

StringValueResolver resolver = mock(StringValueResolver.class);

// when
when(resolver.resolveStringValue(any())).thenAnswer(invocation -> invocation.getArgument(0).toString()+"Resolved");

// then
AsyncHeaders headers = AsyncAnnotationScannerUtil.getAsyncHeaders(operation, resolver);
assertEquals(headers.getSchemaName(), "TestSchema");
assertTrue(headers.containsKey("headerResolved"));
assertEquals(headers.get("headerResolved").getType(), "string");
assertEquals(headers.get("headerResolved").getExample(), "valueResolved");
assertEquals(headers.get("headerResolved").getDescription(), "descriptionResolved");
}

@Test
void processBindingFromAnnotation() throws NoSuchMethodException {
// given
Method m = ClassWithOperationBindingProcessor.class.getDeclaredMethod("methodWithAnnotation", String.class);

// when
Map<String, OperationBinding> bindings = AsyncAnnotationScannerUtil.processOperationBindingFromAnnotation(m, Collections.singletonList(new TestOperationBindingProcessor()));

// then
assertEquals(Maps.newHashMap(TestOperationBindingProcessor.TYPE, TestOperationBindingProcessor.BINDING), bindings);
}

private static class ClassWithOperationBindingProcessor {
@AsyncListener(operation = @AsyncOperation(
channelName = "${test.property.test-channel}",
description = "${test.property.description}",
headers = @AsyncOperation.Headers(
schemaName = "TestSchema",
values = {@AsyncOperation.Headers.Header(name = "header", value = "value", description = "description")}
)
))
@TestOperationBindingProcessor.TestOperationBinding()
private void methodWithAnnotation(String payload) {
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,55 @@ public void scan_componentHasListenerMethodWithAllAttributes() {
.containsExactly(Maps.immutableEntry("test-channel", expectedChannel));
}

@Test
public void scan_componentHasMultipleListenerAnnotations() {
// Given a class with methods annotated with AsyncListener, where only the channel-name is set
setClassToScan(ClassWithMultipleListenerAnnotations.class);

// When scan is called
Map<String, ChannelItem> actualChannels = channelScanner.scan();

// Then the returned collection contains the channel
Message message = Message.builder()
.name(SimpleFoo.class.getName())
.title(SimpleFoo.class.getSimpleName())
.description("")
.payload(PayloadReference.fromModelName(SimpleFoo.class.getSimpleName()))
.headers(HeaderReference.fromModelName(AsyncHeaders.NOT_DOCUMENTED.getSchemaName()))
.bindings(EMPTY_MAP)
.build();

Operation operation1 = Operation.builder()
.description("Auto-generated description")
.operationId("test-channel-1_publish")
.bindings(EMPTY_MAP)
.message(message)
.build();

ChannelItem expectedChannel1 = ChannelItem.builder()
.bindings(null)
.publish(operation1)
.build();

Operation operation2 = Operation.builder()
.description("Auto-generated description")
.operationId("test-channel-2_publish")
.bindings(EMPTY_MAP)
.message(message)
.build();

ChannelItem expectedChannel2 = ChannelItem.builder()
.bindings(null)
.publish(operation2)
.build();

assertThat(actualChannels)
.containsExactlyEntriesOf(
ImmutableMap.of(
"test-channel-1", expectedChannel1,
"test-channel-2", expectedChannel2));
}


private static class ClassWithoutListenerAnnotation {

Expand Down Expand Up @@ -160,6 +209,18 @@ private void methodWithoutAnnotation() {
}
}

private static class ClassWithMultipleListenerAnnotations {

@AsyncListener(operation = @AsyncOperation(
channelName = "test-channel-1"
))
@AsyncListener(operation = @AsyncOperation(
channelName = "test-channel-2"
))
private void methodWithMultipleAnnotation(SimpleFoo payload) {
}
}

@Data
@NoArgsConstructor
private static class SimpleFoo {
Expand Down
Loading