KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sourceforge > cruisecontrol > distributed > util > ZipUtil


1 /****************************************************************************
2 * CruiseControl, a Continuous Integration Toolkit
3 * Copyright (c) 2001, ThoughtWorks, Inc.
4 * 651 W Washington Ave. Suite 600
5 * Chicago, IL 60661 USA
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 *
12 * + Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 *
15 * + Redistributions in binary form must reproduce the above
16 * copyright notice, this list of conditions and the following
17 * disclaimer in the documentation and/or other materials provided
18 * with the distribution.
19 *
20 * + Neither the name of ThoughtWorks, Inc., CruiseControl, nor the
21 * names of its contributors may be used to endorse or promote
22 * products derived from this software without specific prior
23 * written permission.
24 *
25 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
28 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR
29 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
30 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
31 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
32 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
34 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
35 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 ****************************************************************************/

37
38 package net.sourceforge.cruisecontrol.distributed.util;
39
40 import java.io.BufferedInputStream JavaDoc;
41 import java.io.BufferedOutputStream JavaDoc;
42 import java.io.File JavaDoc;
43 import java.io.FileInputStream JavaDoc;
44 import java.io.FileNotFoundException JavaDoc;
45 import java.io.FileOutputStream JavaDoc;
46 import java.io.IOException JavaDoc;
47 import java.io.InputStream JavaDoc;
48 import java.util.Enumeration JavaDoc;
49 import java.util.zip.ZipEntry JavaDoc;
50 import java.util.zip.ZipException JavaDoc;
51 import java.util.zip.ZipFile JavaDoc;
52 import java.util.zip.ZipOutputStream JavaDoc;
53
54 import org.apache.log4j.Logger;
55
56 public final class ZipUtil {
57
58     private static final Logger LOG = Logger.getLogger(ZipUtil.class);
59
60     private ZipUtil() { }
61
62     public static void zipFolderContents(final String JavaDoc outFilename, final String JavaDoc folderToZip) {
63         validateParams(outFilename, folderToZip);
64         BufferedOutputStream JavaDoc bos = null;
65         ZipOutputStream JavaDoc zipOut = null;
66         try {
67             bos = new BufferedOutputStream JavaDoc(new FileOutputStream JavaDoc(outFilename));
68             zipOut = new ZipOutputStream JavaDoc(bos);
69             final File JavaDoc folder = new File JavaDoc(folderToZip);
70             String JavaDoc message = "Zipping files from: " + folderToZip + " to: " + outFilename;
71             LOG.info(message);
72             zipFiles(folder, folder, zipOut);
73             message = "Finished zipping files";
74             LOG.info(message);
75         } catch (FileNotFoundException JavaDoc fnfe) {
76             final String JavaDoc message = "File not found while zipping files to: " + outFilename;
77             LOG.error(message, fnfe);
78             throw new RuntimeException JavaDoc(message, fnfe);
79         } finally {
80             try {
81                 if (zipOut != null) {
82                 zipOut.close();
83                 }
84             } catch (ZipException JavaDoc ze) {
85                 final File JavaDoc file = new File JavaDoc(outFilename);
86                 if ((file.length() == 0) && (file.exists())) {
87                     final String JavaDoc message = "Empty zip file created: " + outFilename;
88                     LOG.debug(message);
89                     try {
90                         // this is required in order to close the file stream if zip is empty
91
bos.close();
92                     } catch (IOException JavaDoc e) {
93                         LOG.error(e);
94                     }
95                     // @todo Should empty zips be created, or should we delete them here?
96
//*
97
// delete the empty zip file
98
if (!file.delete()) {
99                         throw new RuntimeException JavaDoc("Error deleting empty zip file: "
100                                 + file.getAbsolutePath());
101                     }
102                     final String JavaDoc message2 = "Deleted empty zip file: " + outFilename;
103                     LOG.debug(message2);
104                     ///*/
105
}
106             } catch (IOException JavaDoc ioe) {
107                 final String JavaDoc message = "Error occured while closing zip file: " + outFilename;
108                 LOG.error(message, ioe);
109                 throw new RuntimeException JavaDoc(message, ioe);
110             }
111         }
112     }
113
114     private static void zipFiles(final File JavaDoc rootDir, final File JavaDoc folderToZip, final ZipOutputStream JavaDoc zipOutputStream) {
115         final byte[] buf = new byte[1024];
116
117         final String JavaDoc relativePath = folderToZip.toString().substring(rootDir.toString().length());
118
119         FileInputStream JavaDoc in;
120         final File JavaDoc[] files = folderToZip.listFiles();
121
122         for (int i = 0; i < files.length; i++) {
123             final String JavaDoc filename = files[i].getName();
124             if (files[i].isDirectory()) {
125                 final String JavaDoc dirName = relativePath + File.separator + filename;
126                 LOG.debug("adding dir [" + dirName + "]");
127                 zipFiles(rootDir, files[i], zipOutputStream);
128             } else {
129                 String JavaDoc filePath = relativePath + File.separator + filename;
130                 if (filePath.charAt(0) == File.separatorChar) {
131                     filePath = filePath.substring(1);
132                 }
133                 LOG.debug("adding file [" + filePath + "]");
134                 try {
135                     in = new FileInputStream JavaDoc(new File JavaDoc(folderToZip, filename));
136                     zipOutputStream.putNextEntry(new ZipEntry JavaDoc(filePath.replace(File.separatorChar, '/')));
137                     int len;
138                     while ((len = in.read(buf)) > 0) {
139                         zipOutputStream.write(buf, 0, len);
140                     }
141                     zipOutputStream.closeEntry();
142                     in.close();
143                 } catch (IOException JavaDoc ioe) {
144                     final String JavaDoc message = "Error occured while zipping file " + filePath;
145                     LOG.error(message, ioe);
146                     throw new RuntimeException JavaDoc(message, ioe);
147                 }
148             }
149         }
150     }
151
152     private static void validateParams(final String JavaDoc outFilename, final String JavaDoc folderToZip) {
153         if (outFilename == null) {
154             final String JavaDoc message = "Missing output zip file name";
155             LOG.error(message);
156             throw new IllegalArgumentException JavaDoc(message);
157         }
158         if (new File JavaDoc(outFilename).isDirectory()) {
159             final String JavaDoc message = "Output file already exists as directory";
160             LOG.error(message);
161             throw new IllegalArgumentException JavaDoc(message);
162         }
163         if (folderToZip == null) {
164             final String JavaDoc message = "Missing folder to zip";
165             LOG.error(message);
166             throw new IllegalArgumentException JavaDoc(message);
167         }
168         if (!(new File JavaDoc(folderToZip).isDirectory())) {
169             final String JavaDoc message = "Target folder to zip does not exist or is not a directory";
170             LOG.error(message);
171             throw new IllegalArgumentException JavaDoc(message);
172         }
173     }
174
175     /**
176      * @param zipFilePath
177      * @param toDirName
178      * @throws IOException
179      */

180     public static void unzipFileToLocation(final String JavaDoc zipFilePath, final String JavaDoc toDirName) throws IOException JavaDoc {
181         final ZipFile JavaDoc zipFile;
182         final Enumeration JavaDoc enumr;
183         boolean isEmptyFile = false;
184
185         try {
186             zipFile = new ZipFile JavaDoc(zipFilePath);
187             if (zipFile.size() == 0) {
188                 isEmptyFile = true;
189             } else {
190                 final String JavaDoc infoMessage = "Unzipping file: " + zipFilePath;
191                 LOG.info(infoMessage);
192
193                 enumr = zipFile.entries();
194                 while (enumr.hasMoreElements()) {
195                     final ZipEntry JavaDoc target = (ZipEntry JavaDoc) enumr.nextElement();
196                     final String JavaDoc message = "Exploding: " + target.getName();
197                     LOG.debug(message);
198                     saveItem(zipFile, toDirName, target);
199                 }
200                 zipFile.close();
201             }
202         } catch (FileNotFoundException JavaDoc fnfe) {
203             final String JavaDoc message = "Could not find zip file" + zipFilePath;
204             LOG.error(message, fnfe);
205             throw new RuntimeException JavaDoc(message, fnfe);
206         } catch (ZipException JavaDoc ze) {
207             final String JavaDoc message = "Zip error occured while unzipping file " + zipFilePath;
208             LOG.error(message, ze);
209             throw new RuntimeException JavaDoc(message, ze);
210         } catch (IOException JavaDoc ioe) {
211             final String JavaDoc message = "Error occured while unzipping file " + zipFilePath;
212             LOG.error(message, ioe);
213             throw new RuntimeException JavaDoc(message, ioe);
214         }
215
216         if (isEmptyFile) {
217             final String JavaDoc message = "Zip file has no entries: " + zipFilePath;
218             LOG.warn(message);
219             throw new IOException JavaDoc(message);
220         }
221
222         final String JavaDoc infoMessage = "Unzip complete";
223         LOG.info(infoMessage);
224     }
225
226     private static void saveItem(final ZipFile JavaDoc zipFile, final String JavaDoc rootDirName, final ZipEntry JavaDoc entry)
227             throws ZipException JavaDoc, IOException JavaDoc {
228         final InputStream JavaDoc is;
229         BufferedInputStream JavaDoc inStream = null;
230         final FileOutputStream JavaDoc outStream;
231         BufferedOutputStream JavaDoc bufferedOutStream = null;
232         try {
233             final File JavaDoc file = new File JavaDoc(rootDirName, entry.getName());
234             if (entry.isDirectory()) {
235                 file.mkdirs();
236             } else {
237                 is = zipFile.getInputStream(entry);
238                 inStream = new BufferedInputStream JavaDoc(is);
239                 final File JavaDoc dir = new File JavaDoc(file.getParent());
240                 dir.mkdirs();
241                 outStream = new FileOutputStream JavaDoc(file);
242                 bufferedOutStream = new BufferedOutputStream JavaDoc(outStream);
243
244                 int c;
245                 while ((c = inStream.read()) != -1) {
246                     bufferedOutStream.write((byte) c);
247                 }
248             }
249         } catch (ZipException JavaDoc ze) {
250             final String JavaDoc message = "Zip error unzipping entry: " + entry.getName();
251             LOG.error(message, ze);
252             throw new RuntimeException JavaDoc(message, ze);
253         } catch (IOException JavaDoc ioe) {
254             final String JavaDoc message = "I/O error unzipping entry: " + entry.getName();
255             LOG.error(message, ioe);
256             throw new RuntimeException JavaDoc(message, ioe);
257         } finally {
258             if (bufferedOutStream != null) {
259                 bufferedOutStream.close();
260             }
261             if (inStream != null) {
262                 inStream.close();
263             }
264         }
265     }
266 }
267
Popular Tags