示例#1
0
/**
 * Private method to orchestrate the XML parsing using DOM.
 */
int ParameterSet::parseDOM(const char* xmlFile)
{
	bool doNamespaces = true;
	bool doSchema = true;
	bool schemaFullChecking = true;

	// Instantiate the DOM parser.
	static const XMLCh gLS[] = { chLatin_L, chLatin_S, chNull };
	DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(gLS);
	DOMBuilder        *parser = ((DOMImplementationLS*)impl)->createDOMBuilder(DOMImplementationLS::MODE_SYNCHRONOUS, 0);

	parser->setFeature(XMLUni::fgDOMNamespaces, doNamespaces);
	parser->setFeature(XMLUni::fgXercesSchema, doSchema);
	parser->setFeature(XMLUni::fgXercesSchemaFullChecking, schemaFullChecking);
	parser->setFeature(XMLUni::fgDOMValidation, true);

	// enable datatype normalization - default is off
	parser->setFeature(XMLUni::fgDOMDatatypeNormalization, true);

	/*******************
	// optionally you can implement your DOMErrorHandler (e.g. MyDOMErrorHandler)
	// and set it to the builder
	*******************/
	MyDOMErrorHandler* errHandler = new MyDOMErrorHandler();
	parser->setErrorHandler(errHandler);

	DOMDocument *doc = 0;
	
	try {
		doc = parser->parseURI(xmlFile);
		std::cout << "parsed file: " << xmlFile <<"\n";

		// Get all parameters
		DOMNodeList * paramNodes = doc->getElementsByTagName(PARAMETER_TAG_NAME);
		if(NULL != paramNodes) {
			processParamNodes(paramNodes);
		}
	}
	catch (const XMLException& toCatch) {
		char* message = XMLString::transcode(toCatch.getMessage());
		std::cout << "Exception message is: \n" << message << "\n";
		XMLString::release(&message);
		return -1;
	}
	catch (const DOMException& toCatch) {
		char* message = XMLString::transcode(toCatch.msg);
		std::cout << "Exception message is: \n" << message << "\n";
		XMLString::release(&message);
		return -1;
	}
	catch (...) {
		std::cout << "Unexpected Exception in ParameterSet\n" ;
		return -1;
	}

	parser->release();
	delete errHandler;
	return 0;
}
示例#2
0
// 解析TMS返回xml
bool  CTMSSensor::ParseXmlFromTMS(std::string &retXml,int &nRet)
{
	XercesDOMParser *ptrParser = new  XercesDOMParser;
	ptrParser->setValidationScheme(  XercesDOMParser::Val_Never );
	ptrParser->setDoNamespaces( true );
	ptrParser->setDoSchema( false );
	ptrParser->setLoadExternalDTD( false );
	InputSource* ptrInputsource = new  MemBufInputSource((XMLByte*)retXml.c_str(), retXml.size(), "bufId");

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

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


	delete ptrParser;
	delete ptrInputsource;
	ptrInputsource = NULL;
	ptrParser = NULL;
	return true;
}
bool  validateXMLs(char* xmlDirPath, XercesDOMParser* parser)
{
	DIR *pDIR;
	struct dirent *entry;

	cout<<endl<<"Starting validateXMLs... "<<endl;
	if( pDIR = opendir(xmlDirPath) )
	{
		while( entry = readdir(pDIR) )
		{
			if( strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0 )
			{
				static int index = 0;
				if ( entry->d_type == DT_DIR )
				{
					continue;
				}

				string fullPath = string(xmlDirPath) + entry->d_name;

				if ( fullPath.find(".xml")==string::npos )
				{
					continue;
				}

				parser->parse(fullPath.c_str());
				if ( verboseOutput )
				{
					DOMDocument* doc = parser->getDocument();
					DOMNodeList *lst = doc->getElementsByTagName(XS("epp"));
					browseTree(lst->item(0));
				}

				int rc = parser->getErrorCount();
				if ( rc == 0 )
				{
					cout<<"PASSED:: FILE: "<<fullPath;
				}
				else
				{
					cout<<"FAILED:: FILE: "<<fullPath;
				}
				cout<<endl;
			}
		}
		closedir(pDIR);
	}
	cout<<endl<<"Starting validateXMLs...done "<<endl;
	return true;
}
示例#4
0
int ModelicaXML::serializeMoFileToXML(char* fileName)
{
  // ModelicaXML filename (normal operation)
  DOMElement *pModelicaXMLElement = createModelicaXMLDOMElement(fileName);
  if (pModelicaXMLElement) pRootElementModelica->appendChild(pModelicaXMLElement);
  // vomit the current XML Document to file
  std::string xmlFile(fileName);
  xmlFile += ".xml";
  serializeXMLDocumentToFile(xmlFile);

  XMLSize_t elementCount = pModelicaXMLDoc->getElementsByTagName(X("*"))->getLength();
  std::cout << std::endl;
  std::cout << "The tree serialized contains: " << elementCount << " elements." << std::endl;

  return 0;
}
bool ConfigurationFileHandler::getSubAlgorithm(std::string algorithm, std::string subalgorithm, std::string* result){
#ifdef BRICS_XERCES_ENABLE
	if (errorsOccured) {
		return false;
	}

    DOMNode* current = NULL;
    DOMNode* attributeNode = NULL;
    XMLCh* algorithmName = XMLString::transcode(algorithm.c_str());
    XMLCh* subAlgorithmName = XMLString::transcode(subalgorithm.c_str());
    XMLCh* implementationString = XMLString::transcode("implementation");
    bool subAlgorithmFound = false;

    DOMDocument* doc = parser->getDocument();
    DOMNodeList* root = doc->getElementsByTagName(algorithmName);
    if (root->getLength() > 1) {
    	LOG(WARNING) << "More than one " << algorithm << " found, taking the first one";
    } else if(root->getLength() < 1) {
    	LOG(WARNING) << "No algorithm called " << algorithm << " found.";
		return false; //TODO release resouces
    }

    current = root->item(0);

    //search in children notes
	for (current = current->getFirstChild()->getNextSibling(); current!=NULL; current = current->getNextSibling()) {
		string nodeName = XMLString::transcode(current->getNodeName());
		if (nodeName.compare(subalgorithm) == 0) {
		    DOMNamedNodeMap* attributesList =  current->getAttributes();
		    attributeNode = attributesList->getNamedItem(implementationString);
		    if (attributeNode != 0) {
		    	*result = XMLString::transcode(attributeNode->getNodeValue());
		    	subAlgorithmFound = true;
		    	break; //take only first found
		    }
		}
	}

    XMLString::release(&algorithmName);
    XMLString::release(&subAlgorithmName);
    XMLString::release(&implementationString);

    return subAlgorithmFound;
#else
    return false;
#endif
}
示例#6
0
/*
	\brief It accepts a XML (ascii) buffer and it parses it.

	This function is used when we have a char buffer containing an XML fragment, and we have to parse it.
	This function returns the list of PSML items (&lt;section&gt;) contained in the XML buffer.

	\param Buffer: pointer to a buffer that contains the XML fragment (in ascii).
	\param BufSize: number of valid bytes in the previous buffer; not NULL terminated buffers are supported as well.

	\return A pointer to the list of &lt;section&gt; nodes contained into the XML fragment if everything
	is fine, NULL otherwise.
	In case of error, the error message can be retrieved by the GetLastError() method.
*/
DOMNodeList *CPSMLReader::ParseMemBuf(char *Buffer, int BytesToParse)
{
DOMDocument *Document;
XMLCh TempBuffer[NETPDL_MAX_STRING + 1];
MemBufInputSource MemBuf( (const XMLByte *) Buffer, BytesToParse, "", false);

	try
	{
		// Reset any other document previously created
		m_DOMParser->resetDocumentPool();

		// Load the description in memory and get document root
		m_DOMParser->parse(MemBuf);

		Document= m_DOMParser->getDocument();

		if ( (Document->getDocumentElement()) == NULL)
		{
			errorsnprintf(__FILE__, __FUNCTION__, __LINE__, m_errbuf, sizeof(m_errbuf),
				"Fatal error: cannot parse PSML file. Possible errors: "
				"wrong file location, or not well-formed XML file.");
			return NULL;
		}
	}
	catch (...)
	{
		errorsnprintf(__FILE__, __FUNCTION__, __LINE__, m_errbuf, sizeof(m_errbuf), "Unexpected exception during PSML buffer parsing.");
		return NULL;
	}

	if (Document == NULL)
	{
		errorsnprintf(__FILE__, __FUNCTION__, __LINE__, m_errbuf, sizeof(m_errbuf), "Unexpected exception during PSML buffer parsing.");
		return NULL;
	}

	XMLString::transcode(PSML_SECTION, TempBuffer, NETPDL_MAX_STRING);

	// After parsing the '<packet>' fragment, let's list the <section> contained into it
	return Document->getElementsByTagName(TempBuffer);
}
bool ConfigurationFileHandler::getAttribute(std::string algorithm, std::string attribute, int* result) {
#ifdef BRICS_XERCES_ENABLE
	if (errorsOccured) {
		return false;
	}

    DOMNode* current = NULL;
    DOMNode* attributeNode = NULL;
    XMLCh* algorithmName = XMLString::transcode(algorithm.c_str());
    XMLCh* attributeName = XMLString::transcode(attribute.c_str());
    string tmpResult;
    bool attributeFound = false;

    DOMDocument* doc = parser->getDocument();
    DOMNodeList* root = doc->getElementsByTagName(algorithmName);
    if (root->getLength() > 1) {
    	LOG(WARNING) << "More than one " << algorithm << " found, taking the first one";
    } else if(root->getLength() < 1) {
    	LOG(WARNING) << "No algorithm called " << algorithm << " found.";
		return false; //TODO release resouces
    }

    current = root->item(0);
    DOMNamedNodeMap* attributesList =  current->getAttributes();
    attributeNode = attributesList->getNamedItem(attributeName);

    if (attributeNode != 0) {
		    tmpResult = XMLString::transcode(attributeNode->getNodeValue());
		    *result = atoi(tmpResult.c_str());
		    attributeFound = true;
	}

    XMLString::release(&algorithmName);
    XMLString::release(&attributeName);

    return attributeFound;
#else
    return false;
#endif
}
示例#8
0
PerfPart::PerfPart( PMLDocument *doc, ScorePart *part ){
    m_doc = doc;

    DOMDocument *domdoc = part->getElement()->getOwnerDocument();
    m_scorePart = part;
    m_element = domdoc->createElement( XS("perfpart") );       //'perfpart' tag is the m_element for this class

  //create part attribute
    m_element->setAttribute( XS("part"), XS( m_scorePart->getID().c_str() ) );
  
  //append part to performance element
    DOMElement *perf = (DOMElement*)domdoc->getElementsByTagName(XS("performance"))->item(0);
    perf->appendChild( m_element );

    DOMNodeList *nl = m_element->getElementsByTagName(XS(PNote::Tag));

    for( int i=0; i<nl->getLength(); i++ ){
        m_notes.push_back( new PNote( m_doc, (DOMElement*)nl->item(i) ) );

    }

}
int main(int argc, char ** argv) {

   //
    // Initialize the Xerces-c environment
    //
	try
    {
        XMLPlatformUtils::Initialize();
    }

    catch (const XMLException& toCatch)
    {
        fprintf(stderr, "Error during initialization of xerces-c: %s\n",
            XMLString::transcode(toCatch.getMessage()));
         return 1;
    }

    //
    // Parse the command line, which should specify exactly one file, which is an
    //   xml file containing the list of test files to be processed.
    //
    if (argc != 2) {
        printf("usage: %s file_name \n"
               "   where file name is the xml file specifying the list of test files.", argv[0]);
        return 1;
    }
    DOMDocument* fileListDoc = parseFile(argv[1]);
    if (fileListDoc == 0) return 1;


    //
    // Iterate over the list of files, running each as a test.
    //
    XMLCh tempStr[4000];
    XMLString::transcode("testFile", tempStr, 3999);
    DOMNodeList* list = fileListDoc->getElementsByTagName(tempStr);
    int i;
    int numFiles = list->getLength();
    for (i=0; i<numFiles; i++)
    {
        ++gTestsRun;
        DOMNode* tmpNode3 = list->item(i);
        XMLString::transcode("name", tempStr, 3999);
        const XMLCh* fileName = ((DOMElement*) tmpNode3)->getAttribute(tempStr);
        if (processTestFile(fileName) == false)
            ++gTestsFailed;
    };



    //
    // We are done.  Print out a summary of the results
    //
    printf("Encoding Tests Results Summary: \n"
           "   %d encoding tests run.\n"
           "   %d tests passed,\n"
           "   %d tests failed\n", gTestsRun, gTestsRun-gTestsFailed, gTestsFailed);

    delete parser;
    parser = 0;
   return 0;
};
//------------------------------------------------------------------------
//
//  processTestFile   Given the file name of an encoding test xml file,
//                    run it.
//
//------------------------------------------------------------------------
static bool  processTestFile(const XMLCh* fileName)
{
    //
    //  Send the input file through the parse, create a DOM document for it.
    //
    char cFileName[4000];
    XMLString::transcode(fileName, cFileName, 3999);
    DOMDocument* testDoc = parseFile(cFileName);
    if (testDoc == 0)
        return false;    // parse errors in the source xml.

    //
    //  Pull the "data" element out of the document.
    //
    XMLCh tempStr[4000];
    XMLString::transcode("data", tempStr, 3999);
    DOMNodeList* nl = testDoc->getElementsByTagName(tempStr);
    if (nl->getLength() != 1) {
        fprintf(stderr, "Test file \"%s\" must have exactly one \"data\" element.\n", cFileName);
        return false;
    };
    DOMNode* tmpNode = nl->item(0);
    DOMElement* data = (DOMElement*) tmpNode;


    //
    //  Build up a string containing the character data contents of the data element.
    //
    DOMNode* child;
    XMLBuffer elData;
    for (child=data->getFirstChild(); child != 0; child= child->getNextSibling())
    {
		if (child->getNodeType() == DOMNode::COMMENT_NODE)
			continue;
        if (! (child->getNodeType() == DOMNode::TEXT_NODE ||
               child->getNodeType() == DOMNode::CDATA_SECTION_NODE ||
               child->getNodeType() == DOMNode::ENTITY_REFERENCE_NODE))
        {
               fprintf(stderr, "Test file \"%s\": data element contains unexpected children.",
                    cFileName);
               return false;
        }
        elData.append(((DOMCharacterData *)child)->getData());
    };

    //
    //  Pull the "udata" element out of the document
    //
    XMLString::transcode("udata", tempStr, 3999);
    nl = testDoc->getElementsByTagName(tempStr);
    if (nl->getLength() != 1) {
        fprintf(stderr, "Test file \"%s\" must have exactly one \"udata\" element.\n", cFileName);
        return false;
    };
    DOMNode* tmpNode1 = nl->item(0);
    DOMElement* udata = (DOMElement*) tmpNode1;

    //
    //  Build up a string containing the character data contents of the udata element.
    //  This will consist of a whole bunch hex numbers, still in string from
    //

    XMLBuffer rawUData;
    for (child=udata->getFirstChild(); child != 0; child= child->getNextSibling())
    {
        if (child->getNodeType() == DOMNode::COMMENT_NODE)
            continue;
        if (! (child->getNodeType() == DOMNode::TEXT_NODE ||
            child->getNodeType() == DOMNode::CDATA_SECTION_NODE ||
            child->getNodeType() == DOMNode::ENTITY_REFERENCE_NODE))
        {
            fprintf(stderr, "Test file \"%s\": udata element contains unexpected children.",
                cFileName);
            return false;
        }
        rawUData.append(((DOMCharacterData *)child)->getData());
    };


    //
    // Convert the raw (hex numbers)  form of the udata to the corresponding string.
    //
    XMLBuffer uData;
    unsigned int rawIndex = 0;

    while (rawIndex < rawUData.getLen())
    {
        eatWhiteSpace(rawUData.getRawBuffer(), rawIndex);
        XMLCh c = convertHexValue(rawUData.getRawBuffer(), rawIndex);
        if (c > 0)
            uData.append(c);
        else
            if (rawIndex < rawUData.getLen())
            {
                fprintf(stderr, "Test file \"%s\": Bad hex number in udata element.  "
                    "Data character number %d\n", cFileName, uData.getLen());
                return false;
            }
    }


    //
    // Compare the two strings.
    //
    unsigned int i;
    for (i=0; i< elData.getLen(); i++)
    {
        XMLCh* elDataRaw = elData.getRawBuffer();
        XMLCh* uDataRaw = uData.getRawBuffer();
        if (i >= uData.getLen())
        {
            fprintf(stderr, "Test file \"%s\": udata element shorter than data at char number %d\n",
                cFileName, i);
            writeUData(elDataRaw);
            return false;
        }
        if (uDataRaw[i] != elDataRaw[i])
        {
            fprintf(stderr, "Test file \"%s\": comparison failure at character number %d\n",
                cFileName, i);
            writeUData(elDataRaw);
            return false;
        };
    }

    if (elData.getLen() != uData.getLen())
    {
        fprintf(stderr, "Test file \"%s\": udata element longer than data at char number %d\n",
            cFileName, i);
        writeUData(elData.getRawBuffer());
        return false;
    }

    return true;
}
/*
 *  main function
 */
int main(int argc, char** argv) {

	//Scene root, to load all things
	osg::ref_ptr<osg::Group> root = new osg::Group;

	//To add urban background into the scene
	osg::ref_ptr<osg::Node> city = osgDB::readNodeFile("Data/cityLOD0A.osg");
	// osg::ref_ptr<osg::Node> city = osgDB::readNodeFile("Data/cityLOD1.osg");
	osg::ref_ptr<osg::Node> others = osgDB::readNodeFile("Data/others.osg");


    // optimize the scene graph, remove redundant nodes and state etc.
    osgUtil::Optimizer optimizer;

    optimizer.optimize(city);

	root->addChild(city);
	root->addChild(others);

	//A camera for HUD text
	osg::ref_ptr<osg::Camera> Cam = new osg::Camera;

    //Get screen center to be stored in two global variants to be used in later calculation
	GetScreenCenter(ScrCenterX, ScrCenterY);
	SetUpCamera(Cam);


    root->addChild(Cam);
	//Here needs this geode to be replaced in the loop, otherwise impossible to add texts into scene
	std::string datapath, positionpath;

	//A simple function to differentiate displayed info for each function
	MatchDataPosition(datapath, positionpath);
	datapath = "Data/RoadNamesFrench.xml";
	positionpath = "Data/Position1.xml";
	myXparser datasetParser;
	myXparser positionParser;
	datasetParser.readXMLFile(datapath);
	positionParser.readXMLFile(positionpath);
	DOMDocument* datasetDoc = datasetParser.getParseredDoc();
	DOMDocument* positionDoc = positionParser.getParseredDoc();
	DOMNodeList* dataset = datasetDoc->getElementsByTagName(
			XMLString::transcode("Info"));
	DOMNodeList* position = positionDoc->getElementsByTagName(
			XMLString::transcode("Info"));

//	osg::ref_ptr<osg::Geode> textnode = loadInfo(dataset, position);
//	osg::ref_ptr<osg::Group> textGroup = new osg::Group;
//	textGroup->addChild(textnode);
	osg::ref_ptr<osg::Group> textGroup = loadInfo(dataset, position);
	root->addChild(textGroup);


	//Pour afficher des cercles sous les textes pour repérer la position sur la carte

	osg::ref_ptr<osg::Shape> myCircle (new osg::Cylinder(osg::Vec3d(0.0, 0.0, 0.0), 10.0f, 0.0f));
	osg::ref_ptr<osg::ShapeDrawable> circleDrawable (new osg::ShapeDrawable(myCircle.get()));

	circleDrawable->setColor(osg::Vec4d(0.0,0.0,0.0,1.0));

	osg::ref_ptr<osg::Group> circleGroup (new osg::Group);
	osg::ref_ptr<osg::Geode> circleGeode (new osg::Geode);

    const XMLCh* xmlch_x;
    const XMLCh* xmlch_y;
    const XMLCh* xmlch_z;

    root->addChild(circleGroup.get());

	for(int i=0; i < (position->getLength()); i++){
        osg::Vec3d positionTexte;

        DOMNode* positionNode = position->item(i);
        DOMElement* positionElement = dynamic_cast<xercesc::DOMElement*>(positionNode);

        xmlch_x = positionElement->getAttribute(XMLString::transcode("X"));
        xmlch_y = positionElement->getAttribute(XMLString::transcode("Y"));
        xmlch_z = positionElement->getAttribute(XMLString::transcode("Z"));

        osg::Vec3 ObjTextPos;
        ObjTextPos.set(atoi(XMLString::transcode(xmlch_x)),
						atoi(XMLString::transcode(xmlch_y)),
						atoi(XMLString::transcode(xmlch_z)));

        osg::ref_ptr<osg::PositionAttitudeTransform> positionCourant (new osg::PositionAttitudeTransform);

        positionCourant->setPosition(ObjTextPos);

        circleGeode->addChild(new osg::Geode);
        osg::Geode* noeudCourant = circleGeode->getChild(i)->asGeode();

        noeudCourant->addDrawable(circleDrawable.get());

        circleGroup->addChild(positionCourant);
        positionCourant->addChild(noeudCourant);

    }



	//Define the viewer
	osg::ref_ptr<osgViewer::Viewer> viewer = new osgViewer::Viewer;
	SetUpViewer(viewer);
	viewer->addEventHandler(new myKeyboardEventHandler);
	viewer->setSceneData(root);

	// to change to get the right position
	// press SPACE BAR to reset to this position
	//viewer->getCameraManipulator()->setHomePosition(eyeHome,centerHome,upHome,false);

    viewer->getCameraManipulator()->setHomePosition(eyeHome,centerHome,upHome,false);


	//To get the MVPW matrices in this loop, to be used to calculate screen coordinates
	while (!viewer->done()) {
		viewer->frame();
		V = viewer->getCamera()->getViewMatrix();
		P = viewer->getCamera()->getProjectionMatrix();
		W = viewer->getCamera()->getViewport()->computeWindowMatrix();

		viewer->getCamera()->getViewMatrixAsLookAt(eye, center, up);

		//std::cout<<"Eye values:"<<std::fixed<<eye.x()<<" "<<eye.y()<<" "<<eye.z()<<std::endl;
		//std::cout<<"Center values:"<<center.x()<<" "<<center.y()<<" "<<center.z()<<std::endl;
		//std::cout<<"Up values:"<<std::fixed<<up.x()<<" "<<up.y()<<" "<<up.z()<<std::endl;
		/*I don't know why if I put this block into functions then it does not work
		 *those functions are okay without problems in SetUp.cpp
		 */

//		std::string datapath, positionpath;
//		//A simple function to differentiate displayed info for each function
//		MatchDataPosition(datapath, positionpath);
//		myXparser datasetParser;
//		myXparser positionParser;
//		datasetParser.readXMLFile(datapath);
//		positionParser.readXMLFile(positionpath);
//		DOMDocument* datasetDoc = datasetParser.getParseredDoc();
//		DOMDocument* positionDoc = positionParser.getParseredDoc();
//		DOMNodeList* dataset = datasetDoc->getElementsByTagName(
//				XMLString::transcode("Info"));
//		DOMNodeList* position = positionDoc->getElementsByTagName(
//				XMLString::transcode("Info"));

//		root->setChild(root->getNumChildren() - 1,
		//				DisplayInfo(dataset, position).get());
		DisplayInfo(textGroup);

		//To verify if HUD texts display or not
		HUDFilter(Cam);
	}

    viewer->run();

	return EXIT_SUCCESS;
}
static void osmloader_step(ubx_block_t *c) {
	LOG(INFO) << "osmloader: executing: " << c->name;

	/* Just print what the world model has to offer. */
	wmPrinter->reset();
	wmHandle->scene.executeGraphTraverser(wmPrinter, wmHandle->getRootNodeId());
	LOG(DEBUG) << "osmloader: Current state of the world model: " << std::endl << wmPrinter->getDotGraph();

	/* read Id(s) from input port */
	std::vector<brics_3d::rsg::Id> inputDataIds;
	inputDataIds.clear();
	ubx_port_t* inputPort = ubx_port_get(c, "inputDataIds");
	rsg_ids recievedInputDataIs;
	recievedInputDataIs.numberOfIds = 0u;

	int ret = read_rsg_ids(inputPort, &recievedInputDataIs);
	if (ret < 1) {
		LOG(WARNING) << "osmloader: No input IDs given.";
	}

	brics_3d::rsg::Id outputHookId;
	brics_3d::rsg::UbxTypecaster::convertIdsFromUbx(recievedInputDataIs, inputDataIds);
	if (inputDataIds.size() < 1) {
		LOG(WARNING) << "osmloader: Not enough IDs specified. Expected 1 but it is: " << inputDataIds.size() << std::endl << "Using root instead.";
		outputHookId = wmHandle->getRootNodeId();
	} else {
		outputHookId = inputDataIds[0]; // First ID is always the output hook.
	}

	std::vector<brics_3d::rsg::Id> output;
	output.clear();
	output.push_back(outputHookId); // First ID is always the output hook.


	/* The origin */
	brics_3d::rsg::Id originId;
	std::vector<brics_3d::rsg::Attribute> originAttributes;
	if(convertToUtm) {
		originAttributes.push_back(brics_3d::rsg::Attribute("gis:origin","utm"));
	} else {
		originAttributes.push_back(brics_3d::rsg::Attribute("gis:origin","wgs84"));
	}

	/* check if it exists already */
	vector<brics_3d::rsg::Id> resultIds;
	wmHandle->scene.getNodes(originAttributes, resultIds);
	if(resultIds.size() > 0) {
		if(resultIds.size() > 1) {
			LOG(INFO) << "osmloader: Multiple origins found. Taking first one.";
		}
		originId = resultIds[0]; // We take the first one.
		LOG(INFO) << "osmloader: Existing origin found with Id = " << originId;

	} else {
		LOG(INFO) << "osmloader: Adding a new origin node";
		wmHandle->scene.addGroup(outputHookId, originId, originAttributes);
	}




	/*
	 * get and set config data
	 */

	std::string dataSetFolder = "/opt/src/sandbox/brics_3d_function_blocks/data";
	std::string dataSet = *fileName;
    LOG(INFO) << "osmloader: Using file " << dataSet << " .";

    /*
     * define where to store results
     */


	/*
	 * do computation
	 */
    vector<brics_3d::rsg::Id> osmNodesIds;

    /* Open xml file */
	try {
		XMLPlatformUtils::Initialize();
	}

	catch (const XMLException& e) {
		char *pMsg = XMLString::transcode(e.getMessage());
		cerr << "ERROR: An error occured during Xerces initialization.\n"
				<< "  Exception message:"
				<< pMsg;
		XMLString::release(&pMsg);
		return;
	}

	//
	//  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.
	//
	parser = new XercesDOMParser;
	parser->setValidationScheme(XercesDOMParser::Val_Auto);
	parser->setDoNamespaces(false);
	parser->setDoSchema(false);
	parser->setValidationSchemaFullChecking(false);
	parser->setCreateEntityReferenceNodes(false);

	//
	//  Parse the XML file, catching any XML exceptions that might propagate
	//  out of it.
	//
	bool errorsOccured = false;
	try {
		parser->parse(dataSet.c_str());
		int errorCount = parser->getErrorCount();
		if (errorCount > 0) {
			errorsOccured = true;
			LOG(ERROR) << "XML document has " << errorsOccured << " error(s).";
		}

	} catch (const XMLException& e) {
		LOG(ERROR) << "An error occured during parsing\n   Message: " << e.getMessage();
		errorsOccured = true;
	} catch (const DOMException& e) {
		LOG(ERROR) << "A DOM error occured during parsing\n   DOMException code: " << e.code;
		errorsOccured = true;
	} catch (...) {
		LOG(ERROR) << "An error occured during parsing\n" << endl;
		errorsOccured = true;
	}

    LOG(INFO) << "osmloader: Read file. Error: " << errorsOccured;
    if(errorsOccured) {
    	return;
    }

    /* parse xml file */
    DOMNode* current = 0;
    DOMNode* currentChild = 0;
    DOMNode* attributeNode = 0;
    DOMNamedNodeMap* attributesList = 0;
    DOMNamedNodeMap* childAttributesList = 0;
    XMLCh* rootName = XMLString::transcode("osm");
    XMLCh* nodeName = XMLString::transcode("node");
    XMLCh* tagName = XMLString::transcode("tag");
    XMLCh* kName = XMLString::transcode("k");
    XMLCh* vName = XMLString::transcode("v");
    XMLCh* idName = XMLString::transcode("id");
    XMLCh* latName = XMLString::transcode("lat");
    XMLCh* lonName = XMLString::transcode("lon");
    XMLCh* wayName = XMLString::transcode("way");
    XMLCh* refName = XMLString::transcode("ref");
    XMLCh* versionName = XMLString::transcode("version");
    string tmpResult;
    string osmAttributePrefix = "osm:";
    unsigned int nodeCounter = 0;
    unsigned int wayCounter = 0;

   /* <osm version="0.6" generator="Overpass API">
    *  	<note>The data included in this document is from www.openstreetmap.org. The data is made available under ODbL.</note>
    *  	<meta osm_base="2015-01-07T12:43:02Z"/>
    *  	<node id="21101298" lat="50.7776577" lon="7.1853241"><tag k="crossing" v="traffic_signals"/>
    * 		<tag k="highway" v="traffic_signals"/>
    *  	</node>
    * </osm>
    */

    DOMDocument* doc = parser->getDocument();

    /* root node */
    DOMNodeList* root = doc->getElementsByTagName(rootName);

    if (root->getLength() > 1) {
        LOG(WARNING) << "More than one osm elemnt found, taking the first one";
    } else if(root->getLength() < 1) {
    	LOG(ERROR) << "No osm elemnt found.";
		return ;
    }

    current = root->item(0);
    attributesList =  current->getAttributes();
    attributeNode = attributesList->getNamedItem(versionName);

    if (attributeNode != 0) {
    	tmpResult = XMLString::transcode(attributeNode->getNodeValue());
    	LOG(INFO) << "osm version = " << tmpResult;
    }

    /* osm nodes */
    DOMNodeList* osmNodes = doc->getElementsByTagName(nodeName);
	double x = -1.0;
	double y = -1.0;
	double z = 0.0;

    for (int i = 0; i < osmNodes->getLength(); ++i) {
    	unsigned int id = 0;
    	double lon = -1.0;
    	double lat = -1.0;
    	vector<brics_3d::rsg::Attribute> tags;
    	brics_3d::rsg::TimeStamp time = wmHandle->now();

        current = osmNodes->item(i);

        attributesList =  current->getAttributes();

        // Id
        attributeNode = attributesList->getNamedItem(idName);
        if (attributeNode != 0) {
        	tmpResult = XMLString::transcode(attributeNode->getNodeValue());
        	LOG(DEBUG) << "node id = " << tmpResult;
        	tags.push_back(brics_3d::rsg::Attribute(osmAttributePrefix+"node_id", tmpResult));
        	id = atoi(tmpResult.c_str());
        }

        // lon
        attributeNode = attributesList->getNamedItem(lonName);
        if (attributeNode != 0) {
        	tmpResult = XMLString::transcode(attributeNode->getNodeValue());
        	LOG(DEBUG) << "\t node lon = " << tmpResult;
        	lon = atof(tmpResult.c_str());
        }

        // lat
        attributeNode = attributesList->getNamedItem(latName);
        if (attributeNode != 0) {
        	tmpResult = XMLString::transcode(attributeNode->getNodeValue());
        	LOG(DEBUG) << "\t node lat = " << tmpResult;
        	lat = atof(tmpResult.c_str());
        }

        //tags are in the child nodes
        DOMNodeList* childs = current->getChildNodes();

        for (int j = 0; j < childs->getLength(); ++j) {
        	currentChild = childs->item(j);
        	childAttributesList =  currentChild->getAttributes();

        	tmpResult = XMLString::transcode(currentChild->getNodeName());
//        	LOG(DEBUG) << "\t childName = " << tmpResult;
        	if(tmpResult.compare("tag") == 0) {
//        		LOG(DEBUG) << "\t found a tag: ";
        		brics_3d::rsg::Attribute tag;

        		// k
        		attributeNode = childAttributesList->getNamedItem(kName);
        		if (attributeNode != 0) {
        			tmpResult = XMLString::transcode(attributeNode->getNodeValue());
        			LOG(DEBUG) << "\t\t node k = " << tmpResult;
        			tag.key = osmAttributePrefix+tmpResult;
        		} else {
        			continue;
        		}

        		// v
        		attributeNode = childAttributesList->getNamedItem(vName);
        		if (attributeNode != 0) {
        			tmpResult = XMLString::transcode(attributeNode->getNodeValue());
        			LOG(DEBUG) << "\t\t node v = " << tmpResult;
        			tag.value = tmpResult;
        		} else {
        			continue;
        		}

        		tags.push_back(tag);
        	}
        }

        string zone;
        if(convertToUtm) {
        	UTM::LLtoUTM(lon, lat, x, y, zone);
        } else {
        	x = lat;
        	y = lon;
        }
        LOG(DEBUG) << "Pose = (" << x << ", " << y << ", " << z << ") in zone: " << zone;



        /* Add to RSG */
        brics_3d::rsg::Id poseId;
        brics_3d::rsg::Id nodeId = id;

    	vector<brics_3d::rsg::Attribute> poseAttributes;
    	poseAttributes.push_back(brics_3d::rsg::Attribute(osmAttributePrefix + "tf","pose"));
    	if(convertToUtm) {
        	poseAttributes.push_back(brics_3d::rsg::Attribute("tf:type","utm"));
        	poseAttributes.push_back(brics_3d::rsg::Attribute("tf:utm_zone", zone));
    	} else {
        	poseAttributes.push_back(brics_3d::rsg::Attribute("tf:type","wgs84"));
    	}
        brics_3d::HomogeneousMatrix44::IHomogeneousMatrix44Ptr poseOfNode(new brics_3d::HomogeneousMatrix44(1,0,0, 0,1,0, 0,0,1, x,y,z));
        wmHandle->scene.addTransformNode(originId, poseId, poseAttributes, poseOfNode, time);
        output.push_back(poseId);

        wmHandle->scene.addNode(poseId, nodeId, tags, true);
        output.push_back(nodeId);

        nodeCounter++;
	}

    LOG(INFO) << "osmloader: " << nodeCounter <<" nodes loaded.";


    /* place  the camera for the visualizer, based on the last loaded node  */
    brics_3d::rsg::Id camearaId;
    vector<brics_3d::rsg::Attribute> cameraAttributes;
    cameraAttributes.push_back(brics_3d::rsg::Attribute("osg:camera","home"));
    cameraAttributes.push_back(brics_3d::rsg::Attribute("tf:type","wgs84"));
    brics_3d::HomogeneousMatrix44::IHomogeneousMatrix44Ptr poseOfCamera(new brics_3d::HomogeneousMatrix44(1,0,0, 0,1,0, 0,0,1, x,y,z));
    wmHandle->scene.addTransformNode(originId, camearaId, cameraAttributes, poseOfCamera, wmHandle->now());
    //output.push_back(camearaId);


    /* osm ways */

    /* e.g.
     * <way id="139281027">
     *		<nd ref="1526916568"/>
     *		<nd ref="2280218902"/>
     *		<nd ref="1526916486"/>
     *		<tag k="highway" v="residential"/>
     *		<tag k="maxspeed" v="30"/>
     *  	<tag k="name" v="Südstraße"/>
     * </way>
     */
    DOMNodeList* wayNodes = doc->getElementsByTagName(wayName);

    for (int i = 0; i < wayNodes->getLength(); ++i) {
    	unsigned int id = 0;

        current = wayNodes->item(i);

        attributesList =  current->getAttributes();
        attributeNode = attributesList->getNamedItem(idName);
    	vector<brics_3d::rsg::Attribute> tags;
    	vector<brics_3d::rsg::Id> nodeReferences;

        // id
        if (attributeNode != 0) {
        	tmpResult = XMLString::transcode(attributeNode->getNodeValue());
        	LOG(DEBUG) << "way id = " << tmpResult;
        	tags.push_back(brics_3d::rsg::Attribute(osmAttributePrefix+"way_id", tmpResult));
        	id = atoi(tmpResult.c_str());
        }

        /*
         * check children for tags node references
         */
        DOMNodeList* childs = current->getChildNodes();


         for (int j = 0; j < childs->getLength(); ++j) {
         	currentChild = childs->item(j);
         	childAttributesList =  currentChild->getAttributes();


         	tmpResult = XMLString::transcode(currentChild->getNodeName());
         	LOG(DEBUG) << "\t childName = " << tmpResult;
         	if(tmpResult.compare("tag") == 0) {
         		LOG(DEBUG) << "\t found a tag: ";
         		brics_3d::rsg::Attribute tag;

         		// k
         		attributeNode = childAttributesList->getNamedItem(kName);
         		if (attributeNode != 0) {
         			tmpResult = XMLString::transcode(attributeNode->getNodeValue());
         			LOG(DEBUG) << "\t\t node k = " << tmpResult;
         			tag.key = osmAttributePrefix+tmpResult;
         		} else {
         			continue;
         		}

         		// v
         		attributeNode = childAttributesList->getNamedItem(vName);
         		if (attributeNode != 0) {
         			tmpResult = XMLString::transcode(attributeNode->getNodeValue());
         			LOG(DEBUG) << "\t\t node v = " << tmpResult;
         			tag.value = tmpResult;
         		} else {
         			continue;
         		}

         		tags.push_back(tag);
         	} else if (tmpResult.compare("nd") == 0) {
           		LOG(DEBUG) << "\t found a reference: ";
         		unsigned int tmpId;

         		// ref
         		attributeNode = childAttributesList->getNamedItem(refName);
         		if (attributeNode != 0) {
         			tmpResult = XMLString::transcode(attributeNode->getNodeValue());
         			LOG(DEBUG) << "\t\t node ref = " << tmpResult;
         			tmpId = atoi(tmpResult.c_str());
         		} else {
         			continue;
         		}

         		brics_3d::rsg::Id refId = tmpId;
         		nodeReferences.push_back(refId);
         	}
         }

         /* Add to RSG as Connection */
         brics_3d::rsg::Id wayId = id; //TODO add mask
     	 vector<brics_3d::rsg::Id> emptyList;
     	 LOG(DEBUG) << "Adding Connection with ID " << id << ", containing " << nodeReferences.size() << " references.";
         wmHandle->scene.addConnection(originId, wayId, tags, emptyList, nodeReferences , wmHandle->now(), wmHandle-> now(), true);
         wayCounter++;

        /* Add a mesh as visualization of the connection, NOTE: this is static */
         if(nodeReferences.size() >= 2) {
        	 brics_3d::rsg::Id currentNode = nodeReferences[1];
        	 brics_3d::rsg::Id lastNode = nodeReferences[0];
        	 brics_3d::HomogeneousMatrix44::IHomogeneousMatrix44Ptr resultTf(new brics_3d::HomogeneousMatrix44());

        	 brics_3d::ITriangleMesh::ITriangleMeshPtr newMesh(new brics_3d::TriangleMeshExplicit());
        	 brics_3d::rsg::Mesh<brics_3d::ITriangleMesh>::MeshPtr newMeshContainer(new brics_3d::rsg::Mesh<brics_3d::ITriangleMesh>());
        	 newMeshContainer->data = newMesh;

        	 for (int i = 1; i < nodeReferences.size(); ++i) {
        		 currentNode = nodeReferences[i];
        		 double x1, y1, x2, y2;
        		 if( wmHandle->scene.getTransformForNode(lastNode, originId, wmHandle->now(), resultTf)) {
        			 x1 = resultTf->getRawData()[brics_3d::matrixEntry::x];
        			 y1 = resultTf->getRawData()[brics_3d::matrixEntry::y];
        		 } else {
        			 continue;
        		 }

        		 if( wmHandle->scene.getTransformForNode(currentNode, originId, wmHandle->now(), resultTf)) {
        			 x2 = resultTf->getRawData()[brics_3d::matrixEntry::x];
        			 y2 = resultTf->getRawData()[brics_3d::matrixEntry::y];
        		 } else {
        			 continue;
        		 }
        		 lastNode = currentNode;

        		 LOG(DEBUG) << "Segment:" << x1 << ", " << y1 << ", " << x2 << ", " << y2;
        		 double yOffset = -0.1; //m
        		 if(!convertToUtm) {
        			 yOffset *= 0.000014; // delta in WGS 84
        		 }
        		 newMesh->addTriangle(brics_3d::Point3D(x1,y1,0), brics_3d::Point3D(x1,y1+yOffset,0), brics_3d::Point3D(x2,y2,0) );
        	 }

        	 LOG(DEBUG) << "Adding a mesh with "  << newMesh->getSize() << " triangles to visualize a way.";
        	 brics_3d::rsg::Id meshId;
        	 vector<brics_3d::rsg::Attribute> meshAttributes;
        	 meshAttributes.push_back(brics_3d::rsg::Attribute("geo:crs","wgs84"));
        	 meshAttributes.push_back(brics_3d::rsg::Attribute("osm:dbg","way_mesh"));
        	 wmHandle->scene.addGeometricNode(originId, meshId, meshAttributes, newMeshContainer, wmHandle->now());

         }
    }

    LOG(INFO) << "osmloader: " << wayCounter <<" ways loaded.";

    /* clean up xml dom */
    XMLString::release(&nodeName);
    XMLString::release(&tagName);
    XMLString::release(&wayName );
    XMLString::release(&kName);
    XMLString::release(&vName);
    XMLString::release(&idName);
    XMLString::release(&latName );
    XMLString::release(&lonName);
    XMLString::release(& wayName);
    XMLString::release(&refName);
    XMLString::release(&versionName);




	/* push output to microblx */
	ubx_port_t* outputPort = ubx_port_get(c, "outputDataIds");
	rsg_ids toBeSendOutputDataIs;
	toBeSendOutputDataIs.numberOfIds = 0u;
	brics_3d::rsg::UbxTypecaster::convertIdsToUbx(output, toBeSendOutputDataIs);
	write_rsg_ids(outputPort, &toBeSendOutputDataIs);

}
示例#13
0
int main(int argC, char*[])
{
    // Initialize the XML4C2 system.
    try
    {
        XMLPlatformUtils::Initialize();
    }

    catch(const XMLException& toCatch)
    {
        char *pMsg = XMLString::transcode(toCatch.getMessage());
        XERCES_STD_QUALIFIER cerr << "Error during Xerces-c Initialization.\n"
             << "  Exception message:"
             << pMsg;
        XMLString::release(&pMsg);
        return 1;
    }

    // Watch for special case help request
    int errorCode = 0;
    if (argC > 1)
    {
        XERCES_STD_QUALIFIER cout << "\nUsage:\n"
                "    CreateDOMDocument\n\n"
                "This program creates a new DOM document from scratch in memory.\n"
                "It then prints the count of elements in the tree.\n"
             << XERCES_STD_QUALIFIER endl;
        errorCode = 1;
    }
    if(errorCode) {
        XMLPlatformUtils::Terminate();
        return errorCode;
    }

   {
       //  Nest entire test in an inner block.
       //  The tree we create below is the same that the XercesDOMParser would
       //  have created, except that no whitespace text nodes would be created.

       // <company>
       //     <product>Xerces-C</product>
       //     <category idea='great'>XML Parsing Tools</category>
       //     <developedBy>Apache Software Foundation</developedBy>
       // </company>

       DOMImplementation* impl =  DOMImplementationRegistry::getDOMImplementation(X("Core"));

       if (impl != NULL)
       {
           try
           {
               DOMDocument* doc = impl->createDocument(
                           0,                    // root element namespace URI.
                           X("company"),         // root element name
                           0);                   // document type object (DTD).

               DOMElement* rootElem = doc->getDocumentElement();

               DOMElement*  prodElem = doc->createElement(X("product"));
               rootElem->appendChild(prodElem);

               DOMText*    prodDataVal = doc->createTextNode(X("Xerces-C"));
               prodElem->appendChild(prodDataVal);

               DOMElement*  catElem = doc->createElement(X("category"));
               rootElem->appendChild(catElem);

               catElem->setAttribute(X("idea"), X("great"));

               DOMText*    catDataVal = doc->createTextNode(X("XML Parsing Tools"));
               catElem->appendChild(catDataVal);

               DOMElement*  devByElem = doc->createElement(X("developedBy"));
               rootElem->appendChild(devByElem);

               DOMText*    devByDataVal = doc->createTextNode(X("Apache Software Foundation"));
               devByElem->appendChild(devByDataVal);

               //
               // Now count the number of elements in the above DOM tree.
               //

               const XMLSize_t elementCount = doc->getElementsByTagName(X("*"))->getLength();
               XERCES_STD_QUALIFIER cout << "The tree just created contains: " << elementCount
                    << " elements." << XERCES_STD_QUALIFIER endl;

               doc->release();
           }
           catch (const OutOfMemoryException&)
           {
               XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl;
               errorCode = 5;
           }
           catch (const DOMException& e)
           {
               XERCES_STD_QUALIFIER cerr << "DOMException code is:  " << e.code << XERCES_STD_QUALIFIER endl;
               errorCode = 2;
           }
           catch (...)
           {
               XERCES_STD_QUALIFIER cerr << "An error occurred creating the document" << XERCES_STD_QUALIFIER endl;
               errorCode = 3;
           }
       }  // (inpl != NULL)
       else
       {
           XERCES_STD_QUALIFIER cerr << "Requested implementation is not supported" << XERCES_STD_QUALIFIER endl;
           errorCode = 4;
       }
   }

   XMLPlatformUtils::Terminate();
   return errorCode;
}
示例#14
0
/**
 * Main routine that utilizes Xercesc module to create a DOM object in memory 
 * and prints out the resultant DOM structure 
 * @param argC    number of command line args 
 * @param argV    name of command line args 
 * @return        0 if no errors occurred 
 */
int main(int argC, char*argv[]) {
    // Initialize the XML4C2 system.
    try {
        XMLPlatformUtils::Initialize();
} catch (const XMLException& toCatch) {
    char *pMsg = XMLString::transcode(toCatch.getMessage());
    XERCES_STD_QUALIFIER cerr << "Error during Xerces-c Initialization.\n" << "  Exception message:" << pMsg;
    XMLString::release(&pMsg);
    return 1;
}

    // Watch for special case help request
    int errorCode = 0;
    if (argC > 1) {
        XERCES_STD_QUALIFIER
        cout << "\nUsage:\n"
                "    CreateDOMDocument\n\n"
                "This program creates a new DOM document from scratch in memory.\n"
                "It then prints the count of elements in the tree.\n" << XERCES_STD_QUALIFIER
                endl;
        errorCode = 1;
    }
    if (errorCode) {
        XMLPlatformUtils::Terminate();
        return errorCode;
    }


    DOMImplementation* impl = DOMImplementationRegistry::getDOMImplementation(X("Core"));

    if (impl != NULL) {
        try {
            // create a DomDocument instance
            DOMDocument* doc = impl->createDocument(
                    0, // root element namespace URI.
                    X("TheHood"), // root element name
                    0); // document type object (DTD).

            // create root attribute nodes
            DOMAttr* woop_atr = doc->createAttribute(X("WOOP"));
            woop_atr->setValue(X("DANG"));
            DOMAttr* fiyah_atr = doc->createAttribute(X("FIYAH"));
            fiyah_atr->setValue(X("hot"));
            DOMAttr* hungry_atr = doc->createAttribute(X("hungry"));
            hungry_atr->setValue(X("starving"));

            // create root element
            DOMElement* rootElem = doc->getDocumentElement();
            // set root attrs
            rootElem->setAttributeNode(woop_atr);
            rootElem->setAttributeNode(fiyah_atr);
            rootElem->setAttributeNode(hungry_atr);

            //create root child elements
            DOMElement* gangElem = doc->createElement(X("gang"));
            rootElem->appendChild(gangElem);
            DOMText* gangDataVal = doc->createTextNode(X("YoungThugz"));
            gangElem->appendChild(gangDataVal);
            gangElem->setAttribute(X("hardness"), X("rock"));

            //create gang attr nodes
            DOMAttr* members_atr = doc->createAttribute(X("members"));
            members_atr->setValue(X("500"));
            DOMAttr* color_atr = doc->createAttribute(X("color"));
            color_atr->setValue(X("magenta"));
            // set gang attr
            gangElem->setAttributeNode(members_atr);
            gangElem->setAttributeNode(color_atr);
            // create gang elem children
            DOMElement* piruElem = doc->createElement(X("piru"));
            piruElem->setNodeValue(X("w"));
            DOMElement* cripElem = doc->createElement(X("crip"));
            cripElem->setNodeValue(X("t"));
            DOMElement* trgElem = doc->createElement(X("trg"));
            trgElem->setNodeValue(X("o"));
            // append gang elem children
            gangElem->appendChild(piruElem);
            gangElem->appendChild(cripElem);
            gangElem->appendChild(trgElem);

            DOMElement* turfElem = doc->createElement(X("turf"));
            rootElem->appendChild(turfElem);
            turfElem->setAttribute(X("idea"), X("great"));
            DOMText* turfDataVal = doc->createTextNode(X("West Side Projects"));
            turfElem->appendChild(turfDataVal);

            DOMElement* cliqueElem = doc->createElement(X("clique"));
            rootElem->appendChild(cliqueElem);
            DOMText* cliqueDataVal = doc->createTextNode(X("Balla$"));
            cliqueElem->appendChild(cliqueDataVal);
            cliqueElem->setAttribute(X("Comradery"), X("tight"));

            DOMElement* sideElem = doc->createElement(X("side"));
            rootElem->appendChild(sideElem);
            DOMText* sideDataVal = doc->createTextNode(X("North North"));
            sideElem->appendChild(sideDataVal);
            // create side elem children
            DOMElement* tempElem = doc->createElement(X("temperature"));
            tempElem->setNodeValue(X("100 C"));
            DOMElement* med_incomeElem = doc->createElement(X("medianIncome"));
            med_incomeElem->setNodeValue(X("$20,000"));
            DOMElement* schoolsElem = doc->createElement(X("schools"));
            schoolsElem->setNodeValue(X("Regional"));
            // append side elem children
            sideElem->appendChild(tempElem);
            sideElem->appendChild(med_incomeElem);
            sideElem->appendChild(schoolsElem);

            DOMElement* gatElem = doc->createElement(X("gat"));
            rootElem->appendChild(gatElem);
            DOMText* gatDataVal = doc->createTextNode(X("Glock"));
            gatElem->appendChild(gatDataVal);
            //set gat attr
            gatElem->setAttribute(X("caliber"), X(".50"));
            // create gat elem children
            DOMElement* rifleElem = doc->createElement(X("rifle"));
            DOMElement* meleeElem = doc->createElement(X("melee"));
            DOMElement* pieceElem = doc->createElement(X("piece"));
            // append gat elem children
            gatElem->appendChild(rifleElem);
            gatElem->appendChild(meleeElem);
            gatElem->appendChild(pieceElem);

            DOMElement* contraElem = doc->createElement(X("contra"));
            rootElem->appendChild(contraElem);
            DOMText* contraDataVal = doc->createTextNode(X("Cocoa"));
            contraElem->appendChild(contraDataVal);
            contraElem->setAttribute(X("rareness"), X("extreme"));
            // create contra elem children
            DOMElement* methElem = doc->createElement(X("meth"));
            DOMElement* ganjaElem = doc->createElement(X("ganja"));
            DOMElement* ethElem = doc->createElement(X("ethanol"));
            // append contra elem children
            contraElem->appendChild(methElem);
            contraElem->appendChild(ganjaElem);
            contraElem->appendChild(ethElem);
            //create contra attr nodes
            DOMAttr* price_atr = doc->createAttribute(X("price"));
            price_atr->setValue(X("$25"));
            DOMAttr* source_atr = doc->createAttribute(X("source"));
            source_atr->setValue(X("Columbia"));
            // set contra attr
            contraElem->setAttributeNode(price_atr);
            contraElem->setAttributeNode(source_atr);

            DOMElement* rivalsElem = doc->createElement(X("rivals"));
            rootElem->appendChild(rivalsElem);
            DOMText* rivalsDataVal = doc->createTextNode(X("Warrriors"));
            rivalsElem->appendChild(rivalsDataVal);

            DOMElement* policeElem = doc->createElement(X("police"));
            rootElem->appendChild(policeElem);
            DOMText* policeDataVal = doc->createTextNode(X("popo"));
            policeElem->appendChild(policeDataVal);

            DOMElement* drugsElem = doc->createElement(X("drugs"));
            rootElem->appendChild(drugsElem);
            DOMText* drugsDataVal = doc->createTextNode(X("codiene"));
            drugsElem->appendChild(drugsDataVal);
            // create drugs elem children
            DOMElement* mixElem = doc->createElement(X("mix"));
            DOMElement* spriteElem = doc->createElement(X("sprite"));
            DOMElement* leanElem = doc->createElement(X("lean"));
            // append drugs elem children
            drugsElem->appendChild(mixElem);
            drugsElem->appendChild(spriteElem);
            drugsElem->appendChild(leanElem);

            DOMElement* crimeElem = doc->createElement(X("crime"));
            rootElem->appendChild(crimeElem);
            DOMText* crimeDataVal = doc->createTextNode(X("187"));
            crimeElem->appendChild(crimeDataVal);

            //
            // Now count the number of elements in the above DOM tree.
            //

            const XMLSize_t elementCount = doc->getElementsByTagName(X("*"))->getLength();
            XERCES_STD_QUALIFIER cout << "The tree just created contains: " << elementCount
                    << " elements." << XERCES_STD_QUALIFIER endl;

            // create serializer instance
            DOMLSSerializer *theSerializer = ((DOMImplementationLS*) impl)->createLSSerializer();
            // create output instance
            DOMLSOutput *theOutputDesc = ((DOMImplementationLS*) impl)->createLSOutput();

            // referenced the following http://stackoverflow.com/questions/2897317/writing-xml-with-xerces-3-0-1-and-c-on-windows
            // set output from serializer to stdout
            XMLFormatTarget *myFormTarget;
            myFormTarget = new StdOutFormatTarget();
            theOutputDesc->setByteStream(myFormTarget);

            // Make the output more human readable by inserting line feeds.
            if (theSerializer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true))
                theSerializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true);

            // The end-of-line sequence of characters to be used in the XML being written out.
            theSerializer->setNewLine(XMLString::transcode("\r\n"));

            // output the DOM
            theSerializer->write(doc, theOutputDesc);

            cout << endl << endl << "*****************************************" << endl;

            // Using DOMTreeWalker class to traverse tree
            // create tree walker
            DOMTreeWalker* walker = doc->createTreeWalker(rootElem,
                    DOMNodeFilter::SHOW_ELEMENT,
                    NULL,
                    true);
            // create vector to hold Dom nodes
            vector<DOMNode*> elem_vec;
            // traverse tree using walker
            for (DOMNode* current = walker->nextNode(); current != 0; current = walker->nextNode()) {
                // store nodes int vector
                elem_vec.push_back(current);
            }
            // sort function - alphabetically elements
            std::sort(elem_vec.begin(), elem_vec.end(), compare_elem_alpha);

            // iterate through sorted nodes
            for (auto i : elem_vec) {
                int x;
                string text = string(x(i->getTextContent()));
                cout << "Node Name: " << x(i->getNodeName()) << ((text != "") ? " |Text Content: " + text : "") << endl;

                //get attr map
                if (i->hasAttributes()) {
                    DOMNamedNodeMap *attr_map = i->getAttributes();
                    // get each node in the map
                    for (x = 0; x < attr_map->getLength(); x++) {
                        DOMNode *temp = attr_map->item(x);
                        cout << setw(5) << "" << "Attribute" << x + 1 << ": " << x(temp->getNodeName()) << " = "
                                << x(temp->getNodeValue()) << endl;
                    }
                }
            }
            // release doc resources
            doc->release();
        } catch (const OutOfMemoryException&) {
            XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl;
            errorCode = 5;
        } catch (const DOMException& e) {
            XERCES_STD_QUALIFIER cerr << "DOMException code is:  " << e.code << XERCES_STD_QUALIFIER endl;
            errorCode = 2;
        } catch (...) {
            XERCES_STD_QUALIFIER cerr << "An error occurred creating the document" << XERCES_STD_QUALIFIER endl;
            errorCode = 3;
        }
    }// (impl != NULL)
    else {
        XERCES_STD_QUALIFIER cerr << "Requested implementation is not supported" << XERCES_STD_QUALIFIER endl;
        errorCode = 4;
    }


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

								  parse_status = 3;
				 }
				 if (parse_status !=3)
				 {
					 if(is_credit!=1)
					 {
					    strcpy(gSchemaLocation_str,XMLString::transcode(node->getTextContent()));
						if (strlen(gSchemaLocation_str) == 0)
						{
						   emit_bypass(FILE_LINE," schemaLocation is set empty in configurtion file %s",filename);
						   parse_status = 3;
						}
					 }
					 else
					 {
					    strcpy(gSchemaLocation_str_credit,XMLString::transcode(node->getTextContent()));
						if (strlen(gSchemaLocation_str_credit) == 0)
						{
						    emit_bypass(FILE_LINE," schemaLocation is set empty in configurtion file %s",filename);
							parse_status = 3;
						}
					 }
				 }
				 delete parser;
				 delete errHandler;
				 XMLPlatformUtils::Terminate();
				 if (parse_status != 0)
					 return FAILURE;
					 return SUCCESS;
			 }
			 catch (const DOMException& toCatch)
			 {
				 char* message = XMLString::transcode(toCatch.getMessage());
				 emit_bypass(FILE_LINE, "Failed to process file %s", filename);
				 emit_bypass(FILE_LINE, "Exception message is:%s", message);
			 }
			 catch (exception& e)
			 {
				 emit_bypass(FILE_LINE, "Failed to process file %s", filename);
				 emit_bypass(FILE_LINE, "Exception message is:%s", e.what());
			 }
			 catch (...){
				 emit_bypass(FILE_LINE, "Failed to process file %s", filename);
			 }
			 delete parser;
			 delete errHandler;
			 XMLPlatformUtils::Terminate();
			 return FAILURE;
 }