/*
 * 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.connectors.util;

import java.io.*;
import java.util.*;
import java.util.logging.Logger;
import java.util.zip.*;

import com.sun.logging.LogDomains;


/**
 * JarResourceExtractor: JarResourceExtractor maps all resources included in a Zip or Jar file.
 * Additionaly, it provides a method to extract one as a blob.
 * 
 * @author Sivakumar Thyagarajan
 */

public final class JarResourceExtractor {
    static Logger _logger = LogDomains.getLogger(LogDomains.RSR_LOGGER);

    //resourceName as String Vs contents as byte[]
    private Hashtable htJarContents = new Hashtable();
    
    /**
     * creates a JarResourceExtractor. It extracts all resources from a Jar into an
     * internal hashtable, keyed by resource names.
     * 
     * @param jarFileName
     *            a jar or zip file
     */
    public JarResourceExtractor(String jarFileName) {
        init(jarFileName);
    }
    
    /**
     * Extracts a jar resource as a blob.
     * 
     * @param name
     *            a resource name.
     */
    public byte[] getResource(String name) {
        _logger.finer("getResource: " + name);
        return (byte[]) htJarContents.get(name);
    }
    
    /** initializes internal hash tables with Jar file resources. */
    private void init(String jarFileName) {
        try {
            //extract resources and put them into the hashtable.
            FileInputStream fis = new FileInputStream(jarFileName);
            BufferedInputStream bis = new BufferedInputStream(fis);
            ZipInputStream zis = new ZipInputStream(bis);            
            extractResources(zis);
        } catch (Exception ex){
            ex.printStackTrace();
        }
        
    }
    
    /**
     * @throws FileNotFoundException
     * @throws IOException
     */
    private void extractResources(ZipInputStream zis) throws FileNotFoundException, IOException {
        ZipEntry ze = null;
        while ((ze = zis.getNextEntry()) != null) {
            _logger.finer("ExtractResources : " + ze.getName());
            extractZipEntryContents(ze, zis);
        }
    }
    
    /**
     * @param zis
     * @throws IOException
     */
    private void extractZipEntryContents(ZipEntry ze, ZipInputStream zis) throws IOException {
            if (ze.isDirectory()) {
                return;
            }
            
            _logger.finer("ze.getName()=" + ze.getName() + ","
                        + "getSize()=" + ze.getSize());

            byte[] b = getZipEntryContents(ze,zis);
            //If it is a jar go RECURSIVE !!
            if(ze.getName().trim().endsWith(".jar")){
                _logger.finer("JAR - going into it !!");
                BufferedInputStream bis = new BufferedInputStream( (new ByteArrayInputStream(b)));
                extractResources(new ZipInputStream(bis));
            } else {
                //add to internal resource hashtable
                htJarContents.put(ze.getName(), b );
                if (ze.getName().trim().endsWith("class")){ 
                    _logger.finer("CLASS added " + ze.getName());
                }
                _logger.finer(ze.getName() + ",size="
                        + b.length + ",csize=" + ze.getCompressedSize());
            }
    }
    
    private byte[] getZipEntryContents(ZipEntry ze, ZipInputStream zis) throws IOException{
        int size = (int) ze.getSize();
        
        byte[] b = null;
        // -1 means unknown size.
        if (size != -1) {
            //got a proper size, read 'size' bytes
            b = new byte[(int) size];
            
            int rb = 0;
            int chunk = 0;
            
            while (((int) size - rb) > 0) {
                chunk = zis.read(b, rb, (int) size - rb);
                if (chunk == -1) {
                    break;
                }
                rb += chunk;
            }
        } else {
            //size of entry unknown .. keep on reading till we hit a -1
            ArrayList al = new ArrayList();
            int c = 0;
            while( (c = zis.read()) != -1) {
                al.add(new Byte((byte)c));
            }
            Byte[] btArr = (Byte[])al.toArray(new Byte[]{});
            b = new byte[btArr.length];
            _logger.finer("ByteArray length" + btArr.length);
            for (int i = 0; i < btArr.length; i++) {
                b[i] = btArr[i].byteValue();
            }
        }
        
        return b;
    }
}
