KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > config > backup > util > 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.config.backup.util;
29
30 import java.io.*;
31 import java.util.*;
32 import java.util.zip.*;
33
34
35 public class ZipWriter
36 {
37     public ZipWriter(String JavaDoc zipFilename, String JavaDoc dirName) throws ZipFileException
38     {
39         init(zipFilename, dirName);
40         createItemList(null);
41     }
42
43     ///////////////////////////////////////////////////////////////////////////////////////////////////////
44

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

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

61     public ZipWriter(OutputStream outStream, String JavaDoc dirName, String JavaDoc[] fileList) throws ZipFileException
62     {
63         init(outStream, dirName);
64         createItemList(fileList);
65     }
66
67     /**
68      * Exclude any files that are under these directories.
69      * E.g. suppose you have C:/temp/x1, C:/temp/x2 and C:/temp/x3
70      * and the root is set to c:temp. Thhen to exclude the contents of the second
71      * 2 dirs you would send in a String array with "x2" and "x3"
72      * @param dirs an array of top-level directory names
73      */

74
75     public void excludeDirs(String JavaDoc[] dirs)
76     {
77         // make sure the names all end with "/"
78
for(int i = 0; i < dirs.length; i++)
79         {
80             if(!dirs[i].endsWith("/"))
81                 dirs[i] += "/";
82         }
83         
84         // copy all the items we will retain into list
85
List list = new ArrayList(items.length);
86         
87         for(int i = 0; i < items.length; i++)
88         {
89             for(int j = 0; j < dirs.length; j++)
90             {
91                 if(!items[i].name.startsWith(dirs[j]))
92                     list.add(items[i]);
93                 //else
94
//System.out.println("REMOVING: " + items[i].name);
95
}
96         }
97         
98         // reset items to the pruned list
99
if(list.size() != items.length)
100         {
101             items = new ZipItem[list.size()];
102             items = (ZipItem[])list.toArray(items);
103         }
104     }
105
106     //////////////////////////////////////////////////////////////////////////////////////////////////////////////
107

108     private void init(String JavaDoc outFileName, String JavaDoc dirName) throws ZipFileException
109     {
110         try
111         {
112             init(new FileOutputStream(outFileName), dirName);
113         }
114         catch(Exception JavaDoc e)
115         {
116             throw new ZipFileException(e);
117         }
118     }
119
120     //////////////////////////////////////////////////////////////////////////////////////////////////////////////
121

122     private void init(OutputStream outStream, String JavaDoc dirName) throws ZipFileException
123     {
124         try
125         {
126             //make sure it's really a directory
127
File f = new File(dirName);
128             
129             // change the filename to be full-path & UNIX style
130
dirName = FileUtils.safeGetCanonicalPath(f);
131             dirName = dirName.replace('\\', '/'); // all UNIX-style filenames...
132

133             
134             // we need the dirname to end in a '/'
135
if(!dirName.endsWith("/"))
136                 dirName += "/";
137
138             
139             this.dirName = dirName;
140             zipStream = new ZipOutputStream(outStream);
141         }
142         catch(Throwable JavaDoc t)
143         {
144             throw new ZipFileException(t);
145         }
146     }
147
148     //////////////////////////////////////////////////////////////////////////////////////////////////////////////
149

150     /**
151      * Does not throw an exception when there is a duplicate zip entry.
152      *
153      * @throws ZipFileException if an error while creating the archive
154      */

155     public void safeWrite() throws ZipFileException
156     {
157         try
158         {
159             for(int i = 0; i < items.length; i++)
160             {
161                 try
162                 {
163                     addEntry(items[i]);
164                 }
165                 catch (ZipException e)
166                 {
167                     // ignore - duplicate zip entry
168
}
169             }
170             
171             zipStream.close();
172         }
173         catch(ZipFileException z)
174         {
175             throw z;
176         }
177         catch(Exception JavaDoc e)
178         {
179             throw new ZipFileException(e);
180         }
181     }
182
183     //////////////////////////////////////////////////////////////////////////////////////////////////////////////
184

185     public void write() throws ZipFileException
186     {
187         try
188         {
189             for(int i = 0; i < items.length; i++)
190             {
191                 addEntry(items[i]);
192             }
193             
194             zipStream.close();
195         }
196         catch(ZipFileException z)
197         {
198             throw z;
199         }
200         catch(Exception JavaDoc e)
201         {
202             throw new ZipFileException(e);
203         }
204     }
205
206     //////////////////////////////////////////////////////////////////////////////////////////////////////////////
207

208     private void addEntry(ZipItem item) throws ZipFileException, IOException
209     {
210         int totalBytes = 0;
211         ZipEntry ze = new ZipEntry(item.name);
212         
213         zipStream.putNextEntry(ze);
214         
215         // bnevins -- don't try to "read" from a directory file.
216
// Any item.name that ends in "/" must be an empty directory, or it wouldn't be here!
217
// important: if you look inside the zip file with WinZip you
218
// won't see empty directories. But they are there -- and they will
219
// get extracted!
220
if(!item.name.endsWith("/"))
221         {
222             FileInputStream in = new FileInputStream(item.file);
223
224             for(int numBytes = in.read(buffer); numBytes > 0; numBytes = in.read(buffer))
225             {
226                 zipStream.write(buffer, 0, numBytes);
227                 totalBytes += numBytes;
228             }
229             
230             in.close();
231         }
232         zipStream.closeEntry();
233     }
234
235     //////////////////////////////////////////////////////////////////////////////////////////////////////////////
236

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

257                 // bnevins -- add a trailing "/" to empty directories
258
if(f.isDirectory())
259                     items[i].name += "/";
260             }
261         }
262         catch(Throwable JavaDoc t)
263         {
264             throw new ZipFileException(t);
265         }
266             
267     }
268
269     //////////////////////////////////////////////////////////////////////////////////////////////////////////////
270

271     String JavaDoc getDirName()
272     {
273         return dirName;
274     }
275         
276     //////////////////////////////////////////////////////////////////////////////////////////////////////////////
277

278     private static void usage()
279     {
280         System.out.println("usage: java com.elf.util.zip.ZipWriter zip-filename directory-name");
281         System.exit(1);
282     }
283         
284     //////////////////////////////////////////////////////////////////////////////////////////////////////////////
285

286     public static void main(String JavaDoc[] args)
287     {
288         
289         if(args == null || args.length != 2)
290             usage();
291         
292         try
293         {
294             ZipWriter zw = new ZipWriter(args[0], args[1]);
295             zw.write();
296         }
297         catch(ZipFileException e)
298         {
299             System.exit(0);
300         }
301     }
302
303     /////////////////////////////////////////////////////////////////////////////////////////
304

305     //private String zipFilename = null;
306
private String JavaDoc dirName = null;
307     private ZipOutputStream zipStream = null;
308     private byte[] buffer = new byte[16384];
309     private ZipItem[] items = null;
310 }
311
Popular Tags