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

xml/soap/webservice

开发平台:

C/C++

  1. /*
  2.  * The Apache Software License, Version 1.1
  3.  *
  4.  * Copyright (c) 1999-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) 1999, 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.  * $Log: MemParse.cpp,v $
  58.  * Revision 1.12  2001/10/25 15:18:33  tng
  59.  * delete the parser before XMLPlatformUtils::Terminate.
  60.  *
  61.  * Revision 1.11  2001/10/19 18:56:08  tng
  62.  * Pulled the hardcoded "encoding" out of the document itself and made it a #define
  63.  * to make it easier to support other encodings.  Patch from David McCreedy.
  64.  * And other modification for consistent help display and return code across samples.
  65.  *
  66.  * Revision 1.10  2001/08/01 19:11:01  tng
  67.  * Add full schema constraint checking flag to the samples and the parser.
  68.  *
  69.  * Revision 1.9  2001/05/11 13:24:55  tng
  70.  * Copyright update.
  71.  *
  72.  * Revision 1.8  2001/05/03 15:59:40  tng
  73.  * Schema: samples update with schema
  74.  *
  75.  * Revision 1.7  2000/09/11 18:43:48  aruna1
  76.  * OS390 related updates
  77.  *
  78.  * Revision 1.6  2000/03/02 19:53:42  roddey
  79.  * This checkin includes many changes done while waiting for the
  80.  * 1.1.0 code to be finished. I can't list them all here, but a list is
  81.  * available elsewhere.
  82.  *
  83.  * Revision 1.5  2000/02/11 02:37:01  abagchi
  84.  * Removed StrX::transcode
  85.  *
  86.  * Revision 1.4  2000/02/06 07:47:19  rahulj
  87.  * Year 2K copyright swat.
  88.  *
  89.  * Revision 1.3  2000/01/12 00:27:00  roddey
  90.  * Updates to work with the new URL and input source scheme.
  91.  *
  92.  * Revision 1.2  1999/11/20 01:09:55  rahulj
  93.  * Fixed usage message.
  94.  *
  95.  * Revision 1.1.1.1  1999/11/09 01:09:49  twl
  96.  * Initial checkin
  97.  *
  98.  * Revision 1.7  1999/11/08 20:43:36  rahul
  99.  * Swat for adding in Product name and CVS comment log variable.
  100.  *
  101.  */
  102. /**
  103.  * This sample program illustrates how one can use a memory buffer as the
  104.  * input to parser. The memory buffer contains raw bytes representing XML
  105.  * statements.
  106.  *
  107.  * Look at the API documentation for 'MemBufInputSource' for more information
  108.  * on parameters to the constructor.
  109.  *
  110.  */
  111. // ---------------------------------------------------------------------------
  112. //  Includes
  113. // ---------------------------------------------------------------------------
  114. #include <parsers/SAXParser.hpp>
  115. #include <framework/MemBufInputSource.hpp>
  116. #include "MemParse.hpp"
  117. // ---------------------------------------------------------------------------
  118. //  Local const data
  119. //
  120. //  gXMLInMemBuf
  121. //      Defines the memory buffer contents here which parsed by the XML
  122. //      parser. This is the cheap way to do it, instead of reading it from
  123. //      somewhere. For this demo, its fine.
  124. //
  125. //      NOTE: If your encoding is not ascii you will need to change
  126. //            the MEMPARSE_ENCODING #define
  127. //
  128. //  gMemBufId
  129. //      A simple name to give as the system id for the memory buffer. This
  130. //      just for indentification purposes in case of errors. Its not a real
  131. //      system id (and the parser knows that.)
  132. // ---------------------------------------------------------------------------
  133. #ifndef MEMPARSE_ENCODING
  134.    #if defined(OS390)
  135.       #define MEMPARSE_ENCODING "ibm-1047-s390"
  136.    #else
  137.       #define MEMPARSE_ENCODING "ascii"
  138.    #endif
  139. #endif /* ifndef MEMPARSE_ENCODING */
  140. static const char*  gXMLInMemBuf =
  141. "
  142. <?xml version='1.0' encoding='" MEMPARSE_ENCODING "'?>n
  143. <!DOCTYPE company [n
  144. <!ELEMENT company     (product,category,developedAt)>n
  145. <!ELEMENT product     (#PCDATA)>n
  146. <!ELEMENT category    (#PCDATA)>n
  147. <!ATTLIST category idea CDATA #IMPLIED>n
  148. <!ELEMENT developedAt (#PCDATA)>n
  149. ]>nn
  150. <company>n
  151.     <product>XML4C</product>n
  152.     <category idea='great'>XML Parsing Tools</category>n
  153.     <developedAt>n
  154.       IBM Center for Java Technology, Silicon Valley, Cupertino, CAn
  155.     </developedAt>n
  156. </company>
  157. ";
  158. static const char*  gMemBufId = "prodInfo";
  159. // ---------------------------------------------------------------------------
  160. //  Local helper methods
  161. // ---------------------------------------------------------------------------
  162. void usage()
  163. {
  164.     cout << "nUsage:n"
  165.             "    MemParse [options]nn"
  166.             "This program uses the SAX Parser to parse a memory buffern"
  167.             "containing XML statements, and reports the number ofn"
  168.             "elements and attributes found.nn"
  169.             "Options:n"
  170.             "    -v=xxx      Validation scheme [always | never | auto*].n"
  171.             "    -n          Enable namespace processing. Defaults to off.n"
  172.             "    -s          Enable schema processing. Defaults to off.n"
  173.             "    -f          Enable full schema constraint checking. Defaults to off.n"
  174.       "    -?          Show this help.nn"
  175.             "  * = Default if not provided explicitly.n"
  176.          << endl;
  177. }
  178. // ---------------------------------------------------------------------------
  179. //  Program entry point
  180. // ---------------------------------------------------------------------------
  181. int main(int argC, char* argV[])
  182. {
  183.     // Initialize the XML4C2 system
  184.     try
  185.     {
  186.          XMLPlatformUtils::Initialize();
  187.     }
  188.     catch (const XMLException& toCatch)
  189.     {
  190.          cerr << "Error during initialization! Message:n"
  191.               << StrX(toCatch.getMessage()) << endl;
  192.          return 1;
  193.     }
  194.     SAXParser::ValSchemes    valScheme = SAXParser::Val_Auto;
  195.     bool doNamespaces       = false;
  196.     bool doSchema           = false;
  197.     bool schemaFullChecking = false;
  198.     int argInd;
  199.     for (argInd = 1; argInd < argC; argInd++)
  200.     {
  201.         // Break out on first parm not starting with a dash
  202.         if (argV[argInd][0] != '-')
  203.         {
  204.             usage();
  205.             XMLPlatformUtils::Terminate();
  206.             return 1;
  207.         }
  208.         // Watch for special case help request
  209.         if (!strcmp(argV[argInd], "-?"))
  210.         {
  211.             usage();
  212.             XMLPlatformUtils::Terminate();
  213.             return 1;
  214.         }
  215.          else if (!strncmp(argV[argInd], "-v=", 3)
  216.               ||  !strncmp(argV[argInd], "-V=", 3))
  217.         {
  218.             const char* const parm = &argV[argInd][3];
  219.             if (!strcmp(parm, "never"))
  220.                 valScheme = SAXParser::Val_Never;
  221.             else if (!strcmp(parm, "auto"))
  222.                 valScheme = SAXParser::Val_Auto;
  223.             else if (!strcmp(parm, "always"))
  224.                 valScheme = SAXParser::Val_Always;
  225.             else
  226.             {
  227.                 cerr << "Unknown -v= value: " << parm << endl;
  228.                 return 2;
  229.             }
  230.         }
  231.          else if (!strcmp(argV[argInd], "-n")
  232.               ||  !strcmp(argV[argInd], "-N"))
  233.         {
  234.             doNamespaces = true;
  235.         }
  236.          else if (!strcmp(argV[argInd], "-s")
  237.               ||  !strcmp(argV[argInd], "-S"))
  238.         {
  239.             doSchema = true;
  240.         }
  241.          else if (!strcmp(argV[argInd], "-f")
  242.               ||  !strcmp(argV[argInd], "-F"))
  243.         {
  244.             schemaFullChecking = true;
  245.         }
  246.          else
  247.         {
  248.             cerr << "Unknown option '" << argV[argInd]
  249.                  << "', ignoring itn" << endl;
  250.         }
  251.     }
  252.     //
  253.     //  Create a SAX parser object. Then, according to what we were told on
  254.     //  the command line, set it to validate or not.
  255.     //
  256.     SAXParser* parser = new SAXParser;
  257.     parser->setValidationScheme(valScheme);
  258.     parser->setDoNamespaces(doNamespaces);
  259.     parser->setDoSchema(doSchema);
  260.     parser->setValidationSchemaFullChecking(schemaFullChecking);
  261.     //
  262.     //  Create our SAX handler object and install it on the parser, as the
  263.     //  document and error handlers.
  264.     //
  265.     MemParseHandlers handler;
  266.     parser->setDocumentHandler(&handler);
  267.     parser->setErrorHandler(&handler);
  268.     //
  269.     //  Create MemBufferInputSource from the buffer containing the XML
  270.     //  statements.
  271.     //
  272.     //  NOTE: We are using strlen() here, since we know that the chars in
  273.     //  our hard coded buffer are single byte chars!!! The parameter wants
  274.     //  the number of BYTES, not chars, so when you create a memory buffer
  275.     //  give it the byte size (which just happens to be the same here.)
  276.     //
  277.     MemBufInputSource* memBufIS = new MemBufInputSource
  278.     (
  279.         (const XMLByte*)gXMLInMemBuf
  280.         , strlen(gXMLInMemBuf)
  281.         , gMemBufId
  282.         , false
  283.     );
  284.     //
  285.     //  Get the starting time and kick off the parse of the indicated
  286.     //  file. Catch any exceptions that might propogate out of it.
  287.     //
  288.     unsigned long duration;
  289.     int errorCount = 0;
  290.     try
  291.     {
  292.         const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis();
  293.         parser->parse(*memBufIS);
  294.         const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis();
  295.         duration = endMillis - startMillis;
  296.         errorCount = parser->getErrorCount();
  297.     }
  298.     catch (const XMLException& e)
  299.     {
  300.         cerr << "nError during parsing memory stream:n"
  301.              << "Exception message is:  n"
  302.              << StrX(e.getMessage()) << "n" << endl;
  303.         return 4;
  304.     }
  305.     // Print out the stats that we collected and time taken.
  306.     if (!errorCount) {
  307.         cout << "nFinished parsing the memory buffer containing the following "
  308.              << "XML statements:nn"
  309.              << gXMLInMemBuf
  310.              << "nnn"
  311.              << "Parsing took " << duration << " ms ("
  312.              << handler.getElementCount() << " elements, "
  313.              << handler.getAttrCount() << " attributes, "
  314.              << handler.getSpaceCount() << " spaces, "
  315.              << handler.getCharacterCount() << " characters).n" << endl;
  316.     }
  317.     //
  318.     //  Delete the parser itself.  Must be done prior to calling Terminate, below.
  319.     //
  320.     delete parser;
  321.     delete memBufIS;
  322.     // And call the termination method
  323.     XMLPlatformUtils::Terminate();
  324.     if (errorCount > 0)
  325.         return 4;
  326.     else
  327.         return 0;
  328. }