Ejemplo n.º 1
0
void DOMNodeImpl::setTextContent(const XMLCh* textContent){
    DOMNode *thisNode = castToNode(this);
    switch (thisNode->getNodeType()) 
    {
        case DOMNode::ELEMENT_NODE:
        case DOMNode::ENTITY_NODE:
        case DOMNode::ENTITY_REFERENCE_NODE:
        case DOMNode::DOCUMENT_FRAGMENT_NODE:
            {
                if (isReadOnly())
                  throw DOMException(DOMException::NO_MODIFICATION_ALLOWED_ERR, 0, GetDOMNodeMemoryManager);

                // Remove all childs
                DOMNode* current = thisNode->getFirstChild();
                while (current != NULL) 
                {
                    thisNode->removeChild(current);
                    current = thisNode->getFirstChild();
                }
                if (textContent != NULL) 
                {
                    // Add textnode containing data
                    current = ((DOMDocumentImpl*)thisNode->getOwnerDocument())->createTextNode(textContent);
                    thisNode->appendChild(current);
                }
            }
            break;

        case DOMNode::ATTRIBUTE_NODE:
        case DOMNode::TEXT_NODE:
        case DOMNode::CDATA_SECTION_NODE:
        case DOMNode::COMMENT_NODE:
        case DOMNode::PROCESSING_INSTRUCTION_NODE:
            if (isReadOnly())
                throw DOMException(DOMException::NO_MODIFICATION_ALLOWED_ERR, 0, GetDOMNodeMemoryManager);

            thisNode->setNodeValue(textContent);
            break;

        case DOMNode::DOCUMENT_NODE:
        case DOMNode::DOCUMENT_TYPE_NODE:
        case DOMNode::NOTATION_NODE:
            break;

        default:
            throw DOMException(DOMException::NOT_SUPPORTED_ERR, 0, GetDOMNodeMemoryManager);
    }
}
Ejemplo n.º 2
0
void
Importer::addEdgeToScene
(xercesc::DOMNode* edgeNode, Scene* scene)
{
  XMLCh* vertex_ch = XMLString::transcode("vertex");
  std::vector<int> edge;

  for (XMLSize_t i = 0; i < edgeNode->getChildNodes()->getLength(); ++i ) {

    DOMNode* node = edgeNode->getChildNodes()->item(i);
    // Nodo <vertex>?
    if ((node->getNodeType() == DOMNode::ELEMENT_NODE) &&
  	XMLString::equals(node->getNodeName(), vertex_ch))
      edge.push_back(atoi(XMLString::transcode
			  (node->getFirstChild()->getNodeValue())));
  }

  // Recuperar los vértices a partir de su index,
  // para generar y añadir el arco.
  GraphVertex *v1 = scene->getGraph()->getVertex(edge[0]);
  GraphVertex *v2 = scene->getGraph()->getVertex(edge[1]);

  if (v1 && v2)
  {
	  scene->getGraph()->addEdge(v1, v2);
  }

  XMLString::release(&vertex_ch);
}
string CXmlConfig::getValue(DOMNode* parentNode, const string& itemName)
{
	string strValue;
	string strName;
	
	DOMNode* firstChildNode = NULL;
	charArrayToString(parentNode->getNodeName(), strName);
	if (strName == itemName)
	{
		firstChildNode = parentNode->getFirstChild();
		if (firstChildNode != NULL) charArrayToString(firstChildNode->getNodeValue(), strValue);
		return strValue;
	}
	
	DOMNodeList* nodeList = parentNode->getChildNodes();
	for (unsigned int i = 0; i < nodeList->getLength(); ++i)
	{
		DOMNode* nodeTemp = nodeList->item(i);
		if (nodeTemp->getNodeType() == DOMNode::ELEMENT_NODE)
		{
			charArrayToString(nodeTemp->getNodeName(), strName);
			if (strName == itemName)
			{
				firstChildNode = nodeTemp->getFirstChild();
				if (firstChildNode != NULL) charArrayToString(firstChildNode->getNodeValue(), strValue);
				break;
			}
		}
	}
	
	return strValue;
}
Ejemplo n.º 4
0
// 解析TMS返回xml
bool  CTMSSensor::ParseXmlFromTMS(std::string &retXml,int &nRet)
{
	XercesDOMParser *ptrParser = new  XercesDOMParser;
	ptrParser->setValidationScheme(  XercesDOMParser::Val_Never );
	ptrParser->setDoNamespaces( true );
	ptrParser->setDoSchema( false );
	ptrParser->setLoadExternalDTD( false );
	InputSource* ptrInputsource = new  MemBufInputSource((XMLByte*)retXml.c_str(), retXml.size(), "bufId");

	try
	{
		ptrParser->parse(*ptrInputsource);
		DOMDocument* ptrDoc = ptrParser->getDocument();	

		// 读取ret节点
		DOMNodeList *ptrNodeList = ptrDoc->getElementsByTagName(C2X("ret"));
		if(ptrNodeList == NULL)
		{
			LOGIDFMT(ULOG_ERROR,ERROR_PARSE_MONITORSTATE_XML,"ParseXmlFromTMS:ret");
			return false;
		}
		else 
		{
			if(ptrNodeList->getLength() == 0)
			{
				LOGIDFMT(ULOG_ERROR,ERROR_PARSE_MONITORSTATE_XML,"ParseXmlFromTMS:ret");
				return false;
			}
			DOMNode* ptrNode = ptrNodeList->item(0);
			char* pstate =  XMLString::transcode(ptrNode->getFirstChild()->getNodeValue());
			std::string str_state = pstate;
			if(!str_state.empty())
			{
				nRet = atoi(str_state.c_str());
			}
			XMLString::release(&pstate);
			//LOGINFFMT("%s,%s\n",str_name.c_str(),str_state.c_str());
		}
	}
	catch(  XMLException& e )
	{
		char* message =  XMLString::transcode( e.getMessage() );
		XMLString::release( &message );
		LOGIDFMT(ULOG_ERROR,ERROR_PARSE_MONITORSTATE_XML,message);
		delete ptrParser;
		ptrInputsource = NULL;
		delete ptrInputsource;
		ptrParser = NULL;
	}


	delete ptrParser;
	delete ptrInputsource;
	ptrInputsource = NULL;
	ptrParser = NULL;
	return true;
}
Ejemplo n.º 5
0
bool FrameLabelObjectImp::fromXml(DOMNode* pDocument, unsigned int version)
{
   if (pDocument == NULL || Service<SessionManager>()->isSessionLoading() == false)
   {
      return false;
   }

   if (!TextObjectImp::fromXml(pDocument, version))
   {
      return false;
   }

   DOMElement* pElement = static_cast<DOMElement*> (pDocument);
   if (pElement != NULL)
   {
      // Set the autoMode setting (which will also call setLocked)
      setAutoMode(StringUtilities::fromXmlString<bool>(A(pElement->getAttribute(X("autoMode")))));

      // If the object is not currently locked, load all frames
      if (getLocked() == false)
      {
         for (DOMNode* pChild = pDocument->getFirstChild(); 
            pChild != NULL; pChild = pChild->getNextSibling())
         {
            if (XMLString::equals(pChild->getNodeName(), X("Animations")))
            {
               vector<Animation*> animations;
               for (DOMNode* pGrandchild = pChild->getFirstChild();
                  pGrandchild != NULL;
                  pGrandchild = pGrandchild->getNextSibling())
               {
                  if (XMLString::equals(pGrandchild->getNodeName(), X("Animation")))
                  {
                     pElement = dynamic_cast<DOMElement*>(pGrandchild);
                     if (pElement != NULL)
                     {
                        string id(A(pElement->getAttribute(X("id"))));
                        if (id.empty() != true)
                        {
                           Animation* pAnim = dynamic_cast<Animation*>(Service<SessionManager>()->getSessionItem(id));
                           if (pAnim != NULL)
                           {
                              animations.push_back(pAnim);
                           }
                        }
                     }
                  }
               }

               setAnimations(animations);
            }
         }
      }
   }

   return true;
}
Ejemplo n.º 6
0
/*!
	\brief It fills the member of the _nbPDMLPacket structure that is in charge of the packet dump.

	This function extracts the value of the given node, it transforms it into an ascii buffer (appropriately 
	located into the m_asciiBuffer buffer), and updates the appropriate pointer to it.

	This function updates also the pointer into the m_asciiBuffer buffer in order to point to the first
	free location in this buffer.

	\param PDMLDocument The DOMDocument associated to the current PDML packet.
	\param TmpBuffer: pointer to the CAsciiBuffer class, which manages an ascii temporary buffer in which 
	the content of the XML node has to be stored. The XML content will be stored in binary.
	\param ErrBuf: user-allocated buffer (of length 'ErrBufSize') that will keep an error message (if one).
	This buffer will always be NULL terminated.
	\param ErrBufSize: size of the previous buffer.

	\return nbSUCCESS if everything is fine, nbFAILURE if some error occurred.
	In case of errors, the  error message will be returned in the ErrBuf parameter.
*/
int CPDMLReader::FormatDumpItem(DOMDocument *PDMLDocument, CAsciiBuffer *TmpBuffer, char *ErrBuf, int ErrBufSize)
{
XMLCh TempBuffer[NETPDL_MAX_STRING + 1];
const XMLCh *TempPtr;
char* AsciiBufPtr;
DOMNodeList *DumpList;
DOMNode *DumpItem;
DOMNode *DumpValue;

	// Let's initialize this member, just in case
	m_packetSummary.PacketDump= NULL;

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

	// Now, let's get the raw packet dump
	DumpList= PDMLDocument->getElementsByTagName(TempBuffer);
	if (DumpList == NULL)
		return nbSUCCESS;

	// Let's check if the PDML fragment contains also the packet dump. If not, let's return.
	DumpItem= DumpList->item(0);
	if (DumpItem == NULL)
		return nbSUCCESS;

	DumpValue= DumpItem->getFirstChild();
	if (DumpValue == NULL)
		return nbSUCCESS;

	TempPtr= DumpValue->getNodeValue();

	// If the XML element contains that attribute, transform it in ascii and return it to the caller
	if (TempPtr && (*TempPtr) )
	{
		AsciiBufPtr= TmpBuffer->TranscodeAndStore( (wchar_t *)(XMLCh *) TempPtr);

		if (AsciiBufPtr == NULL)
		{
			errorsnprintf(__FILE__, __FUNCTION__, __LINE__, ErrBuf, ErrBufSize, "%s", TmpBuffer->GetLastError() );
			return nbFAILURE;
		}

		// Since we're tranforming an ascii buffer into a bin buffer (which is half the previous one)
		//  there's no problem of buffer overflow.
		ConvertHexDumpAsciiToHexDumpBin(AsciiBufPtr, (unsigned char *) AsciiBufPtr, strlen(AsciiBufPtr) + 1);

		m_packetSummary.PacketDump= (unsigned char *) AsciiBufPtr;
	}
	else	// otherwise, append 'NULL'
		m_packetSummary.PacketDump= NULL;

	return nbSUCCESS;
}
Ejemplo n.º 7
0
float
Importer::getValueFromTag
(xercesc::DOMNode* node, const XMLCh *tag)
{
  for (XMLSize_t i = 0; i < node->getChildNodes()->getLength(); ++i ) {

    DOMNode* aux = node->getChildNodes()->item(i);

    if (aux->getNodeType() == DOMNode::ELEMENT_NODE &&
	XMLString::equals(aux->getNodeName(), tag))
      return atof(XMLString::transcode(aux->getFirstChild()->getNodeValue()));

  }
  return 0.0;
}
Ejemplo n.º 8
0
bool ConfigurationFileHandler::getSubAlgorithm(std::string algorithm, std::string subalgorithm, std::string* result){
#ifdef BRICS_XERCES_ENABLE
	if (errorsOccured) {
		return false;
	}

    DOMNode* current = NULL;
    DOMNode* attributeNode = NULL;
    XMLCh* algorithmName = XMLString::transcode(algorithm.c_str());
    XMLCh* subAlgorithmName = XMLString::transcode(subalgorithm.c_str());
    XMLCh* implementationString = XMLString::transcode("implementation");
    bool subAlgorithmFound = false;

    DOMDocument* doc = parser->getDocument();
    DOMNodeList* root = doc->getElementsByTagName(algorithmName);
    if (root->getLength() > 1) {
    	LOG(WARNING) << "More than one " << algorithm << " found, taking the first one";
    } else if(root->getLength() < 1) {
    	LOG(WARNING) << "No algorithm called " << algorithm << " found.";
		return false; //TODO release resouces
    }

    current = root->item(0);

    //search in children notes
	for (current = current->getFirstChild()->getNextSibling(); current!=NULL; current = current->getNextSibling()) {
		string nodeName = XMLString::transcode(current->getNodeName());
		if (nodeName.compare(subalgorithm) == 0) {
		    DOMNamedNodeMap* attributesList =  current->getAttributes();
		    attributeNode = attributesList->getNamedItem(implementationString);
		    if (attributeNode != 0) {
		    	*result = XMLString::transcode(attributeNode->getNodeValue());
		    	subAlgorithmFound = true;
		    	break; //take only first found
		    }
		}
	}

    XMLString::release(&algorithmName);
    XMLString::release(&subAlgorithmName);
    XMLString::release(&implementationString);

    return subAlgorithmFound;
#else
    return false;
#endif
}
Ejemplo n.º 9
0
void AcsAlarmTestCase::verifyDescriptorElement(DOMDocument * doc)
{
	// Verify the descriptor element
	DOMNodeList * descriptorNodes = doc->getElementsByTagName(DESCRIPTOR_TAG_NAME);
	CPPUNIT_ASSERT_MESSAGE("FaultState::toXML appears to be broken; no descriptor element found",
		(NULL != descriptorNodes && descriptorNodes->getLength() == 1));

	// check value of descriptor
	DOMNode * descriptorElementNode = descriptorNodes->item(0);
	DOMNode * descriptorTextNode = descriptorElementNode->getFirstChild();
	CPPUNIT_ASSERT_MESSAGE("FaultState::toXML appears to be broken; descriptor value is not present or null",
		(NULL != descriptorTextNode));

	const XMLCh * descriptorNodeValue = descriptorTextNode->getNodeValue();
	CPPUNIT_ASSERT_MESSAGE("FaultState::toXML appears to be broken; value of descriptor is not correct",
		(NULL != descriptorNodeValue && XMLString::equals(descriptorNodeValue, DESCRIPTOR_VALUE_XMLCH)));
}
Ejemplo n.º 10
0
void ColladaObject::ReadRootNode(const DOMNode* node)
{
	_ASSERTE(node != NULL);

	DOMNode* currentNode = node->getFirstChild();
	while( currentNode != NULL )
	{
#if _DEBUG	// デバッグ時に名前をチェックする為に
		const XMLCh* name = currentNode->getNodeName();
#endif
		if( IsElementNode( currentNode ) )
		{
			if( Is_COLLADA_NodeName( currentNode ) )		// COLLADA要素が見つかった場合
			{
				currentNode = currentNode->getFirstChild();		// 子ノードを処理する
				continue;
			}
			else if( Is_asset_NodeName( currentNode ) )	// asset要素が見つかった場合
			{
				_ASSERTE(elemAsset == NULL);		// 必ず1つ存在するのでこの時点ではNULL

				elemAsset = new AssetElement();
				elemAsset->ReadNode( currentNode );
			}
			else if( Is_library_NodeName( currentNode ) )	// library要素が見つかった場合
			{
				LibraryElement* elemLibrary = CreateLibraryElement( currentNode );
				if( elemLibrary != NULL )
				{
					elemLibrary->ReadNode( currentNode );
					vecElemLibrary.push_back( elemLibrary );
				}
			}
			else if( Is_scene_NodeName( currentNode ) )	// scene要素が見つかった場合
			{
				_ASSERTE(elemScene == NULL);		// 0または1つ存在するのでこの時点ではNULL

				elemScene = new SceneElement();
				elemScene->ReadNode( currentNode );
			}
		}

		currentNode = currentNode->getNextSibling();	// 次の要素を処理する
	}
}
Ejemplo n.º 11
0
void DomSerializer::GetString(const char* key, CStdString& value, bool required)
{
	// Find the right node
	DOMNode* stringNode = FindElementByName(m_node, CStdString(key));

	if(stringNode)
	{
		// Now, the string associated to element should be the first child (text element)
		DOMNode* textNode = stringNode->getFirstChild();
		if (textNode && textNode->getNodeType() == DOMNode::TEXT_NODE)
		{
			value = XMLStringToLocal(textNode->getNodeValue());
		}
	}
	else if (required)
	{
		throw(CStdString("DomSerializer::GetString: required parameter missing:") + key);
	}
}
Ejemplo n.º 12
0
bool ArcObjectImp::fromXml(DOMNode* pDocument, unsigned int version)
{
    if (pDocument == NULL)
    {
        return false;
    }

    bool bSuccess = false;

    // Load the ellipse properties first to ensure that it has a valid bounding box when loading the arc properties
    DOMNode* pObjectNode = NULL;
    for (pObjectNode = pDocument->getFirstChild(); pObjectNode != NULL; pObjectNode = pObjectNode->getNextSibling())
    {
        if (XMLString::equals(pObjectNode->getNodeName(), X("objects")))
        {
            DOMNode* pEllipseNode = NULL;
            for (pEllipseNode = pObjectNode->getFirstChild();
                    pEllipseNode != NULL;
                    pEllipseNode = pEllipseNode->getNextSibling())
            {
                if (XMLString::equals(pEllipseNode->getNodeName(), X("Graphic")))
                {
                    DOMElement* pElement(static_cast<DOMElement*> (pEllipseNode));
                    string type(A(pElement->getAttribute(X("type"))));

                    GraphicObjectType objectType = StringUtilities::fromXmlString<GraphicObjectType>(type);
                    if (objectType == ELLIPSE_OBJECT)
                    {
                        bSuccess = mpEllipse->fromXml(pEllipseNode, version);
                        break;
                    }
                }
            }
        }
    }

    if (bSuccess == true)
    {
        bSuccess = FilledObjectImp::fromXml(pDocument, version);
    }

    return bSuccess;
}
Ejemplo n.º 13
0
bool ScaleBarObjectImp::fromXml(DOMNode* pDocument, unsigned int version)
{
   if (pDocument == NULL)
   {
      return false;
   }

   bool bSuccess = FilledObjectImp::fromXml(pDocument, version);
   if (bSuccess == true)
   {
      mpGroup->removeAllObjects(true);

      DOMNode* pObjectNode = pDocument->getFirstChild();
      while (pObjectNode != NULL)
      {
         if (XMLString::equals(pObjectNode->getNodeName(), X("objects")))
         {
            DOMNode* pGroupNode = pObjectNode->getFirstChild();
            while (pGroupNode != NULL)
            {
               if (XMLString::equals(pGroupNode->getNodeName(), X("Graphic")))
               {
                  DOMElement* pElement(static_cast<DOMElement*> (pGroupNode));
                  string type(A(pElement->getAttribute(X("type"))));

                  GraphicObjectType objectType = StringUtilities::fromXmlString<GraphicObjectType>(type);
                  if (objectType == GROUP_OBJECT)
                  {
                     bSuccess = mpGroup->fromXml(pGroupNode, version);
                     break;
                  }
               }

               pGroupNode = pGroupNode->getNextSibling();
            }
         }

         pObjectNode = pObjectNode->getNextSibling();
      }
   }

   return bSuccess;
}
Ejemplo n.º 14
0
void XercesUpdateFactory::applyInsertAsFirst(const PendingUpdate &update, DynamicContext *context)
{
  const XercesNodeImpl *nodeImpl = (const XercesNodeImpl*)update.getTarget()->getInterface(Item::gXQilla);
  DOMNode *domnode = const_cast<DOMNode*>(nodeImpl->getDOMNode());
  DOMNode *firstChild = domnode->getFirstChild();
  DOMDocument *doc = const_cast<DOMDocument*>(XPath2Utils::getOwnerDoc(domnode));

  bool untyped = nodeImpl->dmNodeKind() == Node::element_string &&
    XPath2Utils::equals(nodeImpl->getTypeName(), DocumentCache::g_szUntyped) &&
    XPath2Utils::equals(nodeImpl->getTypeURI(), SchemaSymbols::fgURI_SCHEMAFORSCHEMA);

  bool containsElementOrText = false;

  Result children = update.getValue();
  Item::Ptr item;
  while((item = children->next(context)).notNull()) {
    const XercesNodeImpl *childImpl = (const XercesNodeImpl*)item->getInterface(Item::gXQilla);
    DOMNode *newChild = importNodeFix(doc, const_cast<DOMNode*>(childImpl->getDOMNode()), /*deep*/true);

    if(childImpl->dmNodeKind() == Node::element_string ||
       childImpl->dmNodeKind() == Node::text_string) {
      containsElementOrText = true;
    }

    // If the type-name property of $target is xs:untyped, then upd:setToUntyped() is invoked on each
    // element or attribute node in $content.
    if(!untyped) setTypes(newChild, childImpl->getDOMNode());

    // For each node in $content, the parent property is set to parent($target).
    // The children property of $target is modified to add the nodes in $content just before $target,
    // preserving their order.
    domnode->insertBefore(newChild, firstChild);
  }

  // If at least one of the nodes in $content is an element or text node, upd:removeType($target) is invoked.
  if(containsElementOrText) {
    removeType(domnode);
  }

  addToPutSet(update.getTarget(), &update, context);
}
Ejemplo n.º 15
0
list<string> ClsSettingsReader::getListLastFiles() {
#ifdef DEBUG_CLSSETTINGSREADER
    cout << "ClsSettingsReader::getListLastFiles()" << endl;
#endif
    list<string> lstLFO;

    if(iSysSettingReaderState !=  PARSER_BUFFER_PARSED){
	ClsSettingsReaderException clsSettingsReaderException(ClsSettingsReaderException::BUFFER_NOT_PARSED);
	throw clsSettingsReaderException;
    }


    DOMNodeList* dnlstTemp = ddocIqrSetting->getElementsByTagName(XMLString::transcode(ClsTagLibrary::lastFilesOpen()));
    DOMNode* dnTemp=NULL;

    if ( dnlstTemp->getLength() == 1){
	dnTemp = dnlstTemp->item(0);
    } else if ( dnlstTemp->getLength() < 1)	{
	ClsSettingsReaderException clsSettingsReaderException(ClsSettingsReaderException::ENTITY_NOT_FOUND);
	throw clsSettingsReaderException;
    }

    DOMNodeList* dnlstFiles = dnTemp->getChildNodes();
    unsigned int ii = 0;
    while( ii< dnlstFiles->getLength()){
	DOMNode* dnTempTemp = dnlstFiles->item(ii);
	if(dnTempTemp->getNodeType() == 1){
	    DOMNode* dnValue = dnTempTemp->getFirstChild();
	    if(dnValue!=NULL){
		string strValue = XMLString::transcode(dnValue->getNodeValue());
		lstLFO.push_back(strValue);
	    }
	}
	ii++;
    }

    return lstLFO;
};
Ejemplo n.º 16
0
void DeltaApplyEngine::Subtree_Insert( DOMNode *insertSubtreeRoot, XID_t parentXID, int position, const char *xidmapStr ) {

	vddprintf(( "        insert xidmap=%s at (parent=%d, pos=%d)\n", xidmapStr, (int)parentXID, position));
	DOMNode* contentNode  = xiddoc->importNode( insertSubtreeRoot, true );
	DOMNode* parentNode   = xiddoc->getXidMap().getNodeWithXID( parentXID );
	if (parentNode==NULL) THROW_AWAY(("parent node with XID=%d not found",(int)parentXID));

	int actual_pos = 1 ;
	if ((position!=1)&&(!parentNode->hasChildNodes())) THROW_AWAY(("parent has no children but position is %d",position));
	DOMNode* brother = parentNode->getFirstChild();
	while (actual_pos < position) {
	  brother = brother->getNextSibling();
		actual_pos++;
		if ((brother==NULL)&&(actual_pos<position)) THROW_AWAY(("parent has %d children but position is %d",actual_pos-1, position));
		}
	
	// Add node to the tree
	if (brother==NULL) parentNode->appendChild( contentNode );
	else parentNode->insertBefore( contentNode, brother );
	
	xiddoc->getXidMap().mapSubtree( xidmapStr, contentNode );

	}
Ejemplo n.º 17
0
void DomSerializer::GetList(const char* key, std::list<ObjectRef>& value, Object& model, bool required)
{
	// Find the node corresponding to the object list wanting to be populated
	DOMNode* listNode = FindElementByName(m_node, CStdString(key));

	// Create a new serializer and affect it to this object
	if (listNode)
	{
		// Iterate over the nodes #####
		DOMNode* node = listNode->getFirstChild();
		while(node)
		{
			// Create a new object instance
			ObjectRef newObject = model.NewInstance();
			try
			{
				DomSerializer serializer(newObject.get());
				serializer.DeSerialize(node);
				value.push_back(newObject);

			}
			catch (CStdString& e)
			{
				// For now, do not interrupt the deserialization process.
				// in the future, we might let this exception go through if the node has been
				// recognized to bear the proper tag name
				;
			}
			node = node->getNextSibling();
		}

	}
	else if (required)
	{
		throw(CStdString("DomSerializer::GetList: required node missing:") + key);
	}
}
Ejemplo n.º 18
0
const XMLCh*    DOMNodeImpl::getTextContent(XMLCh* pzBuffer, unsigned int& rnBufferLength) const
{

	unsigned int nRemainingBuffer = rnBufferLength;
	rnBufferLength = 0;

	if (pzBuffer)   
		*pzBuffer = 0;

	DOMNode *thisNode = castToNode(this);

	switch (thisNode->getNodeType())
	{
	case DOMNode::ELEMENT_NODE:
    case DOMNode::ENTITY_NODE:
    case DOMNode::ENTITY_REFERENCE_NODE:
    case DOMNode::DOCUMENT_FRAGMENT_NODE:
    {
		DOMNode* current = thisNode->getFirstChild();

		while (current != NULL) 
		{
			if (current->getNodeType() != DOMNode::COMMENT_NODE &&
				current->getNodeType() != DOMNode::PROCESSING_INSTRUCTION_NODE)
			{

				if (pzBuffer)
				{
					unsigned int nContentLength = nRemainingBuffer;
					castToNodeImpl(current)->getTextContent(pzBuffer + rnBufferLength, nContentLength);
					rnBufferLength += nContentLength;
					nRemainingBuffer -= nContentLength;
				}
				else 
				{
					unsigned int nContentLength = 0;
					castToNodeImpl(current)->getTextContent(NULL, nContentLength);
					rnBufferLength += nContentLength;
				}
			}

			current = current->getNextSibling();

		}
    }

    break;

    case DOMNode::ATTRIBUTE_NODE:
    case DOMNode::TEXT_NODE:
    case DOMNode::CDATA_SECTION_NODE:
    case DOMNode::COMMENT_NODE:
    case DOMNode::PROCESSING_INSTRUCTION_NODE:
    {
		const XMLCh* pzValue = thisNode->getNodeValue();
		unsigned int nStrLen = XMLString::stringLen(pzValue);

		if (pzBuffer) 
		{
			unsigned int nContentLength = (nRemainingBuffer >= nStrLen) ? nStrLen : nRemainingBuffer;
			XMLString::copyNString(pzBuffer + rnBufferLength, pzValue, nContentLength);
			rnBufferLength += nContentLength;
			nRemainingBuffer -= nContentLength;
		}
		else 
		{
			rnBufferLength += nStrLen;
		}

    }

    break;

	/***
         DOCUMENT_NODE
		 DOCUMENT_TYPE_NODE
		 NOTATION_NODE
	***/
	default:

		break;
	}

	return pzBuffer;

}
Ejemplo n.º 19
0
void spep::AttributeProcessor::processAttributeStatements( AttributeStatementPointerList &attributeStatements, spep::PrincipalSession &principalSession )
{
	// Loop through all the AttributeStatement elements in the list.
	AttributeStatementPointerList::iterator attributeStatementIterator;
	for( attributeStatementIterator = attributeStatements.begin(); 
		attributeStatementIterator != attributeStatements.end(); 
		++attributeStatementIterator )
	{
		saml2::assertion::AttributeStatementType *attributeStatement = *attributeStatementIterator;
		
		// Loop through the attributes in the statement.
		saml2::assertion::AttributeStatementType::Attribute_iterator attributeIterator;
		for( attributeIterator = attributeStatement->Attribute().begin();
			attributeIterator != attributeStatement->Attribute().end();
			++attributeIterator )
		{
			UnicodeString attributeNameText( UnicodeStringConversion::toUnicodeString( attributeIterator->Name().c_str() ) );
			
			std::map<UnicodeString,UnicodeString>::iterator renameIterator = this->_attributeRenameMap.find( attributeNameText );
			if( renameIterator != this->_attributeRenameMap.end() )
			{
				_localLogger.debug() << "Found rename for attribute " << UnicodeStringConversion::toString(attributeNameText) << "... renaming to " << UnicodeStringConversion::toString( renameIterator->second );
				attributeNameText = renameIterator->second;
			}
			
			// This will either a) create an empty list, or b) let us append to the existing list of values
			std::vector<UnicodeString>& attributeValueList = principalSession.getAttributeMap()[attributeNameText];

			_localLogger.debug() << "Current attribute: " << UnicodeStringConversion::toString( attributeNameText ) << ". " << attributeValueList.size() << " value(s) already populated.";

			// Loop through the attribute values.
			saml2::assertion::AttributeType::AttributeValue_iterator attributeValueIterator;
			for( attributeValueIterator = attributeIterator->AttributeValue().begin();
				attributeValueIterator != attributeIterator->AttributeValue().end();
				++attributeValueIterator )
			{
				
				// Add the attribute value into the list.
				DOMNode *attributeValueNode = attributeValueIterator->_node();
				if( attributeValueNode->getNodeType() == DOMNode::ELEMENT_NODE )
				{
					
					DOMNode *attributeValueChildNode = attributeValueNode->getFirstChild();
					while( attributeValueChildNode != NULL )
					{
						if( attributeValueChildNode->getNodeType() == DOMNode::TEXT_NODE )
						{
							DOMText *attributeValueTextNode = static_cast<DOMText*>(attributeValueChildNode);
							UnicodeString attributeValueText( UnicodeStringConversion::toUnicodeString( attributeValueTextNode->getData() ) );
							
							_localLogger.debug() << "Adding value: " << UnicodeStringConversion::toString( attributeNameText ) << " = " << UnicodeStringConversion::toString( attributeValueText );
							attributeValueList.push_back( attributeValueText );
							
							break;
						}
						else
						{
							attributeValueChildNode = attributeValueChildNode->getNextSibling();
						}
					}
				}
				
			}
			
			_localLogger.debug() << "Finished processing attributes for " << UnicodeStringConversion::toString( attributeNameText ) << ". " << attributeValueList.size() << " attributes in value list now.";
		}
		
	}
	
}
Ejemplo n.º 20
0
DOMNode* DeltaReverse( DOMNode *deltaElement, DOMDocument *reversedDoc ) {
	
	vddprintf(("    reversing time-version header\n"));

	DOMNode* reversedElement = reversedDoc->importNode( deltaElement, false );

	//DOMString from = deltaElement.getAttributes().getNamedItem("from").getNodeValue() ;
        //DOMString to   = deltaElement.getAttributes().getNamedItem("to"  ).getNodeValue() ;
        const XMLCh* from = deltaElement->getAttributes()->getNamedItem(XMLString::transcode("from"))->getNodeValue() ;
        const XMLCh* to = deltaElement->getAttributes()->getNamedItem(XMLString::transcode("to"))->getNodeValue() ;
        
	reversedElement->getAttributes()->getNamedItem(XMLString::transcode("to"))->setNodeValue( from );
	reversedElement->getAttributes()->getNamedItem(XMLString::transcode("from"))->setNodeValue( to );

	DOMNode* fromXidMap = deltaElement->getAttributes()->getNamedItem(XMLString::transcode("fromXidMap"));
	DOMNode* toXidMap   = deltaElement->getAttributes()->getNamedItem(XMLString::transcode("toXidMap"));
	if (fromXidMap!=NULL) {
          //DOMString from = fromXidMap.getNodeValue();
		reversedElement->getAttributes()->getNamedItem(XMLString::transcode("toXidMap"))->setNodeValue( fromXidMap->getNodeValue() );
	}
	if (toXidMap!=NULL) {
          //DOMString to = toXidMap.getNodeValue();
		reversedElement->getAttributes()->getNamedItem(XMLString::transcode("fromXidMap"))->setNodeValue( toXidMap->getNodeValue() );
	}

	// No chanhges in the delta -> ok
	if (!deltaElement->hasChildNodes()) return( reversedElement );
	
	// Input : read Elementary Operation
	DOMNode* child = deltaElement->getFirstChild() ;
	
	// Output : precedent will be used to write Elementary Operation in reverse order
	DOMNode* precedent = NULL; // =NULL by default

	while (child != NULL) {
		if (child->getNodeType()!=DOMNode::ELEMENT_NODE) THROW_AWAY(("Bad type (%d) for Delta Operation Node", (int)child->getNodeType()));
		DOMElement* operationNode = (DOMElement*) child ;
		XyLatinStr operation(child->getLocalName());
		
		// Reverse DELETE into INSERT
		
		if (strcmp(operation, "d")==0) {
			vddprintf(("    reversing delete into insert\n"));
			DOMElement* iElement = reversedDoc->createElementNS(XYDIFF_XYDELTA_NS, XMLString::transcode("xy:i")) ;
			CopyAttr(iElement, operationNode, XMLString::transcode("par"), true);
			CopyAttr(iElement, operationNode, XMLString::transcode("pos"), true);
			CopyAttr(iElement, operationNode, XMLString::transcode("xm"), true);
			CopyAttr(iElement, operationNode, XMLString::transcode("move"), false);
			CopyAttr(iElement, operationNode, XMLString::transcode("update"), false);
			CopyContent(iElement, operationNode);
			reversedElement->insertBefore( iElement, precedent ) ;
			precedent = iElement ;
			}

		// Reverse INSERT into DELETE
		
		else if (strcmp(operation, "i")==0) {
	    		vddprintf(("    reversing insert into delete\n")); 
			DOMElement *iElement = reversedDoc->createElementNS(XYDIFF_XYDELTA_NS, XMLString::transcode("xy:d")) ;
			CopyAttr(iElement, operationNode, XMLString::transcode("par"), true);
			CopyAttr(iElement, operationNode, XMLString::transcode("pos"), true);
			CopyAttr(iElement, operationNode, XMLString::transcode("xm"), true);
			CopyAttr(iElement, operationNode, XMLString::transcode("move"), false);
			CopyAttr(iElement, operationNode, XMLString::transcode("update"), false);
			CopyContent(iElement, operationNode);
			reversedElement->insertBefore( iElement, precedent ) ;
			precedent = iElement ;
		  }
	// Attribute Update
		else if (strcmp(operation, "au")==0) {
			vddprintf(("    reversing attribute update\n"));
			
			//DOMString xidElem  = operationNode.getAttributes().getNamedItem("xid").getNodeValue();
			//DOMString attrName = operationNode.getAttributes().getNamedItem("a").getNodeValue();
			//DOMString oldValue = operationNode.getAttributes().getNamedItem("ov").getNodeValue();
			//DOMString newValue = operationNode.getAttributes().getNamedItem("nv").getNodeValue();
			const XMLCh* xidElem = operationNode->getAttributes()->getNamedItem(XMLString::transcode("xid"))->getNodeValue();
                        const XMLCh* attrName = operationNode->getAttributes()->getNamedItem(XMLString::transcode("a"))->getNodeValue();
                        const XMLCh* oldValue = operationNode->getAttributes()->getNamedItem(XMLString::transcode("ov"))->getNodeValue();
                        const XMLCh* newValue = operationNode->getAttributes()->getNamedItem(XMLString::transcode("nv"))->getNodeValue();
                        

			DOMElement* auElement = reversedDoc->createElementNS(XYDIFF_XYDELTA_NS, XMLString::transcode("xy:au"));
			auElement->setAttribute(XMLString::transcode("xid"), xidElem);
			auElement->setAttribute(XMLString::transcode("a"),   attrName);
			auElement->setAttribute(XMLString::transcode("nv"),  oldValue);
			auElement->setAttribute(XMLString::transcode("ov"),  newValue);
			
			reversedElement->insertBefore(auElement, precedent);
			precedent = auElement ;
		}
	// Attribute Delete
		else if (strcmp(operation, "ad")==0) {
			vddprintf(("    reversing attribute insert into attribute delete\n"));

			//DOMString xidElem  = operationNode.getAttributes().getNamedItem("xid").getNodeValue();
			//DOMString attrName = operationNode.getAttributes().getNamedItem("a").getNodeValue();
			//DOMString attrVal  = operationNode.getAttributes().getNamedItem("v").getNodeValue();
			const XMLCh* xidElem  = operationNode->getAttributes()->getNamedItem(XMLString::transcode("xid"))->getNodeValue();
			const XMLCh* attrName = operationNode->getAttributes()->getNamedItem(XMLString::transcode("a"))->getNodeValue();
			const XMLCh* attrVal  = operationNode->getAttributes()->getNamedItem(XMLString::transcode("v"))->getNodeValue();
			
			DOMElement* aiElement = reversedDoc->createElementNS(XYDIFF_XYDELTA_NS, XMLString::transcode("xy:ai"));
			aiElement->setAttribute(XMLString::transcode("xid"), xidElem);
			aiElement->setAttribute(XMLString::transcode("a"), attrName);
			aiElement->setAttribute(XMLString::transcode("v"), attrVal);
			
			reversedElement->insertBefore(aiElement, precedent);
			precedent = aiElement ;
		}
	// Attribute Insert
		else if (strcmp(operation, "ai")==0) {
			vddprintf(("    reversing attribute delete into attribute insert\n"));

			//DOMString xidElem  = operationNode.getAttributes().getNamedItem("xid").getNodeValue();
			//DOMString attrName = operationNode.getAttributes().getNamedItem("a").getNodeValue();
			//DOMString attrVal  = operationNode.getAttributes().getNamedItem("v").getNodeValue();
                        const XMLCh* xidElem  = operationNode->getAttributes()->getNamedItem(XMLString::transcode("xid"))->getNodeValue();
			const XMLCh* attrName = operationNode->getAttributes()->getNamedItem(XMLString::transcode("a"))->getNodeValue();
			const XMLCh* attrVal  = operationNode->getAttributes()->getNamedItem(XMLString::transcode("v"))->getNodeValue();
			
			DOMElement* adElement = reversedDoc->createElementNS(XYDIFF_XYDELTA_NS, XMLString::transcode("xy:ad"));
			adElement->setAttribute(XMLString::transcode("xid"), xidElem);
			adElement->setAttribute(XMLString::transcode("a"), attrName);
			adElement->setAttribute(XMLString::transcode("v"), attrVal);
			
			reversedElement->insertBefore(adElement, precedent);
			precedent = adElement ;
		}
		
    // Reverse UPDATE to UPDATE
		
		else if (strcmp(operation, "u")==0) {
			vddprintf(("    reversing update\n"));
		  
			DOMNode* oldValue = child->getFirstChild() ;
			if ( oldValue==NULL ) throw ReverseUpdateException("<update> has no child!");
			
			DOMNode* newValue = oldValue->getNextSibling() ;
			if ( newValue==NULL ) throw ReverseUpdateException("<update> has only one child!");
			
			//DOMString xid= child.getAttributes().getNamedItem("xid").getNodeValue() ;
                        const XMLCh* xid= child->getAttributes()->getNamedItem(XMLString::transcode("xid"))->getNodeValue() ;
			
			DOMElement *uElement = reversedDoc->createElementNS(XYDIFF_XYDELTA_NS, XMLString::transcode("xy:u")) ;
			uElement->setAttribute(XMLString::transcode("xid"), xid);
			
			DOMElement* uOld = reversedDoc->createElementNS(XYDIFF_XYDELTA_NS, XMLString::transcode("xy:ov"));
			DOMNode* uOldText = reversedDoc->importNode( newValue->getFirstChild(), true );
			uOld->appendChild( uOldText );
			
			DOMElement* uNew = reversedDoc->createElementNS(XYDIFF_XYDELTA_NS, XMLString::transcode("xy:nv"));
			DOMNode* uNewText = reversedDoc->importNode( oldValue->getFirstChild(), true );
			uNew->appendChild( uNewText );
			
			uElement->appendChild( uOld ) ;
			uElement->appendChild( uNew ) ;
			
		  reversedElement->insertBefore( uElement, precedent ) ;
			precedent = uElement ;
			}
		else if (strcmp(operation, "renameRoot")==0) {
			vddprintf(("    reversing renameRoot operation\n"));

			const XMLCh* rFrom = operationNode->getAttributes()->getNamedItem(XMLString::transcode("from"))->getNodeValue();
			const XMLCh* rTo   = operationNode->getAttributes()->getNamedItem(XMLString::transcode("to"))->getNodeValue();
			
			DOMElement *rrElement = reversedDoc->createElementNS(XYDIFF_XYDELTA_NS, XMLString::transcode("xy:renameRoot"));
			rrElement->setAttribute(XMLString::transcode("from"), rTo);
			rrElement->setAttribute(XMLString::transcode("to"), rFrom);
			
			reversedElement->insertBefore(rrElement, precedent);
			precedent = rrElement ;			
		}
		
		else {
			throw DeltaReverseException("Invalid Data", "main", "Unknown operation <" + std::string(operation) + ">")  ;
		}
				
		child = child->getNextSibling();
		}
	
	return ( reversedElement ) ;
	}
Ejemplo n.º 21
0
static void 
ProcessMETRIC(DOMNode *node, Analysis::Args& args, Prof::Metric::Mgr& mMgr)
{
  static XMLCh* FILE = XMLString::transcode("FILE");
  static XMLCh* COMPUTE = XMLString::transcode("COMPUTE");
  static XMLCh* NAMEATTR = XMLString::transcode("name");
  static XMLCh* DISPLAYATTR = XMLString::transcode("display");
  static XMLCh* PERCENTATTR = XMLString::transcode("percent");
  //static XMLCh* PROPAGATEATTR = XMLString::transcode("propagate");
  static XMLCh* DISPLAYNAMEATTR = XMLString::transcode("displayName");
  static XMLCh* SORTBYATTR = XMLString::transcode("sortBy");

  // get metric attributes
  string metricNm = getAttr(node, NAMEATTR); 
  string metricDispNm = getAttr(node, DISPLAYNAMEATTR); 
  bool metricDoDisp = (getAttr(node, DISPLAYATTR) == "true"); 
  bool metricDoPercent = (getAttr(node,PERCENTATTR) == "true"); 
  bool metricDoSortBy = (getAttr(node,SORTBYATTR) == "true"); 

  if (metricNm.empty()) {
    ConfigParser_Throw("METRIC: Invalid name: '" << metricNm << "'.");
  }
  else if (mMgr.metric(metricNm) != NULL) {
    ConfigParser_Throw("METRIC: Metric name '" << metricNm << "' was previously defined.");
  }

  if (metricDispNm.empty()) {
    ConfigParser_Throw("METRIC: Invalid displayName: '" << metricDispNm << "'.");
  }
    
  DIAG_DevMsgIf(DBG, "CONFIG: " << "METRIC: name=" << metricNm
		<< " display=" <<  ((metricDoDisp) ? "true" : "false")
		<< " doPercent=" <<  ((metricDoPercent) ? "true" : "false")
		<< " sortBy=" <<  ((metricDoSortBy) ? "true" : "false")
		<< " metricDispNm=" << metricDispNm);
		
  // should have exactly one child
  DOMNode* metricImpl = node->getFirstChild();

  for ( ; metricImpl != NULL; metricImpl = metricImpl->getNextSibling()) {

    if (metricImpl->getNodeType() == DOMNode::TEXT_NODE) {
      // DTD ensures this can't contain anything but white space
      continue;
    }
    else if (metricImpl->getNodeType() == DOMNode::COMMENT_NODE) {
      continue;
    }
    
    const XMLCh* metricType = metricImpl->getNodeName();

    if (XMLString::equals(metricType, FILE)) {

      ProcessFILE(metricImpl, args, mMgr, metricNm, 
		  metricDoDisp, metricDoPercent, metricDoSortBy, 
		  metricDispNm);
    }
    else if (XMLString::equals(metricType,COMPUTE)) {

      //bool propagateComputed = false; // tallent
      // (getAttr(metricImpl, PROPAGATEATTR) == "computed"); 

      DOMNode* child = metricImpl->getFirstChild();
      for (; child != NULL; child = child->getNextSibling()) {
	if (child->getNodeType() == DOMNode::TEXT_NODE) {
	  // DTD ensures this can't contain anything but white space
	  continue;
	}
	else if (child->getNodeType() == DOMNode::COMMENT_NODE) {
	  continue;
	}

	using namespace Prof;
	Metric::AExpr* expr = makeMathMLExpr(metricNm.c_str(), child, mMgr);
	mMgr.insert(new Metric::DerivedDesc(metricNm, metricNm, expr,
					    metricDoDisp, metricDoSortBy,
					    metricDoPercent, 
					    false/*isPercent*/));
      }
    } 
    else {
      ConfigParser_Throw("Unexpected METRIC type '" << XMLString::transcode(metricType) << "'.");
    }
  }
}
Ejemplo n.º 22
0
void DeltaApplyEngine::ApplyOperation(DOMNode *operationNode) {
	 
	vddprintf(("ApplyOperation\n"));
	XMLCh dStr[2];
	XMLCh iStr[2];
	XMLCh uStr[2];
	XMLCh adStr[3];
	XMLCh aiStr[3];
	XMLCh auStr[3];
	XMLCh renameRootStr[11];
	XMLString::transcode("d", dStr, 1);
	XMLString::transcode("i", iStr, 1);
	XMLString::transcode("u", uStr, 1);
	XMLString::transcode("ad", adStr, 2);
	XMLString::transcode("ai", aiStr, 2);
	XMLString::transcode("au", auStr, 2);
	XMLString::transcode("renameRoot", renameRootStr, 10);
	XMLCh tempStr[6];
	if (XMLString::equals(operationNode->getLocalName(), dStr)) {
		vddprintf(("        d(elete)\n"));
		
		bool move = false ;
		XMLString::transcode("move", tempStr, 5);
		DOMNode* moveAttr = operationNode->getAttributes()->getNamedItem(tempStr) ;
		XMLString::transcode("yes", tempStr, 5);
		if ((moveAttr!=NULL) && (XMLString::equals(moveAttr->getNodeValue(),tempStr))) {
			move = true;
		}

		XMLString::transcode("xm", tempStr, 5);
		char *xidmapStr = XMLString::transcode(operationNode->getAttributes()->getNamedItem(tempStr)->getNodeValue());		
		if (move) {
			XidMap_Parser parse(xidmapStr) ;
			XID_t myXid = parse.getRootXID();
			Subtree_MoveFrom( myXid );
		  }
		else {
			Subtree_Delete(xidmapStr) ;
		}
		XMLString::release(&xidmapStr);
	}

	else if (XMLString::equals(operationNode->getLocalName(),iStr)) {
		vddprintf(("        i(nsert)\n"));

		bool move = false ;
		XMLString::transcode("move", tempStr, 5);
		DOMNode* moveAttr = operationNode->getAttributes()->getNamedItem(tempStr) ;
		XMLString::transcode("yes", tempStr, 5);
		if ( (moveAttr!=NULL) && (XMLString::equals( moveAttr->getNodeValue(), tempStr ))) {
			move = true;
		}
		XMLString::transcode("pos", tempStr, 5);
		DOMNode *n = operationNode->getAttributes()->getNamedItem(tempStr);
		int position = XyInt(n->getNodeValue());

		XMLString::transcode("par", tempStr, 5);
		n = operationNode->getAttributes()->getNamedItem(tempStr);
		XID_t parentXID = (XID_t)(int)XyInt(n->getNodeValue());

		XMLString::transcode("xm", tempStr, 5);
		char *xidmapStr = XMLString::transcode(operationNode->getAttributes()->getNamedItem(tempStr)->getNodeValue());
		if (move) {
			XidMap_Parser parse(xidmapStr) ;
			XID_t myXid = parse.getRootXID();

			Subtree_MoveTo( myXid, parentXID, position );
		}
		else {
			DOMNode* insertRoot ;
			// get data to insert
			if (operationNode->hasChildNodes()) insertRoot = operationNode->getFirstChild() ;
			else THROW_AWAY(("insert operator element contains no data"));
				
			Subtree_Insert( insertRoot, parentXID, position, xidmapStr ) ;
		}
		XMLString::release(&xidmapStr);
	}

	else if (XMLString::equals(operationNode->getLocalName(), uStr)) {
		vddprintf(("        u(pdate)\n"));
		XMLString::transcode("oldxm", tempStr, 5);
		char *xidmapStr = XMLString::transcode(operationNode->getAttributes()->getNamedItem(tempStr)->getNodeValue());
		XidMap_Parser parse(xidmapStr) ;
		XID_t nodeXID = parse.getRootXID();
		TextNode_Update( nodeXID, operationNode);
		XMLString::release(&xidmapStr);
		}

	else if (XMLString::equals(operationNode->getLocalName(), adStr)) {
		vddprintf(("        a(ttribute) d(elete)\n"));
		XMLString::transcode("xid", tempStr, 5);
		XID_t nodeXID = (XID_t)(int)XyInt(operationNode->getAttributes()->getNamedItem(tempStr)->getNodeValue());

		XMLString::transcode("a", tempStr, 5);
        const XMLCh* attr = operationNode->getAttributes()->getNamedItem(tempStr)->getNodeValue() ;
		Attribute_Delete( nodeXID, attr );
		}
	else if (XMLString::equals(operationNode->getLocalName(), aiStr)) {
		vddprintf(("        a(ttribute) i(nsert)\n"));
		XMLString::transcode("xid", tempStr, 5);
		XID_t nodeXID = (XID_t)(int)XyInt(operationNode->getAttributes()->getNamedItem(tempStr)->getNodeValue());
		XMLString::transcode("a", tempStr, 5);
        const XMLCh* attr = operationNode->getAttributes()->getNamedItem(tempStr)->getNodeValue() ;
		XMLString::transcode("v", tempStr, 5);
        const XMLCh* value = operationNode->getAttributes()->getNamedItem(tempStr)->getNodeValue() ;
		Attribute_Insert( nodeXID, attr, value );
		}
	else if (XMLString::equals(operationNode->getLocalName(), auStr)) {
		vddprintf(("        a(ttribute) u(pdate)\n"));
		XMLString::transcode("xid", tempStr, 5);
		XID_t nodeXID = (XID_t)(int)XyInt(operationNode->getAttributes()->getNamedItem(tempStr)->getNodeValue());
		XMLString::transcode("a", tempStr, 5);
        const XMLCh* attr = operationNode->getAttributes()->getNamedItem(tempStr)->getNodeValue() ;
		XMLString::transcode("nv", tempStr, 5);
        const XMLCh* value = operationNode->getAttributes()->getNamedItem(tempStr)->getNodeValue() ;
		Attribute_Update( nodeXID, attr, value );
		}
	else if (XMLString::equals(operationNode->getLocalName(), renameRootStr)) {
		vddprintf(("        renameRoot\n"));
		DOMNode *root = xiddoc->getDocumentElement();
		XID_t rootXID = xiddoc->getXidMap().getXIDbyNode(root);
		XMLString::transcode("to", tempStr, 5);
        const XMLCh* newrootName = operationNode->getAttributes()->getNamedItem(tempStr)->getNodeValue() ;
		DOMElement* newroot = xiddoc->createElement(newrootName);

		DOMNode* child = root->getFirstChild();
		while(child!=NULL) {
			root->removeChild(child);
			newroot->appendChild(child);
			child = root->getFirstChild();
		}
		DOMNamedNodeMap *attributes = root->getAttributes();
		for(unsigned int i=0;i<attributes->getLength();i++) {
			DOMNode *an = attributes->item(i);
			newroot->setAttribute(an->getNodeName(), an->getNodeValue());
		}
		xiddoc->removeChild(root);
		xiddoc->getXidMap().removeNode(root);
		root->release();
		xiddoc->appendChild(newroot);
		xiddoc->getXidMap().registerNode(newroot, rootXID);
		xiddoc->getXidMap().SetRootElement(newroot);
		}
	}
Ejemplo n.º 23
0
void DSIGSignedInfo::load(void) {


	if (mp_signedInfoNode == 0) {

		// Attempt to load an empty signature element
		throw XSECException(XSECException::LoadEmptySignedInfo);

	}

	if (!strEquals(getDSIGLocalName(mp_signedInfoNode), "SignedInfo")) {

		throw XSECException(XSECException::LoadNonSignedInfo);

	}

	DOMNode * tmpSI = mp_signedInfoNode->getFirstChild();

	// Check for CanonicalizationMethod

	while (tmpSI != 0 && (tmpSI->getNodeType() != DOMNode::ELEMENT_NODE))
		// Skip text and comments
		tmpSI = tmpSI->getNextSibling();

	if (tmpSI == 0 || !strEquals(getDSIGLocalName(tmpSI), "CanonicalizationMethod")) {

		throw XSECException(XSECException::ExpectedDSIGChildNotFound, 
				"Expected <CanonicalizationMethod> as first child of <SignedInfo>");

	}

	// Determine what the canonicalization method is
	DOMNamedNodeMap *tmpAtts = tmpSI->getAttributes();

	DOMNode *algorithm = tmpAtts->getNamedItem(DSIGConstants::s_unicodeStrAlgorithm);

	if (algorithm == 0) {

		throw XSECException(XSECException::ExpectedDSIGChildNotFound,
					"Expected Algorithm attribute in <CanonicalizationMethod>");

	}

	safeBuffer tmpSB;

	tmpSB << (*mp_formatter << algorithm->getNodeValue());

	if (tmpSB.sbStrcmp(URI_ID_C14N_NOC) == 0) {

		m_canonicalizationMethod = CANON_C14N_NOC;

	}

	else if (tmpSB.sbStrcmp(URI_ID_C14N_COM) == 0) {

		m_canonicalizationMethod = CANON_C14N_COM;

	}

	else

		throw XSECException(XSECException::UnknownCanonicalization);

	// Now load the SignatureMethod

	tmpSI = tmpSI->getNextSibling();

	while (tmpSI != 0 && (tmpSI->getNodeType() != DOMNode::ELEMENT_NODE))
		// Skip text and comments
		tmpSI = tmpSI->getNextSibling();

	if (tmpSI == 0 || !strEquals(getDSIGLocalName(tmpSI), "SignatureMethod")) {

		throw XSECException(XSECException::ExpectedDSIGChildNotFound, 
				"Expected <SignatureMethod> as child of <SignedInfo>");
	}


	// Determine the algorithms used to sign this document

	tmpAtts = tmpSI->getAttributes();

	algorithm = tmpAtts->getNamedItem(DSIGConstants::s_unicodeStrAlgorithm);
	
	if (algorithm == 0) {

		throw XSECException(XSECException::ExpectedDSIGChildNotFound,
					"Expected Algorithm attribute in <SignatureMethod>");

	}


	tmpSB << (*mp_formatter << algorithm->getNodeValue());

	if (tmpSB.sbStrcmp(URI_ID_DSA_SHA1) == 0) {

		m_signatureMethod = SIGNATURE_DSA;
		m_hashMethod = HASH_SHA1;

	}

	else if (tmpSB.sbStrcmp(URI_ID_RSA_SHA1) == 0) {

		m_signatureMethod = SIGNATURE_RSA;
		m_hashMethod = HASH_SHA1;

	}

	else if (tmpSB.sbStrcmp(URI_ID_HMAC_SHA1) == 0) {

		m_signatureMethod = SIGNATURE_HMAC;
		m_hashMethod = HASH_SHA1;

		// Check to see if there is a maximum output value

		DOMNode *tmpSOV = tmpSI->getFirstChild();
		while (tmpSOV != NULL && 
			tmpSOV->getNodeType() != DOMNode::ELEMENT_NODE && 
			!strEquals(getDSIGLocalName(tmpSOV), "HMACOutputLength"))
			tmpSOV = tmpSOV->getNextSibling();

		if (tmpSOV != NULL) {

			// Have a max output value!
			tmpSOV = tmpSOV->getFirstChild();
			while (tmpSOV != NULL && tmpSOV->getNodeType() != DOMNode::TEXT_NODE)
				tmpSOV = tmpSOV->getNextSibling();

			if (tmpSOV != NULL) {

				safeBuffer val;
				val << (*mp_formatter << tmpSOV->getNodeValue());
				m_HMACOutputLength = atoi((char *) val.rawBuffer());

			}
		}
	
	}

	else

		throw XSECException(XSECException::UnknownSignatureAlgorithm);


	// Now look at references....

	tmpSI = tmpSI->getNextSibling();

	// Run through the rest of the elements until done

	while (tmpSI != 0 && (tmpSI->getNodeType() != DOMNode::ELEMENT_NODE))
		// Skip text and comments
		tmpSI = tmpSI->getNextSibling();

	if (tmpSI != NULL) {

		// Have an element node - should be a reference, so let's load the list

		mp_referenceList = DSIGReference::loadReferenceListFromXML(mp_parentSignature, tmpSI);

	}

}
Ejemplo n.º 24
0
XERCES_CPP_NAMESPACE_USE

#define ARRAY_SIZE(ARY) ( (int)(sizeof(ARY)/sizeof(ARY[0])) )

#ifdef CONF_DUMP
#define ENABLE_DUMP
#define ENABLE_DUMP1
#endif
#include "ParserDump.h"

void JointParser::parse(DOMNode &target, Eval &eval)
{
	char *name = XMLUtils::getAttribute(target, "name");
	DUMP1(("name %s\n", name));

	m_transform.push();

	DOMNode *p = target.getFirstChild();
	while (p) {
		char *s = XMLString::transcode(p->getNodeName());
		//		printf("%s\n", s);
		if (strcmp(s, "type") == 0) {
			char *type = XMLUtils::parseJointType(*p);
			DUMP1(("type=\"%s\"\n", type));
			Joint *j = 0;
			if (strcmp(type, "fixed") == 0) {
				j = new FixedJoint(name);
			} else if (strcmp(type, "ball") == 0) {
				j = new BallJoint(name);
			} else if (strcmp(type, "hinge") == 0) {
				j = new HingeJoint(name, Vector3d(0, 1, 0));
			}
			
			if (j) {
				m_joint = j;
			}
			XMLString::release(&type);
			/*
		} else if (strcmp(s, "limitOrientation") == 0) {
			double *v = XMLUtils::parseLimitOrientation(*p);
			if (m_joint) {
				delete m_joint;
			}
			m_joint = new HingeJoint(name, Vector3d(v[0], v[1], v[2]));
			*/
				
		} else if (strcmp(s, "translation") == 0) {
			double * values = XMLUtils::parseTranslation(*p, eval);
			DUMP1(("translation (%f, %f, %f)\n", values[0], values[1], values[2]));
			m_transform.curr().push(Vector3d(values[0], values[1], values[2]));

		} else if (strcmp(s, "rotation") == 0) {
			double *values = XMLUtils::parseRotation(*p);
			DUMP1(("rotation (%f, %f, %f, %f)\n", values[0], values[1], values[2], values[3]));
			Rotation rot;
			rot.setAxisAndAngle(values[0], values[1], values[2], values[3]);
			m_transform.curr().push(rot);
			
		} else if (strcmp(s, "axis") == 0) {
			double *values = XMLUtils::parseAxis(*p);
			DUMP1(("axis (%f, %f, %f)\n", values[0], values[1], values[2]));
			
			if (m_joint) {
				if (m_joint->type() == Joint::TYPE_HINGE) {
					HingeJoint *hinge = static_cast<HingeJoint*>(m_joint);
					hinge->setAxis(values[0], values[1], values[2]);
				} else {
					DUMP1(("not hinge type joint. axis ingored\n"));
				}
			} else {
				DUMP1(("no joint type"));
			}
				

		} else if (strcmp(s, "children") == 0) {
			DUMP1(("JOINT TRANSFORM TEST \n"));
			TRANSFORM_TEST(m_transform.curr());
			parseChildren(*p, eval);
		}
		
		p = p->getNextSibling();
		XMLString::release(&s);
	}
	{
		Transform &t = m_transform.curr();
		const Vector3d &v = t.translation();
		if (m_joint) {
			m_f.addJoint(m_joint);
			DUMP(("Joint : (%f, %f, %f)\n", v.x(), v.y(), v.z()));
			m_joint->setAnchor(v.x(), v.y(), v.z());
		}
	}
	m_transform.pop();

	char *strs[] = { name,};
	for (int i=0; i<ARRAY_SIZE(strs); i++) {
		char *p = strs[i];
		XMLString::release(&p);
	}
}
Ejemplo n.º 25
0
int main(int argc, char **argv) {

	XSECCryptoKey				* key = NULL;
	DSIGKeyInfoX509				* keyInfoX509 = NULL;
	OpenSSLCryptoX509			* certs[128];
	int							certCount = 0;
	int							paramCount;
	bool						clearKeyInfo = false;

	// Initialise the XML system

	try {

		XMLPlatformUtils::Initialize();
#ifndef XSEC_NO_XALAN
		XPathEvaluator::initialize();
		XalanTransformer::initialize();
#endif
		XSECPlatformUtils::Initialise();

	}

	catch (const XMLException &e) {

		cerr << "Error during initialisation of Xerces" << endl;
		cerr << "Error Message = : "
		     << e.getMessage() << endl;

	}

	// Initialise OpenSSL
	ERR_load_crypto_strings();
	BIO * bio_err;
	
	if ((bio_err=BIO_new(BIO_s_file())) != NULL)
		BIO_set_fp(bio_err,stderr,BIO_NOCLOSE|BIO_FP_TEXT);

	if (argc < 2) {

		printUsage();
		exit (1);
	}
	
	paramCount = 1;

	while (paramCount < argc - 1) {

		// Run through all parameters

		if (stricmp(argv[paramCount], "--dsakey") == 0 || stricmp(argv[paramCount], "-d") == 0 ||
			stricmp(argv[paramCount], "--rsakey") == 0 || stricmp(argv[paramCount], "-r") == 0) {

			// DSA or RSA Key

			if (paramCount + 3 >= argc) {

				printUsage();
				exit (1);

			}

			if (key != 0) {

				cerr << "\nError loading RSA or DSA key - another key already loaded\n\n";
				printUsage();
				exit(1);

			}

			// Load the signing key
			// For now just read a particular file

			BIO * bioKey;
			if ((bioKey = BIO_new(BIO_s_file())) == NULL) {

				cerr << "Error opening private key file\n\n";
				exit (1);

			}

			if (BIO_read_filename(bioKey, argv[paramCount + 1]) <= 0) {

				cerr << "Error opening private key file\n\n";
				exit (1);

			}

			EVP_PKEY * pkey;
			pkey = PEM_read_bio_PrivateKey(bioKey,NULL,NULL,argv[paramCount + 2]);

			if (pkey == NULL) {

				cerr << "Error loading private key\n\n";
				ERR_print_errors(bio_err);
				exit (1);

			}

			if (stricmp(argv[paramCount], "--dsakey") == 0 || stricmp(argv[paramCount], "-d") == 0) {

				// Check type is correct

				if (pkey->type != EVP_PKEY_DSA) {
					cerr << "DSA Key requested, but OpenSSL loaded something else\n";
					exit (1);
				}

				// Create the XSEC OpenSSL interface
				key = new OpenSSLCryptoKeyDSA(pkey);
			}
			else {
				if (pkey->type != EVP_PKEY_RSA) {
					cerr << "RSA Key requested, but OpenSSL loaded something else\n";
					exit (1);
				}
				key = new OpenSSLCryptoKeyRSA(pkey);
			}

			EVP_PKEY_free(pkey);
			BIO_free(bioKey);

			paramCount += 3;
			
		} /* argv[1] = "dsa/rsa" */


		else if (stricmp(argv[paramCount], "--x509cert") == 0 || stricmp(argv[paramCount], "-x") == 0) {

			// X509Data keyInfo

			if (paramCount + 2 >= argc) {

				printUsage();
				exit (1);

			}

			// Load the signing key
			// For now just read a particular file

			BIO * bioX509;

			if ((bioX509 = BIO_new(BIO_s_file())) == NULL) {

				cerr << "Error opening file\n\n";
				exit (1);

			}

			if (BIO_read_filename(bioX509, argv[paramCount + 1]) <= 0) {

				cerr << "Error opening X509 Certificate " << argv[paramCount + 1] << "\n\n";
				exit (1);

			}

			X509 * x
				;
			x = PEM_read_bio_X509_AUX(bioX509,NULL,NULL,NULL);

			if (x == NULL) {

				cerr << "Error loading certificate key\n\n";
				ERR_print_errors(bio_err);
				exit (1);

			}

			// Create the XSEC OpenSSL interface - used only to translate to Base64

			certs[certCount++] = new OpenSSLCryptoX509(x);
			X509_free(x);
			BIO_free(bioX509);

			paramCount += 2;
			
		} /* argv[1] = "--x509cert" */

		else if (stricmp(argv[paramCount], "--hmackey") == 0 || stricmp(argv[paramCount], "-h") == 0) {

			OpenSSLCryptoKeyHMAC * hmacKey = new OpenSSLCryptoKeyHMAC();
			hmacKey->setKey((unsigned char *) argv[paramCount + 1], strlen(argv[paramCount + 1]));
			key = hmacKey;
			paramCount += 2;

		}

		else if (stricmp(argv[paramCount], "--clearkeys") == 0 || stricmp(argv[paramCount], "-c") == 0) {

			clearKeyInfo = true;
			paramCount += 1;

		}
		else {

			printUsage();
			exit(1);

		}

	}

	// Create and set up the parser

	XercesDOMParser * parser = new XercesDOMParser;
	
	parser->setDoNamespaces(true);
	parser->setCreateEntityReferenceNodes(true);

	// Now parse out file

	bool errorsOccured = false;
	int errorCount = 0;
    try
    {
    	parser->parse(argv[argc - 1]);
        errorCount = parser->getErrorCount();
        if (errorCount > 0)
            errorsOccured = true;
    }

    catch (const XMLException& e)
    {
        cerr << "An error occured during parsing\n   Message: "
             << e.getMessage() << endl;
        errorsOccured = true;
    }


    catch (const DOMException& e)
    {
       cerr << "A DOM error occured during parsing\n   DOMException code: "
             << e.code << endl;
        errorsOccured = true;
    }

	if (errorsOccured) {

		cout << "Errors during parse" << endl;
		exit (1);

	}

	/*

		Now that we have the parsed file, get the DOM document and start looking at it

	*/
	
	DOMNode *doc;		// The document that we parsed

	doc = parser->getDocument();
	DOMDocument *theDOM = parser->getDocument();

	// Find the signature node
	
	DOMNode *sigNode = findDSIGNode(doc, "Signature");

	// Create the signature checker

	if (sigNode == 0) {

		cerr << "Could not find <Signature> node in " << argv[argc-1] << endl;
		exit(1);
	}


	XSECProvider prov;
	DSIGSignature * sig = prov.newSignatureFromDOM(theDOM, sigNode);

	int i;

	try {
		sig->load();
		if (clearKeyInfo == true)
			sig->clearKeyInfo();
		if (key != NULL)
			sig->setSigningKey(key);
		sig->sign();

		// Add any KeyInfo elements

		if (certCount > 0) {

			// Have some certificates - see if there is already an X509 list
			DSIGKeyInfoList * kiList = sig->getKeyInfoList();
			int kiSize = kiList->getSize();

			for (i = 0; i < kiSize; ++i) {

				if (kiList->item(i)->getKeyInfoType() == DSIGKeyInfo::KEYINFO_X509) {
					keyInfoX509 = (DSIGKeyInfoX509 *) kiList->item(i);
					break;
				}
			}

			if (keyInfoX509 == 0) {

				// Not found - need to create
				keyInfoX509 = sig->appendX509Data();

			}

			for (i = 0; i < certCount; ++i) {

				keyInfoX509->appendX509Certificate(certs[i]->getDEREncodingSB().rawCharBuffer());

			}

		} /* certCount > 0 */
	}

	catch (XSECException &e) {
		cerr << "An error occured during signature verification\n   Message: "
		<< e.getMsg() << endl;
		errorsOccured = true;
		exit (1);
	}

	// Print out the result

	DOMPrintFormatTarget* formatTarget = new DOMPrintFormatTarget();
	
    const XMLCh* encNameStr = XMLString::transcode("UTF-8");
    DOMNode *aNode = doc->getFirstChild();
    if (aNode->getNodeType() == DOMNode::ENTITY_NODE)
    {
        const XMLCh* aStr = ((DOMEntity *)aNode)->getEncoding();
        if (!strEquals(aStr, ""))
        {
            encNameStr = aStr;
        }
    }
    unsigned int lent = XMLString::stringLen(encNameStr);
    gEncodingName = new XMLCh[lent + 1];
    XMLString::copyNString(gEncodingName, encNameStr, lent);
    gEncodingName[lent] = 0;

	
	
	gFormatter = new XMLFormatter("UTF-8", formatTarget,
                                          XMLFormatter::NoEscapes, gUnRepFlags);

	cout << doc;

	prov.releaseSignature(sig);
	return 0;
}
Ejemplo n.º 26
0
unsigned int DSIGReference::readHash(XMLByte *toFill, unsigned int maxToFill) {

	// Determine the hash value stored in the reference

	// First set up for input

	unsigned int size;
	DOMNode *tmpElt;
	//const XMLCh * stringHash;

	TXFMBase * nextInput;

	DOMDocument *d = mp_referenceNode->getOwnerDocument();

	safeBuffer b64HashVal;

	// Find the hash value

	tmpElt = mp_referenceNode->getFirstChild();

	while (tmpElt != 0 && !strEquals(getDSIGLocalName(tmpElt), "DigestValue"))
		tmpElt = tmpElt->getNextSibling();

	if (tmpElt == NULL)
		// ERROR
		return 0;

	// Now read the DOMString of the hash

	tmpElt = tmpElt->getFirstChild();
	while (tmpElt != NULL && tmpElt->getNodeType() != DOMNode::TEXT_NODE)
		tmpElt = tmpElt->getNextSibling();

	if (tmpElt == NULL)
		// Something wrong with the underlying XML if no text was found
		throw XSECException(XSECException::NoHashFoundInDigestValue);

	b64HashVal << (*mp_formatter << tmpElt->getNodeValue());

	// Now have the value of the string - create a transform around it

	XSECnew(nextInput, TXFMSB(d));
	((TXFMSB *) nextInput)->setInput(b64HashVal);

	// Create a transform chain (really as a janitor for the entire list)
	TXFMChain * chain;
	XSECnew(chain, TXFMChain(nextInput));
	Janitor<TXFMChain> j_chain(chain);

	// Now create the base64 transform

	XSECnew(nextInput, TXFMBase64(d));
	chain->appendTxfm(nextInput);

	// Now get the value

	size = chain->getLastTxfm()->readBytes(toFill, maxToFill);

	// Clear any documentat modifications

	chain->getLastTxfm()->deleteExpandedNameSpaces();

	return size;

}
Ejemplo n.º 27
0
list<ClsDataClientConfig> ClsDataClientConfigReader::getDataClientConfig(string strFileName)  {
#ifdef DEBUG_CLSDATACLIENTCONFIGREADER
    cout << "ClsDataClientConfigReader::getDataClientConfig()" << endl;
#endif

    list<ClsDataClientConfig> lstConfigs;
#ifdef DEBUG_CLSDATACLIENTCONFIGREADER
    cout << "reading settings from: " << strFileName << endl;
#endif

    bool errorsOccured = false;
    static bool gDoNamespaces = false;

    if(!bXMLPlatformInitialized){
	try {
	    XMLPlatformUtils::Initialize();
	}
	catch(const XMLException& toCatch) {
	    cerr << "Error during Xerces-c Initialization.\n"
		 << "  Exception message:"
		 << toCatch.getMessage() << endl;
	    bXMLPlatformInitialized = false;
	    errorsOccured = true;
//	    return;
	}
	bXMLPlatformInitialized = true;
	errorsOccured = false;
    }
    //--------------------

    if (!errorsOccured) {
	XercesDOMParser* parser = new XercesDOMParser();
	parser->setValidationScheme(XercesDOMParser::Val_Never);
	/*
	  XercesDOMParser::Val_Never;
	  XercesDOMParser::Val_Auto;
	  XercesDOMParser::Val_Always;
	*/


	parser->setDoNamespaces(gDoNamespaces);
	ErrorHandler* errHandler = (ErrorHandler*) new HandlerBase();
	parser->setErrorHandler(errHandler);


	try {
	    parser->parse(strFileName.c_str());

	    int errorCount = parser->getErrorCount();
	    if (errorCount > 0){
		errorsOccured = true;
	    }

	} catch (const XMLException& e) {
	    cerr << "An error occured during parsing (XMLException)\n   NMessage: " <<  XMLString::transcode(e.getMessage()) << endl;
	    ClsDataClientConfigReaderException clsDataClientConfigReaderException(XMLString::transcode(e.getMessage()));
	    errorsOccured = true;
	    throw clsDataClientConfigReaderException;
	} catch (const DOMException& e) {
	    cerr << "An error occured during parsing (DOMException)\n   DMessage: " << XMLString::transcode(e.msg) << endl;
	    ClsDataClientConfigReaderException clsDataClientConfigReaderException(XMLString::transcode(e.msg));
	    errorsOccured = true;
	    throw clsDataClientConfigReaderException;
	} catch (const SAXException& e) {
	    cerr << "An error occured during parsing (SAXException)\n   DMessage: " <<  XMLString::transcode(e.getMessage()) << endl;
	    ClsDataClientConfigReaderException clsDataClientConfigReaderException(XMLString::transcode(e.getMessage()));
	    errorsOccured = true;
	    throw clsDataClientConfigReaderException;
	} catch (...) {
	    cerr << "An error occured during parsing\n " << endl;
	    errorsOccured = true;
	    ClsDataClientConfigReaderException clsDataClientConfigReaderException(ClsDataClientConfigReaderException::PARSE_ERROR);
	    throw clsDataClientConfigReaderException;
	}

	/* DOMNode* dnIqrConfig; */
	DOMDocument *ddocConfig = parser->getDocument();

	DOMNodeList* dnlstClients = ddocConfig->getElementsByTagName(XMLString::transcode(ConfigTagLibrary::DataClientTag()));

	try{
	    if(dnlstClients->getLength()>0){
		DOMNode* dnValue = NULL;

		unsigned int ii = 0;
		while( ii< dnlstClients->getLength()){
		    DOMNode* dnClient = dnlstClients->item(ii);
		    ii++;

		    string strType = getAttributeValue(dnClient, ConfigTagLibrary::TypeTag(), true);
		    string strID = getAttributeValue(dnClient, ConfigTagLibrary::IDTag(), false);
		    ClsDataClientConfig clsDataClientConfig(strID, strType);


		    DOMNodeList* dnlstClientChildren = dnClient->getChildNodes();
		    unsigned int i2 = 0;
		    while( i2< dnlstClientChildren->getLength()){
			DOMNode* dnClientChild = dnlstClientChildren->item(i2);
			if(dnClientChild->getNodeType() == 1){
			    string strName = XMLString::transcode(dnClientChild->getNodeName());
			    if(!strName.compare(ConfigTagLibrary::PositionTag())){
				int iX = 0;
				int iY = 0;
				iX = iqrUtils::string2int(getAttributeValue(dnClientChild, ConfigTagLibrary::PositionXTag(), true));
				iY = iqrUtils::string2int(getAttributeValue(dnClientChild, ConfigTagLibrary::PositionYTag(), true));
				clsDataClientConfig.setPosition(iX, iY);
			    } else if(!strName.compare(ConfigTagLibrary::Geometry())){
				int iWidth = 0;
				int iHeight = 0;
				    iWidth = iqrUtils::string2int(getAttributeValue(dnClientChild, ConfigTagLibrary::GeometryWidthTag(), true));
				    iHeight = iqrUtils::string2int(getAttributeValue(dnClientChild, ConfigTagLibrary::GeometryHeightTag(), true));
				clsDataClientConfig.setGeometry(iWidth, iHeight);
			    } else if(!strName.compare(ConfigTagLibrary::StateVariableDisplayTag())){
				DOMNodeList* dnlstSVD = dnClientChild->getChildNodes();
				unsigned int i3 = 0;
				while( i3< dnlstSVD->getLength()){
				    DOMNode* dnSVD = dnlstSVD->item(i3);
				    if(dnSVD->getNodeType() == 1){
					string strSVDID = getAttributeValue(dnSVD, ConfigTagLibrary::IDTag(), true);
//--					string strItemType = getAttributeValue(dnSVD, ConfigTagLibrary::TypeTag(), true);
					string strItemID = getAttributeValue(dnSVD, ConfigTagLibrary::ItemIDTag(), true);
					string strSelectedIndices = getAttributeValue(dnSVD, ConfigTagLibrary::SelectedIndicesTag(), true);
					ClsStateVariableDisplayConfig clsStateVariableDisplayConfig(/*strItemType,*/ strSVDID, strItemID, strSelectedIndices);
					DOMNodeList* dnlstSVDParams = dnSVD->getChildNodes();
					unsigned int i4 = 0;
					while( i4< dnlstSVDParams->getLength()){
					    DOMNode* dnSVDParam = dnlstSVDParams->item(i4);
					    if(dnSVDParam->getNodeType() == 1){
						string strParamName = XMLString::transcode(dnSVDParam->getNodeName());
						dnValue = dnSVDParam->getFirstChild();
						string strParamValue = "";
						if(dnValue!=NULL){
						    strParamValue = XMLString::transcode(dnValue->getNodeValue());
						}
						pair<string, string> pParam(strParamName, strParamValue);
						clsStateVariableDisplayConfig.addParameter(pParam);
					    }
					    i4++;
					}
					clsDataClientConfig.addStateVariableDisplayConfig(clsStateVariableDisplayConfig);
				    }
				    i3++;
				}
			    } else {
				string strValue = "";
				dnValue = dnClientChild->getFirstChild();
				if(dnValue!=NULL){
				    strValue = XMLString::transcode(dnValue->getNodeValue());
				}
				pair<string, string> pParam(strName, strValue);
				clsDataClientConfig.addParameter(pParam);
			    }
			}
			i2++;
		    }
		    lstConfigs.push_back(clsDataClientConfig);
		}
	    }
	} catch (...) {
	    ClsDataClientConfigReaderException clsDataClientConfigReaderException(ClsDataClientConfigReaderException::PARSE_ERROR);
	    throw clsDataClientConfigReaderException;
	}

	delete errHandler;
    }

    return lstConfigs;
};
Ejemplo n.º 28
0
bool BitMaskImp::fromXml(DOMNode* document, unsigned int version)
{
   string outsideVal(A(static_cast<DOMElement*>(document)->getAttribute(X("outside"))));
   string crcString(A(static_cast<DOMElement*>(document)->getAttribute(X("ecc"))));
   if (outsideVal == "1" || outsideVal == "t" || outsideVal == "true")
   {
      mOutside = true;
   }
   else
   {
      mOutside = false;
   }

   for (DOMNode* pChld = document->getFirstChild(); pChld != NULL; pChld = pChld->getNextSibling())
   {
      if (XMLString::equals(pChld->getNodeName(), X("rectangle")))
      {
         DOMNode* pGchld(pChld->getFirstChild());
         double a;
         double b;
         double c;
         double d;
         XmlReader::StrToQuadCoord(pGchld->getNodeValue(), a, b, c, d);
         mx1 = static_cast<int>(a);
         my1 = static_cast<int>(b);
         mx2 = static_cast<int>(c);
         my2 = static_cast<int>(d);
      }
      else if (XMLString::equals(pChld->getNodeName(), X("boundingBox")))
      {
         DOMNode* pGchld(pChld->getFirstChild());
         double a;
         double b;
         double c;
         double d;
         XmlReader::StrToQuadCoord(pGchld->getNodeValue(), a, b, c, d);
         mbbx1 = static_cast<int>(a);
         mbby1 = static_cast<int>(b);
         mbbx2 = static_cast<int>(c);
         mbby2 = static_cast<int>(d);
      }
      else if (XMLString::equals(pChld->getNodeName(), X("size")))
      {
         // we only need to read 3 coords by StrToQuadCoord still works well
         // as it handles cases where there are fewer than four coords (defaults them to 0.0)
         // so we just pass in a dummy that never actually gets read
         DOMNode* pGchld(pChld->getFirstChild());
         double a;
         double b;
         double c;
         double dummy;
         XmlReader::StrToQuadCoord(pGchld->getNodeValue(), a, b, c, dummy);
         mxSize = static_cast<int>(a);
         mySize = static_cast<int>(b);
         mCount = static_cast<int>(c);
         mSize = mxSize * mySize;
      }
      else if (XMLString::equals(pChld->getNodeName(), X("mask")))
      {
         mpMask = new (nothrow) unsigned int*[mySize];
         if (mpMask == NULL)
         {
            throw XmlReader::DomParseException("Can't create a new unsigned int array", pChld);
         }

         std::string checksum;
         if (crcString.find("ccitt:") != string::npos)
         {
            checksum = crcString.substr(crcString.find(":") + 1);
         }

         DOMNode* pGchld(pChld->getFirstChild());
         mpMask[0] = XmlBase::decodeBase64(reinterpret_cast<const XMLByte*>(A(pGchld->getNodeValue())), 0, checksum);
         if (mpMask[0] == NULL)
         {
            delete [] mpMask;
            mpMask = NULL;
            throw XmlReader::DomParseException("Can't decode the bitmask", pChld);
         }

         for (int i = 1; i < mySize; ++i)
         {
            mpMask[i] = mpMask[i - 1] + mxSize;
         }
      }
   }

   return true;
}
Ejemplo n.º 29
0
int  main()
{
	try {
		XMLPlatformUtils::Initialize();
	}
	catch (const XMLException& toCatch) {
        char *pMessage = XMLString::transcode(toCatch.getMessage());
        fprintf(stderr, "Error during XMLPlatformUtils::Initialize(). \n"
                        "  Message is: %s\n", pMessage);
        XMLString::release(&pMessage);
        return -1;
    }

    /*
    Range tests include testing of

    createRange

    setStart, setStartBefore. setStartAfter,
    setEnd, setEndBefore. setEndAfter
    getStartContainer, getStartOffset
    getEndContainer, getEndOffset
    getCommonAncestorContainer
    selectNode
    selectNodeContents
    insertNode
    deleteContents
    collapse
    getCollapsed
    surroundContents
    compareBoundaryPoints
    cloneRange
    cloneContents
    extractContents
    toString
    detach
    removeChild
    */
    {

        XMLCh tempStr[100];
        XMLString::transcode("Range",tempStr,99);
        {
            DOMImplementation* impl = DOMImplementationRegistry::getDOMImplementation(tempStr);
            DOMDocument* doc = impl->createDocument();

            //Creating a root element
            DOMElement*     root = doc->createElement(xBody);
            doc->appendChild(root);

            //Creating the siblings of root
            DOMElement*     E11 = doc->createElement(xH1);
            root->appendChild(E11);

            DOMElement*     E12 = doc->createElement(xP);
            root->appendChild(E12);

            //Attaching texts to siblings
            DOMText*        textNode1 = doc->createTextNode(xTitle);
            E11->appendChild(textNode1);

            DOMText*        textNode11 = doc->createTextNode(xAnotherText);
            E11->appendChild(textNode11);

            DOMText*        textNode2 = doc->createTextNode(xBlahxyz);
            E12->appendChild(textNode2);

            DOMText*     E210 = doc->createTextNode(xInsertedText);

            doc->release();


        }


        {
            //DOM Tree and some usable node creation
            DOMImplementation* impl = DOMImplementationRegistry::getDOMImplementation(tempStr);
            DOMDocument* doc = impl->createDocument();

            //Creating a root element
            DOMElement*     root = doc->createElement(xBody);
            doc->appendChild(root);

            //Creating the siblings of root
            DOMElement*     E11 = doc->createElement(xH1);
            root->appendChild(E11);

            DOMElement*     E12 = doc->createElement(xP);
            root->appendChild(E12);

            //Attaching texts to siblings
            DOMText*        textNode1 = doc->createTextNode(xTitle);
            E11->appendChild(textNode1);

            DOMText*        textNode11 = doc->createTextNode(xAnotherText);
            E11->appendChild(textNode11);

            DOMText*        textNode2 = doc->createTextNode(xBlahxyz);
            E12->appendChild(textNode2);

            //experimental nodes
            DOMElement*     E120 = doc->createElement(xElement1);
            DOMElement*     E121 = doc->createElement(xElement2);
            DOMElement*     E122 = doc->createElement(xElement3);
            DOMElement*     E311 = doc->createElement(xSurroundNode1);

            DOMText*     E210 = doc->createTextNode(xInsertedText);

            DOMNode* rt = doc->getDocumentElement();
            DOMRange* range = ((DOMDocumentRange*)doc)->createRange();



            //Tests start here
            // Initial dom tree looks like :
            // <Body><H1>TitleAnother Text</H1><P>Blah xyz</P></Body>
            //i.e.,            Body(rt)
            //     _____________|________________
            //     |                           |
            //  ___H1(E11)___                    P(E12)
            //  |           |                    |
            //  "Title"  "Another Text"        "Blah xyz"


            //test for start and end settings of a range
            range->setStart(rt->getFirstChild(), 0);
            TASSERT(range->getStartContainer() == rt->getFirstChild() );
            TASSERT(range->getStartOffset() == 0);

            range->setEnd(rt->getFirstChild(), 1);
            TASSERT(range->getEndContainer() == rt->getFirstChild() );
            TASSERT(range->getEndOffset() == 1);


            //DOMNode* node = range->getCommonAncestorContainer();
            TASSERT(range->getCommonAncestorContainer() == rt->getFirstChild());

            //selection related test
            range->selectNode(rt->getLastChild());
            TASSERT(range->getStartContainer() == rt);
            TASSERT(range->getStartOffset() == 1);
            TASSERT(range->getEndContainer() == rt);
            TASSERT(range->getEndOffset() == 2);

            //insertion related tests
            range->insertNode(E120);

            //only end offset moves and new node gets into range as being inserted at boundary point
            TASSERT(range->getStartContainer() == rt);
            TASSERT(range->getStartOffset() == 1);
            TASSERT(range->getEndContainer() == rt);
            TASSERT(range->getEndOffset() == 3);

            range->insertNode(E121);
            //only end offset moves and new node gets into range as being inserted at boundary point
            TASSERT(range->getStartContainer() == rt);
            TASSERT(range->getStartOffset() == 1);
            TASSERT(range->getEndContainer() == rt);
            TASSERT(range->getEndOffset() == 4);

            rt->insertBefore(E122, rt->getFirstChild());
            //both offsets move as new node is not part of the range
            TASSERT(range->getStartContainer() == rt);
            TASSERT(range->getStartOffset() == 2);
            TASSERT(range->getEndContainer() == rt);
            TASSERT(range->getEndOffset() == 5);

            //After above operations, now the tree looks like:
            // <Body><Element3/><H1>TitleAnother Text</H1><Element2/><Element1/><P>Blah xyz</P></Body>
            //i.e.,            Body(rt)
            //     _____________|_______________________________________________________________
            //     |                |                  |                |                      |
            //  Element3(E122)  ___H1(E11)___        Element2(E121)    Element1(E120)          P(E12)
            //                  |           |                                                  |
            //               "Title"  "Another Text"                                        "Blah xyz"
            //
            // range has rt as start and end container, and 2 as start offset, 5 as end offset

            //changing selection
            range->selectNode(rt->getLastChild()->getPreviousSibling());
            TASSERT(range->getStartContainer() == rt);
            TASSERT(range->getStartOffset() == 3);
            TASSERT(range->getEndContainer() == rt);
            TASSERT(range->getEndOffset() == 4);

            //deleting related tests
            range->deleteContents();
            TASSERT(rt->getLastChild()->getPreviousSibling() == E121);

            range->setStart(rt->getFirstChild()->getNextSibling()->getFirstChild(), 2);
            TASSERT(range->getStartContainer() == rt->getFirstChild()->getNextSibling()->getFirstChild());
            TASSERT(!XMLString::compareString(range->getStartContainer()->getNodeValue(),xTitle));
            TASSERT(range->getStartOffset() == 2);

            range->setEnd(rt->getFirstChild()->getNextSibling()->getFirstChild(), 4);
            TASSERT(range->getEndContainer() == rt->getFirstChild()->getNextSibling()->getFirstChild());
            TASSERT(!XMLString::compareString(range->getEndContainer()->getNodeValue(),xTitle));
            TASSERT(range->getEndOffset() == 4);
            TASSERT(!XMLString::compareString(range->toString(),xtl));

            //inserting text between a text node
            range->insertNode(E210);

            //only end offset moves and new node gets into range as being inserted at boundary point
            TASSERT(range->getStartContainer() == rt->getFirstChild()->getNextSibling()->getFirstChild());
            TASSERT(range->getStartOffset() == 2);
            TASSERT(range->getEndContainer() == rt->getFirstChild()->getNextSibling()->getLastChild()->getPreviousSibling());
            TASSERT(range->getEndOffset() == 2);

            //inserting element node before the selected text node
            range->insertNode(E120);
            //only end offset moves and new node gets into range as being inserted at boundary point
            TASSERT(range->getStartContainer() == rt->getFirstChild()->getNextSibling()->getFirstChild());
            TASSERT(!XMLString::compareString(range->getStartContainer()->getNodeValue(),xTi));
            TASSERT(range->getStartOffset() == 2);
            TASSERT(range->getEndContainer() == rt->getFirstChild()->getNextSibling()->getLastChild()->getPreviousSibling());
            TASSERT(!XMLString::compareString(range->getEndContainer()->getNodeValue(),xtle));
            TASSERT(range->getEndOffset() == 2);
            TASSERT(E11->getChildNodes()->getLength()==6);

           //checking the text replacment
            range->getStartContainer()->setNodeValue(xReplacedText);
            //only the start offset is impact
            TASSERT(range->getStartContainer() == rt->getFirstChild()->getNextSibling()->getFirstChild());
            TASSERT(!XMLString::compareString(range->getStartContainer()->getNodeValue(),xReplacedText));
            TASSERT(range->getStartOffset() == 0);
            TASSERT(range->getEndContainer() == rt->getFirstChild()->getNextSibling()->getLastChild()->getPreviousSibling());
            TASSERT(!XMLString::compareString(range->getEndContainer()->getNodeValue(),xtle));
            TASSERT(range->getEndOffset() == 2);

            //After above operations, now the tree looks like:
            // <Body><Element3/><H1>ReplacedText<Element1/>InsertedTexttleAnother Text</H1><Element2/><P>Blah xyz</P></Body>
            //i.e.,            Body(rt)
            //     _____________|_______________________________________________________________________________________________
            //     |                |                                                                          |                |
            //  Element3(E122)  ___H1(E11)___________________________________________________________        Element2(E121)    P(E12)
            //                  |              |     |                |                      |      |                             |
            //               "ReplacedText"   ""   Element1(E120)   "InsertedText"(E210)   "tle"  "Another Text"              "Blah xyz"
            //
            // range has "ReplacedText" as start container and "tle" as end container
            //   and 0 as start offset, 2 as end offset

            //changing the selection. Preparing for 'surround'
            range->setStart(range->getStartContainer()->getParentNode(), 2);
            range->setEnd(range->getStartContainer(), 5);
            TASSERT(!XMLString::compareString(range->getStartContainer()->getNodeName(),xH1));
            TASSERT(!XMLString::compareString(range->getEndContainer()->getNodeName(),xH1));
            TASSERT(!XMLString::compareString(range->toString(),xInsertedTexttle));

            range->surroundContents(E311);
            TASSERT(!XMLString::compareString(range->getStartContainer()->getNodeName(),xH1));
            TASSERT(range->getStartOffset() == 2);
            TASSERT(!XMLString::compareString(range->getEndContainer()->getNodeName(),xH1));
            TASSERT(range->getEndOffset() == 3);
            TASSERT(E11->getChildNodes()->getLength()==4);
            TASSERT(E311->getChildNodes()->getLength()==3);
            TASSERT(!XMLString::compareString(range->toString(),xInsertedTexttle));

            //After above operations, now the tree looks like:
            // <Body><Element3/><H1>ReplacedText<SurroundNode1><Element1/>InsertedTexttle</SurroundNode1>Another Text</H1><Element2/><P>Blah xyz</P></Body>
            //i.e.,            Body(rt)
            //     _____________|_________________________________________________________________________
            //     |                |                                                    |                |
            //  Element3(E122)  ___H1(E11)___________________________________        Element2(E121)    P(E12)
            //                  |              |     |                      |                            |
            //               "ReplacedText"   ""   SurroundNode1(E311)  "Another Text"              "Blah xyz"
            //                          ____________ |_____________________________
            //                          |                    |                    |
            //                          Element1(E120)   "InsertedText"(E210)   "tle"
            //
            // range has H1 as start and end container and 2 as start offset, 3 as end offset

            //testing cloning
            DOMRange* aRange = range->cloneRange();

            TASSERT(aRange->getStartContainer() == range->getStartContainer());
            TASSERT(aRange->getEndContainer() == range->getEndContainer());
            TASSERT(aRange->getStartOffset() == 2);
            TASSERT(aRange->getEndOffset() == 3);
            //changing the new ranges start
            aRange->setStart(aRange->getStartContainer()->getFirstChild(), 1);

            //comparing the ranges
            short compVal = range->compareBoundaryPoints(DOMRange::END_TO_END, aRange);
            TASSERT(compVal == 0);
            compVal = range->compareBoundaryPoints(DOMRange::START_TO_START, aRange);
            TASSERT(compVal == 1);
            compVal = range->compareBoundaryPoints(DOMRange::START_TO_END, aRange);
            TASSERT(compVal == 1);
            compVal = range->compareBoundaryPoints(DOMRange::END_TO_START, aRange);
            TASSERT(compVal == -1);

            //testing collapse
            //not collapsed
            TASSERT(range->getCollapsed() == false);
            TASSERT(range->getStartOffset() == 2);
            TASSERT(range->getEndOffset() == 3);

            //selectNodeContents
            range->selectNodeContents(rt->getLastChild()->getFirstChild());
            TASSERT(range->getStartContainer() == rt->getLastChild()->getFirstChild());
            TASSERT(range->getEndContainer() == rt->getLastChild()->getFirstChild());
            TASSERT(range->getStartOffset() == 0);
            TASSERT(range->getEndOffset() == 8);
            TASSERT(!XMLString::compareString(range->toString(),xBlahxyz));

            //testing collapse
            range->collapse(true); //collapse to start
            TASSERT(range->getCollapsed() == true);
            TASSERT(range->getStartOffset() == 0);
            TASSERT(range->getEndOffset() == 0);
            TASSERT(!XMLString::compareString(range->toString(),XMLUni::fgZeroLenString));
            TASSERT(aRange->getEndOffset() == 3); //other range is unaffected
            TASSERT(!XMLString::compareString(aRange->toString(),xeplacedTextInsertedTexttle));

            //After above operations, now the tree looks like:
            // <Body><Element3/><H1>ReplacedText<SurroundNode1><Element1/>InsertedTexttle</SurroundNode1>Another Text</H1><Element2/><P>Blah xyz</P></Body>
            //i.e.,            Body(rt)
            //     _____________|_________________________________________________________________________
            //     |                |                                                    |                |
            //  Element3(E122)  ___H1(E11)___________________________________        Element2(E121)    P(E12)
            //                  |              |     |                      |                            |
            //               "ReplacedText"   ""   SurroundNode1(E311)  "Another Text"              "Blah xyz"
            //                          ____________ |_____________________________
            //                          |                    |                    |
            //                          Element1(E120)   "InsertedText"(E210)   "tle"
            //
            // range has "Blah xyz" as start and end container and 0 as start and end offset (collapsed)
            // aRange has "ReplacedText" as start container and H1 as end container
            //    and 1 as start offset and 3 as end offset

            DOMDocumentFragment* docFrag = aRange->cloneContents();
            TASSERT( docFrag != 0);
            range->selectNode(rt->getFirstChild());
            TASSERT(range->getStartContainer() == rt);
            TASSERT(range->getEndContainer() == rt);
            TASSERT(range->getStartOffset() == 0);
            TASSERT(range->getEndOffset() == 1);

            //Testing toString()
            const XMLCh* str = aRange->toString();
            TASSERT(!XMLString::compareString(str, xeplacedTextInsertedTexttle));

            //start and end before and after tests
            range->setStartBefore(rt->getFirstChild());
            TASSERT(range->getStartOffset() == 0);
            range->setEndBefore(rt->getFirstChild());
            TASSERT(range->getEndOffset() == 0);
            range->setStartAfter(rt->getLastChild());
            TASSERT(range->getStartOffset() == 4);

            range->setStartAfter(rt->getFirstChild());
            TASSERT(range->getStartOffset() == 1);

            range->setEndBefore(rt->getLastChild());
            TASSERT(range->getEndOffset() == 3);

            range->setEndAfter(rt->getLastChild());
            TASSERT(range->getEndOffset() == 4);

            //testing extract()
            DOMDocumentFragment* frag2 = range->extractContents();
            TASSERT( frag2 != 0);

            //After above operations, now the tree looks like:
            // <Body><Element3/></Body>
            //i.e.,            Body(rt)
            //                  |
            //               Element3(E122)
            //
            // aRange has rt as start and end container, and 1 as start and end offset (collapsed)
            // range has rt as start and end container, and 1 as start and end offset (collapsed)
            //
            //and frag2 looks:
            // <Body>ReplacedText<SurroundNode1><Element1/>InsertedTexttle</SurroundNode1>Another Text</H1><Element2/><P>Blah xyz</P></Body>
            //i.e.,             Body(rt)
            //      ______________|________________________________________________________
            //      |                                                    |                |
            //   ___H1(E11)___________________________________        Element2(E121)    P(E12)
            //   |              |     |                      |                            |
            //"ReplacedText"   ""   SurroundNode1(E311)  "Another Text"              "Blah xyz"
            //           ____________ |_____________________________
            //           |                    |                    |
            //        Element1(E120)   "InsertedText"(E210)   "tle"
            //

            //the tree do not have those node anymore after extract
            //only Element3 left
            TASSERT(rt->getChildNodes()->getLength()==1);

            //aRange is collapsed
            TASSERT(aRange->getCollapsed() == true);
            TASSERT(aRange->getStartContainer() == rt);
            TASSERT(aRange->getStartOffset() == 1);
            TASSERT(aRange->getEndContainer() == rt);
            TASSERT(aRange->getEndOffset() == 1);

            //range is collapsed as well
            TASSERT(range->getCollapsed() == true);
            TASSERT(range->getStartContainer() == rt);
            TASSERT(range->getStartOffset() == 1);
            TASSERT(range->getEndContainer() == rt);
            TASSERT(range->getEndOffset() == 1);

            //test the document fragment frag2
            TASSERT(frag2->getChildNodes()->getLength()==3);

            //detaching the other range
            aRange->detach();
            range->detach();

            //***************************************************************
            //another set of test
            //TEST createRange, setStart and setEnd, insertnode
            //***************************************************************
            DOMImplementation* impl2 = DOMImplementationRegistry::getDOMImplementation(tempStr);
            DOMDocument* doc2 = impl2->createDocument();

            DOMElement* root2 = doc2->createElement(xroot2);
            doc2->appendChild(root2);
            //case 1: simple text node, start==end
            // <body>text1</body>
            DOMElement* body = doc2->createElement(xBody);
            DOMText* text1 = doc2->createTextNode(xtext1);
            body->appendChild(text1);
            root2->appendChild(body);

            //set range
            DOMRange* range1 = doc2->createRange();
            range1->setStart(text1,1);
            range1->setEnd(text1,3);

            TASSERT(!XMLString::compareString(range1->toString(),xex));
            TASSERT(range1->getStartOffset()==1);
            TASSERT(!XMLString::compareString(range1->getStartContainer()->getNodeValue(),xtext1));
            TASSERT(range1->getEndOffset()==3);
            TASSERT(!XMLString::compareString(range1->getEndContainer()->getNodeValue(),xtext1));

            //now insert a text node
            //<body>ttext2ext1</body>
            DOMText* text2 = doc2->createTextNode(xtext2);
            range1->insertNode(text2);

            TASSERT(!XMLString::compareString(range1->toString(),xtext2ex));
            TASSERT(range1->getStartOffset()==1);
            TASSERT(!XMLString::compareString(range1->getStartContainer()->getNodeValue(),xt));
            TASSERT(range1->getEndOffset()==2);
            TASSERT(!XMLString::compareString(range1->getEndContainer()->getNodeValue(),xext1));

            //now insert a non-text node
            //<body>t<p1/>text2ext1</body>
            DOMElement* p1 = doc2->createElement(xp1);
            range1->insertNode(p1);

            TASSERT(!XMLString::compareString(range1->toString(),xtext2ex));
            TASSERT(range1->getStartOffset()==1);
            TASSERT(!XMLString::compareString(range1->getStartContainer()->getNodeValue(),xt));
            TASSERT(range1->getEndOffset()==2);
            TASSERT(!XMLString::compareString(range1->getEndContainer()->getNodeValue(),xext1));

            //case 2: non-text node, start==end
            // <head><h1/></head>
            DOMElement* head = doc2->createElement(xhead);
            DOMElement* h1 = doc2->createElement(xH1);
            head->appendChild(h1);
            root2->appendChild(head);

            //set range
            DOMRange* range2 = doc2->createRange();
            range2->setStart(head,0);
            range2->setEnd(head,1);

            TASSERT(!XMLString::compareString(range2->toString(),XMLUni::fgZeroLenString));
            TASSERT(range2->getStartOffset()==0);
            TASSERT(!XMLString::compareString(range2->getStartContainer()->getNodeName(),xhead));
            TASSERT(range2->getEndOffset()==1);
            TASSERT(!XMLString::compareString(range2->getEndContainer()->getNodeName(),xhead));

            //now insert a non-text node
            //<head><h2/><h1/></head>
            DOMElement* h2 = doc2->createElement(xh2);
            range2->insertNode(h2);

            TASSERT(!XMLString::compareString(range2->toString(),XMLUni::fgZeroLenString));
            TASSERT(range2->getStartOffset()==0);
            TASSERT(!XMLString::compareString(range2->getStartContainer()->getNodeName(),xhead));
            TASSERT(range2->getEndOffset()==2);
            TASSERT(!XMLString::compareString(range2->getEndContainer()->getNodeName(),xhead));

            //now insert a text node
            //<head>text5<h2/><h1/></head>
            DOMText* text5 = doc2->createTextNode(xtext5);
            range2->insertNode(text5);

            TASSERT(!XMLString::compareString(range2->toString(),xtext5));
            TASSERT(range2->getStartOffset()==0);
            TASSERT(!XMLString::compareString(range2->getStartContainer()->getNodeName(),xhead));
            TASSERT(range2->getEndOffset()==3);
            TASSERT(!XMLString::compareString(range2->getEndContainer()->getNodeName(),xhead));

            //case 3: simple text node, start!=end
            // <body2>text3</body2>
            DOMElement* body2 = doc2->createElement(xbody2);
            DOMText* text3 = doc2->createTextNode(xtext3);
            body2->appendChild(text3);
            root2->appendChild(body2);

            //set range
            DOMRange* range3 = ((DOMDocumentRange*)doc2)->createRange();
            range3->setStart(text3,1);
            range3->setEnd(body2,1);

            TASSERT(!XMLString::compareString(range3->toString(),xext3));
            TASSERT(range3->getStartOffset()==1);
            TASSERT(!XMLString::compareString(range3->getStartContainer()->getNodeValue(),xtext3));
            TASSERT(range3->getEndOffset()==1);
            TASSERT(!XMLString::compareString(range3->getEndContainer()->getNodeName(),xbody2));

            //now insert a textnode
            //<body2>ttext4ext3</body2>
            DOMText* text4 = doc2->createTextNode(xtext4);
            range3->insertNode(text4);

            TASSERT(!XMLString::compareString(range3->toString(),XMLUni::fgZeroLenString));
            TASSERT(range3->getStartOffset()==1);
            TASSERT(!XMLString::compareString(range3->getStartContainer()->getNodeValue(),xt));
            TASSERT(range3->getEndOffset()==1);
            TASSERT(!XMLString::compareString(range3->getEndContainer()->getNodeName(),xbody2));

            //now insert a non-text node
            //<body2>t<p2/>text4ext3</body2>
            DOMElement* p2 = doc2->createElement(xp2);
            range3->insertNode(p2);

            //extra empty node caused by splitting 't'
            TASSERT(!XMLString::compareString(range3->toString(),XMLUni::fgZeroLenString));
            TASSERT(range3->getStartOffset()==1);
            TASSERT(!XMLString::compareString(range3->getStartContainer()->getNodeValue(),xt));
            TASSERT(range3->getEndOffset()==1);
            TASSERT(!XMLString::compareString(range3->getEndContainer()->getNodeName(),xbody2));

            //test toString a bit
            range3->setStart(body2,1);
            range3->setEnd(body2,5);

            TASSERT(!XMLString::compareString(range3->toString(),xtext4ext3));

            range3->setStart(body2,0);
            range3->setEnd(body2,5);

            TASSERT(!XMLString::compareString(range3->toString(),xttext4ext3));

            //case 4: non-text node, start!=end
            // <head2><h3/></head2>
            DOMElement* head2 = doc2->createElement(xhead2);
            DOMElement* h3 = doc2->createElement(xh3);
            head2->appendChild(h3);
            root2->appendChild(head2);

            //set range
            DOMRange* range4 = doc2->createRange();
            range4->setStart(head2,0);
            range4->setEnd(h3,0);

            TASSERT(!XMLString::compareString(range4->toString(),XMLUni::fgZeroLenString));
            TASSERT(range4->getStartOffset()==0);
            TASSERT(!XMLString::compareString(range4->getStartContainer()->getNodeName(),xhead2));
            TASSERT(range4->getEndOffset()==0);
            TASSERT(!XMLString::compareString(range4->getEndContainer()->getNodeName(),xh3));

            //now insert a non-text node
            //<head2><h4/><h3/></head2>
            DOMElement* h4 = doc2->createElement(xh4);
            range4->insertNode(h4);

            TASSERT(!XMLString::compareString(range4->toString(),XMLUni::fgZeroLenString));
            TASSERT(range4->getStartOffset()==0);
            TASSERT(!XMLString::compareString(range4->getStartContainer()->getNodeName(),xhead2));
            TASSERT(range4->getEndOffset()==0);
            TASSERT(!XMLString::compareString(range4->getEndContainer()->getNodeName(),xh3));

            //now insert a text node
            //<head2>text6<h4/><h3/></head2>
            DOMText* text6 = doc2->createTextNode(xtext6);
            range4->insertNode(text6);

            TASSERT(!XMLString::compareString(range4->toString(),xtext6));
            TASSERT(range4->getStartOffset()==0);
            TASSERT(!XMLString::compareString(range4->getStartContainer()->getNodeName(),xhead2));
            TASSERT(range4->getEndOffset()==0);
            TASSERT(!XMLString::compareString(range4->getEndContainer()->getNodeName(),xh3));

            //***************************************************************
            // quick test of updating
            //***************************************************************
            // <upbody>text1</upbody>
            DOMElement* upbody = doc2->createElement(xupbody);
            DOMText* uptext1 = doc2->createTextNode(xuptext1);
            upbody->appendChild(uptext1);
            root2->appendChild(upbody);

            DOMRange* uprange = ((DOMDocumentRange*)doc2)->createRange();
            uprange->setStart(upbody,0);
            uprange->setEnd(upbody,1);

            TASSERT(!XMLString::compareString(uprange->toString(),xuptext1));
            TASSERT(uprange->getStartOffset()==0);
            TASSERT(!XMLString::compareString(uprange->getStartContainer()->getNodeName(),xupbody));
            TASSERT(uprange->getEndOffset()==1);
            TASSERT(!XMLString::compareString(uprange->getEndContainer()->getNodeName(),xupbody));

            // split text
            uptext1->splitText(1);

            TASSERT(!XMLString::compareString(uprange->toString(),xu));
            TASSERT(uprange->getStartOffset()==0);
            TASSERT(!XMLString::compareString(uprange->getStartContainer()->getNodeName(),xupbody));
            TASSERT(uprange->getEndOffset()==1);
            TASSERT(!XMLString::compareString(uprange->getEndContainer()->getNodeName(),xupbody));

            //insert node
            DOMElement* upbody2 = doc2->createElement(xupbody2);
            DOMText* uptext2 = doc2->createTextNode(xuptext2);
            upbody2->appendChild(uptext2);
            root2->appendChild(upbody2);

            DOMRange* uprange2 = ((DOMDocumentRange*)doc2)->createRange();
            uprange2->setStart(uptext2,1);
            uprange2->setEnd(upbody2,1);

            DOMRange* uprange3 = doc2->createRange();
            uprange3->setStart(uptext2,1);
            uprange3->setEnd(upbody2,1);

            TASSERT(!XMLString::compareString(uprange2->toString(),xptext2));
            TASSERT(uprange2->getStartOffset()==1);
            TASSERT(!XMLString::compareString(uprange2->getStartContainer()->getNodeValue(),xuptext2));
            TASSERT(uprange2->getEndOffset()==1);
            TASSERT(!XMLString::compareString(uprange2->getEndContainer()->getNodeName(),xupbody2));

            TASSERT(!XMLString::compareString(uprange3->toString(),xptext2));
            TASSERT(uprange3->getStartOffset()==1);
            TASSERT(!XMLString::compareString(uprange3->getStartContainer()->getNodeValue(),xuptext2));
            TASSERT(uprange3->getEndOffset()==1);
            TASSERT(!XMLString::compareString(uprange3->getEndContainer()->getNodeName(),xupbody2));

            DOMElement* upp1 = doc2->createElement(xupp1);
            uprange2->insertNode(upp1);

            TASSERT(!XMLString::compareString(uprange2->toString(),XMLUni::fgZeroLenString));
            TASSERT(uprange2->getStartOffset()==1);
            TASSERT(!XMLString::compareString(uprange2->getStartContainer()->getNodeValue(),xu));
            TASSERT(uprange2->getEndOffset()==1);
            TASSERT(!XMLString::compareString(uprange2->getEndContainer()->getNodeName(),xupbody2));

            TASSERT(!XMLString::compareString(uprange3->toString(),XMLUni::fgZeroLenString));
            TASSERT(uprange3->getStartOffset()==1);
            TASSERT(!XMLString::compareString(uprange3->getStartContainer()->getNodeValue(),xu));
            TASSERT(uprange3->getEndOffset()==1);
            TASSERT(!XMLString::compareString(uprange3->getEndContainer()->getNodeName(),xupbody2));

            //***************************************************************
            //another set of test
            //<foo><c/><moo><b/></moo>ab<a>Hello cd</a><cool>ef</cool></foo>
            //
            //  ______________________foo_____________________
            //  |          |           |          |           |
            //  c         moo        "ab"         a          cool
            //             |                      |           |
            //             b                    "Hello cd"   "ef"
            //
            DOMImplementation* impl3 = DOMImplementationRegistry::getDOMImplementation(tempStr);
            DOMDocument* doc3 = impl3->createDocument();

            DOMElement* root3 = doc3->createElement(xroot);
            doc3->appendChild(root3);

            DOMElement* foo = doc3->createElement(xfoo);
            DOMElement* moo = doc3->createElement(xmoo);
            DOMElement* cool = doc3->createElement(xcool);
            DOMText* ab = doc3->createTextNode(xab);
            DOMText* cd = doc3->createTextNode(xHellocd);
            DOMText* ef = doc3->createTextNode(xef);

            DOMElement* a = doc3->createElement(xa);
            DOMElement* b = doc3->createElement(xb);
            DOMElement* c = doc3->createElement(xc);

            root3->appendChild(foo);
            foo->appendChild(c);
            foo->appendChild(moo);
            foo->appendChild(ab);
            foo->appendChild(a);
            foo->appendChild(cool);
            moo->appendChild(b);
            a->appendChild(cd);
            cool->appendChild(ef);

            //***************************************************************
            //TEST toString
            //***************************************************************
            DOMRange* newtestrange = ((DOMDocumentRange*)doc3)->createRange();
            //case 1:
            //start container is text node
            //   i) end container is also text node
            //    a) start==end
            //    b) start!=end
            //  ii) end container is not text node
            //    a) start==end => impossible
            //    b) start!=end
            //
            //case 2:
            //start container is not text node
            //   i) end container is text node
            //    a) start==end => impossible
            //    b) start!=end
            //  ii) end container is not text node
            //    a) start==end
            //    b) start!=end

            //case 1, i, a
            newtestrange->setStart( cd, 1 );
            newtestrange->setEnd( cd, 4 );

            TASSERT(!XMLString::compareString(newtestrange->toString(),xell));

            //case 1, i, b
            newtestrange->setStart( cd, 1 );
            newtestrange->setEnd( ef, 2 );

            TASSERT(!XMLString::compareString(newtestrange->toString(),xellocdef));

            //case 1, ii, b
            newtestrange->setStart( cd, 1 );
            newtestrange->setEnd( foo, 4 );

            TASSERT(!XMLString::compareString(newtestrange->toString(),xellocd));

            //case 2, i, b
            newtestrange->setStart( foo, 1 );
            newtestrange->setEnd( cd, 5 );

            TASSERT(!XMLString::compareString(newtestrange->toString(),xabHello));

            //case 2, ii, a
            newtestrange->setStart( foo, 1 );
            newtestrange->setEnd( foo, 4 );

            TASSERT(!XMLString::compareString(newtestrange->toString(),xabHellocd));

            //case 2, ii, b
            newtestrange->setStart( moo, 1 );
            newtestrange->setEnd( foo, 4 );

            TASSERT(!XMLString::compareString(newtestrange->toString(),xabHellocd));

            //***************************************************************
            //test removeChild
            //***************************************************************
            DOMRange* newrange = doc3->createRange();
            newrange->setStart( moo, 0 );
            newrange->setEnd( foo, 4 );

            TASSERT(newrange->getStartOffset()==0);
            TASSERT(!XMLString::compareString(newrange->getStartContainer()->getNodeName(),xmoo));
            TASSERT(newrange->getEndOffset()==4);
            TASSERT(!XMLString::compareString(newrange->getEndContainer()->getNodeName(),xfoo));
            TASSERT(!XMLString::compareString(newrange->toString(),xabHellocd));

            DOMNode* n = newrange->cloneContents();
            DOMNodeList* nol = foo->getChildNodes();

            //removing moo
            DOMNode* rem = foo->removeChild(nol->item(1));
            rem->release();
            TASSERT(newrange->getStartOffset()==1);
            TASSERT(!XMLString::compareString(newrange->getStartContainer()->getNodeName(),xfoo));
            TASSERT(newrange->getEndOffset()==3);
            TASSERT(!XMLString::compareString(newrange->getEndContainer()->getNodeName(),xfoo));
            TASSERT(!XMLString::compareString(newrange->toString(),xabHellocd));

            TASSERT(newtestrange->getStartOffset()==1);
            TASSERT(!XMLString::compareString(newtestrange->getStartContainer()->getNodeName(),xfoo));
            TASSERT(newtestrange->getEndOffset()==3);
            TASSERT(!XMLString::compareString(newtestrange->getEndContainer()->getNodeName(),xfoo));
            TASSERT(!XMLString::compareString(newtestrange->toString(),xabHellocd));

            // Now do some exception test
            newrange->detach();
            EXCEPTION_TEST(newrange->setStart( moo, 0 ), DOMException::INVALID_STATE_ERR);
            EXCEPTION_TEST(newtestrange->setStartBefore(moo), DOMRangeException::INVALID_NODE_TYPE_ERR);


            doc->release();
            doc2->release();
            doc3->release();
        }
    } //creating the dom tree and tests

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

    if (errorOccurred) {
        printf("Test Failed\n");
        return 4;
    }

    printf("Test Run Successfully\n");

    return 0;
};
Ejemplo n.º 30
0
void ConfigManager::Initialize()
{
	bool failed = false;
	m_configTopNode = NULL;

	try
	{
		char* cfgFilename = NULL;
		char* cfgEnvPath = "";
		int cfgAlloc = 0;

		cfgEnvPath = ACE_OS::getenv("ORKAUDIO_CONFIG_PATH");
		if(cfgEnvPath) {
			ACE_DIR* dir = ACE_OS::opendir(cfgEnvPath);
			if(dir) {
				int len = 0;

				ACE_OS::closedir(dir);
				len = strlen(cfgEnvPath)+1+strlen(CONFIG_FILE_NAME)+1;
				cfgFilename = (char*)malloc(len);

				if(cfgFilename) {
					cfgAlloc = 1;
					snprintf(cfgFilename, len, "%s/%s", cfgEnvPath, CONFIG_FILE_NAME);
				}
			}
		}

		if(!cfgFilename) {
			FILE* file = ACE_OS::fopen(CONFIG_FILE_NAME, "r");
			if(file)
			{
				// config.xml exists in the current directory
				cfgFilename = (char*)CONFIG_FILE_NAME;
				fclose(file);
			}
			else
			{
				// config.xml could not be found in the current
				// directory, try to find it in system configuration directory
				cfgFilename = (char*)ETC_CONFIG_FILE_NAME;
			}
		}

        	XMLPlatformUtils::Initialize();

		// By default, the DOM document generated by the parser will be free() by the parser.
		// If we ever need to free the parser and the document separately, we need to do this:
		//		DOMNode *doc = parser->getDocument();
		//		...
		//		parser->adoptDocument();
		//		doc->release();
		//		...
		//		delete parser;
		XercesDOMParser *m_parser = new XercesDOMParser;
		XmlErrorHandler errhandler;
		m_parser->setErrorHandler(&errhandler);
		m_parser->parse(cfgFilename);
		DOMNode	*doc = NULL;
		doc = m_parser->getDocument();

		// XXX is it okay to free here?
		if(cfgAlloc) {
			free(cfgFilename);
		}

		if (doc)
		{
			DOMNode *firstChild = doc->getFirstChild();
			if (firstChild)
			{
				m_configTopNode = firstChild;
				m_config.DeSerializeDom(firstChild);

				/*
				// Write out config to a file
				DOMImplementation* impl =  DOMImplementationRegistry::getDOMImplementation(XStr("Core").unicodeForm());
				XERCES_CPP_NAMESPACE::DOMDocument* myDoc;
				   myDoc = impl->createDocument(
							   0,                    // root element namespace URI.
							   XStr("root").unicodeForm(),         // root element name
							   0);                   // document type object (DTD).
				m_config.SerializeDom(myDoc);
				CStdString toto = DomSerializer::DomNodeToString(myDoc);
				FILE* file = fopen("zzz.xml", "w");
				fwrite((PCSTR)toto,1,toto.GetLength(),file);
				fclose(file);
				*/
			}
			else
			{
				LOG4CXX_ERROR(LOG.configLog, CStdString("Could not parse config file:") + CONFIG_FILE_NAME);
				failed = true;
			}
		}
		else
		{
			LOG4CXX_WARN(LOG.configLog, CStdString("Could not find config file:") + CONFIG_FILE_NAME);
		}
	}
	catch (const CStdString& e)
	{
		LOG4CXX_ERROR(LOG.configLog, e);
		failed = true;
	}
	catch(const XMLException& e)
	{
		LOG4CXX_ERROR(LOG.configLog, e.getMessage());
		failed = true;
	}
	catch(const SAXParseException& e)
	{
		CStdString logMsg;
		logMsg.Format("config.xml error at line:%d, column:%d. (Use xmllint or xml editor to check the configuration)",  e.getLineNumber(), e.getColumnNumber());
		LOG4CXX_ERROR(LOG.configLog, logMsg);
		failed = true;
	}
	if (failed)
	{
		exit(0);
	}
}