Introduction
In this page you can find the example usage for org.springframework.messaging Message getPayload.
Prototype
T getPayload();
Source Link
Document
Return the message payload.
Usage
From source file:
org.springframework.integration.zip.transformer.UnZipTransformer.java
@Override
protected Object doZipTransform(final Message<?> message) throws Exception {
try {//from w w w .ja va 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.UnZipTransformerTests.java
/**
* UnCompress a ZIP archive containing a single file only. The result will be
* a byte array./*from ww w .j av a 2 s .c om*/
* @throws IOException
@Test
public void unzipSingleFileAsInputStreamToByteArray() throws IOException {
final Resource resource = this.resourceLoader.getResource("classpath:testzipdata/single.zip");
final InputStream is = resource.getInputStream();
final Message<InputStream> message = MessageBuilder.withPayload(is).build();
final UnZipTransformer unZipTransformer = new UnZipTransformer();
unZipTransformer.setZipResultType(ZipResultType.BYTE_ARRAY);
unZipTransformer.afterPropertiesSet();
final Message<?> resultMessage = unZipTransformer.transform(message);
Assert.assertNotNull(resultMessage);
@SuppressWarnings("unchecked")
Map<String, byte[]> unzippedData = (Map<String, byte[]>) resultMessage.getPayload();
Assert.assertNotNull(unzippedData);
Assert.assertTrue(unzippedData.size() == 1);
Assert.assertEquals("Spring Integration Rocks!", new String(unzippedData.values().iterator().next()));
From source file:
org.springframework.integration.zip.transformer.UnZipTransformerTests.java
/**
* @throws IOException//from w ww. j av a2 s . co m
@Test
public void unzipSingleFileToByteArray() throws IOException {
final Resource resource = this.resourceLoader.getResource("classpath:testzipdata/single.zip");
final InputStream is = resource.getInputStream();
final File inputFile = new File(this.workDir, "unzipSingleFileToByteArray");
IOUtils.copy(is, new FileOutputStream(inputFile));
final Message<File> message = MessageBuilder.withPayload(inputFile).build();
final UnZipTransformer unZipTransformer = new UnZipTransformer();
unZipTransformer.setZipResultType(ZipResultType.BYTE_ARRAY);
unZipTransformer.afterPropertiesSet();
final Message<?> resultMessage = unZipTransformer.transform(message);
Assert.assertNotNull(resultMessage);
@SuppressWarnings("unchecked")
Map<String, byte[]> unzippedData = (Map<String, byte[]>) resultMessage.getPayload();
Assert.assertNotNull(unzippedData);
Assert.assertTrue(unzippedData.size() == 1);
Assert.assertTrue(inputFile.exists());
Assert.assertEquals("Spring Integration Rocks!", new String(unzippedData.values().iterator().next()));
From source file:
org.springframework.integration.zip.transformer.UnZipTransformerTests.java
/**
* @throws IOException/*from ww w .j a va2 s. co m*/
@Test
public void unzipSingleFileToByteArrayWithDeleteFilesTrue() throws IOException {
final Resource resource = this.resourceLoader.getResource("classpath:testzipdata/single.zip");
final InputStream is = resource.getInputStream();
final File inputFile = new File(this.workDir, "unzipSingleFileToByteArray");
FileOutputStream output = new FileOutputStream(inputFile);
IOUtils.copy(is, output);
output.close();
final Message<File> message = MessageBuilder.withPayload(inputFile).build();
final UnZipTransformer unZipTransformer = new UnZipTransformer();
unZipTransformer.setZipResultType(ZipResultType.BYTE_ARRAY);
unZipTransformer.setDeleteFiles(true);
unZipTransformer.afterPropertiesSet();
final Message<?> resultMessage = unZipTransformer.transform(message);
Assert.assertNotNull(resultMessage);
@SuppressWarnings("unchecked")
Map<String, byte[]> unzippedData = (Map<String, byte[]>) resultMessage.getPayload();
Assert.assertNotNull(unzippedData);
Assert.assertTrue(unzippedData.size() == 1);
Assert.assertFalse(inputFile.exists());
Assert.assertEquals("Spring Integration Rocks!", new String(unzippedData.values().iterator().next()));
From source file:
org.springframework.integration.zip.transformer.UnZipTransformerTests.java
/**
* UnCompress a ZIP archive containing multiple files. The result will be
* a collection of files.//from ww w.j a v a2s . c om
* @throws IOException
@Test
public void unzipMultipleFilesAsInputStreamToByteArray() throws IOException {
final Resource resource = this.resourceLoader.getResource("classpath:testzipdata/countries.zip");
final InputStream is = resource.getInputStream();
final Message<InputStream> message = MessageBuilder.withPayload(is).build();
final UnZipTransformer unZipTransformer = new UnZipTransformer();
unZipTransformer.setZipResultType(ZipResultType.BYTE_ARRAY);
unZipTransformer.afterPropertiesSet();
final Message<?> resultMessage = unZipTransformer.transform(message);
Assert.assertNotNull(resultMessage);
@SuppressWarnings("unchecked")
Map<String, byte[]> unzippedData = (Map<String, byte[]>) resultMessage.getPayload();
Assert.assertNotNull(unzippedData);
Assert.assertTrue(unzippedData.size() == 5);
From source file:
org.springframework.integration.zip.transformer.ZipTransformer.java
/**
* The payload may encompass the following types:
* <ul>/* ww w. j a v a 2 s . co 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.kafka.listener.adapter.MessagingMessageListenerAdapter.java
/**
* Invoke the handler, wrapping any exception to a {@link ListenerExecutionFailedException}
* with a dedicated error message.// w w w. j a va 2s . com
* @param data the data to process during invocation.
* @param acknowledgment the acknowledgment to use if any.
* @param message the message to process.
* @return the result of invocation.
protected final Object invokeHandler(Object data, Acknowledgment acknowledgment, Message<?> message) {
try {
if (data instanceof List && !this.isConsumerRecordList) {
return this.handlerMethod.invoke(message, acknowledgment);
} else {
return this.handlerMethod.invoke(message, data, acknowledgment);
} catch (org.springframework.messaging.converter.MessageConversionException ex) {
throw new ListenerExecutionFailedException(createMessagingErrorMessage(
"Listener method could not " + "be invoked with the incoming message", message.getPayload()),
new MessageConversionException("Cannot handle message", ex));
} catch (MessagingException ex) {
throw new ListenerExecutionFailedException(createMessagingErrorMessage(
"Listener method could not " + "be invoked with the incoming message", message.getPayload()),
} catch (Exception ex) {
throw new ListenerExecutionFailedException("Listener method '"
+ this.handlerMethod.getMethodAsString(message.getPayload()) + "' threw exception", ex);
From source file:
org.springframework.kafka.support.converter.MessagingMessageConverter.java
/**
* Subclasses can convert the payload; by default, it's sent unchanged to Kafka.
* @param message the message.//from w w w. j a va 2s . c o m
* @return the payload.
protected Object convertPayload(Message<?> message) {
Object payload = message.getPayload();
if (payload instanceof KafkaNull) {
return null;
} else {
return payload;
From source file:
org.springframework.kafka.support.converter.StringJsonMessageConverter.java
@Override
protected Object convertPayload(Message<?> message) {
try {// w w w . ja v a 2 s.co m
return this.objectMapper.writeValueAsString(message.getPayload());
} catch (JsonProcessingException e) {
throw new ConversionException("Failed to convert to JSON", e);
From source file:
org.springframework.messaging.handler.annotation.reactive.PayloadMethodArgumentResolver.java
@SuppressWarnings("unchecked")
private Flux<DataBuffer> extractContent(MethodParameter parameter, Message<?> message) {
Object payload = message.getPayload();
if (payload instanceof DataBuffer) {
return Flux.just((DataBuffer) payload);
}/* w w w.ja v a 2 s .c o m*/
if (payload instanceof Publisher) {
return Flux.from((Publisher<?>) payload).map(value -> {
if (value instanceof DataBuffer) {
return (DataBuffer) value;
String className = value.getClass().getName();
throw getUnexpectedPayloadError(message, parameter, "Publisher<" + className + ">");