KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > schema2beans > DDFactory


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.modules.schema2beans;
21
22 import java.util.*;
23 import java.io.*;
24
25 import java.lang.reflect.*;
26
27 import org.w3c.dom.*;
28
29
30 /**
31  * This class provides a dynamic mechanism to instantiate schema2beans graphs.
32  * The first and most common way to instantiate a schema2beans graph is to
33  * call the createGraph() method on the root class of the generated
34  * schema2beans classes.
35  *
36  * It might happen that the code that whish to instantiate a schema2beans graph
37  * doesn't have or know about the class of the schema2beans root element.
38  * Such code should be able to say 'I want to instantiate a schema2beans graph',
39  * and I know that it is named 'graphName'. This is what the register and
40  * create methods are performing.
41  *
42  * The code that knows about the schema2beans classes can register the class
43  * root node using some public name. Then, other part of the code can
44  * instantiate a schema2beans graph using simply the public name (@see create).
45  *
46  * This class also provide some utility methods to dump the content of a
47  * DOM tree as a String (@see XmlToString).
48  *
49  */

50 public class DDFactory extends Object JavaDoc {
51     static HashMap beanClassMap = new HashMap();
52     
53     static int idCount = 0;
54     
55     /**
56      * Create the proper DD bean object graph depending on the document
57      * type of the XML document specified as an input stream.
58      *
59      * @param in the XML document is passed as an input stream.
60      * @return BaseBean is the base object for all DD beans.
61      */

62     public static BaseBean create(InputStream in, String JavaDoc rootName) throws Schema2BeansException {
63     Document doc = null;
64     String JavaDoc docType;
65     BaseBean beanNode = null;
66     Class JavaDoc bean;
67     
68     if (DDLogFlags.debug) {
69         TraceLogger.put(TraceLogger.DEBUG, TraceLogger.SVC_DD,
70         DDLogFlags.DBG_BLD, 1,
71         DDLogFlags.DDCREATE);
72     }
73     
74     doc = GraphManager.createXmlDocument(in, false);
75     
76     if (DDLogFlags.debug) {
77         String JavaDoc str = XmlToString(doc, 999);
78         TraceLogger.put(TraceLogger.DEBUG, TraceLogger.SVC_DD,
79         DDLogFlags.DBG_BLD, 20,
80         DDLogFlags.DDCREATED,
81         str );
82     }
83     
84     synchronized (beanClassMap) {
85         bean = (Class JavaDoc)beanClassMap.get(rootName);
86     }
87     
88     if (bean == null)
89         throw new Schema2BeansException(Common.getMessage(
90         "CantCreateBeanForRootElement_msg", rootName));
91     
92     
93     Constructor c = null;
94     
95     try {
96         Class JavaDoc[] cc = new Class JavaDoc[] {org.w3c.dom.Node JavaDoc.class,
97         int.class};
98         c = bean.getDeclaredConstructor(cc);
99     }
100     catch(NoSuchMethodException JavaDoc me) {
101         throw new Schema2BeansNestedException(Common.getMessage(
102         "CantGetConstructor_msg"), me);
103     }
104     
105     Object JavaDoc[] p = new Object JavaDoc[] {doc, new Integer JavaDoc(Common.NO_DEFAULT_VALUES)};
106     
107     try {
108         beanNode = (BaseBean)c.newInstance(p);
109     }
110     catch(Exception JavaDoc e) {
111         TraceLogger.error(e);
112         throw new Schema2BeansNestedException(Common.getMessage(
113                                           "CantInstanciateBeanClass_msg"), e);
114     }
115     
116     if (DDLogFlags.debug) {
117         TraceLogger.put(TraceLogger.DEBUG, TraceLogger.SVC_DD,
118         DDLogFlags.DBG_BLD, 1,
119         DDLogFlags.DDBEANED,
120         "Created bean graph node for " + rootName );
121     }
122     
123     return beanNode;
124     }
125     
126     /**
127      * Register the root bean to use for a DTD document root name.
128      * Use the default class loader, then tries to use the String name
129      * object class loader. The name of the graph can be any string (it doesn't
130      * have to be the root element name)
131      *
132      * @param name entry name of this graph registry
133      * @param className class name (package and class name) to use
134      * in order to instantiate the schema2beans graph. This should be the
135      * class name of the root of the schema2beans generated classes.
136      */

137     static public void register(String JavaDoc name, String JavaDoc className)
138     throws ClassNotFoundException JavaDoc {
139     Class JavaDoc c = null;
140     try {
141         c = Class.forName(className);
142     } catch(ClassNotFoundException JavaDoc e) {
143         // Try with the String object class loader
144
c = name.getClass().forName(className);
145     }
146     DDFactory.register(name, c);
147     }
148
149     /**
150      * Register the root bean to use for a DTD document root name.
151      * Use the default class loader, then tries to use the String name
152      * object class loader. The name of the graph can be any string (it doesn't
153      * have to be the root element name)
154      *
155      * @param name entry name of this graph registry
156      * @param clazz class to use in order to instantiate the schema2beans graph.
157      * This should be the class of the root of the schema2beans generated classes.
158      */

159     static public void register(String JavaDoc name, Class JavaDoc clazz) {
160     synchronized (beanClassMap) {
161         beanClassMap.put(name, clazz);
162     }
163     }
164
165     /*
166      * This is where the schema2beans runtime can get a unique ID to tag the elts
167      * (any element is uniquely identified using this ID. This is how we
168      * can uniquely track the elements of an array even though the user
169      * mizes the array).
170      */

171     static synchronized int getUniqueId() {
172     return DDFactory.idCount++;
173     }
174     
175     
176     static String JavaDoc typeToString(short type) {
177     switch(type) {
178         case Node.ATTRIBUTE_NODE: return "attr"; // NOI18N
179
case Node.CDATA_SECTION_NODE: return "cdata"; // NOI18N
180
case Node.COMMENT_NODE : return "comment"; // NOI18N
181
case Node.DOCUMENT_FRAGMENT_NODE: return "doc_fragment"; // NOI18N
182
case Node.DOCUMENT_NODE: return "doc"; // NOI18N
183
case Node.DOCUMENT_TYPE_NODE: return "doc_type"; // NOI18N
184
case Node.ELEMENT_NODE: return "element"; // NOI18N
185
case Node.ENTITY_NODE: return "entity"; // NOI18N
186
case Node.ENTITY_REFERENCE_NODE: return "entity_ref"; // NOI18N
187
case Node.NOTATION_NODE: return "notation"; // NOI18N
188
case Node.PROCESSING_INSTRUCTION_NODE: return "processing_instr";// NOI18N
189
case Node.TEXT_NODE: return "text"; // NOI18N
190
default: return "type:" + type; // NOI18N
191
}
192     }
193     
194     
195     /**
196      * Dump the whole content of a DOM tree as a String
197      */

198     static public String JavaDoc XmlToString(Node n) {
199     return XmlToString(n, 9999, null);
200     }
201     
202     /**
203      * Dump the content of a DOM tree as a String. This methods only
204      * recurses for the specified depth.
205      */

206     static public String JavaDoc XmlToString(Node n, int depth) {
207     return XmlToString(n, depth, null);
208     }
209     
210     
211     /**
212      * Dump the content of a DOM tree as a String. This methods only
213      * recurses for the specified depth and only prints elements that
214      * match the filter.
215      */

216     static public String JavaDoc XmlToString(Node n, int depth, String JavaDoc filter) {
217     StringBuffer JavaDoc str = new StringBuffer JavaDoc();
218     nodeToString("", str, n, depth, filter, true); // NOI18N
219
return str.toString();
220     }
221     
222     // Method related to XmlToString
223
static void nodeToString(String JavaDoc indent, StringBuffer JavaDoc str, Node n,
224                  int depth, String JavaDoc filter, boolean root) {
225                  
226     if (root)
227         // Don't go for siblings on the root
228
nodeChildrenToString(indent, str, n, depth, filter);
229     else {
230         for (;n != null; n = n.getNextSibling()) {
231         nodeChildrenToString(indent, str, n, depth, filter);
232         }
233     }
234     }
235     
236     
237     // Method related to XmlToString
238
static void nodeChildrenToString(String JavaDoc indent, StringBuffer JavaDoc str,
239                      Node n, int depth, String JavaDoc filter) {
240                      
241     if ((filter == null) || n.getNodeName().equals(filter)) {
242         String JavaDoc tmp = indent + n.getNodeName();
243         String JavaDoc value = n.getNodeValue();
244         short type = n.getNodeType();
245         
246         if (value == null)
247         value = ""; // NOI18N
248
//else
249
//value = value.trim();
250

251         if (!value.equals("")) // NOI18N
252
tmp += "=" + value; // NOI18N
253

254         tmp += " - " + typeToString(type); // NOI18N
255

256         if ((type != Node.TEXT_NODE && type != Node.CDATA_SECTION_NODE) || (!value.trim().equals(""))) // NOI18N
257
{
258         str.append(tmp);
259         str.append("\n"); // NOI18N
260
}
261         
262         NamedNodeMap map = n.getAttributes();
263         if (map != null && map.getLength() != 0) {
264             List attrNames = new ArrayList(map.getLength());
265             for (int i=0; i<map.getLength(); i++) {
266                 Attr a = (Attr)map.item(i);
267                 attrNames.add(a.getName());
268             }
269             Collections.sort(attrNames);
270             for (Iterator it = attrNames.iterator(); it.hasNext(); ) {
271                 Attr a = (Attr) map.getNamedItem((String JavaDoc)it.next());
272                 str.append(indent);
273                 str.append("attribute: "); // NOI18N
274
str.append(a.getName());
275                 str.append("="); // NOI18N
276
str.append(a.getValue());
277                 str.append("\n"); // NOI18N
278
}
279         }
280     }
281     
282     if (n.getFirstChild() != null && (depth > 0) )
283         nodeToString(indent + " ", str, n.getFirstChild(), // NOI18N
284
depth-1, filter, false);
285     }
286 }
287
288
Popular Tags