KickJava   Java API By Example, From Geeks To Geeks.

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


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.ByteArrayInputStream JavaDoc;
24 import java.io.ByteArrayOutputStream JavaDoc;
25 import java.io.IOException JavaDoc;
26 import java.io.InputStream JavaDoc;
27 import java.io.OutputStream JavaDoc;
28 import java.lang.ref.Reference JavaDoc;
29 import java.util.Collections JavaDoc;
30 import java.util.Date JavaDoc;
31 import java.util.Enumeration JavaDoc;
32 import java.util.HashMap JavaDoc;
33 import java.util.HashSet JavaDoc;
34 import java.util.Iterator JavaDoc;
35 import java.util.Map JavaDoc;
36 import java.util.Set JavaDoc;
37 import java.util.concurrent.ConcurrentHashMap JavaDoc;
38 import java.util.logging.Level JavaDoc;
39 import java.util.logging.Logger JavaDoc;
40
41 /**
42  * Simple implementation of memory file system.
43  * @author Jaroslav Tulach
44  */

45 final class MemoryFileSystem extends AbstractFileSystem implements AbstractFileSystem.Info, AbstractFileSystem.Change, AbstractFileSystem.List, AbstractFileSystem.Attr {
46     private static final Logger JavaDoc ERR = Logger.getLogger(MemoryFileSystem.class.getName());
47     
48     /** time when the filesystem was created. It is supposed to be the default
49      * time of modification for all resources that has not been modified yet
50      */

51     private java.util.Date JavaDoc created = new java.util.Date JavaDoc();
52
53     /** maps String to Entry */
54     private Map JavaDoc<String JavaDoc, Entry> entries = initEntry();
55     
56     @SuppressWarnings JavaDoc("deprecation") // need to set it for compat
57
private void _setSystemName(String JavaDoc s) throws PropertyVetoException JavaDoc {
58         setSystemName(s);
59     }
60
61     /** Creates new MemoryFS */
62     public MemoryFileSystem() {
63         attr = this;
64         list = this;
65         change = this;
66         info = this;
67
68         
69         try {
70             _setSystemName("MemoryFileSystem" + String.valueOf(System.identityHashCode(this)));
71         } catch (PropertyVetoException JavaDoc ex) {
72             ex.printStackTrace();
73         }
74     }
75
76     /** Creates MemoryFS with data */
77     public MemoryFileSystem(String JavaDoc[] resources) {
78         this();
79
80         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
81
82         for (int i = 0; i < resources.length; i++) {
83             sb.append(resources[i]);
84
85             if (resources[i].endsWith("/")) {
86                 // folder
87
getOrCreateEntry(resources[i]).data = null;
88             } else {
89                 getOrCreateEntry(resources[i]).data = new byte[0];
90             }
91         }
92     }
93
94     /** finds entry for given name */
95     private Entry getOrCreateEntry(String JavaDoc n) {
96         if ((n.length() > 0) && (n.charAt(0) == '/')) {
97             n = n.substring(1);
98         }
99
100         boolean isValidEntry = isValidEntry(n);
101         synchronized(entries) {
102             Entry x = entries.get(n);
103
104             if (x == null || !isValidEntry) {
105                 x = new Entry(n);
106                 entries.put(n, x);
107             }
108         
109             return x;
110         }
111     }
112
113     
114
115     private boolean isValidEntry(String JavaDoc n) {
116     return isValidEntry(n, null);
117     }
118     
119     /** finds whether there already is this name */
120     private boolean isValidEntry(String JavaDoc n, Boolean JavaDoc expectedResult) {
121         boolean retval = (n.length() == 0) ? true : false;
122         
123         if ((n.length() > 0) && (n.charAt(0) == '/')) {
124             n = n.substring(1);
125         }
126
127         Entry x = entries.get(n);
128     FileObject fo = null;
129         
130         if (x != null) {
131             Reference JavaDoc ref = findReference(n);
132             if (ref != null) {
133                 fo = (FileObject)ref.get();
134                 retval = (fo != null) ? fo.isValid() : true;
135             }
136         }
137
138     if (ERR.isLoggable(Level.FINE) && expectedResult != null && retval != expectedResult.booleanValue()) {
139         logMessage("entry: " + x + " isValidReference.fo: " + ((fo == null) ? "null" : //NOI18N
140
(fo.isValid() ? "valid" : "invalid")));//NOI18N
141
}
142     
143         return (retval);
144     }
145
146     public String JavaDoc getDisplayName() {
147         return "MemoryFileSystem";
148     }
149
150     public boolean isReadOnly() {
151         return false;
152     }
153
154     public Enumeration JavaDoc<String JavaDoc> attributes(String JavaDoc name) {
155         if (!isValidEntry(name)) {
156             return org.openide.util.Enumerations.empty();
157         }
158         return Collections.enumeration(getOrCreateEntry(name).attrs.keySet());
159     }
160
161     public String JavaDoc[] children(String JavaDoc f) {
162         if ((f.length() > 0) && (f.charAt(0) == '/')) {
163             f = f.substring(1);
164         }
165
166         if ((f.length() > 0) && !f.endsWith("/")) {
167             f = f + "/";
168         }
169
170         Set JavaDoc<String JavaDoc> l = new HashSet JavaDoc<String JavaDoc>();
171
172         //System.out.println("Folder: " + f);
173
synchronized(entries) {
174             Iterator JavaDoc it = entries.keySet().iterator();
175
176             while (it.hasNext()) {
177                 String JavaDoc name = (String JavaDoc) it.next();
178
179                 if (name.startsWith(f) || (f.trim().length() == 0)) {
180                     int i = name.indexOf('/', f.length());
181                     String JavaDoc child = null;
182
183                     if (i > 0) {
184                         child = name.substring(f.length(), i);
185                     } else {
186                         child = name.substring(f.length());
187                     }
188
189                     if (child.trim().length() > 0) {
190                         l.add(child);
191                     }
192                 }
193             }
194
195             return l.toArray(new String JavaDoc[0]);
196         }
197     }
198
199     public void createData(String JavaDoc name) throws IOException JavaDoc {
200         if (isValidEntry(name, Boolean.FALSE)) {
201         StringBuffer JavaDoc message = new StringBuffer JavaDoc();
202         message.append("File already exists: ").append(name);
203             throw new IOException JavaDoc(message.toString());//NOI18N
204
}
205
206         getOrCreateEntry(name).data = new byte[0];
207     }
208
209     public void createFolder(String JavaDoc name) throws java.io.IOException JavaDoc {
210         if (isValidEntry(name, Boolean.FALSE)) {
211         StringBuffer JavaDoc message = new StringBuffer JavaDoc();
212         message.append("Folder already exists: ").append(name);
213             throw new IOException JavaDoc(message.toString());//NOI18N
214
}
215
216         getOrCreateEntry(name).data = null;
217     }
218
219     public void delete(String JavaDoc name) throws IOException JavaDoc {
220         if (entries.remove(name) == null) {
221             throw new IOException JavaDoc("No file to delete: " + name); // NOI18N
222
}
223     }
224
225     public void deleteAttributes(String JavaDoc name) {
226     }
227
228     public boolean folder(String JavaDoc name) {
229         return getOrCreateEntry(name).data == null;
230     }
231
232     public InputStream JavaDoc inputStream(String JavaDoc name) throws java.io.FileNotFoundException JavaDoc {
233         byte[] arr = getOrCreateEntry(name).data;
234
235         if (arr == null) {
236             arr = new byte[0];
237         }
238
239         return new ByteArrayInputStream JavaDoc(arr);
240     }
241
242     public java.util.Date JavaDoc lastModified(String JavaDoc name) {
243         java.util.Date JavaDoc d = getOrCreateEntry(name).last;
244
245         return (d == null) ? created : d;
246     }
247
248     public void lock(String JavaDoc name) throws IOException JavaDoc {
249     }
250
251     public void markUnimportant(String JavaDoc name) {
252     }
253
254     public String JavaDoc mimeType(String JavaDoc name) {
255         return (String JavaDoc) getOrCreateEntry(name).attrs.get("mimeType");
256     }
257
258     public OutputStream JavaDoc outputStream(final String JavaDoc name)
259     throws java.io.IOException JavaDoc {
260         class Out extends ByteArrayOutputStream JavaDoc {
261             public void close() throws IOException JavaDoc {
262                 super.close();
263
264                 getOrCreateEntry(name).data = toByteArray();
265                 getOrCreateEntry(name).last = new Date JavaDoc();
266             }
267         }
268
269         return new Out();
270     }
271
272     public Object JavaDoc readAttribute(String JavaDoc name, String JavaDoc attrName) {
273         return isValidEntry(name) ? getOrCreateEntry(name).attrs.get(attrName) : null;
274     }
275
276     public boolean readOnly(String JavaDoc name) {
277         return false;
278     }
279
280     public void rename(String JavaDoc oldName, String JavaDoc newName)
281     throws IOException JavaDoc {
282         if (!isValidEntry(oldName)) {
283             throw new IOException JavaDoc("The file to rename does not exist.");
284         }
285
286         if (isValidEntry(newName)) {
287             throw new IOException JavaDoc("Cannot rename to existing file");
288         }
289
290         if ((newName.length() > 0) && (newName.charAt(0) == '/')) {
291             newName = newName.substring(1);
292         }
293
294         Entry e = getOrCreateEntry(oldName);
295         entries.remove(oldName);
296         entries.put(newName, e);
297     }
298
299     public void renameAttributes(String JavaDoc oldName, String JavaDoc newName) {
300     }
301
302     public long size(String JavaDoc name) {
303         byte[] d = getOrCreateEntry(name).data;
304
305         return (d == null) ? 0 : d.length;
306     }
307
308     public void unlock(String JavaDoc name) {
309     }
310
311     public void writeAttribute(String JavaDoc name, String JavaDoc attrName, Object JavaDoc value)
312     throws IOException JavaDoc {
313         getOrCreateEntry(name).attrs.put(attrName, value);
314     }
315
316     private Map JavaDoc<String JavaDoc, Entry> initEntry() {
317         if (!ERR.isLoggable(Level.FINE)) {
318             return new ConcurrentHashMap JavaDoc<String JavaDoc, MemoryFileSystem.Entry>();
319         }
320
321     return new ConcurrentHashMap JavaDoc<String JavaDoc, MemoryFileSystem.Entry>() {
322         public MemoryFileSystem.Entry get(String JavaDoc key) {
323         MemoryFileSystem.Entry retval = super.get(key);
324         logMessage("called: GET" + " key: "+key + " result: " + retval);//NOI18N
325
return retval;
326         }
327
328         public MemoryFileSystem.Entry put(String JavaDoc key, MemoryFileSystem.Entry value) {
329         MemoryFileSystem.Entry retval = super.put(key, value);
330         logMessage("called: PUT" + " key: "+key + " value: "+value+ " result: " + retval);//NOI18N
331
return retval;
332         }
333
334         public MemoryFileSystem.Entry remove(String JavaDoc key) {
335         MemoryFileSystem.Entry retval = super.remove(key);
336         logMessage("called: REMOVE" + " key: "+key + " result: " + retval);//NOI18N
337
return retval;
338         }
339     };
340     }
341     
342     static final class Entry {
343         /** String, Object */
344         public Map JavaDoc<String JavaDoc, Object JavaDoc> attrs = new HashMap JavaDoc<String JavaDoc, Object JavaDoc>();
345         public byte[] data;
346         public java.util.Date JavaDoc last;
347     private final String JavaDoc entryName;
348
349     Entry(String JavaDoc entryName) {
350         this.entryName = entryName;
351     }
352     
353
354     public String JavaDoc toString() {
355         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
356         sb.append(" [").append(entryName);//NOI18N
357
sb.append(" -> ").append(super.toString());//NOI18N
358
sb.append("] ");
359         return sb.toString();
360     }
361     }
362     
363     
364     private static void logMessage(final String JavaDoc message) {
365         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
366         sb.append(" -> ").append(message);
367
368         //ucomment if necessary
369
/*ByteArrayOutputStream bos = new ByteArrayOutputStream();
370         PrintWriter pw = new PrintWriter(bos);
371         new Exception().printStackTrace(pw);
372         pw.close();
373         sb.append(bos.toString());
374          */

375         ERR.fine(sb.toString());
376     }
377     
378 }
379
Popular Tags