예제 #1
0
파일: xsdproc.cpp 프로젝트: pippijn/xul
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);
}
	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();
	}
예제 #3
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));

}
예제 #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;
}
예제 #5
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;
}
예제 #6
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;
}
예제 #7
0
// ---------------------------------------------------------------------------
//  DOM Parser
// ---------------------------------------------------------------------------
int TestInit4DOM(const char* xmlFile, bool gDoNamespaces, bool gDoSchema, bool gSchemaFullChecking, Teststate theState)
{
    TESTINITPRE;
    XercesDOMParser* parser = new XercesDOMParser;
    parser->setDoNamespaces(gDoNamespaces);
    parser->setDoSchema(gDoSchema);
    parser->setValidationSchemaFullChecking(gSchemaFullChecking);
    TESTINITPOST;
}
예제 #8
0
Parser* parseHTML(std::string contents) {
  try {
    XMLPlatformUtils::Initialize();
  } catch (const XMLException& toCatch) {
    char* msg = XMLString::transcode(toCatch.getMessage());
    cout << "INIT_ERR:" << endl;
    cout << msg << endl;
    XMLString::release(&msg);
    return NULL;
  }

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

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

  try {
		MemBufInputSource xml((const XMLByte*)contents.c_str(), contents.size(), "html", false);
    parser->parse(xml);
		parser->adoptDocument();
		delete parser;
		delete err;
		XMLPlatformUtils::Terminate();
		return parser;
  } catch (const XMLException &toCatch) {
    char* msg = XMLString::transcode(toCatch.getMessage());
    cout << "XML_ERR: ";
    cout << msg << endl;
    XMLString::release(&msg);
    return parser;
  } catch (const DOMException &toCatch) {
    char* msg = XMLString::transcode(toCatch.getMessage());
    cout << "DOM_ERR: ";
    cout << msg << endl;
    XMLString::release(&msg);
    return parser;
  } catch (const SAXException &toCatch) {
		char* msg = XMLString::transcode(toCatch.getMessage());
		cout << "SAX_ERR: ";
		cout << msg << endl;
		XMLString::release(&msg);
		return parser;
	} catch (...) {
		cout << "!UNKNOWN_ERR!" << endl;
		return parser;
	}

  delete parser;
  delete err;

  XMLPlatformUtils::Terminate();

  return NULL;
}
예제 #9
0
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();
}
예제 #10
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);
    }
}
int myEppParser (char* xsdPath, char* xmlPath)
{
	XMLPlatformUtils::Initialize();  // Initialize Xerces infrastructure
	XercesDOMParser parser;

	ParserErrorHandler parserErrorHandler;

	parser.setErrorHandler(&parserErrorHandler);

	// Enable schema processing.
	parser.setDoSchema(xsdValidationOn);

	// parser.setErrorHandler(&parserErrorHandler);
	parser.setValidationScheme(XercesDOMParser::Val_Auto);
	parser.setDoNamespaces(namespaceParsing);

	parser.cacheGrammarFromParse(true);
	// Let's preparse the schema grammar (.xsd) and cache it.
	loadXSD(xsdPath, &parser);
	validateXMLs(xmlPath, &parser);
	return 0;
}
예제 #12
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;
}
// ---------------------------------------------------------------------------
int
main(int argc, const char** argv)
{
   try
     {
       XMLPlatformUtils::Initialize();
     }
   catch(const XMLException& e)
     {
       StrX tmp_e(e.getMessage());
       cerr << "Xerces initialization error: " << tmp_e.localForm() << endl;
       return 2;
     }
   // check command line for arguments
   if ( argc < 1 )
     {
       cerr << "usage: schema-check <xml-file> [<schema-file> ...]" << endl;
       return 3;
     }
   XercesDOMParser *parser = new XercesDOMParser;
   DOMTreeErrorReporter *errReporter = new DOMTreeErrorReporter();
   parser->setErrorHandler(errReporter);
   parser->setDoNamespaces(true);
   parser->setCreateEntityReferenceNodes(true);
   parser->useCachedGrammarInParse(true);
   if ( argc > 2 )
     {
       parser->setDoSchema(true);
       parser->setDoValidation(true);
       parser->setValidationSchemaFullChecking(true);
       for ( int i = 2; i < argc; i++ )
         {

           if ( parser->loadGrammar(argv[i], Grammar::SchemaGrammarType, true) == 0 )
             {
               cerr << "Error loading grammar " << std::string(argv[i]) << endl;
               return 4;
             }
         }
     }
   bool errorsOccured = true;
   try
     {
       parser->parse(argv[1]);
       errorsOccured = false;
     }
   catch ( const OutOfMemoryException& )
     {
       cerr << "Out of memory exception." << endl;
     }
   catch ( const XMLException& e )
     {
       cerr << "An error occurred during parsing" << endl
            << "    Message: " << StrX(e.getMessage()) << endl;
     }
   catch ( const DOMException& e )
     {
       const unsigned int maxChars = 2047;
       XMLCh errText[maxChars + 1];
       cerr << endl
            << "DOM Error during parsing: '" << std::string(argv[1]) << "'" << endl
            << "DOM Exception code is: " << e.code << endl;
       if ( DOMImplementation::loadDOMExceptionMsg(e.code, errText, maxChars) )
         cerr << "Message is: " << StrX(errText) << endl;
     }
   catch (...)
     {
       cerr << "An error occurred during parsing." << endl;
     }
   return errorsOccured ? 1 : 0;
}
예제 #14
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;
 }
예제 #15
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;
}
예제 #16
0
파일: cipher.cpp 프로젝트: 12019/svn.gov.pt
int evaluate(int argc, char ** argv) {
	
	char					* filename = NULL;
	char					* outfile = NULL;
	unsigned char			* keyStr = NULL;
	bool					doDecrypt = true;
	bool					errorsOccured = false;
	bool					doDecryptElement = false;
	bool					useInteropResolver = false;
	bool					encryptFileAsData = false;
	bool					parseXMLInput = true;
	bool					doXMLOutput = false;
	bool					isXKMSKey = false;
	XSECCryptoKey			* kek = NULL;
	XSECCryptoKey			* key = NULL;
	int						keyLen = 0;
	encryptionMethod		kekAlg = ENCRYPT_NONE;
	encryptionMethod		keyAlg = ENCRYPT_NONE;
	DOMDocument				*doc;
	unsigned char			keyBuf[24];
	XMLFormatTarget			*formatTarget ;

#if defined(_WIN32) && defined (XSEC_HAVE_WINCAPI)
	HCRYPTPROV				win32DSSCSP = 0;		// Crypto Providers
	HCRYPTPROV				win32RSACSP = 0;

	CryptAcquireContext(&win32DSSCSP, NULL, NULL, PROV_DSS, CRYPT_VERIFYCONTEXT);
	CryptAcquireContext(&win32RSACSP, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);

#endif

	if (argc < 2) {

		printUsage();
		return 2;
	}

	// Run through parameters
	int paramCount = 1;

	while (paramCount < argc - 1) {

		if (_stricmp(argv[paramCount], "--decrypt-element") == 0 || _stricmp(argv[paramCount], "-de") == 0) {
			paramCount++;
			doDecrypt = true;
			doDecryptElement = true;
			doXMLOutput = true;
			parseXMLInput = true;
		}
		else if (_stricmp(argv[paramCount], "--interop") == 0 || _stricmp(argv[paramCount], "-i") == 0) {
			// Use the interop key resolver
			useInteropResolver = true;
			paramCount++;
		}
		else if (_stricmp(argv[paramCount], "--encrypt-file") == 0 || _stricmp(argv[paramCount], "-ef") == 0) {
			// Use this file as the input
			doDecrypt = false;
			encryptFileAsData = true;
			doXMLOutput = true;
			parseXMLInput = false;
			paramCount++;
		}
		else if (_stricmp(argv[paramCount], "--encrypt-xml") == 0 || _stricmp(argv[paramCount], "-ex") == 0) {
			// Us this file as an XML input file
			doDecrypt = false;
			encryptFileAsData = false;
			doXMLOutput = true;
			parseXMLInput = true;
			paramCount++;
		}
		else if (_stricmp(argv[paramCount], "--out-file") == 0 || _stricmp(argv[paramCount], "-o") == 0) {
			if (paramCount +2 >= argc) {
				printUsage();
				return 1;
			}
			paramCount++;
			outfile = argv[paramCount];
			paramCount++;
		}
		else if (_stricmp(argv[paramCount], "--xkms") == 0 || _stricmp(argv[paramCount], "-x") == 0) {
			paramCount++;
			isXKMSKey = true;
		}

#if defined (XSEC_HAVE_WINCAPI)
		else if (_stricmp(argv[paramCount], "--wincapi") == 0 || _stricmp(argv[paramCount], "-w") == 0) {
			// Use the interop key resolver
			WinCAPICryptoProvider * cp = new WinCAPICryptoProvider();
			XSECPlatformUtils::SetCryptoProvider(cp);
			paramCount++;
		}
#endif
#if defined (XSEC_HAVE_NSS)
		else if (_stricmp(argv[paramCount], "--nss") == 0 || _stricmp(argv[paramCount], "-n") == 0) {
			// NSS Crypto Provider
			NSSCryptoProvider * cp = new NSSCryptoProvider();
			XSECPlatformUtils::SetCryptoProvider(cp);
			paramCount++;
		}
#endif
		else if (_stricmp(argv[paramCount], "--key") == 0 || _stricmp(argv[paramCount], "-k") == 0) {

			// Have a key!
			paramCount++;
			bool isKEK = false;
			XSECCryptoSymmetricKey::SymmetricKeyType loadKeyAs =
				XSECCryptoSymmetricKey::KEY_NONE;

			if (_stricmp(argv[paramCount], "kek") == 0) {
				isKEK = true;
				paramCount++;
				if (paramCount >= argc) {
					printUsage();
					return 2;
				}
			}

			if (_stricmp(argv[paramCount], "3DES") == 0 ||
				_stricmp(argv[paramCount], "AES128") == 0 ||
				_stricmp(argv[paramCount], "AES192") == 0 ||
				_stricmp(argv[paramCount], "AES256") == 0 ||
				_stricmp(argv[paramCount], "AES128-GCM") == 0 ||
				_stricmp(argv[paramCount], "AES192-GCM") == 0 ||
				_stricmp(argv[paramCount], "AES256-GCM") == 0) {
				
				if (paramCount +2 >= argc) {
					printUsage();
					return 2;
				}

				switch(argv[paramCount][4]) {
				case '\0' :
					keyLen = 24;
					loadKeyAs = XSECCryptoSymmetricKey::KEY_3DES_192;
					keyAlg = ENCRYPT_3DES_CBC;
					break;
				case '2' :
					keyLen = 16;
					loadKeyAs = XSECCryptoSymmetricKey::KEY_AES_128;
					if (isKEK) {
						kekAlg = ENCRYPT_KW_AES128;
					}
					else if (strlen(argv[paramCount]) == 6) {
						keyAlg = ENCRYPT_AES128_CBC;
					}
                    else {
                        keyAlg = ENCRYPT_AES128_GCM;
                    }
					break;
				case '9' :
					keyLen = 24;
					loadKeyAs = XSECCryptoSymmetricKey::KEY_AES_192;
					if (isKEK) {
						kekAlg = ENCRYPT_KW_AES192;
					}
					else if (strlen(argv[paramCount]) == 6) {
						keyAlg = ENCRYPT_AES192_CBC;
					}
                    else {
                        keyAlg = ENCRYPT_AES192_GCM;
                    }
					break;
				case '5' :
					keyLen = 32;
					loadKeyAs = XSECCryptoSymmetricKey::KEY_AES_256;
					if (isKEK) {
						kekAlg = ENCRYPT_KW_AES256;
					}
					else if (strlen(argv[paramCount]) == 6) {
						keyAlg = ENCRYPT_AES256_CBC;
					}
                    else {
                        keyAlg = ENCRYPT_AES256_GCM;
                    }
					break;
				}

				paramCount++;
				unsigned char keyStr[64];
				if (strlen(argv[paramCount]) > 64) {
					cerr << "Key string too long\n";
					return 2;
				}
				XSECCryptoSymmetricKey * sk = 
					XSECPlatformUtils::g_cryptoProvider->keySymmetric(loadKeyAs);

				if (isXKMSKey) {
					unsigned char kbuf[XSEC_MAX_HASH_SIZE];
					CalculateXKMSKEK((unsigned char *) argv[paramCount], (int) strlen(argv[paramCount]), kbuf, XSEC_MAX_HASH_SIZE);
					sk->setKey(kbuf, keyLen);
				}
				else {
					memset(keyStr, 0, 64);
					strcpy((char *) keyStr, argv[paramCount]);
					sk->setKey(keyStr, keyLen);
				}
				paramCount++;
				if (isKEK)
					kek = sk;
				else
					key = sk;
			}


#if defined (XSEC_HAVE_OPENSSL)

			else if (_stricmp(argv[paramCount], "RSA") == 0) {
				// RSA private key file

				if (paramCount + 3 >= argc) {

					printUsage();
					return 2;

				}

				if (!isKEK) {
					cerr << "RSA private keys may only be KEKs\n";
					return 2;
				}

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

					cerr << "Error opening private key file\n\n";
					return 1;

				}

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

					cerr << "Error opening private key file\n\n";
					return 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";
					return 1;

				}

				kek = new OpenSSLCryptoKeyRSA(pkey);
				kekAlg = ENCRYPT_RSA_15;
				EVP_PKEY_free(pkey);
				BIO_free(bioKey);
				paramCount += 3;
			}

			else if (_stricmp(argv[paramCount], "X509") == 0) {

				// X509 cert used to load an encrypting key

				if (paramCount + 2 >= argc) {

					printUsage();
					exit (1);

				}

				if (!isKEK) {
					cerr << "X509 private keys may only be KEKs\n";
					return 2;
				}

				// Load the encrypting 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) {

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

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

				}

				// Now load the key
				EVP_PKEY *pkey;

				pkey = X509_get_pubkey(x);

				if (pkey == NULL || pkey->type != EVP_PKEY_RSA) {
					cerr << "Error extracting RSA key from certificate" << endl;
				}

				kek = new OpenSSLCryptoKeyRSA(pkey);
				kekAlg = ENCRYPT_RSA_15;

				// Clean up

				EVP_PKEY_free (pkey);
				X509_free(x);
				BIO_free(bioX509);

				paramCount += 2;
				
			} /* argv[1] = "--x509cert" */
#endif /* XSEC_HAVE_OPENSSL */
			else {
				printUsage();
				return 2;
			}
		}

		else {
			cerr << "Unknown option: " << argv[paramCount] << endl;
			printUsage();
			return 2;
		}
	}

	if (paramCount >= argc) {
		printUsage();
		return 2;
	}

	if (outfile != NULL) {
		formatTarget = new LocalFileFormatTarget(outfile);
	}
	else {
		formatTarget = new StdOutFormatTarget();
	}

	filename = argv[paramCount];

	if (parseXMLInput) {

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

		// Now parse out file

		xsecsize_t errorCount = 0;
		try
		{
    		parser->parse(filename);
			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;
			return (2);

		}

		/*

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

		*/
		
		doc = parser->adoptDocument();
	}

	else {
		// Create an empty document
		XMLCh tempStr[100];
		XMLString::transcode("Core", tempStr, 99);    
		DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(tempStr);
		doc = impl->createDocument(
			0,                    // root element namespace URI.
			MAKE_UNICODE_STRING("ADoc"),            // root element name
			NULL);// DOMDocumentType());  // document type object (DTD).
	}


	XSECProvider prov;
	XENCCipher * cipher = prov.newCipher(doc);

	if (kek != NULL)
		cipher->setKEK(kek);
	if (key != NULL)
		cipher->setKey(key);

	try {

		if (doDecrypt) {

			if (useInteropResolver == true) {

				// Map out base path of the file
				char path[_MAX_PATH];
				char baseURI[(_MAX_PATH * 2) + 10];
				getcwd(path, _MAX_PATH);

				strcpy(baseURI, "file:///");		

				// Ugly and nasty but quick
				if (filename[0] != '\\' && filename[0] != '/' && filename[1] != ':') {
					strcat(baseURI, path);
					strcat(baseURI, "/");
				} else if (path[1] == ':') {
					path[2] = '\0';
					strcat(baseURI, path);
				}

				strcat(baseURI, filename);

				// Find any ':' and "\" characters
				int lastSlash = 0;
				for (unsigned int i = 8; i < strlen(baseURI); ++i) {
					if (baseURI[i] == '\\') {
						lastSlash = i;
						baseURI[i] = '/';
					}
					else if (baseURI[i] == '/')
						lastSlash = i;
				}

				// The last "\\" must prefix the filename
				baseURI[lastSlash + 1] = '\0';

				XMLCh * uriT = XMLString::transcode(baseURI);

				XencInteropResolver ires(doc, &(uriT[8]));
				XSEC_RELEASE_XMLCH(uriT);
				cipher->setKeyInfoResolver(&ires);

			}
			// Find the EncryptedData node
			DOMNode * n = findXENCNode(doc, "EncryptedData");

			if (doDecryptElement) {
				while (n != NULL) {

					// decrypt
					cipher->decryptElement(static_cast<DOMElement *>(n));

					// Find the next EncryptedData node
					n = findXENCNode(doc, "EncryptedData");
				}

			}
			else {
				XSECBinTXFMInputStream * bis = cipher->decryptToBinInputStream(static_cast<DOMElement *>(n));
				Janitor<XSECBinTXFMInputStream> j_bis(bis);
	
				XMLByte buf[1024];			
				xsecsize_t read = bis->readBytes(buf, 1023);
				while (read > 0) {
					formatTarget->writeChars(buf, read, NULL);
					read = bis->readBytes(buf, 1023);
				}
			}
		}
		else {

			XENCEncryptedData *xenc = NULL;
			// Encrypting
			if (kek != NULL && key == NULL) {
				XSECPlatformUtils::g_cryptoProvider->getRandom(keyBuf, 24);
				XSECCryptoSymmetricKey * k = 
					XSECPlatformUtils::g_cryptoProvider->keySymmetric(XSECCryptoSymmetricKey::KEY_3DES_192);
				k->setKey(keyBuf, 24);
				cipher->setKey(k);
				keyAlg = ENCRYPT_3DES_CBC;
				keyStr = keyBuf;
				keyLen = 24;
			}

			if (encryptFileAsData) {

				// Create a BinInputStream
#if defined(XSEC_XERCES_REQUIRES_MEMMGR)
				BinFileInputStream * is = new BinFileInputStream(filename, XMLPlatformUtils::fgMemoryManager);
#else
				BinFileInputStream * is = new BinFileInputStream(filename);
#endif
				xenc = cipher->encryptBinInputStream(is, keyAlg);

				// Replace the document element
				DOMElement * elt = doc->getDocumentElement();
				doc->replaceChild(xenc->getElement(), elt);
				elt->release();
			}
			else {
				// Document encryption
				cipher->encryptElement(doc->getDocumentElement(), keyAlg);
			}

			// Do we encrypt a created key?
			if (kek != NULL && xenc != NULL) {
				XENCEncryptedKey *xkey = cipher->encryptKey(keyStr, keyLen, kekAlg);
				// Add to the EncryptedData
				xenc->appendEncryptedKey(xkey);
			}
		}

		if (doXMLOutput) {
			// Output the result

			XMLCh core[] = {
				XERCES_CPP_NAMESPACE_QUALIFIER chLatin_C,
				XERCES_CPP_NAMESPACE_QUALIFIER chLatin_o,
				XERCES_CPP_NAMESPACE_QUALIFIER chLatin_r,
				XERCES_CPP_NAMESPACE_QUALIFIER chLatin_e,
				XERCES_CPP_NAMESPACE_QUALIFIER chNull
			};

            DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(core);

#if defined (XSEC_XERCES_DOMLSSERIALIZER)
            // DOM L3 version as per Xerces 3.0 API
            DOMLSSerializer   *theSerializer = ((DOMImplementationLS*)impl)->createLSSerializer();
            Janitor<DOMLSSerializer> j_theSerializer(theSerializer);
            
            // Get the config so we can set up pretty printing
            DOMConfiguration *dc = theSerializer->getDomConfig();
            dc->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, false);

            // Now create an output object to format to UTF-8
            DOMLSOutput *theOutput = ((DOMImplementationLS*)impl)->createLSOutput();
            Janitor<DOMLSOutput> j_theOutput(theOutput);

            theOutput->setEncoding(MAKE_UNICODE_STRING("UTF-8"));
            theOutput->setByteStream(formatTarget);

            theSerializer->write(doc, theOutput);

#else			
			DOMWriter         *theSerializer = ((DOMImplementationLS*)impl)->createDOMWriter();
			Janitor<DOMWriter> j_theSerializer(theSerializer);

			theSerializer->setEncoding(MAKE_UNICODE_STRING("UTF-8"));
			if (theSerializer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, false))
				theSerializer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, false);

			theSerializer->writeNode(formatTarget, *doc);
#endif	
			cout << endl;

		}
	}

	catch (XSECException &e) {
		char * msg = XMLString::transcode(e.getMsg());
		cerr << "An error occured during encryption/decryption operation\n   Message: "
		<< msg << endl;
		XSEC_RELEASE_XMLCH(msg);
		errorsOccured = true;
		if (formatTarget != NULL)
			delete formatTarget;
		doc->release();
		return 2;
	}
	catch (XSECCryptoException &e) {
		cerr << "An error occured during encryption/decryption operation\n   Message: "
		<< e.getMsg() << endl;
		errorsOccured = true;
		if (formatTarget != NULL)
			delete formatTarget;
		doc->release();

#if defined (XSEC_HAVE_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);

		ERR_print_errors(bio_err);
#endif
		return 2;
	}
	
	if (formatTarget != NULL)
		delete formatTarget;

	doc->release();
	return 0;
}
예제 #17
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;
}
예제 #18
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;
};
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;
}
예제 #20
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;
};
예제 #21
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;
}
예제 #22
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;
}
예제 #23
0
DOMDocument *
XIncludeUtils::doXIncludeXMLFileDOM(const XMLCh *href,
                                    const XMLCh *relativeHref,
                                    DOMNode *includeNode,
                                    DOMDocument *parsedDocument,
                                    XMLEntityHandler* entityResolver){
    if (XIncludeUtils::isInCurrentInclusionHistoryStack(href)){
         /* including something back up the current history */
         XIncludeUtils::reportError(parsedDocument, XMLErrs::XIncludeCircularInclusionLoop,
              href, href);
         return NULL;
    }

    if (XMLString::equals(href, parsedDocument->getBaseURI())){
        /* trying to include itself */
        XIncludeUtils::reportError(parsedDocument, XMLErrs::XIncludeCircularInclusionDocIncludesSelf,
              href, href);
        return NULL;
    }

    /* Instantiate the DOM parser. */
    XercesDOMParser parser;
    parser.setDoNamespaces(true);
    /* don't want to recurse the xi processing here */
    parser.setDoXInclude(false);
    /* create the schema info nodes, so that we can detect conflicting notations */
    parser.setCreateSchemaInfo(true);
    XMLInternalErrorHandler xierrhandler;
    parser.setErrorHandler(&xierrhandler);

    DOMDocument *includedNode = NULL;
    try {
        InputSource* is=NULL;
        Janitor<InputSource> janIS(is);
        if(entityResolver) {
            XMLResourceIdentifier resIdentifier(XMLResourceIdentifier::ExternalEntity,
                                                relativeHref,
                                                NULL,
                                                NULL,
                                                includeNode->getBaseURI());
            is=entityResolver->resolveEntity(&resIdentifier);
            janIS.reset(is);
        }
        if(janIS.get()!=NULL)
            parser.parse(*janIS.get());
        else
            parser.parse(href);
        /* need to be able to release the parser but keep the document */
        if (!xierrhandler.getSawError() && !xierrhandler.getSawFatal())
            includedNode = parser.adoptDocument();
    }
    catch (const XMLException& /*toCatch*/)
    {
        XIncludeUtils::reportError(parsedDocument, XMLErrs::XIncludeResourceErrorWarning,
              href, href);
    }
    catch (const DOMException& /*toCatch*/)
    {
        XIncludeUtils::reportError(parsedDocument, XMLErrs::XIncludeResourceErrorWarning,
              href, href);
    }
    catch (...)
    {
        XIncludeUtils::reportError(parsedDocument, XMLErrs::XIncludeResourceErrorWarning,
             href, href);
    }

    //addDocumentURIToCurrentInclusionHistoryStack(href);

    if(includedNode != NULL){
        /* baseURI fixups - see http://www.w3.org/TR/xinclude/#base for details. */
        DOMElement *topLevelElement = includedNode->getDocumentElement();
        if (topLevelElement && topLevelElement->getNodeType() == DOMNode::ELEMENT_NODE ){
            XMLUri parentURI(includeNode->getBaseURI());
            XMLUri includedURI(includedNode->getBaseURI());

            /* if the paths differ we need to add a base attribute */
            if (!XMLString::equals(parentURI.getPath(), includedURI.getPath())){
                if (getBaseAttrValue(topLevelElement) == NULL){
                    /* need to calculate the proper path difference to get the relativePath */
                    topLevelElement->setAttribute(fgXIBaseAttrName, relativeHref);
                } else {
                    /* the included node has base of its own which takes precedence */
                    XIncludeLocation xil(getBaseAttrValue(topLevelElement));
                    if (getBaseAttrValue(includeNode) != NULL){
                        /* prepend any specific base modification of the xinclude node */
                        xil.prependPath(getBaseAttrValue(includeNode));
                    }
                    topLevelElement->setAttribute(fgXIBaseAttrName, xil.getLocation());
                }
            }
        }
    }
    return includedNode;
}
예제 #24
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;
}
예제 #25
0
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;
}
예제 #26
0
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;
}
예제 #27
0
	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();
	}
예제 #28
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;
}
예제 #29
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;
}