Ejemplo n.º 1
0
void musicxml::serialize(std::ostream &os, musicxml::score_timewise const &s) {
  xml::auto_initializer xerces_platform { true, false };

  DOMImplementation *dom {
    DOMImplementationRegistry::getDOMImplementation(ls_id)
  };

  xml::string score_type("score-timewise");
  xml::string dtd_public("-//Recordare//DTD MusicXML " + s.version() +
                         " Timewise//EN");
  xml::string dtd_system("http://www.musicxml.org/dtds/timewise.dtd");

  std::unique_ptr<DOMDocument> doc {
    dom->createDocument (
      nullptr, score_type.c_str(),
      dom->createDocumentType(score_type.c_str(), dtd_public.c_str(),
                              dtd_system.c_str())
    )
  };

  musicxml::score_timewise_(*doc, s);

  xsd::cxx::tree::error_handler<char> eh;
  xml::dom::bits::error_handler_proxy<char> ehp { eh };

  xml::dom::ostream_format_target oft { os };

  std::unique_ptr<DOMLSSerializer> writer { dom->createLSSerializer() };

  DOMConfiguration *conf { writer->getDomConfig() };

  conf->setParameter(XMLUni::fgDOMErrorHandler, &ehp);
  conf->setParameter(XMLUni::fgDOMWRTDiscardDefaultContent, true);
  conf->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true);

  std::unique_ptr<DOMLSOutput> output { dom->createLSOutput() };
  output->setEncoding(xml::string("UTF-8").c_str());
  output->setByteStream(&oft);

  writer->write(doc.get(), output.get());

  eh.throw_if_failed<xsd::cxx::tree::serialization<char>>();
}
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;
}
Ejemplo n.º 3
0
string XmlUtil::convertDomToString() {
    if(!doc)
        throw "DOM is empty"; // FIXME add an exception type for this

    DOMImplementationLS* implLS = dynamic_cast<DOMImplementationLS*>(impl);
    DOMLSSerializer*	theSerializer = implLS->createLSSerializer();
    DOMConfiguration* 	serializerConfig = theSerializer->getDomConfig();

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

    string stringTemp = XMLString::transcode (theSerializer->writeToString(doc));
    theSerializer->release();

    /*string stringDump;
    for (string::iterator it = stringTemp.begin() ; it < stringTemp.end(); ++it) {
    	if (!isspace (*it))
    		stringDump += *it;
    }
    return stringDump;*/
    return stringTemp;
}
Ejemplo n.º 4
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;

}
Ejemplo n.º 5
0
DOMLSParser* ObtainParser(DOMErrorHandler& errHandler) {

	const XMLCh ls_id [] = {chLatin_L, chLatin_S, chNull};

	// Get an implementation of the Load-Store (LS) interface.
	//
	DOMImplementation* impl(DOMImplementationRegistry::getDOMImplementation (ls_id));

	DOMLSParser *parser (impl->createLSParser (DOMImplementationLS::MODE_SYNCHRONOUS, 0));

	DOMConfiguration* conf (parser->getDomConfig ());

	// Discard comment nodes in the document.
	//
	conf->setParameter (XMLUni::fgDOMComments, false);

	// Enable datatype normalization.
	//
	conf->setParameter (XMLUni::fgDOMDatatypeNormalization, true);

	// Do not create EntityReference nodes in the DOM tree. No
	// EntityReference nodes will be created, only the nodes
	// corresponding to their fully expanded substitution text
	// will be created.
	//
	conf->setParameter (XMLUni::fgDOMEntities, false);

	// Perform namespace processing.
	//
	conf->setParameter (XMLUni::fgDOMNamespaces, true);

	// Do not include ignorable whitespace in the DOM tree.
	//
	conf->setParameter (XMLUni::fgDOMElementContentWhitespace, false);

	// Enable/Disable validation.
	//
	conf->setParameter (XMLUni::fgDOMValidate, false);
	conf->setParameter (XMLUni::fgXercesSchema, false);
	conf->setParameter (XMLUni::fgXercesSchemaFullChecking, false);

	// Xerces-C++ 3.1.0 is the first version with working multi import
	// support.
	//
#if _XERCES_VERSION >= 30100
	conf->setParameter (XMLUni::fgXercesHandleMultipleImports, true);
#endif

	// We will release the DOM document ourselves.
	//
	conf->setParameter (XMLUni::fgXercesUserAdoptsDOMDocument, true);

	// Set error handler.
	//
	conf->setParameter (XMLUni::fgDOMErrorHandler, &errHandler);

	return parser;
}
Ejemplo n.º 6
0
SecureDOMParser::SecureDOMParser(const string &schema_location)
{
    DOMConfiguration *conf = getDomConfig();
    // Discard comment nodes in the document.
    conf->setParameter(XMLUni::fgDOMComments, false);
    // Enable datatype normalization.
    conf->setParameter(XMLUni::fgDOMDatatypeNormalization, true);
    // Do not create EntityReference nodes in the DOM tree. No
    // EntityReference nodes will be created, only the nodes
    // corresponding to their fully expanded substitution text
    // will be created.
    conf->setParameter(XMLUni::fgDOMEntities, false);
    conf->setParameter(XMLUni::fgDOMNamespaces, true);
    conf->setParameter(XMLUni::fgDOMElementContentWhitespace, false);
    // Enable validation.
    conf->setParameter(XMLUni::fgDOMValidate, !schema_location.empty());
    conf->setParameter(XMLUni::fgXercesSchema, !schema_location.empty());
    conf->setParameter(XMLUni::fgXercesSchemaFullChecking, false);
    if(!schema_location.empty())
    {
        xml::string sl(schema_location);
        conf->setParameter(XMLUni::fgXercesSchemaExternalSchemaLocation, sl.c_str());
    }
    // Xerces-C++ 3.1.0 is the first version with working multi import
    // support.
    conf->setParameter(XMLUni::fgXercesHandleMultipleImports, true);
    // We will release the DOM document ourselves.
    conf->setParameter(XMLUni::fgXercesUserAdoptsDOMDocument, true);
}
Ejemplo n.º 7
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;
}
Ejemplo n.º 8
0
// ---------------------------------------------------------------------------
//
//   main
//
// ---------------------------------------------------------------------------
int main(int argC, char* argV[])
{

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

    const char*                xmlFile = 0;
    AbstractDOMParser::ValSchemes valScheme = AbstractDOMParser::Val_Auto;
    bool                       doNamespaces       = false;
    bool                       doSchema           = false;
    bool                       schemaFullChecking = false;
    bool                       disallowDoctype    = false;
    bool                       doList = false;
    bool                       errorOccurred = false;
    bool                       recognizeNEL = false;
    bool                       printOutEncounteredEles = false;
    char                       localeStr[64];
    memset(localeStr, 0, sizeof localeStr);

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

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

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

             recognizeNEL = true;
        }
         else if (!strcmp(argV[argInd], "-p")
              ||  !strcmp(argV[argInd], "-P"))
        {
            printOutEncounteredEles = true;
        }
         else if (!strncmp(argV[argInd], "-locale=", 8))
        {
             // Get out the end of line
             strcpy(localeStr, &(argV[argInd][8]));
        }
         else
        {
            XERCES_STD_QUALIFIER cerr << "Unknown option '" << argV[argInd]
                 << "', ignoring it\n" << XERCES_STD_QUALIFIER endl;
        }
    }

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

    // Initialize the XML4C system
    try
    {
        if (strlen(localeStr))
        {
            XMLPlatformUtils::Initialize(localeStr);
        }
        else
        {
            XMLPlatformUtils::Initialize();
        }

        if (recognizeNEL)
        {
            XMLPlatformUtils::recognizeNEL(recognizeNEL);
        }
    }

    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.
    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, doNamespaces);
    config->setParameter(XMLUni::fgXercesSchema, doSchema);
    config->setParameter(XMLUni::fgXercesHandleMultipleImports, true);
    config->setParameter(XMLUni::fgXercesSchemaFullChecking, schemaFullChecking);
    config->setParameter(XMLUni::fgDOMDisallowDoctype, disallowDoctype);

    if (valScheme == AbstractDOMParser::Val_Auto)
    {
        config->setParameter(XMLUni::fgDOMValidateIfSchema, true);
    }
    else if (valScheme == AbstractDOMParser::Val_Never)
    {
        config->setParameter(XMLUni::fgDOMValidate, false);
    }
    else if (valScheme == AbstractDOMParser::Val_Always)
    {
        config->setParameter(XMLUni::fgDOMValidate, true);
    }

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

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

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

    bool more = true;
    XERCES_STD_QUALIFIER ifstream fin;

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

    if (fin.fail()) {
        XERCES_STD_QUALIFIER cerr <<"Cannot open the list file: " << argV[argInd] << XERCES_STD_QUALIFIER endl;
        return 2;
    }

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

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

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

        XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument *doc = 0;

        try
        {
            // reset document pool
            parser->resetDocumentPool();

            const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis();
            doc = parser->parseURI(xmlFile);
            const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis();
            duration = endMillis - startMillis;
        }

        catch (const XMLException& toCatch)
        {
            XERCES_STD_QUALIFIER cerr << "\nError during parsing: '" << xmlFile << "'\n"
                 << "Exception message is:  \n"
                 << StrX(toCatch.getMessage()) << "\n" << XERCES_STD_QUALIFIER endl;
            errorOccurred = true;
            continue;
        }
        catch (const DOMException& toCatch)
        {
            const unsigned int maxChars = 2047;
            XMLCh errText[maxChars + 1];

            XERCES_STD_QUALIFIER cerr << "\nDOM Error during parsing: '" << xmlFile << "'\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;

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

        //
        //  Extract the DOM tree, get the list of all the elements and report the
        //  length as the count of elements.
        //
        if (errorHandler.getSawErrors())
        {
            XERCES_STD_QUALIFIER cout << "\nErrors occurred, no output available\n" << XERCES_STD_QUALIFIER endl;
            errorOccurred = true;
        }
         else
        {
            unsigned int elementCount = 0;
            if (doc) {
                elementCount = countChildElements((DOMNode*)doc->getDocumentElement(), printOutEncounteredEles);
                // test getElementsByTagName and getLength
                XMLCh xa[] = {chAsterisk, chNull};
                if (elementCount != doc->getElementsByTagName(xa)->getLength()) {
                    XERCES_STD_QUALIFIER cout << "\nErrors occurred, element count is wrong\n" << XERCES_STD_QUALIFIER endl;
                    errorOccurred = true;
                }
            }

            // Print out the stats that we collected and time taken.
            XERCES_STD_QUALIFIER cout << xmlFile << ": " << duration << " ms ("
                 << elementCount << " elems)." << XERCES_STD_QUALIFIER endl;
        }
    }

    //
    //  Delete the parser itself.  Must be done prior to calling Terminate, below.
    //
    parser->release();

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

    if (doList)
        fin.close();

    if (errorOccurred)
        return 4;
    else
        return 0;
}
Ejemplo n.º 9
0
int main(int /*argc*/, char ** /*argv*/) {

    Normalizer *normalizer = new Normalizer();

    DOMDocument *doc = normalizer->createDocument();
    bool *tmpTrue = new bool(true);
    bool *tmpFalse = new bool(false);

    DOMElement* docFirstElement = doc->createElementNS(X("http://www.test.com"),X("docEle"));
    doc->appendChild(docFirstElement);
    DOMElement* docFirstElementChild = doc->createElementNS(X("http://www.test2.com"),X("docEleChild"));
    docFirstElement->appendChild(docFirstElementChild);

    //create default ns
    doc->normalizeDocument();
    normalizer->serializeNode(doc);
    XERCES_STD_QUALIFIER cout << "\n\n";

    //add in binding
    docFirstElement->setPrefix(X("po"));
    doc->normalizeDocument();
    normalizer->serializeNode(doc);
    XERCES_STD_QUALIFIER cout << "\n\n";

    //use default
    DOMElement* docFirstElementChildChild = doc->createElementNS(X("http://www.test2.com"),X("docEleChildChild"));
    docFirstElementChild->appendChild(docFirstElementChildChild);
    doc->normalizeDocument();
    normalizer->serializeNode(doc);
    XERCES_STD_QUALIFIER cout << "\n\n";

    // this block is needed to destroy the XMLBuffer 
    {
        //use a binding
        XMLBuffer buf;
        buf.set(XMLUni::fgXMLNSString);
        buf.append(chColon);
        buf.append(X("po2"));
        docFirstElementChild->removeAttributeNS(XMLUni::fgXMLNSURIName, XMLUni::fgXMLNSString);
        docFirstElement->removeAttributeNS(XMLUni::fgXMLNSURIName, XMLUni::fgXMLNSString);
        docFirstElement->setAttributeNS(XMLUni::fgXMLNSURIName, buf.getRawBuffer(), X("http://www.test2.com"));
        docFirstElementChild->setPrefix(X("po2"));
        doc->normalizeDocument();
        normalizer->serializeNode(doc);
        XERCES_STD_QUALIFIER cout << "\n\n";
    }

    //some siblngs to ensure the scope stacks are working
    docFirstElementChildChild = doc->createElementNS(X("http://www.test3.com"),X("docEleChildChild2"));
    docFirstElementChild->appendChild(docFirstElementChildChild);
    docFirstElementChildChild = doc->createElementNS(X("http://www.test4.com"),X("po4:docEleChildChild3"));
    docFirstElementChild->appendChild(docFirstElementChildChild);
    docFirstElementChildChild = doc->createElementNS(X("http://www.test4.com"),X("po4:docEleChildChild4"));
    docFirstElementChild->appendChild(docFirstElementChildChild);
    doc->normalizeDocument();
    normalizer->serializeNode(doc);
    XERCES_STD_QUALIFIER cout << "\n\n";

    //conflicting prefix
    docFirstElementChildChild->setAttributeNS(XMLUni::fgXMLNSURIName, X("po4"), X("conflict"));
    doc->normalizeDocument();
    normalizer->serializeNode(doc);
    XERCES_STD_QUALIFIER cout << "\n\n";
    
    //conflicting default
    docFirstElementChildChild = doc->createElementNS(X("http://www.test4.com"),X("docEleChildChild5"));
    docFirstElementChild->appendChild(docFirstElementChildChild);
    docFirstElementChildChild->setAttributeNS(XMLUni::fgXMLNSURIName, XMLUni::fgXMLNSString, X("conflict"));
    doc->normalizeDocument();
    normalizer->serializeNode(doc);
    XERCES_STD_QUALIFIER cout << "\n\n";

    //set the xmlns to ""
    DOMElement *noNamespaceEle = doc->createElementNS(X(""),X("noNamespace"));
    docFirstElementChildChild->appendChild(noNamespaceEle);
    doc->normalizeDocument();
    normalizer->serializeNode(doc);
    XERCES_STD_QUALIFIER cout << "\n\n";


    //now lets do a bit off attribute testing on the doc ele
    docFirstElement->setAttributeNS(X("http://testattr.com"), X("attr1"), X("value"));
    docFirstElement->setAttributeNS(X("http://testattr.com"), X("attr2"), X("value"));
    docFirstElement->setAttributeNS(X("http://testattr2.com"), X("attr3"), X("value"));
    docFirstElement->setAttributeNS(X("http://www.test.com"), X("attr4"), X("value"));
    docFirstElement->setAttributeNS(X("http://testattr2.com"), X("po:attr5"), X("value"));
    docFirstElement->setAttributeNS(X("http://testattr2.com"), X("poFake:attr6"), X("value"));
    docFirstElement->setAttributeNS(X("http://testattr3.com"), X("po3:attr7"), X("value"));
    doc->normalizeDocument();
    normalizer->serializeNode(doc);
    XERCES_STD_QUALIFIER cout << "\n\n";

    //and now on one of its children
    docFirstElementChildChild->setAttributeNS(X("http://testattr.com"), X("attr1"), X("value"));
    docFirstElementChildChild->setAttributeNS(X("http://testattr.com"), X("attr2"), X("value"));
    docFirstElementChildChild->setAttributeNS(X("http://testattr2.com"), X("attr3"), X("value"));
    docFirstElementChildChild->setAttributeNS(X("http://www.test.com"), X("attr4"), X("value"));
    docFirstElementChildChild->setAttributeNS(X("http://testattr2.com"), X("po:attr5"), X("value"));
    docFirstElementChildChild->setAttributeNS(X("http://testattr2.com"), X("poFake:attr6"), X("value"));
    docFirstElementChildChild->setAttributeNS(X("http://testattr3.com"), X("po3:attr7"), X("value"));
    docFirstElementChildChild->setAttributeNS(X("http://testattr4.com"), X("po4:attr8"), X("value"));
    

    //test for a clash with our NSx attrs
    docFirstElementChildChild->setAttributeNS(X("http://testclash.com"), X("NS1:attr9"), X("value"));
    docFirstElementChildChild->setAttributeNS(XMLUni::fgXMLNSURIName, X("xmlns:NS1"), X("http://testclash.com"));

    //clash with standard prefix
    docFirstElementChildChild->setAttributeNS(X("http://testattr5.com"), X("po:attr10"), X("value"));

    doc->normalizeDocument();
    normalizer->serializeNode(doc);
    XERCES_STD_QUALIFIER cout << "\n\n";


    //2 prefix with the same uri
    docFirstElementChildChild = doc->createElementNS(X("http://www.uri1.com"),X("docEleChildChild6"));
    docFirstElementChild->appendChild(docFirstElementChildChild);
    docFirstElementChildChild->setAttributeNS(XMLUni::fgXMLNSURIName, X("xmlns:uri1"), X("http://www.uri1.com"));
    docFirstElementChildChild->setAttributeNS(XMLUni::fgXMLNSURIName, X("xmlns:uri1b"), X("http://www.uri1.com"));
    docFirstElementChildChild->setAttributeNS(X("http://www.uri1.com"), X("uri1:attr1"), X("value"));
    docFirstElementChildChild->setAttributeNS(X("http://www.uri1.com"), X("uri1b:attr2"), X("value"));
    doc->normalizeDocument();
    normalizer->serializeNode(doc);
    XERCES_STD_QUALIFIER cout << "\n\n";

    //check to see we use the nearest binding and for more inheritence
    DOMElement *docFirstElementChildChildChild = doc->createElementNS(X("http://www.uri1.com"),X("docEleChildChildChild"));
    docFirstElementChildChild->appendChild(docFirstElementChildChildChild);
    docFirstElementChildChild->setAttributeNS(XMLUni::fgXMLNSURIName, X("xmlns:nearerThanPo"), X("http://www.test.com"));
    docFirstElementChildChildChild->setAttributeNS(X("http://testattr.com"), X("attr2"), X("value"));
    docFirstElementChildChildChild->setAttributeNS(X("http://www.test.com"), X("attr1"), X("value"));
    doc->normalizeDocument();
    normalizer->serializeNode(doc);
    XERCES_STD_QUALIFIER cout << "\n\n";


    //NS1.1 stuff

    //test creating default prefix when NS1 has been set to ""
    noNamespaceEle->setAttributeNS(XMLUni::fgXMLNSURIName, X("xmlns:NS1"), X(""));
    DOMElement *noNamespaceChild = doc->createElementNS(X("http://testclash.com"),X("testing1.1Stuff"));
    noNamespaceEle->appendChild(noNamespaceChild);
    doc->normalizeDocument();
    normalizer->serializeNode(doc);

    noNamespaceChild = doc->createElementNS(X("http://testclash.com"),X("NS1:testing1.1Stuff"));
    noNamespaceEle->appendChild(noNamespaceChild);
    
    noNamespaceChild->setAttributeNS(X("http://www.someRandomUri.com"), X("attr"), X("value"));
    doc->normalizeDocument();
    normalizer->serializeNode(doc);


    //check error conditions
    XERCES_STD_QUALIFIER cout << "error conditions" << XERCES_STD_QUALIFIER endl;

    DOMConfiguration *conf = doc->getDOMConfig();
    conf->setParameter(XMLUni::fgDOMErrorHandler, normalizer);
    conf->setParameter(XMLUni::fgDOMNamespaces, true);

    DOMElement *level1Node = doc->createElement(X("level1Node"));
    docFirstElement->appendChild(level1Node);
    doc->normalizeDocument();

    docFirstElement->removeChild(level1Node);
    docFirstElement->setAttribute(X("level1Attr"), X("level1"));
    doc->normalizeDocument();
    docFirstElement->removeAttribute(X("level1Attr"));

    //cant check this as Xerces does not let us do it
    //    noNamespaceChild->setAttributeNS(X("http://www.someRandomUri.com"), X("xmlns"), X("value"));
    //    doc->normalizeDocument();



    //lets do a sanity test on a comment
    DOMComment *comment = doc->createComment(X("some comment"));
    docFirstElement->appendChild(comment);
    doc->normalizeDocument();
    normalizer->serializeNode(doc);

    conf->setParameter(XMLUni::fgDOMComments, false);
    docFirstElement->appendChild(comment);
    doc->normalizeDocument();
    normalizer->serializeNode(doc);


    //and on a CDATA
    DOMCDATASection *cData = doc->createCDATASection(X("some cdata"));
    docFirstElement->appendChild(cData);
    doc->normalizeDocument();
    normalizer->serializeNode(doc);

    conf->setParameter(XMLUni::fgDOMCDATASections, false);
    docFirstElement->appendChild(cData);
    doc->normalizeDocument();
    normalizer->serializeNode(doc);

    delete normalizer;
    delete tmpTrue;
    delete tmpFalse;

    return 0;
}
Ejemplo n.º 10
0
DOMDocument *CouchRunHttpServer::parsePrologue( std::string S_PrologueXMLFilename ){
  bool recognizeNEL = false;
  char localeStr[64];
  memset(localeStr, 0, sizeof localeStr);

  // Initialize the XML4C system
  try {
    if (strlen(localeStr)) {
	  XMLPlatformUtils::Initialize(localeStr);
    }
    else{
	  XMLPlatformUtils::Initialize();
    }
    
    if (recognizeNEL){
      XMLPlatformUtils::recognizeNEL(recognizeNEL);
    }
  }
  catch (const XMLException& toCatch){
    XERCES_STD_QUALIFIER cerr << "Error during initialization! :\n"
			      << StrX(toCatch.getMessage()) << XERCES_STD_QUALIFIER endl;
    return NULL;
  }

  // Instantiate the DOM parser.
  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();
  // enable datatype normalization - default is off
  config->setParameter(XMLUni::fgDOMDatatypeNormalization, true);

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

  //
  //  Get the starting time and kick off the parse of the indicated
  //  file. Catch any exceptions that might propogate out of it.
  //
  unsigned long duration;
  const char *xmlFile = 0;
  bool more = true;
  XERCES_STD_QUALIFIER ifstream fin;

  // Later possibly a list of prologue files rather than a single one
  while (more){
    xmlFile = S_PrologueXMLFilename.c_str();
    more = false;
  }
      
  // Parse XML prologue file
  // Reset error count first
  errorHandler.resetErrors();

  bool errorOccurred = false;

  try{
    // reset document pool
    parser->resetDocumentPool();
      
    const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis();
    XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument *doc = parser->parseURI(xmlFile);
    const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis();
    duration = endMillis - startMillis;
    // Print out the stats that we collected and time taken.
    XERCES_STD_QUALIFIER cout << "Parsed " 
			      << xmlFile << ": " << duration << " ms."
			      << XERCES_STD_QUALIFIER endl;
    return doc;
  }
  catch (const XMLException& toCatch){
    XERCES_STD_QUALIFIER cerr << "\nError during parsing: '" << xmlFile << "'\n"
			      << "Exception message is:  \n"
			      << StrX(toCatch.getMessage()) << "\n" 
                              << XERCES_STD_QUALIFIER endl;
    errorOccurred = true;
    //    continue;
  }
  catch (const DOMException& toCatch){
    const unsigned int maxChars = 2047;
    XMLCh errText[maxChars + 1];
      
    XERCES_STD_QUALIFIER cerr << "\nDOM Error during parsing: '" 
			      << xmlFile << "'\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;
      
    errorOccurred = true;
    //    continue;
  }
  catch (...){
    XERCES_STD_QUALIFIER cerr << "\nUnexpected exception during parsing: '" << xmlFile << "'\n";
    errorOccurred = true;
    //    continue;
  }

  return NULL;
}
Ejemplo n.º 11
0
static std::unique_ptr<DOMDocument>
dom_document(std::istream &is, const std::string &id, bool validate) {
  MemoryManager *mm(XMLPlatformUtils::fgMemoryManager);
  std::unique_ptr<XMLGrammarPool> gp(new XMLGrammarPoolImpl(mm));
  grammar_input_stream gis(musicxml_schema, sizeof(musicxml_schema));
  gp->deserializeGrammars(&gis);
  gp->lockPool();

  DOMImplementation *dom {
    DOMImplementationRegistry::getDOMImplementation(ls_id)
  };

  std::unique_ptr<DOMLSParser> parser {
    dom->createLSParser(DOMImplementationLS::MODE_SYNCHRONOUS, nullptr, mm, gp.get())
  };

  DOMConfiguration *conf { parser->getDomConfig() };

  embedded_resource_resolver resolver;
  conf->setParameter(XMLUni::fgDOMResourceResolver, &resolver);
  // Discard comment nodes in the document.
  conf->setParameter(XMLUni::fgDOMComments, false);

  // Enable datatype normalization.
  conf->setParameter(XMLUni::fgDOMDatatypeNormalization, true);

  // Do not create EntityReference nodes in the DOM tree. No
  // EntityReference nodes will be created, only the nodes
  // corresponding to their fully expanded substitution text
  // will be created.
  conf->setParameter(XMLUni::fgDOMEntities, false);

  // Perform namespace processing.
  conf->setParameter(XMLUni::fgDOMNamespaces, true);

  // Do not include ignorable whitespace in the DOM tree.
  conf->setParameter(XMLUni::fgDOMElementContentWhitespace, false);

  // Enable/Disable validation.
  conf->setParameter(XMLUni::fgDOMValidate, validate);
  conf->setParameter(XMLUni::fgXercesSchema, validate);
  conf->setParameter(XMLUni::fgXercesSchemaFullChecking, false);

  // Use the loaded grammar during parsing and disable loading schemas via other
  // means (e.g., schemaLocation).
  conf->setParameter(XMLUni::fgXercesUseCachedGrammarInParse, true);
  conf->setParameter(XMLUni::fgXercesLoadSchema, false);

// Xerces-C++ 3.1.0 is the first version with working multi import
// support.
#if _XERCES_VERSION >= 30100
  conf->setParameter(XMLUni::fgXercesHandleMultipleImports, true);
#endif

  // We will release the DOM document ourselves.
  conf->setParameter(XMLUni::fgXercesUserAdoptsDOMDocument, true);

  // Set error handler.
  tree::error_handler<char> eh;
  xml::dom::bits::error_handler_proxy<char> ehp { eh };
  conf->setParameter(XMLUni::fgDOMErrorHandler, &ehp);

  // Prepare input stream.
  xml::sax::std_input_source isrc { is, id };
  Wrapper4InputSource wrap { &isrc, false };

  std::unique_ptr<DOMDocument> doc { parser->parse(&wrap) };

  eh.throw_if_failed<tree::parsing<char>>();

  return doc;
}
Ejemplo n.º 12
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
}
Ejemplo n.º 13
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;
}
Ejemplo n.º 14
0
void XmlUtil::convertStringToDom(const string& stringName, const string& schemaFile, const bool validate) {
    ((DOMImplementationLS*)impl)->createLSSerializer();
    parser = ((DOMImplementationLS*)impl)->createLSParser (DOMImplementationLS::MODE_SYNCHRONOUS, 0);

    // remove the old DOM
    if (doc) {
        doc->release();
        doc = NULL;
    }

    if (parser) {
        DOMConfiguration* conf (parser->getDomConfig ());

        conf->setParameter (XMLUni::fgDOMComments, false);
        conf->setParameter (XMLUni::fgDOMDatatypeNormalization, true);
        conf->setParameter (XMLUni::fgDOMEntities, false);
        conf->setParameter (XMLUni::fgDOMNamespaces, true);
        conf->setParameter (XMLUni::fgDOMElementContentWhitespace, false);

        // Enable validation.
        conf->setParameter (XMLUni::fgDOMValidate, validate);
        conf->setParameter (XMLUni::fgXercesSchema, validate);
        conf->setParameter (XMLUni::fgXercesSchemaFullChecking, false);

        // Use the loaded grammar during parsing.
        conf->setParameter (XMLUni::fgXercesUseCachedGrammarInParse, true);

        // Don't load schemas from any other source
        conf->setParameter (XMLUni::fgXercesLoadSchema, false);

        // We will release the DOM document ourselves.
        conf->setParameter (XMLUni::fgXercesUserAdoptsDOMDocument, true);

        error_handler eh;
        parser->getDomConfig ()->setParameter (XMLUni::fgDOMErrorHandler, &eh);

        if (validate) {
            if (!parser->loadGrammar (schemaFile.c_str(), Grammar::SchemaGrammarType, true)) {
                LOG(log::ERROR) << "ERROR: Unable to load schema.xsd";
                return;
            }
            if (eh.failed ()) {
                return;
            }
        }
        if (doc) doc->release();
        XMLCh* sName = XMLString::transcode(stringName.c_str());
        DOMLSInput* input = ((DOMImplementationLS*)impl)->createLSInput();
        input->setStringData(sName);

        doc = parser->parse(input);

        if (eh.failed ()) {
            if (doc) doc->release();
            doc = NULL;
            LOG(log::ERROR) << "problem during parsing of XML file" << endl;
            return;
        }
        XMLString::release(&sName);
    }

}
Ejemplo n.º 15
0
XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument* XmlReaderSAR::parse(string fn, string endTag)
{
   if (mpDoc != NULL)
   {
      mpDoc->release();
      mpDoc = NULL;
   }
   DOMConfiguration* pConfig = mpParser->getDomConfig();
   const void* pOldError = pConfig->getParameter(XMLUni::fgDOMErrorHandler);
   try
   {
      string uri = XmlBase::PathToURL(fn);

      if (!mXmlSchemaLocation.empty())
      {
         string esl("https://comet.balldayton.com/standards/namespaces/2005/v1/comet.xsd ");
         for (unsigned int version = XmlBase::VERSION; version > 0; version--)
         {
            stringstream fname;
            fname << mXmlSchemaLocation << "opticks-" << version << ".xsd";
            FILE* pTmp = fopen(fname.str().c_str(), "r");
            if (pTmp != NULL)
            {
               esl += XmlBase::PathToURL(fname.str()) + " ";
               fclose(pTmp);
               break;
            }
         }
         pConfig->setParameter(XMLUni::fgXercesSchemaExternalSchemaLocation, const_cast<XMLCh*>(X(esl.c_str())));
         pConfig->setParameter(XMLUni::fgXercesSchema, true);
         pConfig->setParameter(XMLUni::fgXercesSchemaFullChecking, true);
         pConfig->setParameter(XMLUni::fgXercesValidationErrorAsFatal, true);
      }

      if (!endTag.empty())
      {
         logSimpleMessage("Partial parse is not available...performing complete parse.");
      }
      XmlReaderErrorHandler errors(this);
      pConfig->setParameter(XMLUni::fgDOMErrorHandler, &errors);
      mpDoc = mpParser->parseURI(uri.c_str());
   }
   catch (const XMLException& exc)
   {
      logException(&exc);
   }
   catch (const DOMException& exc)
   {
      logException(dynamic_cast<const XMLException*>(&exc));
   }
   catch (const XmlBase::XmlException& exc)
   {
      logSimpleMessage(exc.str());
   }
   catch (...)
   {
      logSimpleMessage("XmlReader unexpected parse error");
   }

   pConfig->setParameter(XMLUni::fgDOMErrorHandler, pOldError);
   return mpDoc;
}
Ejemplo n.º 16
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;
}
Ejemplo n.º 17
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;
}
Ejemplo n.º 18
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;
}