KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openide > filesystems > LocalFileSystem


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.openide.filesystems;
21
22 import java.beans.PropertyVetoException JavaDoc;
23 import java.io.File JavaDoc;
24 import java.io.FileInputStream JavaDoc;
25 import java.io.FileNotFoundException JavaDoc;
26 import java.io.FileOutputStream JavaDoc;
27 import java.io.FilterOutputStream JavaDoc;
28 import java.io.IOException JavaDoc;
29 import java.io.InputStream JavaDoc;
30 import java.io.ObjectInputStream JavaDoc;
31 import java.io.ObjectInputValidation JavaDoc;
32 import java.io.OutputStream JavaDoc;
33 import java.io.SyncFailedException JavaDoc;
34 import org.openide.util.NbBundle;
35 import org.openide.util.Utilities;
36
37 /** Local filesystem. Provides access to files on local disk.
38 * <p>For historical reasons many AbstractFileSystem.* methods are implemented
39 * as protected in this class. Do not call them! Subclasses might override
40 * them, or (better) use delegation.
41 */

42 public class LocalFileSystem extends AbstractFileSystem {
43     /** generated Serialized Version UID */
44     private static final long serialVersionUID = -5355566113542272442L;
45
46     /** Controlls the LocalFileSystem's automatic refresh.
47     * If the refresh time interval is set from the System.property, than this value is used.
48     * Otherwise, the refresh time interval is set to 0 which means the refresh
49     * is disabled. */

50     private static final int REFRESH_TIME = Integer.getInteger(
51             "org.openide.filesystems.LocalFileSystem.REFRESH_TIME", 0
52         ).intValue(); // NOI18N
53
private static final int SUCCESS = 0;
54     private static final int FAILURE = 1;
55     private static final int NOT_EXISTS = 3;
56
57     /** root file */
58     private File JavaDoc rootFile = new File JavaDoc("."); // NOI18N
59

60     /** is read only */
61     private boolean readOnly;
62
63     /** Constructor.
64     */

65     public LocalFileSystem() {
66         Impl impl = new Impl(this);
67
68         info = impl;
69         change = impl;
70
71         DefaultAttributes a = new InnerAttrs(this, info, change, impl);
72         attr = a;
73         list = a;
74         setRefreshTime(REFRESH_TIME);
75     }
76
77     /** Constructor. Allows user to provide own capabilities
78     * for this filesystem.
79     * @param cap capabilities for this filesystem
80      * @deprecated Useless.
81     */

82     @Deprecated JavaDoc
83     public LocalFileSystem(FileSystemCapability cap) {
84         this();
85         setCapability(cap);
86     }
87
88     /* Human presentable name */
89     public String JavaDoc getDisplayName() {
90         return rootFile.getAbsolutePath();
91     }
92     
93     @SuppressWarnings JavaDoc("deprecation") // need to set it for compat
94
private void _setSystemName(String JavaDoc s) throws PropertyVetoException JavaDoc {
95         setSystemName(s);
96     }
97
98     /** Set the root directory of the filesystem.
99     * @param r file to set root to
100     * @exception PropertyVetoException if the value if vetoed by someone else (usually
101     * by the {@link org.openide.filesystems.Repository Repository})
102     * @exception IOException if the root does not exists or some other error occured
103     */

104     public synchronized void setRootDirectory(File JavaDoc r) throws PropertyVetoException JavaDoc, IOException JavaDoc {
105         if (!r.exists() || r.isFile()) {
106             FSException.io("EXC_RootNotExist", r.getAbsolutePath()); // NOI18N
107
}
108
109         String JavaDoc oldDisplayName = getDisplayName();
110         _setSystemName(computeSystemName(r));
111
112         rootFile = r;
113
114         firePropertyChange(PROP_ROOT, null, refreshRoot());
115         firePropertyChange(PROP_DISPLAY_NAME, oldDisplayName, getDisplayName());
116     }
117
118     /** Get the root directory of the filesystem.
119      * @return root directory
120     */

121     public File JavaDoc getRootDirectory() {
122         return rootFile;
123     }
124
125     /** Set whether the filesystem should be read only.
126      * @param flag <code>true</code> if it should
127     */

128     public void setReadOnly(boolean flag) {
129         if (flag != readOnly) {
130             readOnly = flag;
131             firePropertyChange(
132                 PROP_READ_ONLY, (!flag) ? Boolean.TRUE : Boolean.FALSE, flag ? Boolean.TRUE : Boolean.FALSE
133             );
134         }
135     }
136
137     /* Test whether filesystem is read only.
138      * @return <true> if filesystem is read only
139      */

140     public boolean isReadOnly() {
141         return readOnly;
142     }
143
144     /** Prepare environment by adding the root directory of the filesystem to the class path.
145     * @param environment the environment to add to
146      * @deprecated Useless.
147     */

148     @Deprecated JavaDoc
149     public void prepareEnvironment(FileSystem.Environment environment) {
150         environment.addClassPath(rootFile.getAbsolutePath());
151     }
152
153     /** Compute the system name of this filesystem for a given root directory.
154     * <P>
155     * The default implementation simply returns the filename separated by slashes.
156     * @see FileSystem#setSystemName
157     * @param rootFile root directory for the filesystem
158     * @return system name for the filesystem
159     */

160     protected String JavaDoc computeSystemName(File JavaDoc rootFile) {
161         String JavaDoc retVal = rootFile.getAbsolutePath().replace(File.separatorChar, '/');
162
163         return ((Utilities.isWindows() || (Utilities.getOperatingSystem() == Utilities.OS_OS2))) ? retVal.toLowerCase()
164                                                                                                  : retVal;
165     }
166
167     //
168
// List
169
//
170
protected String JavaDoc[] children(String JavaDoc name) {
171         File JavaDoc f = getFile(name);
172
173         if (f.isDirectory()) {
174             return f.list();
175         } else {
176             return null;
177         }
178     }
179
180     //
181
// Change
182
//
183
protected void createFolder(String JavaDoc name) throws java.io.IOException JavaDoc {
184         File JavaDoc f = getFile(name);
185
186         if (name.equals("")) { // NOI18N
187
FSException.io("EXC_CannotCreateF", new Object JavaDoc[] { f.getName(), getDisplayName(), f.getAbsolutePath() }); // NOI18N
188
}
189
190         if (f.exists()) {
191             FSException.io(
192                 "EXC_FolderAlreadyExist", new Object JavaDoc[] { f.getName(), getDisplayName(), f.getAbsolutePath() }
193             ); // NOI18N
194
}
195
196         boolean b = createRecursiveFolder(f);
197
198         if (!b) {
199             FSException.io("EXC_CannotCreateF", new Object JavaDoc[] { f.getName(), getDisplayName(), f.getAbsolutePath() }); // NOI18N
200
}
201     }
202
203     /*
204     * @return true if RefreshAction should be enabled
205     */

206     boolean isEnabledRefreshFolder() {
207         return true;
208     }
209
210     /** Creates new folder and all necessary subfolders
211     * @param f folder to create
212     * @return <code>true</code> if the file exists when returning from this method
213     */

214     private static boolean createRecursiveFolder(File JavaDoc f) {
215         if (f.exists()) {
216             return true;
217         }
218
219         if (!f.isAbsolute()) {
220             f = f.getAbsoluteFile();
221         }
222
223         String JavaDoc par = f.getParent();
224
225         if (par == null) {
226             return false;
227         }
228
229         if (!createRecursiveFolder(new File JavaDoc(par))) {
230             return false;
231         }
232
233         f.mkdir();
234
235         return f.exists();
236     }
237
238     protected void createData(String JavaDoc name) throws IOException JavaDoc {
239         File JavaDoc f = getFile(name);
240         boolean isError = true;
241         IOException JavaDoc creationException = null;
242         String JavaDoc annotationMsg = null;
243
244         try {
245             isError = f.createNewFile() ? false : true;
246             isError = isError ? true : (!f.exists());
247
248             if (isError) {
249                 Object JavaDoc[] msgParams;
250                 msgParams = new Object JavaDoc[] { f.getName(), getDisplayName(), f.getAbsolutePath() };
251
252                 annotationMsg = NbBundle.getMessage(LocalFileSystem.class, "EXC_DataAlreadyExist", msgParams); //NOI18N
253
creationException = new SyncFailedException JavaDoc(annotationMsg);
254             }
255         } catch (IOException JavaDoc iex) {
256             isError = true;
257             creationException = iex;
258             annotationMsg = iex.getLocalizedMessage();
259         }
260
261         if (isError) {
262             ExternalUtil.annotate(creationException, annotationMsg);
263             throw creationException;
264         }
265     }
266
267     protected void rename(String JavaDoc oldName, String JavaDoc newName)
268     throws IOException JavaDoc {
269         File JavaDoc of = getFile(oldName);
270         File JavaDoc nf = getFile(newName);
271
272         // #7086 - (nf.exists() && !nf.equals(of)) instead of nf.exists() - fix for Win32
273
if ((nf.exists() && !nf.equals(of)) || !of.renameTo(nf)) {
274             FSException.io("EXC_CannotRename", oldName, getDisplayName(), newName); // NOI18N
275
}
276     }
277
278     protected void delete(String JavaDoc name) throws IOException JavaDoc {
279         File JavaDoc file = getFile(name);
280
281         if (deleteFile(file) != SUCCESS) {
282             if (file.exists()) {
283                 FSException.io("EXC_CannotDelete", name, getDisplayName(), file.getAbsolutePath()); // NOI18N
284
} else {
285                 /** When file externaly deleted and fo.delete () is called before
286                  periodical refresh */

287                 FileObject thisFo = findResource(name);
288
289                 if (thisFo != null) {
290                     if (thisFo.getParent() != null) {
291                         thisFo.getParent().refresh();
292                     }
293
294                     thisFo.refresh();
295
296                     if (thisFo.isValid()) {
297                         FSException.io("EXC_CannotDelete", name, getDisplayName(), file.getAbsolutePath()); // NOI18N
298
}
299                 }
300             }
301         }
302     }
303
304     /** Method that recursivelly deletes all files in a folder.
305     * @return true if successful
306     */

307     private static int deleteFile(File JavaDoc file) {
308         boolean ret = file.delete();
309
310         if (ret) {
311             return SUCCESS;
312         }
313
314         if (!file.exists()) {
315             return NOT_EXISTS;
316         }
317
318         if (file.isDirectory()) {
319             // first of all delete whole content
320
File JavaDoc[] arr = file.listFiles();
321
322             for (int i = 0; i < arr.length; i++) {
323                 if (deleteFile(arr[i]) != SUCCESS) {
324                     return FAILURE;
325                 }
326             }
327         }
328
329         // delete the file itself
330
return (file.delete() ? SUCCESS : FAILURE);
331     }
332
333     //
334
// Info
335
//
336
protected java.util.Date JavaDoc lastModified(String JavaDoc name) {
337         return new java.util.Date JavaDoc(getFile(name).lastModified());
338     }
339
340     protected boolean folder(String JavaDoc name) {
341         return getFile(name).isDirectory();
342     }
343
344     protected boolean readOnly(String JavaDoc name) {
345         File JavaDoc f = getFile(name);
346
347         return !f.canWrite() && f.exists();
348     }
349
350     protected String JavaDoc mimeType(String JavaDoc name) {
351         return null;
352     }
353
354     protected long size(String JavaDoc name) {
355         return getFile(name).length();
356     }
357
358     // ===============================================================================
359
// This part of code could be used for monitoring of closing file streams.
360

361     /* public static java.util.HashMap openedIS = new java.util.HashMap();
362       public static java.util.HashMap openedOS = new java.util.HashMap();
363
364       static class DebugIS extends FileInputStream {
365         public DebugIS(File f) throws java.io.FileNotFoundException { super(f); }
366         public void close() throws IOException { openedIS.remove(this); super.close(); }
367       };
368
369       static class DebugOS extends FileOutputStream {
370         public DebugOS(File f) throws java.io.IOException { super(f); }
371         public void close() throws IOException { openedOS.remove(this); super.close(); }
372       };
373
374       public InputStream inputStream (String name) throws java.io.FileNotFoundException {
375         DebugIS is = new DebugIS(getFile(name));
376         openedIS.put(is, new Exception());
377         return is;
378       }
379
380       public OutputStream outputStream (String name) throws java.io.IOException {
381         DebugOS os = new DebugOS(getFile(name));
382         openedOS.put(os, new Exception());
383         return os;
384       }*/

385
386     // End of the debug part
387
// ============================================================================
388
// Begin of the original part
389
protected InputStream JavaDoc inputStream(String JavaDoc name) throws java.io.FileNotFoundException JavaDoc {
390         FileInputStream JavaDoc fis;
391         File JavaDoc file = null;
392
393         try {
394             fis = new FileInputStream JavaDoc(file = getFile(name));
395         } catch (FileNotFoundException JavaDoc exc) {
396             if ((file == null) || !file.exists()) {
397                 ExternalUtil.annotate(exc, NbBundle.getMessage(LocalFileSystem.class, "EXC_FileOutsideModified"));
398             }
399
400             throw exc;
401         }
402
403         return fis;
404     }
405
406     protected OutputStream JavaDoc outputStream(final String JavaDoc name)
407     throws java.io.IOException JavaDoc {
408         OutputStream JavaDoc retVal = new FileOutputStream JavaDoc(getFile(name));
409
410         // workaround for #42624
411
if (Utilities.isMac()) {
412             retVal = getOutputStreamForMac42624(retVal, name);
413         }
414
415         return retVal;
416     }
417
418     private OutputStream JavaDoc getOutputStreamForMac42624(final OutputStream JavaDoc originalStream, final String JavaDoc name) {
419         final File JavaDoc f = getFile(name);
420         final long lModified = f.lastModified();
421         OutputStream JavaDoc retVal = new FilterOutputStream JavaDoc(originalStream) {
422                 public void close() throws IOException JavaDoc {
423                     super.close();
424
425                     if ((f.length() == 0) && (f.lastModified() == lModified)) {
426                         f.setLastModified(System.currentTimeMillis());
427                     }
428                 }
429             };
430
431         return retVal;
432     }
433
434     // End of the original part
435
// ============================================================================
436
protected void lock(String JavaDoc name) throws IOException JavaDoc {
437         File JavaDoc file = getFile(name);
438
439         if ((!file.canWrite() && file.exists()) || isReadOnly()) {
440             FSException.io("EXC_CannotLock", name, getDisplayName(), file.getAbsolutePath()); // NOI18N
441
}
442     }
443
444     protected void unlock(String JavaDoc name) {
445     }
446
447     protected void markUnimportant(String JavaDoc name) {
448     }
449
450     /** Creates file for given string name.
451     * @param name the name
452     * @return the file
453     */

454     private File JavaDoc getFile(String JavaDoc name) {
455         // XXX should this be name.replace('/', File.separatorChar)? Cf. BT #4745638.
456
return new File JavaDoc(rootFile, name);
457     }
458
459     /**
460     * @param in the input stream to read from
461     * @exception IOException error during read
462     * @exception ClassNotFoundException when class not found
463     */

464     private void readObject(java.io.ObjectInputStream JavaDoc in)
465     throws java.io.IOException JavaDoc, java.lang.ClassNotFoundException JavaDoc {
466         in.defaultReadObject();
467
468         in.registerValidation(
469             new ObjectInputValidation JavaDoc() {
470                 public void validateObject() {
471                     if (attr.getClass() == DefaultAttributes.class) {
472                         Impl impl = new Impl(LocalFileSystem.this);
473                         attr = new InnerAttrs(LocalFileSystem.this, impl, impl, impl);
474                     }
475                 }
476             }, 0
477         );
478     }
479
480     /** The implementation class that implements List, Info
481     * and Change interfaces and delegates all the methods
482     * to appropriate methods of LocalFileSystem.
483     */

484     public static class Impl extends Object JavaDoc implements AbstractFileSystem.List, AbstractFileSystem.Info,
485         AbstractFileSystem.Change {
486         /** generated Serialized Version UID */
487         static final long serialVersionUID = -8432015909317698511L;
488
489         /** pointer to local filesystem */
490         private LocalFileSystem fs;
491
492         /** Pointer to local filesystem
493         * @param fs the filesystem this impl is connected to
494         */

495         public Impl(LocalFileSystem fs) {
496             this.fs = fs;
497         }
498
499         /*
500         *
501         * Scans children for given name
502         */

503         public String JavaDoc[] children(String JavaDoc name) {
504             return fs.children(name);
505         }
506
507         //
508
// Change
509
//
510

511         /*
512         * Creates new folder named name.
513         * @param name name of folder
514         * @throws IOException if operation fails
515         */

516         public void createFolder(String JavaDoc name) throws java.io.IOException JavaDoc {
517             fs.createFolder(name);
518         }
519
520         /*
521         * Create new data file.
522         *
523         * @param name name of the file
524         *
525         * @return the new data file object
526         * @exception IOException if the file cannot be created (e.g. already exists)
527         */

528         public void createData(String JavaDoc name) throws IOException JavaDoc {
529             fs.createData(name);
530         }
531
532         /*
533         * Renames a file.
534         *
535         * @param oldName old name of the file
536         * @param newName new name of the file
537         */

538         public void rename(String JavaDoc oldName, String JavaDoc newName)
539         throws IOException JavaDoc {
540             fs.rename(oldName, newName);
541         }
542
543         /*
544         * Delete the file.
545         *
546         * @param name name of file
547         * @exception IOException if the file could not be deleted
548         */

549         public void delete(String JavaDoc name) throws IOException JavaDoc {
550             fs.delete(name);
551         }
552
553         //
554
// Info
555
//
556

557         /*
558         *
559         * Get last modification time.
560         * @param name the file to test
561         * @return the date
562         */

563         public java.util.Date JavaDoc lastModified(String JavaDoc name) {
564             return fs.lastModified(name);
565         }
566
567         /*
568         * Test if the file is folder or contains data.
569         * @param name name of the file
570         * @return true if the file is folder, false otherwise
571         */

572         public boolean folder(String JavaDoc name) {
573             return fs.folder(name);
574         }
575
576         /*
577         * Test whether this file can be written to or not.
578         * @param name the file to test
579         * @return <CODE>true</CODE> if file is read-only
580         */

581         public boolean readOnly(String JavaDoc name) {
582             return fs.readOnly(name);
583         }
584
585         /*
586         * Get the MIME type of the file.
587         * Uses {@link FileUtil#getMIMEType}.
588         *
589         * @param name the file to test
590         * @return the MIME type textual representation, e.g. <code>"text/plain"</code>
591         */

592         public String JavaDoc mimeType(String JavaDoc name) {
593             return fs.mimeType(name);
594         }
595
596         /*
597         * Get the size of the file.
598         *
599         * @param name the file to test
600         * @return the size of the file in bytes or zero if the file does not contain data (does not
601         * exist or is a folder).
602         */

603         public long size(String JavaDoc name) {
604             return fs.size(name);
605         }
606
607         /*
608         * Get input stream.
609         *
610         * @param name the file to test
611         * @return an input stream to read the contents of this file
612         * @exception FileNotFoundException if the file does not exists or is invalid
613         */

614         public InputStream JavaDoc inputStream(String JavaDoc name) throws java.io.FileNotFoundException JavaDoc {
615             return fs.inputStream(name);
616         }
617
618         /*
619         * Get output stream.
620         *
621         * @param name the file to test
622         * @return output stream to overwrite the contents of this file
623         * @exception IOException if an error occures (the file is invalid, etc.)
624         */

625         public OutputStream JavaDoc outputStream(String JavaDoc name) throws java.io.IOException JavaDoc {
626             return fs.outputStream(name);
627         }
628
629         /*
630         * Does nothing to lock the file.
631         *
632         * @param name name of the file
633         */

634         public void lock(String JavaDoc name) throws IOException JavaDoc {
635             fs.lock(name);
636         }
637
638         /*
639         * Does nothing to unlock the file.
640         *
641         * @param name name of the file
642         */

643         public void unlock(String JavaDoc name) {
644             fs.unlock(name);
645         }
646
647         /*
648         * Does nothing to mark the file as unimportant.
649         *
650         * @param name the file to mark
651         */

652         public void markUnimportant(String JavaDoc name) {
653             fs.markUnimportant(name);
654         }
655     }
656
657     /** This class adds new virtual attribute "java.io.File".
658      * Because of the fact that FileObjects of LocalFileSystem are convertable
659      * to java.io.File by means of attributes. */

660     private static class InnerAttrs extends DefaultAttributes {
661         static final long serialVersionUID = 1257351369229921993L;
662         LocalFileSystem lfs;
663
664         public InnerAttrs(
665             LocalFileSystem lfs, AbstractFileSystem.Info info, AbstractFileSystem.Change change,
666             AbstractFileSystem.List list
667         ) {
668             super(info, change, list);
669             this.lfs = lfs;
670         }
671
672         public Object JavaDoc readAttribute(String JavaDoc name, String JavaDoc attrName) {
673             if (attrName.equals("java.io.File")) { // NOI18N
674

675                 return lfs.getFile(name);
676             }
677
678             return super.readAttribute(name, attrName);
679         }
680     }
681 }
682
Popular Tags