Skip to content

Instantly share code, notes, and snippets.

@emoran
Created February 11, 2020 23:06
Show Gist options
  • Save emoran/d279e808a13c127d97e9493657a8ff23 to your computer and use it in GitHub Desktop.
Save emoran/d279e808a13c127d97e9493657a8ff23 to your computer and use it in GitHub Desktop.
Allows Mulesoft to unzip an InputStream file (.zip) and store the content files on a Array list
package com.moran;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import org.mule.api.MuleMessage;
import org.mule.api.transformer.TransformerException;
import org.mule.transformer.AbstractMessageTransformer;
import org.mule.util.FileUtils;
public class UnZip extends AbstractMessageTransformer{
@SuppressWarnings({ "unused", "resource" })
@Override
public Object transformMessage(MuleMessage message, String encoding) throws TransformerException {
List<InputStream> contentZipFiles = new ArrayList<InputStream>();
try {
FileInputStream zipFileStream = (FileInputStream)message.getPayload();
ZipInputStream zis = new ZipInputStream(zipFileStream);
File targetFile = File.createTempFile("file", "zip");
FileUtils.copyInputStreamToFile(zipFileStream, targetFile);
ZipFile zipFile = new ZipFile(targetFile);
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while(entries.hasMoreElements()){
ZipEntry entry = entries.nextElement();
if(!entry.isDirectory()){
InputStream inputStream = zipFile.getInputStream(entry);
contentZipFiles.add(inputStream);
}
}
zipFileStream.close();
}
catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
return contentZipFiles;
}
}
@kunamule
Copy link

Do you have the class to zip the inputstream?

@emoran
Copy link
Author

emoran commented May 27, 2020

Hi @kunamule I usually use the but I found one that might help:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class App
{
    public static void main( String[] args )
    {
    	byte[] buffer = new byte[1024];

    	try{

    		FileOutputStream fos = new FileOutputStream("C:\\MyFile.zip");
    		ZipOutputStream zos = new ZipOutputStream(fos);
    		ZipEntry ze= new ZipEntry("spy.log");
    		zos.putNextEntry(ze);
    		FileInputStream in = new FileInputStream("C:\\spy.log");

    		int len;
    		while ((len = in.read(buffer)) > 0) {
    			zos.write(buffer, 0, len);
    		}

    		in.close();
    		zos.closeEntry();

    		//remember close it
    		zos.close();

    		System.out.println("Done");

    	}catch(IOException ex){
    	   ex.printStackTrace();
    	}
    }
}

Hope that helps. Best!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment