Exemplo n.º 1
0
int main()
{
   XMLPlatformUtils::Initialize();

   // Populate vector of items
   vector<Item> items;
   items.push_back(Item(Product("Toaster", 29.95), 3));
   items.push_back(Item(Product("Hair dryer", 24.95), 1));

   // Build the DOM document
   DOMImplementation* implementation
      = DOMImplementation::getImplementation();
   DOMDocument* doc = implementation->createDocument();
   doc->setStandalone(true);

   DOMElement* root = create_item_list(doc, items);
   doc->appendChild(root);

   // Print the DOM document

   DOMWriter* writer = implementation->createDOMWriter();
   writer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, true);
   XMLFormatTarget* out = new StdOutFormatTarget();
   writer->writeNode(out, *doc);

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

   return 0;
}
Exemplo n.º 2
0
//DR-2-023-245
void write_cdtrn_to_file(char *file_name) {
	DOMWriter *pWriter;
	XMLFormatTarget *pTarget;
	pWriter = ((DOMImplementationLS*) cdtTrnimpl)->createDOMWriter();
	pWriter->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, true);
	pTarget = new LocalFileFormatTarget(file_name);
	pWriter->writeNode(pTarget, *cdtTrndoc);

	delete pWriter;
	delete pTarget;
}
Exemplo n.º 3
0
void Normalizer::serializeNode(const DOMNode * const node) {
    XMLCh tempStr[100];
    XMLString::transcode("LS", tempStr, 99);
    DOMImplementation *impl          = DOMImplementationRegistry::getDOMImplementation(tempStr);
    DOMWriter         *theSerializer = ((DOMImplementationLS*)impl)->createDOMWriter();
    theSerializer->setFeature(X("format-pretty-print"), true);
    XMLFormatTarget *myFormTarget;
    myFormTarget = new StdOutFormatTarget();

    theSerializer->writeNode(myFormTarget, *node);
}
Exemplo n.º 4
0
    //-----------------------------------------------------------------------
    void XercesWriter::writeXMLFile(const XMLNode* root, const Ogre::String& filename)
    {
        XERCES_CPP_NAMESPACE_USE;

        DOMImplementation* impl = DOMImplementationRegistry::getDOMImplementation(L"Core");
        DOMDocumentType* docType = NULL;
        DOMDocument* doc = impl->createDocument(NULL, transcode(root->getName()).c_str(), docType);

        populateDOMElement(root, doc->getDocumentElement());

        LocalFileFormatTarget destination(filename.c_str());
        DOMWriter* writer = impl->createDOMWriter();
        writer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, true);
        writer->writeNode(&destination, *doc);
        writer->release();
        doc->release();
    }
Exemplo n.º 5
0
void PMLDocument::writeFile( string filename ){


    DOMWriter *writer = m_impl->createDOMWriter();

    m_doc->setEncoding( XS("UTF-8") );
    m_doc->setActualEncoding( XS("UTF-8") );
    writer->setEncoding( XS("UTF-8"));
    writer->setErrorHandler( m_err );
// use indentation in written file


    writer->setFeature( XS("format-pretty-print"), true);
    XMLFormatTarget *outFile = new LocalFileFormatTarget(filename.c_str());

    writer->writeNode( outFile, *m_doc  );
    outFile->flush();

    writer->release();

    delete outFile;
}
Exemplo n.º 6
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;

}
Exemplo n.º 7
0
/**
 * This method converts the entries in the map (created from the command-line arguments)
 * into XML which will then be fed as input into the parameter handling code (i.e. ParameterSet class).
 */
string parameterTask::buildParameterSetXML(const string & xmlFileNamePrefix) 
{
	string retVal;
	try {
		XMLPlatformUtils::Initialize();
	}
	catch (const XMLException& toCatch)
	{
		ACS_LOG(LM_ERROR, "parameterTask::buildParameterSetXML", 
			(LM_ERROR, "Error - XMLException - info: %s\n", StrX(toCatch.getMessage()).localForm()))
	}
	DOMImplementation* impl =  DOMImplementationRegistry::getDOMImplementation(StrX("XML 2.0").unicodeForm());

	if (impl != NULL)
	{
		try
		{
			// create a new DOMDocument which we will populate with 
			// entries from the command-line parameters, in order to 
			// make an xml version of the parameter set for use internally
			string qualifiedName(PARAMETERSET_NAMESPACE_PREFIX);
			qualifiedName.append(":").append(PARAMETERSET_STRING);

			DOMDocument* doc = impl->createDocument(
				StrX(PSET_NAMESPACE_URI).unicodeForm(), // root element namespace URI.
				StrX(qualifiedName.c_str()).unicodeForm(), // root element name
				0); // document type object (DTD).

			doc->setStandalone(true);

			// set our internal auto_ptr to point to the new document
			this->domDocument.reset(doc);

			string schemaHint(PSET_NAMESPACE_URI);
			schemaHint.append(" ").append(PARAMETERSET_SCHEMA_NAME);
			DOMElement* rootElem = doc->getDocumentElement();
			rootElem->setAttribute(StrX("xmlns:xsi").unicodeForm(), StrX("http://www.w3.org/2001/XMLSchema-instance").unicodeForm());
			rootElem->setAttribute(StrX("xsi:schemaLocation").unicodeForm(), 
				StrX(schemaHint.c_str()).unicodeForm());

			DOMElement*  psetdefElem = doc->createElement(StrX(PSETDEF_STRING).unicodeForm());
			rootElem->appendChild(psetdefElem);

			string xmlFileName = xmlFileNamePrefix + ".xml";
			DOMText* psetdefValTextNode = doc->createTextNode(StrX(xmlFileName.c_str()).unicodeForm());
			psetdefElem->appendChild(psetdefValTextNode);
			DOMElement*  nameElem = doc->createElement(StrX(NAME_STRING).unicodeForm());
			rootElem->appendChild(nameElem);
			DOMText* nameValTextNode = doc->createTextNode(StrX("command-line values").unicodeForm());
			nameElem->appendChild(nameValTextNode);

			map<string, vector<string> >::iterator position;
			// for each parameter in the parameterMap
			for(position = parameterMap.begin(); position != parameterMap.end(); ++position) {
				// determine the type by looking it up in our parameter set definition, i.e. psetdef 
				// (which we have obtained by parsing the task's psetdef xml file containing the task's metadata)
				// and add an element of the proper type to the XML document being constructed, with name equal to the
				// key portion of the current map entry, value equal to the value portion of the current map entry.
				ParamSetDef::paramTypesEnum paramType = paramSetDef->getParamTypeForName(position->first);
				switch(paramType) {
					case ParamSetDef::BOOL: {
						DOMElement *boolElem = createBoolElement(position->first, position->second, doc);
						rootElem->appendChild(boolElem);
						break;
					}
					case ParamSetDef::INT: {
						DOMElement *intElem = createIntElement(position->first, position->second, doc);
						rootElem->appendChild(intElem);
						break;
					}
					case ParamSetDef::INT_ARRAY: {
						DOMElement *intArrayElem = createIntArrayElement(position->first, position->second, doc);
						rootElem->appendChild(intArrayElem);
						break;
					}
					case ParamSetDef::DOUBLE: {
						DOMElement *doubleElem = createDoubleElement(position->first, position->second, doc);
						rootElem->appendChild(doubleElem);
						break;
					}
					case ParamSetDef::DOUBLE_ARRAY: {
						DOMElement * doubleArrayElem = 
							createDoubleArrayElement(position->first, position->second, doc);
						rootElem->appendChild(doubleArrayElem);
						break;
					}
					case ParamSetDef::STRING: {
						DOMElement *stringElem = createStringElement(position->first, position->second, doc);
						rootElem->appendChild(stringElem);
						break;
					}
					case ParamSetDef::STRING_ARRAY: {
						DOMElement * stringArrayElem = createStringArrayElement(position->first, position->second, doc);
						rootElem->appendChild(stringArrayElem);
						break;
					}
				}
			}

			// construct the DOM writer
			DOMWriter *domWriter = impl->createDOMWriter();
			if (domWriter->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, true)) {
				domWriter->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, true);
			}

			// construct the MemBufFormatTarget
			XMLFormatTarget *myFormatTarget = new MemBufFormatTarget();

			// set the encoding to be ISO-8859-1
			XMLCh tempStr[100];
			XMLString::transcode("ISO-8859-1", tempStr, 99);
			domWriter->setEncoding(tempStr);

			// serialize the document to an internal memory buffer
			domWriter->writeNode(myFormatTarget, *doc);

			// get the string which is encoded in ISO-8859-1 from the MemBufFormatTarget
			char* theXMLString_Encoded = (char*) 
  					((MemBufFormatTarget*)myFormatTarget)->getRawBuffer();

			retVal = string(StrX(theXMLString_Encoded).localForm());

			// release the memory
			delete myFormatTarget;
			delete domWriter;

			//doc->release();
		}
		catch (const OutOfMemoryException& e)
		{
			ACS_LOG(LM_ERROR, "parameterTask::buildParameterSetXML", 
				(LM_ERROR, "Error - OutOfMemoryException - info: %s\n", StrX(e.getMessage()).localForm()))
		}
		catch (const DOMException& e)
		{
			ACS_LOG(LM_ERROR, "parameterTask::buildParameterSetXML", 
				(LM_ERROR, "Error - DOMException - info: %s\n", StrX(e.getMessage()).localForm()))
		}
	}
	else
	{
Exemplo n.º 8
0
/*=========================================================================+
	Build_Return_XML:
		Build the XML block that eTrust Admin expects the program exit
		to return.

		<eTExitReturn>
			<eTExitReturnCategory></eTExitReturnCategory>
			<eTExitReturnNative></eTExitReturnNative>
			<eTExitContinue></eTExitContinue>
			<eTExitLogMsg></eTExitLogMsg>
			<eTExitCustom></eTExitCustom>
		</eTExitReturn>

	    The return XML buffer provided by eTrust Admin is over 4000 bytes
		long.  There will be no problem fitting the entire output XML
		document into this buffer unless sLogMessage or the custom_msg built
		from the return values array is very long.  Thus, this code attempts
		first to build an XML buffer with all of the provided information
		and if it is too long does the following:
			case 1:  custom_msg is provided
				--> generate a failure exit return block with no custom_msg

			case 2:  sLogMessage is provided, but no custom_msg
				--> replace the very long sLogMessage with a short one.

+=========================================================================*/
void
ExitXMLBlock::Build_Return_XML(
		STATUS_T	tStatus,
		bool		bContinueEtaExecution,
		string		sLogMessage,
		string &	sReturnXML,						// OUT
		int			iMaxReturnLength,
		bool		bObscureValue  // = false
	)
{
	int iRc;
	string	suValue;
	UTF8	pszuValue[32];
	XMLCh*	pxcValue;

	pxcValue = UTF8toUTF16(UTFEXIT_EXITRETURN);
	DOMDocument* pDocument = ExitXMLBlock::g_pImplementation->createDocument(0, pxcValue, 0);
	delete pxcValue;
	DOMElement* pRootElement = pDocument->getDocumentElement();

	// ...eTrust Admin Category.
	suValue = Convert_Status_To_Category_String(tStatus);
	iRc = Add_Element(pDocument, pRootElement, UTFEXIT_EXITRETURNCATEGORY, suValue);

	// ...Program exit return code.
	sprintf(pszuValue, "%d", tStatus);
	iRc = Add_Element(pDocument, pRootElement, UTFEXIT_EXITRETURNNATIVE, pszuValue);

	// ...Should eTrust Admin continue execution?
	suValue = (bContinueEtaExecution ? UTFEXIT_TRUE : UTFEXIT_FALSE);
	iRc = Add_Element(pDocument, pRootElement, UTFEXIT_EXITCONTINUE, suValue);

	// ...Log message.
	if (!sLogMessage.empty()) {
		iRc = Add_Element(pDocument, pRootElement, UTFEXIT_EXITLOGMSG, sLogMessage);
	}

	// ...Custom message (used for return values today; and perhaps for
	// other exit-type specific purposes in the future).
	if (m_vsReturnValues.size() > 0) {
		pxcValue = UTF8toUTF16(UTFEXIT_EXITCUSTOM);
        DOMElement* pElement = pDocument->createElement(pxcValue);
		delete pxcValue;
        pRootElement->appendChild(pElement);

		// Add each return value as <eTFuncReturn>...</eTFuncReturn>
		for (unsigned int iIndex = 0; iIndex <  m_vsReturnValues.size(); iIndex++) {
			if (bObscureValue) {	// add the obscured attribute for passwords
				Add_Element(
					pDocument,
					pElement,
					UTFEXIT_CF_FUNCRETURN,
					m_vsReturnValues[iIndex],
					"obscured",
					"yes");
			} else {
				Add_Element(
					pDocument,
					pElement,
					UTFEXIT_CF_FUNCRETURN,
					m_vsReturnValues[iIndex]);
			}
		}
	}

	// Generate the return XML string
	DOMBuilder* pBuilder;	// Parser
	DOMWriter*	pWriter;	// Serializer

	pWriter = ExitXMLBlock::g_pImplementation->createDOMWriter();
	pBuilder = ExitXMLBlock::g_pImplementation->createDOMBuilder(DOMImplementationLS::MODE_SYNCHRONOUS, 0);
	pWriter->setFeature(XMLUni::fgDOMXMLDeclaration, false);
	pBuilder->resetDocumentPool();

	const XMLCh* pxcReturnXML = pWriter->writeToString(*pRootElement);
	sReturnXML = UTF16toUTF8(pxcReturnXML);

	if (pBuilder) {
		delete pBuilder;
	}
	if (pWriter) {
		delete pWriter;
	}
	
	if (pDocument) {
		delete pDocument;
		pDocument = NULL;
	}

	// Check to make sure it isn't too long for the return buffer
	int iLength = sReturnXML.length();
	if (iLength >= iMaxReturnLength) {
		sReturnXML = "";
		sLogMessage = "ERROR: Return XML buffer too long";

		// If too long, and a custom message was provided, fail the
		// call (and consequently do not report an output value).
		if (m_vsReturnValues.size() > 0) {
			m_vsReturnValues.clear();
			tStatus = E_FAILURE;
			bContinueEtaExecution = false;
		}
	}
}
Exemplo n.º 9
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
        {
            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 DOMWriter
            XMLCh tempStr[100];
            XMLString::transcode("LS", tempStr, 99);
            DOMImplementation *impl          = DOMImplementationRegistry::getDOMImplementation(tempStr);
            DOMWriter         *theSerializer = ((DOMImplementationLS*)impl)->createDOMWriter();

            // set user specified output encoding
            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);

            if (theSerializer->canSetFeature(XMLUni::fgDOMWRTBOM, gWriteBOM))
                theSerializer->setFeature(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();

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

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

            delete theSerializer;

            //
            // 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;

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

    XMLString::release(&gOutputEncoding);

    return retval;
}
Exemplo n.º 10
0
void writeHtmlFile(Tag2Html::MP3Collection* mp3Collection)
{
	XMLPlatformUtils::Initialize();
	DOMImplementation* domImplementation = DOMImplementationRegistry::getDOMImplementation(XMLString::transcode("core"));
	// <html>
	DOMDocument* doc = domImplementation->createDocument(0, XMLString::transcode("html"), 0);

	DOMDocumentType* docType = domImplementation->createDocumentType(XMLString::transcode("html"), XMLString::transcode(""), XMLString::transcode(""));
	doc->insertBefore(docType, doc->getDocumentElement());

	//	<head>
	DOMElement* head = doc->createElement(XMLString::transcode("head"));

	//		<link rel="stylesheet" type="text/css" href="./index.css">
	DOMElement* linkStylesheet = doc->createElement(XMLString::transcode("link"));
	linkStylesheet->setAttribute(XMLString::transcode("rel"), XMLString::transcode("stylesheet"));
	linkStylesheet->setAttribute(XMLString::transcode("type"), XMLString::transcode("text/css"));
	linkStylesheet->setAttribute(XMLString::transcode("href"), XMLString::transcode("index.css"));
	head->appendChild(linkStylesheet);

	//		<title>MP3-Leser</title>
	DOMElement* title = doc->createElement(XMLString::transcode("title"));
	title->setTextContent(XMLString::transcode("MP3-Leser"));
	head->appendChild(title);

	//		<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
	DOMElement* meta = doc->createElement(XMLString::transcode("meta"));
	meta->setAttribute(XMLString::transcode("http-equiv"), XMLString::transcode("Content-Type"));
	meta->setAttribute(XMLString::transcode("content"), XMLString::transcode("text/html"));
	meta->setAttribute(XMLString::transcode("charset"), XMLString::transcode("utf-8"));
	head->appendChild(meta);

	//	<body>
	DOMElement* body = doc->createElement(XMLString::transcode("body"));

	//		<h1>
	DOMElement* h1 = doc->createElement(XMLString::transcode("h1"));

	//			Track List ( view <a href="stats.html">stats</a>, <a href="info.html">info</a> )
	h1->appendChild(doc->createTextNode(XMLString::transcode("Track List ( view ")));
	DOMElement* statsLink = doc->createElement(XMLString::transcode("a"));
	statsLink->setAttribute(XMLString::transcode("href"), XMLString::transcode("stats.html"));
	statsLink->setTextContent(XMLString::transcode("stats"));
	h1->appendChild(statsLink);
	h1->appendChild(doc->createTextNode(XMLString::transcode(", ")));
	DOMElement* infoLink = doc->createElement(XMLString::transcode("a"));
	infoLink->setAttribute(XMLString::transcode("href"), XMLString::transcode("info.html"));
	infoLink->setTextContent(XMLString::transcode("info"));
	h1->appendChild(infoLink);
	h1->appendChild(doc->createTextNode(XMLString::transcode(" )")));
	body->appendChild(h1);

	//		<table align="center" width="1000">
	DOMElement* table = doc->createElement(XMLString::transcode("table"));
	table->setAttribute(XMLString::transcode("align"), XMLString::transcode("center"));

	//			<thead>
	DOMElement* tHead = doc->createElement(XMLString::transcode("thead"));

	//				<tr bgcolor="#CCCCCC">
	DOMElement* tHeadRow = doc->createElement(XMLString::transcode("tr"));
	tHeadRow->setAttribute(XMLString::transcode("bgcolor"), XMLString::transcode("#CCCCCC"));

	//					<th>Track</th>
	DOMElement* tHeadColumnTrack = doc->createElement(XMLString::transcode("th"));
	tHeadColumnTrack->setTextContent(XMLString::transcode("Track"));
	tHeadRow->appendChild(tHeadColumnTrack);

	//					<th>Artist</th>
	DOMElement* tHeadColumnArtist = doc->createElement(XMLString::transcode("th"));
	tHeadColumnArtist->setTextContent(XMLString::transcode("Artist"));
	tHeadRow->appendChild(tHeadColumnArtist);

	//					<th>Title</th>
	DOMElement* tHeadColumnTitle = doc->createElement(XMLString::transcode("th"));
	tHeadColumnTitle->setTextContent(XMLString::transcode("Title"));
	tHeadRow->appendChild(tHeadColumnTitle);

	//					<th>Album</th>
	DOMElement* tHeadColumnAlbum = doc->createElement(XMLString::transcode("th"));
	tHeadColumnAlbum->setTextContent(XMLString::transcode("Album"));
	tHeadRow->appendChild(tHeadColumnAlbum);

	//					<th>Year</th>
	DOMElement* tHeadColumnYear = doc->createElement(XMLString::transcode("th"));
	tHeadColumnYear->setTextContent(XMLString::transcode("Year"));
	tHeadRow->appendChild(tHeadColumnYear);

	//					<th>Genre</th>
	DOMElement* tHeadColumnGenre = doc->createElement(XMLString::transcode("th"));
	tHeadColumnGenre->setTextContent(XMLString::transcode("Genre"));
	tHeadRow->appendChild(tHeadColumnGenre);

	//					<th>Comment</th>
	DOMElement* tHeadColumnComment = doc->createElement(XMLString::transcode("th"));
	tHeadColumnComment->setTextContent(XMLString::transcode("Comment"));
	tHeadRow->appendChild(tHeadColumnComment);

	//					<th>Length</th>
	DOMElement* tHeadColumnLength = doc->createElement(XMLString::transcode("th"));
	tHeadColumnLength->setTextContent(XMLString::transcode("Length"));
	tHeadRow->appendChild(tHeadColumnLength);

	//					<th>Filename</th>
	DOMElement* tHeadColumnFilename = doc->createElement(XMLString::transcode("th"));
	tHeadColumnFilename->setTextContent(XMLString::transcode("Filename"));
	tHeadRow->appendChild(tHeadColumnFilename);

	tHead->appendChild(tHeadRow);
	table->appendChild(tHead);

	//			<tbody>
	DOMElement* tBody = doc->createElement(XMLString::transcode("tbody"));

	ostringstream convert;
	list<Tag2Html::MP3Infos*> sortedList = mp3Collection->getSortedList();
	for (list<Tag2Html::MP3Infos*>::iterator mp3info = sortedList.begin(); mp3info != sortedList.end(); mp3info++) {
		DOMElement* row = doc->createElement(XMLString::transcode("tr"));

		convert.str("");
		convert << (*mp3info)->track;
		DOMElement* trackColumn = doc->createElement(XMLString::transcode("td"));
		trackColumn->setTextContent(XMLString::transcode(convert.str().c_str()));
		row->appendChild(trackColumn);

		DOMElement* artistColumn = doc->createElement(XMLString::transcode("td"));
		artistColumn->setTextContent(XMLString::transcode((*mp3info)->artist.c_str()));
		row->appendChild(artistColumn);

		DOMElement* titleColumn = doc->createElement(XMLString::transcode("td"));
		titleColumn->setTextContent(XMLString::transcode((*mp3info)->title.c_str()));
		row->appendChild(titleColumn);

		DOMElement* albumColumn = doc->createElement(XMLString::transcode("td"));
		albumColumn->setTextContent(XMLString::transcode((*mp3info)->album.c_str()));
		row->appendChild(albumColumn);

		convert.str("");
		convert << (*mp3info)->year;
		DOMElement* yearColumn = doc->createElement(XMLString::transcode("td"));
		yearColumn->setTextContent(XMLString::transcode(convert.str().c_str()));
		row->appendChild(yearColumn);

		DOMElement* genreColumn = doc->createElement(XMLString::transcode("td"));
		genreColumn->setTextContent(XMLString::transcode((*mp3info)->genre.c_str()));
		row->appendChild(genreColumn);

		DOMElement* commentColumn = doc->createElement(XMLString::transcode("td"));
		commentColumn->setTextContent(XMLString::transcode((*mp3info)->comment.c_str()));
		row->appendChild(commentColumn);

		DOMElement* lengthColumn = doc->createElement(XMLString::transcode("td"));
		if ((*mp3info)->length < 3600) {
			char trackLength[12];
			struct tm* timeinfo = new tm();

			int seconds = (*mp3info)->length;
			if (seconds >= 60) {
				int minutes = seconds / 60;
				if (minutes >= 60) {
					timeinfo->tm_hour = minutes / 60;
					timeinfo->tm_min = minutes / 60;
				} else {
					timeinfo->tm_min = seconds / 60;
				}
			}
			timeinfo->tm_sec = seconds % 60;
			strftime(trackLength, 12, "%H:%M:%S", timeinfo);

			lengthColumn->setTextContent(XMLString::transcode(trackLength));
		}
		row->appendChild(lengthColumn);

		DOMElement* filenameColumn = doc->createElement(XMLString::transcode("td"));
		filenameColumn->setTextContent(XMLString::transcode((*mp3info)->filename.c_str()));
		row->appendChild(filenameColumn);

		tBody->appendChild(row);
	}

	table->appendChild(tBody);
	body->appendChild(table);
	doc->getDocumentElement()->appendChild(head);
	doc->getDocumentElement()->appendChild(body);

	DOMWriter* writer = ((DOMImplementationLS*)domImplementation)->createDOMWriter();
	if (writer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, true)) {
		writer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, true);
	}
	if (writer->canSetFeature(XMLUni::fgDOMXMLDeclaration, false)) {
		writer->setFeature(XMLUni::fgDOMXMLDeclaration, false);
	}
	XMLFormatTarget *fileFormatTarget = new LocalFileFormatTarget("index.html");
	writer->writeNode(fileFormatTarget, *doc);
	fileFormatTarget->flush();
	writer->release();

	doc->release();
	XMLPlatformUtils::Terminate();

	writeCssFile();
	writeStatFile(mp3Collection);
	writeInfoFile(mp3Collection);
}
Exemplo n.º 11
0
void writeInfoFile(Tag2Html::MP3Collection* mp3Collection)
{
	ostringstream convert;

	XMLPlatformUtils::Initialize();
	DOMImplementation* domImplementation = DOMImplementationRegistry::getDOMImplementation(XMLString::transcode("core"));
	// <html>
	DOMDocument* doc = domImplementation->createDocument(0, XMLString::transcode("html"), 0);

	DOMDocumentType* docType = domImplementation->createDocumentType(XMLString::transcode("html"), XMLString::transcode(""), XMLString::transcode(""));
	doc->insertBefore(docType, doc->getDocumentElement());

	//	<head>
	DOMElement* head = doc->createElement(XMLString::transcode("head"));

	//		<link rel="stylesheet" type="text/css" href="./index.css">
	DOMElement* headLink = doc->createElement(XMLString::transcode("link"));
	headLink->setAttribute(XMLString::transcode("rel"), XMLString::transcode("stylesheet"));
	headLink->setAttribute(XMLString::transcode("type"), XMLString::transcode("text/css"));
	headLink->setAttribute(XMLString::transcode("href"), XMLString::transcode("index.css"));
	head->appendChild(headLink);

	//		<title>tag2html info page</title>
	DOMElement* headTitle = doc->createElement(XMLString::transcode("title"));
	headTitle->setTextContent(XMLString::transcode("tag2html info page"));
	head->appendChild(headTitle);

	//		<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
	DOMElement* headMeta = doc->createElement(XMLString::transcode("meta"));
	headMeta->setAttribute(XMLString::transcode("http-equiv"), XMLString::transcode("Content-Type"));
	headMeta->setAttribute(XMLString::transcode("content"), XMLString::transcode("text/html"));
	headMeta->setAttribute(XMLString::transcode("charset"), XMLString::transcode("utf-8"));
	head->appendChild(headMeta);

	//	<body>
	DOMElement* body = doc->createElement(XMLString::transcode("body"));

	//		<h1>File Info</h1>
	DOMElement* h1 = doc->createElement(XMLString::transcode("h1"));
	h1->setTextContent(XMLString::transcode("File Info"));
	body->appendChild(h1);

	//		<table align="center">
	DOMElement* table = doc->createElement(XMLString::transcode("table"));
	table->setAttribute(XMLString::transcode("align"), XMLString::transcode("center"));

	//			<thead>
	DOMElement* tHead = doc->createElement(XMLString::transcode("thead"));

	//				<tr bgcolor="#CCCCCC">
	DOMElement* tHeadRow = doc->createElement(XMLString::transcode("tr"));
	tHeadRow->setAttribute(XMLString::transcode("bgcolor"), XMLString::transcode("#CCCCCC"));

	//					<th style="width: 100px; font-weight: bold;">Filename</th>
	DOMElement* tHeadColumn1 = doc->createElement(XMLString::transcode("th"));
	tHeadColumn1->setTextContent(XMLString::transcode("Filename"));
	tHeadRow->appendChild(tHeadColumn1);

	//					<th style="width: 50px; font-weight: bold;">Bitrate</th>
	DOMElement* tHeadColumn2 = doc->createElement(XMLString::transcode("th"));
	tHeadColumn2->setTextContent(XMLString::transcode("Bitrate"));
	tHeadRow->appendChild(tHeadColumn2);

	//					<th style="width: 100px; font-weight: bold;">MPEG Audio Version</th>
	DOMElement* tHeadColumn3 = doc->createElement(XMLString::transcode("th"));
	tHeadColumn3->setTextContent(XMLString::transcode("MPEG Audio Version"));
	tHeadRow->appendChild(tHeadColumn3);

	//					<th style="width: 100px; font-weight: bold;">Layer</th>
	DOMElement* tHeadColumn4 = doc->createElement(XMLString::transcode("th"));
	tHeadColumn4->setTextContent(XMLString::transcode("Layer"));
	tHeadRow->appendChild(tHeadColumn4);

	//					<th style="width: 100px; font-weight: bold;">Error Protection</th>
	DOMElement* tHeadColumn5 = doc->createElement(XMLString::transcode("th"));
	tHeadColumn5->setTextContent(XMLString::transcode("Error Protection"));
	tHeadRow->appendChild(tHeadColumn5);

	//					<th style="width: 100px; font-weight: bold;">Sampling Rate</th>
	DOMElement* tHeadColumn6 = doc->createElement(XMLString::transcode("th"));
	tHeadColumn6->setTextContent(XMLString::transcode("Sampling Rate"));
	tHeadRow->appendChild(tHeadColumn6);

	//					<th style="width: 50px; font-weight: bold;">Private</th>
	DOMElement* tHeadColumn7 = doc->createElement(XMLString::transcode("th"));
	tHeadColumn7->setTextContent(XMLString::transcode("Private"));
	tHeadRow->appendChild(tHeadColumn7);

	//					<th style="width: 100px; font-weight: bold;">Channel Mode</th>
	DOMElement* tHeadColumn8 = doc->createElement(XMLString::transcode("th"));
	tHeadColumn8->setTextContent(XMLString::transcode("Channel Mode"));
	tHeadRow->appendChild(tHeadColumn8);

	//					<th style="width: 100px; font-weight: bold;">Copyright</th>
	DOMElement* tHeadColumn9 = doc->createElement(XMLString::transcode("th"));
	tHeadColumn9->setTextContent(XMLString::transcode("Copyright"));
	tHeadRow->appendChild(tHeadColumn9);

	//					<th style="width: 50px; font-weight: bold;">Original</th>
	DOMElement* tHeadColumn10 = doc->createElement(XMLString::transcode("th"));
	tHeadColumn10->setTextContent(XMLString::transcode("Original"));
	tHeadRow->appendChild(tHeadColumn10);

	//					<th style="width: 100px; font-weight: bold;">Emphasis</th>
	DOMElement* tHeadColumn11 = doc->createElement(XMLString::transcode("th"));
	tHeadColumn11->setTextContent(XMLString::transcode("Emphasis"));
	tHeadRow->appendChild(tHeadColumn11);

	tHead->appendChild(tHeadRow);
	table->appendChild(tHead);

	//			<tbody>
	DOMElement* tBody = doc->createElement(XMLString::transcode("tbody"));

	list<Tag2Html::MP3Infos*> sortedList = mp3Collection->getSortedList();
	for (list<Tag2Html::MP3Infos*>::iterator mp3info = sortedList.begin(); mp3info != sortedList.end(); mp3info++) {
		//				<tr>
		DOMElement* currentRow = doc->createElement(XMLString::transcode("tr"));

		//					<td>" << mytag->filename << "</td>
		DOMElement* columnFilename = doc->createElement(XMLString::transcode("td"));
		columnFilename->setTextContent(XMLString::transcode((*mp3info)->filename.c_str()));
		currentRow->appendChild(columnFilename);

		//					<td>" << myheader->Bitrate << "</td>
		DOMElement* columnBitrate = doc->createElement(XMLString::transcode("td"));
		convert.str("");
		convert << (*mp3info)->bitrate << " kbit/s";
		columnBitrate->setTextContent(XMLString::transcode(convert.str().c_str()));
		currentRow->appendChild(columnBitrate);

		//					<td>" << myheader->MPEG_Audio_Version << "</td>
		DOMElement* columnMPEGAudioVersion = doc->createElement(XMLString::transcode("td"));
		switch((*mp3info)->version) {
			case TagLib::MPEG::Header::Version::Version1:
				columnMPEGAudioVersion->setTextContent(XMLString::transcode("1"));
				break;
			case TagLib::MPEG::Header::Version::Version2:
				columnMPEGAudioVersion->setTextContent(XMLString::transcode("2"));
				break;
			case TagLib::MPEG::Header::Version::Version2_5:
				columnMPEGAudioVersion->setTextContent(XMLString::transcode("2.5"));
				break;
		}
		currentRow->appendChild(columnMPEGAudioVersion);

		//					<td>" << myheader->Layer << "</td>
		DOMElement* columnLayer = doc->createElement(XMLString::transcode("td"));
		convert.str("");
		convert << (*mp3info)->layer;
		columnLayer->setTextContent(XMLString::transcode(convert.str().c_str()));
		currentRow->appendChild(columnLayer);

		//					<td>" << myheader->Error_Protection << "</td>
		DOMElement* columnErrorProtection = doc->createElement(XMLString::transcode("td"));
		if ((*mp3info)->protectionEnabled) {
			columnErrorProtection->setTextContent(XMLString::transcode("yes"));
		} else {
			columnErrorProtection->setTextContent(XMLString::transcode("no"));
		}
		currentRow->appendChild(columnErrorProtection);

		//					<td>" << myheader->Samplerate << "</td>
		DOMElement* columnSamplerate = doc->createElement(XMLString::transcode("td"));
		convert.str("");
		convert << (*mp3info)->samplerate << " Hz";
		columnSamplerate->setTextContent(XMLString::transcode(convert.str().c_str()));
		currentRow->appendChild(columnSamplerate);

		//					<td>" << myheader->Private << "</td>
		DOMElement* columnPrivate = doc->createElement(XMLString::transcode("td"));
		columnPrivate->setTextContent(XMLString::transcode(""));
		currentRow->appendChild(columnPrivate);

		//					<td>" << myheader->Channel_Mode << "</td>
		DOMElement* columnChannelMode = doc->createElement(XMLString::transcode("td"));
		switch((*mp3info)->channelMode) {
			case TagLib::MPEG::Header::ChannelMode::DualChannel:
				columnChannelMode->setTextContent(XMLString::transcode("Dual Channel"));
				break;
			case TagLib::MPEG::Header::ChannelMode::JointStereo:
				columnChannelMode->setTextContent(XMLString::transcode("Joint Stereo"));
				break;
			case TagLib::MPEG::Header::ChannelMode::SingleChannel:
				columnChannelMode->setTextContent(XMLString::transcode("Single Channel"));
				break;
			case TagLib::MPEG::Header::ChannelMode::Stereo:
				columnChannelMode->setTextContent(XMLString::transcode("Stereo"));
				break;
		}
		currentRow->appendChild(columnChannelMode);

		//					<td>" << myheader->Copyright << "</td>
		DOMElement* columnCopyright = doc->createElement(XMLString::transcode("td"));
		if ((*mp3info)->isCopyrighted) {
			columnCopyright->setTextContent(XMLString::transcode("yes"));
		} else {
			columnCopyright->setTextContent(XMLString::transcode("no"));
		}
		currentRow->appendChild(columnCopyright);

		//					<td>" << myheader->Original << "</td>
		DOMElement* columnOriginal = doc->createElement(XMLString::transcode("td"));
		if ((*mp3info)->isOriginal) {
			columnOriginal->setTextContent(XMLString::transcode("yes"));
		} else {
			columnOriginal->setTextContent(XMLString::transcode("no"));
		}
		currentRow->appendChild(columnOriginal);

		//					<td>" << myheader->Emphasis << "</td>
		DOMElement* columnEmphasis = doc->createElement(XMLString::transcode("td"));
		columnEmphasis->setTextContent(XMLString::transcode(""));
		currentRow->appendChild(columnEmphasis);

		tBody->appendChild(currentRow);
	}

	table->appendChild(tBody);

	body->appendChild(table);

	doc->getDocumentElement()->appendChild(head);
	doc->getDocumentElement()->appendChild(body);

	DOMWriter* writer = ((DOMImplementationLS*)domImplementation)->createDOMWriter();
	if (writer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, true)) {
		writer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, true);
	}
	if (writer->canSetFeature(XMLUni::fgDOMXMLDeclaration, false)) {
		writer->setFeature(XMLUni::fgDOMXMLDeclaration, false);
	}
	XMLFormatTarget *fileFormatTarget = new LocalFileFormatTarget("info.html");
	writer->writeNode(fileFormatTarget, *doc);
	fileFormatTarget->flush();
	writer->release();

	doc->release();
	XMLPlatformUtils::Terminate();
}
Exemplo n.º 12
0
void writeStatFile(Tag2Html::MP3Collection* mp3Collection)
{
	ostringstream convert;

	XMLPlatformUtils::Initialize();
	DOMImplementation* domImplementation = DOMImplementationRegistry::getDOMImplementation(XMLString::transcode("core"));
	// <html>
	DOMDocument* doc = domImplementation->createDocument(0, XMLString::transcode("html"), 0);

	DOMDocumentType* docType = domImplementation->createDocumentType(XMLString::transcode("html"), XMLString::transcode(""), XMLString::transcode(""));
	doc->insertBefore(docType, doc->getDocumentElement());

	//	<head>
	DOMElement* head = doc->createElement(XMLString::transcode("head"));

	//		<link rel="stylesheet" type="text/css" href="index.css">
	DOMElement* headLink = doc->createElement(XMLString::transcode("link"));
	headLink->setAttribute(XMLString::transcode("rel"), XMLString::transcode("stylesheet"));
	headLink->setAttribute(XMLString::transcode("type"), XMLString::transcode("text/css"));
	headLink->setAttribute(XMLString::transcode("href"), XMLString::transcode("index.css"));
	head->appendChild(headLink);

	//		<title>tag2html stat page</title>
	DOMElement* headTitle = doc->createElement(XMLString::transcode("title"));
	headTitle->setTextContent(XMLString::transcode("tag2html stat page"));
	head->appendChild(headTitle);

	//		<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
	DOMElement* headMeta = doc->createElement(XMLString::transcode("meta"));
	headMeta->setAttribute(XMLString::transcode("http-equiv"), XMLString::transcode("Content-Type"));
	headMeta->setAttribute(XMLString::transcode("content"), XMLString::transcode("text/html"));
	headMeta->setAttribute(XMLString::transcode("charset"), XMLString::transcode("utf-8"));
	head->appendChild(headMeta);

	//	<body>
	DOMElement* body = doc->createElement(XMLString::transcode("body"));

	//		<br><br><br>
	body->appendChild(doc->createElement(XMLString::transcode("br")));
	body->appendChild(doc->createElement(XMLString::transcode("br")));
	body->appendChild(doc->createElement(XMLString::transcode("br")));

	//		<table align="center" width="300">
	DOMElement* table = doc->createElement(XMLString::transcode("table"));
	table->setAttribute(XMLString::transcode("align"), XMLString::transcode("center"));
	table->setAttribute(XMLString::transcode("width"), XMLString::transcode("300"));

	//			<tbody>
	DOMElement* tbody = doc->createElement(XMLString::transcode("tbody"));

	//				<tr valign="top" bgcolor="#CCCCCC">
	DOMElement* tableRow = doc->createElement(XMLString::transcode("tr"));
	tableRow->setAttribute(XMLString::transcode("valign"), XMLString::transcode("top"));
	tableRow->setAttribute(XMLString::transcode("bgcolor"), XMLString::transcode("#CCCCCC"));

	//					<td align="center">
	DOMElement* tableColumn = doc->createElement(XMLString::transcode("td"));
	tableColumn->setAttribute(XMLString::transcode("align"), XMLString::transcode("center"));
	tableRow->appendChild(tableColumn);

	//						<b>Statistics</b>
	DOMElement* columnStatistics = doc->createElement(XMLString::transcode("b"));
	columnStatistics->setTextContent(XMLString::transcode("Statistics"));
	tableColumn->appendChild(columnStatistics);

	//				<tr>
	DOMElement* tableRow2 = doc->createElement(XMLString::transcode("tr"));

	//					<td>
	DOMElement* tableColumn2 = doc->createElement(XMLString::transcode("td"));

	//						<table class="nb">
	DOMElement* innerTable = doc->createElement(XMLString::transcode("table"));
	innerTable->setAttribute(XMLString::transcode("class"), XMLString::transcode("nb"));

	//							<tr>
	DOMElement* rowFileType = doc->createElement(XMLString::transcode("tr"));

	//								<td style="font-weight: bold;">File Type:</td>
	DOMElement* columnFileType = doc->createElement(XMLString::transcode("td"));
	columnFileType->setAttribute(XMLString::transcode("style"), XMLString::transcode("font-weight: bold;"));
	columnFileType->setTextContent(XMLString::transcode("File Type:"));
	rowFileType->appendChild(columnFileType);

	//								<td>MP3</td>
	DOMElement* columnFileTypeValue = doc->createElement(XMLString::transcode("td"));
	columnFileTypeValue->setTextContent(XMLString::transcode("MP3"));
	rowFileType->appendChild(columnFileTypeValue);

	//							<tr>
	DOMElement* rowFileCount = doc->createElement(XMLString::transcode("tr"));

	//								<td style="font-weight: bold;">File Count:</td>
	DOMElement* columnFileCount = doc->createElement(XMLString::transcode("td"));
	columnFileCount->setAttribute(XMLString::transcode("style"), XMLString::transcode("font-weight: bold;"));
	columnFileCount->setTextContent(XMLString::transcode("File Count:"));
	rowFileCount->appendChild(columnFileCount);

	//								<td>" << mystat->mp3_count << "</td>
	DOMElement* columnFileCountValue = doc->createElement(XMLString::transcode("td"));
	convert.str("");
	convert << mp3Collection->items.size();
	columnFileCountValue->setTextContent(XMLString::transcode(convert.str().c_str()));
	rowFileCount->appendChild(columnFileCountValue);

	//							<tr>\n";
	DOMElement* rowArtistCount = doc->createElement(XMLString::transcode("tr"));

	//								<td style="font-weight: bold;">Artist Count:</td>
	DOMElement* columnArtistCount = doc->createElement(XMLString::transcode("td"));
	columnArtistCount->setAttribute(XMLString::transcode("style"), XMLString::transcode("font-weight: bold;"));
	columnArtistCount->setTextContent(XMLString::transcode("Artist Count:"));
	rowArtistCount->appendChild(columnArtistCount);

	//								<td>" << mystat->art_count << "</td>
	DOMElement* columnArtistCountValue = doc->createElement(XMLString::transcode("td"));
	convert.str("");
	convert << mp3Collection->getArtistCount();
	columnArtistCountValue->setTextContent(XMLString::transcode(convert.str().c_str()));
	rowArtistCount->appendChild(columnArtistCountValue);

	//							<tr>
	DOMElement* rowAlbumCount = doc->createElement(XMLString::transcode("tr"));

	//								<td style="font-weight: bold;">Album Count:</td>
	DOMElement* columnAlbumCount = doc->createElement(XMLString::transcode("td"));
	columnAlbumCount->setAttribute(XMLString::transcode("style"), XMLString::transcode("font-weight: bold;"));
	columnAlbumCount->setTextContent(XMLString::transcode("Album Count:"));
	rowAlbumCount->appendChild(columnAlbumCount);

	//								<td>" << mystat->alb_count << "</td>
	DOMElement* columnAlbumCountValue = doc->createElement(XMLString::transcode("td"));
	convert.str("");
	convert << mp3Collection->getAlbumCount();
	columnAlbumCountValue->setTextContent(XMLString::transcode(convert.str().c_str()));
	rowAlbumCount->appendChild(columnAlbumCountValue);

	//							<tr>
	DOMElement* rowTotalSize = doc->createElement(XMLString::transcode("tr"));

	//								<td style="font-weight: bold;">Total Size:</td>
	DOMElement* columnTotalSize = doc->createElement(XMLString::transcode("td"));
	columnTotalSize->setAttribute(XMLString::transcode("style"), XMLString::transcode("font-weight: bold;"));
	columnTotalSize->setTextContent(XMLString::transcode("Total Filesize:"));
	rowTotalSize->appendChild(columnTotalSize);

	//								<td>" << ( mystat->tot_filesize/(1024*1024)) << " MByte</td>
	DOMElement* columnTotalSizeValue = doc->createElement(XMLString::transcode("td"));
	convert.str("");
	convert << (mp3Collection->getTotalFilesize() / 1024 / 1024) << " MB";
	columnTotalSizeValue->setTextContent(XMLString::transcode(convert.str().c_str()));
	rowTotalSize->appendChild(columnTotalSizeValue);

	//							<tr>
	DOMElement* rowTotalLength = doc->createElement(XMLString::transcode("tr"));

	//								<td style="font-weight: bold;">Total Length:</td>
	DOMElement* columnTotalLength = doc->createElement(XMLString::transcode("td"));
	columnTotalLength->setAttribute(XMLString::transcode("style"), XMLString::transcode("font-weight: bold;"));
	columnTotalLength->setTextContent(XMLString::transcode("Total Length:"));
	rowTotalLength->appendChild(columnTotalLength);

	//								<td> ~ " << mystat->tot_length << "</td>
	DOMElement* columnTotalLengthValue = doc->createElement(XMLString::transcode("td"));
	convert.str("");

	char statLength[12];
	struct tm* timeinfo = new tm();
	int seconds = mp3Collection->getTotalLength();
	if (seconds >= 60) {
		int minutes = seconds / 60;
		if (minutes >= 60) {
			timeinfo->tm_hour = minutes / 60;
			timeinfo->tm_min = minutes / 60;
		} else {
			timeinfo->tm_min = seconds / 60;
		}
	}
	timeinfo->tm_sec = seconds % 60;
	strftime(statLength, 12, "%H:%M:%S", timeinfo);

	columnTotalLengthValue->setTextContent(XMLString::transcode(statLength));
	rowTotalLength->appendChild(columnTotalLengthValue);

	innerTable->appendChild(rowFileType);
	innerTable->appendChild(rowFileCount);
	innerTable->appendChild(rowArtistCount);
	innerTable->appendChild(rowAlbumCount);
	innerTable->appendChild(rowTotalSize);
	innerTable->appendChild(rowTotalLength);
	tableColumn2->appendChild(innerTable);
	tableRow2->appendChild(tableColumn2);

	tbody->appendChild(tableRow);
	tbody->appendChild(tableRow2);
	table->appendChild(tbody);
	body->appendChild(table);

	doc->getDocumentElement()->appendChild(head);
	doc->getDocumentElement()->appendChild(body);

	DOMWriter* writer = ((DOMImplementationLS*)domImplementation)->createDOMWriter();
	if (writer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, true)) {
		writer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, true);
	}
	if (writer->canSetFeature(XMLUni::fgDOMXMLDeclaration, false)) {
		writer->setFeature(XMLUni::fgDOMXMLDeclaration, false);
	}
	XMLFormatTarget *fileFormatTarget = new LocalFileFormatTarget("stats.html");
	writer->writeNode(fileFormatTarget, *doc);
	fileFormatTarget->flush();
	writer->release();

	doc->release();
	XMLPlatformUtils::Terminate();
}
Exemplo n.º 13
0
void JobXML::SaveToFile( std::string strFile )
{
   // error check filename
   if ( strFile.length() == 0 )
   {      
      std::cout << "[Error] Filename: '" << strFile << "' is not valid." << std::endl; 
      return;
   }

   // locals
   DOMWriter *writer = NULL;

   // create writer
   try
   {
      writer = mDOMImplementor->createDOMWriter();
      if ( writer == NULL ) return;
   }   
   catch ( const OutOfMemoryException &e )
   {
      char* message = XMLString::transcode( e.getMessage() );
      std::cout << "[Error] XML writer error:\n  " << message << std::endl;
      XMLString::release( &message );
      return;
   }
   catch ( const DOMException &e )
   {
      char* message = XMLString::transcode( e.getMessage() );
      std::cout << "[Error] XML writer error:\n  " << message << std::endl;
      XMLString::release( &message );
      return;
   }
   catch (...)
   {      
      std::cout << "[Error] Creating XML document!" << std::endl;
      return;
   }

   // set writer features
#if defined(_WIN32) || defined(WIN32) || defined(__WIN32__)
   XMLCh *newline = XMLString::transcode( "\r\n" );
   writer->setNewLine( newline );
   XMLString::release( &newline );
#else
   XMLCh *newline = XMLString::transcode( "\n" );
   writer->setNewLine( newline );
   XMLString::release( &newline );
#endif
   XMLCh *encoding = XMLString::transcode( "UTF-8" );
   writer->setEncoding( encoding );
   XMLString::release( &encoding );

   // set writer features
   if ( writer->canSetFeature( XMLUni::fgDOMWRTCanonicalForm, true ) )
      writer->setFeature( XMLUni::fgDOMWRTCanonicalForm, true );
   //if ( writer->canSetFeature( XMLUni::fgDOMXMLDeclaration, true ) )
   //   writer->setFeature( XMLUni::fgDOMXMLDeclaration, true );
   if ( writer->canSetFeature( XMLUni::fgDOMWRTSplitCdataSections, true ) )
      writer->setFeature( XMLUni::fgDOMWRTSplitCdataSections, true );
   if ( writer->canSetFeature( XMLUni::fgDOMWRTDiscardDefaultContent, true ) )
      writer->setFeature( XMLUni::fgDOMWRTDiscardDefaultContent, true );
   if ( writer->canSetFeature( XMLUni::fgDOMWRTFormatPrettyPrint, true ) )
      writer->setFeature( XMLUni::fgDOMWRTFormatPrettyPrint, true );
   if ( writer->canSetFeature( XMLUni::fgDOMWRTBOM, true ) )
      writer->setFeature( XMLUni::fgDOMWRTBOM, true ); // byte-order-mark

   /*
   // set filter
   DOMWriterFilter *filter = new DOMWriterFilter(
      DOMNodeFilter::SHOW_ALL       |
      DOMNodeFilter::SHOW_DOCUMENT  |
      DOMNodeFilter::SHOW_ELEMENT   |
      DOMNodeFilter::SHOW_ATTRIBUTE |
      DOMNodeFilter::SHOW_DOCUMENT_TYPE );
   writer->setFilter( filter );
   */

   // is this necessary?
   //mDocument->normalizeDocument();

   // do it
   XMLCh *filename = XMLString::transcode( strFile.c_str() );   
   writer->writeNode( &LocalFileFormatTarget( filename ), (*mDocument) );
   XMLString::release( &filename );

   // cleanup
   writer->release();   
}
bool
ComponentInstallationImpl::addInstalledComponent (ComponentImplementation* aComponentImplementation)
{
	//
	// parse the descriptor file
    //
	DOMXMLParser* parser = new DOMXMLParser();
    if (parser->parse(strdup(inst_file_.c_str())) != 0) 
	{
		std::cerr << "Error during parsing " << inst_file_ << std::endl;
        return false;
	}

	//
	// add the new implementation
	//
	DOMDocument* doc = parser->getDocument();
	DOMElement* root = doc->getDocumentElement();
	root->appendChild(doc->createTextNode(X("\n    ")));

	DOMElement* servants = doc->createElement(X("servants"));
	servants->appendChild(doc->createTextNode(X("\n        ")));
	servants->setAttribute(X("code"), X(aComponentImplementation->servant_module_.c_str()));
	servants->setAttribute(X("entry"), X(aComponentImplementation->servant_entry_point_.c_str()));

	DOMElement* business = doc->createElement(X("business"));
	business->appendChild(doc->createTextNode(X("\n        ")));
	business->setAttribute(X("code"), X(aComponentImplementation->executor_module_.c_str()));
	business->setAttribute(X("entry"), X(aComponentImplementation->executor_entry_point_.c_str()));

	DOMElement* impl = doc->createElement(X("implementation"));
	impl->setAttribute(X("id"), X(aComponentImplementation->uuid_.c_str()));
	impl->appendChild (doc->createTextNode(X("\n        ")));
	impl->appendChild (servants);
	impl->appendChild (doc->createTextNode(X("\n        ")));
	impl->appendChild (business);
	impl->appendChild (doc->createTextNode(X("\n    ")));
	root->appendChild (impl);
	root->appendChild (doc->createTextNode(X("\n")));

	//
	// write the new list
	//
	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();

		if (theSerializer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, true))
		{
			theSerializer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, true);
		}

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

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

		delete theSerializer;
		delete myFormTarget;
	}
    catch (XMLException& e)
	{
		std::cerr << "An error occurred during creation of output transcoder. Msg is:" << std::endl;
		std::cerr << StrX(e.getMessage()) << std::endl;
    }

	// delete parser
	delete parser;

	return true;
}
Exemplo n.º 15
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
}