KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > util > JarAccess


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23 package com.sun.enterprise.util;
24
25 import java.io.*;
26 import java.util.*;
27 import java.util.zip.*;
28
29 //START OF IASRI 4660742
30
import java.util.logging.*;
31 import com.sun.logging.*;
32 //END OF IASRI 4660742
33

34
35 /**
36  * This class implements a simple utility for creating and extracting JAR
37  * (Java Archive) files. The JAR format is based on the ZIP file
38  * format, with optional meta-information stored in a MANIFEST entry.
39  * To create an EJB JAR, use
40  * JarAccess.create(jarfile, baseDir, ejbNames, files).
41  *
42  * It borrows from the BeanBox and JDK code.
43  */

44
45 public class JarAccess {
46     // START OF IASRI 4660742
47
static Logger _logger=LogDomains.getLogger(LogDomains.UTIL_LOGGER);
48     // END OF IASRI 4660742
49

50     public static final String JavaDoc MANIFEST = "META-INF/MANIFEST.MF";
51     static final char SEPARATOR = File.separatorChar;
52
53     private File jarName; // the (relative to WD) name of the JarFile
54
private File dirName; // the (relative to WD) name of the base directory
55
private String JavaDoc beanName; // the (relative to base) beanFileName
56
private String JavaDoc[] fileNames; // all (relative to base) file names
57

58     private static LocalStringManagerImpl localStrings =
59     new LocalStringManagerImpl(JarAccess.class);
60
61
62     /**
63      * Create a new JAR file;
64      * Given a base directory, ejb names, and a set of files names,
65      * these two relative to the base directory
66      *
67      * if baseDir is null, it means WD
68      * if beanFIle is null, it means generate no MANIFEST
69      *
70      * Generates a *non-signed* MANIFEST
71      */

72     public static void create(OutputStream out,
73                   File baseDir,
74                   String JavaDoc[] ejbNames,
75                   String JavaDoc[] files)
76     throws IOException
77     {
78     int start = 0;
79     if (ejbNames != null) {
80         start = 1;
81     }
82     JarEntrySource[] data = new JarEntrySource[files.length + start];
83     if (ejbNames != null) {
84         data[0] = makeManifestEntry(ejbNames);
85     }
86     for (int i = 0; i<files.length; i++) {
87         data[i+start] = new JarEntrySource(entryName(files[i]),
88                            new File(baseDir, files[i]));
89     }
90     create(out, data);
91     }
92
93     /**
94      * An InputStream with the data about the Manifest
95      */

96     public static JarEntrySource makeManifestEntry(String JavaDoc[] ejbNames) {
97     StringBuffer JavaDoc s = new StringBuffer JavaDoc("Manifest-Version: 1.0\n");
98     s.append("\n");
99     for ( int i=0; i<ejbNames.length; i++ ) {
100         s.append("Name: "+ejbNames[i]+"\n");
101         s.append("Enterprise-Bean: True\n");
102         s.append("\n");
103     }
104     return new JarEntrySource(MANIFEST,
105         new ByteArrayInputStream(s.toString().getBytes()));
106     }
107
108     /**
109      * Creates a new ZIP file with a bunch of files
110      */

111     public static void create(OutputStream out,
112                String JavaDoc[] files) throws IOException {
113     ZipOutputStream zos = new ZipOutputStream(out);
114     for (int i = 0; i < files.length; i++) {
115         addEntry(zos, new JarEntrySource(new File(files[i])));
116     }
117     zos.close();
118     }
119
120       /**
121      * Creates a new ZIP file with a bunch of entries
122      */

123     public static void create(OutputStream out,
124                JarEntrySource[] entries) throws IOException {
125     ZipOutputStream zos = new ZipOutputStream(out);
126     for (int i = 0; i < entries.length; i++) {
127         try {
128             addEntry(zos, entries[i]);
129         } catch ( Exception JavaDoc ex ) {
130         /** IASRI 4660742
131     ex.printStackTrace();
132     **/

133         // START OF IASRI 4660742
134
_logger.log(Level.SEVERE,"enterprise_util.excep_jaraccess_create",ex);
135         // END OF IASRI 4660742
136
throw new IOException("Invalid JAR entry: "
137                     +entries[i].getName());
138         }
139     }
140     zos.close();
141     }
142
143     private static String JavaDoc entryName(String JavaDoc name) {
144     name = name.replace(File.separatorChar, '/');
145     if (name.startsWith("/")) {
146         name = name.substring(1);
147     } else if (name.startsWith("./")) {
148         name = name.substring(2);
149     }
150     return name;
151     }
152
153     /*
154      * Adds a new file entry to the ZIP output stream.
155      */

156     static void addEntry(ZipOutputStream zos,
157              JarEntrySource source) throws IOException {
158     String JavaDoc name = source.getName();
159     if (name.equals("") || name.equals(".")) {
160         return;
161     }
162
163     // long size = source.getLength();
164

165     ZipEntry e = new ZipEntry(name);
166
167     e.setTime(source.getTime());
168     boolean markOnly = source.isMarkOnly();
169
170     if (markOnly) {
171         e.setMethod(ZipEntry.STORED);
172         e.setSize(0);
173         e.setCrc(0);
174     }
175     zos.putNextEntry(e);
176     if (! markOnly) {
177         byte[] buf = new byte[1024];
178         int len = 0;
179         InputStream is = new BufferedInputStream(source.getInputStream());
180
181         while (len != -1) {
182         try{
183             len = is.read(buf, 0, buf.length);
184         }catch(EOFException eof){
185             break;
186         }
187
188         if(len != -1)
189             zos.write(buf, 0, len);
190         }
191
192         is.close();
193     }
194     zos.closeEntry();
195     }
196
197     /*
198      * Extracts specified entries from JAR file.
199      */

200     public static void extract(InputStream in,
201                    String JavaDoc files[]) throws IOException {
202     ZipInputStream zis = new ZipInputStream(in);
203     ZipEntry e;
204     while ((e = zis.getNextEntry()) != null) {
205         if (files == null) {
206         extractFile(zis, e);
207         } else {
208         String JavaDoc name = e.getName().replace('/', File.separatorChar);
209         for (int i = 0; i < files.length; i++) {
210             if (name.startsWith(files[i])) {
211             extractFile(zis, e);
212             break;
213             }
214         }
215         }
216     }
217     }
218
219     /*
220      * Extracts next entry from JAR file, creating directories as needed.
221      */

222     private static void extractFile(ZipInputStream zis, ZipEntry e)
223     throws IOException
224     {
225     File f = new File(e.getName().replace('/', File.separatorChar));
226     if (e.isDirectory()) {
227         if (!f.exists() && !f.mkdirs() || !f.isDirectory()) {
228         throw new IOException(f + ": could not create directory");
229         }
230     } else {
231         if (f.getParent() != null) {
232         File d = new File(f.getParent());
233         if (!d.exists() && !d.mkdirs() || !d.isDirectory()) {
234             throw new IOException(d + ": could not create directory");
235         }
236         }
237         OutputStream os = new FileOutputStream(f);
238         byte[] b = new byte[512];
239         int len;
240         while ((len = zis.read(b, 0, b.length)) != -1) {
241         os.write(b, 0, len);
242         }
243         zis.closeEntry();
244         os.close();
245     }
246     }
247
248
249     /*
250      * Extracts specified entries from JAR file into the given directory.
251      */

252     public static Vector extract(InputStream in,
253                    String JavaDoc files[],
254                    String JavaDoc directory) throws IOException {
255     Vector extractedFiles = new Vector();
256     ZipInputStream zis = new ZipInputStream(in);
257     ZipEntry e;
258     while ((e = zis.getNextEntry()) != null) {
259         if (files == null) {
260         File extractedFile = extractFile(zis, e, directory);
261         extractedFiles.addElement(extractedFile);
262         } else {
263         String JavaDoc name = e.getName().replace('/', File.separatorChar);
264         for (int i = 0; i < files.length; i++) {
265             if (name.startsWith(files[i])) {
266             File extractedFile = extractFile(zis, e, directory);
267             extractedFiles.addElement(extractedFile);
268             break;
269             }
270         }
271         }
272     }
273     return extractedFiles;
274     }
275
276
277     /*
278      * Extracts next entry from JAR file into the specified directory,
279      * creating intermediate directories as needed.
280      */

281     private static File extractFile(ZipInputStream zis, ZipEntry e, String JavaDoc dir)
282     throws IOException
283     {
284     File f = new File(dir+File.separatorChar+e.getName().replace('/', File.separatorChar));
285     if (e.isDirectory()) {
286         if (!f.exists() && !f.mkdirs() || !f.isDirectory()) {
287         throw new IOException(f + ": could not create directory");
288         }
289     } else {
290         if (f.getParent() != null) {
291         File d = new File(f.getParent());
292         if (!d.exists() && !d.mkdirs() || !d.isDirectory()) {
293             throw new IOException(d + ": could not create directory");
294         }
295         }
296         OutputStream os = new FileOutputStream(f);
297         byte[] b = new byte[512];
298         int len;
299         while ((len = zis.read(b, 0, b.length)) != -1) {
300         os.write(b, 0, len);
301         }
302         zis.closeEntry();
303         os.close();
304     }
305     return f;
306     }
307
308     /*
309      * Lists contents of JAR file.
310      */

311     private static void list(InputStream in, String JavaDoc files[])
312     throws IOException
313     {
314     ZipInputStream zis = new ZipInputStream(in);
315     ZipEntry e;
316     while ((e = zis.getNextEntry()) != null) {
317         String JavaDoc name = e.getName().replace('/', File.separatorChar);
318         /*
319          * In the case of a compressed (deflated) entry, the entry size
320          * is stored immediately following the entry data and cannot be
321          * determined until the entry is fully read. Therefore, we close
322          * the entry first before printing out its attributes.
323          */

324         zis.closeEntry();
325         if (files == null) {
326         printEntry(e);
327         } else {
328         for (int i = 0; i < files.length; i++) {
329             if (name.startsWith(files[i])) {
330             printEntry(e);
331             break;
332             }
333         }
334         }
335     }
336     }
337
338     /*
339      * Prints entry information.
340      */

341     private static void printEntry(ZipEntry e) throws IOException {
342     output(e.getName());
343     }
344
345     /**
346      * Parse the arguments
347      */

348     private boolean parseArgs(String JavaDoc args[]) {
349     int l = args.length;
350     int i;
351     for (i = 0; i<l; i++) {
352         if (args[i].equals("-bean")) {
353         if (i+1 >= l) {
354             error(localStrings.getLocalString("jaraccess.bean.option",
355                                                       ""));
356             return false;
357         }
358         beanName = args[i+1];
359         i += 1;
360         } else if (args[i].equals("-dir")) {
361         if (i+1 >= l) {
362             error(localStrings.getLocalString("jaraccess.dir.option",
363                                                       ""));
364             return false;
365         }
366         dirName = new File(args[i+1]);
367         i += 1;
368         } else {
369         break;
370         }
371     }
372     if (i+1 >= l) {
373         error(localStrings.getLocalString("jaraccess.num.args", ""));
374         return false;
375     }
376     jarName = new File(args[i]);
377     i += 1;
378     fileNames = new String JavaDoc[l-i];
379     for (int j=0; j<l-i ; j++) {
380         fileNames[j] = args[j+i];
381     }
382     // printArgs();
383
return true;
384     }
385
386     /**
387      * Print the argumens read, for debugging
388      */

389     private void printArgs() {
390     /** IASRI 4660742
391     System.err.println("jarName: "+jarName);
392     System.err.println("dirName: "+dirName);
393     System.err.println("beanName: "+beanName);
394     System.err.println("fileNames: "+fileNames);
395     **/

396     // START OF IASRI 4660742
397
if (_logger.isLoggable(Level.FINE)) {
398         _logger.log(Level.FINE,"jarName: "+jarName);
399         _logger.log(Level.FINE,"dirName: "+dirName);
400         _logger.log(Level.FINE,"beanName: "+beanName);
401         _logger.log(Level.FINE,"fileNames: "+fileNames);
402   }
403     // END OF IASRI 4660742
404
if (fileNames != null) {
405         for (int i=0; i<fileNames.length; i++) {
406         /** IASRI 4660742
407         System.err.println("fileNames["+i+"]: "+fileNames[i]);
408         **/

409         // START OF IASRI 4660742
410
if (_logger.isLoggable(Level.FINE)) {
411             _logger.log(Level.FINE,"fileNames["+i+"]: "+fileNames[i]);
412     }
413         // END OF IASRI 4660742
414
}
415     }
416     }
417
418     /**
419      * Print an output message
420      */

421     protected static void output(String JavaDoc s) {
422     /** IASRI 4660742
423     System.err.println(s);
424     **/

425     // START OF IASRI 4660742
426
_logger.log(Level.FINE,s);
427     // END OF IASRI 4660742
428
}
429
430     /**
431      * Print an error message
432      */

433     protected static void error(String JavaDoc s) {
434     /** IASRI 4660742
435     System.err.println(s);
436     */

437     // START OF IASRI 4660742
438
_logger.log(Level.SEVERE,"enterprise_util.some_error",s);
439     // END OF IASRI 4660742
440
}
441
442 }
443
Popular Tags