Esempio n. 1
0
std::vector<std::string> GetXpathResults1(DOMElement* root, std::string querystr)
{
	std::vector<std::string> values;

	DOMDocument* document (root->getOwnerDocument ());

	// Obtain namespace resolver.
	xsd::cxx::xml::dom::auto_ptr<XQillaNSResolver> resolver (
		(XQillaNSResolver*)document->createNSResolver (root));

	//// Create XPath expression.
	//xsd::cxx::xml::dom::auto_ptr<const XQillaExpression> expr (
	//	static_cast<const XQillaExpression*> (
	//	doc->createExpression (
	//	xsd::cxx::xml::string (querystr.c_str()).c_str (),
	//	resolver.get ())));
	//

	//// Execute the query.
	//xsd::cxx::xml::dom::auto_ptr<XPath2Result> r (
	//	static_cast<XPath2Result*> (
	//	expr->evaluate (
	//	doc, XPath2Result::ITERATOR_RESULT, 0)));

	// Parse an XPath 2 expression
	xsd::cxx::xml::dom::auto_ptr<DOMXPathExpression> expression(
		document->createExpression(X (querystr.c_str()), resolver.get ()));

	// Execute the query
	xsd::cxx::xml::dom::auto_ptr<DOMXPathResult> xQillaResult(
		expression->evaluate(
		document,
		DOMXPathResult::ITERATOR_RESULT_TYPE, 0));


	//		root, DOMXPathResult::ORDERED_NODE_SNAPSHOT_TYPE  /*DOMXPathResult::ITERATOR_RESULT_TYPE*/, 0));
	// Not sure it is an ordered list
	while (xQillaResult->iterateNext ())
	{
		//const DOMNode* n (r->asNode ());
		//const XMLCh * value = n->getTextContent	(		);
		char * value = XMLString::transcode(xQillaResult->getStringValue());
		values.push_back(value);
		delete value;

	}
	return values;
}
Esempio n. 2
0
std::vector<std::string> CXercesUtils::GetXpathResults(DOMElement* root, std::string querystr)
{
	std::vector<std::string> values;

	DOMDocument* doc (root->getOwnerDocument ());

	// Obtain namespace resolver.
	xsd::cxx::xml::dom::auto_ptr<DOMXPathNSResolver> resolver (
		doc->createNSResolver (root));

	// Create XPath expression.
	xsd::cxx::xml::dom::auto_ptr<DOMXPathExpression> expr (
		doc->createExpression (
		xsd::cxx::xml::string (querystr.c_str()).c_str (),
		resolver.get ()));

	// Execute the query.
	xsd::cxx::xml::dom::auto_ptr<DOMXPathResult> r (
		expr->evaluate (
		root, DOMXPathResult::ORDERED_NODE_SNAPSHOT_TYPE  /*DOMXPathResult::ITERATOR_RESULT_TYPE*/, 0));

	// If no query matches, then return empty vector
	if (!r.get() ) 
		return values;

	// Iterate over the result.
	for (int i=0; i < r->getSnapshotLength(); i++) 
	{
		r->snapshotItem(i);
		DOMNode* n (r->getNodeValue ());
		const XMLCh * value = n->getTextContent	(		);
		values.push_back(xsd::cxx::xml::transcode<char> (value));
	}

	return values;
}
bool XmlWorldReader::Read(const std::string &file) {
	// ワールドを初期化
	try {
		initialize();
		if (initFlag) {
			initializeWorld();
		}
	} catch (...) {
		return false;
	}

	// TODO: ファイルの有無を確認

	// XMLファイルをパース
	const XMLCh gLS[] = {chLatin_L, chLatin_S, chNull};
	DOMImplementationLS *impl = DOMImplementationRegistry::getDOMImplementation(gLS);
	DOMLSParser *parser = impl->createLSParser(
		DOMImplementationLS::MODE_SYNCHRONOUS, NULL
	);
	DOMDocument *doc = parser->parseURI(file.c_str());
	if (doc == nullptr) {
		return false;
	}

	// rootノードを取得
	DOMElement *worldElement = doc->getDocumentElement();
	if (worldElement == nullptr) {
		parser->release();
		return false;
	}
	{
		YPT::XmlString temp("world");
		bool res = XMLString::equals(worldElement->getNodeName(), temp);
		if (!res) {
			parser->release();
			return false;
		}
	}

	// ロード用クラス作成
	YPT::XmlWorldPartReader partReader(doc);

	// XPathコンテキスト作成
	DOMXPathNSResolver *resolver = doc->createNSResolver(worldElement);
	if (resolver == nullptr) {
		parser->release();
		return false;
	}

	YPT::XmlString str, str2;
	DOMXPathResult *result;

	// --------------------------------------------------
	// ワールド全体の設定
	// --------------------------------------------------

	// ワールド名
	str = worldElement->getAttribute(YPT::XmlString("name"));
	if (str != "") {
		name = str;
	}

	// 重力ベクトル
	result = doc->evaluate(
		YPT::XmlString("./gravity"), worldElement, resolver,
		DOMXPathResult::ORDERED_NODE_SNAPSHOT_TYPE,
		NULL
	);
	if (result != nullptr) {
		if (result->getSnapshotLength() >= 1) {
			str = result->getNodeValue()->getTextContent();
			b2Vec2 temp;
			if (!YPT::ConvertStrToVec2(str.ToChar(), &temp)) {
				world.SetGravity(temp);
			}
		}
		result->release();
	}

	// --------------------------------------------------
	// shapes
	// --------------------------------------------------

	result = doc->evaluate(
		YPT::XmlString("./shape"), worldElement, resolver,
		DOMXPathResult::ORDERED_NODE_SNAPSHOT_TYPE,
		NULL
	);
	if (result != nullptr) {
		const XMLSize_t len = result->getSnapshotLength();
		for (XMLSize_t i = 0; i < len; ++i) {
			result->snapshotItem(i);
			DOMNode *node = result->getNodeValue();
			if (node == nullptr) {
				continue;
			}
			DOMNamedNodeMap *nodeMap = node->getAttributes();
			if (nodeMap == nullptr) {
				continue;
			}
			DOMNode *typeNode = nodeMap->getNamedItem(YPT::XmlString("type"));
			if (typeNode == nullptr) {
				continue;
			}
			str = typeNode->getNodeValue();
			b2Shape::Type type;
			int index;
			if (str == "circle") {
				type = b2Shape::e_circle;
				b2CircleShape temp;
				if (partReader.ReadCircleShape(node, &temp)) {
					circleShapes.push_back(temp);
					index = circleShapes.size()-1;
				} else {
					// 読み込み失敗
					continue;
				}
			} else if (str == "edge") {
				type = b2Shape::e_edge;
				b2EdgeShape temp;
				if (partReader.ReadEdgeShape(node, &temp)) {
					edgeShapes.push_back(temp);
					index = edgeShapes.size()-1;
				} else {
					// 読み込み失敗
					continue;
				}
			} else if (str == "polygon") {
				type = b2Shape::e_polygon;
				b2PolygonShape temp;
				if (partReader.ReadPolygonShape(node, &temp)) {
					polygonShapes.push_back(temp);
					index = polygonShapes.size()-1;
				} else {
					// 読み込み失敗
					continue;
				}
			} else if (str == "chain") {
				type = b2Shape::e_chain;
				b2ChainShape temp;
				if (partReader.ReadChainShape(node, &temp)) {
					chainShapes.push_back(temp);
					index = chainShapes.size()-1;
				} else {
					// 読み込み失敗
					continue;
				}
			} else {
				// 未対応
				continue;
			}

			// nameプロパティがあれば保存
			DOMNode *name = nodeMap->getNamedItem(YPT::XmlString("name"));
			if (name != nullptr) {
				str = name->getNodeValue();
				shapes.insert(ShapesMap::value_type(
					std::string(str),
					std::make_pair(type, index)
				));
			}
		}
		result->release();
	}

	// --------------------------------------------------
	// fixtures
	// --------------------------------------------------

	result = doc->evaluate(
		YPT::XmlString("./fixture"), worldElement, resolver,
		DOMXPathResult::ORDERED_NODE_SNAPSHOT_TYPE,
		NULL
	);
	if (result != nullptr) {
		const XMLSize_t len = result->getSnapshotLength();
		for (XMLSize_t i = 0; i < len; ++i) {
			result->snapshotItem(i);
			DOMNode *node = result->getNodeValue();
			if (node == nullptr) {
				continue;
			}
			DOMXPathResult *result2 = doc->evaluate(
				YPT::XmlString("./shape"), node, resolver,
				DOMXPathResult::ORDERED_NODE_SNAPSHOT_TYPE,
				NULL
			);
			if (result2 == nullptr) {
				continue;
			}
			DOMNode *shapeNode = result2->getNodeValue();
			if (shapeNode == nullptr) {
				continue;
			}
			str = shapeNode->getTextContent();
			result2->release();
			ShapesMap::iterator found = shapes.find(std::string(str));
			if (found == shapes.end()) {
				continue;
			}

			// fixture読み込み
			b2FixtureDef fixtureDef;
			b2Shape *shape = NULL;
			int index = found->second.second;
			switch (found->second.first) {
			case b2Shape::e_circle:
				shape = &circleShapes[index];
				break;
			case b2Shape::e_edge:
				shape = &edgeShapes[index];
				break;
			case b2Shape::e_polygon:
				shape = &polygonShapes[index];
				break;
			case b2Shape::e_chain:
				shape = &chainShapes[index];
				break;
			default:
				// 未対応
				break;
			}
			if (shape == NULL) {
				continue;
			}
			if (partReader.ReadFixture(node, shape, &fixtureDef)) {
				// 読み込み成功
				// nameプロパティがあれば保存する
				DOMNamedNodeMap *nodeMap = node->getAttributes();
				if (nodeMap == nullptr) {
					continue;
				}
				DOMNode *nameNode = nodeMap->getNamedItem(YPT::XmlString("name"));
				if (nameNode == nullptr) {
					continue;
				}
				str = nameNode->getNodeValue();
				fixtures.insert(FixturesMap::value_type(
					std::string(str), fixtureDef
				));
			}
		}
		result->release();
	}

	// --------------------------------------------------
	// bodies
	// --------------------------------------------------

	result = doc->evaluate(
		YPT::XmlString("./body"), worldElement, resolver,
		DOMXPathResult::ORDERED_NODE_SNAPSHOT_TYPE,
		NULL
	);
	if (result != nullptr) {
		const XMLSize_t len = result->getSnapshotLength();
		for (XMLSize_t i = 0; i < len; ++i) {
			result->snapshotItem(i);
			DOMNode *node = result->getNodeValue();
			if (node == nullptr) {
				continue;
			}
			DOMXPathResult *result2 = doc->evaluate(
				YPT::XmlString("./fixtures/fixture"), node, resolver,
				DOMXPathResult::ORDERED_NODE_SNAPSHOT_TYPE,
				NULL
			);
			if (result2 == nullptr) {
				continue;
			}
			std::vector< b2FixtureDef *> fixtureDefs;
			const XMLSize_t fixturesLen = result2->getSnapshotLength();
			for (XMLSize_t j = 0; j < fixturesLen; ++j) {
				result2->snapshotItem(j);
				DOMNode *fixtureNode = result2->getNodeValue();
				if (fixtureNode == nullptr) {
					continue;
				}
				str = fixtureNode->getTextContent();
				FixturesMap::iterator found = fixtures.find(
					std::string(str)
				);
				if (found != fixtures.end()) {
					fixtureDefs.push_back(&found->second);
				}
			}
			result2->release();

			b2Body *body = partReader.ReadBody(world, node, fixtureDefs);
			if (body != nullptr) {
				// 読み込み成功
				// nameプロパティがあれば保存する
				DOMNamedNodeMap *nodeMap = node->getAttributes();
				if (nodeMap == nullptr) {
					continue;
				}
				DOMNode *nameNode = nodeMap->getNamedItem(YPT::XmlString("name"));
				if (nameNode == nullptr) {
					continue;
				}
				str = nameNode->getNodeValue();
				bodies.insert(BodiesMap::value_type(
					std::string(str), body
				));
			}
		}
		result->release();
	}

	// --------------------------------------------------
	// 読み込み完了
	// --------------------------------------------------

	resolver->release();
	parser->release();

	return true;
}
Esempio n. 4
0
// ---------------------------------------------------------------------------
//
//  main
//
// ---------------------------------------------------------------------------
int main(int argC, char* argV[])
{
    int retval = 0;

    // Initialize the XML4C2 system
    try
    {
        XMLPlatformUtils::Initialize();
    }

    catch(const XMLException &toCatch)
    {
        XERCES_STD_QUALIFIER cerr << "Error during Xerces-c Initialization.\n"
             << "  Exception message:"
             << StrX(toCatch.getMessage()) << XERCES_STD_QUALIFIER endl;
        return 1;
    }

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

    // See if non validating dom parser configuration is requested.
    int parmInd;
    for (parmInd = 1; parmInd < argC; parmInd++)
    {
        // Break out on first parm not starting with a dash
        if (argV[parmInd][0] != '-')
            break;

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

            if (!strcmp(parm, "never"))
                gValScheme = XercesDOMParser::Val_Never;
            else if (!strcmp(parm, "auto"))
                gValScheme = XercesDOMParser::Val_Auto;
            else if (!strcmp(parm, "always"))
                gValScheme = XercesDOMParser::Val_Always;
            else
            {
                XERCES_STD_QUALIFIER cerr << "Unknown -v= value: " << parm << XERCES_STD_QUALIFIER endl;
                XMLPlatformUtils::Terminate();
                return 2;
            }
        }
         else if (!strcmp(argV[parmInd], "-n")
              ||  !strcmp(argV[parmInd], "-N"))
        {
            gDoNamespaces = true;
        }
         else if (!strcmp(argV[parmInd], "-s")
              ||  !strcmp(argV[parmInd], "-S"))
        {
            gDoSchema = true;
        }
         else if (!strcmp(argV[parmInd], "-f")
              ||  !strcmp(argV[parmInd], "-F"))
        {
            gSchemaFullChecking = true;
        }
         else if (!strcmp(argV[parmInd], "-e")
              ||  !strcmp(argV[parmInd], "-E"))
        {
            gDoCreate = true;
        }
         else if (!strncmp(argV[parmInd], "-wenc=", 6))
        {
             // Get out the encoding name
             gOutputEncoding = XMLString::transcode( &(argV[parmInd][6]) );
        }
         else if (!strncmp(argV[parmInd], "-wfile=", 7))
        {
             goutputfile =  &(argV[parmInd][7]);
        }
         else if (!strncmp(argV[parmInd], "-wddc=", 6))
        {
            const char* const parm = &argV[parmInd][6];

            if (!strcmp(parm, "on"))
				gDiscardDefaultContent = true;
            else if (!strcmp(parm, "off"))
				gDiscardDefaultContent = false;
            else
            {
                XERCES_STD_QUALIFIER cerr << "Unknown -wddc= value: " << parm << XERCES_STD_QUALIFIER endl;
                XMLPlatformUtils::Terminate();
                return 2;
            }

        }
         else if (!strncmp(argV[parmInd], "-wscs=", 6))
        {
            const char* const parm = &argV[parmInd][6];

            if (!strcmp(parm, "on"))
				gSplitCdataSections = true;
			else if (!strcmp(parm, "off"))
				gSplitCdataSections = false;
            else
            {
                XERCES_STD_QUALIFIER cerr << "Unknown -wscs= value: " << parm << XERCES_STD_QUALIFIER endl;
                XMLPlatformUtils::Terminate();
                return 2;
            }
        }
         else if (!strncmp(argV[parmInd], "-wflt=", 6))
        {
            const char* const parm = &argV[parmInd][6];

            if (!strcmp(parm, "on"))
				gUseFilter = true;
			else if (!strcmp(parm, "off"))
				gUseFilter = false;
            else
            {
                XERCES_STD_QUALIFIER cerr << "Unknown -wflt= value: " << parm << XERCES_STD_QUALIFIER endl;
                XMLPlatformUtils::Terminate();
                return 2;
            }
        }
         else if (!strncmp(argV[parmInd], "-wfpp=", 6))
        {
            const char* const parm = &argV[parmInd][6];

            if (!strcmp(parm, "on"))
				gFormatPrettyPrint = true;
			else if (!strcmp(parm, "off"))
				gFormatPrettyPrint = false;
            else
            {
                XERCES_STD_QUALIFIER cerr << "Unknown -wfpp= value: " << parm << XERCES_STD_QUALIFIER endl;
                XMLPlatformUtils::Terminate();
                return 2;
            }
        }
         else if (!strncmp(argV[parmInd], "-wbom=", 6))
        {
            const char* const parm = &argV[parmInd][6];

            if (!strcmp(parm, "on"))
                gWriteBOM = true;
            else if (!strcmp(parm, "off"))
                gWriteBOM = false;
            else
            {
                XERCES_STD_QUALIFIER cerr << "Unknown -wbom= value: " << parm << XERCES_STD_QUALIFIER endl;
                XMLPlatformUtils::Terminate();
                return 2;
            }
        }
         else if (!strncmp(argV[parmInd], "-xpath=", 7))
        {
             gXPathExpression = &(argV[parmInd][7]);
        }
         else
        {
            XERCES_STD_QUALIFIER cerr << "Unknown option '" << argV[parmInd]
                 << "', ignoring it.\n" << XERCES_STD_QUALIFIER endl;
        }
    }

    //
    //  And now we have to have only one parameter left and it must be
    //  the file name.
    //
    if (parmInd + 1 != argC)
    {
        usage();
        XMLPlatformUtils::Terminate();
        return 1;
    }
    gXmlFile = argV[parmInd];

    //
    //  Create our parser, then attach an error handler to the parser.
    //  The parser will call back to methods of the ErrorHandler if it
    //  discovers errors during the course of parsing the XML document.
    //
    XercesDOMParser *parser = new XercesDOMParser;
    parser->setValidationScheme(gValScheme);
    parser->setDoNamespaces(gDoNamespaces);
    parser->setDoSchema(gDoSchema);
    parser->setValidationSchemaFullChecking(gSchemaFullChecking);
    parser->setCreateEntityReferenceNodes(gDoCreate);

    DOMTreeErrorReporter *errReporter = new DOMTreeErrorReporter();
    parser->setErrorHandler(errReporter);

    //
    //  Parse the XML file, catching any XML exceptions that might propogate
    //  out of it.
    //
    bool errorsOccured = false;
    try
    {
        parser->parse(gXmlFile);
    }
    catch (const OutOfMemoryException&)
    {
        XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl;
        errorsOccured = true;
    }
    catch (const XMLException& e)
    {
        XERCES_STD_QUALIFIER cerr << "An error occurred during parsing\n   Message: "
             << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
        errorsOccured = true;
    }

    catch (const DOMException& e)
    {
        const unsigned int maxChars = 2047;
        XMLCh errText[maxChars + 1];

        XERCES_STD_QUALIFIER cerr << "\nDOM Error during parsing: '" << gXmlFile << "'\n"
             << "DOMException code is:  " << e.code << XERCES_STD_QUALIFIER endl;

        if (DOMImplementation::loadDOMExceptionMsg(e.code, errText, maxChars))
             XERCES_STD_QUALIFIER cerr << "Message is: " << StrX(errText) << XERCES_STD_QUALIFIER endl;

        errorsOccured = true;
    }

    catch (...)
    {
        XERCES_STD_QUALIFIER cerr << "An error occurred during parsing\n " << XERCES_STD_QUALIFIER endl;
        errorsOccured = true;
    }

    // If the parse was successful, output the document data from the DOM tree
    if (!errorsOccured && !errReporter->getSawErrors())
    {
        DOMPrintFilter   *myFilter = 0;

        try
        {
            // get a serializer, an instance of DOMLSSerializer
            XMLCh tempStr[3] = {chLatin_L, chLatin_S, chNull};
            DOMImplementation *impl          = DOMImplementationRegistry::getDOMImplementation(tempStr);
            DOMLSSerializer   *theSerializer = ((DOMImplementationLS*)impl)->createLSSerializer();
            DOMLSOutput       *theOutputDesc = ((DOMImplementationLS*)impl)->createLSOutput();

            // set user specified output encoding
            theOutputDesc->setEncoding(gOutputEncoding);

            // plug in user's own filter
            if (gUseFilter)
            {
                // even we say to show attribute, but the DOMLSSerializer
                // will not show attribute nodes to the filter as
                // the specs explicitly says that DOMLSSerializer shall
                // NOT show attributes to DOMLSSerializerFilter.
                //
                // so DOMNodeFilter::SHOW_ATTRIBUTE has no effect.
                // same DOMNodeFilter::SHOW_DOCUMENT_TYPE, no effect.
                //
                myFilter = new DOMPrintFilter(DOMNodeFilter::SHOW_ELEMENT   |
                                              DOMNodeFilter::SHOW_ATTRIBUTE |
                                              DOMNodeFilter::SHOW_DOCUMENT_TYPE);
                theSerializer->setFilter(myFilter);
            }

            // plug in user's own error handler
            DOMErrorHandler *myErrorHandler = new DOMPrintErrorHandler();
            DOMConfiguration* serializerConfig=theSerializer->getDomConfig();
            serializerConfig->setParameter(XMLUni::fgDOMErrorHandler, myErrorHandler);

            // set feature if the serializer supports the feature/mode
            if (serializerConfig->canSetParameter(XMLUni::fgDOMWRTSplitCdataSections, gSplitCdataSections))
                serializerConfig->setParameter(XMLUni::fgDOMWRTSplitCdataSections, gSplitCdataSections);

            if (serializerConfig->canSetParameter(XMLUni::fgDOMWRTDiscardDefaultContent, gDiscardDefaultContent))
                serializerConfig->setParameter(XMLUni::fgDOMWRTDiscardDefaultContent, gDiscardDefaultContent);

            if (serializerConfig->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, gFormatPrettyPrint))
                serializerConfig->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, gFormatPrettyPrint);

            if (serializerConfig->canSetParameter(XMLUni::fgDOMWRTBOM, gWriteBOM))
                serializerConfig->setParameter(XMLUni::fgDOMWRTBOM, gWriteBOM);

            //
            // Plug in a format target to receive the resultant
            // XML stream from the serializer.
            //
            // StdOutFormatTarget prints the resultant XML stream
            // to stdout once it receives any thing from the serializer.
            //
            XMLFormatTarget *myFormTarget;
            if (goutputfile)
                myFormTarget=new LocalFileFormatTarget(goutputfile);
            else
                myFormTarget=new StdOutFormatTarget();
            theOutputDesc->setByteStream(myFormTarget);

            // get the DOM representation
            DOMDocument *doc = parser->getDocument();

            //
            // do the serialization through DOMLSSerializer::write();
            //
            if(gXPathExpression!=NULL)
            {
                XMLCh* xpathStr=XMLString::transcode(gXPathExpression);
                DOMElement* root = doc->getDocumentElement();
                try
                {
                    DOMXPathNSResolver* resolver=doc->createNSResolver(root);
                    DOMXPathResult* result=doc->evaluate(
                      xpathStr,
                      root,
                      resolver,
                      DOMXPathResult::ORDERED_NODE_SNAPSHOT_TYPE,
                      NULL);

                    XMLSize_t nLength = result->getSnapshotLength();
                    for(XMLSize_t i = 0; i < nLength; i++)
                    {
                      result->snapshotItem(i);
                      theSerializer->write(result->getNodeValue(), theOutputDesc);
                    }

                    result->release();
                    resolver->release ();
                }
                catch(const DOMXPathException& e)
                {
                    XERCES_STD_QUALIFIER cerr << "An error occurred during processing of the XPath expression. Msg is:"
                        << XERCES_STD_QUALIFIER endl
                        << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
                    retval = 4;
                }
                catch(const DOMException& e)
                {
                    XERCES_STD_QUALIFIER cerr << "An error occurred during processing of the XPath expression. Msg is:"
                        << XERCES_STD_QUALIFIER endl
                        << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
                    retval = 4;
                }
                XMLString::release(&xpathStr);
            }
            else
                theSerializer->write(doc, theOutputDesc);

            theOutputDesc->release();
            theSerializer->release();

            //
            // Filter, formatTarget and error handler
            // are NOT owned by the serializer.
            //
            delete myFormTarget;
            delete myErrorHandler;

            if (gUseFilter)
                delete myFilter;

        }
        catch (const OutOfMemoryException&)
        {
            XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl;
            retval = 5;
        }
        catch (XMLException& e)
        {
            XERCES_STD_QUALIFIER cerr << "An error occurred during creation of output transcoder. Msg is:"
                << XERCES_STD_QUALIFIER endl
                << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
            retval = 4;
        }

    }
    else
        retval = 4;

    //
    //  Clean up the error handler. The parser does not adopt handlers
    //  since they could be many objects or one object installed for multiple
    //  handlers.
    //
    delete errReporter;

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

    XMLString::release(&gOutputEncoding);

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

    return retval;
}
Esempio n. 5
0
int main(int argc, char *argv[])
{
	if (argc < 5)
	{
		cout << currentDateTime()  << "Usage: GTTagging.exe video_path flag_roi(1=true, 0=false) flag_load(1=true, 0=false) flag_saveROI(1=true, 0=false)\n";
		return 1;
	}

	/*serialize_video();*/
	string outFilename = "output_video.xml";
	serializeVideo(outFilename);
	removeTrailingSpace(outFilename);

	path video_path (argv[1]);

	string video_name = video_path.filename().replace_extension("").string();

	cout << "video_path filename: " << video_name << endl;

	string base_name = video_path.filename().replace_extension("").string();
	cout << "base_name: " << base_name << endl;

	string base_path = video_path.remove_filename().string();
	cout << "base_path: " << base_path << endl;	

	ostringstream codebook_paramters_path;

	codebook_paramters_path << base_path << "\\" << base_name << "_cparameters.dat";
	cout << "cparameters filename: " <<  codebook_paramters_path.str() << endl;	

	ostringstream xml_path;

	xml_path << base_path << "\\" << base_name << ".xml";
	cout << "xml filename: " <<  xml_path.str() << endl;

	path gt_xml_path (xml_path.str());
	
	try {
		
		XMLPlatformUtils::Initialize();	
		XQillaPlatformUtils::initialize();

	} catch (const XMLException& eXerces) {
		cerr << "Error during Xerces-C initialisation.\n"
			<< "Xerces exception message: "
			<< UTF8(eXerces.getMessage()) << endl;
		return 1;
	}

	try
	{
		if (!exists(gt_xml_path))
		{
			cout << currentDateTime()  << "File: " << gt_xml_path << " doesn't exist!" << endl;
			return 1;
		}

		if (!exists(video_path))
		{
			cout << currentDateTime()  << "File: " << video_path << " doesn't exist!" << endl;
			return 1;
		}		

		cout << currentDateTime()  << "Processing " << video_path << " ..." << endl;

		DOMImplementation* xqillaImplementation = DOMImplementationRegistry::getDOMImplementation(X("XPath2 3.0"));

		DOMLSParser* xmlParser = xqillaImplementation->createLSParser(DOMImplementationLS::MODE_SYNCHRONOUS, 0);

		DOMConfiguration* dc_parser = xmlParser->getDomConfig();

		dc_parser->setParameter(XMLUni::fgDOMNamespaces, true);
		dc_parser->setParameter(XMLUni::fgXercesSchema, true);
		dc_parser->setParameter(XMLUni::fgDOMValidate, true);

		DOMDocument* document = xmlParser->parseURI(xml_path.str().c_str());

		if(document == 0) {
			cerr << "Document not found: " << xml_path.str().c_str() << endl;
			return 1;
		}

		const DOMXPathNSResolver* resolver = document->createNSResolver(document->getDocumentElement());

		XQillaNSResolver* xqillaResolver = (XQillaNSResolver*)resolver;
		xqillaResolver->addNamespaceBinding(X("xs"), X("http://www.w3.org/2001/XMLSchema"));	
		xqillaResolver->addNamespaceBinding(X("fn"), X("http://www.w3.org/2005/xpath-functions"));			

		// Initialize Subsense
		cv::VideoCapture oVideoInput;

		cv::Mat oCurrInputFrame, oCurrSegmMask, oCurrReconstrBGImg;	

		oVideoInput.open(argv[1]);
		oVideoInput >> oCurrInputFrame;
		oVideoInput.set(CV_CAP_PROP_POS_FRAMES,0);	

		// create BGS Subsense object
		BackgroundSubtractorSuBSENSE oBGSAlg;

		// copy loadvars flag
		if (strcmp(argv[3], "1") == 0) {
			oBGSAlg.loadvars = true;
			cout << currentDateTime()  << "Pre-loading codebook ..." << endl;
		} else {
			oBGSAlg.loadvars = false;
			cout << currentDateTime()  << "Building codebook ..." << endl;
		}
			
		// check if open
		if(!oVideoInput.isOpened() || oCurrInputFrame.empty()) {
			printf("Could not open video file at '%s'.\n", argv[1]);
			cv::waitKey();
			return -1;
		}

		// Initialize Subsense variables
		oCurrSegmMask.create(oCurrInputFrame.size(),CV_8UC1);
		oCurrReconstrBGImg.create(oCurrInputFrame.size(),oCurrInputFrame.type());

		// Depending on flag_roi load ROI or not
		cv::Mat R;
		if (strcmp(argv[2], "1") == 0) {
			R = cv::imread("ROI.png",CV_8UC1);
		} else {
			R = cv::Mat(oCurrInputFrame.size(),CV_8UC1,cv::Scalar_<uchar>(255));
		}

		oBGSAlg.saveCodebookParametersPath(codebook_paramters_path.str());
		oBGSAlg.initialize(oCurrInputFrame, R);

		// create visualization windows
		/*cv::namedWindow("input",cv::WINDOW_AUTOSIZE);
		cv::namedWindow("segmentation mask",cv::WINDOW_AUTOSIZE);*/

		int xml_roi_counter = 0;
		int bgs_roi_counter = 0;
		
		int frame_counter = 0;
		//loop through video frames
		while(1) {							
			try {
				std::cout << "frame counter = " << frame_counter << std::endl;
				oVideoInput >> oCurrInputFrame;

				if(oCurrInputFrame.empty())
					break;

				//Process
				oBGSAlg(oCurrInputFrame,oCurrSegmMask);
				//oBGSAlg.getBackgroundImage(oCurrReconstrBGImg);
				std::vector<F_state_struct> F_states;

				// TODO Add function to static lib.
				getRegions(oCurrSegmMask, F_states, pminArea);

				std::ostringstream object_xpath_expression;
				object_xpath_expression << "//object[../@id=\""<< frame_counter++ << "\"]";
				cout << currentDateTime()  << "object_xpath_expression: " << object_xpath_expression.str() << endl;

				const DOMXPathExpression* parsedExpression = document->createExpression(X(object_xpath_expression.str().c_str()), resolver);

				DOMXPathResult* iteratorResult = (DOMXPathResult*)parsedExpression->evaluate(document->getDocumentElement(), DOMXPathResult::ITERATOR_RESULT_TYPE, 0);

				/*ostringstream xml_rois_path;

				xml_rois_path << base_path << "\\" << base_name << "_xml_rois";
				cout << "xml_rois_path filename: " <<  xml_rois_path.str() << endl;

				path xml_rois_dir (xml_rois_path.str());				

				if(!exists(xml_rois_dir)) {
					if (create_directories(xml_rois_dir)) {
						cout << currentDateTime()  << "xml_rois_dir created!" << endl;												
					} else {
						cout << currentDateTime()  << "Cannot create xml_rois_dir!" << endl;
						return 1;
					}
				}*/

				ostringstream bgs_rois_path;

				bgs_rois_path << base_path << "\\" << base_name << "_bgs_rois";
				cout << "bgs_rois_path filename: " <<  bgs_rois_path.str() << endl;

				path bgs_rois_dir (bgs_rois_path.str());

				if(!exists(bgs_rois_dir)) {
					if (create_directories(bgs_rois_dir)) {
						cout << currentDateTime()  << "bgs_rois_dir created!" << endl;												
					} else {
						cout << currentDateTime()  << "Cannot create bgs_rois_dir!" << endl;
						return 1;
					}
				}

				int i = 0;

				while(iteratorResult->iterateNext()) {
					if(iteratorResult->isNode()) {
						DOMNode* n (iteratorResult->getNodeValue ());

						char * localName = XMLString::transcode(n->getLocalName());

						//cout << currentDateTime()  << "Localname: " << localName << endl;

						DOMElement* resultElement = dynamic_cast<DOMElement*>(n);

						if(strcmp( localName, "object") == 0) {

							object* o = new object (*resultElement);
							
							int w = o->w().get();
							int h = o->h().get();
							int x = o->x().get();
							int y = o->y().get();
							
							cout << currentDateTime()  << "fish_species: " << o->fish_species().get() << endl;
							cout << currentDateTime()  << "h: " << h << endl;
							cout << currentDateTime()  << "w: " << w << endl;
							cout << currentDateTime()  << "x: " << x << endl;
							cout << currentDateTime()  << "y: " << y << endl;

							try
							{
								ostringstream fish_specie_path;

								fish_specie_path << base_path << "\\" << o->fish_species().get();
								cout << "fish_specie_path filename: " <<  fish_specie_path.str() << endl;

								path fish_specie_dir (fish_specie_path.str());

								if(!exists(fish_specie_dir)) {
									if (create_directories(fish_specie_dir)) {
										cout << currentDateTime()  << "bgs_rois_dir created!" << endl;												
									} else {
										cout << currentDateTime()  << "Cannot create fish_specie_dir!" << endl;
										return 1;
									}
								}

								std::cout << "XML ROI: " << x << " , " << y << " , " << x+w << " , " << y+h << std::endl;
								Rect xml_roi_rectangle = Rect(Point(x, y), Point(x+w, y+h));

								Mat xmlROI, xmlROI_bg;								
								Mat xmlROIMask = oCurrSegmMask(xml_roi_rectangle);

								xml_roi_counter++;
								oCurrInputFrame(xml_roi_rectangle).copyTo(xmlROI_bg);
								sprintf(printf_buffer, "%s\\%s_roi%04d_bg.png", fish_specie_path.str().c_str(), base_name, xml_roi_counter);

								cout << currentDateTime()  << "Saving to: " << printf_buffer << endl;
								imwrite(printf_buffer, xmlROI_bg);
								cout << currentDateTime()  << "Saved..." << endl;

								oCurrInputFrame(xml_roi_rectangle).copyTo(xmlROI, xmlROIMask);
								sprintf(printf_buffer, "%s\\%s_roi%04d.png\0", fish_specie_path.str().c_str(), base_name, xml_roi_counter);

								cout << currentDateTime()  << "Saving to: " << printf_buffer << endl;
								imwrite(printf_buffer, xmlROI);
								cout << currentDateTime()  << "Saved..." << endl;

								//rectangle( oCurrInputFrame, Point(x, y), Point(x+w, y+h), Scalar( 255, 9, 0 ), +3, 4 );
							}
							catch (exception& e)
							{
								cout << "Error: " <<  e.what() << '\n';
							}
						}
					}
				}

				for(int i=0; i<F_states.size(); i++) {
					std::cout << "BGS ROI: " << F_states.at(i).min_x << " , " << F_states.at(i).min_y << " , " << F_states.at(i).max_x << " , " << F_states.at(i).max_y << std::endl;
					Rect bgs_roi_rectangle = Rect(Point(F_states.at(i).min_x, F_states.at(i).min_y), Point(F_states.at(i).max_x, F_states.at(i).max_y));
			
					Mat bgsROI, bgsROI_bg;
					Mat bgsROIMask = oCurrSegmMask(bgs_roi_rectangle);
			
					bgs_roi_counter++;
					
					oCurrInputFrame(bgs_roi_rectangle).copyTo(bgsROI_bg);
					sprintf(printf_buffer, "%s\\roi%04d_bg.png", bgs_rois_path.str().c_str(), bgs_roi_counter);

					cout << currentDateTime()  << "Saving to: " << printf_buffer << endl;
					imwrite(printf_buffer, bgsROI_bg);
					cout << currentDateTime()  << "Saved..." << endl;

					oCurrInputFrame(bgs_roi_rectangle).copyTo(bgsROI, bgsROIMask);
					sprintf(printf_buffer, "%s\\roi%04d.png\0", bgs_rois_path.str().c_str(), bgs_roi_counter);

					cout << currentDateTime()  << "Saving to: " << printf_buffer << endl;
					imwrite(printf_buffer, bgsROI);
					cout << currentDateTime()  << "Saved..." << endl;

					//rectangle( oCurrInputFrame, Point(F_states.at(i).min_x, F_states.at(i).min_y), Point(F_states.at(i).max_x, F_states.at(i).max_y), Scalar( 0, 55, 255 ), +3, 4 );
				}

				//Background Subtraction Visualization
				/*imshow("input",oCurrInputFrame);
				imshow("segmentation mask",oCurrSegmMask);*/
				//imshow("reconstructed background",oCurrReconstrBGImg);								
				
				/*if(cv::waitKey(1)==27)
					break;*/

				//Save subsense codebooks and parameters
				if (strcmp(argv[4], "1") == 0) {
					oBGSAlg.saveVariables();
				}
			} catch(DOMXPathException &e) {
				cerr << "DOMXPathException: " << UTF8(e.msg) << endl;
				return 1;
			} catch(DOMException &e) {
				cerr << "DOMException: " << UTF8(e.getMessage()) << endl;
				return 1;
			}						
		}		
	} catch (const filesystem_error& ex) {
		cout << currentDateTime()  << ex.what() << '\n';
	}

	XQillaPlatformUtils::terminate();
	XMLPlatformUtils::Terminate();

	return 0;
}