/* JFox, the OpenSource J2EE Application Server
 *
 * Copyright (C) 2002 huihoo.com
 * Distributable under GNU LGPL license
 * See the GNU Lesser General Public License for more details.
 */

package org.jfox.ejb.meta;

import java.io.InputStream;
import java.net.URL;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 * @author <a href="mailto:young_yy@hotmail.com">Young Yang</a>
 */

public class EjbJarDocumentBuilder {

  private static DocumentBuilder db = null;

  static {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {
      dbf.setValidating(false);
      db = dbf.newDocumentBuilder();
      db.setEntityResolver(new EJBEntityResolver());
    }
    catch(ParserConfigurationException e){
      throw new RuntimeException(e);
    }
  }

  /**
   * get the xml root document of ejb-jar.xml in the ejb jar file url
   *
   * @param url the ejb jar file url
   * @return
   * @throws EJBDescriptionException
   */
  public static Element getEjbJarDocument(URL url) throws EJBDescriptionException {
    try {
      JarFile jarFile = new JarFile(url.getFile());
      ZipEntry ejbJarEntry = jarFile.getEntry("META-INF/ejb-jar.xml");
      // if not exist ejb-jar.xml,ignore this jar
      if(ejbJarEntry == null) return null;
      InputStream is = jarFile.getInputStream(ejbJarEntry);
      Document doc = db.parse(is);
      return doc.getDocumentElement();
    }
    catch(Exception e){
      e.printStackTrace();
      throw new EJBDescriptionException(e);
    }
  }

  public static void main(String[] args) {
    System.out.println(EjbJarDocumentBuilder.class.getPackage().getName());
  }
}