Esempio n. 1
0
//
// domPrint  -  Dump the contents of a DOM node.
//              For debugging failures, when all else fails.
//                 Works recursively - initially called with a document node.
//
void ThreadParser::domPrint()
{
    printf("Begin DOMPrint ...\n");
    if (gRunInfo.dom)
    {
        try
        {
            XMLCh tempStr[100];
            XMLString::transcode("LS", tempStr, 99);
            DOMImplementation *impl          = DOMImplementationRegistry::getDOMImplementation(tempStr);
            DOMLSSerializer   *theSerializer = ((DOMImplementationLS*)impl)->createLSSerializer();
            DOMLSOutput       *theOutput     = ((DOMImplementationLS*)impl)->createLSOutput();
            XMLFormatTarget   *myFormTarget  = new StdOutFormatTarget();
            theOutput->setByteStream(myFormTarget);
            DOMNode           *doc           = fXercesDOMParser->getDocument();
            theSerializer->write(doc,theOutput);
            delete myFormTarget;
            theSerializer->release();
            theOutput->release();
        }
        catch (...)
        {
            // do nothing
        }
    }
    printf("End DOMPrint\n");
}
Esempio n. 2
0
CStdString DomSerializer::DomNodeToString(DOMNode* node)
{
	CStdString output;

    DOMImplementation *impl          = DOMImplementationRegistry::getDOMImplementation(XStr("LS").unicodeForm());
    DOMLSSerializer   *theSerializer = ((DOMImplementationLS*)impl)->createLSSerializer();
		DOMConfiguration	* dc 					 = theSerializer->getDomConfig();
    // set user specified output encoding
    //dc->setEncoding(gOutputEncoding);
		dc->setParameter(XStr("format-pretty-print").unicodeForm(), true);

    XMLFormatTarget *myFormTarget;
		myFormTarget = new MemBufFormatTarget ();

		DOMLSOutput *outputStream = ((DOMImplementationLS*)impl)->createLSOutput();
		outputStream->setByteStream(myFormTarget);

    theSerializer->write(node, outputStream);

		output = (char *)((MemBufFormatTarget*)myFormTarget)->getRawBuffer();

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

	return output;
}
Esempio n. 3
0
void serializer::serialize(EObject_ptr obj)
{
    m_root_obj = obj;

    m_impl = DOMImplementationRegistry::getDOMImplementation(X("Core"));

    if (m_impl)
    {
        EClass_ptr cl = obj->eClass();
        EPackage_ptr pkg = cl->getEPackage();

        ::ecorecpp::mapping::type_traits::string_t const& ns_uri = pkg->getNsURI();

        m_doc = m_impl->createDocument(
                (ns_uri.empty()) ? X("NULL") : W(ns_uri), // root element namespace URI.
                W(get_type(obj)), // root element name
                0); // document type object (DTD)

        m_root = m_doc->getDocumentElement();

        // common attributes
        // xmlns:xmi="http://www.omg.org/XMI"
        m_root->setAttribute(X("xmlns:xmi"), X("http://www.omg.org/XMI"));
        // xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        m_root->setAttribute(X("xmlns:xsi"),
                X("http://www.w3.org/2001/XMLSchema-instance"));
        // xmi:version="2.0"
        m_root->setAttribute(X("xmi:version"), X("2.0"));

        serialize_node(m_root, obj);

        // write
        // TODO: outta here

        DOMLSSerializer *theSerializer =
                ((DOMImplementationLS*) m_impl)->createLSSerializer();
        DOMLSOutput *theOutputDesc =
                ((DOMImplementationLS*) m_impl)->createLSOutput();

        DOMConfiguration* serializerConfig = theSerializer->getDomConfig();

        // TODO: set as option
        if (serializerConfig->canSetParameter(
                XMLUni::fgDOMWRTFormatPrettyPrint, true))
            serializerConfig->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint,
                    true);

        XMLFormatTarget *myFormTarget;
        myFormTarget = new LocalFileFormatTarget(X(m_file));
        theOutputDesc->setByteStream(myFormTarget);

        theSerializer->write(m_doc, theOutputDesc);

        theOutputDesc->release();
        theSerializer->release();
        delete myFormTarget;
    }
    else
        throw "Error";
}
/* Write the file. */
bool GQCFileData::Write(const std::string &fileName)
{    
	// Initialize the XML4C2 system.
	try
	{
		XMLPlatformUtils::Initialize();
	}
	catch (const XMLException&)
	{
		return false;
	}

	// Create a DOM implementation object and create the document type for it.
	DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(ToXMLCh(L"LS"));
	DOMDocument* doc = impl->createDocument();
	//doc->setStandalone(true);

	// Create the serializer.
	DOMLSSerializer *theSerializer = ((DOMImplementationLS*)impl)->createLSSerializer();
	DOMLSOutput     *theOutputDesc = ((DOMImplementationLS*)impl)->createLSOutput();
	//theSerializer->setEncoding(ToXMLCh(GENERIC_REPORT_FILE_ENCODING));
	theOutputDesc->setEncoding(ToXMLCh(GENERIC_REPORT_FILE_ENCODING));

    // Create the root element
    DOMElement *rootElement = CreateGenericReportElement(doc);

	// store the parameters
	AddNameValuePairs(ANALYSIS_PARAMETERS, analysisParameters, doc, rootElement);
	AddNameValuePairs(QC_RESULTS, qcResults, doc, rootElement);
	AddNameValuePairs(SAMPLE_SIGNATURE, sampleSignature, doc, rootElement);

    // Add an empty table (required by the DTD)
    AddBlankReportTable(doc, rootElement);

    // Store the element to the document.
    doc->appendChild(rootElement);

	// Write the file.
	bool status = false;
	XMLFormatTarget *myFormTarget = new LocalFileFormatTarget(fileName.c_str());
	theOutputDesc->setByteStream(myFormTarget);
	try
	{
		theSerializer->write(doc, theOutputDesc);
		status = true;
	}
	catch (...)
	{
		status = false;
	}

	// Clean up
	doc->release();
	theOutputDesc->release();
	theSerializer->release();
	delete myFormTarget;
	XMLPlatformUtils::Terminate();

	return status;
}
void EntityXMLFileWriter::WriteEntity(World* world, EntityID entity)
{
    using namespace xercesc;
    DOMDocument* doc = m_DOMImplementation->createDocument(nullptr, X("Entity"), nullptr);
    DOMElement* root = doc->getDocumentElement();
    root->setAttribute(X("xmlns:xsi"), X("http://www.w3.org/2001/XMLSchema-instance"));
    root->setAttribute(X("xsi:noNamespaceSchemaLocation"), X("../Types/Entity.xsd"));
    root->setAttribute(X("xmlns:c"), X("components"));
    const std::string& name = world->GetName(entity);
    if (!name.empty()) {
        root->setAttribute(X("name"), X(name));
    }
    
    DOMElement* componentsElement = doc->createElement(X("Components"));
    root->appendChild(componentsElement);
    appentEntityComponents(componentsElement, world, entity);

    DOMElement* childrenElement = doc->createElement(X("Children"));
    root->appendChild(childrenElement);
    appendEntityChildren(childrenElement, world, entity);

    try {
        LocalFileFormatTarget* target = new LocalFileFormatTarget(X(m_FilePath.string()));
        DOMLSOutput* output = static_cast<DOMImplementationLS*>(m_DOMImplementation)->createLSOutput();
        output->setByteStream(target);
        m_DOMLSSerializer->write(doc, output);
        delete target;
    } catch (const std::runtime_error& e) {
        LOG_ERROR("Failed to save \"%s\": %s", m_FilePath.c_str(), e.what());
    }

    doc->release();
}
Esempio n. 6
0
void SerializeXercesDocument(xercesc::DOMDocument& document, xercesc::XMLFormatTarget& target) {

	// call into xerces for serialization
	// cf. http://xerces.apache.org/xerces-c/program-dom-3.html#DOMLSSerializer

	static const XMLCh gLS[] = { chLatin_L, chLatin_S, chNull };
	DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(gLS);

	// construct the DOMWriter
	DOMLSSerializer *writer = ((DOMImplementationLS*)impl)->createLSSerializer();

    // optionally you can set some features on this serializer
    if (writer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTDiscardDefaultContent, true))
        writer->getDomConfig()->setParameter(XMLUni::fgDOMWRTDiscardDefaultContent, true);

    if (writer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true))
            writer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true);

	// prepare output
	DOMLSOutput *outp = ((DOMImplementationLS*)impl)->createLSOutput();
	outp->setByteStream(&target);

	// serialize the DOMNode to a UTF-16 string
	writer->write(&document, outp);

	// release the memory
	outp->release();
	writer->release();

}
Esempio n. 7
0
static void
serialise (DOMDocument const *doc, std::string const &output)
{
  XMLCh const LS[] = { chLatin_L, chLatin_S, chNull };

  DOMImplementationLS &impl = dynamic_cast<DOMImplementationLS &> (*DOMImplementationRegistry::getDOMImplementation (LS));
  DOMLSSerializer *writer = impl.createLSSerializer ();
  DOMLSOutput *desc = impl.createLSOutput ();

  LocalFileFormatTarget target (output.c_str ());
  desc->setByteStream (&target);

  writer->write (doc, desc);
}
Esempio n. 8
0
    bool serializeDOM(std::ostream& output, bool)
    {
	XMLCh tempStr[100];
	XMLString::transcode("LS", tempStr, 99);
	DOMImplementationLS *impl = dynamic_cast<DOMImplementationLS *>(DOMImplementationRegistry::getDOMImplementation(tempStr));
	DOMLSSerializer   *theSerializer = impl->createLSSerializer();
	DOMLSOutput       *theOutputDesc = impl->createLSOutput();

	bool rc = false;

	try
	{
	    MemBufFormatTarget *myFormTarget = new MemBufFormatTarget();

	    /* do the serialization through DOMLSSerializer::write(); */

	    theOutputDesc->setByteStream(myFormTarget);
	    theSerializer->write(inputFileDOM, theOutputDesc);

	    const XMLByte * data = myFormTarget->getRawBuffer();
	    XMLSize_t len = myFormTarget->getLen();

	    output.write( reinterpret_cast<const char *>(data), len );

	    delete myFormTarget;
	    rc = true;
	}
	catch (IOException& e ) {
	    cerr << StrX(e.getMessage());
	    cerr << "  Code is " << e.getCode();

	    if ( errno != 0 ) {
		cerr << ": " << strerror( errno );
	    }
	}
	catch (XMLException& e)
	{
	    cerr << "An error occurred during creation of output transcoder. Msg is:"
		 << endl
		 << StrX(e.getMessage());
	    if ( errno != 0 ) {
		cerr << ": " << strerror( errno );
	    }
	    cerr << endl;
	    rc = false;
	}
	delete theSerializer;
	return rc;
    }
Esempio n. 9
0
int ModelicaXML::serializeXMLDocumentToFile(mstring xmlFileName)
{
  // fix the file
  XMLFormatTarget *myFormatTarget = new LocalFileFormatTarget(X(xmlFileName.c_str()));
  theOutputDesc->setByteStream(myFormatTarget);

  // serialize a DOMNode to the local file "
  domSerializer->write(pModelicaXMLDoc, theOutputDesc);

  myFormatTarget->flush();

  delete myFormatTarget;

  return 0;
}
Esempio n. 10
0
 /// Dump DOM tree using XercesC handles
 void dumpTree(DOMNode* doc, ostream& os) {
   if ( doc )  {
     DOMImplementation  *imp = DOMImplementationRegistry::getDOMImplementation(Strng_t("LS"));
     MemBufFormatTarget *tar = new MemBufFormatTarget();
     DOMLSOutput        *out = imp->createLSOutput();
     DOMLSSerializer    *wrt = imp->createLSSerializer();
     out->setByteStream(tar);
     wrt->getDomConfig()->setParameter(Strng_t("format-pretty-print"), true);
     wrt->write(doc, out);
     os << tar->getRawBuffer() << endl << flush;
     out->release();
     wrt->release();
     return;
   }
   printout(ERROR,"dumpTree","+++ Cannot dump invalid document.");
 }
Esempio n. 11
0
void Normalizer::serializeNode(const DOMNode * const node) {
    XMLCh tempStr[100];
    XMLString::transcode("LS", tempStr, 99);
    DOMImplementation *impl          = DOMImplementationRegistry::getDOMImplementation(tempStr);
    DOMLSSerializer   *theSerializer = ((DOMImplementationLS*)impl)->createLSSerializer();
    DOMLSOutput       *theOutput     = ((DOMImplementationLS*)impl)->createLSOutput();
    theSerializer->getDomConfig()->setParameter(X("format-pretty-print"), true);
    XMLFormatTarget *myFormTarget;
    myFormTarget = new StdOutFormatTarget();

    theOutput->setByteStream(myFormTarget);
    theSerializer->write(node,theOutput);
    delete myFormTarget;
    theSerializer->release();
    theOutput->release();
}
Esempio n. 12
0
Triggerconf::~Triggerconf ()
{
	if( savechanges ){
	
		//
		// save file
		//
	
		static const XMLCh	gLS []	= {chLatin_L, chLatin_S, chNull};
		DOMImplementation*	impl	= DOMImplementationRegistry::getDOMImplementation(gLS);
		DOMLSSerializer*	writer	= ((DOMImplementationLS*)impl)->createLSSerializer();
	
		if (writer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true))
			writer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true);
	
		if (writer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTBOM, true))
			writer->getDomConfig()->setParameter(XMLUni::fgDOMWRTBOM, true);
	
		XMLFormatTarget* target	= new LocalFileFormatTarget (file.c_str ());
		target->flush();
	
		DOMLSOutput* output = ((DOMImplementationLS*)impl)->createLSOutput();
		output->setByteStream( target );
		writer->write( rootnode , output );
		
		writer->release();
		delete target;
		delete output;

	} // if( savechanges )

	//
	// delete all stuff here
	//

	delete parser;
	delete errhandler;

	//
	// now we can safely terminate xerces
	//

	XMLPlatformUtils::Terminate();
}
int XmlParser::commit(const char* xmlFile) {
   try {
      // Obtain DOM implementation supporting Load/Save
      DOMImplementationLS* pImplementation = dynamic_cast<DOMImplementationLS *>(DOMImplementationRegistry::getDOMImplementation(DualString("LS").asXMLString()));
      if (pImplementation == NULL){
         throw( std::runtime_error( "Unable to obtain suitable DOMImplementation!" ) ) ;
      }

      DOMLSSerializer *pSerializer = pImplementation->createLSSerializer();

      DOMLSOutput *pOutput = pImplementation->createLSOutput();
#if 1
      // Change output format to be pretty (but it isn't)
      DOMConfiguration *pConfiguration = pSerializer->getDomConfig();
      if (pConfiguration->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true))
         pConfiguration->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true);
#if 0
      // Overrides above but seems to have little effect!
      if (pConfiguration->canSetParameter(XMLUni::fgDOMWRTCanonicalForm, true))
         pConfiguration->setParameter(XMLUni::fgDOMWRTCanonicalForm, true);
#endif
#if 1
      //
      if (pConfiguration->canSetParameter(XMLUni::fgDOMWRTEntities, true))
         pConfiguration->setParameter(XMLUni::fgDOMWRTEntities, true);
#endif
#endif
      LocalFileFormatTarget *pTarget = new LocalFileFormatTarget(DualString( xmlFile ).asXMLString());
      pOutput->setByteStream(pTarget);

//      mergeDocument->normalizeDocument(); // Needed?
      pSerializer->write(mergeDocument, pOutput);

      delete pTarget;
      pOutput->release();
      pSerializer->release();

   } catch( const xercesc::XMLException& e ){
      return -1;
   }

   return 0;
}
Esempio n. 14
0
void PrintXMLdoc(const XERCES_CPP_NAMESPACE::DOMDocument* doc)
{
	DOMImplementation* impl =  DOMImplementationRegistry::getDOMImplementation(L"Core");
	DOMLSSerializer   *theSerializer = ((DOMImplementationLS*)impl)->createLSSerializer();
    DOMLSOutput       *theOutputDesc = ((DOMImplementationLS*)impl)->createLSOutput();
	
	DOMConfiguration* serializerConfig=theSerializer->getDomConfig();
	if (serializerConfig->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true))
		serializerConfig->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true);

	XMLFormatTarget *outputStream = new StdOutFormatTarget();
	theOutputDesc->setByteStream(outputStream);

	theSerializer->write(doc, theOutputDesc);

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

	delete outputStream;
}
Esempio n. 15
0
bool XMLIO::Write (DOMImplementation* impl, DOMNode* node, string filename) {

	XMLFormatTarget* mft;

	if (filename.empty())
		mft = new StdOutFormatTarget();
	else
		mft = new LocalFileFormatTarget (StrX(filename).XMLchar());

	// Xerces 2
    #ifdef XSEC_XERCES_HAS_SETIDATTRIBUTE
	DOMWriter* serializer = ((DOMImplementationLS*)impl)->createDOMWriter();

    if (serializer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, true))
		serializer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, true);
	
	serializer->writeNode(mft, *node);

	serializer->release();
    #endif 

    #ifdef XSEC_XERCES_HAS_BOOLSETIDATTRIBUTE
	DOMLSSerializer*   serializer    = ((DOMImplementationLS*) impl)->createLSSerializer();
	DOMLSOutput*       output        = ((DOMImplementationLS*)impl)->createLSOutput(); 
    DOMConfiguration*  configuration = serializer->getDomConfig(); 

	if (configuration->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true))
		configuration->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true); 

	output->setByteStream (mft);
	serializer->write(node, output);

	output->release();
	serializer->release(); 
    #endif

	return true;

}
Esempio n. 16
0
void OutputXML(xercesc::DOMDocument* pmyDOMDocument, std::string filePath) 
{ 
	//Return the first registered implementation that has the desired features. In this case, we are after a DOM implementation that has the LS feature... or Load/Save. 
	DOMImplementation *implementation = DOMImplementationRegistry::getDOMImplementation(XMLString::transcode("LS"));

	// Create a DOMLSSerializer which is used to serialize a DOM tree into an XML document. 
	DOMLSSerializer *serializer = ((DOMImplementationLS*)implementation)->createLSSerializer(); 

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

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

	// Convert the path into Xerces compatible XMLCh*. 
	XMLCh *tempFilePath = XMLString::transcode(filePath.c_str()); 

	// Specify the target for the XML output. 
	XMLFormatTarget *formatTarget = new LocalFileFormatTarget(tempFilePath); 

	// Create a new empty output destination object. 
	DOMLSOutput *output = ((DOMImplementationLS*)implementation)->createLSOutput(); 

	// Set the stream to our target. 
	output->setByteStream(formatTarget); 

	// Write the serialized output to the destination. 
	serializer->write(pmyDOMDocument, output); 

	// Cleanup. 
	serializer->release(); 
	XMLString::release(&tempFilePath); 
	delete formatTarget; 
	output->release(); 
} 
Esempio n. 17
0
//save the document to an external file
void ResultXML::save()
{
    //create the serializer for saving the document
    DOMLSSerializer *serializer = (DOMLSSerializer*)imp->createLSSerializer();

    //configure for saving it in a well presented human readable format
    if(serializer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true)){
       serializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true);
    }

    //set the output for serializing as a stream
    DOMLSOutput *output = ((DOMImplementationLS*)imp)->createLSOutput();
    output->setByteStream(ftarget);

    //use the serializer to save the document and catch any errors encountered
    try{
        serializer->write(root, output);
    }
    catch (const XMLException& e) {
        char* msg = XMLString::transcode(e.getMessage());
        cout << "Error Exception Encountered: " << endl << msg << endl;
        XMLString::release(&msg);
    }
    catch (const DOMException& e) {
        char* msg = XMLString::transcode(e.getMessage());
        cout << "Error Exception Encountered: " << endl << msg << endl;
        XMLString::release(&msg);
    }
    catch (...) {
        cout << "Error Unknown Exception" << endl;
    }

    //force the release of resources held by the serializer and output manager
    output->release();
    serializer->release();
}
Esempio n. 18
0
bool ClsDataClientConfigWriter::saveConfig(string strFileName, list<ClsDataClientConfig> lstConfigs) {
//    cout << "ClsDataClientConfigWriter::saveConfig(string strFileName, list<ClsDataClientConfig> lstConfigs)" << endl;

    if(!bXMLPlatformInitialized){
	try {
	    XMLPlatformUtils::Initialize();
	}
	catch(const XMLException& toCatch) {
	    cerr << "Error during Xerces-c Initialization.\n"
		 << "  Exception message:"
		 << toCatch.getMessage() << endl;
	    bXMLPlatformInitialized = false;
	    return false;
	}
	bXMLPlatformInitialized = true;
    }


    DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(XMLString::transcode((const char*)"Range"));

    DOMDocumentType *dtd = impl->createDocumentType(XMLString::transcode(ConfigTagLibrary::DataManagerConfiguration()),
						    XMLString::transcode("-//INI/iqr421"),
						    XMLString::transcode("iqrDataManagerConfiguration.dtd"));

    DOMDocument *ddocConfig = impl->createDocument(0, XMLString::transcode(ConfigTagLibrary::DataManagerConfiguration()), dtd);

    DOMElement *delemConfig;
    delemConfig = ddocConfig->getDocumentElement();

    list<ClsDataClientConfig>::iterator itConfigs;
    for(itConfigs=lstConfigs.begin(); itConfigs != lstConfigs.end(); itConfigs++){
	string strID = (*itConfigs).getID();
	string strType =  (*itConfigs).getType();
	pair<int,int> pPosition =  (*itConfigs).getPosition();
	pair<int,int> pGeometry =  (*itConfigs).getGeometry();

 	DOMElement *delemDataClient;
	delemDataClient = ddocConfig->createElement(XMLString::transcode(ConfigTagLibrary::DataClientTag()));
	delemDataClient->setAttribute(XMLString::transcode(ConfigTagLibrary::TypeTag()), XMLString::transcode(strType.c_str()));
	delemDataClient->setAttribute(XMLString::transcode(ConfigTagLibrary::IDTag()), XMLString::transcode(strID.c_str()));
	delemConfig->appendChild(delemDataClient);

 	DOMElement *delemPosition;
	delemPosition = ddocConfig->createElement(XMLString::transcode(ConfigTagLibrary::PositionTag()));
	delemPosition->setAttribute(XMLString::transcode(ConfigTagLibrary::PositionXTag()), 
				    XMLString::transcode(iqrUtils::int2string(pPosition.first).c_str()));
	delemPosition->setAttribute(XMLString::transcode(ConfigTagLibrary::PositionYTag()),
				    XMLString::transcode(iqrUtils::int2string(pPosition.second).c_str()));
	delemDataClient->appendChild(delemPosition);

 	DOMElement *delemGeometry;
	delemGeometry = ddocConfig->createElement(XMLString::transcode(ConfigTagLibrary::Geometry()));
	delemGeometry->setAttribute(XMLString::transcode(ConfigTagLibrary::GeometryWidthTag()), 
				    XMLString::transcode(iqrUtils::int2string(pGeometry.first).c_str()));
	delemGeometry->setAttribute(XMLString::transcode(ConfigTagLibrary::GeometryHeightTag()), 
				    XMLString::transcode(iqrUtils::int2string(pGeometry.second).c_str()));
	delemDataClient->appendChild(delemGeometry);



	list<pair<string, string> > lstParameters = (*itConfigs).getListParameters();
	list<pair<string, string> >::iterator itLstParameters;
	for(itLstParameters = lstParameters.begin(); itLstParameters != lstParameters.end(); itLstParameters++){
	    string strParamName = (*itLstParameters).first;
	    string strParamValue = (*itLstParameters).second;
	    DOMElement *delemParameter;
	    delemParameter = ddocConfig->createElement(XMLString::transcode(strParamName.c_str()));
	    delemDataClient->appendChild(delemParameter);
	    DOMText *dtxtParamValue = ddocConfig->createTextNode(XMLString::transcode(strParamValue.c_str()));
	    delemParameter->appendChild(dtxtParamValue);
	}

 	DOMElement *delemSVD;
	delemSVD = ddocConfig->createElement(XMLString::transcode(ConfigTagLibrary::StateVariableDisplayTag()));
	delemDataClient->appendChild(delemSVD);

	list<ClsStateVariableDisplayConfig>lstSVDConfigs =  (*itConfigs).getListStateVariableDisplayConfig();
	list<ClsStateVariableDisplayConfig>::iterator itSVD;
	for(itSVD = lstSVDConfigs.begin(); itSVD != lstSVDConfigs.end(); itSVD++){
	    DOMElement *delemStateVariable;
	    delemStateVariable = ddocConfig->createElement(XMLString::transcode(ConfigTagLibrary::StateVariableDisplaysTag()));
	    delemSVD->appendChild(delemStateVariable);
	    delemStateVariable->setAttribute(XMLString::transcode(ConfigTagLibrary::IDTag()), 
					     XMLString::transcode((*itSVD).getID().c_str()));
	    
/*
	    delemStateVariable->setAttribute(XMLString::transcode(ConfigTagLibrary::TypeTag()), 
					     XMLString::transcode((*itSVD).getItemType().c_str()));
*/
	
	    delemStateVariable->setAttribute(XMLString::transcode(ConfigTagLibrary::ItemIDTag()), 
					     XMLString::transcode((*itSVD).getItemID().c_str()));

	    delemStateVariable->setAttribute(XMLString::transcode(ConfigTagLibrary::SelectedIndicesTag()), 
					     XMLString::transcode((*itSVD).getSelectedIndices().c_str()));

	    list<pair<string, string> > lstParametersSVD = (*itSVD).getListParameters();
	    list<pair<string, string> >::iterator itLstParametersSVD;
	    for(itLstParametersSVD = lstParametersSVD.begin(); itLstParametersSVD != lstParametersSVD.end(); itLstParametersSVD++){
		string strParamName = (*itLstParametersSVD).first;
		string strParamValue = (*itLstParametersSVD).second;
		DOMElement *delemParameter;
		delemParameter = ddocConfig->createElement(XMLString::transcode(strParamName.c_str()));
		delemStateVariable->appendChild(delemParameter);
		DOMText *dtxtParamValue = ddocConfig->createTextNode(XMLString::transcode(strParamValue.c_str()));
		delemParameter->appendChild(dtxtParamValue);
	    }
	}
    }


#if XERCES_VERSION_MAJOR >= 3
    DOMLSSerializer* theSerializer = ((DOMImplementationLS*)impl)->createLSSerializer();
    if (theSerializer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTDiscardDefaultContent, true))
	theSerializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTDiscardDefaultContent, true);

    if (theSerializer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true))
	theSerializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true);
#else
    DOMWriter* theSerializer = ((DOMImplementationLS*)impl)->createDOMWriter();
    if (theSerializer->canSetFeature(XMLUni::fgDOMWRTDiscardDefaultContent, true))
	theSerializer->setFeature(XMLUni::fgDOMWRTDiscardDefaultContent, true);

    if (theSerializer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, true))
	theSerializer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, true);
#endif

    XMLFormatTarget *myFormTarget = new LocalFileFormatTarget(strFileName.c_str());

#if XERCES_VERSION_MAJOR >= 3
    DOMLSOutput* theOutput = ((DOMImplementationLS*)impl)->createLSOutput();
    theOutput->setByteStream(myFormTarget);
#endif


    try {
#if XERCES_VERSION_MAJOR >= 3
	theSerializer->write(delemConfig, theOutput);
#else
	theSerializer->writeNode(myFormTarget, *delemConfig);
#endif
    }
    catch (const XMLException& toCatch) {
	char* message = XMLString::transcode(toCatch.getMessage());
	cerr << "Exception message is: \n"
	     << message << "\n";
	XMLString::release(&message);
    }
    catch (const DOMException& toCatch) {
	char* message = XMLString::transcode(toCatch.msg);
	cerr << "Exception message is: \n"
	     << message << "\n";
	XMLString::release(&message);
    }
    catch (...) {
	cerr << "Unexpected Exception \n" ;
    }

//    cout << myFormTarget->getRawBuffer() << endl;

    theSerializer->release();
    delete myFormTarget;


    return true;

}
Esempio n. 19
0
Triggerconf::Triggerconf(string _filename, bool _autocreateitems, bool _mustexist, bool _savechanges)
	: file( _filename ), autocreate( _autocreateitems ), savechanges( _savechanges ) {

	rootnode	= NULL;
	goodstate	= true;
	lasterror	= "";
    
	try {

		XMLPlatformUtils::Initialize();

		//
		// if the file does not exists we create it with the root node
		// but only if the constructor parameter is fine with this
		//

		FileHandle filehandle = XMLPlatformUtils::openFile (file.c_str ());
		
		if (filehandle == NULL && _mustexist == false) {

			static const XMLCh	gLS []	= {chLatin_L, chLatin_S, chNull};
			DOMImplementation*	impl	= DOMImplementationRegistry::getDOMImplementation(gLS);
			
			XMLCh*			xroot	= XMLString::transcode( ROOT_NAME );
			DOMDocument*		doc	= impl->createDocument( 0, xroot, 0 );
			DOMElement*		elemrt	= doc->getDocumentElement();
			DOMLSSerializer* 	writer  = ((DOMImplementationLS*)impl)->createLSSerializer();
			
			XMLString::release (&xroot);

			if (writer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true))
				writer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true);

			if (writer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTBOM, true))
				writer->getDomConfig()->setParameter(XMLUni::fgDOMWRTBOM, true);

			XMLFormatTarget* target	= new LocalFileFormatTarget (file.c_str ());
			target->flush();

			DOMLSOutput* output = ((DOMImplementationLS*)impl)->createLSOutput();
        		output->setByteStream( target );
            		writer->write( elemrt, output );

			writer->release();
			doc->release();

			delete output;
			delete target;

		} else if (filehandle == NULL && _mustexist == true) {

			setError ("file " + file + " does not exist");
			return;

		} else {

			XMLPlatformUtils::closeFile (filehandle);

		}

		//
		// parse the file
		//

		parser		= new XercesDOMParser ();
		errhandler	= (ErrorHandler*) new HandlerBase ();

		parser->setErrorHandler	(errhandler);
		parser->parse		(file.c_str ());
		rootnode		= getChildOfType (parser->getDocument (), DOMNode::ELEMENT_NODE);

		if (rootnode != NULL) {
		
			char* xmlstring = XMLString::transcode (rootnode->getNodeName ());

			if (((string) ROOT_NAME).compare (xmlstring) == 0)
				resetError();
			else
				setError("invalid root item in file " + file);
		
			XMLString::release (&xmlstring);

		} else
			setError("parsing xml file " + file + " failed");	

	} catch (const XMLException& toCatch) {
		char* message = XMLString::transcode (toCatch.getMessage());
		setError ("failed parsing file " + file + ": " + message);
		XMLString::release(&message);
	}
	catch (const DOMException& toCatch) {
		char* message = XMLString::transcode (toCatch.msg);
		setError ("failed parsing file " + file + ": " + message);
		XMLString::release(&message);
	}
	catch (...) {
		setError( "failed parsing file " + file );
	}

}
Esempio n. 20
0
void  ParameterManager::SaveDocument(XMLFormatTarget* pFormatTarget) const
{
#if (XERCES_VERSION_MAJOR == 2)
    DOMPrintFilter   *myFilter = 0;

    try {
        // get a serializer, an instance of DOMWriter
        XMLCh tempStr[100];
        XMLString::transcode("LS", tempStr, 99);
        DOMImplementation *impl          = DOMImplementationRegistry::getDOMImplementation(tempStr);
        DOMWriter         *theSerializer = ((DOMImplementationLS*)impl)->createDOMWriter();

        // set user specified end of line sequence and output encoding
        theSerializer->setNewLine(gMyEOLSequence);
        theSerializer->setEncoding(gOutputEncoding);

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

        // plug in user's own error handler
        DOMErrorHandler *myErrorHandler = new DOMPrintErrorHandler();
        theSerializer->setErrorHandler(myErrorHandler);

        // set feature if the serializer supports the feature/mode
        if (theSerializer->canSetFeature(XMLUni::fgDOMWRTSplitCdataSections, gSplitCdataSections))
            theSerializer->setFeature(XMLUni::fgDOMWRTSplitCdataSections, gSplitCdataSections);

        if (theSerializer->canSetFeature(XMLUni::fgDOMWRTDiscardDefaultContent, gDiscardDefaultContent))
            theSerializer->setFeature(XMLUni::fgDOMWRTDiscardDefaultContent, gDiscardDefaultContent);

        if (theSerializer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, gFormatPrettyPrint))
            theSerializer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, gFormatPrettyPrint);

        //
        // do the serialization through DOMWriter::writeNode();
        //
        theSerializer->writeNode(pFormatTarget, *_pDocument);

        delete theSerializer;

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

        if (gUseFilter)
            delete myFilter;

    }
    catch (XMLException& e) {
        std::cerr << "An error occurred during creation of output transcoder. Msg is:"
        << std::endl
        << StrX(e.getMessage()) << std::endl;
    }
#else
    try {
        // get a serializer, an instance of DOMWriter
        XMLCh tempStr[100];
        XMLString::transcode("LS", tempStr, 99);
        DOMImplementation *impl          = DOMImplementationRegistry::getDOMImplementation(tempStr);
        DOMLSSerializer   *theSerializer = ((DOMImplementationLS*)impl)->createLSSerializer();

        // set user specified end of line sequence and output encoding
        theSerializer->setNewLine(gMyEOLSequence);
        DOMConfiguration* config = theSerializer->getDomConfig();
        config->setParameter(XStr("format-pretty-print").unicodeForm(),true);

        //
        // do the serialization through DOMWriter::writeNode();
        //
        DOMLSOutput *theOutput = ((DOMImplementationLS*)impl)->createLSOutput();
        theOutput->setEncoding(gOutputEncoding);
        theOutput->setByteStream(pFormatTarget);
        theSerializer->write(_pDocument, theOutput);

        delete theSerializer;
    }
    catch (XMLException& e) {
        std::cerr << "An error occurred during creation of output transcoder. Msg is:"
        << std::endl
        << StrX(e.getMessage()) << std::endl;
    }
#endif
}
Esempio n. 21
0
int evaluate(int argc, char ** argv) {
	
	char					* filename = NULL;
	char					* outfile = NULL;
	unsigned char			* keyStr = NULL;
	bool					doDecrypt = true;
	bool					errorsOccured = false;
	bool					doDecryptElement = false;
	bool					useInteropResolver = false;
	bool					encryptFileAsData = false;
	bool					parseXMLInput = true;
	bool					doXMLOutput = false;
	bool					isXKMSKey = false;
	XSECCryptoKey			* kek = NULL;
	XSECCryptoKey			* key = NULL;
	int						keyLen = 0;
	encryptionMethod		kekAlg = ENCRYPT_NONE;
	encryptionMethod		keyAlg = ENCRYPT_NONE;
	DOMDocument				*doc;
	unsigned char			keyBuf[24];
	XMLFormatTarget			*formatTarget ;

#if defined(_WIN32) && defined (XSEC_HAVE_WINCAPI)
	HCRYPTPROV				win32DSSCSP = 0;		// Crypto Providers
	HCRYPTPROV				win32RSACSP = 0;

	CryptAcquireContext(&win32DSSCSP, NULL, NULL, PROV_DSS, CRYPT_VERIFYCONTEXT);
	CryptAcquireContext(&win32RSACSP, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);

#endif

	if (argc < 2) {

		printUsage();
		return 2;
	}

	// Run through parameters
	int paramCount = 1;

	while (paramCount < argc - 1) {

		if (_stricmp(argv[paramCount], "--decrypt-element") == 0 || _stricmp(argv[paramCount], "-de") == 0) {
			paramCount++;
			doDecrypt = true;
			doDecryptElement = true;
			doXMLOutput = true;
			parseXMLInput = true;
		}
		else if (_stricmp(argv[paramCount], "--interop") == 0 || _stricmp(argv[paramCount], "-i") == 0) {
			// Use the interop key resolver
			useInteropResolver = true;
			paramCount++;
		}
		else if (_stricmp(argv[paramCount], "--encrypt-file") == 0 || _stricmp(argv[paramCount], "-ef") == 0) {
			// Use this file as the input
			doDecrypt = false;
			encryptFileAsData = true;
			doXMLOutput = true;
			parseXMLInput = false;
			paramCount++;
		}
		else if (_stricmp(argv[paramCount], "--encrypt-xml") == 0 || _stricmp(argv[paramCount], "-ex") == 0) {
			// Us this file as an XML input file
			doDecrypt = false;
			encryptFileAsData = false;
			doXMLOutput = true;
			parseXMLInput = true;
			paramCount++;
		}
		else if (_stricmp(argv[paramCount], "--out-file") == 0 || _stricmp(argv[paramCount], "-o") == 0) {
			if (paramCount +2 >= argc) {
				printUsage();
				return 1;
			}
			paramCount++;
			outfile = argv[paramCount];
			paramCount++;
		}
		else if (_stricmp(argv[paramCount], "--xkms") == 0 || _stricmp(argv[paramCount], "-x") == 0) {
			paramCount++;
			isXKMSKey = true;
		}

#if defined (XSEC_HAVE_WINCAPI)
		else if (_stricmp(argv[paramCount], "--wincapi") == 0 || _stricmp(argv[paramCount], "-w") == 0) {
			// Use the interop key resolver
			WinCAPICryptoProvider * cp = new WinCAPICryptoProvider();
			XSECPlatformUtils::SetCryptoProvider(cp);
			paramCount++;
		}
#endif
#if defined (XSEC_HAVE_NSS)
		else if (_stricmp(argv[paramCount], "--nss") == 0 || _stricmp(argv[paramCount], "-n") == 0) {
			// NSS Crypto Provider
			NSSCryptoProvider * cp = new NSSCryptoProvider();
			XSECPlatformUtils::SetCryptoProvider(cp);
			paramCount++;
		}
#endif
		else if (_stricmp(argv[paramCount], "--key") == 0 || _stricmp(argv[paramCount], "-k") == 0) {

			// Have a key!
			paramCount++;
			bool isKEK = false;
			XSECCryptoSymmetricKey::SymmetricKeyType loadKeyAs =
				XSECCryptoSymmetricKey::KEY_NONE;

			if (_stricmp(argv[paramCount], "kek") == 0) {
				isKEK = true;
				paramCount++;
				if (paramCount >= argc) {
					printUsage();
					return 2;
				}
			}

			if (_stricmp(argv[paramCount], "3DES") == 0 ||
				_stricmp(argv[paramCount], "AES128") == 0 ||
				_stricmp(argv[paramCount], "AES192") == 0 ||
				_stricmp(argv[paramCount], "AES256") == 0 ||
				_stricmp(argv[paramCount], "AES128-GCM") == 0 ||
				_stricmp(argv[paramCount], "AES192-GCM") == 0 ||
				_stricmp(argv[paramCount], "AES256-GCM") == 0) {
				
				if (paramCount +2 >= argc) {
					printUsage();
					return 2;
				}

				switch(argv[paramCount][4]) {
				case '\0' :
					keyLen = 24;
					loadKeyAs = XSECCryptoSymmetricKey::KEY_3DES_192;
					keyAlg = ENCRYPT_3DES_CBC;
					break;
				case '2' :
					keyLen = 16;
					loadKeyAs = XSECCryptoSymmetricKey::KEY_AES_128;
					if (isKEK) {
						kekAlg = ENCRYPT_KW_AES128;
					}
					else if (strlen(argv[paramCount]) == 6) {
						keyAlg = ENCRYPT_AES128_CBC;
					}
                    else {
                        keyAlg = ENCRYPT_AES128_GCM;
                    }
					break;
				case '9' :
					keyLen = 24;
					loadKeyAs = XSECCryptoSymmetricKey::KEY_AES_192;
					if (isKEK) {
						kekAlg = ENCRYPT_KW_AES192;
					}
					else if (strlen(argv[paramCount]) == 6) {
						keyAlg = ENCRYPT_AES192_CBC;
					}
                    else {
                        keyAlg = ENCRYPT_AES192_GCM;
                    }
					break;
				case '5' :
					keyLen = 32;
					loadKeyAs = XSECCryptoSymmetricKey::KEY_AES_256;
					if (isKEK) {
						kekAlg = ENCRYPT_KW_AES256;
					}
					else if (strlen(argv[paramCount]) == 6) {
						keyAlg = ENCRYPT_AES256_CBC;
					}
                    else {
                        keyAlg = ENCRYPT_AES256_GCM;
                    }
					break;
				}

				paramCount++;
				unsigned char keyStr[64];
				if (strlen(argv[paramCount]) > 64) {
					cerr << "Key string too long\n";
					return 2;
				}
				XSECCryptoSymmetricKey * sk = 
					XSECPlatformUtils::g_cryptoProvider->keySymmetric(loadKeyAs);

				if (isXKMSKey) {
					unsigned char kbuf[XSEC_MAX_HASH_SIZE];
					CalculateXKMSKEK((unsigned char *) argv[paramCount], (int) strlen(argv[paramCount]), kbuf, XSEC_MAX_HASH_SIZE);
					sk->setKey(kbuf, keyLen);
				}
				else {
					memset(keyStr, 0, 64);
					strcpy((char *) keyStr, argv[paramCount]);
					sk->setKey(keyStr, keyLen);
				}
				paramCount++;
				if (isKEK)
					kek = sk;
				else
					key = sk;
			}


#if defined (XSEC_HAVE_OPENSSL)

			else if (_stricmp(argv[paramCount], "RSA") == 0) {
				// RSA private key file

				if (paramCount + 3 >= argc) {

					printUsage();
					return 2;

				}

				if (!isKEK) {
					cerr << "RSA private keys may only be KEKs\n";
					return 2;
				}

				BIO * bioKey;
				if ((bioKey = BIO_new(BIO_s_file())) == NULL) {

					cerr << "Error opening private key file\n\n";
					return 1;

				}

				if (BIO_read_filename(bioKey, argv[paramCount + 1]) <= 0) {

					cerr << "Error opening private key file\n\n";
					return 1;

				}

				EVP_PKEY * pkey;
				pkey = PEM_read_bio_PrivateKey(bioKey,NULL,NULL,argv[paramCount + 2]);

				if (pkey == NULL) {

					cerr << "Error loading private key\n\n";
					return 1;

				}

				kek = new OpenSSLCryptoKeyRSA(pkey);
				kekAlg = ENCRYPT_RSA_15;
				EVP_PKEY_free(pkey);
				BIO_free(bioKey);
				paramCount += 3;
			}

			else if (_stricmp(argv[paramCount], "X509") == 0) {

				// X509 cert used to load an encrypting key

				if (paramCount + 2 >= argc) {

					printUsage();
					exit (1);

				}

				if (!isKEK) {
					cerr << "X509 private keys may only be KEKs\n";
					return 2;
				}

				// Load the encrypting key
				// For now just read a particular file

				BIO * bioX509;

				if ((bioX509 = BIO_new(BIO_s_file())) == NULL) {

					cerr << "Error opening file\n\n";
					exit (1);

				}

				if (BIO_read_filename(bioX509, argv[paramCount + 1]) <= 0) {

					cerr << "Error opening X509 Certificate " << argv[paramCount + 1] << "\n\n";
					exit (1);

				}

				X509 * x
					;
				x = PEM_read_bio_X509_AUX(bioX509,NULL,NULL,NULL);

				if (x == NULL) {

					BIO * bio_err;
					
					if ((bio_err=BIO_new(BIO_s_file())) != NULL)
						BIO_set_fp(bio_err,stderr,BIO_NOCLOSE|BIO_FP_TEXT);

					cerr << "Error loading certificate key\n\n";
					ERR_print_errors(bio_err);
					BIO_free(bio_err);
					exit (1);

				}

				// Now load the key
				EVP_PKEY *pkey;

				pkey = X509_get_pubkey(x);

				if (pkey == NULL || pkey->type != EVP_PKEY_RSA) {
					cerr << "Error extracting RSA key from certificate" << endl;
				}

				kek = new OpenSSLCryptoKeyRSA(pkey);
				kekAlg = ENCRYPT_RSA_15;

				// Clean up

				EVP_PKEY_free (pkey);
				X509_free(x);
				BIO_free(bioX509);

				paramCount += 2;
				
			} /* argv[1] = "--x509cert" */
#endif /* XSEC_HAVE_OPENSSL */
			else {
				printUsage();
				return 2;
			}
		}

		else {
			cerr << "Unknown option: " << argv[paramCount] << endl;
			printUsage();
			return 2;
		}
	}

	if (paramCount >= argc) {
		printUsage();
		return 2;
	}

	if (outfile != NULL) {
		formatTarget = new LocalFileFormatTarget(outfile);
	}
	else {
		formatTarget = new StdOutFormatTarget();
	}

	filename = argv[paramCount];

	if (parseXMLInput) {

		XercesDOMParser * parser = new XercesDOMParser;
		Janitor<XercesDOMParser> j_parser(parser);
		
		parser->setDoNamespaces(true);
		parser->setCreateEntityReferenceNodes(true);

		// Now parse out file

		xsecsize_t errorCount = 0;
		try
		{
    		parser->parse(filename);
			errorCount = parser->getErrorCount();
			if (errorCount > 0)
				errorsOccured = true;
		}

		catch (const XMLException& e)
		{
			cerr << "An error occured during parsing\n   Message: "
				 << e.getMessage() << endl;
			errorsOccured = true;
		}


		catch (const DOMException& e)
		{
		   cerr << "A DOM error occured during parsing\n   DOMException code: "
				 << e.code << endl;
			errorsOccured = true;
		}

		if (errorsOccured) {

			cout << "Errors during parse" << endl;
			return (2);

		}

		/*

			Now that we have the parsed file, get the DOM document and start looking at it

		*/
		
		doc = parser->adoptDocument();
	}

	else {
		// Create an empty document
		XMLCh tempStr[100];
		XMLString::transcode("Core", tempStr, 99);    
		DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(tempStr);
		doc = impl->createDocument(
			0,                    // root element namespace URI.
			MAKE_UNICODE_STRING("ADoc"),            // root element name
			NULL);// DOMDocumentType());  // document type object (DTD).
	}


	XSECProvider prov;
	XENCCipher * cipher = prov.newCipher(doc);

	if (kek != NULL)
		cipher->setKEK(kek);
	if (key != NULL)
		cipher->setKey(key);

	try {

		if (doDecrypt) {

			if (useInteropResolver == true) {

				// Map out base path of the file
				char path[_MAX_PATH];
				char baseURI[(_MAX_PATH * 2) + 10];
				getcwd(path, _MAX_PATH);

				strcpy(baseURI, "file:///");		

				// Ugly and nasty but quick
				if (filename[0] != '\\' && filename[0] != '/' && filename[1] != ':') {
					strcat(baseURI, path);
					strcat(baseURI, "/");
				} else if (path[1] == ':') {
					path[2] = '\0';
					strcat(baseURI, path);
				}

				strcat(baseURI, filename);

				// Find any ':' and "\" characters
				int lastSlash = 0;
				for (unsigned int i = 8; i < strlen(baseURI); ++i) {
					if (baseURI[i] == '\\') {
						lastSlash = i;
						baseURI[i] = '/';
					}
					else if (baseURI[i] == '/')
						lastSlash = i;
				}

				// The last "\\" must prefix the filename
				baseURI[lastSlash + 1] = '\0';

				XMLCh * uriT = XMLString::transcode(baseURI);

				XencInteropResolver ires(doc, &(uriT[8]));
				XSEC_RELEASE_XMLCH(uriT);
				cipher->setKeyInfoResolver(&ires);

			}
			// Find the EncryptedData node
			DOMNode * n = findXENCNode(doc, "EncryptedData");

			if (doDecryptElement) {
				while (n != NULL) {

					// decrypt
					cipher->decryptElement(static_cast<DOMElement *>(n));

					// Find the next EncryptedData node
					n = findXENCNode(doc, "EncryptedData");
				}

			}
			else {
				XSECBinTXFMInputStream * bis = cipher->decryptToBinInputStream(static_cast<DOMElement *>(n));
				Janitor<XSECBinTXFMInputStream> j_bis(bis);
	
				XMLByte buf[1024];			
				xsecsize_t read = bis->readBytes(buf, 1023);
				while (read > 0) {
					formatTarget->writeChars(buf, read, NULL);
					read = bis->readBytes(buf, 1023);
				}
			}
		}
		else {

			XENCEncryptedData *xenc = NULL;
			// Encrypting
			if (kek != NULL && key == NULL) {
				XSECPlatformUtils::g_cryptoProvider->getRandom(keyBuf, 24);
				XSECCryptoSymmetricKey * k = 
					XSECPlatformUtils::g_cryptoProvider->keySymmetric(XSECCryptoSymmetricKey::KEY_3DES_192);
				k->setKey(keyBuf, 24);
				cipher->setKey(k);
				keyAlg = ENCRYPT_3DES_CBC;
				keyStr = keyBuf;
				keyLen = 24;
			}

			if (encryptFileAsData) {

				// Create a BinInputStream
#if defined(XSEC_XERCES_REQUIRES_MEMMGR)
				BinFileInputStream * is = new BinFileInputStream(filename, XMLPlatformUtils::fgMemoryManager);
#else
				BinFileInputStream * is = new BinFileInputStream(filename);
#endif
				xenc = cipher->encryptBinInputStream(is, keyAlg);

				// Replace the document element
				DOMElement * elt = doc->getDocumentElement();
				doc->replaceChild(xenc->getElement(), elt);
				elt->release();
			}
			else {
				// Document encryption
				cipher->encryptElement(doc->getDocumentElement(), keyAlg);
			}

			// Do we encrypt a created key?
			if (kek != NULL && xenc != NULL) {
				XENCEncryptedKey *xkey = cipher->encryptKey(keyStr, keyLen, kekAlg);
				// Add to the EncryptedData
				xenc->appendEncryptedKey(xkey);
			}
		}

		if (doXMLOutput) {
			// Output the result

			XMLCh core[] = {
				XERCES_CPP_NAMESPACE_QUALIFIER chLatin_C,
				XERCES_CPP_NAMESPACE_QUALIFIER chLatin_o,
				XERCES_CPP_NAMESPACE_QUALIFIER chLatin_r,
				XERCES_CPP_NAMESPACE_QUALIFIER chLatin_e,
				XERCES_CPP_NAMESPACE_QUALIFIER chNull
			};

            DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(core);

#if defined (XSEC_XERCES_DOMLSSERIALIZER)
            // DOM L3 version as per Xerces 3.0 API
            DOMLSSerializer   *theSerializer = ((DOMImplementationLS*)impl)->createLSSerializer();
            Janitor<DOMLSSerializer> j_theSerializer(theSerializer);
            
            // Get the config so we can set up pretty printing
            DOMConfiguration *dc = theSerializer->getDomConfig();
            dc->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, false);

            // Now create an output object to format to UTF-8
            DOMLSOutput *theOutput = ((DOMImplementationLS*)impl)->createLSOutput();
            Janitor<DOMLSOutput> j_theOutput(theOutput);

            theOutput->setEncoding(MAKE_UNICODE_STRING("UTF-8"));
            theOutput->setByteStream(formatTarget);

            theSerializer->write(doc, theOutput);

#else			
			DOMWriter         *theSerializer = ((DOMImplementationLS*)impl)->createDOMWriter();
			Janitor<DOMWriter> j_theSerializer(theSerializer);

			theSerializer->setEncoding(MAKE_UNICODE_STRING("UTF-8"));
			if (theSerializer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, false))
				theSerializer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, false);

			theSerializer->writeNode(formatTarget, *doc);
#endif	
			cout << endl;

		}
	}

	catch (XSECException &e) {
		char * msg = XMLString::transcode(e.getMsg());
		cerr << "An error occured during encryption/decryption operation\n   Message: "
		<< msg << endl;
		XSEC_RELEASE_XMLCH(msg);
		errorsOccured = true;
		if (formatTarget != NULL)
			delete formatTarget;
		doc->release();
		return 2;
	}
	catch (XSECCryptoException &e) {
		cerr << "An error occured during encryption/decryption operation\n   Message: "
		<< e.getMsg() << endl;
		errorsOccured = true;
		if (formatTarget != NULL)
			delete formatTarget;
		doc->release();

#if defined (XSEC_HAVE_OPENSSL)
		ERR_load_crypto_strings();
		BIO * bio_err;
		if ((bio_err=BIO_new(BIO_s_file())) != NULL)
			BIO_set_fp(bio_err,stderr,BIO_NOCLOSE|BIO_FP_TEXT);

		ERR_print_errors(bio_err);
#endif
		return 2;
	}
	
	if (formatTarget != NULL)
		delete formatTarget;

	doc->release();
	return 0;
}
Esempio n. 22
0
int main(int argC, char*argV[])
{
        // Initialize the XML4C2 system.
        try
        {
                XMLPlatformUtils::Initialize();/*init*/
        }
        catch(const XMLException& toCatch)
        {
                char *pMsg = XMLString::transcode(toCatch.getMessage());
                XERCES_STD_QUALIFIER cerr << "Error during Xerces-c Initialization.\n"
                        << "  Exception message:"
                        << pMsg;
                XMLString::release(&pMsg);
                return 1;
        }

        DOMImplementation* impl =  DOMImplementationRegistry::getDOMImplementation(X("LS"));/**Implementation*/
        DOMLSSerializer*   theSerializer = ((DOMImplementationLS*)impl)->createLSSerializer();/** createLSSerializer*/
        DOMLSOutput       *theOutputDesc = ((DOMImplementationLS*)impl)->createLSOutput();/**createLSOutput*/
        MemBufFormatTarget* target = new MemBufFormatTarget();
        theOutputDesc->setByteStream(target);

        if (impl != NULL)
        {
                try
                {
                        DOMDocument* doc = impl->createDocument(
                                        0,                    // root element namespace URI. /**可用资源标识*/
                                        X("corporation"),     // root element name /**a large companny*/
                                        0);                   // document type object (DTD). /**mem mannager mode object*/
                        doc->setXmlStandalone(true);

                        DOMElement*  rootElem = doc->getDocumentElement();
                        rootElem->setAttribute(X("xmlns"), X("com:cmcc:corporation"));
                        rootElem->setAttribute(X("xmlns:xsi"), X("http://www.w3.org/2001/XMLSchema-instance"));
                        rootElem->setAttribute(X("xsi:schemaLocation"), X("com:cmcc:corporation corporation.xsd"));

                        //add node
                        DOMElement*  prodElem = doc->createElement(X("eid"));
                        rootElem->appendChild(prodElem);

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

                        XercesDOMParser* parser = new XercesDOMParser();

                        //add basic child
                        MemBufInputSource* basic_mem = new MemBufInputSource(
                                        (const XMLByte* )basic_string.c_str(),
                                        strlen(basic_string.c_str()),
                                        "basic",
                                        false);
                        parser->parse( *basic_mem );
                        DOMDocument* xmlDoc = parser->getDocument();
                        DOMElement* basic_root = xmlDoc->getDocumentElement();
                        DOMNode* newnode = doc->importNode((DOMNode* )basic_root, true);
                        rootElem->appendChild(newnode); 
                        delete basic_mem;

                        //add the rules child
                        MemBufInputSource* rules_mem = new MemBufInputSource(
                                        (const XMLByte* )rules_string.c_str(),
                                        rules_string.length(),
                                        "rules",
                                        false);
                        parser->parse( *rules_mem );
                        xmlDoc = parser->getDocument();
                        DOMElement* rules_root = xmlDoc->getDocumentElement();
                        newnode = doc->importNode((DOMNode* )rules_root, true);
                        rootElem->appendChild(newnode);
                        delete rules_mem;

                        //add the accounts child
                        MemBufInputSource* accounts_mem = new MemBufInputSource(
                                        (const XMLByte* )accounts_string.c_str(),
                                        accounts_string.length(),
                                        "accounts",
                                        false);
                        parser->parse( *accounts_mem );
                        xmlDoc = parser->getDocument();
                        DOMElement* accounts_root = xmlDoc->getDocumentElement();
                        newnode = doc->importNode((DOMNode* )accounts_root, true);
                        rootElem->appendChild(newnode);
                        delete accounts_mem;

                        theSerializer->write(doc, theOutputDesc);
                        std::cout<< target->getRawBuffer()<< std::endl;

                        delete target;
                        delete parser;
                        theOutputDesc->release();
                        theSerializer->release();
                        doc->release();
                }
                catch(const OutOfMemoryException&)
                {
                        XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl;
                }
                catch (const DOMException& e)
                {
                        XERCES_STD_QUALIFIER cerr << "DOMException code is:  " << e.code << XERCES_STD_QUALIFIER endl;
                }
                catch (...)
                {
                        XERCES_STD_QUALIFIER cerr << "An error occurred creating the document" << XERCES_STD_QUALIFIER endl;
                }
        }
        else
        {
                XERCES_STD_QUALIFIER cerr << "Requested implementation is not supported" << XERCES_STD_QUALIFIER endl;
        }

        XMLPlatformUtils::Terminate();
        return 0;
}
bool ServerConfigXMLReader::readServerConfig(const std::string & path) {

    this->serverConfig = ServerConfig();

    try {
        XMLPlatformUtils::Initialize();
    }  catch (const XMLException& toCatch) {

        char * message = XMLString::transcode(toCatch.getMessage());
        cout << "Error during initialization! :\n" << message << "\n";
        XMLString::release(&message);

        return false;
    }

    XercesDOMParser * parser = new XercesDOMParser();

    //parser->setValidationScheme(XercesDOMParser::Val_Auto);
    parser->setDoNamespaces(true);
    parser->setDoXInclude(true);
    //parser->setValidationScheme(XercesDOMParser::Val_Always);
  //  parser->setDoSchema(true);
  //  parser->setValidationSchemaFullChecking(true);

    XMLParseErrorReporter * xmlParseErrorReporter = new XMLParseErrorReporter();;
    parser->setErrorHandler(xmlParseErrorReporter);
    try {
        parser->parse(path.c_str());
    }  catch (const XMLException & toCatch) {
        char * message = XMLString::transcode(toCatch.getMessage());
        cout << "Exception message is: \n" << message << "\n";
        XMLString::release(&message);
        return false;
    }
    catch (const DOMException& toCatch) {
        char * message = XMLString::transcode(toCatch.msg);
        cout << "Exception message is: \n" << message << "\n";
        XMLString::release(&message);
        return false;
    }
    catch (...) {
        cout << "Unexpected Exception \n" ;
        return false;
    }

    DOMDocument * domDocument = parser->getDocument();
    removeBaseAttr(domDocument);

    // 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(0);

    XMLDOMErrorReporter * xmlDOMErrorReporter = new XMLDOMErrorReporter();
    DOMConfiguration * serializerConfig = theSerializer->getDomConfig();
    serializerConfig->setParameter(XMLUni::fgDOMErrorHandler, xmlDOMErrorReporter);

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

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

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

    if (serializerConfig->canSetParameter(XMLUni::fgDOMWRTBOM, false))
        serializerConfig->setParameter(XMLUni::fgDOMWRTBOM, false);
/*
    XMLFormatTarget * myFormTarget = new StdOutFormatTarget();
    theOutputDesc->setByteStream(myFormTarget);

    theSerializer->write(domDocument, theOutputDesc);
*/
    MemBufFormatTarget * myFormTarget = new MemBufFormatTarget();
    theOutputDesc->setByteStream(myFormTarget);

    theSerializer->write(domDocument, theOutputDesc);
/*
    XMLFormatTarget * myFormTarget2 = new StdOutFormatTarget();
    theOutputDesc->setByteStream(myFormTarget2);
    theSerializer->write(domDocument, theOutputDesc);
*/

    MemBufInputSource * memInput = new MemBufInputSource(myFormTarget->getRawBuffer(), myFormTarget->getLen(), path.c_str());
    XercesDOMParser * parser2 = new XercesDOMParser();
    
    parser2->setDoNamespaces(true);
    parser2->setDoXInclude(true);
  //  parser2->setValidationScheme(XercesDOMParser::Val_Always);
   // parser2->setDoSchema(true);
   // parser2->setValidationSchemaFullChecking(true);

    parser2->setErrorHandler(xmlParseErrorReporter);
    try {
        parser2->parse(*memInput);
    }  catch (const XMLException & toCatch) {
        char * message = XMLString::transcode(toCatch.getMessage());
        cout << "Exception message is: \n" << message << "\n";
        XMLString::release(&message);
        return false;
    }
    catch (const DOMException& toCatch) {
        char * message = XMLString::transcode(toCatch.msg);
        cout << "Exception message is: \n" << message << "\n";
        XMLString::release(&message);
        return false;
    }
    catch (...) {
        cout << "Unexpected Exception \n" ;
        return false;
    }

    DOMDocument * domDocument2 = parser2->getDocument();
    XMLNodeFilter * xmlNodeFilter = new XMLNodeFilter();
    DOMTreeWalker * domTreeWalker = domDocument->createTreeWalker(domDocument2, DOMNodeFilter::SHOW_ALL, xmlNodeFilter, true);

    this->serverConfig = extractServerConfig(domDocument2, domTreeWalker);

    domTreeWalker->release();
    delete xmlNodeFilter;
 

    delete xmlDOMErrorReporter;
    delete xmlParseErrorReporter;
    delete parser;

    XMLPlatformUtils::Terminate();

    return true;
}
Esempio n. 24
0
void CTibiaItem::saveItemLists()
{
	if (!xmlInitialised)
	{
		XMLPlatformUtils::Initialize();
		xmlInitialised = 1;
	}

	char installPath[1024]       = { '\0' };
	unsigned long installPathLen = 1023;
	HKEY hkey                    = NULL;
	if (!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\\Tibia Auto\\", 0, KEY_READ, &hkey))
	{
		RegQueryValueEx(hkey, TEXT("Install_Dir"), NULL, NULL, (unsigned char *)installPath, &installPathLen);
		RegCloseKey(hkey);
	}
	if (!strlen(installPath))
	{
		AfxMessageBox("ERROR! Unable to read TA install directory! Please reinstall!");
		PostQuitMessage(-1);
		return;
	}
	XercesDOMParser *parser = new XercesDOMParser();
	try
	{
		//int itemNr;
		char pathBuf[2048];
		sprintf(pathBuf, "%s\\data\\tibiaauto-items.xml", installPath);

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

		xercesc::DOMDocument *doc = impl->createDocument(0, XMLString::transcode("item-definitions"), 0);
		doc->createComment((const unsigned short *)"<!-- Tibia Items for Tibia -->");

		DOMElement *root = doc->getDocumentElement();

		//ITEMS
		DOMNode *itemsNode = doc->createElement(XMLString::transcode("items"));
		root->appendChild(itemsNode);
		//recursively save data structure to XML
		saveItemsBranch(itemsNode, itemTree, doc);

		//FOOD
		DOMNode *foodNode = doc->createElement(XMLString::transcode("foods"));
		root->appendChild(foodNode);
		{
			int size = foodList.GetCount();
			for (int i = 0; i < size; i++)
			{
				char buf[512];
				DOMElement*  itemElem = doc->createElement(XMLString::transcode("item"));
				foodNode->appendChild(itemElem);
				char* name = foodList.GetTextAtIndex(i);
				int id     = foodList.GetValueAtIndex(i);
				int time   = foodList.GetExtraInfoAtIndex(i);

				sprintf(buf, "0x%x", id);
				itemElem->setAttribute(XMLString::transcode("id"), XMLString::transcode(buf));

				itemElem->setAttribute(XMLString::transcode("name"), XMLString::transcode(name));

				sprintf(buf, "%d", time);
				itemElem->setAttribute(XMLString::transcode("time"), XMLString::transcode(buf));
			}
		}
		//CONSTS
		/* never any need to save constants anymore
		   DOMNode *constsNode = doc->createElement(XMLString::transcode("consts"));
		   root->appendChild(constsNode);
		   int size = constCodeList.GetCount();
		   for (int i=0;i<size;i++){
		   char buf[512];
		   DOMElement*  itemElem = doc->createElement(XMLString::transcode("const"));
		   constsNode->appendChild(itemElem);
		   char* code=constCodeList.GetTextAtIndex(i);
		   int value=constCodeList.GetValueAtIndex(i);

		   sprintf(buf, "0x%x", value);
		   itemElem->setAttribute(XMLString::transcode("value"), XMLString::transcode(buf));

		   itemElem->setAttribute(XMLString::transcode("code"), XMLString::transcode(code));
		   }
		 */

		XMLCh tempStr[100];
		XMLString::transcode("LS", tempStr, 99);

		impl = DOMImplementationRegistry::getDOMImplementation(tempStr);
		DOMLSSerializer* theSerializer = ((DOMImplementationLS*)impl)->createLSSerializer();
		DOMConfiguration* dc           = theSerializer->getDomConfig();
		if (dc->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true))
			dc->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true);
		XMLFormatTarget *outFile = new LocalFileFormatTarget(pathBuf);
		DOMLSOutput *lsOut       = ((DOMImplementationLS*)impl)->createLSOutput();
		lsOut->setByteStream(outFile);
		theSerializer->write(doc, lsOut);
		theSerializer->release();
		lsOut->release();
		delete outFile;
	}
	catch (...)
	{
		AfxMessageBox("Unable to save item definitions!");
	}

	delete parser;
}
Esempio n. 25
0
int main(void){
	
	Metadata metadata;
	
	metadata.addMetadata("key1", "val1");
	
	vector<string> values;
	
	values.push_back("val1");
	values.push_back("val2");
	values.push_back("val3");
	
	metadata.addMetadata("key2", values);
	
	cout << "Checking the value of key1: Value: " << metadata.getMetadata("key1") << endl;
	cout << "Checking the value of key2: Value: " << metadata.getMetadata("key2") << endl;

	vector<string> key2Vals = metadata.getAllMetadata("key2");
	cout << "Checking all values for key2: Values: " << endl;
		
	for(int i=0; i < key2Vals.size(); i++){
		 cout << "Value: " << key2Vals[i] << endl;
	}
		
    if(metadata.getAllMetadata("key3") == cas::Metadata::EMPTY_VEC){
    	   cout << "No multiple values for key3!" << endl;
    }
    
    if(metadata.getMetadata("key3") == cas::Metadata::EMPTY_STR){
    	cout << "No singular value for key3!" << endl;
    }
	
	metadata.addMetadata("key3", "val3");
	
	if(metadata.getMetadata("key3") != cas::Metadata::EMPTY_STR){
		cout << "New value for key3: " << metadata.getMetadata("key3") << endl;
	}
	
	if(!metadata.containsKey("blah")){
		cout << "Metadata doesn't contain key blah: correct!" << endl;
	}
	
	if(metadata.containsKey("key3")){
		cout << "Metadata contains key key3: correct!" << endl;
	}
	
	if(metadata.isMultiValued("key2")){
		cout << "Key2 is correctly multi-valued: correct!" << endl;
	}
	
	if(!metadata.isMultiValued("key3")){
		cout << "Key3 is correctly NOT multi-valued: correct!" << endl;
	}
	
	metadata.addMetadata("key4", "val99");
	
	if(metadata.getMetadata("key4") != cas::Metadata::EMPTY_STR){
		cout << "Metadata exists for key4, now deleting key4 and retesting" << endl;
		
		metadata.removeMetadata("key4");
		
		if(metadata.getMetadata("key4") == cas::Metadata::EMPTY_STR){
			cout << "Metadata successfully removed for key4! " << endl;
		}
	}
	
	vector<string> key5vals;
	key5vals.push_back("key5val1");
	key5vals.push_back("key5val2");
	
	metadata.addMetadata("key5", key5vals);
	
	vector<string> key5replvals;
	key5replvals.push_back("key5_replaced_val1");
	key5replvals.push_back("key5_replaced_val2");
	
	metadata.replaceMetadata("key5", key5replvals);

	for(int i=0; i < metadata.getAllMetadata("key5").size(); i++){
		 cout << "Value: " << metadata.getAllMetadata("key5")[i] << endl;
	}	
	
	metadata.addMetadata("key6", "key6val1");
	
	if(metadata.getMetadata("key6") == "key6val1"){
		cout << "key6: value = key6val1, as appropriate" << endl;
	}
	
	metadata.replaceMetadata("key6", "key6_replaced_val1");
	
	if(metadata.getMetadata("key6") == "key6_replaced_val1"){
		cout << "key6: value = key6_replaced_val1, as appropriate" << endl;
	}
	
	
	cout << "XML is: " << endl;
    DOMDocument* doc = metadata.toXML();
	XMLCh tempStr[100];
 

	XMLString::transcode("LS", tempStr, 99);
	DOMImplementation *impl          = DOMImplementationRegistry::getDOMImplementation(tempStr);
    DOMLSSerializer* theSerializer = ((DOMImplementationLS*)impl)->createLSSerializer();


	if (theSerializer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true))
	  theSerializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true);

	XMLFormatTarget *myFormTarget;
        myFormTarget = new StdOutFormatTarget();
    DOMLSOutput* theOutput = ((DOMImplementationLS*)impl)->createLSOutput();
    theOutput->setByteStream(myFormTarget);

	theSerializer->write((DOMNode*)doc, theOutput);
	
	cout << "Now attempting to parse cas xml document: data/sample.met.xml" << endl;
	
	XercesDOMParser parser_;
	
	parser_.setValidationScheme( xercesc::XercesDOMParser::Val_Never ) ;
	parser_.setDoNamespaces( false ) ;
	parser_.setDoSchema( false ) ;
	parser_.setLoadExternalDTD( false ) ;
	
	 parser_.parse("./data/sample.met.xml") ;

    // there's no need to free this pointer -- it's
    // owned by the parent parser object
    DOMDocument* xmlDoc = parser_.getDocument() ;
    
    cout << "Metadata XML file parsed: constructing CAS Metadata object from it " << endl;
    
    Metadata newMetadata(xmlDoc);
    
    cout << "Outputting XML from CAS Metadata " << endl;
        
    DOMDocument *newDoc = newMetadata.toXML();
    theSerializer->write((DOMNode*)doc, theOutput);
    
	return 1;
		
}
Esempio n. 26
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. 27
0
void CTibiaItem::saveItemLists()
{
	if (!xmlInitialised)
	{
		XMLPlatformUtils::Initialize();
		xmlInitialised = 1;
	}
	XercesDOMParser *parser = new XercesDOMParser();
	try
	{
		//int itemNr;
		char pathBuf[2048];
		sprintf(pathBuf, "%s\\data\\tibiaauto-items.xml", CInstallPath::getInstallPath().c_str());

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

		xercesc::DOMDocument *doc = impl->createDocument(0, XMLString::transcode("item-definitions"), 0);
		doc->createComment((const unsigned short *)"<!-- Tibia Items for Tibia -->");

		DOMElement *root = doc->getDocumentElement();

		//ITEMS
		DOMNode *itemsNode = doc->createElement(XMLString::transcode("items"));
		root->appendChild(itemsNode);
		//recursively save data structure to XML
		saveItemsBranch(itemsNode, itemTree, doc);

		//FOOD
		DOMNode *foodNode = doc->createElement(XMLString::transcode("foods"));
		root->appendChild(foodNode);
		{
			int size = foodList.GetCount();
			for (int i = 0; i < size; i++)
			{
				char buf[512];
				DOMElement*  itemElem = doc->createElement(XMLString::transcode("item"));
				foodNode->appendChild(itemElem);
				char* name = foodList.GetTextAtIndex(i);
				int id     = foodList.GetValueAtIndex(i);
				int time   = foodList.GetExtraInfoAtIndex(i);

				sprintf(buf, "0x%x", id);
				itemElem->setAttribute(XMLString::transcode("id"), XMLString::transcode(buf));

				itemElem->setAttribute(XMLString::transcode("name"), XMLString::transcode(name));

				sprintf(buf, "%d", time);
				itemElem->setAttribute(XMLString::transcode("time"), XMLString::transcode(buf));
			}
		}
		//CONSTS
		/* never any need to save constants anymore
		   DOMNode *constsNode = doc->createElement(XMLString::transcode("consts"));
		   root->appendChild(constsNode);
		   int size = constCodeList.GetCount();
		   for (int i=0;i<size;i++){
		   char buf[512];
		   DOMElement*  itemElem = doc->createElement(XMLString::transcode("const"));
		   constsNode->appendChild(itemElem);
		   char* code=constCodeList.GetTextAtIndex(i);
		   int value=constCodeList.GetValueAtIndex(i);

		   sprintf(buf, "0x%x", value);
		   itemElem->setAttribute(XMLString::transcode("value"), XMLString::transcode(buf));

		   itemElem->setAttribute(XMLString::transcode("code"), XMLString::transcode(code));
		   }
		 */

		XMLCh tempStr[100];
		XMLString::transcode("LS", tempStr, 99);

		impl = DOMImplementationRegistry::getDOMImplementation(tempStr);
		DOMLSSerializer* theSerializer = ((DOMImplementationLS*)impl)->createLSSerializer();
		DOMConfiguration* dc           = theSerializer->getDomConfig();
		if (dc->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true))
			dc->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true);
		XMLFormatTarget *outFile = new LocalFileFormatTarget(pathBuf);
		DOMLSOutput *lsOut       = ((DOMImplementationLS*)impl)->createLSOutput();
		lsOut->setByteStream(outFile);
		theSerializer->write(doc, lsOut);
		theSerializer->release();
		lsOut->release();
		delete outFile;
	}
	catch (...)
	{
		AfxMessageBox("Unable to save item definitions!");
	}

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


}
Esempio n. 29
0
// ---------------------------------------------------------------------------
//
//   main
//
// ---------------------------------------------------------------------------
int main(int argC, char* argV[])
{
	char						*testFileName;
	char						*outputFileName;

    for (int argInd = 1; argInd < argC; argInd++)
	{
        if (!strcmp(argV[argInd], "-?") || !strcmp(argV[argInd], "-h"))
        {
			/* print help and exit */
            usage();
            return 2;
        }
    }

	if (argC < 3){
		usage();
		return 2;
	}

	testFileName = argV[argC-2];
	outputFileName = argV[argC-1];

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

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

	//============================================================================
	// Instantiate the DOM parser to use for the source documents
	//============================================================================
    static const XMLCh gLS[] = { chLatin_L, chLatin_S, chNull };
    DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(gLS);
    DOMLSParser       *parser = ((DOMImplementationLS*)impl)->createLSParser(DOMImplementationLS::MODE_SYNCHRONOUS, 0);
    DOMConfiguration  *config = parser->getDomConfig();

    config->setParameter(XMLUni::fgDOMNamespaces, true);
    config->setParameter(XMLUni::fgXercesSchema, true);
    config->setParameter(XMLUni::fgXercesSchemaFullChecking, true);

	if(config->canSetParameter(XMLUni::fgXercesDoXInclude, true)){
		config->setParameter(XMLUni::fgXercesDoXInclude, true);
	}
    
    // enable datatype normalization - default is off
    //config->setParameter(XMLUni::fgDOMDatatypeNormalization, true);

    // And create our error handler and install it
    XIncludeErrorHandler errorHandler;
    config->setParameter(XMLUni::fgDOMErrorHandler, &errorHandler);

    XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument *doc = 0;

    try
    {
        // load up the test source document
		XERCES_STD_QUALIFIER cerr << "Parse " << testFileName << " in progress ...";
        parser->resetDocumentPool();
		doc = parser->parseURI(testFileName);
		XERCES_STD_QUALIFIER cerr << " finished." << XERCES_STD_QUALIFIER endl;
    }
    catch (const XMLException& toCatch)
    {
        XERCES_STD_QUALIFIER cerr << "\nError during parsing: '" << testFileName << "'\n"
                << "Exception message is:  \n"
                << StrX(toCatch.getMessage()) << "\n" << XERCES_STD_QUALIFIER endl;
    }
    catch (const DOMException& toCatch)
    {
        const unsigned int maxChars = 2047;
        XMLCh errText[maxChars + 1];

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

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

    }
    catch (...)
    {
        XERCES_STD_QUALIFIER cerr << "\nUnexpected exception during parsing: '" << testFileName << "'\n";
    }

    if (!errorHandler.getSawErrors() && doc) {
	    DOMLSSerializer	*writer = ((DOMImplementationLS*)impl)->createLSSerializer();
	    DOMLSOutput     *theOutputDesc = ((DOMImplementationLS*)impl)->createLSOutput();

		try {
			// write out the results
			XERCES_STD_QUALIFIER cerr << "Writing result to: " << outputFileName << XERCES_STD_QUALIFIER endl;

			XMLFormatTarget *myFormTarget = new LocalFileFormatTarget(outputFileName);
			theOutputDesc->setByteStream(myFormTarget);
			writer->write(doc, theOutputDesc);
            delete myFormTarget;
		}
		catch (const XMLException& toCatch)
		{
		    XERCES_STD_QUALIFIER cerr << "\nXMLException during writing: '" << testFileName << "'\n"
				<< "Exception message is:  \n"
				<< StrX(toCatch.getMessage()) << "\n" << XERCES_STD_QUALIFIER endl;
		}
		catch (const DOMException& toCatch)
		{
			const unsigned int maxChars = 2047;
			XMLCh errText[maxChars + 1];

			XERCES_STD_QUALIFIER cerr << "\nDOM Error during writing: '" << testFileName << "'\n"
				<< "DOMException code is:  " << toCatch.code << XERCES_STD_QUALIFIER endl;

			if (DOMImplementation::loadDOMExceptionMsg(toCatch.code, errText, maxChars))
				XERCES_STD_QUALIFIER cerr << "Message is: " << StrX(errText) << XERCES_STD_QUALIFIER endl;
		}
		catch (...)
		{
			XERCES_STD_QUALIFIER cerr << "\nUnexpected exception during writing: '" << testFileName << "'\n";
		}
        writer->release();
        theOutputDesc->release();
    }

    //
    //  Delete the parser itself.  Must be done prior to calling Terminate, below.
    //
    parser->release();
	// And call the termination method
    XMLPlatformUtils::Terminate();

    return 0;
}