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
int main(int argc, char** argv)
{
	// build a DOM document and write it to standard output.

	AutoPtr<Document> pDoc = new Document;
	
	AutoPtr<Element> pRoot = pDoc->createElement("root");
	pDoc->appendChild(pRoot);

	AutoPtr<Element> pChild1 = pDoc->createElement("child1");
	AutoPtr<Text> pText1 = pDoc->createTextNode("text1");
	pChild1->appendChild(pText1);
	pRoot->appendChild(pChild1);

	AutoPtr<Element> pChild2 = pDoc->createElement("child2");
	AutoPtr<Text> pText2 = pDoc->createTextNode("text2");
	pChild2->appendChild(pText2);
	pRoot->appendChild(pChild2);
	
	DOMWriter writer;
	writer.setNewLine("\n");
	writer.setOptions(XMLWriter::PRETTY_PRINT);
	writer.writeNode(std::cout, pDoc);
	
	return 0;
}
Exemplo n.º 3
0
  /** Serialize the coordinate transform
  *
  * @return The coordinate transform in its serialized form.
  */
  std::string CoordTransformAffine::toXMLString() const
  {
     using namespace Poco::XML;

      AutoPtr<Document> pDoc = new Document;
      AutoPtr<Element> coordTransformElement = pDoc->createElement("CoordTransform");
      pDoc->appendChild(coordTransformElement);

      AutoPtr<Element> coordTransformTypeElement = pDoc->createElement("Type");
      coordTransformTypeElement->appendChild(pDoc->createTextNode("CoordTransformAffine"));
      coordTransformElement->appendChild(coordTransformTypeElement);

      AutoPtr<Element> paramListElement = pDoc->createElement("ParameterList");

      AutoPtr<Text> formatText = pDoc->createTextNode("%s%s%s");
      paramListElement->appendChild(formatText);

      coordTransformElement->appendChild(paramListElement);

      std::stringstream xmlstream;

      DOMWriter writer;
      writer.writeNode(xmlstream, pDoc);

      // Convert the members to parameters
      AffineMatrixParameter affineMatrixParameter(inD, outD);
      affineMatrixParameter.setMatrix(affineMatrix);
      Mantid::API::InDimParameter inD_param(inD);
      Mantid::API::OutDimParameter outD_param(outD);

      std::string formattedXMLString = boost::str(boost::format(xmlstream.str().c_str())
        % inD_param.toXMLString().c_str() % outD_param.toXMLString().c_str() % affineMatrixParameter.toXMLString().c_str());
      return formattedXMLString;
  }
Exemplo n.º 4
0
  /** Serialize to an XML string
   * @return XML string
   */
  std::string BoxController::toXMLString() const
  {
    using namespace Poco::XML;

    //Create the root element for this fragment.
    AutoPtr<Document> pDoc = new Document;
    AutoPtr<Element> pBoxElement = pDoc->createElement("BoxController");
    pDoc->appendChild(pBoxElement);

    AutoPtr<Element> element;
    AutoPtr<Text> text;
    std::string vecStr;

    element = pDoc->createElement("NumDims");
    text = pDoc->createTextNode(boost::str(boost::format("%d") % this->getNDims()));
    element->appendChild( text );
    pBoxElement->appendChild(element);

    element = pDoc->createElement("MaxId");
    text = pDoc->createTextNode(boost::str(boost::format("%d") % this->getMaxId()));
    element->appendChild( text );
    pBoxElement->appendChild(element);

    element = pDoc->createElement("SplitThreshold");
    text = pDoc->createTextNode(boost::str(boost::format("%d") % this->getSplitThreshold()));
    element->appendChild( text );
    pBoxElement->appendChild(element);

    element = pDoc->createElement("MaxDepth");
    text = pDoc->createTextNode(boost::str(boost::format("%d") % this->getMaxDepth()));
    element->appendChild( text );
    pBoxElement->appendChild(element);

    element = pDoc->createElement("SplitInto");
    vecStr = Kernel::Strings::join( this->m_splitInto.begin(), this->m_splitInto.end(), ",");
    text = pDoc->createTextNode( vecStr );
    element->appendChild( text );
    pBoxElement->appendChild(element);

    element = pDoc->createElement("NumMDBoxes");
    vecStr = Kernel::Strings::join( this->m_numMDBoxes.begin(), this->m_numMDBoxes.end(), ",");
    text = pDoc->createTextNode( vecStr );
    element->appendChild( text );
    pBoxElement->appendChild(element);

    element = pDoc->createElement("NumMDGridBoxes");
    vecStr = Kernel::Strings::join( this->m_numMDGridBoxes.begin(), this->m_numMDGridBoxes.end(), ",");
    text = pDoc->createTextNode( vecStr );
    element->appendChild( text );
    pBoxElement->appendChild(element);

    //Create a string representation of the DOM tree.
    std::stringstream xmlstream;
    DOMWriter writer;
    writer.writeNode(xmlstream, pDoc);

    return xmlstream.str().c_str();
  }
Exemplo n.º 5
0
/**
 * Save grouping to the XML file specified.
 *
 * @param        g :: Struct with grouping information
 * @param filename :: XML filename where information will be saved
 */
void saveGroupingToXML(const Grouping& g, const std::string& filename)
{
  std::ofstream outFile(filename.c_str());
  if (!outFile)
    throw Mantid::Kernel::Exception::FileError("Unable to open output file", filename);

  DOMWriter writer;
  writer.setNewLine("\n");
  writer.setOptions(XMLWriter::PRETTY_PRINT);

  Poco::AutoPtr<Poco::XML::Document> mDoc = new Document();

  // Create root element with a description
  Poco::AutoPtr<Element> rootElem = mDoc->createElement("detector-grouping");
  rootElem->setAttribute("description", g.description);
  mDoc->appendChild(rootElem);

  // Create group elements
  for (size_t gi = 0; gi < g.groups.size(); gi++)
  {
    Poco::AutoPtr<Element> gElem = mDoc->createElement("group");
    gElem->setAttribute("name", g.groupNames[gi]);
    rootElem->appendChild(gElem);

    Poco::AutoPtr<Element> idsElem = mDoc->createElement("ids");
    idsElem->setAttribute("val", g.groups[gi]);
    gElem->appendChild(idsElem);
  }

  // Create pair elements
  for (size_t pi = 0; pi < g.pairs.size(); pi++)
  {
    Poco::AutoPtr<Element> gElem = mDoc->createElement("pair");
    gElem->setAttribute("name", g.pairNames[pi]);
    rootElem->appendChild(gElem);

    Poco::AutoPtr<Element> fwElem = mDoc->createElement("forward-group");
    fwElem->setAttribute("val", g.groupNames[g.pairs[pi].first]);
    gElem->appendChild(fwElem);

    Poco::AutoPtr<Element> bwElem = mDoc->createElement("backward-group");
    bwElem->setAttribute("val", g.groupNames[g.pairs[pi].second]);
    gElem->appendChild(bwElem);

    Poco::AutoPtr<Element> alphaElem = mDoc->createElement("alpha");
    alphaElem->setAttribute("val", boost::lexical_cast<std::string>(g.pairAlphas[pi]));
    gElem->appendChild(alphaElem);
  } 

  // Create default group/pair name element
  Poco::AutoPtr<Element> gElem = mDoc->createElement("default");
  gElem->setAttribute("name", g.defaultName);
  rootElem->appendChild(gElem);

  writer.writeNode(outFile, mDoc);
}
Exemplo n.º 6
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.º 7
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);
}
/** Put the parameters into one workspace
  * @param column :: [input] column of the output table workspace
  * @param ws :: [input/output] the group workspace parameters are to be put in
  * @param nProf :: the PROF Number, which is used to determine fitting function
 * for the parameters.
  * @param parameterXMLString :: string where the XML document filename is
 * stored
  */
void LoadFullprofResolution::putParametersIntoWorkspace(
    API::Column_const_sptr column, API::MatrixWorkspace_sptr ws, int nProf,
    std::string &parameterXMLString) {

  // Get instrument name from matrix workspace
  std::string instrumentName = ws->getInstrument()->getName();

  // Convert table workspace column into DOM XML document
  //   Set up writer to Paremeter file
  DOMWriter writer;
  writer.setNewLine("\n");
  writer.setOptions(XMLWriter::PRETTY_PRINT);

  //   Get current time
  Kernel::DateAndTime date = Kernel::DateAndTime::getCurrentTime();
  std::string ISOdate = date.toISO8601String();
  std::string ISOdateShort =
      ISOdate.substr(0, 19); // Remove fraction of seconds

  //   Create document
  AutoPtr<Document> mDoc = new Document();
  AutoPtr<Element> rootElem = mDoc->createElement("parameter-file");
  rootElem->setAttribute("date", ISOdateShort);
  mDoc->appendChild(rootElem);

  //   Add instrument
  AutoPtr<Element> instrumentElem = mDoc->createElement("component-link");
  instrumentElem->setAttribute("name", instrumentName);
  rootElem->appendChild(instrumentElem);
  if (nProf == 9) // put parameters into BackToBackExponential function
  {
    addBBX_S_Parameters(column, mDoc, instrumentElem);
    addBBX_A_Parameters(column, mDoc, instrumentElem);
    addBBX_B_Parameters(column, mDoc, instrumentElem);
  } else // Assume IkedaCarpenter PV
  {
    addALFBEParameter(column, mDoc, instrumentElem, "Alph0");
    addALFBEParameter(column, mDoc, instrumentElem, "Beta0");
    addALFBEParameter(column, mDoc, instrumentElem, "Alph1");
    addALFBEParameter(column, mDoc, instrumentElem, "Beta1");
    addSigmaParameters(column, mDoc, instrumentElem);
    addGammaParameters(column, mDoc, instrumentElem);
  }

  // Convert DOM XML document into string
  std::ostringstream outFile;
  writer.writeNode(outFile, mDoc);
  parameterXMLString = outFile.str();

  // Useful code for testing upgrades commented out for production use
  // std::ofstream outfileDebug("C:/Temp/test4_fullprof.xml");
  // outfileDebug << parameterXMLString;
  // outfileDebug.close();
}
Exemplo n.º 9
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.º 10
0
 /**
  * Write the XML to the file
  */	  
 void vtkGeometryCacheWriter::write()
 {
   DOMWriter writer;
   writer.setNewLine("\n");
   writer.setOptions(XMLWriter::PRETTY_PRINT);
   std::ofstream file;
   try
   {
     file.open(mFileName.c_str(),std::ios::trunc);
     writer.writeNode(file, mDoc);
     file.close();
   }
   catch(...)
   {
     PLog.error("Geometry Cache file writing exception");
   }
 }
Exemplo n.º 11
0
  /** Serialize the coordinate transform distance
  *
  * @return The coordinate transform distance in its serialized form.
  */
  std::string CoordTransformDistance::toXMLString() const
  {
     using namespace Poco::XML;

      AutoPtr<Document> pDoc = new Document;
      AutoPtr<Element> coordTransformElement = pDoc->createElement("CoordTransform");
      pDoc->appendChild(coordTransformElement);

      AutoPtr<Element> coordTransformTypeElement = pDoc->createElement("Type");
      coordTransformTypeElement->appendChild(pDoc->createTextNode("CoordTransformDistance"));
      coordTransformElement->appendChild(coordTransformTypeElement);

      AutoPtr<Element> paramListElement = pDoc->createElement("ParameterList");

      AutoPtr<Text> formatText = pDoc->createTextNode("%s%s%s%s");
      paramListElement->appendChild(formatText);
      coordTransformElement->appendChild(paramListElement);

      std::stringstream xmlstream;

      DOMWriter writer;
      writer.writeNode(xmlstream, pDoc);

      // Convert the members to parameters
      Mantid::API::InDimParameter inD_param(inD);
      Mantid::API::OutDimParameter outD_param(outD);
      CoordCenterVectorParam m_center_param(inD);
      DimensionsUsedVectorParam m_dimensionsUsed_param(inD);

      // Create and copy the arrays.
      for (size_t d=0; d<inD; d++)
      {
        m_center_param.addValue(d, m_center[d]);
        m_dimensionsUsed_param.addValue(d, m_dimensionsUsed[d]);
      }

      std::string formattedXMLString = boost::str(boost::format(xmlstream.str().c_str())
        % inD_param.toXMLString().c_str()
        % outD_param.toXMLString().c_str()
        % m_center_param.toXMLString().c_str()
        % m_dimensionsUsed_param.toXMLString().c_str());

      return formattedXMLString;
  }
//
// domPrint  -  Dump the contents of a DOM node.
//              For debugging failures, when all else fails.
//                 Works recursively - initially called with a document node.
//
void ThreadParser::domPrint()
{
    printf("Begin DOMPrint ...\n");
    if (gRunInfo.dom)
    {
        try
        {
            XMLCh tempStr[100];
            XMLString::transcode("LS", tempStr, 99);
            DOMImplementation *impl          = DOMImplementationRegistry::getDOMImplementation(tempStr);
            DOMWriter         *theSerializer = ((DOMImplementationLS*)impl)->createDOMWriter();
            XMLFormatTarget   *myFormTarget  = new StdOutFormatTarget();
            DOMNode           *doc           = fXercesDOMParser->getDocument();
            theSerializer->writeNode(myFormTarget, *doc);
            delete theSerializer;
        }
        catch (...)
        {
            // do nothing
        }
    }
    printf("End DOMPrint\n");
}
Exemplo n.º 13
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.º 14
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.º 15
0
// MÉTODO ContentRDF :: createAction
int
ContentRDF::
createAction(string act, string actor, vector<string> arguments, string &content)
{

  vector<string>::iterator it;
  int errorCode = 0;

  try
    {
      // Inicialización del sistema.
      XMLPlatformUtils::Initialize();
    }
  
  catch(const XMLException& toCatch)
    {
      char *pMsg = XMLString::transcode(toCatch.getMessage());
      XERCES_STD_QUALIFIER cerr << "Error al inicializar xerces-c.\n"
				<< "  Mensaje de excepción:"
				<< pMsg;
      XMLString::release(&pMsg);
      return 1;
    }// Fin catch

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

  if (impl != NULL) {
    
    try
      {

	// *** rdf:RDF es la raíz del mensaje.
	DOMDocument *action = impl->createDocument(0, X("RDF"), 0);
	action->setEncoding(X("UTF-8"));

	// *** Comentario inicial.
	//action->createComment(X("<?xml version=\"1.0\" standalone=\"no\">"));
	//action->createComment(X("<!DOCTYPE fipa-message SYSTEM \"aclRep.dtd\">"));
	
	// *** Atributos de rdf:RDF.
	DOMElement* rootElem = action->getDocumentElement();
	rootElem->setAttribute(X("xmlnsrdf"), X("http://www.w3.org/1999/02/22-rdf-syntax.ns#"));
	rootElem->setAttribute(X("xmlnsfipa"), X("http://www.fipa.org/schemas/fipa-rdf0#"));
	
	DOMElement* actionElem = action->createElement(X("Action"));
	rootElem->appendChild(actionElem);
	actionElem->setAttribute(X("ID"), X((actor + "Action").c_str()));
	
	// *** Actor.
	DOMElement* actorElem = action->createElement(X("Actor"));
	actionElem->appendChild(actorElem);
	DOMText* actorText = action->createTextNode(X(actor.c_str()));
	actorElem->appendChild(actorText);

	// *** Act.
	DOMElement* actElem = action->createElement(X("Act"));
	actionElem->appendChild(actElem);
	DOMText* actText = action->createTextNode(X(act.c_str()));
	actElem->appendChild(actText);

	// *** Arguments.
	DOMElement* argumentsElem = action->createElement(X("Argument"));
	actionElem->appendChild(argumentsElem);
	DOMElement* bagElem = action->createElement(X("Bag"));
	argumentsElem->appendChild(bagElem);

	// Lista de argumentos.
	DOMElement* argumentElem;
	DOMText* argumentText;

	for (it = arguments.begin(); it != arguments.end(); it++) {
	  argumentElem = action->createElement(X("Li"));
	  bagElem->appendChild(argumentElem);
	  argumentText = action->createTextNode(X((*it).c_str()));
	  argumentElem->appendChild(argumentText);
	}// Fin for

	// Serialización a través de DOMWriter
	XMLCh tempStr[100];
	XMLString::transcode("LS", tempStr, 99);
	DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(tempStr);
	DOMWriter *theSerializer = ((DOMImplementationLS*)impl)->createDOMWriter();

	// Conversión a string
	XMLCh *buf = theSerializer->writeToString(*action);
	char *salida = XMLString::transcode(buf);
	string s1(salida);
	content = s1;
	
	XMLString::release(&buf);
	XMLString::release(&salida);

	delete theSerializer;

	XMLPlatformUtils::Terminate();

      }// Fin try
    
    catch (const OutOfMemoryException&)
      {
	XERCES_STD_QUALIFIER cerr << "Error debido a falta de memoria." << XERCES_STD_QUALIFIER endl;
	errorCode = 5;
      }// Fin catch
    catch (const DOMException& e)
      {
	XERCES_STD_QUALIFIER cerr << "DOMException en:  " << e.code << XERCES_STD_QUALIFIER endl;
	errorCode = 2;
      }// Fin catch
    catch (...)
      {
	XERCES_STD_QUALIFIER cerr << "Se produjo un error al crear el mensaje ACL." << XERCES_STD_QUALIFIER endl;
	errorCode = 3;
      }// Fin catch

  }// Fin if

  else {
    XERCES_STD_QUALIFIER cerr << "La implementación requerida no está disponible." << XERCES_STD_QUALIFIER endl;
    errorCode = 4;
  }// Fin else
    
  XMLPlatformUtils::Terminate();
  return errorCode;  

}
Exemplo n.º 16
0
void SaveDetectorsGrouping::printToXML(std::map<int, std::vector<detid_t> > groupdetidrangemap, std::string xmlfilename) {

    // 1. Get Instrument information
    Geometry::Instrument_const_sptr instrument = mGroupWS->getInstrument();
    std::string name = instrument->getName();
    g_log.debug() << "Instrument " << name << std::endl;

    // 2. Start document (XML)
    AutoPtr<Document> pDoc = new Document;
    AutoPtr<Element> pRoot = pDoc->createElement("detector-grouping");
    pDoc->appendChild(pRoot);
    pRoot->setAttribute("instrument", name);

    // Set description if was specified by user
    if(mGroupWS->run().hasProperty("Description"))
    {
        std::string description = mGroupWS->run().getProperty("Description")->value();
        pRoot->setAttribute("description", description);
    }

    // 3. Append Groups
    for (std::map<int, std::vector<detid_t> >::iterator it = groupdetidrangemap.begin();
            it != groupdetidrangemap.end(); ++it) {

        // a) Group Node
        int groupid = it->first;
        std::stringstream sid;
        sid << groupid;

        AutoPtr<Element> pChildGroup = pDoc->createElement("group");
        pChildGroup->setAttribute("ID",  sid.str());
        // Set name if was specified by user
        std::string groupNameProp = "GroupName_" + sid.str();
        if(mGroupWS->run().hasProperty(groupNameProp))
        {
            std::string groupName = mGroupWS->run().getProperty(groupNameProp)->value();
            pChildGroup->setAttribute("name", groupName);
        }

        pRoot->appendChild(pChildGroup);

        g_log.debug() << "Group ID = " << groupid << std::endl;

        // b) Detector ID Child Nodes
        std::stringstream ss;

        for (size_t i = 0; i < it->second.size()/2; i ++)
        {
            // i. Generate text value

            bool writedata = true;
            detid_t ist = it->second[i*2];
            detid_t ied = it->second[i*2+1];
            // "a-b" or "a"
            if (ist < ied) {
                ss << ist << "-" << ied;
            } else if (ist == ied) {
                ss << ist;
            } else {
                writedata = false;
                g_log.error() << "Impossible to have this situation!" << std::endl;
                throw std::invalid_argument("Impossible to have this sitaution!");
            }
            // add ","
            if (writedata && i < it->second.size()/2-1) {
                ss << ",";
            }

            g_log.debug() << "Detectors:  " << it->second[i*2] << ", " << it->second[i*2+1] << std::endl;
        } // FOREACH Detectors Range Set


        std::string textvalue = ss.str();

        g_log.debug() << "Detector IDs Node: " << textvalue << std::endl;

        // c) Create element
        AutoPtr<Element> pDetid = pDoc->createElement("detids");
        AutoPtr<Text> pText1 = pDoc->createTextNode(textvalue);
        pDetid->appendChild(pText1);
        pChildGroup->appendChild(pDetid);

    } // FOREACH GroupID

    // 4. Write file
    DOMWriter writer;
    writer.setNewLine("\n");
    writer.setOptions(XMLWriter::PRETTY_PRINT);

    std::ofstream ofs;
    ofs.open(xmlfilename.c_str(), std::fstream::out);

    ofs << "<?xml version=\"1.0\"?>\n";

    writer.writeNode(std::cout, pDoc);
    writer.writeNode(ofs, pDoc);
    ofs.close();

}
Exemplo n.º 17
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
}
Exemplo n.º 18
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.º 19
0
/*!
	\brief It gets a list of DOM nodes containing a protocol, and formats them into _nbPDMLProto structures.

	This function converts each protocol and all its child fields. This function will call the FormatFieldsItem()
	for this purpose.

	\param PDMLDocument The DOMDocument associated to the current PDML packet.

	\return The number of '&lt;proto&gt;' that have been copied in the returned buffer, 
	nbFAILURE if some error occurred.
	The error message is stored in the m_errbuf internal buffer.
*/
int CPDMLReader::FormatProtoItem(DOMDocument *PDMLDocument)
{
DOMNodeList *ProtoList;
XMLCh TempBuffer[NETPDL_MAX_STRING + 1];
unsigned int ProtoNumber;
unsigned int TotNumProto;

	XMLString::transcode(PDML_PROTO, TempBuffer, NETPDL_MAX_STRING);

	// After parsing the '<packet>' fragment, let's list the <proto> contained into it
	ProtoList= PDMLDocument->getElementsByTagName(TempBuffer);

	// Get the number of protocols contained in this packet
	TotNumProto= ProtoList->getLength();

	// Check if the protocol structures allocated previously are enough. If not, let's allocate new structures
	if (TotNumProto >= m_maxNumProto)
	{
		if (UpdateProtoList(&m_maxNumProto, &m_protoList, m_errbuf, sizeof(m_errbuf)) == nbFAILURE)
			return nbFAILURE;
	}

	// Reset the buffer
	m_asciiBuffer.ClearBuffer(false /* resizing not permitted */);

	for (ProtoNumber= 0; ProtoNumber < TotNumProto; ProtoNumber++)
	{
	DOMElement *ProtoItem;

		// Set everything to zero
		memset(m_protoList[ProtoNumber], 0, sizeof(_nbPDMLProto));

		// Update pointer to the packet summary
		m_protoList[ProtoNumber]->PacketSummary= &m_packetSummary;

		// Updates the protocol chain
		if (ProtoNumber >= 1)
		{
			m_protoList[ProtoNumber - 1]->NextProto= m_protoList[ProtoNumber];
			m_protoList[ProtoNumber]->PreviousProto= m_protoList[ProtoNumber - 1];
		}

		ProtoItem= (DOMElement *) ProtoList->item(ProtoNumber);

		// Copies all the attributes of this proto in the new structure
 		if (AppendItemString(ProtoItem, PDML_FIELD_ATTR_NAME,
			&(m_protoList[ProtoNumber]->Name), &m_asciiBuffer, m_errbuf, sizeof(m_errbuf)) == nbFAILURE)
			return nbFAILURE;
 		if (AppendItemString(ProtoItem, PDML_FIELD_ATTR_LONGNAME,
			&(m_protoList[ProtoNumber]->LongName), &m_asciiBuffer, m_errbuf, sizeof(m_errbuf)) == nbFAILURE)
			return nbFAILURE;
		if (AppendItemLong(ProtoItem, PDML_FIELD_ATTR_SIZE,
			&(m_protoList[ProtoNumber]->Size), m_errbuf, sizeof(m_errbuf)) == nbFAILURE)
			return nbFAILURE;
		if (AppendItemLong(ProtoItem, PDML_FIELD_ATTR_POSITION,
			&(m_protoList[ProtoNumber]->Position), m_errbuf, sizeof(m_errbuf)) == nbFAILURE)
			return nbFAILURE;

#ifdef DOM_DEBUG
		// FULVIO This code is still present, because it should be needed in order to solve
		// a bug discovered on Dec 4, 2006
		// See my email in the mailbox
		// 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();

		MemBufFormatTarget myFormTarget;

		theSerializer->writeNode(&myFormTarget, *ProtoItem);

		const XMLByte *Result= myFormTarget.getRawBuffer();

		delete theSerializer;
#endif

		if (ProtoItem->hasChildNodes() )
		{
			if (FormatFieldNodes(ProtoItem->getFirstChild(), m_protoList[ProtoNumber], NULL) == nbFAILURE)
				return nbFAILURE;
		}
	}

	// Update the pointer to the first protocol
	if (TotNumProto > 0)
		m_packetSummary.FirstProto= m_protoList[0];
	else
		m_packetSummary.FirstProto= NULL;

	return (int) ProtoNumber;
}
Exemplo n.º 20
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.º 21
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.º 22
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.º 23
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();
}
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.º 25
0
std::string MDHistoDimension::toXMLString() const {
  using namespace Poco::XML;

  // Create the root element for this fragment.
  AutoPtr<Document> pDoc = new Document;
  AutoPtr<Element> pDimensionElement = pDoc->createElement("Dimension");
  pDoc->appendChild(pDimensionElement);

  // Set the id.
  AutoPtr<Attr> idAttribute = pDoc->createAttribute("ID");
  idAttribute->setNodeValue(this->getDimensionId());
  pDimensionElement->setAttributeNode(idAttribute);

  // Set the name.
  AutoPtr<Element> nameElement = pDoc->createElement("Name");
  AutoPtr<Text> nameText = pDoc->createTextNode(this->getName());
  nameElement->appendChild(nameText);
  pDimensionElement->appendChild(nameElement);

  // Set the units.
  AutoPtr<Element> unitsElement = pDoc->createElement("Units");
  AutoPtr<Text> unitsText = pDoc->createTextNode(this->getUnits());
  unitsElement->appendChild(unitsText);
  pDimensionElement->appendChild(unitsElement);

  // Set the upper bounds
  AutoPtr<Element> upperBoundsElement = pDoc->createElement("UpperBounds");
  AutoPtr<Text> upperBoundsText = pDoc->createTextNode(
      boost::str(boost::format("%.4f") % this->getMaximum()));
  upperBoundsElement->appendChild(upperBoundsText);
  pDimensionElement->appendChild(upperBoundsElement);

  // Set the lower bounds
  AutoPtr<Element> lowerBoundsElement = pDoc->createElement("LowerBounds");
  AutoPtr<Text> lowerBoundsText = pDoc->createTextNode(
      boost::str(boost::format("%.4f") % this->getMinimum()));
  lowerBoundsElement->appendChild(lowerBoundsText);
  pDimensionElement->appendChild(lowerBoundsElement);

  // Set the number of bins
  AutoPtr<Element> numberOfBinsElement = pDoc->createElement("NumberOfBins");
  AutoPtr<Text> numberOfBinsText = pDoc->createTextNode(
      boost::str(boost::format("%.4d") % this->getNBins()));
  numberOfBinsElement->appendChild(numberOfBinsText);
  pDimensionElement->appendChild(numberOfBinsElement);

  // Provide upper and lower limits for integrated dimensions.
  if (this->getIsIntegrated()) {
    AutoPtr<Element> integratedElement = pDoc->createElement("Integrated");
    // Set the upper limit
    AutoPtr<Element> upperLimitElement = pDoc->createElement("UpperLimit");
    AutoPtr<Text> upperLimitText = pDoc->createTextNode(boost::str(
        boost::format("%.4f") % this->getMaximum())); // Dimension does not yet
                                                      // provide integration
                                                      // ranges.
    upperLimitElement->appendChild(upperLimitText);
    integratedElement->appendChild(upperLimitElement);

    // Set the lower limit
    AutoPtr<Element> lowerLimitElement = pDoc->createElement("LowerLimit");
    AutoPtr<Text> lowerLimitText = pDoc->createTextNode(boost::str(
        boost::format("%.4f") % this->getMinimum())); // Dimension does not yet
                                                      // provide integration
                                                      // ranges.
    lowerLimitElement->appendChild(lowerLimitText);
    integratedElement->appendChild(lowerLimitElement);

    pDimensionElement->appendChild(integratedElement);
  }

  // Create a string representation of the DOM tree.
  std::stringstream xmlstream;
  DOMWriter writer;
  writer.writeNode(xmlstream, pDoc);

  return xmlstream.str().c_str();
}
Exemplo n.º 26
0
const std::string &MDGeometryBuilderXML<CheckDimensionPolicy>::create() const {
  using namespace Poco::XML;
  if (true == m_changed) {
    // Create the root element for this fragment.
    AutoPtr<Document> pDoc = new Document;
    AutoPtr<Element> dimensionSetElement = pDoc->createElement("DimensionSet");
    pDoc->appendChild(dimensionSetElement);

    // Loop through dimensions and generate xml for each.
    std::string dimensionXMLString;

    DimensionContainerType::iterator it = m_vecDimensions.begin();

    for (; it != m_vecDimensions.end(); ++it) {
      dimensionXMLString += (*it)->toXMLString();
    }

    // Pass dimensions to dimension set.
    AutoPtr<Text> percents = pDoc->createTextNode("%s");
    dimensionSetElement->appendChild(percents);

    // x-dimension mapping.
    AutoPtr<Element> xDimensionElement = pDoc->createElement("XDimension");
    AutoPtr<Element> xDimensionIdElement =
        pDoc->createElement("RefDimensionId");
    if (hasXDimension()) {
      std::string xDimensionId = this->m_spXDimension->getDimensionId();
      AutoPtr<Text> idXText = pDoc->createTextNode(xDimensionId);
      xDimensionIdElement->appendChild(idXText);
    }
    xDimensionElement->appendChild(xDimensionIdElement);
    dimensionSetElement->appendChild(xDimensionElement);

    // y-dimension mapping.
    AutoPtr<Element> yDimensionElement = pDoc->createElement("YDimension");
    AutoPtr<Element> yDimensionIdElement =
        pDoc->createElement("RefDimensionId");
    if (hasYDimension()) {
      std::string yDimensionId = this->m_spYDimension->getDimensionId();
      AutoPtr<Text> idYText = pDoc->createTextNode(yDimensionId);
      yDimensionIdElement->appendChild(idYText);
    }
    yDimensionElement->appendChild(yDimensionIdElement);
    dimensionSetElement->appendChild(yDimensionElement);

    // z-dimension mapping.
    AutoPtr<Element> zDimensionElement = pDoc->createElement("ZDimension");
    AutoPtr<Element> zDimensionIdElement =
        pDoc->createElement("RefDimensionId");
    if (hasZDimension()) {
      std::string zDimensionId = this->m_spZDimension->getDimensionId();
      AutoPtr<Text> idZText = pDoc->createTextNode(zDimensionId);
      zDimensionIdElement->appendChild(idZText);
    }
    zDimensionElement->appendChild(zDimensionIdElement);
    dimensionSetElement->appendChild(zDimensionElement);

    // t-dimension mapping.
    AutoPtr<Element> tDimensionElement = pDoc->createElement("TDimension");
    AutoPtr<Element> tDimensionIdElement =
        pDoc->createElement("RefDimensionId");
    if (hasTDimension()) {
      std::string tDimensionId = this->m_spTDimension->getDimensionId();
      AutoPtr<Text> idTText = pDoc->createTextNode(tDimensionId);
      tDimensionIdElement->appendChild(idTText);
    }
    tDimensionElement->appendChild(tDimensionIdElement);
    dimensionSetElement->appendChild(tDimensionElement);

    std::stringstream xmlstream;
    DOMWriter writer;
    writer.writeNode(xmlstream, pDoc);

    m_lastResult = boost::str(boost::format(xmlstream.str().c_str()) %
                              dimensionXMLString.c_str());
    m_changed = false;
  }
  return m_lastResult;
}
Exemplo n.º 27
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.º 28
0
/**
 * save XML grouping file
 */
void saveGroupingTabletoXML(Ui::MuonAnalysis& m_uiForm, const std::string& filename)
{
  std::ofstream outFile(filename.c_str());
  if (!outFile)
  {
    throw Mantid::Kernel::Exception::FileError("Unable to open file:", filename);
  }

  DOMWriter writer;
  writer.setNewLine("\n");
  writer.setOptions(XMLWriter::PRETTY_PRINT);

  Poco::XML::Document* mDoc = new Document();
  Element* rootElem = mDoc->createElement("detector-grouping");
  rootElem->setAttribute("description", m_uiForm.groupDescription->text().toStdString());
  mDoc->appendChild(rootElem);

  // loop over groups in table

  std::vector<int> groupToRow;
  whichGroupToWhichRow(m_uiForm, groupToRow);

  int num = static_cast<int>(groupToRow.size());
  for (int i = 0; i < num; i++)
  {
    Element* gElem = mDoc->createElement("group");
    gElem->setAttribute("name", m_uiForm.groupTable->item(groupToRow[i],0)->text().toStdString());
    rootElem->appendChild(gElem);
    Element* idsElem = mDoc->createElement("ids");
    idsElem->setAttribute("val", m_uiForm.groupTable->item(groupToRow[i],1)->text().toStdString());
    gElem->appendChild(idsElem);
  }

  // loop over pairs in pair table

  num = m_uiForm.pairTable->rowCount();
  for (int i = 0; i < num; i++)
  {
    QTableWidgetItem *itemName = m_uiForm.pairTable->item(i,0);
    if (!itemName)
      break;
    if ( itemName->text().isEmpty() )
      break;
    QTableWidgetItem *itemAlpha = m_uiForm.pairTable->item(i,3);
    if (!itemAlpha)
      break;
    if ( itemAlpha->text().isEmpty() )
      break;

    QComboBox* qw1 = static_cast<QComboBox*>(m_uiForm.pairTable->cellWidget(i,1));
    QComboBox* qw2 = static_cast<QComboBox*>(m_uiForm.pairTable->cellWidget(i,2));

    Element* gElem = mDoc->createElement("pair");
    gElem->setAttribute("name", itemName->text().toStdString());
    rootElem->appendChild(gElem);
    Element* fwElem = mDoc->createElement("forward-group");
    fwElem->setAttribute("val", qw1->currentText().toStdString());
    gElem->appendChild(fwElem);
    Element* bwElem = mDoc->createElement("backward-group");
    bwElem->setAttribute("val", qw2->currentText().toStdString());
    gElem->appendChild(bwElem);
    Element* alphaElem = mDoc->createElement("alpha");
    alphaElem->setAttribute("val", itemAlpha->text().toStdString());
    gElem->appendChild(alphaElem);
  } 

  // save default

  Element* gElem = mDoc->createElement("default");
  gElem->setAttribute("name", m_uiForm.frontGroupGroupPairComboBox->currentText().toStdString());
  rootElem->appendChild(gElem);

  writer.writeNode(outFile, mDoc);
}
Exemplo n.º 29
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();   
}