use of org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler in project spring-integration by spring-projects.
the class SourcePollingChannelAdapterFactoryBeanTests method testInterrupted.
@Test
public void testInterrupted() throws Exception {
final CountDownLatch startLatch = new CountDownLatch(1);
MessageSource<Object> ms = () -> {
startLatch.countDown();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new MessagingException("Interrupted awaiting stopLatch", e);
}
return null;
};
SourcePollingChannelAdapter pollingChannelAdapter = new SourcePollingChannelAdapter();
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.setWaitForTasksToCompleteOnShutdown(true);
taskScheduler.setAwaitTerminationSeconds(1);
taskScheduler.afterPropertiesSet();
pollingChannelAdapter.setTaskScheduler(taskScheduler);
MessagePublishingErrorHandler errorHandler = new MessagePublishingErrorHandler();
Log errorHandlerLogger = TestUtils.getPropertyValue(errorHandler, "logger", Log.class);
errorHandlerLogger = spy(errorHandlerLogger);
DirectFieldAccessor dfa = new DirectFieldAccessor(errorHandler);
dfa.setPropertyValue("logger", errorHandlerLogger);
pollingChannelAdapter.setErrorHandler(errorHandler);
pollingChannelAdapter.setSource(ms);
pollingChannelAdapter.setOutputChannel(new NullChannel());
pollingChannelAdapter.setBeanFactory(mock(BeanFactory.class));
pollingChannelAdapter.afterPropertiesSet();
LogAccessor adapterLogger = TestUtils.getPropertyValue(pollingChannelAdapter, "logger", LogAccessor.class);
adapterLogger = spy(adapterLogger);
when(adapterLogger.isDebugEnabled()).thenReturn(true);
dfa = new DirectFieldAccessor(pollingChannelAdapter);
dfa.setPropertyValue("logger", adapterLogger);
pollingChannelAdapter.start();
assertThat(startLatch.await(10, TimeUnit.SECONDS)).isTrue();
pollingChannelAdapter.stop();
taskScheduler.shutdown();
verifyNoInteractions(errorHandlerLogger);
verify(adapterLogger).debug(ArgumentMatchers.<Supplier<String>>argThat(logMessage -> logMessage.get().contains("Poll interrupted - during stop()?")));
}
use of org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler in project spring-integration by spring-projects.
the class FileWritingMessageHandlerTests method lockForFlush.
@Test
public void lockForFlush() throws Exception {
File tempFolder = new File(tempDir, UUID.randomUUID().toString());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
final BufferedOutputStream out = spy(new BufferedOutputStream(baos));
FileWritingMessageHandler handler = new FileWritingMessageHandler(tempFolder) {
@Override
protected BufferedOutputStream createOutputStream(File fileToWriteTo, boolean append) {
return out;
}
};
handler.setFileExistsMode(FileExistsMode.APPEND_NO_FLUSH);
handler.setFileNameGenerator(message -> "foo.txt");
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.afterPropertiesSet();
handler.setTaskScheduler(taskScheduler);
handler.setOutputChannel(new NullChannel());
handler.setBeanFactory(mock(BeanFactory.class));
handler.setFlushInterval(10);
handler.setFlushWhenIdle(false);
handler.afterPropertiesSet();
handler.start();
final AtomicBoolean writing = new AtomicBoolean();
final AtomicBoolean closeWhileWriting = new AtomicBoolean();
willAnswer(i -> {
writing.set(true);
Thread.sleep(500);
writing.set(false);
return null;
}).given(out).write(any(byte[].class), anyInt(), anyInt());
willAnswer(i -> {
closeWhileWriting.compareAndSet(false, writing.get());
return null;
}).given(out).close();
handler.handleMessage(new GenericMessage<>("foo".getBytes()));
verify(out).write(any(byte[].class), anyInt(), anyInt());
assertThat(closeWhileWriting.get()).isFalse();
handler.stop();
}
use of org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler in project spring-integration by spring-projects.
the class FileWritingMessageHandlerTests method noFlushAppend.
@Test
public void noFlushAppend() throws Exception {
File tempFolder = new File(tempDir, UUID.randomUUID().toString());
FileWritingMessageHandler handler = new FileWritingMessageHandler(tempFolder);
handler.setFileExistsMode(FileExistsMode.APPEND_NO_FLUSH);
handler.setFileNameGenerator(message -> "foo.txt");
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.afterPropertiesSet();
handler.setTaskScheduler(taskScheduler);
handler.setOutputChannel(new NullChannel());
handler.setBeanFactory(mock(BeanFactory.class));
handler.setFlushInterval(30000);
handler.afterPropertiesSet();
handler.start();
File file = new File(tempFolder, "foo.txt");
handler.handleMessage(new GenericMessage<>("foo"));
handler.handleMessage(new GenericMessage<>("bar"));
handler.handleMessage(new GenericMessage<>("baz"));
// change of payload type forces flush
handler.handleMessage(new GenericMessage<>("qux".getBytes()));
assertThat(file.length()).isGreaterThanOrEqualTo(9L);
// forces flush
handler.stop();
assertThat(file.length()).isEqualTo(12L);
handler.setFlushInterval(100);
handler.start();
handler.handleMessage(new GenericMessage<InputStream>(new ByteArrayInputStream("fiz".getBytes())));
int n = 0;
while (n++ < 100 && file.length() < 15) {
Thread.sleep(100);
}
assertThat(file.length()).isEqualTo(15L);
handler.handleMessage(new GenericMessage<InputStream>(new ByteArrayInputStream("buz".getBytes())));
handler.trigger(new GenericMessage<>(Matcher.quoteReplacement(file.getAbsolutePath())));
assertThat(file.length()).isEqualTo(18L);
assertThat(TestUtils.getPropertyValue(handler, "fileStates", Map.class).size()).isEqualTo(0);
handler.setFlushInterval(30000);
final AtomicBoolean called = new AtomicBoolean();
handler.setFlushPredicate((fileAbsolutePath, firstWrite, lastWrite, triggerMessage) -> {
called.set(true);
return true;
});
handler.handleMessage(new GenericMessage<InputStream>(new ByteArrayInputStream("box".getBytes())));
handler.trigger(new GenericMessage<>("foo"));
assertThat(file.length()).isEqualTo(21L);
assertThat(called.get()).isTrue();
handler.handleMessage(new GenericMessage<InputStream>(new ByteArrayInputStream("bux".getBytes())));
called.set(false);
handler.flushIfNeeded((fileAbsolutePath, firstWrite, lastWrite) -> {
called.set(true);
return true;
});
assertThat(file.length()).isEqualTo(24L);
assertThat(called.get()).isTrue();
handler.stop();
LogAccessor logger = spy(TestUtils.getPropertyValue(handler, "logger", LogAccessor.class));
new DirectFieldAccessor(handler).setPropertyValue("logger", logger);
when(logger.isDebugEnabled()).thenReturn(true);
final AtomicInteger flushes = new AtomicInteger();
doAnswer(i -> {
flushes.incrementAndGet();
return null;
}).when(logger).debug(startsWith("Flushed:"));
handler.setFlushInterval(50);
handler.setFlushWhenIdle(false);
handler.start();
for (int i = 0; i < 40; i++) {
handler.handleMessage(new GenericMessage<>("foo"));
Thread.sleep(5);
}
assertThat(flushes.get()).isGreaterThanOrEqualTo(2);
handler.stop();
}
use of org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler in project spring-integration by spring-projects.
the class DelayHandlerTests method setup.
@BeforeEach
public void setup() {
input.setBeanName("input");
output.setBeanName("output");
taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.afterPropertiesSet();
delayHandler = new DelayHandler(DELAYER_MESSAGE_GROUP_ID, taskScheduler);
delayHandler.setOutputChannel(output);
delayHandler.setBeanFactory(mock(BeanFactory.class));
input.subscribe(delayHandler);
output.subscribe(resultHandler);
}
use of org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler in project spring-integration by spring-projects.
the class TcpOutboundGatewayTests method testAsync.
private void testAsync(boolean singleUse) throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
final AtomicBoolean done = new AtomicBoolean();
final AtomicReference<ServerSocket> serverSocket = new AtomicReference<>();
ThreadPoolTaskScheduler sched = new ThreadPoolTaskScheduler();
sched.initialize();
TcpOutboundGateway gateway = null;
try {
this.executor.execute(() -> {
try {
ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(0, 100);
serverSocket.set(server);
latch.countDown();
int i = 0;
while (true) {
Socket socket = server.accept();
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
ByteArrayCrLfSerializer deser = new ByteArrayCrLfSerializer();
try {
deser.deserialize(is);
} catch (SoftEndOfStreamException e) {
continue;
}
deser.serialize(("reply" + ++i).getBytes(), os);
if (!singleUse) {
deser.deserialize(is);
deser.serialize(("reply" + ++i).getBytes(), os);
}
socket.close();
}
} catch (Exception e) {
if (!done.get()) {
e.printStackTrace();
}
}
});
assertThat(latch.await(10000, TimeUnit.MILLISECONDS)).isTrue();
AbstractClientConnectionFactory ccf = new TcpNetClientConnectionFactory("localhost", serverSocket.get().getLocalPort());
ccf.setSoTimeout(10000);
ccf.setSingleUse(singleUse);
ccf.start();
gateway = new TcpOutboundGateway();
gateway.setConnectionFactory(ccf);
gateway.setAsync(true);
QueueChannel replyChannel = new QueueChannel();
AtomicReference<Thread> thread = new AtomicReference<>();
replyChannel.addInterceptor(new ChannelInterceptor() {
@Override
public void postSend(Message<?> message, MessageChannel channel, boolean sent) {
thread.set(Thread.currentThread());
}
});
gateway.setRequiresReply(true);
gateway.setOutputChannel(replyChannel);
gateway.setBeanFactory(mock(BeanFactory.class));
gateway.setTaskScheduler(sched);
gateway.afterPropertiesSet();
gateway.handleMessage(MessageBuilder.withPayload("Test1").build());
gateway.handleMessage(MessageBuilder.withPayload("Test2").build());
Message<?> reply1 = replyChannel.receive(10000);
assertThat(reply1).isNotNull();
if (singleUse) {
assertThat(reply1.getPayload()).satisfiesAnyOf(payload -> assertThat(payload).isEqualTo("reply1".getBytes()), payload -> assertThat(payload).isEqualTo("reply2".getBytes()));
} else {
assertThat(reply1.getPayload()).isEqualTo("reply1".getBytes());
}
Message<?> reply2 = replyChannel.receive(10000);
assertThat(reply2).isNotNull();
if (singleUse) {
assertThat(reply1.getPayload()).satisfiesAnyOf(payload -> assertThat(payload).isEqualTo("reply1".getBytes()), payload -> assertThat(payload).isEqualTo("reply2".getBytes()));
assertThat(reply1.getPayload()).isNotEqualTo(reply2.getPayload());
} else {
assertThat(reply2.getPayload()).isEqualTo("reply2".getBytes());
}
assertThat(thread.get()).isNotSameAs(Thread.currentThread());
} finally {
if (gateway != null) {
gateway.stop();
}
done.set(true);
if (serverSocket.get() != null) {
serverSocket.get().close();
}
sched.shutdown();
}
}
Aggregations