/*
 * The contents of this file are subject to the terms 
 * of the Common Development and Distribution License 
 * (the License).  You may not use this file except in
 * compliance with the License.
 * 
 * You can obtain a copy of the license at 
 * https://glassfish.dev.java.net/public/CDDLv1.0.html or
 * glassfish/bootstrap/legal/CDDLv1.0.txt.
 * See the License for the specific language governing 
 * permissions and limitations under the License.
 * 
 * When distributing Covered Code, include this CDDL 
 * Header Notice in each file and include the License file 
 * at glassfish/bootstrap/legal/CDDLv1.0.txt.  
 * If applicable, add the following below the CDDL Header, 
 * with the fields enclosed by brackets [] replaced by
 * you own identifying information: 
 * "Portions Copyrighted [year] [name of copyright owner]"
 * 
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 */
package com.sun.enterprise.tools.admingui.util;

import java.util.jar.JarInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.io.IOException;
import java.io.OutputStream;

public class JarExtract {
    
    public static void extract(String fileName, String dir) throws IOException {
        if(fileName == null || dir == null ) {
            //localize this message
            throw new IOException("extract method: dir, or fileName is null");
        }
        File f = new File(fileName);
        if(!f.exists()) {
            //localize this message.
            throw new IOException(fileName + ": file not found");
        }
        FileInputStream fin = new FileInputStream(f);
        JarInputStream jin = new JarInputStream(fin);
         ZipEntry e;
        
         while((e =jin.getNextEntry()) != null ) {    
            extract(jin, e, dir);
        }
        
    }
    
    private static void extract(JarInputStream jin, ZipEntry e, String dir) 
        throws IOException {
        
        File f = new File(dir + File.separatorChar + e.getName().replace('/', File.separatorChar));
	if (e.isDirectory()) {
	    if (!f.exists() && !f.mkdirs() || !f.isDirectory()) {
                //localize this mesg.
		throw new IOException(f + ": could not create directory");
	    }
	} else {
	    if (f.getParent() != null) {
		File d = new File(f.getParent());
		if (!d.exists() && !d.mkdirs() || !d.isDirectory()) {
                    //localize this mesg.
		    throw new IOException(d + ": could not create directory");
		}
	    }
	    OutputStream os = new FileOutputStream(f);
	    byte[] b = new byte[512];
	    int len;
	    while ((len = jin.read(b, 0, b.length)) != -1) {
		os.write(b, 0, len);
	    }
	    jin.closeEntry();
	    os.close();
	}
    
    }
    
}
