/**
    Execution method to run the extraction.
    @return implicit function if one could be found, or a NullImplicitFunction.
    */
    Mantid::Geometry::MDImplicitFunction* vtkDataSetToImplicitFunction::execute()
    {
      using Mantid::Geometry::NullImplicitFunction;
      using Mantid::Geometry::MDGeometryXMLDefinitions;
      std::unique_ptr<Mantid::Geometry::MDImplicitFunction> function =
          Mantid::Kernel::make_unique<NullImplicitFunction>();

      FieldDataToMetadata convert;
      std::string xmlString = convert(m_dataset->GetFieldData(), XMLDefinitions::metaDataId()); 
      if (false == xmlString.empty())
      {
        Poco::XML::DOMParser pParser;
        Poco::AutoPtr<Poco::XML::Document> pDoc = pParser.parseString(xmlString);
        Poco::XML::Element* pRootElem = pDoc->documentElement();
        Poco::XML::Element* functionElem = pRootElem->getChildElement(MDGeometryXMLDefinitions::functionElementName());
        if(NULL != functionElem)
        {
          auto existingFunction =
              std::unique_ptr<Mantid::Geometry::MDImplicitFunction>(
                  Mantid::API::ImplicitFunctionFactory::Instance()
                      .createUnwrapped(functionElem));
          function.swap(existingFunction);
        }
      }
      return function.release();
    }
示例#2
0
 ImplicitFunctionParameterParser* ImplicitFunctionParameterParserFactoryImpl::createImplicitFunctionParameterParserFromXML(Poco::XML::Element* parametersElement) const
 {
   if(parametersElement->localName() != "ParameterList")
   {
     throw std::runtime_error("Expected passed element to be ParameterList.");
   }
   Poco::XML::NodeList* parameters = parametersElement->getElementsByTagName("Parameter");
   ImplicitFunctionParameterParser* paramParser = NULL;
   ImplicitFunctionParameterParser* nextParser = NULL;
   for(unsigned long i = 0 ; i < parameters->length(); i++)
   {
     Poco::XML::Element* parameter = dynamic_cast<Poco::XML::Element*>(parameters->item(i));
     std::string paramParserName = parameter->getChildElement("Type")->innerText() + "Parser"; //Append parser to the name. Fixed convention
     ImplicitFunctionParameterParser* childParamParser = this->createUnwrapped(paramParserName);
     if(paramParser != NULL)
     {
       nextParser->setSuccessorParser(childParamParser);
     }
     else
     {
       paramParser = childParamParser;
     }
     nextParser = childParamParser;
   }
   return paramParser;
 }
示例#3
0
/* Validate all of the pipelines in the given config file.
* This method does some basic parsing of the config file to learn
* about the various pipelines that exist in the file.
*/
bool ValidatePipeline::isValid(const char *a_configPath) const
{
    bool failed = false;

    std::ifstream in(a_configPath);
    if (!in) {
        fprintf(stdout, "Error opening pipeline config file: %s\n", a_configPath);
    } else {
        try {
            Poco::XML::InputSource src(in);
            Poco::XML::DOMParser parser;
            // basic parsing
            Poco::AutoPtr<Poco::XML::Document> xmlDoc = parser.parse(&src);

            // must have at least one pipeline element
            Poco::AutoPtr<Poco::XML::NodeList> pipelines =
                xmlDoc->getElementsByTagName(TskPipelineManager::PIPELINE_ELEMENT);

            if (pipelines->length() == 0) {
                fprintf(stdout, "No pipelines found in config file.\n");
            } else {
                // parse all pipelines in the config file
                for (unsigned long i = 0; i < pipelines->length(); i++)
                {
                    Poco::XML::Node * pNode = pipelines->item(i);
                    Poco::XML::Element* pElem = dynamic_cast<Poco::XML::Element*>(pNode);
                    Poco::XML::DOMWriter writer;
                    std::ostringstream pipelineXml;
                    writer.writeNode(pipelineXml, pNode);

                    std::string pipelineType = pElem->getAttribute(TskPipelineManager::PIPELINE_TYPE_ATTRIBUTE);

                    TskPipeline * pipeline = 0;
                    if (pipelineType == TskPipelineManager::FILE_ANALYSIS_PIPELINE_STR)
                        pipeline = new TskFileAnalysisPipeline();
                    else if (pipelineType == TskPipelineManager::REPORTING_PIPELINE_STR)
                        pipeline = new TskReportPipeline();
                    else {
                        fprintf(stdout, "Unsupported pipeline type: %s\n", pipelineType.c_str());
                        failed = true;
                        continue;
                    }

                    try {
                        pipeline->validate(pipelineXml.str());
                    } catch (...) {
                        fprintf(stdout, "Error parsing pipeline: %s\n", pElem->getAttribute(TskPipelineManager::PIPELINE_TYPE_ATTRIBUTE).c_str());
                        failed = true;
                    }
                    delete pipeline;
                }
            }
        } catch (Poco::XML::SAXParseException& ex) {
            fprintf(stderr, "Error parsing pipeline config file: %s (%s)\n", a_configPath, ex.what());
        }
    }

    // If any of the pipelines failed validation we return false
    return failed ? false : true;
}
void XMLConfiguration::removeRaw(const std::string& key)
{
	Poco::XML::Node* pNode = findNode(key);

	if (pNode)
	{
		if (pNode->nodeType() == Poco::XML::Node::ELEMENT_NODE)
		{
			Poco::XML::Node* pParent = pNode->parentNode();
			if (pParent)
			{
				pParent->removeChild(pNode);
			}
		}
		else if (pNode->nodeType() == Poco::XML::Node::ATTRIBUTE_NODE)
		{
			Poco::XML::Attr* pAttr = dynamic_cast<Poco::XML::Attr*>(pNode);
			Poco::XML::Element* pOwner = pAttr->ownerElement();
			if (pOwner)
			{
				pOwner->removeAttributeNode(pAttr);
			}
		}
	}
}
示例#5
0
bool ofXml::removeAttributes(const string& path) 
{
    Poco::XML::Element *e;
    if(element) {
        if(path.find("[@") == string::npos) {
            // we need to create a proper path
            string attributePath = "[@" + path + "]";
            e = (Poco::XML::Element*) element->getNodeByPath(attributePath);
        } else {
            e = (Poco::XML::Element*) element->getNodeByPath(path);
        }

    } else {
        ofLogWarning("ofXml") << "clearAttributes(): no element set yet";
        return false;
    }
    
    if(e) {
        Poco::XML::NamedNodeMap *map = e->attributes();
        
        for(unsigned long i = 0; i < map->length(); i++) {
            e->removeAttribute(map->item(i)->nodeName());
        }
        
        map->release();
        return true;
    }
    return false;
}
示例#6
0
bool ofXml::setToSibling()
{
    Poco::XML::Element *node;
    if(element) {
        node = (Poco::XML::Element*) element->nextSibling();
    } else {
        ofLogWarning("ofXml") << "setToSibling() << no element set yet";
        return false;
    }

	/* If we get NULL for node, then we do not have a sibling.
	   We can only savely check the type on a non-Null node (thus
	   avoiding NULL-pointer dereferences). Empty space is treated
	   as a text node and we do not want that. We are also not
	   interessted in comments. If we find a non-TEXT_NODE or
	   non-COMMENT_NODE, we do not look further for a sibling. */
	while(NULL != node){
	  if((node->nodeType() == Poco::XML::Node::TEXT_NODE)
		 || (node->nodeType() == Poco::XML::Node::COMMENT_NODE)) {
		node = (Poco::XML::Element*) node->nextSibling();
	  } else {
		break;
	  }
	}
	// make sure we actually got a sibling
    if(NULL == node) {
        return false;
    }

    // we're cool now
    element = node;
    return true;
}
示例#7
0
 /// Called from constructor to fill live listener name
 void InstrumentInfo::fillLiveData(const Poco::XML::Element* elem)
 {
   // Get the first livedata element (will be NULL if there's none)
   Poco::XML::Element * live = elem->getChildElement("livedata");
   if ( live )
   {
     // Get the name of the listener - empty string will be returned if missing
     m_liveListener = live->getAttribute("listener");
     // Get the host+port. Would have liked to put straight into a Poco::Net::SocketAddress
     // but that tries to contact the given address on construction, which won't always be possible (or scalable)
     m_liveDataAddress = live->getAttribute("address");
     // Warn rather than throw if there are problems with the address
     if ( m_liveDataAddress.empty() )
     {
       g_log.warning() << "No connection details specified for live data listener of " << m_name << "\n";
     }
     // Check for a colon, which would suggest that a host & port are present
     else if ( m_liveDataAddress.find(":") == std::string::npos )
     {
       g_log.warning() << "Live data address for " << m_name << " appears not to have both host and port specified.\n";
     }
   }
   // Apply the facility default listener if none specified for this instrument
   if ( m_liveListener.empty() )
   {
     m_liveListener = m_facility->liveListener();
   }
 }
示例#8
0
/**
 * Parse the runinfo file to find the names of the neutron event files.
 *
 * @param runinfo Runinfo file with full path.
 * @param dataDir Directory where the runinfo file lives.
 * @param eventFilenames vector of all possible event files. This is filled by
 *the algorithm.
 */
void LoadPreNexus::parseRuninfo(const string &runinfo, string &dataDir,
                                vector<string> &eventFilenames) {
  eventFilenames.clear();

  // Create a Poco Path object for runinfo filename
  Poco::Path runinfoPath(runinfo, Poco::Path::PATH_GUESS);
  // Now lets get the directory
  Poco::Path dirPath(runinfoPath.parent());
  dataDir = dirPath.absolute().toString();
  g_log.debug() << "Data directory \"" << dataDir << "\"\n";

  std::ifstream in(runinfo.c_str());
  Poco::XML::InputSource src(in);

  Poco::XML::DOMParser parser;
  Poco::AutoPtr<Poco::XML::Document> pDoc = parser.parse(&src);

  Poco::XML::NodeIterator it(pDoc, Poco::XML::NodeFilter::SHOW_ELEMENT);
  Poco::XML::Node *pNode = it.nextNode(); // root node
  while (pNode) {
    if (pNode->nodeName() == "RunInfo") // standard name for this type
    {
      pNode = pNode->firstChild();
      while (pNode) {
        if (pNode->nodeName() == "FileList") {
          pNode = pNode->firstChild();
          while (pNode) {
            if (pNode->nodeName() == "DataList") {
              pNode = pNode->firstChild();
              while (pNode) {
                if (pNode->nodeName() == "scattering") {
                  Poco::XML::Element *element =
                      static_cast<Poco::XML::Element *>(pNode);
                  eventFilenames.push_back(element->getAttribute("name"));
                }
                pNode = pNode->nextSibling();
              }
            } else // search for DataList
              pNode = pNode->nextSibling();
          }
        } else // search for FileList
          pNode = pNode->nextSibling();
      }
    } else // search for RunInfo
      pNode = pNode->nextSibling();
  }

  // report the results to the log
  if (eventFilenames.size() == 1) {
    g_log.debug() << "Found 1 event file: \"" << eventFilenames[0] << "\"\n";
  } else {
    g_log.debug() << "Found " << eventFilenames.size() << " event files:";
    for (auto &eventFilename : eventFilenames) {
      g_log.debug() << "\"" << eventFilename << "\" ";
    }
    g_log.debug() << "\n";
  }
}
示例#9
0
/// Called from constructor to fill compute resources map
void FacilityInfo::fillComputeResources(const Poco::XML::Element* elem)
{
    Poco::AutoPtr<Poco::XML::NodeList> pNL_compute = elem->getElementsByTagName("computeResource");
    unsigned long n = pNL_compute->length();
    for (unsigned long i = 0; i < n; i++)
    {
        Poco::XML::Element* elem = dynamic_cast<Poco::XML::Element*>(pNL_compute->item(i));
        std::string name = elem->getAttribute("name");

        m_computeResources.insert( std::make_pair(name, boost::shared_ptr<RemoteJobManager>(new RemoteJobManager(elem))));
    }
}
示例#10
0
  /** Static method that sets the data inside this BoxController from an XML string
   *
   * @param xml :: string generated by BoxController::toXMLString()
   */
  void BoxController::fromXMLString(const std::string & xml)
  {
    using namespace Poco::XML;
    Poco::XML::DOMParser pParser;
    Poco::AutoPtr<Poco::XML::Document> pDoc = pParser.parseString(xml);
    Poco::XML::Element* pBoxElement = pDoc->documentElement();

    std::string s;
    s = pBoxElement->getChildElement("NumDims")->innerText();
    Strings::convert(s, nd);
    if (nd <= 0 || nd > 20) throw std::runtime_error("BoxController::fromXMLString(): Bad number of dimensions found.");

    size_t ival;
    Strings::convert(pBoxElement->getChildElement("MaxId")->innerText(), ival);
    this->setMaxId(ival);
    Strings::convert(pBoxElement->getChildElement("SplitThreshold")->innerText(), ival);
    this->setSplitThreshold(ival);
    Strings::convert(pBoxElement->getChildElement("MaxDepth")->innerText(), ival);
    this->setMaxDepth(ival);

    s = pBoxElement->getChildElement("SplitInto")->innerText();
    this->m_splitInto = splitStringIntoVector<size_t>(s);

    s = pBoxElement->getChildElement("NumMDBoxes")->innerText();
    this->m_numMDBoxes = splitStringIntoVector<size_t>(s);

    s = pBoxElement->getChildElement("NumMDGridBoxes")->innerText();
    this->m_numMDGridBoxes = splitStringIntoVector<size_t>(s);

    this->calcNumSplit();
  }
示例#11
0
bool ofXml::removeAttribute(const string& path) 
{

    string attributeName, pathToAttribute;

    Poco::XML::Element *e;
    if(element) {
        
        bool hasPath = false;

        // you can pass either /node[@attr] or just attr
        if(path.find("[@") != string::npos)
        {
            int attrBegin = path.find("[@");
            int start = attrBegin + 2;
            int end = path.find("]", start);
            attributeName = path.substr( start, end - start );
            pathToAttribute = path.substr(0, attrBegin);
            hasPath = true;
        }
        else
        {
            attributeName = path;
        }
        
        if(hasPath) {
            e = (Poco::XML::Element*) element->getNodeByPath(pathToAttribute);
        } else {
            e = element;
        }

    } else {
        ofLogWarning("ofXml") << "clearAttributes(): no element set yet";
        return false;
    }
    
    if(e) {
        Poco::XML::NamedNodeMap *map = e->attributes();
        
		for(unsigned long i = 0; i < map->length(); i++) {
            if(map->item(i)->nodeName() == attributeName) {
                e->removeAttribute(map->item(i)->nodeName());
            }
        }
        
        map->release();
        return true;
    }
    return false;
}
void DebugBreakpointManager::SaveState(const Poco::Path& path) const
{
  Poco::XML::Document* doc = new Poco::XML::Document();
  Poco::XML::Element* breakpoints = doc->createElement(BREAKPOINTS_TAG);
  doc->appendChild(breakpoints)->release();

  for (std::set<unsigned long>::const_iterator i = m_ObjectBreakpoints.begin(); i
      != m_ObjectBreakpoints.end(); ++i)
  {
    Poco::XML::Element* objectBreakpoint = doc->createElement(OBJECT_TAG);
    breakpoints->appendChild(objectBreakpoint)->release();
    std::stringstream ss;
    ss << *i;
    objectBreakpoint->setAttribute(ID_ATTR, ss.str());

    const Object* obj = DebugUtil::GetObject(*i);
    if (obj)
    {
      objectBreakpoint->setAttribute(CLASSNAME_ATTR, obj->GetClassName());

    }
  }

  for (Poco::HashMap<int, const Object*>::ConstIterator i =
      m_SmartPointerBreakpoints.begin(); i != m_SmartPointerBreakpoints.end(); ++i)
  {
    Poco::XML::Element* spBreakpoint = doc->createElement(SMARTPOINTER_TAG);
    breakpoints->appendChild(spBreakpoint)->release();
    std::stringstream ss;
    ss << i->first;
    spBreakpoint->setAttribute(ID_ATTR, ss.str());

    const Object* obj = i->second;
    if (i->second)
    {
      spBreakpoint->setAttribute(CLASSNAME_ATTR, obj->GetClassName());
      ss.clear();
      ss << obj->GetTraceId();
      spBreakpoint->setAttribute(OBJECTID_ATTR, ss.str());
    }
  }

  Poco::FileOutputStream writer(path.toString());
  Poco::XML::DOMWriter out;
  out.setOptions(3); //write declaration and pretty print
  out.writeNode(writer, doc);

  doc->release();
}
示例#13
0
    /**
    Execution method to run the extraction.
    @return location string
    */
    std::string vtkDataSetToWsLocation::execute()
    {
      using Mantid::Geometry::MDGeometryXMLDefinitions;
      FieldDataToMetadata convert;
      std::string xmlString = convert(m_dataset->GetFieldData(), XMLDefinitions::metaDataId());

      Poco::XML::DOMParser pParser;
      Poco::XML::Document* pDoc = pParser.parseString(xmlString);
      Poco::XML::Element* pRootElem = pDoc->documentElement();
      Poco::XML::Element* wsLocationElem = pRootElem->getChildElement(MDGeometryXMLDefinitions::workspaceLocationElementName());
      if(wsLocationElem == NULL)
      {
        throw std::runtime_error("The element containing the workspace location must be present.");
      }
      return wsLocationElem->innerText();
    }
Poco::XML::Node* XMLConfiguration::findAttribute(const std::string& name, Poco::XML::Node* pNode, bool create)
{
	Poco::XML::Node* pResult(0);
	Poco::XML::Element* pElem = dynamic_cast<Poco::XML::Element*>(pNode);
	if (pElem)
	{
		pResult = pElem->getAttributeNode(name);
		if (!pResult && create)
		{
			Poco::AutoPtr<Poco::XML::Attr> pAttr = pNode->ownerDocument()->createAttribute(name);
			pElem->setAttributeNode(pAttr);
			return pAttr;
		}
	}
	return pResult;
}
ImplicitFunctionParser *
ImplicitFunctionParserFactoryImpl::createImplicitFunctionParserFromXML(
    Poco::XML::Element *functionElement) const {
    const std::string &name = functionElement->localName();
    if (name != "Function") {
        throw std::runtime_error(
            "Root node must be a Funtion element. Unable to determine parsers.");
    }

    Poco::XML::Element *typeElement = functionElement->getChildElement("Type");
    std::string functionParserName = typeElement->innerText() + "Parser";
    ImplicitFunctionParser *functionParser =
        this->createUnwrapped(functionParserName);

    Poco::XML::Element *parametersElement =
        functionElement->getChildElement("ParameterList");

    // Get the parameter parser for the current function parser and append that to
    // the function parser.
    ImplicitFunctionParameterParser *paramParser =
        Mantid::API::ImplicitFunctionParameterParserFactory::Instance()
        .createImplicitFunctionParameterParserFromXML(parametersElement);
    functionParser->setParameterParser(paramParser);

    Poco::AutoPtr<Poco::XML::NodeList> childFunctions =
        functionElement->getElementsByTagName("Function");
    ImplicitFunctionParser *childParser = nullptr;
    for (unsigned long i = 0; i < childFunctions->length(); i++) {
        // Recursive call to handle nested parameters.
        ImplicitFunctionParser *tempParser = createImplicitFunctionParserFromXML(
                dynamic_cast<Poco::XML::Element *>(childFunctions->item(i)));
        if (i == 0) {
            childParser = tempParser;
            // Add the first child function parser to the parent (composite) directly.
            functionParser->setSuccessorParser(childParser);
        } else {
            // Add all other function parsers are added as successors to those before
            // them in the loop.
            childParser->setSuccessorParser(tempParser);
            childParser = tempParser;
        }
    }

    return functionParser;
}
示例#16
0
bool ofXml::addChild( const string& path )
{
    vector<string> tokens;
    
    if(path.find('/') != string::npos) {
        tokens = tokenize(path, "/");
    }
    
    // is this a tokenized tag?
    if(tokens.size() > 1) 
    {
        // don't 'push' down into the new nodes
        Poco::XML::Element *el = element;
        
        vector<Poco::XML::Element*> toBeReleased;
        
		for(std::size_t i = 0; i < tokens.size(); i++)
        {
            Poco::XML::Element *pe = getPocoDocument()->createElement(tokens.at(i));
            el->appendChild(pe);
            toBeReleased.push_back(pe);
            el = pe;
        }
        
        if(element) {
            element->appendChild(el);
        } else {
            element = el;
        }

        return true;
        
    } else {
        Poco::XML::Element* pe = getPocoDocument()->createElement(path);
        
        if(element) {
            element->appendChild(pe);
        } else {
            document->appendChild(pe);
            element = document->documentElement();
        }
    }
    return true;
}
示例#17
0
/// Called from constructor to fill archive interface names
void FacilityInfo::fillArchiveNames(const Poco::XML::Element *elem) {
  Poco::AutoPtr<Poco::XML::NodeList> pNL_archives =
      elem->getElementsByTagName("archive");
  if (pNL_archives->length() > 1) {
    g_log.error("Facility must have only one archive tag");
    throw std::runtime_error("Facility must have only one archive tag");
  } else if (pNL_archives->length() == 1) {
    Poco::AutoPtr<Poco::XML::NodeList> pNL_interfaces =
        elem->getElementsByTagName("archiveSearch");
    for (unsigned int i = 0; i < pNL_interfaces->length(); ++i) {
      Poco::XML::Element *elem =
          dynamic_cast<Poco::XML::Element *>(pNL_interfaces->item(i));
      std::string plugin = elem->getAttribute("plugin");
      if (!plugin.empty()) {
        m_archiveSearch.push_back(plugin);
      }
    }
  }
}
Poco::XML::Node* XMLConfiguration::findElement(const std::string& attr, const std::string& value, Poco::XML::Node* pNode)
{
	Poco::XML::Node* pRefNode = pNode;
	Poco::XML::Element* pElem = dynamic_cast<Poco::XML::Element*>(pNode);
	if (!(pElem && pElem->getAttribute(attr) == value))
	{
		pNode = pNode->nextSibling();
		while (pNode)
		{
			if (pNode->nodeName() == pRefNode->nodeName())
			{
				pElem = dynamic_cast<Poco::XML::Element*>(pNode);
				if (pElem && pElem->getAttribute(attr) == value) break;
			}
			pNode = pNode->nextSibling();
		}
	}
	return pNode;
}
示例#19
0
bool ofXml::removeContents(const string& path) {
    
    Poco::XML::Element *e;
    if(element) {
        e = (Poco::XML::Element*) element->getNodeByPath(path);
    } else {
        ofLogWarning("ofXml") << "clearContents(): no element set yet";
        return false;
    }
    
    if(e) {
        Poco::XML::NodeList *list = e->childNodes();
        for(unsigned long i = 0; i < list->length(); i++) {
            element->removeChild(list->item(i));
        }
        list->release();
        return true;
    }
    return false;
}
示例#20
0
/** Create the dimension as a MDHistogram dimension.
*/
Mantid::Geometry::MDHistoDimension* IMDDimensionFactory::doCreate() const
{
  using namespace Mantid::Geometry;

  if(m_dimensionXML == NULL)
  {
    throw std::runtime_error("Must provide dimension xml before creation");
  }

  Poco::XML::NamedNodeMap* attributes = m_dimensionXML->attributes();

  //First and only attribute is the dimension id.
  Poco::XML::Node* dimensionId = attributes->item(0);
  std::string id = dimensionId->innerText();

  std::string name = m_dimensionXML->getChildElement("Name")->innerText();
  Poco::XML::Element* unitsElement = m_dimensionXML->getChildElement("Units");
  std::string units = "None";
  if(NULL != unitsElement)
  {
   //Set units if they exist.
   units = unitsElement->innerText();
  }
  double upperBounds = atof(m_dimensionXML->getChildElement("UpperBounds")->innerText().c_str());
  double lowerBounds = atof(m_dimensionXML->getChildElement("LowerBounds")->innerText().c_str());
  unsigned int nBins = atoi(m_dimensionXML->getChildElement("NumberOfBins")->innerText().c_str());
  Poco::XML::Element* integrationXML = m_dimensionXML->getChildElement("Integrated");

  if (NULL != integrationXML)
  {
    double upperLimit = atof(integrationXML->getChildElement("UpperLimit")->innerText().c_str());
    double lowerLimit = atof(integrationXML->getChildElement("LowerLimit")->innerText().c_str());

    //As it is not currently possible to set integration ranges on a MDDimension or MDGeometryDescription, boundaries become integration ranges.
    upperBounds = upperLimit;
    lowerBounds = lowerLimit;
  }

  return new MDHistoDimension(name, id, units, lowerBounds, upperBounds, nBins);
}
示例#21
0
bool ofXml::setValue(const string& path, const string& value)
{
    Poco::XML::Element *e;
    if(element) {
        e = (Poco::XML::Element*) element->getNodeByPath(path);
    } else {
        ofLogWarning("ofXml") << "setValue(): no element set yet";
        return false;
    }
    
    if(!e) {
        ofLogWarning("ofXml") <<  "setValue(): path \"" + path + "\" doesn't exist";
        return false;
    }
    
    if(!e->firstChild()){
    	Poco::XML::Text *node = getPocoDocument()->createTextNode(ofToString(value));
    	e->appendChild(node);
    	node->release();
        return true;
    }

    if(e->firstChild()->nodeType() == Poco::XML::Node::TEXT_NODE) {
        Poco::XML::Text *node = getPocoDocument()->createTextNode(ofToString(value));
        e->replaceChild( (Poco::XML::Node*) node, e->firstChild()); // swap out
        node->release();
        return true;
    }else{
    	return false;
    }
}
示例#22
0
bool ofXml::setToPrevSibling()
{
    Poco::XML::Element *node;
    if(element) {
        node = (Poco::XML::Element*) element->previousSibling();
    } else {
        ofLogWarning("ofXml") << "setToPrevSibling(): no element set yet";
        return false;
    }
    
    // empty space in the XML doc is treated as text nodes. blerg.
    while(node && node->nodeType() == Poco::XML::Node::TEXT_NODE) {
        node = (Poco::XML::Element*) node->previousSibling();
    }
    
    if(!node || node->nodeType() == Poco::XML::Node::TEXT_NODE) {
        return false;
    }

    element = node;
    return true;
}
示例#23
0
    /**
    Execution method to run the extraction.
    @return implicit function if one could be found, or a NullImplicitFunction.
    */
    Mantid::Geometry::MDImplicitFunction* vtkDataSetToImplicitFunction::execute()
    {
      using Mantid::MDAlgorithms::NullImplicitFunction;
      using Mantid::Geometry::MDGeometryXMLDefinitions;
      Mantid::Geometry::MDImplicitFunction* function = new NullImplicitFunction;

      FieldDataToMetadata convert;
      std::string xmlString = convert(m_dataset->GetFieldData(), XMLDefinitions::metaDataId()); 
      if (false == xmlString.empty())
      {
        Poco::XML::DOMParser pParser;
        Poco::XML::Document* pDoc = pParser.parseString(xmlString);
        Poco::XML::Element* pRootElem = pDoc->documentElement();
        Poco::XML::Element* functionElem = pRootElem->getChildElement(MDGeometryXMLDefinitions::functionElementName());
        if(NULL != functionElem)
        {
          delete function;
          function = Mantid::API::ImplicitFunctionFactory::Instance().createUnwrapped(functionElem);
        }
      }
      return function;
    }
/**
 * Set the geometry for the object
 */
void vtkGeometryCacheReader::readCacheForObject(Object *obj) {
  // Get the element corresponding to the name of the object
  std::stringstream objName;
  objName << obj->getName();
  Poco::XML::Element *pEle = getElementByObjectName(objName.str());
  if (pEle == NULL) // Element not found
  {
    g_log.debug("Cache not found for Object with name " + objName.str());
    return;
  }
  // Read the cache from the element
  int noOfTriangles = 0, noOfPoints = 0;
  double *Points;
  int *Faces;
  std::stringstream buff;
  // Read number of points
  buff << pEle->getAttribute("NumberOfPoints");
  buff >> noOfPoints;
  buff.clear();
  // Read number of triangles
  buff << pEle->getAttribute("NumberOfPolys");
  buff >> noOfTriangles;
  buff.clear();

  // Read Points
  Element *pPts = pEle->getChildElement("Points")->getChildElement("DataArray");
  readPoints(pPts, &noOfPoints, &Points);

  // Read Triangles
  Element *pTris = pEle->getChildElement("Polys")->getChildElement("DataArray");
  readTriangles(pTris, &noOfTriangles, &Faces);

  // First check whether Object can be written to the file
  boost::shared_ptr<GeometryHandler> handle = obj->getGeometryHandler();
  handle->setGeometryCache(noOfPoints, noOfTriangles, Points, Faces);
}
示例#25
0
void DebugUtil::SaveState()
{
    Poco::Path path;
    if (!GetPersistencePath(path)) return;

    path.setFileName(DEBUG_UTIL_XML);

    Poco::XML::Document* doc = new Poco::XML::Document();
    Poco::XML::Element* debugutil = doc->createElement(DEBUGUTIL_TAG);
    doc->appendChild(debugutil)->release();

    for (std::set<unsigned int>::const_iterator i = m_TracedObjects.begin();
            i != m_TracedObjects.end(); ++i)
    {
        Poco::XML::Element* traceObject = doc->createElement(TRACEOBJECT_TAG);
        debugutil->appendChild(traceObject)->release();
        std::stringstream ss;
        ss << *i;
        traceObject->setAttribute(ID_ATTR, ss.str());
    }

    for (std::set<std::string>::const_iterator i = m_TracedClasses.begin();
            i != m_TracedClasses.end(); ++i)
    {
        Poco::XML::Element* traceClass = doc->createElement(TRACECLASS_TAG);
        debugutil->appendChild(traceClass)->release();
        traceClass->setAttribute(NAME_ATTR, *i);
    }

    try
    {
        Poco::FileOutputStream writer(path.toString());
        Poco::XML::DOMWriter out;
        out.setOptions(3); //write declaration and pretty print
        out.writeNode(writer, doc);

        doc->release();

        // save BreakpointManager
        path.setFileName(DebugBreakpointManager::BREAKPOINTS_XML);
        GetBreakpointManager()->SaveState(path);
    }
    catch (Poco::FileException& e)
    {
        BERRY_WARN << e.displayText();
    }

}
示例#26
0
svgtiny_code svgtiny_parse(struct svgtiny_diagram *diagram,
		const char *buffer, size_t size, const char *url,
		int viewport_width, int viewport_height)
{
	
    Poco::XML::Document *document;
	//Poco::XML::Element *svg;
    Poco::XML::Element *svg;
	struct svgtiny_parse_state state;
	float x, y, width, height;
	svgtiny_code code;

	assert(diagram);
	assert(buffer);
	assert(url);
    
    std::string str(buffer);
    
    Poco::XML::DOMParser parser;
    document = parser.parseString(str);

    svg = document->documentElement();
    
    //std::cout << svg->localName() << std::endl;
    
	if (!svg)
		return svgtiny_NOT_SVG;
    if (svg->localName().compare("svg") != 0)
		return svgtiny_NOT_SVG;

	/* get graphic dimensions */
	state.diagram = diagram;
	state.document = document;
	state.viewport_width = viewport_width;
	state.viewport_height = viewport_height;
	svgtiny_parse_position_attributes(svg, state, &x, &y, &width, &height);
	diagram->width = width;
	diagram->height = height;

	/* set up parsing state */
	state.viewport_width = width;
	state.viewport_height = height;
	state.ctm.a = 1; /*(float) viewport_width / (float) width;*/
	state.ctm.b = 0;
	state.ctm.c = 0;
	state.ctm.d = 1; /*(float) viewport_height / (float) height;*/
	state.ctm.e = 0; /*x;*/
	state.ctm.f = 0; /*y;*/
	/*state.style = css_base_style;
	state.style.font_size.value.length.value = option_font_size * 0.1;*/
	state.fill = 0x000000;
	state.stroke = svgtiny_TRANSPARENT;
	state.stroke_width = 1;
	state.linear_gradient_stop_count = 0;

	/* parse tree */
	code = svgtiny_parse_svg(svg, state, diagram);

	/* free XML tree */
	//xmlFreeDoc(document);

	return code;
}
示例#27
0
svgtiny_code svgtiny_parse_svg(Poco::XML::Element *svg,
		struct svgtiny_parse_state state, svgtiny_diagram *diagram)
{
	float x, y, width, height;
	Poco::XML::Attr *view_box;
	Poco::XML::Element *child;

	svgtiny_parse_position_attributes(svg, state, &x, &y, &width, &height);
	svgtiny_parse_paint_attributes(svg, &state);
	svgtiny_parse_font_attributes(svg, &state);
    
    view_box = svg->getAttributeNode("viewBox");
    
	if (view_box) {
		//const char *s = (const char *) view_box->children->content;
        const char *s = (const char *) view_box->getValue().c_str();
		float min_x, min_y, vwidth, vheight;
		if (sscanf(s, "%f,%f,%f,%f",
				&min_x, &min_y, &vwidth, &vheight) == 4 ||
				sscanf(s, "%f %f %f %f",
				&min_x, &min_y, &vwidth, &vheight) == 4) {
                    
            // Koki Nomura
            diagram->viewBox_x = min_x;
            diagram->viewBox_y = min_y;
            diagram->viewBox_width = vwidth;
            diagram->viewBox_height = vheight;
                    
            if (state.viewport_width == 0) {
                state.viewport_width = diagram->viewBox_width;
                diagram->width = diagram->viewBox_width;
            }
            if (state.viewport_height == 0) {
                state.viewport_height = diagram->viewBox_height;
                diagram->height = diagram->viewBox_height;
            }
            //--------------
                    
			state.ctm.a = (float) state.viewport_width / vwidth;
			state.ctm.d = (float) state.viewport_height / vheight;
			state.ctm.e += -min_x * state.ctm.a;
			state.ctm.f += -min_y * state.ctm.d;
        }
	}

	svgtiny_parse_transform_attributes(svg, &state);


    // this is how this should work, but it doesn't
    //Poco::XML::NodeIterator it(svg, Poco::XML::NodeFilter::SHOW_ELEMENT | Poco::XML::NodeFilter::SHOW_TEXT);
    //Poco::XML::Node* pNode = it.nextNode();
    //while (pNode)
    
    
    // Note: this should be using the NodeIterator, but it doesn't seem to work as advertised when using
    // a Node as the root for the iterator constructor. Really weird.
    Poco::XML::ChildNodesList *cnl = ( Poco::XML::ChildNodesList *) svg->childNodes();
    int i  = 0, l = cnl->length();
    while( i < l )
    {
    
		svgtiny_code code = svgtiny_OK;
        
        child = (Poco::XML::Element *) cnl->item(i);
        
        //std::cout << child->localName() << std::endl;

        // I think this can't happen?
		if (child->nodeType() == Poco::XML::Element::ELEMENT_NODE) {
			const char *name = (const char *) child->localName().c_str();
            
			if (strcmp(name, "svg") == 0)
				code = svgtiny_parse_svg(child, state, diagram);
			else if (strcmp(name, "g") == 0)
				code = svgtiny_parse_svg(child, state, diagram);
			else if (strcmp(name, "a") == 0)
				code = svgtiny_parse_svg(child, state, diagram);
			else if (strcmp(name, "path") == 0)
				code = svgtiny_parse_path(child, state);
			else if (strcmp(name, "rect") == 0)
				code = svgtiny_parse_rect(child, state);
			else if (strcmp(name, "circle") == 0)
				code = svgtiny_parse_circle(child, state);
			else if (strcmp(name, "ellipse") == 0)
				code = svgtiny_parse_ellipse(child, state);
			else if (strcmp(name, "line") == 0)
				code = svgtiny_parse_line(child, state);
			else if (strcmp(name, "polyline") == 0)
				code = svgtiny_parse_poly(child, state, false);
			else if (strcmp(name, "polygon") == 0)
				code = svgtiny_parse_poly(child, state, true);
            else if (strcmp(name, "text") == 0)
				code = svgtiny_parse_text(child, state);
            
            // not sure about this
        } else if (child->nodeType() == Poco::XML::Element::TEXT_NODE) {
            
            const char *name = (const char *) child->localName().c_str();
            
			if (strcmp(name, "text") == 0)
				code = svgtiny_parse_text(child, state);
		}
        
        //pNode = it.nextNode();
        i++;

		if (code != svgtiny_OK)
			return code;
	}
	return svgtiny_OK;
}
示例#28
0
  /**
   * Reads detctor ids for groups from an XML grouping file, such as one created by the SpatialGrouping algorithm.
   * @param filename :: path and name of input file
   * @throw FileError is there is a problem with the XML file
   */
  void ReadGroupsFromFile::readXMLGroupingFile(const std::string& filename)
  {
    Poco::XML::DOMParser xmlParser;
    Poco::XML::Document* file;
    try
    {
      file = xmlParser.parse(filename);
    }
    catch ( ... )
    {
      throw Kernel::Exception::FileError("Unable to parse file: ", filename);
    }

    Poco::XML::Element* root = file->documentElement();
  
    if ( ! root->hasChildNodes() )
    {
      throw Kernel::Exception::FileError("No root element in XML grouping file: ", filename);
    }

    Poco::XML::NodeList* groups = root->getElementsByTagName("group");

    if ( groups->length() == 0 )
    {
      throw Kernel::Exception::FileError("XML group file contains no group elements:", filename);
    }

    unsigned int nGroups = static_cast<unsigned int>(groups->length());
    for ( unsigned int i = 0; i < nGroups; i++ )
    {
      // Get the "detids" element from the grouping file
      Poco::XML::Element* elem = static_cast<Poco::XML::Element*>(groups->item(i));
      Poco::XML::Element* group = elem->getChildElement("detids");

      if ( ! group )
      {
        throw Mantid::Kernel::Exception::FileError("XML Group File, group contains no <detids> element:", filename);
      }
  
      std::string ids = group->getAttribute("val");

      Poco::StringTokenizer data(ids, ",", Poco::StringTokenizer::TOK_TRIM);

      if ( data.begin() != data.end() )
      {
        for ( Poco::StringTokenizer::Iterator it = data.begin(); it != data.end(); ++it )
        {
          // cast the string to an int
          int detID;
          try
          {
            detID = boost::lexical_cast<int>(*it);
          } catch ( boost::bad_lexical_cast & )
          {
            throw Mantid::Kernel::Exception::FileError("Could cast string to integer in input XML file", filename);
          }
  
          if ( calibration.find(detID) == calibration.end() )
          {
            // add detector to a group
            calibration[detID] = std::pair<int,int>(i+1, 1);
          }
        }
      }
    }

    progress(0.7);
  }
示例#29
0
const bool SoneXML::ParseXML(const std::string &xml)
{
	bool parsed=false;
	Poco::XML::DOMParser dp;

	dp.setEntityResolver(0);

	Initialize();

	try
	{
		Poco::AutoPtr<Poco::XML::Document> doc=dp.parseString(FixCDATA(xml));
		Poco::XML::Element *root=XMLGetFirstChild(doc,"sone");
		Poco::XML::Element *posts=NULL;
		Poco::XML::Element *replies=NULL;
		Poco::XML::Element *txt=NULL;
		Poco::XML::Element *profile=NULL;
		Poco::XML::Element *albums=NULL;

		if(root)
		{
			posts=XMLGetFirstChild(root,"posts");
			replies=XMLGetFirstChild(root,"replies");
			profile=XMLGetFirstChild(root,"profile");
			albums=XMLGetFirstChild(root,"albums");
		}

		if(posts)
		{

			txt=XMLGetFirstChild(posts,"post");
			while(txt)
			{
				std::string id("");
				std::string timestr("");
				Poco::Timestamp::TimeVal timeval;
				Poco::DateTime messagetime;
				std::string messagetext("");

				Poco::XML::Element *el;
				el=XMLGetFirstChild(txt,"id");
				if(el && el->firstChild())
				{
					id=el->firstChild()->getNodeValue();
				}

				el=XMLGetFirstChild(txt,"time");
				if(el && el->firstChild())
				{
					timestr=el->firstChild()->getNodeValue();
					StringFunctions::Convert(timestr,timeval);
					messagetime=Poco::Timestamp(timeval*static_cast<Poco::Timestamp::TimeVal>(1000));
				}

				el=XMLGetFirstChild(txt,"text");
				if(el && el->firstChild())
				{
					messagetext=el->firstChild()->getNodeValue();
				}

				if(id!="" && messagetext!="")
				{
					m_messages.push_back(message(messagetime,id,std::string(""),messagetext));
				}

				txt=XMLGetNextSibling(txt,"post");
			}
		}

		if(replies)
		{

			txt=XMLGetFirstChild(replies,"reply");
			while(txt)
			{
				std::string id("");
				std::string replyto("");
				std::string timestr("");
				Poco::Timestamp::TimeVal timeval;
				Poco::DateTime messagetime;
				std::string messagetext("");

				Poco::XML::Element *el;
				el=XMLGetFirstChild(txt,"id");
				if(el && el->firstChild())
				{
					id=el->firstChild()->getNodeValue();
				}

				el=XMLGetFirstChild(txt,"post-id");
				if(el && el->firstChild())
				{
					replyto=el->firstChild()->getNodeValue();
				}

				el=XMLGetFirstChild(txt,"time");
				if(el && el->firstChild())
				{
					timestr=el->firstChild()->getNodeValue();
					StringFunctions::Convert(timestr,timeval);
					messagetime=Poco::Timestamp(timeval*static_cast<Poco::Timestamp::TimeVal>(1000));
				}

				el=XMLGetFirstChild(txt,"text");
				if(el && el->firstChild())
				{
					messagetext=el->firstChild()->getNodeValue();
				}

				if(id!="" && messagetext!="")
				{
					m_messages.push_back(message(messagetime,id,replyto,messagetext));
				}

				txt=XMLGetNextSibling(txt,"reply");
			}

		}

		if(profile)
		{
			std::string avatarid("");
			Poco::XML::Element *avatar=XMLGetFirstChild(profile,"avatar");
			if(avatar && avatar->firstChild() && avatar->firstChild()->getNodeValue()!="")
			{
				std::string avatarid=avatar->firstChild()->getNodeValue();
				if(albums)
				{
					Poco::XML::Element *album=XMLGetFirstChild(albums,"album");
					while(album)
					{
						Poco::XML::Element *images=XMLGetFirstChild(album,"images");
						if(images)
						{
							Poco::XML::Element *image=XMLGetFirstChild(images,"image");
							while(image)
							{
								Poco::XML::Element *imid=XMLGetFirstChild(image,"id");
								if(imid && imid->firstChild())
								{
									if(imid->firstChild()->getNodeValue()==avatarid)
									{
										Poco::XML::Element *key=XMLGetFirstChild(image,"key");
										if(key && key->firstChild())
										{
											m_avatar=key->firstChild()->getNodeValue();
										}
									}
								}
								image=XMLGetNextSibling(image,"image");
							}
						}
						album=XMLGetNextSibling(album,"album");
					}
				}
			}
		}

		parsed=true;

	}
	catch(...)
	{
	}

	return parsed;

}
示例#30
0
svgtiny_code svgtiny_parse(svgInfo &info,struct svgtiny_diagram *diagram, const char *buffer,int viewport_width, int viewport_height){
	
    Poco::XML::Document *document;
    Poco::XML::Element *svg;
	struct svgtiny_parse_state state;
	float x, y, width, height;
	svgtiny_code code;

    
    
    
	assert(diagram);
	assert(buffer);

    
    string rawXMLstring(buffer);
    
    //info.rawXML = rawXMLstring;
    
    //parser is statically allocated
    Poco::XML::DOMParser parser;
    
    /*
     Why does this upset the internal SVG parser?
     */
    //parser.setFeature(Poco::XML::XMLReader::FEATURE_NAMESPACES, false);
    
    document = parser.parseString(rawXMLstring);
    

    svg = document->documentElement();
    
    
    
    //std::cout << svg->localName() << std::endl;
    
	if (!svg){
		code = svgtiny_NOT_SVG;
        return code;
    }else if(svg->localName().compare("svg") != 0){
		code= svgtiny_NOT_SVG;
        return code;
    }else{
    
    
	/* get graphic dimensions */
	state.diagram = diagram;
	state.document = document;
	state.viewport_width = viewport_width;
	state.viewport_height = viewport_height;
	svgtiny_parse_position_attributes(svg, state, &x, &y, &width, &height);
	diagram->width = width;
	diagram->height = height;

	/* set up parsing state */
	state.viewport_width = width;
	state.viewport_height = height;
	state.ctm.a = 1; /*(float) viewport_width / (float) width;*/
	state.ctm.b = 0;
	state.ctm.c = 0;
	state.ctm.d = 1; /*(float) viewport_height / (float) height;*/
	state.ctm.e = 0; /*x;*/
	state.ctm.f = 0; /*y;*/
	/*state.style = css_base_style;
	state.style.font_size.value.length.value = option_font_size * 0.1;*/
	state.fill = 0x000000;
	state.stroke = svgtiny_TRANSPARENT;
	state.stroke_width = 1;
	state.linear_gradient_stop_count = 0;
        
        
        //borg
    state.info = &info;

	/* parse tree */

    ofPtr<svgNode> rootnode(new svgNode());
    rootnode->type = SVG_TAG_TYPE_DOCUMENT;
    info.rootnode = rootnode;
        
        
        
        //store root svg info
        
        info.width = ofToString(svg->getAttribute("width").c_str());
        info.height = ofToString(svg->getAttribute("height").c_str());
        info.x = ofToString(svg->getAttribute("x").c_str());
        info.y = ofToString(svg->getAttribute("y").c_str());
        info.viewbox = ofToString(svg->getAttribute("viewBox").c_str());
        info.id = ofToString(svg->getAttribute("id").c_str());
        info.xmlns = ofToString(svg->getAttribute("xmlns").c_str());
        info.version = ofToString(svg->getAttribute("version").c_str());
        info.preserveAspectRatio = ofToString(svg->getAttribute("preserveAspectRatio").c_str());
               
        
	code = svgtiny_parse_svg(info,svg, state,rootnode);

    }
    
        
    
	/* free XML tree */
	//xmlFreeDoc(document);
    
    
    //return without namespace
    //parser.setFeature(Poco::XML::XMLReader::FEATURE_NAMESPACES, false);
    //document = parser.parseString(rawXMLstring);

	return code;
}