Example usage for org.springframework.integration.channel NullChannel NullChannel

List of usage examples for org.springframework.integration.channel NullChannel NullChannel

Introduction

In this page you can find the example usage for org.springframework.integration.channel NullChannel NullChannel.

Prototype

NullChannel

Source Link

Usage

From source file:eric.bottard.tis100.Runner.java

public Runner(int rows, int columns, String specificationFile, File solution) throws IOException {

    Specification specification = new LuaSpecification(specificationFile, rows, columns);

    List<String> nodeSources = loadSolution(solution, specification.getLayout());

    this.rows = rows;
    this.columns = columns;

    verticalChannels = new MessageChannel[columns * (rows + 1) * 2];
    horizontalChannels = new MessageChannel[rows * (columns + 1) * 2];

    // channels[2*x] = ltr / down-to-up
    // channels[2*x + 1] = rtl / up-to-down
    for (int row = 0; row <= rows; row++) {
        for (int column = 0; column < columns; column++) {
            verticalChannels[(row * columns + column) * 2] = (row == 0 || row == rows) ? new NullChannel()
                    : new RendezvousChannel();
            if (row == 0) {
                verticalChannels[(row * columns + column) * 2 + 1] = new QueueChannel(40);
            } else if (row == rows) {
                verticalChannels[(row * columns + column) * 2 + 1] = new PublishSubscribeChannel();
            } else {
                verticalChannels[(row * columns + column) * 2 + 1] = new RendezvousChannel();
            }/*  ww w .  j  a  v a2  s . co m*/
        }
    }

    for (int row = 0; row < rows; row++) {
        for (int column = 0; column <= columns; column++) {
            horizontalChannels[(column * rows + row) * 2] = (column == 0 || column == columns)
                    ? new NullChannel()
                    : new RendezvousChannel();
            horizontalChannels[(column * rows + row) * 2 + 1] = (column == 0 || column == columns)
                    ? new NullChannel()
                    : new RendezvousChannel();
        }
    }

    Thread[] threads = new Thread[rows * columns];
    Object mutex = new Object();

    for (int row = 0; row < rows; row++) {
        for (int column = 0; column < columns; column++) {
            final SpringNode node = NodeFactory.buildNode(nodeSources.get(row * columns + column));
            final NodePrettyPrinter printer = new NodePrettyPrinter(4 + row * 19,
                    SpecificationPrettyPrinter.WIDTH + 10 + column * 37, node);
            Ports ports = new PortsMapping(row, column);
            node.setPorts(ports);
            nodes.add(node);
            threads[row * columns + column] = new Thread() {
                @Override
                public void run() {

                    boolean more;
                    do {
                        synchronized (mutex) {
                            printer.draw(System.out);
                        }
                        try {
                            Thread.sleep(150);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        more = node.tick();
                    } while (more);
                }
            };
        }
    }

    List<Integer>[] actuals = new List[columns];
    SpecificationPrettyPrinter specificationPrettyPrinter = new SpecificationPrettyPrinter(specification, 2, 2,
            actuals);

    for (int i = 0; i < columns; i++) {
        Specification.Stream stream = specification.getInputStreams()[i];
        if (stream != null) {
            for (Integer in : stream.getData()) {
                verticalChannels[1 + 2 * i].send(new GenericMessage<>(in));
            }
        }
        stream = specification.getOutputStreams()[i];
        final List<Integer> actual = actuals[i] = new ArrayList<>();
        if (stream != null) {
            ((SubscribableChannel) verticalChannels[1 + 2 * (i + rows * columns)])
                    .subscribe(new MessageHandler() {
                        @Override
                        public void handleMessage(Message<?> message) throws MessagingException {
                            actual.add((Integer) message.getPayload());
                            synchronized (mutex) {
                                specificationPrettyPrinter.draw(System.out);
                            }
                        }
                    });
        }
    }
    synchronized (mutex) {
        specificationPrettyPrinter.draw(System.out);
    }

    for (int i = 0; i < rows * columns; i++) {
        threads[i].start();
    }

}

From source file:io.spring.batch.configuration.JobConfiguration.java

@Bean
public PollableChannel outboundStaging() {
    return new NullChannel();
}

From source file:org.springframework.batch.integration.partition.RemotePartitioningWorkerStepBuilder.java

/**
 * Create an {@link IntegrationFlow} with a {@link StepExecutionRequestHandler}
 * configured as a service activator listening to the input channel and replying
 * on the output channel.//w w w .  j  a va 2  s.c  om
 */
private void configureWorkerIntegrationFlow() {
    Assert.notNull(this.inputChannel, "An InputChannel must be provided");
    Assert.notNull(this.jobExplorer, "A JobExplorer must be provided");

    if (this.stepLocator == null) {
        BeanFactoryStepLocator beanFactoryStepLocator = new BeanFactoryStepLocator();
        beanFactoryStepLocator.setBeanFactory(this.beanFactory);
        this.stepLocator = beanFactoryStepLocator;
    }
    if (this.outputChannel == null) {
        if (logger.isDebugEnabled()) {
            logger.debug("The output channel is set to a NullChannel. "
                    + "The master step must poll the job repository for workers status.");
        }
        this.outputChannel = new NullChannel();
    }

    StepExecutionRequestHandler stepExecutionRequestHandler = new StepExecutionRequestHandler();
    stepExecutionRequestHandler.setJobExplorer(this.jobExplorer);
    stepExecutionRequestHandler.setStepLocator(this.stepLocator);

    StandardIntegrationFlow standardIntegrationFlow = IntegrationFlows.from(this.inputChannel)
            .handle(stepExecutionRequestHandler, SERVICE_ACTIVATOR_METHOD_NAME).channel(this.outputChannel)
            .get();
    IntegrationFlowContext integrationFlowContext = this.beanFactory.getBean(IntegrationFlowContext.class);
    integrationFlowContext.registration(standardIntegrationFlow).autoStartup(false).register();
}

From source file:org.springframework.integration.config.SourcePollingChannelAdapterFactoryBeanTests.java

@Test
public void testInterrupted() throws Exception {
    final CountDownLatch startLatch = new CountDownLatch(1);

    MessageSource<Object> ms = () -> {
        startLatch.countDown();/*from www. j a v a 2s  .co m*/
        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();

    Log adapterLogger = TestUtils.getPropertyValue(pollingChannelAdapter, "logger", Log.class);
    adapterLogger = spy(adapterLogger);
    when(adapterLogger.isDebugEnabled()).thenReturn(true);

    dfa = new DirectFieldAccessor(pollingChannelAdapter);
    dfa.setPropertyValue("logger", adapterLogger);

    pollingChannelAdapter.start();

    assertTrue(startLatch.await(10, TimeUnit.SECONDS));
    pollingChannelAdapter.stop();

    taskScheduler.shutdown();

    verifyZeroInteractions(errorHandlerLogger);
    verify(adapterLogger).debug(contains("Poll interrupted - during stop()?"));
}

From source file:org.springframework.integration.file.FileWritingMessageHandlerTests.java

@Test
public void supportedType() throws Exception {
    handler.setOutputChannel(new NullChannel());
    handler.handleMessage(new GenericMessage<String>("test"));
    assertThat(outputDirectory.listFiles()[0], notNullValue());
}

From source file:org.springframework.integration.file.FileWritingMessageHandlerTests.java

@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();/*from www  . j  a v  a 2  s .  co  m*/
    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"));
    handler.handleMessage(new GenericMessage<byte[]>("qux".getBytes())); // change of payload type forces flush
    assertThat(file.length(), greaterThanOrEqualTo(9L));
    handler.stop(); // forces flush
    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();
}

From source file:org.springframework.integration.file.FileWritingMessageHandlerTests.java

@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/*from  w w w  .  j a va  2s  .c  om*/
        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();
}

From source file:org.springframework.integration.ip.tcp.connection.ConnectionFactoryTests.java

public void testObtainConnectionIds(AbstractServerConnectionFactory serverFactory) throws Exception {
    final List<IpIntegrationEvent> events = Collections.synchronizedList(new ArrayList<IpIntegrationEvent>());
    int expectedEvents = serverFactory instanceof TcpNetServerConnectionFactory ? 7 // Listening, + OPEN, CLOSE, EXCEPTION for each side
            : 5; // Listening, + OPEN, CLOSE (but we *might* get exceptions, depending on timing).
    final CountDownLatch serverListeningLatch = new CountDownLatch(1);
    final CountDownLatch eventLatch = new CountDownLatch(expectedEvents);
    ApplicationEventPublisher publisher = new ApplicationEventPublisher() {

        @Override// www .  ja va2  s . c om
        public void publishEvent(ApplicationEvent event) {
            LogFactory.getLog(this.getClass()).trace("Received: " + event);
            events.add((IpIntegrationEvent) event);
            if (event instanceof TcpConnectionServerListeningEvent) {
                serverListeningLatch.countDown();
            }
            eventLatch.countDown();
        }

        @Override
        public void publishEvent(Object event) {

        }

    };
    serverFactory.setBeanName("serverFactory");
    serverFactory.setApplicationEventPublisher(publisher);
    serverFactory = spy(serverFactory);
    final CountDownLatch serverConnectionInitLatch = new CountDownLatch(1);
    doAnswer(invocation -> {
        Object result = invocation.callRealMethod();
        serverConnectionInitLatch.countDown();
        return result;
    }).when(serverFactory).wrapConnection(any(TcpConnectionSupport.class));
    ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
    scheduler.setPoolSize(10);
    scheduler.afterPropertiesSet();
    BeanFactory bf = mock(BeanFactory.class);
    when(bf.containsBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME)).thenReturn(true);
    when(bf.getBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME, TaskScheduler.class))
            .thenReturn(scheduler);
    serverFactory.setBeanFactory(bf);
    TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter();
    adapter.setOutputChannel(new NullChannel());
    adapter.setConnectionFactory(serverFactory);
    adapter.start();
    assertTrue("Listening event not received", serverListeningLatch.await(10, TimeUnit.SECONDS));
    assertThat(events.get(0), instanceOf(TcpConnectionServerListeningEvent.class));
    assertThat(((TcpConnectionServerListeningEvent) events.get(0)).getPort(), equalTo(serverFactory.getPort()));
    int port = serverFactory.getPort();
    TcpNetClientConnectionFactory clientFactory = new TcpNetClientConnectionFactory("localhost", port);
    clientFactory.registerListener(message -> false);
    clientFactory.setBeanName("clientFactory");
    clientFactory.setApplicationEventPublisher(publisher);
    clientFactory.start();
    TcpConnectionSupport client = clientFactory.getConnection();
    List<String> clients = clientFactory.getOpenConnectionIds();
    assertEquals(1, clients.size());
    assertTrue(clients.contains(client.getConnectionId()));
    assertTrue("Server connection failed to register", serverConnectionInitLatch.await(1, TimeUnit.SECONDS));
    List<String> servers = serverFactory.getOpenConnectionIds();
    assertEquals(1, servers.size());
    assertTrue(serverFactory.closeConnection(servers.get(0)));
    servers = serverFactory.getOpenConnectionIds();
    assertEquals(0, servers.size());
    int n = 0;
    clients = clientFactory.getOpenConnectionIds();
    while (n++ < 100 && clients.size() > 0) {
        Thread.sleep(100);
        clients = clientFactory.getOpenConnectionIds();
    }
    assertEquals(0, clients.size());
    assertTrue(eventLatch.await(10, TimeUnit.SECONDS));
    assertThat("Expected at least " + expectedEvents + " events; got: " + events.size() + " : " + events,
            events.size(), greaterThanOrEqualTo(expectedEvents));

    FooEvent event = new FooEvent(client, "foo");
    client.publishEvent(event);
    assertThat("Expected at least " + expectedEvents + " events; got: " + events.size() + " : " + events,
            events.size(), greaterThanOrEqualTo(expectedEvents + 1));

    try {
        event = new FooEvent(mock(TcpConnectionSupport.class), "foo");
        client.publishEvent(event);
        fail("Expected exception");
    } catch (IllegalArgumentException e) {
        assertTrue("Can only publish events with this as the source".equals(e.getMessage()));
    }

    SocketAddress address = serverFactory.getServerSocketAddress();
    if (address instanceof InetSocketAddress) {
        InetSocketAddress inetAddress = (InetSocketAddress) address;
        assertEquals(port, inetAddress.getPort());
    }
    serverFactory.stop();
    scheduler.shutdown();
}

From source file:org.springframework.integration.mqtt.MqttAdapterTests.java

private MqttPahoMessageDrivenChannelAdapter buildAdapter(final IMqttClient client, Boolean cleanSession,
        ConsumerStopAction action) throws MqttException, MqttSecurityException {
    DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory() {

        @Override//w  w  w . j  ava  2 s  . c o m
        public IMqttClient getClientInstance(String uri, String clientId) throws MqttException {
            return client;
        }

    };
    factory.setServerURIs("tcp://localhost:1883");
    if (cleanSession != null) {
        factory.setCleanSession(cleanSession);
    }
    if (action != null) {
        factory.setConsumerStopAction(action);
    }
    given(client.isConnected()).willReturn(true);
    MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter("client", factory,
            "foo");
    adapter.setApplicationEventPublisher(mock(ApplicationEventPublisher.class));
    adapter.setOutputChannel(new NullChannel());
    adapter.setTaskScheduler(mock(TaskScheduler.class));
    adapter.afterPropertiesSet();
    return adapter;
}