01: /*
02: * Copyright 2007 the original author or authors.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16:
17: package org.springframework.xml.xpath;
18:
19: import java.util.Properties;
20: import javax.xml.transform.Source;
21: import javax.xml.transform.TransformerException;
22: import javax.xml.transform.dom.DOMResult;
23:
24: import org.springframework.xml.transform.TransformerObjectSupport;
25: import org.w3c.dom.DOMException;
26: import org.w3c.dom.Document;
27: import org.w3c.dom.Element;
28: import org.w3c.dom.Node;
29:
30: /**
31: * Abstract base class for implementations of {@link XPathOperations}. Contains a namespaces property.
32: *
33: * @author Arjen Poutsma
34: * @since 1.0.0
35: */
36: public abstract class AbstractXPathTemplate extends
37: TransformerObjectSupport implements XPathOperations {
38:
39: private Properties namespaces;
40:
41: /** Returns namespaces used in the XPath expression. */
42: public Properties getNamespaces() {
43: return namespaces;
44: }
45:
46: /** Sets namespaces used in the XPath expression. Maps prefixes to namespaces. */
47: public void setNamespaces(Properties namespaces) {
48: this .namespaces = namespaces;
49: }
50:
51: public final void evaluate(String expression, Source context,
52: NodeCallbackHandler callbackHandler) throws XPathException {
53: evaluate(expression, context,
54: new NodeCallbackHandlerNodeMapper(callbackHandler));
55: }
56:
57: /** Static inner class that adapts a {@link NodeCallbackHandler} to the interface of {@link NodeMapper}. */
58: private static class NodeCallbackHandlerNodeMapper implements
59: NodeMapper {
60:
61: private final NodeCallbackHandler callbackHandler;
62:
63: public NodeCallbackHandlerNodeMapper(
64: NodeCallbackHandler callbackHandler) {
65: this .callbackHandler = callbackHandler;
66: }
67:
68: public Object mapNode(Node node, int nodeNum)
69: throws DOMException {
70: callbackHandler.processNode(node);
71: return null;
72: }
73: }
74:
75: /**
76: * Returns the root element of the given source.
77: *
78: * @param source the source to get the root element from
79: * @return the root element
80: */
81: protected Element getRootElement(Source source)
82: throws TransformerException {
83: DOMResult domResult = new DOMResult();
84: transform(source, domResult);
85: Document document = (Document) domResult.getNode();
86: return document.getDocumentElement();
87: }
88:
89: }
|