void ItemDataLoader::loadData(string filename)
	{
		XMLPlatformUtils::Initialize();

		XmlHelper::initializeTranscoder();
		XercesDOMParser* parser = new XercesDOMParser();

        parser->setValidationScheme(XercesDOMParser::Val_Always);    // optional.
        parser->setDoNamespaces(true);    // optional
		
		XmlPtr res = XmlResourceManager::getSingleton().create(filename, 
			Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
		res->parseBy(parser);

		DOMDocument* doc = parser->getDocument();
		DOMElement* dataDocumentContent = XmlHelper::getChildNamed(
            doc->getDocumentElement(), "Inhalt");

		initializeWeapons(XmlHelper::getChildNamed(dataDocumentContent, "Waffen"));
		initializeArmors(XmlHelper::getChildNamed(dataDocumentContent, "Rüstungen"));
		initializeItems(XmlHelper::getChildNamed(dataDocumentContent, "Gegenstände"));
		
		doc->release();

        res.setNull();
        XmlResourceManager::getSingleton().remove(filename);

		XMLPlatformUtils::Terminate();
	}
Example #2
0
map<string, DatasetSpecification> Specifications::readDatasetIndex(string str){
  map<string, DatasetSpecification> result;
  XERCES_CPP_NAMESPACE_USE
  XMLPlatformUtils::Initialize();
  XercesDOMParser parser;
  parser.setValidationScheme(XercesDOMParser::Val_Always);
  HandlerBase errHandler;// = (ErrorHandler*) new HandlerBase();
  parser.setErrorHandler(&errHandler);
  parser.parse(str.c_str());
  DOMDocument * doc = parser.getDocument();
  DOMElement* elementRoot = doc->getDocumentElement();
  DOMNodeList *entries = 
    elementRoot->getElementsByTagName(XMLString::transcode("dataset"));
  
  cout << "Databases in index:\n";
  for(size_t i = 0; i < entries->getLength(); ++i){
    DOMNode *current = entries->item(i);
    DatasetSpecification dss;
    dss.name = XMLString::transcode(current->getAttributes()->
				    getNamedItem(XMLString::transcode("name"))->
				    getNodeValue());
    dss.root = XMLString::transcode(current->getAttributes()->
				    getNamedItem(XMLString::transcode("root"))->
				    getNodeValue());
    cout << "  name: " << dss.name << " root: " << dss.root << endl;
    DOMNodeList *categories = current->getChildNodes();
    for(size_t j = 0; j < categories->getLength(); ++j)
      if((string) XMLString::transcode(categories->item(j)->getNodeName()) ==
	 "category")
	dss.categories.push_back(XMLString::transcode(categories->item(j)->getTextContent()));
    result[dss.name] = dss;
  }
  return result;
}
Example #3
0
void Parameters::readFile(string str){
  file = str;
  XMLPlatformUtils::Initialize();
  XercesDOMParser parser;
  parser.setValidationScheme(XercesDOMParser::Val_Always);
  HandlerBase errHandler;// = (ErrorHandler*) new HandlerBase();
  parser.setErrorHandler(&errHandler);
  parser.parse(str.c_str());
  DOMDocument * doc = parser.getDocument();
  DOMElement* elementRoot = doc->getDocumentElement();

  // Extract floats
  DOMElement* floatRoot = (DOMElement *) 
    elementRoot->getElementsByTagName(XMLString::transcode("real"))->item(0);
  DOMElement* child = floatRoot->getFirstElementChild();
  do{
    saveReal(XMLString::transcode(child->getNodeName()),  
		    atof(XMLString::transcode(child->getTextContent())));
    child = child->getNextElementSibling();
  }while(child != NULL);

  // Extract integers
  DOMElement* intRoot = (DOMElement *) 
    elementRoot->getElementsByTagName(XMLString::transcode("integer"))->item(0);
  child = intRoot->getFirstElementChild();
  do{
    saveInteger(
		    XMLString::transcode(child->getNodeName()),  
		    atoi(XMLString::transcode(child->getTextContent())));
    child = child->getNextElementSibling();
  }while(child != NULL);
}
Example #4
0
bool SYSTEM::CXMLConfiguration::Open(std::string xmlpath)
{
    // ÅäÖýâÎö¹æÔò
    static const XMLCh gLS[] = { chLatin_L, chLatin_S, chNull };
    impl = DOMImplementationRegistry::getDOMImplementation(gLS);
    if(!impl)
        return false;
//		throw CException(GET_TEXT(ERR_XML_DOM_IMPLEMENTATION));
    if(parser == NULL)
        parser = new XercesDOMParser;
    XercesDOMParser* xmlparser = (XercesDOMParser*)parser;
    xmlparser->setValidationScheme(XercesDOMParser::Val_Never);
    xmlparser->setDoNamespaces(false);
    xmlparser->setDoSchema(false);
    xmlparser->setValidationSchemaFullChecking(false);
    xmlparser->setCreateEntityReferenceNodes(false);
    xmlparser->setIncludeIgnorableWhitespace(false);

    xmlparser->resetDocumentPool();	//ÖØÖÃÎĵµ»º³å³Ø
    xmlparser->parse(xmlpath.c_str());
    doc = xmlparser->getDocument();
    if(doc)
        itemElement = ((XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument*)doc)->getDocumentElement();	//¸³Óè¸ù½Úµã
    else
        return false;
    //throw CException(boost::str(boost::format(GET_TEXT(ERR_PARSE_CONFIG_FILE)) % xmlpath));

    xmlFile = xmlpath;
    return true;
}
Example #5
0
void SYSTEM::CXMLConfiguration::Parse(std::string xmlcontent)
{
    // ÅäÖýâÎö¹æÔò
    static const XMLCh gLS[] = { chLatin_L, chLatin_S, chNull };
    impl = DOMImplementationRegistry::getDOMImplementation(gLS);
    if(!impl)
        return;
//		throw CException(GET_TEXT(ERR_XML_DOM_IMPLEMENTATION));
    if(parser == NULL)
        parser = new XercesDOMParser;

    XercesDOMParser* xmlparser = (XercesDOMParser*)parser;

    xmlparser->setValidationScheme(XercesDOMParser::Val_Never);
    xmlparser->setLoadExternalDTD(false);

    xmlparser->setDoNamespaces(false);
    xmlparser->setDoSchema(false);
    xmlparser->setValidationSchemaFullChecking(false);
    xmlparser->setCreateEntityReferenceNodes(false);
    xmlparser->setIncludeIgnorableWhitespace(false);

    xmlparser->resetDocumentPool();	//ÖØÖÃÎĵµ»º³å³Ø

    MemBufInputSource input((XMLByte*) xmlcontent.c_str(), xmlcontent.size(), "memory");
    xmlparser->parse(input);
    doc = xmlparser->getDocument();
    if(doc)
        itemElement = ((XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument*)doc)->getDocumentElement();	//¸³Óè¸ù½Úµã
    else
        return;
//		throw CException(boost::str(boost::format(GET_TEXT(ERR_PARSE_CONFIG_FILE)) % xmlcontent));

}
Example #6
0
void Generation::readGenerations(const string &file,
        vector<GenerationPtr> &generations) {
    XMLPlatformUtils::Initialize();
    XercesDOMParser parser;

    GenerationErrorHandler handler;
    parser.setErrorHandler(&handler);
    parser.setEntityResolver(&handler);

    parser.parse(file.c_str());

    DOMDocument *doc = parser.getDocument();
    DOMElement *root = doc->getDocumentElement();

    XMLCh tempStr[12];
    XMLString::transcode("generation", tempStr, 11);
    DOMNodeList *list = root->getElementsByTagName(tempStr);

    int length = list->getLength();
    for (int i = 0; i < length; ++i) {
        DOMElement *item = (DOMElement *)list->item(i);
        GenerationPtr generation(new Generation());
        generation->m_impl->m_owner = generation.get();
        generation->m_impl->getGeneration(item);
        generation->m_impl->m_idx = i;
        generations.push_back(generation);
    }
}
bool XMLSceneryReader::openFile(const char* fileName) {

	bool result = false;

	XercesDOMParser* parser = new XercesDOMParser;
    
	parser->setValidationScheme(XercesDOMParser::Val_Never);
	parser->setDoSchema(false);
	parser->setLoadExternalDTD(false);
	parser->setErrorHandler(new XMLSceneryErrorHandler);

	parser->parse(LocalFileInputSource(XMLString::transcode(fileName)));

	if(!parser->getErrorCount()) {

		m_root = parser->getDocument()->getFirstChild();
		m_node = m_root;

		result = true;

	}

	return result;

}
Example #8
0
static void
xsdproc (std::string const &schemadir, std::string const &input, std::string const &output)
{
  XercesDOMParser parser;
  parser.setExternalSchemaLocation ((
    "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul " + schemadir + "/xul.xsd          "
    "http://www.w3.org/1999/xhtml                                  " + schemadir + "/xul-html.xsd     "
    "http://www.w3.org/2000/10/xlink-ns                            " + schemadir + "/xml/xlink.xsd    "
    //"http://www.w3.org/2001/SMIL20/                                " + schemadir + "/smil/smil20.xsd  "
    "http://www.w3.org/2001/XInclude                               " + schemadir + "/xml/xinclude.xsd "
    "http://www.w3.org/2002/07/owl#                                " + schemadir + "/owl/owl.xsd      "
    "http://www.w3.org/XML/1998/namespace                          " + schemadir + "/xml/xml.xsd      "
  ).c_str ());
  parser.setCreateEntityReferenceNodes (true);
  parser.setDoNamespaces (true);
  parser.setDoSchema (true);
  parser.setDoXInclude (true);
  parser.setHandleMultipleImports (true);
  parser.setValidationSchemaFullChecking (true);
  parser.setValidationScheme (XercesDOMParser::Val_Always);

  error_handler handler;
  parser.setErrorHandler (&handler);

  parser.parse (input.c_str ());

  if (handler.failed)
    throw std::runtime_error ("validation failed for " + input);

  serialise (parser.getDocument (), output);
}
Example #9
0
// XSAnnotation methods
void XSAnnotation::writeAnnotation(DOMNode* node, ANNOTATION_TARGET targetType)
{
    XercesDOMParser *parser = new (fMemoryManager) XercesDOMParser(0, fMemoryManager);
    parser->setDoNamespaces(true);
    parser->setValidationScheme(XercesDOMParser::Val_Never);
    
    DOMDocument* futureOwner = (targetType == W3C_DOM_ELEMENT) ?
        ((DOMElement*)node)->getOwnerDocument() :
        (DOMDocument*)node;

    MemBufInputSource* memBufIS = new (fMemoryManager) MemBufInputSource
    (
        (const XMLByte*)fContents
        , XMLString::stringLen(fContents)*sizeof(XMLCh)
        , ""
        , false
        , fMemoryManager
    );
    memBufIS->setEncoding(XMLUni::fgXMLChEncodingString);

    try
    {        
        parser->parse(*memBufIS);
    }
    catch (const XMLException&)
    {
        // REVISIT:  should we really eat this?
    }

    DOMNode* newElem = futureOwner->importNode((parser->getDocument())->getDocumentElement(), true);
    node->insertBefore(newElem, node->getFirstChild());

    delete parser;
    delete memBufIS;
}
//
// domPrint  -  Dump the contents of a DOM node.
//              For debugging failures, when all else fails.
//                 Works recursively - initially called with a document node.
//
void ThreadParser::domPrint()
{
    printf("Begin DOMPrint ...\n");
    if (gRunInfo.dom)
    {
        try
        {
            XMLCh tempStr[100];
            XMLString::transcode("LS", tempStr, 99);
            DOMImplementation *impl          = DOMImplementationRegistry::getDOMImplementation(tempStr);
            DOMLSSerializer   *theSerializer = ((DOMImplementationLS*)impl)->createLSSerializer();
            DOMLSOutput       *theOutput     = ((DOMImplementationLS*)impl)->createLSOutput();
            XMLFormatTarget   *myFormTarget  = new StdOutFormatTarget();
            theOutput->setByteStream(myFormTarget);
            DOMNode           *doc           = fXercesDOMParser->getDocument();
            theSerializer->write(doc,theOutput);
            delete myFormTarget;
            theSerializer->release();
            theOutput->release();
        }
        catch (...)
        {
            // do nothing
        }
    }
    printf("End DOMPrint\n");
}
Example #11
0
// 解析TMS返回xml
bool  CTMSSensor::ParseXmlFromTMS(std::string &retXml,int &nRet)
{
	XercesDOMParser *ptrParser = new  XercesDOMParser;
	ptrParser->setValidationScheme(  XercesDOMParser::Val_Never );
	ptrParser->setDoNamespaces( true );
	ptrParser->setDoSchema( false );
	ptrParser->setLoadExternalDTD( false );
	InputSource* ptrInputsource = new  MemBufInputSource((XMLByte*)retXml.c_str(), retXml.size(), "bufId");

	try
	{
		ptrParser->parse(*ptrInputsource);
		DOMDocument* ptrDoc = ptrParser->getDocument();	

		// 读取ret节点
		DOMNodeList *ptrNodeList = ptrDoc->getElementsByTagName(C2X("ret"));
		if(ptrNodeList == NULL)
		{
			LOGIDFMT(ULOG_ERROR,ERROR_PARSE_MONITORSTATE_XML,"ParseXmlFromTMS:ret");
			return false;
		}
		else 
		{
			if(ptrNodeList->getLength() == 0)
			{
				LOGIDFMT(ULOG_ERROR,ERROR_PARSE_MONITORSTATE_XML,"ParseXmlFromTMS:ret");
				return false;
			}
			DOMNode* ptrNode = ptrNodeList->item(0);
			char* pstate =  XMLString::transcode(ptrNode->getFirstChild()->getNodeValue());
			std::string str_state = pstate;
			if(!str_state.empty())
			{
				nRet = atoi(str_state.c_str());
			}
			XMLString::release(&pstate);
			//LOGINFFMT("%s,%s\n",str_name.c_str(),str_state.c_str());
		}
	}
	catch(  XMLException& e )
	{
		char* message =  XMLString::transcode( e.getMessage() );
		XMLString::release( &message );
		LOGIDFMT(ULOG_ERROR,ERROR_PARSE_MONITORSTATE_XML,message);
		delete ptrParser;
		ptrInputsource = NULL;
		delete ptrInputsource;
		ptrParser = NULL;
	}


	delete ptrParser;
	delete ptrInputsource;
	ptrInputsource = NULL;
	ptrParser = NULL;
	return true;
}
bool 
CategoryTranslationLoader::loadTranslations( const MC2String& filename ) try {
   // load and parse file
   XercesDOMParser parser;
   parser.setValidationScheme( XercesDOMParser::Val_Auto );
   parser.setIncludeIgnorableWhitespace( false );

   parser.parse( filename.c_str() );

   if ( parser.getDocument() == NULL ) {
      return false;
   }

   loadTranslations( parser.getDocument() );

   return true;

} catch ( const XMLTool::Exception& e ) {
   // any xml exception here is bad.
   return false;
}
DOMDocument* DsaDataLoader::loadDataFile(string filename)
{

    XercesDOMParser* parser = new XercesDOMParser();
    parser->setValidationScheme(XercesDOMParser::Val_Always);    // optional.
    parser->setDoNamespaces(true);    // optional

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

    XmlPtr res =
        XmlResourceManager::getSingleton().create(
            filename,
            Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
    res.getPointer()->parseBy(parser);
    return parser->getDocument();
}
Example #14
0
void XMLRuntime::read(const string& filename, FreeAX25::Runtime::Configuration& config) {
    XercesDOMParser parser;
    parser.setValidationScheme(XercesDOMParser::Val_Always);
    parser.setDoNamespaces(true);
    parser.setDoSchema(true);
    parser.setDoXInclude(true);
    parser.setHandleMultipleImports(true);
    parser.setValidationSchemaFullChecking(true);
    parser.setCreateEntityReferenceNodes(false);
    parser.setIncludeIgnorableWhitespace(false);

    DOMTreeErrorReporter errReporter;
    parser.setErrorHandler(&errReporter);

    parser.parse(filename.c_str());

    if (errReporter.getSawErrors())
    	throw exception();

    // Now read configuration from the DOM Tree:
    XERCES_CPP_NAMESPACE::DOMDocument* doc = parser.getDocument();
    assert(doc != nullptr);

    auto rootElement = doc->getDocumentElement();
    auto configName = rootElement->getAttribute(toX("name"));
    config.setId(fmX(configName));

    { // Get settings:
		auto nodeList = rootElement->getElementsByTagName(toX("Settings"));
		if (nodeList->getLength() > 0)
			readSettings(
					"",
					static_cast<DOMElement*>(nodeList->item(0)),
					config.settings);
    }

    { // Get plugins:
		auto nodeList = rootElement->getElementsByTagName(toX("Plugins"));
		if (nodeList->getLength() > 0)
			readPlugins(
					"",
					static_cast<DOMElement*>(nodeList->item(0)),
					config.plugins);
    }
}
Example #15
0
DOMDocument* tsp::Tool::parserXml(string myxml) {
	if (!initXmlEngine() || myxml.empty())
		return NULL;

	XercesDOMParser* parser = new XercesDOMParser();
	parser->setValidationScheme(XercesDOMParser::Val_Always);
	parser->setDoNamespaces(true);    // optional

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

	try {
		MemBufInputSource src((const XMLByte*) myxml.c_str(), myxml.length(),
				"dummy", false);

		parser->parse(src);

	} catch (const XMLException& toCatch) {
		char* message = XMLString::transcode(toCatch.getMessage());
		cout << "Exception message is: \n" << message << "\n";
		XMLString::release(&message);
		return NULL;
	} catch (const DOMException& toCatch) {
		char* message = XMLString::transcode(toCatch.msg);
		cout << "Exception message is: \n" << message << "\n";
		XMLString::release(&message);
		return NULL;
	} catch (...) {
		cout << "Unexpected Exception \n";
		return NULL;
	}

	DOMDocument* doc;
	doc = parser->getDocument();

	delete errHandler;
	return doc;
}
Example #16
0
//initialize a ResultXML object using an existing xml file
ResultXML::ResultXML(const char *file)
{
    //sets-up for XML processing and handle any errors if unsuccessful
    try{
        XMLPlatformUtils::Initialize();
    }
    catch (XMLException &e){
        char *msg = XMLString::transcode(e.getMessage());
        XERCES_STD_QUALIFIER cerr << "Error During Initialization: " << endl << msg;
        XMLString::release(&msg);
    }
    catch (...){
        cerr << "Error Unknown Exception Encountered!" << endl;
    }

    //create a parser and set it to validate document but not load a DTD or use a schema
    XercesDOMParser *parser = new XercesDOMParser();
    parser->setValidationScheme(XercesDOMParser::Val_Always);
    parser->setDoSchema(false);
    parser->setLoadExternalDTD(false);

    try{
        //create unicode strings to for later use
        XMLCh *spdName = XMLString::transcode("speed_result");
        XMLCh *memName = XMLString::transcode("memory_result");
        XMLCh *sectName = XMLString::transcode("section_list");
        XMLCh *fname = XMLString::transcode(file);

        //set the save location, parse the file and retrieve the required nodes
        ftarget = new LocalFileFormatTarget(fname);
        parser->parse(file);
        doc = parser->getDocument();
        root = doc->getDocumentElement();

        DOMNodeList *nlist = root->getChildNodes();

        //go through the nodelist finding the top level child nodes and assign them to the right member variables
        for(XMLSize_t i=0; i<nlist->getLength(); i++){

            DOMNode *curNode = nlist->item(i);
            DOMElement *curElm;

            //safely check for element node before casting
            if(curNode->getNodeType() == DOMNode::ELEMENT_NODE){
                curElm = dynamic_cast<DOMElement*>(curNode);
            }

            //check the tag name and assign accordingly
            if(XMLString::equals(spdName, curElm->getTagName())){
                spdResult = curElm;
            }
            else if(XMLString::equals(memName, curElm->getTagName())){
                memResult = curElm;
            }
            else if(XMLString::equals(sectName, curElm->getTagName())){
                sectList = curElm;
            }
        }

        //release the memory occupied by the encoded strings
        XMLString::release(&spdName);
        XMLString::release(&memName);
        XMLString::release(&sectName);
        XMLString::release(&fname);
    }
    catch (const OutOfMemoryException&){

        XERCES_STD_QUALIFIER cerr << "Error Out of Memory Exception: " << XERCES_STD_QUALIFIER endl;
    }
    catch (const DOMException& e){

        XERCES_STD_QUALIFIER cerr << "Error DOMException Encountered Code:  " << e.code << XERCES_STD_QUALIFIER endl;
    }
    catch (...){

        XERCES_STD_QUALIFIER cerr << "Unknown Error Encountered, Could Not Create Document" << XERCES_STD_QUALIFIER endl;
    }

    delete parser;
}
bool ColladaFile::Load(LPCWSTR lpszFileName)
{
	if( PathFileExists( lpszFileName ) == FALSE )
	{
		std::wstring strMessage;
		strMessage = strMessage + L"Colladaファイル[" + lpszFileName + L"]が見つかりませんでした";
		MessageBox( NULL, strMessage.c_str(), L"ColladaFile::Load()", MB_OK | MB_ICONERROR );
		return false;
	}

	XercesDOMParser* domParser = new XercesDOMParser();

	domParser->setValidationScheme( AbstractDOMParser::Val_Auto );	// 構文が特殊な場合にのみ報告する
    domParser->setDoNamespaces( false );							// 名前空間処理はしない
    domParser->setDoSchema( false );								// スキーマ処理はしない
    domParser->setValidationSchemaFullChecking( false );			// 完全な構文のチェックはしない

	DomErrorReporter* errorHandler = new DomErrorReporter();
	domParser->setErrorHandler( errorHandler );

	bool bException = false;
	try
	{
		domParser->parse( (const XMLCh*)lpszFileName );
	}
	catch( const OutOfMemoryException& )
	{
		MessageBox( NULL, L"XMLファイルを処理中にメモリが不足しました", L"ColladaFile::Load()-OutOfMemoryException", MB_OK | MB_ICONERROR );
		bException = false;
	}
	catch( const XMLException& ex )
	{
		std::wstring strMessage = L"XMLファイルを処理中にエラーが発生しました\n\n";
		strMessage += (const wchar_t*)ex.getMessage();
		MessageBox( NULL, strMessage.c_str(), L"ColladaFile::Load()-XMLException", MB_OK | MB_ICONERROR );
		bException = false;
	}
	catch( const DOMException& ex )
	{
		std::wstring strMessage = L"XMLファイルを処理中にエラーが発生しました\n\n";
		XMLCh temp[2048];
		DOMImplementation::loadDOMExceptionMsg( ex.code, temp, 2047 );
		strMessage += StrX( temp ).getStr();
		MessageBox( NULL, strMessage.c_str(), L"ColladaFile::Load()-DOMException", MB_OK | MB_ICONERROR );
		bException = false;
	}
	catch( ... )
	{
		MessageBox( NULL, L"XMLファイルを処理中にエラーが発生しました", L"ColladaFile::Load()", MB_OK | MB_ICONERROR );
		bException = false;
	}

	bool bError = bException || errorHandler->HasError();
	if( bError == false )	// エラーが発生しなかった場合はドキュメントを処理する
	{
		CreateColladaObject( dynamic_cast<DOMNode*>(domParser->getDocument()) );
		
		if( colladaObject->ValidElements() == false )
		{
			std::wstring strMessage = L"読み込まれたCOLLADAファイルが不完全です\n\n";
			strMessage += colladaObject->GetErrorMessage();
			MessageBox( NULL, strMessage.c_str(), L"COLLADAファイルの読み込み", MB_OK | MB_ICONWARNING );
			bError = true;
		}
	}
	else
	{
		std::wstring strMessage;
		if( errorHandler->GetFatalErrorMessage().empty() == false )
		{
			strMessage += L"致命的なエラー\n";
			strMessage += errorHandler->GetFatalErrorMessage();
		}

		if( errorHandler->GetErrorMessage().empty() == false )
		{
			strMessage += L"エラー\n";
			strMessage += errorHandler->GetErrorMessage();
		}

		if( strMessage.empty() == false )	// エラーメッセージがある場合は表示する
		{
			MessageBox( NULL, strMessage.c_str(), L"ColladaFile::Load()", MB_OK | MB_ICONERROR );
		}
	}

	delete errorHandler;
	delete domParser;

	return bError == false;
}
Example #18
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 #19
0
bool XmlWorldParser::process_xml(const char* xmlFile) {

	try {
		XMLPlatformUtils::Initialize();
	} catch (const XMLException& toCatch) {
		char* message = XMLString::transcode(toCatch.getMessage());
		cout << "Error during initialization! :\n" << message << "\n";
		XMLString::release(&message);
		return 1;
	}

	XercesDOMParser* parser = new XercesDOMParser();
	parser->setValidationScheme(XercesDOMParser::Val_Always);
	parser->setDoNamespaces(true); // optional

	/**
	 * Configure parser error handling
	 */
	ErrorHandler* errHandler = (ErrorHandler*) new HandlerBase();
	//	ErrorHandler *errHandler =(ErrorHandler*) new DOMPrintErrorHandler();
	parser->setErrorHandler(errHandler);

	try {
		parser->parse(xmlFile);
	} catch (const XMLException& toCatch) {
		char* message = XMLString::transcode(toCatch.getMessage());
		cout << "Exception message is: \n" << message << "\n";
		XMLString::release(&message);
		return -1;
	} catch (const DOMException& toCatch) {
		char* message = XMLString::transcode(toCatch.msg);
		cout << "Exception message is: \n" << message << "\n";
		XMLString::release(&message);
		return -1;
	} catch (const SAXException& toCatch) {
		char* message = XMLString::transcode(toCatch.getMessage());
		cout << "Exception message is: " << message << "\n";
		XMLString::release(&message);
		return -1;
	} catch (const exception& toCatch) {
		cout << "Unexpected Exception \n" << toCatch.what() << endl;
		return -1;
	}

	/**
	 * Walk through the document, adding bodies and joints in their relative frames
	 */
	DOMDocument* doc = parser->getDocument();
	DOMTreeWalker* walker = doc->createTreeWalker(doc->getDocumentElement(),
			DOMNodeFilter::SHOW_ELEMENT, new BodiesInWorld(), true);
	/** Initial world frame */
	double transform[3] = { 0, 0, 0 };
	processNode(walker, transform);

	//TODO Ensure that I am cleaning up everything I need to
	/** Clean up no longer needed resources **/
	doc->release();
	delete errHandler;

	return true;
}
bool ServerConfigXMLReader::readServerConfig(const std::string & path) {

    this->serverConfig = ServerConfig();

    try {
        XMLPlatformUtils::Initialize();
    }  catch (const XMLException& toCatch) {

        char * message = XMLString::transcode(toCatch.getMessage());
        cout << "Error during initialization! :\n" << message << "\n";
        XMLString::release(&message);

        return false;
    }

    XercesDOMParser * parser = new XercesDOMParser();

    //parser->setValidationScheme(XercesDOMParser::Val_Auto);
    parser->setDoNamespaces(true);
    parser->setDoXInclude(true);
    //parser->setValidationScheme(XercesDOMParser::Val_Always);
  //  parser->setDoSchema(true);
  //  parser->setValidationSchemaFullChecking(true);

    XMLParseErrorReporter * xmlParseErrorReporter = new XMLParseErrorReporter();;
    parser->setErrorHandler(xmlParseErrorReporter);
    try {
        parser->parse(path.c_str());
    }  catch (const XMLException & toCatch) {
        char * message = XMLString::transcode(toCatch.getMessage());
        cout << "Exception message is: \n" << message << "\n";
        XMLString::release(&message);
        return false;
    }
    catch (const DOMException& toCatch) {
        char * message = XMLString::transcode(toCatch.msg);
        cout << "Exception message is: \n" << message << "\n";
        XMLString::release(&message);
        return false;
    }
    catch (...) {
        cout << "Unexpected Exception \n" ;
        return false;
    }

    DOMDocument * domDocument = parser->getDocument();
    removeBaseAttr(domDocument);

    // 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(0);

    XMLDOMErrorReporter * xmlDOMErrorReporter = new XMLDOMErrorReporter();
    DOMConfiguration * serializerConfig = theSerializer->getDomConfig();
    serializerConfig->setParameter(XMLUni::fgDOMErrorHandler, xmlDOMErrorReporter);

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

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

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

    if (serializerConfig->canSetParameter(XMLUni::fgDOMWRTBOM, false))
        serializerConfig->setParameter(XMLUni::fgDOMWRTBOM, false);
/*
    XMLFormatTarget * myFormTarget = new StdOutFormatTarget();
    theOutputDesc->setByteStream(myFormTarget);

    theSerializer->write(domDocument, theOutputDesc);
*/
    MemBufFormatTarget * myFormTarget = new MemBufFormatTarget();
    theOutputDesc->setByteStream(myFormTarget);

    theSerializer->write(domDocument, theOutputDesc);
/*
    XMLFormatTarget * myFormTarget2 = new StdOutFormatTarget();
    theOutputDesc->setByteStream(myFormTarget2);
    theSerializer->write(domDocument, theOutputDesc);
*/

    MemBufInputSource * memInput = new MemBufInputSource(myFormTarget->getRawBuffer(), myFormTarget->getLen(), path.c_str());
    XercesDOMParser * parser2 = new XercesDOMParser();
    
    parser2->setDoNamespaces(true);
    parser2->setDoXInclude(true);
  //  parser2->setValidationScheme(XercesDOMParser::Val_Always);
   // parser2->setDoSchema(true);
   // parser2->setValidationSchemaFullChecking(true);

    parser2->setErrorHandler(xmlParseErrorReporter);
    try {
        parser2->parse(*memInput);
    }  catch (const XMLException & toCatch) {
        char * message = XMLString::transcode(toCatch.getMessage());
        cout << "Exception message is: \n" << message << "\n";
        XMLString::release(&message);
        return false;
    }
    catch (const DOMException& toCatch) {
        char * message = XMLString::transcode(toCatch.msg);
        cout << "Exception message is: \n" << message << "\n";
        XMLString::release(&message);
        return false;
    }
    catch (...) {
        cout << "Unexpected Exception \n" ;
        return false;
    }

    DOMDocument * domDocument2 = parser2->getDocument();
    XMLNodeFilter * xmlNodeFilter = new XMLNodeFilter();
    DOMTreeWalker * domTreeWalker = domDocument->createTreeWalker(domDocument2, DOMNodeFilter::SHOW_ALL, xmlNodeFilter, true);

    this->serverConfig = extractServerConfig(domDocument2, domTreeWalker);

    domTreeWalker->release();
    delete xmlNodeFilter;
 

    delete xmlDOMErrorReporter;
    delete xmlParseErrorReporter;
    delete parser;

    XMLPlatformUtils::Terminate();

    return true;
}
Example #21
0
void CTibiaItem::refreshItemLists()
{
	if (!criticalSectionInitialized)
	{
		InitializeCriticalSection(&ItemsInitCriticalSection);
		criticalSectionInitialized = true;
	}
	EnterCriticalSection(&ItemsInitCriticalSection);
	if (itemListsFresh)
	{
		LeaveCriticalSection(&ItemsInitCriticalSection);
		return;
	}
	itemListsFresh = 1;
	if (!xmlInitialised)
	{
		XMLPlatformUtils::Initialize();
		xmlInitialised = 1;
	}

	XercesDOMParser *parser = new XercesDOMParser();
	try
	{
		int listNr, itemNr, rootNr;

		//reset all lists
		constCodeList.RemoveAll();
		foodList.RemoveAll();
		lootList.RemoveAll();
		itemList.RemoveAll();
		if (itemTree)
			delete itemTree;

		itemTree = new CTibiaTree(new CTibiaTreeBranchData("Root"));

		char pathBuf[2048];
		sprintf(pathBuf, "%s\\data\\tibiaauto-items.xml", CInstallPath::getInstallPath().c_str());
		parser->parse(pathBuf);
		DOMNode  *doc = parser->getDocument();
		for (rootNr = 0; rootNr < (int)doc->getChildNodes()->getLength(); rootNr++)
		{
			DOMNode *root = doc->getChildNodes()->item(rootNr);

			if (wcscmp(root->getNodeName(), L"item-definitions"))
				continue;
			for (listNr = 0; listNr < (int)root->getChildNodes()->getLength(); listNr++)
			{
				DOMNode *listNode = root->getChildNodes()->item(listNr);

				//ITEMS
				if (!wcscmp(listNode->getNodeName(), L"items"))
					//recursively add to itemTree from XML tree, works with older versions
					parseItemsBranch(listNode, itemTree);

				//FOOD
				if (!wcscmp(listNode->getNodeName(), L"foods"))
				{
					for (itemNr = 0; itemNr < (int)listNode->getChildNodes()->getLength(); itemNr++)
					{
						int attrNr;
						DOMNode *item = listNode->getChildNodes()->item(itemNr);
						if (wcscmp(item->getNodeName(), L"item"))
							continue;

						int objectId     = 0;
						int eatTime      = 0;
						char *objectName = NULL;

						for (attrNr = 0; attrNr < (int)item->getAttributes()->getLength(); attrNr++)
						{
							DOMNode *attrNode = item->getAttributes()->item(attrNr);
							if (!wcscmp(attrNode->getNodeName(), L"name"))
								objectName = CUtil::wc2c(attrNode->getNodeValue());
							if (!wcscmp(attrNode->getNodeName(), L"id"))
							{
								char *idTmp = CUtil::wc2c(attrNode->getNodeValue());
								sscanf(idTmp, "0x%x", &objectId);
								if (objectId == 0)
									sscanf(idTmp, "%d", &objectId);
								free(idTmp);
							}
							if (!wcscmp(attrNode->getNodeName(), L"time"))
							{
								char *idTmp = CUtil::wc2c(attrNode->getNodeValue());
								sscanf(idTmp, "%d", &eatTime);
								free(idTmp);
							}
						}
						if (!objectId || !objectName || !strlen(objectName))
						{
							if (objectName)
								free(objectName);
							continue;
						}

						foodList.Add(objectId, objectName, eatTime);
						if (objectName)
							free(objectName);
						//delete item;//wis
					}
				}

				//CONSTS
				//SECTION IS UNUSED, FOR CURRENT TIBIA see next section for loading from const file
				if (!wcscmp(listNode->getNodeName(), L"consts"))
				{
					for (itemNr = 0; itemNr < (int)listNode->getChildNodes()->getLength(); itemNr++)
					{
						int attrNr;
						DOMNode *item = listNode->getChildNodes()->item(itemNr);
						if (wcscmp(item->getNodeName(), L"const"))
							continue;

						int constValue  = 0;
						char *constCode = NULL;

						for (attrNr = 0; attrNr < (int)item->getAttributes()->getLength(); attrNr++)
						{
							DOMNode *attrNode = item->getAttributes()->item(attrNr);
							if (!wcscmp(attrNode->getNodeName(), L"code"))
								constCode = CUtil::wc2c(attrNode->getNodeValue());
							if (!wcscmp(attrNode->getNodeName(), L"value"))
							{
								char *idTmp = CUtil::wc2c(attrNode->getNodeValue());
								sscanf(idTmp, "0x%x", &constValue);
								if (constValue == 0)
									sscanf(idTmp, "%d", &constValue);
								free(idTmp);
							}
						}
						if (!constCode || !strlen(constCode))
						{
							if (constCode)
								free(constCode);
							continue;
						}

						int i, len;
						len = strlen(constCode);
						for (i = 0; i < len; i++)
							constCode[i] = tolower(constCode[i]);

						constCodeList.Add(constValue, constCode, 0);
						if (constCode)
							free(constCode);
						//delete item;//wis
					}
				}

				//LOOT
				//SECTION IS UNUSED, FOR CURRENT TIBIA
				if (!wcscmp(listNode->getNodeName(), L"looted"))
				{
					for (itemNr = 0; itemNr < (int)listNode->getChildNodes()->getLength(); itemNr++)
					{
						int attrNr;
						DOMNode *item = listNode->getChildNodes()->item(itemNr);
						if (wcscmp(item->getNodeName(), L"item"))
							continue;

						int objectId     = 0;
						char *objectName = NULL;

						for (attrNr = 0; attrNr < (int)item->getAttributes()->getLength(); attrNr++)
						{
							DOMNode *attrNode = item->getAttributes()->item(attrNr);
							if (!wcscmp(attrNode->getNodeName(), L"name"))
								objectName = CUtil::wc2c(attrNode->getNodeValue());
							if (!wcscmp(attrNode->getNodeName(), L"id"))
							{
								char *idTmp = CUtil::wc2c(attrNode->getNodeValue());
								sscanf(idTmp, "0x%x", &objectId);
								free(idTmp);
							}
						}
						if (!objectId || !objectName || !strlen(objectName))
						{
							if (objectName)
								free(objectName);
							continue;
						}
						lootList.Add(objectId, objectName, 0);
						if (objectName)
							free(objectName);
					}
				}
			}
		}

		//Create data lists from tree structure loaded by XML
		traverseTreeForItemList(itemTree, &itemList);
		if (lootList.GetCount() == 0)
			traverseTreeForLootList(itemTree, &lootList);                      // get loot from tree if not loaded from file

		sprintf(pathBuf, "%s\\data\\tibiaauto-consts.xml", CInstallPath::getInstallPath().c_str());
		OFSTRUCT lpOpen;
		if (OpenFile(pathBuf, &lpOpen, OF_EXIST) != HFILE_ERROR)
		{
			constCodeList.RemoveAll();

			delete parser;
			parser = new XercesDOMParser();
			parser->parse(pathBuf);
			doc = parser->getDocument();
			for (rootNr = 0; rootNr < (int)doc->getChildNodes()->getLength(); rootNr++)
			{
				DOMNode *root = doc->getChildNodes()->item(rootNr);

				if (wcscmp(root->getNodeName(), L"const-definitions"))
					continue;
				for (listNr = 0; listNr < (int)root->getChildNodes()->getLength(); listNr++)
				{
					DOMNode *listNode = root->getChildNodes()->item(listNr);


					//CONSTS
					if (!wcscmp(listNode->getNodeName(), L"consts"))
					{
						for (itemNr = 0; itemNr < (int)listNode->getChildNodes()->getLength(); itemNr++)
						{
							int attrNr;
							DOMNode *item = listNode->getChildNodes()->item(itemNr);
							if (wcscmp(item->getNodeName(), L"const"))
								continue;

							int constValue  = 0;
							char *constCode = NULL;

							for (attrNr = 0; attrNr < (int)item->getAttributes()->getLength(); attrNr++)
							{
								DOMNode *attrNode = item->getAttributes()->item(attrNr);
								if (!wcscmp(attrNode->getNodeName(), L"code"))
									constCode = CUtil::wc2c(attrNode->getNodeValue());
								if (!wcscmp(attrNode->getNodeName(), L"value"))
								{
									char *idTmp = CUtil::wc2c(attrNode->getNodeValue());
									sscanf(idTmp, "0x%x", &constValue);
									if (constValue == 0)
										sscanf(idTmp, "%d", &constValue);
									free(idTmp);
								}
							}
							if (!constCode || !strlen(constCode))
							{
								if (constCode)
									free(constCode);
								continue;
							}

							int i, len;
							len = strlen(constCode);
							for (i = 0; i < len; i++)
								constCode[i] = tolower(constCode[i]);

							constCodeList.Add(constValue, constCode, 0);
							if (constCode)
								free(constCode);
						}
					}
				}
			}
		}//if file tibiaauto-consts.xml exists
	}
	catch (...)
	{
		AfxMessageBox("Unable to load const/item definitions!");
		/*
		   AfxMessageBox("Debug Item Tree");
		   char buf[11111];
		   itemTree->toString(buf);
		   AfxMessageBox(buf);
		   AfxMessageBox("Debug Food");
		   foodList.toString(buf);
		   AfxMessageBox(buf);
		   AfxMessageBox("Debug Consts");
		   constCodeList.toString(buf);
		   AfxMessageBox(buf);
		 */
	}

	delete parser;
	LeaveCriticalSection(&ItemsInitCriticalSection);
}
	void InputManager::loadKeyMapping(const Ogre::String& filename)
	{
		using namespace XERCES_CPP_NAMESPACE;
		using XERCES_CPP_NAMESPACE::DOMDocument;
		using std::make_pair;

		XMLPlatformUtils::Initialize();
		XmlHelper::initializeTranscoder();

		XercesDOMParser* parser = new XercesDOMParser();
        parser->setValidationScheme(XercesDOMParser::Val_Always);    // optional.
        parser->setDoNamespaces(true);    // optional

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

		XMLCh* ALT = XMLString::transcode("AltChar");
		XMLCh* SHIFT = XMLString::transcode("ShiftChar");
		XMLCh* NORMAL = XMLString::transcode("NormalChar");
		XMLCh* DESCR = XMLString::transcode("KeyDescription");
		XMLCh* CODE = XMLString::transcode("KeyCode");
		XMLCh* KEY = XMLString::transcode("Key");
		
		XmlPtr res = 
			XmlResourceManager::getSingleton().create(
			filename, 
			ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
		res->parseBy(parser);
		DOMDocument* doc = parser->getDocument();
		DOMElement* dataDocumentContent = doc->getDocumentElement();

		DOMNodeList* keymaps = dataDocumentContent->getElementsByTagName(KEY);
		for (unsigned int idx = 0; idx < keymaps->getLength(); idx++)
		{
			DOMElement* key = static_cast<DOMElement*>(keymaps->item(idx));
			int keycode = XMLString::parseInt(key->getAttribute(CODE));

			const XMLCh* xmlch;

			xmlch = key->getAttribute(NORMAL);
			if (xmlch != NULL && XMLString::stringLen(xmlch) > 0)
			{
				CeGuiString s(XmlHelper::transcodeToString(xmlch)); 
				mKeyMapNormal.insert(make_pair(keycode, s[0]));
			}

			xmlch = key->getAttribute(ALT);
			if (xmlch != NULL && XMLString::stringLen(xmlch) > 0)
			{
				CeGuiString s(XmlHelper::transcodeToString(xmlch)); 
				mKeyMapAlt.insert(make_pair(keycode, s[0]));
			}

			xmlch = key->getAttribute(SHIFT);
			if (xmlch != NULL && XMLString::stringLen(xmlch) > 0)
			{
				CeGuiString s(XmlHelper::transcodeToString(xmlch)); 
				mKeyMapShift.insert(make_pair(keycode, s[0]));
			}

			xmlch = key->getAttribute(DESCR);
			mKeyNames.insert(make_pair(keycode, XmlHelper::transcodeToString(xmlch)));
		}

		XMLString::release(&ALT);
		XMLString::release(&SHIFT);
		XMLString::release(&NORMAL);
		XMLString::release(&CODE);
		XMLString::release(&DESCR);
		XMLString::release(&KEY);

		doc->release();
		XMLPlatformUtils::Terminate();

        //XmlResourceManager::getSingleton().remove(filename);
        //res.setNull();
	}
Example #23
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 #24
0
void ClsSettingsReader::parseBuffer(string strFileName)  {

#ifdef DEBUG_CLSSETTINGSREADER
    cout << "ClsSettingsReader::parseBuffer()" << endl;
#endif

    cout << "reading settings from: " << strFileName << endl;

    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;
	    return;
	}
	bXMLPlatformInitialized = true;
    }
    //--------------------


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

//    cout << __FILE__ << ":" << __LINE__ << endl;
    parser->setDoNamespaces(gDoNamespaces);
    ErrorHandler* errHandler = (ErrorHandler*) new HandlerBase();
    parser->setErrorHandler(errHandler);
//    cout << __FILE__ << ":" << __LINE__ << endl;

    bool errorsOccured = false;
    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;
	ClsSettingsReaderException clsSettingsReaderException(XMLString::transcode(e.getMessage()));
	errorsOccured = true;
	throw clsSettingsReaderException;
    } catch (const DOMException& e) {
	cerr << "An error occured during parsing (DOMException)\n   DMessage: " << XMLString::transcode(e.msg) << endl;
	ClsSettingsReaderException clsSettingsReaderException(XMLString::transcode(e.msg));
	errorsOccured = true;
	throw clsSettingsReaderException;
    } catch (const SAXException& e) {
	cerr << "An error occured during parsing (SAXException)\n   DMessage: " <<  XMLString::transcode(e.getMessage()) << endl;
	ClsSettingsReaderException clsSettingsReaderException(XMLString::transcode(e.getMessage()));
	errorsOccured = true;
	throw clsSettingsReaderException;
    } catch (...) {
	cerr << "An error occured during parsing\n " << endl;
	errorsOccured = true;
	ClsSettingsReaderException clsSettingsReaderException(ClsSettingsReaderException::PARSE_ERROR);
	throw clsSettingsReaderException;
    }

    if (errorsOccured){
	cerr << "An error occured during parsing\n " << endl;
	ClsSettingsReaderException clsSettingsReaderException(ClsSettingsReaderException::PARSE_ERROR);
	throw clsSettingsReaderException;
    }

    if (!errorsOccured) {
	DOMNode* dnIqrSetting;
	DOMNodeList* dnlstTemp;

	ddocIqrSetting = parser->getDocument();

	// first we have to find the top System node
	dnlstTemp = ddocIqrSetting->getElementsByTagName(XMLString::transcode((const char*)"iqrSetting"));

	dnlstTemp = ddocIqrSetting->getElementsByTagName(XMLString::transcode(ClsTagLibrary::iqrSettings()));




	if ( dnlstTemp->getLength() == 1){
	    dnIqrSetting = dnlstTemp->item(0);
	} else if ( dnlstTemp->getLength() < 1)	{
	    ClsSettingsReaderException clsSettingsReaderException(ClsSettingsReaderException::NO_IQRSETTING_NODE);
	    throw clsSettingsReaderException;
	}

	iSysSettingReaderState = PARSER_BUFFER_PARSED;
    }

    delete errHandler;
//     delete parser;
};
Example #25
0
/* Method to call to initisalize the parsing */
int XMLData::parseXML(string filePath) {
	try {
		XMLPlatformUtils::Initialize();
	} catch (const XMLException& toCatch) {
		char* message = XMLString::transcode(toCatch.getMessage());
		cout << "Error during initialization! :\n" << message << "\n";
		XMLString::release(&message);
		return 1;
	}

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

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

	try {
		parser->parse(filePath.c_str());
		DOMDocument* dom = parser->getDocument();
		XMLData::parseDOMNode(dom);
	} catch (const XMLException& e) {
		char* message = XMLString::transcode(e.getMessage());
		cout << "XMLException is: \n\t" << message << "\n";
		XMLString::release(&message);
		return 2;
	} catch (const DOMException& e) {
		char* message = XMLString::transcode(e.msg);
		cout << "DOMException is: \n\t" << message << "\n";
		XMLString::release(&message);
		return 3;
	} catch (const SAXException& e) {
		char* message = XMLString::transcode(e.getMessage());
		cout << "SAXException is: \n\t" << message << "\n";
		XMLString::release(&message);
		return 4;
	} catch (...) {
		cout << "Unexpected Exception \n";
		return 5;
	}

	delete parser;
	delete errHandler;

	XMLPlatformUtils::Terminate();

	if(hairTypeLength == -1) {
		hairTypeLength = nbBitsMin(hairTypes.size()-1);
	}
	if(limbTypeLength == -1) {
		limbTypeLength = nbBitsMin(limbTypes.size()-1);
	}
	if(mouthWidthTypeLength == -1) {
		mouthWidthTypeLength = nbBitsMin(mouthWidthTypes.size()-1);
	}
	if(teethTypeLength == -1) {
		teethTypeLength = nbBitsMin(teethTypes.size()-1);
	}

	return 0;
}
Example #26
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
        {
            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 DOMWriter
            XMLCh tempStr[100];
            XMLString::transcode("LS", tempStr, 99);
            DOMImplementation *impl          = DOMImplementationRegistry::getDOMImplementation(tempStr);
            DOMWriter         *theSerializer = ((DOMImplementationLS*)impl)->createDOMWriter();

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

            // plug in user's own filter
            if (gUseFilter)
            {
                // even we say to show attribute, but the DOMWriter
                // will not show attribute nodes to the filter as
                // the specs explicitly says that DOMWriter shall
                // NOT show attributes to DOMWriterFilter.
                //
                // 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();
            theSerializer->setErrorHandler(myErrorHandler);

            // set feature if the serializer supports the feature/mode
            if (theSerializer->canSetFeature(XMLUni::fgDOMWRTSplitCdataSections, gSplitCdataSections))
                theSerializer->setFeature(XMLUni::fgDOMWRTSplitCdataSections, gSplitCdataSections);

            if (theSerializer->canSetFeature(XMLUni::fgDOMWRTDiscardDefaultContent, gDiscardDefaultContent))
                theSerializer->setFeature(XMLUni::fgDOMWRTDiscardDefaultContent, gDiscardDefaultContent);

            if (theSerializer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, gFormatPrettyPrint))
                theSerializer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, gFormatPrettyPrint);

            if (theSerializer->canSetFeature(XMLUni::fgDOMWRTBOM, gWriteBOM))
                theSerializer->setFeature(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();

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

            //
            // do the serialization through DOMWriter::writeNode();
            //
            theSerializer->writeNode(myFormTarget, *doc);

            delete theSerializer;

            //
            // 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;

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

    XMLString::release(&gOutputEncoding);

    return retval;
}
int main(int argc, char **argv) {

	XSECCryptoKey				* key = NULL;
	DSIGKeyInfoX509				* keyInfoX509 = NULL;
	OpenSSLCryptoX509			* certs[128];
	int							certCount = 0;
	int							paramCount;
	bool						clearKeyInfo = false;

	// Initialise the XML system

	try {

		XMLPlatformUtils::Initialize();
#ifndef XSEC_NO_XALAN
		XPathEvaluator::initialize();
		XalanTransformer::initialize();
#endif
		XSECPlatformUtils::Initialise();

	}

	catch (const XMLException &e) {

		cerr << "Error during initialisation of Xerces" << endl;
		cerr << "Error Message = : "
		     << e.getMessage() << endl;

	}

	// Initialise OpenSSL
	ERR_load_crypto_strings();
	BIO * bio_err;
	
	if ((bio_err=BIO_new(BIO_s_file())) != NULL)
		BIO_set_fp(bio_err,stderr,BIO_NOCLOSE|BIO_FP_TEXT);

	if (argc < 2) {

		printUsage();
		exit (1);
	}
	
	paramCount = 1;

	while (paramCount < argc - 1) {

		// Run through all parameters

		if (stricmp(argv[paramCount], "--dsakey") == 0 || stricmp(argv[paramCount], "-d") == 0 ||
			stricmp(argv[paramCount], "--rsakey") == 0 || stricmp(argv[paramCount], "-r") == 0) {

			// DSA or RSA Key

			if (paramCount + 3 >= argc) {

				printUsage();
				exit (1);

			}

			if (key != 0) {

				cerr << "\nError loading RSA or DSA key - another key already loaded\n\n";
				printUsage();
				exit(1);

			}

			// Load the signing key
			// For now just read a particular file

			BIO * bioKey;
			if ((bioKey = BIO_new(BIO_s_file())) == NULL) {

				cerr << "Error opening private key file\n\n";
				exit (1);

			}

			if (BIO_read_filename(bioKey, argv[paramCount + 1]) <= 0) {

				cerr << "Error opening private key file\n\n";
				exit (1);

			}

			EVP_PKEY * pkey;
			pkey = PEM_read_bio_PrivateKey(bioKey,NULL,NULL,argv[paramCount + 2]);

			if (pkey == NULL) {

				cerr << "Error loading private key\n\n";
				ERR_print_errors(bio_err);
				exit (1);

			}

			if (stricmp(argv[paramCount], "--dsakey") == 0 || stricmp(argv[paramCount], "-d") == 0) {

				// Check type is correct

				if (pkey->type != EVP_PKEY_DSA) {
					cerr << "DSA Key requested, but OpenSSL loaded something else\n";
					exit (1);
				}

				// Create the XSEC OpenSSL interface
				key = new OpenSSLCryptoKeyDSA(pkey);
			}
			else {
				if (pkey->type != EVP_PKEY_RSA) {
					cerr << "RSA Key requested, but OpenSSL loaded something else\n";
					exit (1);
				}
				key = new OpenSSLCryptoKeyRSA(pkey);
			}

			EVP_PKEY_free(pkey);
			BIO_free(bioKey);

			paramCount += 3;
			
		} /* argv[1] = "dsa/rsa" */


		else if (stricmp(argv[paramCount], "--x509cert") == 0 || stricmp(argv[paramCount], "-x") == 0) {

			// X509Data keyInfo

			if (paramCount + 2 >= argc) {

				printUsage();
				exit (1);

			}

			// Load the signing key
			// For now just read a particular file

			BIO * bioX509;

			if ((bioX509 = BIO_new(BIO_s_file())) == NULL) {

				cerr << "Error opening file\n\n";
				exit (1);

			}

			if (BIO_read_filename(bioX509, argv[paramCount + 1]) <= 0) {

				cerr << "Error opening X509 Certificate " << argv[paramCount + 1] << "\n\n";
				exit (1);

			}

			X509 * x
				;
			x = PEM_read_bio_X509_AUX(bioX509,NULL,NULL,NULL);

			if (x == NULL) {

				cerr << "Error loading certificate key\n\n";
				ERR_print_errors(bio_err);
				exit (1);

			}

			// Create the XSEC OpenSSL interface - used only to translate to Base64

			certs[certCount++] = new OpenSSLCryptoX509(x);
			X509_free(x);
			BIO_free(bioX509);

			paramCount += 2;
			
		} /* argv[1] = "--x509cert" */

		else if (stricmp(argv[paramCount], "--hmackey") == 0 || stricmp(argv[paramCount], "-h") == 0) {

			OpenSSLCryptoKeyHMAC * hmacKey = new OpenSSLCryptoKeyHMAC();
			hmacKey->setKey((unsigned char *) argv[paramCount + 1], strlen(argv[paramCount + 1]));
			key = hmacKey;
			paramCount += 2;

		}

		else if (stricmp(argv[paramCount], "--clearkeys") == 0 || stricmp(argv[paramCount], "-c") == 0) {

			clearKeyInfo = true;
			paramCount += 1;

		}
		else {

			printUsage();
			exit(1);

		}

	}

	// Create and set up the parser

	XercesDOMParser * parser = new XercesDOMParser;
	
	parser->setDoNamespaces(true);
	parser->setCreateEntityReferenceNodes(true);

	// Now parse out file

	bool errorsOccured = false;
	int errorCount = 0;
    try
    {
    	parser->parse(argv[argc - 1]);
        errorCount = parser->getErrorCount();
        if (errorCount > 0)
            errorsOccured = true;
    }

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


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

	if (errorsOccured) {

		cout << "Errors during parse" << endl;
		exit (1);

	}

	/*

		Now that we have the parsed file, get the DOM document and start looking at it

	*/
	
	DOMNode *doc;		// The document that we parsed

	doc = parser->getDocument();
	DOMDocument *theDOM = parser->getDocument();

	// Find the signature node
	
	DOMNode *sigNode = findDSIGNode(doc, "Signature");

	// Create the signature checker

	if (sigNode == 0) {

		cerr << "Could not find <Signature> node in " << argv[argc-1] << endl;
		exit(1);
	}


	XSECProvider prov;
	DSIGSignature * sig = prov.newSignatureFromDOM(theDOM, sigNode);

	int i;

	try {
		sig->load();
		if (clearKeyInfo == true)
			sig->clearKeyInfo();
		if (key != NULL)
			sig->setSigningKey(key);
		sig->sign();

		// Add any KeyInfo elements

		if (certCount > 0) {

			// Have some certificates - see if there is already an X509 list
			DSIGKeyInfoList * kiList = sig->getKeyInfoList();
			int kiSize = kiList->getSize();

			for (i = 0; i < kiSize; ++i) {

				if (kiList->item(i)->getKeyInfoType() == DSIGKeyInfo::KEYINFO_X509) {
					keyInfoX509 = (DSIGKeyInfoX509 *) kiList->item(i);
					break;
				}
			}

			if (keyInfoX509 == 0) {

				// Not found - need to create
				keyInfoX509 = sig->appendX509Data();

			}

			for (i = 0; i < certCount; ++i) {

				keyInfoX509->appendX509Certificate(certs[i]->getDEREncodingSB().rawCharBuffer());

			}

		} /* certCount > 0 */
	}

	catch (XSECException &e) {
		cerr << "An error occured during signature verification\n   Message: "
		<< e.getMsg() << endl;
		errorsOccured = true;
		exit (1);
	}

	// Print out the result

	DOMPrintFormatTarget* formatTarget = new DOMPrintFormatTarget();
	
    const XMLCh* encNameStr = XMLString::transcode("UTF-8");
    DOMNode *aNode = doc->getFirstChild();
    if (aNode->getNodeType() == DOMNode::ENTITY_NODE)
    {
        const XMLCh* aStr = ((DOMEntity *)aNode)->getEncoding();
        if (!strEquals(aStr, ""))
        {
            encNameStr = aStr;
        }
    }
    unsigned int lent = XMLString::stringLen(encNameStr);
    gEncodingName = new XMLCh[lent + 1];
    XMLString::copyNString(gEncodingName, encNameStr, lent);
    gEncodingName[lent] = 0;

	
	
	gFormatter = new XMLFormatter("UTF-8", formatTarget,
                                          XMLFormatter::NoEscapes, gUnRepFlags);

	cout << doc;

	prov.releaseSignature(sig);
	return 0;
}
Example #28
0
//-----------------------------------------------------------------------------
// Purpose: load up a project and parse it
//-----------------------------------------------------------------------------
bool CVCProjConvert::LoadProject( const char *project )
{
#ifdef _WIN32
	HRESULT hr;
	IXMLDOMDocument *pXMLDoc=NULL;

	hr = ::CoCreateInstance(CLSID_DOMDocument, 
							NULL, 
							CLSCTX_INPROC_SERVER, 
							IID_IXMLDOMDocument, 
							(void**)&pXMLDoc);

	if (FAILED(hr))
	{
		Msg ("Cannot instantiate msxml2.dll\n");
		Msg ("Please download the MSXML run-time (url below)\n");
		Msg ("http://msdn.microsoft.com/downloads/default.asp?url=/downloads/sample.asp?url=/msdn-files/027/001/766/msdncompositedoc.xml\n");
		return false;
	}

	VARIANT_BOOL vtbool;
	_variant_t bstrProject(project);

	pXMLDoc->put_async( VARIANT_BOOL(FALSE) );
	hr = pXMLDoc->load(bstrProject,&vtbool);
	if (FAILED(hr) || vtbool==VARIANT_FALSE)
	{
		Msg ("Could not open %s.\n", bstrProject);
		pXMLDoc->Release();
		return false;
	} 
#elif _LINUX
	XercesDOMParser* parser = new XercesDOMParser();
        parser->setValidationScheme(XercesDOMParser::Val_Always);    // optional.
        parser->setDoNamespaces(true);    // optional

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

        try {
            parser->parse(project);
        }
        catch (const XMLException& toCatch) {
            char* message = XMLString::transcode(toCatch.getMessage());
            Error( "Exception message is: %s\n", message );    
            XMLString::release(&message);
            return;
        }
        catch (const DOMException& toCatch) {
            char* message = XMLString::transcode(toCatch.msg);
            Error( "Exception message is: %s\n", message );    
            XMLString::release(&message);
            return;
        }
        catch (...) {
            Error( "Unexpected Exception \n" );
            return;
        }
	
	DOMDocument *pXMLDoc = parser->getDocument();
#endif

	ExtractProjectName( pXMLDoc );
	if ( !m_Name.IsValid() )
	{
		Msg( "Failed to extract project name\n" );
		return false;
	}
	char baseDir[ MAX_PATH ];
	Q_ExtractFilePath( project, baseDir, sizeof(baseDir) );
	Q_StripTrailingSlash( baseDir );
	m_BaseDir = baseDir;

	ExtractConfigurations( pXMLDoc );
	if ( m_Configurations.Count() == 0 )
	{
		Msg( "Failed to find any configurations to load\n" );
		return false;
	}

	ExtractFiles( pXMLDoc );

#ifdef _WIN32
	pXMLDoc->Release();
#elif _LINUX
	delete pXMLDoc;
	delete errHandler;
#endif

	m_bProjectLoaded = true;
	return true;
}
//=======================================================================
void geometryLoader::loadXML(std::string configFile)
{
    // Initialize XERCES-C
    try
    {
        XMLPlatformUtils::Initialize();
    }
    catch(const XMLException &toCatch)
    {
        XERCES_STD_QUALIFIER cerr << "Error during Xerces-c Initialization.\n"
                << "  Exception message:"
                << toCatch.getMessage() << XERCES_STD_QUALIFIER endl;
        exit(-1);
    }

    struct stat fileStatus;
    int returnStatus = stat(configFile.c_str(), &fileStatus);
    if( returnStatus == ENOENT )
    {
        ss_.str("") ; ss_ << "ABORT: Path to " << configFile << " does not exist, or path is an empty string." ;
        STDLINE(ss_.str(),ACRed) ;
        exit(-1) ;
    }
    else if( returnStatus == ENOTDIR )
    {
        ss_.str("") ; ss_ << "ABORT: A component of the path of " << configFile << " is not a directory.";
        STDLINE(ss_.str(),ACRed) ;
        exit(-1) ;
    }
    else if( returnStatus == ELOOP )
    {
        ss_.str("") ; ss_ << "ABORT: Too many symbolic links encountered while traversing the path to " << configFile;
        STDLINE(ss_.str(),ACRed) ;
        exit(-1) ;
    }
    else if( returnStatus == EACCES )
    {
        ss_.str("") ; ss_ << "ABORT: Permission denied to read " << configFile;
        STDLINE(ss_.str(),ACRed) ;
        exit(-1) ;
    }
    else if( returnStatus == ENAMETOOLONG )
    {
        ss_.str("") ; ss_ << "ABORT: Cannot read " << configFile;
        STDLINE(ss_.str(),ACRed) ;
        exit(-1) ;
    }
    else if( returnStatus == -1  )
    {
        ss_.str("") ; ss_ << "ABORT: Could not find configuration file "
                << "'"
                << configFile
                << "'!";
        STDLINE(ss_.str(),ACRed) ;
        exit(-1) ;
    }

    static XercesDOMParser::ValSchemes gValScheme = XercesDOMParser::Val_Auto;   // gValScheme = XercesDOMParser::Val_Never;
    // gValScheme = XercesDOMParser::Val_Auto;
    // gValScheme = XercesDOMParser::Val_Always;

    XercesDOMParser *parser = new XercesDOMParser();
    parser->setValidationScheme(gValScheme);

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

    try
    {
        parser->parse(configFile.c_str());
    }
    catch (const OutOfMemoryException&)
    {
        STDLINE("F A T A L   E R R O R (A): ",ACRed) ;
        XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl;
        exit(-1) ;
    }
    catch (const XMLException& e)
    {
        STDLINE("F A T A L   E R R O R (B): ",ACRed) ;
        XERCES_STD_QUALIFIER cerr << "An error occurred during parsing\n   Message: "
                << xercesc::XMLString::transcode(e.getMessage()) << XERCES_STD_QUALIFIER endl;
        exit(-1) ;
    }

    catch (const DOMException& e)
    {
        STDLINE("F A T A L   E R R O R (C): ",ACRed) ;
        const unsigned int maxChars = 2047;
        XMLCh errText[maxChars + 1];

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

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

        exit(-1) ;
    }

    catch (...)
    {
        STDLINE("F A T A L   E R R O R (D): ",ACRed) ;
        XERCES_STD_QUALIFIER cerr << "An error occurred during parsing\n " << XERCES_STD_QUALIFIER endl;
        exit(-1) ;
    }

    STDLINE("Configuration successfully parsed",ACGreen) ;

    DOMDocument * xmlDoc  = parser->getDocument();
    testBeamGeometryXml_  = xmlDoc->getDocumentElement();

    if( !testBeamGeometryXml_ )
    {
        STDLINE("F A T A L   E R R O R: ",ACRed) ;
        XERCES_STD_QUALIFIER cerr << "Empty configuration file\n " << XERCES_STD_QUALIFIER endl;
        XERCES_STD_QUALIFIER cerr << "This should never occur, the parser should have already detected this error!\n " << XERCES_STD_QUALIFIER endl;
        exit(-1) ;
    }

    theGeometry_->setGeometryFileName(configFile);
}
//------------------------------------------------------------------------
//
//  parse   - This is the method that is invoked by the rest of
//            the test program to actually parse an XML file.
//
//------------------------------------------------------------------------
int ThreadParser::parse(int fileNum)
{
    MemBufInputSource *mbis = 0;
    InFileInfo        *fInfo = &gRunInfo.files[fileNum];
    bool              errors = false;

    fCheckSum = 0;

    if (gRunInfo.inMemory) {
        mbis = new  MemBufInputSource((const XMLByte *) fInfo->fileContent,
                                       fInfo->fileSize,
                                       fInfo->uFileName,
                                       false);
    }

    try
    {
        if (gRunInfo.dom) {
            // Do a DOM parse
            fXercesDOMParser->resetDocumentPool();
            if (gRunInfo.inMemory)
                fXercesDOMParser->parse(*mbis);
            else
                fXercesDOMParser->parse(fInfo->fileName);
            fDoc = fXercesDOMParser->getDocument();
            domCheckSum(fDoc);
        }
        else if (gRunInfo.sax) {
            // Do a SAX1 parse
            if (gRunInfo.inMemory)
                fSAXParser->parse(*mbis);
            else
                fSAXParser->parse(fInfo->fileName);
        }
        else {
            // Do a SAX2 parse
            if (gRunInfo.inMemory)
                fSAX2Parser->parse(*mbis);
            else
                fSAX2Parser->parse(fInfo->fileName);
        }
    }
    catch (const OutOfMemoryException&)
    {
	    fprintf(stderr, " during parsing: %s\n OutOfMemoryException.\n", fInfo->fileName);
	    errors = true;
    }
    catch (const XMLException& e)
    {
        char *exceptionMessage = XMLString::transcode(e.getMessage());
        fprintf(stderr, " during parsing: %s\n Exception message is: %s\n",
            fInfo->fileName, exceptionMessage);
        XMLString::release(&exceptionMessage);
        errors = true;
    }
    catch (const DOMException& toCatch)
    {
        fprintf(stderr, " during parsing: %s\n DOMException code is: %i\n",
            fInfo->fileName, toCatch.code);
        errors = true;
    }
    catch (const SAXParseException& e)
    {
        char *exceptionMessage = XMLString::transcode(e.getMessage());
        fprintf(stderr, " during parsing: %s\n Exception message is: %s\n",
            fInfo->fileName, exceptionMessage);
        XMLString::release(&exceptionMessage);
        errors = true;
    }
    catch (...)
    {
        fprintf(stderr, "Unexpected exception during parsing\n");
        errors = true;
    }

    delete mbis;
    if (errors) {
        fflush(stderr);
        return 0;  // if errors occurred, return zero as if checksum = 0;
    }
    return fCheckSum;
}