Home » xmlbeans-2.5.0-src » org.apache.xmlbeans.samples » enumeration » [javadoc | source]

    1   /*   Copyright 2004 The Apache Software Foundation
    2    *
    3    *   Licensed under the Apache License, Version 2.0 (the "License");
    4    *   you may not use this file except in compliance with the License.
    5    *   You may obtain a copy of the License at
    6    *
    7    *       http://www.apache.org/licenses/LICENSE-2.0
    8    *
    9    *   Unless required by applicable law or agreed to in writing, software
   10    *   distributed under the License is distributed on an "AS IS" BASIS,
   11    *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   12    *   See the License for the specific language governing permissions and
   13    *  limitations under the License.
   14    */
   15   
   16   package org.apache.xmlbeans.samples.enumeration;
   17   
   18   import org.apache.xmlbeans.XmlError;
   19   import org.apache.xmlbeans.XmlException;
   20   import org.apache.xmlbeans.XmlObject;
   21   import org.apache.xmlbeans.XmlOptions;
   22   import org.apache.xmlbeans.samples.enumeration.schemaenum.easypo.LineItem;
   23   import org.apache.xmlbeans.samples.enumeration.schemaenum.easypo.PurchaseOrderDocument;
   24   import org.apache.xmlbeans.samples.enumeration.schemaenum.pricesummary.ItemType;
   25   import org.apache.xmlbeans.samples.enumeration.schemaenum.pricesummary.PriceSummaryDocument;
   26   import org.apache.xmlbeans.samples.enumeration.schemaenum.pricesummary.PriceType;
   27   
   28   import java.io.File;
   29   import java.io.IOException;
   30   import java.util.ArrayList;
   31   
   32   /**
   33    * This sample illustrates how you can access XML values that are
   34    * defined in schema as enumerations. When a schema containing
   35    * enumerations is compiled, the generated Java types represent the
   36    * schema enumerations with Java enumerations. You can access these through
   37    * their constants and corresponding int values.
   38    * <p/>
   39    * The schemas used by this sample are defined in PriceSummary.xsd and
   40    * EasyPO.xsd.
   41    */
   42   public class SchemaEnum
   43   {
   44       /**
   45        * Receives an PO XML instance and uses its data to create an XML
   46        * document based another schema, and which summarizes the items
   47        * in the PO by price.
   48        *
   49        * @param args An array containing one argument: the path to an XML instance
   50        *             conforming to the schema in EasyPO.xsd.
   51        */
   52       public static void main(String[] args)
   53       {
   54           // Create an instance of this class to work with.
   55           SchemaEnum thisSample = new SchemaEnum();
   56   
   57           // Create an instance of a type based on the received XML's schema
   58           // and use it to print what the sample received.
   59           PurchaseOrderDocument poDoc = thisSample.parseXml(args[0]);
   60           System.out.println("Received XML: \n\n" + poDoc.toString());
   61   
   62           // Print the summarized items in XML based on a different schema.
   63           PriceSummaryDocument summaryDoc = thisSample.summarizeItems(poDoc);
   64           System.out.println("Summarized items: \n\n" + summaryDoc.toString());
   65   
   66           // Print a simple non-XML list of items by threshold.
   67           String sortedItems = thisSample.sortByThreshold(summaryDoc);
   68           System.out.println("Sorted items: \n" + sortedItems);
   69   
   70           // Validate the result.
   71           System.out.println("New XML is valid: " +
   72                   thisSample.validateXml(summaryDoc));
   73       }
   74   
   75       /**
   76        * <p>This method uses values in the incoming XML to construct
   77        * a new XML document of a different schema. PriceSummary.xsd, the schema
   78        * for the new document, defines XML enumerations for a price
   79        * threshold attribute. Items whose price is between $10 and $20 receive
   80        * a threshold value of "Between10And20Dollars"; items above 20 get a threshold
   81        * value of "Above20Dollars".</p>
   82        * <p/>
   83        * <p>This method loops through the purchase order items, creating a summary
   84        * document that specifies their threshold value.</p>
   85        * <p/>
   86        * <p>You can verify this method's work by comparing the resulting XML with
   87        * the XML in PriceSummary.xml. You can also use this method's return value
   88        * to test the sortByThreshold method.</p>
   89        */
   90       public PriceSummaryDocument summarizeItems(PurchaseOrderDocument poDoc)
   91       {
   92           PurchaseOrderDocument.PurchaseOrder po = poDoc.getPurchaseOrder();
   93   
   94           // Create a new instance of the PriceSummary schema. This is the document
   95           // the code creates, extracting values from the purchase order.
   96           PriceSummaryDocument summaryDoc = PriceSummaryDocument.Factory.newInstance();
   97           PriceSummaryDocument.PriceSummary summary = summaryDoc.addNewPriceSummary();
   98   
   99           // Create <price> elements to hold <item> elements according to their
  100           // price threshold.
  101           PriceType priceZero = summary.addNewPrice();
  102           PriceType priceTen = summary.addNewPrice();
  103           PriceType priceTwenty = summary.addNewPrice();
  104   
  105           // Set the threshold attribute value for the two new elements.
  106           priceZero.setThreshold(PriceType.Threshold.BELOW_10_DOLLARS);
  107           priceTen.setThreshold(PriceType.Threshold.BETWEEN_10_AND_20_DOLLARS);
  108           priceTwenty.setThreshold(PriceType.Threshold.ABOVE_20_DOLLARS);
  109   
  110           // Loop through the purchase order <line-item> elements. If their
  111           // <price> child element is between 10.00 and 20.00, add the <line-item>
  112           // to the <price> element whose threshold is 10.00. For those over 20.00,
  113           // add them to the <price> element whose threshold is 20.00.
  114   
  115           // There don't happen to be any under 10.00, but handle this case anyway.
  116           LineItem[] items = po.getLineItemArray();
  117           for (int i = 0; i < items.length; i++)
  118           {
  119               LineItem item = items[i];
  120   
  121               if (item.getPrice() < 10.00)
  122               {
  123   
  124                   ItemType newItem = priceZero.addNewItem();
  125                   newItem.setTitle(item.getDescription());
  126                   newItem.xsetQuantity(item.xgetQuantity());
  127                   newItem.setAmount(item.getPrice());
  128   
  129               } else if (item.getPrice() >= 10.00 && item.getPrice() < 20.00)
  130               {
  131   
  132                   ItemType newItem = priceTen.addNewItem();
  133                   newItem.setTitle(item.getDescription());
  134                   newItem.xsetQuantity(item.xgetQuantity());
  135                   newItem.setAmount(item.getPrice());
  136   
  137               } else if (item.getPrice() >= 20.00)
  138               {
  139   
  140                   ItemType newItem = priceTwenty.addNewItem();
  141                   newItem.setTitle(item.getDescription());
  142                   newItem.xsetQuantity(item.xgetQuantity());
  143                   newItem.setAmount(item.getPrice());
  144               }
  145           }
  146           return summaryDoc;
  147       }
  148   
  149       /**
  150        * <p>This method loops through a price summary XML document to
  151        * create a string that lists the items grouped by threshold.
  152        * Unlike the summarizeItems method, which creates a new XML
  153        * document that contains an attribute whose value is enumerated,
  154        * this method retrieves values from an enumeration.</p>
  155        * <p/>
  156        * <p>This method illustrates how you can use the int value corresponding
  157        * to enumerations to specify them in Java switch statements.</p>
  158        */
  159       public String sortByThreshold(PriceSummaryDocument summaryDoc)
  160       {
  161           // Extract the summary element from the incoming XML, then use it
  162           // to extract an array of the price elements.
  163           PriceSummaryDocument.PriceSummary summary = summaryDoc.getPriceSummary();
  164           PriceType[] priceElements = summary.getPriceArray();
  165   
  166           StringBuffer responseBuffer = new StringBuffer();
  167   
  168           // Create string buffers to hold the sorted results of the values
  169           // retrieved.
  170           StringBuffer zeroBuffer = new StringBuffer("\nItems under 10 dollars: \n");
  171           StringBuffer tenBuffer = new StringBuffer("\nItems between 10 and 20 dollars: \n");
  172           StringBuffer twentyBuffer = new StringBuffer("\nItems more than 20 dollars: \n");
  173   
  174           // Loop through the price elements, extracting the array of <item> child
  175           // elements in each.
  176           for (int i = 0; i < priceElements.length; i++)
  177           {
  178               ItemType[] itemElements = priceElements[i].getItemArray();
  179   
  180               // Loop through the <item> elements, discovering which threshold
  181               // the item belongs to, then using the element's <title> value
  182               // in in a sorted list.
  183               for (int j = 0; j < itemElements.length; j++)
  184               {
  185                   ItemType item = itemElements[j];
  186   
  187                   // For each <item> element, find out the int value of its <price>
  188                   // parent element's threshold attribute value. Append the item's
  189                   // title to the appropriate string buffer.
  190                   switch (priceElements[i].getThreshold().intValue())
  191                   {
  192   
  193                       case PriceType.Threshold.INT_BELOW_10_DOLLARS:
  194                           zeroBuffer.append(" " + item.getTitle() + "\n");
  195                           break;
  196   
  197                       case PriceType.Threshold.INT_BETWEEN_10_AND_20_DOLLARS:
  198                           tenBuffer.append(" " + item.getTitle() + "\n");
  199                           break;
  200   
  201                       case PriceType.Threshold.INT_ABOVE_20_DOLLARS:
  202                           twentyBuffer.append(" " + item.getTitle() + "\n");
  203                           break;
  204   
  205                       default:
  206                           System.out.println("Yo! Something unexpected happened!");
  207                           break;
  208                   }
  209               }
  210           }
  211           responseBuffer.append(tenBuffer);
  212           responseBuffer.append(twentyBuffer);
  213           return responseBuffer.toString();
  214       }
  215   
  216       /**
  217        * <p>Validates the XML, printing error messages when the XML is invalid. Note
  218        * that this method will properly validate any instance of a compiled schema
  219        * type because all of these types extend XmlObject.</p>
  220        * <p/>
  221        * <p>Note that in actual practice, you'll probably want to use an assertion
  222        * when validating if you want to ensure that your code doesn't pass along
  223        * invalid XML. This sample prints the generated XML whether or not it's
  224        * valid so that you can see the result in both cases.</p>
  225        *
  226        * @param xml The XML to validate.
  227        * @return <code>true</code> if the XML is valid; otherwise, <code>false</code>
  228        */
  229       public boolean validateXml(XmlObject xml)
  230       {
  231           boolean isXmlValid = false;
  232   
  233           // A collection instance to hold validation error messages.
  234           ArrayList validationMessages = new ArrayList();
  235   
  236           // Validate the XML, collecting messages.
  237           isXmlValid = xml.validate(new XmlOptions().setErrorListener(validationMessages));
  238   
  239           if (!isXmlValid)
  240           {
  241               System.out.println("Invalid XML: ");
  242               for (int i = 0; i < validationMessages.size(); i++)
  243               {
  244                   XmlError error = (XmlError) validationMessages.get(i);
  245                   System.out.println(error.getMessage());
  246                   System.out.println(error.getObjectLocation());
  247               }
  248           }
  249           return isXmlValid;
  250       }
  251   
  252       /**
  253        * <p>Creates a File from the XML path provided in main arguments, then
  254        * parses the file's contents into a type generated from schema.</p>
  255        * <p/>
  256        * <p>Note that this work might have been done in main. Isolating it here
  257        * makes the code separately available from outside this class.</p>
  258        *
  259        * @param xmlFilePath A path to XML based on the schema in inventory.xsd.
  260        * @return An instance of a generated schema type that contains the parsed
  261        *         XML.
  262        */
  263       public PurchaseOrderDocument parseXml(String xmlFilePath)
  264       {
  265           File poFile = new File(xmlFilePath);
  266           PurchaseOrderDocument poDoc = null;
  267           try
  268           {
  269               poDoc = PurchaseOrderDocument.Factory.parse(poFile);
  270           } catch (XmlException e)
  271           {
  272               e.printStackTrace();
  273           } catch (IOException e)
  274           {
  275               e.printStackTrace();
  276           }
  277           return poDoc;
  278       }
  279   }

Home » xmlbeans-2.5.0-src » org.apache.xmlbeans.samples » enumeration » [javadoc | source]