Exemple #1
0
void			XMLparser::parseConfigFile(std::string& configFile)
{
	DOMElement	*currentElement;
	DOMElement	*elementRoot;
	DOMNode		*currentNode;
	DOMNodeList	*children;
	XMLSize_t	nodeCount;
	DOMDocument	*xmlDoc;

	this->ConfigFileParser_->parse(configFile.c_str());
	xmlDoc = this->ConfigFileParser_->getDocument();
	elementRoot = xmlDoc->getDocumentElement();

	if (!elementRoot)
		std::cerr << "empty XML document" << std::endl;

	children = elementRoot->getChildNodes();
	nodeCount = children->getLength();
	for(XMLSize_t xx = 0; xx < nodeCount; ++xx)
	{
		currentNode = children->item(xx);
		if(currentNode->getNodeType() &&
			currentNode->getNodeType() == DOMNode::ELEMENT_NODE)
		{
			currentElement = dynamic_cast< xercesc::DOMElement* >(currentNode);
			this->getAttributes(currentElement);
		}
	}
	if (conf["port"].mValue.empty() || conf["thread-number"].mValue.empty() || conf["root-dir"].mValue.empty())
	  {
		this->putDefaultValues();
	  }	
}
//=============================================================================
// METHOD: SPELLxmlConfigReaderXC::findElementsByName
//=============================================================================
SPELLxmlNodeList SPELLxmlConfigReaderXC::findElementsByName( std::string tagName )
{
    SPELLxmlNodeList result;
    if (m_document == NULL)
    {
        THROW_EXCEPTION("Cannot find elements", "No document available", SPELL_ERROR_CONFIG);
    }

    DEBUG("[CFGR] Get elements by name: " + tagName);

    // Get the tag translation
    XMLCh* tag = XMLString::transcode(tagName.c_str());

    // Get the top-level element
    DOMElement* elementRoot = m_document->getDocumentElement();
    if( !elementRoot )
	{
    	THROW_EXCEPTION("Cannot get root element", "Empty document", SPELL_ERROR_CONFIG);
	}

    DOMNodeList* children = elementRoot->getChildNodes();

    const XMLSize_t nodeCount = children->getLength();

    // For all nodes, children of "root" in the XML tree.
    for (XMLSize_t xx = 0; xx < nodeCount; ++xx)
    {
        DOMNode* currentNode = children->item(xx);
        if (currentNode->getNodeType() && // true is not NULL
                currentNode->getNodeType() == DOMNode::ELEMENT_NODE) // is element
        {
            // Found node which is an Element. Re-cast node as element
            DOMElement* currentElement = dynamic_cast<xercesc::DOMElement*> (currentNode);
            if (XMLString::equals(currentElement->getTagName(), tag))
            {
                result.push_back( convertToNode( currentElement ) );
            }
        }
    }

    XMLString::release(&tag);

    DEBUG("[CFGR] Found " + ISTR(result.size()) + " elements");

    return result;
}
void XmlPropertyReader::parseGameObjectFile(Ogre::DataStreamPtr &stream, const Ogre::String &groupName)
{
    initializeXml();

    XERCES_CPP_NAMESPACE::DOMDocument* doc = loadDocument(stream);

    DOMNodeList* godefsXml = doc->getDocumentElement()->getElementsByTagName(AutoXMLCh("gameobjectclass").data());
    for (unsigned int idx = 0; idx < godefsXml->getLength(); idx++)
    {
		PropertyRecordPtr ps(new PropertyRecord());
		DOMElement* curNode = static_cast<DOMElement*>(godefsXml->item(idx));
		
		const DOMNamedNodeMap* godefAttrs = curNode->getAttributes();
		for (XMLSize_t attrIdx = 0; attrIdx < godefAttrs->getLength(); attrIdx++)
		{
			PropertyEntry entry = processProperty(static_cast<DOMAttr*>(godefAttrs->item(attrIdx)));
            if (entry.first != "")
            {
                ps->setProperty(entry.first, entry.second);
            }
		}

        DOMNodeList* godefChildren = curNode->getChildNodes();
        for (XMLSize_t childIdx = 0; childIdx < godefChildren->getLength(); childIdx++)
        {
            DOMNode* curChild = godefChildren->item(childIdx);
            if (curChild->getNodeType() == DOMNode::ELEMENT_NODE)
            {
                PropertyEntry entry = processProperty(static_cast<DOMElement*>(curChild));
                if (entry.first != "")
                {
                    ps->setProperty(entry.first, entry.second);
                }
            }
        }
        mPropertyRecords.push_back(ps);
    }
	
    shutdownXml();
}
Exemple #4
0
int  main()
{
	try {
		XMLPlatformUtils::Initialize();
	}
	catch (const XMLException& toCatch) {
        char *pMessage = XMLString::transcode(toCatch.getMessage());
        fprintf(stderr, "Error during XMLPlatformUtils::Initialize(). \n"
                        "  Message is: %s\n", pMessage);
        XMLString::release(&pMessage);
        return -1;
    }

    /*
    Range tests include testing of

    createRange

    setStart, setStartBefore. setStartAfter,
    setEnd, setEndBefore. setEndAfter
    getStartContainer, getStartOffset
    getEndContainer, getEndOffset
    getCommonAncestorContainer
    selectNode
    selectNodeContents
    insertNode
    deleteContents
    collapse
    getCollapsed
    surroundContents
    compareBoundaryPoints
    cloneRange
    cloneContents
    extractContents
    toString
    detach
    removeChild
    */
    {

        XMLCh tempStr[100];
        XMLString::transcode("Range",tempStr,99);
        {
            DOMImplementation* impl = DOMImplementationRegistry::getDOMImplementation(tempStr);
            DOMDocument* doc = impl->createDocument();

            //Creating a root element
            DOMElement*     root = doc->createElement(xBody);
            doc->appendChild(root);

            //Creating the siblings of root
            DOMElement*     E11 = doc->createElement(xH1);
            root->appendChild(E11);

            DOMElement*     E12 = doc->createElement(xP);
            root->appendChild(E12);

            //Attaching texts to siblings
            DOMText*        textNode1 = doc->createTextNode(xTitle);
            E11->appendChild(textNode1);

            DOMText*        textNode11 = doc->createTextNode(xAnotherText);
            E11->appendChild(textNode11);

            DOMText*        textNode2 = doc->createTextNode(xBlahxyz);
            E12->appendChild(textNode2);

            DOMText*     E210 = doc->createTextNode(xInsertedText);

            doc->release();


        }


        {
            //DOM Tree and some usable node creation
            DOMImplementation* impl = DOMImplementationRegistry::getDOMImplementation(tempStr);
            DOMDocument* doc = impl->createDocument();

            //Creating a root element
            DOMElement*     root = doc->createElement(xBody);
            doc->appendChild(root);

            //Creating the siblings of root
            DOMElement*     E11 = doc->createElement(xH1);
            root->appendChild(E11);

            DOMElement*     E12 = doc->createElement(xP);
            root->appendChild(E12);

            //Attaching texts to siblings
            DOMText*        textNode1 = doc->createTextNode(xTitle);
            E11->appendChild(textNode1);

            DOMText*        textNode11 = doc->createTextNode(xAnotherText);
            E11->appendChild(textNode11);

            DOMText*        textNode2 = doc->createTextNode(xBlahxyz);
            E12->appendChild(textNode2);

            //experimental nodes
            DOMElement*     E120 = doc->createElement(xElement1);
            DOMElement*     E121 = doc->createElement(xElement2);
            DOMElement*     E122 = doc->createElement(xElement3);
            DOMElement*     E311 = doc->createElement(xSurroundNode1);

            DOMText*     E210 = doc->createTextNode(xInsertedText);

            DOMNode* rt = doc->getDocumentElement();
            DOMRange* range = ((DOMDocumentRange*)doc)->createRange();



            //Tests start here
            // Initial dom tree looks like :
            // <Body><H1>TitleAnother Text</H1><P>Blah xyz</P></Body>
            //i.e.,            Body(rt)
            //     _____________|________________
            //     |                           |
            //  ___H1(E11)___                    P(E12)
            //  |           |                    |
            //  "Title"  "Another Text"        "Blah xyz"


            //test for start and end settings of a range
            range->setStart(rt->getFirstChild(), 0);
            TASSERT(range->getStartContainer() == rt->getFirstChild() );
            TASSERT(range->getStartOffset() == 0);

            range->setEnd(rt->getFirstChild(), 1);
            TASSERT(range->getEndContainer() == rt->getFirstChild() );
            TASSERT(range->getEndOffset() == 1);


            //DOMNode* node = range->getCommonAncestorContainer();
            TASSERT(range->getCommonAncestorContainer() == rt->getFirstChild());

            //selection related test
            range->selectNode(rt->getLastChild());
            TASSERT(range->getStartContainer() == rt);
            TASSERT(range->getStartOffset() == 1);
            TASSERT(range->getEndContainer() == rt);
            TASSERT(range->getEndOffset() == 2);

            //insertion related tests
            range->insertNode(E120);

            //only end offset moves and new node gets into range as being inserted at boundary point
            TASSERT(range->getStartContainer() == rt);
            TASSERT(range->getStartOffset() == 1);
            TASSERT(range->getEndContainer() == rt);
            TASSERT(range->getEndOffset() == 3);

            range->insertNode(E121);
            //only end offset moves and new node gets into range as being inserted at boundary point
            TASSERT(range->getStartContainer() == rt);
            TASSERT(range->getStartOffset() == 1);
            TASSERT(range->getEndContainer() == rt);
            TASSERT(range->getEndOffset() == 4);

            rt->insertBefore(E122, rt->getFirstChild());
            //both offsets move as new node is not part of the range
            TASSERT(range->getStartContainer() == rt);
            TASSERT(range->getStartOffset() == 2);
            TASSERT(range->getEndContainer() == rt);
            TASSERT(range->getEndOffset() == 5);

            //After above operations, now the tree looks like:
            // <Body><Element3/><H1>TitleAnother Text</H1><Element2/><Element1/><P>Blah xyz</P></Body>
            //i.e.,            Body(rt)
            //     _____________|_______________________________________________________________
            //     |                |                  |                |                      |
            //  Element3(E122)  ___H1(E11)___        Element2(E121)    Element1(E120)          P(E12)
            //                  |           |                                                  |
            //               "Title"  "Another Text"                                        "Blah xyz"
            //
            // range has rt as start and end container, and 2 as start offset, 5 as end offset

            //changing selection
            range->selectNode(rt->getLastChild()->getPreviousSibling());
            TASSERT(range->getStartContainer() == rt);
            TASSERT(range->getStartOffset() == 3);
            TASSERT(range->getEndContainer() == rt);
            TASSERT(range->getEndOffset() == 4);

            //deleting related tests
            range->deleteContents();
            TASSERT(rt->getLastChild()->getPreviousSibling() == E121);

            range->setStart(rt->getFirstChild()->getNextSibling()->getFirstChild(), 2);
            TASSERT(range->getStartContainer() == rt->getFirstChild()->getNextSibling()->getFirstChild());
            TASSERT(!XMLString::compareString(range->getStartContainer()->getNodeValue(),xTitle));
            TASSERT(range->getStartOffset() == 2);

            range->setEnd(rt->getFirstChild()->getNextSibling()->getFirstChild(), 4);
            TASSERT(range->getEndContainer() == rt->getFirstChild()->getNextSibling()->getFirstChild());
            TASSERT(!XMLString::compareString(range->getEndContainer()->getNodeValue(),xTitle));
            TASSERT(range->getEndOffset() == 4);
            TASSERT(!XMLString::compareString(range->toString(),xtl));

            //inserting text between a text node
            range->insertNode(E210);

            //only end offset moves and new node gets into range as being inserted at boundary point
            TASSERT(range->getStartContainer() == rt->getFirstChild()->getNextSibling()->getFirstChild());
            TASSERT(range->getStartOffset() == 2);
            TASSERT(range->getEndContainer() == rt->getFirstChild()->getNextSibling()->getLastChild()->getPreviousSibling());
            TASSERT(range->getEndOffset() == 2);

            //inserting element node before the selected text node
            range->insertNode(E120);
            //only end offset moves and new node gets into range as being inserted at boundary point
            TASSERT(range->getStartContainer() == rt->getFirstChild()->getNextSibling()->getFirstChild());
            TASSERT(!XMLString::compareString(range->getStartContainer()->getNodeValue(),xTi));
            TASSERT(range->getStartOffset() == 2);
            TASSERT(range->getEndContainer() == rt->getFirstChild()->getNextSibling()->getLastChild()->getPreviousSibling());
            TASSERT(!XMLString::compareString(range->getEndContainer()->getNodeValue(),xtle));
            TASSERT(range->getEndOffset() == 2);
            TASSERT(E11->getChildNodes()->getLength()==6);

           //checking the text replacment
            range->getStartContainer()->setNodeValue(xReplacedText);
            //only the start offset is impact
            TASSERT(range->getStartContainer() == rt->getFirstChild()->getNextSibling()->getFirstChild());
            TASSERT(!XMLString::compareString(range->getStartContainer()->getNodeValue(),xReplacedText));
            TASSERT(range->getStartOffset() == 0);
            TASSERT(range->getEndContainer() == rt->getFirstChild()->getNextSibling()->getLastChild()->getPreviousSibling());
            TASSERT(!XMLString::compareString(range->getEndContainer()->getNodeValue(),xtle));
            TASSERT(range->getEndOffset() == 2);

            //After above operations, now the tree looks like:
            // <Body><Element3/><H1>ReplacedText<Element1/>InsertedTexttleAnother Text</H1><Element2/><P>Blah xyz</P></Body>
            //i.e.,            Body(rt)
            //     _____________|_______________________________________________________________________________________________
            //     |                |                                                                          |                |
            //  Element3(E122)  ___H1(E11)___________________________________________________________        Element2(E121)    P(E12)
            //                  |              |     |                |                      |      |                             |
            //               "ReplacedText"   ""   Element1(E120)   "InsertedText"(E210)   "tle"  "Another Text"              "Blah xyz"
            //
            // range has "ReplacedText" as start container and "tle" as end container
            //   and 0 as start offset, 2 as end offset

            //changing the selection. Preparing for 'surround'
            range->setStart(range->getStartContainer()->getParentNode(), 2);
            range->setEnd(range->getStartContainer(), 5);
            TASSERT(!XMLString::compareString(range->getStartContainer()->getNodeName(),xH1));
            TASSERT(!XMLString::compareString(range->getEndContainer()->getNodeName(),xH1));
            TASSERT(!XMLString::compareString(range->toString(),xInsertedTexttle));

            range->surroundContents(E311);
            TASSERT(!XMLString::compareString(range->getStartContainer()->getNodeName(),xH1));
            TASSERT(range->getStartOffset() == 2);
            TASSERT(!XMLString::compareString(range->getEndContainer()->getNodeName(),xH1));
            TASSERT(range->getEndOffset() == 3);
            TASSERT(E11->getChildNodes()->getLength()==4);
            TASSERT(E311->getChildNodes()->getLength()==3);
            TASSERT(!XMLString::compareString(range->toString(),xInsertedTexttle));

            //After above operations, now the tree looks like:
            // <Body><Element3/><H1>ReplacedText<SurroundNode1><Element1/>InsertedTexttle</SurroundNode1>Another Text</H1><Element2/><P>Blah xyz</P></Body>
            //i.e.,            Body(rt)
            //     _____________|_________________________________________________________________________
            //     |                |                                                    |                |
            //  Element3(E122)  ___H1(E11)___________________________________        Element2(E121)    P(E12)
            //                  |              |     |                      |                            |
            //               "ReplacedText"   ""   SurroundNode1(E311)  "Another Text"              "Blah xyz"
            //                          ____________ |_____________________________
            //                          |                    |                    |
            //                          Element1(E120)   "InsertedText"(E210)   "tle"
            //
            // range has H1 as start and end container and 2 as start offset, 3 as end offset

            //testing cloning
            DOMRange* aRange = range->cloneRange();

            TASSERT(aRange->getStartContainer() == range->getStartContainer());
            TASSERT(aRange->getEndContainer() == range->getEndContainer());
            TASSERT(aRange->getStartOffset() == 2);
            TASSERT(aRange->getEndOffset() == 3);
            //changing the new ranges start
            aRange->setStart(aRange->getStartContainer()->getFirstChild(), 1);

            //comparing the ranges
            short compVal = range->compareBoundaryPoints(DOMRange::END_TO_END, aRange);
            TASSERT(compVal == 0);
            compVal = range->compareBoundaryPoints(DOMRange::START_TO_START, aRange);
            TASSERT(compVal == 1);
            compVal = range->compareBoundaryPoints(DOMRange::START_TO_END, aRange);
            TASSERT(compVal == 1);
            compVal = range->compareBoundaryPoints(DOMRange::END_TO_START, aRange);
            TASSERT(compVal == -1);

            //testing collapse
            //not collapsed
            TASSERT(range->getCollapsed() == false);
            TASSERT(range->getStartOffset() == 2);
            TASSERT(range->getEndOffset() == 3);

            //selectNodeContents
            range->selectNodeContents(rt->getLastChild()->getFirstChild());
            TASSERT(range->getStartContainer() == rt->getLastChild()->getFirstChild());
            TASSERT(range->getEndContainer() == rt->getLastChild()->getFirstChild());
            TASSERT(range->getStartOffset() == 0);
            TASSERT(range->getEndOffset() == 8);
            TASSERT(!XMLString::compareString(range->toString(),xBlahxyz));

            //testing collapse
            range->collapse(true); //collapse to start
            TASSERT(range->getCollapsed() == true);
            TASSERT(range->getStartOffset() == 0);
            TASSERT(range->getEndOffset() == 0);
            TASSERT(!XMLString::compareString(range->toString(),XMLUni::fgZeroLenString));
            TASSERT(aRange->getEndOffset() == 3); //other range is unaffected
            TASSERT(!XMLString::compareString(aRange->toString(),xeplacedTextInsertedTexttle));

            //After above operations, now the tree looks like:
            // <Body><Element3/><H1>ReplacedText<SurroundNode1><Element1/>InsertedTexttle</SurroundNode1>Another Text</H1><Element2/><P>Blah xyz</P></Body>
            //i.e.,            Body(rt)
            //     _____________|_________________________________________________________________________
            //     |                |                                                    |                |
            //  Element3(E122)  ___H1(E11)___________________________________        Element2(E121)    P(E12)
            //                  |              |     |                      |                            |
            //               "ReplacedText"   ""   SurroundNode1(E311)  "Another Text"              "Blah xyz"
            //                          ____________ |_____________________________
            //                          |                    |                    |
            //                          Element1(E120)   "InsertedText"(E210)   "tle"
            //
            // range has "Blah xyz" as start and end container and 0 as start and end offset (collapsed)
            // aRange has "ReplacedText" as start container and H1 as end container
            //    and 1 as start offset and 3 as end offset

            DOMDocumentFragment* docFrag = aRange->cloneContents();
            TASSERT( docFrag != 0);
            range->selectNode(rt->getFirstChild());
            TASSERT(range->getStartContainer() == rt);
            TASSERT(range->getEndContainer() == rt);
            TASSERT(range->getStartOffset() == 0);
            TASSERT(range->getEndOffset() == 1);

            //Testing toString()
            const XMLCh* str = aRange->toString();
            TASSERT(!XMLString::compareString(str, xeplacedTextInsertedTexttle));

            //start and end before and after tests
            range->setStartBefore(rt->getFirstChild());
            TASSERT(range->getStartOffset() == 0);
            range->setEndBefore(rt->getFirstChild());
            TASSERT(range->getEndOffset() == 0);
            range->setStartAfter(rt->getLastChild());
            TASSERT(range->getStartOffset() == 4);

            range->setStartAfter(rt->getFirstChild());
            TASSERT(range->getStartOffset() == 1);

            range->setEndBefore(rt->getLastChild());
            TASSERT(range->getEndOffset() == 3);

            range->setEndAfter(rt->getLastChild());
            TASSERT(range->getEndOffset() == 4);

            //testing extract()
            DOMDocumentFragment* frag2 = range->extractContents();
            TASSERT( frag2 != 0);

            //After above operations, now the tree looks like:
            // <Body><Element3/></Body>
            //i.e.,            Body(rt)
            //                  |
            //               Element3(E122)
            //
            // aRange has rt as start and end container, and 1 as start and end offset (collapsed)
            // range has rt as start and end container, and 1 as start and end offset (collapsed)
            //
            //and frag2 looks:
            // <Body>ReplacedText<SurroundNode1><Element1/>InsertedTexttle</SurroundNode1>Another Text</H1><Element2/><P>Blah xyz</P></Body>
            //i.e.,             Body(rt)
            //      ______________|________________________________________________________
            //      |                                                    |                |
            //   ___H1(E11)___________________________________        Element2(E121)    P(E12)
            //   |              |     |                      |                            |
            //"ReplacedText"   ""   SurroundNode1(E311)  "Another Text"              "Blah xyz"
            //           ____________ |_____________________________
            //           |                    |                    |
            //        Element1(E120)   "InsertedText"(E210)   "tle"
            //

            //the tree do not have those node anymore after extract
            //only Element3 left
            TASSERT(rt->getChildNodes()->getLength()==1);

            //aRange is collapsed
            TASSERT(aRange->getCollapsed() == true);
            TASSERT(aRange->getStartContainer() == rt);
            TASSERT(aRange->getStartOffset() == 1);
            TASSERT(aRange->getEndContainer() == rt);
            TASSERT(aRange->getEndOffset() == 1);

            //range is collapsed as well
            TASSERT(range->getCollapsed() == true);
            TASSERT(range->getStartContainer() == rt);
            TASSERT(range->getStartOffset() == 1);
            TASSERT(range->getEndContainer() == rt);
            TASSERT(range->getEndOffset() == 1);

            //test the document fragment frag2
            TASSERT(frag2->getChildNodes()->getLength()==3);

            //detaching the other range
            aRange->detach();
            range->detach();

            //***************************************************************
            //another set of test
            //TEST createRange, setStart and setEnd, insertnode
            //***************************************************************
            DOMImplementation* impl2 = DOMImplementationRegistry::getDOMImplementation(tempStr);
            DOMDocument* doc2 = impl2->createDocument();

            DOMElement* root2 = doc2->createElement(xroot2);
            doc2->appendChild(root2);
            //case 1: simple text node, start==end
            // <body>text1</body>
            DOMElement* body = doc2->createElement(xBody);
            DOMText* text1 = doc2->createTextNode(xtext1);
            body->appendChild(text1);
            root2->appendChild(body);

            //set range
            DOMRange* range1 = doc2->createRange();
            range1->setStart(text1,1);
            range1->setEnd(text1,3);

            TASSERT(!XMLString::compareString(range1->toString(),xex));
            TASSERT(range1->getStartOffset()==1);
            TASSERT(!XMLString::compareString(range1->getStartContainer()->getNodeValue(),xtext1));
            TASSERT(range1->getEndOffset()==3);
            TASSERT(!XMLString::compareString(range1->getEndContainer()->getNodeValue(),xtext1));

            //now insert a text node
            //<body>ttext2ext1</body>
            DOMText* text2 = doc2->createTextNode(xtext2);
            range1->insertNode(text2);

            TASSERT(!XMLString::compareString(range1->toString(),xtext2ex));
            TASSERT(range1->getStartOffset()==1);
            TASSERT(!XMLString::compareString(range1->getStartContainer()->getNodeValue(),xt));
            TASSERT(range1->getEndOffset()==2);
            TASSERT(!XMLString::compareString(range1->getEndContainer()->getNodeValue(),xext1));

            //now insert a non-text node
            //<body>t<p1/>text2ext1</body>
            DOMElement* p1 = doc2->createElement(xp1);
            range1->insertNode(p1);

            TASSERT(!XMLString::compareString(range1->toString(),xtext2ex));
            TASSERT(range1->getStartOffset()==1);
            TASSERT(!XMLString::compareString(range1->getStartContainer()->getNodeValue(),xt));
            TASSERT(range1->getEndOffset()==2);
            TASSERT(!XMLString::compareString(range1->getEndContainer()->getNodeValue(),xext1));

            //case 2: non-text node, start==end
            // <head><h1/></head>
            DOMElement* head = doc2->createElement(xhead);
            DOMElement* h1 = doc2->createElement(xH1);
            head->appendChild(h1);
            root2->appendChild(head);

            //set range
            DOMRange* range2 = doc2->createRange();
            range2->setStart(head,0);
            range2->setEnd(head,1);

            TASSERT(!XMLString::compareString(range2->toString(),XMLUni::fgZeroLenString));
            TASSERT(range2->getStartOffset()==0);
            TASSERT(!XMLString::compareString(range2->getStartContainer()->getNodeName(),xhead));
            TASSERT(range2->getEndOffset()==1);
            TASSERT(!XMLString::compareString(range2->getEndContainer()->getNodeName(),xhead));

            //now insert a non-text node
            //<head><h2/><h1/></head>
            DOMElement* h2 = doc2->createElement(xh2);
            range2->insertNode(h2);

            TASSERT(!XMLString::compareString(range2->toString(),XMLUni::fgZeroLenString));
            TASSERT(range2->getStartOffset()==0);
            TASSERT(!XMLString::compareString(range2->getStartContainer()->getNodeName(),xhead));
            TASSERT(range2->getEndOffset()==2);
            TASSERT(!XMLString::compareString(range2->getEndContainer()->getNodeName(),xhead));

            //now insert a text node
            //<head>text5<h2/><h1/></head>
            DOMText* text5 = doc2->createTextNode(xtext5);
            range2->insertNode(text5);

            TASSERT(!XMLString::compareString(range2->toString(),xtext5));
            TASSERT(range2->getStartOffset()==0);
            TASSERT(!XMLString::compareString(range2->getStartContainer()->getNodeName(),xhead));
            TASSERT(range2->getEndOffset()==3);
            TASSERT(!XMLString::compareString(range2->getEndContainer()->getNodeName(),xhead));

            //case 3: simple text node, start!=end
            // <body2>text3</body2>
            DOMElement* body2 = doc2->createElement(xbody2);
            DOMText* text3 = doc2->createTextNode(xtext3);
            body2->appendChild(text3);
            root2->appendChild(body2);

            //set range
            DOMRange* range3 = ((DOMDocumentRange*)doc2)->createRange();
            range3->setStart(text3,1);
            range3->setEnd(body2,1);

            TASSERT(!XMLString::compareString(range3->toString(),xext3));
            TASSERT(range3->getStartOffset()==1);
            TASSERT(!XMLString::compareString(range3->getStartContainer()->getNodeValue(),xtext3));
            TASSERT(range3->getEndOffset()==1);
            TASSERT(!XMLString::compareString(range3->getEndContainer()->getNodeName(),xbody2));

            //now insert a textnode
            //<body2>ttext4ext3</body2>
            DOMText* text4 = doc2->createTextNode(xtext4);
            range3->insertNode(text4);

            TASSERT(!XMLString::compareString(range3->toString(),XMLUni::fgZeroLenString));
            TASSERT(range3->getStartOffset()==1);
            TASSERT(!XMLString::compareString(range3->getStartContainer()->getNodeValue(),xt));
            TASSERT(range3->getEndOffset()==1);
            TASSERT(!XMLString::compareString(range3->getEndContainer()->getNodeName(),xbody2));

            //now insert a non-text node
            //<body2>t<p2/>text4ext3</body2>
            DOMElement* p2 = doc2->createElement(xp2);
            range3->insertNode(p2);

            //extra empty node caused by splitting 't'
            TASSERT(!XMLString::compareString(range3->toString(),XMLUni::fgZeroLenString));
            TASSERT(range3->getStartOffset()==1);
            TASSERT(!XMLString::compareString(range3->getStartContainer()->getNodeValue(),xt));
            TASSERT(range3->getEndOffset()==1);
            TASSERT(!XMLString::compareString(range3->getEndContainer()->getNodeName(),xbody2));

            //test toString a bit
            range3->setStart(body2,1);
            range3->setEnd(body2,5);

            TASSERT(!XMLString::compareString(range3->toString(),xtext4ext3));

            range3->setStart(body2,0);
            range3->setEnd(body2,5);

            TASSERT(!XMLString::compareString(range3->toString(),xttext4ext3));

            //case 4: non-text node, start!=end
            // <head2><h3/></head2>
            DOMElement* head2 = doc2->createElement(xhead2);
            DOMElement* h3 = doc2->createElement(xh3);
            head2->appendChild(h3);
            root2->appendChild(head2);

            //set range
            DOMRange* range4 = doc2->createRange();
            range4->setStart(head2,0);
            range4->setEnd(h3,0);

            TASSERT(!XMLString::compareString(range4->toString(),XMLUni::fgZeroLenString));
            TASSERT(range4->getStartOffset()==0);
            TASSERT(!XMLString::compareString(range4->getStartContainer()->getNodeName(),xhead2));
            TASSERT(range4->getEndOffset()==0);
            TASSERT(!XMLString::compareString(range4->getEndContainer()->getNodeName(),xh3));

            //now insert a non-text node
            //<head2><h4/><h3/></head2>
            DOMElement* h4 = doc2->createElement(xh4);
            range4->insertNode(h4);

            TASSERT(!XMLString::compareString(range4->toString(),XMLUni::fgZeroLenString));
            TASSERT(range4->getStartOffset()==0);
            TASSERT(!XMLString::compareString(range4->getStartContainer()->getNodeName(),xhead2));
            TASSERT(range4->getEndOffset()==0);
            TASSERT(!XMLString::compareString(range4->getEndContainer()->getNodeName(),xh3));

            //now insert a text node
            //<head2>text6<h4/><h3/></head2>
            DOMText* text6 = doc2->createTextNode(xtext6);
            range4->insertNode(text6);

            TASSERT(!XMLString::compareString(range4->toString(),xtext6));
            TASSERT(range4->getStartOffset()==0);
            TASSERT(!XMLString::compareString(range4->getStartContainer()->getNodeName(),xhead2));
            TASSERT(range4->getEndOffset()==0);
            TASSERT(!XMLString::compareString(range4->getEndContainer()->getNodeName(),xh3));

            //***************************************************************
            // quick test of updating
            //***************************************************************
            // <upbody>text1</upbody>
            DOMElement* upbody = doc2->createElement(xupbody);
            DOMText* uptext1 = doc2->createTextNode(xuptext1);
            upbody->appendChild(uptext1);
            root2->appendChild(upbody);

            DOMRange* uprange = ((DOMDocumentRange*)doc2)->createRange();
            uprange->setStart(upbody,0);
            uprange->setEnd(upbody,1);

            TASSERT(!XMLString::compareString(uprange->toString(),xuptext1));
            TASSERT(uprange->getStartOffset()==0);
            TASSERT(!XMLString::compareString(uprange->getStartContainer()->getNodeName(),xupbody));
            TASSERT(uprange->getEndOffset()==1);
            TASSERT(!XMLString::compareString(uprange->getEndContainer()->getNodeName(),xupbody));

            // split text
            uptext1->splitText(1);

            TASSERT(!XMLString::compareString(uprange->toString(),xu));
            TASSERT(uprange->getStartOffset()==0);
            TASSERT(!XMLString::compareString(uprange->getStartContainer()->getNodeName(),xupbody));
            TASSERT(uprange->getEndOffset()==1);
            TASSERT(!XMLString::compareString(uprange->getEndContainer()->getNodeName(),xupbody));

            //insert node
            DOMElement* upbody2 = doc2->createElement(xupbody2);
            DOMText* uptext2 = doc2->createTextNode(xuptext2);
            upbody2->appendChild(uptext2);
            root2->appendChild(upbody2);

            DOMRange* uprange2 = ((DOMDocumentRange*)doc2)->createRange();
            uprange2->setStart(uptext2,1);
            uprange2->setEnd(upbody2,1);

            DOMRange* uprange3 = doc2->createRange();
            uprange3->setStart(uptext2,1);
            uprange3->setEnd(upbody2,1);

            TASSERT(!XMLString::compareString(uprange2->toString(),xptext2));
            TASSERT(uprange2->getStartOffset()==1);
            TASSERT(!XMLString::compareString(uprange2->getStartContainer()->getNodeValue(),xuptext2));
            TASSERT(uprange2->getEndOffset()==1);
            TASSERT(!XMLString::compareString(uprange2->getEndContainer()->getNodeName(),xupbody2));

            TASSERT(!XMLString::compareString(uprange3->toString(),xptext2));
            TASSERT(uprange3->getStartOffset()==1);
            TASSERT(!XMLString::compareString(uprange3->getStartContainer()->getNodeValue(),xuptext2));
            TASSERT(uprange3->getEndOffset()==1);
            TASSERT(!XMLString::compareString(uprange3->getEndContainer()->getNodeName(),xupbody2));

            DOMElement* upp1 = doc2->createElement(xupp1);
            uprange2->insertNode(upp1);

            TASSERT(!XMLString::compareString(uprange2->toString(),XMLUni::fgZeroLenString));
            TASSERT(uprange2->getStartOffset()==1);
            TASSERT(!XMLString::compareString(uprange2->getStartContainer()->getNodeValue(),xu));
            TASSERT(uprange2->getEndOffset()==1);
            TASSERT(!XMLString::compareString(uprange2->getEndContainer()->getNodeName(),xupbody2));

            TASSERT(!XMLString::compareString(uprange3->toString(),XMLUni::fgZeroLenString));
            TASSERT(uprange3->getStartOffset()==1);
            TASSERT(!XMLString::compareString(uprange3->getStartContainer()->getNodeValue(),xu));
            TASSERT(uprange3->getEndOffset()==1);
            TASSERT(!XMLString::compareString(uprange3->getEndContainer()->getNodeName(),xupbody2));

            //***************************************************************
            //another set of test
            //<foo><c/><moo><b/></moo>ab<a>Hello cd</a><cool>ef</cool></foo>
            //
            //  ______________________foo_____________________
            //  |          |           |          |           |
            //  c         moo        "ab"         a          cool
            //             |                      |           |
            //             b                    "Hello cd"   "ef"
            //
            DOMImplementation* impl3 = DOMImplementationRegistry::getDOMImplementation(tempStr);
            DOMDocument* doc3 = impl3->createDocument();

            DOMElement* root3 = doc3->createElement(xroot);
            doc3->appendChild(root3);

            DOMElement* foo = doc3->createElement(xfoo);
            DOMElement* moo = doc3->createElement(xmoo);
            DOMElement* cool = doc3->createElement(xcool);
            DOMText* ab = doc3->createTextNode(xab);
            DOMText* cd = doc3->createTextNode(xHellocd);
            DOMText* ef = doc3->createTextNode(xef);

            DOMElement* a = doc3->createElement(xa);
            DOMElement* b = doc3->createElement(xb);
            DOMElement* c = doc3->createElement(xc);

            root3->appendChild(foo);
            foo->appendChild(c);
            foo->appendChild(moo);
            foo->appendChild(ab);
            foo->appendChild(a);
            foo->appendChild(cool);
            moo->appendChild(b);
            a->appendChild(cd);
            cool->appendChild(ef);

            //***************************************************************
            //TEST toString
            //***************************************************************
            DOMRange* newtestrange = ((DOMDocumentRange*)doc3)->createRange();
            //case 1:
            //start container is text node
            //   i) end container is also text node
            //    a) start==end
            //    b) start!=end
            //  ii) end container is not text node
            //    a) start==end => impossible
            //    b) start!=end
            //
            //case 2:
            //start container is not text node
            //   i) end container is text node
            //    a) start==end => impossible
            //    b) start!=end
            //  ii) end container is not text node
            //    a) start==end
            //    b) start!=end

            //case 1, i, a
            newtestrange->setStart( cd, 1 );
            newtestrange->setEnd( cd, 4 );

            TASSERT(!XMLString::compareString(newtestrange->toString(),xell));

            //case 1, i, b
            newtestrange->setStart( cd, 1 );
            newtestrange->setEnd( ef, 2 );

            TASSERT(!XMLString::compareString(newtestrange->toString(),xellocdef));

            //case 1, ii, b
            newtestrange->setStart( cd, 1 );
            newtestrange->setEnd( foo, 4 );

            TASSERT(!XMLString::compareString(newtestrange->toString(),xellocd));

            //case 2, i, b
            newtestrange->setStart( foo, 1 );
            newtestrange->setEnd( cd, 5 );

            TASSERT(!XMLString::compareString(newtestrange->toString(),xabHello));

            //case 2, ii, a
            newtestrange->setStart( foo, 1 );
            newtestrange->setEnd( foo, 4 );

            TASSERT(!XMLString::compareString(newtestrange->toString(),xabHellocd));

            //case 2, ii, b
            newtestrange->setStart( moo, 1 );
            newtestrange->setEnd( foo, 4 );

            TASSERT(!XMLString::compareString(newtestrange->toString(),xabHellocd));

            //***************************************************************
            //test removeChild
            //***************************************************************
            DOMRange* newrange = doc3->createRange();
            newrange->setStart( moo, 0 );
            newrange->setEnd( foo, 4 );

            TASSERT(newrange->getStartOffset()==0);
            TASSERT(!XMLString::compareString(newrange->getStartContainer()->getNodeName(),xmoo));
            TASSERT(newrange->getEndOffset()==4);
            TASSERT(!XMLString::compareString(newrange->getEndContainer()->getNodeName(),xfoo));
            TASSERT(!XMLString::compareString(newrange->toString(),xabHellocd));

            DOMNode* n = newrange->cloneContents();
            DOMNodeList* nol = foo->getChildNodes();

            //removing moo
            DOMNode* rem = foo->removeChild(nol->item(1));
            rem->release();
            TASSERT(newrange->getStartOffset()==1);
            TASSERT(!XMLString::compareString(newrange->getStartContainer()->getNodeName(),xfoo));
            TASSERT(newrange->getEndOffset()==3);
            TASSERT(!XMLString::compareString(newrange->getEndContainer()->getNodeName(),xfoo));
            TASSERT(!XMLString::compareString(newrange->toString(),xabHellocd));

            TASSERT(newtestrange->getStartOffset()==1);
            TASSERT(!XMLString::compareString(newtestrange->getStartContainer()->getNodeName(),xfoo));
            TASSERT(newtestrange->getEndOffset()==3);
            TASSERT(!XMLString::compareString(newtestrange->getEndContainer()->getNodeName(),xfoo));
            TASSERT(!XMLString::compareString(newtestrange->toString(),xabHellocd));

            // Now do some exception test
            newrange->detach();
            EXCEPTION_TEST(newrange->setStart( moo, 0 ), DOMException::INVALID_STATE_ERR);
            EXCEPTION_TEST(newtestrange->setStartBefore(moo), DOMRangeException::INVALID_NODE_TYPE_ERR);


            doc->release();
            doc2->release();
            doc3->release();
        }
    } //creating the dom tree and tests

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

    if (errorOccurred) {
        printf("Test Failed\n");
        return 4;
    }

    printf("Test Run Successfully\n");

    return 0;
};
void GetConfig::readConfigFile(string& configFile) throw (std::runtime_error) {
	// Test to see if the file is ok.

	struct stat fileStatus;

	int iretStat = stat(configFile.c_str(), &fileStatus);
	if (iretStat == ENOENT)
		throw(std::runtime_error(
				"Path file_name does not exist, or path is an empty string."));
	else if (iretStat == ENOTDIR)
		throw(std::runtime_error("A component of the path is not a directory."));
	else if (iretStat == ELOOP)
		throw(std::runtime_error(
				"Too many symbolic links encountered while traversing the path."));
	else if (iretStat == EACCES)
		throw(std::runtime_error("Permission denied."));
	else if (iretStat == ENAMETOOLONG)
		throw(std::runtime_error("File can not be read\n"));

	// Configure DOM parser.

	m_ConfigFileParser->setValidationScheme(XercesDOMParser::Val_Never);
	m_ConfigFileParser->setDoNamespaces(false);
	m_ConfigFileParser->setDoSchema(false);
	m_ConfigFileParser->setLoadExternalDTD(false);

	try {
		m_ConfigFileParser->parse(configFile.c_str());

		// no need to free this pointer - owned by the parent parser object
		DOMDocument* xmlDoc = m_ConfigFileParser->getDocument();

		// Get the top-level element: NAme is "root". No attributes for "root"

		DOMElement* elementRoot = xmlDoc->getDocumentElement();
		if (!elementRoot)
			throw(std::runtime_error("empty XML document"));

		// Parse XML file for tags of interest: "ApplicationSettings"
		// Look one level nested within "root". (child of root)

		DOMNodeList* children = elementRoot->getChildNodes();
		const XMLSize_t nodeCount = children->getLength();

		// For all nodes, children of "root" in the XML tree.

		for (XMLSize_t i = 0; i < nodeCount; ++i) {
			DOMNode* currentNode = children->item(i);
			if (currentNode->getNodeType() &&  // true is not NULL
					currentNode->getNodeType() == DOMNode::ELEMENT_NODE) // is element
							{
				DOMElement* currentElement =
						dynamic_cast<xercesc::DOMElement*>(currentNode);
				if (XMLString::equals(currentElement->getTagName(),
						TAG_Player)) {

					const XMLCh* xmlch_Score = currentElement->getAttribute(
							ATTR_Score);
					m_Score = XMLString::transcode(xmlch_Score);

					const XMLCh* xmlch_HighSpeed = currentElement->getAttribute(
							ATTR_HighSpeed);
					m_HighSpeed = XMLString::transcode(xmlch_HighSpeed);

					const XMLCh* xmlch_HighTraction =
							currentElement->getAttribute(ATTR_HighTraction);
					m_HighTraction = XMLString::transcode(xmlch_HighTraction);

					const XMLCh* xmlch_HighTrack = currentElement->getAttribute(
							ATTR_HighTrack);
					m_HighTrack = XMLString::transcode(xmlch_HighTrack);

					const XMLCh* xmlch_MediumTrack =
							currentElement->getAttribute(ATTR_MediumTrack);
					m_MediumTrack = XMLString::transcode(xmlch_MediumTrack);

					const XMLCh* xmlch_Invicible = currentElement->getAttribute(
							ATTR_Invincible);
					m_Invincible = XMLString::transcode(xmlch_Invicible);

					break; // Data found. No need to look at other elements in tree.
				}
			}
		}
	} catch (xercesc::XMLException& e) {
		char* message = xercesc::XMLString::transcode(e.getMessage());
		ostringstream errBuf;
		errBuf << "Error parsing file: " << message << flush;
		XMLString::release(&message);
	}
}
Exemple #6
0
void PEPConfig::initialize(string& configFile) throw (std::runtime_error) {

	Lock initLock(m_lock);

	if (m_initCount == INT_MAX) {
		Category::getInstance("PEPConfig").crit("library initialized too many times");
		return;
	}

	if (m_initCount >= 1) {
		++m_initCount;
		return;
	}

	const char* logconf = getenv("SHIBSP_LOGGING");

	string logpath = configFile.substr(0, configFile.find_last_of('/'));
	if (!logconf || !*logconf) {
		if (isEnabled(PEPConfig::OutOfProcess) && !isEnabled(PEPConfig::InProcess))
			logconf = logpath.append("/pepd.logger").c_str();
		else if (isEnabled(PEPConfig::InProcess) && !isEnabled(PEPConfig::OutOfProcess))
			logconf = logpath.append("/mod_pep.logger").c_str();
		else
			logconf = logpath.append("/pepd.logger").c_str();
	}

	XMLToolingConfig::getConfig().log_config(logconf);

	Category& log = Category::getInstance("Config");
	log.debug("library initialization started");

	XMLToolingConfig::getConfig().user_agent = string("PEP");

	if (!XMLToolingConfig::getConfig().init()) {
		log.fatal("failed to initialize XMLTooling library");
		throw(std::runtime_error("failed to initialize XMLTooling library"));
	}

	if (m_PEPInstance) {
		delete m_PEPInstance;
	}
	m_PEPInstance = new PEP();

	statConfigFile(configFile);

	// register listener service factories
	registerListenerServices();

	// Configure DOM parser.
	m_ConfigFileParser->setValidationScheme(XercesDOMParser::Val_Never);
	m_ConfigFileParser->setDoNamespaces(false);
	m_ConfigFileParser->setDoSchema(false);
	m_ConfigFileParser->setLoadExternalDTD(false);

	try {
		m_ConfigFileParser->parse(configFile.c_str());

		// no need to free this pointer - owned by the parent parser object
		DOMDocument* xmlDoc = m_ConfigFileParser->getDocument();

		// Get the top-level element: NAme is "root". No attributes for "root"

		DOMElement* elementRoot = xmlDoc->getDocumentElement();
		if (!elementRoot)
			throw(std::runtime_error("empty XML document"));

		// Parse XML file for tags of interest: "ApplicationSettings"
		// Look one level nested within "root". (child of root)

		DOMNodeList* children = elementRoot->getChildNodes();
		const XMLSize_t nodeCount = children->getLength();

		// For all nodes, children of "root" in the XML tree.

		for (XMLSize_t xx = 0; xx < nodeCount; ++xx) {

			DOMNode* currentNode = children->item(xx);

			if (currentNode->getNodeType() && currentNode->getNodeType() == DOMNode::ELEMENT_NODE) { // is element

			// Found node which is an Element. Re-cast node as element
				DOMElement* currentElement = dynamic_cast<xercesc::DOMElement*>(currentNode);

				if (XMLString::equals(currentElement->getTagName(), APPLICATION_DEFAULTS_ELEM)) {
					parseApplicationConfig(currentElement);
				} else if (XMLString::equals(currentElement->getTagName(), LISTENER_ELEM)) {
					parseListenerServiceConfig(currentElement);
				}
			}
		}
	} catch (xercesc::XMLException& e) {
		char* message = xercesc::XMLString::transcode(e.getMessage());
		ostringstream errBuf;
		errBuf << "Error parsing file: " << message << flush;
		XMLString::release(&message);
	}
	++m_initCount;
}
/**
 *  This function:
 *  - Tests the access and availability of the XML configuration file.
 *  - Configures the xerces-c DOM parser.
 *  - Reads and extracts the pertinent information from the XML config file.
 *
 *  @param in configFile The text string name of the configuration file.
 */
void
AppConfigFileParse::readConfigFile(string& configFile)
throw(std::runtime_error) {
    // Test to see if the file is ok.

    struct stat fileStatus;

    if (stat(configFile.c_str(), &fileStatus)<0) {
        if (errno == ENOENT)
            throw(std::runtime_error("Could not find application(s) configuration file '" + configFile + "'."));
        else if (errno == ENOTDIR)
            throw(std::runtime_error("A component of the path is not a directory."));
#ifndef _WIN32
        else if (errno == ELOOP)
            throw(std::runtime_error("Too many symbolic links encountered while traversing the path."));
#endif
        else if (errno == EACCES)
            throw(std::runtime_error("Permission denied."));
        else if (errno == ENAMETOOLONG)
            throw(std::runtime_error("File can not be read\n"));
    }
    // Configure DOM parser.

    m_ConfigFileParser->setValidationScheme(XercesDOMParser::Val_Never);
    m_ConfigFileParser->setDoNamespaces(false);
    m_ConfigFileParser->setDoSchema(false);
    m_ConfigFileParser->setLoadExternalDTD(false);

    try {
        m_ConfigFileParser->parse(configFile.c_str());

        // no need to free this pointer - owned by the parent parser object
        DOMDocument* xmlDoc = m_ConfigFileParser->getDocument();

        // Get the top-level element: NAme is "root". No attributes for "root"
        DOMElement* elementRoot = xmlDoc->getDocumentElement();
        if (!elementRoot) throw(std::runtime_error("empty XML document"));

        DOMNodeList* applications = elementRoot->getElementsByTagName(TAG_Application);
        XMLSize_t nodeCount = applications->getLength();

        // Loop all <Application> tags
        for (XMLSize_t xx = 0; xx < nodeCount; ++xx) {

            DOMNode* currentNode = applications->item(xx);

            if (currentNode->getNodeType() &&  // true is not NULL
                    currentNode->getNodeType() == DOMNode::ELEMENT_NODE) { // is element

                Application* app = new Application();

                DOMElement* currentElememt = dynamic_cast< xercesc::DOMElement* >(currentNode);

                DOMNodeList* children = currentElememt->getChildNodes();

                for (XMLSize_t yy = 0; yy < children->getLength(); ++yy) {

                    DOMNode* _node = children->item(yy);

                    DOMElement* _element = static_cast< xercesc::DOMElement* >(_node);

                    // Application name
                    if (XMLString::equals(_element->getTagName(), TAG_Name)) {
                        DOMNodeList* children2 = _element->getChildNodes();
                        for (XMLSize_t index = 0; index < children2->getLength(); ++index) {
                            //std::cout << XMLString::transcode(children2->item(index)->getNodeValue()) << std::endl;
                            app->m_name = XMLString::transcode(children2->item(index)->getNodeValue());
                        }
                    }

                    // Application executable
                    if (XMLString::equals(_element->getTagName(), TAG_Executable)) {
                        DOMNodeList* children2 = _element->getChildNodes();
                        for (XMLSize_t index = 0; index < children2->getLength(); ++index) {
                            //std::cout << XMLString::transcode(children2->item(index)->getNodeValue()) << std::endl;
                            app->m_executable = XMLString::transcode(children2->item(index)->getNodeValue());
                        }
                    }

                    // Application IP
                    if (XMLString::equals(_element->getTagName(), TAG_Ip)) {
                        DOMNodeList* children2 = _element->getChildNodes();
                        for (XMLSize_t index = 0; index < children2->getLength(); ++index) {
                            //std::cout << XMLString::transcode(children2->item(index)->getNodeValue()) << std::endl;
                            app->m_ip = XMLString::transcode(children2->item(index)->getNodeValue());
                        }
                    }

                    // Application Port
                    if (XMLString::equals(_element->getTagName(), TAG_Port)) {
                        DOMNodeList* children2 = _element->getChildNodes();
                        for (XMLSize_t index = 0; index < children2->getLength(); ++index) {
                            //std::cout << XMLString::transcode(children2->item(index)->getNodeValue()) << std::endl;
                            app->m_port = XMLString::transcode(children2->item(index)->getNodeValue());
                        }
                    }

                    // Application seed
                    if (XMLString::equals(_element->getTagName(), TAG_Seed)) {
                        DOMNodeList* children2 = _element->getChildNodes();
                        for (XMLSize_t index = 0; index < children2->getLength(); ++index) {
                            //std::cout << XMLString::transcode(children2->item(index)->getNodeValue()) << std::endl;
                            app->m_seed = XMLString::transcode(children2->item(index)->getNodeValue());
                        }
                    }

                    // Application Rate
                    if (XMLString::equals(_element->getTagName(), TAG_Rate)) {
                        DOMNodeList* children2 = _element->getChildNodes();
                        for (XMLSize_t index = 0; index < children2->getLength(); ++index) {
                            //std::cout << XMLString::transcode(children2->item(index)->getNodeValue()) << std::endl;
                            app->m_rate = XMLString::transcode(children2->item(index)->getNodeValue());
                        }
                    }

                    // Application Result Container
                    if (XMLString::equals(_element->getTagName(), TAG_ResultContainer)) {
                        DOMNodeList* children2 = _element->getChildNodes();
                        for (XMLSize_t index = 0; index < children2->getLength(); ++index) {
                            //std::cout << XMLString::transcode(children2->item(index)->getNodeValue()) << std::endl;
                            app->m_resultContainer = XMLString::transcode(children2->item(index)->getNodeValue());
                        }
                    }

                    // Application Service Id
                    if (XMLString::equals(_element->getTagName(), TAG_ServiceId)) {
                        const XMLCh* xmlch_Unicast  = _element->getAttribute(ATTR_Unicast);
                        app->m_unicastServiceId = XMLString::transcode(xmlch_Unicast);
                        const XMLCh* xmlch_Multicast  = _element->getAttribute(ATTR_Multicast);
                        app->m_multicastServiceId = XMLString::transcode(xmlch_Multicast);
                        const XMLCh* xmlch_Broadcast  = _element->getAttribute(ATTR_Broadcast);
                        app->m_broadcastServiceId = XMLString::transcode(xmlch_Broadcast);
                        const XMLCh* xmlch_TopoBroadcast  = _element->getAttribute(ATTR_TopoBroacast);
                        app->m_topoBroadcastServiceId = XMLString::transcode(xmlch_TopoBroadcast);
                        const XMLCh* xmlch_GeoBroadcast  = _element->getAttribute(ATTR_GeoBroacast);
                        app->m_geoBroadcastServiceId = XMLString::transcode(xmlch_GeoBroadcast);
                    }

                    // Applications nodes ID (nodes that will have installed the application regardless of the penetration rates)
                    if (XMLString::equals(_element->getTagName(), TAG_Stations)) {
                        DOMNodeList* children2 = _element->getChildNodes();
                        for (XMLSize_t index = 0; index < children2->getLength(); ++index) {
                            DOMNode* __node = children2->item(index);
                            DOMElement* __element = static_cast< xercesc::DOMElement* >(__node);
                            if (XMLString::equals(__element->getTagName(), TAG_Id)) {
                                DOMNodeList* children3 = __element->getChildNodes();
                                for (XMLSize_t index2 = 0; index2 < children3->getLength(); ++index2) {
                                    //std::cout << XMLString::transcode(children3->item(index2)->getNodeValue()) << std::endl;
                                    app->m_stations.push_back(XMLString::transcode(children3->item(index2)->getNodeValue()));
                                }
                            }
                        }
                    }
                }

                m_ApplicationCollection->push_back(app);
            }
        }
    } catch (xercesc::XMLException& e) {
        char* message = xercesc::XMLString::transcode(e.getMessage());
        ostringstream errBuf;
        errBuf << "Error parsing file: " << message << flush;
        XMLString::release(&message);
    }
}
Exemple #8
0
/*=========================================================================+
	Parse_ETA_Input_XML:

		Parse the input XML block.

		eTrust Admin sends an XML block containing data of the
		object being processed.  The XML block also contains
		optional authentication data.

	The format of the input XML block is:
		<eTExitInvoke eTExitType={type of exit}>
			< {objectclass} >
				<eTDN> {dn of object being processed} </eTDN>
				<eTName> {name of object being processed} </eTName>
				< {attribute} > {value} </ {attribute} >
			< {objectclass} >

			<Authentication>
				<Type> {type of authentication} </Type>
				<User> {user to authenticate as} </User>
				<Password> {password (in the clear)} </Password>
			</Authentication>
		</eTExitInvoke>


		The {attribute} and {value} are specific to the object
		being processed.  E.g., if the object has attribute "City"
		and value "Renton", the XML block will contains the tag:
			<City>Renton</City>

		If the attribute is multi-valued, each value will have a
		separate tag:
			<City>Renton</City>
			<City>Kirkland</City>

+=========================================================================*/
int
ExitXMLBlock::Parse_ETA_Input_XML()
{
	int				iRc			= -1;		// failure
	DOMElement*		pElement	= NULL;
	DOMNodeList*	pNodeList	= NULL;
	XMLCh*			pxcTag		= NULL;
	const XMLCh*	pxcValue	= NULL;
	UTF8*			pszuValue	= NULL;
	string			sTagName;
	string			sTagValue;
	string			sErrMsg;
	int				iTagCount;

	// Load the XML document.
	try {
		m_pXmlBuilder->resetDocumentPool();
		MemBufInputSource oSource(
							(const XMLByte*)m_sInputXML.c_str(),
							m_sInputXML.length(),
							"InputBuffer",
							false);
		Wrapper4InputSource oWrapper(&oSource, false);
		m_pXmlDocument = m_pXmlBuilder->parse(oWrapper);
	}
	catch (const XMLException& toCatch) {
		sErrMsg = XMLString::transcode(toCatch.getMessage());
        cerr << "\nError during parsing\nException message is: \n" << sErrMsg << "\n";
		goto exit;
	}
	catch (const DOMException& toCatch) {
        const unsigned int iMaxChars = 2047;
        XMLCh pzcErrMsg[iMaxChars + 1];
		sErrMsg = XMLString::transcode(toCatch.msg);
		cerr << "\nDOM Error during parsing\nException message is: \n" << sErrMsg << "\n";
        if (DOMImplementation::loadDOMExceptionMsg(toCatch.code, pzcErrMsg, iMaxChars))
                cerr << "Message is: " << XMLString::transcode(pzcErrMsg) << endl;
		goto exit;
	}
	catch (...) {
        cerr << "\nUnexpected exception during parsing\n";
		goto exit;
	}

	// Get the exit type from the top level node's tag attribute.
	pElement = m_pXmlDocument->getDocumentElement();

	pxcTag = UTF8toUTF16(UTFEXIT_EXITTYPE);
	pxcValue = pElement->getAttribute(pxcTag);
	delete pxcTag;
	if (pxcValue) {
		this->m_sExitType = UTF16toUTF8(pxcValue);
	}

	// Find all the child nodes.
	pNodeList = pElement->getChildNodes();
	if (!pNodeList) {
		goto exit;
	}

	/*
	|| Get the number of tags found under the top level node.
	|| If the node_list is empty initialize the tag count to 0.
	*/
	iTagCount = pNodeList->getLength();
	// cout << "Tag Count:" << iTagCount << endl;

	// Get the tag and value under the top level node and parse each tag.
	for (int iIndex = 0; iIndex < iTagCount; iIndex++) {
		DOMNode* pNode = pNodeList->item(iIndex);
		if (!pNode) {
			// Error!
			continue;
		}

		short siTagType = pNode->getNodeType();
		if (siTagType != 1 /* DOMNode::NodeType::ELEMENT_NODE */) {
			continue;
		}

		/*
		|| Get the tag name.  If failed to get the tag name,
		|| skip the current tag.
		*/
		pxcValue = pNode->getNodeName();
		if (pxcValue) {
			sTagName = UTF16toUTF8(pxcValue);
		}

		pxcValue = pNode->getNodeValue();
		if (pxcValue) {
			sTagValue = UTF16toUTF8(pxcValue);
		}

#if 0
		cout << "Node Name: '" << sTagName << "'" << endl;
		cout << "Node Type: " << siTagType << endl;
		cout << "Node Value: '" << (sTagValue.empty() ? "<empty>" : sTagValue) << "'" << endl;
		const XMLCh* pxcValue = pNode->getTextContent();
		string sTagText = UTF16toUTF8(pxcValue);
		cout << "Node Text: '" << (sTagText.empty() ? "<empty>" : sTagText) << "'" << endl;
		cout << endl;
#endif

		if (sTagName == UTFEXIT_AUTHENTICATION) {
			Parse_Authentication_Block(sTagName);

		} else {
			this->m_sObjectClass = sTagName;
			Parse_Object_Block(this->m_sObjectClass);
		}
	}
	iRc = 0;	// success!

exit:
	return iRc;
}
Exemple #9
0
int main()
{
    
  FreeImage_Initialise();
  BOOL bMemoryCache = TRUE;
  fipMultiPage src(bMemoryCache);
  // Open src file (read-only, use memory cache)
  src.open(fname.c_str(), FALSE, TRUE);
  unsigned int img_frames = src.getPageCount();
  cout<<img_frames<<endl;
  
  fipImage image;

  image = src.lockPage(0);

  cout<<"meta data count: MAIN  "<<image.getMetadataCount(FIMD_EXIF_MAIN )<<endl;
  cout<<"meta data count: EXIF  "<<image.getMetadataCount(FIMD_EXIF_EXIF )<<endl;
  cout<<"meta data count: XMP   "<<image.getMetadataCount(FIMD_XMP  )<<endl;
  cout<<"meta data count: IPTC  "<<image.getMetadataCount(FIMD_IPTC )<<endl;
  cout<<"meta data count: GOETIFF  "<<image.getMetadataCount(FIMD_GEOTIFF )<<endl;


  fipTag tag;
  fipMetadataFind finder;
  if( finder.findFirstMetadata(FIMD_EXIF_MAIN, image, tag) ) {
    do {
      // process the tag
      cout << tag.getKey() << "\n";
    } while( finder.findNextMetadata(tag) );
  }

  cout<<"try to get at the data"<<endl;
  
  image.getMetadata(FIMD_EXIF_MAIN,"ImageDescription",tag);
  cout<<(const char*)tag.getValue()<<endl;
  cout<<"type: "<<tag.getType()<<endl;
  
  const char * xml_str = (const char*)tag.getValue();
  
    // set up xml parser stuff
  try
  {
    XMLPlatformUtils::Initialize();  // Initialize Xerces infrastructure
  }
  catch( xercesc::XMLException& e )
  {
    char* message = XMLString::transcode( e.getMessage() );
    cerr << "XML toolkit initialization error: " << message << endl;
    XMLString::release( &message );
    // throw exception here to return ERROR_XERCES_INIT
  }
  

  XMLCh* elm_name = XMLString::transcode("PlaneInfo");
  XMLCh* key_str = XMLString::transcode("id");
  XMLCh* type_str = XMLString::transcode("type");
  XMLCh* value_str = XMLString::transcode("value");
  XMLCh* pram_str = XMLString::transcode("prop");
    
  
  XercesDOMParser *config_parser = new XercesDOMParser;
  
  config_parser->setValidationScheme( XercesDOMParser::Val_Never );
  config_parser->setDoNamespaces( false );
  config_parser->setDoSchema( false );
  config_parser->setLoadExternalDTD( false );

  MemBufInputSource* memBuf = new MemBufInputSource((const XMLByte*)xml_str
					       , strlen(xml_str)
					       , gMemBufId
					       ,false
					       );
  
  
  vector<Config_pram> prams_;
  
  try
  {
    config_parser->parse(*memBuf);
    
    DOMDocument * doc = config_parser->getDocument();
    DOMElement* root = doc->getDocumentElement();
    if(!root) throw(std::runtime_error("empty xml"));
    
    DOMNodeList* children = root->getChildNodes();
    const XMLSize_t node_count = children ->getLength();
    
    

    for( XMLSize_t j = 0;j<node_count;++j)
    {
      // get current node
      DOMNode* current_node = children->item(j);
      if(current_node  && 	// make sure that current_node is non NULL
	 current_node->getNodeType() == DOMNode::ELEMENT_NODE)
      {
	// cast to dom element
	DOMElement* cur_elm = dynamic_cast<DOMElement*>(current_node);
	// look for top level groups
	parse_elements(cur_elm,prams_,pram_str,key_str,value_str,type_str);
	// see if this is the element that we want
	if(XMLString::equals(cur_elm->getTagName(),elm_name))
	{
	  DOMNodeList* pram_elms = cur_elm->getChildNodes();
	  const XMLSize_t pram_count =  pram_elms->getLength();
	  for(XMLSize_t k = 0; k<pram_count; ++k)
	  {
	    parse_elements(pram_elms->item(k),prams_,pram_str,key_str,value_str,type_str);
	    
	  }
	  
	}
	
      }
    }
	   
  }
  catch( xercesc::XMLException& e )
  {
    char* message = xercesc::XMLString::transcode( e.getMessage() );
    std::ostringstream errBuf;
    errBuf << "Error parsing file: " << message << std::flush;
    XMLString::release( &message );

  }
  
  
  XMLString::release(&key_str);
  XMLString::release(&type_str);
  XMLString::release(&value_str);
  XMLString::release(&pram_str);
  
  // clean up xml stuff
  XMLString::release(&elm_name);
  delete config_parser;
  delete memBuf;
  try
  {
    XMLPlatformUtils::Terminate();  // Terminate Xerces
  }
  catch( xercesc::XMLException& e )
  {
    char* message = xercesc::XMLString::transcode( e.getMessage() );

    cerr << "XML ttolkit teardown error: " << message << endl;
    XMLString::release( &message );
  }

  
  for(unsigned int j = 0; j<prams_.size();++j)
    cout<<prams_[j].key<<": "
	<<'('<<prams_[j].type<<") "
	<<prams_[j].value<<endl;
  



  
  
  // clear the input data
  src.unlockPage(image,false);
  
  src.close(0);
  
  FreeImage_DeInitialise();

  return 0;
  
}
Exemple #10
0
XERCES_CPP_NAMESPACE_USE

int main( int argc, char *argv[] )
{
    std::cout << "****************************" << std::endl;
    std::cout << "XML DOM PARSER PLAY" << std::endl;
    std::cout << "****************************" << std::endl;

    try
    {
        XMLPlatformUtils::Initialize();
    }
    catch( const XMLException& ex )
    {
        std::cerr << "error with xml initialisation:" << ex.getMessage() << std::endl;
        return 1;
    }

    std::cout << "Building parser ..." << std::endl;
    XercesDOMParser* parser = new XercesDOMParser();
    if( !parser )
    {
        std::cerr << "no parser" << std::endl;
        return 1;
    }
    parser->setValidationScheme(XercesDOMParser::Val_Always);
    parser->setDoNamespaces(false);
    parser->setDoSchema(false);
    parser->setCreateEntityReferenceNodes(false);

    std::cout << "Building error handler" << std::endl;
    ErrorHandler* errHandler = dynamic_cast<ErrorHandler*>(new HandlerBase());
    if( errHandler == 0 )
    {
        std::cerr << "ibad cast" << std::endl;
        return 1;
    } 
    
    if( errHandler == 0 )
    {
        std::cerr << "error with errorhandler caszting:" << std::endl;
        return 1;
    }
    parser->setErrorHandler(errHandler);

    char* xmlFile = "/home/suggitpe/test/RPMS/config/rpms_config.xml";
    try
    {
        parser->parse(xmlFile);
        if( parser->getErrorCount() == 0 )
        {
            std::cerr << "errors in parsing" << std::endl;
            return 1;
        }
        DOMDocument * doc = parser->getDocument();
        if( doc->hasChildNodes() )
        {
            std::cout << "Num nodes: " << doc->getChildNodes()->getLength() << std::endl;
            for( int i = 0; i < doc->getChildNodes()->getLength();++i )
            {
                cout << "\t" << i << " type: " << doc->getChildNodes()->item(i)->getNodeType() << endl;
                if( doc->getChildNodes()->item(i)->getNodeType() == 1 )
                {
                    DOMElement *e = dynamic_cast<DOMElement*>(doc->getChildNodes()->item(i));
                    if( !e ) { cerr << "bad cast" << endl; }
                    if( e->hasChildNodes() )
                    {
                        cout << "\t\telement found with " << e->getChildNodes()->getLength() << " nodes"<< endl;
                    }
                    else
                    {
                        cout << "No child nodes" << endl;
                    }
                }
            }

            cout << "now for the other way" << endl;
            XMLCh * name = XMLString::transcode("system_components");
            DOMNodeList *list = doc->getDocumentElement()->getElementsByTagName( name );
            XMLString::release(&name);
            
            std::cout << "Got list [" << list->getLength() << "]" << std::endl;
            for( XMLSize_t i =0; i < list->getLength(); ++i )
            {
                std::cout << "." << std::endl;
            }
        }
        else
        {
            std::cout << "no child nodes" << std::endl;
        }
    }
    catch( const XMLException& ex )
    {
        std::cerr << "error with xml parser:" << ex.getMessage() << std::endl;
        return 1;
    }
    catch( const DOMException& dex )
    {
        std::cerr << "error with xml parser:" << dex.msg << std::endl;
        return 1;
    }
    catch(...)
    {
        std::cerr << "unknown problems" << std::endl;
        return 1;
            
    }
    delete parser;
    delete errHandler;

    std::cout << "****************************" << std::endl;
    std::cout << "" << std::endl;
    return 0;
}
Exemple #11
0
void
Importer::parseScene
(const char* path, Scene *scene)
{
  // Inicialización.
  try {
    XMLPlatformUtils::Initialize();
  }
  catch (const XMLException& toCatch) {
    char* message = XMLString::transcode(toCatch.getMessage());
    cout << "Error durante la inicialización! :\n"
	 << message << "\n";
    XMLString::release(&message);
    return;
  }

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

  // 'Parseando' el fichero xml...
  try {
    parser->parse(path);
  }
  catch (const XMLException& toCatch) {
    char* message = XMLString::transcode(toCatch.getMessage());
    cout << "Excepción capturada: \n"
	 << message << "\n";
    XMLString::release(&message);
  }
  catch (const DOMException& toCatch) {
    char* message = XMLString::transcode(toCatch.msg);
    cout << "Excepción capturada: \n"
	 << message << "\n";
    XMLString::release(&message);
  }
  catch (...) {
    cout << "Excepción no esperada.\n" ;
    return;
  }

  DOMDocument* xmlDoc;
  DOMElement* elementRoot;

  try {
    // Obtener el elemento raíz del documento.
    xmlDoc = parser->getDocument(); 
    elementRoot = xmlDoc->getDocumentElement();

    if(!elementRoot)
      throw(std::runtime_error("Documento XML vacío."));

  }
  catch (xercesc::XMLException& e ) {
    char* message = xercesc::XMLString::transcode( e.getMessage() );
    ostringstream errBuf;
    errBuf << "Error 'parseando': " << message << flush;
    XMLString::release( &message );
    return;
  }

  XMLCh* camera_ch = XMLString::transcode("camera");  
  XMLCh* graph_ch = XMLString::transcode("graph");  

  // Procesando los nodos hijos del raíz...
  for (XMLSize_t i = 0; 
       i < elementRoot->getChildNodes()->getLength(); 
       ++i ) {
    
    DOMNode* node = elementRoot->getChildNodes()->item(i);

    if (node->getNodeType() == DOMNode::ELEMENT_NODE) {      
	// Nodo <graph>?
	if (XMLString::equals(node->getNodeName(), graph_ch))
	  parseGraph(node, scene);
    }
    
  }
  // Liberar recursos.
  XMLString::release(&camera_ch);
  XMLString::release(&graph_ch);

  delete parser;
}
bool XercesCatalogResolver::ReadCatalog()
{
	bool isOk = true;

	gLog.log(eTypLogDebug, "Deb > CatalogResolver read catalog file");

	try {
		// no need to free this pointer - owned by the parent parser object
		DOMDocument *xmlDoc = mParser->getDocument();
		if (!xmlDoc)
			return false;

		// Get the top-level root element
		DOMElement *elementRoot = xmlDoc->getDocumentElement();
		if (!elementRoot) {
			gLog.log(eTypLogError, "Err > Empty XML document");
			return false;
		}

		// Look one level nested within root (child of root)
		DOMNodeList *children = elementRoot->getChildNodes();
		const XMLSize_t nodeCount = children->getLength();

		XMLCh *elemPublic = XMLString::transcode("public");
		//XMLCh *elemSystem = XMLString::transcode("system");
		XMLCh *attrPublicId = XMLString::transcode("publicId");
		XMLCh *attrUri = XMLString::transcode("uri");

		// Iterate nodes, children of "root" in the XML tree.
		short nodeType;
		std::string publicId, uri;
		for (XMLSize_t i = 0; i < nodeCount; ++i) {
			DOMNode *currentNode = children->item(i);
			// If node is an element
			nodeType = currentNode->getNodeType();
			if (nodeType == DOMNode::ELEMENT_NODE) { // is element
				// Re-cast node as element
				DOMElement *currentElement = static_cast<xercesc::DOMElement*>(currentNode); // dynamic_cast returns null under linux
				if (!currentElement) {
					gLog.log(eTypLogError, "Err > Null catalog node element");
					isOk = false;
					continue;
				}
				// Use public element
				if (XMLString::equals(currentElement->getTagName(), elemPublic)) {
					// Read attributes of element
					publicId = XMLString::transcode(currentElement->getAttribute(attrPublicId));
					uri = XMLString::transcode(currentElement->getAttribute(attrUri));
					mCatalogMap[publicId] = uri;
				}
				// Other elements: system rewriteURI rewriteSystem delegatePublic delegateSystem
				//else if (!XMLString::equals(currentElement->getTagName(), elemSystem)) {
				//	gLog.log(eTypLogError, "Err > Incorrect catalog node element");
				//	isOk = false;
				//}
			}
		}

		XMLString::release(&elemPublic);
		//XMLString::release(&elemSystem);
		XMLString::release(&attrPublicId);
		XMLString::release(&attrUri);
	}
	catch (const AppException &e) {
		gLog.log(eTypLogError, "Err > Application exception during catalog reading - %s", e.what());
		isOk = false;
	}
	catch (const OutOfMemoryException &) {
		gLog.log(eTypLogError, "Err > Out of memory exception during catalog reading");
		isOk = false;
	}
	catch (const XMLException &e) {
		XercesString message(e.getMessage());
		gLog.log(eTypLogError, "Err > Xerces exception during catalog reading: %s", message.localForm());
		isOk = false;
	}
	catch (std::exception &e) {
		gLog.log(eTypLogError, "Err > Unknown exception during catalog reading - %s", e.what());
		isOk = false;
	}

	return isOk;
}