简体   繁体   中英

Unzip a file using Apache Camel UnZippedMessageProcessor

Trying to unzip a file using Apache Camel, I tried the example given in http://camel.apache.org/zip-file-dataformat.html but I can't find UnZippedMessageProcessor class. Here's the code:

import java.util.Iterator;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.dataformat.zipfile.ZipFileDataFormat;

public class TestRoute extends RouteBuilder {

@Override
public void configure() throws Exception {

    ZipFileDataFormat zipFile = new ZipFileDataFormat();
    zipFile.setUsingIterator(true);
    from("file:src/test/resources/org/apache/camel/dataformat/zipfile/")
            .unmarshal(zipFile).split(body(Iterator.class)).streaming()
            .process(new UnZippedMessageProcessor()).end();

}
}

Anyone tried to do this or have another way to unzip a file through a Camel route?

Thank you in advance!

You can also define the route like this, you can find the ZipSplitter inside of camel-zipfile.

 from("file:src/test/resources/org/apache/camel/dataformat/zipfile?consumer.delay=1000&noop=true")
  .split(new ZipSplitter())
  .streaming().convertBodyTo(String.class).to("mock:processZipEntry")
  .end()

This would be a lot easier to figure out if the documentation wasn't so sparse. First, like someone else mentioned, the docs assume that you'll write your own Processor implementation. A simple one looks like this:

public class ZipEntryProcessor implements Processor {

    @Override
    public void process(Exchange exchange) throws Exception {
        System.out.println(exchange.getIn().getBody().toString());
    }

}

If you debug the process method, you'll see that the body of the input message is of type ZipInputStreamWrapper , which extends the Java class BufferedInputStream . That's useful information because it tells you that you could probably use Camel's built-in data transformations so that you don't have to write your own processor.

So here's how you consume a zip file and extract all of its entries to a directory on the file system:

from("file:src/test/resources/org/apache/camel/dataformat/zipfile/")
            .split(new ZipSplitter())
                .streaming()
                .to("file://C:/Temp/")
                .end();

It's actually ridiculously simple. Also, you have to make sure you understand the file component URI syntax properly too. That tripped me up the most. Here's an excellent blog post about that topic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM