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; }
void Parameters::readFile(string str){ file = str; XMLPlatformUtils::Initialize(); XercesDOMParser parser; parser.setValidationScheme(XercesDOMParser::Val_Always); HandlerBase errHandler;// = (ErrorHandler*) new HandlerBase(); parser.setErrorHandler(&errHandler); parser.parse(str.c_str()); DOMDocument * doc = parser.getDocument(); DOMElement* elementRoot = doc->getDocumentElement(); // Extract floats DOMElement* floatRoot = (DOMElement *) elementRoot->getElementsByTagName(XMLString::transcode("real"))->item(0); DOMElement* child = floatRoot->getFirstElementChild(); do{ saveReal(XMLString::transcode(child->getNodeName()), atof(XMLString::transcode(child->getTextContent()))); child = child->getNextElementSibling(); }while(child != NULL); // Extract integers DOMElement* intRoot = (DOMElement *) elementRoot->getElementsByTagName(XMLString::transcode("integer"))->item(0); child = intRoot->getFirstElementChild(); do{ saveInteger( XMLString::transcode(child->getNodeName()), atoi(XMLString::transcode(child->getTextContent()))); child = child->getNextElementSibling(); }while(child != NULL); }
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)); }
// 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; }
bool XMLSceneryReader::openFile(const char* fileName) { bool result = false; XercesDOMParser* parser = new XercesDOMParser; parser->setValidationScheme(XercesDOMParser::Val_Never); parser->setDoSchema(false); parser->setLoadExternalDTD(false); parser->setErrorHandler(new XMLSceneryErrorHandler); parser->parse(LocalFileInputSource(XMLString::transcode(fileName))); if(!parser->getErrorCount()) { m_root = parser->getDocument()->getFirstChild(); m_node = m_root; result = true; } return result; }
void Generation::readGenerations(const string &file, vector<GenerationPtr> &generations) { XMLPlatformUtils::Initialize(); XercesDOMParser parser; GenerationErrorHandler handler; parser.setErrorHandler(&handler); parser.setEntityResolver(&handler); parser.parse(file.c_str()); DOMDocument *doc = parser.getDocument(); DOMElement *root = doc->getDocumentElement(); XMLCh tempStr[12]; XMLString::transcode("generation", tempStr, 11); DOMNodeList *list = root->getElementsByTagName(tempStr); int length = list->getLength(); for (int i = 0; i < length; ++i) { DOMElement *item = (DOMElement *)list->item(i); GenerationPtr generation(new Generation()); generation->m_impl->m_owner = generation.get(); generation->m_impl->getGeneration(item); generation->m_impl->m_idx = i; generations.push_back(generation); } }
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); }
map<string, DatasetSpecification> Specifications::readDatasetIndex(string str){ map<string, DatasetSpecification> result; XERCES_CPP_NAMESPACE_USE XMLPlatformUtils::Initialize(); XercesDOMParser parser; parser.setValidationScheme(XercesDOMParser::Val_Always); HandlerBase errHandler;// = (ErrorHandler*) new HandlerBase(); parser.setErrorHandler(&errHandler); parser.parse(str.c_str()); DOMDocument * doc = parser.getDocument(); DOMElement* elementRoot = doc->getDocumentElement(); DOMNodeList *entries = elementRoot->getElementsByTagName(XMLString::transcode("dataset")); cout << "Databases in index:\n"; for(size_t i = 0; i < entries->getLength(); ++i){ DOMNode *current = entries->item(i); DatasetSpecification dss; dss.name = XMLString::transcode(current->getAttributes()-> getNamedItem(XMLString::transcode("name"))-> getNodeValue()); dss.root = XMLString::transcode(current->getAttributes()-> getNamedItem(XMLString::transcode("root"))-> getNodeValue()); cout << " name: " << dss.name << " root: " << dss.root << endl; DOMNodeList *categories = current->getChildNodes(); for(size_t j = 0; j < categories->getLength(); ++j) if((string) XMLString::transcode(categories->item(j)->getNodeName()) == "category") dss.categories.push_back(XMLString::transcode(categories->item(j)->getTextContent())); result[dss.name] = dss; } return result; }
// 解析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; }
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; }
bool canResolve(const std::string& url) { URL absUrl(url); if (absUrl.scheme() == "") { absUrl = URL("file://" + url); } try { XercesDOMParser* parser = new XercesDOMParser(); std::string tmp = absUrl; parser->parse(tmp.c_str()); return true; } catch(...) { return false; } }
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); } }
bool CategoryTranslationLoader::loadTranslations( const MC2String& filename ) try { // load and parse file XercesDOMParser parser; parser.setValidationScheme( XercesDOMParser::Val_Auto ); parser.setIncludeIgnorableWhitespace( false ); parser.parse( filename.c_str() ); if ( parser.getDocument() == NULL ) { return false; } loadTranslations( parser.getDocument() ); return true; } catch ( const XMLTool::Exception& e ) { // any xml exception here is bad. return false; }
DOMDocument* 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; }
//----------------------------------------------------------------------------- // 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; }
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; }
// --------------------------------------------------------------------------- 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; }
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; }
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; }
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; };
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; };
//======================================================================= void geometryLoader::loadXML(std::string configFile) { // Initialize XERCES-C try { XMLPlatformUtils::Initialize(); } catch(const XMLException &toCatch) { XERCES_STD_QUALIFIER cerr << "Error during Xerces-c Initialization.\n" << " Exception message:" << toCatch.getMessage() << XERCES_STD_QUALIFIER endl; exit(-1); } struct stat fileStatus; int returnStatus = stat(configFile.c_str(), &fileStatus); if( returnStatus == ENOENT ) { ss_.str("") ; ss_ << "ABORT: Path to " << configFile << " does not exist, or path is an empty string." ; STDLINE(ss_.str(),ACRed) ; exit(-1) ; } else if( returnStatus == ENOTDIR ) { ss_.str("") ; ss_ << "ABORT: A component of the path of " << configFile << " is not a directory."; STDLINE(ss_.str(),ACRed) ; exit(-1) ; } else if( returnStatus == ELOOP ) { ss_.str("") ; ss_ << "ABORT: Too many symbolic links encountered while traversing the path to " << configFile; STDLINE(ss_.str(),ACRed) ; exit(-1) ; } else if( returnStatus == EACCES ) { ss_.str("") ; ss_ << "ABORT: Permission denied to read " << configFile; STDLINE(ss_.str(),ACRed) ; exit(-1) ; } else if( returnStatus == ENAMETOOLONG ) { ss_.str("") ; ss_ << "ABORT: Cannot read " << configFile; STDLINE(ss_.str(),ACRed) ; exit(-1) ; } else if( returnStatus == -1 ) { ss_.str("") ; ss_ << "ABORT: Could not find configuration file " << "'" << configFile << "'!"; STDLINE(ss_.str(),ACRed) ; exit(-1) ; } static XercesDOMParser::ValSchemes gValScheme = XercesDOMParser::Val_Auto; // gValScheme = XercesDOMParser::Val_Never; // gValScheme = XercesDOMParser::Val_Auto; // gValScheme = XercesDOMParser::Val_Always; XercesDOMParser *parser = new XercesDOMParser(); parser->setValidationScheme(gValScheme); DOMTreeErrorReporter *errReporter = new DOMTreeErrorReporter(); parser->setErrorHandler(errReporter); try { parser->parse(configFile.c_str()); } catch (const OutOfMemoryException&) { STDLINE("F A T A L E R R O R (A): ",ACRed) ; XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl; exit(-1) ; } catch (const XMLException& e) { STDLINE("F A T A L E R R O R (B): ",ACRed) ; XERCES_STD_QUALIFIER cerr << "An error occurred during parsing\n Message: " << xercesc::XMLString::transcode(e.getMessage()) << XERCES_STD_QUALIFIER endl; exit(-1) ; } catch (const DOMException& e) { STDLINE("F A T A L E R R O R (C): ",ACRed) ; const unsigned int maxChars = 2047; XMLCh errText[maxChars + 1]; XERCES_STD_QUALIFIER cerr << "\nDOM Error during parsing: '" << configFile << "'\n" << "DOMException code is: " << e.code << XERCES_STD_QUALIFIER endl; if (DOMImplementation::loadDOMExceptionMsg(e.code, errText, maxChars)) XERCES_STD_QUALIFIER cerr << "Message is: " << xercesc::XMLString::transcode(errText) << XERCES_STD_QUALIFIER endl; exit(-1) ; } catch (...) { STDLINE("F A T A L E R R O R (D): ",ACRed) ; XERCES_STD_QUALIFIER cerr << "An error occurred during parsing\n " << XERCES_STD_QUALIFIER endl; exit(-1) ; } STDLINE("Configuration successfully parsed",ACGreen) ; DOMDocument * xmlDoc = parser->getDocument(); testBeamGeometryXml_ = xmlDoc->getDocumentElement(); if( !testBeamGeometryXml_ ) { STDLINE("F A T A L E R R O R: ",ACRed) ; XERCES_STD_QUALIFIER cerr << "Empty configuration file\n " << XERCES_STD_QUALIFIER endl; XERCES_STD_QUALIFIER cerr << "This should never occur, the parser should have already detected this error!\n " << XERCES_STD_QUALIFIER endl; exit(-1) ; } theGeometry_->setGeometryFileName(configFile); }
int main(int argc, char** argv) { if(argc != 3){ cerr << "Usage: " << argv[0] << " file1.xml file2.xml" << endl; } string filename1 = string(argv[1]); string filename2 = string(argv[2]); XMLPlatformUtils::Initialize(); XercesDOMParser * parser = new XercesDOMParser(); parser->parse(filename1.c_str()); DOMDocument * doc1 = parser->adoptDocument(); parser->parse(filename2.c_str()); DOMDocument * doc2 = parser->adoptDocument(); XMLCh* tmp = XMLString::transcode("iteration"); DOMNodeList* list1 = doc1->getElementsByTagName(tmp); DOMNodeList* list2 = doc2->getElementsByTagName(tmp); XMLString::release(&tmp); if(list1->getLength() != list2->getLength()){ cout << "Different number of iterations: " << list1->getLength() << " vs " <<list2->getLength() << std::endl; exit(1); } bool correct = true; for(unsigned iter = 0; iter < list1->getLength(); iter++){ bool iter_correct = true; DOMElement * it1 = dynamic_cast<DOMElement*>(list1->item(iter)); DOMElement * it2 = dynamic_cast<DOMElement*>(list2->item(iter)); XMLCh* tmp = XMLString::transcode("etotal"); DOMElement* child1 = dynamic_cast<DOMElement*>(it1->getElementsByTagName(tmp)->item(0)); DOMElement* child2 = dynamic_cast<DOMElement*>(it2->getElementsByTagName(tmp)->item(0)); XMLString::release(&tmp); double etotal1 = strtod(XMLString::transcode(child1->getTextContent()), NULL); double etotal2 = strtod(XMLString::transcode(child2->getTextContent()), NULL); cout << endl; cout << "Energy 1 = " << scientific << etotal1 << endl; cout << "Energy 2 = " << scientific << etotal2 << endl; cout << "Difference = " << scientific << fabs(etotal1 - etotal2) << endl; if(fabs(etotal1 - etotal2) > energy_tol){ iter_correct = false; } correct = correct && iter_correct; cout << endl; cout << "Iteration\t" << iter << "\t:\t"; if(iter_correct){ cout << "[ OK ]" << endl; } else { cout << "[ FAIL ]" << endl; } } doc1->release(); doc2->release(); XMLPlatformUtils::Terminate(); if(!correct) return 1; }
/* 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; }
// --------------------------------------------------------------------------- // // 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; }
//------------------------------------------------------------------------ // // parse - This is the method that is invoked by the rest of // the test program to actually parse an XML file. // //------------------------------------------------------------------------ int ThreadParser::parse(int fileNum) { MemBufInputSource *mbis = 0; InFileInfo *fInfo = &gRunInfo.files[fileNum]; bool errors = false; fCheckSum = 0; if (gRunInfo.inMemory) { mbis = new MemBufInputSource((const XMLByte *) fInfo->fileContent, fInfo->fileSize, fInfo->uFileName, false); } try { if (gRunInfo.dom) { // Do a DOM parse fXercesDOMParser->resetDocumentPool(); if (gRunInfo.inMemory) fXercesDOMParser->parse(*mbis); else fXercesDOMParser->parse(fInfo->fileName); fDoc = fXercesDOMParser->getDocument(); domCheckSum(fDoc); } else if (gRunInfo.sax) { // Do a SAX1 parse if (gRunInfo.inMemory) fSAXParser->parse(*mbis); else fSAXParser->parse(fInfo->fileName); } else { // Do a SAX2 parse if (gRunInfo.inMemory) fSAX2Parser->parse(*mbis); else fSAX2Parser->parse(fInfo->fileName); } } catch (const OutOfMemoryException&) { fprintf(stderr, " during parsing: %s\n OutOfMemoryException.\n", fInfo->fileName); errors = true; } catch (const XMLException& e) { char *exceptionMessage = XMLString::transcode(e.getMessage()); fprintf(stderr, " during parsing: %s\n Exception message is: %s\n", fInfo->fileName, exceptionMessage); XMLString::release(&exceptionMessage); errors = true; } catch (const DOMException& toCatch) { fprintf(stderr, " during parsing: %s\n DOMException code is: %i\n", fInfo->fileName, toCatch.code); errors = true; } catch (const SAXParseException& e) { char *exceptionMessage = XMLString::transcode(e.getMessage()); fprintf(stderr, " during parsing: %s\n Exception message is: %s\n", fInfo->fileName, exceptionMessage); XMLString::release(&exceptionMessage); errors = true; } catch (...) { fprintf(stderr, "Unexpected exception during parsing\n"); errors = true; } delete mbis; if (errors) { fflush(stderr); return 0; // if errors occurred, return zero as if checksum = 0; } return fCheckSum; }
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; }
//initialize a ResultXML object using an existing xml file ResultXML::ResultXML(const char *file) { //sets-up for XML processing and handle any errors if unsuccessful try{ XMLPlatformUtils::Initialize(); } catch (XMLException &e){ char *msg = XMLString::transcode(e.getMessage()); XERCES_STD_QUALIFIER cerr << "Error During Initialization: " << endl << msg; XMLString::release(&msg); } catch (...){ cerr << "Error Unknown Exception Encountered!" << endl; } //create a parser and set it to validate document but not load a DTD or use a schema XercesDOMParser *parser = new XercesDOMParser(); parser->setValidationScheme(XercesDOMParser::Val_Always); parser->setDoSchema(false); parser->setLoadExternalDTD(false); try{ //create unicode strings to for later use XMLCh *spdName = XMLString::transcode("speed_result"); XMLCh *memName = XMLString::transcode("memory_result"); XMLCh *sectName = XMLString::transcode("section_list"); XMLCh *fname = XMLString::transcode(file); //set the save location, parse the file and retrieve the required nodes ftarget = new LocalFileFormatTarget(fname); parser->parse(file); doc = parser->getDocument(); root = doc->getDocumentElement(); DOMNodeList *nlist = root->getChildNodes(); //go through the nodelist finding the top level child nodes and assign them to the right member variables for(XMLSize_t i=0; i<nlist->getLength(); i++){ DOMNode *curNode = nlist->item(i); DOMElement *curElm; //safely check for element node before casting if(curNode->getNodeType() == DOMNode::ELEMENT_NODE){ curElm = dynamic_cast<DOMElement*>(curNode); } //check the tag name and assign accordingly if(XMLString::equals(spdName, curElm->getTagName())){ spdResult = curElm; } else if(XMLString::equals(memName, curElm->getTagName())){ memResult = curElm; } else if(XMLString::equals(sectName, curElm->getTagName())){ sectList = curElm; } } //release the memory occupied by the encoded strings XMLString::release(&spdName); XMLString::release(&memName); XMLString::release(§Name); XMLString::release(&fname); } catch (const OutOfMemoryException&){ XERCES_STD_QUALIFIER cerr << "Error Out of Memory Exception: " << XERCES_STD_QUALIFIER endl; } catch (const DOMException& e){ XERCES_STD_QUALIFIER cerr << "Error DOMException Encountered Code: " << e.code << XERCES_STD_QUALIFIER endl; } catch (...){ XERCES_STD_QUALIFIER cerr << "Unknown Error Encountered, Could Not Create Document" << XERCES_STD_QUALIFIER endl; } delete parser; }
UINT APIENTRY CXMLDOMDocument::ParseThread(void *pParm) { ATLTRACE(_T("CXMLDOMDocument::ParseThread\n")); CXMLDOMDocument *pThis = reinterpret_cast<CXMLDOMDocument *> (pParm); if (NULL == pThis) return 0; if (!pThis->m_bAbort && pThis->m_FileName.length() > 0) { CBindStatCallbackObj *pCallbackObj = NULL; HRESULT hr = CBindStatCallbackObj::CreateInstance(&pCallbackObj); if (S_OK != hr) pCallbackObj = NULL; if (pCallbackObj != NULL) { pCallbackObj->AddRef(); pCallbackObj->m_pDoc = pThis; } TCHAR name[MAX_PATH] = _T(""); if (pThis->m_bAsync) pThis->PostMessage(MSG_READY_STATE_CHANGE,1); hr = URLDownloadToCacheFile(NULL,pThis->m_FileName,name,URLOSTRM_GETNEWESTVERSION,0,pCallbackObj); if (pCallbackObj != NULL) pCallbackObj->Release(); if (E_ABORT == hr) pThis->m_bAbort = true; else { if (S_OK != hr) { _bstr_t error = _T("Failed to download ") + pThis->m_FileName + _T(": "); _com_error comError(hr); error += comError.ErrorMessage(); pThis->m_pParseError->SetData(1,pThis->m_FileName,error,_T(""),0,0,0); pThis->m_bParseError = true; } } if (S_OK == hr) { pThis->m_FileName = name; if (pThis->m_bAsync) pThis->PostMessage(MSG_READY_STATE_CHANGE,2); } } XercesDOMParser parser; // // If set to true then an node supporting IXMLDOMProcessingInstruction // is added for the XML declaration. // // Setting to true in a custom DLL will better mimic // MSXML.DLL but at a cost of conformance errors // using David Brownell's suite //parser.setToCreateXMLDeclTypeNode(false); parser.setIncludeIgnorableWhitespace(pThis->m_bPreserveWhiteSpace); if (!pThis->m_bParseError && !pThis->m_bAbort) { parser.setDoValidation(pThis->m_bThreadValidate); // // this brings the COM component into better mimicry to MSXML // by not throwing a validation error when there is no DOCTYPE // parser.setValidationScheme(pThis->m_bThreadValidate ? AbstractDOMParser::Val_Auto : AbstractDOMParser::Val_Never); } if (!pThis->m_bParseError && !pThis->m_bAbort) parser.setErrorHandler(pThis); if (!pThis->m_bParseError && !pThis->m_bAbort) pThis->m_pParseError->Reset(); if (!pThis->m_bParseError && !pThis->m_bAbort) pThis->m_bParseError = false; try { if (!pThis->m_bParseError && !pThis->m_bAbort) { if (pThis->m_FileName.length() > 0) parser.parse(static_cast<LPCTSTR> (pThis->m_FileName)); else { XMLByte *pXMLByte = reinterpret_cast<XMLByte*> (static_cast<XMLCh*>(pThis->m_xml)); MemBufInputSource memBufIS(pXMLByte,pThis->m_xml.length()*sizeof(XMLCh),OLESTR("IBMXMLParser"),false); memBufIS.setEncoding(OLESTR("UTF-16LE")); if (!pThis->m_bParseError && !pThis->m_bAbort) parser.parse(memBufIS); } } } catch(...) { pThis->m_bParseError = true; return 0; } if (!pThis->m_bParseError && !pThis->m_bAbort) pThis->m_TmpDocument = parser.adoptDocument(); if (!pThis->m_bParseError && !pThis->m_bAbort && pThis->m_bAsync) pThis->PostMessage(MSG_READY_STATE_CHANGE,4); return 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; }