KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openide > util > lookup > AbstractLookupBaseHid


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.util.lookup;
21
22 import javax.swing.ActionMap JavaDoc;
23 import javax.swing.InputMap JavaDoc;
24 import org.openide.util.*;
25
26 import java.lang.ref.WeakReference JavaDoc;
27 import java.util.*;
28 import junit.framework.*;
29 import org.netbeans.junit.*;
30 import java.io.Serializable JavaDoc;
31 import org.openide.util.Lookup.Template;
32
33 public class AbstractLookupBaseHid extends NbTestCase {
34     private static AbstractLookupBaseHid running;
35
36     /** instance content to work with */
37     InstanceContent ic;
38     /** the lookup to work on */
39     protected Lookup instanceLookup;
40     /** the lookup created to work with */
41     private Lookup lookup;
42     /** implementation of methods that can influence the behaviour */
43     Impl impl;
44     
45     protected AbstractLookupBaseHid(java.lang.String JavaDoc testName, Impl impl) {
46         super(testName);
47         if (impl == null && (this instanceof Impl)) {
48             impl = (Impl)this;
49         }
50         this.impl = impl;
51     }
52     
53     protected void setUp () {
54         this.ic = new InstanceContent ();
55         this.instanceLookup = createInstancesLookup (ic);
56         this.lookup = createLookup (instanceLookup);
57         running = this;
58     }
59     
60     protected void tearDown () {
61         running = null;
62     }
63     
64     /** The methods to influence test behaviour */
65     public static interface Impl {
66         /** Creates the initial abstract lookup.
67          */

68         public Lookup createInstancesLookup (InstanceContent ic);
69         /** Creates an lookup for given lookup. This class just returns
70          * the object passed in, but subclasses can be different.
71          * @param lookup in lookup
72          * @return a lookup to use
73          */

74         public Lookup createLookup (Lookup lookup);
75         
76         /** If the impl has any caches that would prevent the system
77          * to not garbage collect correctly, then clear them now.
78          */

79         public void clearCaches ();
80     }
81     
82     private Lookup createInstancesLookup (InstanceContent ic) {
83         return impl.createInstancesLookup (ic);
84     }
85     
86     private Lookup createLookup (Lookup lookup) {
87         return impl.createLookup (lookup);
88     }
89     
90     /** instances that we register */
91     private static Object JavaDoc[] INSTANCES = new Object JavaDoc[] {
92         new Integer JavaDoc (10),
93         new Object JavaDoc ()
94     };
95     
96     /** Test if first is really first.
97      */

98     public void testFirst () {
99         Object JavaDoc i1 = new Integer JavaDoc (1);
100         Object JavaDoc i2 = new Integer JavaDoc (2);
101         
102         ic.add (i1);
103         ic.add (i2);
104         
105         Object JavaDoc found = lookup.lookup (Integer JavaDoc.class);
106         if (found != i1) {
107             fail ("First object is not first: " + found + " != " + i1);
108         }
109         
110         ArrayList list = new ArrayList ();
111         list.add (i2);
112         list.add (i1);
113         ic.set (list, null);
114         
115         found = lookup.lookup (Integer JavaDoc.class);
116         if (found != i2) {
117             fail ("Second object is not first after reorder: " + found + " != " + i2);
118         }
119         
120     }
121     
122
123
124     /** Tests ordering of items in the lookup.
125     */

126     public void testOrder () {
127         addInstances (INSTANCES);
128
129         if (INSTANCES[0] != lookup.lookup (INSTANCES[0].getClass ())) {
130             fail ("First object in intances not found");
131         }
132
133         Iterator all = lookup.lookup (new Lookup.Template (Object JavaDoc.class)).allInstances ().iterator ();
134         checkIterator ("Difference between instances added and found", all, Arrays.asList (INSTANCES));
135     }
136     
137     /** Checks the reorder of items in lookup reflects the result.
138      * Testing both classes and interfaces, because they are often treated
139      * especially.
140      */

141     public void testReorder () {
142         String JavaDoc s1 = "s2";
143         String JavaDoc s2 = "s1";
144         Runnable JavaDoc r1 = new Runnable JavaDoc () {
145             public void run () {}
146         };
147         Runnable JavaDoc r2 = new Runnable JavaDoc () {
148             public void run () {}
149         };
150         ArrayList l = new ArrayList ();
151
152         l.add (s1);
153         l.add (s2);
154         l.add (r1);
155         l.add (r2);
156         ic.set (l, null);
157      
158         assertEquals ("s1 is found", s1, lookup.lookup (String JavaDoc.class));
159         assertEquals ("r1 is found", r1, lookup.lookup (Runnable JavaDoc.class));
160         
161         Collections.reverse (l);
162         
163         ic.set (l, null);
164         
165         assertEquals ("s2 is found", s2, lookup.lookup (String JavaDoc.class));
166         assertEquals ("r2 is found", r2, lookup.lookup (Runnable JavaDoc.class));
167     }
168     
169     /** Tries to set empty collection to the lookup.
170      */

171     public void testSetEmpty () {
172         ic.add ("A serializable string");
173         lookup.lookup (Serializable JavaDoc.class);
174         
175         ic.set (Collections.EMPTY_LIST, null);
176     }
177     
178     /** Tests a more complex reorder on nodes.
179      */

180     public void testComplexReorder () {
181         Integer JavaDoc i1 = new Integer JavaDoc (1);
182         Long JavaDoc i2 = new Long JavaDoc (2);
183         
184         ArrayList l = new ArrayList ();
185         l.add (i1);
186         l.add (i2);
187         ic.set (l, null);
188         
189         assertEquals ("Find integer", i1, lookup.lookup (Integer JavaDoc.class));
190         assertEquals ("Find long", i2, lookup.lookup (Long JavaDoc.class));
191         assertEquals ("Find number", i1, lookup.lookup (Number JavaDoc.class));
192         
193         Collections.reverse (l);
194         
195         ic.set (l, null);
196         
197         assertEquals ("Find integer", i1, lookup.lookup (Integer JavaDoc.class));
198         assertEquals ("Find long", i2, lookup.lookup (Long JavaDoc.class));
199         assertEquals ("Find number", i2, lookup.lookup (Number JavaDoc.class));
200     }
201     
202     /** Checks whether setPairs keeps the order.
203      */

204     public void testSetPairs () {
205         // test setPairs method
206
ArrayList li = new ArrayList();
207         li.addAll (Arrays.asList (INSTANCES));
208         ic.set (li, null);
209         
210         Lookup.Result res = lookup.lookup (new Lookup.Template (Object JavaDoc.class));
211         Iterator all = res.allInstances ().iterator ();
212         checkIterator ("Original order not kept", all, li);
213         
214         // reverse the order
215
Collections.reverse (li);
216         
217         // change the pairs
218
LL listener = new LL (res);
219         res.addLookupListener (listener);
220         ic.set (li, null);
221         if (listener.getCount () != 1) {
222             fail ("Result has not changed even we set reversed order");
223         }
224         
225         all = res.allInstances ().iterator ();
226         checkIterator ("Reversed order not kept", all, li);
227     }
228
229     /** Checks whether setPairs fires correct events.
230      */

231     public void testSetPairsFire () {
232         // test setPairs method
233
ArrayList li = new ArrayList();
234         li.addAll (Arrays.asList (INSTANCES));
235         ic.set (li, null);
236         
237         Lookup.Result res = lookup.lookup (new Lookup.Template (Integer JavaDoc.class));
238         Iterator all = res.allInstances ().iterator ();
239         checkIterator ("Integer is not there", all, Collections.nCopies (1, INSTANCES[0]));
240         
241         // change the pairs
242
LL listener = new LL (res);
243         res.addLookupListener (listener);
244
245         ArrayList l2 = new ArrayList (li);
246         l2.remove (INSTANCES[0]);
247         ic.set (l2, null);
248
249         all = lookup.lookup (new Lookup.Template (Object JavaDoc.class)).allInstances ().iterator ();
250         checkIterator ("The removed integer is not noticed", all, l2);
251
252         if (listener.getCount () != 1) {
253             fail ("Nothing has not been fired");
254         }
255     }
256
257     /** Checks whether set pairs does not fire when they should not.
258     */

259     public void testSetPairsDoesNotFire () {
260         Object JavaDoc tmp = new Object JavaDoc ();
261
262         ArrayList li = new ArrayList();
263         li.add (tmp);
264         li.addAll (Arrays.asList (INSTANCES));
265         ic.set (li, null);
266         
267         Lookup.Result res = lookup.lookup (new Lookup.Template (Integer JavaDoc.class));
268         Iterator all = res.allInstances ().iterator ();
269         checkIterator ("Integer is not there", all, Collections.nCopies (1, INSTANCES[0]));
270         
271         // change the pairs
272
LL listener = new LL (res);
273         res.addLookupListener (listener);
274
275         ArrayList l2 = new ArrayList (li);
276         l2.remove (tmp);
277         ic.set (l2, null);
278
279         all = lookup.lookup (new Lookup.Template (Object JavaDoc.class)).allInstances ().iterator ();
280         checkIterator ("The removed integer is not noticed", all, l2);
281
282         if (listener.getCount () != 0) {
283             fail ("Something has been fired");
284         }
285     }
286     
287     /** Test whether after registration it is possible to find registered objects
288     *
289      */

290     public void testLookupAndAdd () throws Exception JavaDoc {
291         addInstances (INSTANCES);
292
293         for (int i = 0; i < INSTANCES.length; i++) {
294             Object JavaDoc obj = INSTANCES[i];
295             findAll (lookup, obj.getClass (), true);
296         }
297     }
298
299     /** Tries to find all classes and superclasses in the lookup.
300     */

301     private void findAll (Lookup lookup, Class JavaDoc clazz, boolean shouldBeThere) {
302         if (clazz == null) return;
303
304         Object JavaDoc found = lookup.lookup (clazz);
305         if (found == null) {
306             if (shouldBeThere) {
307                 // should find at either instance or something else, but must
308
// find at least something
309
fail ("Lookup (" + clazz.getName () + ") found nothing");
310             }
311         } else {
312             if (!shouldBeThere) {
313                 // should find at either instance or something else, but must
314
// find at least something
315
fail ("Lookup (" + clazz.getName () + ") found " + found);
316             }
317         }
318
319         Lookup.Result res = lookup.lookup (new Lookup.Template (clazz));
320         Collection collection = res.allInstances ();
321
322         for (int i = 0; i < INSTANCES.length; i++) {
323             boolean isSubclass = clazz.isInstance (INSTANCES[i]);
324             boolean isThere = collection.contains (INSTANCES[i]);
325
326             if (isSubclass != isThere) {
327                 // a problem found
328
// should find at either instance or something else, but must
329
// find at least something
330
fail ("Lookup.Result (" + clazz.getName () + ") for " + INSTANCES[i] + " is subclass: " + isSubclass + " isThere: " + isThere);
331             }
332         }
333
334         // go on for superclasses
335

336         findAll (lookup, clazz.getSuperclass (), shouldBeThere);
337
338         Class JavaDoc[] ies = clazz.getInterfaces ();
339         for (int i = 0; i < ies.length; i++) {
340             findAll (lookup, ies[i], shouldBeThere);
341         }
342     }
343     
344     /** Test if it is possible to remove a registered object. */
345     public void testRemoveRegisteredObject() {
346         Integer JavaDoc inst = new Integer JavaDoc(10);
347         
348         ic.add(inst);
349         if (lookup.lookup(inst.getClass()) == null) {
350             // should find an instance
351
fail("Lookup (" + inst.getClass().getName () + ") found nothing");
352         }
353         
354         ic.remove(inst);
355         if (lookup.lookup(inst.getClass()) != null) {
356             // should NOT find an instance
357
fail("Lookup (" + inst.getClass().getName () +
358                 ") found an instance after remove operation");
359         }
360     }
361     
362     public void testCanReturnReallyStrangeResults () throws Exception JavaDoc {
363         class QueryingPair extends org.openide.util.lookup.AbstractLookup.Pair {
364             private Integer JavaDoc i = new Integer JavaDoc (434);
365             
366             //
367
// do the test
368
//
369

370             public void doTest () throws Exception JavaDoc {
371                 ic.add (i);
372                 ic.addPair (this);
373                 
374                 Object JavaDoc found = lookup.lookup (QueryingPair.class);
375                 assertEquals ("This object is found", this, found);
376             }
377             
378             
379             //
380
// Implementation of pair
381
//
382

383             public java.lang.String JavaDoc getId() {
384                 return getType ().toString();
385             }
386
387             public java.lang.String JavaDoc getDisplayName() {
388                 return getId ();
389             }
390
391             public java.lang.Class JavaDoc getType() {
392                 return getClass ();
393             }
394
395             protected boolean creatorOf(java.lang.Object JavaDoc obj) {
396                 return obj == this;
397             }
398
399             protected boolean instanceOf(java.lang.Class JavaDoc c) {
400                 assertEquals ("Integer found or exception is thrown", i, lookup.lookup (Integer JavaDoc.class));
401                 return c.isAssignableFrom(getType ());
402             }
403
404             public java.lang.Object JavaDoc getInstance() {
405                 return this;
406             }
407             
408             
409         }
410         
411         
412         QueryingPair qp = new QueryingPair ();
413         qp.doTest ();
414     }
415     
416     /** Test of firing events. */
417     public void testLookupListener() {
418         Integer JavaDoc inst = new Integer JavaDoc(10);
419         Lookup.Result res = lookup.lookup(new Lookup.Template(inst.getClass()));
420         res.allInstances ();
421         
422         LL listener = new LL(res);
423         res.addLookupListener(listener);
424         
425         ic.add(inst);
426         if (listener.getCount() == 0) {
427             fail("None event fired during NbLookup.addPair()");
428         }
429         
430         ic.remove(inst);
431         if (listener.getCount() == 0) {
432             fail("None event fired during NbLookup.removePair()");
433         }
434         
435         ic.add(inst);
436         if (listener.getCount() == 0) {
437             fail("None event fired during second NbLookup.addPair()");
438         }
439         
440         ic.remove(inst);
441         if (listener.getCount() == 0) {
442             fail("None event fired during second NbLookup.removePair()");
443         }
444     }
445     
446     /** Testing identity of the lookup.
447      */

448     public void testId () {
449         AbstractLookup.Template templ;
450         int cnt;
451         
452         addInstances (INSTANCES);
453         
454         AbstractLookup.Result res = lookup.lookup (new AbstractLookup.Template ());
455         Iterator it;
456         it = res.allItems ().iterator ();
457         while (it.hasNext ()) {
458             AbstractLookup.Item item = (AbstractLookup.Item)it.next ();
459             
460             templ = new AbstractLookup.Template (null, item.getId (), null);
461             cnt = lookup.lookup (templ).allInstances ().size ();
462             if (cnt != 1) {
463                 fail ("Identity lookup failed. Instances = " + cnt);
464             }
465
466             templ = new AbstractLookup.Template (item.getType (), item.getId (), null);
467             cnt = lookup.lookup (templ).allInstances ().size ();
468             if (cnt != 1) {
469                 fail ("Identity lookup with type failed. Instances = " + cnt);
470             }
471             
472             templ = new AbstractLookup.Template (this.getClass (), item.getId (), null);
473             cnt = lookup.lookup (templ).allInstances ().size ();
474             if (cnt != 0) {
475                 fail ("Identity lookup with wrong type failed. Instances = " + cnt);
476             }
477             
478             templ = new AbstractLookup.Template (null, null, item.getInstance ());
479             cnt = lookup.lookup (templ).allInstances ().size ();
480             if (cnt != 1) {
481                 fail ("Instance lookup failed. Instances = " + cnt);
482             }
483
484             templ = new AbstractLookup.Template (null, item.getId (), item.getInstance ());
485             cnt = lookup.lookup (templ).allInstances ().size ();
486             if (cnt != 1) {
487                 fail ("Instance & identity lookup failed. Instances = " + cnt);
488             }
489             
490         }
491     }
492     
493     /** Tests adding and removing.
494      */

495     public void testAddAndRemove () throws Exception JavaDoc {
496         Object JavaDoc map = new javax.swing.ActionMap JavaDoc ();
497         LL ll = new LL ();
498         
499         Lookup.Result res = lookup.lookup (new Lookup.Template (map.getClass ()));
500         res.allItems();
501         res.addLookupListener (ll);
502         ll.source = res;
503         
504         ic.add (map);
505         
506         assertEquals ("First change when adding", ll.getCount (), 1);
507         
508         ic.remove (map);
509         
510         assertEquals ("Second when removing", ll.getCount (), 1);
511         
512         ic.add (map);
513         
514         assertEquals ("Third when readding", ll.getCount (), 1);
515         
516         ic.remove (map);
517         
518         assertEquals ("Forth when reremoving", ll.getCount (), 1);
519         
520     }
521     
522     /** Will a class garbage collect even it is registered in lookup.
523      */

524     public void testGarbageCollect () throws Exception JavaDoc {
525         ClassLoader JavaDoc l = new CL ();
526         Class JavaDoc c = l.loadClass (Garbage.class.getName ());
527         WeakReference JavaDoc ref = new WeakReference JavaDoc (c);
528
529         lookup.lookup (c);
530         
531         // now test garbage collection
532
c = null;
533         l = null;
534         impl.clearCaches ();
535         assertGC ("The classloader has not been garbage collected!", ref);
536     }
537                 
538     /** Items are the same as results.
539      */

540     public void testItemsAndIntances () {
541         addInstances (INSTANCES);
542         
543         Lookup.Template t = new Lookup.Template (Object JavaDoc.class);
544         Lookup.Result r = lookup.lookup (t);
545         Collection items = r.allItems ();
546         Collection insts = r.allInstances ();
547         
548         if (items.size () != insts.size ()) {
549             fail ("Different size of sets");
550         }
551         
552         Iterator it = items.iterator ();
553         while (it.hasNext ()) {
554             Lookup.Item item = (Lookup.Item)it.next ();
555             if (!insts.contains (item.getInstance ())) {
556                 fail ("Intance " + item.getInstance () + " is missing in " + insts);
557             }
558         }
559     }
560     
561     /** Checks search for interface.
562      */

563     public void testSearchForInterface () {
564         Lookup.Template t = new Lookup.Template (Serializable JavaDoc.class, null, null);
565         
566         assertNull("Nothing to find", lookup.lookupItem (t));
567         
568         Serializable JavaDoc s = new Serializable JavaDoc () {};
569         ic.add (s);
570         
571         Lookup.Item item = lookup.lookupItem (t);
572         assertNotNull ("Something found", item);
573     }
574
575     /** Test to add broken item if it incorrectly answers instanceOf questions.
576      */

577     public void testIncorectInstanceOf40364 () {
578         final Long JavaDoc sharedLong = new Long JavaDoc (0);
579         
580         class P extends AbstractLookup.Pair {
581             public boolean isLong;
582             
583             P (boolean b) {
584                 isLong = b;
585             }
586             
587             protected boolean creatorOf (Object JavaDoc obj) {
588                 return obj == sharedLong;
589             }
590             
591             public String JavaDoc getDisplayName () {
592                 return "";
593             }
594             
595             public String JavaDoc getId () {
596                 return "";
597             }
598             
599             public Object JavaDoc getInstance () {
600                 return sharedLong;
601             }
602             
603             public Class JavaDoc getType () {
604                 return isLong ? Long JavaDoc.class : Number JavaDoc.class;
605             }
606             
607             protected boolean instanceOf (Class JavaDoc c) {
608                 return c.isAssignableFrom (getType ());
609             }
610     
611             public int hashCode () {
612                 return getClass ().hashCode ();
613             }
614
615             public boolean equals (Object JavaDoc obj) {
616                 return obj != null && getClass ().equals (obj.getClass ());
617             }
618         }
619         
620         // to create the right structure in the lookup
621
lookup.lookup (Object JavaDoc.class);
622         lookup.lookup (Long JavaDoc.class);
623         lookup.lookup (Number JavaDoc.class);
624         
625         P lng1 = new P (true);
626         ic.addPair (lng1);
627
628         P lng2 = new P (false);
629         ic.setPairs (Collections.singleton (lng2));
630         
631         Collection res = lookup.lookup (new Lookup.Template (Object JavaDoc.class)).allItems ();
632         assertEquals ("Just one pair", 1, res.size ());
633     }
634
635     public void testAbsolutelyCrazyWayToSimulateIssue48590ByChangingTheBehaviourOfEqualOnTheFly () throws Exception JavaDoc {
636         class X implements testInterfaceInheritanceA, testInterfaceInheritanceB {
637         }
638         final X shared = new X ();
639         
640         class P extends AbstractLookup.Pair {
641             public int howLong;
642             
643             P (int b) {
644                 howLong = b;
645             }
646             
647             protected boolean creatorOf (Object JavaDoc obj) {
648                 return obj == shared;
649             }
650             
651             public String JavaDoc getDisplayName () {
652                 return "";
653             }
654             
655             public String JavaDoc getId () {
656                 return "";
657             }
658             
659             public Object JavaDoc getInstance () {
660                 return shared;
661             }
662             
663             public Class JavaDoc getType () {
664                 return howLong == 0 ? testInterfaceInheritanceB.class : testInterfaceInheritanceA.class;
665             }
666             
667             protected boolean instanceOf (Class JavaDoc c) {
668                 return c.isAssignableFrom (getType ());
669             }
670     
671             public int hashCode () {
672                 return getClass ().hashCode ();
673             }
674
675             public boolean equals (Object JavaDoc obj) {
676                 if (obj instanceof P) {
677                     P p = (P)obj;
678                     if (this.howLong > 0) {
679                         this.howLong--;
680                         return false;
681                     }
682                     if (p.howLong > 0) {
683                         p.howLong--;
684                         return false;
685                     }
686                     return getClass ().equals (p.getClass ());
687                 }
688                 return false;
689             }
690         }
691         
692         // to create the right structure in the lookup
693
Lookup.Result a = lookup.lookup (new Lookup.Template (testInterfaceInheritanceA.class));
694         Lookup.Result b = lookup.lookup (new Lookup.Template (testInterfaceInheritanceB.class));
695         
696         P lng1 = new P (0);
697         ic.addPair (lng1);
698         
699         assertEquals ("One in a", 1, a.allItems ().size ());
700         assertEquals ("One in b", 1, b.allItems ().size ());
701
702         P lng2 = new P (1);
703         
704
705         /* Following call used to generate this exception:
706     java.lang.IllegalStateException: Duplicate pair in treePair1: pair2: index1: 0 index2: 0 item1: org.openide.util.lookup.AbstractLookupBaseHid$1X@1a457b6 item2: org.openide.util.lookup.AbstractLookupBaseHid$1X@1a457b6 id1: 7a78d3 id2: 929206
707     at org.openide.util.lookup.ALPairComparator.compare(ALPairComparator.java:52)
708     at java.util.Arrays.mergeSort(Arrays.java:1284)
709     at java.util.Arrays.sort(Arrays.java:1223)
710     at java.util.Collections.sort(Collections.java:159)
711     at org.openide.util.lookup.InheritanceTree.retainAllInterface(InheritanceTree.java:753)
712     at org.openide.util.lookup.InheritanceTree.retainAll(InheritanceTree.java:183)
713     at org.openide.util.lookup.DelegatingStorage.retainAll(DelegatingStorage.java:83)
714     at org.openide.util.lookup.AbstractLookup.setPairsAndCollectListeners(AbstractLookup.java:238)
715     at org.openide.util.lookup.AbstractLookup.setPairs(AbstractLookup.java:203)
716     at org.openide.util.lookup.AbstractLookup$Content.setPairs(AbstractLookup.java:885)
717     at org.openide.util.lookup.AbstractLookupBaseHid.testAbsolutelyCrazyWayToSimulateIssue48590ByChangingTheBehaviourOfEqualOnTheFly(AbstractLookupBaseHid.java:696)
718     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
719     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
720     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
721     at org.netbeans.junit.NbTestCase.run(NbTestCase.java:119)
722     */

723         ic.setPairs (Collections.singleton (lng2));
724
725         
726     }
727     
728     public void testInstancesArePreservedFoundWhenFixing48590 () throws Exception JavaDoc {
729         class X implements Runnable JavaDoc, Serializable JavaDoc {
730             public void run () {
731                 
732             }
733             
734             public void assertOnlyMe (String JavaDoc msg, Lookup.Result res) {
735                 Collection col = res.allInstances ();
736                 assertEquals (msg + " just one", 1, col.size ());
737                 assertSame (msg + " and it is me", this, col.iterator ().next ());
738             }
739         }
740         
741         Lookup.Result runnable = lookup.lookup (new Lookup.Template (Runnable JavaDoc.class));
742         Lookup.Result serial = lookup.lookup (new Lookup.Template (Serializable JavaDoc.class));
743         
744         
745         X x = new X ();
746         ic.add (x);
747         
748         
749         x.assertOnlyMe ("x implements it (1)", runnable);
750         x.assertOnlyMe ("x implements it (2)", serial);
751         
752         ic.set (Collections.singleton (x), null);
753         
754         x.assertOnlyMe ("x implements it (3)", runnable);
755         x.assertOnlyMe ("x implements it (4)", serial);
756     }
757     
758     /** Testing lookup of inherited classes. */
759     public void testInheritance() {
760         class A {}
761         class B extends A implements java.rmi.Remote JavaDoc {}
762         class BB extends B {}
763         class C extends A implements java.rmi.Remote JavaDoc {}
764         class D extends A {}
765         
766         A[] types = {new B(), new BB(), new C(), new D()};
767         
768         for (int i = 0; i < types.length; i++) {
769             ic.add(types[i]);
770             if (lookup.lookup(types[i].getClass()) == null) {
771                 // should find an instance
772
fail("Lookup (" + types[i].getClass().getName () + ") found nothing");
773             }
774         }
775         
776         int size1, size2;
777         
778         //interface query
779
size1 = lookup.lookup(new Lookup.Template(java.rmi.Remote JavaDoc.class)).allInstances().size();
780         size2 = countInstances(types, java.rmi.Remote JavaDoc.class);
781         
782         if (size1 != size2) fail("Lookup with interface failed: " + size1 + " != " + size2);
783         
784         // superclass query
785
size1 = lookup.lookup(new Lookup.Template(A.class)).allInstances().size();
786         size2 = countInstances(types, A.class);
787         
788         if (size1 != size2) fail("Lookup with superclass failed: " + size1 + " != " + size2);
789     }
790     
791     /** Test interface inheritance.
792      */

793     public void testInterfaceInheritance() {
794         testInterfaceInheritanceA[] types = {
795             new testInterfaceInheritanceB() {},
796             new testInterfaceInheritanceBB() {},
797             new testInterfaceInheritanceC() {},
798             new testInterfaceInheritanceD() {}
799         };
800         
801         for (int i = 0; i < types.length; i++) {
802             ic.add(types[i]);
803             if (lookup.lookup(types[i].getClass()) == null) {
804                 // should find an instance
805
fail("Lookup (" + types[i].getClass().getName () + ") found nothing");
806             }
807         }
808         
809         int size1, size2;
810         
811         //interface query
812
LL l = new LL ();
813         Lookup.Result res = lookup.lookup(new Lookup.Template(java.rmi.Remote JavaDoc.class));
814         l.source = res;
815         size1 = res.allInstances().size();
816         size2 = countInstances(types, java.rmi.Remote JavaDoc.class);
817         
818         if (size1 != size2) fail("Lookup with interface failed: " + size1 + " != " + size2);
819         
820         // superclass query
821
size1 = lookup.lookup(new Lookup.Template(testInterfaceInheritanceA.class)).allInstances().size();
822         size2 = countInstances(types, testInterfaceInheritanceA.class);
823         
824         if (size1 != size2) fail("Lookup with superclass failed: " + size1 + " != " + size2);
825         
826         res.addLookupListener (l);
827         ic.remove (types[0]);
828         
829         if (l.getCount () != 1) {
830             fail ("No notification that a Remote is removed");
831         }
832     }
833     
834     /** Checks whether the AbstractLookup is guarded against modifications
835      * while doing some kind of modification.
836      */

837     public void testModificationArePreventedWhenDoingModifications () throws Exception JavaDoc {
838         BrokenPair broken = new BrokenPair (true, false);
839         ic.addPair (broken);
840         
841         Lookup.Template templ = new Lookup.Template (BrokenPair.class);
842         Object JavaDoc item = lookup.lookupItem (templ);
843         assertEquals ("Broken is found", broken, item);
844     }
845     
846     public void testModificationArePreventedWhenDoingModificationsResult () throws Exception JavaDoc {
847         BrokenPair broken = new BrokenPair (false, true);
848         ic.addPair (broken);
849         
850         Lookup.Template templ = new Lookup.Template (BrokenPair.class);
851         
852         Collection c = lookup.lookup (templ).allInstances();
853         assertEquals ("One item", 1, c.size ());
854         assertEquals ("Broken is found again", broken, c.iterator().next ());
855     }
856     
857     public void testModificationArePreventedWhenDoingModificationsItemAndResult () throws Exception JavaDoc {
858         BrokenPair broken = new BrokenPair (false, true);
859         ic.addPair (broken);
860         
861         Lookup.Template templ = new Lookup.Template (BrokenPair.class);
862         Object JavaDoc item = lookup.lookupItem (templ);
863         assertEquals ("Broken is found", broken, item);
864         
865         Collection c = lookup.lookup (templ).allInstances();
866         assertEquals ("One item", 1, c.size ());
867         assertEquals ("Broken is found again", broken, c.iterator().next ());
868     }
869
870     public void testModificationArePreventedWhenDoingModificationsResultAndItem () throws Exception JavaDoc {
871         BrokenPair broken = new BrokenPair (false, true);
872         ic.addPair (broken);
873         
874         Lookup.Template templ = new Lookup.Template (BrokenPair.class);
875         Collection c = lookup.lookup (templ).allInstances();
876         assertEquals ("One item", 1, c.size ());
877         assertEquals ("Broken is found again", broken, c.iterator().next ());
878         
879         Object JavaDoc item = lookup.lookupItem (templ);
880         assertEquals ("Broken is found", broken, item);
881     }
882     
883     public void testAddALotOfPairsIntoTheLookupOneByOne () throws Exception JavaDoc {
884         Lookup.Result res = lookup.lookup (new Lookup.Template (Integer JavaDoc.class));
885         for (int i = 0; i < 1000; i++) {
886             ic.add (new Integer JavaDoc (i));
887         }
888         assertEquals (
889             "there is the right count",
890             1000,
891             res.allItems().size ()
892         );
893     }
894     
895     public void testAddALotOfPairsIntoTheLookup () throws Exception JavaDoc {
896         ArrayList arr = new ArrayList ();
897         for (int i = 0; i < 1000; i++) {
898             arr.add (new Integer JavaDoc (i));
899         }
900         ic.set (arr, null);
901         
902         assertEquals (
903             "there is the right count",
904             1000,
905             lookup.lookup (new Lookup.Template (Integer JavaDoc.class)).allItems().size ()
906         );
907     }
908
909     
910     public void testDoubleAddIssue35274 () throws Exception JavaDoc {
911         class P extends AbstractLookup.Pair {
912             protected boolean creatorOf(Object JavaDoc obj) { return false; }
913             public String JavaDoc getDisplayName() { return ""; }
914             public String JavaDoc getId() { return ""; }
915             public Object JavaDoc getInstance() { return null; }
916             public Class JavaDoc getType() { return Object JavaDoc.class; }
917             protected boolean instanceOf(Class JavaDoc c) { return c.isAssignableFrom(getType ()); }
918             
919             public int hashCode () { return getClass ().hashCode(); };
920             public boolean equals (Object JavaDoc obj) { return getClass () == obj.getClass (); };
921         }
922         
923         P p = new P ();
924         
925         ic.addPair (p);
926         ic.addPair (p);
927         
928         Lookup.Result result = lookup.lookup (new Lookup.Template (Object JavaDoc.class));
929         Collection res = result.allItems ();
930         assertEquals ("One item there", 1, res.size ());
931         assertTrue ("It is the p", p == res.iterator ().next ());
932         
933         P p2 = new P ();
934         ic.addPair (p2);
935         
936         WeakReference JavaDoc ref = new WeakReference JavaDoc (result);
937         result = null;
938         assertGC ("The result can disappear", ref);
939         
940         impl.clearCaches ();
941         
942         result = lookup.lookup (new Lookup.Template (Object JavaDoc.class));
943         res = result.allItems ();
944         assertEquals ("One item is still there", 1, res.size ());
945         assertTrue ("But the p2 replaced p", p2 == res.iterator ().next ());
946         
947     }
948     
949     /** Test for proper serialization.
950      */

951     public void testSerializationSupport () throws Exception JavaDoc {
952         doSerializationSupport (1);
953     }
954     public void testDoubleSerializationSupport () throws Exception JavaDoc {
955         doSerializationSupport (2);
956     }
957
958     private void doSerializationSupport (int count) throws Exception JavaDoc {
959         if (lookup instanceof Serializable JavaDoc) {
960             ic.addPair (new SerialPair ("1"));
961             ic.addPair (new SerialPair ("2"));
962             ic.addPair (new SerialPair ("3"));
963
964             Lookup l = (Lookup)new org.openide.util.io.NbMarshalledObject (lookup).get ();
965
966             assertEquals ("Able to answer simple query", "1", l.lookup (String JavaDoc.class));
967
968             assertEquals ("Three objects there", 3, l.lookup (new Lookup.Template (String JavaDoc.class)).allInstances().size ());
969
970             while (count-- > 0) {
971                 l = (Lookup)new org.openide.util.io.NbMarshalledObject (l).get ();
972             }
973
974             assertEquals ("Able to answer simple query", "1", l.lookup (String JavaDoc.class));
975
976             assertEquals ("Three objects there", 3, l.lookup (new Lookup.Template (String JavaDoc.class)).allInstances().size ());
977         }
978     }
979
980     /** When a lookup with two different versions of the same class
981      * get's serialized, the results may be very bad.
982      */

983     public void testSerializationOfTwoClassesWithTheSameName () throws Exception JavaDoc {
984         if (lookup instanceof Serializable JavaDoc) {
985             doTwoSerializedClasses (false, false);
986         }
987     }
988     public void testSerializationOfTwoClassesWithTheSameNameButQueryBeforeSave () throws Exception JavaDoc {
989         if (lookup instanceof Serializable JavaDoc) {
990             doTwoSerializedClasses (true, false);
991         }
992     }
993     public void testSerializationOfTwoClassesWithTheSameNameWithBroken () throws Exception JavaDoc {
994         if (lookup instanceof Serializable JavaDoc) {
995             doTwoSerializedClasses (false, true);
996         }
997     }
998     public void testSerializationOfTwoClassesWithTheSameNameButQueryBeforeSaveWithBroken () throws Exception JavaDoc {
999         if (lookup instanceof Serializable JavaDoc) {
1000            doTwoSerializedClasses (true, true);
1001        }
1002    }
1003   
1004    private void doTwoSerializedClasses (boolean queryBeforeSerialization, boolean useBroken) throws Exception JavaDoc {
1005        ClassLoader JavaDoc loader = new CL ();
1006        Class JavaDoc c = loader.loadClass (Garbage.class.getName ());
1007
1008        // in case of InheritanceTree it creates a slot for class Garbage
1009
lookup.lookup(c);
1010
1011        // but creates new instance and adds it into the lookup
1012
// without querying for it
1013
loader = new CL ();
1014        c = loader.loadClass (Garbage.class.getName ());
1015
1016        Object JavaDoc theInstance = c.newInstance ();
1017
1018        ic.addPair (new SerialPair (theInstance));
1019
1020        Broken2Pair broken = null;
1021        if (useBroken) {
1022            broken = new Broken2Pair ();
1023            ic.addPair (broken);
1024            
1025            assertNull (
1026                "We need to create the slot for the List as " +
1027                "the Broken2Pair will ask for it after deserialization",
1028                lookup.lookup (java.awt.List JavaDoc.class)
1029            );
1030        }
1031
1032        if (queryBeforeSerialization) {
1033            assertEquals ("Instance is found", theInstance, lookup.lookup (c));
1034        }
1035        
1036        // replace the old lookup with new one
1037
lookup = (Lookup)new org.openide.util.io.NbMarshalledObject (lookup).get ();
1038        
1039        Lookup.Result result = lookup.lookup (new Lookup.Template (Garbage.class));
1040        assertEquals ("One item is the result", 1, result.allInstances ().size ());
1041        Object JavaDoc r = result.allInstances ().iterator ().next ();
1042        assertNotNull("A value is found", r);
1043        assertEquals ("It is of the right class", Garbage.class, r.getClass());
1044    }
1045   
1046    /** Test of reorder and item change which used to fail on interfaces.
1047     */

1048    public void testReoderingIssue13779 () throws Exception JavaDoc {
1049        LinkedList arr = new LinkedList ();
1050        
1051        class R extends Exception JavaDoc implements Cloneable JavaDoc {
1052        }
1053        Object JavaDoc o1 = new R ();
1054        Object JavaDoc o2 = new R ();
1055        Object JavaDoc o3 = new R ();
1056        
1057        arr.add (o1);
1058        arr.add (o2);
1059        
1060        ic.set (arr, null);
1061        
1062        Lookup.Result objectResult = lookup.lookup (new Lookup.Template (Exception JavaDoc.class));
1063        Lookup.Result interfaceResult = lookup.lookup (new Lookup.Template (Cloneable JavaDoc.class));
1064        objectResult.allItems ();
1065        interfaceResult.allItems ();
1066        
1067        LL l1 = new LL (objectResult);
1068        LL l2 = new LL (interfaceResult);
1069        
1070        objectResult.addLookupListener(l1);
1071        interfaceResult.addLookupListener(l2);
1072        
1073        arr.addFirst (o3);
1074        
1075        ic.set (arr, null);
1076        
1077        assertEquals ("One change on objects", 1, l1.getCount ());
1078        assertEquals ("One change on interfaces", 1, l2.getCount ());
1079        
1080        arr.addFirst (new Cloneable JavaDoc () { });
1081        ic.set (arr, null);
1082        
1083        assertEquals ("No change on objects", 0, l1.getCount ());
1084        assertEquals ("But one change on interfaces", 1, l2.getCount ());
1085        
1086    }
1087    
1088    public void testDeadlockBetweenProxyResultAndLookupIssue47772 () throws Exception JavaDoc {
1089        final String JavaDoc myModule = "My Module";
1090        ic.add (myModule);
1091        
1092        class MyProxy extends ProxyLookup {
1093            public MyProxy () {
1094                super (new Lookup[] { lookup });
1095            }
1096        }
1097        final MyProxy my = new MyProxy ();
1098        
1099        final Lookup.Result allModules = my.lookup (new Lookup.Template (String JavaDoc.class));
1100        
1101        class PairThatNeedsInfoAboutModules extends AbstractLookup.Pair {
1102            public String JavaDoc getDisplayName () {
1103                return "Need a module";
1104            }
1105            public String JavaDoc getId () {
1106                return getDisplayName ();
1107            }
1108            public Class JavaDoc getType () {
1109                return Integer JavaDoc.class;
1110            }
1111            protected boolean instanceOf (Class JavaDoc c) {
1112                if (c == Integer JavaDoc.class) {
1113                    synchronized (this) {
1114                        notifyAll ();
1115                        try {
1116                            wait (1000);
1117                        } catch (InterruptedException JavaDoc ex) {
1118                            fail (ex.getMessage ());
1119                        }
1120                    }
1121                    java.util.Collection JavaDoc coll = allModules.allInstances ();
1122                    assertEquals ("Size is 1", 1, coll.size ());
1123                    assertEquals ("My module is there", myModule, coll.iterator ().next ());
1124                }
1125                return c.isAssignableFrom (Integer JavaDoc.class);
1126            }
1127            
1128            public Object JavaDoc getInstance () {
1129                return new Integer JavaDoc (10);
1130            }
1131            
1132            protected boolean creatorOf (Object JavaDoc obj) {
1133                return new Integer JavaDoc (10).equals (obj);
1134            }
1135        }
1136        
1137        PairThatNeedsInfoAboutModules pair = new PairThatNeedsInfoAboutModules ();
1138        ic.addPair (pair);
1139        
1140        synchronized (pair) {
1141            class BlockInInstanceOf implements Runnable JavaDoc {
1142                public void run () {
1143                    Integer JavaDoc i = (Integer JavaDoc)my.lookup (Integer JavaDoc.class);
1144                    assertEquals (new Integer JavaDoc (10), i);
1145                }
1146            }
1147            BlockInInstanceOf blk = new BlockInInstanceOf ();
1148            RequestProcessor.getDefault ().post (blk);
1149            pair.wait ();
1150        }
1151        
1152        java.util.Collection JavaDoc coll = allModules.allInstances ();
1153        assertEquals ("Size is 1", 1, coll.size ());
1154        assertEquals ("My module is there", myModule, coll.iterator ().next ());
1155    }
1156
1157    public void testAWayToGenerateProblem13779 () {
1158        ic.add (new Integer JavaDoc (1));
1159        ic.add (new Integer JavaDoc (2));
1160        ic.add (new Integer JavaDoc (1));
1161        ic.add (new Integer JavaDoc (2));
1162        
1163        Collection c = lookup.lookup (new Lookup.Template (Integer JavaDoc.class)).allInstances ();
1164        assertEquals ("There are two objects", 2, c.size ());
1165        
1166    }
1167    
1168    /** Replacing items with different objects.
1169     */

1170    public void testReplacingObjectsDoesNotGenerateException () throws Exception JavaDoc {
1171        LinkedList arr = new LinkedList ();
1172        
1173        class R extends Exception JavaDoc implements Cloneable JavaDoc {
1174        }
1175        arr.add (new R ());
1176        arr.add (new R ());
1177        
1178        ic.set (arr, null);
1179        
1180        arr.clear();
1181        
1182        arr.add (new R ());
1183        arr.add (new R ());
1184        
1185        ic.set (arr, null);
1186    }
1187
1188    public void testAfterDeserializationNoQueryIsPeformedOnAlreadyQueriedObjects() throws Exception JavaDoc {
1189        if (! (lookup instanceof Serializable JavaDoc)) {
1190            // well this test works only for serializable lookups
1191
return;
1192        }
1193        
1194        SerialPair my = new SerialPair ("no");
1195        ic.addPair (my);
1196        
1197        Lookup.Result res = lookup.lookup (new Lookup.Template (String JavaDoc.class));
1198        assertEquals ("One instance", 1, res.allInstances().size ());
1199        assertEquals ("my.instanceOf called once", 1, my.countInstanceOf);
1200        
1201        Lookup serial = (Lookup)new org.openide.util.io.NbMarshalledObject (lookup).get ();
1202        
1203        Lookup.Result r2 = serial.lookup(new Lookup.Template(String JavaDoc.class));
1204        
1205        assertEquals ("One item", 1, r2.allItems ().size ());
1206        Object JavaDoc one = r2.allItems().iterator().next ();
1207        assertEquals ("The right class", SerialPair.class, one.getClass());
1208        SerialPair p = (SerialPair)one;
1209        
1210        assertEquals ("p.instanceOf has not been queried", 0, p.countInstanceOf);
1211    }
1212    
1213    /** Checks the iterator */
1214    private void checkIterator (String JavaDoc msg, Iterator it1, List list) {
1215        int cnt = 0;
1216        Iterator it2 = list.iterator ();
1217        while (it1.hasNext () && it2.hasNext ()) {
1218            Object JavaDoc n1 = it1.next ();
1219            Object JavaDoc n2 = it2.next ();
1220            
1221            if (n1 != n2) {
1222                fail (msg + " iterator[" + cnt + "] = " + n1 + " but list[" + cnt + "] = " + n2);
1223            }
1224            
1225            cnt++;
1226        }
1227        
1228        if (it1.hasNext ()) {
1229            fail ("Iterator has more elements than list");
1230        }
1231        
1232        if (it2.hasNext ()) {
1233            fail ("List has more elements than iterator");
1234        }
1235    }
1236    
1237    
1238    public void testResultsAreUnmodifyableOrAtLeastTheyDoNotPropagateToCache() throws Exception JavaDoc {
1239        String JavaDoc s = "Ahoj";
1240        
1241        ic.add(s);
1242        
1243        Lookup.Result res = lookup.lookup(new Template(String JavaDoc.class));
1244        
1245        for (int i = 1; i < 5; i++) {
1246            Collection c1 = res.allInstances();
1247            Collection c2 = res.allClasses();
1248            Collection c3 = res.allItems();
1249
1250            assertTrue(i + ": c1 has it", c1.contains(s));
1251            assertTrue(i + ": c2 has it", c2.contains(s.getClass()));
1252            assertEquals(i + ": c3 has one", 1, c3.size());
1253            Lookup.Item item = (Lookup.Item) c3.iterator().next();
1254            assertEquals(i + ": c3 has it", s, item.getInstance());
1255
1256            try {
1257                c1.remove(s);
1258                assertEquals("No elements now", 0, c1.size());
1259            } catch (UnsupportedOperationException JavaDoc ex) {
1260                // ok, this need not be supported
1261
}
1262            try {
1263                c2.remove(s.getClass());
1264                assertEquals("No elements now", 0, c2.size());
1265            } catch (UnsupportedOperationException JavaDoc ex) {
1266                // ok, this need not be supported
1267
}
1268            try {
1269                c3.remove(item);
1270                assertEquals("No elements now", 0, c3.size());
1271            } catch (UnsupportedOperationException JavaDoc ex) {
1272                // ok, this need not be supported
1273
}
1274        }
1275    }
1276    
1277    public void testSomeProblemWithDVBFrameworkSeemsToBeInLookup() {
1278        for (int i = 0; i < 5; i++) {
1279            ic.add(lookup);
1280            assertEquals("Can be found", lookup, lookup.lookup(lookup.getClass()));
1281            ic.set(Collections.EMPTY_LIST, null);
1282        }
1283    }
1284
1285    public void testListeningAndQueryingByTwoListenersInstances() {
1286        doListeningAndQueryingByTwoListeners(0);
1287    }
1288    public void testListeningAndQueryingByTwoListenersClasses() {
1289        doListeningAndQueryingByTwoListeners(1);
1290    }
1291    public void testListeningAndQueryingByTwoListenersItems() {
1292        doListeningAndQueryingByTwoListeners(2);
1293    }
1294    
1295    
1296    private void doListeningAndQueryingByTwoListeners(final int type) {
1297        class L implements LookupListener {
1298            Lookup.Result integer = lookup.lookup(new Template(Integer JavaDoc.class));
1299            Lookup.Result number = lookup.lookup(new Template(Number JavaDoc.class));
1300            Lookup.Result serial = lookup.lookup(new Template(Serializable JavaDoc.class));
1301            
1302            {
1303                integer.addLookupListener(this);
1304                number.addLookupListener(this);
1305                serial.addLookupListener(this);
1306            }
1307            
1308            int round;
1309            
1310            public void resultChanged(LookupEvent ev) {
1311                Collection c1 = get(type, integer);
1312                Collection c2 = get(type, number);
1313                Collection c3 = get(type, serial);
1314                
1315                assertEquals("round " + round + " c1 vs. c2", c1, c2);
1316                assertEquals("round " + round + " c1 vs. c3", c1, c3);
1317                assertEquals("round " + round + " c2 vs. c3", c2, c3);
1318                
1319                round++;
1320            }
1321
1322            private Collection get(int type, Lookup.Result res) {
1323                Collection c;
1324                switch(type) {
1325                    case 0: c = res.allInstances(); break;
1326                    case 1: c = res.allClasses(); break;
1327                    case 2: c = res.allItems(); break;
1328                    default: c = null; fail("Type: " + type); break;
1329                }
1330                
1331                assertNotNull(c);
1332                return new ArrayList(c);
1333            }
1334        }
1335        
1336        L listener = new L();
1337        listener.resultChanged(null);
1338        
1339        for(int i = 0; i < 100; i++) {
1340            ic.add(new Integer JavaDoc(i));
1341        }
1342        
1343        assertEquals("3x100+1 checks", 301, listener.round);
1344    }
1345    
1346    public void testChangeOfNodeDoesNotFireChangeInActionMap() {
1347        ActionMap JavaDoc am = new ActionMap JavaDoc();
1348        Lookup s = Lookups.singleton(am);
1349        doChangeOfNodeDoesNotFireChangeInActionMap(am, s, false);
1350    }
1351    public void testChangeOfNodeDoesNotFireChangeInActionMapSimple() {
1352        ActionMap JavaDoc am = new ActionMap JavaDoc();
1353        Lookup s = Lookups.singleton(am);
1354        doChangeOfNodeDoesNotFireChangeInActionMap(am, s, true);
1355    }
1356
1357    public void testChangeOfNodeDoesNotFireChangeInActionMapWithBeforeLookupSimple() {
1358        doChangeOfNodeDoesNotFireChangeInActionMapWithBeforeLookup(true);
1359    }
1360    
1361    public void testChangeOfNodeDoesNotFireChangeInActionMapWithBeforeLookup() {
1362        doChangeOfNodeDoesNotFireChangeInActionMapWithBeforeLookup(false);
1363    }
1364    private void doChangeOfNodeDoesNotFireChangeInActionMapWithBeforeLookup(boolean wrapBySimple) {
1365        final ActionMap JavaDoc am = new ActionMap JavaDoc();
1366        
1367        class Before extends AbstractLookup {
1368            public InstanceContent ic;
1369            public Before() {
1370                this(new InstanceContent());
1371            }
1372            
1373            private Before(InstanceContent ic) {
1374                super(ic);
1375                this.ic = ic;
1376            }
1377
1378            protected void beforeLookup(Template template) {
1379                if (ic != null) {
1380                    ic.add(am);
1381                    ic = null;
1382                }
1383            }
1384        }
1385        
1386        Before s = new Before();
1387        doChangeOfNodeDoesNotFireChangeInActionMap(am, s, wrapBySimple);
1388        
1389        assertNull("beforeLookup called once", s.ic);
1390    }
1391    
1392    private void doChangeOfNodeDoesNotFireChangeInActionMap(final ActionMap JavaDoc am, Lookup actionMapLookup, final boolean wrapBySimple) {
1393        Lookup[] lookups = { lookup, actionMapLookup };
1394        
1395        class Provider implements Lookup.Provider {
1396            ProxyLookup delegate;
1397            Lookup query;
1398            
1399            public Provider(Lookup[] arr) {
1400                if (wrapBySimple) {
1401                    delegate = new ProxyLookup(arr);
1402                    query = Lookups.proxy(this);
1403                } else {
1404                    query = delegate = new ProxyLookup(arr);
1405                }
1406            }
1407            
1408            public Lookup getLookup() {
1409                return delegate;
1410            }
1411            
1412            public void setLookups(Lookup[] arr) {
1413                if (wrapBySimple) {
1414                    delegate = new ProxyLookup(arr);
1415                } else {
1416                    delegate.setLookups(arr);
1417                }
1418            }
1419        }
1420        
1421        Provider p = new Provider(lookups);
1422        
1423        Lookup.Result res = p.query.lookup(new Lookup.Template(ActionMap JavaDoc.class));
1424        LL ll = new LL();
1425        res.addLookupListener(ll);
1426
1427        Collection c = res.allInstances();
1428        assertFalse("Has next", c.isEmpty());
1429        
1430        ActionMap JavaDoc am1 = (ActionMap JavaDoc)c.iterator().next();
1431        assertEquals("Am is there", am, am1);
1432        
1433        assertEquals("No change in first get", 0, ll.getCount());
1434        
1435        Object JavaDoc m1 = new InputMap JavaDoc();
1436        Object JavaDoc m2 = new InputMap JavaDoc();
1437        
1438        ic.add(m1);
1439        assertEquals("No change in ActionMap 1", 0, ll.getCount());
1440        ic.set(Collections.singletonList(m2), null);
1441        assertEquals("No change in ActionMap 2", 0, ll.getCount());
1442        ic.add(m2);
1443        assertEquals("No change in ActionMap 3", 0, ll.getCount());
1444        p.setLookups(new Lookup[]{ lookup, actionMapLookup, Lookup.EMPTY });
1445        assertEquals("No change in ActionMap 4", 0, ll.getCount());
1446        
1447        ActionMap JavaDoc am2 = (ActionMap JavaDoc)p.query.lookup(ActionMap JavaDoc.class);
1448        assertEquals("Still the same action map", am, am2);
1449        
1450        
1451        class Before extends AbstractLookup {
1452            public InstanceContent ic;
1453            public Before() {
1454                this(new InstanceContent());
1455            }
1456            
1457            private Before(InstanceContent ic) {
1458                super(ic);
1459                this.ic = ic;
1460            }
1461
1462            protected void beforeLookup(Template template) {
1463                if (ic != null) {
1464                    ic.add(am);
1465                    ic = null;
1466                }
1467            }
1468        }
1469        
1470        Before s = new Before();
1471        
1472        // adding different Before, but returning the same instance
1473
// this happens with metaInfServices lookup often, moreover
1474
// it adds the instance in beforeLookup, which confuses a lot
1475
p.setLookups(new Lookup[]{ lookup, new Before() });
1476        assertEquals("No change in ActionMap 5", 0, ll.getCount());
1477        
1478        
1479    }
1480
1481    
1482
1483    public void testMultipleListeners() {
1484        Object JavaDoc object = new ImplementationObject();
1485        ic.add(object);
1486        
1487        Listener[] listeners = new Listener[4];
1488        Lookup.Result result = lookup.lookup(new Lookup.Template(LookupObject.class));
1489        for(int i = 0; i < listeners.length; ++i) {
1490            listeners[i] = new Listener();
1491            result.addLookupListener(listeners[i]);
1492        }
1493        // initialize listening
1494
result.allItems();
1495        
1496        ic.remove(object);
1497        
1498        // Apparently, only odd-numbered listeners get called when there are multiple LookupListeners on a result
1499
//for(int i = 0; i < listeners.length; ++i) {
1500
// System.out.println("Listener " + i + ": " + listeners[i].wasCalled());
1501
//}
1502
for(int i = 0; i < listeners.length; ++i) {
1503            assertTrue("Listener " + i + " called", listeners[i].wasCalled());
1504        }
1505    }
1506    
1507    private class Listener implements LookupListener {
1508        private boolean listenerCalled = false;
1509        
1510        public void resultChanged(LookupEvent ev) {
1511            listenerCalled = true;
1512        }
1513        
1514        public boolean wasCalled() {
1515            return listenerCalled;
1516        }
1517        
1518        public void reset() {
1519            listenerCalled = false;
1520        }
1521    }
1522    
1523    private interface LookupObject {}
1524    private class ImplementationObject implements LookupObject {}
1525    private class NullObject implements LookupObject {}
1526    
1527    
1528    public void testReturnSomethingElseThenYouClaimYouWillReturn() {
1529        class Liar extends AbstractLookup.Pair {
1530            public Object JavaDoc obj;
1531            
1532            protected boolean instanceOf(Class JavaDoc c) {
1533                return c.isAssignableFrom(String JavaDoc.class);
1534            }
1535
1536            protected boolean creatorOf(Object JavaDoc obj) {
1537                return this.obj == obj;
1538            }
1539
1540            public Object JavaDoc getInstance() {
1541                return this.obj;
1542            }
1543
1544            public Class JavaDoc getType() {
1545                return String JavaDoc.class;
1546            }
1547
1548            public String JavaDoc getId() {
1549                return String JavaDoc.class.getName();
1550            }
1551
1552            public String JavaDoc getDisplayName() {
1553                return getId();
1554            }
1555        }
1556        
1557        
1558        Liar l = new Liar();
1559        l.obj = new Integer JavaDoc(5);
1560        
1561        this.ic.addPair(l);
1562        
1563        Collection c = lookup.lookup(new Lookup.Template(String JavaDoc.class)).allInstances();
1564        assertTrue("It is empty: " + c, c.isEmpty());
1565    }
1566    
1567    /** Adds instances to the instance lookup.
1568     */

1569    private void addInstances (Object JavaDoc[] instances) {
1570        for (int i = 0; i < instances.length; i++) {
1571            ic.add(instances[i]);
1572        }
1573    }
1574    
1575    /** Count instances of clazz in an array. */
1576    private int countInstances (Object JavaDoc[] objs, Class JavaDoc clazz) {
1577        int count = 0;
1578        for (int i = 0; i < objs.length; i++) {
1579            if (clazz.isInstance(objs[i])) count++;
1580        }
1581        return count;
1582    }
1583    
1584    /** Counting listener */
1585    protected static class LL implements LookupListener {
1586        private int count = 0;
1587        public Object JavaDoc source;
1588        
1589        public LL () {
1590            this (null);
1591        }
1592        
1593        public LL (Object JavaDoc source) {
1594            this.source = source;
1595        }
1596        
1597        public void resultChanged(LookupEvent ev) {
1598            ++count;
1599            if (source != null) {
1600                assertSame ("Source is the same", source, ev.getSource ());
1601// assertSame ("Result is the same", source, ev.getResult ());
1602
}
1603        }
1604
1605        public int getCount() {
1606            int i = count;
1607            count = 0;
1608            return i;
1609        }
1610    };
1611
1612    /** A set of interfaces for testInterfaceInheritance
1613     */

1614    interface testInterfaceInheritanceA {}
1615    interface testInterfaceInheritanceB extends testInterfaceInheritanceA, java.rmi.Remote JavaDoc {}
1616    interface testInterfaceInheritanceBB extends testInterfaceInheritanceB {}
1617    interface testInterfaceInheritanceC extends testInterfaceInheritanceA, java.rmi.Remote JavaDoc {}
1618    interface testInterfaceInheritanceD extends testInterfaceInheritanceA {}
1619    
1620    /** A special class for garbage test */
1621    public static final class Garbage extends Object JavaDoc implements Serializable JavaDoc {
1622        static final long serialVersionUID = 435340912534L;
1623    }
1624    
1625
1626    /* A classloader that can load one class in a special way */
1627    private static class CL extends ClassLoader JavaDoc {
1628        public CL () {
1629            super (null);
1630        }
1631
1632        public Class JavaDoc findClass (String JavaDoc name) throws ClassNotFoundException JavaDoc {
1633            if (name.equals (Garbage.class.getName ())) {
1634                String JavaDoc n = name.replace ('.', '/');
1635                java.io.InputStream JavaDoc is = getClass ().getResourceAsStream ("/" + n + ".class");
1636                byte[] arr = new byte[8096];
1637                try {
1638                    int cnt = is.read (arr);
1639                    if (cnt == arr.length) {
1640                        fail ("Buffer to load the class is not big enough");
1641                    }
1642
1643                    return defineClass (name, arr, 0, cnt);
1644                } catch (java.io.IOException JavaDoc ex) {
1645                        ex.printStackTrace();
1646                        fail ("IO Exception");
1647                        return null;
1648                }
1649            } else {
1650                return null;
1651            }
1652        }
1653
1654        /** Convert obj to other object. There is no need to implement
1655         * cache mechanism. It is provided by AbstractLookup.Item.getInstance().
1656         * Method should be called more than once because Lookup holds
1657         * just weak reference.
1658         */

1659        public Object JavaDoc convert(Object JavaDoc obj) {
1660            return null;
1661        }
1662
1663        /** Return type of converted object. */
1664        public Class JavaDoc type(Object JavaDoc obj) {
1665            try {
1666                return loadClass (Garbage.class.getName ());
1667            } catch (ClassNotFoundException JavaDoc ex) {
1668                fail ("Class not found");
1669                throw new InternalError JavaDoc ();
1670            }
1671        }
1672    }
1673
1674    public static final class SerialPair extends AbstractLookup.Pair
1675    implements java.io.Serializable JavaDoc {
1676        static final long serialVersionUID = 54305834L;
1677        private Object JavaDoc value;
1678        public transient int countInstanceOf;
1679        
1680        public SerialPair (Object JavaDoc value) {
1681            this.value = value;
1682        }
1683        
1684        protected boolean creatorOf(Object JavaDoc obj) {
1685            return obj == value;
1686        }
1687        
1688        public String JavaDoc getDisplayName() {
1689            return getId ();
1690        }
1691        
1692        public String JavaDoc getId() {
1693            return value.toString();
1694        }
1695        
1696        public Object JavaDoc getInstance() {
1697            return value;
1698        }
1699        
1700        public Class JavaDoc getType() {
1701            return value.getClass ();
1702        }
1703        
1704        protected boolean instanceOf(Class JavaDoc c) {
1705            countInstanceOf++;
1706            return c.isInstance(value);
1707        }
1708    } // end of SerialPair
1709

1710    private static class BrokenPair extends AbstractLookup.Pair {
1711        private transient ThreadLocal JavaDoc IN = new ThreadLocal JavaDoc ();
1712        private boolean checkModify;
1713        private boolean checkQuery;
1714        
1715        public BrokenPair (boolean checkModify, boolean checkQuery) {
1716            this.checkModify = checkModify;
1717            this.checkQuery = checkQuery;
1718        }
1719        
1720        protected boolean creatorOf(Object JavaDoc obj) { return this == obj; }
1721        public String JavaDoc getDisplayName() { return "Broken"; }
1722        public String JavaDoc getId() { return "broken"; }
1723        public Object JavaDoc getInstance() { return this; }
1724        public Class JavaDoc getType() { return getClass (); }
1725        protected boolean instanceOf(Class JavaDoc c) {
1726            
1727            if (checkQuery) {
1728                if (IN.get () == null) {
1729                    try {
1730                        IN.set (this);
1731                        // broken behaviour, tries to modify the lookup
1732
// queries have to survive
1733

1734                        running.lookup.lookup (java.awt.List JavaDoc.class);
1735
1736                        //
1737
// creation of new result has to survive as well
1738
Lookup.Result myQuery = running.lookup.lookup (new Lookup.Template (java.awt.Button JavaDoc.class));
1739                        Collection all = myQuery.allItems ();
1740                    } finally {
1741                        IN.set (null);
1742                    }
1743                }
1744            }
1745                
1746
1747            if (checkModify) {
1748                //
1749
// modifications should fail
1750
//
1751

1752                try {
1753                    running.ic.addPair (new SerialPair (""));
1754                    fail ("Modification from a query should be prohibited");
1755                } catch (IllegalStateException JavaDoc ex) {
1756                }
1757                
1758                try {
1759                    running.ic.removePair (this);
1760                    fail ("This has to throw the exception");
1761                } catch (IllegalStateException JavaDoc ex) {
1762                }
1763                try {
1764                    running.ic.setPairs (Collections.EMPTY_SET);
1765                    fail ("This has to throw the exception as well");
1766                } catch (IllegalStateException JavaDoc ex) {
1767                }
1768            }
1769            
1770            return c.isAssignableFrom(getType ());
1771        }
1772    } // end of BrokenPair
1773

1774    private static class Broken2Pair extends AbstractLookup.Pair {
1775        static final long serialVersionUID = 4532587018501L;
1776        public transient ThreadLocal JavaDoc IN;
1777        
1778        public Broken2Pair () {
1779        }
1780        
1781        private void writeObject (java.io.ObjectOutputStream JavaDoc oos) throws java.io.IOException JavaDoc {
1782        }
1783        
1784        private void readObject (java.io.ObjectInputStream JavaDoc ois) throws java.io.IOException JavaDoc, ClassNotFoundException JavaDoc {
1785            IN = new ThreadLocal JavaDoc ();
1786        }
1787        
1788        protected boolean creatorOf(Object JavaDoc obj) { return this == obj; }
1789        public String JavaDoc getDisplayName() { return "Broken"; }
1790        public String JavaDoc getId() { return "broken"; }
1791        public Object JavaDoc getInstance() { return this; }
1792        public Class JavaDoc getType() { return getClass (); }
1793        protected boolean instanceOf(Class JavaDoc c) {
1794            
1795            // behaviour gets broken only after deserialization
1796
if (IN != null && IN.get () == null) {
1797                try {
1798                    IN.set (this);
1799
1800                    // creation of new result has to survive as well
1801
Lookup.Result myQuery = running.lookup.lookup (new Lookup.Template (java.awt.List JavaDoc.class));
1802                    Collection all = myQuery.allItems ();
1803                } finally {
1804                    IN.set (null);
1805                }
1806            }
1807            
1808            return c.isAssignableFrom(getType ());
1809        }
1810    } // end of Broken2Pair
1811
}
1812
Popular Tags