01: package org.wso2.esb.util;
02:
03: import org.apache.axiom.om.OMElement;
04: import org.apache.axiom.om.impl.builder.StAXOMBuilder;
05: import org.apache.axiom.om.xpath.AXIOMXPath;
06: import org.apache.commons.logging.Log;
07: import org.apache.commons.logging.LogFactory;
08: import org.jaxen.JaxenException;
09: import org.jaxen.SimpleNamespaceContext;
10: import org.jaxen.XPath;
11: import org.wso2.esb.ServiceBusConstants;
12: import org.wso2.utils.ServerException;
13:
14: import javax.xml.stream.XMLStreamException;
15: import java.io.FileNotFoundException;
16: import java.util.List;
17:
18: public class XmlConfiguration {
19:
20: private static Log log = LogFactory.getLog(XmlConfiguration.class);
21:
22: private StAXOMBuilder builder;
23:
24: private String serverNamespace = ServiceBusConstants.ESB_XML_NAMESPACE;
25:
26: public XmlConfiguration(String xmlFile) throws ServerException {
27: this (xmlFile, null);
28: }
29:
30: public XmlConfiguration(String xmlFile, String serverNamespace)
31: throws ServerException {
32: if (serverNamespace != null) {
33: this .serverNamespace = serverNamespace;
34: }
35: try {
36: builder = new StAXOMBuilder(xmlFile);
37: } catch (XMLStreamException e) {
38: log.error(e);
39: throw new ServerException(e);
40: } catch (FileNotFoundException e) {
41: log.error(e);
42: throw new ServerException(e);
43: }
44: }
45:
46: public String getUniqueValue(String xPath) {
47: SimpleNamespaceContext nsCtx = new SimpleNamespaceContext();
48: nsCtx.addNamespace("ns", serverNamespace);
49: try {
50: XPath xp = new AXIOMXPath(xPath);
51: xp.setNamespaceContext(nsCtx);
52: OMElement elem = builder.getDocumentElement();
53: if (elem != null) {
54: List nodeList = xp.selectNodes(elem);
55: Object obj;
56: if (!nodeList.isEmpty()
57: && ((obj = nodeList.get(0)) != null)) {
58: return ((OMElement) obj).getText();
59: }
60: }
61: } catch (JaxenException e) {
62: throw new RuntimeException("XPath expression " + xPath
63: + " failed", e);
64: }
65: return null;
66: }
67:
68: public OMElement[] getElements(String xPath) {
69: SimpleNamespaceContext nsCtx = new SimpleNamespaceContext();
70: nsCtx.addNamespace("ns", serverNamespace);
71: try {
72: XPath xp = new AXIOMXPath(xPath);
73: xp.setNamespaceContext(nsCtx);
74: OMElement elem = builder.getDocumentElement();
75: if (elem != null) {
76: List nodeList = xp.selectNodes(elem);
77: return (OMElement[]) nodeList
78: .toArray(new OMElement[nodeList.size()]);
79: }
80: } catch (JaxenException e) {
81: throw new RuntimeException("XPath expression " + xPath
82: + " failed", e);
83: }
84: return new OMElement[0];
85: }
86: }
|