First Commit from Source Code Reply

This commit is contained in:
vincenzofariello
2024-05-09 17:40:24 +02:00
parent 11e3b57c5b
commit 107a016cb9
35225 changed files with 1111346 additions and 1 deletions

View File

@@ -0,0 +1,48 @@
Sample: XQueryXPath
Author: Steven Traut (straut@bea.com)
Last Updated: May 14, 2008
Versions:
xmlbeans-v1 1.0.3
xmlbeans-v2 2.4.0
-----------------------------------------------------------------------------
This sample illustrates how you can use the XMLBeans API to execute
XPath and XQuery expressions. The sample illustrates these features:
- Using the XmlObject.selectPath and XmlCursor.selectPath methods
to execute XPath expressions. The selectPath method's results (if
any) are always chunks of the instance queried against. In other
words, changes to query results change the original instance.
However, you work with results differently depending on whether
selectPath was called from an XmlObject or XmlCursor instance. See
the SelectPath class for more information.
- Using the XmlObject.execQuery and XmlCursor.execQuery methods
to execute XQuery expressions. Results of these queries are copied
into new XML, meaning that changes to results do not change the
original instance. Here again, you work with results differently
depending how which method you used to query. See the ExecQuery
class for more information.
A note about dependencies. Very simple XPath expressions -- e.g.,
expressions without predicates or function calls -- require only
the xbean.jar on your class path. More complex XPath expressions
and XQuery expressions require an XPath/XQuery engine, such as
Saxon. XMLBeans 2.4.0 supports the use of Saxon 9. Two Saxon jars,
saxon9.jar and saxon9-dom.jar, as well as xbean_xpath.jar, are
required on the classpath for code in this sample to run.
These jars are created in the build/lib directory if you build
XMLBeans from Apache source.
To try out this sample:
1. Set XMLBEANS_HOME in your environment
2. Ant must be on your PATH
3. xbean_xpath.jar, saxon9.jar, and saxon9-dom.jar must be on your
classpath.
These files are created in the build/lib directory when you
build XMLBeans from source.
4. To compile the schemas and sample source, run "ant build"
5. To execute the sample, run "ant run"

View File

@@ -0,0 +1,120 @@
<!--
Copyright 2004 The Apache Software Foundation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<project name="XQueryXPath" default="build">
<property environment="env"/>
<path id="XQueryXPath.path">
<path refid="xmlbeans.path"/>
<fileset dir="build/lib" includes="*.jar"/>
<pathelement path="build/classes"/>
<pathelement path="${env.CLASSPATH}"/>
</path>
<target name="init">
<property name="xmlbeans.home" value="${env.XMLBEANS_HOME}"/>
<echo message="xmlbeans.home: ${xmlbeans.home}"/>
<!-- check for xbean.jar from binary distribution -->
<available
property="xmlbeans.lib"
value="${xmlbeans.home}/lib"
file="${xmlbeans.home}/lib/xbean.jar" />
<!-- check for xbean.jar compiled from source -->
<available
property="xmlbeans.lib"
value="${xmlbeans.home}/build/lib"
file="${xmlbeans.home}/build/lib/xbean.jar" />
<fail message="Set XMLBEANS_HOME in your environment."
unless="xmlbeans.lib"/>
<echo message="xmlbeans.lib: ${xmlbeans.lib}"/>
<path id="xmlbeans.path">
<fileset dir="${xmlbeans.lib}" includes="*.jar"/>
</path>
<taskdef name="xmlbean"
classname="org.apache.xmlbeans.impl.tool.XMLBean"
classpathref="xmlbeans.path"/>
</target>
<!-- ========================== clean ==== -->
<target name="clean">
<delete dir="build"/>
</target>
<!-- ========================== build ==== -->
<target name="build" depends="init,schemas.jar,XQueryXPath.classes">
</target>
<target name="schemas.check">
<uptodate property="schemas.notRequired"
targetfile="build/lib/schemas.jar">
<srcfiles dir="schemas" includes="**/*.xsd"/>
</uptodate>
</target>
<target name="schemas.jar" depends="init,schemas.check"
unless="schemas.notRequired">
<mkdir dir="build/lib"/>
<xmlbean schema="schemas"
destfile="build/lib/schemas.jar"
classpathref="xmlbeans.path"
debug="on"
/>
</target>
<target name="XQueryXPath.classes" depends="init">
<mkdir dir="build/classes"/>
<javac srcdir="src"
destdir="build/classes"
classpathref="XQueryXPath.path"
debug="on"
source="1.4"
/>
</target>
<!-- ========================== run ==== -->
<target name="run" depends="init,build">
<echo message="============================== running XQueryXPath"/>
<java
classname="org.apache.xmlbeans.samples.xquery.XQueryXPath"
classpathref="XQueryXPath.path"
fork="true">
<arg line="xml/employees.xml"/>
</java>
</target>
<!-- ========================== test ==== -->
<target name="test" depends="init,build">
<echo message="============================== testing XQueryXPath"/>
<java
classname="org.apache.xmlbeans.samples.xquery.XQueryXPathTest"
classpathref="XQueryXPath.path"
fork="true">
<arg line="xml/employees.xml"/>
</java>
</target>
</project>

View File

@@ -0,0 +1,52 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright 2004 The Apache Software Foundation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"
targetNamespace="http://xmlbeans.apache.org/samples/xquery/employees"
xmlns="http://xmlbeans.apache.org/samples/xquery/employees">
<xs:element name="employees">
<xs:complexType>
<xs:sequence>
<xs:element name="employee" type="employeeType" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name="employeeType">
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="address" type="addressType" maxOccurs="unbounded"/>
<xs:element name="phone" type="phoneType" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="addressType">
<xs:sequence>
<xs:element name="street" type="xs:string"/>
<xs:element name="city" type="xs:NCName"/>
<xs:element name="state" type="xs:NCName"/>
<xs:element name="zip" type="xs:integer"/>
</xs:sequence>
<xs:attribute name="location" type="xs:NCName" use="required"/>
</xs:complexType>
<xs:complexType name="phoneType">
<xs:simpleContent>
<xs:extension base="xs:string">
<xs:attribute name="location" type="xs:NCName" use="required"/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:schema>

View File

@@ -0,0 +1,154 @@
/* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.xmlbeans.samples.xquery;
import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlObject;
/**
* This class demonstrates how to use the execQuery method to execute XQuery
* expressions. Compare the code here with the code in the SelectPath class.
* That class uses the selectPath method to execute XPath expressions.
* <p/>
* You can call the execQuery method from either an XmlObject or XmlCursor
* instance. Calling from XmlObject returns an XmlObject array. Calling
* from XmlCursor returns a new XmlCursor instance positioned at the root
* of a fragment containing copies of the XML queried against. Results of the
* query (if any) are sibling children of the fragment's root.
*/
public class ExecQuery
{
final static String m_namespaceDeclaration =
"declare namespace xq='http://xmlbeans.apache.org/samples/xquery/employees';";
/**
* Uses XQuery to retrieve work <phone> elements from the incoming XML, then
* changes the number in the results.
*
* This method demonstrates the following characteristics of the execQuery method:
*
* - it supports XQuery.
* - the XML it returns is a copy of the XML queried against; contrast this with
* the selectPath method, which returns a portion of the original document.
* Changes to returned XML do not impact the XML queried against.
* - execQuery called from an XmlCursor returns a cursor positioned at
* the STARTDOC token of a new XML fragment. Contrast this with the
* XmlCursor.selectPath method, which stores results as "selections" in
* the cursor used to execute the query.
*
* @param empDoc The incoming XML.
* @return <code>true</code> if the XPath expression returned results;
* otherwise, <code>false</code>.
*/
public boolean updateWorkPhone(XmlObject empDoc)
{
boolean hasResults = false;
// A cursor instance to query with.
XmlCursor empCursor = empDoc.newCursor();
// The expression: Get the <employee> elements with <state> elements whose
// value is "WA".
String queryExpression =
"for $e in $this/xq:employees/xq:employee " +
"let $s := $e/xq:address/xq:state " +
"where $s = 'WA' " +
"return $e//xq:phone[@location='work']";
// Execute the query. Results, if any, will be available at
// the position of the resultCursor in a new XML document.
XmlCursor resultCursor =
empCursor.execQuery(m_namespaceDeclaration + queryExpression);
System.out.println("The query results, <phone> element copies made " +
"from the received document: \n");
System.out.println(resultCursor.getObject().toString() + "\n");
// If there are results, the results will be children of the fragment root
// where the new cursor is positioned. This statement tests for children
// and moves the cursor if to the first if it exists.
if (resultCursor.toFirstChild())
{
hasResults = true;
// Use the cursor to loop through the results, printing each sibling
// <employee> element returned by the query.
int i = 0;
do
{
// Change the phone numbers.
XmlCursor editCursor = resultCursor.newCursor();
editCursor.toLastAttribute();
editCursor.toNextToken();
editCursor.removeXml();
editCursor.insertChars("(206)555-1234");
} while (resultCursor.toNextSibling());
resultCursor.toStartDoc();
System.out.println("The query results after changes: \n");
System.out.println(resultCursor.getObject().toString() + "\n");
System.out.println("The received document -- note that it is unchanged. " +
"Changes were made to the copy created by the execQuery method. \n");
System.out.println(empDoc + "\n");
}
return hasResults;
}
/**
* Uses XQuery to retrieve work <zip> elements from the incoming XML, adding the
* elements as children to a <zip-list> element.
*
* This method demonstrates the following characteristics of the execQuery method:
*
* - it supports XQuery.
* - execQuery called from an XmlObject returns an array of XmlObject instances.
* These are bound to copies of the received XML.
*
* @param empDoc The incoming XML.
* @return <code>true</code> if the XPath expression returned results;
* otherwise, <code>false</code>.
*/
public boolean collectZips(XmlObject empDoc)
{
// The query is designed to return results, so return
// true if it does.
boolean hasResults = false;
// The expression: Get the <zip> elements and return them as children
// of a new <zip-list> element.
String queryExpression =
"let $e := $this/xq:employees " +
"return " +
"<zip-list> " +
"{for $z in $e/xq:employee/xq:address/xq:zip " +
"return $z} " +
"</zip-list>";
// Execute the query. Results will be copies of the XML queried against,
// stored as members of an XmlObject array.
XmlObject[] results =
empDoc.execQuery(m_namespaceDeclaration + queryExpression);
// Print the results.
if (results.length > 0)
{
hasResults = true;
System.out.println("The query results: \n");
System.out.println(results[0].toString() + "\n");
}
return hasResults;
}
}

View File

@@ -0,0 +1,172 @@
/* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.xmlbeans.samples.xquery;
import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.samples.xquery.employees.PhoneType;
/**
* This class demonstrates how to use the selectPath method to execute XPath
* expressions. Compare the code here with the code in the ExecQuery class.
* That class uses the execQuery method to execute XQuery expressions.
* <p/>
* You can call the selectPath method from either an XmlObject or XmlCursor
* instance. Calling from XmlObject returns an XmlObject array. Calling
* from XmlCursor returns void, and you use methods of the cursor to
* navigate among returned "selections".
*/
public class SelectPath
{
// Declare a namespace corresponding to the namespace declared in the XML
// instance. The string here will be used as part of the XPath expression to
// ensure that the query finds namespace-qualified elements in the XML.
final static String m_namespaceDeclaration =
"declare namespace xq='http://xmlbeans.apache.org/samples/xquery/employees';";
/**
* Prints the XML bound to <em>empDoc</em>, uses XPath to
* retrieve elements containing work phone numbers, changes the numbers
* to another number, then prints the XML again to display the changes.
*
* This method demonstrates the following characteristics of the selectPath method:
*
* - it supports expressions that include predicates
* - the XML it returns is the XML queried against -- not a copy, as with results
* returned via execQuery methods and XQuery. Changes to this XML update
* the XML queried against.
* - selectPath called from an XMLBean type (instead of a cursor) returns an
* array of results (if any). These results can be cast to a matching type
* generated from schema.
*
* @param empDoc The incoming XML.
* @return <code>true</code> if the XPath expression returned results;
* otherwise, <code>false</code>.
*/
public boolean updateWorkPhone(XmlObject empDoc)
{
boolean hasResults = false;
// Print the XML received.
System.out.println("XML as received by updateWorkPhone method: \n\n"
+ empDoc.toString());
// Create a variable with the query expression.
String pathExpression =
"$this/xq:employees/xq:employee/xq:phone[@location='work']";
// Execute the query.
XmlObject[] results = empDoc.selectPath(m_namespaceDeclaration
+ pathExpression);
if (results.length > 0)
{
hasResults = true;
// <phone> elements returned from the expression will conform to the
// schema, so bind them to the appropriate XMLBeans type generated
// from the schema.
PhoneType[] phones = (PhoneType[]) results;
// Change all the work phone numbers to the same number.
for (int i = 0; i < phones.length; i++)
{
phones[i].setStringValue("(206)555-1234");
}
// Print the XML with updates.
System.out.println("\nXML as updated by updateWorkPhone method (each work \n" +
"phone number has been changed to the same number): \n\n"
+ empDoc.toString() + "\n");
}
return hasResults;
}
/**
* Uses the XPath text() function to get values from <name>
* elements in received XML, then collects those values as the value of a
* <names> element created here.
* <p/>
* Demonstrates the following characteristics of the selectPath method:
* <p/>
* - It supports expressions that include XPath function calls.
* - selectPath called from an XmlCursor instance (instead of an XMLBeans
* type) places results (if any) into the cursor's selection set.
*
* @param empDoc The incoming XML.
* @return <code>true</code> if the XPath expression returned results;
* otherwise, <code>false</code>.
*/
public boolean collectNames(XmlObject empDoc)
{
boolean hasResults = false;
// Create a cursor with which to execute query expressions. The cursor
// is inserted at the very beginning of the incoming XML, then moved to
// the first element's START token.
XmlCursor pathCursor = empDoc.newCursor();
pathCursor.toFirstChild();
// Execute the path expression, qualifying it with the namespace
// declaration.
pathCursor.selectPath(m_namespaceDeclaration
+ "$this//xq:employee/xq:name/text()");
// If there are results, then go ahead and do stuff.
if (pathCursor.getSelectionCount() > 0)
{
hasResults = true;
// Create a new <names> element into which names from the XML
// will be copied. Note that this element is in the default
// namespace; it's not part of the schema.
XmlObject namesElement = null;
try
{
namesElement = XmlObject.Factory.parse("<names/>");
} catch (XmlException e)
{
e.printStackTrace();
}
// Add a cursor the new element and put it between its START and END
// tokens, where new values can be inserted.
XmlCursor namesCursor = namesElement.newCursor();
namesCursor.toFirstContentToken();
namesCursor.toEndToken();
// Loop through the selections, appending the incoming <name> element's
// value to the new <name> element's value. (Of course, this could have
// been done with a StringBuffer, but that wouldn't show the cursor in
// use.)
while (pathCursor.toNextSelection())
{
namesCursor.insertChars(pathCursor.getTextValue());
if (pathCursor.hasNextSelection())
{
namesCursor.insertChars(", ");
}
}
// Dispose of the cursors now that they're not needed.
pathCursor.dispose();
namesCursor.dispose();
// Print the new element.
System.out.println("\nNames collected by collectNames method: \n\n"
+ namesElement + "\n");
}
return hasResults;
}
}

View File

@@ -0,0 +1,117 @@
/* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.xmlbeans.samples.xquery;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlObject;
import java.io.File;
import java.io.IOException;
/**
* A sample to XMLBeans API features for executing XPath and XQuery
* expressions. The sample illustrates these features:
*
* - Using the XmlObject.selectPath and XmlCursor.selectPath methods
* to execute XPath expressions. The selectPath method's results (if
* any) are always chunks of the instance queried against. In other
* words, changes to query results change the original instance.
* However, you work with results differently depending on whether
* selectPath was called from an XmlObject or XmlCursor instance. See
* the SelectPath class for more information.
* - Using the XmlObject.execQuery and XmlCursor.execQuery methods
* to execute XQuery expressions. Results of these queries are copied
* into new XML, meaning that changes to results do not change the
* original instance. Here again, you work with results differently
* depending how which method you used to query. See the ExecQuery
* class for more information.
*/
public class XQueryXPath
{
/**
* Receives an employees list XML instance, passing the instance to
* methods that execute queries against it.
*
* @param args An array in which the first item is a
* path to the XML instance file.
*/
public static void main(String[] args)
throws org.apache.xmlbeans.XmlException, java.io.IOException
{
XQueryXPath sample = new XQueryXPath();
sample.executeQueries(args);
}
/**
* Returns <code>true</code> if all of the sample methods returned true
* (i.e., their query expressions returned results).
*
* @param args An array in which the first item is a
* path to the XML instance file.
* @return <code>true</code> if all of the sample methods returned true
* (i.e., their query expressions returned results); otherwise,
* <code>false</code>.
*/
public boolean executeQueries(String[] args)
{
XmlObject xml = this.parseXml(args[0]);
// Execute the XQuery samples.
ExecQuery xquerySample = new ExecQuery();
System.out.println("Running ExecQuery.selectEmpsByStateCursor\n");
boolean xqWorkPhoneSuccessful = xquerySample.updateWorkPhone(xml);
System.out.println("Running ExecQuery.selectZipsNewDocCursor\n");
boolean xqCollectZips = xquerySample.collectZips(xml);
// Execute the XPath samples.
SelectPath xpathSample = new SelectPath();
System.out.println("Running SelectPath.updateWorkPhone \n");
boolean xpWorkPhoneSuccessful = xpathSample.updateWorkPhone(xml);
System.out.println("Running SelectPath.collectNames \n");
boolean xpCollectNames = xpathSample.collectNames(xml);
return (xqWorkPhoneSuccessful && xqCollectZips
&& xpWorkPhoneSuccessful && xpCollectNames) ? true : false;
}
/**
* <p>Creates a File from the XML path provided in main arguments, then
* parses the file's contents into a type generated from schema.</p>
* @param xmlFilePath A path to XML based on the schema in inventory.xsd.
* @return An instance of a generated schema type that contains the parsed
* XML.
*/
public XmlObject parseXml(String xmlFilePath)
{
File xmlFile = new File(xmlFilePath);
XmlObject xml = null;
try
{
xml = XmlObject.Factory.parse(xmlFile);
} catch (XmlException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
return xml;
}
}

View File

@@ -0,0 +1,32 @@
/* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.xmlbeans.samples.xquery;
/**
* A class with which to test the XQueryXPath sample.
*/
public class XQueryXPathTest
{
/**
* Tests the XQueryXPath sample.
*/
public static void main(String[] args)
throws org.apache.xmlbeans.XmlException, java.io.IOException
{
XQueryXPath sample = new XQueryXPath();
boolean queriesSuccessful = sample.executeQueries(args);
assert queriesSuccessful;
}
}

View File

@@ -0,0 +1,71 @@
<!--
Copyright 2004 The Apache Software Foundation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<employees xmlns="http://xmlbeans.apache.org/samples/xquery/employees">
<employee>
<name>Fred Jones</name>
<address location="home">
<street>900 Aurora Ave.</street>
<city>Seattle</city>
<state>WA</state>
<zip>98115</zip>
</address>
<address location="work">
<street>2011 152nd Avenue NE</street>
<city>Redmond</city>
<state>WA</state>
<zip>98052</zip>
</address>
<phone location="work">(425)555-5665</phone>
<phone location="home">(206)555-5555</phone>
<phone location="mobile">(206)555-4321</phone>
</employee>
<employee>
<name>Sally Smith</name>
<address location="home">
<street>1430 Oak Place</street>
<city>Salem</city>
<state>OR</state>
<zip>97125</zip>
</address>
<address location="work">
<street>765 Main St.</street>
<city>Keizer</city>
<state>OR</state>
<zip>97303</zip>
</address>
<phone location="work">(503)555-3856</phone>
<phone location="home">(503)555-6951</phone>
<phone location="mobile">(503)555-5152</phone>
</employee>
<employee>
<name>Gladys Kravitz</name>
<address location="home">
<street>1313 Mockingbird Lane</street>
<city>Seattle</city>
<state>WA</state>
<zip>98115</zip>
</address>
<address location="work">
<street>2011 152nd Avenue NE</street>
<city>Redmond</city>
<state>WA</state>
<zip>98052</zip>
</address>
<phone location="work">(425)555-6897</phone>
<phone location="home">(206)555-6594</phone>
<phone location="mobile">(206)555-7894</phone>
</employee>
</employees>