Exemplo n.º 1
0
int main(int argc, char *argv[])
{
//	QApplication a(argc, argv);
// 	testSclParser w;
// 	w.show();
	int seconds = time((time_t*)NULL);
	CScl* pScl= new CScl;
	XMLPlatformUtils::Initialize();
	MemoryManager*       fgMemoryManager = XMLPlatformUtils::fgMemoryManager;
	//XMLGrammarPool* pGrammarPool  = new XMLGrammarPoolImpl(XMLPlatformUtils::fgMemoryManager);
	SAX2XMLReader* parser = XMLReaderFactory::createXMLReader(XMLPlatformUtils::fgMemoryManager);
	SclSAX2Handler*myContentHandler = new SclSAX2Handler(pScl,1);		
	parser->setContentHandler((SclSAX2Handler*)myContentHandler);
	///m_pSclFacty->LoadSclFile();
	parser->parse("yab.scd");//½âÎöxmlÎļþ	

	int seconds2 = time((time_t*)NULL);

	int SpendTime = seconds2-seconds;

	printf("Reading SCD...%d have elapsed",SpendTime);
	char* strIP = pScl->GetIEDIP("CL1101A","MMS_A");
	char* strManufacture = pScl->GetManufacturer("CL1101A");
	
	printf("CL1101A ip = %s\n",strIP);
	printf("CL1101A manufacture = %s\n",strManufacture);
	return 0;
//	return a.exec();
}
Exemplo n.º 2
0
bool WMessageResources::readResourceFile(std::string locale,
					 KeyValueMap& valueMap)
{
  std::string fileName
    = path_ + (locale.length() > 0 ? "_" : "") + locale + ".xml";

  {
    std::ifstream test(fileName.c_str());
    if (!test)
      return false;
  }

  std::cerr << "Reading resource file: " << fileName << std::endl;

  try {
    SAX2XMLReader* reader = XMLReaderFactory::createXMLReader();
    WMessageHandler handler(valueMap);
    reader->setContentHandler(&handler);
    reader->setErrorHandler(&handler);
    reader->parse(fileName.c_str());
    delete reader;

    return true;

  } catch (const std::exception& e) {
    std::cerr << "Exception caught reading XML file: "
	      << fileName << ": " << e.what() << std::endl;

    return false;
  }
}
Exemplo n.º 3
0
void XSAnnotation::writeAnnotation(ContentHandler* handler)
{   
    SAX2XMLReader* parser = XMLReaderFactory::createXMLReader(fMemoryManager);
    parser->setFeature(XMLUni::fgSAX2CoreNameSpaces, true);
    parser->setFeature(XMLUni::fgSAX2CoreValidation, false);
    parser->setContentHandler(handler);
    
    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&)
    {
    }

    delete parser;
    delete memBufIS;
}
Exemplo n.º 4
0
// ===========================================================================
// method definitions
// ===========================================================================
GUISettingsHandler::GUISettingsHandler(const std::string &content, bool isFile) throw()
    : SUMOSAXHandler(content), myDelay(-1), myZoom(-1), myXPos(-1), myYPos(-1), myCurrentColorer(SUMO_TAG_NOTHING), myCurrentScheme(0) {
    if (isFile) {
        XMLSubSys::runParser(*this, content);
    } else {
        setFileName("registrySettings");
        SAX2XMLReader *reader = XMLSubSys::getSAXReader(*this);
        MemBufInputSource memBufIS((const XMLByte*)content.c_str(),content.size(),"registrySettings");
        reader->parse(memBufIS);
        delete reader;
    }
}
Exemplo n.º 5
0
// Other include files, declarations, and non-Xerces-C++ initializations.
XERCES_CPP_NAMESPACE_USE 
  
/*int main(int argc, char** argv){
	char* xmlFile = "well-formatted-new.xml";
	//char *xmlFile = "GridLABD_Multi_Example.xml";
	return loadall_xml(xmlFile);
}*/

int loadall_xml(char *filename){
	if(filename == NULL)
		return 0;
	try{
		XMLPlatformUtils::Initialize();
	} catch(const XMLException& /*toCatch*/){
		output_error("Load_XML: Xerces Initialization failed.");
		output_debug(" * something really spectacularly nasty happened inside Xerces and outside our control.");
		return 0;
	}

	SAX2XMLReader* parser = XMLReaderFactory::createXMLReader();
	parser->setFeature(XMLUni::fgXercesDynamic, true);
	//parser->setFeature(XMLUni::fgSAX2CoreValidation, true);   
	//parser->setFeature(XMLUni::fgSAX2CoreNameSpaces, true);   // optional

	gld_loadHndl *defaultHandler = new gld_loadHndl();
	parser->setContentHandler(defaultHandler);
	parser->setErrorHandler(defaultHandler);
	
	try {
		parser->parse(filename);
	} catch (const XMLException& toCatch){
		char* message = XMLString::transcode(toCatch.getMessage());
		output_error("Load_XML: XMLException from Xerces: %s", message);
		XMLString::release(&message);
		return 0;
	} catch (const SAXParseException& toCatch){
		char* message = XMLString::transcode(toCatch.getMessage());
		output_error("Load_XML: SAXParseException from Xerces: %s", message);
		XMLString::release(&message);
		return 0;
	} catch (...) {
		output_error("Load_XML: unexpected exception from Xerces.");
		return 0;
	}
	if(!defaultHandler->did_load()){
		output_error("Load_XML: loading failed.");
		return 0;
	}
	delete parser;
	delete defaultHandler;
	return 1;
}
Exemplo n.º 6
0
bool
O2Profile::
ImportFromXML(const wchar_t *filename, const char *in, uint len)
{
	bool ret = false;

	SAX2XMLReader* parser = XMLReaderFactory::createXMLReader();
	O2Profile_SAX2Handler handler(Logger, this);
	parser->setContentHandler(&handler);
	parser->setErrorHandler(&handler);

	Lock();
	{
		try {
			if (filename) {
#ifdef _MSC_VER			/** VC++ */
				LocalFileInputSource source(filename);
#else				/** GCC/Clang */
				LocalFileInputSource source(reinterpret_cast<const XMLCh*>(filename));
#endif
				parser->parse(source);
			}
			else {
				MemBufInputSource source((const XMLByte*)in, len, "");
				parser->parse(source);
			}
			ret = true;
		}
		catch (const OutOfMemoryException &e) {
			if (Logger) {
				Logger->AddLog(O2LT_ERROR, MODULE, 0, 0,
					L"SAX2: Out of Memory: %s", e.getMessage());
			}
		}
		catch (const XMLException &e) {
			if (Logger) {
				Logger->AddLog(O2LT_ERROR, MODULE, 0, 0,
					L"SAX2: Exception: %s", e.getMessage());
			}
		}
		catch (...) {
			if (Logger) {
				Logger->AddLog(O2LT_ERROR, MODULE, 0, 0,
					L"SAX2: Unexpected exception during parsing.");
			}
		}
	}
	Unlock();

	delete parser;
	return (ret);
}
Exemplo n.º 7
0
/*
 =======================================================================================================================
 *  TODO:
 =======================================================================================================================
 */
void cLoadXML::Sax2ReadXML (const char* filename) {

	/* create SAX2 parser and read the basic building block setting file */
	SAX2XMLReader*	parser;

	/* create handler that will parse the XML elements */
	SHandler*  handler;
	parser = XMLReaderFactory::createXMLReader ();
	handler = new SHandler (recordNode, recordLink, nodeIndex, linkIndex);

	parser->setContentHandler (handler);
	parser->setErrorHandler (handler);

	try
	{
		parser->parse (filename);
	}

	catch (const XMLException&toCatch) {
		char*  message;
		message = XMLString::transcode (toCatch.getMessage ());

		/*
		 * err << "Exception message is: \n" ;
		 * << message << "\n";
		 */
		XMLString::release (&message);
	}

	catch (const SAXParseException&toCatch) {
		char*  message;
		message = XMLString::transcode (toCatch.getMessage ());

		/*
		 * err << "Exception message is: \n" ;
		 * << message << "\n";
		 */
		XMLString::release (&message);
	}

	catch (...) {

		/*
		 * err << "Unexpected Exception \n" ;
		 */
	}

	delete parser;
	delete handler;
	XMLPlatformUtils::Terminate ();
}
Exemplo n.º 8
0
static 
bool parseOne(BinOutputStream*    outStream
            , const char* const   xmlFile)
{
    //we don't use janitor here
    MemoryManager*  theMemMgr   = new MemoryManagerImpl();
    XMLGrammarPool* theGramPool = new XMLGrammarPoolImpl(theMemMgr);
    SAX2XMLReader*  theParser   = getParser(theGramPool, false);  //don't emit error
    bool            retVal      = true;

    theParser->setFeature(XMLUni::fgXercesCacheGrammarFromParse, true);

    //scan instance document and cache grammar
    try
    {
        theParser->parse(xmlFile);
    }
    catch (...)
    {
        //do nothing, it could be an invalid instance document, but the grammar is fine
    }

    //serialize the grammar pool
    try
    {
        theGramPool->serializeGrammars(outStream);
    }
    catch (const XSerializationException& e)
    {
        //do emit error here so that we know serialization failure
        XERCES_STD_QUALIFIER cerr << "An error occurred during serialization\n   Message: "
            << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;

        retVal = false;
    }

    catch (...)
    {
        //do emit error here so that we know serialization failure
        XERCES_STD_QUALIFIER cerr << "An error occurred during serialization\n" << XERCES_STD_QUALIFIER endl;

        retVal = false;
    }

    //the order is important
    delete theParser;
    delete theGramPool;
    delete theMemMgr;

    return retVal;
}
Exemplo n.º 9
0
    int GpXmlReader::ReadFile(string& filename, GpCodeModel* model)
    {
        DEBOUT("GpXmlReader::ReadFile()");
        SAX2XMLReader* parser = XMLReaderFactory::createXMLReader();
        parser->setFeature(XMLUni::fgSAX2CoreValidation, true);
        parser->setFeature(XMLUni::fgSAX2CoreNameSpaces, true); // optional

        if (!model)
        {
            throw std::invalid_argument("Null pointer passed to  GpXmlReader::ReadFile()");
        }

        GpXmlSAXContentHandler* handler = new GpXmlSAXContentHandler(model);
        parser->setContentHandler(handler);
        parser->setErrorHandler(handler);

        try
        {
            parser->parse(filename.c_str() );
        }
        catch (const XMLException& toCatch)
        {
            char* message = XMLString::transcode(toCatch.getMessage() );
            cout << "Exception message is: \n"
                 << message << "\n";
            XMLString::release(&message);
            return -1;
        }
        catch (const SAXParseException& toCatch)
        {
            char* message = XMLString::transcode(toCatch.getMessage() );
            cout << "Exception message is: \n"
                 << message << "\n";
            XMLString::release(&message);
            return -1;
        }
        catch (const std::exception& except)
        {
            cout << except.what() << '\n';
            return -1;
        }
        catch (...)
        {
            cout << "Unexpected Exception \n";
            return -1;
        }

        delete parser;
        delete handler;
        return 0;
    }
Exemplo n.º 10
0
//////////////////////////////////////////////////////////////////////////////
/// \brief 지정된 위치에 있는 파일 또는 웹 문서를 파싱한다.
/// 
/// \param pURL 
//////////////////////////////////////////////////////////////////////////////
void XMLParser::parseURL(const char* pURL)
{
	assert(pURL != NULL);
	assert(m_pHandler != NULL);

	// SAX 파서 오브젝트를 생성한다. 그리고 feature를 설정한다.
	// SAX2에서 지원되는 feature는 다음과 같다.
	//
	// validation (default: true) 
	// namespaces (default: true) 
	// namespace-prefixes (default: false) 
	// validation/dynamic (default: false) 
	// reuse-grammar (default: false) 
	// schema (default: true) 
	// schema-full-checking (default: false) 
	// load-external-dtd (default: true) 
	// continue-after-fatal-error (default: false) 
	// validation-error-as-fatal (default: false) 
	//
	// 자세한 사항은 다음 주소를 참고하기 바란다.
	// http://xml.apache.org/xerces-c/program-sax2.html#SAX2Features 
	SAX2XMLReader* pParser = XMLReaderFactory::createXMLReader();
	pParser->setFeature(XMLUni::fgSAX2CoreNameSpaces, true);
	pParser->setFeature(XMLUni::fgXercesSchema, true);
	pParser->setFeature(XMLUni::fgXercesSchemaFullChecking, false);
	pParser->setFeature(XMLUni::fgSAX2CoreNameSpacePrefixes, false);
	pParser->setFeature(XMLUni::fgSAX2CoreValidation, true);
	pParser->setFeature(XMLUni::fgXercesDynamic, true);
	pParser->setContentHandler(m_pHandler);
	pParser->setErrorHandler(m_pHandler);

	try
	{
		pParser->parse(pURL);
	}
	catch (const XMLException& e)
	{
		XMLUtil::filelog(
			"\nError during parsing! Exception Message: \n%s\n",
			XMLUtil::WideCharToString(e.getMessage()).c_str());
	}
	catch (...)
	{
		XMLUtil::filelog(
			"Unexpected exception during parsing!\n");
	}

	delete pParser;
}
Exemplo n.º 11
0
int main (int argc, char* args[]) {

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

	StdInInputSource lStdInStream;
	SAX2XMLReader* parser = XMLReaderFactory::createXMLReader();
	parser->setFeature(XMLUni::fgSAX2CoreValidation, true);
	parser->setFeature(XMLUni::fgSAX2CoreNameSpaces, true);   // optional

	XMLSerializer* defaultHandler = new XMLSerializer(wcout);
	parser->setContentHandler(defaultHandler);
	parser->setErrorHandler(defaultHandler);

	try {
		parser->parse(lStdInStream);
	}
	catch (const XMLException& toCatch) {
		char* message = XMLString::transcode(toCatch.getMessage());
		cout << "Exception message is: \n"
			<< message << "\n";
		XMLString::release(&message);
		return -1;
	}
	catch (const SAXParseException& toCatch) {
		char* message = XMLString::transcode(toCatch.getMessage());
		cout << "Exception message is: \n"
			<< message << "\n";
		XMLString::release(&message);
		return -1;
	}
	catch (...) {
		cout << "Unexpected Exception \n" ;
		return -1;
	}

	delete parser;
	delete defaultHandler;
	return 0;
}
Exemplo n.º 12
0
    XERCES_CPP_NAMESPACE::SAX2XMLReader* XercesParser::createReader(XERCES_CPP_NAMESPACE::DefaultHandler& handler)
    {
        XERCES_CPP_NAMESPACE_USE;

        SAX2XMLReader* reader = XMLReaderFactory::createXMLReader();

        // set basic settings we want from parser
        reader->setFeature(XMLUni::fgSAX2CoreNameSpaces, true);

        // set handlers
        reader->setContentHandler(&handler);
        reader->setErrorHandler(&handler);

        return reader;
    }
Exemplo n.º 13
0
// ---------------------------------------------------------------------------
//	LoadEx()
//	独自の情報を別ファイルから読む
// ---------------------------------------------------------------------------
bool
O2Boards::
LoadEx(void)
{
	bool ret = false;

	struct _stat st;
	if (_wstat(exfilepath.c_str(), &st) == -1)
		return false;
	if (st.st_size == 0)
		return false;

	SAX2XMLReader* parser = XMLReaderFactory::createXMLReader();
	parser->setContentHandler(this);
	parser->setErrorHandler(this);

	try {
#ifdef _MSC_VER
		LocalFileInputSource source(exfilepath.c_str());
#else
		LocalFileInputSource source(reinterpret_cast<const XMLCh*>(exfilepath.c_str()));
#endif
		parser->parse(source);
		ret = true;
	}
	catch (const OutOfMemoryException &e) {
		if (Logger) {
			Logger->AddLog(O2LT_ERROR, MODULE, 0, 0,
				L"SAX2: Out of Memory: %s", e.getMessage());
		}
	}
	catch (const XMLException &e) {
		if (Logger) {
			Logger->AddLog(O2LT_ERROR, MODULE, 0, 0,
				L"SAX2: Exception: %s", e.getMessage());
		}
	}
	catch (...) {
		if (Logger) {
			Logger->AddLog(O2LT_ERROR, MODULE, 0, 0,
				L"SAX2: Unexpected exception during parsing.");
		}
	}

	delete parser;
	return (ret);
}
Exemplo n.º 14
0
static 
void parseTwo(BinInputStream*     inStream
            , const char* const   xmlFile)
{
    //we don't use janitor here
    MemoryManager*  theMemMgr   = new MemoryManagerImpl();
    XMLGrammarPool* theGramPool = new XMLGrammarPoolImpl(theMemMgr);
    bool            errorSeen   = false;

    //de-serialize grammar pool
    try
    {
        theGramPool->deserializeGrammars(inStream);
    }

    catch(const XSerializationException& e)
    {
        XERCES_STD_QUALIFIER cerr << "An error occurred during de-serialization\n   Message: "
            << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;

        errorSeen = true;
    }

    catch (...)
    {
        //do emit error here so that we know serialization failure
        XERCES_STD_QUALIFIER cerr << "An error occurred during de-serialization\n" << XERCES_STD_QUALIFIER endl;

        errorSeen = true;
    }

    if (!errorSeen)
    {
        SAX2XMLReader*  theParser   = getParser(theGramPool, true); //set the handler

        theParser->setFeature(XMLUni::fgXercesUseCachedGrammarInParse, true);
        parseFile(theParser, xmlFile);
        delete theParser;
    }

    //the order is important
    delete theGramPool;
    delete theMemMgr;

    return;
}
Exemplo n.º 15
0
size_t
O2IMDB::
ImportFromXML(const wchar_t *filename, const char *in, uint len)
{
	SAX2XMLReader* parser = XMLReaderFactory::createXMLReader();
	O2IMDB_SAX2Handler handler(Logger, this);
	parser->setContentHandler(&handler);
	parser->setErrorHandler(&handler);

	try {
		if (filename) {

#ifdef _MSC_VER         /** loose VC++ cast...*/
			LocalFileInputSource source(filename);
#else                   /** use reinterpret_cast for GCC */
			LocalFileInputSource source(reinterpret_cast<const XMLCh*>(filename));
#endif
			parser->parse(source);
		}
		else {
			MemBufInputSource source((const XMLByte*)in, len, "");
			parser->parse(source);
		}
	}
	catch (const OutOfMemoryException &e) {
		if (Logger) {
			Logger->AddLog(O2LT_ERROR, MODULE, 0, 0,
				L"SAX2: Out of Memory: %s", e.getMessage());
		}
	}
	catch (const XMLException &e) {
		if (Logger) {
			Logger->AddLog(O2LT_ERROR, MODULE, 0, 0,
				L"SAX2: Exception: %s", e.getMessage());
		}
	}
	catch (...) {
		if (Logger) {
			Logger->AddLog(O2LT_ERROR, MODULE, 0, 0,
				L"SAX2: Unexpected exception during parsing.");
		}
	}

	delete parser;
	return (handler.GetParseNum());
}
Exemplo n.º 16
0
// ---------------------------------------------------------------------------
//  SAX2 XML Reader
// ---------------------------------------------------------------------------
int TestInit4SAX2(const char* xmlFile, bool gDoNamespaces, bool gDoSchema, bool gSchemaFullChecking, Teststate theState)
{
    TESTINITPRE;
    SAX2XMLReader* parser = XMLReaderFactory::createXMLReader();

    XMLCh* doNamespaceFeature = XMLString::transcode("http://xml.org/sax/features/namespaces");
    parser->setFeature(doNamespaceFeature, gDoNamespaces);

    XMLCh* doSchemaFeature = XMLString::transcode("http://apache.org/xml/features/validation/schema");
    parser->setFeature(doSchemaFeature, gDoSchema);

    XMLCh* fullSchemaCheckFeature = XMLString::transcode("http://apache.org/xml/features/validation/schema-full-checking");
    parser->setFeature(fullSchemaCheckFeature, gSchemaFullChecking);

    XMLString::release(&doNamespaceFeature);
    XMLString::release(&doSchemaFeature);
    XMLString::release(&fullSchemaCheckFeature);

    TESTINITPOST;
}
Exemplo n.º 17
0
uint64
O2IPFilter::
ImportFromXML(const wchar_t *filename, const char *in, uint len)
{
	SAX2XMLReader* parser = XMLReaderFactory::createXMLReader();
	O2IPFilter_SAX2Handler handler(name.c_str(), Logger, this);
	parser->setContentHandler(&handler);
	parser->setErrorHandler(&handler);

	try {
		if (filename) {
			LocalFileInputSource source(filename);
			parser->parse(source);
		}
		else {
			MemBufInputSource source((const XMLByte*)in, len, "");
			parser->parse(source);
		}
	}
	catch (const OutOfMemoryException &e) {
		if (Logger) {
			Logger->AddLog(O2LT_ERROR, name.c_str(), 0, 0,
				L"SAX2: Out of Memory: %s", e.getMessage());
		}
	}
	catch (const XMLException &e) {
		if (Logger) {
			Logger->AddLog(O2LT_ERROR, name.c_str(), 0, 0,
				L"SAX2: Exception: %s", e.getMessage());
		}
	}
	catch (...) {
		if (Logger) {
			Logger->AddLog(O2LT_ERROR, name.c_str(), 0, 0,
				L"SAX2: Unexpected exception during parsing.");
		}
	}

	delete parser;
	return (handler.GetParseNum());
}
Exemplo n.º 18
0
//////////////////////////////////////////////////////////////////////////////
/// \brief 인수로 넘겨지는 문자열을 XML 문서로 가정하고 파싱한다.
/// 
/// \param buffer 
//////////////////////////////////////////////////////////////////////////////
void XMLParser::parse(const char* buffer)
{
	assert(buffer != NULL);
	assert(m_pHandler != NULL);

	// SAX 파서 오브젝트를 생성한다. 그리고 feature를 설정한다.
	// feature에 관한 사항은 XMLParser::parseURL() 함수를 참고하기 바란다.
	SAX2XMLReader* pParser = XMLReaderFactory::createXMLReader();
	pParser->setFeature(XMLUni::fgSAX2CoreNameSpaces, true);
	pParser->setFeature(XMLUni::fgXercesSchema, true);
	pParser->setFeature(XMLUni::fgXercesSchemaFullChecking, false);
	pParser->setFeature(XMLUni::fgSAX2CoreNameSpacePrefixes, false);
	pParser->setFeature(XMLUni::fgSAX2CoreValidation, true);
	pParser->setFeature(XMLUni::fgXercesDynamic, true);
	pParser->setContentHandler(m_pHandler);
	pParser->setErrorHandler(m_pHandler);

	try
	{
		MemBufInputSource source(
			(const XMLByte*)(buffer), (unsigned int)strlen(buffer), "", false);
		pParser->parse(source);
	}
	catch (const XMLException& e)
	{
		XMLUtil::filelog(
			"\nError during parsing! Exception Message: \n%s\n",
			XMLUtil::WideCharToString(e.getMessage()).c_str());
	}
	catch (...)
	{
		XMLUtil::filelog(
			"Unexpected exception during parsing!\n");
	}

	delete pParser;
}
Exemplo n.º 19
0
// ---------------------------------------------------------------------------
//  Program entry point
// ---------------------------------------------------------------------------
int main(int argC, char* argV[])
{

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

    int argInd;
    for (argInd = 1; argInd < argC; argInd++)
    {
        // Break out on first parm not starting with a dash
        if (argV[argInd][0] != '-')
            break;

        // Watch for special case help request
        if (!strcmp(argV[argInd], "-?"))
        {
            usage();
            return 2;
        }
        // TODO: add option to generate the XML summarizing the result
        else if (!strncmp(argV[argInd], "-v=", 3)
             ||  !strncmp(argV[argInd], "-V=", 3))
        {
        }
        else
        {
            XERCES_STD_QUALIFIER cout << "Unknown option '" << argV[argInd]
                << "', ignoring it\n" << XERCES_STD_QUALIFIER endl;
        }
    }

    //
    //  There should be only one and only one parameter left, and that
    //  should be the file name.
    //
    if (argInd != argC - 1)
    {
        usage();
        return 1;
    }

    try
    {
        XMLPlatformUtils::Initialize();
    }

    catch (const XMLException& toCatch)
    {
        XERCES_STD_QUALIFIER cout << "Error during initialization! Message:\n"
            << StrX(toCatch.getMessage()) << XERCES_STD_QUALIFIER endl;
        return 1;
    }

    //
    //  Create a SAX parser object.
    //
    SAX2XMLReader* parser = XMLReaderFactory::createXMLReader();
    parser->setFeature(XMLUni::fgSAX2CoreNameSpaces, true);
    parser->setFeature(XMLUni::fgSAX2CoreValidation, false);

    const char* xmlFile = argV[argInd];

    // Discover if the test suite is the XML or XMLSchema one
    RootExtractor rootExtractor;
    parser->setContentHandler(&rootExtractor);
    try
    {
        parser->parse(xmlFile);
    }
    catch (...)
    {
    }

    XMLCh* uniFile = XMLString::transcode(xmlFile);
    XMLCh* uri = new XMLCh[XMLString::stringLen(xmlFile) + 9];
    XMLString::fixURI(uniFile, uri);
    BaseHarnessHandlers* handler=NULL;
    if(rootExtractor.isXMLSuite())
    {
        // XML Test Suite
        handler=new XMLHarnessHandlers(uri);
    }
    else
    {
        // XMLSchema Test Suite
        handler=new XSTSHarnessHandlers(uri);
    }
    XMLString::release(&uniFile);
    delete [] uri;
    parser->setContentHandler(handler);
    parser->setErrorHandler(handler);

    //
    //  Get the starting time and kick off the parse of the indicated
    //  file. Catch any exceptions that might propogate out of it.
    //
    bool errorOccurred=false;
    const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis();
    try
    {
        parser->parse(xmlFile);
    }
    catch (const OutOfMemoryException&)
    {
        XERCES_STD_QUALIFIER cout << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl;
        errorOccurred = true;
    }
    catch (const XMLException& e)
    {
        XERCES_STD_QUALIFIER cout << "\nError during parsing: '" << xmlFile << "'\n"
            << "Exception message is:  \n"
            << StrX(e.getMessage()) << "\n" << XERCES_STD_QUALIFIER endl;
        errorOccurred = true;
    }
    catch (...)
    {
        XERCES_STD_QUALIFIER cout << "\nUnexpected exception during parsing: '" << xmlFile << "'\n";
        errorOccurred = true;
    }
    const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis();
    unsigned long duration = endMillis - startMillis;

    if (handler->getSawErrors())
        errorOccurred = true;

    XERCES_STD_QUALIFIER cout << "Total tests: " << handler->getTotalTests() << XERCES_STD_QUALIFIER endl;
    XERCES_STD_QUALIFIER cout << "Failed tests: " << handler->getFailedTests() << XERCES_STD_QUALIFIER endl;
    XERCES_STD_QUALIFIER cout << "Success rate: " << ((double)(handler->getTotalTests()-handler->getFailedTests()))/(double)handler->getTotalTests()*100 << "%" << XERCES_STD_QUALIFIER endl;
    XERCES_STD_QUALIFIER cout << "Duration: ";
    if(duration > 60000)
    {
        XERCES_STD_QUALIFIER cout << duration/60000 << ":";
        duration=duration % 60000;
    }
    if(duration/1000 < 10)
        XERCES_STD_QUALIFIER cout << "0";
    XERCES_STD_QUALIFIER cout << duration/1000 << "." << duration % 1000 << XERCES_STD_QUALIFIER endl;

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

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

    if (errorOccurred)
        return 4;
    else
        return 0;

}
Exemplo n.º 20
0
    std::vector< toppers::xml::container::object* > cfg1_out::xml_parser_init( std::string input_file )
    {
      SAX2XMLReader::ValSchemes    valScheme    = SAX2XMLReader::Val_Auto;
      bool                         doNamespaces = true;
      bool                         doSchema = true;
      bool                         schemaFullChecking = false;
      bool                         identityConstraintChecking = true;
      bool                         namespacePrefixes = true;
      bool                         recognizeNEL = false;

      // Initialize the XML4C2 system
      try
      {
        XMLPlatformUtils::Initialize();
      }
      catch (const XMLException& toCatch)
      {
        std::vector<toppers::xml::container::object*> object_array;
        fatal( _("Error during initialization! Message:\n%" ), toNative(toCatch.getMessage()));
        return object_array;
      }

      //
      //  Create a SAX parser object. Then, according to what we were told on
      //  the command line, set it to validate or not.
      //
      SAX2XMLReader* parser = XMLReaderFactory::createXMLReader();
      parser->setFeature(XMLUni::fgSAX2CoreNameSpaces, doNamespaces);
      parser->setFeature(XMLUni::fgXercesSchema, doSchema);
      parser->setFeature(XMLUni::fgXercesHandleMultipleImports, true);
      parser->setFeature(XMLUni::fgXercesSchemaFullChecking, schemaFullChecking);
      parser->setFeature(XMLUni::fgXercesIdentityConstraintChecking, identityConstraintChecking);
      parser->setFeature(XMLUni::fgSAX2CoreNameSpacePrefixes, namespacePrefixes);

      if (valScheme == SAX2XMLReader::Val_Auto)
      {
        parser->setFeature(XMLUni::fgSAX2CoreValidation, true);
        parser->setFeature(XMLUni::fgXercesDynamic, true);
      }
      if (valScheme == SAX2XMLReader::Val_Never)
      {
        parser->setFeature(XMLUni::fgSAX2CoreValidation, false);
      }
      if (valScheme == SAX2XMLReader::Val_Always)
      {
        parser->setFeature(XMLUni::fgSAX2CoreValidation, true);
        parser->setFeature(XMLUni::fgXercesDynamic, false);
      }

      /* External Schema file */
      // XMLファイルのチェック
      namespace fs = boost::filesystem;

      if( !fs::exists( input_file ) )
      {
        fatal( _("'%1%` is not exist."), input_file );
      }
      /* 設定ファイルがある場合はパラメータ名のチェックを行う */
      std::string paraname( get_global_string( "ini-file" ) );
      std::string strAUTOSARVersion;
      std::string strSchema;
      std::string strSchemaLocation;
      std::string strContainerPath;
      std::string strModuleName;
      //std::cout << "AUTOSAR ini-file (ini file name):[" << paraname << "]" << std::endl;
      if( !paraname.empty() )
      {
        strAUTOSARVersion = get_global_string( "XML_AUTOSARVersion" );
        if( strAUTOSARVersion.empty() )
        {
          strAUTOSARVersion = "4";
          warning( _( " \"AUTOSARVersion\" parameter is not found in AUTOSAR ini-file. Use default value." ) );
        }
        strSchema = get_global_string( "XML_Schema" );
        if( strSchema.empty() )
        {
          strSchema = "AUTOSAR_4-0-3_STRICT.xsd";
          warning( _( " \"Schema\" parameter is not found in AUTOSAR ini-file. Use default value." ) );
        }
        strSchemaLocation = get_global_string( "XML_SchemaLocation" );
        if( strSchemaLocation.empty() )
        {
          strSchemaLocation = "http://autosar.org/schema/r4.0";
          warning( _( " \"SchemaLocation\" parameter is not found in AUTOSAR ini-file. Use default value." ) );
        }
        strContainerPath = get_global_string( "XML_ContainerPath" );
        if( strContainerPath.empty() )
        {
          strContainerPath = "/AUTOSAR/EcucDefs";
          warning( _( " \"ContainerPath\" parameter is not found in AUTOSAR ini-file. Use default value." ) );
        }
      }
      toppers::global( "XML_AUTOSARVersion" ) = strAUTOSARVersion;
      toppers::global( "XML_Schema" )         = strSchema;
      toppers::global( "XML_SchemaLocation" ) = strSchemaLocation;
      toppers::global( "XML_ContainerPath" )  = strContainerPath;

      // XMLファイルの中にxsi:schemaLocation属性があればその要素を取得
      std::string sstr( "xsi:schemaLocation" );
      std::string buf;
      toppers::read( input_file, buf );

      std::list<std::string> results;
      string::size_type index( buf.find( sstr ) );
      if( index != string::npos )
      {
        string::size_type index2( buf.substr( index ).find( "\"" ) );
        string::size_type index3( buf.substr( index+index2+1 ).find( "\"" ) );
        sstr = buf.substr( index+index2+1, index3 );
        split( results, sstr, boost::is_space() );
      }

      // スキーマファイルのチェック
      std::ostringstream ostream;
      if( results.size() == 2 && fs::exists( results.back() ) )
      {
        ostream << sstr;
      }
      else
      {
        ostream << get_global_string( "XML_SchemaLocation" ) << " " << fs::absolute( get_global_string( "cfg-directory" ).c_str() ).string() 
         << "/" << get_global_string( "XML_Schema" );
      }
      XMLCh* str (XMLString::transcode (ostream.str().c_str()));

      parser->setProperty(XMLUni::fgXercesSchemaExternalSchemaLocation, str);

      //
      //  Create our SAX handler object and install it on the parser, as the
      //  document and error handler.
      //
      SAX2Handlers handler;
      parser->setContentHandler(&handler);
      parser->setErrorHandler(&handler);

      //reset error count first
      handler.resetErrors();

      handler.filename = input_file;

      try
      {
        parser->parse(input_file.c_str());
      }
      catch (const OutOfMemoryException&)
      {
        warning("OutOfMemoryException");
      }
      catch (const XMLException& e)
      {
        warning( _("\nError during parsing: '%'\nException message is:  \n%\n"), input_file, toNative(e.getMessage()));
      }
      catch (...)
      {
        warning( _("\nUnexpected exception during parsing: '%'\n"), input_file);
      }

      delete parser;

      XMLPlatformUtils::Terminate();

      return handler.object_array;
    }
Exemplo n.º 21
0
int _tmain(int argc, _TCHAR* argv[])
{
	// Initialize the XML4C2 system
	try
	{
		XMLPlatformUtils::Initialize();
	}
	catch (const XMLException& toCatch)
	{
		std::cout << "Error during initialization!" << std::endl;
		return 1;
	}

	// specify source XML file.
	xmlFile = "test_data.xml";

	//
	//  Create a SAX parser object. Then, according to what we were told on
	//  the command line, set it to validate or not.
	//
	SAX2XMLReader* parser;
	SAX2XMLReader* reader = XMLReaderFactory::createXMLReader();
	SAX2XMLReader* filter = NULL;

	parser=reader;

	//
	//  Create the handler object and install it as the document and error
	//  handler for the parser. Then parse the file and catch any exceptions
	//  that propogate out
	//
	int errorCount = 0;
	int errorCode = 0;
	try
	{
		MyHandler handler;

		parser->setContentHandler(&handler);
		parser->setErrorHandler(&handler);
		parser->parse(xmlFile);
		errorCount = parser->getErrorCount();
	}
	catch (const OutOfMemoryException&)
	{
		std::cout << "OutOfMemoryException" << std::endl;
		errorCode = 5;          
	}
	catch (const XMLException& toCatch)
	{
		std::cout << "An error occurred." << std::endl;
		errorCode = 4;
	}

	if(errorCode) {
		XMLPlatformUtils::Terminate();
		return errorCode;
	}

	//
	//  Delete the parser itself.  Must be done prior to calling Terminate, below.
	//
	delete reader;
	if(filter)
		delete filter;

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

	getchar();

	if (errorCount > 0)
		return 4;
	else
		return 0;

}
Exemplo n.º 22
0
int main(int argc, char** argv)
{
  const char* encodingName = "UTF-8";
  //SAX2XMLReader::ValSchemes valScheme = SAX2XMLReader::Val_Auto;
  SAX2XMLReader::ValSchemes valScheme = SAX2XMLReader::Val_Always;
  bool expandNamespaces = false;
  bool doNamespaces = true;
  bool doSchema = true;
  bool schemaFullChecking = true;
  bool namespacePrefixes = false;
  SAX2XMLReader* parser = 0;
  
  try
  {
    XMLPlatformUtils::Initialize();
  }

  catch (const XMLException& toCatch)
  {
    cout << " Error during XML initialization :\n"
         << StrX(toCatch.getMessage()) << endl;
  }
    
  parser = XMLReaderFactory::createXMLReader();
  if (valScheme == SAX2XMLReader::Val_Auto)
  {
      parser->setFeature(XMLUni::fgSAX2CoreValidation, true);
      parser->setFeature(XMLUni::fgXercesDynamic, true);
  }

  if (valScheme == SAX2XMLReader::Val_Never)
  {
      parser->setFeature(XMLUni::fgSAX2CoreValidation, false);
  }

  if (valScheme == SAX2XMLReader::Val_Always)
  {
      parser->setFeature(XMLUni::fgSAX2CoreValidation, true);
      parser->setFeature(XMLUni::fgXercesDynamic, false);
  }

  parser->setFeature(XMLUni::fgSAX2CoreNameSpaces, doNamespaces);
  parser->setFeature(XMLUni::fgXercesSchema, doSchema);
  parser->setFeature(XMLUni::fgXercesSchemaFullChecking, schemaFullChecking);
  parser->setFeature(XMLUni::fgSAX2CoreNameSpacePrefixes, namespacePrefixes);

  int errorCount = 0;
  XMLPScanToken token;
 
  try
  {
    TestHandler handler;
    parser->setContentHandler(&handler);
    parser->setErrorHandler(&handler);

    if ( !parser->parseFirst(argv[1],token) )
    {
      cout << "parseFirst() failed" << endl;
      XMLPlatformUtils::Terminate();
      exit(1);
    }
    cout << "parseFirst() completed" << endl;

    bool gotMore = true;
    bool done = false;
    while ( gotMore && !done )
    {
      gotMore = parser->parseNext(token);
      if ( !gotMore )
        cout << "parseNext() returned 0" << endl;
      cout << "buffer = " << handler.buffer << endl;
      if ( handler.buffer.size() > 32 )
        handler.buffer = "";
    }

    errorCount = parser->getErrorCount();
    
    cout << handler.buffer << endl;
  }

  catch (const XMLException& toCatch)
  {
    cout << "\nAn error occurred\n  Error: "
         << StrX(toCatch.getMessage())
         << "\n" << endl;
    XMLPlatformUtils::Terminate();
    delete parser;
    throw;
  }

  catch (const SAXParseException& e)
  {
    cout << "\na SAXParseException occurred in file "
         << StrX(e.getSystemId())
         << ", line " << e.getLineNumber()
         << ", char " << e.getColumnNumber()
         << "\n  Message: " << StrX(e.getMessage()) << endl;
    XMLPlatformUtils::Terminate();
    delete parser;
    throw;
  }
 
  delete parser;
  XMLPlatformUtils::Terminate();
}
Exemplo n.º 23
0
//------------------------------------------------------------------------
//
//  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;
}
Exemplo n.º 24
0
/**
 * @brief Plug the handler into the handler driver
 * @param pHandler Pointer to the SAX handler to plug in
 * @param inputFileNames Vector of input XML files to parse
* @param debugOut The debug message output stream 
 * @date November 27, 2005
 * @author Mingsheng Hong ([email protected])
 * @version 1.0
 */
void pluginHandler (SimpleHandler* pHandler, 
					const vector<string>& inputFileNames,
					const size_t printFrequency,
					ostream& debugOut) {
	// Initialize the XML4C2 system
	//set default values as follows
	valScheme = SAX2XMLReader::Val_Never;
    doNamespaces = false;
	doSchema = false;

    //
    //  Create a SAX parser object. Then, according to what we were told on
    //  the command line, set it to validate or not.
    //
    SAX2XMLReader* parser;
    SAX2XMLReader* reader = XMLReaderFactory::createXMLReader();
    parser=reader;

    //
    //  Then, according to what we were told on
    //  the command line, set it to validate or not.
    //
    if (valScheme == SAX2XMLReader::Val_Auto) {
        parser->setFeature(XMLUni::fgSAX2CoreValidation, true);
        parser->setFeature(XMLUni::fgXercesDynamic, true);
    }

    if (valScheme == SAX2XMLReader::Val_Never) {
        parser->setFeature(XMLUni::fgSAX2CoreValidation, false);
    }

    if (valScheme == SAX2XMLReader::Val_Always) {
        parser->setFeature(XMLUni::fgSAX2CoreValidation, true);
        parser->setFeature(XMLUni::fgXercesDynamic, false);
    }

    parser->setFeature(XMLUni::fgSAX2CoreNameSpaces, doNamespaces);
    parser->setFeature(XMLUni::fgXercesSchema, doSchema);
    parser->setFeature(XMLUni::fgXercesSchemaFullChecking, schemaFullChecking);
    parser->setFeature(XMLUni::fgSAX2CoreNameSpacePrefixes, namespacePrefixes);

    //
    //  Create the handler object and install it as the document and error
    //  handler for the parser. Then parse the file and catch any exceptions
    //  that propogate out
    //

    int errorCount = 0;
    int errorCode = 0;
    try {
        parser->setContentHandler(pHandler);
        parser->setErrorHandler(pHandler);

		for (size_t fileIdx = 0; fileIdx < inputFileNames.size(); ++fileIdx) {
			const char* xmlFile = inputFileNames[fileIdx].c_str();
			if (fileIdx % printFrequency == 0) {
				debugOut
					<<"opening XML file "<<xmlFile<<endl;
			}
			try { 
				parser->parse(xmlFile);  
			}
			catch (string &s) {  
				//Ideally, this exception which stems from ValueIDMap OR AIR_Handler
				//should be a more "sophisticated" type, such as a CayugaException.
				cerr << "Cayuga could not use input file " << xmlFile 
					<<" "<< s <<endl;
				continue;
			}
		}

        errorCount = parser->getErrorCount();
    }
    catch (const OutOfMemoryException&) {
        XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" 
			<< XERCES_STD_QUALIFIER endl;
        errorCode = 5;          
    }
    catch (const XMLException& toCatch) {
        XERCES_STD_QUALIFIER cerr << "\nAn error occurred\n  Error: "
             << toCatch.getMessage()
             << "\n" << XERCES_STD_QUALIFIER endl;
        errorCode = 4;
    }

    if(errorCode) {
        XMLPlatformUtils::Terminate();
		cerr<<"SAX parser has error."<<endl;
		exit(-1);
    }

    //
    // Delete the parser itself. Must be done prior to calling Terminate, below.
    //
    delete reader;
}
Exemplo n.º 25
0
// ---------------------------------------------------------------------------
//  Program entry point
// ---------------------------------------------------------------------------
int main(int argC, char* argV[])
{
    // Initialize the XML4C2 system
    try
    {
        cms::concurrency::xercesInitialize();
    }

    catch (const XMLException& toCatch)
    {
        cerr << "Error during initialization! Message:\n"
            << StrX(toCatch.getMessage()) << endl;
        return 1;
    }

    // Check command line and extract arguments.
    if (argC < 2)
    {
        usage2();
        cms::concurrency::xercesTerminate();
        return 1;
    }

    const char*                  xmlFile      = 0;
    SAX2XMLReader::ValSchemes    valScheme    = SAX2XMLReader::Val_Auto;
    bool                         doNamespaces = true;
    bool                         doSchema = true;
    bool                         schemaFullChecking = false;
    bool                         doList = false;
    bool                         errorOccurred = false;
    bool                         namespacePrefixes = false;

    int argInd;
    for (argInd = 1; argInd < argC; ++argInd)
    {
        // Break out on first parm not starting with a dash
        if (argV[argInd][0] != '-')
            break;

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

            if (!strcmp(parm, "never"))
                valScheme = SAX2XMLReader::Val_Never;
            else if (!strcmp(parm, "auto"))
                valScheme = SAX2XMLReader::Val_Auto;
            else if (!strcmp(parm, "always"))
                valScheme = SAX2XMLReader::Val_Always;
            else
            {
                cerr << "Unknown -v= value: " << parm << endl;
                cms::concurrency::xercesTerminate();
                return 2;
            }
        }
         else if (!strcmp(argV[argInd], "-n")
              ||  !strcmp(argV[argInd], "-N"))
        {
            doNamespaces = false;
        }
         else if (!strcmp(argV[argInd], "-s")
              ||  !strcmp(argV[argInd], "-S"))
        {
            doSchema = false;
        }
         else if (!strcmp(argV[argInd], "-f")
              ||  !strcmp(argV[argInd], "-F"))
        {
            schemaFullChecking = true;
        }
         else if (!strcmp(argV[argInd], "-l")
              ||  !strcmp(argV[argInd], "-L"))
        {
            doList = true;
        }
         else if (!strcmp(argV[argInd], "-p")
              ||  !strcmp(argV[argInd], "-P"))
        {
            namespacePrefixes = true;
        }
         else if (!strcmp(argV[argInd], "-special:nel"))
        {
            // turning this on will lead to non-standard compliance behaviour
            // it will recognize the unicode character 0x85 as new line character
            // instead of regular character as specified in XML 1.0
            // do not turn this on unless really necessary
            XMLPlatformUtils::recognizeNEL(true);
        }
        else
        {
            cerr << "Unknown option '" << argV[argInd]
                << "', ignoring it\n" << endl;
        }
    }

    //
    //  There should be only one and only one parameter left, and that
    //  should be the file name.
    //
    if (argInd != argC - 1)
    {
        usage2();
        cms::concurrency::xercesTerminate();
        return 1;
    }

    //
    //  Create a SAX parser object. Then, according to what we were told on
    //  the command line, set it to validate or not.
    //
    SAX2XMLReader* parser = XMLReaderFactory::createXMLReader();
    parser->setFeature(XMLUni::fgSAX2CoreNameSpaces, doNamespaces);
    parser->setFeature(XMLUni::fgXercesSchema, doSchema);
    parser->setFeature(XMLUni::fgXercesSchemaFullChecking, schemaFullChecking);
    parser->setFeature(XMLUni::fgSAX2CoreNameSpacePrefixes, namespacePrefixes);

    if (valScheme == SAX2XMLReader::Val_Auto)
    {
        parser->setFeature(XMLUni::fgSAX2CoreValidation, true);
        parser->setFeature(XMLUni::fgXercesDynamic, true);
    }
    if (valScheme == SAX2XMLReader::Val_Never)
    {
        parser->setFeature(XMLUni::fgSAX2CoreValidation, false);
    }
    if (valScheme == SAX2XMLReader::Val_Always)
    {
        parser->setFeature(XMLUni::fgSAX2CoreValidation, true);
        parser->setFeature(XMLUni::fgXercesDynamic, false);
    }

    //
    //  Create our SAX handler object and install it on the parser, as the
    //  document and error handler.
    //
    SaxToDom2 handler;
    parser->setContentHandler(&handler);
    parser->setErrorHandler(&handler);

    //
    //  Get the starting time and kick off the parse of the indicated
    //  file. Catch any exceptions that might propogate out of it.
    //
    unsigned long TOTALduration = 0;
    unsigned long duration;

    bool more = true;
    ifstream fin;

    // the input is a list file
    if (doList)
        fin.open(argV[argInd]);

    cout << "argInd = " << argInd << endl;

    while (more)
    {
        char fURI[1000];
        //initialize the array to zeros
        memset(fURI,0,sizeof(fURI));

        if (doList) {
            if (! fin.eof() ) {
                fin.getline (fURI, sizeof(fURI));
                if (!*fURI)
                    continue;
                else {
                    xmlFile = fURI;
                    cerr << "==Parsing== " << xmlFile << endl;
                }
            }
            else
                break;
        }
        else {
            xmlFile = argV[argInd];
            more = false;
        }

        //reset error count first
        handler.resetErrors();

        try
        {
            const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis();
	     cout << "start parsing:" << xmlFile << endl;
            parser->parse(xmlFile);
	     cout << "parsing ended" << endl;
            const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis();
            duration = endMillis - startMillis;
	    TOTALduration += duration;
	    cout << "duration = " << duration << endl;
        }

        catch (const XMLException& e)
        {
            cerr << "\nError during parsing: '" << xmlFile << "'\n"
                << "Exception message is:  \n"
                << StrX(e.getMessage()) << "\n" << endl;
            errorOccurred = true;
            continue;
        }

        catch (...)
        {
            cerr << "\nUnexpected exception during parsing: '" << xmlFile << "'\n";
            errorOccurred = true;
            continue;
        }


        // Print out the stats that we collected and time taken
        if (true && getenv("DOTEST"))
        {
	
	   TinyDomTest2 test(handler.dom());
	   vector<const AttList2*> allAtts;
	   AttList2 atl2;
	   Node2 n2(TagName("Box"), atl2);
	   test.allNodes(n2, allAtts);
	   unsigned int i = 0;
	   for (; i < allAtts.size(); ++i) {
	      const AttList2 & a = *(allAtts[i]);
	      AttList2::const_iterator it = a.begin();
	      for (; it != a.end(); ++it) {
	         cout << it->first.str() << '=' << it->second.str() << ' ';
	      }
	      cout << endl;
	   }
	   cout << "dom-size=" << handler.dom().size() << endl;
	   /*
	   TinyDomWalker walker(handler.dom());
	   bool go = true;
	   TagName name("Box");
	   while (go) {
	      if (name.sameName(walker.current().first)) {
	        cout << walker.current().first.str() << endl;
	      }
	      go = walker.next();
	   }
	   */
	   
	   
	   
        }
        else
            errorOccurred = true;
    }

    if (doList)
        fin.close();

    cout << "Total Duration: ~ " << TOTALduration << endl;

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

    // And call the termination method
    cms::concurrency::xercesTerminate();

    if (errorOccurred)
        return 4;
    else
        return 0;

}
Exemplo n.º 26
0
// Main entry to read file and decode into objects
// xmlFile are command arg - relative or full path, dos path in windows
int CommonAnalysis::ReadFile(const char *xmlFile,bool useWorkingDir)
{
    // set directory of input file
    archiver->SetInputDirPath(xmlFile,useWorkingDir);

    // Initialize the XML4C2 system
    SAX2XMLReader* parser;
    try
    {   XMLPlatformUtils::Initialize();

        //  Create a SAX parser object.
        parser=XMLReaderFactory::createXMLReader();

        // Validation (first means yes or no, second means to skip if no DTD, even if yes)
        parser->setFeature(XMLString::transcode("http://xml.org/sax/features/validation"),GetValidate());
        parser->setFeature(XMLString::transcode("http://apache.org/xml/features/validation/dynamic"),true);
        if(!GetValidate())
        {   parser->setFeature(XMLString::transcode("http://apache.org/xml/features/nonvalidating/load-external-dtd"),
                               GetValidate());
        }

        // default settings
        parser->setFeature(XMLString::transcode("http://apache.org/xml/features/validation/schema"),doSchema);
        parser->setFeature(XMLString::transcode("http://apache.org/xml/features/validation/schema-full-checking"),schemaFullChecking);
    }

    catch(const XMLException& toCatch)
    {   cerr << "\nAn error occurred while initializing Xerces: "
             << StrX(toCatch.getMessage()) << endl;
        return XercesInitErr;
    }

    catch(std::bad_alloc&)
    {   cerr << "\nMemory error initializing Xerces" << endl;
        return XercesInitErr;
    }

    catch( ... )
    {   cerr << "\nUnexpected error initializing Xerces" << endl;
        return XercesInitErr;
    }

    // parce the file
#ifdef MPM_CODE
    MPMReadHandler *handler=new MPMReadHandler();
#else
    FEAReadHandler *handler=new FEAReadHandler();
#endif
    try
    {   // create the handler
        parser->setContentHandler(handler);
        parser->setErrorHandler(handler);
        parser->parse(xmlFile);

        // Reading done, not clean up and exit
#ifdef MPM_CODE
        delete parser;				// Must be done prior to calling Terminate, below.
#else
        // delete parser;			// not sure why cannot delete the parser in FEA code
#endif
        handler->FinishUp();
        delete handler;
        XMLPlatformUtils::Terminate();
    }

    catch(const XMLException& toCatch)
    {   char *message = XMLString::transcode(toCatch.getMessage());
        cerr << "\nParcing error: " << message << endl;
        return ReadFileErr;
    }

    catch(const SAXException& err)
    {   char *message = XMLString::transcode(err.getMessage());
        cerr << "\nInput file error: " << message << endl;
        return ReadFileErr;
    }

    catch(std::bad_alloc& ba)
    {   cerr << "\nMemory error: " << ba.what() << endl;
        return ReadFileErr;
    }

    catch(const char *errMsg)
    {   cerr << errMsg << endl;
        return ReadFileErr;
    }

    catch( ... )
    {   cerr << "Unexpected error occurred while reading XML file" << endl;
        return ReadFileErr;
    }

    return noErr;
}
Exemplo n.º 27
0
void
XML_Parser::parseFile(const std::string& emitClassQualifier_in,
                      const bool& emitStringConversionUtilities_in,
                      const bool& emitTaggedUnions_in,
                      const std::string& filename_in,
                      const bool& generateIncludeHeader_in,
                      const std::string& directory_in,
                      const std::string& preambleFilename_in,
                      const bool& filePerDefinition_in,
                      const std::string& typePrefix_in,
                      const std::string& typePostfix_in,
                      const bool& validate_in)
{
  ACE_TRACE(ACE_TEXT("XML_Parser::parseFile"));

  ACE_DEBUG((LM_DEBUG,
             ACE_TEXT("parsing (XML) file \"%s\"...\n"),
             filename_in.c_str()));

  // Create a SAX parser object. Then, according to what we were told on
  // the command line, set it to validate or not
  SAX2XMLReader* reader = NULL;
  try
  {
    reader = XMLReaderFactory::createXMLReader();
  }
  catch (...)
  {
    ACE_DEBUG((LM_ERROR,
               ACE_TEXT("caught exception in XMLReaderFactory::createXMLReader, returning\n")));

    return;
  }
  if (!reader)
  {
    ACE_DEBUG((LM_ERROR,
               ACE_TEXT("failed to XMLReaderFactory::createXMLReader, returning\n")));

    return;
  } // end IF

  // Then, according to what we were told on
  // the command line, set it to validate or not.
  if (validate_in)
  {
    // "automatic" validation...
    reader->setFeature(XMLUni::fgSAX2CoreValidation, true);
    reader->setFeature(XMLUni::fgXercesDynamic, true);
//     reader->setFeature(XMLUni::fgXercesDynamic, false);
  } // end IF
  else
  {
    reader->setFeature(XMLUni::fgSAX2CoreValidation, false);
  } // end ELSE

  reader->setFeature(XMLUni::fgSAX2CoreNameSpaces, true);
  reader->setFeature(XMLUni::fgXercesSchema, true);
//   reader->setFeature(XMLUni::fgXercesHandleMultipleImports, true);
  reader->setFeature(XMLUni::fgXercesSchemaFullChecking, true);
  reader->setFeature(XMLUni::fgSAX2CoreNameSpacePrefixes, true);

  // Create the handler object and install it as the document and error
  // handler for the parser. Then parse the file and catch any exceptions
  // that propogate out
  int errorCount = 0;
  std::string schemaFilename = ACE::basename(filename_in.c_str());
  std::string preamble;
  ACE_stat stat;
  if (!preambleFilename_in.empty() &&
      (ACE_OS::stat(preambleFilename_in.c_str(), &stat) != -1)) // exists ?
  {
    std::ifstream preambleStream(preambleFilename_in.c_str(), std::ios_base::in);
    if (!preambleStream.is_open())
    {
      ACE_DEBUG((LM_ERROR,
                 ACE_TEXT("failed to open preamble file: \"%s\", returning\n"),
                 preambleFilename_in.c_str()));

      return;
    } // end IF
    std::string line;
    while (std::getline(preambleStream, line))
    {
      preamble += line;
      preamble += ACE_TEXT_ALWAYS_CHAR("\n");
    } // end WHILE
    preambleStream.close();
  } // end IF
  XML_Handler handler(emitClassQualifier_in,
                      emitStringConversionUtilities_in,
                      emitTaggedUnions_in,
                      schemaFilename,
                      generateIncludeHeader_in,
                      directory_in,
                      preamble,
                      filePerDefinition_in,
                      typePrefix_in,
                      typePostfix_in);
  try
  {
    reader->setContentHandler(&handler);
    reader->setErrorHandler(&handler);
    reader->parse(filename_in.c_str());
    errorCount = reader->getErrorCount();
  }
  catch (const OutOfMemoryException& exception_in)
  {
    char* message = XMLString::transcode(exception_in.getMessage());
    ACE_ASSERT(message);

    ACE_DEBUG((LM_ERROR,
               ACE_TEXT("caught OutOfMemoryException: \"%s\", returning\n"),
			   message));

		// clean up
		XMLString::release(&message);
		delete reader;
    reader = NULL;

    return;
  }
  catch (const XMLException& exception_in)
  {
    char* message = XMLString::transcode(exception_in.getMessage());
    ACE_ASSERT(message);

    ACE_DEBUG((LM_ERROR,
               ACE_TEXT("caught XMLException: \"%s\", returning\n"),
               message));

    // clean up
    XMLString::release(&message);
    delete reader;
    reader = NULL;

    return;
  }
  catch (const SAXParseException& exception_in)
  {
    char* message = XMLString::transcode(exception_in.getMessage());
    ACE_ASSERT(message);

    ACE_DEBUG((LM_ERROR,
               ACE_TEXT("caught SAXParseException: \"%s\", returning\n"),
               message));

    // clean up
    XMLString::release(&message);
    delete reader;
    reader = NULL;

    return;
  }
  catch (...)
  {
    ACE_DEBUG((LM_ERROR,
               ACE_TEXT("SAX2XMLReader: caught exception, returning\n")));

    // clean up
    delete reader;
    reader = NULL;

    return;
  }

  // Delete the parser itself. Must be done prior to calling Terminate
  delete reader;
  reader = NULL;

  ACE_DEBUG((LM_DEBUG,
             ACE_TEXT("parsing (XML) file \"%s\"...finished (%d errors)\n"),
             ACE_TEXT(filename_in.c_str()),
             errorCount));
}
Exemplo n.º 28
0
//____________________________________________________________________________
void X2DB::parse(request_rec *r, my_server_config *config, const char *buf,
				 apr_size_t len)
{
	try {
		XMLPlatformUtils::Initialize();
	} catch (const XMLException &x) {
		XERCES_STD_QUALIFIER cout << "Error during initialization! :\n"
			<< XMLString::transcode(x.getMessage()) << XERCES_STD_QUALIFIER endl;
		return;
	}
    SAX2XMLReader *parser = XMLReaderFactory::createXMLReader();
	parser->setFeature(XMLUni::fgSAX2CoreValidation, true);
	parser->setFeature(XMLUni::fgXercesDynamic, true);
    parser->setFeature(XMLUni::fgSAX2CoreNameSpaces, true);
    parser->setFeature(XMLUni::fgXercesSchema, true);
    parser->setFeature(XMLUni::fgXercesSchemaFullChecking, false);
    parser->setFeature(XMLUni::fgSAX2CoreNameSpacePrefixes, false);
    int errorCode = 0;
	try {
		X2DB handler(r, config);
		parser->setContentHandler(&handler);
		parser->setErrorHandler(&handler);
		ap_rputs("<result>", r);
		parser->parse(MemBufInputSource(reinterpret_cast<XMLByte *>(const_cast<char *>(buf)), len, "HTTP"));
		ap_rprintf(r, "<parse-errors count=\"%d\"/>", parser->getErrorCount());
		ap_rputs("</result>", r);
	} catch (const OutOfMemoryException &) {
		XERCES_STD_QUALIFIER cout << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl;
		errorCode = 5;
	} catch (const XMLException &x) {
		XERCES_STD_QUALIFIER cout << "\nAn error occurred\n  Error: "
			<< XMLString::transcode(x.getMessage())
			<< "\n" << XERCES_STD_QUALIFIER endl;
		errorCode = 4;
	}
	if (errorCode) {
		XMLPlatformUtils::Terminate();
		return;
	}
	delete parser;
	XMLPlatformUtils::Terminate();
	return;
}
Exemplo n.º 29
0
bool amis::io::XercesSaxParseBase::parseFile(const ambulant::net::url* filepath)
{
	SAX2XMLReader* parser;
	mFilepath = *filepath;
	mError.clear();
	amis::util::Log::Instance()->writeMessage("Parsing file: ", filepath, "XercesSaxParseBase::parseFile");
	//try-catch block for Xerces platform utilities
	try
	{
		XMLPlatformUtils::Initialize();
	}
	
	catch (const XMLException& toCatch)
	{
		mError.setCode(amis::PARSE_ERROR);
		char *msg = XMLString::transcode(toCatch.getMessage());
		string str;
		str.assign(msg);	
		mError.setMessage(str);
		XMLString::release(&msg);
		amis::util::Log::Instance()->writeError(mError, "XercesSaxParseBase::parseFile");
		return false;
	}
		
	//assuming we've made it this far, create a new parser
	parser = XMLReaderFactory::createXMLReader();

	//set these parser features to turn off DTD loading and validation
	parser->setFeature(XMLUni::fgXercesLoadExternalDTD, false);
	parser->setFeature(XMLUni::fgSAX2CoreValidation, false);
	
	amis::io::UrlInputSource* p_input_source = amis::io::NewUrlInputSource(mFilepath);
	if (p_input_source == NULL)
	{
		mError.setCode(amis::PARSE_ERROR);
		string str;
		str.assign("Could not create input source for " + mFilepath.get_url());	
		mError.setMessage(str);
		delete p_input_source;
		delete parser;
		XMLPlatformUtils::Terminate();
		amis::util::Log::Instance()->writeError(mError, "XercesSaxParseBase::parseFile");
		return false;
	}

	//try-catch block for Xerces parsing
	try 
	{
		//give the sax parser pointers to our content and error handler object
		parser->setContentHandler(this);
		parser->setErrorHandler(this);
		//parser begins parsing; expect SAX Events soon
		parser->parse((*p_input_source));
	}
	
	catch (const XMLException& toCatch)
	{	
		mError.setCode(amis::PARSE_ERROR);
		char *msg = XMLString::transcode(toCatch.getMessage());
		string str;
		str.assign(msg);	
		mError.setMessage(str);
		XMLString::release(&msg);
		delete p_input_source;
		delete parser;
		XMLPlatformUtils::Terminate();
		amis::util::Log::Instance()->writeError(mError, "XercesSaxParseBase::parseFile");
		return false;
	}
	
	delete p_input_source;
	delete parser;

	try
	{
		XMLPlatformUtils::Terminate();
	}
	catch (...)//const XMLException& toCatch)
	{
		amis::util::Log::Instance()->writeWarning("Exception while terminating XMLPlatformUtils", 
			"XercesSaxParseBase::parseFile");
	}

	if (mError.getCode() != amis::OK) return false;
	amis::util::Log::Instance()->writeMessage("Done parsing.", "XercesSaxParseBase::parseFile");
	return true;

}
// ---------------------------------------------------------------------------
//  Program entry point
// ---------------------------------------------------------------------------
int main(int argC, char* argV[])
{
    // Initialize the XML4C2 system
    try
    {
         XMLPlatformUtils::Initialize();
    }

    catch (const XMLException& toCatch)
    {
         XERCES_STD_QUALIFIER cerr << "Error during initialization! :\n"
              << StrX(toCatch.getMessage()) << XERCES_STD_QUALIFIER endl;
         return 1;
    }

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

    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"))
                valScheme = SAX2XMLReader::Val_Never;
            else if (!strcmp(parm, "auto"))
                valScheme = SAX2XMLReader::Val_Auto;
            else if (!strcmp(parm, "always"))
                valScheme = SAX2XMLReader::Val_Always;
            else
            {
                XERCES_STD_QUALIFIER cerr << "Unknown -v= value: " << parm << XERCES_STD_QUALIFIER endl;
                XMLPlatformUtils::Terminate();
                return 2;
            }
        }
         else if (!strcmp(argV[parmInd], "-e")
              ||  !strcmp(argV[parmInd], "-E"))
        {
            expandNamespaces = true;
        }
         else if (!strncmp(argV[parmInd], "-x=", 3)
              ||  !strncmp(argV[parmInd], "-X=", 3))
        {
            // Get out the encoding name
            encodingName = &argV[parmInd][3];
        }
         else if (!strncmp(argV[parmInd], "-u=", 3)
              ||  !strncmp(argV[parmInd], "-U=", 3))
        {
            const char* const parm = &argV[parmInd][3];

            if (!strcmp(parm, "fail"))
                unRepFlags = XMLFormatter::UnRep_Fail;
            else if (!strcmp(parm, "rep"))
                unRepFlags = XMLFormatter::UnRep_Replace;
            else if (!strcmp(parm, "ref"))
                unRepFlags = XMLFormatter::UnRep_CharRef;
            else
            {
                XERCES_STD_QUALIFIER cerr << "Unknown -u= value: " << parm << XERCES_STD_QUALIFIER endl;
                XMLPlatformUtils::Terminate();
                return 2;
            }
        }
         else if (!strcmp(argV[parmInd], "-n")
              ||  !strcmp(argV[parmInd], "-N"))
        {
            doNamespaces = false;
        }
         else if (!strcmp(argV[parmInd], "-s")
              ||  !strcmp(argV[parmInd], "-S"))
        {
            doSchema = false;
        }
         else if (!strcmp(argV[parmInd], "-f")
              ||  !strcmp(argV[parmInd], "-F"))
        {
            schemaFullChecking = true;
        }
         else if (!strcmp(argV[parmInd], "-p")
              ||  !strcmp(argV[parmInd], "-P"))
        {
            namespacePrefixes = true;
        }
         else if (!strcmp(argV[parmInd], "-sa"))
        {
            sortAttributes = true;
        }
         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;
    }
    xmlFile = argV[parmInd];

    //
    //  Create a SAX parser object. Then, according to what we were told on
    //  the command line, set it to validate or not.
    //
    SAX2XMLReader* parser;
    SAX2XMLReader* reader = XMLReaderFactory::createXMLReader();
    SAX2XMLReader* filter = NULL;
    if(sortAttributes)
    {
        filter=new SAX2SortAttributesFilter(reader);
        parser=filter;
    }
    else
        parser=reader;

    //
    //  Then, according to what we were told on
    //  the command line, set it to validate or not.
    //
    if (valScheme == SAX2XMLReader::Val_Auto)
    {
        parser->setFeature(XMLUni::fgSAX2CoreValidation, true);
        parser->setFeature(XMLUni::fgXercesDynamic, true);
    }

    if (valScheme == SAX2XMLReader::Val_Never)
    {
        parser->setFeature(XMLUni::fgSAX2CoreValidation, false);
    }

    if (valScheme == SAX2XMLReader::Val_Always)
    {
        parser->setFeature(XMLUni::fgSAX2CoreValidation, true);
        parser->setFeature(XMLUni::fgXercesDynamic, false);
    }

    parser->setFeature(XMLUni::fgSAX2CoreNameSpaces, doNamespaces);
    parser->setFeature(XMLUni::fgXercesSchema, doSchema);
    parser->setFeature(XMLUni::fgXercesSchemaFullChecking, schemaFullChecking);
    parser->setFeature(XMLUni::fgSAX2CoreNameSpacePrefixes, namespacePrefixes);

    //
    //  Create the handler object and install it as the document and error
    //  handler for the parser. Then parse the file and catch any exceptions
    //  that propogate out
    //

    int errorCount = 0;
    int errorCode = 0;
    try
    {
        SAX2PrintHandlers handler(encodingName, unRepFlags, expandNamespaces);
        parser->setContentHandler(&handler);
        parser->setErrorHandler(&handler);
        parser->parse(xmlFile);
        errorCount = parser->getErrorCount();
    }
    catch (const OutOfMemoryException&)
    {
        XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl;
        errorCode = 5;          
    }
    catch (const XMLException& toCatch)
    {
        XERCES_STD_QUALIFIER cerr << "\nAn error occurred\n  Error: "
             << StrX(toCatch.getMessage())
             << "\n" << XERCES_STD_QUALIFIER endl;
        errorCode = 4;
    }

    if(errorCode) {
        XMLPlatformUtils::Terminate();
        return errorCode;
    }

    //
    //  Delete the parser itself.  Must be done prior to calling Terminate, below.
    //
    delete reader;
    if(filter)
        delete filter;

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

    if (errorCount > 0)
        return 4;
    else
        return 0;
}