コード例 #1
0
ファイル: ili2reader.cpp プロジェクト: imincik/pkg-gdal
void ILI2Reader::SetFieldValues(OGRFeature *feature, DOMElement* elem) {
  int type = 0;
  //recursively search children
  for (DOMElement *childElem = (DOMElement *)elem->getFirstChild();
        type == 0 && childElem && childElem->getNodeType() == DOMNode::ELEMENT_NODE;
        childElem = (DOMElement*)childElem->getNextSibling()) {
    type = getGeometryTypeOfElem(childElem);
    if (type == 0) {
      if (childElem->getFirstChild() && childElem->getFirstChild()->getNodeType() == DOMNode::ELEMENT_NODE) {
        SetFieldValues(feature, childElem);
      } else {
        char *fName = fieldName(childElem);
        int fIndex = feature->GetFieldIndex(fName);
        if (fIndex != -1) {
          char * objVal = getObjValue(childElem);
          if (objVal == NULL)
            objVal = getREFValue(childElem); // only to try
          feature->SetField(fIndex, objVal);
          CPLFree(objVal);
        } else {
          CPLDebug( "OGR_ILI","Attribute '%s' not found", fName);
          m_missAttrs.push_back(fName);
        }
        CPLFree(fName);
      }
    } else {
      feature->SetGeometryDirectly(getGeometry(childElem, type));
    }
  }
}
コード例 #2
0
void XercesUpdateFactory::applyReplaceElementContent(const PendingUpdate &update, DynamicContext *context)
{
  const XercesNodeImpl *nodeImpl = (const XercesNodeImpl*)update.getTarget()->getInterface(Item::gXQilla);
  DOMElement *domnode = (DOMElement*)nodeImpl->getDOMNode();

  // 1. For each node $C that is a child of $target, the parent property of $C is set to empty.
  DOMNode *child = domnode->getFirstChild();
  while(child != 0) {
    forDeletion_.insert(child);
    child = child->getNextSibling();
  }

  const XMLCh *value = update.getValue().first()->asString(context);
  if(value != 0 && *value != 0) {
    // 2. The parent property of $text is set to $target.
    // 3a. children is set to consist exclusively of $text. If $text is an empty sequence, then $target has
    //     no children.
    // 3b. typed-value and string-value are set to the content property of $text. If $text is an empty sequence,
    //     then typed-value is an empty sequence and string-value is an empty string.
    domnode->appendChild(domnode->getOwnerDocument()->createTextNode(value));
  }

  // 3c. upd:removeType($target) is invoked.
  removeType(domnode);

  addToPutSet(update.getTarget(), &update, context);
}
コード例 #3
0
void XSECNameSpaceExpander::expandNameSpaces(void) {

	if (m_expanded)
		return;				// Don't do this twice!

	DOMElement	*docElt;		// The document element - do not expand it's namespaces
	
	docElt = mp_doc->getDocumentElement();
	int count = attNodeCount(docElt);

	DOMNode *c;

	c = docElt->getFirstChild();

	while (c != NULL) {
		if (c->getNodeType() == DOMNode::ELEMENT_NODE)
			recurse((DOMElement *) c);
		c = c->getNextSibling();
	}

	m_expanded = true;

	count = attNodeCount(docElt);

}
コード例 #4
0
Talent* DsaDataLoader::processTalent(int gruppe, DOMElement* talentXml)
{
    CeGuiString desc = XmlHelper::getValueAsUtf8(XmlHelper::getChildNamed(talentXml, "Beschreibung"));
    CeGuiString probe = XmlHelper::getValueAsUtf8(XmlHelper::getChildNamed(talentXml, "Probe"));
    CeGuiString art = XmlHelper::getValueAsUtf8(XmlHelper::getChildNamed(talentXml, "Art"));
    DOMElement* eBeNode = XmlHelper::getChildNamed(talentXml, "eBE");
    int ebe = EBE_KEINE_BE;
    if (eBeNode != NULL)
        ebe = getEBeFromString(XMLString::transcode(eBeNode->getFirstChild()->getNodeValue()));

    CeGuiString name = XmlHelper::transcodeToString(talentXml->getAttribute(XMLString::transcode("ID")));
    EigenschaftTripel eigenschaften;
    eigenschaften.first = probe.substr(0,2);
    eigenschaften.second = probe.substr(3,2);
    eigenschaften.third = probe.substr(6,2);
    probe.clear();

    Talent* t = new Talent(
        name,
        desc,
        eigenschaften,
        ebe,
        gruppe);

    return t;
}
コード例 #5
0
ファイル: PointSetImp.cpp プロジェクト: Siddharthk/opticks
bool PointSetImp::fromXml(DOMNode* pDocument, unsigned int version)
{
   if (pDocument == NULL || !PlotObjectImp::fromXml(pDocument, version))
   {
      return false;
   }

   DOMElement* pElem = static_cast<DOMElement*>(pDocument);
   mSymbols = StringUtilities::fromXmlString<bool>(A(pElem->getAttribute(X("symbols"))));
   mLine = StringUtilities::fromXmlString<bool>(A(pElem->getAttribute(X("line"))));
   ColorType color = StringUtilities::fromXmlString<ColorType>(A(pElem->getAttribute(X("lineColor"))));
   mLineColor = COLORTYPE_TO_QCOLOR(color);
   mLineWidth = StringUtilities::fromXmlString<int>(A(pElem->getAttribute(X("lineWidth"))));
   mLineStyle = StringUtilities::fromXmlString<LineStyle>(A(pElem->getAttribute(X("lineStyle"))));

   for (DOMNode* pChld = pElem->getFirstChild(); pChld != NULL; pChld = pChld->getNextSibling())
   {
      if (XMLString::equals(pChld->getNodeName(), X("Point")))
      {
         PointImp* pPoint = dynamic_cast<PointImp*>(addPoint());
         if (pPoint == NULL || !pPoint->fromXml(pChld, version))
         {
            return false;
         }
      }
   }

   return true;
}
コード例 #6
0
ファイル: LayerImporter.cpp プロジェクト: Tom-VdE/opticks
vector<ImportDescriptor*> LayerImporter::getImportDescriptors(const string& filename, bool reportErrors)
{
   vector<ImportDescriptor*> descriptors;
   if (!filename.empty())
   {
      MessageLog* pLog = NULL;
      if (reportErrors == true)
      {
         Service<MessageLogMgr> pLogMgr;
         pLog = pLogMgr->getLog();
      }

      XmlReader xml(pLog);
      XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument* pDoc = xml.parse(filename, "metadata");
      DOMElement* pRootElement = NULL;
      if (pDoc != NULL)
      {
         pRootElement = pDoc->getDocumentElement();
      }
      if (pRootElement != NULL)
      {
         for (DOMNode* pChild = pRootElement->getFirstChild();
            pChild != NULL;
            pChild = pChild->getNextSibling())
         {
            if (pChild->getNodeType() == DOMNode::ELEMENT_NODE)
            {
               DOMElement* pChildElement = static_cast<DOMElement*>(pChild);
               string cNodeName = A(pChildElement->getNodeName());

               ImportDescriptor* pImportDescriptor = ModelImporter::populateImportDescriptor(pChildElement, filename);
               if (pImportDescriptor != NULL)
               {
                  DataDescriptor* pDataDescriptor = pImportDescriptor->getDataDescriptor();
                  if (NULL != pDataDescriptor)
                  {
                     DynamicObject* pMetadataZ = pDataDescriptor->getMetadata();
                     VERIFYRV(pMetadataZ, descriptors);
                     if (!pMetadataZ->getAttributeByPath("Layer/Import Options/Use Pixel Coordinates").isValid())
                     {
                        pMetadataZ->setAttributeByPath("Layer/Import Options/Use Pixel Coordinates", false);
                     }
                  }
                  descriptors.push_back(pImportDescriptor);
               }
            }
         }
      }
   }

   return descriptors;
}
コード例 #7
0
ファイル: ili2reader.cpp プロジェクト: imincik/pkg-gdal
void ILI2Reader::setFieldDefn(OGRFeatureDefn *featureDef, DOMElement* elem) {
  int type = 0;
  //recursively search children
  for (DOMElement *childElem = (DOMElement *)elem->getFirstChild();
        type == 0 && childElem && childElem->getNodeType() == DOMNode::ELEMENT_NODE;
        childElem = (DOMElement*)childElem->getNextSibling()) {
    type = getGeometryTypeOfElem(childElem);
    if (type == 0) {
      if (childElem->getFirstChild() && childElem->getFirstChild()->getNodeType() == DOMNode::ELEMENT_NODE) {
        setFieldDefn(featureDef, childElem);
      } else {
        char *fName = fieldName(childElem);
        if (featureDef->GetFieldIndex(fName) == -1) {
          CPLDebug( "OGR_ILI", "AddFieldDefn: %s",fName );
          OGRFieldDefn oFieldDefn(fName, OFTString);
          featureDef->AddFieldDefn(&oFieldDefn);
        }
        CPLFree(fName);
      }
    }
  }
}
コード例 #8
0
ファイル: Parameter.cpp プロジェクト: SparkyCola/FreeCAD
void  ParameterGrp::SetASCII(const char* Name, const char *sValue)
{
    // find or create the Element
    DOMElement *pcElem = FindOrCreateElement(_pGroupNode,"FCText",Name);
    // and set the value
    DOMNode *pcElem2 = pcElem->getFirstChild();
    if (!pcElem2) {
        XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument *pDocument = _pGroupNode->getOwnerDocument();
        DOMText *pText = pDocument->createTextNode(XUTF8Str(sValue).unicodeForm());
        pcElem->appendChild(pText);
    }
    else {
        pcElem2->setNodeValue(XUTF8Str(sValue).unicodeForm());
    }
    // trigger observer
    Notify(Name);

}
コード例 #9
0
Kampftechnik* DsaDataLoader::processKampftechnik(DOMElement* kampftechnikXml)
{
    CeGuiString desc = XmlHelper::getValueAsUtf8(XmlHelper::getChildNamed(kampftechnikXml, "Beschreibung"));
    CeGuiString art = XmlHelper::getValueAsUtf8(XmlHelper::getChildNamed(kampftechnikXml, "Art"));
    DOMElement* eBeNode = XmlHelper::getChildNamed(kampftechnikXml, "eBE");
    int ebe = EBE_KEINE_BE;
    if (eBeNode != NULL)
        ebe = getEBeFromString(XMLString::transcode(eBeNode->getFirstChild()->getNodeValue()));

    CeGuiString name = XmlHelper::transcodeToString(kampftechnikXml->getAttribute(XMLString::transcode("ID")));

    Kampftechnik* k = new Kampftechnik(
        name,
        desc,
        ebe);

    return k;

}
コード例 #10
0
ファイル: LayerImporter.cpp プロジェクト: Siddharthk/opticks
vector<ImportDescriptor*> LayerImporter::getImportDescriptors(const string& filename, bool reportErrors)
{
   vector<ImportDescriptor*> descriptors;
   if (!filename.empty())
   {
      MessageLog* pLog = NULL;
      if (reportErrors == true)
      {
         Service<MessageLogMgr> pLogMgr;
         pLog = pLogMgr->getLog();
      }

      XmlReader xml(pLog);
      XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument* pDoc = xml.parse(filename, "metadata");
      DOMElement* pRootElement = NULL;
      if (pDoc != NULL)
      {
         pRootElement = pDoc->getDocumentElement();
      }
      if (pRootElement != NULL)
      {
         for (DOMNode* pChild = pRootElement->getFirstChild();
            pChild != NULL;
            pChild = pChild->getNextSibling())
         {
            if (pChild->getNodeType() == DOMNode::ELEMENT_NODE)
            {
               DOMElement* pChildElement = static_cast<DOMElement*>(pChild);
               string cNodeName = A(pChildElement->getNodeName());

               ImportDescriptor* pImportDescriptor = ModelImporter::populateImportDescriptor(pChildElement, filename);
               if (pImportDescriptor != NULL)
               {
                  descriptors.push_back(pImportDescriptor);
               }
            }
         }
      }
   }

   return descriptors;
}
コード例 #11
0
ファイル: Parameter.cpp プロジェクト: SparkyCola/FreeCAD
std::vector<std::pair<std::string,std::string> > ParameterGrp::GetASCIIMap(const char * sFilter) const
{
    std::vector<std::pair<std::string,std::string> >  vrValues;
    DOMElement *pcTemp;// = _pGroupNode->getFirstChild();
    std::string Name;

    pcTemp = FindElement(_pGroupNode,"FCText");
    while ( pcTemp) {
        Name = StrXUTF8( ((DOMElement*)pcTemp)->getAttributes()->getNamedItem(XStr("Name").unicodeForm())->getNodeValue()).c_str();
        // check on filter condition
        if (sFilter == NULL || Name.find(sFilter)!= std::string::npos) {
            // retrive the text element
            DOMNode *pcElem2 = pcTemp->getFirstChild();
            if (pcElem2)
                vrValues.push_back(std::make_pair(Name, std::string(StrXUTF8(pcElem2->getNodeValue()).c_str())));
        }
        pcTemp = FindNextElement(pcTemp,"FCText");
    }

    return vrValues;
}
コード例 #12
0
ファイル: Parameter.cpp プロジェクト: SparkyCola/FreeCAD
std::string ParameterGrp::GetASCII(const char* Name, const char * pPreset) const
{
    // check if Element in group
    DOMElement *pcElem = FindElement(_pGroupNode,"FCText",Name);
    // if not return preset
    if (!pcElem) {
        if (pPreset==0)
            return std::string("");
        else
            return std::string(pPreset);
    }
    // if yes check the value and return
    DOMNode *pcElem2 = pcElem->getFirstChild();
    if (pcElem2)
        return std::string(StrXUTF8(pcElem2->getNodeValue()).c_str());
    else if (pPreset==0)
        return std::string("");

    else
        return std::string(pPreset);
}
コード例 #13
0
ファイル: CustomLayerImp.cpp プロジェクト: jonatho7/opticks
bool CustomLayerImp::fromXml(DOMNode* pDocument, unsigned int version)
{
    if (!LayerImp::fromXml(pDocument, version))
    {
        return false;
    }

    DOMElement* pElem = static_cast<DOMElement*>(pDocument);
    setAcceptsMouseEvents(StringUtilities::fromXmlString<bool>(A(pElem->getAttribute(X("mouseEventsSupported")))));
    for (DOMNode* pChld = pElem->getFirstChild(); pChld != NULL; pChld = pChld->getNextSibling())
    {
        if (XMLString::equals(pChld->getNodeName(), X("mouseCursor")))
        {
            string cursorStr = string(A(pChld->getTextContent()));
            if (cursorStr.empty() == false)
            {
                QByteArray cursorArray(QByteArray::fromBase64(QByteArray::fromRawData(
                                           cursorStr.c_str(), cursorStr.size())));
                QDataStream cursorStream(&cursorArray, QIODevice::ReadOnly);
                cursorStream >> mMouseCursor;
            }
        }
コード例 #14
0
ファイル: CurveImp.cpp プロジェクト: Siddharthk/opticks
bool CurveImp::fromXml(DOMNode* pDocument, unsigned int version)
{
   if (pDocument == NULL || !PlotObjectImp::fromXml(pDocument, version))
   {
      return false;
   }

   DOMElement* pElem = static_cast<DOMElement*>(pDocument);
   ColorType color = StringUtilities::fromXmlString<ColorType>(A(pElem->getAttribute(X("color"))));
   mColor = COLORTYPE_TO_QCOLOR(color);
   mLineWidth = StringUtilities::fromXmlString<int>(A(pElem->getAttribute(X("lineWidth"))));
   mLineStyle = StringUtilities::fromXmlString<LineStyle>(A(pElem->getAttribute(X("lineStyle"))));

   for (DOMNode* pChld = pElem->getFirstChild(); pChld != NULL; pChld = pChld->getNextSibling())
   {
      if (XMLString::equals(pChld->getNodeName(), X("Point")))
      {
         mPoints.push_back(StringUtilities::fromXmlString<LocationType>(A(pChld->getTextContent())));
      }
   }

   return true;
}
コード例 #15
0
ファイル: AxisImp.cpp プロジェクト: wzssyqa/opticks-cmake
bool AxisImp::fromXml(DOMNode* pDocument, unsigned int version)
{
    DOMElement* pElmnt = dynamic_cast<DOMElement*>(pDocument);
    if (pElmnt == NULL)
    {
        return false;
    }

    mTitle = A(pElmnt->getAttribute(X("title")));
    for (DOMNode* pNode = pElmnt->getFirstChild(); pNode != NULL; pNode = pNode->getNextSibling())
    {
        if (XMLString::equals(pNode->getNodeName(), X("titleFont")))
        {
            DOMElement* pFontElement = static_cast<DOMElement*>(pNode);
            if (mTitleFont.fromXml(pFontElement, version) == false)
            {
                return false;
            }
        }
    }

    ColorType color = StringUtilities::fromXmlString<ColorType>(A(pElmnt->getAttribute(X("titleColor"))));
    mTitleColor = COLORTYPE_TO_QCOLOR(color);
    mScaleType = StringUtilities::fromXmlString<ScaleType>(A(pElmnt->getAttribute(X("scaleType"))));
    mMaxMajorTicks = StringUtilities::fromXmlString<int>(A(pElmnt->getAttribute(X("maxMajorTicks"))));
    mMaxMinorTicks = StringUtilities::fromXmlString<int>(A(pElmnt->getAttribute(X("maxMinorTicks"))));
    mScaleDraw.setLabelFormat(A(pElmnt->getAttribute(X("scaleDrawLabelFormat"))));

    double minValue = StringUtilities::fromXmlString<double>(A(pElmnt->getAttribute(X("minValue"))));
    double maxValue = StringUtilities::fromXmlString<double>(A(pElmnt->getAttribute(X("maxValue"))));
    setValueRange(minValue, maxValue);

    updateScale();
    updateSize();

    return true;
}
コード例 #16
0
string InputHandler::getAttributeValueByName(const XMLCh* elementNode, const XMLCh* attribute, const XMLCh* name)
{

     crusde_debug("%s, line: %d, InputHandler::getAttributeValueByName(%s) name = %s ", __FILE__, __LINE__, XMLString::transcode(elementNode),
     XMLString::transcode(name));
     assert(doc);

     DOMElement *root = doc->getDocumentElement();
     DOMNode *child = root->getFirstChild();
     DOMNamedNodeMap *attributes = NULL;
		
     while (child)
     {
          if(child != NULL)
               if( child->getNodeType() == DOMNode::ELEMENT_NODE )
               {
                    if(child->hasAttributes())
                    {
                         attributes = child->getAttributes();

                         if( XMLString::compareIString( child->getNodeName(), elementNode) == 0 && 
                             XMLString::compareIString( attributes->getNamedItem(ATTR_name.xmlStr())->getNodeValue(), name) == 0 )
                         {
                              char *val = XMLString::transcode(attributes->getNamedItem(attribute)->getNodeValue());
                              string value(val);
                              XMLString::release(&val);
                              return value;
                         }
                    }
               }

          child = child->getNextSibling();
     }
	
     return string();
}
コード例 #17
0
bool SpectralLibraryManager::deserialize(SessionItemDeserializer& deserializer)
{
    if (isBatch() == true)
    {
        setInteractive();
    }

    bool success = execute(NULL, NULL);

    if (success)
    {

        std::vector<Signature*> signatures;
        Service<SessionManager> pSessionManager;
        XmlReader reader(NULL, false);
        DOMElement* pRootElement = deserializer.deserialize(reader, "SpectralLibraryManager");
        for (DOMNode* pChild = pRootElement->getFirstChild(); pChild != NULL; pChild = pChild->getNextSibling())
        {
            DOMElement* pElement = static_cast<DOMElement*>(pChild);
            if (XMLString::equals(pElement->getNodeName(), X("Signature")))
            {
                std::string signatureId = A(pElement->getAttribute(X("signatureId")));
                Signature* pSignature = dynamic_cast<Signature*>(pSessionManager->getSessionItem(signatureId));
                if (pSignature != NULL)
                {
                    signatures.push_back(pSignature);
                }
            }
        }

        clearLibrary();
        addSignatures(signatures);
    }

    return success;
}
コード例 #18
0
ret_ CXMLLoaderActions::LoadDataBlock(CData &Data,
									  const DOMElement *pElement)
{
#ifdef _DEBUG_
	if (!pElement)
		return PARAMETER_NULL | PARAMETER_2;
#endif

	DOMElement *pChild = (DOMElement *)pElement->getFirstChild();

	if (!pChild)
		return XML_LOADER_ERROR;

	auto_xerces_str	wsObject	("v_object");
	auto_xerces_str wsB1		("v_b_1");
	auto_xerces_str wsUB1		("v_ub_1");
	auto_xerces_str wsB2		("v_b_2");
	auto_xerces_str wsUB2		("v_ub_2");
	auto_xerces_str wsB4		("v_b_4");
	auto_xerces_str wsUB4		("v_ub_4");
	auto_xerces_str wsB8		("v_b_8");
	auto_xerces_str wsUB8		("v_ub_8");
	auto_xerces_str wsFB4		("v_fb_4");
	auto_xerces_str wsFB8		("v_fb_8");
	auto_xerces_str	wsString	("v_string");
	auto_xerces_str wsGroup		("v_group");

	auto_xerces_str	wsName		("name");
	auto_xerces_str	wsValue		("value");

	while (pChild)
	{
		if (0 == XMLString::compareString(pChild->getNodeName(), wsObject))
		{
			auto_xerces_str sName	(pChild->getAttribute(wsName));
			auto_xerces_str sValue	(pChild->getAttribute(wsValue));

			if (false_v == Data.Define(sName, (obj_)null_v))
				return XML_LOADER_ERROR;
		}
		else if (0 == XMLString::compareString(pChild->getNodeName(), wsB1))
		{
			auto_xerces_str sName	(pChild->getAttribute(wsName));
			auto_xerces_str sValue	(pChild->getAttribute(wsValue));

			if (0 == strcmp(sValue, SIGN_UNBOUNDED))
			{
				if (false_v == Data.Define(sName, B_1))
					return XML_LOADER_ERROR;
			}
			else
			{
				if (false_v == Data.Define(sName, B_1, (b_4)atoi(sValue)))
					return XML_LOADER_ERROR;
			}

		}
		else if (0 == XMLString::compareString(pChild->getNodeName(), wsUB1))
		{
			auto_xerces_str sName	(pChild->getAttribute(wsName));
			auto_xerces_str sValue	(pChild->getAttribute(wsValue));

			if (0 == strcmp(sValue, SIGN_UNBOUNDED))
			{
				if (false_v == Data.Define(sName, UB_1))
					return XML_LOADER_ERROR;
			}
			else
			{
				if (false_v == Data.Define(sName, UB_1, (b_4)atoi(sValue)))
					return XML_LOADER_ERROR;
			}
		}
		else if (0 == XMLString::compareString(pChild->getNodeName(), wsB2))
		{
			auto_xerces_str sName	(pChild->getAttribute(wsName));
			auto_xerces_str sValue	(pChild->getAttribute(wsValue));

			if (0 == strcmp(sValue, SIGN_UNBOUNDED))
			{
				if (false_v == Data.Define(sName, B_2))
					return XML_LOADER_ERROR;
			}
			else
			{
				if (false_v == Data.Define(sName, B_2, (b_4)atoi(sValue)))
					return XML_LOADER_ERROR;
			}
		}
		else if (0 == XMLString::compareString(pChild->getNodeName(), wsUB2))
		{
			auto_xerces_str sName	(pChild->getAttribute(wsName));
			auto_xerces_str sValue	(pChild->getAttribute(wsValue));

			if (0 == strcmp(sValue, SIGN_UNBOUNDED))
			{
				if (false_v == Data.Define(sName, UB_2))
					return XML_LOADER_ERROR;
			}
			else
			{
				if (false_v == Data.Define(sName, UB_2, (b_4)atoi(sValue)))
					return XML_LOADER_ERROR;
			}
		}
		else if (0 == XMLString::compareString(pChild->getNodeName(), wsB4))
		{
			auto_xerces_str sName	(pChild->getAttribute(wsName));
			auto_xerces_str sValue	(pChild->getAttribute(wsValue));

			if (0 == strcmp(sValue, SIGN_UNBOUNDED))
			{
				if (false_v == Data.Define(sName, B_4))
					return XML_LOADER_ERROR;
			}
			else
			{
				if (false_v == Data.Define(sName, B_4, (b_4)atoi(sValue)))
					return XML_LOADER_ERROR;
			}
		}
		else if (0 == XMLString::compareString(pChild->getNodeName(), wsUB4))
		{
			auto_xerces_str sName	(pChild->getAttribute(wsName));
			auto_xerces_str sValue	(pChild->getAttribute(wsValue));

			if (0 == strcmp(sValue, SIGN_UNBOUNDED))
			{
				if (false_v == Data.Define(sName, UB_4))
					return XML_LOADER_ERROR;
			}
			else
			{
				if (false_v == Data.Define(sName, UB_4, (b_4)atoi(sValue)))
					return XML_LOADER_ERROR;
			}
		}
		else if (0 == XMLString::compareString(pChild->getNodeName(), wsB8))
		{
			auto_xerces_str sName	(pChild->getAttribute(wsName));
			auto_xerces_str sValue	(pChild->getAttribute(wsValue));

			if (0 == strcmp(sValue, SIGN_UNBOUNDED))
			{
				if (false_v == Data.Define(sName, B_8))
					return XML_LOADER_ERROR;
			}
			else
			{
				if (false_v == Data.Define(sName, B_8, (b_8)atoll(sValue)))
					return XML_LOADER_ERROR;
			}
		}
		else if (0 == XMLString::compareString(pChild->getNodeName(), wsUB8))
		{
			auto_xerces_str sName	(pChild->getAttribute(wsName));
			auto_xerces_str sValue	(pChild->getAttribute(wsValue));

			if (0 == strcmp(sValue, SIGN_UNBOUNDED))
			{
				if (false_v == Data.Define(sName, UB_8))
					return XML_LOADER_ERROR;
			}
			else
			{
				if (false_v == Data.Define(sName, UB_8, (ub_8)atoll(sValue)))
					return XML_LOADER_ERROR;
			}
		}
		else if (0 == XMLString::compareString(pChild->getNodeName(), wsFB4))
		{
			auto_xerces_str sName	(pChild->getAttribute(wsName));
			auto_xerces_str sValue	(pChild->getAttribute(wsValue));

			if (0 == strcmp(sValue, SIGN_UNBOUNDED))
			{
				if (false_v == Data.Define(sName, FB_4))
					return XML_LOADER_ERROR;
			}
			else
			{
				if (false_v == Data.Define(sName, (fb_4)atof(sValue)))
					return XML_LOADER_ERROR;
			}
		}
		else if (0 == XMLString::compareString(pChild->getNodeName(), wsFB8))
		{
			auto_xerces_str sName	(pChild->getAttribute(wsName));
			auto_xerces_str sValue	(pChild->getAttribute(wsValue));

			if (0 == strcmp(sValue, SIGN_UNBOUNDED))
			{
				if (false_v == Data.Define(sName, FB_8))
					return XML_LOADER_ERROR;
			}
			else
			{
				if (false_v == Data.Define(sName, (fb_8)atof(sValue)))
					return XML_LOADER_ERROR;
			}
		}
		else if (0 == XMLString::compareString(pChild->getNodeName(), wsString))
		{
			auto_xerces_str sName	(pChild->getAttribute(wsName));
			auto_xerces_str sValue	(pChild->getAttribute(wsValue));

			if (0 == strcmp(sValue, SIGN_UNBOUNDED))
			{
				if (false_v == Data.Define(sName, (ch_1 *)""))
					return XML_LOADER_ERROR;
			}
			else
			{
				if (false_v == Data.Define(sName, sValue))
					return XML_LOADER_ERROR;
			}
		}
		else if (0 == XMLString::compareString(pChild->getNodeName(), wsGroup))
		{
			auto_xerces_str wsNormal("normal");
			auto_xerces_str wsFloat	("float");
			auto_xerces_str wsString("string");

			auto_xerces_str	wsName	("name");
			auto_xerces_str	wsLength("length");
			auto_xerces_str	wsSigned("signed");
			auto_xerces_str	wsSize	("size");

			auto_xerces_str sName	(pChild->getAttribute(wsName));
			auto_xerces_str sSize	(pChild->getAttribute(wsSize));

			CFieldGroupDefined *pGroupField = new CFieldGroupDefined(
				sName, 
				sSize);

			DOMElement *pSub = (DOMElement *)pChild->getFirstChild();

			if (!pSub)
				return XML_LOADER_ERROR;

			while (pSub)
			{
				if (0 == XMLString::compareString(pSub->getNodeName(),
												  wsNormal))
				{
					auto_xerces_str sName (pElement->getAttribute(wsName));
					auto_xerces_str	sLength(pElement->getAttribute(wsLength));
					auto_xerces_str	sSigned(pElement->getAttribute(wsSigned));

					EFieldType Type;

					GetFieldType(
						FIELD_NORMAL_STYLE, 
						atoi(sLength), 
						0 == strcmp(sSigned, "true") ? true_v : false_v,
						Type);
					
					CFieldNumber *pField = new CFieldNumber(sName, 
															Type, 
															pGroupField);

					pGroupField->SetSubField(pField);
				}
				else if (0 == XMLString::compareString(pSub->getNodeName(),
													   wsFloat))
				{
					auto_xerces_str sName (pElement->getAttribute(wsName));
					auto_xerces_str	sLength(pElement->getAttribute(wsLength));

					EFieldType Type;

					GetFieldType(FIELD_FLOAT_STYLE, 
								 atoi(sLength), 
								 false_v, 
								 Type);
					
					CFieldNumber *pField = new CFieldNumber(sName, 
															Type, 
															pGroupField);

					pGroupField->SetSubField(pField);
				}
				else if (0 == XMLString::compareString(pSub->getNodeName(),
													   wsString))
				{
					auto_xerces_str sName (pElement->getAttribute(wsName));
					auto_xerces_str	sLength(pElement->getAttribute(wsLength));
					auto_xerces_str	sSize(pElement->getAttribute(wsSize));
					
					CFieldString *pField = new CFieldString(sName, 
															atoi(sSize), 
															pGroupField);

					pGroupField->SetSubField(pField);
				}

				pSub = (DOMElement *)pSub->getNextSibling();
			}
			
			if (false_v == Data.Define(pGroupField))
				return XML_LOADER_ERROR;
		}

		pChild = (DOMElement *)pChild->getNextSibling();
	}

	return SUCCESS;
}
コード例 #19
0
ファイル: XIncludeUtils.cpp プロジェクト: kanbang/Colt
// ---------------------------------------------------------------------------
//  This method assumes that currentNode is an xinclude element and parses
//   it accordingly, acting on what it finds.
// ---------------------------------------------------------------------------
bool
XIncludeUtils::doDOMNodeXInclude(DOMNode *xincludeNode, DOMDocument *parsedDocument, XMLEntityHandler* entityResolver){
    bool modifiedNode = false;
    /* the relevant attributes to look for */
    const XMLCh *href = NULL;
    const XMLCh *parse = NULL;
    const XMLCh *xpointer = NULL;
    const XMLCh *encoding = NULL;
    const XMLCh *accept = NULL;
    const XMLCh *acceptlanguage = NULL;
    DOMNode *includeParent = xincludeNode->getParentNode();


    if(xincludeNode->hasAttributes()) {
        /* get all the attributes of the node */
        DOMNamedNodeMap *pAttributes = xincludeNode->getAttributes();
        XMLSize_t nSize = pAttributes->getLength();
        for(XMLSize_t i=0;i<nSize;++i) {
            DOMAttr *pAttributeNode = (DOMAttr*) pAttributes->item(i);
            const XMLCh *attrName = pAttributeNode->getName();
            /* check each attribute against the potential useful names */
            if (XMLString::equals(attrName, XIncludeUtils::fgXIIncludeHREFAttrName)){
                href = pAttributeNode->getValue();
            } else if (XMLString::equals(attrName, XIncludeUtils::fgXIIncludeParseAttrName)){
                parse = pAttributeNode->getValue();
            } else if (XMLString::equals(attrName, XIncludeUtils::fgXIIncludeXPointerAttrName)){
                xpointer = pAttributeNode->getValue();
            } else if (XMLString::equals(attrName, XIncludeUtils::fgXIIncludeEncodingAttrName)){
                encoding = pAttributeNode->getValue();
            } else if (XMLString::equals(attrName, XIncludeUtils::fgXIIncludeAcceptAttrName)){
                accept = pAttributeNode->getValue();
            } else if (XMLString::equals(attrName, XIncludeUtils::fgXIIncludeAcceptLanguageAttrName)){
                acceptlanguage = pAttributeNode->getValue();
            } else {
                /* if any other attribute is in the xi namespace, it's an error */
                const XMLCh *attrNamespaceURI = pAttributeNode->getNamespaceURI();
                if (attrNamespaceURI && XMLString::equals(attrNamespaceURI, XIncludeUtils::fgXIIIncludeNamespaceURI)){
                } else {
                    /* ignore - any other attribute is allowed according to spec,
                       and must be ignored */
                }
            }
        }
    }
    // 3.1 xi:include Element
    // The children property of the xi:include element may include a single xi:fallback element;
    // the appearance of more than one xi:fallback element, an xi:include element,
    // or any other element from the XInclude namespace is a fatal error.
    DOMNode *child;
    DOMElement *fallback = NULL;
    for (child = xincludeNode->getFirstChild(); child != 0; child=child->getNextSibling()){
        if(child->getNodeType()!=DOMNode::ELEMENT_NODE)
            continue;
        if ( isXIFallbackDOMNode(child) ){
            if (fallback != NULL){
                /* fatal error - there are more than one fallback children */
                XIncludeUtils::reportError(xincludeNode, XMLErrs::XIncludeMultipleFallbackElems,
                    parsedDocument->getDocumentURI(), parsedDocument->getDocumentURI());
                return false;
            }
            fallback = (DOMElement*)child;
        }
        else if(isXIIncludeDOMNode(child) || XMLString::equals(child->getNamespaceURI(), XIncludeUtils::fgXIIIncludeNamespaceURI)) {
            /* fatal error - an xi element different from xi:fallback is a child of xi:include */
            XIncludeUtils::reportError(xincludeNode, XMLErrs::XIncludeDisallowedChild,
                child->getNodeName(), parsedDocument->getDocumentURI());
            return false;
        }
    }

    if (href == NULL){
        /* this is an unrecoverable error until we have xpointer support -
           if there is an xpointer, the current document is assumed
           however, there is no xpointer support yet */
        XIncludeUtils::reportError(xincludeNode, XMLErrs::XIncludeNoHref,
            NULL, parsedDocument->getDocumentURI());
        return false;
    }

    /* set up the accept and accept-language values */
    if (accept != NULL){

    }

    if (parse == NULL){
        /* use the default, as specified */
        parse = XIncludeUtils::fgXIIncludeParseAttrXMLValue;
    }

    if (xpointer != NULL){
        /* not supported yet */
        /* Note that finding an xpointer attr along with parse="text" is a Fatal Error
         *  - http://www.w3.org/TR/xinclude/#include-location */
        XIncludeUtils::reportError(xincludeNode, XMLErrs::XIncludeXPointerNotSupported,
            NULL, href);
        return false;
    }

    /* set up the href according to what has gone before */
    XIncludeLocation hrefLoc(href);
    XIncludeLocation relativeLocation(href);
    const XMLCh *includeBase = xincludeNode->getBaseURI();
    if (includeBase != NULL){
        hrefLoc.prependPath(includeBase);
    }

    if (getBaseAttrValue(xincludeNode) != NULL){
        relativeLocation.prependPath(getBaseAttrValue(xincludeNode));
    }

    /*  Take the relevant action - we need to retrieve the target as a whole before
        we can know if it was successful or not, therefore the do* methods do
        not modify the parsedDocument. Swapping the results in is left to the
        caller (i.e. here) */
    DOMText *includedText = NULL;
    DOMDocument *includedDoc = NULL;
    if (XMLString::equals(parse, XIncludeUtils::fgXIIncludeParseAttrXMLValue)){
        /* including a XML element */
        includedDoc = doXIncludeXMLFileDOM(hrefLoc.getLocation(), relativeLocation.getLocation(), xincludeNode, parsedDocument, entityResolver);
    } else if (XMLString::equals(parse, XIncludeUtils::fgXIIncludeParseAttrTextValue)){
        /* including a text value */
        includedText = doXIncludeTEXTFileDOM(hrefLoc.getLocation(), relativeLocation.getLocation(), encoding, xincludeNode, parsedDocument, entityResolver);
    } else {
        /* invalid parse attribute value - fatal error according to the specification */
        XIncludeUtils::reportError(xincludeNode, XMLErrs::XIncludeInvalidParseVal,
            parse, parsedDocument->getDocumentURI());
        return false;
    }

    RefVectorOf<DOMNode> delayedProcessing(12,false);
    if (includedDoc == NULL && includedText == NULL){
        /* there was an error - this is now a resource error
           let's see if there is a fallback */
        XIncludeUtils::reportError(xincludeNode, XMLErrs::XIncludeIncludeFailedResourceError,
            hrefLoc.getLocation(), parsedDocument->getDocumentURI());

        if (includeParent == NULL){
            includeParent = parsedDocument;
        }

        // we could be getting errors trying to insert elements at the root of the document, so we should use replaceChild;
        // in order to handle multiple nodes, add them to a document fragment and use that to replace the original node
        if (fallback){
            /* baseURI fixups - see http://www.w3.org/TR/xinclude/#base for details. */
            XMLUri parentURI(includeParent->getBaseURI());
            XMLUri includedURI(fallback->getBaseURI());

            if (fallback->hasChildNodes()){
                DOMDocumentFragment* frag = parsedDocument->createDocumentFragment();
                DOMNode *child = fallback->getFirstChild();
                /* add the content of the fallback element, and remove the fallback elem itself */
                for ( ; child != NULL ; child=child->getNextSibling()){
                    if (child->getNodeType() == DOMNode::DOCUMENT_TYPE_NODE){
                        continue;
                    }
                    DOMNode *newNode = parsedDocument->importNode(child, true);
                    /* if the paths differ we need to add a base attribute */
                    if (newNode->getNodeType()==DOMNode::ELEMENT_NODE && !XMLString::equals(parentURI.getPath(), includedURI.getPath())){
                        if (getBaseAttrValue(newNode) == NULL){
                            /* need to calculate the proper path difference to get the relativePath */
                            ((DOMElement*)newNode)->setAttribute(fgXIBaseAttrName, getBaseAttrValue(fallback->getParentNode()));
                        } else {
                            /* the included node has base of its own which takes precedence */
                            XIncludeLocation xil(getBaseAttrValue(newNode));
                            if (getBaseAttrValue(fallback->getParentNode()) != NULL){
                                /* prepend any specific base modification of the xinclude node */
                                xil.prependPath(getBaseAttrValue(fallback->getParentNode()));
                            }
                            ((DOMElement*)newNode)->setAttribute(fgXIBaseAttrName, xil.getLocation());
                        }
                    }
                    DOMNode *newChild = frag->appendChild(newNode);
                    // don't process the node now, wait until it is placed in the final position
                    delayedProcessing.addElement(newChild);
                    //parseDOMNodeDoingXInclude(newChild, parsedDocument, entityResolver);
                }
                includeParent->replaceChild(frag, xincludeNode);
                frag->release();

                for(XMLSize_t i=0;i<delayedProcessing.size();i++)
                {
                    DOMNode* childNode=delayedProcessing.elementAt(i);
                    parseDOMNodeDoingXInclude(childNode, parsedDocument, entityResolver);
                }
                modifiedNode = true;
            } else {
                /* empty fallback element - simply remove it! */
                includeParent->removeChild(xincludeNode);
                modifiedNode = true;
            }
        } else {
            XIncludeUtils::reportError(xincludeNode, XMLErrs::XIncludeIncludeFailedNoFallback,
                parsedDocument->getDocumentURI(), parsedDocument->getDocumentURI());
            return false;
        }
    } else {
        if (includedDoc){
            /* record the successful include while we process the children */
            addDocumentURIToCurrentInclusionHistoryStack(hrefLoc.getLocation());

            DOMDocumentFragment* frag = parsedDocument->createDocumentFragment();
            /* need to import the document prolog here */
            DOMNode *child = includedDoc->getFirstChild();
            for (; child != NULL; child = child->getNextSibling()) {
                if (child->getNodeType() == DOMNode::DOCUMENT_TYPE_NODE)
                    continue;
                // check for NOTATION or ENTITY clash
                if(child->getNodeType()==DOMNode::ELEMENT_NODE && includedDoc->getDoctype()!=NULL) {
                    DOMNamedNodeMap *pAttributes = child->getAttributes();
                    XMLSize_t nSize = pAttributes->getLength();
                    for(XMLSize_t i=0;i<nSize;++i) {
                        DOMAttr *pAttributeNode = (DOMAttr*) pAttributes->item(i);
                        const DOMTypeInfo * typeInfo=pAttributeNode->getSchemaTypeInfo();
                        if(typeInfo && XMLString::equals(typeInfo->getTypeNamespace(), XMLUni::fgInfosetURIName)) {
                            if(XMLString::equals(typeInfo->getTypeName(), XMLUni::fgNotationString)) {
                                const XMLCh* notationName=pAttributeNode->getNodeValue();
                                DOMNotation* notat=(DOMNotation*)includedDoc->getDoctype()->getNotations()->getNamedItem(notationName);
                                // ensure we have a DTD
                                if(parsedDocument->getDoctype()==NULL)
                                    parsedDocument->insertBefore(parsedDocument->createDocumentType(parsedDocument->getDocumentElement()->getNodeName(), NULL,NULL), parsedDocument->getFirstChild());
                                DOMNotation* myNotation=(DOMNotation*)parsedDocument->getDoctype()->getNotations()->getNamedItem(notationName);
                                if(myNotation==NULL)
                                {
                                    // it's missing, add it
                                    parsedDocument->getDoctype()->getNotations()->setNamedItem(parsedDocument->importNode(notat, true));
                                }
                                else if(XMLString::equals(myNotation->getPublicId(), notat->getPublicId()) &&
                                        XMLString::equals(myNotation->getSystemId(), notat->getSystemId()) &&
                                        XMLString::equals(myNotation->getBaseURI(), notat->getBaseURI()))
                                {
                                    // it's duplicate, ignore it
                                }
                                else
                                {
                                    // it's a conflict, report it
                                    XIncludeUtils::reportError(xincludeNode, XMLErrs::XIncludeConflictingNotation,
                                        notationName, parsedDocument->getDocumentURI());
                                }
                            }
                            else if(XMLString::equals(typeInfo->getTypeName(), XMLUni::fgEntityString)) {
                                const XMLCh* entityName=pAttributeNode->getNodeValue();
                                DOMEntity* ent=(DOMEntity*)includedDoc->getDoctype()->getEntities()->getNamedItem(entityName);
                                // ensure we have a DTD
                                if(parsedDocument->getDoctype()==NULL)
                                    parsedDocument->insertBefore(parsedDocument->createDocumentType(parsedDocument->getDocumentElement()->getNodeName(), NULL,NULL), parsedDocument->getFirstChild());
                                DOMEntity* myEnt=(DOMEntity*)parsedDocument->getDoctype()->getEntities()->getNamedItem(entityName);
                                if(myEnt==NULL)
                                {
                                    // it's missing, add it
                                    parsedDocument->getDoctype()->getEntities()->setNamedItem(parsedDocument->importNode(ent, true));
                                }
                                else if(XMLString::equals(myEnt->getPublicId(), ent->getPublicId()) &&
                                        XMLString::equals(myEnt->getSystemId(), ent->getSystemId()) &&
                                        XMLString::equals(myEnt->getBaseURI(), ent->getBaseURI()))
                                {
                                    // it's duplicate, ignore it
                                }
                                else
                                {
                                    // it's a conflict, report it
                                    XIncludeUtils::reportError(xincludeNode, XMLErrs::XIncludeConflictingEntity,
                                        entityName, parsedDocument->getDocumentURI());
                                }
                            }
                        }
                    }
                }
                DOMNode *newNode = parsedDocument->importNode(child, true);
                DOMNode *newChild = frag->appendChild(newNode);
                // don't process the node now, wait until it is placed in the final position
                delayedProcessing.addElement(newChild);
                //parseDOMNodeDoingXInclude(newChild, parsedDocument, entityResolver);
            }
            includeParent->replaceChild(frag, xincludeNode);
            frag->release();

            for(XMLSize_t i=0;i<delayedProcessing.size();i++)
            {
                DOMNode* childNode=delayedProcessing.elementAt(i);
                parseDOMNodeDoingXInclude(childNode, parsedDocument, entityResolver);
            }
            popFromCurrentInclusionHistoryStack(NULL);
            modifiedNode = true;
        } else if (includedText){
            includeParent->replaceChild(includedText, xincludeNode);
            modifiedNode = true;
        }
    }

    if (includedDoc)
        includedDoc->release();

    return modifiedNode;
}
コード例 #20
0
ファイル: pdmlreader.cpp プロジェクト: gerpe/fresdwn
/*!
	\brief It gets a list of DOM nodes containing a protocol, and formats them into _nbPDMLProto structures.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

#ifdef DOM_DEBUG
		// FULVIO This code is still present, because it should be needed in order to solve
		// a bug discovered on Dec 4, 2006
		// See my email in the mailbox
		// get a serializer, an instance of DOMWriter
		XMLCh tempStr[100];
		XMLString::transcode("LS", tempStr, 99);

		DOMImplementation *impl          = DOMImplementationRegistry::getDOMImplementation(tempStr);
		DOMWriter         *theSerializer = ((DOMImplementationLS*)impl)->createDOMWriter();

		MemBufFormatTarget myFormTarget;

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

		const XMLByte *Result= myFormTarget.getRawBuffer();

		delete theSerializer;
#endif

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

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

	return (int) ProtoNumber;
}
コード例 #21
0
ファイル: ili2reader.cpp プロジェクト: imincik/pkg-gdal
OGRLineString *getLineString(DOMElement *elem, int bAsLinearRing) {
  // elem -> POLYLINE
  OGRLineString *ls;
  if (bAsLinearRing)
      ls = new OGRLinearRing();
  else
      ls = new OGRLineString();

  DOMElement *lineElem = (DOMElement *)elem->getFirstChild();
  while (lineElem != NULL) {
    char* pszTagName = XMLString::transcode(lineElem->getTagName());
    if (cmpStr(ILI2_COORD, pszTagName) == 0)
    {
      OGRPoint* poPoint = getPoint(lineElem);
      ls->addPoint(poPoint);
      delete poPoint;
    }
    else if (cmpStr(ILI2_ARC, pszTagName) == 0) {
      // end point
      OGRPoint *ptEnd = new OGRPoint();
      // point on the arc
      OGRPoint *ptOnArc = new OGRPoint();
      // radius
      double radius = 0;

      DOMElement *arcElem = (DOMElement *)lineElem->getFirstChild();
      while (arcElem != NULL) {
        char* pszTagName = XMLString::transcode(arcElem->getTagName());
        char* pszObjValue = getObjValue(arcElem);
        if (cmpStr("C1", pszTagName) == 0)
          ptEnd->setX(atof(pszObjValue));
        else if (cmpStr("C2", pszTagName) == 0)
          ptEnd->setY(atof(pszObjValue));
        else if (cmpStr("C3", pszTagName) == 0)
          ptEnd->setZ(atof(pszObjValue));
        else if (cmpStr("A1", pszTagName) == 0)
          ptOnArc->setX(atof(pszObjValue));
        else if (cmpStr("A2", pszTagName) == 0)
          ptOnArc->setY(atof(pszObjValue));
        else if (cmpStr("A3", pszTagName) == 0)
          ptOnArc->setZ(atof(pszObjValue));
        else if (cmpStr("R", pszTagName) == 0)
          radius = atof(pszObjValue);
        CPLFree(pszObjValue);
        XMLString::release(&pszTagName);

        arcElem = (DOMElement *)arcElem->getNextSibling();
      }

      ptEnd->flattenTo2D();
      ptOnArc->flattenTo2D();
      OGRPoint *ptStart = getPoint((DOMElement *)lineElem->getPreviousSibling()); // COORD or ARC
      interpolateArc(ls, ptStart, ptOnArc, ptEnd, PI/180);

      delete ptStart;
      delete ptEnd;
      delete ptOnArc;
    } /* else { // FIXME StructureValue in Polyline not yet supported
    } */
    XMLString::release(&pszTagName);

    lineElem = (DOMElement *)lineElem->getNextSibling();
  }

  return ls;
}
コード例 #22
0
//------------------------------------------------------------------------
//
//  processTestFile   Given the file name of an encoding test xml file,
//                    run it.
//
//------------------------------------------------------------------------
static bool  processTestFile(const XMLCh* fileName)
{
    //
    //  Send the input file through the parse, create a DOM document for it.
    //
    char cFileName[4000];
    XMLString::transcode(fileName, cFileName, 3999);
    DOMDocument* testDoc = parseFile(cFileName);
    if (testDoc == 0)
        return false;    // parse errors in the source xml.

    //
    //  Pull the "data" element out of the document.
    //
    XMLCh tempStr[4000];
    XMLString::transcode("data", tempStr, 3999);
    DOMNodeList* nl = testDoc->getElementsByTagName(tempStr);
    if (nl->getLength() != 1) {
        fprintf(stderr, "Test file \"%s\" must have exactly one \"data\" element.\n", cFileName);
        return false;
    };
    DOMNode* tmpNode = nl->item(0);
    DOMElement* data = (DOMElement*) tmpNode;


    //
    //  Build up a string containing the character data contents of the data element.
    //
    DOMNode* child;
    XMLBuffer elData;
    for (child=data->getFirstChild(); child != 0; child= child->getNextSibling())
    {
		if (child->getNodeType() == DOMNode::COMMENT_NODE)
			continue;
        if (! (child->getNodeType() == DOMNode::TEXT_NODE ||
               child->getNodeType() == DOMNode::CDATA_SECTION_NODE ||
               child->getNodeType() == DOMNode::ENTITY_REFERENCE_NODE))
        {
               fprintf(stderr, "Test file \"%s\": data element contains unexpected children.",
                    cFileName);
               return false;
        }
        elData.append(((DOMCharacterData *)child)->getData());
    };

    //
    //  Pull the "udata" element out of the document
    //
    XMLString::transcode("udata", tempStr, 3999);
    nl = testDoc->getElementsByTagName(tempStr);
    if (nl->getLength() != 1) {
        fprintf(stderr, "Test file \"%s\" must have exactly one \"udata\" element.\n", cFileName);
        return false;
    };
    DOMNode* tmpNode1 = nl->item(0);
    DOMElement* udata = (DOMElement*) tmpNode1;

    //
    //  Build up a string containing the character data contents of the udata element.
    //  This will consist of a whole bunch hex numbers, still in string from
    //

    XMLBuffer rawUData;
    for (child=udata->getFirstChild(); child != 0; child= child->getNextSibling())
    {
        if (child->getNodeType() == DOMNode::COMMENT_NODE)
            continue;
        if (! (child->getNodeType() == DOMNode::TEXT_NODE ||
            child->getNodeType() == DOMNode::CDATA_SECTION_NODE ||
            child->getNodeType() == DOMNode::ENTITY_REFERENCE_NODE))
        {
            fprintf(stderr, "Test file \"%s\": udata element contains unexpected children.",
                cFileName);
            return false;
        }
        rawUData.append(((DOMCharacterData *)child)->getData());
    };


    //
    // Convert the raw (hex numbers)  form of the udata to the corresponding string.
    //
    XMLBuffer uData;
    unsigned int rawIndex = 0;

    while (rawIndex < rawUData.getLen())
    {
        eatWhiteSpace(rawUData.getRawBuffer(), rawIndex);
        XMLCh c = convertHexValue(rawUData.getRawBuffer(), rawIndex);
        if (c > 0)
            uData.append(c);
        else
            if (rawIndex < rawUData.getLen())
            {
                fprintf(stderr, "Test file \"%s\": Bad hex number in udata element.  "
                    "Data character number %d\n", cFileName, uData.getLen());
                return false;
            }
    }


    //
    // Compare the two strings.
    //
    unsigned int i;
    for (i=0; i< elData.getLen(); i++)
    {
        XMLCh* elDataRaw = elData.getRawBuffer();
        XMLCh* uDataRaw = uData.getRawBuffer();
        if (i >= uData.getLen())
        {
            fprintf(stderr, "Test file \"%s\": udata element shorter than data at char number %d\n",
                cFileName, i);
            writeUData(elDataRaw);
            return false;
        }
        if (uDataRaw[i] != elDataRaw[i])
        {
            fprintf(stderr, "Test file \"%s\": comparison failure at character number %d\n",
                cFileName, i);
            writeUData(elDataRaw);
            return false;
        };
    }

    if (elData.getLen() != uData.getLen())
    {
        fprintf(stderr, "Test file \"%s\": udata element longer than data at char number %d\n",
            cFileName, i);
        writeUData(elData.getRawBuffer());
        return false;
    }

    return true;
}
コード例 #23
0
BatchItem BatchFlatfileStorage::dequeue()
{
	DEBUG( "Dequeue" );
	if( !m_CrtStorage.is_open() )
	{
		stringstream errorMessage;
		errorMessage << "Batch file [" << m_CrtStorageId << "] was not opened";
		
		TRACE( errorMessage.str() );
		throw runtime_error( errorMessage.str() );
	}
	
	if ( m_NextItem.getSequence() == BatchItem::INVALID_SEQUENCE )
	{
		TRACE( "Attempt to read past the end of the batch file" );
		throw runtime_error( "Attempt to read past the end of the batch file" );
	}
	
	// alloc buffer and perform a first read
	DEBUG( "Buffer is " << ( ( m_Buffer == NULL ) ? "empty" : "available " ) );
	
	if ( m_Buffer == NULL )
	{
		DEBUG( "Allocating buffer [" << m_ChunkSize << "] bytes ..." );
		m_Buffer = new unsigned char[ m_ChunkSize + 1 ];
		m_CrtIndex = 0;
		memset( m_Buffer, 0, m_ChunkSize + 1 );
		
		m_CrtStorage.read( ( char * )m_Buffer, m_ChunkSize );
		m_BufferLength = m_CrtStorage.gcount();

		string bufferEx = "";
		if ( m_BufferLength > 100 )
			bufferEx = string( ( char * )m_Buffer, 100 ) + string( "..." );
		else
			bufferEx = string( ( char * )m_Buffer );
		DEBUG( "Position in file is [" << m_BufferLength << "]. Buffer is [" << bufferEx << "]" );
	}

	BatchItem item( m_NextItem );

	XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument* outputData = NULL;
	DOMImplementation* implementation = DOMImplementationRegistry::getDOMImplementation( unicodeForm( "Core" ) );
	outputData = implementation->createDocument(
		0,						// root element namespace URI.
		unicodeForm( "root" ),	// root element name
		0 );					// document type object (DTD).

	try
	{
		DOMElement* rootElem = outputData->createElement( unicodeForm( "Message" ) );
		DEBUG( "Root element created." );
				
		outputData->getDocumentElement()->appendChild( rootElem );
		DEBUG( "Root node appended." );

		bool matched = false;
		
		// if there is no parser ( no template ) just base64 what we read and consider a match
		if ( m_Parser.getTemplateFile().length() == 0 )
		{
			matched = ( m_BufferLength > 0 );

			/*// quick workaround xmling
			string base64Value = "<bin>" + Base64::encode( m_Buffer, m_BufferLength ) + "</bin>";  

			//recreate the template structure as if there was one
			XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument* doc = rootElem->getOwnerDocument();
			DOMElement* element = doc->createElement( unicodeForm( "dummy" ) );
			rootElem->appendChild( element );

			DOMElement* secelement = doc->createElement( unicodeForm( "dummy" ) );
			element->appendChild( secelement );

			secelement->setAttribute( unicodeForm( "base64" ), unicodeForm( base64Value ) );*/
		}
		else
		{
			DEBUG( "Attempting match of batch template at index [" << m_CrtIndex << "] ..." );
			try
			{
				ManagedBuffer inputBuffer( m_Buffer + m_CrtIndex, ManagedBuffer::Ref, m_ChunkSize - m_CrtIndex );
				matched = m_Parser.Matches( inputBuffer, rootElem );
			}
			catch( ... )
			{
				TRACE( "Match failed" );
				throw;
			}
		}
		DEBUG( "Match " << ( matched ? "successful" : "failed" ) );
		
		if ( !matched )
		{
			DEBUG( "Template doesn't match .." );
			// if end of file, no more reads
			if ( m_CrtStorage.eof() )
			{
				DEBUG( "EOF" );
				// no items read
				if ( m_CrtSequence == 0 )
				{
					DEBUG( "Current sequence is 0" );
					stringstream errorMessage;
					errorMessage << "Batch file [" << m_CrtStorageId << "] contains no usable data";
					TRACE( errorMessage.str() );
					throw runtime_error( errorMessage.str() );
				}
				DEBUG( "Current sequence is [" << m_CrtSequence << "] at index [" << m_CrtIndex << "]. Buffer size [" << m_BufferLength << "]" );
				
				if ( m_CrtIndex == m_BufferLength )
				{
					item.setSequence( BatchItem::LAST_IN_SEQUENCE );
					item.setLast();
					m_NextItem.setSequence( BatchItem::INVALID_SEQUENCE );
				}
				else
				{
					stringstream errorMessage;
					errorMessage << "Batch file [" << m_CrtStorageId << "] contains no usable data";
					TRACE( errorMessage.str() );
					throw runtime_error( errorMessage.str() );
				}
				
			}
			// is not end of file, but template doesn't match
			// reason : wrong format or Chunksize is not multiple of message size
			// solution: 
			// 		repositoning in the file back to the end of the last match and delete the buffer and dequeue again
			//		if match is OK the file is parsed with next chunk
			//		if it was a problem with the format the first match failed, crtIndex will be 0 and will throw an exception
			//		
			else
			{
				if ( m_CrtIndex == 0 )
				{
					DEBUG( "Current position in chunk is "  );
					stringstream errorMessage;
					errorMessage << "Batch file [" << m_CrtStorageId << "] contains no usable data";
					TRACE( errorMessage.str() );
					throw runtime_error( errorMessage.str() );	
				}
				else
				{
					//repositioning in the file to the end of the last match 
					DEBUG( "Current position in chunk is " << m_CrtIndex );
					m_CrtStorage.seekg( m_CrtIndex - m_ChunkSize, ios::cur );
					// reset the chunk
					if ( m_Buffer != NULL )
					{
						delete[] m_Buffer;
						m_Buffer = NULL;
					}
					//try with next chunk or reset the chunk and verify if it is bad formatted storage
					dequeue();
					
				}
			}
			// realloc buffer
		}
		else // template matched
		{
			m_NextItem.setSequence( m_CrtSequence++ );
			m_NextItem.setBatchId( m_CrtStorageId );
			m_NextItem.setMessageId( Collaboration::GenerateGuid() );

			if ( m_Parser.getTemplateFile().length() == 0 )
			{	
				// quick workaround xmling
				string base64Value = Base64::encode( m_Buffer, m_BufferLength );  
				rootElem->setAttribute( unicodeForm( "base64" ), unicodeForm( base64Value ) );

				m_NextItem.setPayload( XmlUtil::SerializeToString( outputData ) );

				// reset the chunk
				if ( m_Buffer != NULL )
				{
					delete[] m_Buffer;
					m_Buffer = NULL;
				}
			}
			else
			{
				m_CrtIndex += m_Parser.getMatchEnd();
			
				DEBUG( "End point for match is : " << m_CrtIndex );
			
				// from root( Message ) -> child ( template format ) -> child ( selection friendly name ) -> attribute ( data )
				if( rootElem == NULL )
					throw logic_error( "Root empty" );
				if( rootElem->getFirstChild() == NULL )
					throw logic_error( "Template child empty" );
				if( rootElem->getFirstChild()->getFirstChild() == NULL )
				{
					TRACE( XmlUtil::SerializeToString( rootElem ) );
					throw logic_error( "Template child2 empty" );
				}

				DOMNamedNodeMap *attributes = rootElem->getFirstChild()->getFirstChild()->getAttributes();
				if ( attributes != NULL )
				{
					DEBUG( "Number of attributes for selection : " << attributes->getLength() );
				
					for ( unsigned int i=0; i<attributes->getLength(); i++ )
					{
						DOMAttr *attribute = dynamic_cast< DOMAttr * >( attributes->item( i ) );
						if ( attribute == NULL )
							continue;

						string attributeName = localForm( attribute->getName() );
						string attributeValue = localForm( attribute->getValue() );
					
						string attributeValueToLog = ( attributeValue.length() > 100 ) ? attributeValue.substr( 0, 100 ) + string( "..." ) : attributeValue;
						DEBUG( "Attribute [" << attributeName << "] = [" << attributeValueToLog << "]" );
						m_NextItem.setPayload( attributeValue );
					}
				}
			}
		}
		if ( outputData != NULL )
		{
			outputData->release();
			outputData = NULL;
		}
	}
	catch( ... )
	{
		if ( outputData != NULL )
		{
			outputData->release();
			outputData = NULL;
		}
		throw;
	}
	return item;
}
コード例 #24
0
ファイル: main.cpp プロジェクト: lgwizme/macaon
// 2006/11/07
void handleDocument(DOMDocument* document, char* outputfile)
{
  if (document == NULL) {
    cerr << _PREFIX_ << "WARNING null XML Document\n";
    return;
  }
  DOMElement* docElement = NULL;
  docElement = document->getDocumentElement();

  if (docElement == NULL) {
    cerr << _PREFIX_ << "WARNING null XML Document Element\n";
    return;
  }


  DOMNodeList* sections = docElement->getElementsByTagName(XMLString::transcode("section"));
  int sCount = 0;
  int paragraphID = 1;

  for (unsigned int i = 0; i < sections->getLength(); i++) {
    int sectID = i+1;
    if (verbose) cerr << _PREFIX_ << "Section " << i;
    DOMElement* aSect = NULL;
    aSect = (DOMElement*)sections->item(i);
    string sectName = XMLString::transcode(((DOMElement*)aSect)->getAttribute(XMLString::transcode("name")));
    string analyze =
      XMLString::transcode(((DOMElement*)aSect)->getAttribute(XMLString::transcode("analyze")));
    if (verbose) cerr << " ['" << sectName << "'";
    // Ignore non affected sections 
    if ( ( analyze == "yes" ) ||
         ( sectName.length() == 0 ) ||
         ( affectedSections.find(sectName + "|") != string::npos )) {      
      
      if (verbose) cerr << " analyze=yes ";
      // Deal with unnamed and affected sections

      // create a stream
      aSect->normalize();
      stringstream text(XMLString::transcode(aSect->getTextContent()));

      if (verbose) {
        string temp(XMLString::transcode(aSect->getTextContent()));
        cerr << temp.length() << " charcters]\n" << _PREFIX_ << "           ";
      }

      aSect->removeChild(aSect->getFirstChild());

      vector<vector<string> > result;
      result = seg->segmentInVectors(text);

      for(vector<vector<string> >::iterator itp = result.begin(); 
          itp != result.end(); 
          itp++) {
        stringstream parID;
        parID << _ID_PREFIX_SECTION << sectID << _ID_PREFIX_PARAGRAPH << paragraphID++;
        sCount += addSegmentedParagraphToSection(*itp,aSect,parID.str().c_str());
      }
   
      if (verbose) cerr << endl;
    } else {
      if (verbose) cerr << " analyze=no]" << endl;
    }
  }

  if (stamp) stampDocument(docElement);

  /* SERIALIZE XML DOCUMENT */
  if (outputfile == NULL) xmlInterface->serializeTo(document);
  else xmlInterface->serializeTo(document,outputfile);

  if (verbose) cerr << _PREFIX_ << "Segmented in " << sCount << " sentences." << endl;
}
コード例 #25
0
void pop_monteTest::testReportML()
{
  printf( "\n--- %s ---\n", "Report Test" );
  const double scale = 0.05;

  //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  // Parse the generated reportML document.
  //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  xercesc::XercesDOMParser *reportParser = new xercesc::XercesDOMParser;
  reportParser->setValidationScheme( XercesDOMParser::Val_Auto );
  reportParser->setDoNamespaces( true );
  reportParser->setDoSchema( true );
  reportParser->setValidationSchemaFullChecking( true );
  reportParser->setCreateEntityReferenceNodes( true );
  
  try{
    reportParser->parse( fSavedReportML );
  }
  catch( const XMLException& e )
    {
      XMLPlatformUtils::Terminate();
      char buf[MAXCHARS + 1];
      snprintf( buf, MAXCHARS, "An error occurred during parsing %s.\n   Message: %s\n",
	       fReportML, XMLString::transcode(e.getMessage() ) );
      
      CPPUNIT_ASSERT_MESSAGE( buf, false );
    }
  catch( const DOMException& e )
    {
      
      XMLCh errText[MAXCHARS + 1]; 
      if (DOMImplementation::loadDOMExceptionMsg(e.code, errText, MAXCHARS))
	{
          XMLPlatformUtils::Terminate();
          char buf[MAXCHARS + 1];
          snprintf( buf, MAXCHARS, "DOM Error during parsing \"%s\".\nDOMException code is: %d.\nMessage is: %s.\n",
                   fReportML, e.code, XMLString::transcode(errText) );
          CPPUNIT_ASSERT_MESSAGE( buf, false );
	}
    }
  catch( ... )
    {
      XMLPlatformUtils::Terminate();
      char buf[MAXCHARS + 1];
      snprintf( buf, MAXCHARS, "An unknown error occurred during parsing %s.\n", fSavedReportML );
      
      CPPUNIT_ASSERT_MESSAGE( buf, false );
    }
  
  report = reportParser->getDocument();
  CPPUNIT_ASSERT( report );

  //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  // Verify if any error was caught during the runtime.
  // The <eroor_list> tag should appear even when there's no error.
  // However, it should not contain any error message.
  //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  DOMNodeList *error_list;
  error_list = report->getElementsByTagName( XML.X_ERROR_LIST );
  CPPUNIT_ASSERT_EQUAL( 1, (int)error_list->getLength() );
  DOMElement* error = dynamic_cast<DOMElement*>( error_list->item(0) );
  if( error->hasChildNodes() )
  {
     const XMLCh* error_message = error->getFirstChild()->getNodeValue();
     CPPUNIT_ASSERT_MESSAGE( "<error_list> should have been empty.", XMLString::isAllWhiteSpace( error_message ) );
  }
  else
  {
     CPPUNIT_ASSERT( true );
  }
   
  //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  // Verify the objective value.
  //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  double obj_out = 0.0;
  DOMNodeList * objOut_list = report->getElementsByTagName( XML.X_POP_OBJ_OUT );
  if( objOut_list->getLength() > 0 )
    {
      DOMElement* objOut = dynamic_cast<DOMElement*>( objOut_list->item(0) );
      DOMNodeList* value_list = objOut->getElementsByTagName( XML.X_VALUE );
      int n = value_list->getLength();
      CPPUNIT_ASSERT_EQUAL( 1, n );
      obj_out = atof( XMLString::transcode( value_list->item(0)->getFirstChild()->getNodeValue() ) );      
      // CPPUNIT_ASSERT_DOUBLES_EQUAL( nm_obj, obj_out, scale * nm_obj );
    }

  //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  // Verify the final estimate for theta
  //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  double theta_out[thetaLen];
  DOMNodeList * thetaOut_list = report->getElementsByTagName( XML.X_THETA_OUT );
  if( thetaOut_list->getLength() > 0 )
    {
      DOMElement* thetaOut = dynamic_cast<DOMElement*>( thetaOut_list->item(0) );
      DOMNodeList* value_list = thetaOut->getElementsByTagName( XML.X_VALUE );
      int n = value_list->getLength();
      CPPUNIT_ASSERT_EQUAL( thetaLen, n );
      for( int i=0; i<n; i++ )
	{
	  theta_out[i] = atof( XMLString::transcode( value_list->item(i)->getFirstChild()->getNodeValue() ) );
	  //CPPUNIT_ASSERT_DOUBLES_EQUAL( nm_theta[i], theta_out[i], scale * nm_theta[i] );
	}
    }

  //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  // Verify the final estimate for Omega
  //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  double omega_out[omegaOrder];
  DOMNodeList * omegaOut_list = report->getElementsByTagName( XML.X_OMEGA_OUT );
  if( omegaOut_list->getLength() > 0 )
    {
      DOMElement* omegaOut = dynamic_cast<DOMElement*>( omegaOut_list->item(0) );
      DOMNodeList* value_list = omegaOut->getElementsByTagName( XML.X_VALUE );
      int n = value_list->getLength();
      CPPUNIT_ASSERT_EQUAL( omegaOrder, n );
      for( int i=0; i<+n; i++ )
	{
	  omega_out[i] = atof( XMLString::transcode( value_list->item(i)->getFirstChild()->getNodeValue() ) );
	  //CPPUNIT_ASSERT_DOUBLES_EQUAL( nm_omega[i], omega_out[i], scale * nm_omega[i] );
	}
    }

  //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  // Grab a pointer to the top of "pop_monte_result" sub-tree.
  //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  DOMNodeList *pop_monte_result = report->getElementsByTagName( XML.X_POP_MONTE_RESULT );
  CPPUNIT_ASSERT( pop_monte_result->getLength() == 1 );
  DOMElement *ind_stat_result = dynamic_cast<DOMElement*>( pop_monte_result->item( 0 ) );
  CPPUNIT_ASSERT( ind_stat_result != NULL );
  okToClean = true;
}
コード例 #26
0
ファイル: ili2reader.cpp プロジェクト: Wedjaa/node-gdal
static OGRCompoundCurve *getPolyline(DOMElement *elem) {
  // elem -> POLYLINE
  OGRCompoundCurve *ogrCurve = new OGRCompoundCurve();
  OGRLineString *ls = new OGRLineString();

  DOMElement *lineElem = (DOMElement *)elem->getFirstChild();
  while (lineElem != NULL) {
    char* pszTagName = XMLString::transcode(lineElem->getTagName());
    if (cmpStr(ILI2_COORD, pszTagName) == 0)
    {
      OGRPoint* poPoint = getPoint(lineElem);
      ls->addPoint(poPoint);
      delete poPoint;
    }
    else if (cmpStr(ILI2_ARC, pszTagName) == 0) {
      //Finish line and start arc
      if (ls->getNumPoints() > 1) {
        ogrCurve->addCurveDirectly(ls);
        ls = new OGRLineString();
      } else {
        ls->empty();
      }
      OGRCircularString *arc = new OGRCircularString();
      // end point
      OGRPoint *ptEnd = new OGRPoint();
      // point on the arc
      OGRPoint *ptOnArc = new OGRPoint();
      // radius
      // double radius = 0;

      DOMElement *arcElem = (DOMElement *)lineElem->getFirstChild();
      while (arcElem != NULL) {
        char* pszTagName2 = XMLString::transcode(arcElem->getTagName());
        char* pszObjValue = getObjValue(arcElem);
        if (cmpStr("C1", pszTagName2) == 0)
          ptEnd->setX(CPLAtof(pszObjValue));
        else if (cmpStr("C2", pszTagName2) == 0)
          ptEnd->setY(CPLAtof(pszObjValue));
        else if (cmpStr("C3", pszTagName2) == 0)
          ptEnd->setZ(CPLAtof(pszObjValue));
        else if (cmpStr("A1", pszTagName2) == 0)
          ptOnArc->setX(CPLAtof(pszObjValue));
        else if (cmpStr("A2", pszTagName2) == 0)
          ptOnArc->setY(CPLAtof(pszObjValue));
        else if (cmpStr("A3", pszTagName2) == 0)
          ptOnArc->setZ(CPLAtof(pszObjValue));
        else if (cmpStr("R", pszTagName2) == 0) {
          // radius = CPLAtof(pszObjValue);
        }
        CPLFree(pszObjValue);
        XMLString::release(&pszTagName2);

        arcElem = (DOMElement *)arcElem->getNextSibling();
      }

      OGRPoint *ptStart = getPoint((DOMElement *)lineElem->getPreviousSibling()); // COORD or ARC
      arc->addPoint(ptStart);
      arc->addPoint(ptOnArc);
      arc->addPoint(ptEnd);
      ogrCurve->addCurveDirectly(arc);

      delete ptStart;
      delete ptEnd;
      delete ptOnArc;
    } /* else { // TODO: StructureValue in Polyline not yet supported
    } */
    XMLString::release(&pszTagName);

    lineElem = (DOMElement *)lineElem->getNextSibling();
  }

  if (ls->getNumPoints() > 1) {
    ogrCurve->addCurveDirectly(ls);
  }
  else {
    delete ls;
  }
  return ogrCurve;
}
コード例 #27
0
    Weapon* ItemDataLoader::processWeapon(int group, DOMElement* weaponXml)
    {
		// Itemname
		CeGuiString name = XmlHelper::getAttributeValueAsString(weaponXml,"Name");
		// Beschreibung
		CeGuiString desc = XmlHelper::getAttributeValueAsString(weaponXml,"Beschreibung");
		// Eindeutiger Zuordner
		CeGuiString id = XmlHelper::getAttributeValueAsString(weaponXml,"ID");

		// Image fürs Inventar
		CeGuiString imageName = XmlHelper::getValueAsString(XmlHelper::getChildNamed(weaponXml, "Bildname"));

		// Größe im Inventar
		int size_x = XmlHelper::getAttributeValueAsInteger(XmlHelper::getChildNamed(weaponXml, "Größe"),"X");
		int size_y = XmlHelper::getAttributeValueAsInteger(XmlHelper::getChildNamed(weaponXml, "Größe"),"Y");

		// Containerplatz für andere Gegenstände, die dieser aufnahmen kann
		int place_x = XmlHelper::getAttributeValueAsInteger(XmlHelper::getChildNamed(weaponXml, "Platz"),"X");
		int place_y = XmlHelper::getAttributeValueAsInteger(XmlHelper::getChildNamed(weaponXml, "Platz"),"Y");

		// Schaden der Waffe in Anzahl W6, W20 und Modifikator
		DOMElement* tpNode = XmlHelper::getChildNamed(weaponXml, "TP");
		int w6 = XmlHelper::getAttributeValueAsInteger(tpNode, "W6");
		int w20 = XmlHelper::getAttributeValueAsInteger(tpNode, "W20");
		int boni = XmlHelper::getAttributeValueAsInteger(tpNode, "Boni");

		// TP / KK
		int tp = XmlHelper::getAttributeValueAsInteger(XmlHelper::getChildNamed(weaponXml, "TpKk"), "Tp");
		int kk = XmlHelper::getAttributeValueAsInteger(XmlHelper::getChildNamed(weaponXml, "TpKk"), "Kk");

		// Bruchfaktor
		int bf = XmlHelper::getValueAsInteger(XmlHelper::getChildNamed(weaponXml, "Bf"));
		//Initiative bonus
		int ini = XmlHelper::getValueAsInteger(XmlHelper::getChildNamed(weaponXml, "Ini"));

		// Distanzklasse
		int dK = Weapon::DK_N;
		DOMElement* dkNode = XmlHelper::getChildNamed(weaponXml, "Dk");
		if (dkNode != NULL)
			dK = getDKFromString(AutoChar(dkNode->getFirstChild()->getNodeValue()).data());
		
		CeGuiString talent = XmlHelper::getValueAsString(XmlHelper::getChildNamed(weaponXml, "Talent"));

		CeGuiString mesh = XmlHelper::getValueAsString(XmlHelper::getChildNamed(weaponXml, "Mesh"));

		int length = XmlHelper::getValueAsInteger(XmlHelper::getChildNamed(weaponXml, "Länge"));
		int weight = XmlHelper::getValueAsInteger(XmlHelper::getChildNamed(weaponXml, "Gewicht"));

		int attackMod = XmlHelper::getAttributeValueAsInteger(XmlHelper::getChildNamed(weaponXml, "WM"), "Attacke");
		int paradeMod = XmlHelper::getAttributeValueAsInteger(XmlHelper::getChildNamed(weaponXml, "WM"), "Parade");

		int preis = XmlHelper::getValueAsInteger(XmlHelper::getChildNamed(weaponXml, "Preis"));

		// Neuen Waffenprototyp erzeugen und zurückgeben
		Weapon* w = new Weapon(
			name,
			desc
			);
		w->setImageName(imageName);
		w->setMeshName(mesh);
		w->setItemType(Item::ITEMTYPE_WEAPON);
		w->setSize(size_x,size_y);
		if (place_x > 0 && place_y > 0)
		{
			w->setContainer(true,make_pair<int,int>(place_x,place_y));
		}
		w->setTp(w6, w20, boni);
		w->setTpKk(tp, kk);
		w->setBf(bf);
		w->setIni(ini);
		w->setWeight(weight);
		w->setDk(static_cast<Weapon::Distanzklasse>(dK));
		w->setKampftechnik(talent);
		w->setPrice(preis);
        return w;
    }
コード例 #28
0
ret_ CXMLLoaderActions::Load(XercesDOMParser *pParser,
							 const ch_1 *pszEnvironmentPath)
{
#ifdef _DEBUG_
	if (!pParser)
		return PARAMETER_NULL | PARAMETER_1;

	if (!pszEnvironmentPath)
		return PARAMETER_NULL | PARAMETER_2;

	if (null_v == pszEnvironmentPath[0])
		return PARAMETER_EMPTY | PARAMETER_2;
#endif

	SetParser(pParser);

	ch_1 sActions[ENVIRONMENT_PATH_LENGTH];

	memset(sActions, 0, ENVIRONMENT_PATH_LENGTH);
	sprintf(sActions, "%s%s", pszEnvironmentPath, ACTIONS_XML_FILE);

	DOMDocument *pActionsDoc = null_v;

	try
	{
		GetParser()->parse(sActions);
        pActionsDoc = GetParser()->getDocument();
	}
    catch (const OutOfMemoryException &err)
    {
		auto_xerces_str sErr(err.getMessage());

		printf("%s\n", (const ch_1 *)sErr);

 		return XML_LOADER_ERROR;
    }
	catch (const XMLException &err)
    {
		auto_xerces_str sErr(err.getMessage());

		printf("%s\n", (const ch_1 *)sErr);

 		return XML_LOADER_ERROR;
	}
    catch (const DOMException &err)
    {
		auto_xerces_str sErr(err.msg);

		printf("%s\n", (const ch_1 *)sErr);

 		return XML_LOADER_ERROR;
	}
	catch (...)
    {
		printf("Unexpected error during parsing.\n");

		return XML_LOADER_ERROR;
    }

	if (!pActionsDoc)
		return XML_LOADER_ERROR;
	
	DOMElement *pRoot = pActionsDoc->getDocumentElement();

	if (!pRoot)
		return XML_LOADER_ERROR;

	DOMElement *pChild = (DOMElement *)pRoot->getFirstChild();

	if (!pChild)
		return XML_LOADER_ERROR;

	auto_xerces_str wsDataBlock("data_block");
	auto_xerces_str wsStart("start");
	auto_xerces_str wsProcessor("processor");
	auto_xerces_str wsEnd("end");

	while (pChild)
	{
		if (0 == XMLString::compareString(pChild->getNodeName(),
										  wsDataBlock))
		{
			if (SUCCESS != LoadDataBlock(CUIManager::Instance()->Data(),
										 pChild))
			{
				return XML_LOADER_ERROR;
			}
		}
		else if (0 == XMLString::compareString(pChild->getNodeName(),
											   wsStart))
		{
			if (SUCCESS != LoadProgram(&CUIManager::Instance()->Data(),
									   CUIManager::Instance()->StartProgram(),
									   pChild))
			{
				return XML_LOADER_ERROR;
			}
		}
		else if (0 == XMLString::compareString(pChild->getNodeName(),
											   wsProcessor))
		{
			if (SUCCESS != LoadProcessor(pChild))
				return XML_LOADER_ERROR;

			m_pTmpContainer = null_v;
		}
		else if (0 == XMLString::compareString(pChild->getNodeName(),
											   wsEnd))
		{
			if (SUCCESS != LoadProgram(&CUIManager::Instance()->Data(),
									   CUIManager::Instance()->EndProgram(),
									   pChild))
			{
				return XML_LOADER_ERROR;
			}
		}

		pChild = (DOMElement *)pChild->getNextSibling();
	}

	return SUCCESS;
}
コード例 #29
0
ret_ CXMLLoaderNetwork::Load(XercesDOMParser *pParser,
							 const ch_1 *pszEnvironmentPath)
{
	_START(LOAD);

#ifdef _DEBUG_
	if (!pParser)
		_RET(PARAMETER_NULL | PARAMETER_1);

	if (!pszEnvironmentPath)
		_RET(PARAMETER_NULL | PARAMETER_2);

	if (null_v == pszEnvironmentPath[0])
		_RET(PARAMETER_EMPTY | PARAMETER_2);
#endif

	SetParser(pParser);

	ch_1 sNetwork[ENVIRONMENT_PATH_LENGTH];

	memset(sNetwork, 0, ENVIRONMENT_PATH_LENGTH);
	strncpy(sNetwork, pszEnvironmentPath, ENVIRONMENT_PATH_LENGTH);
	strncat(sNetwork, NETWORK_XML_FILE, ENVIRONMENT_PATH_LENGTH);

	DOMDocument *pNetworkDoc = null_v;

	try
	{
		GetParser()->parse(sNetwork);
        pNetworkDoc = GetParser()->getDocument();
	}
    catch (const OutOfMemoryException &err)
    {
		auto_xerces_str sErr(err.getMessage());

		printf("%s\n", (const ch_1 *)sErr);

 		_RET(XML_LOADER_ERROR);
    }
	catch (const XMLException &err)
    {
		auto_xerces_str sErr(err.getMessage());

		printf("%s\n", (const ch_1 *)sErr);

 		_RET(XML_LOADER_ERROR);
	}
    catch (const DOMException &err)
    {
        auto_xerces_str sErr(err.getMessage());

		printf("%s\n", (const ch_1 *)sErr);

 		_RET(XML_LOADER_ERROR);
	}
	catch (...)
    {
		printf("Unexpected error during parsing.\n");

		_RET(XML_LOADER_ERROR);
    }

	DOMElement *pRoot = pNetworkDoc->getDocumentElement();

	if (!pRoot)
		_RET(XML_LOADER_ERROR);

	DOMElement *pChild = (DOMElement *)pRoot->getFirstChild();

	if (!pChild)
		_RET(XML_LOADER_ERROR);

	auto_xerces_str wsIdentity		("identity");
	auto_xerces_str wsPDU			("pdu");
	auto_xerces_str wsDirection		("direction");
	auto_xerces_str	wsName			("name");
	auto_xerces_str	wsProtocolName	("protocol");
	auto_xerces_str wsCommandID		("command_id");
	auto_xerces_str wsSizeID		("size_id");
	auto_xerces_str	wsLocalPort		("local_port");
	auto_xerces_str wsAuto			("auto");

	auto_xerces_str wsFilter		("filter");
	auto_xerces_str wsMaxConnections("max_connections");
	auto_xerces_str wsRemoteIP		("remote_ip");
	auto_xerces_str	wsRemotePort	("remote_port");
	auto_xerces_str wsReconnect		("reconnect");

	auto_xerces_str wsAcceptorName	("acceptor");
	auto_xerces_str	wsConnectorName	("connector");
 	auto_xerces_str wsReceiverName	("receiver");
	auto_xerces_str wsSenderName	("sender");

	auto_xerces_str wsType			("type");


	while (pChild)
    {
		ENetworkType NetworkType = NETWORK_NONE;
		CProtocolInfo *pProtocol = null_v;
		CField *pCommandIDField	= null_v;
		CField *pSizeIDField = null_v;
		bool_ bIsAutoStart = true_v;

		if (0 == XMLString::compareString(pChild->getNodeName(),
										  wsAcceptorName))
		{
			NetworkType = NETWORK_ACCEPTOR;
		}
		else if (0 == XMLString::compareString(pChild->getNodeName(),
											   wsConnectorName))
		{
			NetworkType = NETWORK_CONNECTOR;
		}
		else if (0 == XMLString::compareString(pChild->getNodeName(),
											   wsReceiverName))
		{
			NetworkType = NETWORK_RECEIVER;
		}
		else if (0 == XMLString::compareString(pChild->getNodeName(),
											   wsSenderName))
		{
			NetworkType = NETWORK_SENDER;
		}
		else
		{
			pChild = (DOMElement *)pChild->getNextSibling();

			continue;
		}

		auto_xerces_str sProtocolName(pChild->getAttribute(wsProtocolName));

		if (SUCCESS != _ERR(
				CXMLLoaderProtocol::Instance()->Load(pParser,
													 pszEnvironmentPath,
													 sProtocolName)))
		{
			_RET(XML_LOADER_ERROR);
		}

		//
		if (SUCCESS != _ERR(
                CProtocolManager::instance()->getProtocol(sProtocolName,
                        pProtocol)))
		{
			_RET(XML_LOADER_ERROR);
		}

		//
		auto_xerces_str sCommandID(pChild->getAttribute(wsCommandID));

        if (SUCCESS != _ERR(pProtocol->getHeadField(sCommandID,
                pCommandIDField))
			|| FIELD_NORMAL_STYLE !=
                (pCommandIDField->type() & FIELD_NORMAL_STYLE)
                || 4 < _LEN(pCommandIDField->type()))
		{
			_RET(XML_LOADER_ERROR);
		}

		//
		auto_xerces_str sSizeID(pChild->getAttribute(wsSizeID));

        if (SUCCESS != _ERR(pProtocol->getHeadField(sSizeID,
                pSizeIDField))
			|| FIELD_NORMAL_STYLE !=
                (pSizeIDField->type() & FIELD_NORMAL_STYLE)
                || 4 < _LEN(pSizeIDField->type()))
		{
			_RET(XML_LOADER_ERROR);
		}

		//
		auto_xerces_str wsAutoFalse("false");

		if (0 == XMLString::compareString(wsAutoFalse,
										  pChild->getAttribute(wsAuto)))
		{
			bIsAutoStart = false_v;
		}

        CNode *pNetwork = null_v;
		auto_xerces_str sName(pChild->getAttribute(wsName));

		switch (NetworkType)
		{
		case NETWORK_NONE:
			_RET(XML_LOADER_ERROR);
		case NETWORK_ACCEPTOR:
			{
				auto_xerces_str	sLocalPort(pChild->getAttribute(wsLocalPort));
				auto_xerces_str
					sMaxConnections(pChild->getAttribute(wsMaxConnections));

				pNetwork = new CAcceptor(pProtocol,
										 pCommandIDField,
										 pSizeIDField,
										 (ub_2)atoi(sLocalPort),
										 (size_)atoi(sMaxConnections),
										 bIsAutoStart);
			}

			break;
		case NETWORK_CONNECTOR:
			{
				//
				auto_xerces_str	nLocalPort	(pChild->getAttribute(wsLocalPort));
				auto_xerces_str	sRemoteIP	(pChild->getAttribute(wsRemoteIP));
				auto_xerces_str	nRemotePort
					(pChild->getAttribute(wsRemotePort));
				auto_xerces_str	sReconnect	(pChild->getAttribute(wsReconnect));

				pNetwork = new CConnector(pProtocol,
										  pCommandIDField,
										  pSizeIDField,
										  (ub_2)atoi(nLocalPort),
										  (const ch_1 *)sRemoteIP,
										  (ub_2)atoi(nRemotePort),
										  (b_4)atoi(sReconnect),
										  bIsAutoStart);
			}

			break;
		case NETWORK_RECEIVER:
			{
				//
				auto_xerces_str sLocalPort(pChild->getAttribute(wsLocalPort));


				pNetwork = new CReceiver(pProtocol,
										 pCommandIDField,
										 pSizeIDField,
										 (ub_2)atoi(sLocalPort),
										 bIsAutoStart);
			}

			break;
		case NETWORK_SENDER:
			{
				//
				auto_xerces_str sLocalPort(pChild->getAttribute(wsLocalPort));

				pNetwork = new CSender(pProtocol,
									   pCommandIDField,
									   pSizeIDField,
									   (ub_2)atoi(sLocalPort),
									   bIsAutoStart);
			}
		}

        CNodeConf *pNetworkConf = (CNodeConf *) pNetwork->getConf();

		//
		DOMElement *pSub = (DOMElement *)pChild->getFirstChild();

		if (!pSub)
			_RET(XML_LOADER_ERROR);

		while (pSub)
		{
			if (0 == XMLString::compareString(pSub->getNodeName(),
											  wsIdentity))
			{
				//
				auto_xerces_str sIdentity(pSub->getAttribute(wsIdentity));
				ch_1 			*sIdentityName = null_v;

				if (SUCCESS != _ERR(GetLastName(sIdentity, sIdentityName)))
					_RET(XML_LOADER_ERROR);

                v_ *pV = pProtocol->data().value(sIdentityName);

				if (!pV)
					_RET(XML_LOADER_ERROR);

				//
				auto_xerces_str	sPDU(pSub->getAttribute(wsPDU));
                CPduInfo *pPDU = null_v;

                if (SUCCESS != _ERR(pProtocol->getPdu(sPDU, pPDU)))
					_RET(XML_LOADER_ERROR);

				//
				auto_xerces_str sDirection(pSub->getAttribute(wsDirection));
				EDirection		Direction;

				if (SUCCESS != _ERR(GetDirection(sDirection, Direction)))
					_RET(XML_LOADER_ERROR);

				//
				if (SUCCESS != _ERR(pNetworkConf->ConfigPDU(*pV,
															pPDU,
															Direction)))
				{
					_RET(XML_LOADER_ERROR);
				}
			}
			else if (0 == XMLString::compareString(pSub->getNodeName(),
												   wsFilter))
			{
				CIPFilter *pIPFilter = null_v;

				if (NETWORK_ACCEPTOR == NetworkType)
				{
					pIPFilter =
						&((CAcceptorConf *)pNetworkConf)->IPFilter();
				}
				else if (NETWORK_RECEIVER == NetworkType)
				{
					pIPFilter =
						&((CReceiverConf *)pNetworkConf)->IPFilter();
				}
				else
				{
					_RET(XML_LOADER_ERROR);
				}

				auto_xerces_str sType(pSub->getAttribute(wsType));

				if (0 == strcmp(sType, "forbid")) {
                    pIPFilter->setForbid(true_v);
                } else if (0 == strcmp(sType, "permit")) {
                    pIPFilter->setForbid(false_v);
                }

                auto_xerces_str sIPGroup(pSub->getTextContent());

                if (false_v == pIPFilter->addIpGroup((const ch_1 *) sIPGroup))
					_RET(XML_LOADER_ERROR);
			}

			pSub = (DOMElement *)pSub->getNextSibling();
		}

        if (SUCCESS != _ERR(CNetworkManager::instance()->AddNetwork(
														(const char *)sName,
														NetworkType,
														pNetwork)))
		{
			_RET(XML_LOADER_ERROR);
		}

		pChild = (DOMElement *)pChild->getNextSibling();
	}

	_RET(SUCCESS);
}
コード例 #30
0
ret_ CXMLLoaderActions::LoadSend(CProgram &Program,
								 const DOMElement *pElement,
								 const CPDUInfo *pPDU)

{
#ifdef _DEBUG_
	if (!pElement)
		return (PARAMETER_NULL | PARAMETER_2);
#endif

	//
	CProtocolInfo *pProtocol = CProtocolManager::Instance()->GetProtocol();

	//
	auto_xerces_str	wsPDU	("pdu");
	auto_xerces_str	sPDU	(pElement->getAttribute(wsPDU));

	CPDUInfo *pPDUInfo = null_v;

	if (SUCCESS != (pProtocol->GetPDU(sPDU, pPDUInfo)))
		return XML_LOADER_ERROR;

	COptSend *pOperator = new COptSend(pPDUInfo);
	
	// For send operation, sub elements are not necessary.
	DOMElement *pSub = (DOMElement *)pElement->getFirstChild();

	if (pSub)
	{
		auto_xerces_str wsFieldVariable("field_variable");
		auto_xerces_str	wsFieldName("field_name");

		while (pSub)
		{
			if (0 == XMLString::compareString(pSub->getNodeName(), wsFieldVariable))
			{
				//
				DOMElement	*pVariable = (DOMElement *)pSub->getFirstChild();
				CAutoPtr<CVariable> OV_;

				if (!pVariable)
					return XML_LOADER_ERROR;

				while (pVariable)
				{
					ret_ Ret = LoadVariable(Program.Data(), 
											pVariable, 
											OV_.Ptr(),
											pPDU);

					if (SUCCESS != Ret && XML_INVALID_ELEMENT != Ret)
						return Ret;

					if (SUCCESS == Ret)
						break;

					pVariable = (DOMElement *)pVariable->getNextSibling();
				}

				//
				auto_xerces_str	sFieldName(pSub->getAttribute(wsFieldName));
				CField *pField = null_v;
			
				if (SUCCESS != pPDUInfo->GetField(sFieldName, pField))
					return XML_LOADER_ERROR;
			
				//
				if (false_v == pOperator->AddEvaluate(sFieldName, OV_.Ptr()))
					return XML_LOADER_ERROR;
			}

			pSub = (DOMElement *)pSub->getNextSibling();
		}
	}

	if (false_v == Program.AddOperator(pOperator))
		return XML_LOADER_ERROR;

	return SUCCESS;
}