a9c57f385f5191856d870b829492d75314061ebb
[policy/apex-pdp.git] / core / core-infrastructure / src / main / java / org / onap / policy / apex / core / infrastructure / xml / XPathReader.java
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
26 import javax.xml.XMLConstants;
27 import javax.xml.namespace.QName;
28 import javax.xml.parsers.DocumentBuilderFactory;
29 import javax.xml.xpath.XPath;
30 import javax.xml.xpath.XPathExpression;
31 import javax.xml.xpath.XPathExpressionException;
32 import javax.xml.xpath.XPathFactory;
33
34 import org.slf4j.ext.XLogger;
35 import org.slf4j.ext.XLoggerFactory;
36 import org.w3c.dom.Document;
37
38 /**
39  * A generic class for applying the XPATH queries on XML files.
40  *
41  * @author Sajeevan Achuthan (sajeevan.achuthan@ericsson.com)
42  */
43 public class XPathReader {
44
45     // Logger for this class
46     private static final XLogger LOGGER = XLoggerFactory.getXLogger(XPathReader.class);
47
48     private String xmlFileName = null;
49     private InputStream xmlStream = null;
50     private Document xmlDocument;
51     private XPath xpath;
52
53     /**
54      * Construct Reader for the file passed in.
55      *
56      * @param xmlFileName the xml file name
57      */
58     public XPathReader(final String xmlFileName) {
59         this.xmlFileName = xmlFileName;
60         init();
61     }
62
63     /**
64      * Construct Reader for the stream passed in.
65      *
66      * @param xmlStream a stream of XML
67      */
68     public XPathReader(final InputStream xmlStream) {
69         this.xmlStream = xmlStream;
70         init();
71     }
72
73     /**
74      * Initialise the x-path reader.
75      */
76     private void init() {
77         try {
78             LOGGER.info("Initializing XPath reader");
79             DocumentBuilderFactory df = DocumentBuilderFactory.newInstance();
80             df.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
81
82             // Check if this is operating on a file
83             if (xmlFileName != null) {
84                 xmlDocument = df.newDocumentBuilder().parse(xmlFileName);
85             } else if (xmlStream != null) {
86                 // Check if this is operating on a stream
87                 xmlDocument = df.newDocumentBuilder().parse(xmlStream);
88             } else {
89                 // We have an error
90                 LOGGER.error("XPath reader not initialized with either a file or a stream");
91                 return;
92             }
93
94             xpath = XPathFactory.newInstance().newXPath();
95             LOGGER.info("Initialized XPath reader");
96         } catch (final Exception ex) {
97             LOGGER.error("Error parsing XML file/stream from XPath reading, reason :\n" + ex.getMessage(), ex);
98         }
99     }
100
101     /**
102      * Read items from the file using xpath.
103      *
104      * @param expression x-path expression
105      * @param returnType XML node Set
106      * @return last node collected
107      */
108     public Object read(final String expression, final QName returnType) {
109         try {
110             final XPathExpression xPathExpression = xpath.compile(expression);
111             return xPathExpression.evaluate(xmlDocument, returnType);
112         } catch (final XPathExpressionException ex) {
113             LOGGER.error("Failed to read XML file for XPath processing, reason:\n" + ex.getMessage(), ex);
114             return null;
115         }
116     }
117 }