Пример #1
1
Poco::AutoPtr<Poco::XML::Document> Twitter::invoke(const std::string& httpMethod, const std::string& twitterMethod, Poco::Net::HTMLForm& form)
{
    // Create the request URI.
    // We use the XML version of the Twitter API.
    Poco::URI uri(_uri + twitterMethod + ".xml");
    std::string path(uri.getPath());

    Poco::Net::HTTPClientSession session(uri.getHost(), uri.getPort());
    Poco::Net::HTTPRequest req(httpMethod, path, Poco::Net::HTTPMessage::HTTP_1_1);

    // Add username and password (HTTP basic authentication) to the request.
    Poco::Net::HTTPBasicCredentials cred(_username, _password);
    cred.authenticate(req);

    // Send the request.
    form.prepareSubmit(req);
    std::ostream& ostr = session.sendRequest(req);
    form.write(ostr);

    // Receive the response.
    Poco::Net::HTTPResponse res;
    std::istream& rs = session.receiveResponse(res);

    // Create a DOM document from the response.
    Poco::XML::DOMParser parser;
    parser.setFeature(Poco::XML::DOMParser::FEATURE_FILTER_WHITESPACE, true);
    parser.setFeature(Poco::XML::XMLReader::FEATURE_NAMESPACES, false);
    Poco::XML::InputSource source(rs);
    Poco::AutoPtr<Poco::XML::Document> pDoc = parser.parse(&source);

    // If everything went fine, return the XML document.
    // Otherwise look for an error message in the XML document.
    if (res.getStatus() == Poco::Net::HTTPResponse::HTTP_OK)
    {
        return pDoc;
    }
    else
    {
        std::string error(res.getReason());
        Poco::AutoPtr<Poco::XML::NodeList> pList = pDoc->getElementsByTagName("error");
        if (pList->length() > 0)
        {
            error += ": ";
            error += pList->item(0)->innerText();
        }
        throw Poco::ApplicationException("Twitter Error", error);
    }
}
Пример #2
0
    void Mapper::LoadInputMappings(const std::string &file)
    {
        if (boost::filesystem::exists(file) == false)
        {
            InputModuleOIS::LogInfo("Input mappings file not found, using default mappings.");

            Export(file);
        } else
        {
            InputModuleOIS::LogInfo("Loading input mappings from file " + file + "...");
            try
            {
                Poco::XML::InputSource source(file);
                Poco::XML::DOMParser parser;
                Poco::XML::AutoPtr<Poco::XML::Document> document = parser.parse(&source);
                
                if (!document.isNull())
                {
                    Poco::XML::Node* node = document->firstChild();
                    if (node)
                    {
                        LoadInputMappings(node);
                    }
                }
                else
                {
                    throw Exception("Failed to parse xml document.");
                }
            } catch (std::exception &e)
            {
                InputModuleOIS::LogInfo(e.what());
                InputModuleOIS::LogInfo("Failed to parse input mappings file, using default mappings.");
            }
        }
    }
Пример #3
0
XmlHandler::XmlHandler(std::string filename) {

  std::ifstream in(filename);
  Poco::XML::InputSource src(in);
  Poco::XML::DOMParser parser;
  pDoc = parser.parse(&src);
}
Пример #4
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;
}
Пример #5
0
/**Set the xml string from which the dimension will be generated.
 @param dimensionXMLString : xml string to generate the dimension from.
*/
void IMDDimensionFactory::setXMLString(const std::string& dimensionXMLString)
{
  Poco::XML::DOMParser pParser;
  Poco::XML::Document* pDoc = pParser.parseString(dimensionXMLString);
  Poco::XML::Element* pDimensionElement = pDoc->documentElement();
  m_dimensionXML = pDimensionElement;
}
    /**
    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();
    }
Пример #7
0
//---------------------------------------------------------
bool ofXml::loadFromBuffer( const string& buffer )
{
    Poco::XML::DOMParser parser;
    
    // release and nullptr out if we already have a document
    if(document) {
        document->release();
    }
    
    try {
        document = parser.parseString(buffer);
    	element = (Poco::XML::Element*) document->firstChild();
    	document->normalize();
    	return true;
	} catch( const Poco::XML::SAXException & e ) {
		ofLogError("ofXml") << "parse error: " << e.message();
        document = new Poco::XML::Document;
        element = document->documentElement();
        return false;
    } catch( const exception & e ) {
        short msg = atoi(e.what());
        ofLogError("ofXml") << "parse error: " << DOMErrorMessage(msg);
        document = new Poco::XML::Document;
        element = document->documentElement();
        return false;
    }
}
Пример #8
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();
  }
Пример #9
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";
  }
}
void XMLConfiguration::load(Poco::XML::InputSource* pInputSource)
{
	poco_check_ptr (pInputSource);
	
	Poco::XML::DOMParser parser;
	parser.setFeature(Poco::XML::XMLReader::FEATURE_NAMESPACES, false);
	parser.setFeature(Poco::XML::DOMParser::FEATURE_FILTER_WHITESPACE, true);
	Poco::XML::AutoPtr<Poco::XML::Document> pDoc = parser.parse(pInputSource);
	load(pDoc);
}
Пример #11
0
void Configure::loadChannelList(void)
{
    std::ifstream in(SystemInfo::instance().getExecutePath() + "\\config\\channelList.xml");
    Poco::XML::InputSource src(in);
    Poco::XML::DOMParser parser;

    try
    {
        Poco::AutoPtr<Poco::XML::Document> pDoc = parser.parse(&src);
        Poco::XML::NodeIterator it(pDoc, Poco::XML::NodeFilter::SHOW_ALL);
        Poco::XML::Node* pNode = it.nextNode();

        static int index = 0;
		std::string channelInfo[3];
        while (pNode)  
        {
            if(pNode->nodeName() == "Row")
            {
                pNode = it.nextNode();
                if(pNode->nodeName() != "#text")
                {
                    continue; //No text node present
                }
                index = 0;
                if(m_encodeChannel == channelInfo[1])
                {
                    // 找到频道对照表
                    m_encodeChannelID = channelInfo[0];
                    m_encodeChannelPrefix = channelInfo[2];
                    LOG(INFO) << "get channel info : ID [" << m_encodeChannelID << "] Prefix[" << m_encodeChannelPrefix << "].";
                    return;
                }
            }
            if(pNode->nodeName() == "Cell")
            {
                pNode = it.nextNode();
                if(pNode->nodeName() != "#text")
                {
                    pNode = it.nextNode();
                    continue; //No text node present
                }
                channelInfo[index++] = pNode->nodeValue();
            }

            pNode = it.nextNode();//指向下一个node
        }
    }
    catch(std::exception& e)
    {
        LOG(ERROR) << "parse channelList xml file error." << e.what() ;
    }
}
Пример #12
0
const bool BoardListXML::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,"BoardList");
		Poco::XML::Element *boardel=NULL;

		boardel=XMLGetFirstChild(root,"Board");
		while(boardel)
		{
			std::string name="";
			std::string description="";

			Poco::XML::Element *txt=XMLGetFirstChild(boardel,"Name");
			if(txt && txt->firstChild())
			{
				name=SanitizeSingleString(txt->firstChild()->getNodeValue());
				StringFunctions::LowerCase(name,name);
			}
			txt=XMLGetFirstChild(boardel,"Description");
			if(txt && txt->firstChild())
			{
				description=SanitizeSingleString(txt->firstChild()->getNodeValue());
			}

			if(name!="" && description!="")
			{
				m_boards.push_back(board(name,description));
			}

			boardel=XMLGetNextSibling(boardel,"Board");
		}

		parsed=true;

	}
	catch(...)
	{
	}

	return parsed;
}
void ExtensionPointService::handleExtensions(Bundle::ConstPtr pBundle, std::istream& istr, GenericHandler handler, Direction dir)
{
	Poco::XML::DOMParser parser;
	parser.setFeature(Poco::XML::XMLReader::FEATURE_NAMESPACES, false);
	parser.setFeature(Poco::XML::DOMParser::FEATURE_FILTER_WHITESPACE, true);
	Poco::XML::InputSource source(istr);
	AutoPtr<Document> pDoc(parser.parse(&source));
	Node* pRoot = pDoc->firstChild();
	while (pRoot && pRoot->nodeName() != EXTENSIONS_ELEM)
	{
		pRoot = pRoot->nextSibling();
	}
	if (pRoot)
	{
		Node* pNode = (dir == DIR_FORWARD ? pRoot->firstChild() : pRoot->lastChild());
		while (pNode)
		{
			if (pNode->nodeType() == Node::ELEMENT_NODE)
			{
				if (pNode->nodeName() == EXTENSION_ELEM)
				{
					Element* pElem = static_cast<Element*>(pNode);
					const std::string& id = pElem->getAttribute(POINT_ATTR);
					if (!id.empty())
					{
						(this->*handler)(pBundle, id, pElem);
					}
					else
					{
						_logger.error(std::string("No point attribute found in extension element of bundle ")
							+ pBundle->symbolicName());
					}
				}
				else
				{
					_logger.warning(std::string("Unsupported element '")
						+ pNode->nodeName()
						+ "' found in "
						+ EXTENSIONS_XML
						+ " of bundle "
						+ pBundle->symbolicName());
				}
			}

			pNode = (dir == DIR_FORWARD ? pNode->nextSibling() : pNode->previousSibling());
		}
	}
	else throw Poco::NotFoundException("No extensions element found");
}
Пример #14
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();
    }
/*
 * Initalize Poco XML Parser
 */
void LoadGroupXMLFile::initializeXMLParser(const std::string &filename) {
  const std::string xmlText = Kernel::Strings::loadFile(filename);

  // Set up the DOM parser and parse xml file
  Poco::XML::DOMParser pParser;
  try {
    m_pDoc = pParser.parseString(xmlText);
  } catch (Poco::Exception &exc) {
    throw Kernel::Exception::FileError(
        exc.displayText() + ". Unable to parse File:", filename);
  } catch (...) {
    throw Kernel::Exception::FileError("Unable to parse File:", filename);
  }
  // Get pointer to root element
  m_pRootElem = m_pDoc->documentElement();
  if (!m_pRootElem->hasChildNodes()) {
    throw Kernel::Exception::InstrumentDefinitionError(
        "No root element in XML instrument file", filename);
  }
}
Пример #16
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;
    }
Пример #17
0
const bool IdentityIntroductionXML::ParseXML(const std::string &xml)
{
	FreenetSSKKey ssk;
	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,"IdentityIntroduction");
		Poco::XML::Element *txt=NULL;

		txt=XMLGetFirstChild(root,"Identity");
		if(txt)
		{
			if(txt->firstChild())
			{
				m_identity=SanitizeSingleString(txt->firstChild()->getNodeValue());
				if(ssk.TryParse(m_identity)==false)
				{
					return false;
				}
				m_identity=ssk.GetBaseKey();
			}
		}

		parsed=true;
	}
	catch(...)
	{
	}

	return parsed;
}
Пример #18
0
void TskPipeline::initialize(const std::string & pipelineConfig)
{
    if (pipelineConfig.empty())
    {
        throw TskException("TskPipeline::initialize: Pipeline configuration string is empty.");
    }

    try
    {
        Poco::XML::DOMParser parser;
        Poco::AutoPtr<Poco::XML::Document> xmlDoc = parser.parseString(pipelineConfig);

        // Get all Module elements
        Poco::AutoPtr<Poco::XML::NodeList> modules =
            xmlDoc->getElementsByTagName(TskPipeline::MODULE_ELEMENT);

        if (modules->length() == 0)
        {
            LOGWARN(L"TskPipeline::initialize - No modules found in config file.");
            return;
        }

        // Size our list based on the number of modules
        m_modules.resize(modules->length());

        // Iterate through the module elements, make sure they are increasing order
        // we now allow for gaps to make it easier to comment things out.
        int prevOrder = -1;
        for (unsigned int i = 0; i < modules->length(); i++)
        {
            Poco::XML::Node * pNode = modules->item(i);
            Poco::XML::Element* pElem = dynamic_cast<Poco::XML::Element*>(pNode);
            Poco::XML::XMLString orderStr = pElem->getAttribute(TskPipeline::MODULE_ORDER_ATTR);
            if (orderStr == "") {
                throw TskException("TskPipeline::initialize: Module order missing.");
            }
            int order;
            try
            {
                order = Poco::NumberParser::parse(orderStr);
            } catch (Poco::SyntaxException ex)
            {
                std::stringstream msg;
                msg << "TskPipeline::initialize - Module order must a decimal number. Got " << orderStr.c_str();
                throw TskException(msg.str());
            }
            if (order <= prevOrder)
            {
                std::stringstream msg;
                msg << "TskPipeline::initialize - Expecting order bigger than " << prevOrder << ", got " << order;
                throw TskException(msg.str());
            }
            prevOrder = order;
        }

        // Iterate through the module elements creating a new Module for each one
        m_modules.clear();
        for (unsigned int i = 0; i < modules->length(); i++)
        {
            Poco::XML::Node * pNode = modules->item(i);
            Poco::XML::Element* pElem = dynamic_cast<Poco::XML::Element*>(pNode);

            if (!pElem)
                continue;

            // Create a new module
            TskModule * pModule = createModule(pElem);

            if (pModule == NULL)
            {
                throw TskException("TskPipeline::initialize - Module creation failed.");
            }

            if (m_loadDll)
            {
                TskImgDB& imgDB = TskServices::Instance().getImgDB();

                // Insert into Modules table
                int moduleId = 0;
                if (imgDB.addModule(pModule->getName(), pModule->getDescription(), moduleId))
                {
                    std::stringstream errorMsg;
                    errorMsg << "TskPipeline::initialize - Failed to insert into Modules table. "
                             << " module name=" << pModule->getName() ;
                    throw TskException(errorMsg.str());
                }
                else
                {
                    pModule->setModuleId(moduleId);
                    m_moduleNames.insert(std::make_pair(moduleId, pModule->getName()));
                    m_moduleExecTimes.insert(std::make_pair(moduleId, Poco::Timespan()));
                }
                bool duplicate = false;
                for (std::vector<TskModule*>::iterator it = m_modules.begin(); it != m_modules.end(); it++) {
                    if ((*it)->getModuleId() == pModule->getModuleId()) {
                        duplicate = true;
                        std::stringstream msg;
                        msg << "TskPipeline::initialize - " << pModule->getName() << " is a duplicate module. " <<
                            "The duplicate will not be added to the pipeline";
                        throw TskException(msg.str());
                    }
                }
                if (!duplicate)
                    m_modules.push_back(pModule);
            }
        }
    }
    // rethrow this, otherwise it is caught by std::exception and we lose the detail.
    catch (TskException& ex) {
        throw(ex);
    }
    catch (std::exception& ex)
    {
        std::stringstream errorMsg;
        errorMsg << "TskPipeline::initialize - Pipeline initialization failed: " <<ex.what() ;
        throw TskException(errorMsg.str());
    }
}
Пример #19
0
/**
 * @param filenames : List of files to search
 * @param exts : List of extensions to check against
 * @return list of archive locations
 */
std::string SNSDataArchive::getArchivePath(const std::set<std::string>& filenames, const std::vector<std::string>& exts) const
{
  std::set<std::string>::const_iterator iter = filenames.begin();
  std::string filename = *iter;

  //ICAT4 web service take upper case filename such as HYSA_2662
  std::transform(filename.begin(),filename.end(),filename.begin(),toupper);

  std::vector<std::string>::const_iterator iter2 = exts.begin();
  for(; iter2!=exts.end(); ++iter2)
  {
    g_log.debug() << *iter2 << ";";
  }
  g_log.debug()  << "\n";

  std::string baseURL("http://icat.sns.gov:8080/icat-rest-ws/datafile/filename/");

  std::string URL(baseURL + filename);
  g_log.debug() << "URL: " << URL << "\n";

  Poco::URI uri(URL);
  std::string path(uri.getPathAndQuery());

  Poco::Net::HTTPClientSession session(uri.getHost(), uri.getPort());
  Poco::Net::HTTPRequest req(Poco::Net::HTTPRequest::HTTP_GET, path, Poco::Net::HTTPMessage::HTTP_1_1);
  session.sendRequest(req);

  Poco::Net::HTTPResponse res;
  std::istream& rs = session.receiveResponse(res);
  g_log.debug() << "res.getStatus(): " << res.getStatus() << "\n";

  // Create a DOM document from the response.
  Poco::XML::DOMParser parser;
  Poco::XML::InputSource source(rs);
  Poco::AutoPtr<Poco::XML::Document> pDoc = parser.parse(&source);

  std::vector<std::string> locations;

  // If everything went fine, return the XML document.
  // Otherwise look for an error message in the XML document.
  if (res.getStatus() == Poco::Net::HTTPResponse::HTTP_OK)
  {
    std::string location;
    Poco::AutoPtr<Poco::XML::NodeList> pList = pDoc->getElementsByTagName("location");
    for(unsigned long i = 0 ; i < pList->length(); i++)
    {
      location = pList->item(i)->innerText();
      g_log.debug() << "location: " << location << "\n";
      locations.push_back(location);
    }
  }
  else
  {
    std::string error(res.getReason());
    throw Poco::ApplicationException("HTTPRequest Error", error);
  }

  std::vector<std::string>::const_iterator ext = exts.begin();
  for (; ext != exts.end(); ++ext)
  {
    std::string datafile = filename + *ext;
    std::vector<std::string>::const_iterator iter = locations.begin();
    for(; iter!=locations.end(); ++iter)
    {
      if (boost::algorithm::ends_with((*iter), datafile))
      {
        return *iter;
      } // end if
    } // end for iter

  }  // end for ext
  return "";
}
Пример #20
0
const bool MessageXML::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,"Message");
		Poco::XML::Element *txt=NULL;

		txt=XMLGetFirstChild(root,"Date");
		if(txt)
		{
			if(txt->firstChild())
			{
				m_date=SanitizeSingleString(txt->firstChild()->getNodeValue());
			}
		}
		txt=XMLGetFirstChild(root,"Time");
		if(txt)
		{
			if(txt->firstChild())
			{
				m_time=SanitizeSingleString(txt->firstChild()->getNodeValue());
			}
		}
		txt=XMLGetFirstChild(root,"Subject");
		if(txt)
		{
			if(txt->firstChild())
			{
				m_subject=SanitizeSingleString(txt->firstChild()->getNodeValue());
			}
		}
		txt=XMLGetFirstChild(root,"MessageID");
		if(txt)
		{
			if(txt->firstChild())
			{
				m_messageid=SanitizeSingleString(txt->firstChild()->getNodeValue());
			}
		}
		txt=XMLGetFirstChild(root,"ReplyBoard");
		if(txt)
		{
			if(txt->firstChild())
			{
				m_replyboard=SanitizeSingleString(txt->firstChild()->getNodeValue());
				// strip off everything after , in board name
				if(m_replyboard.find(',')!=std::string::npos)
				{
					m_replyboard.erase(m_replyboard.find(','));
				}
				m_replyboard=Board::FixBoardName(m_replyboard);
			}
		}
		txt=XMLGetFirstChild(root,"Body");
		if(txt)
		{
			if(txt->firstChild())
			{
				m_body=txt->firstChild()->getNodeValue();
			}
		}
		Poco::XML::Element *boards=XMLGetFirstChild(root,"Boards");
		if(boards)
		{
			Poco::XML::Element *board=XMLGetFirstChild(boards,"Board");
			while(board)
			{
				if(board->firstChild())
				{
					std::string boardname=SanitizeSingleString(board->firstChild()->getNodeValue());
					// strip off everything after , in board name
					if(boardname.find(',')!=std::string::npos)
					{
						boardname.erase(boardname.find(','));
					}
					boardname=Board::FixBoardName(boardname);
					m_boards.push_back(boardname);
				}
				board=XMLGetNextSibling(board,"Board");
			}
		}
		Poco::XML::Element *inreplyto=XMLGetFirstChild(root,"InReplyTo");
		if(inreplyto)
		{
			Poco::XML::Element *message=XMLGetFirstChild(inreplyto,"Message");
			while(message)
			{
				Poco::XML::Element *orderel=XMLGetFirstChild(message,"Order");
				Poco::XML::Element *messageidel=XMLGetFirstChild(message,"MessageID");
				if(orderel && orderel->firstChild() && messageidel && messageidel->firstChild())
				{
					int order=-1;
					std::string messageid="";

					StringFunctions::Convert(orderel->firstChild()->getNodeValue(),order);
					messageid=messageidel->firstChild()->getNodeValue();

					if(order!=-1 && messageid!="")
					{
						m_inreplyto[order]=messageid;
					}
				}
				message=XMLGetNextSibling(message,"Message");
			}
		}
		Poco::XML::Element *attachments=XMLGetFirstChild(root,"Attachments");
		if(attachments)
		{
			Poco::XML::Element *file=XMLGetFirstChild(attachments,"File");
			while(file)
			{
				Poco::XML::Element *keyel=XMLGetFirstChild(file,"Key");
				Poco::XML::Element *sizeel=XMLGetFirstChild(file,"Size");

				if(keyel && keyel->firstChild() && sizeel && sizeel->firstChild())
				{
					int size=-1;
					std::string key="";
					
					StringFunctions::Convert(sizeel->firstChild()->getNodeValue(),size);
					key=keyel->firstChild()->getNodeValue();

					if(size!=-1 && key!="")
					{
						m_fileattachments.push_back(fileattachment(key,size));
					}
				}

				file=XMLGetNextSibling(file,"File");
			}
		}

		parsed=true;

	}
	catch(Poco::Exception &e)
	{
		m_lasterror="Caught exception - "+e.displayText();
	}
	catch(...)
	{
	}

	return parsed;
}
Пример #21
0
void DebugUtil::RestoreState()
{
    Poco::Path path;
    if (!GetPersistencePath(path)) return;

    path.setFileName(DEBUG_UTIL_XML);

    try
    {
        Poco::XML::DOMParser parser;

        Poco::FileInputStream reader(path.toString());
        Poco::XML::InputSource source(reader);

        //source.setSystemId(baseDir);
        Poco::XML::Document* doc = parser.parse(&source);
        Poco::XML::Element* debugutil = doc->documentElement();

        if (debugutil)
        {
            // restore traced objects
            Poco::XML::NodeList* elementList = debugutil->getElementsByTagName(TRACEOBJECT_TAG);
            for (std::size_t i = 0; i < elementList->length(); i++)
            {
                Poco::XML::Element* elem =
                    dynamic_cast<Poco::XML::Element*> (elementList->item(static_cast<unsigned long>(i)));

                if (!elem->hasAttribute(ID_ATTR)) continue;

                const std::string& attr = elem->getAttribute(ID_ATTR);

                int traceId = 0;
                try
                {
                    traceId = Poco::NumberParser::parse(attr);
                }
                catch (const Poco::SyntaxException& e)
                {
                    BERRY_WARN << e.displayText();
                }

                DebugUtil::TraceObject(traceId);
            }
            elementList->release();

            // restore traced classes
            elementList = debugutil->getElementsByTagName(TRACECLASS_TAG);
            for (std::size_t i = 0; i < elementList->length(); i++)
            {
                Poco::XML::Element* elem =
                    dynamic_cast<Poco::XML::Element*> (elementList->item(static_cast<unsigned long>(i)));

                if (!elem->hasAttribute(NAME_ATTR)) continue;

                const std::string& traceClass = elem->getAttribute(NAME_ATTR);
                if (!traceClass.empty())
                    DebugUtil::TraceClass(traceClass);
            }
            elementList->release();
        }

        doc->release();
    }
    catch (Poco::XML::SAXParseException& e)
    {
        BERRY_WARN << e.displayText();
    }
    catch (Poco::FileNotFoundException&)
    {

    }
    catch (Poco::FileException& e)
    {
        BERRY_WARN << e.displayText();
    }

    // restore BreakpointManager
    path.setFileName(DebugBreakpointManager::BREAKPOINTS_XML);
    GetBreakpointManager()->RestoreState(path);
}
Пример #22
0
bool Configure::load(void)
{
    std::ifstream in(SystemInfo::instance().getExecutePath() + "\\config\\sys.xml");
    Poco::XML::InputSource src(in);
    Poco::XML::DOMParser parser;

    try
    {
        Poco::AutoPtr<Poco::XML::Document> pDoc = parser.parse(&src);
        Poco::XML::NodeIterator it(pDoc, Poco::XML::NodeFilter::SHOW_ALL);
        Poco::XML::Node* pNode = it.nextNode();


        while (pNode)  
        {  
            if(pNode->nodeName() == "EncodChannel")
            {
                pNode = it.nextNode();
                if(pNode->nodeName() != "#text")
                {
                    continue; //No text node present
                }
                m_encodeChannel = pNode->nodeValue();
				Poco::XML::XMLString tt = Poco::XML::toXMLString(m_encodeChannel);
            }

            if(pNode->nodeName() == "InputTSPath")
            {
				getNetWorkPathAttr(pNode->attributes(),&m_inputTSPath);
                pNode = it.nextNode();
                if(pNode->nodeName() != "#text")
                {
                    continue; //No text node present
                }
				m_inputTSPath.path = pNode->nodeValue();
				m_inputTSPath.objectName = "o:";
            }

            if(pNode->nodeName() == "InputXMLPath")
            {
				getNetWorkPathAttr(pNode->attributes(),&m_inputXMLPath);
                pNode = it.nextNode();
                if(pNode->nodeName() != "#text")
                {
                    continue; //No text node present
                }
				m_inputXMLPath.path = pNode->nodeValue();
				m_inputXMLPath.objectName = "p:";
            }

            if(pNode->nodeName() == "OutputTSPath")
            {
				getNetWorkPathAttr(pNode->attributes(),&m_outputTSPath);
                pNode = it.nextNode();
                if(pNode->nodeName() != "#text")
                {
                    continue; //No text node present
                }
				m_outputTSPath.path = pNode->nodeValue();
				m_outputTSPath.objectName = "q:";
            }

            if(pNode->nodeName() == "OutputXMLPath")
            {
				getNetWorkPathAttr(pNode->attributes(),&m_outputXMLPath);
                pNode = it.nextNode();
                if(pNode->nodeName() != "#text")
                {
                    continue; //No text node present
                }
				m_outputXMLPath.path = pNode->nodeValue();
				m_outputXMLPath.objectName = "r:";
            }

            if(pNode->nodeName() == "OutputStream1")
            {
				getOutputStreamAttr(pNode->attributes(),&m_outputStream[0]);
                pNode = it.nextNode();
                if(pNode->nodeName() != "#text")
                {
                    continue; //No text node present
                }
            }
            if(pNode->nodeName() == "OutputStream2")
            {
				getOutputStreamAttr(pNode->attributes(),&m_outputStream[1]);
                pNode = it.nextNode();
                if(pNode->nodeName() != "#text")
                {
                    continue; //No text node present
                }
            }
            if(pNode->nodeName() == "OutputStream3")
            {
				getOutputStreamAttr(pNode->attributes(),&m_outputStream[2]);
                pNode = it.nextNode();
                if(pNode->nodeName() != "#text")
                {
                    continue; //No text node present
                }
            }
            if(pNode->nodeName() == "Storage")
            {
                if(pNode->attributes())//看看是否真有属性  
                {  
                    for(int i = 0 ; i < pNode->attributes()->length() ; i++)
                    {  
                        Poco::XML::Node* attr = pNode->attributes()->item(i);  
			            if(attr->nodeName() == "KeepingDateTime")
			            {
				            m_keepDateTime = boost::lexical_cast<int>(attr->nodeValue());
			            }
                    }//属性结束
                }
                pNode = it.nextNode();
                if(pNode->nodeName() != "#text")
                {
                    continue; //No text node present
                }
            }
			

            //LOG(INFO) << "name : " << pNode->nodeName() ;//取出当前节点的Name  
            //LOG(INFO)<< "value : " << pNode->nodeValue() ;//取出当前节点的Value  
            pNode = it.nextNode();//指向下一个node  
        }
    }
    catch(std::exception& e)
    {
        LOG(ERROR) << "parse xml file error." << e.what() ;
        return false;
    }

    this->loadChannelList();

    if(m_encodeChannel.empty() || m_encodeChannelID.empty() || m_encodeChannelPrefix.empty() ||
		m_inputTSPath.path.empty() || m_inputTSPath.objectName.empty() ||
		m_inputXMLPath.path.empty() || m_inputXMLPath.objectName.empty() ||
		m_outputTSPath.path.empty() || m_outputTSPath.objectName.empty() ||
		m_outputXMLPath.path.empty() || m_outputXMLPath.objectName.empty() ||
		m_outputStream[0].bitrate.empty() || m_outputStream[0].enable.empty() || m_outputStream[0].resolutionRatio.empty() ||
		m_outputStream[1].bitrate.empty() || m_outputStream[1].enable.empty() || m_outputStream[1].resolutionRatio.empty() ||
		m_outputStream[2].bitrate.empty() || m_outputStream[2].enable.empty() || m_outputStream[2].resolutionRatio.empty() ||
        m_keepDateTime == -2)
    {
        return false;
    }

    LOG(INFO) << "EncodChannel [" << Configure::instance().m_encodeChannel << "] ID[" << m_encodeChannelID << "] Prefix[" << m_encodeChannelPrefix << "].";
	LOG(INFO) << "InputTSPath [" << Configure::instance().m_inputTSPath.path << "]" << " as [" << Configure::instance().m_inputTSPath.objectName << "]";
	LOG(INFO) << "InputXMLPath [" << Configure::instance().m_inputXMLPath.path << "]" << " as [" << Configure::instance().m_inputXMLPath.objectName << "]";
	LOG(INFO) << "OutputTSPath [" << Configure::instance().m_outputTSPath.path << "]" << " as [" << Configure::instance().m_outputTSPath.objectName << "]";
	LOG(INFO) << "OutputXMLPath [" << Configure::instance().m_outputXMLPath.path << "]" << " as [" << Configure::instance().m_outputXMLPath.objectName << "]";
	LOG(INFO) << "OutputStream1 [" << Configure::instance().m_outputStream[0].enable << ", " << Configure::instance().m_outputStream[0].bitrate << ", " << Configure::instance().m_outputStream[0].resolutionRatio << "]";
    LOG(INFO) << "OutputStream2 [" << Configure::instance().m_outputStream[1].enable << ", " << Configure::instance().m_outputStream[1].bitrate << ", " << Configure::instance().m_outputStream[1].resolutionRatio << "]";
	LOG(INFO) << "OutputStream3 [" << Configure::instance().m_outputStream[2].enable << ", " << Configure::instance().m_outputStream[2].bitrate << ", " << Configure::instance().m_outputStream[2].resolutionRatio << "]";
	LOG(INFO) << "stoage keep DateTime [" << m_keepDateTime << "].";

    return true;
}
Пример #23
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);
  }
Пример #24
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;
}
void DebugBreakpointManager::RestoreState(const Poco::Path& path)
{
  try
  {
    Poco::XML::DOMParser parser;

    Poco::FileInputStream reader(path.toString());
    Poco::XML::InputSource source(reader);

    //source.setSystemId(baseDir);
    Poco::XML::Document* doc = parser.parse(&source);
    Poco::XML::Element* breakpoints = doc->documentElement();

    if (breakpoints)
    {
      // restore object breakpoints
      Poco::XML::NodeList* elementList = breakpoints->getElementsByTagName(
          OBJECT_TAG);
      for (std::size_t i = 0; i < elementList->length(); i++)
      {
        Poco::XML::Element* elem =
            dynamic_cast<Poco::XML::Element*> (elementList->item(i));

        if (!elem->hasAttribute(ID_ATTR))
          continue;

        const std::string& attr = elem->getAttribute(ID_ATTR);

        int traceId = 0;
        try
        {
          traceId = Poco::NumberParser::parse(attr);
        } catch (const Poco::SyntaxException& e)
        {
          BERRY_WARN << e.displayText();
        }

        DebugUtil::GetBreakpointManager()->AddObjectBreakpoint(traceId);
      }
      elementList->release();

      // restore smartpointer breakpoints
      elementList = breakpoints->getElementsByTagName(SMARTPOINTER_TAG);
      for (std::size_t i = 0; i < elementList->length(); i++)
      {
        Poco::XML::Element* elem =
            dynamic_cast<Poco::XML::Element*> (elementList->item(i));

        if (!elem->hasAttribute(ID_ATTR))
          continue;

        const std::string& attr = elem->getAttribute(ID_ATTR);

        int spId = 0;
        try
        {
          spId = Poco::NumberParser::parse(attr);
        } catch (const Poco::SyntaxException& e)
        {
          BERRY_WARN << e.displayText();
        }

        DebugUtil::GetBreakpointManager()->AddSmartpointerBreakpoint(spId);
      }
      elementList->release();
    }

    doc->release();
  } catch (Poco::XML::SAXParseException& e)
  {
    BERRY_WARN << e.displayText();
  }
  catch (Poco::FileNotFoundException& /*e*/)
  {

  }
  catch (Poco::FileException& e)
  {
    BERRY_WARN << e.displayText();
  }
}
Пример #26
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;

}
Пример #27
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;
}
Пример #28
0
/**
Peforms the processing associated with these transformations.
*/
void MDGeometryXMLParser::execute() {
  Poco::XML::DOMParser pParser;
  Poco::AutoPtr<Poco::XML::Document> pDoc = pParser.parseString(m_xmlToProcess);
  Poco::XML::Element *pRootElem = pDoc->documentElement();
  // Apply root node checking if supplied.
  Poco::XML::Element *geometryXMLElement = nullptr;
  if (!m_rootNodeName.empty()) {
    Poco::XML::Element *temp = pRootElem->getChildElement(m_rootNodeName);
    geometryXMLElement = temp;
    if (geometryXMLElement == nullptr) {
      std::string message =
          "Root node was not found to be the expected value of " +
          m_rootNodeName;
      throw std::runtime_error(message);
    }
  } else {
    // The default is to take the root node to be the geometry xml element.
    geometryXMLElement = pRootElem;
  }

  Poco::AutoPtr<Poco::XML::NodeList> dimensionsXML =
      geometryXMLElement->getElementsByTagName(
          MDGeometryXMLDefinitions::workspaceDimensionElementName());
  size_t nDimensions = dimensionsXML->length();
  VecIMDDimension_sptr vecAllDims(nDimensions);

  ////Extract dimensions
  for (size_t i = 0; i < nDimensions; i++) {
    Poco::XML::Element *dimensionXML = static_cast<Poco::XML::Element *>(
        dimensionsXML->item(static_cast<unsigned long>(i)));
    vecAllDims[i] = createDimension(*dimensionXML);
  }
  VecIMDDimension_sptr vecNonMappedDims = vecAllDims;
  Poco::XML::Element *xDimensionElement = geometryXMLElement->getChildElement(
      MDGeometryXMLDefinitions::workspaceXDimensionElementName());
  std::string xDimId =
      xDimensionElement
          ->getChildElement(
                MDGeometryXMLDefinitions::workspaceRefDimensionElementName())
          ->innerText();
  if (!xDimId.empty()) {
    auto xDimensionIt =
        find_if(vecAllDims.begin(), vecAllDims.end(), findID(xDimId));
    if (xDimensionIt == vecAllDims.end()) {
      throw std::invalid_argument("Cannot determine x-dimension mapping.");
    }
    m_xDimension = *xDimensionIt;
    vecNonMappedDims.erase(std::remove_if(vecNonMappedDims.begin(),
                                          vecNonMappedDims.end(),
                                          findID(xDimId)),
                           vecNonMappedDims.end());
  }

  Poco::XML::Element *yDimensionElement = geometryXMLElement->getChildElement(
      MDGeometryXMLDefinitions::workspaceYDimensionElementName());
  std::string yDimId =
      yDimensionElement
          ->getChildElement(
                MDGeometryXMLDefinitions::workspaceRefDimensionElementName())
          ->innerText();

  if (!yDimId.empty()) {
    auto yDimensionIt =
        find_if(vecAllDims.begin(), vecAllDims.end(), findID(yDimId));
    if (yDimensionIt == vecAllDims.end()) {
      throw std::invalid_argument("Cannot determine y-dimension mapping.");
    }
    m_yDimension = *yDimensionIt;
    vecNonMappedDims.erase(std::remove_if(vecNonMappedDims.begin(),
                                          vecNonMappedDims.end(),
                                          findID(yDimId)),
                           vecNonMappedDims.end());
  }

  Poco::XML::Element *zDimensionElement = geometryXMLElement->getChildElement(
      MDGeometryXMLDefinitions::workspaceZDimensionElementName());
  std::string zDimId =
      zDimensionElement
          ->getChildElement(
                MDGeometryXMLDefinitions::workspaceRefDimensionElementName())
          ->innerText();

  if (!zDimId.empty()) {
    auto zDimensionIt =
        find_if(vecAllDims.begin(), vecAllDims.end(), findID(zDimId));
    if (zDimensionIt == vecAllDims.end()) {
      throw std::invalid_argument("Cannot determine z-dimension mapping.");
    }
    m_zDimension = *zDimensionIt;
    vecNonMappedDims.erase(std::remove_if(vecNonMappedDims.begin(),
                                          vecNonMappedDims.end(),
                                          findID(zDimId)),
                           vecNonMappedDims.end());
  }

  Poco::XML::Element *tDimensionElement = geometryXMLElement->getChildElement(
      MDGeometryXMLDefinitions::workspaceTDimensionElementName());
  std::string tDimId =
      tDimensionElement
          ->getChildElement(
                MDGeometryXMLDefinitions::workspaceRefDimensionElementName())
          ->innerText();
  if (!tDimId.empty()) {
    auto tDimensionIt =
        find_if(vecAllDims.begin(), vecAllDims.end(), findID(tDimId));
    if (tDimensionIt == vecAllDims.end()) {
      throw std::invalid_argument("Cannot determine t-dimension mapping.");
    }
    m_tDimension = *tDimensionIt;
    if (!vecNonMappedDims.empty()) {
      vecNonMappedDims.erase(std::remove_if(vecNonMappedDims.begin(),
                                            vecNonMappedDims.end(),
                                            findID(tDimId)),
                             vecNonMappedDims.end());
    }
  }
  m_vecNonMappedDims = vecNonMappedDims; // Copy with strong guarantee.
  m_vecAllDims = vecAllDims;
  m_executed = true;
}