Search in sources :

Example 16 with ThreadPoolTaskScheduler

use of org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler in project spring-integration by spring-projects.

the class DelayerHandlerRescheduleIntegrationTests method testDelayerHandlerRescheduleWithMongoDbMessageStore.

@SuppressWarnings("unchecked")
private void testDelayerHandlerRescheduleWithMongoDbMessageStore(String config) throws Exception {
    AbstractApplicationContext context = new ClassPathXmlApplicationContext(config, this.getClass());
    MessageChannel input = context.getBean("input", MessageChannel.class);
    MessageGroupStore messageStore = context.getBean("messageStore", MessageGroupStore.class);
    String delayerMessageGroupId = DELAYER_ID + ".messageGroupId";
    messageStore.removeMessageGroup(delayerMessageGroupId);
    Message<String> message1 = MessageBuilder.withPayload("test1").build();
    input.send(message1);
    input.send(MessageBuilder.withPayload("test2").build());
    // Emulate restart and check DB state before next start
    // Interrupt taskScheduler as quickly as possible
    ThreadPoolTaskScheduler taskScheduler = (ThreadPoolTaskScheduler) IntegrationContextUtils.getTaskScheduler(context);
    taskScheduler.shutdown();
    taskScheduler.getScheduledExecutor().awaitTermination(10, TimeUnit.SECONDS);
    assertEquals(2, messageStore.messageGroupSize(delayerMessageGroupId));
    MessageGroup messageGroup = messageStore.getMessageGroup(delayerMessageGroupId);
    Iterator<Message<?>> iterator = messageGroup.getMessages().iterator();
    Message<?> messageInStore = iterator.next();
    Object payload = messageInStore.getPayload();
    // INT-3049
    assertTrue(payload instanceof DelayHandler.DelayedMessageWrapper);
    Message<String> original1 = (Message<String>) ((DelayHandler.DelayedMessageWrapper) payload).getOriginal();
    messageInStore = iterator.next();
    Message<String> original2 = (Message<String>) ((DelayHandler.DelayedMessageWrapper) messageInStore.getPayload()).getOriginal();
    assertThat(message1, Matchers.anyOf(Matchers.is(original1), Matchers.is(original2)));
    context.close();
    context.refresh();
    PollableChannel output = context.getBean("output", PollableChannel.class);
    Message<?> message = output.receive(20000);
    assertNotNull(message);
    Object payload1 = message.getPayload();
    message = output.receive(20000);
    assertNotNull(message);
    Object payload2 = message.getPayload();
    assertNotSame(payload1, payload2);
    messageStore = context.getBean("messageStore", MessageGroupStore.class);
    assertEquals(0, messageStore.messageGroupSize(delayerMessageGroupId));
    context.close();
}
Also used : DelayHandler(org.springframework.integration.handler.DelayHandler) MessageGroupStore(org.springframework.integration.store.MessageGroupStore) Message(org.springframework.messaging.Message) MessageGroup(org.springframework.integration.store.MessageGroup) ThreadPoolTaskScheduler(org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler) AbstractApplicationContext(org.springframework.context.support.AbstractApplicationContext) MessageChannel(org.springframework.messaging.MessageChannel) ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) PollableChannel(org.springframework.messaging.PollableChannel)

Example 17 with ThreadPoolTaskScheduler

use of org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler in project spring-integration by spring-projects.

the class MqttAdapterTests method testInboundOptionsApplied.

@Test
public void testInboundOptionsApplied() throws Exception {
    DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
    factory.setCleanSession(false);
    factory.setConnectionTimeout(23);
    factory.setKeepAliveInterval(45);
    factory.setPassword("pass");
    MemoryPersistence persistence = new MemoryPersistence();
    factory.setPersistence(persistence);
    final SocketFactory socketFactory = mock(SocketFactory.class);
    factory.setSocketFactory(socketFactory);
    final Properties props = new Properties();
    factory.setSslProperties(props);
    factory.setUserName("user");
    Will will = new Will("foo", "bar".getBytes(), 2, true);
    factory.setWill(will);
    factory = spy(factory);
    final IMqttClient client = mock(IMqttClient.class);
    willAnswer(invocation -> client).given(factory).getClientInstance(anyString(), anyString());
    final AtomicBoolean connectCalled = new AtomicBoolean();
    final AtomicBoolean failConnection = new AtomicBoolean();
    final CountDownLatch waitToFail = new CountDownLatch(1);
    final CountDownLatch failInProcess = new CountDownLatch(1);
    final CountDownLatch goodConnection = new CountDownLatch(2);
    final MqttException reconnectException = new MqttException(MqttException.REASON_CODE_SERVER_CONNECT_ERROR);
    willAnswer(invocation -> {
        if (failConnection.get()) {
            failInProcess.countDown();
            waitToFail.await(10, TimeUnit.SECONDS);
            throw reconnectException;
        }
        MqttConnectOptions options = invocation.getArgument(0);
        assertEquals(23, options.getConnectionTimeout());
        assertEquals(45, options.getKeepAliveInterval());
        assertEquals("pass", new String(options.getPassword()));
        assertSame(socketFactory, options.getSocketFactory());
        assertSame(props, options.getSSLProperties());
        assertEquals("user", options.getUserName());
        assertEquals("foo", options.getWillDestination());
        assertEquals("bar", new String(options.getWillMessage().getPayload()));
        assertEquals(2, options.getWillMessage().getQos());
        connectCalled.set(true);
        goodConnection.countDown();
        return null;
    }).given(client).connect(any(MqttConnectOptions.class));
    final AtomicReference<MqttCallback> callback = new AtomicReference<MqttCallback>();
    willAnswer(invocation -> {
        callback.set(invocation.getArgument(0));
        return null;
    }).given(client).setCallback(any(MqttCallback.class));
    given(client.isConnected()).willReturn(true);
    MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter("foo", "bar", factory, "baz", "fix");
    QueueChannel outputChannel = new QueueChannel();
    adapter.setOutputChannel(outputChannel);
    ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
    taskScheduler.initialize();
    adapter.setTaskScheduler(taskScheduler);
    adapter.setBeanFactory(mock(BeanFactory.class));
    ApplicationEventPublisher applicationEventPublisher = mock(ApplicationEventPublisher.class);
    final BlockingQueue<MqttIntegrationEvent> events = new LinkedBlockingQueue<MqttIntegrationEvent>();
    willAnswer(invocation -> {
        events.add(invocation.getArgument(0));
        return null;
    }).given(applicationEventPublisher).publishEvent(any(MqttIntegrationEvent.class));
    adapter.setApplicationEventPublisher(applicationEventPublisher);
    adapter.setRecoveryInterval(500);
    adapter.afterPropertiesSet();
    adapter.start();
    verify(client, times(1)).connect(any(MqttConnectOptions.class));
    assertTrue(connectCalled.get());
    MqttMessage message = new MqttMessage("qux".getBytes());
    callback.get().messageArrived("baz", message);
    Message<?> outMessage = outputChannel.receive(0);
    assertNotNull(outMessage);
    assertEquals("qux", outMessage.getPayload());
    MqttIntegrationEvent event = events.poll(10, TimeUnit.SECONDS);
    assertThat(event, instanceOf(MqttSubscribedEvent.class));
    assertEquals("Connected and subscribed to [baz, fix]", ((MqttSubscribedEvent) event).getMessage());
    // lose connection and make first reconnect fail
    failConnection.set(true);
    RuntimeException e = new RuntimeException("foo");
    adapter.connectionLost(e);
    event = events.poll(10, TimeUnit.SECONDS);
    assertThat(event, instanceOf(MqttConnectionFailedEvent.class));
    assertSame(event.getCause(), e);
    assertTrue(failInProcess.await(10, TimeUnit.SECONDS));
    waitToFail.countDown();
    failConnection.set(false);
    event = events.poll(10, TimeUnit.SECONDS);
    assertThat(event, instanceOf(MqttConnectionFailedEvent.class));
    assertSame(event.getCause(), reconnectException);
    // reconnect can now succeed; however, we might have other failures on a slow server (500ms retry).
    assertTrue(goodConnection.await(10, TimeUnit.SECONDS));
    int n = 0;
    while (!(event instanceof MqttSubscribedEvent) && n++ < 20) {
        event = events.poll(10, TimeUnit.SECONDS);
    }
    assertThat(event, instanceOf(MqttSubscribedEvent.class));
    assertEquals("Connected and subscribed to [baz, fix]", ((MqttSubscribedEvent) event).getMessage());
    taskScheduler.destroy();
}
Also used : MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) QueueChannel(org.springframework.integration.channel.QueueChannel) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Properties(java.util.Properties) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) ThreadPoolTaskScheduler(org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler) MqttPahoMessageDrivenChannelAdapter(org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter) MqttException(org.eclipse.paho.client.mqttv3.MqttException) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) BeanFactory(org.springframework.beans.factory.BeanFactory) Will(org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory.Will) MqttIntegrationEvent(org.springframework.integration.mqtt.event.MqttIntegrationEvent) DefaultMqttPahoClientFactory(org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) SocketFactory(javax.net.SocketFactory) MqttCallback(org.eclipse.paho.client.mqttv3.MqttCallback) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) IMqttClient(org.eclipse.paho.client.mqttv3.IMqttClient) MqttSubscribedEvent(org.springframework.integration.mqtt.event.MqttSubscribedEvent) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) MqttConnectionFailedEvent(org.springframework.integration.mqtt.event.MqttConnectionFailedEvent) Test(org.junit.Test)

Example 18 with ThreadPoolTaskScheduler

use of org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler in project spring-integration by spring-projects.

the class ByteStreamWritingMessageHandlerTests method initialize.

@Before
public void initialize() {
    stream = new ByteArrayOutputStream();
    handler = new ByteStreamWritingMessageHandler(stream);
    this.channel = new QueueChannel(10);
    this.endpoint = new PollingConsumer(channel, handler);
    scheduler = new ThreadPoolTaskScheduler();
    this.endpoint.setTaskScheduler(scheduler);
    scheduler.afterPropertiesSet();
    trigger.reset();
    endpoint.setTrigger(trigger);
    endpoint.setBeanFactory(mock(BeanFactory.class));
}
Also used : PollingConsumer(org.springframework.integration.endpoint.PollingConsumer) QueueChannel(org.springframework.integration.channel.QueueChannel) BeanFactory(org.springframework.beans.factory.BeanFactory) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ThreadPoolTaskScheduler(org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler) Before(org.junit.Before)

Example 19 with ThreadPoolTaskScheduler

use of org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler in project spring-integration by spring-projects.

the class CharacterStreamWritingMessageHandlerTests method initialize.

@Before
public void initialize() {
    writer = new StringWriter();
    handler = new CharacterStreamWritingMessageHandler(writer);
    this.channel = new QueueChannel(10);
    trigger.reset();
    this.endpoint = new PollingConsumer(channel, handler);
    scheduler = new ThreadPoolTaskScheduler();
    this.endpoint.setTaskScheduler(scheduler);
    scheduler.afterPropertiesSet();
    trigger.reset();
    endpoint.setTrigger(trigger);
    endpoint.setBeanFactory(mock(BeanFactory.class));
}
Also used : PollingConsumer(org.springframework.integration.endpoint.PollingConsumer) StringWriter(java.io.StringWriter) QueueChannel(org.springframework.integration.channel.QueueChannel) BeanFactory(org.springframework.beans.factory.BeanFactory) ThreadPoolTaskScheduler(org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler) Before(org.junit.Before)

Example 20 with ThreadPoolTaskScheduler

use of org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler in project spring-integration by spring-projects.

the class TcpSendingMessageHandlerTests method testNetCrLfClientMode.

@Test
public void testNetCrLfClientMode() throws Exception {
    final AtomicReference<ServerSocket> serverSocket = new AtomicReference<ServerSocket>();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicBoolean done = new AtomicBoolean();
    this.executor.execute(() -> {
        try {
            ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(0);
            serverSocket.set(server);
            latch.countDown();
            Socket socket = server.accept();
            int i = 0;
            while (true) {
                byte[] b = new byte[6];
                readFully(socket.getInputStream(), b);
                b = ("Reply" + (++i) + "\r\n").getBytes();
                socket.getOutputStream().write(b);
            }
        } catch (Exception e) {
            if (!done.get()) {
                e.printStackTrace();
            }
        }
    });
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    AbstractConnectionFactory ccf = new TcpNetClientConnectionFactory("localhost", serverSocket.get().getLocalPort());
    noopPublisher(ccf);
    ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer();
    ccf.setSerializer(serializer);
    ccf.setDeserializer(serializer);
    ccf.setSoTimeout(Integer.MAX_VALUE);
    TcpSendingMessageHandler handler = new TcpSendingMessageHandler();
    handler.setConnectionFactory(ccf);
    TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter();
    adapter.setConnectionFactory(ccf);
    QueueChannel channel = new QueueChannel();
    adapter.setOutputChannel(channel);
    handler.setClientMode(true);
    handler.setRetryInterval(10000);
    handler.setBeanFactory(mock(BeanFactory.class));
    handler.afterPropertiesSet();
    ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
    taskScheduler.setPoolSize(1);
    taskScheduler.initialize();
    handler.setTaskScheduler(taskScheduler);
    handler.start();
    adapter.start();
    handler.handleMessage(MessageBuilder.withPayload("Test").build());
    handler.handleMessage(MessageBuilder.withPayload("Test").build());
    Message<?> mOut = channel.receive(10000);
    assertNotNull(mOut);
    assertEquals("Reply1", new String((byte[]) mOut.getPayload()));
    mOut = channel.receive(10000);
    assertNotNull(mOut);
    assertEquals("Reply2", new String((byte[]) mOut.getPayload()));
    done.set(true);
    handler.stop();
    handler.start();
    handler.stop();
    adapter.stop();
    ccf.stop();
    serverSocket.get().close();
}
Also used : ByteArrayCrLfSerializer(org.springframework.integration.ip.tcp.serializer.ByteArrayCrLfSerializer) AbstractConnectionFactory(org.springframework.integration.ip.tcp.connection.AbstractConnectionFactory) QueueChannel(org.springframework.integration.channel.QueueChannel) ServerSocket(java.net.ServerSocket) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) TcpNetClientConnectionFactory(org.springframework.integration.ip.tcp.connection.TcpNetClientConnectionFactory) MessagingException(org.springframework.messaging.MessagingException) SocketException(java.net.SocketException) IOException(java.io.IOException) ThreadPoolTaskScheduler(org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) BeanFactory(org.springframework.beans.factory.BeanFactory) ServerSocket(java.net.ServerSocket) Socket(java.net.Socket) Test(org.junit.Test)

Aggregations

ThreadPoolTaskScheduler (org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler)122 Test (org.junit.Test)41 Bean (org.springframework.context.annotation.Bean)32 BeanFactory (org.springframework.beans.factory.BeanFactory)31 Test (org.junit.jupiter.api.Test)26 CountDownLatch (java.util.concurrent.CountDownLatch)19 QueueChannel (org.springframework.integration.channel.QueueChannel)19 GenericMessage (org.springframework.messaging.support.GenericMessage)13 AtomicReference (java.util.concurrent.atomic.AtomicReference)12 ExecutorService (java.util.concurrent.ExecutorService)10 DirectFieldAccessor (org.springframework.beans.DirectFieldAccessor)8 MqttPahoMessageDrivenChannelAdapter (org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter)8 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)7 MqttPahoMessageHandler (org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler)6 JmsTemplate (org.springframework.jms.core.JmsTemplate)6 ArrayList (java.util.ArrayList)5 Log (org.apache.commons.logging.Log)5 MessageChannel (org.springframework.messaging.MessageChannel)5 File (java.io.File)4 ConnectionFactory (javax.jms.ConnectionFactory)4