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

Fixes the saga list injection bug, issue 2462. #2463

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
32 changes: 32 additions & 0 deletions config/src/main/java/org/axonframework/config/Configuration.java
Expand Up @@ -43,7 +43,9 @@
import org.axonframework.serialization.upcasting.event.EventUpcasterChain;
import org.axonframework.tracing.SpanFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
Expand Down Expand Up @@ -272,6 +274,36 @@ default <T> T getComponent(@Nonnull Class<T> componentType) {
*/
<T> T getComponent(@Nonnull Class<T> componentType, @Nonnull Supplier<T> defaultImpl);

/**
* Returns the Components declared under the given {@code componentType}, typically the interface the component
* implements.
*
* @param componentType The type of component
* @param <T> The type of component
* @return the component registered for the given type, or {@code null} if no such component exists
*/
default <T> List<T> getComponents(@Nonnull Class<T> componentType) {
return getComponents(componentType, () -> null);
}

/**
* Returns the Components declared under the given {@code componentType}, typically the interface the component
* implements, reverting to the given {@code defaultImpl} if no such component is defined.
* <p>
* When no component was previously registered, the default is then configured as the component for the given type.
*
* @param componentType The type of component
* @param defaultImpl The supplier of the default to return if no component was registered
* @param <T> The type of component
* @return the component registered for the given type, or the value returned by the {@code defaultImpl} supplier,
* if no component was registered
*/
default <T> List<T> getComponents(@Nonnull Class<T> componentType, @Nonnull Supplier<T> defaultImpl) {
List<T> result = new ArrayList<>();
Optional.ofNullable(getComponent(componentType, defaultImpl)).ifPresent(result::add);
return result;
}

/**
* Returns the message monitor configured for a component of given {@code componentType} and {@code componentName}.
*
Expand Down
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2010-2018. Axon Framework
* Copyright (c) 2010-2022. Axon Framework
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -18,6 +18,7 @@

import org.axonframework.modelling.saga.AbstractResourceInjector;

import java.util.Collection;
import java.util.Optional;

/**
Expand All @@ -40,4 +41,9 @@ public ConfigurationResourceInjector(Configuration configuration) {
protected <R> Optional<R> findResource(Class<R> requiredType) {
return Optional.ofNullable(configuration.getComponent(requiredType));
}

@Override
protected <R> Collection<R> findResources(Class<R> requiredType) {
return configuration.getComponents(requiredType);
}
}
Expand Up @@ -301,6 +301,21 @@ protected <T> Optional<T> defaultComponent(Class<T> type, Configuration configur
return Optional.empty();
}

/**
* Method returning a default component to use for given {@code type} for given {@code configuration}, or an empty
* Optional if no default can be provided.
*
* @param type The type of component to find a default for.
* @param configuration The configuration the component is configured in.
* @param <T> The type of component.
* @return An Optional containing a default component, or empty if none can be provided.
*/
protected <T> List<T> defaultComponents(Class<T> type, Configuration configuration) {
List<T> result = new ArrayList<>();
defaultComponent(type, configuration).ifPresent(result::add);
return result;
}

/**
* Returns a {@link DefaultCommandGateway} that will use the configuration's {@link CommandBus} to dispatch
* commands.
Expand Down Expand Up @@ -932,6 +947,31 @@ public <T> T getComponent(@Nonnull Class<T> componentType, @Nonnull Supplier<T>
return componentType.cast(component);
}

@SuppressWarnings("unchecked")
@Override
public <T> List<T> getComponents(@Nonnull Class<T> componentType, @Nonnull Supplier<T> defaultImpl) {
List<T> result = new ArrayList<>();
components.forEach(
(t, c) -> {
if (t.isAssignableFrom(componentType)) {
result.add((T) c.get());
}
}
);
List<T> defaultComponents = defaultComponents(componentType, config);
if (defaultComponents.isEmpty()) {
Optional.ofNullable(getComponent(componentType, defaultImpl)).ifPresent(result::add);
} else {
defaultComponents.forEach(d -> components.put(d.getClass(), new Component<>(
config,
d.getClass().getSimpleName(),
c -> d
)));
return defaultComponents;
}
return result;
}

@Override
public <M extends Message<?>> MessageMonitor<? super M> messageMonitor(@Nonnull Class<?> componentType,
@Nonnull String componentName) {
Expand Down
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2010-2018. Axon Framework
* Copyright (c) 2010-2022. Axon Framework
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -24,6 +24,11 @@
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;

Expand Down Expand Up @@ -58,10 +63,28 @@ private void injectFieldResources(Object saga) {
.filter(ann -> AnnotationUtils.isAnnotationPresent(field, ann))
.forEach(annotatedFields -> {
Class<?> requiredType = field.getType();
findResource(requiredType).ifPresent(resource -> injectFieldResource(saga, field, resource));
if (Arrays.asList(requiredType.getInterfaces()).contains(Collection.class)) {
injectCollection(saga, requiredType, field);
} else {
injectSingleton(saga, requiredType, field);
}
findResource(requiredType).ifPresent(resource -> injectFieldResource(saga,
field,
resource));
}));
}

private void injectSingleton(Object saga, Class<?> requiredType, Field field) {
findResource(requiredType).ifPresent(resource -> injectFieldResource(saga, field, resource));
}

private void injectCollection(Object saga, Class<?> requiredType, Field field) {
ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType();
Class<?> collectionOf = (Class<?>) parameterizedType.getActualTypeArguments()[0];
Collection<?> collection = findResources(collectionOf);
injectFieldResource(saga, field, transformCollectionToCorrectType(collection, requiredType));
}

/**
* Returns a resource of given {@code requiredType} or an empty Optional if the resource is not registered with the
* injector.
Expand All @@ -72,6 +95,16 @@ private void injectFieldResources(Object saga) {
*/
protected abstract <R> Optional<R> findResource(Class<R> requiredType);

/**
* Returns resources of given {@code requiredType} or an empty Collection if the resource is not registered with the
* injector.
*
* @param requiredType the class of the resource to find
* @param <R> the resource type
* @return a Collection that contains as many resources as are found
*/
protected abstract <R> Collection<R> findResources(Class<R> requiredType);

private void injectFieldResource(Object saga, Field injectField, Object resource) {
try {
ReflectionUtils.ensureAccessible(injectField);
Expand All @@ -87,10 +120,34 @@ private void injectMethodResources(Object saga) {
.filter(a -> AnnotationUtils.isAnnotationPresent(method, a))
.forEach(a -> {
Class<?> requiredType = method.getParameterTypes()[0];
findResource(requiredType).ifPresent(resource -> injectMethodResource(saga, method, resource));
if (Arrays.asList(requiredType.getInterfaces()).contains(Collection.class)) {
injectCollection(saga, requiredType, method);
} else {
injectSingleton(saga, requiredType, method);
}
}));
}

private void injectSingleton(Object saga, Class<?> requiredType, Method method) {
findResource(requiredType).ifPresent(resource -> injectMethodResource(saga, method, resource));
}

private void injectCollection(Object saga, Class<?> requiredType, Method method) {
ParameterizedType parameterizedType = (ParameterizedType) method.getGenericParameterTypes()[0];
Class<?> collectionOf = (Class<?>) parameterizedType.getActualTypeArguments()[0];
Collection<?> collection = findResources(collectionOf);
injectMethodResource(saga, method, transformCollectionToCorrectType(collection, requiredType));
}

private Collection<?> transformCollectionToCorrectType(Collection<?> collection, Class<?> requiredType) {
if (requiredType.isAssignableFrom(List.class)) {
return new ArrayList<>(collection);
} else {
throw new SagaInstantiationException(String.format("don't know how to create instance of %s", requiredType),
new RuntimeException("injecting collection failed"));
}
}

private void injectMethodResource(Object saga, Method injectMethod, Object resource) {
try {
ReflectionUtils.ensureAccessible(injectMethod);
Expand Down
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2010-2018. Axon Framework
* Copyright (c) 2010-2022. Axon Framework
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -19,14 +19,14 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.stream.StreamSupport;

/**
* A resource injector that checks for @Inject annotated fields and setter methods to inject resources. If a field is
* annotated with @Inject, a Resource of the type of that field is injected into it, if present. If
* a method is annotated with @Inject, the method is invoked with a Resource of the type of the first parameter, if
* present.
* annotated with @Inject, a Resource of the type of that field is injected into it, if present. If a method is
* annotated with @Inject, the method is invoked with a Resource of the type of the first parameter, if present.
*
* @author Allard Buijze
* @since 1.1
Expand Down Expand Up @@ -59,8 +59,19 @@ public SimpleResourceInjector(Collection<?> resources) {
@Override
protected <R> Optional<R> findResource(Class<R> requiredType) {
return (Optional<R>) StreamSupport.stream(resources.spliterator(), false)
.filter(requiredType::isInstance)
.findFirst();
.filter(requiredType::isInstance)
.findFirst();
}

@SuppressWarnings("unchecked")
@Override
protected <R> Collection<R> findResources(Class<R> requiredType) {
List<R> result = new ArrayList<>();
resources.forEach(i -> {
if (requiredType.isInstance(i)) {
result.add((R) i);
}
});
return result;
}
}
Expand Up @@ -155,6 +155,11 @@ public <T> T getComponent(@Nonnull Class<T> componentType, @Nonnull Supplier<T>
return config.getComponent(componentType, defaultImpl);
}

@Override
public <T> List<T> getComponents(@Nonnull Class<T> componentType, @Nonnull Supplier<T> defaultImpl) {
return config.getComponents(componentType, defaultImpl);
}

@Override
public <M extends Message<?>> MessageMonitor<? super M> messageMonitor(@Nonnull Class<?> componentType,
@Nonnull String componentName) {
Expand Down
Expand Up @@ -21,7 +21,9 @@
import org.axonframework.config.DefaultConfigurer;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
Expand Down Expand Up @@ -50,6 +52,11 @@ protected <T> Optional<T> defaultComponent(Class<T> type, Configuration config)
return locator.findBean(type);
}

@Override
protected <T> List<T> defaultComponents(Class<T> type, Configuration config) {
return locator.findBeans(type);
}

private static class ComponentLocator {

private final ConfigurableListableBeanFactory beanFactory;
Expand All @@ -68,12 +75,19 @@ public <T> Optional<T> findBean(Class<T> componentType) {
} else {
Optional<T> primary = findPrimary(componentType, candidates);
if (!primary.isPresent()) {
throw new AxonConfigurationException("Expected single candidate for component [" + componentType.getSimpleName() + "]. Found candidates: " + Arrays.deepToString(candidates));
throw new AxonConfigurationException(
"Expected single candidate for component [" + componentType.getSimpleName()
+ "]. Found candidates: " + Arrays.deepToString(candidates));
}
return primary;
}
}

public <T> List<T> findBeans(Class<T> componentType) {
String[] candidates = beanFactory.getBeanNamesForType(componentType);
return findAll(componentType, candidates);
}

private <T> Optional<T> findPrimary(Class<T> componentType, String[] candidates) {
String primary = null;
for (String candidate : candidates) {
Expand All @@ -91,5 +105,13 @@ private <T> Optional<T> findPrimary(Class<T> componentType, String[] candidates)
return Optional.of(beanFactory.getBean(primary, componentType));
}
}

private <T> List<T> findAll(Class<T> componentType, String[] candidates) {
List<T> result = new ArrayList<>();
Arrays.stream(candidates).forEach(
c -> result.add(beanFactory.getBean(c, componentType))
);
return result;
}
}
}