KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > util > zip > ZipWriter


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
24 /* Byron Nevins, April 2000
25  * ZipFile -- A utility class for exploding jar files that contain EJB(s). Used *only* in this package by the EJBImporter class
26  */

27
28 package com.sun.enterprise.util.zip;
29
30 import java.io.*;
31 import java.util.zip.*;
32
33 import com.sun.enterprise.util.diagnostics.Reporter;
34 import com.sun.enterprise.util.diagnostics.StackTrace;
35 import com.sun.enterprise.util.io.FileListerRelative;
36
37 public class ZipWriter
38 {
39     public ZipWriter(String JavaDoc zipFilename, String JavaDoc dirName) throws ZipFileException
40     {
41         init(zipFilename, dirName);
42         createItemList(null);
43     }
44
45     ///////////////////////////////////////////////////////////////////////////////////////////////////////
46

47     public ZipWriter(String JavaDoc zipFilename, String JavaDoc dirName, ZipItem[] theItems) throws ZipFileException
48     {
49         items = theItems;
50         init(zipFilename, dirName);
51     }
52
53     ///////////////////////////////////////////////////////////////////////////////////////////////////////
54

55     public ZipWriter(String JavaDoc zipFilename, String JavaDoc dirName, String JavaDoc[] fileList) throws ZipFileException
56     {
57         init(zipFilename, dirName);
58         createItemList(fileList);
59     }
60
61     ///////////////////////////////////////////////////////////////////////////////////////////////////////
62

63     public ZipWriter(OutputStream outStream, String JavaDoc dirName, String JavaDoc[] fileList) throws ZipFileException
64     {
65         init(outStream, dirName);
66         createItemList(fileList);
67     }
68
69     //////////////////////////////////////////////////////////////////////////////////////////////////////////////
70

71     private void init(String JavaDoc outFileName, String JavaDoc dirName) throws ZipFileException
72     {
73         try
74         {
75             init(new FileOutputStream(outFileName), dirName);
76         }
77         catch(Exception JavaDoc e)
78         {
79             throw new ZipFileException(e);
80         }
81     }
82
83     //////////////////////////////////////////////////////////////////////////////////////////////////////////////
84

85     private void init(OutputStream outStream, String JavaDoc dirName) throws ZipFileException
86     {
87         try
88         {
89             // note -- these asserts will be caught & repackaged as a ZipFileException
90
Reporter.insist(dirName);
91             
92             //make sure it's really a directory
93
File f = new File(dirName);
94             Reporter.insist(f.exists(), "directory (" + dirName + ") doesn't exist");
95             Reporter.insist(f.isDirectory());
96             
97             // change the filename to be full-path & UNIX style
98
try
99             {
100                 dirName = f.getCanonicalPath();
101             }
102             catch(IOException e)
103             {
104                 Reporter.warn("Couldn't getCanonicalPath() for " + dirName);
105             }
106             
107             dirName = dirName.replace('\\', '/'); // all UNIX-style filenames...
108

109             
110             // we need the dirname to end in a '/'
111
if(!dirName.endsWith("/"))
112                 dirName += "/";
113
114             
115             this.dirName = dirName;
116             zipStream = new ZipOutputStream(outStream);
117         }
118         catch(Throwable JavaDoc t)
119         {
120             throw new ZipFileException(t);
121         }
122     }
123
124     //////////////////////////////////////////////////////////////////////////////////////////////////////////////
125

126     /**
127      * Does not throw an exception when there is a duplicate zip entry.
128      *
129      * @throws ZipFileException if an error while creating the archive
130      */

131     public void safeWrite() throws ZipFileException
132     {
133         try
134         {
135             for(int i = 0; i < items.length; i++)
136             {
137                 try
138                 {
139                     addEntry(items[i]);
140                 }
141                 catch (ZipException e)
142                 {
143                     // ignore - duplicate zip entry
144
}
145             }
146             
147             zipStream.close();
148         }
149         catch(ZipFileException z)
150         {
151             Reporter.critical(new StackTrace(z));
152             throw z;
153         }
154         catch(Exception JavaDoc e)
155         {
156             Reporter.critical(new StackTrace(e));
157             throw new ZipFileException(e);
158         }
159     }
160
161     //////////////////////////////////////////////////////////////////////////////////////////////////////////////
162

163     public void write() throws ZipFileException
164     {
165         try
166         {
167             for(int i = 0; i < items.length; i++)
168             {
169                 addEntry(items[i]);
170             }
171             
172             zipStream.close();
173         }
174         catch(ZipFileException z)
175         {
176             Reporter.critical(new StackTrace(z));
177             throw z;
178         }
179         catch(Exception JavaDoc e)
180         {
181             Reporter.critical(new StackTrace(e));
182             throw new ZipFileException(e);
183         }
184     }
185
186     //////////////////////////////////////////////////////////////////////////////////////////////////////////////
187

188     private void addEntry(ZipItem item) throws ZipFileException, IOException
189     {
190         int totalBytes = 0;
191         FileInputStream in = new FileInputStream(item.file);
192         ZipEntry ze = new ZipEntry(item.name);
193         
194         zipStream.putNextEntry(ze);
195
196         for(int numBytes = in.read(buffer); numBytes > 0; numBytes = in.read(buffer))
197         {
198             zipStream.write(buffer, 0, numBytes);
199             totalBytes += numBytes;
200         }
201         
202         /* Bug 4753245
203          * WBN 11/22/02
204          * The in.close() method was missing -- causing problems when trying to delete this file in
205          * other code -- at least until the garbage collector gets around to closing it.
206          * Normally I wouldn't put this inside a try/catch -- an error ought to be returned,
207          * but this is a special low-risk-toleration time. Adding the try/catch is safer. The
208          * code will behave exactly like before if an Exception is thrown. It can't possibly hurt anything
209          * to add the close()
210          */

211         try // note: feel free to remove this try sometime in the future!
212
{
213             in.close();
214         }
215         catch(Exception JavaDoc e)
216         {
217             // ignore it
218
Reporter.warn("Couldn't close the FileInputStream for the file: " + item.file);
219         }
220         
221         zipStream.closeEntry();
222         Reporter.verbose("Wrote " + item.name + " to Zip File. Wrote " + totalBytes + " bytes.");
223     }
224
225     //////////////////////////////////////////////////////////////////////////////////////////////////////////////
226

227     private void createItemList(String JavaDoc[] files) throws ZipFileException
228     {
229         try
230         {
231             if(files == null)
232             {
233                 FileListerRelative lister = new FileListerRelative(new File(dirName));
234                 files = lister.getFiles();
235             }
236
237             if(files.length <= 0)
238                 throw new ZipFileException("No files to add!");
239
240             items = new ZipItem[files.length];
241
242             for(int i = 0; i < files.length; i++)
243             {
244                 File f = new File(dirName + files[i]);
245                 items[i] = new ZipItem(f, files[i].replace('\\', '/')); // just in case...
246
}
247         }
248         catch(Throwable JavaDoc t)
249         {
250             throw new ZipFileException(t);
251         }
252             
253     }
254
255     //////////////////////////////////////////////////////////////////////////////////////////////////////////////
256

257     String JavaDoc getDirName()
258     {
259         return dirName;
260     }
261         
262     //////////////////////////////////////////////////////////////////////////////////////////////////////////////
263

264     private static void usage()
265     {
266         System.out.println("usage: java com.elf.util.zip.ZipWriter zip-filename directory-name");
267         System.exit(1);
268     }
269         
270     //////////////////////////////////////////////////////////////////////////////////////////////////////////////
271

272     public static void main(String JavaDoc[] args)
273     {
274         Reporter.setSeverityLevel(0);
275         
276         if(args == null || args.length != 2)
277             usage();
278         
279         try
280         {
281             ZipWriter zw = new ZipWriter(args[0], args[1]);
282             zw.write();
283             Reporter.verbose("" + zw);
284         }
285         catch(ZipFileException e)
286         {
287             Reporter.verbose("ZipFileException: " + e);
288             System.exit(0);
289         }
290     }
291
292     /////////////////////////////////////////////////////////////////////////////////////////
293

294     //private String zipFilename = null;
295
private String JavaDoc dirName = null;
296     private ZipOutputStream zipStream = null;
297     private byte[] buffer = new byte[16384];
298     private ZipItem[] items = null;
299 }
300
Popular Tags