KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ejen > util > XSLUtil


1 //
2
// Ejen (code generation system)
3
// Copyright (C) 2001, 2002 François Wolff (ejen@noos.fr).
4
//
5
// This file is part of Ejen.
6
//
7
// Ejen is free software; you can redistribute it and/or modify
8
// it under the terms of the GNU General Public License as published by
9
// the Free Software Foundation; either version 2 of the License, or
10
// (at your option) any later version.
11
//
12
// Ejen is distributed in the hope that it will be useful,
13
// but WITHOUT ANY WARRANTY; without even the implied warranty of
14
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
// GNU General Public License for more details.
16
//
17
// You should have received a copy of the GNU General Public License
18
// along with Ejen; if not, write to the Free Software
19
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20
//
21
package org.ejen.util;
22
23 import org.ejen.EjenConstants;
24 import java.io.StringReader JavaDoc;
25 import java.lang.reflect.Constructor JavaDoc;
26 import javax.xml.transform.TransformerException JavaDoc;
27 import javax.xml.transform.TransformerFactory JavaDoc;
28 import javax.xml.transform.ErrorListener JavaDoc;
29 import javax.xml.transform.stream.StreamSource JavaDoc;
30 import org.w3c.dom.Node JavaDoc;
31 import org.w3c.dom.NodeList JavaDoc;
32 import org.w3c.dom.NamedNodeMap JavaDoc;
33 import org.w3c.dom.Document JavaDoc;
34 import org.w3c.dom.traversal.NodeIterator;
35 import org.apache.xml.utils.PrefixResolverDefault;
36 import org.apache.xml.utils.WrappedRuntimeException;
37 import org.apache.xalan.extensions.XSLProcessorContext;
38 import org.apache.xalan.extensions.ExpressionContext;
39 import org.apache.xalan.templates.ElemExtensionCall;
40 import org.apache.xalan.templates.AVT;
41 import org.apache.xalan.processor.StylesheetHandler;
42 import org.apache.xalan.processor.TransformerFactoryImpl;
43 import org.apache.xalan.transformer.TransformerImpl;
44 import org.apache.xpath.NodeSet;
45 import org.apache.xpath.XPathContext;
46 import org.apache.xpath.XPathContext.XPathExpressionContext;
47 import org.apache.xpath.XPath;
48 import org.apache.xpath.objects.XObject;
49
50 /**
51  * XSL utility (static methods used in java code).
52  * @author F. Wolff
53  * @version 1.0
54  */

55 public class XSLUtil {
56
57     /**
58      * Prevents instanciation.
59      */

60     protected XSLUtil() {}
61
62     /**
63      * Returns a new TransformerImpl using the
64      * {@link org.ejen.EjenConstants#DEFAULT_XSL_DATA}
65      * String as source.
66      * @param tfi the TransformerFactoryImpl to use to build the TransformerImpl.
67      * @return the new TransformerImpl.
68      * @throws org.apache.xml.utils.WrappedRuntimeException ...
69      */

70     public static TransformerImpl getDefaultTransformer(TransformerFactoryImpl tfi) {
71         try {
72             return (TransformerImpl) (tfi.newTransformer(new StreamSource JavaDoc(new StringReader JavaDoc(EjenConstants.DEFAULT_XSL_DATA))));
73         } catch (Exception JavaDoc e) {
74             throw new WrappedRuntimeException(e);
75         }
76     }
77
78     /**
79      * Returns an interpreted value (AVT) of a Node attribute whose name is 'name'.
80      * @param context the XSLProcessorContext to be used.
81      * @param elem the ElemExtensionCall to be used.
82      * @param name name of the attribute.
83      * @param throwsIfNull if true, an IllegalArgumentException will be thrown
84      * if no 'name' attribute can be found, otherwise null will returned.
85      * @return the interpreted value (AVT) of the Node attribute.
86      * @throws java.lang.IllegalArgumentException ...
87      * @throws org.apache.xml.utils.WrappedRuntimeException ...
88      */

89     public static String JavaDoc getAttribute(XSLProcessorContext context,
90             ElemExtensionCall elem,
91             String JavaDoc name,
92             boolean throwsIfNull) {
93         try {
94             String JavaDoc value = elem.getAttribute(name, context.getContextNode(),
95                     context.getTransformer());
96
97             if (value == null && throwsIfNull) {
98                 throw new IllegalArgumentException JavaDoc("no \"" + name
99                         + "\" attribute");
100             }
101             return value;
102         } catch (Exception JavaDoc e) {
103             throw new WrappedRuntimeException(e);
104         }
105     }
106
107     /**
108      * Returns an XObject value (AVT or not) of a Node attribute whose name is 'name'.
109      * @param context the XSLProcessorContext to be used.
110      * @param elem the ElemExtensionCall to be used.
111      * @param name name of the attribute.
112      * @param isAVT should the value be interpreted as an AVT?
113      * @param throwsIfNull if true, an IllegalArgumentException will be thrown
114      * if no 'name' attribute can be found, otherwise null will returned.
115      * @return the interpreted value (if AVT) of the Node attribute.
116      * @throws java.lang.IllegalArgumentException ...
117      * @throws org.apache.xml.utils.WrappedRuntimeException ...
118      */

119     public static XObject getXOAttribute(XSLProcessorContext context,
120             ElemExtensionCall elem,
121             String JavaDoc name,
122             boolean isAVT,
123             boolean throwsIfNull) {
124         String JavaDoc value = null;
125
126         try {
127             if (isAVT) {
128                 value = elem.getAttribute(name, context.getContextNode(),
129                         context.getTransformer());
130             } else {
131                 value = elem.getAttribute(name);
132             }
133             if (value == null && throwsIfNull) {
134                 throw new IllegalArgumentException JavaDoc("no \"" + name
135                         + "\" attribute");
136             }
137         } catch (Exception JavaDoc e) {
138             throw new WrappedRuntimeException(e);
139         }
140         return (value == null) ? null : evaluate(context, elem, value);
141     }
142
143     /**
144      * Returns an Object value (AVT or not) of a Node attribute whose name is 'name'.
145      * @param context the XSLProcessorContext to be used.
146      * @param elem the ElemExtensionCall to be used.
147      * @param name name of the attribute.
148      * @param clazz Class of the Object to return.
149      * @param isAVT should the value be interpreted as an AVT?
150      * @param throwsIfNull if true, an IllegalArgumentException will be thrown
151      * if no 'name' attribute can be found, otherwise null will returned.
152      * @return the interpreted value (if AVT) of the Node attribute.
153      * @throws java.lang.ClassCastException if the Object is not an instance of
154      * clazz.
155      * @throws java.lang.IllegalArgumentException ...
156      * @throws org.apache.xml.utils.WrappedRuntimeException ...
157      */

158     public static Object JavaDoc getOAttribute(XSLProcessorContext context,
159             ElemExtensionCall elem,
160             String JavaDoc name,
161             Class JavaDoc clazz,
162             boolean isAVT,
163             boolean throwsIfNull) {
164         XObject xo = getXOAttribute(context, elem, name, isAVT, throwsIfNull);
165
166         if (xo == null) {
167             return null;
168         }
169         if (xo.object() == null
170                 || clazz.isAssignableFrom(xo.object().getClass())) {
171             return xo.object();
172         }
173         throw new WrappedRuntimeException(new ClassCastException JavaDoc("Class of \""
174                 + name + "\" attribute should be " + clazz));
175     }
176
177     /**
178      * Returns an interpreted value (AVT) of a Node attribute whose name is "avt".
179      * @param context the XSLProcessorContext to be used.
180      * @param elem the ElemExtensionCall to be used.
181      * @return the evaluated result.
182      * @throws java.lang.IllegalArgumentException bad context.
183      * @throws org.apache.xml.utils.WrappedRuntimeException ...
184      */

185     public static String JavaDoc evaluate(XSLProcessorContext context, ElemExtensionCall elem) {
186         return getAttribute(context, elem, "avt", true);
187     }
188
189     /**
190      * Returns an interpreted value (AVT) of a Node attribute whose name is equals
191      * to the avt parameter.
192      * @param context the ExpressionContext to be used.
193      * @param avt the name of the attribute.
194      * @return the evaluated result.
195      * @throws java.lang.IllegalArgumentException bad context.
196      * @throws org.apache.xml.utils.WrappedRuntimeException ...
197      */

198     public static String JavaDoc evaluate(ExpressionContext context, String JavaDoc avt) {
199         try {
200             if (!(context instanceof XPathExpressionContext)) {
201                 throw new IllegalArgumentException JavaDoc("bad context: " + context);
202             }
203             XPathExpressionContext xpec = (XPathExpressionContext) context;
204             StylesheetHandler sh = (StylesheetHandler) (
205                     ((TransformerFactoryImpl) (TransformerFactory.newInstance())).newTemplatesHandler()
206                     );
207
208             return evaluateAttribute(sh, xpec.getXPathContext(),
209                     xpec.getContextNode(), avt);
210         } catch (Exception JavaDoc e) {
211             throw new WrappedRuntimeException(e);
212         }
213     }
214
215     /**
216      * Returns the interpretion (AVT) of the expression parameter.
217      * @param context the XSLProcessorContext to be used.
218      * @param elem the ElemExtensionCall to be used.
219      * @param expression the expression to be evaluated.
220      * @return the evaluated result.
221      * @throws org.apache.xml.utils.WrappedRuntimeException ...
222      */

223     public static XObject evaluate(XSLProcessorContext context,
224             ElemExtensionCall elem,
225             String JavaDoc expression) {
226         try {
227             XPathContext xpc = context.getTransformer().getXPathContext();
228             XPath xp = new XPath(expression, elem, xpc.getNamespaceContext(),
229                     XPath.SELECT);
230
231             return xp.execute(xpc, context.getContextNode(), elem);
232         } catch (Exception JavaDoc e) {
233             throw new WrappedRuntimeException(e);
234         }
235     }
236
237     /**
238      * Returns an XObject resulting from the evaluation of the str parameter.
239      * @param contextNode the Node to be used as context.
240      * @param str the expression to be evaluated.
241      * @return the evaluated result.
242      * @throws org.apache.xml.utils.WrappedRuntimeException ...
243      */

244     public static XObject evaluate(Node JavaDoc contextNode, String JavaDoc str) {
245         return evaluate(contextNode, str, contextNode, null);
246     }
247
248     /**
249      * Returns an XObject resulting from the evaluation of the str parameter.
250      * @param contextNode the Node to be used as context.
251      * @param str the expression to be evaluated.
252      * @param el the ErrorListener to be used.
253      * @return the evaluated result.
254      * @throws org.apache.xml.utils.WrappedRuntimeException ...
255      */

256     public static XObject evaluate(Node JavaDoc contextNode, String JavaDoc str, ErrorListener JavaDoc el) {
257         return evaluate(contextNode, str, contextNode, el);
258     }
259
260     /**
261      * Returns an XObject resulting from the evaluation of the str parameter.
262      * @param contextNode the Node to be used as context.
263      * @param str the expression to be evaluated.
264      * @param namespaceNode the namespace Node to be used.
265      * @param el the ErrorListener to be used.
266      * @return the evaluated result.
267      * @throws org.apache.xml.utils.WrappedRuntimeException ...
268      */

269     public static XObject evaluate(Node JavaDoc contextNode, String JavaDoc str, Node JavaDoc namespaceNode, ErrorListener JavaDoc el) {
270         try {
271             XPathContext xpc = new XPathContext();
272             PrefixResolverDefault pr = new PrefixResolverDefault((namespaceNode.getNodeType()
273                     == Node.DOCUMENT_NODE)
274                     ? ((Document JavaDoc) namespaceNode).getDocumentElement()
275                     : namespaceNode);
276             XPath xp = new XPath(str, null, pr, XPath.SELECT, el);
277             int iContextNode = xpc.getDTMHandleFromNode(contextNode);
278
279             return xp.execute(xpc, iContextNode, pr);
280         } catch (Exception JavaDoc e) {
281             throw new WrappedRuntimeException(e);
282         }
283     }
284     
285     // DT 11.08.2003 BEGIN
286
// Construct AVT, depending on java release
287
private static AVT constructAVT(StylesheetHandler handler,
288             String JavaDoc uri,
289             String JavaDoc name,
290             String JavaDoc rawName,
291             String JavaDoc stringedValue) throws Exception JavaDoc {
292         Class JavaDoc[] parameterType = new Class JavaDoc[6];
293         Constructor JavaDoc avtConstr = null;
294         AVT avt = null;
295
296         try {
297             parameterType[0] = Class.forName("org.apache.xalan.processor.StylesheetHandler");
298             parameterType[1] = Class.forName("java.lang.String");
299             parameterType[2] = Class.forName("java.lang.String");
300             parameterType[3] = Class.forName("java.lang.String");
301             parameterType[4] = Class.forName("java.lang.String");
302             parameterType[5] = Class.forName("org.apache.xalan.templates.ElemTemplateElement");
303             avtConstr = Class.forName("org.apache.xalan.templates.AVT").getConstructor(parameterType);
304             
305             Object JavaDoc[] parameter = new Object JavaDoc[6];
306
307             parameter[0] = handler;
308             parameter[1] = uri;
309             parameter[2] = name;
310             parameter[3] = rawName;
311             parameter[4] = stringedValue;
312             parameter[5] = null;
313             avt = (AVT) avtConstr.newInstance(parameter);
314         } catch (Exception JavaDoc e) {
315             parameterType = new Class JavaDoc[5];
316             parameterType[0] = Class.forName("org.apache.xalan.processor.StylesheetHandler");
317             parameterType[1] = Class.forName("java.lang.String");
318             parameterType[2] = Class.forName("java.lang.String");
319             parameterType[3] = Class.forName("java.lang.String");
320             parameterType[4] = Class.forName("java.lang.String");
321             avtConstr = Class.forName("org.apache.xalan.templates.AVT").getConstructor(parameterType);
322             
323             Object JavaDoc[] parameter = new Object JavaDoc[5];
324
325             parameter[0] = handler;
326             parameter[1] = uri;
327             parameter[2] = name;
328             parameter[3] = rawName;
329             parameter[4] = stringedValue;
330             avt = (AVT) avtConstr.newInstance(parameter);
331         }
332         
333         return avt;
334     }
335
336     // DT 11.08.2003 END
337

338     /**
339      * Returns a String resulting from the evaluation of the expr parameter (AVT).
340      * @param sh the StylesheetHandler to be used.
341      * @param xpc the XPathContext to be used.
342      * @param node the Node to be used as context.
343      * @param expr the expression to be evaluated.
344      * @param namespaceNode the namespace Node to be used.
345      * @param el the ErrorListener to be used.
346      * @return the evaluated result.
347      * @throws javax.xml.transform.TransformerException ...
348      */

349     public static String JavaDoc evaluateAttribute(StylesheetHandler sh,
350             XPathContext xpc,
351             Node JavaDoc node,
352             String JavaDoc expr)
353         throws TransformerException JavaDoc {
354         String JavaDoc uri = node.getNamespaceURI();
355
356         if (uri == null) {
357             uri = "";
358         }
359             
360         String JavaDoc name = node.getNodeName();
361
362         if (name == null) {
363             name = "";
364         }
365         String JavaDoc prefix = node.getPrefix();
366         String JavaDoc rawName = ((prefix != null) ? prefix + ":" : "") + name;
367         // DT 11.08.2003 BEGIN
368
// AVT avt = new AVT(sh, uri, name, rawName, expr);
369
AVT avt = null;
370
371         try {
372             avt = constructAVT(sh, uri, name, rawName, expr);
373         } catch (Exception JavaDoc e) {
374             e.printStackTrace();
375             throw new TransformerException JavaDoc("AVT constructor not found");
376         }
377         // DT 11.08.2003 END
378
PrefixResolverDefault pr = new PrefixResolverDefault((node.getNodeType()
379                 == Node.DOCUMENT_NODE)
380                 ? ((Document JavaDoc) node).getDocumentElement()
381                 : node);
382
383         // System.out.println("Result " + avt.evaluate(xpc, xpc.getDTMHandleFromNode(node), pr).toString());
384
return avt.evaluate(xpc, xpc.getDTMHandleFromNode(node), pr).toString();
385     }
386
387     /**
388      * Checks ni1 and ni2 for strict equality (same names, same attributes,
389      * same child nodes...).
390      * @param ni1 the first NodeIterator.
391      * @param ni2 the second NodeIterator.
392      * @return true if ni1 equals ni2, false otherwise.
393      */

394     public static boolean equals(NodeIterator ni1, NodeIterator ni2) {
395         NodeSet ns1 = new NodeSet(ni1);
396         NodeSet ns2 = new NodeSet(ni2);
397
398         if (ns1.getLength() != ns2.getLength()) {
399             return false;
400         }
401         for (int i = 0; i < ns1.getLength(); i++) {
402             if (!equals(ns1.elementAt(i), ns2.elementAt(i))) {
403                 return false;
404             }
405         }
406         return true;
407     }
408
409     /**
410      * Checks n1 and n2 for strict equality (same names, same attributes,
411      * same child nodes...).
412      * @param n1 the first Node.
413      * @param n2 the second Node.
414      * @return true if n1 equals n2, false otherwise.
415      */

416     public static boolean equals(Node JavaDoc n1, Node JavaDoc n2) {
417         if (n1 == null && n2 == null) {
418             return true;
419         }
420         if (n1 == null || n2 == null) {
421             return false;
422         }
423         if (n1.getNodeType() != n2.getNodeType()) {
424             return false;
425         }
426         if (!n1.getNodeName().equals(n2.getNodeName())) {
427             return false;
428         }
429         String JavaDoc v1 = n1.getNodeValue();
430         String JavaDoc v2 = n2.getNodeValue();
431
432         if ((v1 == null && v2 != null) || (v1 != null && !v1.equals(v2))) {
433             return false;
434         }
435         NamedNodeMap JavaDoc nnm1 = n1.getAttributes();
436         NamedNodeMap JavaDoc nnm2 = n2.getAttributes();
437
438         if ((nnm1 == null || nnm2 == null) && nnm1 != nnm2) {
439             return false;
440         }
441         if (nnm1 != null) {
442             int nnm1Length = nnm1.getLength();
443
444             if (nnm1Length != nnm2.getLength()) {
445                 return false;
446             }
447             for (int i = 0; i < nnm1Length; i++) {
448                 if (!equals(nnm1.item(i), nnm2.item(i))) {
449                     return false;
450                 }
451             }
452         }
453         
454         NodeList JavaDoc nl1 = n1.getChildNodes();
455         NodeList JavaDoc nl2 = n2.getChildNodes();
456         int nl1Length = nl1.getLength();
457
458         if (nl1Length != nl2.getLength()) {
459             return false;
460         }
461         for (int i = 0; i < nl1Length; i++) {
462             if (!equals(nl1.item(i), nl2.item(i))) {
463                 return false;
464             }
465         }
466         
467         return true;
468     }
469
470     /**
471      * Returns the Document used in the context parameter.
472      * @param context an ExpressionContext.
473      * @return the Document.
474      * @throws org.apache.xml.utils.WrappedRuntimeException failed...
475      */

476     public static Document JavaDoc getContextDocument(ExpressionContext context) {
477         try {
478             return context.getContextNode().getOwnerDocument();
479         } catch (Exception JavaDoc e) {
480             throw new WrappedRuntimeException("Failed to get Document from ExpressionContext",
481                     e);
482         }
483     }
484 }
485
Popular Tags