KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > util > explorer > parser > lib > ZipManager


1 /*====================================================================
2
3 Objectweb Explorer Framework
4 Copyright (C) 2000-2004 INRIA - USTL - LIFL - GOAL
5 Contact: openccm@objectweb.org
6
7 This library is free software; you can redistribute it and/or
8 modify it under the terms of the GNU Lesser General Public
9 License as published by the Free Software Foundation; either
10 version 2.1 of the License, or any later version.
11
12 This library is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Lesser General Public License for more details.
16
17 You should have received a copy of the GNU Lesser General Public
18 License along with this library; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
20 USA
21
22 Initial developer(s): Jerome Moroy, Philippe Merle.
23 Contributor(s): ______________________________________.
24
25 ====================================================================*/

26 package org.objectweb.util.explorer.parser.lib;
27
28 import java.io.File JavaDoc;
29 import java.io.FileOutputStream JavaDoc;
30 import java.io.IOException JavaDoc;
31 import java.io.InputStream JavaDoc;
32 import java.io.OutputStream JavaDoc;
33 import java.net.MalformedURLException JavaDoc;
34 import java.net.URL JavaDoc;
35 import java.util.Enumeration JavaDoc;
36 import java.util.Iterator JavaDoc;
37 import java.util.List JavaDoc;
38 import java.util.Vector JavaDoc;
39 import java.util.zip.ZipEntry JavaDoc;
40 import java.util.zip.ZipException JavaDoc;
41 import java.util.zip.ZipFile JavaDoc;
42
43 import org.objectweb.util.explorer.core.common.lib.BasicLoggable;
44 import org.objectweb.util.explorer.core.common.lib.ClassResolver;
45 import org.objectweb.util.explorer.explorerConfig.Zip;
46 import org.objectweb.util.explorer.explorerConfig.beans.ExplorerBean;
47 import org.objectweb.util.explorer.parser.api.ExplorerParser;
48
49 /**
50  * This component manages the "zip" XML element.
51  *
52  * @author <a HREF="mailto:Jerome.Moroy@lifl.fr">Jérôme Moroy</a>,
53  * <a HREF="mailto:Philippe.Merle@lifl.fr">Philippe Merle</a>.
54  *
55  * @version 0.1
56  */

57 public class ZipManager
58      extends BasicLoggable
59   implements ExplorerParser
60 {
61
62     //==================================================================
63
//
64
// Internal States.
65
//
66
// ==================================================================
67

68     /** The directory in which the zip file will be extracted. */
69     protected File JavaDoc extractedFolder_ = null;
70     
71     // ==================================================================
72
//
73
// Constructors.
74
//
75
// ==================================================================
76

77     /**
78      * Default constructor
79      */

80     public ZipManager(){
81         // In order to remove the temporary folder before stopping the program
82
System.runFinalizersOnExit(true);
83     }
84     
85     // ==================================================================
86
//
87
// Internal methods.
88
//
89
// ==================================================================
90

91     /**
92      * Removes the given file and recursively removes if the target file is a directory.
93      */

94     protected void remove(File JavaDoc file){
95         if(file!=null) {
96             if(file.isDirectory()){
97                 File JavaDoc[] children = file.listFiles();
98                 for(int i = 0 ; i < children.length ; i++)
99                     remove(children[i]);
100             }
101             file.delete();
102         }
103     }
104     
105     /**
106      * Writes a file on the given input stream.
107      * Note that the stream are closed when leaving the this method.
108      */

109     protected void writeFile(InputStream JavaDoc input, OutputStream JavaDoc output) throws IOException JavaDoc {
110         int bufferSize = 1024;
111         byte[] buffer = new byte[bufferSize];
112         int length=0;
113         while((length = input.read(buffer))>0){
114             output.write(buffer, 0, length);
115         }
116         output.close();
117         input.close();
118     }
119     
120     /**
121      * Extracts a ZipEntry into the tmp dir.
122      * @param file The zip file.
123      * @param entry The entry to extract.
124      * @throws IOException Throws when an IOException occured.
125      */

126     protected void extractEntry(ZipFile JavaDoc file, ZipEntry JavaDoc entry, String JavaDoc fileName) throws IOException JavaDoc {
127         writeFile(file.getInputStream(entry), new FileOutputStream JavaDoc(fileName));
128     }
129
130     /*
131      * It seems there is a problem with the methods "mkdirs()" and "deleteOnExit()" when they are working together.
132      * Indeed, the mkdirs method recursively creates the directory contained in this File definition and the deleteOnExit method
133      * removes those files when the virtual machine terminates, but when more than one directory is defined in the File, the first one
134      * is not removed by the deleteOnExit calling.
135      * It is the only problem that prevents this class to remove the "finalize()" method.
136      */

137     /**
138      * Creates the given directory.
139      * @param path The path of the disrectory to create
140      */

141     protected void createDirectory(String JavaDoc path){
142         File JavaDoc directory = new File JavaDoc(path);
143         if(!directory.exists()){
144             // the mkdirs method (used with deleteOnExit) doesn't remove the first directory of a directories path.
145
directory.deleteOnExit();
146             directory.mkdirs();
147         }
148     }
149     
150     /**
151      * Extracts a Zip archive
152      */

153     protected void extractFile(File JavaDoc file, Vector JavaDoc javaArchives) throws IOException JavaDoc {
154         ZipFile JavaDoc zipFile = null;
155         try {
156             zipFile = new ZipFile JavaDoc(file.toString());
157         } catch (ZipException JavaDoc e) {
158             // Nothing to do
159
} finally {
160             file.deleteOnExit();
161         }
162         if(zipFile!=null){
163             for(Enumeration JavaDoc entries = zipFile.entries();entries.hasMoreElements();){
164                 ZipEntry JavaDoc zipEntry = (ZipEntry JavaDoc)entries.nextElement();
165                 if(zipEntry.isDirectory()){
166                     createDirectory(extractedFolder_.getCanonicalPath() + "/" + zipEntry.getName());
167                 } else {
168                     // Creates the directories
169
int indice = zipEntry.getName().lastIndexOf('/');
170                     if(indice!=-1){
171                         createDirectory(extractedFolder_.getCanonicalPath() + "/" + zipEntry.getName().substring(0,indice));
172                     }
173                     // Computes the name of the file
174
String JavaDoc fileName = extractedFolder_.getCanonicalPath() + "/" + zipEntry.getName();
175                     // Extracts the entry
176
try {
177                         extractEntry(zipFile, zipEntry, fileName);
178                     } catch (IOException JavaDoc e) {
179                         getTrace().warn("IOException: " + e.getMessage());
180                         e.printStackTrace();
181                     }
182                     if(zipEntry.getName().toLowerCase().endsWith(".jar")) {
183                         // Adds the java archive into the vector containing the Java archive to load
184
File JavaDoc jarFile = new File JavaDoc(fileName);
185                         jarFile.deleteOnExit();
186                         try {
187                             javaArchives.add(jarFile.toURL());
188                         } catch (IOException JavaDoc e) {
189                             getTrace().warn("IOException: " + e.getMessage());
190                             e.printStackTrace();
191                         }
192                     } else {
193                         extractFile(new File JavaDoc(fileName), javaArchives);
194                     }
195                 }
196             }
197         }
198     }
199     
200     /**
201      * Loads the contained jar archives of the given zip element.
202      * @param zip A zip archive containing the jar archives to load.
203      */

204     protected void loadZip(URL JavaDoc zipURL) throws IOException JavaDoc {
205         if(zipURL!=null){
206             Vector JavaDoc javaArchives = new Vector JavaDoc();
207
208             // Copies the zip file into the java temp directory
209
String JavaDoc fileName = extractedFolder_.getCanonicalPath() + "/temp.zip";
210             writeFile(zipURL.openStream(), new FileOutputStream JavaDoc(fileName));
211
212             // Extracts the zip file
213
File JavaDoc zipFile = new File JavaDoc(fileName);
214             zipFile.deleteOnExit();
215             extractFile(zipFile, javaArchives);
216             
217             // Loads the jar contained in the given zip file
218
ClassResolver.addContext((URL JavaDoc[])javaArchives.toArray(new URL JavaDoc[0]));
219         }
220     }
221     
222     /**
223      * Unzips all the zip archives of the given list and for each archive,
224      * loads the contained jar archives.
225      * @param zipList A list of zip archives containing the jar archives to load.
226      */

227     protected void loadZips(List JavaDoc zipList){
228         if(zipList!=null && zipList.size() > 0){
229             if(extractedFolder_== null){
230                 // Ceates a temp directory
231
String JavaDoc tmpDir = System.getProperty("java.io.tmpdir");
232                 if ((!tmpDir.endsWith("/")) && (!tmpDir.endsWith("\\")))
233                     tmpDir = tmpDir + "/";
234                 extractedFolder_ = new File JavaDoc(tmpDir + "explorer" + System.currentTimeMillis());
235                 extractedFolder_.mkdir();
236                 extractedFolder_.deleteOnExit();
237             }
238             for(Iterator JavaDoc i = zipList.iterator() ; i.hasNext() ; ){
239                 Zip zip = (Zip)i.next();
240                 try {
241                     loadZip(new URL JavaDoc(zip.getUrl()));
242                 } catch (MalformedURLException JavaDoc e) {
243                     getTrace().warn("MalformedURLException: " + e.getMessage());
244                 } catch (IOException JavaDoc e) {
245                     getTrace().warn("IOException: " + e.getMessage());
246                 }
247             }
248         }
249     }
250     
251     // ==================================================================
252
//
253
// Public methods for ExplorerParser interface.
254
//
255
// ==================================================================
256

257     /* (non-Javadoc)
258      * @see org.objectweb.util.explorer.parser.api.ExplorerParser#parseExplorer(org.objectweb.util.explorer.explorerConfig.beans.ExplorerBean)
259      */

260     public void parseExplorer(ExplorerBean explorer) {
261         loadZips(explorer.getZipList());
262     }
263
264     // ==================================================================
265
//
266
// Public method surcharging java.lang.Object methods.
267
//
268
// ==================================================================
269

270     /**
271      * Removes the temporary folder containing the extracting files.
272      * Overriding methods
273      * @see java.lang.Object#finalize()
274      */

275     public void finalize() throws Throwable JavaDoc {
276         if(extractedFolder_!=null && extractedFolder_.exists()){
277             remove(extractedFolder_);
278         }
279     }
280 }
281
Popular Tags