KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > core > xml > FactoriesTest


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.netbeans.core.xml;
21
22 import java.io.*;
23 import java.net.*;
24 import java.util.*;
25 import javax.xml.parsers.*;
26 import javax.xml.parsers.SAXParserFactory JavaDoc;
27 import junit.framework.*;
28 import org.netbeans.core.startup.DOMFactoryImpl;
29 import org.netbeans.core.startup.SAXFactoryImpl;
30 import org.netbeans.junit.*;
31 import org.openide.util.*;
32 import org.xml.sax.*;
33
34
35
36 /**
37  * A test verifying that by default, cheap JDK-default crimson parser is used,
38  * but if you ask for some fancy features, possible better parser is provided.
39  *
40  * @author Nenik
41  */

42 public class FactoriesTest extends NbTestCase {
43     static SAXParserFactory JavaDoc origSAX;
44     static DocumentBuilderFactory origDOM;
45     static {
46         origSAX = SAXParserFactory.newInstance();
47         origDOM = DocumentBuilderFactory.newInstance();
48         SAXFactoryImpl.install();
49         DOMFactoryImpl.install();
50         System.setSecurityManager (new org.netbeans.TopSecurityManager ());
51     }
52     /** Creates a new instance of FactoriesTest */
53     public FactoriesTest(String JavaDoc testName) {
54         super(testName);
55     }
56     
57     public static void main(java.lang.String JavaDoc[] args) {
58         junit.textui.TestRunner.run(suite());
59     }
60     
61     public static Test suite() {
62         NbTestSuite suite = new NbTestSuite(FactoriesTest.class);
63         return suite;
64     }
65
66     
67     protected void setUp () throws Exception JavaDoc {
68         System.setProperty("org.openide.util.Lookup", "org.netbeans.core.xml.FactoriesTest$Lkp");
69         assertNotNull ("ErrManager has to be in lookup", org.openide.util.Lookup.getDefault ().lookup (ErrManager.class));
70         
71         SAXParserFactory JavaDoc sax = SAXParserFactory.newInstance ();
72         if (!(sax instanceof SAXFactoryImpl)) {
73             fail ("We expect to see our factory, but was: " + sax);
74         }
75         
76         DocumentBuilderFactory dom = DocumentBuilderFactory.newInstance ();
77         if (!(dom instanceof DOMFactoryImpl)) {
78             fail ("We expect to see our factory, but was: " + dom);
79         }
80         
81     }
82
83     
84     /** Check whether factory provides cheap parser by default */
85     public void testCreateCheapSAXParser() throws Exception JavaDoc {
86         SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
87         assertFalse("JDK-provided parser", testMap.containsKey(parser));
88     }
89     
90     /** Check whether factory provides cheap parser by default */
91     public void testCreateFeaturedSAXParser() throws Exception JavaDoc {
92         String JavaDoc[] features = new String JavaDoc[] {
93             SaxFactory1.class.getName(),
94             SaxFactory2.class.getName(),
95             SaxFactory3.class.getName(),
96             SaxFactory4.class.getName(),
97         };
98         
99         for (int i=0; i<features.length; i++) {
100             String JavaDoc feature = features[i];
101             SAXParserFactory JavaDoc fact = SAXParserFactory.newInstance();
102             fact.setFeature(feature, true);
103             
104             SAXParser parser = fact.newSAXParser();
105             assertEquals("Parser with feature " + feature, feature, testMap.get(parser));
106         }
107     }
108     
109     /** Check whether factory fails for unsupported feature */
110     public void testCreateNonexistingSAXParser() throws Exception JavaDoc {
111         SAXParserFactory JavaDoc fact = SAXParserFactory.newInstance();
112         try {
113             fact.setFeature("NoNeXiStInGfEaTuRe", true);
114         } catch (Exception JavaDoc e) {
115             return; // OK
116
}
117         
118         fail ("Created parser with unsupported feature");
119     }
120
121         /** Check whether factory provides cheap parser by default */
122     public void testCreateCheapDOMBuilder() throws Exception JavaDoc {
123         DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
124         assertFalse("JDK-provided builder", testMap.containsKey(builder));
125     }
126     
127     /** Check whether factory provides cheap parser by default */
128     public void testCreateFeaturedDOMBuilder() throws Exception JavaDoc {
129         String JavaDoc[] features = new String JavaDoc[] {
130             DOMFactory1.class.getName(),
131             DOMFactory2.class.getName(),
132             DOMFactory3.class.getName(),
133             DOMFactory4.class.getName(),
134         };
135         
136         for (int i=0; i<features.length; i++) {
137             String JavaDoc feature = features[i];
138             DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
139             fact.setAttribute(feature, "YES");
140             
141             DocumentBuilder builder = fact.newDocumentBuilder();
142             assertEquals("Builder with feature " + feature, feature, testMap.get(builder));
143         }
144     }
145     
146     /** Check whether factory fails for unsupported feature */
147     public void testCreateNonexistingDOMBuilder() throws Exception JavaDoc {
148         DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
149         try {
150             fact.setAttribute("NoNeXiStInGfEaTuRe", "YES");
151         } catch (Exception JavaDoc e) {
152             return; // OK
153
}
154         
155         fail ("Created builder with unsupported feature");
156     }
157     
158     /** For cases the factories are not on classpath we fallback to
159      * some implementation.
160      */

161     public void testFactoriesAreNotOnClassPath () throws Exception JavaDoc {
162         ClassLoader JavaDoc parent = SAXFactoryImpl.class.getClassLoader ();
163         assertNotNull ("We have a classloader", parent);
164         parent = parent.getParent ();
165         assertNotNull ("Still not null", parent);
166         
167         try {
168             Class JavaDoc l = parent.loadClass (SAXFactoryImpl.class.getName ());
169             fail ("The classloader " + parent + " should not be able to load: " + l);
170         } catch (ClassNotFoundException JavaDoc ex) {
171             // ok, satisfied
172
}
173         
174         CL loader = new CL (parent, FactoriesRunnableHid.class.getName (), getClass ().getResource ("FactoriesRunnableHid.class"));
175         Class JavaDoc runnableClass = loader.loadClass (FactoriesRunnableHid.class.getName ());
176         assertNotNull (runnableClass);
177         assertFalse ("Different class than our", FactoriesRunnableHid.class == runnableClass);
178         
179         Thread.currentThread ().setContextClassLoader (loader);
180         Runnable JavaDoc run = (Runnable JavaDoc)runnableClass.newInstance ();
181         run.run ();
182         
183         /** the runnable also implements map so we can get some values from it ;-) */
184         Map map = (Map)run;
185         
186         Object JavaDoc dom = map.get ("dom");
187         Object JavaDoc sax = map.get ("sax");
188         
189         assertNotNull ("Wants dom", dom);
190         assertNotNull ("Wants sax", sax);
191      
192         assertEquals ("We should use orignal sax", origSAX.getClass (), sax.getClass ());
193         assertEquals ("We should use orignal dom", origDOM.getClass (), dom.getClass ());
194         
195     }
196
197     
198     static Map testMap = new WeakHashMap();
199     
200     static class GenericSAXFactory extends SAXParserFactory JavaDoc {
201         String JavaDoc supported;
202         boolean value;
203         
204         GenericSAXFactory() {
205             this.supported = getClass().getName();
206         }
207         
208         public SAXParser newSAXParser() throws ParserConfigurationException, SAXException {
209             SAXParser parser = origSAX.newSAXParser();
210             testMap.put(parser, supported);
211             return parser;
212         }
213
214         public boolean getFeature(String JavaDoc name) throws ParserConfigurationException, SAXNotRecognizedException, SAXNotSupportedException {
215             if (supported.equals(name)) return value;
216             return false;
217         }
218
219
220         public void setFeature(String JavaDoc name, boolean value) throws ParserConfigurationException, SAXNotRecognizedException, SAXNotSupportedException {
221             if (supported.equals(name)) {
222                 this.value = value;
223             } else {
224                 throw new ParserConfigurationException(name + " not supported" );
225             }
226         }
227         
228     }
229     
230     public static class SaxFactory1 extends GenericSAXFactory {}
231     public static class SaxFactory2 extends GenericSAXFactory {}
232     public static class SaxFactory3 extends GenericSAXFactory {}
233     public static class SaxFactory4 extends GenericSAXFactory {}
234     
235     static class GenericDOMFactory extends DocumentBuilderFactory {
236         String JavaDoc supported;
237         Object JavaDoc value;
238         
239         GenericDOMFactory() {
240             this.supported = getClass().getName();
241         }
242         
243         public DocumentBuilder newDocumentBuilder() throws ParserConfigurationException {
244             DocumentBuilder builder = origDOM.newDocumentBuilder();
245             testMap.put(builder, supported);
246             return builder;
247         }
248     
249     
250         public java.lang.Object JavaDoc getAttribute(java.lang.String JavaDoc name) throws java.lang.IllegalArgumentException JavaDoc {
251             if (supported.equals(name)) return value;
252             return null;
253         }
254
255
256
257         public void setAttribute(java.lang.String JavaDoc name, java.lang.Object JavaDoc value) throws java.lang.IllegalArgumentException JavaDoc {
258             if (supported.equals(name)) {
259                 this.value = value;
260             } else {
261                 throw new IllegalArgumentException JavaDoc(name + " not supported" );
262             }
263         }
264
265         public boolean getFeature(java.lang.String JavaDoc name) throws javax.xml.parsers.ParserConfigurationException JavaDoc {
266             return false;
267         }
268
269         public void setFeature(java.lang.String JavaDoc name, boolean value) throws javax.xml.parsers.ParserConfigurationException JavaDoc {
270         }
271     }
272     
273     public static class DOMFactory1 extends GenericDOMFactory {}
274     public static class DOMFactory2 extends GenericDOMFactory {}
275     public static class DOMFactory3 extends GenericDOMFactory {}
276     public static class DOMFactory4 extends GenericDOMFactory {}
277
278     
279     
280     //
281
// Our fake lookup
282
//
283
public static final class Lkp extends org.openide.util.lookup.AbstractLookup {
284         public Lkp () {
285             this (new org.openide.util.lookup.InstanceContent ());
286         }
287         
288         private Lkp (org.openide.util.lookup.InstanceContent ic) {
289             super (ic);
290             ic.add (new ErrManager ());
291             ic.add (new SaxFactory1());
292             ic.add (new SaxFactory2());
293             ic.add (new SaxFactory3());
294             ic.add (new SaxFactory4());
295             ic.add (new DOMFactory1());
296             ic.add (new DOMFactory2());
297             ic.add (new DOMFactory3());
298             ic.add (new DOMFactory4());
299         }
300     }
301     //
302
// Logging support
303
//
304
public static final class ErrManager extends org.openide.ErrorManager {
305         public static final StringBuffer JavaDoc messages = new StringBuffer JavaDoc ();
306         
307         private String JavaDoc prefix;
308         
309         public ErrManager () {
310             this (null);
311         }
312         public ErrManager (String JavaDoc prefix) {
313             this.prefix = prefix;
314         }
315         
316         public Throwable JavaDoc annotate (Throwable JavaDoc t, int severity, String JavaDoc message, String JavaDoc localizedMessage, Throwable JavaDoc stackTrace, java.util.Date JavaDoc date) {
317             return t;
318         }
319         
320         public Throwable JavaDoc attachAnnotations (Throwable JavaDoc t, org.openide.ErrorManager.Annotation[] arr) {
321             return t;
322         }
323         
324         public org.openide.ErrorManager.Annotation[] findAnnotations (Throwable JavaDoc t) {
325             return null;
326         }
327         
328         public org.openide.ErrorManager getInstance (String JavaDoc name) {
329             return new ErrManager ();
330         }
331         
332         public void log (int severity, String JavaDoc s) {
333             if (prefix != null) {
334                 messages.append (prefix);
335                 messages.append (s);
336                 messages.append ('\n');
337             }
338         }
339         
340         public void notify (int severity, Throwable JavaDoc t) {
341             log (severity, t.getMessage ());
342         }
343         
344         public boolean isNotifiable (int severity) {
345             return prefix != null;
346         }
347         
348         public boolean isLoggable (int severity) {
349             return prefix != null;
350         }
351         
352     } // end of ErrManager
353

354     /** Our own classloader that loads FactoriesRunnableHid
355      */

356     public static final class CL extends ClassLoader JavaDoc {
357         private String JavaDoc name;
358         private URL url;
359         
360         public CL (ClassLoader JavaDoc parent, String JavaDoc className, URL url) {
361             super (parent);
362             this.name = className;
363             this.url = url;
364         }
365
366         protected Class JavaDoc findClass(String JavaDoc str) throws ClassNotFoundException JavaDoc {
367             if (str.equals (name)) {
368                 try {
369                     InputStream is = url.openStream ();
370                     byte[] arr = new byte[4096];
371                     int len = is.read (arr);
372                     return defineClass (name, arr, 0, len);
373                 } catch (java.io.IOException JavaDoc ex) {
374                     throw new ClassNotFoundException JavaDoc (ex.getMessage ());
375                 }
376             }
377             throw new ClassNotFoundException JavaDoc ();
378         }
379         
380         
381     } // end of CL
382
}
383
Popular Tags