Example #1
0
// ---------------------------------------------------------------------------
//
//  main
//
// ---------------------------------------------------------------------------
int main(int argC, char* argV[])
{
    int retval = 0;

    // Initialize the XML4C2 system
    try
    {
        XMLPlatformUtils::Initialize();
    }

    catch(const XMLException &toCatch)
    {
        XERCES_STD_QUALIFIER cerr << "Error during Xerces-c Initialization.\n"
             << "  Exception message:"
             << StrX(toCatch.getMessage()) << XERCES_STD_QUALIFIER endl;
        return 1;
    }

    // Check command line and extract arguments.
    if (argC < 2)
    {
        usage();
        XMLPlatformUtils::Terminate();
        return 1;
    }

    // See if non validating dom parser configuration is requested.
    int parmInd;
    for (parmInd = 1; parmInd < argC; parmInd++)
    {
        // Break out on first parm not starting with a dash
        if (argV[parmInd][0] != '-')
            break;

        // Watch for special case help request
        if (!strcmp(argV[parmInd], "-?"))
        {
            usage();
            XMLPlatformUtils::Terminate();
            return 2;
        }
         else if (!strncmp(argV[parmInd], "-v=", 3)
              ||  !strncmp(argV[parmInd], "-V=", 3))
        {
            const char* const parm = &argV[parmInd][3];

            if (!strcmp(parm, "never"))
                gValScheme = XercesDOMParser::Val_Never;
            else if (!strcmp(parm, "auto"))
                gValScheme = XercesDOMParser::Val_Auto;
            else if (!strcmp(parm, "always"))
                gValScheme = XercesDOMParser::Val_Always;
            else
            {
                XERCES_STD_QUALIFIER cerr << "Unknown -v= value: " << parm << XERCES_STD_QUALIFIER endl;
                XMLPlatformUtils::Terminate();
                return 2;
            }
        }
         else if (!strcmp(argV[parmInd], "-n")
              ||  !strcmp(argV[parmInd], "-N"))
        {
            gDoNamespaces = true;
        }
         else if (!strcmp(argV[parmInd], "-s")
              ||  !strcmp(argV[parmInd], "-S"))
        {
            gDoSchema = true;
        }
         else if (!strcmp(argV[parmInd], "-f")
              ||  !strcmp(argV[parmInd], "-F"))
        {
            gSchemaFullChecking = true;
        }
         else if (!strcmp(argV[parmInd], "-e")
              ||  !strcmp(argV[parmInd], "-E"))
        {
            gDoCreate = true;
        }
         else if (!strncmp(argV[parmInd], "-wenc=", 6))
        {
             // Get out the encoding name
             gOutputEncoding = XMLString::transcode( &(argV[parmInd][6]) );
        }
         else if (!strncmp(argV[parmInd], "-wfile=", 7))
        {
             goutputfile =  &(argV[parmInd][7]);
        }
         else if (!strncmp(argV[parmInd], "-wddc=", 6))
        {
            const char* const parm = &argV[parmInd][6];

            if (!strcmp(parm, "on"))
				gDiscardDefaultContent = true;
            else if (!strcmp(parm, "off"))
				gDiscardDefaultContent = false;
            else
            {
                XERCES_STD_QUALIFIER cerr << "Unknown -wddc= value: " << parm << XERCES_STD_QUALIFIER endl;
                XMLPlatformUtils::Terminate();
                return 2;
            }

        }
         else if (!strncmp(argV[parmInd], "-wscs=", 6))
        {
            const char* const parm = &argV[parmInd][6];

            if (!strcmp(parm, "on"))
				gSplitCdataSections = true;
			else if (!strcmp(parm, "off"))
				gSplitCdataSections = false;
            else
            {
                XERCES_STD_QUALIFIER cerr << "Unknown -wscs= value: " << parm << XERCES_STD_QUALIFIER endl;
                XMLPlatformUtils::Terminate();
                return 2;
            }
        }
         else if (!strncmp(argV[parmInd], "-wflt=", 6))
        {
            const char* const parm = &argV[parmInd][6];

            if (!strcmp(parm, "on"))
				gUseFilter = true;
			else if (!strcmp(parm, "off"))
				gUseFilter = false;
            else
            {
                XERCES_STD_QUALIFIER cerr << "Unknown -wflt= value: " << parm << XERCES_STD_QUALIFIER endl;
                XMLPlatformUtils::Terminate();
                return 2;
            }
        }
         else if (!strncmp(argV[parmInd], "-wfpp=", 6))
        {
            const char* const parm = &argV[parmInd][6];

            if (!strcmp(parm, "on"))
				gFormatPrettyPrint = true;
			else if (!strcmp(parm, "off"))
				gFormatPrettyPrint = false;
            else
            {
                XERCES_STD_QUALIFIER cerr << "Unknown -wfpp= value: " << parm << XERCES_STD_QUALIFIER endl;
                XMLPlatformUtils::Terminate();
                return 2;
            }
        }
         else if (!strncmp(argV[parmInd], "-wbom=", 6))
        {
            const char* const parm = &argV[parmInd][6];

            if (!strcmp(parm, "on"))
                gWriteBOM = true;
            else if (!strcmp(parm, "off"))
                gWriteBOM = false;
            else
            {
                XERCES_STD_QUALIFIER cerr << "Unknown -wbom= value: " << parm << XERCES_STD_QUALIFIER endl;
                XMLPlatformUtils::Terminate();
                return 2;
            }
        }
         else if (!strncmp(argV[parmInd], "-xpath=", 7))
        {
             gXPathExpression = &(argV[parmInd][7]);
        }
         else
        {
            XERCES_STD_QUALIFIER cerr << "Unknown option '" << argV[parmInd]
                 << "', ignoring it.\n" << XERCES_STD_QUALIFIER endl;
        }
    }

    //
    //  And now we have to have only one parameter left and it must be
    //  the file name.
    //
    if (parmInd + 1 != argC)
    {
        usage();
        XMLPlatformUtils::Terminate();
        return 1;
    }
    gXmlFile = argV[parmInd];

    //
    //  Create our parser, then attach an error handler to the parser.
    //  The parser will call back to methods of the ErrorHandler if it
    //  discovers errors during the course of parsing the XML document.
    //
    XercesDOMParser *parser = new XercesDOMParser;
    parser->setValidationScheme(gValScheme);
    parser->setDoNamespaces(gDoNamespaces);
    parser->setDoSchema(gDoSchema);
    parser->setValidationSchemaFullChecking(gSchemaFullChecking);
    parser->setCreateEntityReferenceNodes(gDoCreate);

    DOMTreeErrorReporter *errReporter = new DOMTreeErrorReporter();
    parser->setErrorHandler(errReporter);

    //
    //  Parse the XML file, catching any XML exceptions that might propogate
    //  out of it.
    //
    bool errorsOccured = false;
    try
    {
        parser->parse(gXmlFile);
    }
    catch (const OutOfMemoryException&)
    {
        XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl;
        errorsOccured = true;
    }
    catch (const XMLException& e)
    {
        XERCES_STD_QUALIFIER cerr << "An error occurred during parsing\n   Message: "
             << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
        errorsOccured = true;
    }

    catch (const DOMException& e)
    {
        const unsigned int maxChars = 2047;
        XMLCh errText[maxChars + 1];

        XERCES_STD_QUALIFIER cerr << "\nDOM Error during parsing: '" << gXmlFile << "'\n"
             << "DOMException code is:  " << e.code << XERCES_STD_QUALIFIER endl;

        if (DOMImplementation::loadDOMExceptionMsg(e.code, errText, maxChars))
             XERCES_STD_QUALIFIER cerr << "Message is: " << StrX(errText) << XERCES_STD_QUALIFIER endl;

        errorsOccured = true;
    }

    catch (...)
    {
        XERCES_STD_QUALIFIER cerr << "An error occurred during parsing\n " << XERCES_STD_QUALIFIER endl;
        errorsOccured = true;
    }

    // If the parse was successful, output the document data from the DOM tree
    if (!errorsOccured && !errReporter->getSawErrors())
    {
        DOMPrintFilter   *myFilter = 0;

        try
        {
            // get a serializer, an instance of DOMLSSerializer
            XMLCh tempStr[3] = {chLatin_L, chLatin_S, chNull};
            DOMImplementation *impl          = DOMImplementationRegistry::getDOMImplementation(tempStr);
            DOMLSSerializer   *theSerializer = ((DOMImplementationLS*)impl)->createLSSerializer();
            DOMLSOutput       *theOutputDesc = ((DOMImplementationLS*)impl)->createLSOutput();

            // set user specified output encoding
            theOutputDesc->setEncoding(gOutputEncoding);

            // plug in user's own filter
            if (gUseFilter)
            {
                // even we say to show attribute, but the DOMLSSerializer
                // will not show attribute nodes to the filter as
                // the specs explicitly says that DOMLSSerializer shall
                // NOT show attributes to DOMLSSerializerFilter.
                //
                // so DOMNodeFilter::SHOW_ATTRIBUTE has no effect.
                // same DOMNodeFilter::SHOW_DOCUMENT_TYPE, no effect.
                //
                myFilter = new DOMPrintFilter(DOMNodeFilter::SHOW_ELEMENT   |
                                              DOMNodeFilter::SHOW_ATTRIBUTE |
                                              DOMNodeFilter::SHOW_DOCUMENT_TYPE);
                theSerializer->setFilter(myFilter);
            }

            // plug in user's own error handler
            DOMErrorHandler *myErrorHandler = new DOMPrintErrorHandler();
            DOMConfiguration* serializerConfig=theSerializer->getDomConfig();
            serializerConfig->setParameter(XMLUni::fgDOMErrorHandler, myErrorHandler);

            // set feature if the serializer supports the feature/mode
            if (serializerConfig->canSetParameter(XMLUni::fgDOMWRTSplitCdataSections, gSplitCdataSections))
                serializerConfig->setParameter(XMLUni::fgDOMWRTSplitCdataSections, gSplitCdataSections);

            if (serializerConfig->canSetParameter(XMLUni::fgDOMWRTDiscardDefaultContent, gDiscardDefaultContent))
                serializerConfig->setParameter(XMLUni::fgDOMWRTDiscardDefaultContent, gDiscardDefaultContent);

            if (serializerConfig->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, gFormatPrettyPrint))
                serializerConfig->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, gFormatPrettyPrint);

            if (serializerConfig->canSetParameter(XMLUni::fgDOMWRTBOM, gWriteBOM))
                serializerConfig->setParameter(XMLUni::fgDOMWRTBOM, gWriteBOM);

            //
            // Plug in a format target to receive the resultant
            // XML stream from the serializer.
            //
            // StdOutFormatTarget prints the resultant XML stream
            // to stdout once it receives any thing from the serializer.
            //
            XMLFormatTarget *myFormTarget;
            if (goutputfile)
                myFormTarget=new LocalFileFormatTarget(goutputfile);
            else
                myFormTarget=new StdOutFormatTarget();
            theOutputDesc->setByteStream(myFormTarget);

            // get the DOM representation
            DOMDocument *doc = parser->getDocument();

            //
            // do the serialization through DOMLSSerializer::write();
            //
            if(gXPathExpression!=NULL)
            {
                XMLCh* xpathStr=XMLString::transcode(gXPathExpression);
                DOMElement* root = doc->getDocumentElement();
                try
                {
                    DOMXPathNSResolver* resolver=doc->createNSResolver(root);
                    DOMXPathResult* result=doc->evaluate(
                      xpathStr,
                      root,
                      resolver,
                      DOMXPathResult::ORDERED_NODE_SNAPSHOT_TYPE,
                      NULL);

                    XMLSize_t nLength = result->getSnapshotLength();
                    for(XMLSize_t i = 0; i < nLength; i++)
                    {
                      result->snapshotItem(i);
                      theSerializer->write(result->getNodeValue(), theOutputDesc);
                    }

                    result->release();
                    resolver->release ();
                }
                catch(const DOMXPathException& e)
                {
                    XERCES_STD_QUALIFIER cerr << "An error occurred during processing of the XPath expression. Msg is:"
                        << XERCES_STD_QUALIFIER endl
                        << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
                    retval = 4;
                }
                catch(const DOMException& e)
                {
                    XERCES_STD_QUALIFIER cerr << "An error occurred during processing of the XPath expression. Msg is:"
                        << XERCES_STD_QUALIFIER endl
                        << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
                    retval = 4;
                }
                XMLString::release(&xpathStr);
            }
            else
                theSerializer->write(doc, theOutputDesc);

            theOutputDesc->release();
            theSerializer->release();

            //
            // Filter, formatTarget and error handler
            // are NOT owned by the serializer.
            //
            delete myFormTarget;
            delete myErrorHandler;

            if (gUseFilter)
                delete myFilter;

        }
        catch (const OutOfMemoryException&)
        {
            XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl;
            retval = 5;
        }
        catch (XMLException& e)
        {
            XERCES_STD_QUALIFIER cerr << "An error occurred during creation of output transcoder. Msg is:"
                << XERCES_STD_QUALIFIER endl
                << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
            retval = 4;
        }

    }
    else
        retval = 4;

    //
    //  Clean up the error handler. The parser does not adopt handlers
    //  since they could be many objects or one object installed for multiple
    //  handlers.
    //
    delete errReporter;

    //
    //  Delete the parser itself.  Must be done prior to calling Terminate, below.
    //
    delete parser;

    XMLString::release(&gOutputEncoding);

    // And call the termination method
    XMLPlatformUtils::Terminate();

    return retval;
}
Example #2
0
list<ClsDataClientConfig> ClsDataClientConfigReader::getDataClientConfig(string strFileName)  {
#ifdef DEBUG_CLSDATACLIENTCONFIGREADER
    cout << "ClsDataClientConfigReader::getDataClientConfig()" << endl;
#endif

    list<ClsDataClientConfig> lstConfigs;
#ifdef DEBUG_CLSDATACLIENTCONFIGREADER
    cout << "reading settings from: " << strFileName << endl;
#endif

    bool errorsOccured = false;
    static bool gDoNamespaces = false;

    if(!bXMLPlatformInitialized){
	try {
	    XMLPlatformUtils::Initialize();
	}
	catch(const XMLException& toCatch) {
	    cerr << "Error during Xerces-c Initialization.\n"
		 << "  Exception message:"
		 << toCatch.getMessage() << endl;
	    bXMLPlatformInitialized = false;
	    errorsOccured = true;
//	    return;
	}
	bXMLPlatformInitialized = true;
	errorsOccured = false;
    }
    //--------------------

    if (!errorsOccured) {
	XercesDOMParser* parser = new XercesDOMParser();
	parser->setValidationScheme(XercesDOMParser::Val_Never);
	/*
	  XercesDOMParser::Val_Never;
	  XercesDOMParser::Val_Auto;
	  XercesDOMParser::Val_Always;
	*/


	parser->setDoNamespaces(gDoNamespaces);
	ErrorHandler* errHandler = (ErrorHandler*) new HandlerBase();
	parser->setErrorHandler(errHandler);


	try {
	    parser->parse(strFileName.c_str());

	    int errorCount = parser->getErrorCount();
	    if (errorCount > 0){
		errorsOccured = true;
	    }

	} catch (const XMLException& e) {
	    cerr << "An error occured during parsing (XMLException)\n   NMessage: " <<  XMLString::transcode(e.getMessage()) << endl;
	    ClsDataClientConfigReaderException clsDataClientConfigReaderException(XMLString::transcode(e.getMessage()));
	    errorsOccured = true;
	    throw clsDataClientConfigReaderException;
	} catch (const DOMException& e) {
	    cerr << "An error occured during parsing (DOMException)\n   DMessage: " << XMLString::transcode(e.msg) << endl;
	    ClsDataClientConfigReaderException clsDataClientConfigReaderException(XMLString::transcode(e.msg));
	    errorsOccured = true;
	    throw clsDataClientConfigReaderException;
	} catch (const SAXException& e) {
	    cerr << "An error occured during parsing (SAXException)\n   DMessage: " <<  XMLString::transcode(e.getMessage()) << endl;
	    ClsDataClientConfigReaderException clsDataClientConfigReaderException(XMLString::transcode(e.getMessage()));
	    errorsOccured = true;
	    throw clsDataClientConfigReaderException;
	} catch (...) {
	    cerr << "An error occured during parsing\n " << endl;
	    errorsOccured = true;
	    ClsDataClientConfigReaderException clsDataClientConfigReaderException(ClsDataClientConfigReaderException::PARSE_ERROR);
	    throw clsDataClientConfigReaderException;
	}

	/* DOMNode* dnIqrConfig; */
	DOMDocument *ddocConfig = parser->getDocument();

	DOMNodeList* dnlstClients = ddocConfig->getElementsByTagName(XMLString::transcode(ConfigTagLibrary::DataClientTag()));

	try{
	    if(dnlstClients->getLength()>0){
		DOMNode* dnValue = NULL;

		unsigned int ii = 0;
		while( ii< dnlstClients->getLength()){
		    DOMNode* dnClient = dnlstClients->item(ii);
		    ii++;

		    string strType = getAttributeValue(dnClient, ConfigTagLibrary::TypeTag(), true);
		    string strID = getAttributeValue(dnClient, ConfigTagLibrary::IDTag(), false);
		    ClsDataClientConfig clsDataClientConfig(strID, strType);


		    DOMNodeList* dnlstClientChildren = dnClient->getChildNodes();
		    unsigned int i2 = 0;
		    while( i2< dnlstClientChildren->getLength()){
			DOMNode* dnClientChild = dnlstClientChildren->item(i2);
			if(dnClientChild->getNodeType() == 1){
			    string strName = XMLString::transcode(dnClientChild->getNodeName());
			    if(!strName.compare(ConfigTagLibrary::PositionTag())){
				int iX = 0;
				int iY = 0;
				iX = iqrUtils::string2int(getAttributeValue(dnClientChild, ConfigTagLibrary::PositionXTag(), true));
				iY = iqrUtils::string2int(getAttributeValue(dnClientChild, ConfigTagLibrary::PositionYTag(), true));
				clsDataClientConfig.setPosition(iX, iY);
			    } else if(!strName.compare(ConfigTagLibrary::Geometry())){
				int iWidth = 0;
				int iHeight = 0;
				    iWidth = iqrUtils::string2int(getAttributeValue(dnClientChild, ConfigTagLibrary::GeometryWidthTag(), true));
				    iHeight = iqrUtils::string2int(getAttributeValue(dnClientChild, ConfigTagLibrary::GeometryHeightTag(), true));
				clsDataClientConfig.setGeometry(iWidth, iHeight);
			    } else if(!strName.compare(ConfigTagLibrary::StateVariableDisplayTag())){
				DOMNodeList* dnlstSVD = dnClientChild->getChildNodes();
				unsigned int i3 = 0;
				while( i3< dnlstSVD->getLength()){
				    DOMNode* dnSVD = dnlstSVD->item(i3);
				    if(dnSVD->getNodeType() == 1){
					string strSVDID = getAttributeValue(dnSVD, ConfigTagLibrary::IDTag(), true);
//--					string strItemType = getAttributeValue(dnSVD, ConfigTagLibrary::TypeTag(), true);
					string strItemID = getAttributeValue(dnSVD, ConfigTagLibrary::ItemIDTag(), true);
					string strSelectedIndices = getAttributeValue(dnSVD, ConfigTagLibrary::SelectedIndicesTag(), true);
					ClsStateVariableDisplayConfig clsStateVariableDisplayConfig(/*strItemType,*/ strSVDID, strItemID, strSelectedIndices);
					DOMNodeList* dnlstSVDParams = dnSVD->getChildNodes();
					unsigned int i4 = 0;
					while( i4< dnlstSVDParams->getLength()){
					    DOMNode* dnSVDParam = dnlstSVDParams->item(i4);
					    if(dnSVDParam->getNodeType() == 1){
						string strParamName = XMLString::transcode(dnSVDParam->getNodeName());
						dnValue = dnSVDParam->getFirstChild();
						string strParamValue = "";
						if(dnValue!=NULL){
						    strParamValue = XMLString::transcode(dnValue->getNodeValue());
						}
						pair<string, string> pParam(strParamName, strParamValue);
						clsStateVariableDisplayConfig.addParameter(pParam);
					    }
					    i4++;
					}
					clsDataClientConfig.addStateVariableDisplayConfig(clsStateVariableDisplayConfig);
				    }
				    i3++;
				}
			    } else {
				string strValue = "";
				dnValue = dnClientChild->getFirstChild();
				if(dnValue!=NULL){
				    strValue = XMLString::transcode(dnValue->getNodeValue());
				}
				pair<string, string> pParam(strName, strValue);
				clsDataClientConfig.addParameter(pParam);
			    }
			}
			i2++;
		    }
		    lstConfigs.push_back(clsDataClientConfig);
		}
	    }
	} catch (...) {
	    ClsDataClientConfigReaderException clsDataClientConfigReaderException(ClsDataClientConfigReaderException::PARSE_ERROR);
	    throw clsDataClientConfigReaderException;
	}

	delete errHandler;
    }

    return lstConfigs;
};
Example #3
0
XERCES_CPP_NAMESPACE_USE

int main( int argc, char *argv[] )
{
    std::cout << "****************************" << std::endl;
    std::cout << "XML DOM PARSER PLAY" << std::endl;
    std::cout << "****************************" << std::endl;

    try
    {
        XMLPlatformUtils::Initialize();
    }
    catch( const XMLException& ex )
    {
        std::cerr << "error with xml initialisation:" << ex.getMessage() << std::endl;
        return 1;
    }

    std::cout << "Building parser ..." << std::endl;
    XercesDOMParser* parser = new XercesDOMParser();
    if( !parser )
    {
        std::cerr << "no parser" << std::endl;
        return 1;
    }
    parser->setValidationScheme(XercesDOMParser::Val_Always);
    parser->setDoNamespaces(false);
    parser->setDoSchema(false);
    parser->setCreateEntityReferenceNodes(false);

    std::cout << "Building error handler" << std::endl;
    ErrorHandler* errHandler = dynamic_cast<ErrorHandler*>(new HandlerBase());
    if( errHandler == 0 )
    {
        std::cerr << "ibad cast" << std::endl;
        return 1;
    } 
    
    if( errHandler == 0 )
    {
        std::cerr << "error with errorhandler caszting:" << std::endl;
        return 1;
    }
    parser->setErrorHandler(errHandler);

    char* xmlFile = "/home/suggitpe/test/RPMS/config/rpms_config.xml";
    try
    {
        parser->parse(xmlFile);
        if( parser->getErrorCount() == 0 )
        {
            std::cerr << "errors in parsing" << std::endl;
            return 1;
        }
        DOMDocument * doc = parser->getDocument();
        if( doc->hasChildNodes() )
        {
            std::cout << "Num nodes: " << doc->getChildNodes()->getLength() << std::endl;
            for( int i = 0; i < doc->getChildNodes()->getLength();++i )
            {
                cout << "\t" << i << " type: " << doc->getChildNodes()->item(i)->getNodeType() << endl;
                if( doc->getChildNodes()->item(i)->getNodeType() == 1 )
                {
                    DOMElement *e = dynamic_cast<DOMElement*>(doc->getChildNodes()->item(i));
                    if( !e ) { cerr << "bad cast" << endl; }
                    if( e->hasChildNodes() )
                    {
                        cout << "\t\telement found with " << e->getChildNodes()->getLength() << " nodes"<< endl;
                    }
                    else
                    {
                        cout << "No child nodes" << endl;
                    }
                }
            }

            cout << "now for the other way" << endl;
            XMLCh * name = XMLString::transcode("system_components");
            DOMNodeList *list = doc->getDocumentElement()->getElementsByTagName( name );
            XMLString::release(&name);
            
            std::cout << "Got list [" << list->getLength() << "]" << std::endl;
            for( XMLSize_t i =0; i < list->getLength(); ++i )
            {
                std::cout << "." << std::endl;
            }
        }
        else
        {
            std::cout << "no child nodes" << std::endl;
        }
    }
    catch( const XMLException& ex )
    {
        std::cerr << "error with xml parser:" << ex.getMessage() << std::endl;
        return 1;
    }
    catch( const DOMException& dex )
    {
        std::cerr << "error with xml parser:" << dex.msg << std::endl;
        return 1;
    }
    catch(...)
    {
        std::cerr << "unknown problems" << std::endl;
        return 1;
            
    }
    delete parser;
    delete errHandler;

    std::cout << "****************************" << std::endl;
    std::cout << "" << std::endl;
    return 0;
}
Example #4
0
 int parse_header_config(char *filename,int is_credit)
 {
	      int parse_status = 0 ; // if parse_status is non-zero , return FAILURE
		       struct stat st;
			        if(lstat(filename,&st) != 0)
		     {
		          emit_bypass(FILE_LINE,"configuration file %s doesn't exist,please check ENV HEADER_CONFIG_PATH is set",filename);
                  return FAILURE;
			 }
			 DOMNodeList *nodeList = NULL;
			 DOMNode *node = NULL;
			 try {
				 XMLPlatformUtils::Initialize();
			 }
			 catch (const XMLException& toCatch) {
				 char* message = XMLString::transcode(toCatch.getMessage());
				 emit_bypass(FILE_LINE, "Failed to process file %s", filename);
				 emit_bypass(FILE_LINE, " Error during initialization %s",message);
				 XMLString::release(&message);
				 return FAILURE;
			 }
			 XercesDOMParser* parser = new XercesDOMParser();
			 parser->setValidationScheme(XercesDOMParser::Val_Always);
			 parser->setDoNamespaces(true);
			 ErrorHandler* errHandler = (ErrorHandler*) new HandlerBase();
			 parser->setErrorHandler(errHandler);
			 try
			 {
				 parser->parse(filename);
				 DOMDocument *doc = parser->getDocument();
				 nodeList = doc->getElementsByTagName(XMLString::transcode("xmlns"));
				 node = nodeList->item(0);
				 if (!node)
				 {
					 emit_bypass(FILE_LINE,"xmlns is not found in configurtion file %s",filename);
					 parse_status = 1;
				 }
				 if (parse_status !=1 )
				 {
					 if(is_credit!=1)
					 {
					    strcpy(gXmlns_str,XMLString::transcode(node->getTextContent()));
					    if (strlen(gXmlns_str) == 0)
					    {
					        emit_bypass(FILE_LINE,"xmlns is set empty in configurtion file %s",filename);
						    parse_status = 1;
						}
				     }
					 else
					 {
					     strcpy(gXmlns_str_credit,XMLString::transcode(node->getTextContent()));
						 if(strlen(gXmlns_str_credit) == 0)
						 {
						    emit_bypass(FILE_LINE,"xmlns is set empty in configurtion file %s",filename);
						    parse_status = 1;
					     }
					 }
				 }
				 nodeList = doc->getElementsByTagName(XMLString::transcode("xsi"));
				 node = nodeList->item(0);
				 if (!node)
				 {
					 emit_bypass(FILE_LINE,"xsi is not found in configuration file %s",filename);
					 parse_status = 2;
				 }
				 if (parse_status != 2)
				 {
					 if(is_credit!=1)
					 {
					    strcpy(gXsi_str,XMLString::transcode(node->getTextContent()));
						if (strlen(gXsi_str) == 0)
						{
						    emit_bypass(FILE_LINE,"xsi is set empty in configurtion file %s",filename);
							parse_status = 2;
						}
					 }
					 else
					 {
					    strcpy(gXsi_str_credit,XMLString::transcode(node->getTextContent()));
                        if (strlen(gXsi_str_credit) == 0)
						{
						   emit_bypass(FILE_LINE,"xsi is set empty in configurtion file %s",filename);
						   parse_status = 2;
						}
					 }
				 }
				 nodeList = doc->getElementsByTagName(XMLString::transcode("schemaLocation"));
				 node = nodeList->item(0);
				 if (!node)
				 {
					              emit_bypass(FILE_LINE,"schemaLocation is not found in configuration file %s",filename);

								  parse_status = 3;
				 }
				 if (parse_status !=3)
				 {
					 if(is_credit!=1)
					 {
					    strcpy(gSchemaLocation_str,XMLString::transcode(node->getTextContent()));
						if (strlen(gSchemaLocation_str) == 0)
						{
						   emit_bypass(FILE_LINE," schemaLocation is set empty in configurtion file %s",filename);
						   parse_status = 3;
						}
					 }
					 else
					 {
					    strcpy(gSchemaLocation_str_credit,XMLString::transcode(node->getTextContent()));
						if (strlen(gSchemaLocation_str_credit) == 0)
						{
						    emit_bypass(FILE_LINE," schemaLocation is set empty in configurtion file %s",filename);
							parse_status = 3;
						}
					 }
				 }
				 delete parser;
				 delete errHandler;
				 XMLPlatformUtils::Terminate();
				 if (parse_status != 0)
					 return FAILURE;
					 return SUCCESS;
			 }
			 catch (const DOMException& toCatch)
			 {
				 char* message = XMLString::transcode(toCatch.getMessage());
				 emit_bypass(FILE_LINE, "Failed to process file %s", filename);
				 emit_bypass(FILE_LINE, "Exception message is:%s", message);
			 }
			 catch (exception& e)
			 {
				 emit_bypass(FILE_LINE, "Failed to process file %s", filename);
				 emit_bypass(FILE_LINE, "Exception message is:%s", e.what());
			 }
			 catch (...){
				 emit_bypass(FILE_LINE, "Failed to process file %s", filename);
			 }
			 delete parser;
			 delete errHandler;
			 XMLPlatformUtils::Terminate();
			 return FAILURE;
 }
Example #5
0
void
Importer::parseScene
(const char* path, Scene *scene)
{
  // Inicialización.
  try {
    XMLPlatformUtils::Initialize();
  }
  catch (const XMLException& toCatch) {
    char* message = XMLString::transcode(toCatch.getMessage());
    cout << "Error durante la inicialización! :\n"
	 << message << "\n";
    XMLString::release(&message);
    return;
  }

  XercesDOMParser* parser = new XercesDOMParser();
  parser->setValidationScheme(XercesDOMParser::Val_Always);

  // 'Parseando' el fichero xml...
  try {
    parser->parse(path);
  }
  catch (const XMLException& toCatch) {
    char* message = XMLString::transcode(toCatch.getMessage());
    cout << "Excepción capturada: \n"
	 << message << "\n";
    XMLString::release(&message);
  }
  catch (const DOMException& toCatch) {
    char* message = XMLString::transcode(toCatch.msg);
    cout << "Excepción capturada: \n"
	 << message << "\n";
    XMLString::release(&message);
  }
  catch (...) {
    cout << "Excepción no esperada.\n" ;
    return;
  }

  DOMDocument* xmlDoc;
  DOMElement* elementRoot;

  try {
    // Obtener el elemento raíz del documento.
    xmlDoc = parser->getDocument(); 
    elementRoot = xmlDoc->getDocumentElement();

    if(!elementRoot)
      throw(std::runtime_error("Documento XML vacío."));

  }
  catch (xercesc::XMLException& e ) {
    char* message = xercesc::XMLString::transcode( e.getMessage() );
    ostringstream errBuf;
    errBuf << "Error 'parseando': " << message << flush;
    XMLString::release( &message );
    return;
  }

  XMLCh* camera_ch = XMLString::transcode("camera");  
  XMLCh* graph_ch = XMLString::transcode("graph");  

  // Procesando los nodos hijos del raíz...
  for (XMLSize_t i = 0; 
       i < elementRoot->getChildNodes()->getLength(); 
       ++i ) {
    
    DOMNode* node = elementRoot->getChildNodes()->item(i);

    if (node->getNodeType() == DOMNode::ELEMENT_NODE) {      
	// Nodo <graph>?
	if (XMLString::equals(node->getNodeName(), graph_ch))
	  parseGraph(node, scene);
    }
    
  }
  // Liberar recursos.
  XMLString::release(&camera_ch);
  XMLString::release(&graph_ch);

  delete parser;
}
Example #6
0
int ParameterManager::LoadDocument(const XERCES_CPP_NAMESPACE_QUALIFIER InputSource& inputSource)
{
    //
    //  Create our parser, then attach an error handler to the parser.
    //  The parser will call back to methods of the ErrorHandler if it
    //  discovers errors during the course of parsing the XML document.
    //
    XercesDOMParser *parser = new XercesDOMParser;
    parser->setValidationScheme(gValScheme);
    parser->setDoNamespaces(gDoNamespaces);
    parser->setDoSchema(gDoSchema);
    parser->setValidationSchemaFullChecking(gSchemaFullChecking);
    parser->setCreateEntityReferenceNodes(gDoCreate);

    DOMTreeErrorReporter *errReporter = new DOMTreeErrorReporter();
    parser->setErrorHandler(errReporter);

    //
    //  Parse the XML file, catching any XML exceptions that might propagate
    //  out of it.
    //
    bool errorsOccured = false;
    try {
        parser->parse(inputSource);
    }

    catch (const XMLException& e) {
        std::cerr << "An error occurred during parsing\n   Message: "
        << StrX(e.getMessage()) << std::endl;
        errorsOccured = true;
    }

    catch (const DOMException& e) {
        std::cerr << "A DOM error occurred during parsing\n   DOMException code: "
        << e.code << std::endl;
        errorsOccured = true;
    }

    catch (...) {
        std::cerr << "An error occurred during parsing\n " << std::endl;
        errorsOccured = true;
    }

    if (errorsOccured) {
        delete parser;
        delete errReporter;
        return 0;
    }

    _pDocument = parser->adoptDocument();
    delete parser;
    delete errReporter;

    if (!_pDocument)
        throw XMLBaseException("Malformed Parameter document: Invalid document");

    DOMElement* rootElem = _pDocument->getDocumentElement();
    if (!rootElem)
        throw XMLBaseException("Malformed Parameter document: Root group not found");

    _pGroupNode = FindElement(rootElem,"FCParamGroup","Root");

    if (!_pGroupNode)
        throw XMLBaseException("Malformed Parameter document: Root group not found");

    return 1;
}
Example #7
0
int parseTEI( const char* xmlFile, bool english, SentenceList& sentenceList )
{
  try
  {
    XMLPlatformUtils::Initialize();
  }

  catch(const XMLException &toCatch)
  {
    std::cerr << "Error during Xerces-c Initialization.\n"
         << "  Exception message:"
         << StrX(toCatch.getMessage()) << std::endl;
    return 1;
  }

  //
  //  Create our parser, then attach an error handler to the parser.
  //  The parser will call back to methods of the ErrorHandler if it
  //  discovers errors during the course of parsing the XML document.
  //
  XercesDOMParser *parser = new XercesDOMParser;
  parser->setValidationScheme(XercesDOMParser::Val_Never);
  parser->setDoNamespaces(false);
  parser->setDoSchema(false);
  parser->setValidationSchemaFullChecking(false);
  parser->setCreateEntityReferenceNodes(false);

  DOMTreeErrorReporter *errReporter = new DOMTreeErrorReporter();
  parser->setErrorHandler(errReporter);

  //
  //  Parse the XML file, catching any XML exceptions that might propogate
  //  out of it.
  //
  bool errorsOccured = false;
  try
  {
    parser->parse(xmlFile);
  }
  catch (const XMLException& e)
  {
    std::cerr << "An error occurred during parsing\n   Message: "
         << StrX(e.getMessage()) << std::endl;
    errorsOccured = true;
  }
  catch (const DOMException& e)
  {
    const unsigned int maxChars = 2047;
    XMLCh errText[maxChars + 1];

    std::cerr << "\nDOM Error during parsing: '" << xmlFile << "'\n"
         << "DOMException code is:  " << e.code << std::endl;

    if (DOMImplementation::loadDOMExceptionMsg(e.code, errText, maxChars))
         std::cerr << "Message is: " << StrX(errText) << std::endl;

    errorsOccured = true;
  }
  catch (...)
  {
    std::cerr << "An error occurred during parsing\n " << std::endl;
    errorsOccured = true;
  }

  if (errorsOccured || errReporter->getSawErrors())
    return -1;

  // get the DOM representation
  DOMNode *doc = parser->getDocument();

  sentenceList.clear();
  buildSentenceListFromDOMTree(doc,sentenceList,english);

  delete errReporter;

  // Delete the parser itself.  Must be done prior to calling Terminate, below.
  delete parser;

  // And call the termination method
  XMLPlatformUtils::Terminate();

  return 0;
}