1 22 23 package com.izforge.izpack.util; 24 25 import java.io.BufferedOutputStream ; 26 import java.io.File ; 27 import java.io.IOException ; 28 import java.io.OutputStream ; 29 import java.util.jar.JarFile ; 30 import java.util.jar.Manifest ; 31 33 40 52 public class JarOutputStream extends org.apache.tools.zip.ZipOutputStream 53 { 54 private static final int JAR_MAGIC = 0xCAFE; 55 private boolean firstEntry = true; 56 private boolean preventClose = false; 57 58 66 public JarOutputStream(OutputStream out) throws IOException 67 { 68 super(out); 69 } 70 71 82 public JarOutputStream(File fout, Manifest man) throws IOException 83 { 84 super( fout ); 85 if (man == null) 86 { 87 throw new NullPointerException ("man"); 88 } 89 org.apache.tools.zip.ZipEntry e = 90 new org.apache.tools.zip.ZipEntry(JarFile.MANIFEST_NAME); 91 putNextEntry(e); 92 man.write(new BufferedOutputStream (this)); 93 closeEntry(); 94 } 95 102 public JarOutputStream(File arg0) throws IOException 103 { 104 super(arg0); 105 } 106 118 public void putNextEntry(org.apache.tools.zip.ZipEntry ze) throws IOException 119 { 120 if (firstEntry) 121 { 122 byte[] edata = ze.getExtra(); 125 if (edata != null && !hasMagic(edata)) 126 { 127 byte[] tmp = new byte[edata.length + 4]; 129 System.arraycopy(tmp, 4, edata, 0, edata.length); 130 edata = tmp; 131 } 132 else 133 { 134 edata = new byte[4]; 135 } 136 set16(edata, 0, JAR_MAGIC); set16(edata, 2, 0); ze.setExtra(edata); 139 firstEntry = false; 140 } 141 super.putNextEntry(ze); 142 } 143 144 147 public boolean isPreventClose() 148 { 149 return preventClose; 150 } 151 160 public void setPreventClose(boolean preventClose) 161 { 162 this.preventClose = preventClose; 163 } 164 165 175 public void close() throws IOException 176 { 177 if( ! isPreventClose() ) 178 super.close(); 179 } 180 181 190 public void closeAlways() throws IOException 191 { 192 setPreventClose( false ); 193 close(); 194 } 195 196 200 private static boolean hasMagic(byte[] edata) 201 { 202 203 try 204 { 205 int i = 0; 206 while (i < edata.length) 207 { 208 if (get16(edata, i) == JAR_MAGIC) 209 { 210 return true; 211 } 212 i += get16(edata, i + 2) + 4; 213 } 214 } 215 catch (ArrayIndexOutOfBoundsException e) 216 { 217 } 219 return false; 220 } 221 222 226 private static int get16(byte[] b, int off) 227 { 228 return (b[off] & 0xff) | ((b[off+1] & 0xff) << 8); 229 } 230 231 235 private static void set16(byte[] b, int off, int value) 236 { 237 b[off] = (byte)value; 238 b[off+1] = (byte)(value >> 8); 239 } 240 241 } 242 | Popular Tags |