package org.jerrymouse.gaes.mavenPlugin.install;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

import org.codehaus.plexus.util.IOUtil;

public class UnZipGae {

	File zipFile;

	File unZipDir;

	public UnZipGae(File zipFile, File unZipDir) {
		super();
		this.zipFile = zipFile;
		this.unZipDir = unZipDir;
	}

	public void unZip() {
		if (unZipDir.exists()) {
			unZipDir.delete();
		}
		unZipDir.mkdirs();
		try {
			ZipFile zip = new ZipFile(zipFile);
			Enumeration<? extends ZipEntry> enumeration = zip.entries();
			while (enumeration.hasMoreElements()) {
				ZipEntry zipEntry = (ZipEntry) enumeration.nextElement();
				System.out.println("Unzipping: " + zipEntry.getName());

				File outputFile = new File(unZipDir.getAbsolutePath() + "/"
						+ zipEntry.getName());

				if (zipEntry.isDirectory()) {
					outputFile.mkdir();
				} else {

					BufferedInputStream input = new BufferedInputStream(zip
							.getInputStream(zipEntry));
					FileOutputStream output = new FileOutputStream(outputFile);

					IOUtil.copy(input, output);
				}
			}
		} catch (ZipException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

class ZipFileUnzipDemo {
	public static void main(String[] args) {
		String zipname = "data.zip";

		try {
			ZipFile zipFile = new ZipFile(zipname);
			Enumeration enumeration = zipFile.entries();

			while (enumeration.hasMoreElements()) {
				ZipEntry zipEntry = (ZipEntry) enumeration.nextElement();

				BufferedInputStream bis = new BufferedInputStream(zipFile
						.getInputStream(zipEntry));

				int size;
				byte[] buffer = new byte[2048];

				FileOutputStream fos = new FileOutputStream(zipEntry.getName());
				BufferedOutputStream bos = new BufferedOutputStream(fos,
						buffer.length);

				while ((size = bis.read(buffer, 0, buffer.length)) != -1) {
					bos.write(buffer, 0, size);
				}

				bos.flush();
				bos.close();
				fos.close();

				bis.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
