f2090737007ab155b73fe9239f8fd510ad12e7e9
[policy/apex-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2020 Nordix Foundation.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.apex.core.infrastructure.xml;
23
24 import java.io.InputStream;
25 import javax.xml.XMLConstants;
26 import javax.xml.namespace.QName;
27 import javax.xml.parsers.DocumentBuilderFactory;
28 import javax.xml.xpath.XPath;
29 import javax.xml.xpath.XPathExpression;
30 import javax.xml.xpath.XPathExpressionException;
31 import javax.xml.xpath.XPathFactory;
32 import org.slf4j.ext.XLogger;
33 import org.slf4j.ext.XLoggerFactory;
34 import org.w3c.dom.Document;
35
36 /**
37  * A generic class for applying the XPATH queries on XML files.
38  *
39  * @author Sajeevan Achuthan (sajeevan.achuthan@ericsson.com)
40  */
41 public class XPathReader {
42
43     // Logger for this class
44     private static final XLogger LOGGER = XLoggerFactory.getXLogger(XPathReader.class);
45
46     private String xmlFileName = null;
47     private InputStream xmlStream = null;
48     private Document xmlDocument;
49     private XPath xpath;
50
51     /**
52      * Construct Reader for the file passed in.
53      *
54      * @param xmlFileName the xml file name
55      */
56     public XPathReader(final String xmlFileName) {
57         this.xmlFileName = xmlFileName;
58         init();
59     }
60
61     /**
62      * Construct Reader for the stream passed in.
63      *
64      * @param xmlStream a stream of XML
65      */
66     public XPathReader(final InputStream xmlStream) {
67         this.xmlStream = xmlStream;
68         init();
69     }
70
71     /**
72      * Initialise the x-path reader.
73      */
74     private void init() {
75         try {
76             LOGGER.info("Initializing XPath reader");
77             DocumentBuilderFactory df = DocumentBuilderFactory.newInstance();
78             df.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
79             df.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
80             df.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
81             // Check if this is operating on a file
82             if (xmlFileName != null) {
83                 xmlDocument = df.newDocumentBuilder().parse(xmlFileName);
84             } else if (xmlStream != null) {
85                 // Check if this is operating on a stream
86                 xmlDocument = df.newDocumentBuilder().parse(xmlStream);
87             } else {
88                 // We have an error
89                 LOGGER.error("XPath reader not initialized with either a file or a stream");
90                 return;
91             }
92
93             xpath = XPathFactory.newInstance().newXPath();
94             LOGGER.info("Initialized XPath reader");
95         } catch (final Exception ex) {
96             LOGGER.error("Error parsing XML file/stream from XPath reading, reason :\n" + ex.getMessage(), ex);
97         }
98     }
99
100     /**
101      * Read items from the file using xpath.
102      *
103      * @param expression x-path expression
104      * @param returnType XML node Set
105      * @return last node collected
106      */
107     public Object read(final String expression, final QName returnType) {
108         try {
109             final XPathExpression xPathExpression = xpath.compile(expression);
110             return xPathExpression.evaluate(xmlDocument, returnType);
111         } catch (final XPathExpressionException ex) {
112             LOGGER.error("Failed to read XML file for XPath processing, reason:\n" + ex.getMessage(), ex);
113             return null;
114         }
115     }
116 }