KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > utils > zip > JahiaArchiveFileHandler


1 //
2
// ____.
3
// __/\ ______| |__/\. _______
4
// __ .____| | \ | +----+ \
5
// _______| /--| | | - \ _ | : - \_________
6
// \\______: :---| : : | : | \________>
7
// |__\---\_____________:______: :____|____:_____\
8
// /_____|
9
//
10
// . . . i n j a h i a w e t r u s t . . .
11
//
12
//
13
//
14
// JahiaArchiveFileHandler
15
//
16
// NK 15.01.2001
17
//
18
//
19

20
21 package org.jahia.utils.zip;
22
23
24 import java.io.BufferedInputStream JavaDoc;
25 import java.io.BufferedOutputStream JavaDoc;
26 import java.io.File JavaDoc;
27 import java.io.FileInputStream JavaDoc;
28 import java.io.FileOutputStream JavaDoc;
29 import java.io.IOException JavaDoc;
30 import java.io.InputStream JavaDoc;
31 import java.io.OutputStream JavaDoc;
32 import java.util.jar.JarFile JavaDoc;
33 import java.util.zip.ZipEntry JavaDoc;
34 import java.util.zip.ZipFile JavaDoc;
35 import java.util.zip.ZipInputStream JavaDoc;
36
37 import org.jahia.exceptions.JahiaArchiveFileException;
38 import org.jahia.exceptions.JahiaException;
39 import org.jahia.utils.JahiaConsole;
40
41 /**
42  * A Wrapper to handle some manipulations on .jar, .war and .ear files
43  *
44  * @author Khue ng
45  */

46 public class JahiaArchiveFileHandler {
47
48     private static final String JavaDoc CLASS_NAME = JahiaArchiveFileHandler.class.getName();
49
50    /** The full path to the file **/
51    private String JavaDoc m_FilePath;
52    /** The JarFile object **/
53    private JarFile JavaDoc m_JarFile;
54
55    /**
56     * Constructor
57     *
58     * @param (String) path, the full path to the file
59     * @exception IOException
60     */

61    public JahiaArchiveFileHandler ( String JavaDoc path ) throws IOException JavaDoc {
62
63       m_FilePath = path;
64       File JavaDoc f = new File JavaDoc(path);
65       try {
66
67          m_JarFile = new JarFile JavaDoc(f);
68
69       } catch ( IOException JavaDoc ioe ) {
70          JahiaConsole.println(CLASS_NAME+"::Constructor","IOException occurred " + f.getAbsolutePath() );
71          throw new IOException JavaDoc (CLASS_NAME +" IOException occurred ");
72       } catch ( java.lang.NullPointerException JavaDoc e ) {
73          JahiaConsole.println(CLASS_NAME+"::Constructor","NullPointerException " + f.getAbsolutePath() );
74          throw new IOException JavaDoc (CLASS_NAME + " NullPointerException occurred ");
75       }
76
77       if ( m_JarFile == null ) {
78
79          throw new IOException JavaDoc (CLASS_NAME+" source file is null");
80       }
81
82    }
83
84
85    /**
86     * Decompresses the file in it's current location
87     *
88     */

89    public void unzip() throws JahiaException {
90
91       try {
92
93          File JavaDoc f = new File JavaDoc(m_FilePath);
94
95          //JahiaConsole.println(CLASS_NAME + ".upzip"," Start Decompressing " + f.getName() );
96

97          String JavaDoc parentPath = f.getParent() + File.separator;
98          String JavaDoc path = null;
99
100          FileInputStream JavaDoc fis = new FileInputStream JavaDoc(m_FilePath);
101          BufferedInputStream JavaDoc bis = new BufferedInputStream JavaDoc(fis);
102          ZipInputStream JavaDoc zis = new ZipInputStream JavaDoc(bis);
103          ZipFile JavaDoc zf = new ZipFile JavaDoc(m_FilePath);
104          ZipEntry JavaDoc ze = null;
105          String JavaDoc zeName = null;
106
107          try{
108
109             while ( (ze = zis.getNextEntry()) != null ){
110                zeName = ze.getName();
111                path = parentPath + genPathFile(zeName);
112                File JavaDoc fo = new File JavaDoc(path);
113
114                if ( ze.isDirectory() ){
115                   fo.mkdirs();
116                } else {
117                   copyStream(zis,new FileOutputStream JavaDoc(fo));
118                }
119                zis.closeEntry();
120             }
121          } finally {
122
123             // Important !!!
124
zf.close();
125             fis.close();
126             zis.close();
127             bis.close();
128          }
129
130
131          //JahiaConsole.println(CLASS_NAME+".unzip"," Decompressing " + f.getName() + " done ! ");
132

133       } catch ( IOException JavaDoc ioe ) {
134
135          JahiaConsole.println("JahiaArchiveFileHandler"," fail unzipping " + ioe.getMessage() );
136
137          throw new JahiaException ("JahiaArchiveFileHandler", "faile processing unzip",
138                                     JahiaException.SERVICE_ERROR, JahiaException.ERROR_SEVERITY);
139
140       }
141
142    }
143
144
145    /**
146     * Decompress the file in a gived folder
147     *
148     * @param (String) path
149     */

150    public void unzip(String JavaDoc path) throws JahiaException {
151
152       try {
153
154          File JavaDoc f = new File JavaDoc(m_FilePath);
155
156          //JahiaConsole.println(CLASS_NAME+".unzip(path)"," Start Decompressing " + f.getName() );
157

158          String JavaDoc destPath = null;
159
160          FileInputStream JavaDoc fis = new FileInputStream JavaDoc(m_FilePath);
161          BufferedInputStream JavaDoc bis = new BufferedInputStream JavaDoc(fis);
162          ZipInputStream JavaDoc zis = new ZipInputStream JavaDoc(bis);
163          ZipFile JavaDoc zf = new ZipFile JavaDoc(m_FilePath);
164          ZipEntry JavaDoc ze = null;
165          String JavaDoc zeName = null;
166
167          try {
168
169             while ( (ze = zis.getNextEntry()) != null ){
170
171                zeName = ze.getName();
172
173                destPath = path + File.separator + genPathFile(zeName);
174
175                File JavaDoc fo = new File JavaDoc(destPath);
176
177                if ( ze.isDirectory() ){
178
179                   fo.mkdirs();
180                } else {
181                   File JavaDoc parent = new File JavaDoc(fo.getParent());
182                   parent.mkdirs();
183                   FileOutputStream JavaDoc fos = new FileOutputStream JavaDoc(fo);
184                   copyStream(zis,fos);
185                }
186                zis.closeEntry();
187             }
188          } finally {
189
190             // Important !!!
191
zf.close();
192             fis.close();
193             zis.close();
194             bis.close();
195          }
196
197          //JahiaConsole.println(CLASS_NAME+".unzip(path)"," Decompressing " + f.getName() + " done ! ");
198

199       } catch ( IOException JavaDoc ioe ) {
200
201          JahiaConsole.println(CLASS_NAME+".unzip(path)"," fail unzipping " + ioe.getMessage() );
202
203          throw new JahiaException (CLASS_NAME, "faile processing unzip",
204                                     JahiaException.SERVICE_ERROR, JahiaException.ERROR_SEVERITY, ioe);
205
206       }
207
208    }
209
210
211    /**
212     * Extract an entry of file type in the jar file
213     * Return a File Object reference to the uncompressed file
214     *
215     * @param (String) entryName, the entry name
216     * @return (File) fo, a File Handler to the file ( It's a temporary file )
217     */

218    public File JavaDoc extractFile( String JavaDoc entryName ) throws IOException JavaDoc, JahiaArchiveFileException {
219
220        File JavaDoc tmpFile = null;
221
222
223       // Create a temporary file and write the content of the file in it
224
ZipEntry JavaDoc entry = m_JarFile.getEntry(entryName);
225
226       if ( (entry != null) && !entry.isDirectory() ) {
227
228          InputStream JavaDoc ins = m_JarFile.getInputStream(entry);
229
230          if ( ins != null ){
231
232              // File f = new File(""); does not work on UNIX systems because we
233
// don't have write permissions all over the disk by default like
234
// under Windows.
235
// However Khue says it's necessary for Tomcat 4.0.2 ... This is
236
// weird, more investigation will be needed. Maybe Tomcat 4.0.2
237
// messes with jahia.io.tmpdir global system property ?
238
// tmpFile = File.createTempFile("jahia_temp","",f);
239

240              tmpFile = File.createTempFile("jahia_temp","",null);
241
242              if ( tmpFile == null || !tmpFile.canWrite() ){
243                  throw new IOException JavaDoc ("extractFile error creating temporary file");
244              }
245              FileOutputStream JavaDoc outs = new FileOutputStream JavaDoc(tmpFile);
246              copyStream(ins,outs);
247              outs.flush();
248              outs.close();
249          }
250       } else {
251          JahiaConsole.println(CLASS_NAME+".extractFile(entry)", " entryName" + " is null or a directory " );
252          throw new JahiaArchiveFileException (JahiaException.ENTRY_NOT_FOUND);
253       }
254
255       return tmpFile;
256
257    }
258
259
260    /**
261     * Extract an entry in a gived folder. If this entry is a directory,
262     * all its contents are extracted too.
263     *
264     * @param (String) entryName, the name of an entry in the jar
265     * @param (String) destPath, the path to the destination folder
266     */

267    public void extractEntry( String JavaDoc entryName,
268                              String JavaDoc destPath ) throws JahiaException {
269
270       try {
271
272          ZipEntry JavaDoc entry = m_JarFile.getEntry(entryName);
273
274          if ( entry == null ){
275             StringBuffer JavaDoc strBuf = new StringBuffer JavaDoc(1024);
276             strBuf.append(" extractEntry(), cannot find entry ");
277             strBuf.append(entryName);
278             strBuf.append(" in the jar file ");
279             //JahiaConsole.println(CLASS_NAME + ".extractEntry", strBuf.toString());
280

281             throw new JahiaException (CLASS_NAME, strBuf.toString(),
282                                     JahiaException.SERVICE_ERROR, JahiaException.ERROR_SEVERITY);
283
284          }
285
286
287          File JavaDoc destDir = new File JavaDoc(destPath);
288          if ( destDir == null || !destDir.isDirectory() || !destDir.canWrite() ){
289
290             JahiaConsole.println(CLASS_NAME+".extractEntry()"," cannot access to the destination dir ");
291
292             throw new JahiaException (CLASS_NAME," cannot access to the destination dir ",
293                                     JahiaException.SERVICE_ERROR, JahiaException.ERROR_SEVERITY);
294          }
295
296
297          File JavaDoc f = new File JavaDoc(m_FilePath);
298
299          //JahiaConsole.println(CLASS_NAME+".extractEntry(entryName,path)"," Decompressing entry " + entryName );
300

301          String JavaDoc path = null;
302
303          FileInputStream JavaDoc fis = new FileInputStream JavaDoc(m_FilePath);
304          BufferedInputStream JavaDoc bis = new BufferedInputStream JavaDoc(fis);
305          ZipInputStream JavaDoc zis = new ZipInputStream JavaDoc(bis);
306          ZipFile JavaDoc zf = new ZipFile JavaDoc(m_FilePath);
307          ZipEntry JavaDoc ze = null;
308          String JavaDoc zeName = null;
309          boolean isFile = false;
310
311          //JahiaConsole.println(CLASS_NAME+".extractEntry(entryName,path)"," Decompressing entry " + entryName + " in " + destDir.getAbsolutePath() );
312

313          while ( (ze = zis.getNextEntry()) != null && !ze.getName().equalsIgnoreCase(entryName) ) {
314             // loop until the requested entry
315
//JahiaConsole.println(CLASS_NAME+".extractEntry(extryName, path)"," bypass " + ze.getName() );
316
zis.closeEntry();
317          }
318
319          //JahiaConsole.println(CLASS_NAME+".extractEntry(entryName,path)"," found entry " + ze.getName());
320

321          try{
322
323             if ( ze.isDirectory() ){
324
325                //JahiaConsole.println(CLASS_NAME+".extractEntry(entryName,path)"," entry " + ze.getName() + " is a Directory Entry ");
326

327                while ( ze != null ){
328                   zeName = ze.getName();
329                   path = destPath + File.separator + genPathFile(zeName);
330                   File JavaDoc fo = new File JavaDoc(path);
331                   if ( ze.isDirectory() ){
332                      fo.mkdirs();
333                   } else {
334
335                      FileOutputStream JavaDoc outs = new FileOutputStream JavaDoc(fo);
336                      copyStream(zis,outs);
337                      //outs.flush();
338
//outs.close();
339
}
340                   zis.closeEntry();
341                   ze = zis.getNextEntry();
342
343                }
344             } else {
345
346                //JahiaConsole.println(CLASS_NAME+".extractEntry(entryName,path)"," entry " + ze.getName() + " is a File Entry ");
347

348                zeName = ze.getName();
349                path = destPath + File.separator + genPathFile(zeName);
350
351                //JahiaConsole.println(CLASS_NAME+".extractEntry(entryName,path)"," file path " + path );
352

353                File JavaDoc fo = new File JavaDoc(path);
354                FileOutputStream JavaDoc outs = new FileOutputStream JavaDoc(fo);
355                copyStream(zis,outs);
356                //outs.flush();
357
//outs.close();
358
}
359
360             //JahiaConsole.println(CLASS_NAME+".extractEntry(entryName,path)"," extract " + entryName + " done ! ");
361

362          } finally {
363
364             // Important !!!
365
zf.close();
366             fis.close();
367             zis.close();
368             bis.close();
369          }
370
371
372
373       } catch ( IOException JavaDoc ioe ) {
374
375          JahiaConsole.println(CLASS_NAME," fail unzipping " + ioe.getMessage() );
376
377          throw new JahiaException (CLASS_NAME, "faile processing unzip",
378                                     JahiaException.SERVICE_ERROR, JahiaException.ERROR_SEVERITY);
379
380       }
381
382    }
383
384
385    /**
386     * Return an entry in the jar file of the gived name or null if not found
387     *
388     * @param (String) entryName the entry name
389     * @return (ZipEntry) the entry
390     */

391    public ZipEntry JavaDoc getEntry(String JavaDoc entryName){
392
393       return m_JarFile.getEntry(entryName);
394
395    }
396
397
398    /**
399     * Check if an entry is a directory or not
400     *
401     * @param (String) entryName the entry name
402     * @return (boolean) true if the entry exists and is a a directory
403     */

404    public boolean isDirectory(String JavaDoc entryName){
405       return ((m_JarFile.getEntry(entryName) != null) && m_JarFile.getEntry(entryName).isDirectory());
406    }
407
408    /**
409     * Check if an entry exist or not
410     *
411     * @param (String) entryName the entry name
412     * @return (boolean) true if exist
413     */

414    public boolean entryExists(String JavaDoc entryName){
415       return ( m_JarFile.getEntry(entryName) != null );
416    }
417
418
419    /**
420     * Close the Zip file. Important to close the JarFile object
421     * to be able to delete it from disk.
422     *
423     */

424    public void closeArchiveFile(){
425
426       try {
427          m_JarFile.close();
428       } catch ( IOException JavaDoc e ) {
429          JahiaConsole.println(CLASS_NAME,"cannot close jar file");
430          // cannot close file
431
}
432
433    }
434
435
436    /**
437     * Generates a file path for a gived entry name
438     * Parses "/" char and replaces them with File.separator char
439     *
440     */

441    protected String JavaDoc genPathFile(String JavaDoc entryName){
442
443       StringBuffer JavaDoc sb = new StringBuffer JavaDoc(entryName.length());
444       for ( int i= 0; i< entryName.length() ; i++ ){
445          if ( entryName.charAt(i) == '/' ){
446             sb.append(File.separator);
447          } else {
448             sb.append(entryName.charAt(i));
449          }
450       }
451
452       return ( sb.toString() );
453
454    }
455
456
457     /**
458      * Copy an InputStream to an OutPutStream
459      *
460      * @param ins An InputStream.
461      * @param outs An OutputStream.
462      * @exception IOException.
463      */

464    protected void copyStream( InputStream JavaDoc ins,
465                             OutputStream JavaDoc outs)
466        throws IOException JavaDoc
467    {
468       int bufferSize = 1024;
469       byte[] writeBuffer = new byte[bufferSize];
470
471       BufferedOutputStream JavaDoc bos =
472          new BufferedOutputStream JavaDoc(outs, bufferSize);
473       int bufferRead;
474       while((bufferRead = ins.read(writeBuffer)) != -1)
475          bos.write(writeBuffer,0,bufferRead);
476       bos.flush();
477       bos.close();
478       outs.flush();
479       outs.close();
480    }
481
482
483
484
485
486 } // End Class JahiaArchiveFileHandler
487
Popular Tags