IDOMCount.cpp
上传用户:huihehuasu
上传日期:2007-01-10
资源大小:6948k
文件大小:13k
源码类别:

xml/soap/webservice

开发平台:

C/C++

  1. /*
  2.  * The Apache Software License, Version 1.1
  3.  *
  4.  * Copyright (c) 2001 The Apache Software Foundation.  All rights
  5.  * reserved.
  6.  *
  7.  * Redistribution and use in source and binary forms, with or without
  8.  * modification, are permitted provided that the following conditions
  9.  * are met:
  10.  *
  11.  * 1. Redistributions of source code must retain the above copyright
  12.  *    notice, this list of conditions and the following disclaimer.
  13.  *
  14.  * 2. Redistributions in binary form must reproduce the above copyright
  15.  *    notice, this list of conditions and the following disclaimer in
  16.  *    the documentation and/or other materials provided with the
  17.  *    distribution.
  18.  *
  19.  * 3. The end-user documentation included with the redistribution,
  20.  *    if any, must include the following acknowledgment:
  21.  *       "This product includes software developed by the
  22.  *        Apache Software Foundation (http://www.apache.org/)."
  23.  *    Alternately, this acknowledgment may appear in the software itself,
  24.  *    if and wherever such third-party acknowledgments normally appear.
  25.  *
  26.  * 4. The names "Xerces" and "Apache Software Foundation" must
  27.  *    not be used to endorse or promote products derived from this
  28.  *    software without prior written permission. For written
  29.  *    permission, please contact apache@apache.org.
  30.  *
  31.  * 5. Products derived from this software may not be called "Apache",
  32.  *    nor may "Apache" appear in their name, without prior written
  33.  *    permission of the Apache Software Foundation.
  34.  *
  35.  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
  36.  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  37.  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  38.  * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
  39.  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  40.  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  41.  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  42.  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  43.  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  44.  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  45.  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  46.  * SUCH DAMAGE.
  47.  * ====================================================================
  48.  *
  49.  * This software consists of voluntary contributions made by many
  50.  * individuals on behalf of the Apache Software Foundation, and was
  51.  * originally based on software copyright (c) 2001, International
  52.  * Business Machines, Inc., http://www.ibm.com .  For more information
  53.  * on the Apache Software Foundation, please see
  54.  * <http://www.apache.org/>.
  55.  */
  56. /*
  57.  * $Id: IDOMCount.cpp,v 1.14 2001/11/28 20:07:43 tng Exp $
  58.  */
  59. // ---------------------------------------------------------------------------
  60. //  Includes
  61. // ---------------------------------------------------------------------------
  62. #include <util/PlatformUtils.hpp>
  63. #include <sax/SAXException.hpp>
  64. #include <sax/SAXParseException.hpp>
  65. #include <parsers/IDOMParser.hpp>
  66. #include <idom/IDOM_DOMException.hpp>
  67. #include <idom/IDOM_Document.hpp>
  68. #include <idom/IDOM_NodeList.hpp>
  69. #include "IDOMCount.hpp"
  70. #include <string.h>
  71. #include <stdlib.h>
  72. #include <fstream.h>
  73. // ---------------------------------------------------------------------------
  74. //  This is a simple program which invokes the DOMParser to build a DOM
  75. //  tree for the specified input file. It then walks the tree and counts
  76. //  the number of elements. The element count is then printed.
  77. // ---------------------------------------------------------------------------
  78. static void usage()
  79. {
  80.     cout << "nUsage:n"
  81.             "    IDOMCount [options] <XML file | List file>nn"
  82.             "This program invokes the IDOM parser, builds the DOM tree,n"
  83.             "and then prints the number of elements found in each XML file.nn"
  84.             "Options:n"
  85.             "    -l          Indicate the input file is a List File that has a list of xml files.n"
  86.             "                Default to off (Input file is an XML file).n"
  87.             "    -v=xxx      Validation scheme [always | never | auto*].n"
  88.             "    -n          Enable namespace processing. Defaults to off.n"
  89.             "    -s          Enable schema processing. Defaults to off.n"
  90.             "    -f          Enable full schema constraint checking. Defaults to off.n"
  91.       "    -?          Show this help.nn"
  92.             "  * = Default if not provided explicitly.n"
  93.          << endl;
  94. }
  95. // ---------------------------------------------------------------------------
  96. //
  97. //  Recursively Count up the total number of child Elements under the specified Node.
  98. //
  99. // ---------------------------------------------------------------------------
  100. static int countChildElements(IDOM_Node *n)
  101. {
  102.     IDOM_Node *child;
  103.     int count = 0;
  104.     if (n) {
  105.         if (n->getNodeType() == IDOM_Node::ELEMENT_NODE)
  106.         {
  107.             count++;
  108.             for (child = n->getFirstChild(); child != 0; child=child->getNextSibling())
  109.             {
  110.                 if (child->getNodeType() == IDOM_Node::ELEMENT_NODE)
  111.                 {
  112.                     count += countChildElements(child);
  113.                 }
  114.             }
  115.         }
  116.     }
  117.     return count;
  118. }
  119. // ---------------------------------------------------------------------------
  120. //
  121. //   main
  122. //
  123. // ---------------------------------------------------------------------------
  124. int main(int argC, char* argV[])
  125. {
  126.     // Initialize the XML4C system
  127.     try
  128.     {
  129.         XMLPlatformUtils::Initialize();
  130.     }
  131.     catch (const XMLException& toCatch)
  132.     {
  133.          cerr << "Error during initialization! :n"
  134.               << StrX(toCatch.getMessage()) << endl;
  135.          return 1;
  136.     }
  137.     // Check command line and extract arguments.
  138.     if (argC < 2)
  139.     {
  140.         usage();
  141.         XMLPlatformUtils::Terminate();
  142.         return 1;
  143.     }
  144.     const char*               xmlFile = 0;
  145.     IDOMParser::ValSchemes    valScheme = IDOMParser::Val_Auto;
  146.     bool                      doNamespaces       = false;
  147.     bool                      doSchema           = false;
  148.     bool                      schemaFullChecking = false;
  149.     bool                      doList = false;
  150.     bool                      errorOccurred = false;
  151.     int argInd;
  152.     for (argInd = 1; argInd < argC; argInd++)
  153.     {
  154.         // Break out on first parm not starting with a dash
  155.         if (argV[argInd][0] != '-')
  156.             break;
  157.         // Watch for special case help request
  158.         if (!strcmp(argV[argInd], "-?"))
  159.         {
  160.             usage();
  161.             XMLPlatformUtils::Terminate();
  162.             return 2;
  163.         }
  164.          else if (!strncmp(argV[argInd], "-v=", 3)
  165.               ||  !strncmp(argV[argInd], "-V=", 3))
  166.         {
  167.             const char* const parm = &argV[argInd][3];
  168.             if (!strcmp(parm, "never"))
  169.                 valScheme = IDOMParser::Val_Never;
  170.             else if (!strcmp(parm, "auto"))
  171.                 valScheme = IDOMParser::Val_Auto;
  172.             else if (!strcmp(parm, "always"))
  173.                 valScheme = IDOMParser::Val_Always;
  174.             else
  175.             {
  176.                 cerr << "Unknown -v= value: " << parm << endl;
  177.                 XMLPlatformUtils::Terminate();
  178.                 return 2;
  179.             }
  180.         }
  181.          else if (!strcmp(argV[argInd], "-n")
  182.               ||  !strcmp(argV[argInd], "-N"))
  183.         {
  184.             doNamespaces = true;
  185.         }
  186.          else if (!strcmp(argV[argInd], "-s")
  187.               ||  !strcmp(argV[argInd], "-S"))
  188.         {
  189.             doSchema = true;
  190.         }
  191.          else if (!strcmp(argV[argInd], "-f")
  192.               ||  !strcmp(argV[argInd], "-F"))
  193.         {
  194.             schemaFullChecking = true;
  195.         }
  196.          else if (!strcmp(argV[argInd], "-l")
  197.               ||  !strcmp(argV[argInd], "-L"))
  198.         {
  199.             doList = true;
  200.         }
  201.          else
  202.         {
  203.             cerr << "Unknown option '" << argV[argInd]
  204.                  << "', ignoring itn" << endl;
  205.         }
  206.     }
  207.     //
  208.     //  There should be only one and only one parameter left, and that
  209.     //  should be the file name.
  210.     //
  211.     if (argInd != argC - 1)
  212.     {
  213.         usage();
  214.         XMLPlatformUtils::Terminate();
  215.         return 1;
  216.     }
  217.     // Instantiate the DOM parser.
  218.     IDOMParser* parser = new IDOMParser;
  219.     parser->setValidationScheme(valScheme);
  220.     parser->setDoNamespaces(doNamespaces);
  221.     parser->setDoSchema(doSchema);
  222.     parser->setValidationSchemaFullChecking(schemaFullChecking);
  223.     // And create our error handler and install it
  224.     DOMCountErrorHandler errorHandler;
  225.     parser->setErrorHandler(&errorHandler);
  226.     //
  227.     //  Get the starting time and kick off the parse of the indicated
  228.     //  file. Catch any exceptions that might propogate out of it.
  229.     //
  230.     unsigned long duration;
  231.     bool more = true;
  232.     ifstream fin;
  233.     // the input is a list file
  234.     if (doList)
  235.         fin.open(argV[argInd]);
  236.     while (more)
  237.     {
  238.         char fURI[1000];
  239.         //initialize the array to zeros
  240.         memset(fURI,0,sizeof(fURI));
  241.         if (doList) {
  242.             if (! fin.eof() ) {
  243.                 fin.getline (fURI, sizeof(fURI));
  244.                 if (!*fURI)
  245.                     continue;
  246.                 else {
  247.                     xmlFile = fURI;
  248.                     cerr << "==Parsing== " << xmlFile << endl;
  249.                 }
  250.             }
  251.             else
  252.                 break;
  253.         }
  254.         else {
  255.             xmlFile = argV[argInd];
  256.             more = false;
  257.         }
  258.         //reset error count first
  259.         errorHandler.resetErrors();
  260.         try
  261.         {
  262.             const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis();
  263.             parser->resetDocumentPool();
  264.             parser->parse(xmlFile);
  265.             const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis();
  266.             duration = endMillis - startMillis;
  267.         }
  268.         catch (const XMLException& toCatch)
  269.         {
  270.             cerr << "nError during parsing: '" << xmlFile << "'n"
  271.                  << "Exception message is:  n"
  272.                  << StrX(toCatch.getMessage()) << "n" << endl;
  273.             errorOccurred = true;
  274.             continue;
  275.         }
  276.         catch (const IDOM_DOMException& toCatch)
  277.         {
  278.             cerr << "nDOM Error during parsing: '" << xmlFile << "'n"
  279.                  << "DOMException code is:  n"
  280.                  << toCatch.code << "n" << endl;
  281.             errorOccurred = true;
  282.             continue;
  283.         }
  284.         catch (...)
  285.         {
  286.             cerr << "nUnexpected exception during parsing: '" << xmlFile << "'n";
  287.             errorOccurred = true;
  288.             continue;
  289.         }
  290.         //
  291.         //  Extract the DOM tree, get the list of all the elements and report the
  292.         //  length as the count of elements.
  293.         //
  294.         if (errorHandler.getSawErrors())
  295.         {
  296.             cout << "nErrors occured, no output availablen" << endl;
  297.             errorOccurred = true;
  298.         }
  299.          else
  300.         {
  301.             IDOM_Document *doc = parser->getDocument();
  302.             unsigned int elementCount = 0;
  303.             if (doc) {
  304.                 elementCount = countChildElements((IDOM_Node*)doc->getDocumentElement());
  305.                 // test getElementsByTagName and getLength
  306.                 XMLCh xa[] = {chAsterisk, chNull};
  307.                 if (elementCount != doc->getElementsByTagName(xa)->getLength()) {
  308.                     cout << "nErrors occured, element count is wrongn" << endl;
  309.                     errorOccurred = true;
  310.                 }
  311.             }
  312.             // Print out the stats that we collected and time taken.
  313.             cout << xmlFile << ": " << duration << " ms ("
  314.                  << elementCount << " elems)." << endl;
  315.         }
  316.     }
  317.     //
  318.     //  Delete the parser itself.  Must be done prior to calling Terminate, below.
  319.     //
  320.     delete parser;
  321.     // And call the termination method
  322.     XMLPlatformUtils::Terminate();
  323.     if (doList)
  324.         fin.close();
  325.     if (errorOccurred)
  326.         return 4;
  327.     else
  328.         return 0;
  329. }
  330. DOMCountErrorHandler::DOMCountErrorHandler() :
  331.     fSawErrors(false)
  332. {
  333. }
  334. DOMCountErrorHandler::~DOMCountErrorHandler()
  335. {
  336. }
  337. // ---------------------------------------------------------------------------
  338. //  DOMCountHandlers: Overrides of the SAX ErrorHandler interface
  339. // ---------------------------------------------------------------------------
  340. void DOMCountErrorHandler::error(const SAXParseException& e)
  341. {
  342.     fSawErrors = true;
  343.     cerr << "nError at file " << StrX(e.getSystemId())
  344.          << ", line " << e.getLineNumber()
  345.          << ", char " << e.getColumnNumber()
  346.          << "n  Message: " << StrX(e.getMessage()) << endl;
  347. }
  348. void DOMCountErrorHandler::fatalError(const SAXParseException& e)
  349. {
  350.     fSawErrors = true;
  351.     cerr << "nFatal Error at file " << StrX(e.getSystemId())
  352.          << ", line " << e.getLineNumber()
  353.          << ", char " << e.getColumnNumber()
  354.          << "n  Message: " << StrX(e.getMessage()) << endl;
  355. }
  356. void DOMCountErrorHandler::warning(const SAXParseException& e)
  357. {
  358.     cerr << "nWarning at file " << StrX(e.getSystemId())
  359.          << ", line " << e.getLineNumber()
  360.          << ", char " << e.getColumnNumber()
  361.          << "n  Message: " << StrX(e.getMessage()) << endl;
  362. }
  363. void DOMCountErrorHandler::resetErrors()
  364. {
  365.     fSawErrors = false;
  366. }