Example usage for org.springframework.messaging Message getHeaders

List of usage examples for org.springframework.messaging Message getHeaders

Introduction

In this page you can find the example usage for org.springframework.messaging Message getHeaders.

Prototype

MessageHeaders getHeaders();

Source Link

Document

Return message headers for the message (never null but may be empty).

Usage

From source file:org.springframework.integration.history.MessageHistoryIntegrationTests.java

@Test
public void testMessageHistoryWithHistoryWriter() {
    ConfigurableApplicationContext ac = new ClassPathXmlApplicationContext(
            "messageHistoryWithHistoryWriter.xml", MessageHistoryIntegrationTests.class);
    SampleGateway gateway = ac.getBean("sampleGateway", SampleGateway.class);
    DirectChannel endOfThePipeChannel = ac.getBean("endOfThePipeChannel", DirectChannel.class);
    MessageHandler handler = Mockito.spy(new MessageHandler() {
        @Override/*from  w w  w.  ja  v a2 s . com*/
        public void handleMessage(Message<?> message) {
            Iterator<Properties> historyIterator = message.getHeaders()
                    .get(MessageHistory.HEADER_NAME, MessageHistory.class).iterator();

            Properties event = historyIterator.next();
            assertEquals("sampleGateway", event.getProperty(MessageHistory.NAME_PROPERTY));
            assertEquals("gateway", event.getProperty(MessageHistory.TYPE_PROPERTY));

            event = historyIterator.next();
            assertEquals("bridgeInChannel", event.getProperty(MessageHistory.NAME_PROPERTY));
            assertEquals("channel", event.getProperty(MessageHistory.TYPE_PROPERTY));

            event = historyIterator.next();
            assertEquals("testBridge", event.getProperty(MessageHistory.NAME_PROPERTY));
            assertEquals("bridge", event.getProperty(MessageHistory.TYPE_PROPERTY));

            event = historyIterator.next();
            assertEquals("headerEnricherChannel", event.getProperty(MessageHistory.NAME_PROPERTY));
            assertEquals("channel", event.getProperty(MessageHistory.TYPE_PROPERTY));

            event = historyIterator.next();
            assertEquals("testHeaderEnricher", event.getProperty(MessageHistory.NAME_PROPERTY));
            assertEquals("transformer", event.getProperty(MessageHistory.TYPE_PROPERTY));

            event = historyIterator.next();
            assertEquals("chainChannel", event.getProperty(MessageHistory.NAME_PROPERTY));
            assertEquals("channel", event.getProperty(MessageHistory.TYPE_PROPERTY));

            event = historyIterator.next();
            assertEquals("sampleChain", event.getProperty(MessageHistory.NAME_PROPERTY));
            assertEquals("chain", event.getProperty(MessageHistory.TYPE_PROPERTY));

            event = historyIterator.next();
            assertEquals("sampleChain$child.service-activator-within-chain",
                    event.getProperty(MessageHistory.NAME_PROPERTY));
            assertEquals("service-activator", event.getProperty(MessageHistory.TYPE_PROPERTY));

            event = historyIterator.next();
            assertEquals("filterChannel", event.getProperty(MessageHistory.NAME_PROPERTY));
            assertEquals("channel", event.getProperty(MessageHistory.TYPE_PROPERTY));

            event = historyIterator.next();
            assertEquals("testFilter", event.getProperty(MessageHistory.NAME_PROPERTY));
            assertEquals("filter", event.getProperty(MessageHistory.TYPE_PROPERTY));

            event = historyIterator.next();
            assertEquals("splitterChannel", event.getProperty(MessageHistory.NAME_PROPERTY));
            assertEquals("channel", event.getProperty(MessageHistory.TYPE_PROPERTY));

            event = historyIterator.next();
            assertEquals("testSplitter", event.getProperty(MessageHistory.NAME_PROPERTY));
            assertEquals("splitter", event.getProperty(MessageHistory.TYPE_PROPERTY));

            event = historyIterator.next();
            assertEquals("aggregatorChannel", event.getProperty(MessageHistory.NAME_PROPERTY));
            assertEquals("channel", event.getProperty(MessageHistory.TYPE_PROPERTY));

            event = historyIterator.next();
            assertEquals("testAggregator", event.getProperty(MessageHistory.NAME_PROPERTY));
            assertEquals("aggregator", event.getProperty(MessageHistory.TYPE_PROPERTY));

            event = historyIterator.next();
            assertEquals("endOfThePipeChannel", event.getProperty(MessageHistory.NAME_PROPERTY));
            assertEquals("channel", event.getProperty(MessageHistory.TYPE_PROPERTY));

            MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel();
            replyChannel.send(message);
        }
    });
    endOfThePipeChannel.subscribe(handler);
    Message<?> result = gateway.echo("hello");
    Mockito.verify(handler, Mockito.times(1)).handleMessage(Mockito.any(Message.class));
    assertNotNull(result);
    //assertEquals("hello", result);
    ac.close();
}

From source file:org.springframework.integration.history.MessageHistoryIntegrationTests.java

@Test
public void testMessageHistoryWithoutHistoryWriter() {
    ConfigurableApplicationContext ac = new ClassPathXmlApplicationContext(
            "messageHistoryWithoutHistoryWriter.xml", MessageHistoryIntegrationTests.class);
    SampleGateway gateway = ac.getBean("sampleGateway", SampleGateway.class);
    DirectChannel endOfThePipeChannel = ac.getBean("endOfThePipeChannel", DirectChannel.class);
    MessageHandler handler = Mockito.spy(new MessageHandler() {
        @Override/*from   w w w. j  a  v  a  2  s  . c  o  m*/
        public void handleMessage(Message<?> message) {
            assertNull(message.getHeaders().get(MessageHistory.HEADER_NAME, MessageHistory.class));
            MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel();
            replyChannel.send(message);
        }
    });
    endOfThePipeChannel.subscribe(handler);
    gateway.echo("hello");
    Mockito.verify(handler, Mockito.times(1)).handleMessage(Mockito.any(Message.class));
    ac.close();
}

From source file:org.springframework.integration.history.MessageHistoryIntegrationTests.java

@Test
public void testMessageHistoryParser() {
    ConfigurableApplicationContext ac = new ClassPathXmlApplicationContext(
            "messageHistoryWithHistoryWriterNamespace.xml", MessageHistoryIntegrationTests.class);
    SampleGateway gateway = ac.getBean("sampleGateway", SampleGateway.class);
    DirectChannel endOfThePipeChannel = ac.getBean("endOfThePipeChannel", DirectChannel.class);
    MessageHandler handler = Mockito.spy(new MessageHandler() {
        @Override/* www. j av a  2 s.  c  om*/
        public void handleMessage(Message<?> message) {
            Iterator<Properties> historyIterator = message.getHeaders()
                    .get(MessageHistory.HEADER_NAME, MessageHistory.class).iterator();
            assertTrue(historyIterator.hasNext());
            MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel();
            replyChannel.send(message);
        }
    });
    endOfThePipeChannel.subscribe(handler);
    gateway.echo("hello");
    Mockito.verify(handler, Mockito.times(1)).handleMessage(Mockito.any(Message.class));
    ac.close();
}

From source file:org.springframework.integration.history.MessageHistoryIntegrationTests.java

@Test
public void testMessageHistoryParserWithNamePatterns() {
    ConfigurableApplicationContext ac = new ClassPathXmlApplicationContext(
            "messageHistoryWithHistoryWriterNamespaceAndPatterns.xml", MessageHistoryIntegrationTests.class);
    SampleGateway gateway = ac.getBean("sampleGateway", SampleGateway.class);
    DirectChannel endOfThePipeChannel = ac.getBean("endOfThePipeChannel", DirectChannel.class);
    MessageHandler handler = Mockito.spy(new MessageHandler() {
        @Override//w ww  .j a  va 2  s .co m
        public void handleMessage(Message<?> message) {
            Iterator<Properties> historyIterator = message.getHeaders()
                    .get(MessageHistory.HEADER_NAME, MessageHistory.class).iterator();
            assertTrue(historyIterator.hasNext());
            Properties gatewayHistory = historyIterator.next();
            assertEquals("sampleGateway", gatewayHistory.get("name"));
            assertTrue(historyIterator.hasNext());
            Properties chainHistory = historyIterator.next();
            assertEquals("sampleChain", chainHistory.get("name"));
            assertFalse(historyIterator.hasNext());
            MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel();
            replyChannel.send(message);
        }
    });
    endOfThePipeChannel.subscribe(handler);
    gateway.echo("hello");
    Mockito.verify(handler, Mockito.times(1)).handleMessage(Mockito.any(Message.class));
    ac.close();
}

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

@Test
public void integrationTest() throws Exception {
    TestingUtilities.waitListening(serverCf, null);
    new DirectFieldAccessor(this.clientAdapterCf).setPropertyValue("port", this.serverCf.getPort());

    this.outbound.send(new GenericMessage<>("Hello, world!"));
    Message<?> m = inbound.receive(10000);
    assertNotNull(m);/*from   ww w .  j  av  a  2 s  .c  om*/
    String connectionId = m.getHeaders().get(IpHeaders.CONNECTION_ID, String.class);

    // assert we use the same connection from the pool
    outbound.send(new GenericMessage<String>("Hello, world!"));
    m = inbound.receive(10000);
    assertNotNull(m);
    assertEquals(connectionId, m.getHeaders().get(IpHeaders.CONNECTION_ID, String.class));
}

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

@Test
//   @Repeat(1000) // INT-3722
public void gatewayIntegrationTest() throws Exception {
    final List<String> connectionIds = new ArrayList<String>();
    final AtomicBoolean okToRun = new AtomicBoolean(true);
    Executors.newSingleThreadExecutor().execute(() -> {
        while (okToRun.get()) {
            Message<?> m = inbound.receive(1000);
            if (m != null) {
                connectionIds.add((String) m.getHeaders().get(IpHeaders.CONNECTION_ID));
                replies.send(MessageBuilder.withPayload("foo:" + new String((byte[]) m.getPayload()))
                        .copyHeaders(m.getHeaders()).build());
            }//ww w  .  j ava  2 s .  c  o m
        }
    });
    TestingUtilities.waitListening(serverCf, null);
    new DirectFieldAccessor(this.clientGatewayCf).setPropertyValue("port", this.serverCf.getPort());

    this.toGateway.send(new GenericMessage<>("Hello, world!"));
    Message<?> m = fromGateway.receive(1000);
    assertNotNull(m);
    assertEquals("foo:" + "Hello, world!", new String((byte[]) m.getPayload()));

    BlockingQueue<?> connections = TestUtils.getPropertyValue(this.gatewayCF, "pool.available",
            BlockingQueue.class);
    // wait until the connection is returned to the pool
    int n = 0;
    while (n++ < 100 && connections.size() == 0) {
        Thread.sleep(100);
    }

    // assert we use the same connection from the pool
    toGateway.send(new GenericMessage<String>("Hello, world2!"));
    m = fromGateway.receive(1000);
    assertNotNull(m);
    assertEquals("foo:" + "Hello, world2!", new String((byte[]) m.getPayload()));

    assertEquals(2, connectionIds.size());
    assertEquals(connectionIds.get(0), connectionIds.get(1));

    okToRun.set(false);
}

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

@Test
public void testInboundGatewayNoConnectionEvents() {
    TcpInboundGateway gw = new TcpInboundGateway();
    AbstractServerConnectionFactory scf = new AbstractServerConnectionFactory(0) {

        @Override/*from w  w  w.  j  a v  a2s . c o m*/
        public void run() {
        }
    };
    final AtomicReference<ApplicationEvent> theEvent = new AtomicReference<ApplicationEvent>();
    scf.setApplicationEventPublisher(new ApplicationEventPublisher() {

        @Override
        public void publishEvent(Object event) {
        }

        @Override
        public void publishEvent(ApplicationEvent event) {
            theEvent.set(event);
        }

    });
    gw.setConnectionFactory(scf);
    DirectChannel requestChannel = new DirectChannel();
    requestChannel.subscribe(new MessageHandler() {

        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            ((MessageChannel) message.getHeaders().getReplyChannel()).send(message);
        }
    });
    gw.setRequestChannel(requestChannel);
    gw.start();
    Message<String> message = MessageBuilder.withPayload("foo").setHeader(IpHeaders.CONNECTION_ID, "bar")
            .build();
    gw.onMessage(message);
    assertNotNull(theEvent.get());
    TcpConnectionFailedCorrelationEvent event = (TcpConnectionFailedCorrelationEvent) theEvent.get();
    assertEquals("bar", event.getConnectionId());
    assertSame(message, ((MessagingException) event.getCause()).getFailedMessage());
}

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

@Test
public void testOutboundGatewayNoConnectionEvents() {
    TcpOutboundGateway gw = new TcpOutboundGateway();
    AbstractClientConnectionFactory ccf = new AbstractClientConnectionFactory("localhost", 0) {
    };/* w w w.j  a v  a 2s.  c  o  m*/
    final AtomicReference<ApplicationEvent> theEvent = new AtomicReference<ApplicationEvent>();
    ccf.setApplicationEventPublisher(new ApplicationEventPublisher() {

        @Override
        public void publishEvent(Object event) {
        }

        @Override
        public void publishEvent(ApplicationEvent event) {
            theEvent.set(event);
        }

    });
    gw.setConnectionFactory(ccf);
    DirectChannel requestChannel = new DirectChannel();
    requestChannel
            .subscribe(message -> ((MessageChannel) message.getHeaders().getReplyChannel()).send(message));
    gw.start();
    Message<String> message = MessageBuilder.withPayload("foo").setHeader(IpHeaders.CONNECTION_ID, "bar")
            .build();
    gw.onMessage(message);
    assertNotNull(theEvent.get());
    TcpConnectionFailedCorrelationEvent event = (TcpConnectionFailedCorrelationEvent) theEvent.get();
    assertEquals("bar", event.getConnectionId());
    MessagingException messagingException = (MessagingException) event.getCause();
    assertSame(message, messagingException.getFailedMessage());
    assertEquals("Cannot correlate response - no pending reply for bar", messagingException.getMessage());

    message = new GenericMessage<String>("foo");
    gw.onMessage(message);
    assertNotNull(theEvent.get());
    event = (TcpConnectionFailedCorrelationEvent) theEvent.get();
    assertNull(event.getConnectionId());
    messagingException = (MessagingException) event.getCause();
    assertSame(message, messagingException.getFailedMessage());
    assertEquals("Cannot correlate response - no connection id", messagingException.getMessage());
}

From source file:org.springframework.integration.ip.udp.DatagramPacketMulticastSendingHandlerTests.java

@Test
public void verifySendMulticastWithAcks() throws Exception {

    MulticastSocket socket;/*from   ww  w . ja v  a 2  s.  c  o  m*/
    try {
        socket = new MulticastSocket();
    } catch (Exception e) {
        return;
    }
    final int testPort = socket.getLocalPort();
    final AtomicInteger ackPort = new AtomicInteger();

    final String multicastAddress = "225.6.7.8";
    final String payload = "foobar";
    final CountDownLatch listening = new CountDownLatch(2);
    final CountDownLatch ackListening = new CountDownLatch(1);
    final CountDownLatch ackSent = new CountDownLatch(2);
    Runnable catcher = () -> {
        try {
            byte[] buffer = new byte[1000];
            DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length);
            MulticastSocket socket1 = new MulticastSocket(testPort);
            socket1.setInterface(InetAddress.getByName(multicastRule.getNic()));
            socket1.setSoTimeout(8000);
            InetAddress group = InetAddress.getByName(multicastAddress);
            socket1.joinGroup(group);
            listening.countDown();
            assertTrue(ackListening.await(10, TimeUnit.SECONDS));
            LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " waiting for packet");
            socket1.receive(receivedPacket);
            socket1.close();
            byte[] src = receivedPacket.getData();
            int length = receivedPacket.getLength();
            int offset = receivedPacket.getOffset();
            byte[] dest = new byte[6];
            System.arraycopy(src, offset + length - 6, dest, 0, 6);
            assertEquals(payload, new String(dest));
            LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " received packet");
            DatagramPacketMessageMapper mapper = new DatagramPacketMessageMapper();
            mapper.setAcknowledge(true);
            mapper.setLengthCheck(true);
            Message<byte[]> message = mapper.toMessage(receivedPacket);
            Object id = message.getHeaders().get(IpHeaders.ACK_ID);
            byte[] ack = id.toString().getBytes();
            DatagramPacket ackPack = new DatagramPacket(ack, ack.length,
                    new InetSocketAddress(multicastRule.getNic(), ackPort.get()));
            DatagramSocket out = new DatagramSocket();
            out.send(ackPack);
            LogFactory.getLog(getClass())
                    .debug(Thread.currentThread().getName() + " sent ack to " + ackPack.getSocketAddress());
            out.close();
            ackSent.countDown();
            socket1.close();
        } catch (Exception e) {
            listening.countDown();
            e.printStackTrace();
        }
    };
    Executor executor = Executors.newFixedThreadPool(2);
    executor.execute(catcher);
    executor.execute(catcher);
    assertTrue(listening.await(10000, TimeUnit.MILLISECONDS));
    MulticastSendingMessageHandler handler = new MulticastSendingMessageHandler(multicastAddress, testPort,
            true, true, "localhost", 0, 10000);
    handler.setLocalAddress(this.multicastRule.getNic());
    handler.setMinAcksForSuccess(2);
    handler.setBeanFactory(mock(BeanFactory.class));
    handler.afterPropertiesSet();
    handler.start();
    waitAckListening(handler);
    ackPort.set(handler.getAckPort());
    ackListening.countDown();
    handler.handleMessage(MessageBuilder.withPayload(payload).build());
    assertTrue(ackSent.await(10000, TimeUnit.MILLISECONDS));
    handler.stop();
    socket.close();
}

From source file:org.springframework.integration.jdbc.store.JdbcMessageStore.java

@Override
@SuppressWarnings("unchecked")
public <T> Message<T> addMessage(final Message<T> message) {
    UUID id = message.getHeaders().getId();
    final String messageId = getKey(id);
    final byte[] messageBytes = this.serializer.convert(message);

    if (logger.isDebugEnabled()) {
        logger.debug("Inserting message with id key=" + messageId);
    }/*from  w  w  w.  j  a  v  a 2s .  com*/

    try {
        this.jdbcTemplate.update(getQuery(Query.CREATE_MESSAGE), ps -> {
            ps.setString(1, messageId);
            ps.setString(2, this.region);
            ps.setTimestamp(3, new Timestamp(System.currentTimeMillis()));

            this.lobHandler.getLobCreator().setBlobAsBytes(ps, 4, messageBytes);
        });
    } catch (DuplicateKeyException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("The Message with id [" + id + "] already exists.\n"
                    + "Ignoring INSERT and SELECT existing...");
        }
        return (Message<T>) getMessage(id);
    }
    return message;
}