use of org.springframework.integration.channel.NullChannel in project spring-integration by spring-projects.
the class FileTailingMessageProducerTests method testIdleEvent.
@Test
public void testIdleEvent() throws Exception {
ApacheCommonsFileTailingMessageProducer adapter = new ApacheCommonsFileTailingMessageProducer();
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.afterPropertiesSet();
adapter.setTaskScheduler(taskScheduler);
CountDownLatch idleCountDownLatch = new CountDownLatch(1);
CountDownLatch fileExistCountDownLatch = new CountDownLatch(1);
adapter.setApplicationEventPublisher(event -> {
if (event instanceof FileTailingIdleEvent) {
idleCountDownLatch.countDown();
}
if (event instanceof FileTailingEvent) {
FileTailingEvent fileTailingEvent = (FileTailingEvent) event;
if (fileTailingEvent.getMessage().contains("File not found")) {
fileExistCountDownLatch.countDown();
}
}
});
File file = spy(new File(this.testDir, "foo"));
file.delete();
adapter.setFile(file);
adapter.setOutputChannel(new NullChannel());
adapter.setIdleEventInterval(10);
adapter.afterPropertiesSet();
adapter.start();
boolean noFile = fileExistCountDownLatch.await(10, TimeUnit.SECONDS);
assertTrue("file does not exist event did not emit ", noFile);
boolean noEvent = idleCountDownLatch.await(100, TimeUnit.MILLISECONDS);
assertFalse("event should not emit when no file exit", noEvent);
verify(file, atLeastOnce()).exists();
file.createNewFile();
boolean eventRaised = idleCountDownLatch.await(10, TimeUnit.SECONDS);
assertTrue("idle event did not emit", eventRaised);
adapter.stop();
file.delete();
}
use of org.springframework.integration.channel.NullChannel in project spring-integration by spring-projects.
the class FileWritingMessageHandlerTests method lockForFlush.
@Test
public void lockForFlush() throws Exception {
File tempFolder = this.temp.newFolder();
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());
assertFalse(closeWhileWriting.get());
handler.stop();
}
use of org.springframework.integration.channel.NullChannel in project spring-integration by spring-projects.
the class FileWritingMessageHandlerTests method noFlushAppend.
@Test
public void noFlushAppend() throws Exception {
File tempFolder = this.temp.newFolder();
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<String>("foo"));
handler.handleMessage(new GenericMessage<String>("bar"));
handler.handleMessage(new GenericMessage<String>("baz"));
// change of payload type forces flush
handler.handleMessage(new GenericMessage<byte[]>("qux".getBytes()));
assertThat(file.length(), greaterThanOrEqualTo(9L));
// forces flush
handler.stop();
assertThat(file.length(), equalTo(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(), equalTo(15L));
handler.handleMessage(new GenericMessage<InputStream>(new ByteArrayInputStream("buz".getBytes())));
handler.trigger(new GenericMessage<String>(Matcher.quoteReplacement(file.getAbsolutePath())));
assertThat(file.length(), equalTo(18L));
assertEquals(0, TestUtils.getPropertyValue(handler, "fileStates", Map.class).size());
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<String>("foo"));
assertThat(file.length(), equalTo(21L));
assertTrue(called.get());
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(), equalTo(24L));
assertTrue(called.get());
handler.stop();
Log logger = spy(TestUtils.getPropertyValue(handler, "logger", Log.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<String>("foo"));
Thread.sleep(5);
}
assertThat(flushes.get(), greaterThanOrEqualTo(2));
handler.stop();
}
use of org.springframework.integration.channel.NullChannel in project spring-integration by spring-projects.
the class AggregatorAnnotationTests method testAnnotationWithDefaultSettings.
@Test
public void testAnnotationWithDefaultSettings() {
ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "classpath:/org/springframework/integration/config/annotation/testAnnotatedAggregator.xml" });
final String endpointName = "endpointWithDefaultAnnotation";
MessageHandler aggregator = this.getAggregator(context, endpointName);
assertTrue(getPropertyValue(aggregator, "releaseStrategy") instanceof SimpleSequenceSizeReleaseStrategy);
assertNull(getPropertyValue(aggregator, "outputChannel"));
assertTrue(getPropertyValue(aggregator, "discardChannel") instanceof NullChannel);
assertEquals(-1L, getPropertyValue(aggregator, "messagingTemplate.sendTimeout"));
assertEquals(false, getPropertyValue(aggregator, "sendPartialResultOnExpiry"));
context.close();
}
use of org.springframework.integration.channel.NullChannel in project spring-integration by spring-projects.
the class ContentEnricherTests method replyChannelReplyTimingOut.
/**
* In this test a {@link Target} message is passed into a {@link ContentEnricher}.
* The Enricher passes the message to a "request-channel" that is backed by a
* {@link QueueChannel}. The consumer of the "request-channel" takes a long
* time to execute, longer actually than the specified "replyTimeout" set on
* the {@link ContentEnricher}.
*
* Due to the occurring replyTimeout, a Null replyMessage is returned and because
* "requiresReply" is set to "true" on the {@link ContentEnricher}, a
* {@link ReplyRequiredException} is raised.
*/
@Test
public void replyChannelReplyTimingOut() throws Exception {
final long requestTimeout = 500L;
final long replyTimeout = 100L;
final DirectChannel replyChannel = new DirectChannel();
final QueueChannel requestChannel = new QueueChannel(1);
final ContentEnricher enricher = new ContentEnricher();
enricher.setRequestChannel(requestChannel);
enricher.setReplyChannel(replyChannel);
enricher.setOutputChannel(new NullChannel());
enricher.setRequestTimeout(requestTimeout);
enricher.setReplyTimeout(replyTimeout);
final ExpressionFactoryBean expressionFactoryBean = new ExpressionFactoryBean("payload");
expressionFactoryBean.setSingleton(false);
expressionFactoryBean.afterPropertiesSet();
final Map<String, Expression> expressions = new HashMap<String, Expression>();
expressions.put("name", new LiteralExpression("cartman"));
expressions.put("child.name", expressionFactoryBean.getObject());
enricher.setPropertyExpressions(expressions);
enricher.setRequiresReply(true);
enricher.setBeanName("Enricher");
enricher.setBeanFactory(mock(BeanFactory.class));
enricher.afterPropertiesSet();
final AbstractReplyProducingMessageHandler handler = new AbstractReplyProducingMessageHandler() {
@Override
protected Object handleRequestMessage(Message<?> requestMessage) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
fail(e.getMessage());
}
return new Target("child");
}
};
handler.setBeanFactory(mock(BeanFactory.class));
handler.afterPropertiesSet();
final PollingConsumer consumer = new PollingConsumer(requestChannel, handler);
final TestErrorHandler errorHandler = new TestErrorHandler();
consumer.setTrigger(new PeriodicTrigger(0));
consumer.setErrorHandler(errorHandler);
consumer.setTaskScheduler(taskScheduler);
consumer.setBeanFactory(mock(BeanFactory.class));
consumer.afterPropertiesSet();
consumer.start();
final Target target = new Target("replace me");
Message<?> requestMessage = MessageBuilder.withPayload(target).setReplyChannel(replyChannel).build();
try {
enricher.handleMessage(requestMessage);
} catch (ReplyRequiredException e) {
assertEquals("No reply produced by handler 'Enricher', and its 'requiresReply' property is set to true.", e.getMessage());
return;
}
fail("ReplyRequiredException expected.");
}
Aggregations