KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > settings > convertors > SerialDataConvertorTest


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 2002-2003 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.settings.convertors;
21
22 import org.netbeans.core.startup.layers.SystemFileSystem;
23 import org.openide.filesystems.*;
24 import org.openide.filesystems.FileSystem; // override java.io.FileSystem
25
import org.openide.loaders.*;
26 import org.openide.cookies.*;
27 import org.openide.modules.ModuleInfo;
28 import org.openide.util.*;
29 import java.io.*;
30 import java.lang.ref.Reference JavaDoc;
31 import java.lang.ref.WeakReference JavaDoc;
32 import java.util.*;
33
34 import org.netbeans.junit.*;
35 import org.openide.nodes.Node;
36
37 /**
38  * @author Jan Pokorsky
39  */

40 public class SerialDataConvertorTest extends NbTestCase {
41     /** folder to create instances in */
42     private DataFolder folder;
43     /** filesystem containing created instances */
44     private FileSystem lfs;
45     
46     /** Creates new DataFolderTest */
47     public SerialDataConvertorTest(String JavaDoc name) {
48         super (name);
49     }
50     
51     /** Setups variables.
52      */

53     protected void setUp () throws Exception JavaDoc {
54         Lookup.getDefault().lookup(ModuleInfo.class);
55         lfs = Repository.getDefault().getDefaultFileSystem();
56         org.openide.filesystems.FileUtil.createFolder(lfs.getRoot(), "BB/AAA");
57         org.openide.filesystems.FileUtil.createFolder(lfs.getRoot(), "system/Services/lookupTest");
58         org.openide.filesystems.FileUtil.createFolder(lfs.getRoot(), "testCreateInstance");
59         
60         
61         String JavaDoc fsstruct [] = new String JavaDoc [] {
62             "BB/AAA/",
63             "system/Services/lookupTest/",
64             "testCreateInstance/",
65         };
66         
67         FileObject bb = lfs.findResource("/BB");
68         FileObject bb_aaa = lfs.findResource("/BB/AAA");
69         
70         DataObject dest = DataObject.find(bb_aaa);
71         
72         assertTrue("Destination folder doesn't exist.", dest != null);
73         assertTrue("Destination folder is not valid.", dest.isValid ());
74         
75         folder = DataFolder.findFolder (bb);
76     }
77     
78     public void test50177ProblemSimulation () throws Exception JavaDoc {
79         FileObject testFolder = FileUtil.createFolder(Repository.getDefault().getDefaultFileSystem().getRoot (), "Services");
80         assertNotNull(testFolder);
81         
82         InstanceDataObject ido = InstanceDataObject.create(DataFolder.findFolder(testFolder), "test50177ProblemSimulation", new Ex50177(),null);
83         
84         Lookup.Item item = Lookup.getDefault().lookupItem(new Lookup.Template (Ex50177.class, null, null));
85         assertNotNull(item);
86         String JavaDoc id = item.getId();
87         
88         Ex50177 exObj = (Ex50177)item.getInstance();
89         assertNotNull(exObj);
90         
91         exObj.setSomething("set any value shouldn't cause #50177");
92         SerialDataConvertorTest.waitUntilIsSaved (ido);
93
94         //!!! this is the failing line causing #50177
95
assertNotNull(Lookup.getDefault().lookupItem(new Lookup.Template (null, id, null)));
96     }
97
98     public void test50177Cause () throws Exception JavaDoc {
99         FileObject testFolder = FileUtil.createFolder(Repository.getDefault().getDefaultFileSystem().getRoot (), "Services");
100         assertNotNull(testFolder);
101         
102         InstanceDataObject ido = InstanceDataObject.create(DataFolder.findFolder(testFolder), "test50177Cause", new Ex50177(),null);
103         String JavaDoc idoName = ido.getName();
104         
105         Ex50177 exObj = (Ex50177)ido.instanceCreate();
106         assertNotNull(exObj);
107         assertEquals(idoName, ido.getName());
108         
109         exObj.setSomething("any value");//set any value shouldn't cause #50177
110
SerialDataConvertorTest.waitUntilIsSaved (ido);
111         //!!! this is the failing line causing #50177
112
assertEquals(idoName, ido.getName());
113     }
114
115     private static void waitUntilIsSaved (InstanceDataObject ido) throws InterruptedException JavaDoc {
116             SaveCookie sc = (SaveCookie)ido.getCookie(SaveCookie.class);
117             for (int i = 0; i < 5 && sc != null; i++) {
118                 Thread.sleep (3000);
119                 sc = (SaveCookie)ido.getCookie(SaveCookie.class);
120             }
121             assertNull(sc);
122     }
123     
124     public void test50177SideEffectsAfterRename () throws Exception JavaDoc {
125         FileObject testFolder = FileUtil.createFolder(Repository.getDefault().getDefaultFileSystem().getRoot (), "Services");
126         assertNotNull(testFolder);
127         
128         InstanceDataObject ido = InstanceDataObject.create(DataFolder.findFolder(testFolder), "test50177SideEffectsAfterRename", new Ex50177(),null);
129         FileObject fo = ido.getPrimaryFile();
130         fo.setAttribute("SystemFileSystem.localizingBundle", "org.netbeans.modules.settings.convertors.data.Bundle");
131         
132         String JavaDoc newName = "newName";
133         ido.getNodeDelegate().setName(newName);
134         SerialDataConvertorTest.waitUntilIsSaved (ido);
135         assertEquals(newName, ido.getNodeDelegate().getDisplayName());
136         
137         /// simulates recretaion of instance e.g. after IDE restart
138
fo = FileUtil.copyFile(fo, fo.getParent(),"copiedPeer", fo.getExt());
139         fo.setAttribute("SystemFileSystem.localizingBundle", "org.netbeans.modules.settings.convertors.data.Bundle");
140         ido = (InstanceDataObject)DataObject.find(fo);
141         
142         assertEquals(newName, ido.getNodeDelegate().getDisplayName());
143     }
144     
145     public static final class Ex50177 extends org.openide.ServiceType {
146     /** generated Serialized Version UID */
147         private static final long serialVersionUID = -7572487174423654252L;
148         private String JavaDoc name = "My Own Ex";
149         
150         protected String JavaDoc displayName() {
151             return name;
152         }
153         public HelpCtx getHelpCtx() {
154             return HelpCtx.DEFAULT_HELP;
155         }
156         
157         
158         private String JavaDoc something;
159         public String JavaDoc getSomething () {
160             return something;
161         }
162         public void setSomething (String JavaDoc s) {
163             String JavaDoc old = something;
164             something = s;
165             firePropertyChange("Something", old, s);
166         }
167
168         public void setName(String JavaDoc name) {
169             this.name = name;
170             firePropertyChange(name, null, name);
171         }
172     }
173     
174     /** Checks whether the instance is the same.
175      */

176     public void testSame() throws Exception JavaDoc {
177
178         Ser ser = new Ser ("1");
179         
180         InstanceDataObject i = InstanceDataObject.create (folder, null, ser, null);
181         
182         Object JavaDoc n = i.instanceCreate ();
183         if (n != ser) {
184             fail ("instanceCreate is not the same: " + ser + " != " + n);
185         }
186         
187         i.delete ();
188     }
189     
190     /** Test whether instances survive garbage collection.
191      */

192     public void testSameWithGC () throws Exception JavaDoc {
193         Object JavaDoc ser = new java.awt.Button JavaDoc();
194         
195         FileObject prim = InstanceDataObject.create (folder, "MyName", ser, null).getPrimaryFile ();
196         String JavaDoc name = prim.getName ();
197         String JavaDoc ext = prim.getExt ();
198         prim = null;
199
200         System.gc ();
201         System.gc ();
202         System.gc ();
203         System.gc ();
204         System.gc ();
205         System.gc ();
206         System.gc ();
207         System.gc ();
208         System.gc ();
209         
210         FileObject fo = folder.getPrimaryFile ().getFileObject (name, ext);
211         assertTrue ("MyName.settings not found", fo != null);
212         
213         DataObject obj = DataObject.find (fo);
214         
215         InstanceCookie ic = (InstanceCookie)obj.getCookie (InstanceCookie.class);
216         assertTrue ("Object: " + obj + " does not have instance cookie", ic != null);
217         
218         Object JavaDoc value = ic.instanceCreate ();
219         if (value != ser) {
220             fail ("Value is different than serialized: " + System.identityHashCode (ser) + " value: " + System.identityHashCode (value));
221         }
222         
223         obj.delete ();
224     }
225     
226     /** Tests the creation in atomic section.
227      */

228     public void testSameInAtomicSection () throws Exception JavaDoc {
229         class AtomAct extends FileChangeAdapter
230         implements FileSystem.AtomicAction {
231             
232             private java.awt.Button JavaDoc testSer = new java.awt.Button JavaDoc ();
233             
234             private FileObject data;
235             private InstanceDataObject obj;
236             
237             public void run () throws IOException {
238                 folder.getPrimaryFile ().addFileChangeListener (this);
239                 data = folder.getPrimaryFile ().createData ("SomeData");
240                 
241                 
242                 obj = InstanceDataObject.create (folder, null, testSer, null);
243             }
244             
245             public void doTest () throws Exception JavaDoc {
246                 Object JavaDoc now = obj.instanceCreate ();
247                 if (now != testSer) {
248                     fail ("Different values. Original: " + testSer + " now: " + now);
249                 }
250             }
251             
252             public void cleanUp () throws Exception JavaDoc {
253                 data.delete ();
254                 obj.delete ();
255             }
256             
257             public void fileDataCreated (FileEvent ev) {
258                 try {
259                     Thread.sleep (500);
260                 } catch (Exception JavaDoc ex) {
261                 }
262             }
263         }
264
265         
266         AtomAct t = new AtomAct ();
267         try {
268             folder.getPrimaryFile().getFileSystem ().runAtomicAction (t);
269
270             t.doTest ();
271         } finally {
272             t.cleanUp ();
273         }
274     }
275
276     /** Tests whether createFromTemplate works correctly.
277     */

278     public void testCreateFromTemplateForSettingsFile () throws Exception JavaDoc {
279         Object JavaDoc ser = new java.awt.Button JavaDoc ();
280
281         InstanceDataObject obj = InstanceDataObject.create (folder, "SomeName", ser, null);
282         obj.setTemplate (true);
283
284         DataObject newObj = obj.createFromTemplate(folder, "NewName");
285         
286         if (!newObj.getName().equals ("NewName")) {
287             fail ("Wrong name of new data object: " + newObj.getName ());
288         }
289
290         InstanceCookie ic = (InstanceCookie)newObj.getCookie (InstanceCookie.class);
291         
292         if (ic == null) {
293             fail ("No instance cookie for " + newObj);
294         }
295
296         if (ic.instanceCreate () != ser) {
297             fail ("created instance is different than the original in template");
298         }
299         
300         if (ic.instanceCreate () == obj.instanceCreate ()) {
301             fail ("Instance of the new object is same as the current of the template");
302         }
303     }
304     
305     /** Test if the Lookup reflects IDO' cokie changes. */
306     public void testLookupRefreshOfInstanceCookieChanges() throws Exception JavaDoc {
307 // Object ser = new java.awt.Button ();
308
Object JavaDoc ser = new java.beans.beancontext.BeanContextChildSupport JavaDoc();
309
310         FileObject lookupFO = lfs.findResource("/system/Services/lookupTest");
311         FileObject systemFO = lfs.findResource("/system");
312         
313         FolderLookup lookup = new FolderLookup(DataFolder.findFolder(systemFO));
314         Lookup l = lookup.getLookup();
315         DataFolder folderTest = DataFolder.findFolder(lookupFO);
316         
317         InstanceDataObject ido = InstanceDataObject.create (folderTest, "testLookupRefresh", ser, null);
318         Lookup.Result res = l.lookup(new Lookup.Template(ser.getClass()));
319         Collection col = res.allInstances ();
320         InstanceCookie ic = (InstanceCookie) ido.getCookie(InstanceCookie.class);
321         assertEquals("IDO did not create new InstanceCookie", ser, ic.instanceCreate());
322         
323         Set origSet = new HashSet(Arrays.asList(new Object JavaDoc[] {ser}));
324         assertEquals("wrong lookup result", origSet, new HashSet(col));
325         
326         assertTrue("Lookup is not finished and surprisingly returned a result", lookup.isFinished ());
327         
328         Object JavaDoc found = col.iterator().next();
329         assertEquals("found wrong object instance", ser, found);
330         
331         // due to #14795 workaround
332
Thread.sleep(1000);
333         
334         // external file change forcing IDO to create new InstanceCookie
335
final FileObject fo = ido.getPrimaryFile();
336         lfs.runAtomicAction(new FileSystem.AtomicAction() {
337             public void run() throws IOException {
338                 FileLock lock = null;
339                 try {
340                     InputStream in = fo.getInputStream();
341                     byte[] buf = new byte[(int)fo.getSize()];
342                     in.read(buf);
343                     in.close();
344
345                     lock = fo.lock();
346                     OutputStream out = fo.getOutputStream(lock);
347                     out.write(buf);
348                     out.write(32);
349                     out.flush();
350                     out.close();
351                     
352                 } finally {
353                     if (lock != null) lock.releaseLock();
354                 }
355             }
356         });
357         
358         col = res.allInstances ();
359         ic = (InstanceCookie) ido.getCookie(InstanceCookie.class);
360         origSet = new HashSet(Arrays.asList(new Object JavaDoc[] {ic.instanceCreate()}));
361         
362         assertEquals("wrong lookup result", origSet, new HashSet(col));
363         
364         found = col.iterator().next();
365         assertTrue("IDO did not create new InstanceCookie", ser != ic.instanceCreate());
366         assertTrue("Lookup did not refresh changed InstanceCookie", ser != found);
367     }
368     /*
369     private void assertEquals(boolean b1, boolean b2) {
370         assertEquals(b1 ? Boolean.TRUE : Boolean.FALSE, b2 ? Boolean.TRUE : Boolean.FALSE);
371     }
372     */

373     /** Checks whether the instance is not saved multiple times.
374      *
375     public void testMultiSave () throws Exception {
376         Ser ser1 = new Ser ("1");
377         Ser ser2 = new Ser ("2");
378         
379         InstanceDataObject i = InstanceDataObject.create (folder, null, ser1, null);
380         
381         Thread.sleep (3000);
382         
383         InstanceDataObject j = InstanceDataObject.create (folder, null, ser2, null);
384         Thread.sleep (3000);
385         
386         Object n = i.instanceCreate ();
387         if (n != ser1) {
388             fail ("instanceCreate is not the same: ");
389         }
390         i.instanceCreate ();
391         j.instanceCreate ();
392         j.instanceCreate ();
393         
394     } */

395     
396     public static final class Ser extends Object JavaDoc implements Externalizable {
397         static final long serialVersionUID = -123456;
398         public int deserialized;
399         public int serialized;
400         private String JavaDoc name;
401         
402         private int property;
403         
404         private java.beans.PropertyChangeSupport JavaDoc propertyChangeSupport = new java.beans.PropertyChangeSupport JavaDoc(this);
405         
406         public Ser (String JavaDoc name) {
407             this.name = name;
408         }
409         
410         public synchronized void readExternal(java.io.ObjectInput JavaDoc objectInput)
411         throws java.io.IOException JavaDoc, java.lang.ClassNotFoundException JavaDoc {
412 // System.err.println(name + " deserialized");
413
deserialized++;
414         }
415         
416         public synchronized void writeExternal(java.io.ObjectOutput JavaDoc objectOutput)
417         throws java.io.IOException JavaDoc {
418 // System.err.println(name + " serialized");
419
serialized++;
420         }
421         
422         public void addPropertyChangeListener(java.beans.PropertyChangeListener JavaDoc l) {
423             propertyChangeSupport.addPropertyChangeListener(l);
424         }
425         
426         public void removePropertyChangeListener(java.beans.PropertyChangeListener JavaDoc l) {
427             propertyChangeSupport.removePropertyChangeListener(l);
428         }
429         
430         public int getProperty() {
431             return this.property;
432         }
433         
434         public void setProperty(int property) {
435             int oldProperty = this.property;
436             this.property = property;
437             propertyChangeSupport.firePropertyChange("property", new Integer JavaDoc(oldProperty), new Integer JavaDoc(property));
438         }
439         
440     }
441     
442     /** Tests creating .settings file (<code>IDO.create</code>) using parameter
443      * <code>create</code>
444      */

445     public void testCreateSettings() throws Exception JavaDoc {
446         FileObject fo = lfs.findResource("/testCreateInstance");
447         assertNotNull("missing folder /testCreateInstance", fo);
448         DataFolder folder = DataFolder.findFolder(fo);
449         assertNotNull("cannot find DataFolder /testCreateInstance", folder);
450         
451         // test non null filename
452
String JavaDoc filename = "testCreateSettings";
453         Object JavaDoc obj = new javax.swing.JButton JavaDoc();
454         InstanceDataObject ido = InstanceDataObject.create(folder, filename, obj, null, false);
455         assertNotNull("InstanceDataObject.create cannot return null!", ido);
456         
457         InstanceDataObject ido2 = InstanceDataObject.create(folder, filename, obj, null, false);
458         assertNotNull("InstanceDataObject.create cannot return null!", ido2);
459         assertEquals("InstanceDataObject.create(..., false) must reuse existing file: ",
460             ido.getPrimaryFile(), ido2.getPrimaryFile());
461         
462         for (int i = 0; i < 3; i++) {
463             ido2 = InstanceDataObject.create(folder, filename, obj, null, true);
464             assertNotNull("InstanceDataObject.create cannot return null!", ido2);
465             assertTrue("InstanceDataObject.create(..., true) must create new file: "
466                 + "step: " + i + ", "
467                 + ido2.getPrimaryFile(), ido.getPrimaryFile() != ido2.getPrimaryFile());
468         }
469         
470         // test null filename
471
ido = InstanceDataObject.create(folder, null, obj, null, false);
472         assertNotNull("InstanceDataObject.create cannot return null!", ido);
473         
474         ido2 = InstanceDataObject.create(folder, null, obj, null, false);
475         assertNotNull("InstanceDataObject.create cannot return null!", ido2);
476         // filename == null => always create new file (ignore create parameter) => backward compatibility
477
assertTrue("InstanceDataObject.create(..., false) must create new file: "
478             + ido2.getPrimaryFile(), ido.getPrimaryFile() != ido2.getPrimaryFile());
479         
480         for (int i = 0; i < 3; i++) {
481             ido2 = InstanceDataObject.create(folder, null, obj, null, true);
482             assertNotNull("InstanceDataObject.create cannot return null!", ido2);
483             assertTrue("InstanceDataObject.create(..., true) must create new file: "
484                 + ido2.getPrimaryFile(), ido.getPrimaryFile() != ido2.getPrimaryFile());
485         }
486     }
487     
488     public void testDeleteSettings() throws Exception JavaDoc {
489         FileObject root = lfs.getRoot();
490         DataFolder folder = DataFolder.findFolder(root);
491         
492         String JavaDoc filename = "testDeleteSettings";
493         javax.swing.JButton JavaDoc obj = new javax.swing.JButton JavaDoc();
494         InstanceDataObject ido = InstanceDataObject.create(folder, filename, obj, null, false);
495         assertNotNull("InstanceDataObject.create cannot return null!", ido);
496         
497         // test if file object does not remain locked when ido is deleted and
498
// the storing is not rescheduled in consequence of the serialization
499
obj.setForeground(java.awt.Color.black);
500         Thread.sleep(500);
501         ido.delete();
502         assertNull(filename + ".settings was not deleted!", root.getFileObject(filename));
503         Thread.sleep(3000);
504         assertNull(filename + ".settings was not deleted!", root.getFileObject(filename));
505         
506         filename = "testDeleteSettings2";
507         Ser ser = new Ser("bla");
508         ido = InstanceDataObject.create(folder, filename, ser, null, false);
509         assertNotNull("InstanceDataObject.create cannot return null!", ido);
510         
511         ser.setProperty(10);
512         ido.delete();
513         assertNull(filename + ".settings was not deleted!", root.getFileObject(filename));
514         Thread.sleep(3000);
515         assertNull(filename + ".settings was not deleted!", root.getFileObject(filename));
516     }
517
518     public void testDisabledOrUnknownModule() throws Exception JavaDoc {
519         final FileObject valid = lfs.findResource("/Settings/org-netbeans-modules-settings-convertors-FooSettingDisabledOrUnknownModule.settings");
520         assertNotNull(valid);
521         DataObject ido = DataObject.find(valid);
522         InstanceCookie ic = (InstanceCookie) ido.getCookie(InstanceCookie.class);
523         assertNull("There shouldn't be provided InstanceCookie for disabled module", ic);
524     }
525
526     public void testDeleteOfUnrecognizedSettingsFile () throws Exception JavaDoc {
527         final FileObject corrupted = lfs.findResource("/Settings/org-netbeans-modules-settings-convertors-FooSettingUnrecognizedSettingsFile.settings");
528         assertNotNull(corrupted);
529         
530         DataObject ido = DataObject.find(corrupted);
531         org.openide.nodes.Node node = ido.getNodeDelegate();
532         node.destroy();
533         FileObject corrupted2 = lfs.findResource("/Settings/org-netbeans-modules-settings-convertors-FooSettingUnrecognizedSettingsFile.settings");
534         assertNull(corrupted2);
535     }
536     
537     public void testCorruptedSettingsFile() throws Exception JavaDoc {
538         final FileObject corrupted = lfs.findResource("/Settings/org-netbeans-modules-settings-convertors-FooSettingSerialDataCorruptedTest.settings");
539         assertNotNull(corrupted);
540         
541         DataObject ido = DataObject.find(corrupted);
542         InstanceCookie ic = (InstanceCookie) ido.getCookie(InstanceCookie.class);
543         assertNotNull("Missing InstanceCookie", ic);
544         
545         Object JavaDoc obj = null;
546         try {
547             obj = ic.instanceCreate();
548         } catch (IOException ex) {
549         }
550         assertNull("corrupted .settings file cannot provide an object", obj);
551         
552         final FileObject valid = lfs.findResource("/Settings/org-netbeans-modules-settings-convertors-FooSettingSerialDataCorruptedTest2.settings");
553         assertNotNull(valid);
554         
555         // simulate revert to default of a corrupted setting object
556
corrupted.getFileSystem().runAtomicAction(new FileSystem.AtomicAction() {
557             public void run() throws IOException {
558                 FileLock l = null;
559                 OutputStream os = null;
560                 try {
561                     l = corrupted.lock();
562                     os = corrupted.getOutputStream(l);
563                     FileUtil.copy(valid.getInputStream(), os);
564                     os.flush();
565                 } finally {
566                     if (os != null) try { os.close(); } catch (IOException ex) {}
567                     if (l != null) l.releaseLock();
568                 }
569             }
570         });
571         
572         ic = (InstanceCookie) ido.getCookie(InstanceCookie.class);
573         assertNotNull("Missing InstanceCookie", ic);
574         assertNotNull("the persisted object cannot be read", ic.instanceCreate());
575     }
576 }
577
Popular Tags