/*
 * Created on 13.11.2003
 *
 * To change the template for this generated file go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
package de.kksoftware.demo.xml;

import java.util.*;
import java.io.*;
import java.util.jar.*;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;

/**
 * @author administrator
 *
 * To change the template for this generated type comment go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
public class WriteJarFile {

	public static void main(String[] args) throws Exception {
		// open an EJB jar file
		JarFile oJar = new JarFile(new File("GeneralKey.jar"));

		// create a stream to the new archive
		OutputStream oOut = new FileOutputStream(new File("MyKey.jar"));
		JarOutputStream oJarOut = new JarOutputStream(oOut);
		
		// copy all entries of the archive except the deployment descriptor
		int iSize = 0;
		byte[] oBuffer = new byte[1024];
		Enumeration oEntries = oJar.entries();
		while (oEntries.hasMoreElements()) {
			JarEntry oEntry = (JarEntry)oEntries.nextElement();
			if (!oEntry.getName().equals("META-INF/ejb-jar.xml")){
				System.out.println ("copying jar entry "+oEntry.getName()+" ...");
				oJarOut.putNextEntry(oEntry);
				InputStream oJarInStream = oJar.getInputStream(oEntry);
				while ((iSize = oJarInStream.read(oBuffer))!=-1){
					oJarOut.write(oBuffer, 0, iSize);
				}
				oJarInStream.close();
			}
		}
		// create my own descriptor
		Element oRoot = new Element("myejb-jar");
		Document oDoc = new Document(oRoot);
		Element oNode = new Element("mynode");
		oRoot.addContent(oNode);
		// write it instead of the original one
		System.out.println ("writing myejb-jar.xml");
		oJarOut.putNextEntry(new JarEntry("META-INF/myejb-jar.xml"));
		XMLOutputter oXMLOut = new XMLOutputter("    ", true);
		oXMLOut.output(oDoc, oJarOut);

		// all done
		oJarOut.close();
		oOut.close();
	}
}

