KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > continuent > sequoia > controller > backup > backupers > Zipper


1 /**
2  * Sequoia: Database clustering technology.
3  * Copyright (C) 2002-2004 French National Institute For Research In Computer
4  * Science And Control (INRIA).
5  * Contact: sequoia@continuent.org
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  * Initial developer(s): Emmanuel Cecchet
20  * Contributor(s): Nicolas Modrzyk
21  */

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

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

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

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

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

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