View Javadoc
1   /*
2    * Kuali Coeus, a comprehensive research administration system for higher education.
3    * 
4    * Copyright 2005-2015 Kuali, Inc.
5    * 
6    * This program is free software: you can redistribute it and/or modify
7    * it under the terms of the GNU Affero General Public License as
8    * published by the Free Software Foundation, either version 3 of the
9    * License, or (at your option) any later version.
10   * 
11   * This program is distributed in the hope that it will be useful,
12   * but WITHOUT ANY WARRANTY; without even the implied warranty of
13   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   * GNU Affero General Public License for more details.
15   * 
16   * You should have received a copy of the GNU Affero General Public License
17   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18   */
19  package org.kuali.coeus.s2sgen.impl.util;
20  
21  import org.apache.xpath.XPathAPI;
22  import org.w3c.dom.Document;
23  import org.w3c.dom.Node;
24  
25  import javax.xml.parsers.DocumentBuilderFactory;
26  import javax.xml.transform.TransformerException;
27  import java.io.ByteArrayInputStream;
28  
29  /**
30   * Class processes XPath Queries.
31   * 
32   */
33  public class XPathExecutor {
34  
35  	private Document doc;
36  	
37  	public XPathExecutor( String xml ) throws Exception{
38  		
39  		init( xml );
40  	}
41  	
42  	/**
43  	 * Method evaulates the XPath expression against the xml string.
44  	 * Currently utilizing a DOM implementation.
45  	 * @param xPath
46  	 * @return first node value returned
47  	 * @throws Exception
48  	 */
49  	public String execute( String xPath ) throws Exception {
50  
51  		if ( xPath == null ){
52  			return null;
53  		}
54  		
55  		// Evaluate the xpath expression
56  		return XPathAPI.eval( getDoc(), xPath ).toString();
57  		
58  	
59  	}
60  	
61  	/**
62  	 * For a given XPath, a DOM Node that the XPath resolve to is returned.
63  	 * @param xpath A valid XPath referring to the Node that is to be returned
64  	 * @return The Node referred to by the xpath argument.
65  	 * @throws TransformerException
66  	 */
67  	public Node getNode(String xpath)
68  		throws TransformerException
69  	{
70  	    return XPathAPI.selectSingleNode(getDoc(), xpath);
71  	}
72  	
73  	private void init( String xml ) throws Exception {
74  	
75  		if ( xml == null ) {
76  			return;
77  		}
78  		
79  
80  		try(ByteArrayInputStream stream = new ByteArrayInputStream(xml.getBytes())) {
81  		    DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
82  		    dfactory.setNamespaceAware(true);
83  		    setDoc( dfactory.newDocumentBuilder().parse(stream) );
84  		}
85  	}
86  
87  	
88  	/**
89  	 * @return the Document.
90  	 */
91  	public Document getDoc() {
92  		return doc;
93  	}
94  	/**
95  	 * @param doc the Document.
96  	 */
97  	public void setDoc(Document doc) {
98  		this.doc = doc;
99  	}
100 
101 }
102