KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jdesktop > jdic > packager > impl > FileOperUtility


1 /*
2  * Copyright (C) 2004 Sun Microsystems, Inc. All rights reserved. Use is
3  * subject to license terms.
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the Lesser GNU General Public License as
7  * published by the Free Software Foundation; either version 2 of the
8  * License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
18  * USA.
19  */

20 package org.jdesktop.jdic.packager.impl;
21
22 import java.io.File JavaDoc;
23 import java.io.InputStream JavaDoc;
24 import java.io.OutputStream JavaDoc;
25 import java.io.DataOutputStream JavaDoc;
26 import java.io.DataInputStream JavaDoc;
27 import java.io.FileInputStream JavaDoc;
28 import java.io.FileOutputStream JavaDoc;
29 import java.io.IOException JavaDoc;
30 import java.util.StringTokenizer JavaDoc;
31 import java.net.URL JavaDoc;
32
33 import com.sun.deploy.net.proxy.DeployProxySelector;
34 import com.sun.deploy.net.proxy.StaticProxyManager;
35 import com.sun.deploy.services.ServiceManager;
36 import com.sun.deploy.services.PlatformType;
37 import com.sun.javaws.jnl.ExtensionDesc;
38 import com.sun.javaws.jnl.IconDesc;
39 import com.sun.javaws.jnl.InformationDesc;
40 import com.sun.javaws.jnl.JARDesc;
41 import com.sun.javaws.jnl.JREDesc;
42 import com.sun.javaws.jnl.LaunchDesc;
43 import com.sun.javaws.jnl.LaunchDescFactory;
44 import com.sun.javaws.jnl.PackageDesc;
45 import com.sun.javaws.jnl.PropertyDesc;
46 import com.sun.javaws.jnl.ResourceVisitor;
47 import com.sun.javaws.jnl.ResourcesDesc;
48
49 /**
50  * This class contains some Utilities related to File Operation.
51  */

52 public class FileOperUtility {
53     static {
54         if (System.getProperty("os.name").indexOf("Windows") != -1) {
55             ServiceManager.setService(PlatformType.STANDALONE_TIGER_WIN32);
56         } else {
57             ServiceManager.setService(PlatformType.STANDALONE_TIGER_UNIX);
58         }
59         
60         try {
61             DeployProxySelector.reset();
62         } catch (Throwable JavaDoc t) {
63             StaticProxyManager.reset();
64         }
65     }
66     
67     /**
68      * copy remote file pointed by url to a local directory
69      *
70      * @param url points to a remote file
71      * @param codebase remote codebase
72      * @param localbase local directory where store the file
73      * @throws IOException
74      */

75     public static void urlFile2LocalFile(URL JavaDoc url, URL JavaDoc codebase,
76             String JavaDoc localbase) throws IOException JavaDoc {
77         if (url == null || url.getFile() == null || url.getFile().length() <= 0)
78             return;
79         String JavaDoc relPath = getRelativePath(url.toString(), codebase.toString());
80         File JavaDoc localFile = new File JavaDoc(localbase + File.separator + relPath);
81         copyRemoteFile(url, localFile);
82     }
83     
84     private static void createLocalFile(File JavaDoc localFile) throws IOException JavaDoc {
85         if (localFile == null)
86             return;
87         
88         if (!localFile.getParentFile().exists()) {
89             try {
90                  if (!localFile.getParentFile().mkdirs()) {
91                      throw new IOException JavaDoc("Cannot make parent directory " +
92                            "when trying to create local file");
93                  }
94             } catch (Exception JavaDoc e) {
95                  throw new IOException JavaDoc("Cannot make parent directory when " +
96                        "trying to create local file: " + e.getMessage());
97             }
98         }
99        
100         if (localFile.exists()) {
101             try {
102                 if (!localFile.delete()) {
103                      throw new IOException JavaDoc("Cannot delete original file when " +
104                             "trying to create local file");
105                 }
106             } catch (Exception JavaDoc e) {
107                 throw new IOException JavaDoc("Cannot delete original file when " +
108                         "trying to create local file: " + e.getMessage());
109             }
110         }
111
112         try {
113             if (!localFile.createNewFile()) {
114                 throw new IOException JavaDoc("Cannot create new local file");
115             }
116         } catch (Exception JavaDoc e) {
117             throw new IOException JavaDoc("Cannot create new local file: " +
118                     e.getMessage());
119         }
120     }
121     
122     private static void copyRemoteFile(URL JavaDoc url, File JavaDoc localFile)
123             throws IOException JavaDoc {
124         if (url == null || localFile == null)
125             return;
126         
127         if (url.getFile() == "" || url.getFile() == null)
128             return;
129         
130         if (localFile.isDirectory()) {
131             localFile = new File JavaDoc(localFile.getPath() + File.separator +
132                     url.getFile());
133         }
134         
135         if (!localFile.exists()) {
136             createLocalFile(localFile);
137         }
138      
139         DataInputStream JavaDoc inStream = new DataInputStream JavaDoc(url.openStream());
140         DataOutputStream JavaDoc outStream = new DataOutputStream JavaDoc(
141                 new FileOutputStream JavaDoc(localFile));
142
143         copyStream(inStream, outStream);
144     }
145     
146     private static void copyStream(InputStream JavaDoc inStream,
147             OutputStream JavaDoc outStream) throws IOException JavaDoc {
148         int readbytes = 0;
149                                 
150         try {
151             do {
152                 byte[] buffer = new byte[512];
153                 readbytes = inStream.read(buffer, 0, 512);
154                 if (readbytes <= 0) {
155                     break;
156                 }
157                 
158                 outStream.write(buffer, 0, readbytes);
159                 outStream.flush();
160             } while (true);
161         } catch (IOException JavaDoc ioE) {
162             ioE.printStackTrace();
163         } finally {
164             if (inStream != null) {
165                 inStream.close();
166             }
167             if (outStream != null) {
168                 outStream.close();
169             }
170         }
171     }
172     
173     /**
174      * get relative path according the give path and base
175      *
176      * @param path
177      * @param base
178      * @return relative path
179      */

180     public static String JavaDoc getRelativePath(String JavaDoc path, String JavaDoc base) {
181         if (path == null || base == null)
182             return null;
183         // On Windows Plaform, change all the path string to lower case
184
if (System.getProperty("os.name").toLowerCase().startsWith("windows")) {
185             path = path.toLowerCase();
186             base = base.toLowerCase();
187         }
188         if (path.lastIndexOf(base) < 0) {
189             int index = path.lastIndexOf("/");
190             if (index < 0) {
191                 return path;
192             } else {
193                 return path.substring(index + 1);
194             }
195         }
196         String JavaDoc relPath = path.substring(path.lastIndexOf(base) + base.length());
197         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(relPath, "/", false);
198         String JavaDoc nativeRelPath = "";
199         while (st.hasMoreTokens()) {
200             if (nativeRelPath.length() == 0) {
201                 nativeRelPath = st.nextToken();
202             } else {
203                 nativeRelPath += File.separator + st.nextToken();
204             }
205         }
206         
207         return nativeRelPath;
208     }
209     
210     /**
211      * copy source file to dest
212      *
213      * @param sourceFileName name of the source, could be either directory or a file
214      * @param destFileName name of the dest, could be either a file or a directory
215      * @throws IOException
216      */

217     public static void copyLocalFile(String JavaDoc sourceFileName, String JavaDoc destFileName)
218             throws IOException JavaDoc {
219         File JavaDoc sourceFile = new File JavaDoc(sourceFileName);
220         File JavaDoc destFile = new File JavaDoc(destFileName);
221         
222         if (!sourceFile.exists())
223             return;
224         
225         /* return if source and dest are pointing at the same path */
226         if (destFile.exists() && sourceFile.getPath().
227                 equals(destFile.getPath())) {
228             return;
229         }
230         
231         if (sourceFile.isFile()) {
232             if (destFile.isDirectory()) {
233                 destFile = new File JavaDoc(destFile.getPath() + File.separator +
234                         sourceFile.getName());
235             }
236             createLocalFile(destFile);
237
238             DataInputStream JavaDoc inStream = new DataInputStream JavaDoc(
239                     new FileInputStream JavaDoc(sourceFile));
240             DataOutputStream JavaDoc outStream = new DataOutputStream JavaDoc(
241                     new FileOutputStream JavaDoc(destFile));
242             
243             copyStream(inStream, outStream);
244         } else if (sourceFile.isDirectory()) {
245             if (destFile.exists() && !destFile.isDirectory()) {
246                 throw new IOException JavaDoc("cannot copy directory because there " +
247                         "is a file with the same name in destination: " +
248                         destFile.getPath());
249             }
250             
251             try {
252                 if (!destFile.exists() && !destFile.mkdirs()) {
253                     throw new IOException JavaDoc("cannot create local directory: " +
254                             destFile.getPath());
255                 }
256                 
257                 File JavaDoc[] filelist = sourceFile.listFiles();
258                 if (filelist == null)
259                     return;
260                 for (int i = 0; i < filelist.length; i++) {
261                     if (filelist[i].getPath().equals(destFile.getPath())) {
262                         return;
263                     }
264                     String JavaDoc destName = destFileName + File.separator +
265                             getRelativePath(filelist[i].getCanonicalPath(),
266                                     sourceFile.getCanonicalPath());
267                     copyLocalFile(filelist[i].getCanonicalPath(), destName);
268                 }
269             } catch (Exception JavaDoc e) {
270                 throw new IOException JavaDoc("Cannot copy local directory: " +
271                         e.getMessage());
272             }
273         }
274     }
275     
276     /**
277      * delete the directory
278      *
279      * @param dir directory to be deleted
280      * @throws IOException
281      */

282     public static void deleteDirTree(File JavaDoc dir) throws IOException JavaDoc {
283         if (dir == null || !dir.isDirectory())
284             return;
285         File JavaDoc[] filelist = dir.listFiles();
286         try {
287             if (filelist == null) {
288                 if (!dir.delete()) {
289                     throw new IOException JavaDoc("Cannot delete directory: " +
290                             dir.getPath());
291                 }
292                 return;
293             }
294             for (int i = 0; i < filelist.length; i++) {
295                 if (filelist[i].isFile()) {
296                     if (!filelist[i].delete()) {
297                         throw new IOException JavaDoc("Cannot delete file: " +
298                                 filelist[i].getPath());
299                     }
300                 } else if (filelist[i].isDirectory()) {
301                     deleteDirTree(filelist[i]);
302                 }
303             }
304         } catch (Exception JavaDoc e) {
305             throw new IOException JavaDoc("Failed to delete directory: " +
306                     e.getMessage());
307         }
308     }
309     
310     /**
311      * Creates an unique local temp directory.
312      * @return The name of the created directory.
313      * @throws IOException If failed to create such a directory.
314      */

315     public static String JavaDoc createUniqueTmpDir()
316         throws IOException JavaDoc {
317         // Create a unique temp directory.
318
String JavaDoc tempDirPath = null;
319         try {
320             File JavaDoc sysTempDir = new File JavaDoc(System.getProperty("java.io.tmpdir"));
321
322             File JavaDoc tempFile = File.createTempFile("jnlp", "jnlp", sysTempDir);
323
324             tempDirPath = tempFile.getPath();
325             tempFile.delete();
326             tempFile = new File JavaDoc(tempDirPath);
327             tempFile.mkdirs();
328             tempFile.deleteOnExit();
329         } catch (IOException JavaDoc e) {
330             throw new IOException JavaDoc(
331                         "Failed to create a local temp directory: "
332                         + tempDirPath);
333         }
334         return tempDirPath + File.separator;
335     }
336     
337     /**
338      * get all the resource to local according to a remote jnlp file
339      *
340      * @param jnlp remote jnlp file location
341      * @param localBase local directory which stores the resources
342      * @return URL points to the local jnlp file
343      * @throws IOException
344      */

345     protected static URL JavaDoc getRemoteResource(URL JavaDoc jnlp, String JavaDoc localBase)
346             throws IOException JavaDoc {
347         URL JavaDoc localJnlpUrl = null;
348         URL JavaDoc codebase = null;
349         try {
350             LaunchDesc laDesc = LaunchDescFactory.buildDescriptor(jnlp);
351             codebase = laDesc.getCodebase();
352             String JavaDoc jnlpName = jnlp.getFile().substring(
353                     jnlp.getFile().lastIndexOf("/") + 1);
354             File JavaDoc localJnlpFile = new File JavaDoc(localBase +
355                     File.separator + jnlpName);
356             copyRemoteFile(jnlp, localJnlpFile);
357  
358             if (localJnlpFile == null || !localJnlpFile.exists()) {
359                  throw new IOException JavaDoc("Cannot copy remote jnlp file to " +
360                         "local");
361             }
362             localJnlpUrl = localJnlpFile.toURL();
363             
364             InformationDesc infoDesc = laDesc.getInformation();
365             IconDesc[] iconArray = infoDesc.getIcons();
366             for (int i = 0; i < iconArray.length; i++) {
367                 URL JavaDoc iconURL = iconArray[i].getLocation();
368                 urlFile2LocalFile(iconURL, codebase, localBase);
369             }
370             ResourcesDesc reDesc = laDesc.getResources();
371             reDesc.visit(
372                     new JDICPackagerResourceCopyVisitor(codebase, localBase));
373         } catch (Exception JavaDoc e) {
374             throw new IOException JavaDoc("Exception when geting remote resource: " +
375                     e.getMessage());
376         }
377         
378         return localJnlpUrl;
379     }
380
381     /**
382      * Evaluate if the given directory is readable.
383      * @param dirPath The given directory.
384      * @return true If the given file is a valid directory and is readable.
385      */

386     public static boolean isDirectoryReadable(File JavaDoc dirPath) {
387         if (dirPath.isDirectory()) {
388             if (dirPath.canRead()) {
389                 return true;
390             }
391         }
392         return false;
393     }
394
395     /**
396      * Evaluate if the given directory is writable.
397      * @param dirPath The given direcotry to be evaluated.
398      * @return true If the given file is a valid directory and is writableable.
399      */

400     public static boolean isDirectoryWritable(File JavaDoc dirPath) {
401         if (dirPath.isDirectory()) {
402             if (dirPath.canWrite()) {
403                 return true;
404             }
405         }
406         return false;
407     }
408     
409     /**
410      * Evaluate if the given directory is readable.
411      *
412      * @param filePath the given file to be evaluated
413      * @return true is the filePath is readable, otherwise, false
414      */

415     public static boolean isFileReadable(File JavaDoc filePath) {
416         if (filePath.isFile()) {
417             if (filePath.canRead()) {
418                 return true;
419             }
420         }
421         return false;
422     }
423     
424     /**
425      * get the file name without extension
426      *
427      * @param filePath input file
428      * @return filename without extension
429      */

430     public static String JavaDoc getFileNameWithoutExt(File JavaDoc filePath) {
431         if (filePath == null)
432             return null;
433         
434         String JavaDoc fileName = filePath.getName();
435         if (fileName == null)
436             return null;
437         
438         return (fileName.substring(0, fileName.lastIndexOf(".")));
439     }
440 }
441
442 /**
443  * Resource Visitor to copy all the remote resource files to the local base
444  */

445
446 class JDICPackagerResourceCopyVisitor implements ResourceVisitor {
447     private URL JavaDoc codebase = null;
448     private String JavaDoc localBase = null;
449
450     public JDICPackagerResourceCopyVisitor(URL JavaDoc incodebase, String JavaDoc inlocalbase) {
451         codebase = incodebase;
452         localBase = inlocalbase;
453     }
454     public void visitJARDesc(JARDesc jad) {
455         try {
456             FileOperUtility.urlFile2LocalFile(jad.getLocation(),
457                     codebase, localBase);
458         } catch (IOException JavaDoc ioE) {
459             ioE.printStackTrace();
460         }
461     }
462     
463     public void visitExtensionDesc(ExtensionDesc ed) {
464         try {
465 /*
466             FileOperUtility.urlFile2LocalFile(ed.getLocation(),
467                     codebase, localBase);
468 */

469             FileOperUtility.getRemoteResource(ed.getLocation(),
470                     localBase);
471         } catch (IOException JavaDoc ioE) {
472             ioE.printStackTrace();
473         }
474     }
475     
476     public void visitPropertyDesc(PropertyDesc prd) {}
477     
478     public void visitJREDesc(JREDesc jrd) {}
479     
480     public void visitPackageDesc(PackageDesc pad) {}
481 }
482
Popular Tags