001: /*
002: * Copyright 2005-2007 The Kuali Foundation.
003: *
004: *
005: * Licensed under the Educational Community License, Version 1.0 (the "License");
006: * you may not use this file except in compliance with the License.
007: * You may obtain a copy of the License at
008: *
009: * http://www.opensource.org/licenses/ecl1.php
010: *
011: * Unless required by applicable law or agreed to in writing, software
012: * distributed under the License is distributed on an "AS IS" BASIS,
013: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014: * See the License for the specific language governing permissions and
015: * limitations under the License.
016: */
017: package edu.iu.uis.eden.xml;
018:
019: import java.io.StringReader;
020:
021: import javax.xml.xpath.XPath;
022: import javax.xml.xpath.XPathConstants;
023: import javax.xml.xpath.XPathExpressionException;
024: import javax.xml.xpath.XPathFactory;
025:
026: import junit.framework.TestCase;
027:
028: import org.apache.log4j.Logger;
029: import org.junit.Ignore;
030: import org.junit.Test;
031: import org.w3c.dom.Node;
032: import org.w3c.dom.NodeList;
033: import org.xml.sax.InputSource;
034:
035: public class XPathTest extends TestCase {
036: private static final Logger LOG = Logger.getLogger(XPathTest.class);
037:
038: private static final String STYLESHEET_RESOURCE = "edu/iu/uis/eden/edoclite/DefaultStyle.xsl";
039: private static final String INITIAL_EDOC_XML = "initial_edldoc.xml";
040: private static final String SAMPLE_EDOC_XML = "sample_edldoc.xml";
041:
042: @Ignore("The tests in this test case need to be fixed???")
043: @Test
044: public void testTheTestsInThisTestCaseNeedToBeFixed() {
045:
046: }
047:
048: private static final String TEST_DOC = "<root name=\"root\">\n"
049: + " <child name=\"child1\">\n"
050: + " <child_1 name=\"child1_1\">\n"
051: + " <closedSimple/>\n"
052: + " <emptySimple></emptySimple>\n"
053: + " <textSimple>some text 1</textSimple>\n"
054: + " </child_1>\n" + " </child>\n"
055: + " <child name=\"child2\">\n"
056: + " <child_2 name=\"child2_1\">\n"
057: + " <closedSimple/>\n"
058: + " <emptySimple></emptySimple>\n"
059: + " <textSimple>some text 2</textSimple>\n"
060: + " </child_2>\n" + " </child>\n" + "</root>";
061:
062: private static final String TEST_ATTRIBUTE_DOC = "<root name=\"root\">\n"
063: + " <field name=\"one\" type=\"ALL\"/>\n"
064: + " <field name=\"two\" type=\"REPORT\"/>\n"
065: + " <field name=\"three\"/>\n" + "</root>";
066:
067: private static final XPath XPATH = XPathFactory.newInstance()
068: .newXPath();
069:
070: private static final InputSource getTestInputSource() {
071: return new InputSource(new StringReader(TEST_DOC));
072: }
073:
074: @Test
075: public void testAttributeAbsence() throws XPathExpressionException {
076: NodeList nodes = (NodeList) XPATH.evaluate(
077: "/root/child[not(@nonExistentAttribute)]",
078: getTestInputSource(), XPathConstants.NODESET);
079: assertEquals(2, nodes.getLength());
080: assertEquals("child1", nodes.item(0).getAttributes()
081: .getNamedItem("name").getNodeValue());
082: assertEquals("child2", nodes.item(1).getAttributes()
083: .getNamedItem("name").getNodeValue());
084:
085: // now try with an equivalent compound expression
086: nodes = (NodeList) XPATH
087: .evaluate(
088: "/root/*[local-name(.) = 'child' or (@nonExistentAttribute)]",
089: getTestInputSource(), XPathConstants.NODESET);
090: assertEquals(2, nodes.getLength());
091: assertEquals("child1", nodes.item(0).getAttributes()
092: .getNamedItem("name").getNodeValue());
093: assertEquals("child2", nodes.item(1).getAttributes()
094: .getNamedItem("name").getNodeValue());
095:
096: nodes = (NodeList) XPATH.evaluate("/root/child[not(@name)]",
097: getTestInputSource(), XPathConstants.NODE);
098: assertNull(nodes);
099:
100: // now use a more specific test document
101: nodes = (NodeList) XPATH.evaluate(
102: "/root/field[@type='ALL' or not(@type)]",
103: new InputSource(new StringReader(TEST_ATTRIBUTE_DOC)),
104: XPathConstants.NODESET);
105: assertEquals(2, nodes.getLength());
106: assertEquals("one", nodes.item(0).getAttributes().getNamedItem(
107: "name").getNodeValue());
108: assertEquals("three", nodes.item(1).getAttributes()
109: .getNamedItem("name").getNodeValue());
110: }
111:
112: @Test
113: public void testSelectJustChilds() throws XPathExpressionException {
114: NodeList nodes = (NodeList) XPATH.evaluate("/root/child",
115: getTestInputSource(), XPathConstants.NODESET);
116: assertEquals(2, nodes.getLength());
117: assertEquals("child1", nodes.item(0).getAttributes()
118: .getNamedItem("name").getNodeValue());
119: assertEquals("child2", nodes.item(1).getAttributes()
120: .getNamedItem("name").getNodeValue());
121: }
122:
123: @Test
124: public void testSelectAbsoluteChild()
125: throws XPathExpressionException {
126: Node node = (Node) XPATH.evaluate("/root/child",
127: getTestInputSource(), XPathConstants.NODE);
128: assertEquals("child1", node.getAttributes()
129: .getNamedItem("name").getNodeValue());
130: }
131:
132: @Test
133: public void testSelectAnyChild() throws XPathExpressionException {
134: Node anyNode = (Node) XPATH.evaluate("//child",
135: getTestInputSource(), XPathConstants.NODE);
136: assertEquals("child1", anyNode.getAttributes().getNamedItem(
137: "name").getNodeValue());
138: }
139:
140: @Test
141: public void testNonexistent() throws XPathExpressionException {
142: final String expr = "//child/child_1/nonExistent";
143: Node nonexistent = (Node) XPATH.evaluate(expr,
144: getTestInputSource(), XPathConstants.NODE);
145: assertNull(nonexistent);
146: String valueOfNonexistentElement = (String) XPATH.evaluate(
147: expr, getTestInputSource(), XPathConstants.STRING);
148: // a non-existent element does not have a 'null' text value but a zero-length string
149: assertEquals("", valueOfNonexistentElement);
150: }
151:
152: @Test
153: public void testClosedSimple() throws XPathExpressionException {
154: final String expr = "//child/child_1/closedSimple";
155: Node closedSimple = (Node) XPATH.evaluate(expr,
156: getTestInputSource(), XPathConstants.NODE);
157: assertNotNull(closedSimple);
158: assertNull(closedSimple.getFirstChild());
159: String valueOfClosedTag = (String) XPATH.evaluate(expr,
160: getTestInputSource(), XPathConstants.STRING);
161: // a closed element does not have a 'null' text value but a zero-length string
162: assertEquals("", valueOfClosedTag);
163: }
164:
165: @Test
166: public void testEmptySimple() throws XPathExpressionException {
167: final String expr = "//child/child_1/emptySimple";
168: Node emptySimple = (Node) XPATH.evaluate(expr,
169: getTestInputSource(), XPathConstants.NODE);
170: assertNotNull(emptySimple);
171: assertNull(emptySimple.getFirstChild());
172: String valueOfEmptyTag = (String) XPATH.evaluate(expr,
173: getTestInputSource(), XPathConstants.STRING);
174: // a closed element does not have a 'null' text value but a zero-length string
175: assertEquals("", valueOfEmptyTag);
176: }
177:
178: @Test
179: public void testText() throws XPathExpressionException {
180: final String expr = "//child/child_2[@name='child2_1']/textSimple";
181: final String expected = "some text 2";
182: Node textSimple = (Node) XPATH.evaluate(expr,
183: getTestInputSource(), XPathConstants.NODE);
184: assertNotNull(textSimple);
185: assertNotNull(textSimple.getFirstChild());
186: String valueOfTextTag = (String) XPATH.evaluate(expr,
187: getTestInputSource(), XPathConstants.STRING);
188: // a closed element does not have a 'null' text value but a zero-length string
189: assertEquals(expected, valueOfTextTag);
190: }
191:
192: /*public void testTransformInitialDoc() throws Exception {
193: TransformerFactory factory = TransformerFactory.newInstance();
194: Source styleSheet = new StreamSource(this.getClass().getClassLoader().getResourceAsStream(STYLESHEET_RESOURCE));
195: Templates templates = templates = factory.newTemplates(styleSheet);
196: Transformer transformer = templates.newTransformer();
197: transformer.setOutputProperty("indent", "yes");
198: transformer.setParameter("readOnly", "false");
199: //transformer.setParameter("docType", docType);
200: //transformer.setParameter("schema", schema);
201:
202: Source input = new StreamSource(this.getClass().getResourceAsStream(INITIAL_EDOC_XML));
203: transformer.transform(input, new StreamResult(System.out));
204: }
205:
206: public void testFieldHasMatchingUserValues() throws Exception {
207: LOG.info("testFieldHasMatchingUserValues");
208: DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
209:
210: XPath xpath = XPathFactory.newInstance().newXPath();
211: Document doc = db.parse(this.getClass().getResourceAsStream(SAMPLE_EDOC_XML));
212: // enumerate all fields
213: final String fieldDefs = "/edlContent/edl/field/display/values";
214: NodeList nodes = (NodeList) xpath.evaluate(fieldDefs, doc, XPathConstants.NODESET);
215:
216: for (int i = 0; i < nodes.getLength(); i++) {
217: Node node = nodes.item(i);
218: String name = (String) xpath.evaluate("../../@name", node, XPathConstants.STRING);
219: LOG.debug("Name: " + name);
220: LOG.debug("Value: " + node.getFirstChild().getNodeValue());
221: final String expr = "/edlContent/data/version[@current='true']/fieldEntry[@name=current()/../../@name and value=current()]";
222: NodeList matchingUserValues = (NodeList) xpath.evaluate(expr, node, XPathConstants.NODESET);
223: LOG.debug(matchingUserValues + "");
224: LOG.debug(matchingUserValues.getLength() + "");
225: if ("gender".equals(name)) {
226: assertTrue("Matching values > 0", matchingUserValues.getLength() > 0);
227: }
228: for (int j = 0; j < matchingUserValues.getLength(); j++) {
229: LOG.debug(matchingUserValues.item(j).getFirstChild().getNodeValue());
230: }
231: }
232: }
233:
234: public void testUpdateEDLDocument() throws Exception {
235: final Map params = new HashMap();
236: params.put("givenname", new String[] { "Frank" });
237: params.put("surname", new String[] { "Miller" });
238: params.put("email", new String[] { "frank@bogus.blah.asdlajsd.co.uk" });
239: params.put("gender", new String[] { "male" });
240: params.put("color", new String[] { "blue" });
241: params.put("food", new String[] { "sandwiches", "soup" });
242:
243: DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
244:
245: XPath xpath = XPathFactory.newInstance().newXPath();
246: String versionsExpression = "/edlContent/data/version";
247:
248: // try an initial empty doc
249: EDLDocument edlDoc = new EDLDocument(db.parse(this.getClass().getResourceAsStream(INITIAL_EDOC_XML)));
250: int numVersionsBefore = ((NodeList) xpath.evaluate(versionsExpression, edlDoc.getDocument(), XPathConstants.NODESET)).getLength();
251: LOG.debug("Initial before:");
252: LOG.debug(edlDoc);
253: edlDoc.update(null, params);
254: LOG.debug("Initial after:");
255: LOG.debug(edlDoc);
256: int numVersionsAfter = ((NodeList) xpath.evaluate(versionsExpression, edlDoc.getDocument(), XPathConstants.NODESET)).getLength();
257: assertEquals(numVersionsBefore + 1, numVersionsAfter);
258:
259: numVersionsBefore = ((NodeList) xpath.evaluate(versionsExpression, edlDoc.getDocument(), XPathConstants.NODESET)).getLength();
260: LOG.debug("Initial 2nd time before:");
261: LOG.debug(edlDoc);
262: edlDoc.update(null, params);
263: LOG.debug("Initial 2nd time after:");
264: LOG.debug(edlDoc);
265: numVersionsAfter = ((NodeList) xpath.evaluate(versionsExpression, edlDoc.getDocument(), XPathConstants.NODESET)).getLength();
266: assertEquals(numVersionsBefore + 1, numVersionsAfter);
267:
268: // try a sample doc
269: edlDoc = new EDLDocument(db.parse(this.getClass().getResourceAsStream(SAMPLE_EDOC_XML)));
270: numVersionsBefore = ((NodeList) xpath.evaluate(versionsExpression, edlDoc.getDocument(), XPathConstants.NODESET)).getLength();
271: LOG.debug("Sample before:");
272: LOG.debug(edlDoc);
273: edlDoc.update(null, params);
274: LOG.debug("Sample after:");
275: LOG.debug(edlDoc);
276: numVersionsAfter = ((NodeList) xpath.evaluate(versionsExpression, edlDoc.getDocument(), XPathConstants.NODESET)).getLength();
277: assertEquals(numVersionsBefore + 1, numVersionsAfter);
278: }
279:
280: public void testXPathStuff() throws Exception {
281: InputStream edlDocContent = new TestUtilities().loadResource(this.getClass(), "edldoccontent.xml");
282: org.w3c.dom.Document w3cDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(edlDocContent);
283: // Document document = new DOMBuilder().build(w3cDocument);
284: // DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
285: // Document routeDocument = builder.parse(new File("ParallelRouting.xml"));
286:
287: XPath xpath = XPathFactory.newInstance().newXPath();
288: xpath.getXPathFunctionResolver();
289: // String expression = "//version[@current='true']/fieldEntry[@name='name']/value";
290: // xpath.getXPathFunctionResolver().resolveFunction();s
291: String expression = "//version[@current='true']/fieldEntry[@name=concat('n', 'ame')]/value";
292: String expression2 = "local-name(//field[@name='name']/@name)";
293: String expression3 = "//version[@current='true']/fieldEntry[@name=local-name(//field[@name='name']/@name)]/value";
294: Node node = (Node) xpath.evaluate(expression3, w3cDocument, XPathConstants.NODE);
295: xpath.evaluate(expression3, w3cDocument);
296: node.getNodeValue();
297: node.getNodeType();
298: ((Text)node.getFirstChild()).getNodeValue();
299: int i =1;
300: }*/
301: }
|