use of org.springframework.core.log.LogAccessor in project spring-integration by spring-projects.
the class MqttAdapterTests method testDifferentQos.
@Test
public void testDifferentQos() throws Exception {
DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
MqttConnectOptions connectOptions = new MqttConnectOptions();
connectOptions.setCleanSession(false);
connectOptions.setConnectionTimeout(23);
connectOptions.setKeepAliveInterval(45);
connectOptions.setPassword("pass".toCharArray());
MemoryPersistence persistence = new MemoryPersistence();
factory.setPersistence(persistence);
final SocketFactory socketFactory = SocketFactory.getDefault();
connectOptions.setSocketFactory(socketFactory);
final Properties props = new Properties();
connectOptions.setSSLProperties(props);
connectOptions.setUserName("user");
connectOptions.setWill("foo", "bar".getBytes(), 2, true);
factory = spy(factory);
MqttAsyncClient aClient = mock(MqttAsyncClient.class);
final MqttClient client = mock(MqttClient.class);
willAnswer(invocation -> client).given(factory).getClientInstance(anyString(), anyString());
given(client.isConnected()).willReturn(true);
new DirectFieldAccessor(client).setPropertyValue("aClient", aClient);
willAnswer(new CallsRealMethods()).given(client).connect(any(MqttConnectOptions.class));
willAnswer(new CallsRealMethods()).given(client).subscribe(any(String[].class), any(int[].class));
willAnswer(new CallsRealMethods()).given(client).subscribe(any(String[].class), any(int[].class), isNull());
willReturn(alwaysComplete).given(aClient).connect(any(MqttConnectOptions.class), any(), any());
IMqttToken token = mock(IMqttToken.class);
given(token.getGrantedQos()).willReturn(new int[] { 2, 0 });
willReturn(token).given(aClient).subscribe(any(String[].class), any(int[].class), isNull(), isNull(), any());
MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter("foo", "bar", factory, "baz", "fix");
AtomicReference<Method> method = new AtomicReference<>();
ReflectionUtils.doWithMethods(MqttPahoMessageDrivenChannelAdapter.class, m -> {
m.setAccessible(true);
method.set(m);
}, m -> m.getName().equals("connectAndSubscribe"));
assertThat(method.get()).isNotNull();
LogAccessor logger = spy(TestUtils.getPropertyValue(adapter, "logger", LogAccessor.class));
new DirectFieldAccessor(adapter).setPropertyValue("logger", logger);
given(logger.isWarnEnabled()).willReturn(true);
method.get().invoke(adapter);
verify(logger, atLeastOnce()).warn(ArgumentMatchers.<Supplier<? extends CharSequence>>argThat(logMessage -> logMessage.get().equals("Granted QOS different to Requested QOS; topics: [baz, fix] " + "requested: [1, 1] granted: [2, 0]")));
verify(client).setTimeToWait(30_000L);
new DirectFieldAccessor(adapter).setPropertyValue("running", Boolean.TRUE);
adapter.stop();
verify(client).disconnectForcibly(5_000L);
}
use of org.springframework.core.log.LogAccessor in project spring-integration by spring-projects.
the class MqttAdapterTests method testReconnect.
@Test
public void testReconnect() throws Exception {
final IMqttClient client = mock(IMqttClient.class);
MqttPahoMessageDrivenChannelAdapter adapter = buildAdapterIn(client, null, ConsumerStopAction.UNSUBSCRIBE_NEVER);
adapter.setRecoveryInterval(10);
LogAccessor logger = spy(TestUtils.getPropertyValue(adapter, "logger", LogAccessor.class));
new DirectFieldAccessor(adapter).setPropertyValue("logger", logger);
given(logger.isDebugEnabled()).willReturn(true);
final AtomicInteger attemptingReconnectCount = new AtomicInteger();
willAnswer(i -> {
if (attemptingReconnectCount.getAndIncrement() == 0) {
adapter.connectionLost(new RuntimeException("while schedule running"));
}
i.callRealMethod();
return null;
}).given(logger).debug("Attempting reconnect");
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.initialize();
adapter.setTaskScheduler(taskScheduler);
adapter.start();
adapter.connectionLost(new RuntimeException("initial"));
verify(client).close();
Thread.sleep(1000);
// the following assertion should be equalTo, but leq to protect against a slow CI server
assertThat(attemptingReconnectCount.get()).isLessThanOrEqualTo(2);
AtomicReference<Object> failed = new AtomicReference<>();
adapter.setApplicationEventPublisher(failed::set);
adapter.connectionLost(new IllegalStateException());
assertThat(failed.get()).isInstanceOf(MqttConnectionFailedEvent.class);
adapter.stop();
taskScheduler.destroy();
}
use of org.springframework.core.log.LogAccessor in project spring-integration by spring-projects.
the class LoggingHandlerTests method testChangeLevel.
@Test
@SuppressWarnings("unchecked")
public void testChangeLevel() {
LoggingHandler loggingHandler = new LoggingHandler(Level.INFO);
loggingHandler.setBeanFactory(mock(BeanFactory.class));
loggingHandler.afterPropertiesSet();
DirectFieldAccessor accessor = new DirectFieldAccessor(loggingHandler);
LogAccessor log = (LogAccessor) accessor.getPropertyValue("messageLogger");
log = spy(log);
accessor.setPropertyValue("messageLogger", log);
when(log.isInfoEnabled()).thenReturn(true);
loggingHandler.handleMessage(new GenericMessage<>("foo"));
verify(log, times(1)).info(any(Supplier.class));
verify(log, never()).warn(any(Supplier.class));
loggingHandler.setLevel(Level.WARN);
loggingHandler.handleMessage(new GenericMessage<>("foo"));
verify(log, times(1)).info(any(Supplier.class));
verify(log, times(1)).warn(any(Supplier.class));
}
use of org.springframework.core.log.LogAccessor in project spring-integration by spring-projects.
the class JsonToObjectTransformerParserTests method testDefaultObjectMapper.
@Test
@SuppressWarnings("unchecked")
public void testDefaultObjectMapper() {
Object jsonToObjectTransformer = TestUtils.getPropertyValue(this.defaultJacksonMapperTransformer, "transformer");
assertThat(TestUtils.getPropertyValue(jsonToObjectTransformer, "jsonObjectMapper").getClass()).isEqualTo(Jackson2JsonObjectMapper.class);
DirectFieldAccessor dfa = new DirectFieldAccessor(jsonToObjectTransformer);
LogAccessor logger = (LogAccessor) spy(dfa.getPropertyValue("logger"));
dfa.setPropertyValue("logger", logger);
String jsonString = "{\"firstName\":\"John\",\"lastName\":\"Doe\",\"age\":42," + "\"address\":{\"number\":123,\"street\":\"Main Street\"}}";
QueueChannel replyChannel = new QueueChannel();
Message<String> message = MessageBuilder.withPayload(jsonString).setReplyChannel(replyChannel).build();
this.defaultObjectMapperInput.send(message);
Message<?> reply = replyChannel.receive(0);
assertThat(reply).isNotNull();
assertThat(reply.getPayload()).isNotNull();
assertThat(reply.getPayload().getClass()).isEqualTo(TestPerson.class);
TestPerson person = (TestPerson) reply.getPayload();
assertThat(person.getFirstName()).isEqualTo("John");
assertThat(person.getLastName()).isEqualTo("Doe");
assertThat(person.getAge()).isEqualTo(42);
assertThat(person.getAddress().toString()).isEqualTo("123 Main Street");
ArgumentCaptor<Supplier<String>> argumentCaptor = ArgumentCaptor.forClass(Supplier.class);
verify(logger).debug(any(Exception.class), argumentCaptor.capture());
String logMessage = argumentCaptor.getValue().get();
assertThat(logMessage).startsWith("Cannot build a ResolvableType from the request message");
}
use of org.springframework.core.log.LogAccessor in project spring-integration by spring-projects.
the class AsyncAmqpGatewayTests method testConfirmsAndReturns.
@Test
void testConfirmsAndReturns() throws Exception {
CachingConnectionFactory ccf = new CachingConnectionFactory("localhost");
ccf.setPublisherConfirmType(CachingConnectionFactory.ConfirmType.CORRELATED);
ccf.setPublisherReturns(true);
RabbitTemplate template = new RabbitTemplate(ccf);
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(ccf);
container.setBeanName("replyContainer");
container.setQueueNames("asyncRQ1");
container.afterPropertiesSet();
container.start();
AsyncRabbitTemplate asyncTemplate = new AsyncRabbitTemplate(template, container);
asyncTemplate.setEnableConfirms(true);
asyncTemplate.setMandatory(true);
SimpleMessageListenerContainer receiver = new SimpleMessageListenerContainer(ccf);
receiver.setBeanName("receiver");
receiver.setQueueNames("asyncQ1");
final CountDownLatch waitForAckBeforeReplying = new CountDownLatch(1);
MessageListenerAdapter messageListener = new MessageListenerAdapter((ReplyingMessageListener<String, String>) foo -> {
try {
waitForAckBeforeReplying.await(10, TimeUnit.SECONDS);
} catch (@SuppressWarnings("unused") InterruptedException e) {
Thread.currentThread().interrupt();
}
return foo.toUpperCase();
});
receiver.setMessageListener(messageListener);
receiver.afterPropertiesSet();
receiver.start();
AsyncAmqpOutboundGateway gateway = new AsyncAmqpOutboundGateway(asyncTemplate);
LogAccessor logger = spy(TestUtils.getPropertyValue(gateway, "logger", LogAccessor.class));
given(logger.isDebugEnabled()).willReturn(true);
final CountDownLatch replyTimeoutLatch = new CountDownLatch(1);
willAnswer(invocation -> {
invocation.callRealMethod();
replyTimeoutLatch.countDown();
return null;
}).given(logger).debug(ArgumentMatchers.<Supplier<String>>argThat(logMessage -> logMessage.get().startsWith("Reply not required and async timeout for")));
new DirectFieldAccessor(gateway).setPropertyValue("logger", logger);
QueueChannel outputChannel = new QueueChannel();
outputChannel.setBeanName("output");
QueueChannel returnChannel = new QueueChannel();
returnChannel.setBeanName("returns");
QueueChannel ackChannel = new QueueChannel();
ackChannel.setBeanName("acks");
QueueChannel errorChannel = new QueueChannel();
errorChannel.setBeanName("errors");
gateway.setOutputChannel(outputChannel);
gateway.setReturnChannel(returnChannel);
gateway.setConfirmAckChannel(ackChannel);
gateway.setConfirmNackChannel(ackChannel);
gateway.setConfirmCorrelationExpressionString("#this");
gateway.setExchangeName("");
gateway.setRoutingKey("asyncQ1");
gateway.setBeanFactory(mock(BeanFactory.class));
gateway.afterPropertiesSet();
gateway.start();
Message<?> message = MessageBuilder.withPayload("foo").setErrorChannel(errorChannel).build();
gateway.handleMessage(message);
Message<?> ack = ackChannel.receive(10000);
assertThat(ack).isNotNull();
assertThat(ack.getPayload()).isEqualTo("foo");
assertThat(ack.getHeaders().get(AmqpHeaders.PUBLISH_CONFIRM)).isEqualTo(true);
waitForAckBeforeReplying.countDown();
Message<?> received = outputChannel.receive(10000);
assertThat(received).isNotNull();
assertThat(received.getPayload()).isEqualTo("FOO");
// timeout tests
asyncTemplate.setReceiveTimeout(10);
receiver.setMessageListener(message1 -> {
});
// reply timeout with no requiresReply
message = MessageBuilder.withPayload("bar").setErrorChannel(errorChannel).build();
gateway.handleMessage(message);
assertThat(replyTimeoutLatch.await(10, TimeUnit.SECONDS)).isTrue();
// reply timeout with requiresReply
gateway.setRequiresReply(true);
message = MessageBuilder.withPayload("baz").setErrorChannel(errorChannel).build();
gateway.handleMessage(message);
received = errorChannel.receive(10000);
assertThat(received).isInstanceOf(ErrorMessage.class);
ErrorMessage error = (ErrorMessage) received;
assertThat(error.getPayload()).isInstanceOf(MessagingException.class);
assertThat(error.getPayload().getCause()).isInstanceOf(AmqpReplyTimeoutException.class);
asyncTemplate.setReceiveTimeout(30000);
receiver.setMessageListener(messageListener);
// error on sending result
DirectChannel errorForce = new DirectChannel();
errorForce.setBeanName("errorForce");
errorForce.subscribe(message1 -> {
throw new RuntimeException("intentional");
});
gateway.setOutputChannel(errorForce);
message = MessageBuilder.withPayload("qux").setErrorChannel(errorChannel).build();
gateway.handleMessage(message);
received = errorChannel.receive(10000);
assertThat(received).isInstanceOf(ErrorMessage.class);
error = (ErrorMessage) received;
assertThat(error.getPayload()).isInstanceOf(MessagingException.class);
assertThat(((MessagingException) error.getPayload()).getFailedMessage().getPayload()).isEqualTo("QUX");
gateway.setRoutingKey(UUID.randomUUID().toString());
message = MessageBuilder.withPayload("fiz").setErrorChannel(errorChannel).build();
gateway.handleMessage(message);
Message<?> returned = returnChannel.receive(10000);
assertThat(returned).isNotNull();
assertThat(returned).isInstanceOf(ErrorMessage.class);
assertThat(returned.getPayload()).isInstanceOf(ReturnedAmqpMessageException.class);
ReturnedAmqpMessageException payload = (ReturnedAmqpMessageException) returned.getPayload();
assertThat(payload.getFailedMessage().getPayload()).isEqualTo("fiz");
ackChannel.receive(10000);
ackChannel.purge(null);
asyncTemplate = mock(AsyncRabbitTemplate.class);
RabbitMessageFuture future = asyncTemplate.new RabbitMessageFuture(null, null);
willReturn(future).given(asyncTemplate).sendAndReceive(anyString(), anyString(), any(org.springframework.amqp.core.Message.class));
DirectFieldAccessor dfa = new DirectFieldAccessor(future);
dfa.setPropertyValue("nackCause", "nacknack");
SettableListenableFuture<Boolean> confirmFuture = new SettableListenableFuture<>();
confirmFuture.set(false);
dfa.setPropertyValue("confirm", confirmFuture);
new DirectFieldAccessor(gateway).setPropertyValue("template", asyncTemplate);
message = MessageBuilder.withPayload("buz").setErrorChannel(errorChannel).build();
gateway.handleMessage(message);
ack = ackChannel.receive(10000);
assertThat(ack).isNotNull();
assertThat(returned).isInstanceOf(ErrorMessage.class);
assertThat(returned.getPayload()).isInstanceOf(ReturnedAmqpMessageException.class);
NackedAmqpMessageException nack = (NackedAmqpMessageException) ack.getPayload();
assertThat(nack.getFailedMessage().getPayload()).isEqualTo("buz");
assertThat(nack.getNackReason()).isEqualTo("nacknack");
asyncTemplate.stop();
receiver.stop();
ccf.destroy();
}
Aggregations