View Javadoc

1   /*
2    * Copyright 2007-2008 the original author or authors.
3    * 
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * 
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    * 
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.gwe.p2elv2.functions;
18  
19  import java.io.ByteArrayInputStream;
20  import java.io.InputStream;
21  import java.io.StringWriter;
22  import java.util.ArrayList;
23  import java.util.HashMap;
24  import java.util.List;
25  
26  import javax.xml.transform.OutputKeys;
27  import javax.xml.transform.Transformer;
28  import javax.xml.transform.TransformerException;
29  import javax.xml.transform.TransformerFactory;
30  import javax.xml.transform.TransformerFactoryConfigurationError;
31  import javax.xml.transform.dom.DOMSource;
32  import javax.xml.transform.stream.StreamResult;
33  import javax.xml.xpath.XPath;
34  import javax.xml.xpath.XPathConstants;
35  import javax.xml.xpath.XPathFactory;
36  
37  import org.apache.commons.logging.Log;
38  import org.apache.commons.logging.LogFactory;
39  import org.gwe.p2elv2.PFunction;
40  import org.gwe.p2elv2.PStatementContext;
41  import org.gwe.p2elv2.PVarValue;
42  import org.gwe.p2elv2.PVarValueSpace;
43  import org.w3c.dom.NamedNodeMap;
44  import org.w3c.dom.Node;
45  import org.w3c.dom.NodeList;
46  import org.xml.sax.InputSource;
47  
48  
49  /**
50   * @author Marco Ruiz
51   * @since Aug 11, 2008
52   */
53  public class PFXPath extends PFunction {
54  
55  	private static Log log = LogFactory.getLog(PFXPath.class);
56  
57  	public PFXPath() { super("xpath"); }
58  
59      public PVarValueSpace calculateValues(List<String> params, PStatementContext ctx) {
60          PVarValueSpace result = new PVarValueSpace();
61          String source = params.get(0);
62          String expression = params.get(1);
63  		
64  		XPath xpath = XPathFactory.newInstance().newXPath();
65  		try {
66  			InputSource inputSource = new InputSource(readSource(source, ctx));
67  	        NodeList queryResult = (NodeList) xpath.evaluate(expression, inputSource, XPathConstants.NODESET);
68  	        int length = queryResult.getLength();
69  			for (int idx = 0; idx < length; idx++) {
70  		        Node item = queryResult.item(idx);
71  				String value = (item.getNodeType() == Node.ATTRIBUTE_NODE || expression.endsWith("text()")) ? 
72  						item.getTextContent() : createXMLString(item);
73  				value = value.replaceAll("^\\s*", "").replaceAll("\\s*$", "");
74  				log.info("XPath value " + idx + " formatted = [" + value + "]");
75  				result.add(new PVarValue(value));
76              }
77  			if (result.size() == 0) result.add(new PVarValue(""));
78          } catch (Exception e) {
79          	e.printStackTrace();
80          	log.warn("Error while parsing source '" + source + "' using xpath expression '" + expression + "'", e);
81          }
82  		
83      	return result;
84      }
85      
86      private InputStream readSource(String source, PStatementContext ctx) {
87      	try {
88  	        return ctx.getKeys().createFileLink(source).createHandle().getInputStream();
89          } catch (Exception e) {
90          	return new ByteArrayInputStream(source.getBytes());
91          }
92      }
93      
94      private String createXMLString(Node source) throws TransformerFactoryConfigurationError, TransformerException {
95      	Transformer transformer = TransformerFactory.newInstance().newTransformer();
96      	transformer.setOutputProperty(OutputKeys.INDENT, "yes");
97  
98      	StreamResult result = new StreamResult(new StringWriter());
99      	transformer.transform(new DOMSource(source), result);
100 
101     	return result.getWriter().toString();
102     }
103 
104 	private HashMap<String, String> readAttributes(Node ele) {
105 		HashMap<String, String> result = new HashMap<String, String>();
106 	    NamedNodeMap attrs = ele.getAttributes();
107 	    for (int idx = 0; idx < attrs.getLength(); idx++) {
108 	    	Node attr = attrs.item(idx);
109 	    	result.put(attr.getNodeName(), attr.getNodeValue());
110 	    }
111 	    return result;
112     }
113     
114     public static void main(String[] args) {
115 
116     	List<String> params = new ArrayList<String>();
117 //    	params.add("<catalog><entries><entry URI=\"uri2\">content2</entry><entry URI=\"uri3\">content3</entry><entry URI=\"uri4\">content4</entry></entries></catalog>");
118     	
119     	String xml = "<ResultSet title=\"Scans\"><results><columns><column>ID</column><column>Name</column><column>Size</column><column serverRoot=\"\">URI</column></columns>" + 
120     	"<rows>" + 
121     	"<row><cell>1394/OAS1_0101_MR1_mpr-3_anon.hdr</cell><cell>OAS1_0101_MR1_mpr-3_anon.hdr</cell><cell>348</cell><cell>/REST/projects/CENTRAL_OASIS_CS/subjects/OAS1_0101/experiments/OAS1_0101_MR1/scans/mpr-3/resources/1394/files/OAS1_0101_MR1_mpr-3_anon.hdr</cell></row>" + 
122     	"<row><cell>1394/OAS1_0101_MR1_mpr-3_anon.img</cell><cell>OAS1_0101_MR1_mpr-3_anon.img</cell><cell>16777216</cell><cell>/REST/projects/CENTRAL_OASIS_CS/subjects/OAS1_0101/experiments/OAS1_0101_MR1/scans/mpr-3/resources/1394/files/OAS1_0101_MR1_mpr-3_anon.img</cell></row>" + 
123     	"<row><cell>1394/OAS1_0101_MR1_mpr-3_anon_sag_66.gif</cell><cell>OAS1_0101_MR1_mpr-3_anon_sag_66.gif</cell><cell>35836</cell><cell>/REST/projects/CENTRAL_OASIS_CS/subjects/OAS1_0101/experiments/OAS1_0101_MR1/scans/mpr-3/resources/1394/files/OAS1_0101_MR1_mpr-3_anon_sag_66.gif</cell></row>" + 
124     	"</rows></results></ResultSet>";
125   
126     	params.add(xml);
127 //    	params.add("//rows/row/cell[4]/text()");
128     	params.add("//rows/row/cell[(position()=4)and((substring-after(.,'.')='hdr')or(substring-after(.,'.')='nrrd'))]/text()"); // [ends-with(., '.hdr')]");
129 //    	params.add("//rows/row/cell[position()=1]"); // [ends-with(., '.hdr')]");
130 //    	params.add("//cell[starts-with(., '.hdr')]");
131     	
132     	
133     	PFXPath function = new PFXPath();
134 		PVarValueSpace result = function.calculateValues(params, null);
135 		System.out.println(result);
136     }
137     
138     public static void main2(String[] args) {
139     	System.out.println("\n\r\nALFA\n\r\n".replaceAll("^\\s*", "").replaceAll("\\s*$", ""));
140     	
141     	List<String> params = new ArrayList<String>();
142     	params.add("<catalog><entries><entry URI=\"uri2\">content2</entry><entry URI=\"uri3\">content3</entry><entry URI=\"uri4\">content4</entry></entries></catalog>");
143     	params.add("//rows/row/cell[4]/text()");
144     	
145     	PFXPath function = new PFXPath();
146 		PVarValueSpace result = function.calculateValues(params, null);
147 		System.out.println(result);
148 		
149 		for (PVarValue varValue : result) {
150 			params.clear();
151 			params.add(varValue.toString());
152 			params.add("/entry/@URI");
153 			
154 			PVarValueSpace entryRes = function.calculateValues(params, null);
155 			System.out.println(entryRes);
156         }
157     }
158     
159 }