KickJava   Java API By Example, From Geeks To Geeks.

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


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
23 import java.awt.Button JavaDoc;
24 import java.awt.Color JavaDoc;
25 import java.beans.*;
26 import java.beans.beancontext.BeanContextChildSupport JavaDoc;
27 import java.io.*;
28 import java.lang.ref.WeakReference JavaDoc;
29 import java.util.*;
30 import java.util.logging.Level JavaDoc;
31 import javax.swing.JButton JavaDoc;
32 import org.netbeans.junit.NbTestCase;
33 import org.openide.cookies.InstanceCookie;
34 import org.openide.filesystems.*;
35 import org.openide.modules.ModuleInfo;
36 import org.openide.options.SystemOption;
37 import org.openide.util.*;
38 import org.openide.util.lookup.AbstractLookup;
39
40 /**
41  * @author Vita Stejskal, Jesse Glick, Jan Pokorsky
42  */

43 public class InstanceDataObjectTest extends NbTestCase {
44     /** folder to create instances in */
45     private DataFolder folder;
46     /** filesystem containing created instances */
47     private FileSystem lfs;
48     
49     /** Creates new DataFolderTest */
50     public InstanceDataObjectTest(String JavaDoc name) {
51         super (name);
52     }
53     
54     @Override JavaDoc
55     protected Level JavaDoc logLevel() {
56         return Level.INFO;
57     }
58
59     
60     
61     protected void setUp () throws Exception JavaDoc {
62         // initialize module layers
63
Lookup.getDefault().lookup(ModuleInfo.class);
64         
65         String JavaDoc fsstruct [] = new String JavaDoc [] {
66             "AA/AAA/A1/",
67             "BB/AAA/",
68             "system/Services/lookupTest/",
69             "testCreateInstance/",
70             "testFindInstance/",
71             "testFindInstance/button[javax-swing-JButton].instance",
72             "testFindInstance/button2[java-awt-Button].instance",
73             "testFindInstance/javax-swing-JButton.instance",
74         };
75         
76         TestUtilHid.destroyLocalFileSystem (getName());
77         clearWorkDir();
78         lfs = TestUtilHid.createLocalFileSystem (getWorkDir(), fsstruct);
79
80         FileObject bb = lfs.findResource("/BB");
81         FileObject aa_aaa = lfs.findResource("/AA/AAA");
82         FileObject bb_aaa = lfs.findResource("/BB/AAA");
83         
84         DataObject src = DataObject.find(aa_aaa);
85         DataObject dest = DataObject.find(bb_aaa);
86         
87         assertTrue("Source folder doesn't exist.", src != null);
88         assertTrue("Destination folder doesn't exist.", dest != null);
89         assertTrue("Source folder is not valid.", src.isValid ());
90         assertTrue("Destination folder is not valid.", dest.isValid ());
91         
92         folder = DataFolder.findFolder (bb);
93         
94         FileObject fo = lfs.findResource("/testFindInstance");
95         fo.createData("fileWithInstanceClass", "instance").setAttribute("instanceClass", "javax.swing.JButton");
96     }
97
98     /** #28118, win sys relies that instance data object fires cookie
99      * changes when its settings file removed, it gets into corruped state otherwise. */

100     public void testFiringEventWhenDeleted() throws Exception JavaDoc {
101         // Init.
102
Lookup.getDefault().lookup(ModuleInfo.class);
103         
104         FileObject root = Repository.getDefault().getDefaultFileSystem().getRoot();
105         FileObject myFolder = root.createFolder("My"); // NOI18N
106

107         final InstanceDataObject ido = InstanceDataObject.create(
108             DataFolder.findFolder(myFolder),
109             "object",
110             new Integer JavaDoc(2),
111             null);
112         System.err.println("Created instance " + ido);
113         
114         class Listener implements PropertyChangeListener {
115             private PropertyChangeEvent evt;
116             
117             private Exception JavaDoc exception;
118             
119             public void propertyChange(PropertyChangeEvent evt) {
120                 System.err.println("Event received->" + evt
121                         + " name=" + evt.getPropertyName());
122                 if(DataObject.PROP_VALID.equals(evt.getPropertyName())) {
123                     this.evt = evt;
124                     
125                     synchronized(ido) {
126                         System.err.println("Event came -> notifying");
127                         ido.notify();
128                     }
129                 }
130             }
131         }
132         
133         final Listener l = new Listener();
134         ido.addPropertyChangeListener(l);
135
136         synchronized(ido) {
137
138             // XXX I don't know whether the firing of event should be
139
// synch or not. Anyway giving a chance to instance data object
140
// that it needs not to be sych.
141
org.openide.util.RequestProcessor.getDefault().post(new java.lang.Runnable JavaDoc() {
142
143                                                                     public void run() {
144                                                                         try {
145                                                                             final org.openide.filesystems.FileObject primary = ido.getPrimaryFile();
146
147                                                                             java.lang.System.err.println("Deleting file=" +
148                                                                                                          primary);
149                                                                             primary.delete();
150                                                                         }
151                                                                         catch (java.io.IOException JavaDoc ioe) {
152                                                                             Exceptions.printStackTrace(ioe);
153                                                                             l.exception = ioe;
154                                                                         }
155                                                                     }
156
157                                                                     {
158                                                                     }
159                                                                 });
160         
161             System.err.println("Waiting for the event with 30 sec timeout");
162             ido.wait(30000);
163         }
164         
165         if(l.exception != null) {
166             throw l.exception;
167         }
168         
169         ido.removePropertyChangeListener(l);
170         
171         assertNotNull("PROP_COOKIE change event has to come", l.evt);
172     }
173     
174     /**test creating of instances from .instance files; alternatives with
175      * instanceClass/instanceOf/instanceCreate
176      */

177     public void testInstanceDefinitions() throws Exception JavaDoc {
178         FileSystem fs = new XMLFileSystem(this.getClass().getClassLoader().
179             getResource("org/openide/loaders/data/InstanceDataObjectTest.xml"));
180         
181         testParticularInstanceDefinition(fs.findResource("testInstanceDefinitions/a.instance"));
182         testParticularInstanceDefinition(fs.findResource("testInstanceDefinitions/b.instance"));
183         testParticularInstanceDefinition(fs.findResource("testInstanceDefinitions/c.instance"));
184         testParticularInstanceDefinition(fs.findResource("testInstanceDefinitions/d.instance"));
185         testParticularInstanceDefinition(fs.findResource("testInstanceDefinitions/e.instance"));
186         testParticularInstanceDefinition(fs.findResource(
187             "testInstanceDefinitions/org-openide-loaders-InstanceDataObjectTest$TestDefinitions.instance"));
188         testParticularInstanceDefinition(fs.findResource(
189             "testInstanceDefinitions/hu[org-openide-loaders-InstanceDataObjectTest$TestDefinitions].instance"));
190     }
191     
192     private void testParticularInstanceDefinition(FileObject fo) throws Exception JavaDoc {
193         assertNotNull(fo);
194         String JavaDoc filename = fo.getNameExt();
195         DataObject dobj = DataObject.find(fo);
196         InstanceCookie.Of ic = (InstanceCookie.Of) dobj.getCookie(InstanceCookie.Of.class);
197         assertNotNull(filename, ic);
198         
199         assertTrue(filename, ic.instanceOf(Runnable JavaDoc.class));
200         assertTrue(filename, ic.instanceOf(TestDefinitions.class));
201         
202         assertEquals(filename, ic.instanceClass(), TestDefinitions.class);
203         assertNotNull(filename, ic.instanceCreate());
204     }
205     
206     public static class TestDefinitions implements Runnable JavaDoc {
207         public TestDefinitions() {}
208         
209         static TestDefinitions create() {
210             return new TestDefinitions();
211         }
212         public void run() {
213         }
214         
215     }
216     
217     /** Checks whether the instance is the same.
218      */

219     public void testSame() throws Exception JavaDoc {
220
221         Ser ser = new Ser ("1");
222         
223         InstanceDataObject i = InstanceDataObject.create (folder, null, ser, null);
224         
225         Object JavaDoc n = i.instanceCreate ();
226         if (n != ser) {
227             fail ("instanceCreate is not the same: " + ser + " != " + n);
228         }
229         
230         i.delete ();
231     }
232     
233     /** Test whether instances survive garbage collection.
234      */

235     public void testSameWithGC () throws Exception JavaDoc {
236         Object JavaDoc ser = new Button JavaDoc();
237         
238         FileObject prim = InstanceDataObject.create (folder, "MyName", ser, null).getPrimaryFile ();
239         String JavaDoc name = prim.getName ();
240         String JavaDoc ext = prim.getExt ();
241         prim = null;
242
243         System.gc ();
244         System.gc ();
245         System.gc ();
246         System.gc ();
247         System.gc ();
248         System.gc ();
249         System.gc ();
250         System.gc ();
251         System.gc ();
252         
253         FileObject fo = folder.getPrimaryFile ().getFileObject (name, ext);
254         assertTrue ("MyName.settings not found", fo != null);
255         
256         DataObject obj = DataObject.find (fo);
257         
258         InstanceCookie ic = (InstanceCookie)obj.getCookie (InstanceCookie.class);
259         assertTrue ("Object: " + obj + " does not have instance cookie", ic != null);
260         
261         Object JavaDoc value = ic.instanceCreate ();
262         if (value != ser) {
263             fail ("Value is different than serialized: " + System.identityHashCode (ser) + " value: " + System.identityHashCode (value));
264         }
265         
266         obj.delete ();
267     }
268     
269     /** Tests the creation in atomic section.
270      */

271     public void testSameInAtomicSection () throws Exception JavaDoc {
272         class Work extends FileChangeAdapter
273         implements FileSystem.AtomicAction {
274             
275             private Button JavaDoc testSer = new Button JavaDoc ();
276             
277             private FileObject data;
278             private InstanceDataObject obj;
279             
280             public void run () throws IOException {
281                 folder.getPrimaryFile ().addFileChangeListener (this);
282                 data = folder.getPrimaryFile ().createData ("SomeData");
283                 
284                 
285                 obj = InstanceDataObject.create (folder, null, testSer, null);
286             }
287             
288             public void doTest () throws Exception JavaDoc {
289                 Object JavaDoc now = obj.instanceCreate ();
290                 if (now != testSer) {
291                     fail ("Different values. Original: " + testSer + " now: " + now);
292                 }
293             }
294             
295             public void cleanUp () throws Exception JavaDoc {
296                 data.delete ();
297                 obj.delete ();
298             }
299             
300             public void fileDataCreated (FileEvent ev) {
301                 try {
302                     Thread.sleep (500);
303                 } catch (Exception JavaDoc ex) {
304                 }
305             }
306         }
307
308         
309         Work t = new Work ();
310         try {
311             folder.getPrimaryFile().getFileSystem ().runAtomicAction (t);
312
313             t.doTest ();
314         } finally {
315             t.cleanUp ();
316         }
317     }
318
319     /** Tests whether createFromTemplate works correctly.
320     */

321     public void testCreateFromTemplateForSettingsFile () throws Exception JavaDoc {
322         Object JavaDoc ser = new Button JavaDoc();
323
324         InstanceDataObject obj = InstanceDataObject.create (folder, "SomeName", ser, null);
325         obj.setTemplate (true);
326
327         DataObject newObj = obj.createFromTemplate(folder, "NewName");
328         
329         if (!newObj.getName().equals ("NewName")) {
330             fail ("Wrong name of new data object: " + newObj.getName ());
331         }
332
333         InstanceCookie ic = (InstanceCookie)newObj.getCookie (InstanceCookie.class);
334         
335         if (ic == null) {
336             fail ("No instance cookie for " + newObj);
337         }
338
339         if (ic.instanceCreate () != ser) {
340             fail ("created instance is different than the original in template");
341         }
342         
343         if (ic.instanceCreate () == obj.instanceCreate ()) {
344             fail ("Instance of the new object is same as the current of the template");
345         }
346     }
347     
348     /** Tests whether handleCopy works correctly.
349     */

350     public void testHandleCopyForSettingsFile () throws Exception JavaDoc {
351         Object JavaDoc ser = new Button JavaDoc();
352
353         InstanceDataObject obj = InstanceDataObject.create (folder, null, ser, null);
354         
355         InstanceCookie icOrig = (InstanceCookie) obj.getCookie (InstanceCookie.class);
356         assertNotNull("No instance cookie for " + obj, icOrig);
357         assertEquals("created instance is different from the original", ser, icOrig.instanceCreate());
358         
359         DataObject newObj = obj.copy(folder);
360         
361         InstanceCookie ic = (InstanceCookie) newObj.getCookie (InstanceCookie.class);
362         
363         assertNotNull("No instance cookie for " + newObj, ic);
364         assertTrue("created instance is same as the original", ic.instanceCreate() != icOrig.instanceCreate());
365         
366     }
367     
368     /** Test if the Lookup reflects IDO' cokie changes. */
369     public void testLookupRefreshOfInstanceCookieChanges() throws Exception JavaDoc {
370 // Object ser = new Button();
371
Object JavaDoc ser = new BeanContextChildSupport JavaDoc();
372
373         FileObject lookupFO = lfs.findResource("/system/Services/lookupTest");
374         FileObject systemFO = lfs.findResource("/system");
375         
376         FolderLookup lookup = new FolderLookup(DataFolder.findFolder(systemFO));
377         Lookup l = lookup.getLookup();
378         DataFolder folderTest = DataFolder.findFolder(lookupFO);
379         
380         InstanceDataObject ido = InstanceDataObject.create (folderTest, "testLookupRefresh", ser, null);
381         Collection col = l.lookupAll(ser.getClass());
382         InstanceCookie ic = (InstanceCookie) ido.getCookie(InstanceCookie.class);
383         assertEquals("IDO did not create new InstanceCookie", ser, ic.instanceCreate());
384         
385         Set origSet = new HashSet(Arrays.asList(new Object JavaDoc[] {ser}));
386         assertEquals("wrong lookup result", origSet, new HashSet(col));
387         
388         assertTrue("Lookup is not finished and surprisingly returned a result", lookup.isFinished ());
389         
390         Object JavaDoc found = col.iterator().next();
391         assertEquals("found wrong object instance", ser, found);
392         
393         // due to #14795 workaround
394
Thread.sleep(1000);
395         
396         // external file change forcing IDO to create new InstanceCookie
397
final FileObject fo = ido.getPrimaryFile();
398         lfs.runAtomicAction(new FileSystem.AtomicAction() {
399             public void run() throws IOException {
400                 FileLock lock = null;
401                 try {
402                     InputStream in = fo.getInputStream();
403                     byte[] buf = new byte[(int)fo.getSize()];
404                     in.read(buf);
405                     in.close();
406
407                     lock = fo.lock();
408                     OutputStream out = fo.getOutputStream(lock);
409                     out.write(buf);
410                     out.write(32);
411                     out.flush();
412                     out.close();
413                     
414                 } finally {
415                     if (lock != null) lock.releaseLock();
416                 }
417             }
418         });
419         
420         col = l.lookupAll(ser.getClass());
421         ic = (InstanceCookie) ido.getCookie(InstanceCookie.class);
422         origSet = new HashSet(Arrays.asList(new Object JavaDoc[] {ic.instanceCreate()}));
423         
424         assertEquals("wrong lookup result", origSet, new HashSet(col));
425         
426         found = col.iterator().next();
427         assertTrue("IDO did not create new InstanceCookie", ser != ic.instanceCreate());
428         assertTrue("Lookup did not refresh changed InstanceCookie", ser != found);
429     }
430     
431     /** Test method InstanceDataObject.create producing .instance files. */
432     public void testCreateInstance () throws Exception JavaDoc {
433         FileObject fo = lfs.findResource("/testCreateInstance");
434         assertNotNull("missing folder /testCreateInstance", fo);
435         DataFolder folder = DataFolder.findFolder(fo);
436         assertNotNull("cannot find DataFolder /testCreateInstance", folder);
437         String JavaDoc filename = null;
438         InstanceDataObject ido = InstanceDataObject.create(folder, filename, "javax.swing.JButton");
439         assertEquals("created wrong filename: ", "javax-swing-JButton", ido.getName());
440         InstanceDataObject ido2 = InstanceDataObject.create(folder, filename, "javax.swing.JButton");
441         assertEquals("creating the same instance failed", ido, ido2);
442         InstanceCookie ic = (InstanceCookie) ido.getCookie(InstanceCookie.class);
443         assertEquals("wrong classname: ", "javax.swing.JButton", ic.instanceClass().getName());
444         
445         filename = "new file";
446         ido = InstanceDataObject.create(folder, filename, "javax.swing.JButton");
447         assertEquals("created wrong filename: ", filename, ido.getName());
448         ido2 = InstanceDataObject.create(folder, filename, "javax.swing.JButton");
449         assertEquals("creating the same instance failed", ido, ido2);
450         ic = (InstanceCookie) ido.getCookie(InstanceCookie.class);
451         assertEquals("wrong classname: ", "javax.swing.JButton", ic.instanceClass().getName());
452     }
453     
454     /** Test method InstanceDataObject.find searching .instance files. */
455     public void testFindInstance () throws Exception JavaDoc {
456         FileObject fo = lfs.findResource("/testFindInstance");
457         assertNotNull("missing folder /testFindInstance", fo);
458         DataFolder folder = DataFolder.findFolder(fo);
459         assertNotNull("cannot find DataFolder /testFindInstance", folder);
460         
461         InstanceDataObject ido = InstanceDataObject.find(folder, "button2", "java.awt.Button");
462         assertNotNull("ido not found: 'button2'", ido);
463         assertEquals("found wrong ido", "button2", ido.getName());
464         InstanceCookie ic = (InstanceCookie) ido.getCookie(InstanceCookie.class);
465         assertEquals("found ido with wrong classname", "java.awt.Button", ic.instanceClass().getName());
466         
467         ido = InstanceDataObject.find(folder, "button", "javax.swing.JButton");
468         assertNotNull("ido not found: 'button'", ido);
469         assertEquals("found wrong ido", "button", ido.getName());
470         ic = (InstanceCookie) ido.getCookie(InstanceCookie.class);
471         assertEquals("found ido with wrong classname", "javax.swing.JButton", ic.instanceClass().getName());
472         
473         String JavaDoc renamed = "renamed_button";
474         ido.rename(renamed);
475         assertNotNull("missing IDO.EA_NAME in " + ido.getPrimaryFile(), ido.getPrimaryFile().getAttribute("name"));
476         ido = InstanceDataObject.find(folder, renamed, "javax.swing.JButton");
477         assertNotNull("ido not found: " + ido.getName(), ido);
478         assertEquals("found wrong ido", renamed, ido.getName());
479         ic = (InstanceCookie) ido.getCookie(InstanceCookie.class);
480         assertEquals("found ido with wrong classname", "javax.swing.JButton", ic.instanceClass().getName());
481         
482         ido = InstanceDataObject.find(folder, "button", "javax.swing.JButton");
483         assertEquals("ido should not be found: ", null, ido);
484         
485         ido = InstanceDataObject.find(folder, "fileWithInstanceClass", "javax.swing.JButton");
486         assertNotNull("ido not found: 'fileWithInstanceClass'", ido);
487         assertEquals("found wrong ido", "fileWithInstanceClass", ido.getName());
488         ic = (InstanceCookie) ido.getCookie(InstanceCookie.class);
489         assertEquals("found ido with wrong classname", "javax.swing.JButton", ic.instanceClass().getName());
490         
491         ido = InstanceDataObject.find(folder, null, "javax.swing.JButton");
492         assertNotNull("ido not found 'javax-swing-JButton'", ido);
493         assertEquals("found wrong ido", "javax-swing-JButton", ido.getName());
494         ic = (InstanceCookie) ido.getCookie(InstanceCookie.class);
495         assertEquals("found ido with wrong classname", "javax.swing.JButton", ic.instanceClass().getName());
496         
497         ido = InstanceDataObject.find(folder, null, "java.awt.Button");
498         assertEquals("ido should not be found: ", null, ido);
499     }
500
501     /** Test method InstanceDataObject.remove removing .instance files. */
502     public void testRemoveInstance () throws Exception JavaDoc {
503         FileObject fo = lfs.findResource("/testFindInstance");
504         assertNotNull("missing folder /testFindInstance", fo);
505         DataFolder folder = DataFolder.findFolder(fo);
506         assertNotNull("cannot find DataFolder /testFindInstance", folder);
507         
508         assertEquals(InstanceDataObject.remove(folder, "button2", "java.awt.Button"), true);
509         assertEquals(InstanceDataObject.remove(folder, "button2", "java.awt.Button"), false);
510         
511         InstanceDataObject ido = InstanceDataObject.find(folder, "button", "javax.swing.JButton");
512         String JavaDoc renamed = "renamed_button";
513         ido.rename(renamed);
514         assertEquals(InstanceDataObject.remove(folder, renamed, "javax.swing.JButton"), true);
515         assertEquals(InstanceDataObject.remove(folder, renamed, "javax.swing.JButton"), false);
516         
517         assertEquals(InstanceDataObject.remove(folder, "fileWithInstanceClass", "javax.swing.JButton"), true);
518         assertEquals(InstanceDataObject.remove(folder, "fileWithInstanceClass", "javax.swing.JButton"), false);
519         
520         assertEquals(InstanceDataObject.remove(folder, null, "javax.swing.JButton"), true);
521         assertEquals(InstanceDataObject.remove(folder, null, "javax.swing.JButton"), false);
522     }
523
524     @SuppressWarnings JavaDoc("unchecked")
525     public void testClassCastIssue91694() throws Exception JavaDoc {
526         FileObject fo = lfs.findResource("/testFindInstance");
527         assertNotNull("missing folder /testFindInstance", fo);
528         DataFolder folder = DataFolder.findFolder(fo);
529         assertNotNull("cannot find DataFolder /testFindInstance", folder);
530
531         JButton JavaDoc b = new JButton JavaDoc();
532         
533         
534         InstanceDataObject ido = InstanceDataObject.create(folder, "MyButtonek", b, null);
535         
536         Class JavaDoc c = Object JavaDoc.class;
537         Object JavaDoc res = ido.getCookie(c);
538         assertNotNull("Some object found", res);
539         assertEquals("This finds InstanceDataObject", InstanceDataObject.class, res.getClass());
540     }
541     
542     public void testWhenAFileInToolsOptionsIsRevertedTheSettingIsUpdatedIssue20962 () throws Exception JavaDoc {
543         TestUtilHid.destroyLocalFileSystem (getName() + "2");
544         String JavaDoc[] fsstruct = {
545             "system/Services/lookupTest/",
546         };
547         FileSystem sndlfs = TestUtilHid.createLocalFileSystem (new File (getWorkDir(), "2"), fsstruct);
548         
549
550         Object JavaDoc x = new Integer JavaDoc (10);
551         String JavaDoc path;
552         {
553             FileObject lookupFO = lfs.findResource("/system/Services/lookupTest");
554             DataFolder folderTest = DataFolder.findFolder(lookupFO);
555             InstanceDataObject ido = InstanceDataObject.create (folderTest, "testLookupRefresh", x, null);
556             path = ido.getPrimaryFile ().getPath ();
557             WeakReference JavaDoc ref = new WeakReference JavaDoc (ido);
558             ido = null;
559             assertGC ("disappear", ref);
560         }
561
562         Object JavaDoc y = new Integer JavaDoc (11);
563         FileObject lookupFO;
564         {
565             lookupFO = sndlfs.findResource("/system/Services/lookupTest");
566             DataFolder folderTest = DataFolder.findFolder(lookupFO);
567             InstanceDataObject ido = InstanceDataObject.create (folderTest, "testLookupRefresh", y, null);
568             
569             assertEquals (
570                 "The same path", path,
571                 ido.getPrimaryFile ().getPath ()
572             );
573             WeakReference JavaDoc ref = new WeakReference JavaDoc (ido);
574             ido = null;
575             assertGC ("disappear", ref);
576         }
577         
578         MultiFileSystem mfs = new MultiFileSystem (new FileSystem[] {
579             sndlfs,
580             lfs,
581         });
582         
583         FileObject file = mfs.findResource (path);
584         assertNotNull ("File is really found", file);
585         
586         InstanceDataObject ido = (InstanceDataObject)DataObject.find (file);
587         
588         InstanceCookie ic = (InstanceCookie)ido.getCookie (InstanceCookie.class);
589         assertNotNull ("Has cookie", ic);
590         assertEquals ("And its value is y", y, ic.instanceCreate ());
591         
592
593         lookupFO.delete ();
594         
595         ic = (InstanceCookie)ido.getCookie (InstanceCookie.class);
596         assertNotNull ("Has cookie", ic);
597         assertEquals ("And its value is x", x, ic.instanceCreate ());
598     }
599
600     
601     public void testWeAreAbleToResetSharedClassObjectByCallingResetOnItIssue20962 () throws Exception JavaDoc {
602         FileObject lookupFO;
603         {
604             Object JavaDoc x = Setting.findObject (Setting.class, true);
605             lookupFO = lfs.findResource("/system/Services/lookupTest");
606             DataFolder folderTest = DataFolder.findFolder(lookupFO);
607             InstanceDataObject ido = InstanceDataObject.create (folderTest, "testLookupRefresh", x, null);
608             lookupFO = ido.getPrimaryFile ();
609             WeakReference JavaDoc ref = new WeakReference JavaDoc (ido);
610             Setting.resetCalled = 0;
611         }
612
613         InstanceDataObject ido = (InstanceDataObject)DataObject.find (lookupFO);
614         InstanceCookie ic = (InstanceCookie)ido.getCookie (InstanceCookie.class);
615         assertNotNull ("Has cookie", ic);
616         Object JavaDoc obj = ic.instanceCreate ();
617         assertNotNull ("Not null", obj);
618         assertEquals ("It is settings", Setting.class, obj.getClass ());
619         
620         
621         FileLock lock = lookupFO.lock ();
622         OutputStream os = lookupFO.getOutputStream (lock);
623         
624         PrintWriter pw = new PrintWriter (os);
625         pw.println ("<?xml version=\"1.0\"?>");
626         pw.println ("<!DOCTYPE settings PUBLIC \"-//NetBeans//DTD Session settings 1.0//EN\" \"http://www.netbeans.org/dtds/sessionsettings-1_0.dtd\">");
627         pw.println ("<settings version=\"1.0\">");
628         pw.println (" <module name=\"org.openide.options\" spec=\"1.13\"/>");
629         pw.println (" <instanceof class=\"org.openide.options.SystemOption\"/>");
630         pw.println (" <instance class=\"" + Setting.class.getName () + "\"/>");
631         pw.println ("</settings>");
632         pw.close ();
633         lock.releaseLock ();
634         
635         ic = (InstanceCookie)ido.getCookie (InstanceCookie.class);
636         assertNotNull ("Has cookie", ic);
637         assertNotNull ("Not null", obj);
638         assertEquals ("It is settings", Setting.class, obj.getClass ());
639         Setting s = (Setting)Setting.findObject (Setting.class, true);
640         assertEquals ("Refresh has been called", 1, s.resetCalled);
641     }
642     
643     /** Checks whether the instance is not saved multiple times.
644      *
645     public void testMultiSave () throws Exception {
646         Ser ser1 = new Ser ("1");
647         Ser ser2 = new Ser ("2");
648         
649         InstanceDataObject i = InstanceDataObject.create (folder, null, ser1, null);
650         
651         Thread.sleep (3000);
652         
653         InstanceDataObject j = InstanceDataObject.create (folder, null, ser2, null);
654         Thread.sleep (3000);
655         
656         Object n = i.instanceCreate ();
657         if (n != ser1) {
658             fail ("instanceCreate is not the same: ");
659         }
660         i.instanceCreate ();
661         j.instanceCreate ();
662         j.instanceCreate ();
663         
664     } */

665     
666     public static final class Ser extends Object JavaDoc implements Externalizable {
667         static final long serialVersionUID = -123456;
668         public int deserialized;
669         public int serialized;
670         public int listenerCount;
671         private String JavaDoc name;
672         
673         private int property;
674         
675         private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
676         
677         public Ser (String JavaDoc name) {
678             this.name = name;
679         }
680         
681         public synchronized void readExternal(ObjectInput objectInput)
682         throws IOException, ClassNotFoundException JavaDoc {
683 // System.err.println(name + " deserialized");
684
deserialized++;
685         }
686         
687         public synchronized void writeExternal(ObjectOutput objectOutput)
688         throws IOException {
689 // System.err.println(name + " serialized");
690
serialized++;
691         }
692         
693         public void addPropertyChangeListener(PropertyChangeListener l) {
694             listenerCount++;
695             propertyChangeSupport.addPropertyChangeListener(l);
696         }
697         
698         public void removePropertyChangeListener(PropertyChangeListener l) {
699             listenerCount--;
700             propertyChangeSupport.removePropertyChangeListener(l);
701         }
702         
703         public int getProperty() {
704             return this.property;
705         }
706         
707         public void setProperty(int property) {
708             int oldProperty = this.property;
709             this.property = property;
710             propertyChangeSupport.firePropertyChange("property", new Integer JavaDoc(oldProperty), new Integer JavaDoc(property));
711         }
712         
713     }
714     
715     /** Test filename escaping and unescaping functionality.
716      * @see "#16479"
717      */

718     public void testEscapeAndUnescape() throws Exception JavaDoc {
719         // First make sure plain things are not escaped.
720
assertEquals("hello-x_99", InstanceDataObject.escape("hello-x_99"));
721         assertEquals("hello-x_99", InstanceDataObject.unescape("hello-x_99"));
722         // That high bits are.
723
assertEquals("x#ABCDy", InstanceDataObject.escape("x\uABCDy"));
724         // Now that the operation is symmetric.
725
String JavaDoc[] names = new String JavaDoc[] {
726             "hello",
727             "back \\ slash",
728             "control\ncharacters",
729             "test #1",
730             "\u0158ekni `\u0159' dob\u0159e!",
731             "maybe this is Chinese: \u1234\u5678\uABCD?",
732             "junk1: !@#$%^&*",
733         "junk2: ()-_=+[]{}",
734         "junk3: #~;:'\"/?",
735         "junk4: .>,<\\|`~",
736             " ...ahem.",
737             "trailing: ",
738             "too many internal",
739         };
740         for (int i = 0; i < names.length; i++) {
741             assertEquals(names[i], InstanceDataObject.unescape(InstanceDataObject.escape(names[i])));
742         }
743         // Now the fun part: check that the filesystem can actually store the filenames
744
// we are making. For best results, try this on different OS's.
745
File dir = File.createTempFile("InstanceDataObjectTest", "");
746         assertTrue(dir.delete());
747         assertTrue(dir.mkdir());
748         for (int i = 0; i < names.length; i++) {
749             String JavaDoc name = InstanceDataObject.escape(names[i]);
750             //System.err.println("testing: " + name);
751
File x = new File(dir, name);
752             try {
753                 assertTrue(x.createNewFile());
754             } catch (IOException ioe) {
755                 ioe.printStackTrace();
756                 fail("could not make file named '" + name + "'");
757             }
758             x = new File(dir, name);
759             assertTrue("acknowledges existence of a file named '" + name + "'", x.isFile());
760             String JavaDoc[] children = dir.list();
761             assertEquals("correctly read filename '" + name + "'",
762                 Arrays.asList(new String JavaDoc[] {name}),
763                 Arrays.asList(children));
764             assertTrue("can delete a file named '" + name + "'", x.delete());
765         }
766         dir.delete();
767     }
768
769     /** Test very long filename escaping functionality.
770      * @see "#17186"
771      */

772     public void testEscapeAndCut() throws Exception JavaDoc {
773         // First make sure plain things are not escaped and not cut.
774
assertEquals("hello-x_99", InstanceDataObject.escapeAndCut("hello-x_99"));
775         // That high bits are.
776
assertEquals("x#ABCDy", InstanceDataObject.escapeAndCut("x\uABCDy"));
777         // Now that the operation is symmetric.
778
char[] charBuf = new char[100];
779         Arrays.fill(charBuf, 'a');
780         String JavaDoc[] names = new String JavaDoc[2];
781         names[0] = new String JavaDoc(charBuf);
782         charBuf[50] = 'b';
783         names[1] = new String JavaDoc(charBuf);
784         String JavaDoc ename0 = InstanceDataObject.escapeAndCut(names[0]);
785         String JavaDoc ename1 = InstanceDataObject.escapeAndCut(names[1]);
786         assertNotNull("Cutting failed: src: " + names[0] + " dst: " + ename0, ename0);
787         assertNotNull("Cutting failed: src: " + names[1] + " dst: " + ename1, ename1);
788         assertTrue("Unchanged: " + names[0], !names[0].equals(ename0));
789         assertTrue("Unchanged: " + names[1], !names[1].equals(ename1));
790         assertTrue("Cutting failed: src: " + names[0] + " dst: " + ename0 +
791             ", src: " + names[1] + " dst: " + ename1, !ename0.equals(ename1));
792         
793         // Now the fun part: check that the filesystem can actually store the filenames
794
// we are making. For best results, try this on different OS's.
795
File dir = File.createTempFile("InstanceDataObjectTest", "");
796         assertTrue(dir.delete());
797         assertTrue(dir.mkdir());
798         for (int i = 0; i < names.length; i++) {
799             String JavaDoc name = InstanceDataObject.escapeAndCut(names[i]);
800             //System.err.println("testing: " + name);
801
File x = new File(dir, name);
802             try {
803                 assertTrue(x.createNewFile());
804             } catch (IOException ioe) {
805                 ioe.printStackTrace();
806                 fail("could not make file named '" + name + "'");
807             }
808             x = new File(dir, name);
809             assertTrue("acknowledges existence of a file named '" + name + "'", x.isFile());
810             String JavaDoc[] children = dir.list();
811             assertEquals("correctly read filename '" + name + "'",
812                 Arrays.asList(new String JavaDoc[] {name}),
813                 Arrays.asList(children));
814             assertTrue("can delete a file named '" + name + "'", x.delete());
815         }
816         dir.delete();
817     }
818     
819     /** Tests creating .settings file (<code>IDO.create</code>) using parameter
820      * <code>create</code>
821      */

822     public void testCreateSettings() throws Exception JavaDoc {
823         FileObject fo = lfs.findResource("/testCreateInstance");
824         assertNotNull("missing folder /testCreateInstance", fo);
825         DataFolder folder = DataFolder.findFolder(fo);
826         assertNotNull("cannot find DataFolder /testCreateInstance", folder);
827         
828         // test non null filename
829
String JavaDoc filename = "testCreateSettings";
830         Object JavaDoc obj = new JButton JavaDoc();
831         InstanceDataObject ido = InstanceDataObject.create(folder, filename, obj, null, false);
832         assertNotNull("InstanceDataObject.create cannot return null!", ido);
833         
834         InstanceDataObject ido2 = InstanceDataObject.create(folder, filename, obj, null, false);
835         assertNotNull("InstanceDataObject.create cannot return null!", ido2);
836         assertEquals("InstanceDataObject.create(..., false) must reuse existing file: ",
837             ido.getPrimaryFile(), ido2.getPrimaryFile());
838         
839         for (int i = 0; i < 3; i++) {
840             ido2 = InstanceDataObject.create(folder, filename, obj, null, true);
841             assertNotNull("InstanceDataObject.create cannot return null!", ido2);
842             assertTrue("InstanceDataObject.create(..., true) must create new file: "
843                 + "step: " + i + ", "
844                 + ido2.getPrimaryFile(), ido.getPrimaryFile() != ido2.getPrimaryFile());
845         }
846         
847         // test null filename
848
ido = InstanceDataObject.create(folder, null, obj, null, false);
849         assertNotNull("InstanceDataObject.create cannot return null!", ido);
850         
851         ido2 = InstanceDataObject.create(folder, null, obj, null, false);
852         assertNotNull("InstanceDataObject.create cannot return null!", ido2);
853         // filename == null => always create new file (ignore create parameter) => backward compatibility
854
assertTrue("InstanceDataObject.create(..., false) must create new file: "
855             + ido2.getPrimaryFile(), ido.getPrimaryFile() != ido2.getPrimaryFile());
856         
857         for (int i = 0; i < 3; i++) {
858             ido2 = InstanceDataObject.create(folder, null, obj, null, true);
859             assertNotNull("InstanceDataObject.create cannot return null!", ido2);
860             assertTrue("InstanceDataObject.create(..., true) must create new file: "
861                 + ido2.getPrimaryFile(), ido.getPrimaryFile() != ido2.getPrimaryFile());
862         }
863         
864     }
865     
866     /** Tests instanceOf attribute.
867      */

868     public void testInstanceOfAttribute () throws Exception JavaDoc {
869         FileObject fo = FileUtil.createData (lfs.getRoot (), "BB/AAA/X.instance");
870         fo.setAttribute ("instanceClass", "java.lang.Number");
871         fo.setAttribute ("instanceCreate", new Long JavaDoc (1L));
872         fo.setAttribute ("instanceOf", "java.lang.Object,java.lang.Long");
873         
874         DataObject obj = DataObject.find (fo);
875         assertNotNull("Object found", obj);
876         
877         InstanceCookie.Of c = (InstanceCookie.Of)obj.getCookie(InstanceCookie.Of.class);
878         assertNotNull ("Cookie found", c);
879         
880         assertTrue("Instance of object", c.instanceOf(Object JavaDoc.class));
881         assertTrue("Not declared to be Serializable", !c.instanceOf(Serializable.class));
882         assertTrue("Declared to be also Long", c.instanceOf(Long JavaDoc.class));
883         assertTrue("Nobody knows about it being number", !c.instanceOf(Number JavaDoc.class));
884         
885         assertEquals ("Class is defined to be Number", Number JavaDoc.class, c.instanceClass());
886         Object JavaDoc o = c.instanceCreate ();
887         assertTrue ("It is a long", o instanceof Long JavaDoc);
888         assertEquals ("It is 1", 1, ((Long JavaDoc)o).intValue());
889     }
890     
891     public void testDeleteSettings() throws Exception JavaDoc {
892         FileObject root = lfs.getRoot();
893         DataFolder folder = DataFolder.findFolder(root);
894         
895         String JavaDoc filename = "testDeleteSettings";
896         JButton JavaDoc obj = new JButton JavaDoc();
897         InstanceDataObject ido = InstanceDataObject.create(folder, filename, obj, null, false);
898         assertNotNull("InstanceDataObject.create cannot return null!", ido);
899         
900         // test if file object does not remain locked when ido is deleted and
901
// the storing is not rescheduled in consequence of the serialization
902
obj.setForeground(Color.black);
903         Thread.sleep(500);
904         ido.delete();
905         assertNull(filename + ".settings was not deleted!", root.getFileObject(filename));
906         Thread.sleep(3000);
907         assertNull(filename + ".settings was not deleted!", root.getFileObject(filename));
908         
909         filename = "testDeleteSettings2";
910         Ser ser = new Ser("bla");
911         ido = InstanceDataObject.create(folder, filename, ser, null, false);
912         assertNotNull("InstanceDataObject.create cannot return null!", ido);
913         
914         ser.setProperty(10);
915         ido.delete();
916         assertNull(filename + ".settings was not deleted!", root.getFileObject(filename));
917         Thread.sleep(3000);
918         assertNull(filename + ".settings was not deleted!", root.getFileObject(filename));
919     }
920     
921     public void testDeleteSettingsRemovesListener() throws Exception JavaDoc {
922         FileObject root = lfs.getRoot();
923         DataFolder folder = DataFolder.findFolder(root);
924         
925         String JavaDoc filename = "testDeleteSettings3";
926         Ser ser = new Ser("bla");
927         InstanceDataObject ido = InstanceDataObject.create(folder, filename, ser, null, false);
928         assertNotNull("InstanceDataObject.create cannot return null!", ido);
929         assertTrue("Listener not attached!", ser.listenerCount == 1);
930         ido.delete();
931         assertTrue("Listener remained attached!", ser.listenerCount == 0);
932     }
933     
934     public void testCookieChangeEvent () throws Exception JavaDoc {
935         FileObject fo = FileUtil.createData (lfs.getRoot (), "GG/AAA/X.settings");
936         //assertTrue (fo.getFileSystem().toString(), fo.getFileSystem().isDefault());
937
DataObject newSetting = InstanceDataObject.create((DataFolder)DataFolder.find(fo.getParent()),"myString","myString", null);
938         
939         final List events = new ArrayList();
940         
941         DataObject obj = DataObject.find (fo);
942         assertNotNull(obj);
943         assertNull (obj.getCookie(InstanceCookie.class));
944         
945
946         obj.addPropertyChangeListener(new PropertyChangeListener() {
947             public void propertyChange(PropertyChangeEvent evt) {
948                 if (evt.getPropertyName().equals(DataObject.PROP_COOKIE)) {
949                     events.add(evt);
950                 }
951             }
952         });
953
954         copySetting(fo, newSetting.getPrimaryFile());
955
956
957         InputStream is = fo.getInputStream();
958         byte[] all = new byte[is.available()];
959         is.read(all);
960         is.close();
961
962         assertNotNull (obj.getCookie(InstanceCookie.class));
963         assertEquals (new String JavaDoc (all),1, events.size());
964     }
965
966     public void testSerFileChange () throws Exception JavaDoc {
967         FileObject fo = FileUtil.createData (lfs.getRoot (), "HH/BBB/Y.ser");
968         FileObject services = FileUtil.createData (Repository.getDefault().getDefaultFileSystem().getRoot (), "Services");
969         assertNotNull (services);
970         assertTrue (services.isFolder());
971         SerEnvironmentProvider environmentProvider = new SerEnvironmentProvider();
972         assertNotNull (InstanceDataObject.create((DataFolder)DataFolder.find(services),"serprovider", environmentProvider,null ));
973         Object JavaDoc obj = new ArrayList ();
974         
975         writeObject(fo, obj);
976         DataObject ser = DataObject.find(fo);
977         InstanceCookie ic = (InstanceCookie)ser.getCookie(InstanceCookie.class);
978
979         
980         assertNotNull (ic);
981         Object JavaDoc instance = ic.instanceCreate();
982         assertNotNull (instance);
983         assertEquals (instance.getClass(), ArrayList.class);
984         assertEquals (((ArrayList)instance).size(), 0);
985         
986
987         ((ArrayList)obj).add("element");
988         Thread.sleep(2000);
989         writeObject(fo, obj);
990         ic = (InstanceCookie)ser.getCookie(InstanceCookie.class);
991         assertNotNull (ic);
992         Object JavaDoc instance2 = ic.instanceCreate();
993         assertNotNull (instance2);
994         assertEquals (instance2.getClass(), ArrayList.class);
995         assertEquals (((ArrayList)instance2).size(), 1);
996
997         environmentProvider.assertUsage();
998         
999     }
1000    
1001    private static class SerEnvironmentProvider implements Environment.Provider, Serializable {
1002        private boolean failure = false;
1003        public void assertUsage () {
1004            if (failure) {
1005                fail ("InstanceDataObject has hardcoded impl. for *.ser files and no EnvironmentProvider should be called.");
1006            }
1007        }
1008        public Lookup getEnvironment(DataObject obj) {
1009            failure = true;
1010            return new AbstractLookup (new AbstractLookup.Content ());
1011        }
1012    }
1013
1014    private void writeObject(FileObject fo, Object JavaDoc obj) throws IOException {
1015        FileLock fLock = fo.lock();
1016        OutputStream os = null;
1017        
1018        try {
1019            os = fo.getOutputStream(fLock);
1020            ObjectOutputStream obs = new ObjectOutputStream (os);
1021            obs.writeObject(obj);
1022        } finally {
1023            if (os != null) os.close();
1024            if (fLock != null) fLock.releaseLock();
1025        }
1026    }
1027    
1028    public void testHelp() throws Exception JavaDoc {
1029        FileObject fo = FileUtil.createData(lfs.getRoot(), "bla/bla/hle/X.settings");
1030        InstanceDataObject ico = (InstanceDataObject)DataObject.find(fo);
1031        HelpCtx x = ico.getHelpCtx();
1032        assertNotNull("This used to throw stack overflow, issue 68715", x);
1033        
1034    }
1035
1036    public void testCookieChangeEvent2 () throws Exception JavaDoc {
1037        FileObject fo = FileUtil.createData (lfs.getRoot (), "GG/AAA/X.settings");
1038        //assertTrue (fo.getFileSystem().toString(), fo.getFileSystem().isDefault());
1039
DataObject newSetting = InstanceDataObject.create((DataFolder)DataFolder.find(fo.getParent()),"myString","myString", null);
1040        copySetting(fo, newSetting.getPrimaryFile());
1041        final List events = new ArrayList();
1042        
1043        DataObject obj = DataObject.find (fo);
1044        assertNotNull(obj);
1045        assertNotNull (obj.getCookie(InstanceCookie.class));
1046        
1047
1048        obj.addPropertyChangeListener(new PropertyChangeListener() {
1049            public void propertyChange(PropertyChangeEvent evt) {
1050                if (evt.getPropertyName().equals(DataObject.PROP_COOKIE)) {
1051                    events.add(evt);
1052                }
1053            }
1054        });
1055        newSetting = InstanceDataObject.create((DataFolder)DataFolder.find(fo.getParent()),"myString2","myString2", null);
1056        copySetting(fo, newSetting.getPrimaryFile());
1057
1058
1059        InputStream is = fo.getInputStream();
1060        byte[] all = new byte[is.available()];
1061        is.read(all);
1062        is.close();
1063
1064        assertNotNull (obj.getCookie(InstanceCookie.class));
1065        assertEquals (new String JavaDoc (all),1, events.size());
1066    }
1067
1068    private void copySetting(FileObject fo, FileObject primaryFile) throws IOException {
1069        FileLock fLock = fo.lock();
1070
1071        OutputStream outputStream = null;
1072        InputStream inputStream = null;
1073        try {
1074            outputStream = fo.getOutputStream(fLock);
1075            inputStream = primaryFile.getInputStream();
1076            FileUtil.copy(inputStream, outputStream);
1077        } finally {
1078            if (fLock != null) fLock.releaseLock();
1079            if (inputStream != null) inputStream.close();
1080            if (outputStream != null) outputStream.close();
1081        }
1082    }
1083
1084    public static final class Setting extends SystemOption {
1085        private static int resetCalled;
1086        
1087        protected void reset () {
1088            resetCalled++;
1089        }
1090        
1091        public String JavaDoc displayName () {
1092            return "My Setting";
1093        }
1094    }
1095}
1096
Popular Tags