Start version 2.0

* Upgrade to Spring Integration 5.5
* Minimum Java 8
* Migrate test to Junit 5 and AssertJ
* Migrate test logging to Log4J 2
This commit is contained in:
Artem Bilan
2021-06-25 13:48:58 -04:00
parent c9125be8cc
commit 494c15c7ec
26 changed files with 454 additions and 639 deletions

View File

@@ -1,10 +1,18 @@
buildscript {
repositories {
mavenCentral()
maven { url 'https://plugins.gradle.org/m2' }
maven { url 'https://repo.spring.io/plugins-release-local' }
}
}
plugins {
id 'java-library'
id 'eclipse'
id 'idea'
id 'jacoco'
id 'org.sonarqube' version '2.8'
id 'com.jfrog.artifactory' version '4.19.0'
id 'com.jfrog.artifactory' version '4.21.0'
}
description = 'Spring Integration Zip Adapter'
@@ -13,10 +21,11 @@ group = 'org.springframework.integration'
repositories {
mavenCentral()
if (version.endsWith('BUILD-SNAPSHOT')) {
maven { url 'https://repo.spring.io/libs-snapshot' }
maven { url 'https://repo.spring.io/release' }
maven { url 'https://repo.spring.io/milestone' }
if (version.endsWith('SNAPSHOT')) {
maven { url 'https://repo.spring.io/snapshot' }
}
maven { url 'https://repo.spring.io/libs-milestone' }
}
java {
@@ -24,8 +33,8 @@ java {
withSourcesJar()
}
sourceCompatibility=1.6
targetCompatibility=1.6
sourceCompatibility=1.8
targetCompatibility=1.8
ext {
@@ -36,8 +45,10 @@ ext {
linkScmConnection = 'https://github.com/spring-projects/spring-integration-extensions.git'
linkScmDevConnection = 'git@github.com:spring-projects/spring-integration-extensions.git'
slf4jVersion = '1.7.30'
springIntegrationVersion = '4.3.24.RELEASE'
assertjVersion = '3.20.2'
junitVersion = '5.7.2'
log4jVersion = '2.14.1'
springIntegrationVersion = '5.5.1'
ztZipVersion = '1.14'
idPrefix = 'zip'
@@ -58,7 +69,7 @@ sourceSets {
}
jacoco {
toolVersion = '0.8.6'
toolVersion = '0.8.7'
}
dependencies {
@@ -66,7 +77,13 @@ dependencies {
api "org.zeroturnaround:zt-zip:$ztZipVersion"
testImplementation "org.springframework.integration:spring-integration-test:$springIntegrationVersion"
testRuntimeOnly "org.slf4j:slf4j-log4j12:$slf4jVersion"
testImplementation "org.assertj:assertj-core:$assertjVersion"
testImplementation "org.junit.jupiter:junit-jupiter-api:$junitVersion"
testRuntimeOnly "org.apache.logging.log4j:log4j-jcl:$log4jVersion"
testRuntimeOnly "org.apache.logging.log4j:log4j-slf4j-impl:$log4jVersion"
testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:$junitVersion"
testRuntimeOnly "org.junit.platform:junit-platform-launcher:1.7.2"
}
@@ -81,7 +98,7 @@ test {
jacoco {
destinationFile = file("$buildDir/jacoco.exec")
}
useJUnitPlatform()
if (System.properties['sonar.host.url']) {
finalizedBy jacocoTestReport
}
@@ -119,7 +136,7 @@ task api(type: Javadoc) {
source = sourceSets.main.allJava
classpath = project.sourceSets.main.compileClasspath
destinationDir = new File(buildDir, "api")
destinationDir = new File(buildDir, 'api')
}
task schemaZip(type: Zip) {
@@ -168,7 +185,7 @@ task distZip(type: Zip, dependsOn: [docsZip, schemaZip]) {
description = "Builds -${archiveClassifier} archive, containing all jars and docs, " +
"suitable for community download page."
ext.baseDir = "${project.name}-${project.version}";
ext.baseDir = "${project.name}-${project.version}"
from('src/dist') {
include 'readme.txt'
@@ -177,11 +194,11 @@ task distZip(type: Zip, dependsOn: [docsZip, schemaZip]) {
into "${baseDir}"
}
from(zipTree(docsZip.archivePath)) {
from(zipTree(docsZip.archiveFile)) {
into "${baseDir}/docs"
}
from(zipTree(schemaZip.archivePath)) {
from(zipTree(schemaZip.archiveFile)) {
into "${baseDir}/schema"
}
@@ -200,7 +217,7 @@ task depsZip(type: Zip, dependsOn: distZip) { zipTask ->
description = "Builds -${archiveClassifier} archive, containing everything " +
"in the -${distZip.archiveClassifier} archive plus all dependencies."
from zipTree(distZip.archivePath)
from zipTree(distZip.archiveFile)
gradle.taskGraph.whenReady { taskGraph ->
if (taskGraph.hasTask(":${zipTask.name}")) {
@@ -209,7 +226,7 @@ task depsZip(type: Zip, dependsOn: distZip) { zipTask ->
rootProject.configurations.runtime.resolvedConfiguration.resolvedArtifacts.each { artifact ->
def dependency = artifact.moduleVersion.id
if (!projectName.equals(dependency.name)) {
if (projectName != dependency.name) {
artifacts << artifact.file
}
}

View File

@@ -1 +1 @@
version=1.0.5.BUILD-SNAPSHOT
version=2.0.0-SNAPSHOT

View File

@@ -1,5 +1,9 @@
apply plugin: 'maven-publish'
tasks.withType(GenerateModuleMetadata) {
enabled = false
}
publishing {
publications {
mavenJava(MavenPublication) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015-2016 the original author or authors.
* Copyright 2015-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,12 +13,14 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.zip;
/**
* Zip adapter specific message headers.
*
* @author Gunnar Hillert
* @since 1.0
*
*/
public abstract class ZipHeaders {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015-2017 the original author or authors.
* Copyright 2015-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -35,8 +35,6 @@ import org.springframework.util.Assert;
* @author Gunnar Hillert
* @author Andriy Kryvtsun
* @author Artem Bilan
*
* @since 1.0
*/
public class UnZipResultSplitter extends AbstractMessageSplitter {
@@ -48,7 +46,7 @@ public class UnZipResultSplitter extends AbstractMessageSplitter {
Map<String, Object> unzippedEntries = (Map<String, Object>) message.getPayload();
MessageHeaders headers = message.getHeaders();
List<MessageBuilder<Object>> messageBuilders = new ArrayList<MessageBuilder<Object>>(unzippedEntries.size());
List<MessageBuilder<Object>> messageBuilders = new ArrayList<>(unzippedEntries.size());
for (Map.Entry<String, Object> entry : unzippedEntries.entrySet()) {
String path = FilenameUtils.getPath(entry.getKey());

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015-2016 the original author or authors.
* Copyright 2015-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,8 +19,6 @@ package org.springframework.integration.zip.transformer;
import java.io.File;
import java.nio.charset.Charset;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.integration.file.DefaultFileNameGenerator;
import org.springframework.integration.file.FileNameGenerator;
import org.springframework.integration.transformer.AbstractTransformer;
@@ -32,28 +30,25 @@ import org.springframework.util.Assert;
*
* @author Gunnar Hillert
* @author Artem Bilan
* @since 1.0
*
*/
public abstract class AbstractZipTransformer extends AbstractTransformer {
private static final Log logger = LogFactory.getLog(ZipTransformer.class);
protected Charset charset = Charset.defaultCharset();
protected volatile Charset charset = Charset.defaultCharset();
protected volatile FileNameGenerator fileNameGenerator;
protected FileNameGenerator fileNameGenerator;
protected ZipResultType zipResultType = ZipResultType.FILE;
protected volatile File workDirectory =
protected File workDirectory =
new File(System.getProperty("java.io.tmpdir") + File.separator + "ziptransformer");
protected volatile boolean deleteFiles;
protected boolean deleteFiles;
/**
* If the payload is an instance of {@link File}, this property specifies
* whether to delete the {@link File} after transformation.
* Default is <em>false</em>.
*
* @param deleteFiles Defaults to <em>false</em> if not set
*/
public void setDeleteFiles(boolean deleteFiles) {
@@ -64,26 +59,22 @@ public abstract class AbstractZipTransformer extends AbstractTransformer {
* Set the work-directory. The work directory is used when the {@link ZipResultType}
* is set to {@link ZipResultType#FILE}. By default this property is set to
* the System temporary directory containing a sub-directory "ziptransformer".
*
* @param workDirectory Must not be null and must not represent a file.
*/
public void setWorkDirectory(File workDirectory) {
Assert.notNull(workDirectory, "workDirectory must not be null.");
Assert.isTrue(!workDirectory.isFile(), "The workDirectory specified must not point to a file");
Assert.isTrue(workDirectory.isDirectory(), "The workDirectory specified must be a directory.");
this.workDirectory = workDirectory;
}
/**
* Defines the format of the data returned after transformation. Available
* options are:
*
* <ul>
* <li>File</li>
* <li>Byte Array</li>
* </ul>
*
* Defaults to {@link ZipResultType#FILE}.
*
* @param zipResultType Must not be null
*/
public void setZipResultType(ZipResultType zipResultType) {
@@ -92,16 +83,14 @@ public abstract class AbstractZipTransformer extends AbstractTransformer {
}
@Override
protected void onInit() throws Exception {
protected void onInit() {
super.onInit();
if (!this.workDirectory.exists()) {
if (logger.isInfoEnabled()) {
logger.info(String.format("Creating work directory '%s'.", this.workDirectory));
}
Assert.isTrue(this.workDirectory.mkdirs(), "Can't create the 'workDirectory': " + this.workDirectory);
logger.info(() -> "Creating work directory: " + this.workDirectory);
Assert.isTrue(this.workDirectory.mkdirs(), () -> "Can't create the 'workDirectory': " + this.workDirectory);
}
final DefaultFileNameGenerator defaultFileNameGenerator = new DefaultFileNameGenerator();
DefaultFileNameGenerator defaultFileNameGenerator = new DefaultFileNameGenerator();
defaultFileNameGenerator.setBeanFactory(getBeanFactory());
defaultFileNameGenerator.setConversionService(getConversionService());
this.fileNameGenerator = defaultFileNameGenerator;
@@ -112,22 +101,16 @@ public abstract class AbstractZipTransformer extends AbstractTransformer {
* @param message the message and its payload must not be null.
*/
@Override
protected Object doTransform(Message<?> message) throws Exception {
Assert.notNull(message, "message must not be null");
final Object payload = message.getPayload();
Assert.notNull(payload, "payload must not be null");
protected Object doTransform(Message<?> message) {
return doZipTransform(message);
}
/**
* Subclasses must implement this method to provide the Zip transformation
* logic.
*
* @param message The message will never be null.
* @return The result of the Zip transformation.
* @throws Exception Any exception.
*/
protected abstract Object doZipTransform(Message<?> message) throws Exception;
protected abstract Object doZipTransform(Message<?> message);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015-2016 the original author or authors.
* Copyright 2015-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -29,49 +29,38 @@ import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.zeroturnaround.zip.ZipEntrySource;
import org.zeroturnaround.zip.ZipException;
import org.springframework.core.log.LogAccessor;
/**
* Once the Spring Integration Zip support matures, we need to contribute the
* methods in this utility class back to the ZT Zip project.
*
* @author Gunnar Hillert
* @since 1.0
*/
public class SpringZipUtils {
private static final Log logger = LogFactory.getLog(SpringZipUtils.class);
private static final LogAccessor logger = new LogAccessor(SpringZipUtils.class);
public static byte[] pack(Collection<ZipEntrySource> entries, int compressionLevel) {
if (logger.isDebugEnabled()) {
logger.debug(String.format("Creating byte array from '%s'.",
entries));
}
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
logger.debug(() -> "Creating byte array from: " + entries);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
pack(entries, outputStream, compressionLevel);
return outputStream.toByteArray();
}
public static void pack(Collection<ZipEntrySource> entries, File zip, int compressionLevel) {
logger.debug(() -> "Creating '" + zip + "' from " + entries + ".");
if (logger.isDebugEnabled()) {
logger.debug("Creating '" + zip + "' from " + entries + ".");
}
final FileOutputStream outputStream;
FileOutputStream outputStream;
try {
outputStream = new FileOutputStream(zip);
}
catch (FileNotFoundException e) {
throw new IllegalStateException(String.format("File '%s' not found.", zip.getAbsolutePath()), e);
}
pack(entries, outputStream, compressionLevel);
}

View File

@@ -26,8 +26,6 @@ import java.util.TreeMap;
import java.util.zip.ZipEntry;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.zeroturnaround.zip.ZipEntryCallback;
import org.zeroturnaround.zip.ZipException;
import org.zeroturnaround.zip.ZipUtil;
@@ -44,13 +42,9 @@ import org.springframework.messaging.MessagingException;
* @author Artem Bilan
* @author Ingo Dueppe
*
* @since 1.0
*
*/
public class UnZipTransformer extends AbstractZipTransformer {
private static final Log logger = LogFactory.getLog(UnZipTransformer.class);
private volatile boolean expectSingleResult = false;
/**
@@ -73,8 +67,8 @@ public class UnZipTransformer extends AbstractZipTransformer {
@Override
protected Object doZipTransform(final Message<?> message) {
try {
final Object payload = message.getPayload();
final Object unzippedData;
Object payload = message.getPayload();
Object unzippedData;
InputStream inputStream = null;
@@ -83,13 +77,12 @@ public class UnZipTransformer extends AbstractZipTransformer {
final File filePayload = (File) payload;
if (filePayload.isDirectory()) {
throw new UnsupportedOperationException(String.format("Cannot unzip a directory: '%s'",
filePayload.getAbsolutePath()));
throw new UnsupportedOperationException("Cannot unzip a directory: " +
filePayload.getAbsolutePath());
}
if (!SpringZipUtils.isValid(filePayload)) {
throw new IllegalStateException(String.format("Not a zip file: '%s'.",
filePayload.getAbsolutePath()));
throw new IllegalStateException("Not a zip file: " + filePayload.getAbsolutePath());
}
inputStream = new FileInputStream(filePayload);
@@ -101,12 +94,11 @@ public class UnZipTransformer extends AbstractZipTransformer {
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()));
throw new IllegalArgumentException("Unsupported payload type '" + payload.getClass().getSimpleName()
+ "'. The only supported payload types are java.io.File, byte[] and java.io.InputStream");
}
final SortedMap<String, Object> uncompressedData = new TreeMap<String, Object>();
final SortedMap<String, Object> uncompressedData = new TreeMap<>();
ZipUtil.iterate(inputStream, new ZipEntryCallback() {
@@ -118,11 +110,9 @@ public class UnZipTransformer extends AbstractZipTransformer {
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));
}
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);
@@ -167,9 +157,7 @@ public class UnZipTransformer extends AbstractZipTransformer {
});
if (uncompressedData.isEmpty()) {
if (logger.isWarnEnabled()) {
logger.warn("No data unzipped from payload with message Id " + message.getHeaders().getId());
}
logger.warn(() -> "No data unzipped from payload with message Id " + message.getHeaders().getId());
unzippedData = null;
}
else {
@@ -195,9 +183,7 @@ public class UnZipTransformer extends AbstractZipTransformer {
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 + "'");
}
logger.warn(() -> "failed to delete File '" + filePayload + "'");
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015-2016 the original author or authors.
* Copyright 2015-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,11 +13,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.zip.transformer;
/**
* @author Gunnar Hillert
* @since 1.0
*/
public enum ZipResultType {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015-2016 the original author or authors.
* Copyright 2015-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,13 +17,13 @@
package org.springframework.integration.zip.transformer;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.zip.Deflater;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.zeroturnaround.zip.ByteSource;
import org.zeroturnaround.zip.FileSource;
import org.zeroturnaround.zip.ZipEntrySource;
@@ -49,13 +49,10 @@ import org.springframework.util.StringUtils;
*
* @author Gunnar Hillert
* @author Artem Bilan
* @since 1.0
*
*/
public class ZipTransformer extends AbstractZipTransformer {
private static final Log logger = LogFactory.getLog(ZipTransformer.class);
private static final String ZIP_EXTENSION = ".zip";
private volatile int compressionLevel = Deflater.DEFAULT_COMPRESSION;
@@ -63,8 +60,7 @@ public class ZipTransformer extends AbstractZipTransformer {
private volatile boolean useFileAttributes = true;
/**
* Sets the compression level. Default is {@link Deflater#DEFAULT_COMPRESSION}.
*
* Set the compression level. Default is {@link Deflater#DEFAULT_COMPRESSION}.
* @param compressionLevel Must be an integer value from 0-9.
*/
public void setCompressionLevel(int compressionLevel) {
@@ -73,9 +69,7 @@ public class ZipTransformer extends AbstractZipTransformer {
}
/**
* Specifies whether the name of the file shall be used for the
* zip entry.
*
* Specify whether the name of the file shall be used for the zip entry.
* @param useFileAttributes Defaults to true if not set explicitly
*/
public void setUseFileAttributes(boolean useFileAttributes) {
@@ -84,20 +78,17 @@ public class ZipTransformer extends AbstractZipTransformer {
/**
* The payload may encompass the following types:
*
* <ul>
* <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 {
protected Object doZipTransform(Message<?> message) {
final Object payload = message.getPayload();
final Object zippedData;
final String baseFileName = this.fileNameGenerator.generateFileName(message);
@@ -128,7 +119,7 @@ public class ZipTransformer extends AbstractZipTransformer {
lastModifiedDate = new Date();
}
java.util.List<ZipEntrySource> entries = new ArrayList<ZipEntrySource>();
java.util.List<ZipEntrySource> entries = new ArrayList<>();
if (payload instanceof Iterable<?>) {
int counter = 1;
@@ -144,9 +135,7 @@ public class ZipTransformer extends AbstractZipTransformer {
final ZipEntrySource zipEntrySource = createZipEntrySource(item, lastModifiedDate, baseName + "_"
+ counter + fileExtension, this.useFileAttributes);
if (logger.isDebugEnabled()) {
logger.debug("ZipEntrySource path: '" + zipEntrySource.getPath() + "'");
}
logger.debug(() -> "ZipEntrySource path: '" + zipEntrySource.getPath() + "'");
entries.add(zipEntrySource);
counter++;
}
@@ -161,7 +150,12 @@ public class ZipTransformer extends AbstractZipTransformer {
if (ZipResultType.FILE.equals(this.zipResultType)) {
final File zippedFile = new File(this.workDirectory, zipFileName);
FileCopyUtils.copy(zippedBytes, zippedFile);
try {
FileCopyUtils.copy(zippedBytes, zippedFile);
}
catch (IOException ex) {
throw new UncheckedIOException(ex);
}
zippedData = zippedFile;
}
else if (ZipResultType.BYTE_ARRAY.equals(this.zipResultType)) {
@@ -189,8 +183,8 @@ public class ZipTransformer extends AbstractZipTransformer {
}
private void deleteFile(Object fileToDelete) {
if (fileToDelete instanceof File && !((File) fileToDelete).delete() && logger.isWarnEnabled()) {
logger.warn("Failed to delete File '" + fileToDelete + "'");
if (fileToDelete instanceof File && !((File) fileToDelete).delete()) {
logger.warn(() -> "Failed to delete File '" + fileToDelete + "'");
}
}
@@ -210,8 +204,7 @@ public class ZipTransformer extends AbstractZipTransformer {
}
else if (item instanceof byte[] || item instanceof String) {
byte[] bytesToCompress = null;
byte[] bytesToCompress;
if (item instanceof String) {
bytesToCompress = ((String) item).getBytes(this.charset);

View File

@@ -1,4 +1,4 @@
http\://www.springframework.org/schema/integration/zip/spring-integration-zip-1.0.xsd=org/springframework/integration/zip/config/spring-integration-zip-1.0.xsd
http\://www.springframework.org/schema/integration/zip/spring-integration-zip.xsd=org/springframework/integration/zip/config/spring-integration-zip-1.0.xsd
https\://www.springframework.org/schema/integration/zip/spring-integration-zip-1.0.xsd=org/springframework/integration/zip/config/spring-integration-zip-1.0.xsd
https\://www.springframework.org/schema/integration/zip/spring-integration-zip.xsd=org/springframework/integration/zip/config/spring-integration-zip-1.0.xsd
http\://www.springframework.org/schema/integration/zip/spring-integration-zip-1.0.xsd=org/springframework/integration/zip/config/spring-integration-zip.xsd
http\://www.springframework.org/schema/integration/zip/spring-integration-zip.xsd=org/springframework/integration/zip/config/spring-integration-zip.xsd
https\://www.springframework.org/schema/integration/zip/spring-integration-zip-1.0.xsd=org/springframework/integration/zip/config/spring-integration-zip.xsd
https\://www.springframework.org/schema/integration/zip/spring-integration-zip.xsd=org/springframework/integration/zip/config/spring-integration-zip.xsd

View File

@@ -11,6 +11,8 @@
http://www.springframework.org/schema/integration/zip https://www.springframework.org/schema/integration/zip/spring-integration-zip.xsd
http://www.springframework.org/schema/integration https://www.springframework.org/schema/integration/spring-integration.xsd">
<context:property-placeholder/>
<int:channel id="input"/>
<int:chain input-channel="input" output-channel="out">
@@ -26,9 +28,8 @@
</int:interceptors>
</int:channel>
<int:logging-channel-adapter id="logger" log-full-message="true" level="WARN"/>
<int:logging-channel-adapter id="logger" log-full-message="true" level="INFO"/>
<int-file:outbound-channel-adapter id="write-file" channel="out" directory-expression="'${workDir}/' + headers.zip_entryPath" auto-create-directory="true"/>
<int-file:outbound-channel-adapter id="write-file" channel="out" directory-expression="'${workDir}/' + headers.zip_entryPath"/>
<context:property-placeholder properties-ref="properties"/>
</beans>

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015-2016 the original author or authors.
* Copyright 2015-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,110 +16,95 @@
package org.springframework.integration.zip;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.fail;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.nio.file.Files;
import java.nio.file.Path;
import org.apache.commons.io.IOUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.zeroturnaround.zip.ZipException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.integration.transformer.MessageTransformationException;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandlingException;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
/**
*
* @author Gunnar Hillert
* @since 1.0
*
* @author Artem Bilan
*/
@SpringJUnitConfig
@DirtiesContext
public class UnZip2FileTests {
private AnnotationConfigApplicationContext context;
private ResourceLoader resourceLoader;
@Autowired
private ApplicationContext context;
@Autowired
private MessageChannel input;
private static final Properties properties = new Properties();
@TempDir
public static File workDir;
@Rule
public TemporaryFolder testFolder = new TemporaryFolder();
private File workDir;
@Before
public void setup() throws IOException {
this.workDir = this.testFolder.newFolder();
properties.put("workDir", this.workDir);
System.out.print(this.workDir.getAbsolutePath());
this.context = new AnnotationConfigApplicationContext();
this.context.register(ContextConfiguration.class);
this.context.refresh();
this.input = this.context.getBean("input", MessageChannel.class);
this.resourceLoader = this.context;
@BeforeAll
public static void setup() {
System.setProperty("workDir", workDir.getAbsolutePath());
}
@After
public void cleanup() {
if (this.context != null) {
this.context.close();
}
@BeforeEach
public void cleanUp() {
cleanupDirectory(workDir);
}
@Test
public void unZipWithOneEntry() throws Exception {
final Resource resource = this.resourceLoader.getResource("classpath:testzipdata/single.zip");
final Resource resource = this.context.getResource("classpath:testzipdata/single.zip");
final InputStream is = resource.getInputStream();
byte[] zipdata = IOUtils.toByteArray(is);
is.close();
final Message<byte[]> message = MessageBuilder.withPayload(zipdata).build();
input.send(message);
Assert.assertTrue(this.workDir.list().length == 1);
assertThat(workDir.list()).hasSize(1);
File fileInWorkDir = this.workDir.listFiles()[0];
File fileInWorkDir = workDir.listFiles()[0];
Assert.assertTrue(fileInWorkDir.isFile());
Assert.assertEquals("single.txt", fileInWorkDir.getName());
assertThat(fileInWorkDir).isFile();
assertThat(fileInWorkDir).hasName("single.txt");
}
@Test
public void unZipWithMultipleEntries() throws Exception {
final Resource resource = resourceLoader.getResource("classpath:testzipdata/countries.zip");
final Resource resource = this.context.getResource("classpath:testzipdata/countries.zip");
final InputStream is = resource.getInputStream();
byte[] zipdata = IOUtils.toByteArray(is);
is.close();
final Message<byte[]> message = MessageBuilder.withPayload(zipdata).build();
input.send(message);
Assert.assertTrue(this.workDir.list().length == 4);
assertThat(workDir.list()).hasSize(4);
File[] files = this.workDir.listFiles();
File[] files = workDir.listFiles();
boolean continents = false;
boolean de = false;
@@ -129,58 +114,47 @@ public class UnZip2FileTests {
for (File file : files) {
if (file.getName().equals("continents")) {
continents = true;
Assert.assertTrue(file.isDirectory());
Assert.assertTrue(file.list().length == 2);
assertThat(file).isDirectory();
assertThat(file.list()).hasSize(2);
}
if (file.getName().equals("de.txt")) {
de = true;
Assert.assertTrue(file.isFile());
assertThat(file).isFile();
}
if (file.getName().equals("fr.txt")) {
fr = true;
Assert.assertTrue(file.isFile());
assertThat(file).isFile();
}
if (file.getName().equals("pl.txt")) {
pl = true;
Assert.assertTrue(file.isFile());
assertThat(file).isFile();
}
}
Assert.assertTrue(continents);
Assert.assertTrue(de);
Assert.assertTrue(fr);
Assert.assertTrue(pl);
assertThat(continents).isTrue();
assertThat(de).isTrue();
assertThat(fr).isTrue();
assertThat(pl).isTrue();
}
@Test
public void unZipTraversal() throws Exception {
final Resource resource = this.resourceLoader.getResource("classpath:testzipdata/zip-malicious-traversal.zip");
final Resource resource = this.context.getResource("classpath:testzipdata/zip-malicious-traversal.zip");
final InputStream is = resource.getInputStream();
byte[] zipdata = IOUtils.toByteArray(is);
final Message<byte[]> message = MessageBuilder.withPayload(zipdata).build();
try {
input.send(message);
fail("Expected Exception");
}
catch (Exception e) {
Assert.assertThat(e, instanceOf(MessageTransformationException.class));
Assert.assertThat(e.getCause(), instanceOf(MessageHandlingException.class));
Assert.assertThat(e.getCause().getCause(), instanceOf(ZipException.class));
Assert.assertThat(e.getCause().getCause().getMessage(),
containsString("is trying to leave the target output directory"));
}
assertThatExceptionOfType(MessageTransformationException.class)
.isThrownBy(() -> input.send(message))
.withRootCauseInstanceOf(ZipException.class)
.withMessageContaining("is trying to leave the target output directory");
}
@Configuration
@ImportResource("classpath:org/springframework/integration/zip/UnZip2FileTests-context.xml")
public static class ContextConfiguration {
@Bean
Properties properties() throws IOException {
return properties;
private static void cleanupDirectory(File dir) {
for (File file: dir.listFiles()) {
if (file.isDirectory())
cleanupDirectory(file);
file.delete();
}
}
}

View File

@@ -11,6 +11,8 @@
http://www.springframework.org/schema/integration/zip https://www.springframework.org/schema/integration/zip/spring-integration-zip.xsd
http://www.springframework.org/schema/integration https://www.springframework.org/schema/integration/spring-integration.xsd">
<context:property-placeholder/>
<int:channel id="input"/>
<int-zip:zip-transformer input-channel="input" output-channel="write-file" result-type="BYTE_ARRAY">
@@ -21,5 +23,4 @@
<int-file:outbound-channel-adapter id="write-file" directory="${workDir}" auto-create-directory="true"/>
<context:property-placeholder properties-ref="properties"/>
</beans>

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015-2016 the original author or authors.
* Copyright 2015-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,126 +16,108 @@
package org.springframework.integration.zip;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.integration.file.FileHeaders;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
/**
*
* @author Gunnar Hillert
* @author Artem Bilan
* @since 1.0
*
*/
@SpringJUnitConfig
@DirtiesContext
public class Zip2FileTests {
private AnnotationConfigApplicationContext context;
@Autowired
private MessageChannel input;
private static final Properties properties = new Properties();
@TempDir
public static File workDir;
@Rule
public TemporaryFolder testFolder = new TemporaryFolder();
private File workDir;
@Before
public void setup() throws IOException {
this.workDir = testFolder.newFolder();
properties.put("workDir", workDir);
context = new AnnotationConfigApplicationContext();
context.register(ContextConfiguration.class);
context.refresh();
input = context.getBean("input", MessageChannel.class);
@BeforeAll
public static void setup() {
System.setProperty("workDir", workDir.getAbsolutePath());
}
@After
public void cleanup() {
if (context != null) {
context.close();
@BeforeEach
public void cleanUp() {
for (File file : workDir.listFiles()) {
file.delete();
}
}
@Test
public void zipStringWithDefaultFileName() throws IOException, InterruptedException {
public void zipStringWithDefaultFileName() {
final Message<String> message = MessageBuilder.withPayload("Zip me up.").build();
input.send(message);
assertThat(workDir.list()).hasSize(1);
Assert.assertTrue(this.workDir.list().length == 1);
File fileInWorkDir = workDir.listFiles()[0];
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"));
assertThat(fileInWorkDir.isFile()).isTrue();
assertThat(fileInWorkDir.getName()).contains(message.getHeaders().getId().toString());
assertThat(fileInWorkDir.getName()).endsWith(".zip");
}
@Test
public void zipStringWithExplicitFileName() throws IOException, InterruptedException {
public void zipStringWithExplicitFileName() {
input.send(MessageBuilder.withPayload("Zip me up.")
.setHeader(FileHeaders.FILENAME, "zipString.zip")
.build());
Assert.assertTrue(this.workDir.list().length == 1);
Assert.assertEquals("zipString.zip", this.workDir.listFiles()[0].getName());
assertThat(workDir.list()).hasSize(1);
assertThat(workDir.list()[0]).isEqualTo("zipString.zip");
}
@Test
public void zipBytesWithExplicitFileName() throws IOException, InterruptedException {
public void zipBytesWithExplicitFileName() {
input.send(MessageBuilder.withPayload("Zip me up.".getBytes())
.setHeader(FileHeaders.FILENAME, "zipString.zip")
.build());
Assert.assertTrue(this.workDir.list().length == 1);
Assert.assertEquals("zipString.zip", this.workDir.listFiles()[0].getName());
assertThat(workDir.list()).hasSize(1);
assertThat(workDir.list()[0]).isEqualTo("zipString.zip");
}
@Test
public void zipFile() throws IOException, InterruptedException {
final File fileToCompress = testFolder.newFile();
FileUtils.writeStringToFile(fileToCompress, "hello world");
public void zipFile() throws IOException {
File fileToCompress = File.createTempFile("test1", "tmp");
FileUtils.writeStringToFile(fileToCompress, "hello world", Charset.defaultCharset());
input.send(MessageBuilder.withPayload(fileToCompress).build());
Assert.assertTrue(this.workDir.list().length == 1);
Assert.assertEquals(fileToCompress.getName() + ".zip", this.workDir.listFiles()[0].getName());
assertThat(workDir.list()).hasSize(1);
assertThat(workDir.list()[0]).isEqualTo(fileToCompress.getName() + ".zip");
}
@Test
public void zipIterableWithMultipleStrings() throws IOException, InterruptedException {
public void zipIterableWithMultipleStrings() {
String stringToCompress1 = "String1";
String stringToCompress2 = "String2";
String stringToCompress3 = "String3";
String stringToCompress4 = "String4";
final List<String> stringsToCompress = new ArrayList<String>(4);
List<String> stringsToCompress = new ArrayList<>(4);
stringsToCompress.add(stringToCompress1);
stringsToCompress.add(stringToCompress2);
@@ -146,19 +128,19 @@ public class Zip2FileTests {
.setHeader(FileHeaders.FILENAME, "zipWith4Strings.zip")
.build());
Assert.assertTrue(this.workDir.list().length == 1);
Assert.assertEquals("zipWith4Strings.zip", this.workDir.listFiles()[0].getName());
assertThat(workDir.list()).hasSize(1);
assertThat(workDir.list()[0]).isEqualTo("zipWith4Strings.zip");
}
@Test
public void zipIterableWithDifferentTypes() throws IOException, InterruptedException {
public void zipIterableWithDifferentTypes() throws IOException {
String stringToCompress = "String1";
byte[] bytesToCompress = "String2".getBytes();
final File fileToCompress = testFolder.newFile();
FileUtils.writeStringToFile(fileToCompress, "hello world");
File fileToCompress = File.createTempFile("test2", "tmp");
FileUtils.writeStringToFile(fileToCompress, "hello world", Charset.defaultCharset());
final List<Object> objectsToCompress = new ArrayList<Object>(3);
final List<Object> objectsToCompress = new ArrayList<>(3);
objectsToCompress.add(stringToCompress);
objectsToCompress.add(bytesToCompress);
@@ -168,19 +150,8 @@ public class Zip2FileTests {
.setHeader(FileHeaders.FILENAME, "objects-to-compress.zip")
.build());
Assert.assertTrue(this.workDir.list().length == 1);
Assert.assertEquals("objects-to-compress.zip", this.workDir.listFiles()[0].getName());
}
@Configuration
@ImportResource("classpath:org/springframework/integration/zip/Zip2FileTests-context.xml")
public static class ContextConfiguration {
@Bean
Properties properties() throws IOException {
return properties;
}
assertThat(workDir.list()).hasSize(1);
assertThat(workDir.list()[0]).isEqualTo("objects-to-compress.zip");
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015-2016 the original author or authors.
* Copyright 2015-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
@@ -13,18 +13,15 @@
package org.springframework.integration.zip.config.xml;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.File;
import java.nio.charset.Charset;
import org.junit.After;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.channel.AbstractMessageChannel;
import org.springframework.integration.endpoint.EventDrivenConsumer;
import org.springframework.integration.file.DefaultFileNameGenerator;
@@ -33,32 +30,32 @@ import org.springframework.integration.test.util.TestUtils;
import org.springframework.integration.transformer.MessageTransformingHandler;
import org.springframework.integration.zip.transformer.UnZipTransformer;
import org.springframework.integration.zip.transformer.ZipResultType;
import org.springframework.util.Assert;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
/**
*
* @author Gunnar Hillert
* @since 1.0
* @author Artem Bilan
*
*/
@SpringJUnitConfig
@DirtiesContext
public class UnZipTransformerParserTests {
@Autowired
private ConfigurableApplicationContext context;
@Test
public void testUnZipTransformerParserWithDefaults() {
setUp("UnZipTransformerParserTests.xml", getClass());
EventDrivenConsumer consumer = this.context.getBean("unzipTransformerWithDefaults", EventDrivenConsumer.class);
EventDrivenConsumer consumer = this.context.getBean("unzipTransformerWithDefaults", EventDrivenConsumer.class);
final AbstractMessageChannel inputChannel = TestUtils.getPropertyValue(consumer, "inputChannel", AbstractMessageChannel.class);
assertEquals("input", inputChannel.getComponentName());
assertThat(inputChannel.getComponentName()).isEqualTo("input");
final MessageTransformingHandler handler = TestUtils.getPropertyValue(consumer, "handler", MessageTransformingHandler.class);
final AbstractMessageChannel outputChannel = TestUtils.getPropertyValue(handler, "outputChannel", AbstractMessageChannel.class);
assertEquals("output", outputChannel.getComponentName());
assertThat(TestUtils.getPropertyValue(handler, "outputChannelName")).isEqualTo("output");
final UnZipTransformer unZipTransformer = TestUtils.getPropertyValue(handler, "transformer", UnZipTransformer.class);
@@ -69,37 +66,34 @@ public class UnZipTransformerParserTests {
final Boolean deleteFiles = TestUtils.getPropertyValue(unZipTransformer, "deleteFiles", Boolean.class);
final Boolean expectSingleResult = TestUtils.getPropertyValue(unZipTransformer, "expectSingleResult", Boolean.class);
assertNotNull(charset);
assertNotNull(fileNameGenerator);
assertNotNull(zipResultType);
assertNotNull(workDirectory);
assertNotNull(deleteFiles);
assertNotNull(expectSingleResult);
assertThat(charset).isNotNull();
assertThat(fileNameGenerator).isNotNull();
assertThat(zipResultType).isNotNull();
assertThat(workDirectory).isNotNull();
assertThat(deleteFiles).isNotNull();
assertThat(expectSingleResult).isNotNull();
assertEquals(Charset.defaultCharset(), charset);
Assert.isInstanceOf(DefaultFileNameGenerator.class, fileNameGenerator);
assertEquals(ZipResultType.FILE, zipResultType);
assertEquals(new File(System.getProperty("java.io.tmpdir") + File.separator + "ziptransformer"), workDirectory);
assertTrue("WorkDirectory should exist.", workDirectory.exists());
assertTrue("WorkDirectory should be a directory.", workDirectory.isDirectory());
assertFalse("By default the 'deleteFiles' property should be false.", deleteFiles);
assertFalse("The 'expectSingleResult' property should be false.", expectSingleResult);
assertThat(charset).isEqualTo(Charset.defaultCharset());
assertThat(fileNameGenerator).isInstanceOf(DefaultFileNameGenerator.class);
assertThat(zipResultType).isEqualTo(ZipResultType.FILE);
assertThat(workDirectory)
.isEqualTo(new File(System.getProperty("java.io.tmpdir") + File.separator + "ziptransformer"));
assertThat(workDirectory.exists()).isTrue();
assertThat(workDirectory.isDirectory()).isTrue();
assertThat(deleteFiles).isFalse();
assertThat(expectSingleResult).isFalse();
}
@Test
public void testUnZipTransformerParserWithExplicitSettings() {
setUp("UnZipTransformerParserTests.xml", getClass());
EventDrivenConsumer consumer = this.context.getBean("unzipTransformer", EventDrivenConsumer.class);
EventDrivenConsumer consumer = this.context.getBean("unzipTransformer", EventDrivenConsumer.class);
final AbstractMessageChannel inputChannel = TestUtils.getPropertyValue(consumer, "inputChannel", AbstractMessageChannel.class);
assertEquals("input", inputChannel.getComponentName());
assertThat(inputChannel.getComponentName()).isEqualTo("input");
final MessageTransformingHandler handler = TestUtils.getPropertyValue(consumer, "handler", MessageTransformingHandler.class);
final AbstractMessageChannel outputChannel = TestUtils.getPropertyValue(handler, "outputChannel", AbstractMessageChannel.class);
assertEquals("output", outputChannel.getComponentName());
assertThat(TestUtils.getPropertyValue(handler, "outputChannelName")).isEqualTo("output");
final UnZipTransformer unZipTransformer = TestUtils.getPropertyValue(handler, "transformer", UnZipTransformer.class);
@@ -110,32 +104,22 @@ public class UnZipTransformerParserTests {
final Boolean deleteFiles = TestUtils.getPropertyValue(unZipTransformer, "deleteFiles", Boolean.class);
final Boolean expectSingleResult = TestUtils.getPropertyValue(unZipTransformer, "expectSingleResult", Boolean.class);
assertNotNull(charset);
assertNotNull(fileNameGenerator);
assertNotNull(zipResultType);
assertNotNull(workDirectory);
assertNotNull(deleteFiles);
assertNotNull(expectSingleResult);
assertThat(charset).isNotNull();
assertThat(fileNameGenerator).isNotNull();
assertThat(zipResultType).isNotNull();
assertThat(workDirectory).isNotNull();
assertThat(deleteFiles).isNotNull();
assertThat(expectSingleResult).isNotNull();
assertEquals(Charset.defaultCharset(), charset);
Assert.isInstanceOf(DefaultFileNameGenerator.class, fileNameGenerator);
assertEquals(ZipResultType.FILE, zipResultType);
assertEquals(new File(System.getProperty("java.io.tmpdir") + File.separator + "ziptransformer"), workDirectory);
assertTrue("WorkDirectory should exist.", workDirectory.exists());
assertTrue("WorkDirectory should be a directory.", workDirectory.isDirectory());
assertTrue("The 'deleteFiles' property should be true.", deleteFiles);
assertTrue("The 'expectSingleResult' property should be true.", expectSingleResult);
}
@After
public void tearDown(){
if(context != null){
context.close();
}
}
public void setUp(String name, Class<?> cls){
context = new ClassPathXmlApplicationContext(name, cls);
assertThat(charset).isEqualTo(Charset.defaultCharset());
assertThat(fileNameGenerator).isInstanceOf(DefaultFileNameGenerator.class);
assertThat(zipResultType).isEqualTo(ZipResultType.FILE);
assertThat(workDirectory)
.isEqualTo(new File(System.getProperty("java.io.tmpdir") + File.separator + "ziptransformer"));
assertThat(workDirectory.exists()).isTrue();
assertThat(workDirectory.isDirectory()).isTrue();
assertThat(deleteFiles).isTrue();
assertThat(expectSingleResult).isTrue();
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015-2017 the original author or authors.
* Copyright 2015-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
@@ -13,22 +13,17 @@
package org.springframework.integration.zip.config.xml;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import java.io.File;
import java.nio.charset.Charset;
import java.util.zip.Deflater;
import org.junit.After;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.channel.AbstractMessageChannel;
@@ -39,32 +34,30 @@ import org.springframework.integration.test.util.TestUtils;
import org.springframework.integration.transformer.MessageTransformingHandler;
import org.springframework.integration.zip.transformer.ZipResultType;
import org.springframework.integration.zip.transformer.ZipTransformer;
import org.springframework.util.Assert;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
/**
* @author Gunnar Hillert
* @author Artem Bilan
*
* @since 1.0
*/
@SpringJUnitConfig
@DirtiesContext
public class ZipTransformerParserTests {
@Autowired
private ConfigurableApplicationContext context;
@Test
public void testZipTransformerParserWithDefaults() {
setUp("ZipTransformerParserTests.xml", getClass());
EventDrivenConsumer consumer = this.context.getBean("zipTransformerWithDefaults", EventDrivenConsumer.class);
final AbstractMessageChannel inputChannel = TestUtils.getPropertyValue(consumer, "inputChannel", AbstractMessageChannel.class);
assertEquals("input", inputChannel.getComponentName());
assertThat(inputChannel.getComponentName()).isEqualTo("input");
final MessageTransformingHandler handler = TestUtils.getPropertyValue(consumer, "handler", MessageTransformingHandler.class);
final AbstractMessageChannel outputChannel = TestUtils.getPropertyValue(handler, "outputChannel", AbstractMessageChannel.class);
assertEquals("output", outputChannel.getComponentName());
assertThat(TestUtils.getPropertyValue(handler, "outputChannelName")).isEqualTo("output");
final ZipTransformer zipTransformer = TestUtils.getPropertyValue(handler, "transformer", ZipTransformer.class);
@@ -75,37 +68,34 @@ public class ZipTransformerParserTests {
final Integer compressionLevel = TestUtils.getPropertyValue(zipTransformer, "compressionLevel", Integer.class);
final Boolean deleteFiles = TestUtils.getPropertyValue(zipTransformer, "deleteFiles", Boolean.class);
assertNotNull(charset);
assertNotNull(fileNameGenerator);
assertNotNull(zipResultType);
assertNotNull(workDirectory);
assertNotNull(compressionLevel);
assertNotNull(deleteFiles);
assertThat(charset).isNotNull();
assertThat(fileNameGenerator).isNotNull();
assertThat(zipResultType).isNotNull();
assertThat(workDirectory).isNotNull();
assertThat(deleteFiles).isNotNull();
assertThat(compressionLevel).isNotNull();
assertEquals(Charset.defaultCharset(), charset);
Assert.isInstanceOf(DefaultFileNameGenerator.class, fileNameGenerator);
assertEquals(ZipResultType.FILE, zipResultType);
assertEquals(new File(System.getProperty("java.io.tmpdir") + File.separator + "ziptransformer"), workDirectory);
assertTrue("WorkDirectory should exist.", workDirectory.exists());
assertTrue("WorkDirectory should be a directory.", workDirectory.isDirectory());
assertEquals(Integer.valueOf(Deflater.DEFAULT_COMPRESSION), Integer.valueOf(compressionLevel));
assertFalse("By default the 'deleteFiles' property should be false.", deleteFiles);
assertThat(charset).isEqualTo(Charset.defaultCharset());
assertThat(fileNameGenerator).isInstanceOf(DefaultFileNameGenerator.class);
assertThat(zipResultType).isEqualTo(ZipResultType.FILE);
assertThat(workDirectory)
.isEqualTo(new File(System.getProperty("java.io.tmpdir") + File.separator + "ziptransformer"));
assertThat(workDirectory.exists()).isTrue();
assertThat(workDirectory.isDirectory()).isTrue();
assertThat(deleteFiles).isFalse();
assertThat(compressionLevel).isEqualTo(Deflater.DEFAULT_COMPRESSION);
}
@Test
public void testZipTransformerParserWithExplicitSettings() {
setUp("ZipTransformerParserTests.xml", getClass());
EventDrivenConsumer consumer = this.context.getBean("zipTransformer", EventDrivenConsumer.class);
final AbstractMessageChannel inputChannel = TestUtils.getPropertyValue(consumer, "inputChannel", AbstractMessageChannel.class);
assertEquals("input", inputChannel.getComponentName());
assertThat(inputChannel.getComponentName()).isEqualTo("input");
final MessageTransformingHandler handler = TestUtils.getPropertyValue(consumer, "handler", MessageTransformingHandler.class);
final AbstractMessageChannel outputChannel = TestUtils.getPropertyValue(handler, "outputChannel", AbstractMessageChannel.class);
assertEquals("output", outputChannel.getComponentName());
assertThat(TestUtils.getPropertyValue(handler, "outputChannelName")).isEqualTo("output");
final ZipTransformer zipTransformer = TestUtils.getPropertyValue(handler, "transformer", ZipTransformer.class);
@@ -116,45 +106,33 @@ public class ZipTransformerParserTests {
final Integer compressionLevel = TestUtils.getPropertyValue(zipTransformer, "compressionLevel", Integer.class);
final Boolean deleteFiles = TestUtils.getPropertyValue(zipTransformer, "deleteFiles", Boolean.class);
assertNotNull(charset);
assertNotNull(fileNameGenerator);
assertNotNull(zipResultType);
assertNotNull(workDirectory);
assertNotNull(compressionLevel);
assertNotNull(deleteFiles);
assertThat(charset).isNotNull();
assertThat(fileNameGenerator).isNotNull();
assertThat(zipResultType).isNotNull();
assertThat(workDirectory).isNotNull();
assertThat(deleteFiles).isNotNull();
assertThat(compressionLevel).isNotNull();
assertEquals(Charset.defaultCharset(), charset);
Assert.isInstanceOf(DefaultFileNameGenerator.class, fileNameGenerator);
assertEquals(ZipResultType.BYTE_ARRAY, zipResultType);
assertEquals(new File(System.getProperty("java.io.tmpdir") + File.separator + "ziptransformer"), workDirectory);
assertTrue("WorkDirectory should exist.", workDirectory.exists());
assertTrue("WorkDirectory should be a directory.", workDirectory.isDirectory());
assertEquals(Integer.valueOf(2), Integer.valueOf(compressionLevel));
assertTrue("The 'deleteFiles' property should be true.", deleteFiles);
assertThat(charset).isEqualTo(Charset.defaultCharset());
assertThat(fileNameGenerator).isInstanceOf(DefaultFileNameGenerator.class);
assertThat(zipResultType).isEqualTo(ZipResultType.BYTE_ARRAY);
assertThat(workDirectory)
.isEqualTo(new File(System.getProperty("java.io.tmpdir") + File.separator + "ziptransformer"));
assertThat(workDirectory.exists()).isTrue();
assertThat(workDirectory.isDirectory()).isTrue();
assertThat(compressionLevel).isEqualTo(2);
assertThat(deleteFiles).isTrue();
}
@Test
public void testZipTransformerParserWithIncorrectResultType() {
try {
setUp("ZipTransformerParserTestsWithIncorrectResultType.xml", getClass());
fail("Expected a BeanDefinitionParsingException to be thrown.");
}
catch (BeanCreationException e) {
assertThat(e.getMessage(), containsString("Failed to convert property value of type 'java.lang.String' " +
"to required type 'org.springframework.integration.zip.transformer.ZipResultType'"));
}
}
@After
public void tearDown() {
if (context != null) {
context.close();
}
}
public void setUp(String name, Class<?> cls) {
context = new ClassPathXmlApplicationContext(name, cls);
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() ->
new ClassPathXmlApplicationContext("ZipTransformerParserTestsWithIncorrectResultType.xml",
getClass()))
.withMessageContaining("Failed to convert property value of type 'java.lang.String' " +
"to required type 'org.springframework.integration.zip.transformer.ZipResultType'");
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2016 the original author or authors.
* Copyright 2016-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,14 +16,12 @@
package org.springframework.integration.zip.splitter;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.LinkedHashMap;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.channel.QueueChannel;
@@ -32,14 +30,15 @@ import org.springframework.integration.support.MessageBuilder;
import org.springframework.integration.zip.ZipHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
/**
* @author Andriy Kryvtsun
* @author Artem Bilan
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@SpringJUnitConfig
@DirtiesContext
public class UnZipResultSplitterTests {
private static final String DIR_1 = "dir1/";
@@ -83,14 +82,14 @@ public class UnZipResultSplitterTests {
private static void checkMessageWithHeaderValue(Message<?> message, String headerName, String headerValue,
String payload) {
assertNotNull(message);
assertThat(message).isNotNull();
checkHeaderValue(message, headerName, headerValue);
checkPayload(message, payload);
}
@Test
public void splitPreservingServiceHeaderValues() {
Message<?> inMessage = MessageBuilder.withPayload(createPayload())
.setHeader(ZipHeaders.ZIP_ENTRY_PATH, "dir")
.setHeader(FileHeaders.FILENAME, "filename")
@@ -107,25 +106,26 @@ public class UnZipResultSplitterTests {
private static void checkMessageWithServiceHeaderValues(Message<?> message, String path, String filename,
String payload) {
assertNotNull(message);
assertThat(message).isNotNull();
checkHeaderValue(message, ZipHeaders.ZIP_ENTRY_PATH, path);
checkHeaderValue(message, FileHeaders.FILENAME, filename);
checkPayload(message, payload);
}
private static Map<String, Object> createPayload() {
Map<String, Object> payload = new LinkedHashMap<String, Object>();
Map<String, Object> payload = new LinkedHashMap<>();
payload.put(DIR_1 + FILE_1, DATA_1);
payload.put(DIR_2 + FILE_2, DATA_2);
return payload;
}
private static void checkPayload(Message<?> message, String payload) {
assertEquals(payload, message.getPayload());
assertThat(message.getPayload()).isEqualTo(payload);
}
private static void checkHeaderValue(Message<?> message, String headerName, String headerValue) {
assertEquals(headerValue, message.getHeaders().get(headerName));
assertThat(message.getHeaders().get(headerName)).isEqualTo(headerValue);
}
}

View File

@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-zip="http://www.springframework.org/schema/integration/zip"
xsi:schemaLocation="http://www.springframework.org/schema/integration https://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration/zip https://www.springframework.org/schema/integration/zip/spring-integration-zip.xsd">
</beans>

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015-2019 the original author or authors.
* Copyright 2015-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,62 +16,49 @@
package org.springframework.integration.zip.transformer;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.instanceOf;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.zeroturnaround.zip.ZipException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.integration.transformer.MessageTransformationException;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandlingException;
import org.springframework.messaging.MessagingException;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
/**
*
* @author Gunnar Hillert
* @author Artem Bilan
* @author Ingo Dueppe
*
* @since 1.0
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@SpringJUnitConfig
@DirtiesContext
public class UnZipTransformerTests {
@Rule
public TemporaryFolder testFolder = new TemporaryFolder();
@TempDir
public File workDir;
@Autowired
private ResourceLoader resourceLoader;
private File workDir;
@Before
public void setup() throws IOException {
this.workDir = testFolder.newFolder();
}
@Test
public void unzipFlatFileEntryZip() throws IOException {
final Resource zipResource = this.resourceLoader.getResource("classpath:testzipdata/flatfileentry.zip");
@@ -85,13 +72,12 @@ public class UnZipTransformerTests {
final Message<?> resultMessage = unZipTransformer.transform(message);
Assert.assertNotNull(resultMessage);
assertThat(resultMessage).isNotNull();
@SuppressWarnings("unchecked")
Map<String, byte[]> unzippedData = (Map<String, byte[]>) resultMessage.getPayload();
Assert.assertNotNull(unzippedData);
Assert.assertEquals(1, unzippedData.size());
assertThat(unzippedData).isNotNull().hasSize(1);
}
@Test
@@ -107,26 +93,26 @@ public class UnZipTransformerTests {
final Message<?> resultMessage = unZipTransformer.transform(message);
Assert.assertNotNull(resultMessage);
assertThat(resultMessage).isNotNull();
@SuppressWarnings("unchecked")
Map<String, byte[]> unzippedData = (Map<String, byte[]>) resultMessage.getPayload();
Assert.assertNotNull(unzippedData);
Assert.assertEquals(1, unzippedData.size());
Assert.assertEquals("Spring Integration Rocks!", new String(unzippedData.values().iterator().next()));
assertThat(unzippedData).isNotNull().hasSize(1);
assertThat(new String(unzippedData.values().iterator().next())).isEqualTo("Spring Integration Rocks!");
}
@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));
FileOutputStream out = new FileOutputStream(inputFile);
IOUtils.copy(is, out);
is.close();
out.close();
final Message<File> message = MessageBuilder.withPayload(inputFile).build();
@@ -136,16 +122,14 @@ public class UnZipTransformerTests {
final Message<?> resultMessage = unZipTransformer.transform(message);
Assert.assertNotNull(resultMessage);
assertThat(resultMessage).isNotNull();
@SuppressWarnings("unchecked")
Map<String, byte[]> unzippedData = (Map<String, byte[]>) resultMessage.getPayload();
Assert.assertNotNull(unzippedData);
Assert.assertEquals(1, unzippedData.size());
Assert.assertTrue(inputFile.exists());
Assert.assertEquals("Spring Integration Rocks!", new String(unzippedData.values().iterator().next()));
assertThat(unzippedData).isNotNull().hasSize(1);
assertThat(inputFile).exists();
assertThat(new String(unzippedData.values().iterator().next())).isEqualTo("Spring Integration Rocks!");
}
@Test
@@ -157,6 +141,7 @@ public class UnZipTransformerTests {
FileOutputStream output = new FileOutputStream(inputFile);
IOUtils.copy(is, output);
is.close();
output.close();
final Message<File> message = MessageBuilder.withPayload(inputFile).build();
@@ -168,16 +153,14 @@ public class UnZipTransformerTests {
final Message<?> resultMessage = unZipTransformer.transform(message);
Assert.assertNotNull(resultMessage);
assertThat(resultMessage).isNotNull();
@SuppressWarnings("unchecked")
Map<String, byte[]> unzippedData = (Map<String, byte[]>) resultMessage.getPayload();
Assert.assertNotNull(unzippedData);
Assert.assertEquals(1, unzippedData.size());
Assert.assertFalse(inputFile.exists());
Assert.assertEquals("Spring Integration Rocks!", new String(unzippedData.values().iterator().next()));
assertThat(unzippedData).isNotNull().hasSize(1);
assertThat(inputFile).doesNotExist();
assertThat(new String(unzippedData.values().iterator().next())).isEqualTo("Spring Integration Rocks!");
}
@Test
@@ -193,13 +176,12 @@ public class UnZipTransformerTests {
final Message<?> resultMessage = unZipTransformer.transform(message);
Assert.assertNotNull(resultMessage);
assertThat(resultMessage).isNotNull();
@SuppressWarnings("unchecked")
Map<String, byte[]> unzippedData = (Map<String, byte[]>) resultMessage.getPayload();
Assert.assertNotNull(unzippedData);
Assert.assertEquals(5, unzippedData.size());
assertThat(unzippedData).isNotNull().hasSize(5);
}
@Test
@@ -214,23 +196,17 @@ public class UnZipTransformerTests {
unZipTransformer.setExpectSingleResult(true);
unZipTransformer.afterPropertiesSet();
try {
unZipTransformer.transform(message);
}
catch (MessagingException e) {
Assert.assertTrue(e.getMessage().contains("The UnZip operation extracted "
+ "5 result objects but expectSingleResult was 'true'."));
return;
}
Assert.fail("Expected a MessagingException to be thrown.");
assertThatExceptionOfType(MessagingException.class)
.isThrownBy(() -> unZipTransformer.transform(message))
.withMessageContaining("The UnZip operation extracted 5 result objects " +
"but expectSingleResult was 'true'.");
}
@Test
public void unzipInvalidZipFile() throws IOException {
File fileToUnzip = this.testFolder.newFile();
FileUtils.writeStringToFile(fileToUnzip, "hello world");
File fileToUnzip = File.createTempFile("test1", "tmp");
FileUtils.writeStringToFile(fileToUnzip, "hello world", Charset.defaultCharset());
UnZipTransformer unZipTransformer = new UnZipTransformer();
unZipTransformer.setZipResultType(ZipResultType.BYTE_ARRAY);
@@ -239,14 +215,9 @@ public class UnZipTransformerTests {
Message<File> message = MessageBuilder.withPayload(fileToUnzip).build();
try {
unZipTransformer.transform(message);
Assert.fail("Expected a MessagingException to be thrown.");
}
catch (MessagingException e) {
Assert.assertTrue(e.getMessage().contains(String.format("Not a zip file: '%s'.",
fileToUnzip.getAbsolutePath())));
}
assertThatExceptionOfType(MessagingException.class)
.isThrownBy(() -> unZipTransformer.transform(message))
.withMessageContaining(String.format("Not a zip file: %s", fileToUnzip.getAbsolutePath()));
}
@Test
@@ -259,16 +230,16 @@ public class UnZipTransformerTests {
final UnZipTransformer unZipTransformer = new UnZipTransformer();
unZipTransformer.afterPropertiesSet();
try {
unZipTransformer.transform(message);
}
catch (Exception e) {
Assert.assertThat(e, instanceOf(MessageTransformationException.class));
Assert.assertThat(e.getCause(), instanceOf(MessageHandlingException.class));
Assert.assertThat(e.getCause().getCause(), instanceOf(ZipException.class));
Assert.assertThat(e.getCause().getCause().getMessage(),
containsString("is trying to leave the target output directory"));
}
assertThatExceptionOfType(MessageTransformationException.class)
.isThrownBy(() -> unZipTransformer.transform(message))
.withRootCauseInstanceOf(ZipException.class)
.withMessageContaining("is trying to leave the target output directory");
}
@Configuration
public static class TestConfiguration {
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015-2016 the original author or authors.
* Copyright 2015-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,6 +16,7 @@
package org.springframework.integration.zip.transformer;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import java.io.ByteArrayInputStream;
@@ -30,10 +31,8 @@ import java.util.List;
import java.util.Set;
import java.util.UUID;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.zeroturnaround.zip.ZipUtil;
import org.springframework.beans.factory.BeanFactory;
@@ -45,16 +44,14 @@ import org.springframework.messaging.Message;
*
* @author Gunnar Hillert
* @author Artem Bilan
* @since 1.0
*
*/
public class ZipTransformerTests {
@Rule
public TemporaryFolder testFolder = new TemporaryFolder();
@TempDir
public File workDir;
@Test
public void zipString() throws IOException {
public void zipString() {
final ZipTransformer zipTransformer = new ZipTransformer();
zipTransformer.setBeanFactory(mock(BeanFactory.class));
zipTransformer.setZipResultType(ZipResultType.BYTE_ARRAY);
@@ -65,32 +62,29 @@ public class ZipTransformerTests {
final Date fileDate = new Date();
final Message<String> message = MessageBuilder.withPayload(stringToCompress)
.setHeader(ZipHeaders.ZIP_ENTRY_FILE_NAME, "test.txt")
.setHeader(ZipHeaders.ZIP_ENTRY_LAST_MODIFIED_DATE, fileDate)
.build();
.setHeader(ZipHeaders.ZIP_ENTRY_FILE_NAME, "test.txt")
.setHeader(ZipHeaders.ZIP_ENTRY_LAST_MODIFIED_DATE, fileDate)
.build();
final Message<?> result = zipTransformer.transform(message);
Object resultPayload = result.getPayload();
Assert.assertTrue("Expected payload to be an instance of byte but was "
+ resultPayload.getClass().getName(), resultPayload instanceof byte[]);
assertThat(resultPayload).isInstanceOf(byte[].class);
final File temporaryTestDirectory = testFolder.newFolder();
ZipUtil.unpack(new ByteArrayInputStream((byte[]) resultPayload), this.workDir);
ZipUtil.unpack(new ByteArrayInputStream((byte[]) resultPayload), temporaryTestDirectory);
final File unzippedEntry = new File(temporaryTestDirectory, "test.txt");
Assert.assertTrue(unzippedEntry.exists());
Assert.assertTrue(unzippedEntry.isFile());
final File unzippedEntry = new File(this.workDir, "test.txt");
assertThat(unzippedEntry).exists().isFile();
//See https://stackoverflow.com/questions/3725662/what-is-the-earliest-timestamp-value-that-is-supported-in-zip-file-format
Assert.assertTrue((fileDate.getTime() - 3000) < unzippedEntry.lastModified());
Assert.assertTrue((fileDate.getTime() + 3000) > unzippedEntry.lastModified());
assertThat(unzippedEntry.lastModified())
.isGreaterThan(fileDate.getTime() - 3000)
.isLessThan(fileDate.getTime() + 3000);
}
@Test
public void zipStringCollection() throws IOException {
public void zipStringCollection() {
final ZipTransformer zipTransformer = new ZipTransformer();
zipTransformer.setBeanFactory(mock(BeanFactory.class));
zipTransformer.setZipResultType(ZipResultType.BYTE_ARRAY);
@@ -100,7 +94,7 @@ public class ZipTransformerTests {
final String string2ToCompress = "Kenny";
final String string3ToCompress = "Butters";
final List<String> strings = new ArrayList<String>(3);
final List<String> strings = new ArrayList<>(3);
strings.add(string1ToCompress);
strings.add(string2ToCompress);
@@ -109,55 +103,46 @@ public class ZipTransformerTests {
final Date fileDate = new Date();
final Message<List<String>> message = MessageBuilder.withPayload(strings)
.setHeader(ZipHeaders.ZIP_ENTRY_FILE_NAME, "test.txt")
.setHeader(ZipHeaders.ZIP_ENTRY_LAST_MODIFIED_DATE, fileDate)
.build();
.setHeader(ZipHeaders.ZIP_ENTRY_FILE_NAME, "test.txt")
.setHeader(ZipHeaders.ZIP_ENTRY_LAST_MODIFIED_DATE, fileDate)
.build();
final Message<?> result = zipTransformer.transform(message);
Object resultPayload = result.getPayload();
Assert.assertTrue("Expected payload to be an instance of byte but was "
+ resultPayload.getClass().getName(), resultPayload instanceof byte[]);
assertThat(resultPayload).isInstanceOf(byte[].class);
final File temporaryTestDirectory = testFolder.newFolder();
ZipUtil.unpack(new ByteArrayInputStream((byte[]) resultPayload), this.workDir);
ZipUtil.unpack(new ByteArrayInputStream((byte[]) resultPayload), temporaryTestDirectory);
File[] files = this.workDir.listFiles();
File[] files = temporaryTestDirectory.listFiles();
assertThat(files).hasSizeGreaterThanOrEqualTo(3);
Assert.assertTrue(files.length >= 3);
final Set<String> expectedFileNames = new HashSet<String>();
final Set<String> expectedFileNames = new HashSet<>();
expectedFileNames.add("test_1.txt");
expectedFileNames.add("test_2.txt");
expectedFileNames.add("test_3.txt");
for (File file : files) {
if (file.getName().startsWith("test")) {
Assert.assertTrue(file.exists());
Assert.assertTrue(file.isFile());
assertThat(file).exists().isFile();
//See https://stackoverflow.com/questions/3725662/what-is-the-earliest-timestamp-value-that-is-supported-in-zip-file-format
Assert.assertTrue(String.format("%s : %s", fileDate.getTime() - 4000, file.lastModified()),
(fileDate.getTime() - 4000) < file.lastModified());
Assert.assertTrue((fileDate.getTime() + 4000) > file.lastModified());
assertThat(file.lastModified())
.isLessThan(fileDate.getTime() + 4000)
.isGreaterThan(fileDate.getTime() - 4000);
Assert.assertTrue(
String.format("File '%s' did not end with '.txt'.", file.getName()),
file.getName().endsWith(".txt"));
assertThat(file).hasExtension("txt");
Assert.assertTrue(expectedFileNames.contains(file.getName()));
assertThat(expectedFileNames).contains(file.getName());
}
}
}
@Test
public void zipStringToFile() throws IOException {
public void zipStringToFile() {
final ZipTransformer zipTransformer = new ZipTransformer();
zipTransformer.setBeanFactory(mock(BeanFactory.class));
zipTransformer.afterPropertiesSet();
@@ -166,30 +151,26 @@ public class ZipTransformerTests {
final String zipEntryFileName = "test.txt";
final Message<String> message = MessageBuilder.withPayload(stringToCompress)
.setHeader(ZipHeaders.ZIP_ENTRY_FILE_NAME, zipEntryFileName)
.build();
.setHeader(ZipHeaders.ZIP_ENTRY_FILE_NAME, zipEntryFileName)
.build();
final Message<?> result = zipTransformer.transform(message);
Assert.assertTrue("Expected payload to be an instance of file but was "
+ result.getPayload().getClass().getName(), result.getPayload() instanceof File);
assertThat(result.getPayload()).isInstanceOf(File.class);
final File payload = (File) result.getPayload();
System.out.println(payload.getAbsolutePath());
Assert.assertEquals(message.getHeaders().getId().toString() + ".msg.zip", payload.getName());
Assert.assertTrue(SpringZipUtils.isValid(payload));
assertThat(payload).hasName(message.getHeaders().getId().toString() + ".msg.zip");
assertThat((SpringZipUtils.isValid(payload))).isTrue();
final byte[] zipEntryData = ZipUtil.unpackEntry(payload, "test.txt");
Assert.assertNotNull("Entry '" + zipEntryFileName + "' was not found.", zipEntryData);
Assert.assertTrue("Hello World".equals(new String(zipEntryData)));
assertThat(zipEntryData).isNotNull();
assertThat(new String(zipEntryData)).isEqualTo("Hello World");
}
@Test
public void zipFile() throws IOException {
public void zipFile() {
ZipTransformer zipTransformer = new ZipTransformer();
zipTransformer.setBeanFactory(mock(BeanFactory.class));
@@ -198,34 +179,34 @@ public class ZipTransformerTests {
final File testFile = createTestFile(10);
Assert.assertTrue(testFile.exists());
assertThat(testFile).exists();
final Message<File> message = MessageBuilder.withPayload(testFile).build();
final Message<?> result = zipTransformer.transform(message);
Assert.assertTrue(result.getPayload() instanceof File);
assertThat(result.getPayload()).isInstanceOf(File.class);
final File payload = (File) result.getPayload();
Assert.assertEquals(testFile.getName() + ".zip", payload.getName());
Assert.assertTrue(SpringZipUtils.isValid(payload));
assertThat(payload).hasName(testFile.getName() + ".zip");
assertThat(SpringZipUtils.isValid(payload)).isTrue();
}
@Test
public void zipCollection() throws IOException {
public void zipCollection() {
final File testFile1 = createTestFile(1);
final File testFile2 = createTestFile(2);
final File testFile3 = createTestFile(3);
final File testFile4 = createTestFile(4);
Assert.assertTrue(testFile1.exists());
Assert.assertTrue(testFile2.exists());
Assert.assertTrue(testFile3.exists());
Assert.assertTrue(testFile4.exists());
assertThat(testFile1).exists();
assertThat(testFile2).exists();
assertThat(testFile3).exists();
assertThat(testFile4).exists();
final Collection<File> files = new ArrayList<File>();
final Collection<File> files = new ArrayList<>();
files.add(testFile1);
files.add(testFile2);
@@ -240,38 +221,23 @@ public class ZipTransformerTests {
final Message<?> result = zipTransformer.transform(message);
Assert.assertTrue(result.getPayload() instanceof File);
assertThat(result.getPayload()).isInstanceOf(File.class);
final File outputZipFile = (File) result.getPayload();
Assert.assertTrue(outputZipFile.exists());
Assert.assertTrue(outputZipFile.isFile());
Assert.assertTrue(outputZipFile.getName().endsWith("zip"));
Assert.assertTrue(SpringZipUtils.isValid(outputZipFile));
assertThat(outputZipFile).exists().isFile().hasExtension("zip");
assertThat(SpringZipUtils.isValid(outputZipFile)).isTrue();
}
private File createTestFile(int size) throws IOException {
private File createTestFile(int size) {
final File testFile = new File(this.workDir, "testdata" + UUID.randomUUID().toString() + ".data");
final File temporaryTestDirectory = this.testFolder.newFolder();
final File testFile = new File(temporaryTestDirectory, "testdata" + UUID.randomUUID().toString() + ".data");
RandomAccessFile f = null;
try {
f = new RandomAccessFile(testFile, "rw");
f.setLength(size * 1024 * 1024);
try (RandomAccessFile f = new RandomAccessFile(testFile, "rw")) {
f.setLength((long) size * 1024 * 1024);
}
catch (Exception e) {
System.err.println(e);
}
finally {
try {
if (f != null) {
f.close();
}
} catch (IOException e) {}
}
return testFile;
}

View File

@@ -1,8 +0,0 @@
log4j.rootCategory=WARN, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{HH:mm:ss.SSS} %-5p [%t][%c] %m%n
log4j.category.org.springframework.integration=INFO
log4j.category.org.springframework.integration.zip=INFO

View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="STDOUT" target="SYSTEM_OUT">
<PatternLayout pattern="%d %p [%t] [%c] - %m%n" />
</Console>
</Appenders>
<Loggers>
<Logger name="org.springframework.integration" level="warn"/>
<Logger name="org.springframework.integration.zip" level="warn"/>
<Root level="warn">
<AppenderRef ref="STDOUT" />
</Root>
</Loggers>
</Configuration>