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.syslog.inbound.SyslogReceivingChannelAdapterTests.java

@Test
public void testUdp() throws Exception {
    SyslogReceivingChannelAdapterFactoryBean factory = new SyslogReceivingChannelAdapterFactoryBean(
            SyslogReceivingChannelAdapterFactoryBean.Protocol.udp);
    int port = SocketUtils.findAvailableUdpSocket(1514);
    factory.setPort(port);/*from w ww . ja v  a 2  s . c  om*/
    PollableChannel outputChannel = new QueueChannel();
    factory.setOutputChannel(outputChannel);
    factory.setBeanFactory(mock(BeanFactory.class));
    factory.afterPropertiesSet();
    factory.start();
    UdpSyslogReceivingChannelAdapter adapter = (UdpSyslogReceivingChannelAdapter) factory.getObject();
    Thread.sleep(1000);
    byte[] buf = "<157>JUL 26 22:08:35 WEBERN TESTING[70729]: TEST SYSLOG MESSAGE".getBytes("UTF-8");
    DatagramPacket packet = new DatagramPacket(buf, buf.length, new InetSocketAddress("localhost", port));
    DatagramSocket socket = new DatagramSocket();
    socket.send(packet);
    socket.close();
    Message<?> message = outputChannel.receive(10000);
    assertNotNull(message);
    assertEquals("WEBERN", message.getHeaders().get("syslog_HOST"));
    adapter.stop();
}

From source file:org.springframework.integration.syslog.inbound.SyslogReceivingChannelAdapterTests.java

@Test
public void testTcp() throws Exception {
    SyslogReceivingChannelAdapterFactoryBean factory = new SyslogReceivingChannelAdapterFactoryBean(
            SyslogReceivingChannelAdapterFactoryBean.Protocol.tcp);
    int port = SocketUtils.findAvailableServerSocket(1514);
    factory.setPort(port);/*from  w  w w. jav  a 2s  .  c om*/
    PollableChannel outputChannel = new QueueChannel();
    factory.setOutputChannel(outputChannel);
    ApplicationEventPublisher publisher = mock(ApplicationEventPublisher.class);
    final CountDownLatch latch = new CountDownLatch(2);
    doAnswer(invocation -> {
        latch.countDown();
        return null;
    }).when(publisher).publishEvent(any(ApplicationEvent.class));
    factory.setApplicationEventPublisher(publisher);
    factory.setBeanFactory(mock(BeanFactory.class));
    factory.afterPropertiesSet();
    factory.start();
    TcpSyslogReceivingChannelAdapter adapter = (TcpSyslogReceivingChannelAdapter) factory.getObject();
    Log logger = spy(TestUtils.getPropertyValue(adapter, "logger", Log.class));
    doReturn(true).when(logger).isDebugEnabled();
    final CountDownLatch sawLog = new CountDownLatch(1);
    doAnswer(invocation -> {
        if (((String) invocation.getArgument(0)).contains("Error on syslog socket")) {
            sawLog.countDown();
        }
        invocation.callRealMethod();
        return null;
    }).when(logger).debug(anyString());
    new DirectFieldAccessor(adapter).setPropertyValue("logger", logger);
    Thread.sleep(1000);
    byte[] buf = "<157>JUL 26 22:08:35 WEBERN TESTING[70729]: TEST SYSLOG MESSAGE\n".getBytes("UTF-8");
    Socket socket = SocketFactory.getDefault().createSocket("localhost", port);
    socket.getOutputStream().write(buf);
    socket.close();
    assertTrue(sawLog.await(10, TimeUnit.SECONDS));
    Message<?> message = outputChannel.receive(10000);
    assertNotNull(message);
    assertEquals("WEBERN", message.getHeaders().get("syslog_HOST"));
    adapter.stop();
    assertTrue(latch.await(10, TimeUnit.SECONDS));
}

From source file:org.springframework.integration.syslog.inbound.SyslogReceivingChannelAdapterTests.java

@Test
public void testAsMapFalse() throws Exception {
    SyslogReceivingChannelAdapterFactoryBean factory = new SyslogReceivingChannelAdapterFactoryBean(
            SyslogReceivingChannelAdapterFactoryBean.Protocol.udp);
    int port = SocketUtils.findAvailableUdpSocket(1514);
    factory.setPort(port);/*from   w ww .jav a  2 s .  com*/
    PollableChannel outputChannel = new QueueChannel();
    factory.setOutputChannel(outputChannel);
    factory.setBeanFactory(mock(BeanFactory.class));
    factory.afterPropertiesSet();
    factory.start();
    UdpSyslogReceivingChannelAdapter adapter = (UdpSyslogReceivingChannelAdapter) factory.getObject();
    DefaultMessageConverter defaultMessageConverter = new DefaultMessageConverter();
    defaultMessageConverter.setAsMap(false);
    adapter.setConverter(defaultMessageConverter);
    Thread.sleep(1000);
    byte[] buf = "<157>JUL 26 22:08:35 WEBERN TESTING[70729]: TEST SYSLOG MESSAGE".getBytes("UTF-8");
    DatagramPacket packet = new DatagramPacket(buf, buf.length, new InetSocketAddress("localhost", port));
    DatagramSocket socket = new DatagramSocket();
    socket.send(packet);
    socket.close();
    Message<?> message = outputChannel.receive(10000);
    assertNotNull(message);
    assertEquals("WEBERN", message.getHeaders().get("syslog_HOST"));
    assertEquals("<157>JUL 26 22:08:35 WEBERN TESTING[70729]: TEST SYSLOG MESSAGE",
            new String((byte[]) message.getPayload(), "UTF-8"));
    adapter.stop();
}

From source file:org.springframework.integration.x.bus.MessageBusSupport.java

protected final Message<?> serializePayloadIfNecessary(Message<?> message, MediaType to) {
    Object originalPayload = message.getPayload();
    Object originalContentType = message.getHeaders().get(MessageHeaders.CONTENT_TYPE);
    Object contentType = originalContentType;
    if (to.equals(ALL)) {
        return message;
    } else if (to.equals(APPLICATION_OCTET_STREAM)) {
        contentType = resolveContentType(originalPayload);
        Object payload = serializePayloadIfNecessary(originalPayload);
        MessageBuilder<Object> messageBuilder = MessageBuilder.withPayload(payload)
                .copyHeaders(message.getHeaders()).setHeader(MessageHeaders.CONTENT_TYPE, contentType);
        if (originalContentType != null) {
            messageBuilder.setHeader(ORIGINAL_CONTENT_TYPE_HEADER, originalContentType);
        }//from  w ww.ja v  a 2s . co  m
        return messageBuilder.build();
    } else {
        throw new IllegalArgumentException("'to' can only be 'ALL' or 'APPLICATION_OCTET_STREAM'");
    }
}

From source file:org.springframework.integration.x.bus.MessageBusSupport.java

protected final Message<?> deserializePayloadIfNecessary(Message<?> message) {
    Message<?> messageToSend = message;
    Object originalPayload = message.getPayload();
    MimeType contentType = contentTypeResolver.resolve(message.getHeaders());
    Object payload = deserializePayload(originalPayload, contentType);
    if (payload != null) {
        MessageBuilder<Object> transformed = MessageBuilder.withPayload(payload)
                .copyHeaders(message.getHeaders());
        Object originalContentType = message.getHeaders().get(ORIGINAL_CONTENT_TYPE_HEADER);
        transformed.setHeader(MessageHeaders.CONTENT_TYPE, originalContentType);
        transformed.setHeader(ORIGINAL_CONTENT_TYPE_HEADER, null);
        messageToSend = transformed.build();
    }/* www .  j  av  a2 s .  c  om*/
    return messageToSend;
}

From source file:org.springframework.integration.zip.splitter.UnZipResultSplitter.java

@Override
@SuppressWarnings("unchecked")
protected Object splitMessage(Message<?> message) {
    Assert.state(message.getPayload() instanceof Map,
            "The UnZipResultSplitter supports only Map<String, Object> payload");
    Map<String, Object> unzippedEntries = (Map<String, Object>) message.getPayload();
    MessageHeaders headers = message.getHeaders();

    List<MessageBuilder<Object>> messageBuilders = new ArrayList<MessageBuilder<Object>>(
            unzippedEntries.size());/*from w  w w.  jav a 2 s .c  o  m*/

    for (Map.Entry<String, Object> entry : unzippedEntries.entrySet()) {
        String path = FilenameUtils.getPath(entry.getKey());
        String filename = FilenameUtils.getName(entry.getKey());
        MessageBuilder<Object> messageBuilder = MessageBuilder.withPayload(entry.getValue())
                .setHeader(FileHeaders.FILENAME, filename).setHeader(ZipHeaders.ZIP_ENTRY_PATH, path)
                .copyHeadersIfAbsent(headers);
        messageBuilders.add(messageBuilder);
    }

    return messageBuilders;
}

From source file:org.springframework.integration.zip.transformer.UnZipTransformer.java

@Override
protected Object doZipTransform(final Message<?> message) throws Exception {

    try {// ww  w .  j  ava  2  s .co  m
        final Object payload = message.getPayload();
        final Object unzippedData;

        InputStream inputStream = null;

        try {
            if (payload instanceof File) {
                final File filePayload = (File) payload;

                if (filePayload.isDirectory()) {
                    throw new UnsupportedOperationException(
                            String.format("Cannot unzip a directory: '%s'", filePayload.getAbsolutePath()));
                }

                if (!SpringZipUtils.isValid(filePayload)) {
                    throw new IllegalStateException(
                            String.format("Not a zip file: '%s'.", filePayload.getAbsolutePath()));
                }

                inputStream = new FileInputStream(filePayload);
            } else if (payload instanceof InputStream) {
                inputStream = (InputStream) payload;
            } else if (payload instanceof byte[]) {
                inputStream = new ByteArrayInputStream((byte[]) payload);
            } else {
                throw new IllegalArgumentException(String.format("Unsupported payload type '%s'. "
                        + "The only supported payload types are java.io.File, byte[] and java.io.InputStream",
                        payload.getClass().getSimpleName()));
            }

            final SortedMap<String, Object> uncompressedData = new TreeMap<String, Object>();

            ZipUtil.iterate(inputStream, new ZipEntryCallback() {

                @Override
                public void process(InputStream zipEntryInputStream, ZipEntry zipEntry) throws IOException {

                    final String zipEntryName = zipEntry.getName();
                    final long zipEntryTime = zipEntry.getTime();
                    final long zipEntryCompressedSize = zipEntry.getCompressedSize();
                    final String type = zipEntry.isDirectory() ? "directory" : "file";

                    if (logger.isInfoEnabled()) {
                        logger.info(String.format(
                                "Unpacking Zip Entry - Name: '%s',Time: '%s', "
                                        + "Compressed Size: '%s', Type: '%s'",
                                zipEntryName, zipEntryTime, zipEntryCompressedSize, type));
                    }

                    if (ZipResultType.FILE.equals(zipResultType)) {
                        final File destinationFile = checkPath(message, zipEntryName);

                        if (zipEntry.isDirectory()) {
                            destinationFile.mkdirs(); //NOSONAR false positive
                        } else {
                            SpringZipUtils.copy(zipEntryInputStream, destinationFile);
                            uncompressedData.put(zipEntryName, destinationFile);
                        }
                    } else if (ZipResultType.BYTE_ARRAY.equals(zipResultType)) {
                        if (!zipEntry.isDirectory()) {
                            checkPath(message, zipEntryName);
                            byte[] data = IOUtils.toByteArray(zipEntryInputStream);
                            uncompressedData.put(zipEntryName, data);
                        }
                    } else {
                        throw new IllegalStateException("Unsupported zipResultType " + zipResultType);
                    }
                }

                public File checkPath(final Message<?> message, final String zipEntryName) throws IOException {
                    final File tempDir = new File(workDirectory, message.getHeaders().getId().toString());
                    tempDir.mkdirs(); //NOSONAR false positive
                    final File destinationFile = new File(tempDir, zipEntryName);

                    /* If we see the relative traversal string of ".." we need to make sure
                     * that the outputdir + name doesn't leave the outputdir.
                     */
                    if (!destinationFile.getCanonicalPath().startsWith(workDirectory.getCanonicalPath())) {
                        throw new ZipException("The file " + zipEntryName
                                + " is trying to leave the target output directory of " + workDirectory);
                    }
                    return destinationFile;
                }
            });

            if (uncompressedData.isEmpty()) {
                if (logger.isWarnEnabled()) {
                    logger.warn(
                            "No data unzipped from payload with message Id " + message.getHeaders().getId());
                }
                unzippedData = null;
            } else {

                if (this.expectSingleResult) {
                    if (uncompressedData.size() == 1) {
                        unzippedData = uncompressedData.values().iterator().next();
                    } else {
                        throw new MessagingException(message,
                                String.format(
                                        "The UnZip operation extracted %s "
                                                + "result objects but expectSingleResult was 'true'.",
                                        uncompressedData.size()));
                    }
                } else {
                    unzippedData = uncompressedData;
                }

            }
        } finally {
            IOUtils.closeQuietly(inputStream);
            if (payload instanceof File && this.deleteFiles) {
                final File filePayload = (File) payload;
                if (!filePayload.delete() && logger.isWarnEnabled()) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("failed to delete File '" + filePayload + "'");
                    }
                }
            }
        }
        return unzippedData;
    } catch (Exception e) {
        throw new MessageHandlingException(message, "Failed to apply Zip transformation.", e);
    }
}

From source file:org.springframework.integration.zip.transformer.ZipTransformer.java

/**
 * The payload may encompass the following types:
 *
 * <ul>/*from   w  ww. jav  a 2  s.  c o m*/
 *   <li>{@link File}
 *...<li>{@link String}
 *...<li>byte[]
 *...<li>{@link Iterable}
 * </ul>
 *
 * When providing an {@link Iterable}, nested Iterables are not supported. However,
 * payloads can be of of any of the other supported types.
 *
 */
@Override
protected Object doZipTransform(Message<?> message) throws Exception {
    final Object payload = message.getPayload();
    final Object zippedData;
    final String baseFileName = this.fileNameGenerator.generateFileName(message);

    final String zipEntryName;
    final String zipFileName;

    if (message.getHeaders().containsKey(ZipHeaders.ZIP_ENTRY_FILE_NAME)) {
        zipEntryName = (String) message.getHeaders().get(ZipHeaders.ZIP_ENTRY_FILE_NAME);
    } else {
        zipEntryName = baseFileName;
    }

    if (message.getHeaders().containsKey(FileHeaders.FILENAME)) {
        zipFileName = (String) message.getHeaders().get(FileHeaders.FILENAME);
    } else {
        zipFileName = baseFileName + ZIP_EXTENSION;
    }

    final Date lastModifiedDate;

    if (message.getHeaders().containsKey(ZipHeaders.ZIP_ENTRY_LAST_MODIFIED_DATE)) {
        lastModifiedDate = (Date) message.getHeaders().get(ZipHeaders.ZIP_ENTRY_LAST_MODIFIED_DATE);
    } else {
        lastModifiedDate = new Date();
    }

    java.util.List<ZipEntrySource> entries = new ArrayList<ZipEntrySource>();

    if (payload instanceof Iterable<?>) {
        int counter = 1;

        String baseName = FilenameUtils.getBaseName(zipEntryName);
        String fileExtension = FilenameUtils.getExtension(zipEntryName);

        if (StringUtils.hasText(fileExtension)) {
            fileExtension = FilenameUtils.EXTENSION_SEPARATOR_STR + fileExtension;
        }

        for (Object item : (Iterable<?>) payload) {

            final ZipEntrySource zipEntrySource = createZipEntrySource(item, lastModifiedDate,
                    baseName + "_" + counter + fileExtension, this.useFileAttributes);
            if (logger.isDebugEnabled()) {
                logger.debug("ZipEntrySource path: '" + zipEntrySource.getPath() + "'");
            }
            entries.add(zipEntrySource);
            counter++;
        }
    } else {
        final ZipEntrySource zipEntrySource = createZipEntrySource(payload, lastModifiedDate, zipEntryName,
                this.useFileAttributes);
        entries.add(zipEntrySource);
    }

    final byte[] zippedBytes = SpringZipUtils.pack(entries, this.compressionLevel);

    if (ZipResultType.FILE.equals(this.zipResultType)) {
        final File zippedFile = new File(this.workDirectory, zipFileName);
        FileCopyUtils.copy(zippedBytes, zippedFile);
        zippedData = zippedFile;
    } else if (ZipResultType.BYTE_ARRAY.equals(this.zipResultType)) {
        zippedData = zippedBytes;
    } else {
        throw new IllegalStateException("Unsupported zipResultType " + this.zipResultType);
    }

    if (this.deleteFiles) {
        if (payload instanceof Iterable<?>) {
            for (Object item : (Iterable<?>) payload) {
                deleteFile(item);
            }
        } else {
            deleteFile(payload);
        }
    }
    return getMessageBuilderFactory().withPayload(zippedData).copyHeaders(message.getHeaders())
            .setHeader(FileHeaders.FILENAME, zipFileName).build();
}

From source file:org.springframework.integration.zip.Zip2FileTests.java

@Test
public void zipStringWithDefaultFileName() throws IOException, InterruptedException {

    final Message<String> message = MessageBuilder.withPayload("Zip me up.").build();

    input.send(message);//w  w  w .  j  av  a  2s  .  c  o  m

    Assert.assertTrue(this.workDir.list().length == 1);

    File fileInWorkDir = this.workDir.listFiles()[0];

    Assert.assertTrue(fileInWorkDir.isFile());
    Assert.assertTrue(fileInWorkDir.getName().contains(message.getHeaders().getId().toString()));
    Assert.assertTrue("The created file should have a 'zip' file extension.",
            fileInWorkDir.getName().endsWith(".zip"));
}

From source file:org.springframework.kafka.support.converter.MessagingMessageConverter.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override// w  ww.  ja v  a  2s  .c o m
public ProducerRecord<?, ?> fromMessage(Message<?> message, String defaultTopic) {
    MessageHeaders headers = message.getHeaders();
    Object topicHeader = headers.get(KafkaHeaders.TOPIC);
    String topic = null;
    if (topicHeader instanceof byte[]) {
        topic = new String(((byte[]) topicHeader), StandardCharsets.UTF_8);
    } else if (topicHeader instanceof String) {
        topic = (String) topicHeader;
    } else if (topicHeader == null) {
        Assert.state(defaultTopic != null, "With no topic header, a defaultTopic is required");
    } else {
        throw new IllegalStateException(
                KafkaHeaders.TOPIC + " must be a String or byte[], not " + topicHeader.getClass());
    }
    Integer partition = headers.get(KafkaHeaders.PARTITION_ID, Integer.class);
    Object key = headers.get(KafkaHeaders.MESSAGE_KEY);
    Object payload = convertPayload(message);
    Long timestamp = headers.get(KafkaHeaders.TIMESTAMP, Long.class);
    Headers recordHeaders = initialRecordHeaders(message);
    if (this.headerMapper != null) {
        this.headerMapper.fromHeaders(headers, recordHeaders);
    }
    return new ProducerRecord(topic == null ? defaultTopic : topic, partition, timestamp, key, payload,
            recordHeaders);
}