KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openide > loaders > DataFolderTest


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.loaders;
21
22 import org.openide.filesystems.*;
23
24 import java.beans.*;
25 import java.io.File JavaDoc;
26 import java.io.IOException JavaDoc;
27 import java.util.ArrayList JavaDoc;
28 import java.util.Arrays JavaDoc;
29
30 import org.netbeans.junit.*;
31
32 /** Test recognition of objects in folders, and folder ordering.
33  *
34  * @author Vita Stejskal, Jesse Glick
35  */

36 public class DataFolderTest extends LoggingTestCaseHid {
37     private ArrayList JavaDoc hold = new ArrayList JavaDoc();
38
39     /** Creates new DataFolderTest */
40     public DataFolderTest (String JavaDoc name) {
41         super (name);
42     }
43
44     protected void setUp () throws Exception JavaDoc {
45         clearWorkDir ();
46     }
47     
48     public void testPossibleToCallFindDataObjectDirectly () throws Exception JavaDoc {
49         String JavaDoc fsstruct [] = new String JavaDoc [] {
50             "AA/",
51         };
52         
53         FileSystem lfs = TestUtilHid.createLocalFileSystem(getWorkDir(), fsstruct);
54
55         FileObject fo = lfs.findResource ("AA");
56         DataObject df = DataLoaderPool.getFolderLoader().findDataObject(fo, new DataLoader.RecognizedFiles () {
57             public void markRecognized (FileObject fo) {
58             }
59         });
60         
61         assertEquals ("Found the right one", fo, df.getPrimaryFile());
62     }
63     
64     /** Tests whether children are updated immediately.
65      */

66     public void testChildren () throws Exception JavaDoc {
67         String JavaDoc fsstruct [] = new String JavaDoc [] {
68             "AA/",
69         };
70         
71         TestUtilHid.destroyLocalFileSystem (getName());
72         FileSystem lfs = TestUtilHid.createLocalFileSystem(getWorkDir(), fsstruct);
73
74         
75         DataFolder df = DataFolder.findFolder (lfs.findResource ("AA"));
76         
77         if (df.getChildren ().length != 0) {
78             fail ("Children are not empty");
79         }
80         
81         FileObject fo = df.getPrimaryFile ().createData ("X.instance");
82         
83         DataObject[] arr = df.getChildren ();
84         if (arr.length != 1) {
85             fail ("Children does not contain one element but " + arr.length);
86         }
87         
88         if (!fo.equals (arr[0].getPrimaryFile ())) {
89             fail ("Primary file of only element is diffent");
90         }
91         
92         fo.delete ();
93         
94         if (arr[0].isValid ()) {
95             fail ("The element is still valid even fileobject has been deleted");
96         }
97         
98         arr = df.getChildren ();
99         if (arr.length != 0) {
100             fail ("Still there is something in children - length is " + arr.length);
101         }
102     }
103     
104     /** Tests whether children are gced if not needed. This test
105      * uses getNodeDelegate to obtain the children - if we use
106      * regular DataFolder.getChildren issue #30153 did not occur.
107      */

108     public void testChildrenAreGCed () throws Exception JavaDoc {
109         String JavaDoc fsstruct [] = new String JavaDoc [] {
110             "AA/",
111             "AA/a.txt",
112             "AA/b.txt"
113         };
114         FileSystem lfs = TestUtilHid.createLocalFileSystem(getWorkDir(), fsstruct);
115
116         DataFolder df = DataFolder.findFolder (lfs.findResource ("AA"));
117         java.lang.ref.WeakReference JavaDoc wr[] = new java.lang.ref.WeakReference JavaDoc[2];
118         
119         hold.add(df);
120         hold.add(lfs);
121         
122         
123         org.openide.nodes.Node [] na = df.getNodeDelegate().getChildren().getNodes(true);
124         wr[0] = new java.lang.ref.WeakReference JavaDoc(na[0].getCookie(DataObject.class));
125         wr[1] = new java.lang.ref.WeakReference JavaDoc(na[1].getCookie(DataObject.class));
126         na = null;
127         assertGC("First object can go away", wr[0]);
128         assertGC("Second object can go away", wr[1]);
129     }
130     
131     /** Tests whether children are updated immediatelly.
132      */

133     public void testAddToChildren () throws Exception JavaDoc {
134         String JavaDoc fsstruct [] = new String JavaDoc [] {
135             "AA/",
136         };
137         
138         FileSystem lfs = TestUtilHid.createLocalFileSystem(getWorkDir(), fsstruct);
139
140         
141         DataFolder df = DataFolder.findFolder (lfs.findResource ("AA"));
142
143         int expected = 0;
144         int count = 5;
145         while (count-- > 0) {
146         
147             int len = df.getChildren ().length;
148             if (len != expected) {
149                 fail ("Children are not of size: " + expected + " but " + len);
150             }
151         
152             FileObject fo = df.getPrimaryFile ().createData ("X" + expected + ".instance");
153         
154             DataObject[] arr = df.getChildren ();
155             
156             expected++;
157             
158             if (arr.length != expected) {
159                 fail ("Children does not contain " + expected + "element(s) but " + arr.length);
160             }
161         
162             DataObject last = arr[expected - 1];
163             FileObject prim = last.getPrimaryFile ();
164             if (!fo.equals (prim)) {
165                 fail ("Primary file of " + last + " is diffent than " + fo);
166             }
167         }
168     }
169     
170     /** Tests whether children are updated immediatelly.
171      */

172     public void testOrderInAtomicAction () throws Exception JavaDoc {
173         String JavaDoc fsstruct [] = new String JavaDoc [] {
174             "AA/",
175         };
176         
177         TestUtilHid.destroyLocalFileSystem (getName());
178         FileSystem lfs = TestUtilHid.createLocalFileSystem(getWorkDir(), fsstruct);
179
180         
181         DataFolder df = DataFolder.findFolder (lfs.findResource ("AA"));
182
183         int expected = 0;
184         int count = 5;
185         while (count-- > 0) {
186             class Code implements FileSystem.AtomicAction {
187                 private DataFolder folder;
188                 private int cnt;
189                 
190                 private DataObject[] origArr;
191                 private DataObject[] desireArr;
192                 
193                 
194                 public Code (DataFolder folder, int cnt) {
195                     this.folder = folder;
196                     this.cnt = cnt;
197                 }
198                 
199                 public void init () {
200                     origArr = folder.getChildren ();
201                     
202                     if (origArr.length != cnt) {
203                         fail ("Unexpected length " + cnt + " != " + Arrays.asList (origArr));
204                     }
205                 }
206                 
207                 public void run () throws IOException JavaDoc {
208                     DataObject obj = InstanceDataObject.create (folder, "X" + cnt, Object JavaDoc.class);
209                     
210                     // the children should still remain unchanged
211
DataObject[] currArr = folder.getChildren ();
212                     assertChildrenArrays ("After create", origArr, currArr, true);
213                     
214                     ArrayList JavaDoc arr = new ArrayList JavaDoc (currArr.length + 1);
215                     arr.add (obj);
216                     arr.addAll (Arrays.asList (currArr));
217                     desireArr = (DataObject[])arr.toArray (new DataObject[0]);
218                     
219                     folder.setOrder (desireArr);
220                     
221                     // should not be changed, still
222
DataObject[] afterArr = folder.getChildren ();
223                     assertChildrenArrays ("End of atomic", afterArr, origArr, true);
224                 }
225                     
226                 
227                 public void check () {
228                     DataObject[] currArr = folder.getChildren ();
229                     assertChildrenArrays ("After atomic", desireArr, currArr, true);
230                 }
231                 
232             }
233             
234             Code code = new Code (df, expected++);
235             code.init ();
236             df.getPrimaryFile().getFileSystem ().runAtomicAction (code);
237             code.check ();
238         }
239     }
240     
241     /** Testing order of folder. Needed in order to survive switching of
242      * layers on system filesystem.
243      */

244     public void testOrderWhenAttributeIsChanged () throws Exception JavaDoc {
245 // if (System.getProperty("netbeans.user") == null)
246
// fail("Test can't run in this environment, use -Dxtest.mode=ide");
247

248         String JavaDoc fsstruct [] = new String JavaDoc [] {
249             "AA/AAA/",
250             "AA/BBB/",
251             "AA/CCC/"
252         };
253         
254         TestUtilHid.destroyLocalFileSystem (getName());
255         FileSystem lfs = TestUtilHid.createLocalFileSystem(getWorkDir(), fsstruct);
256
257         
258         DataFolder df = DataFolder.findFolder (lfs.findResource ("AA"));
259         DataObject[] arr = df.getChildren ();
260
261         String JavaDoc append = "";
262         StringBuffer JavaDoc sb = new StringBuffer JavaDoc (255);
263         for (int i = arr.length - 1; i >= 0; i--) {
264             sb.append (append);
265             sb.append (arr[i].getPrimaryFile ().getNameExt ());
266             append = "/";
267         }
268         
269         OrderListener l = new OrderListener();
270         df.addPropertyChangeListener(l);
271         
272         // set order attribute
273
df.getPrimaryFile ().setAttribute (DataFolder.EA_ORDER, sb.toString ());
274         
275         assertTrue(l.gotSomething());
276         
277         assertChildrenArrays ("", arr, df.getChildren (), false);
278     }
279     
280     private static final class OrderListener implements PropertyChangeListener {
281         public int count = 0;
282         public synchronized void propertyChange(PropertyChangeEvent ev) {
283             if (DataFolder.PROP_CHILDREN.equals(ev.getPropertyName())) {
284                 count++;
285                 notifyAll();
286             }
287         }
288         public synchronized boolean gotSomething() throws InterruptedException JavaDoc {
289             if (count > 0) return true;
290             wait(3000);
291             return count > 0;
292         }
293     }
294     
295     public void testOrderWhenSet () throws Exception JavaDoc {
296         String JavaDoc fsstruct [] = new String JavaDoc [] {
297             "AA/AAA/",
298             "AA/BBB/",
299             "AA/CCC/"
300         };
301         
302         TestUtilHid.destroyLocalFileSystem (getName());
303         FileSystem lfs = TestUtilHid.createLocalFileSystem(getWorkDir(), fsstruct);
304
305         
306         DataFolder df = DataFolder.findFolder (lfs.findResource ("AA"));
307         DataObject[] arr = df.getChildren ();
308         DataObject[] rev = new DataObject [arr.length];
309         
310         for (int i = 0; i < arr.length; i++) {
311             rev [arr.length - 1 - i] = arr [i];
312         }
313
314         OrderListener l = new OrderListener();
315         df.addPropertyChangeListener(l);
316         
317         // set new order
318
df.setOrder (rev);
319         
320         assertTrue(l.gotSomething());
321         
322         assertChildrenArrays ("", arr, df.getChildren (), false);
323     }
324
325     public void testOrderWhenMultiFileSystemSetDelegatesIsCalled () throws Exception JavaDoc {
326         String JavaDoc fsstruct [] = new String JavaDoc [] {
327             "AA/AAA/",
328             "AA/BBB/",
329             "AA/CCC/"
330         };
331
332         FileSystem lfsA = TestUtilHid.createLocalFileSystem(new File JavaDoc(getWorkDir(), "A"), fsstruct);
333         FileSystem lfsB = TestUtilHid.createLocalFileSystem(new File JavaDoc(getWorkDir(), "B"), fsstruct);
334         
335         DataFolder dfA = DataFolder.findFolder (lfsA.findResource ("AA"));
336         DataFolder dfB = DataFolder.findFolder (lfsB.findResource ("AA"));
337
338         DataObject[] arr = dfB.getChildren ();
339         DataObject[] rev = new DataObject [arr.length];
340         
341         for (int i = 0; i < arr.length; i++) {
342             rev [arr.length - 1 - i] = arr [i];
343         }
344
345         // set new order - force attr write
346
dfA.setOrder (dfA.getChildren ());
347         dfB.setOrder (rev);
348
349         //System.out.println("dfA " + dfA.getPrimaryFile ().getAttribute (DataFolder.EA_ORDER));
350
//System.out.println("dfB " + dfB.getPrimaryFile ().getAttribute (DataFolder.EA_ORDER));
351

352         MFS mfs = new MFS (new FileSystem [] { lfsA, lfsB });
353         DataFolder df = DataFolder.findFolder (mfs.findResource ("AA"));
354         
355         arr = df.getChildren ();
356         //System.out.println("df " + df.getPrimaryFile ().getAttribute (DataFolder.EA_ORDER));
357

358         OrderListener l = new OrderListener();
359         df.addPropertyChangeListener(l);
360         
361         // change layers -> change attributes
362
mfs.set ( new FileSystem [] { lfsB, lfsA });
363         
364         assertTrue(l.gotSomething());
365         //System.out.println("df " + df.getPrimaryFile ().getAttribute (DataFolder.EA_ORDER));
366
assertChildrenArrays ("", arr, df.getChildren (), false);
367     }
368     
369     // #13820:
370
public void testOrderWhenFileRenamed() throws Exception JavaDoc {
371         TestUtilHid.destroyLocalFileSystem(getName());
372         FileSystem fs = TestUtilHid.createLocalFileSystem(getWorkDir(), new String JavaDoc[] {
373             "folder/a1/",
374             "folder/b2/",
375             "folder/c3/",
376         });
377         DataFolder folder = DataFolder.findFolder(fs.findResource("folder"));
378         assertEquals("initial order is alphabetical", "a1/b2/c3", childrenOrder(folder));
379         OrderListener l = new OrderListener();
380         folder.addPropertyChangeListener(l);
381         DataObject.find(fs.findResource("folder/b2")).rename("d4");
382         assertTrue("Renaming a file fires PROP_CHILDREN on folder", l.gotSomething());
383         assertEquals("order after rename is still alphabetical", "a1/c3/d4", childrenOrder(folder));
384     }
385     
386     public void testSortMode() throws Exception JavaDoc {
387         TestUtilHid.destroyLocalFileSystem(getName());
388         FileSystem fs = TestUtilHid.createLocalFileSystem(getWorkDir(), new String JavaDoc[] {
389             "folder/a/",
390             "folder/b.xml",
391             "folder/c/",
392             "folder/e.xml",
393             "folder/d.instance",
394         });
395         assertTrue(fs.findResource("folder/a").isFolder());
396         assertTrue(fs.findResource("folder/b.xml").isData());
397         assertTrue(fs.findResource("folder/c").isFolder());
398         assertTrue(fs.findResource("folder/e.xml").isData());
399         assertTrue(fs.findResource("folder/d.instance").isData());
400         DataFolder folder = DataFolder.findFolder(fs.findResource("folder"));
401         assertEquals("initial order is alphabetical, folders first", "a/c/b.xml/d.instance/e.xml", childrenOrder(folder));
402         folder.setSortMode(DataFolder.SortMode.NAMES);
403         assertEquals("next order is alphabetical", "a/b.xml/c/d.instance/e.xml", childrenOrder(folder));
404         folder.setSortMode(DataFolder.SortMode.CLASS);
405         assertEquals("last order is by type", "d.instance/a/c/b.xml/e.xml", childrenOrder(folder));
406     }
407     
408     /** Produce a string representation of the order of children
409      * in a folder: primary filenames separated by slashes.
410      * Useful for comparing against expected values.
411      */

412     private static String JavaDoc childrenOrder(DataFolder folder) {
413         DataObject[] kids = folder.getChildren();
414         StringBuffer JavaDoc buf = new StringBuffer JavaDoc(kids.length * 20);
415         for (int i = 0; i < kids.length; i++) {
416             if (i > 0) buf.append('/');
417             buf.append(kids[i].getPrimaryFile().getNameExt());
418         }
419         return buf.toString();
420     }
421     
422     private static class MFS extends MultiFileSystem {
423         public MFS (FileSystem [] fs) {
424             super (fs);
425         }
426         public void set (FileSystem [] fs) {
427             setDelegates (fs);
428         }
429     }
430
431     private void assertChildrenArrays (
432         String JavaDoc msg, DataObject orig[], DataObject reverted[], boolean same
433     ) {
434         if (orig.length != reverted.length) {
435             StringBuffer JavaDoc buf = new StringBuffer JavaDoc (500);
436             buf.append (msg);
437             buf.append (" different length!? ");
438             buf.append (orig.length);
439             buf.append (" != ");
440             buf.append (reverted.length);
441             buf.append ("\nOrig: ");
442             buf.append (Arrays.asList (orig));
443             buf.append ("\nNew : ");
444             buf.append (Arrays.asList (reverted));
445             fail (buf.toString ());
446         }
447        
448         for (int i = 0; i < orig.length; i++) {
449             int indx = same ? i : orig.length - 1 - i;
450             
451             if (orig[i] != reverted [indx]) {
452                 StringBuffer JavaDoc buf = new StringBuffer JavaDoc (500);
453                 for (int j = 0; j < orig.length; j++) {
454                     buf.append ("orig[" + j + "] = " + orig[j] + "\n");
455                 }
456                 for (int j = 0; j < orig.length; j++) {
457                     buf.append ("reverted[" + j + "] = " + reverted[j] + "\n");
458                 }
459         
460                 buf.insert (0, "Order of children is not " +
461                     (same ? "preserved " : "reverted ")
462                 );
463                 fail (msg + " " + buf.toString ());
464             }
465         }
466     }
467     
468     /** Test that DataFolder fires PROP_CHILDREN when a loader is added/removed
469      * and this would cause some objects to be invalidated somehow.
470      * Inspired by unexpected failure in FolderInstanceTest.testFolderInstanceNeverPassesInvObjects.
471      */

472     public void testPropChildrenFiredAfterInvalidation() throws Exception JavaDoc {
473         String JavaDoc[] names = new String JavaDoc[10];
474         for (int i = 0; i < names.length; i++) {
475             names[i] = "folder/file" + i + ".simple";
476         }
477         TestUtilHid.destroyLocalFileSystem(getName());
478         FileSystem lfs = TestUtilHid.createLocalFileSystem(getWorkDir(), names);
479         // Adding it to the repository is necessary for the test to work.
480
// Otherwise PROP_CHILDREN is never fired, and getChildren sticks
481
// to whatever it last had. #15572
482
Repository.getDefault().addFileSystem(lfs);
483         try {
484             FileObject folder = lfs.findResource("folder");
485             DataLoader l = DataLoader.getLoader(DataLoaderOrigTest.SimpleUniFileLoader.class);
486             DataFolder f = DataFolder.findFolder(folder);
487             f.getChildren();
488             OrderListener ol = new OrderListener();
489             f.addPropertyChangeListener(ol);
490             assertEquals(0, ol.count);
491             DataObject old0 = DataObject.find(lfs.findResource(names[0]));
492             assertTrue(old0.isValid());
493             assertEquals("org.openide.loaders.DefaultDataObject", old0.getClass().getName());
494             //System.err.println("adding a loader");
495
AddLoaderManuallyHid.addRemoveLoader(l, true);
496             try {
497                 //System.err.println("added it");
498
Thread.sleep(5000); // give it time to refresh
499
//System.err.println("5 secs later");
500
//System.err.println("loader pool: " + java.util.Arrays.asList(LDataLoaderPool.getDefault ()).toArray()));
501
//System.err.println("our old object: " + old0);
502
//System.err.println("loader recog says: " + DataObject.find(lfs.findResource(names[0])));
503
//System.err.println("but on next one loader recog says: " + DataObject.find(lfs.findResource(names[1])));
504
assertTrue("After adding a loader, the old object is invalid", ! old0.isValid());
505                 DataObject[] kids = f.getChildren();
506                 //System.err.println("kids=" + java.util.Arrays.asList(kids));
507
assertEquals("Adding the loader refreshed a sample file after a while", "org.openide.loaders.DataLoaderOrigTest$SimpleDataObject", DataObject.find(lfs.findResource(names[0])).getClass().getName());
508                 assertEquals("After adding the loader, we have the correct number of objects", names.length, kids.length);
509                 assertEquals("getChildren gives us the new data objects", "org.openide.loaders.DataLoaderOrigTest$SimpleDataObject", kids[names.length - 1].getClass().getName());
510                 assertTrue("Adding a useful loader causes PROP_CHILDREN to be fired", ol.gotSomething());
511                 ol.count = 0;
512             } finally {
513                 AddLoaderManuallyHid.addRemoveLoader(l, false);
514             }
515             Thread.sleep(1000);
516             assertEquals("org.openide.loaders.DefaultDataObject", DataObject.find(lfs.findResource(names[0])).getClass().getName());
517             assertTrue("Removing a loader also triggers PROP_CHILDREN", ol.gotSomething());
518         } finally {
519             Repository.getDefault().removeFileSystem(lfs);
520         }
521         TestUtilHid.destroyLocalFileSystem(getName());
522     }
523     
524 }
525
Popular Tags