/*
*Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
*WSO2 Inc. licenses this file to you 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
*
*http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing,
*software distributed under the License is distributed on an
*"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
*KIND, either express or implied. See the License for the
*specific language governing permissions and limitations
*under the License.
*/
package org.wso2.carbon.automation.extensions.servers.utils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class ArchiveExtractor {
private static final Log log = LogFactory.getLog(ArchiveExtractor.class);
public void extractFile(String sourceFilePath, String extractedDir) throws IOException {
FileOutputStream fileoutputstream = null;
String fileDestination = extractedDir + File.separator;
byte[] buf = new byte[1024];
ZipInputStream zipinputstream = null;
ZipEntry zipentry;
try {
zipinputstream = new ZipInputStream(new FileInputStream(sourceFilePath));
zipentry = zipinputstream.getNextEntry();
while (zipentry != null) {
//for each entry to be extracted
String entryName = fileDestination + zipentry.getName();
entryName = entryName.replace('/', File.separatorChar);
entryName = entryName.replace('\\', File.separatorChar);
int n;
File newFile = new File(entryName);
boolean fileCreated = false;
if (zipentry.isDirectory()) {
if (!newFile.exists()) {
fileCreated = newFile.mkdirs();
}
zipentry = zipinputstream.getNextEntry();
continue;
} else {
File resourceFile =
new File(entryName.substring(0, entryName.lastIndexOf(File.separator)));
if (!resourceFile.exists()) {
if (!resourceFile.mkdirs()) {
break;
}
}
}
fileoutputstream = new FileOutputStream(entryName);
while ((n = zipinputstream.read(buf, 0, 1024)) > -1) {
fileoutputstream.write(buf, 0, n);
}
fileoutputstream.close();
zipinputstream.closeEntry();
zipentry = zipinputstream.getNextEntry();
}
zipinputstream.close();
} catch (IOException e) {
log.error("Error on archive extraction ", e);
throw new IOException("Error on archive extraction ", e);
} finally {
if (fileoutputstream != null) {
fileoutputstream.close();
}
if (zipinputstream != null) {
zipinputstream.close();
}
}
}
}