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,34 @@
Sample: MixedContent
Author: Steven Traut (straut@bea.com)
Last Updated: Sept. 6, 2004
Versions:
xmlbeans-1.0.3
xmlbeans-v2
-----------------------------------------------------------------------------
This sample illustrates how you can work with mixed content XML by combining
strong types generated from schema with an XmlCursor instance. The XmlCursor
interface is provided with XMLBeans for just this kind of use. With strong types
you can only get or set the full value of an element; by using a cursor you can
"dive into" the contents of an element, manipulating child elements that are
embedded in the content and surrounded by other text.
The sample's XML is a pseudo-inventory of nonsensical items, each with a unique
ID and a description. Where the name of one item is mentioned in the description
of another, the sample code wraps the name with a <link> element whose id
attribute is the ID of the named item.
When you run this sample, you'll see it print potentially three blocks of
information:
- The XML it got from the inventoryitems.xml file.
- The XML it generated by associating cross-mentioned items.
- The results from validating the resulting XML, if the XML is invalid.
To try out this sample:
1. Set XMLBEANS_HOME in your environment
2. Ant must be on your PATH
3. To compile the schemas and sample source, run "ant build"
4. 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="MixedContent" default="build">
<property environment="env"/>
<path id="MixedContent.path">
<path refid="xmlbeans.path"/>
<fileset dir="build/lib" includes="*.jar"/>
<pathelement path="build/classes"/>
</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 enviornment."
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,MixedContent.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"
srcgendir="build/src"
classpathref="xmlbeans.path"
debug="on"
/>
</target>
<target name="MixedContent.classes" depends="init">
<mkdir dir="build/classes"/>
<javac srcdir="src"
destdir="build/classes"
classpathref="MixedContent.path"
debug="on"
source="1.4"
/>
</target>
<!-- ========================== run ==== -->
<target name="run" depends="init,build">
<echo message="============================== running MixedContent"/>
<java
classname="org.apache.xmlbeans.samples.cursor.MixedContent"
classpathref="MixedContent.path"
fork="true">
<arg line="xml/inventoryitems.xml"/>
</java>
</target>
<!-- ========================== test ==== -->
<target name="test" depends="init,build">
<echo message="============================== testing MixedContent"/>
<java
classname="org.apache.xmlbeans.samples.cursor.MixedContentTest"
classpathref="MixedContent.path"
fork="true">
<arg line="xml/inventoryitems.xml"/>
</java>
</target>
</project>

View File

@@ -0,0 +1,49 @@
<?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 targetNamespace="http://xmlbeans.apache.org/samples/cursor/mixedcontent"
xmlns:mc="http://xmlbeans.apache.org/samples/cursor/mixedcontent"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified">
<xs:complexType name="descriptionType" mixed="true">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="link" type="mc:linkType"/>
</xs:choice>
</xs:complexType>
<xs:element name="inventory">
<xs:complexType>
<xs:sequence>
<xs:element name="item" type="mc:itemType" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name="itemType">
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="description" type="mc:descriptionType"/>
<xs:element name="price" type="xs:double"/>
<xs:element name="quantity" type="xs:int"/>
</xs:sequence>
<xs:attribute name="id" type="xs:int" use="required"/>
</xs:complexType>
<xs:complexType name="linkType">
<xs:simpleContent>
<xs:extension base="xs:string">
<xs:attribute name="id" type="xs:int" use="required"/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:schema>

View File

@@ -0,0 +1,263 @@
/* 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
*
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* Unless required by applicable law or agreed to in writing, software
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.xmlbeans.samples.cursor;
import org.apache.xmlbeans.*;
import org.apache.xmlbeans.samples.cursor.mixedcontent.DescriptionType;
import org.apache.xmlbeans.samples.cursor.mixedcontent.InventoryDocument;
import org.apache.xmlbeans.samples.cursor.mixedcontent.ItemType;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
/**
* <p>This sample illustrates how you can use an XML cursor
* to manipulate the content of an element. Even though
* working with strongly-typed XML (in which you are accessing
* the XML through an API generated from schema) provides easy
* access for getting and setting the entire value of an
* element or attribute, it does not easily provide finer
* grained access to an element's content. This sample
* shows how you can use an XML cursor to "dive into" an
* element's content, manipulating it on a character-by-
* character level.</p>
* <p/>
* <p>The code in this sample is designed to look at the
* description of each item in an inventory list, creating
* a link wherever the description contains a reference
* to another item in the inventory list. This alters the
* &lt;description&gt; element so that it contains a mix of text and
* link elements. Such an element is said to have "mixed
* content."</p>
* <p/>
* This sample uses the schema defined in inventory.xsd.
*/
public class MixedContent
{
/**
* Receives an inventory XML instance and rewrites it so that items listed
* in the inventory point to one another via &lt;link&gt; elements.
*
* @param args An array containing one argument: the path to an XML instance
* conforming to the schema in inventory.xsd.
*/
public static void main(String[] args)
{
// Create an instance of this sample to work with.
MixedContent thisSample = new MixedContent();
// Create an schema type instance from the XML indicated by the path.
InventoryDocument inventoryDoc = thisSample.parseXml(args[0]);
// Print what was received.
System.out.println("Received XML: \n\n" + inventoryDoc.toString());
// Edit the XML, adding <link> elements to associate related items.
InventoryDocument linkedResultDoc = thisSample.linkItems(inventoryDoc);
// Print the updated XML.
System.out.println("XML with linked items: \n\n" + linkedResultDoc.toString());
// Validate the result.
System.out.println("New XML is valid: " +
thisSample.validateXml(linkedResultDoc));
}
/**
* <p>Creates "links" between items in an inventory list by inserting
* a &lt;link&gt; element for each linked item. An XmlCursor
* instance passes through each &lt;description&gt; element, looking
* for text matching the name of an item.</p>
*
* @param inventoryDoc An XML document conforming to the schema in
* inventory.xsd.
*/
public InventoryDocument linkItems(InventoryDocument inventoryDoc)
{
// Retrieve the &lt;inventory&gt; element and get an array of
// the &lt;item&gt; elements it contains.
InventoryDocument.Inventory inventory = inventoryDoc.getInventory();
ItemType[] items = inventory.getItemArray();
// Loop through the &lt;item&gt; elements, examining the
// description for each to see if another inventory item
// is mentioned.
for (int i = 0; i < items.length; i++)
{
// Get details about the current item, including
// its length. This will be used to measure text
// while exploring the description.
String itemName = items[i].getName();
String itemId = new Integer(items[i].getId()).toString();
int itemCharCount = itemName.length();
// Loop through the item descriptions, looking at each
// for the name of the current item.
for (int j = 0; j < items.length; j++)
{
DescriptionType description = items[j].getDescription();
// Insert an XmlCursor instance and set it at
// the beginning of the <&lt;description&gt; element's text,
// just after the start tag.
XmlCursor cursor = description.newCursor();
cursor.toLastAttribute();
cursor.toNextToken();
// Get a String containing the characters to the
// immediate right of the cursor, up to the next
// token (in this case, the next element after
// the description element). Get the number of
// characters to the right of the cursor; this will
// be used to mark the distance the cursor should move
// before trying another item's description. Also,
// create a charCount variable to mark the cursor's
// current position.
String cursorChars = cursor.getChars();
int descCharCount = cursorChars.length();
int charCount = 0;
// As long at the cursor hasn't reached the end of the
// description text, check to see if the text to the
// cursor's immediate right matches the item name sought.
// If it does match, remove the text and create a link
// element to replace it.
while (charCount < descCharCount)
{
// A char array to hold the characters currently being
// checked.
char[] chars = new char[itemCharCount];
// Pass the char array with the getChars method. This
// method will find the chars from the cursor's
// immediate right to the char at itemCharCount (the
// length of the item name currently sought). The
// method's second argument indicates where in the char
// array the found text should begin -- in this case, at the
// beginning.
int charsReturned = cursor.getChars(chars, 0, itemCharCount);
// If the characters in chars match the item name, then
// make a link from the text.
if (new String(chars).equals(itemName))
{
// Remove the found item name.
cursor.removeChars(itemCharCount);
// Begin a new link element whose namespace is the
// same as the rest of the inventory document. The
// beginElement method creates a new element with the
// name specified around the current cursor.
cursor.beginElement("link",
"http://xmlbeans.apache.org/samples/cursor/mixedcontent");
// Insert an id attribute and make its value the id of
// the item sought.
cursor.insertAttributeWithValue("id", itemId);
// Insert the item name as the element's value.
cursor.insertChars(itemName);
}
// Move on to the next character in the description.
cursor.toNextChar(1);
// Increment the counter tracking the cursor's position.
charCount++;
}
// Be sure to dispose of a cursor that's no longer needed.
// This allows it to be garbage collected.
cursor.dispose();
}
}
// Return the edited document.
return inventoryDoc;
}
/**
* <p>Validates the XML, printing error messages when the XML is invalid. Note
* that this method will properly validate any instance of a compiled schema
* type because all of these types extend XmlObject.</p>
*
* <p>Note that in actual practice, you'll probably want to use an assertion
* when validating if you want to ensure that your code doesn't pass along
* invalid XML. This sample prints the generated XML whether or not it's
* valid so that you can see the result in both cases.</p>
*
* @param xml The XML to validate.
* @return <code>true</code> if the XML is valid; otherwise, <code>false</code>
*/
public boolean validateXml(XmlObject xml)
{
boolean isXmlValid = false;
// A collection instance to hold validation error messages.
ArrayList validationMessages = new ArrayList();
// Validate the XML, collecting messages.
isXmlValid = xml.validate(
new XmlOptions().setErrorListener(validationMessages));
// If the XML isn't valid, print the messages.
if (!isXmlValid)
{
System.out.println("Invalid XML: ");
for (int i = 0; i < validationMessages.size(); i++)
{
XmlError error = (XmlError) validationMessages.get(i);
System.out.println(error.getMessage());
System.out.println(error.getObjectLocation());
}
}
return isXmlValid;
}
/**
* <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>
*
* <p>Note that this work might have been done in main. Isolating it here
* makes the code separately available from outside this class.</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 InventoryDocument parseXml(String xmlFilePath)
{
// Get the XML instance into a file using the path provided.
File inventoryFile = new File(xmlFilePath);
// Create an instance of a type generated from schema to hold the XML.
InventoryDocument inventoryDoc = null;
try
{
// Parse the instance into the type generated from the schema.
inventoryDoc = InventoryDocument.Factory.parse(inventoryFile);
} catch (XmlException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
return inventoryDoc;
}
}

View File

@@ -0,0 +1,50 @@
/* 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.cursor;
import org.apache.xmlbeans.samples.cursor.mixedcontent.InventoryDocument;
/**
* A class with which to test the MixedContent sample.
*/
public class MixedContentTest
{
/**
* Tests the MixedContent sample.
*
* @param args An array in which the first item is a path to an XML file
* based on the schema in inventory.xsd.
*/
public static void main(String[] args)
{
// Create an instance of this sample to work with.
MixedContent sample = new MixedContent();
// Create an schema type instance from the XML indicated by the path.
InventoryDocument inventoryDoc = sample.parseXml(args[0]);
// Validate the XML.
boolean exampleIsValid = sample.validateXml(inventoryDoc);
assert exampleIsValid;
// Edit the XML, adding <link> elements to associate related items.
InventoryDocument linkedResultDoc = sample.linkItems(inventoryDoc);
// Validate the XML.
boolean newXmlIsValid = sample.validateXml(linkedResultDoc);
assert newXmlIsValid;
}
}

View File

@@ -0,0 +1,36 @@
<!--
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.
-->
<inventory xmlns="http://xmlbeans.apache.org/samples/cursor/mixedcontent">
<item id="897946">
<name>locking flange harbinger</name>
<description>Completely myopic gyrating mill-flange.</description>
<price>21.79</price>
<quantity>4594</quantity>
</item>
<item id="745621">
<name>protaic calliphange</name>
<description>Asymmetrical flared-gill spongimass. Complements the locking flange harbinger
with perfect precision.</description>
<price>19.95</price>
<quantity>2</quantity>
</item>
<item id="784269">
<name>gyrating mill-flange</name>
<description>Polymorphic atrophical mylobium. Not compatible with any other device ever made.</description>
<price>.99</price>
<quantity>1205987</quantity>
</item>
</inventory>