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 ExpressionEvaluatingMessageSourceIntegrationTests method test.
@Test
public void test() throws Exception {
QueueChannel channel = new QueueChannel();
String payloadExpression = "'test-' + T(org.springframework.integration.endpoint.ExpressionEvaluatingMessageSourceIntegrationTests).next()";
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.afterPropertiesSet();
Map<String, Expression> headerExpressions = new HashMap<String, Expression>();
headerExpressions.put("foo", new LiteralExpression("x"));
headerExpressions.put("bar", new SpelExpressionParser().parseExpression("7 * 6"));
ExpressionFactoryBean factoryBean = new ExpressionFactoryBean(payloadExpression);
factoryBean.afterPropertiesSet();
Expression expression = factoryBean.getObject();
ExpressionEvaluatingMessageSource<Object> source = new ExpressionEvaluatingMessageSource<Object>(expression, Object.class);
source.setBeanFactory(mock(BeanFactory.class));
source.setHeaderExpressions(headerExpressions);
SourcePollingChannelAdapter adapter = new SourcePollingChannelAdapter();
adapter.setSource(source);
adapter.setTaskScheduler(scheduler);
adapter.setMaxMessagesPerPoll(3);
adapter.setTrigger(new PeriodicTrigger(60000));
adapter.setOutputChannel(channel);
adapter.setErrorHandler(t -> {
throw new IllegalStateException("unexpected exception in test", t);
});
adapter.start();
List<Message<?>> messages = new ArrayList<Message<?>>();
for (int i = 0; i < 3; i++) {
messages.add(channel.receive(1000));
}
scheduler.destroy();
Message<?> message1 = messages.get(0);
assertThat(message1.getPayload()).isEqualTo("test-1");
assertThat(message1.getHeaders().get("foo")).isEqualTo("x");
assertThat(message1.getHeaders().get("bar")).isEqualTo(42);
Message<?> message2 = messages.get(1);
assertThat(message2.getPayload()).isEqualTo("test-2");
assertThat(message2.getHeaders().get("foo")).isEqualTo("x");
assertThat(message2.getHeaders().get("bar")).isEqualTo(42);
Message<?> message3 = messages.get(2);
assertThat(message3.getPayload()).isEqualTo("test-3");
assertThat(message3.getHeaders().get("foo")).isEqualTo("x");
assertThat(message3.getHeaders().get("bar")).isEqualTo(42);
}
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 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();
}
Aggregations