KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > cjdbc > common > util > Zipper


1 /**
2  * C-JDBC: Clustered JDBC.
3  * Copyright (C) 2002-2004 French National Institute For Research In Computer
4  * Science And Control (INRIA).
5  * Contact: c-jdbc@objectweb.org
6  *
7  * This library is free software; you can redistribute it and/or modify it
8  * under the terms of the GNU Lesser General Public License as published by the
9  * Free Software Foundation; either version 2.1 of the License, or any later
10  * version.
11  *
12  * This library is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14  * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
15  * for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public License
18  * along with this library; if not, write to the Free Software Foundation,
19  * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
20  *
21  * Initial developer(s): Emmanuel Cecchet
22  * Contributor(s): Nicolas Modrzyk
23  */

24
25 package org.objectweb.cjdbc.common.util;
26
27 import java.io.BufferedInputStream JavaDoc;
28 import java.io.BufferedOutputStream JavaDoc;
29 import java.io.File JavaDoc;
30 import java.io.FileInputStream JavaDoc;
31 import java.io.FileOutputStream JavaDoc;
32 import java.io.IOException JavaDoc;
33 import java.util.zip.ZipEntry JavaDoc;
34 import java.util.zip.ZipInputStream JavaDoc;
35 import java.util.zip.ZipOutputStream JavaDoc;
36
37 import org.objectweb.cjdbc.common.i18n.Translate;
38 import org.objectweb.cjdbc.common.log.Trace;
39
40 /**
41  * Zip utility class to compress a directory into a single zip file and
42  * vice-versa.
43  *
44  * @author <a HREF="mailto:emmanuel.cecchet@emicnetworks.com">Emmanuel Cecchet</a>
45  * @author <a HREF="mailto:Nicolas.Modrzyk@inrialpes.fr">Nicolas Modrzyk </a>
46  */

47 public class Zipper
48 {
49   /** Extension for zipped file names */
50   public static final String JavaDoc ZIP_EXT = ".zip";
51
52   private static final int BUFFER_SIZE = 2048;
53
54   /** Store full path in zip when archiving */
55   public static final int STORE_FULL_PATH_IN_ZIP = 0;
56   /** Store only file names in zip when archiving */
57   public static final int STORE_NAME_ONLY_IN_ZIP = 1;
58   /** Store relative path in zip when archiving */
59   public static final int STORE_RELATIVE_PATH_IN_ZIP = 2;
60   /** Store path relative to root directory in zip when archiving */
61   public static final int STORE_PATH_FROM_ZIP_ROOT = 3;
62
63   static Trace logger = Trace
64                                                             .getLogger(Zipper.class
65                                                                 .getName());
66
67   /**
68    * Create a zip file from directory
69    *
70    * @param zipName name of the file to create
71    * @param rootDir root directory to archive
72    * @param storePolicy the store policy to use (STORE_FULL_PATH_IN_ZIP,
73    * STORE_NAME_ONLY_IN_ZIP, STORE_RELATIVE_PATH_IN_ZIP or
74    * STORE_PATH_FROM_ZIP_ROOT)
75    * @throws Exception if fails
76    */

77   public static void zip(String JavaDoc zipName, String JavaDoc rootDir, int storePolicy)
78       throws Exception JavaDoc
79   {
80     if (zipName == null || rootDir == null)
81       throw new Exception JavaDoc("Invalid arguments to create zip file");
82     try
83     {
84       FileOutputStream JavaDoc fos = new FileOutputStream JavaDoc(zipName);
85       ZipOutputStream JavaDoc zos = new ZipOutputStream JavaDoc(fos);
86
87       directoryWalker(rootDir, rootDir, zos, storePolicy);
88
89       zos.flush();
90       zos.finish();
91       zos.close();
92       fos.close();
93     }
94     catch (IOException JavaDoc e)
95     {
96       logger.error(e.getMessage());
97       throw e;
98     }
99   }
100
101   /**
102    * Expand the content of the zip file
103    *
104    * @param zipName of the file to expand
105    * @param targetDir where to place unzipped files
106    * @throws Exception if fails
107    */

108   public static void unzip(String JavaDoc zipName, String JavaDoc targetDir) throws Exception JavaDoc
109   {
110     File JavaDoc ftargetDir = new File JavaDoc(targetDir);
111     if (!ftargetDir.exists())
112       ftargetDir.mkdirs();
113     if (!ftargetDir.exists())
114       throw new Exception JavaDoc(Translate.get("zip.invalid.target.directory"));
115
116     File JavaDoc fzipname = new File JavaDoc(zipName);
117     if (!fzipname.exists())
118       throw new Exception JavaDoc(Translate.get("zip.invalid.source.file", zipName));
119
120     try
121     {
122       FileInputStream JavaDoc fis = new FileInputStream JavaDoc(fzipname);
123       ZipInputStream JavaDoc zis = new ZipInputStream JavaDoc(fis);
124
125       ZipEntry JavaDoc entry;
126
127       byte[] data = new byte[BUFFER_SIZE];
128       while ((entry = zis.getNextEntry()) != null)
129       {
130         int count;
131         String JavaDoc target = targetDir + File.separator + entry.getName();
132         File JavaDoc fget = new File JavaDoc(target);
133         fget.mkdirs(); // create needed new directories
134
fget.delete(); // delete directory but not parents
135
if (logger.isDebugEnabled())
136           logger.debug(Translate.get("zip.extracting", new String JavaDoc[]{
137               String.valueOf(entry), fget.getAbsolutePath()}));
138         FileOutputStream JavaDoc fos = new FileOutputStream JavaDoc(target);
139
140         BufferedOutputStream JavaDoc dest = new BufferedOutputStream JavaDoc(fos, BUFFER_SIZE);
141         while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1)
142         {
143           dest.write(data, 0, count);
144         }
145         dest.flush();
146         dest.close();
147       }
148       zis.close();
149     }
150     catch (Exception JavaDoc e)
151     {
152       logger.error("Error while uncompressing archive", e);
153       throw e;
154     }
155   }
156
157   /**
158    * Walk through currentDir and recursively in its subdirectories. Each file
159    * found is zipped.
160    *
161    * @param currentDir directory to walk through
162    * @param rootDir root directory for path references
163    * @param zos ZipOutputSteam to write to
164    * @param storePolicy file path storing policy
165    * @throws IOException if an error occurs
166    */

167   private static void directoryWalker(String JavaDoc currentDir, String JavaDoc rootDir,
168       ZipOutputStream JavaDoc zos, int storePolicy) throws IOException JavaDoc
169   {
170     File JavaDoc dirObj = new File JavaDoc(currentDir);
171     if (dirObj.exists() == true)
172     {
173       if (dirObj.isDirectory() == true)
174       {
175
176         File JavaDoc[] fileList = dirObj.listFiles();
177
178         for (int i = 0; i < fileList.length; i++)
179         {
180           if (fileList[i].isDirectory())
181           {
182             directoryWalker(fileList[i].getPath(), rootDir, zos, storePolicy);
183           }
184           else if (fileList[i].isFile())
185           {
186             zipFile(fileList[i].getPath(), zos, storePolicy, rootDir);
187           }
188         }
189       }
190       else
191       {
192         if (logger.isDebugEnabled())
193           logger.debug(Translate.get("zip.not.directory", rootDir));
194       }
195     }
196     else
197     {
198       if (logger.isDebugEnabled())
199         logger.debug(Translate.get("zip.directory.not.found", rootDir));
200     }
201   }
202
203   /**
204    * TODO: zipFunc definition.
205    *
206    * @param filePath file to compress
207    * @param zos ZipOutputSteam to write to
208    * @param storePolicy file path storing policy
209    * @param rootDir root directory for path references
210    * @throws IOException if an error occurs
211    */

212   private static void zipFile(String JavaDoc filePath, ZipOutputStream JavaDoc zos,
213       int storePolicy, String JavaDoc rootDir) throws IOException JavaDoc
214   {
215     File JavaDoc ffilePath = new File JavaDoc(filePath);
216     String JavaDoc path = "";
217     switch (storePolicy)
218     {
219       case STORE_FULL_PATH_IN_ZIP :
220         path = ffilePath.getAbsolutePath();
221         break;
222       case STORE_NAME_ONLY_IN_ZIP :
223         ffilePath.getName();
224         break;
225       case STORE_RELATIVE_PATH_IN_ZIP :
226         File JavaDoc f = new File JavaDoc("");
227         String JavaDoc pathToHere = f.getAbsolutePath();
228         path = ffilePath.getAbsolutePath();
229         path = path.substring(path.indexOf(pathToHere + File.separator)
230             + pathToHere.length());
231         break;
232       case STORE_PATH_FROM_ZIP_ROOT :
233         path = ffilePath.getAbsolutePath();
234         String JavaDoc tmpDir = rootDir + File.separator;
235         // Strip rootdir from absolute path
236
path = path.substring(path.indexOf(tmpDir) + tmpDir.length());
237         break;
238       default :
239         break;
240     }
241
242     if (logger.isDebugEnabled())
243       logger
244           .debug(Translate.get("zip.archiving", new String JavaDoc[]{filePath, path}));
245
246     FileInputStream JavaDoc fileStream = new FileInputStream JavaDoc(filePath);
247     BufferedInputStream JavaDoc bis = new BufferedInputStream JavaDoc(fileStream);
248
249     ZipEntry JavaDoc fileEntry = new ZipEntry JavaDoc(path);
250     zos.putNextEntry(fileEntry);
251
252     byte[] data = new byte[BUFFER_SIZE];
253     int byteCount;
254     while ((byteCount = bis.read(data, 0, BUFFER_SIZE)) > -1)
255       zos.write(data, 0, byteCount);
256   }
257
258 }
Popular Tags