KickJava   Java API By Example, From Geeks To Geeks.

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


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 java.io.File JavaDoc;
23 import java.io.FileOutputStream JavaDoc;
24 import java.io.IOException JavaDoc;
25 import java.io.InputStream JavaDoc;
26 import java.io.InputStreamReader JavaDoc;
27 import java.net.URL JavaDoc;
28 import java.net.URLClassLoader JavaDoc;
29 import java.util.ArrayList JavaDoc;
30 import java.util.Collections JavaDoc;
31 import java.util.Enumeration JavaDoc;
32 import java.util.List JavaDoc;
33 import java.util.Set JavaDoc;
34 import java.util.Set JavaDoc;
35 import java.util.TreeSet JavaDoc;
36 import java.util.jar.JarEntry JavaDoc;
37 import java.util.jar.JarOutputStream JavaDoc;
38 import java.util.logging.Level JavaDoc;
39 import java.util.logging.Logger JavaDoc;
40 import java.util.regex.Matcher JavaDoc;
41 import java.util.regex.Pattern JavaDoc;
42 import org.netbeans.junit.NbTestCase;
43 import org.openide.util.Lookup;
44 import org.openide.util.LookupEvent;
45 import org.openide.util.LookupListener;
46 import org.openide.util.RequestProcessor;
47
48 /** Test finding services from manifest.
49  * @author Jesse Glick
50  */

51 public class MetaInfServicesLookupTest extends NbTestCase {
52     private Logger JavaDoc LOG;
53     
54     public MetaInfServicesLookupTest(String JavaDoc name) {
55         super(name);
56         LOG = Logger.getLogger("Test." + name);
57     }
58     
59     private String JavaDoc prefix() {
60         return "META-INF/services/";
61     }
62     
63     protected Level JavaDoc logLevel() {
64         return Level.INFO;
65     }
66
67     private URL JavaDoc findJar(String JavaDoc n) throws IOException JavaDoc {
68         LOG.info("Looking for " + n);
69         File JavaDoc jarDir = new File JavaDoc(getWorkDir(), "jars");
70         jarDir.mkdirs();
71         File JavaDoc jar = new File JavaDoc(jarDir, n);
72         if (jar.exists()) {
73             return jar.toURI().toURL();
74         }
75         
76         LOG.info("generating " + jar);
77         
78         URL JavaDoc data = MetaInfServicesLookupTest.class.getResource(n.replaceAll("\\.jar", "\\.txt"));
79         assertNotNull("Data found", data);
80         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
81         InputStreamReader JavaDoc r = new InputStreamReader JavaDoc(data.openStream());
82         for(;;) {
83             int ch = r.read();
84             if (ch == -1) {
85                 break;
86             }
87             sb.append((char)ch);
88         }
89         
90         JarOutputStream JavaDoc os = new JarOutputStream JavaDoc(new FileOutputStream JavaDoc(jar));
91         
92         Pattern JavaDoc p = Pattern.compile(":([^:]+):([^:]*)", Pattern.MULTILINE | Pattern.DOTALL);
93         Matcher JavaDoc m = p.matcher(sb);
94         Pattern JavaDoc foobar = Pattern.compile("^(org\\.(foo|bar)\\..*)$", Pattern.MULTILINE);
95         Set JavaDoc<String JavaDoc> names = new TreeSet JavaDoc<String JavaDoc>();
96         while (m.find()) {
97             assert m.groupCount() == 2;
98             String JavaDoc entryName = prefix() + m.group(1);
99             LOG.info("putting there entry: " + entryName);
100             os.putNextEntry(new JarEntry JavaDoc(entryName));
101             os.write(m.group(2).getBytes());
102             os.closeEntry();
103             
104             Matcher JavaDoc fb = foobar.matcher(m.group(2));
105             while (fb.find()) {
106                 String JavaDoc clazz = fb.group(1).replace('.', '/') + ".class";
107                 LOG.info("will copy " + clazz);
108                 names.add(clazz);
109             }
110         }
111         
112         for (String JavaDoc copy : names) {
113             os.putNextEntry(new JarEntry JavaDoc(copy));
114             LOG.info("copying " + copy);
115             InputStream JavaDoc from = MetaInfServicesLookupTest.class.getResourceAsStream("/" + copy);
116             assertNotNull(copy, from);
117             for (;;) {
118                 int ch = from.read();
119                 if (ch == -1) {
120                     break;
121                 }
122                 os.write(ch);
123             }
124             from.close();
125             os.closeEntry();;
126         }
127         os.close();
128         LOG.info("done " + jar);
129         return jar.toURI().toURL();
130     }
131
132     ClassLoader JavaDoc c1, c2, c2a, c3, c4;
133
134     protected void setUp() throws Exception JavaDoc {
135         clearWorkDir();
136         ClassLoader JavaDoc app = getClass().getClassLoader().getParent();
137         ClassLoader JavaDoc c0 = app;
138         
139         c1 = new URLClassLoader JavaDoc(new URL JavaDoc[] {
140             findJar("services-jar-1.jar"),
141         }, c0);
142         c2 = new URLClassLoader JavaDoc(new URL JavaDoc[] {
143             findJar("services-jar-2.jar"),
144         }, c1);
145         c2a = new URLClassLoader JavaDoc(new URL JavaDoc[] {
146             findJar("services-jar-2.jar"),
147         }, c1);
148         c3 = new URLClassLoader JavaDoc(new URL JavaDoc[] { findJar("services-jar-2.jar") },
149             c0
150         );
151         c4 = new URLClassLoader JavaDoc(new URL JavaDoc[] {
152             findJar("services-jar-1.jar"),
153             findJar("services-jar-2.jar"),
154         }, c0);
155     }
156
157     public void testBasicUsage() throws Exception JavaDoc {
158         Lookup l = Lookups.metaInfServices(c2);
159         Class JavaDoc xface = c1.loadClass("org.foo.Interface");
160         List JavaDoc results = new ArrayList JavaDoc(l.lookup(new Lookup.Template(xface)).allInstances());
161         assertEquals(2, results.size());
162         // Note that they have to be in order:
163
assertEquals("org.foo.impl.Implementation1", results.get(0).getClass().getName());
164         assertEquals("org.bar.Implementation2", results.get(1).getClass().getName());
165         // Make sure it does not gratuitously replace items:
166
List JavaDoc results2 = new ArrayList JavaDoc(l.lookup(new Lookup.Template(xface)).allInstances());
167         assertEquals(results, results2);
168     }
169
170     public void testLoaderSkew() throws Exception JavaDoc {
171         Class JavaDoc xface1 = c1.loadClass("org.foo.Interface");
172         Lookup l3 = Lookups.metaInfServices(c3);
173         // If we cannot load Interface, there should be no impls of course... quietly!
174
assertEquals(Collections.EMPTY_LIST,
175                 new ArrayList JavaDoc(l3.lookup(new Lookup.Template(xface1)).allInstances()));
176         Lookup l4 = Lookups.metaInfServices(c4);
177         // If we can load Interface but it is the wrong one, ignore it.
178
assertEquals(Collections.EMPTY_LIST,
179                 new ArrayList JavaDoc(l4.lookup(new Lookup.Template(xface1)).allInstances()));
180         // Make sure l4 is really OK - it can load from its own JARs.
181
Class JavaDoc xface4 = c4.loadClass("org.foo.Interface");
182         assertEquals(2, l4.lookup(new Lookup.Template(xface4)).allInstances().size());
183     }
184
185     public void testStability() throws Exception JavaDoc {
186         Lookup l = Lookups.metaInfServices(c2);
187         Class JavaDoc xface = c1.loadClass("org.foo.Interface");
188         Object JavaDoc first = l.lookup(new Lookup.Template(xface)).allInstances().iterator().next();
189         l = Lookups.metaInfServices(c2a);
190         Object JavaDoc second = l.lookup(new Lookup.Template(xface)).allInstances().iterator().next();
191         assertEquals(first, second);
192     }
193
194     public void testMaskingOfResources() throws Exception JavaDoc {
195         Lookup l1 = Lookups.metaInfServices(c1);
196         Lookup l2 = Lookups.metaInfServices(c2);
197         Lookup l4 = Lookups.metaInfServices(c4);
198
199         assertNotNull("services1.jar defines a class that implements runnable", l1.lookup(Runnable JavaDoc.class));
200         assertNull("services2.jar does not defines a class that implements runnable", l2.lookup(Runnable JavaDoc.class));
201         assertNull("services1.jar defines Runnable, but services2.jar masks it out", l4.lookup(Runnable JavaDoc.class));
202     }
203
204     public void testOrdering() throws Exception JavaDoc {
205         Lookup l = Lookups.metaInfServices(c1);
206         Class JavaDoc xface = c1.loadClass("java.util.Comparator");
207         List JavaDoc results = new ArrayList JavaDoc(l.lookup(new Lookup.Template(xface)).allInstances());
208         assertEquals(1, results.size());
209
210         l = Lookups.metaInfServices(c2);
211         xface = c2.loadClass("java.util.Comparator");
212         results = new ArrayList JavaDoc(l.lookup(new Lookup.Template(xface)).allInstances());
213         assertEquals(2, results.size());
214         // Test order:
215
assertEquals("org.bar.Comparator2", results.get(0).getClass().getName());
216         assertEquals("org.foo.impl.Comparator1", results.get(1).getClass().getName());
217
218         // test that items without position are always at the end
219
l = Lookups.metaInfServices(c2);
220         xface = c2.loadClass("java.util.Iterator");
221         results = new ArrayList JavaDoc(l.lookup(new Lookup.Template(xface)).allInstances());
222         assertEquals(2, results.size());
223         // Test order:
224
assertEquals("org.bar.Iterator2", results.get(0).getClass().getName());
225         assertEquals("org.foo.impl.Iterator1", results.get(1).getClass().getName());
226     }
227
228     public void testNoCallToGetResourceForObjectIssue65124() throws Exception JavaDoc {
229         class Loader extends ClassLoader JavaDoc {
230             private int counter;
231
232             protected URL JavaDoc findResource(String JavaDoc name) {
233                 if (name.equals("META-INF/services/java.lang.Object")) {
234                     counter++;
235                 }
236
237                 URL JavaDoc retValue;
238
239                 retValue = super.findResource(name);
240                 return retValue;
241             }
242
243             protected Enumeration JavaDoc findResources(String JavaDoc name) throws IOException JavaDoc {
244                 if (name.equals("META-INF/services/java.lang.Object")) {
245                     counter++;
246                 }
247                 Enumeration JavaDoc retValue;
248
249                 retValue = super.findResources(name);
250                 return retValue;
251             }
252         }
253         Loader JavaDoc loader = new Loader JavaDoc();
254         Lookup l = Lookups.metaInfServices(loader);
255
256         Object JavaDoc no = l.lookup(String JavaDoc.class);
257         assertNull("Not found of course", no);
258         assertEquals("No lookup of Object", 0, loader.counter);
259     }
260
261     public void testListenersAreNotifiedWithoutHoldingALockIssue36035() throws Exception JavaDoc {
262         final Lookup l = Lookups.metaInfServices(c2);
263         final Class JavaDoc xface = c1.loadClass("org.foo.Interface");
264         final Lookup.Result res = l.lookup(new Lookup.Template(Object JavaDoc.class));
265
266         class L implements LookupListener, Runnable JavaDoc {
267             private Thread JavaDoc toInterrupt;
268
269             public void run() {
270                 assertNotNull("Possible to query lookup", l.lookup(xface));
271                 assertEquals("and there are two items", 2, res.allInstances().size());
272                 toInterrupt.interrupt();
273             }
274
275             public synchronized void resultChanged(LookupEvent ev) {
276                 toInterrupt = Thread.currentThread();
277                 RequestProcessor.getDefault().post(this);
278                 try {
279                     wait(3000);
280                     fail("Should be interrupted - means it was not possible to finish query in run() method");
281                 } catch (InterruptedException JavaDoc ex) {
282                     // this is what we want
283
}
284             }
285         }
286         L JavaDoc listener = new L JavaDoc();
287
288         res.addLookupListener(listener);
289         assertEquals("Nothing yet", 0, res.allInstances().size());
290
291         assertNotNull("Interface found", l.lookup(xface));
292         assertNotNull("Listener notified", listener.toInterrupt);
293
294         assertEquals("Now two", 2, res.allInstances().size());
295     }
296 }
297
Popular Tags