Search in sources :

Example 6 with NullChannel

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();
}
Also used : FileTailingIdleEvent(org.springframework.integration.file.tail.FileTailingMessageProducerSupport.FileTailingIdleEvent) FileTailingEvent(org.springframework.integration.file.tail.FileTailingMessageProducerSupport.FileTailingEvent) CountDownLatch(java.util.concurrent.CountDownLatch) File(java.io.File) NullChannel(org.springframework.integration.channel.NullChannel) ThreadPoolTaskScheduler(org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler) Test(org.junit.Test)

Example 7 with NullChannel

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();
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) BeanFactory(org.springframework.beans.factory.BeanFactory) ByteArrayOutputStream(org.apache.commons.io.output.ByteArrayOutputStream) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream) NullChannel(org.springframework.integration.channel.NullChannel) ThreadPoolTaskScheduler(org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler) Test(org.junit.Test)

Example 8 with NullChannel

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();
}
Also used : Log(org.apache.commons.logging.Log) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) ThreadPoolTaskScheduler(org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ByteArrayInputStream(java.io.ByteArrayInputStream) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) BeanFactory(org.springframework.beans.factory.BeanFactory) File(java.io.File) NullChannel(org.springframework.integration.channel.NullChannel) Test(org.junit.Test)

Example 9 with NullChannel

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();
}
Also used : ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) MessageHandler(org.springframework.messaging.MessageHandler) ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) SimpleSequenceSizeReleaseStrategy(org.springframework.integration.aggregator.SimpleSequenceSizeReleaseStrategy) NullChannel(org.springframework.integration.channel.NullChannel) Test(org.junit.Test)

Example 10 with NullChannel

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.");
}
Also used : PollingConsumer(org.springframework.integration.endpoint.PollingConsumer) ReplyRequiredException(org.springframework.integration.handler.ReplyRequiredException) QueueChannel(org.springframework.integration.channel.QueueChannel) Message(org.springframework.messaging.Message) DirectChannel(org.springframework.integration.channel.DirectChannel) HashMap(java.util.HashMap) TestErrorHandler(org.springframework.integration.config.TestErrorHandler) LiteralExpression(org.springframework.expression.common.LiteralExpression) Matchers.containsString(org.hamcrest.Matchers.containsString) PeriodicTrigger(org.springframework.scheduling.support.PeriodicTrigger) ExpressionFactoryBean(org.springframework.integration.config.ExpressionFactoryBean) LiteralExpression(org.springframework.expression.common.LiteralExpression) Expression(org.springframework.expression.Expression) BeanFactory(org.springframework.beans.factory.BeanFactory) AbstractReplyProducingMessageHandler(org.springframework.integration.handler.AbstractReplyProducingMessageHandler) NullChannel(org.springframework.integration.channel.NullChannel) Test(org.junit.Test)

Aggregations

NullChannel (org.springframework.integration.channel.NullChannel)19 Test (org.junit.Test)12 BeanFactory (org.springframework.beans.factory.BeanFactory)10 ThreadPoolTaskScheduler (org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler)7 File (java.io.File)4 CountDownLatch (java.util.concurrent.CountDownLatch)3 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)3 Log (org.apache.commons.logging.Log)2 CoreMatchers.containsString (org.hamcrest.CoreMatchers.containsString)2 Message (org.springframework.amqp.core.Message)2 AsyncRabbitTemplate (org.springframework.amqp.rabbit.AsyncRabbitTemplate)2 ConnectionFactory (org.springframework.amqp.rabbit.connection.ConnectionFactory)2 RabbitTemplate (org.springframework.amqp.rabbit.core.RabbitTemplate)2 DirectFieldAccessor (org.springframework.beans.DirectFieldAccessor)2 ApplicationEventPublisher (org.springframework.context.ApplicationEventPublisher)2 TaskScheduler (org.springframework.scheduling.TaskScheduler)2 PeriodicTrigger (org.springframework.scheduling.support.PeriodicTrigger)2 BufferedOutputStream (java.io.BufferedOutputStream)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 FileInputStream (java.io.FileInputStream)1