de.otto.synapse.consumer.MethodInvokingMessageConsumer Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of synapse-core Show documentation
Show all versions of synapse-core Show documentation
A library used at otto.de to implement Spring Boot based event-sourcing microservices.
package de.otto.synapse.consumer;
import de.otto.synapse.message.Message;
import jakarta.annotation.Nonnull;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Objects;
import java.util.regex.Pattern;
/**
* A {@link MessageConsumer} that is calling a method of a class instance for every accepted {@link Message}
*
*
*
* @param The expected type of the message's payload
*/
public class MethodInvokingMessageConsumer implements MessageConsumer {
private final Pattern keyPattern;
private final Class payloadType;
private final Object instance;
private final Method method;
public MethodInvokingMessageConsumer(final String keyPattern,
final Class payloadType,
final Object instance,
final Method method) {
Objects.requireNonNull(keyPattern, "keyPattern must not be null");
Objects.requireNonNull(payloadType, "payloadType must not be null");
Objects.requireNonNull(instance, "Unable to build MethodInvokingMessageConsumer: instance parameter is null");
Objects.requireNonNull(method, "Unable to build MethodInvokingNMessageConsumer: method parameter is null");
if (method.getParameterCount() != 1) {
throw new IllegalArgumentException("Unable to build MethodInvokingMessageConsumer: illegal number of arguments");
}
final Class> paramType = method.getParameterTypes()[0];
if (!paramType.equals(Message.class)) {
throw new IllegalArgumentException("Unable to build MethodInvokingMessageConsumer: expected parameter type is Message, not " + paramType.getName());
}
this.keyPattern = Pattern.compile(keyPattern);
this.payloadType = payloadType;
this.method = method;
this.instance = instance;
}
/**
* Returns the expected payload type of {@link Message messages} consumed by this MessageConsumer.
*
* @return payload type
*/
@Nonnull
@Override
public Class payloadType() {
return payloadType;
}
/**
* Returns the pattern of {@link Message#getKey()} () message keys} accepted by this consumer.
*
* @return Pattern
*/
@Nonnull
@Override
public Pattern keyPattern() {
return keyPattern;
}
@Override
public void accept(final Message message) {
try {
method.invoke(instance, message);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new IllegalStateException(e);
}
}
}