Ejemplo n.º 1
0
// ---------------------------------------------------------------------------
//  GeneralAttributeCheck: Validation methods
// ---------------------------------------------------------------------------
void
GeneralAttributeCheck::checkAttributes(const DOMElement* const elem,
                                       const unsigned short elemContext,
                                       TraverseSchema* const schema,
                                       const bool isTopLevel,
                                       ValueVectorOf<DOMNode*>* const nonXSAttList)
{
    if (nonXSAttList)
        nonXSAttList->removeAllElements();

    if (elem == 0 || !fAttMap || elemContext>=E_Count)
        return;

    const XMLCh* elemName = elem->getLocalName();
    if (!XMLString::equals(SchemaSymbols::fgURI_SCHEMAFORSCHEMA, elem->getNamespaceURI())) {
        schema->reportSchemaError
        (
            elem
            , XMLUni::fgXMLErrDomain
            , XMLErrs::ELTSchemaNS
            , elemName
        );
    }

    DOMNamedNodeMap* eltAttrs = elem->getAttributes();
    const XMLSize_t  attrCount = eltAttrs->getLength();
    XMLByte          attList[A_Count];

    memset(attList, 0, sizeof(attList));

    for (XMLSize_t i = 0; i < attrCount; i++) {

        DOMNode*     attribute = eltAttrs->item(i);
        const XMLCh* attName = attribute->getNodeName();

        // skip namespace declarations
        if (XMLString::equals(attName, XMLUni::fgXMLNSString)
            || XMLString::startsWith(attName, XMLUni::fgXMLNSColonString))
            continue;

        // Bypass attributes that start with xml
        // add this to the list of "non-schema" attributes
        if ((*attName == chLatin_X || *attName == chLatin_x)
           && (*(attName+1) == chLatin_M || *(attName+1) == chLatin_m)
           && (*(attName+2) == chLatin_L || *(attName+2) == chLatin_l)) {

           if (nonXSAttList)
                nonXSAttList->addElement(attribute);

            continue;
        }

        // for attributes with namespace prefix
        const XMLCh* attrURI = attribute->getNamespaceURI();

        if (attrURI != 0 && *attrURI) {

            // attributes with schema namespace are not allowed
            // and not allowed on "documentation" and "appInfo"
            if (XMLString::equals(attrURI, SchemaSymbols::fgURI_SCHEMAFORSCHEMA) ||
                XMLString::equals(elemName, SchemaSymbols::fgELT_APPINFO) ||
                XMLString::equals(elemName, SchemaSymbols::fgELT_DOCUMENTATION)) {

                schema->reportSchemaError(elem, XMLUni::fgXMLErrDomain,
                                          isTopLevel?XMLErrs::AttributeDisallowedGlobal:XMLErrs::AttributeDisallowedLocal, 
                                          attName, elemName);
            }
            else if (nonXSAttList)
            {
                nonXSAttList->addElement(attribute);
            }

            continue;
        }

        int attNameId = A_Invalid;
        attName = attribute->getLocalName();

        bool bContinue=false;   // workaround for Borland bug with 'continue' in 'catch'
        try {
            attNameId= fAttMap->get(attName, fMemoryManager);
        }
        catch(const OutOfMemoryException&)
        {
            throw;
        }
        catch(...) {

            schema->reportSchemaError(elem, XMLUni::fgXMLErrDomain,
                                      isTopLevel?XMLErrs::AttributeDisallowedGlobal:XMLErrs::AttributeDisallowedLocal, 
                                      attName, elemName);
            bContinue=true;
        }
        if(bContinue)
            continue;

        if (fgElemAttTable[elemContext][attNameId] & Att_Mask) {

            attList[attNameId] = 1;
            validate
            (
                elem
                , attName
                , attribute->getNodeValue()
                , fgElemAttTable[elemContext][attNameId] & DV_Mask
                , schema
            );
        }
        else {
            schema->reportSchemaError(elem, XMLUni::fgXMLErrDomain,
                                      isTopLevel?XMLErrs::AttributeDisallowedGlobal:XMLErrs::AttributeDisallowedLocal, 
                                      attName, elemName);
        }
    }

    // ------------------------------------------------------------------
    // Check for required attributes
    // ------------------------------------------------------------------
    for (unsigned int j=0; j < A_Count; j++) {

        if ((fgElemAttTable[elemContext][j] & Att_Required) && attList[j] == 0) {
            schema->reportSchemaError(elem, XMLUni::fgXMLErrDomain, 
                                      isTopLevel?XMLErrs::AttributeRequiredGlobal:XMLErrs::AttributeRequiredLocal, 
                                      fAttNames[j], elemName);
        }
    }
}
Ejemplo n.º 2
0
void InputHandler::initParamsFromDOM(DOMNode *node, multimap<string, ParamWrapper*> registry)
{

     assert(node);
     char *tmp = XMLString::transcode(node->getNodeName());
     crusde_debug("%s, line: %d, initParamsFromDOM for node: %s.", __FILE__, __LINE__, tmp);
     XMLString::release(&tmp);

     DOMNode *child = node->getFirstChild();
     DOMNamedNodeMap *attributes = NULL;
     DOMNode *attr = NULL;

     multimap<string, ParamWrapper*>::iterator key_iter;
     pair< multimap<string, ParamWrapper*>::iterator, multimap<string, ParamWrapper*>::iterator > key_range;

     list<string> params_set;

     int count_keys(-1);
     unsigned int count_set(0);
     int empty_param(0);

     while (child)
     {
          if( child->getNodeType() == DOMNode::ELEMENT_NODE)
          {
               attributes = child->getAttributes();
               attr = attributes->getNamedItem(ATTR_name.xmlStr());

               char* name = XMLString::transcode(attr->getNodeValue());

               if( XMLString::compareIString(child->getNodeName(), TAG_parameter.xmlStr()) == 0 )
               {			
                    //get number of keys that equal name
                    count_keys = static_cast<int>( registry.count(string(name)) );
                    //if there is anything in the registry ... 
                    if( count_keys > 0 )
                    {		
                         //equal_range gives two results: an iterator to the first and last element with key==name
                         key_range = registry.equal_range(string(name));
                         //all keys have values that are adresses of double variables in the repsective plugins
                         //each of those variables now gets a value assigned. the same value.
                         for ( key_iter=key_range.first; key_iter != key_range.second; ++key_iter)
                         {
                              //get the value from the DOM
                              StrXML value(attributes->getNamedItem(ATTR_value.xmlStr())->getNodeValue());
                              //write it into the variable that's strored at key_iter->second
                              if( (key_iter->second)->isString() )
                              {
                                   (key_iter->second)->setValue( value.cppStr() );
                              }
                              else if( (key_iter->second)->isDouble() )
                              {
                                   (key_iter->second)->setValue( static_cast<double>( atof(value.cStr()) ) );
                              }

                              ++count_set;
                         }
                         //memorize the key that was set only once
                         params_set.push_back(key_range.first->first);
                    }
                    else //if not found there might be a spelling mistake either in input, or plugin, or both :)
                    {
                         StrXML paramName(attributes->getNamedItem(ATTR_name.xmlStr())->getNodeValue());
                         crusde_warning("Parameter %s (coming from the experiment definition) not registered! Misspelled in XML file or Plug-in definition?",paramName.cStr());
                    }
               }

               XMLString::release(&name);         	
          }
		
          child = child->getNextSibling();
     }
	
     //two cases are possible for leftover parameters: 
     //     i)  they are optional parameters - check registry for that
     //     ii) they are unitialized - oh well, we gotta stop there
     if(count_set < registry.size())
     {
          multimap<string, ParamWrapper*>::iterator map_iter = registry.begin();
          list<string>::iterator found_iter;
          string out_string("Error: Parameters that remain uninitialized: \n");		

          while (map_iter != registry.end())
          {
               if(!map_iter->second->isOptional())
               {
                    found_iter = params_set.begin();
                    //as long as we're not at the end and could not find the parameter in the list of set 
                    //parameters, continue looking.
                    while( found_iter != params_set.end() && (*found_iter).compare(map_iter->first) != 0  ) 
                    {
                         ++found_iter;
                    } 	
                    //if we're at the end, the parameter was not in out list ... tell the user.			
                    if(found_iter==params_set.end() ) 
                    {
                         ++empty_param;
                         out_string.append("\t");
                         out_string.append(map_iter->first);
                         out_string.append("\n");
                    }
               }
		
               //get to the next unique value in the registry ... avoid printing multiple keys twice.
               map_iter = ( registry.equal_range(map_iter->first) ).second;
          }

          if(empty_param > 0) 
          {
               crusde_error("%s, Aborting.", out_string.c_str());
          }
     }		
}	
static void removeBaseAttr(DOMDocument * domDocument) {

    XMLNodeFilter * nodeFilter = new XMLNodeFilter();
    DOMTreeWalker * domTreeWalker = domDocument->createTreeWalker(domDocument, DOMNodeFilter::SHOW_ALL, nodeFilter, true);

    DOMNode * node = domTreeWalker->getCurrentNode();
    while (node) {
        DOMNamedNodeMap * nodeMap = node->getAttributes();
        if (nodeMap != 0) {
            DOMNode * attr = nodeMap->getNamedItem(XMLString::transcode("xml:base"));
            if (attr) {
                DOMNode * node = nodeMap->removeNamedItem(XMLString::transcode("xml:base"));

                TFINFO("[Server Config] filtered attribute: " << XMLString::transcode(node->getNodeName()) << "=" << XMLString::transcode(node->getNodeValue()));
                node->release();
            }
        }
        node = domTreeWalker->nextNode();
    }
    delete nodeFilter;
}
Ejemplo n.º 4
0
xmlstream& operator<<(xmlstream& target, const DOMNode* toWrite)
{
    // Get the name and value out for convenience
    const XMLCh* nodeName = toWrite->getNodeName();
    const XMLCh* nodeValue = toWrite->getNodeValue();


	switch (toWrite->getNodeType())
    {
		case DOMNode::TEXT_NODE:
        {
            outputContent(target, nodeValue);
            break;
        }

        case DOMNode::PROCESSING_INSTRUCTION_NODE :
        {
            target  << XMLStrL("<?")
                    << nodeName
                    << XMLStrL(' ')
                    << nodeValue
                    << XMLStrL("?>");
            break;
        }

        case DOMNode::DOCUMENT_NODE :
        {
            //
            //  Bug here:  we need to find a way to get the encoding name
            //  for the default code page on the system where the program
            //  is running, and plug that in for the encoding name.
            //
            XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument* document=(XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument*)toWrite;
            target << XMLStrL("<?xml version=\"") << document->getVersion() << XMLStrL("\"");
            const XMLCh* str = document->getEncoding();
            if (str != 0)
                target << XMLStrL(" encoding=\"") << str << XMLStrL("\"");
            if(document->getStandalone())
                target << XMLStrL(" standalone=\"yes\"");
            target << XMLStrL("?>");

            DOMNode* child = toWrite->getFirstChild();
            while( child != 0)
            {
                target << child;
                child = child->getNextSibling();
            }
            break;
        }

        case DOMNode::ELEMENT_NODE :
        {
            // Output the element start tag.
            target << XMLStrL('<') << nodeName;

            // Output any attributes on this element
            DOMNamedNodeMap* attributes = toWrite->getAttributes();
            int attrCount = attributes->getLength();
            for (int i = 0; i < attrCount; i++)
            {
                DOMNode*  attribute = attributes->item(i);

                target  << XMLStrL(' ') << attribute->getNodeName()
                        << XMLStrL(" = \"");
                        //  Note that "<" must be escaped in attribute values.
                        outputContent(target, attribute->getNodeValue());
                        target << XMLStrL('"');
            }

            //
            //  Test for the presence of children, which includes both
            //  text content and nested elements.
            //
            DOMNode* child = toWrite->getFirstChild();
            if (child != 0)
            {
                // There are children. Close start-tag, and output children.
                target << XMLStrL(">");
                while( child != 0)
                {
                    target << child;
                    child = child->getNextSibling();
                }

                // Done with children.  Output the end tag.
                target << XMLStrL("</") << nodeName << XMLStrL(">");
            }
            else
            {
                //
                //  There were no children. Output the short form close of
                //  the element start tag, making it an empty-element tag.
                //
                target << XMLStrL("/>");
            }
            break;
        }

        case DOMNode::ENTITY_REFERENCE_NODE:
        {
            DOMNode* child;
            for (child = toWrite->getFirstChild(); child != 0; child = child->getNextSibling())
                target << child;
            break;
        }

        case DOMNode::CDATA_SECTION_NODE:
        {
            target << XMLStrL("<![CDATA[") << nodeValue << XMLStrL("]]>");
            break;
        }

        case DOMNode::COMMENT_NODE:
        {
            target << XMLStrL("<!--") << nodeValue << XMLStrL("-->");
            break;
        }

        case DOMNode::DOCUMENT_TYPE_NODE:
        {
			DOMDocumentType* doctype = (DOMDocumentType*)toWrite;;

			target << XMLStrL("<!DOCTYPE ") << nodeName ;
			const XMLCh* id = doctype->getPublicId();
			if (id != 0)
				target << XMLStrL(" PUBLIC \"") << id << XMLStrL("\"");
			id = doctype->getSystemId();
			if (id != 0)
				target << XMLStrL(" SYSTEM \"") << id << XMLStrL("\"");
			id = doctype->getInternalSubset();
			if (id !=0)
				target << XMLStrL(" [ ") << id  << XMLStrL("]");
			target  << XMLStrL(">");
            break;
        }
		case DOMNode::ENTITY_NODE:
        {
			DOMEntity* entity = (DOMEntity*)toWrite;;

			target << XMLStrL("<!ENTITY ") << nodeName;
			const XMLCh* id = entity->getPublicId();
			if (id != 0)
				target << XMLStrL("PUBLIC \"") << id << XMLStrL("\"");
			id = entity->getSystemId();
			if (id != 0)
				target << XMLStrL("SYSTEM \"") << id << XMLStrL("\"");
			id = entity->getNotationName();
			if (id != 0)
				target << XMLStrL("NDATA \"") << id << XMLStrL("\"");

            break;
        }
        default:
            target << XMLStrL("<!-- Unrecognized node type -->");
    }
	return target;
}
Ejemplo n.º 5
0
void FDPLoader::loadEntity(DOMNode* pSource)
{
	DOMNamedNodeMap* attrList = pSource->getAttributes();
	std::string alias, category;
	DOMNode* attr = attrList->getNamedItem(XercesString("alias"));
	if(attr)
	{
		char* aliasPtr = XMLString::transcode(attr->getNodeValue());
		alias.assign(aliasPtr);
		XMLString::release(&aliasPtr);
	}

	attr = attrList->getNamedItem(XercesString("category"));
	if(attr)
	{
		char* catPtr = XMLString::transcode(attr->getNodeValue());
		category.assign(catPtr);
		XMLString::release(&catPtr);
	}
		
	DOMNodeIterator* iterator = m_pDoc->createNodeIterator(pSource, 
		DOMNodeFilter::SHOW_ELEMENT | DOMNodeFilter::SHOW_ATTRIBUTE, NULL, true);
	// use the tree walker to print out the text nodes.
	for ( DOMNode* current = iterator->nextNode(); current != 0; current = iterator->nextNode() )
	{
		if(XercesString(current->getNodeName()) == "mesh")
		{
			char *fileTmp, *formatTmp, *pathTmp;
			XEngine::MeshInfo info;
			attrList = current->getAttributes();
			attr = attrList->getNamedItem(XercesString("file"));
			if(attr)
			{
				fileTmp = XMLString::transcode(attr->getNodeValue());
				info.file.assign(fileTmp);
				XMLString::release(&fileTmp);
			}

			attr = attrList->getNamedItem(XercesString("format"));
			if(attr)
			{
				formatTmp = XMLString::transcode(attr->getNodeValue());
				info.format.assign(formatTmp);
				XMLString::release(&formatTmp);
			}

			attr = attrList->getNamedItem(XercesString("path"));
			if(attr)
			{
				pathTmp = XMLString::transcode(attr->getNodeValue());
				info.path.assign(pathTmp);
				XMLString::release(&pathTmp);
			}
			else
				info.path.assign("");
			
			info.keyframe_alias = alias;
			info.keyframe_category = category;

			if(alias == "Rest")
				m_faceEntityMeshInfo.push_back(info);
			// push the Rest state into the morph target dictionary as well
			m_morphTargetsMeshInfos[alias].push_back(info);
		}
		else if(XercesString(current->getNodeName()) == "bind")
		{
			XEngine::MeshInfo info;
			std::string submesh, item;
			attrList = current->getAttributes();
			attr = attrList->getNamedItem(XercesString("submesh"));
			if(attr)
			{
				char* submeshTmp = XMLString::transcode(attr->getNodeValue());
				submesh.assign(submeshTmp);
				XMLString::release(&submeshTmp);
			}
			
			attr = attrList->getNamedItem(XercesString("item"));
			if(attr)
			{
				char* itemTmp = XMLString::transcode(attr->getNodeValue());
				item.assign(itemTmp);
				XMLString::release(&itemTmp);
			}
			if(item == "LeftEye" || item == "RightEye") // eye pivots
			{
				Vector3 eye(0, 0, 0);
				//std::string x, y, z;
				attr = attrList->getNamedItem(XercesString("pivotX"));
				if(attr)
					eye.x = toFloat(attr->getNodeValue());
				attr = attrList->getNamedItem(XercesString("pivotY"));
				if(attr)
					eye.y = toFloat(attr->getNodeValue());
				attr = attrList->getNamedItem(XercesString("pivotZ"));
				if(attr)
					eye.z = toFloat(attr->getNodeValue());
				if(item == "LeftEye")
					m_pFDP->setLeftEyePivot(eye);
				else
					m_pFDP->setRightEyePivot(eye);
			}
			
			m_bindings.insert(std::make_pair(submesh, item));
		}
	}
}
Ejemplo n.º 6
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.º 7
0
/* NOTE: need to keep _type field in consideration as attribute type/entitlement depends on it.*/
EppMarkHolder* EppMarkHolder::fromXML( const DOMNode& root, const char* ns )
{
	/*
	  this->_name = _src._name;
	  this->_org = _src._org;
	  this->_addr = _src._addr;
	  this->_voice = _src._voice;
	  this->_fax = _src._fax;
	  this->_email = _src._email;
	  this->_addParam = _src._addParam;
	  this->_type = _src._type;

	 */
	EppMarkHolder *_ret = new EppMarkHolder(EPPMARK_HOLDER, ns);
	//_ret->setNameSpace(ns);
	int nsLen = strlen(ns);

	if( null == _ret )
		return null;
	DOMNodeList* list  = root.getChildNodes();
	DOMNamedNodeMap* attrs = root.getAttributes();

	for( unsigned int i = 0; i < list->getLength(); i++ )
	{
		DOMNode* node = list->item(i);
		DOMString name = node->getLocalName();
		if( name.isNull() )
		{
			name = node->getNodeName();
		}
		if( name.isNull() )
			continue;
		if( name.substringData(0, nsLen + 1).equals((_ret->getNameSpace() + ":").c_str()) )
		{
			name = name.substringData(nsLen + 1, name.length() - ( nsLen + 1 ));
			if( name.equals("name") )
			{
				_ret->_name = EppUtil::getText(*node);
			}
			else if ( name.equals("org") )
			{
				_ret->_org = EppUtil::getText(*node);
			}
			else if ( name.equals("addr") )
			{
				EppMarkAddress* mAddr = (EppMarkAddress*)EppMarkAddress::fromXML( *node, ns );
				_ret->_addr = *mAddr;
				delete mAddr;
			}
			else if ( name.equals("voice") )
			{
				EppE164 *_v = EppE164::fromXML(*node);
				if( NULL != _v )
				{
					_ret->_voice = *_v;
					delete _v;
				}
			}
			else if ( name.equals("fax") )
			{
				EppE164 *_f = EppE164::fromXML(*node);
				if( NULL != _f )
				{
					_ret->_fax = *_f;
					delete _f;
				}
			}
			else if ( name.equals("email") )
			{
				_ret->_email = EppUtil::getText(*node);
			}
		}
	}

	for( unsigned int i = 0; i < attrs->getLength();i++ )
	{
		DOMNode* attr = attrs->item(i);
		DOMString _v = attr->getNodeValue();
		if( XS(attr->getNodeName()).equals("entitlement") )
		{
			_ret->_type = EPPMARK_HOLDER;
			if( _v.length() > 0 )
			{
				_ret->_addParam = _v;
			}
			break;
		}
		else if ( XS(attr->getNodeName()).equals("type") )
		{
			_ret->_type = EPPMARK_CONTACT;
			if( _v.length() > 0 )
			{
				_ret->_addParam = _v;
			}
			break;
		}
	}
	return _ret;
}
Ejemplo n.º 8
0
void CTibiaItem::refreshItemLists()
{
	if (!criticalSectionInitialized)
	{
		InitializeCriticalSection(&ItemsInitCriticalSection);
		criticalSectionInitialized = true;
	}
	EnterCriticalSection(&ItemsInitCriticalSection);
	if (itemListsFresh)
	{
		LeaveCriticalSection(&ItemsInitCriticalSection);
		return;
	}
	itemListsFresh = 1;
	if (!xmlInitialised)
	{
		XMLPlatformUtils::Initialize();
		xmlInitialised = 1;
	}

	XercesDOMParser *parser = new XercesDOMParser();
	try
	{
		int listNr, itemNr, rootNr;

		//reset all lists
		constCodeList.RemoveAll();
		foodList.RemoveAll();
		lootList.RemoveAll();
		itemList.RemoveAll();
		if (itemTree)
			delete itemTree;

		itemTree = new CTibiaTree(new CTibiaTreeBranchData("Root"));

		char pathBuf[2048];
		sprintf(pathBuf, "%s\\data\\tibiaauto-items.xml", CInstallPath::getInstallPath().c_str());
		parser->parse(pathBuf);
		DOMNode  *doc = parser->getDocument();
		for (rootNr = 0; rootNr < (int)doc->getChildNodes()->getLength(); rootNr++)
		{
			DOMNode *root = doc->getChildNodes()->item(rootNr);

			if (wcscmp(root->getNodeName(), L"item-definitions"))
				continue;
			for (listNr = 0; listNr < (int)root->getChildNodes()->getLength(); listNr++)
			{
				DOMNode *listNode = root->getChildNodes()->item(listNr);

				//ITEMS
				if (!wcscmp(listNode->getNodeName(), L"items"))
					//recursively add to itemTree from XML tree, works with older versions
					parseItemsBranch(listNode, itemTree);

				//FOOD
				if (!wcscmp(listNode->getNodeName(), L"foods"))
				{
					for (itemNr = 0; itemNr < (int)listNode->getChildNodes()->getLength(); itemNr++)
					{
						int attrNr;
						DOMNode *item = listNode->getChildNodes()->item(itemNr);
						if (wcscmp(item->getNodeName(), L"item"))
							continue;

						int objectId     = 0;
						int eatTime      = 0;
						char *objectName = NULL;

						for (attrNr = 0; attrNr < (int)item->getAttributes()->getLength(); attrNr++)
						{
							DOMNode *attrNode = item->getAttributes()->item(attrNr);
							if (!wcscmp(attrNode->getNodeName(), L"name"))
								objectName = CUtil::wc2c(attrNode->getNodeValue());
							if (!wcscmp(attrNode->getNodeName(), L"id"))
							{
								char *idTmp = CUtil::wc2c(attrNode->getNodeValue());
								sscanf(idTmp, "0x%x", &objectId);
								if (objectId == 0)
									sscanf(idTmp, "%d", &objectId);
								free(idTmp);
							}
							if (!wcscmp(attrNode->getNodeName(), L"time"))
							{
								char *idTmp = CUtil::wc2c(attrNode->getNodeValue());
								sscanf(idTmp, "%d", &eatTime);
								free(idTmp);
							}
						}
						if (!objectId || !objectName || !strlen(objectName))
						{
							if (objectName)
								free(objectName);
							continue;
						}

						foodList.Add(objectId, objectName, eatTime);
						if (objectName)
							free(objectName);
						//delete item;//wis
					}
				}

				//CONSTS
				//SECTION IS UNUSED, FOR CURRENT TIBIA see next section for loading from const file
				if (!wcscmp(listNode->getNodeName(), L"consts"))
				{
					for (itemNr = 0; itemNr < (int)listNode->getChildNodes()->getLength(); itemNr++)
					{
						int attrNr;
						DOMNode *item = listNode->getChildNodes()->item(itemNr);
						if (wcscmp(item->getNodeName(), L"const"))
							continue;

						int constValue  = 0;
						char *constCode = NULL;

						for (attrNr = 0; attrNr < (int)item->getAttributes()->getLength(); attrNr++)
						{
							DOMNode *attrNode = item->getAttributes()->item(attrNr);
							if (!wcscmp(attrNode->getNodeName(), L"code"))
								constCode = CUtil::wc2c(attrNode->getNodeValue());
							if (!wcscmp(attrNode->getNodeName(), L"value"))
							{
								char *idTmp = CUtil::wc2c(attrNode->getNodeValue());
								sscanf(idTmp, "0x%x", &constValue);
								if (constValue == 0)
									sscanf(idTmp, "%d", &constValue);
								free(idTmp);
							}
						}
						if (!constCode || !strlen(constCode))
						{
							if (constCode)
								free(constCode);
							continue;
						}

						int i, len;
						len = strlen(constCode);
						for (i = 0; i < len; i++)
							constCode[i] = tolower(constCode[i]);

						constCodeList.Add(constValue, constCode, 0);
						if (constCode)
							free(constCode);
						//delete item;//wis
					}
				}

				//LOOT
				//SECTION IS UNUSED, FOR CURRENT TIBIA
				if (!wcscmp(listNode->getNodeName(), L"looted"))
				{
					for (itemNr = 0; itemNr < (int)listNode->getChildNodes()->getLength(); itemNr++)
					{
						int attrNr;
						DOMNode *item = listNode->getChildNodes()->item(itemNr);
						if (wcscmp(item->getNodeName(), L"item"))
							continue;

						int objectId     = 0;
						char *objectName = NULL;

						for (attrNr = 0; attrNr < (int)item->getAttributes()->getLength(); attrNr++)
						{
							DOMNode *attrNode = item->getAttributes()->item(attrNr);
							if (!wcscmp(attrNode->getNodeName(), L"name"))
								objectName = CUtil::wc2c(attrNode->getNodeValue());
							if (!wcscmp(attrNode->getNodeName(), L"id"))
							{
								char *idTmp = CUtil::wc2c(attrNode->getNodeValue());
								sscanf(idTmp, "0x%x", &objectId);
								free(idTmp);
							}
						}
						if (!objectId || !objectName || !strlen(objectName))
						{
							if (objectName)
								free(objectName);
							continue;
						}
						lootList.Add(objectId, objectName, 0);
						if (objectName)
							free(objectName);
					}
				}
			}
		}

		//Create data lists from tree structure loaded by XML
		traverseTreeForItemList(itemTree, &itemList);
		if (lootList.GetCount() == 0)
			traverseTreeForLootList(itemTree, &lootList);                      // get loot from tree if not loaded from file

		sprintf(pathBuf, "%s\\data\\tibiaauto-consts.xml", CInstallPath::getInstallPath().c_str());
		OFSTRUCT lpOpen;
		if (OpenFile(pathBuf, &lpOpen, OF_EXIST) != HFILE_ERROR)
		{
			constCodeList.RemoveAll();

			delete parser;
			parser = new XercesDOMParser();
			parser->parse(pathBuf);
			doc = parser->getDocument();
			for (rootNr = 0; rootNr < (int)doc->getChildNodes()->getLength(); rootNr++)
			{
				DOMNode *root = doc->getChildNodes()->item(rootNr);

				if (wcscmp(root->getNodeName(), L"const-definitions"))
					continue;
				for (listNr = 0; listNr < (int)root->getChildNodes()->getLength(); listNr++)
				{
					DOMNode *listNode = root->getChildNodes()->item(listNr);


					//CONSTS
					if (!wcscmp(listNode->getNodeName(), L"consts"))
					{
						for (itemNr = 0; itemNr < (int)listNode->getChildNodes()->getLength(); itemNr++)
						{
							int attrNr;
							DOMNode *item = listNode->getChildNodes()->item(itemNr);
							if (wcscmp(item->getNodeName(), L"const"))
								continue;

							int constValue  = 0;
							char *constCode = NULL;

							for (attrNr = 0; attrNr < (int)item->getAttributes()->getLength(); attrNr++)
							{
								DOMNode *attrNode = item->getAttributes()->item(attrNr);
								if (!wcscmp(attrNode->getNodeName(), L"code"))
									constCode = CUtil::wc2c(attrNode->getNodeValue());
								if (!wcscmp(attrNode->getNodeName(), L"value"))
								{
									char *idTmp = CUtil::wc2c(attrNode->getNodeValue());
									sscanf(idTmp, "0x%x", &constValue);
									if (constValue == 0)
										sscanf(idTmp, "%d", &constValue);
									free(idTmp);
								}
							}
							if (!constCode || !strlen(constCode))
							{
								if (constCode)
									free(constCode);
								continue;
							}

							int i, len;
							len = strlen(constCode);
							for (i = 0; i < len; i++)
								constCode[i] = tolower(constCode[i]);

							constCodeList.Add(constValue, constCode, 0);
							if (constCode)
								free(constCode);
						}
					}
				}
			}
		}//if file tibiaauto-consts.xml exists
	}
	catch (...)
	{
		AfxMessageBox("Unable to load const/item definitions!");
		/*
		   AfxMessageBox("Debug Item Tree");
		   char buf[11111];
		   itemTree->toString(buf);
		   AfxMessageBox(buf);
		   AfxMessageBox("Debug Food");
		   foodList.toString(buf);
		   AfxMessageBox(buf);
		   AfxMessageBox("Debug Consts");
		   constCodeList.toString(buf);
		   AfxMessageBox(buf);
		 */
	}

	delete parser;
	LeaveCriticalSection(&ItemsInitCriticalSection);
}
bool
XMLParserThread::xmlParseSMSFormatRequest( DOMNode* cur, 
                                           DOMNode* out,
                                           DOMDocument* reply,
                                           bool indent )
try {
   bool ok = true;
   int indentLevel = 1;

   MC2String indentStr( indentLevel*3, ' ' );
   indentStr.insert( 0, "\n" );
   XStr XindentStr( indentStr.c_str() );

   bool smsMessage = false;
   bool routeMessage = false;
   bool wayfinderRouteSMS = false;
   bool wayfinderDestinationSMS = false;
   bool wayfinderFavouriteSMS = false;
   char* smsMessageText = NULL;
   char* phoneModelName = NULL;
   char* phoneManufacturerName = NULL;
   uint32 routeID = 0;
   uint32 routeCreateTime = 0;
   StringTable::languageCode language = StringTable::ENGLISH;
   char* signature = NULL;
   char* originString = NULL;
   char* originLocationString = NULL;
   char* destinationString = NULL;
   char* destinationLocationString = NULL;
   CellularPhoneModel* model = NULL; // For routeMessage
   bool wapLink = false; // For routeMessage
   int32 wayfinderSMSVersion = MAX_INT32;
   int32 wayfinderOriginLat = MAX_INT32;
   int32 wayfinderOriginLon = MAX_INT32;
   int32 wayfinderDestinationLat = MAX_INT32;
   int32 wayfinderDestinationLon = MAX_INT32;
   MC2String wayfinderOriginDescription;
   MC2String wayfinderDestinationDescription;
   MC2String errorCode = "-1";
   MC2String errorMessage = "Failed to handle request.";
   int32 wayfinderFavouriteLat;
   int32 wayfinderFavouriteLon;
   MC2String wayfinderFavouriteName;
   MC2String wayfinderFavouriteShortName;
   MC2String wayfinderFavouriteDescription;
   MC2String wayfinderFavouriteCategory;
   MC2String wayfinderFavouriteMapIconName;
   // Create sms_format_reply element
   DOMElement* sms_format_reply = 
      reply->createElement( X( "sms_format_reply" ) );
   // Transaction ID
   sms_format_reply->setAttribute( 
      X( "transaction_id" ), cur->getAttributes()->getNamedItem( 
         X( "transaction_id" ) )->getNodeValue() );
   out->appendChild( sms_format_reply );
   if ( indent ) {
      // Newline
      out->insertBefore( reply->createTextNode( XindentStr.XMLStr() ), 
                         sms_format_reply );
   }
   
   // Look for Wayfinder sms version
   DOMNamedNodeMap* attributes = cur->getAttributes();
   DOMNode* attribute;
   for ( uint32 i = 0 ; i < attributes->getLength() ; i++ ) {
      attribute = attributes->item( i );
      if ( XMLString::equals( attribute->getNodeName(),
                              "wayfinder_sms_version" ) ) {
         MC2String tmpStr = 
            XMLUtility::transcodefrom( attribute->getNodeValue() );
         wayfinderSMSVersion = atoi( tmpStr.c_str() );
      }
   }

   XMLSMSCommon::InviteData inviteData; // for invite_sms

   XMLSMSCommon::PlaceSMSData placeData; // for place_sms

   for ( DOMNode* child = cur->getFirstChild();
         child != NULL && ok; 
         child = child->getNextSibling() ) {
      if ( child->getNodeType() != DOMNode::ELEMENT_NODE ) {
         continue;
      }
      // See if the element is a known type
      if ( XMLString::equals( child->getNodeName(), "smsmessage" ) ) {
         smsMessageText = XMLUtility::getChildTextValue( child );
         smsMessage = true;
      } else if ( XMLString::equals( child->getNodeName(),
                                     "phone_manufacturer" ) ) {
         phoneManufacturerName = 
            XMLUtility::getChildTextValue( child );
      } else if ( XMLString::equals( child->getNodeName(),
                                     "phone_model" ) ) {
         phoneModelName = XMLUtility::getChildTextValue( child );
      } else if ( XMLString::equals( child->getNodeName(),
                                     "route_sms_message" ) ) {
         routeMessage = 
            xmlParseSendSMSRequestRouteSMSMessage( child, model, wapLink );
      } else if ( XMLString::equals( child->getNodeName(),
                                     "route_message_data" ) ) {
         routeMessage = 
            XMLSMSCommon::
            xmlParseSendSMSRequestRouteMessageData( child, 
                                                    routeID,
                                                    routeCreateTime,
                                                    language,
                                                    signature,
                                                    originString,
                                                    originLocationString,
                                                    destinationString,
                                                    destinationLocationString );

      } else if( XMLString::equals( child->getNodeName(),
                                    "wayfinder_route_sms" ) ) {
         wayfinderRouteSMS = 
            XMLSMSCommon::
            xmlParseWayfinderSMS( child, signature,
                                  wayfinderOriginLat,
                                  wayfinderOriginLon,
                                  wayfinderOriginDescription,
                                  wayfinderDestinationLat,
                                  wayfinderDestinationLon,
                                  wayfinderDestinationDescription,
                                  errorCode, errorMessage );
         if ( ! wayfinderRouteSMS ) {
            ok = false;
            // errorCode and errorMessage is set by 
            // xmlParseWayfinderSMS
            mc2log << warn << "XMLParserThread::"
                   << "xmlParseSendSMSRequest failed to parse "
                   << "wayfinder_route_sms." << endl;
         }              
      } else if ( XMLString::equals( child->getNodeName(),
                                     "wayfinder_destination_sms" ) ) {
         wayfinderDestinationSMS = 
            XMLSMSCommon::
            xmlParseWayfinderSMS( child, signature,
                                  wayfinderOriginLat, wayfinderOriginLon,
                                  wayfinderOriginDescription,
                                  wayfinderDestinationLat, 
                                  wayfinderDestinationLon,
                                  wayfinderDestinationDescription, 
                                  errorCode, errorMessage );
         if ( ! wayfinderDestinationSMS ) {
            ok = false;
            // errorCode and errorMessage is set by 
            // xmlParseWayfinderSMS
            mc2log << warn << "XMLParserThread::"
                   << "xmlParseSendSMSRequest failed to parse "
                   << "wayfinder_destination_sms." << endl;
         } 
      } else if( XMLString::equals( child->getNodeName(),
                                    "wayfinder_favourite_sms" ) ) {
         wayfinderFavouriteSMS = 
            XMLSMSCommon::
            xmlParseWayfinderFavouriteSMS( child, signature,
                                           wayfinderFavouriteLat,
                                           wayfinderFavouriteLon,
                                           wayfinderFavouriteName,
                                           wayfinderFavouriteShortName,
                                           wayfinderFavouriteDescription,
                                           wayfinderFavouriteCategory,
                                           wayfinderFavouriteMapIconName,
                                           errorCode, errorMessage );
         if( ! wayfinderFavouriteSMS ) {
            // errorCode and errorMessage is set by 
            // xmlParseWayfinderFavouriteSMS
            mc2log << warn << "XMLParserThread::"
                   << "xmlParseSMSFormatRequest failed to parse "
                   << "wayfinder_favourite_sms." << endl;
         }
      } else if ( XMLString::equals( child->getNodeName(),
                                     "invite_sms" ) ) {
         XMLTool::getAttribValue( inviteData.m_type, "type", child );
         XMLTool::getNodeValue( inviteData.m_name, "name", child );
      } else if ( XMLString::equals( child->getNodeName(),
                                     "place_sms" ) ) {
         ok = parsePlaceSMS( placeData, child, errorCode, errorMessage );
      } else {
         mc2log << warn << "XMLParserThread::"
            "xmlParseSMSFormatRequest "
            "odd Element in sms_format_request element: "
                << child->getNodeName() << endl;
      }
   }

   
   // Handle request
   if ( ok ) {
      // The smses
      StringVector* smsVector = new StringVector();

      if ( smsMessage ) {
         // ExpandStringItemVector?
         ok = false;
         errorMessage = "Formating of smsmessage is not yet supported.";
      } else if ( routeMessage ) {
         if ( !wapLink ) {
            ok = handleRouteMessage( this, 
                                     routeID, routeCreateTime, 
                                     language,
                                     smsVector, model, signature, 
                                     errorMessage );
         } else {
            ok = handleWAPLinkSMS( this,
                                   routeID, routeCreateTime,
                                   language, smsVector,
                                   model, signature,
                                   errorMessage );
         }
         
         if ( ok ) {
            mc2log << info << "XMLParserThread::xmlParseSMSFormatRequest ";
            if ( !wapLink ) {
               mc2log << "routeID " << routeID << " routeCreateTime "
                      << routeCreateTime;
            } else {
               mc2log << "wapLink true";
            }
            mc2log << " signature " << signature << " model " 
                   << model->getName() 
                   << " nbrSMSes " << smsVector->getSize() << endl;

            // Add smses
            XMLSMSCommon::appendSMSList( sms_format_reply, reply, smsVector,
                                         indentLevel + 1, indent );
         } // Not ok handled below

      } else if ( wayfinderDestinationSMS || wayfinderRouteSMS ) {
         // Make sms data
         WayfinderSMSRequest* wayReq = new WayfinderSMSRequest( 
            getNextRequestID() );
         MC2Coordinate origin( wayfinderOriginLat, wayfinderOriginLon );
         MC2Coordinate dest( wayfinderDestinationLat,
                             wayfinderDestinationLon );
         wayReq->addMessage( 
            "DUMMY", "NO_WAY",
            origin,
            wayfinderOriginDescription.c_str(),
            dest,
            wayfinderDestinationDescription.c_str(),
            signature, wayfinderSMSVersion );
         smsVector->addLast( StringUtility::newStrDup( const_cast<char*>( 
            wayReq->getLastDestinationMessage() ) ) );
         // Add sms
         XMLSMSCommon::appendSMSList( sms_format_reply, reply, smsVector,
                                      indentLevel + 1, indent );

         delete wayReq;
      } else if( wayfinderFavouriteSMS ) {
         // Make sms data
         WayfinderSMSRequest* wayReq = new WayfinderSMSRequest(
            getNextRequestID() );
         
         MC2Coordinate coord( wayfinderFavouriteLat, wayfinderFavouriteLon );

         wayReq->addFavouriteMessage( "DUMMY", "NO_WAY",
                                      coord,
                                      wayfinderFavouriteName,
                                      wayfinderFavouriteShortName,
                                      wayfinderFavouriteDescription,
                                      wayfinderFavouriteCategory,
                                      wayfinderFavouriteMapIconName,
                                      signature,
                                      wayfinderSMSVersion );
         smsVector->addLast( StringUtility::newStrDup( const_cast<char*>( 
            wayReq->getLastDestinationMessage() ) ) );
         // Add sms
         XMLSMSCommon::appendSMSList( sms_format_reply, reply, smsVector,
                                      indentLevel + 1, indent );
         delete wayReq;
      } else if ( !inviteData.m_type.empty() ) { 
         XMLSMSCommon::
            composeInviteSMS( sms_format_reply, reply, indentLevel + 1, indent,
                              getCurrentUser(), inviteData );
      } else if ( ! placeData.m_type.empty() ) {
         XMLSMSCommon::
            composePlaceSMS( *this,
                             sms_format_reply, reply, indentLevel + 1, indent,
                             getCurrentUser(), placeData );
      } else {
         // Couldn't get all needed indata
         ok = false;
         errorMessage = "Couldn't get all needed indata.";
      }

      if ( ok ) {
         mc2log << info << "SMSFormat: OK " << smsVector->getSize()
                << " SMSes ";
         if ( smsVector->getSize() > 0 ) {
            mc2log << "Last " << smsVector->getElementAt( 0 );
         }
         mc2log << endl;
      } // Error printed below

      smsVector->deleteAllObjs();
      delete smsVector;

   } // Not ok handled below

   if ( ! ok ) {
      mc2log << info << "SMSFormat: Error " << errorCode << ","
             << errorMessage << endl;
      // Error 
      XMLServerUtility::
         appendStatusNodes( sms_format_reply, reply, indentLevel + 1, indent,
                            errorCode.c_str(), errorMessage.c_str() );
      // Error handled
      ok = true;
   }

   if ( indent ) {
      // Newline and indent before end sms_format_reply tag   
      sms_format_reply->appendChild( 
         reply->createTextNode( XindentStr.XMLStr() ) );
   }
 
   delete [] smsMessageText;
   delete [] phoneModelName;
   delete [] phoneManufacturerName;
   delete [] signature;
   delete [] originString;
   delete [] originLocationString;
   delete [] destinationString;
   delete [] destinationLocationString;
   delete model;

   return ok;
} catch ( const XMLTool::Exception& e ) {
   
   return false;
}
Ejemplo n.º 10
0
void
DomUtilsInternal::Dom2XMLString( 
            const DOMNode* toWrite, 
            XMLFormatter& fmt )
{
    int i;
    DOMNode child;
    int attrCount;
    DOMString id;
    DOMNamedNodeMap attributes;
    DOMDocumentType doctype;


    // Get the name and value out for convenience
    DOMString   nodeName = toWrite.getNodeName();
    DOMString   nodeValue = toWrite.getNodeValue();
    unsigned long lent = nodeValue.length();

    switch (toWrite.getNodeType())
    {
        case DOMNode::ELEMENT_NODE:
            // The name has to be representable without any escapes
            fmt  << XMLFormatter::NoEscapes << chOpenAngle << nodeName;

            // Output the element start tag.

            // Output any attributes on this element
            attributes = ((DOMElement&)toWrite).getAttributes();
            attrCount = attributes.getLength();
            for (i = 0; i < attrCount; i++)
            {
                DOMNode  attribute = attributes.item(i);

                //
                //  Again the name has to be completely representable. But the
                //  attribute can have refs and requires the attribute style
                //  escaping.
                //
                fmt  << XMLFormatter::NoEscapes
                             << chSpace << attribute.getNodeName() 
                             << chEqual << chDoubleQuote
                             << XMLFormatter::AttrEscapes
                             << attribute.getNodeValue() 
                             << XMLFormatter::NoEscapes
                             << chDoubleQuote;
            }

            //
            //  Test for the presence of children, which includes both
            //  text content and nested elements.
            //
            child = toWrite.getFirstChild();
            if ( !child.isNull() )
            {
                // There are children. Close start-tag, and output children.
                // No escapes are legal here
                fmt << XMLFormatter::NoEscapes << chCloseAngle;

                while( !child.isNull() )
                {
                    DomUtilsInternal::Dom2XMLString( child, fmt );
                    child = child.getNextSibling();
                }

                //
                // Done with children.  Output the end tag.
                //
                fmt << XMLFormatter::NoEscapes << gEndElement
                            << nodeName << chCloseAngle;
            }
            else
            {
                //
                //  There were no children. Output the short form close of
                //  the element start tag, making it an empty-element tag.
                //
                fmt << XMLFormatter::NoEscapes << chForwardSlash << chCloseAngle;
            }
            break;

        case DOMNode::TEXT_NODE:
            fmt.formatBuf( nodeValue.rawBuffer(),  lent, XMLFormatter::CharEscapes );
            break;


        case DOMNode::CDATA_SECTION_NODE :
            fmt << XMLFormatter::NoEscapes << gStartCDATA
                        << nodeValue << gEndCDATA;
            break;

        case DOMNode::ENTITY_REFERENCE_NODE:
            fmt << XMLFormatter::NoEscapes << chAmpersand
                << nodeName << chSemiColon;
            break;

        case DOMNode::PROCESSING_INSTRUCTION_NODE :
            fmt << XMLFormatter::NoEscapes << gStartPI << nodeName;
            if (lent > 0)
            {
                fmt << chSpace << nodeValue;
            }
            fmt << XMLFormatter::NoEscapes << gEndPI;
            break;

        case DOMNode::COMMENT_NODE :
            fmt << XMLFormatter::NoEscapes << gStartComment
                        << nodeValue << gEndComment;
            break;

        case DOMNode::DOCUMENT_NODE :
            child = toWrite.getFirstChild();
            while( !child.isNull() )
            {
                DomUtilsInternal::Dom2XMLString( child, fmt );
                child = child.getNextSibling();
                if ( !child.isNull() )
                {
                    fmt << chCR;
                }
            }
            break;

        case DOMNode::DOCUMENT_TYPE_NODE :
            doctype = (DOMDocumentType &)toWrite;

            fmt << XMLFormatter::NoEscapes  << gStartDoctype
                        << nodeName;

            id = doctype.getPublicId();
            if (id != 0)
            {
                fmt << XMLFormatter::NoEscapes << chSpace << gPublic
                    << id << chDoubleQuote;
                id = doctype.getSystemId();
                if (id != 0)
                {
                    fmt << XMLFormatter::NoEscapes << chSpace 
                       << chDoubleQuote << id << chDoubleQuote;
                }
            }
            else
            {
                id = doctype.getSystemId();
                if (id != 0)
                {
                    fmt << XMLFormatter::NoEscapes << chSpace << gSystem
                        << id << chDoubleQuote;
                }
            }

            id = doctype.getInternalSubset(); 
            if (id !=0)
                fmt << XMLFormatter::NoEscapes << chOpenSquare
                            << id << chCloseSquare;

            fmt << XMLFormatter::NoEscapes << chCloseAngle;
            break;


        case DOMNode::ENTITY_NODE:
            fmt << XMLFormatter::NoEscapes << gStartEntity
                        << nodeName;

            id = ((DOMEntity &)toWrite).getPublicId();
            if (id != 0)
                fmt << XMLFormatter::NoEscapes << gPublic
                            << id << chDoubleQuote;

            id = ((DOMEntity &)toWrite).getSystemId();
            if (id != 0)
                fmt << XMLFormatter::NoEscapes << gSystem
                            << id << chDoubleQuote;

            id = ((DOMEntity &)toWrite).getNotationName();
            if (id != 0)
                fmt << XMLFormatter::NoEscapes << gNotation
                            << id << chDoubleQuote;

            fmt << XMLFormatter::NoEscapes << chCloseAngle << chCR << chLF;
            break;

        case DOMNode::XML_DECL_NODE:
            fmt << gXMLDecl1 << ((DOMXMLDecl &)toWrite).getVersion();

            fmt << gXMLDecl2 << fmt.getEncodingName();
            
            id = ((DOMXMLDecl &)toWrite).getStandalone();
            if ( id!= 0 )
                fmt << gXMLDecl3 << id;
            
            fmt << gXMLDecl4;
            break;
    }
}
Ejemplo n.º 11
0
void GeomAttributesBuilder::getParameters()
{
	// First set default parameters.
	// The parameters are dependent on the type of geom
	//	box:			length, width, height (all doubles)
	//	ccylinder:	radius, length (all doubles)
	//	sphere:		radius (all doubles)
	//	plane:		normal_x, normal_y, normal_z, d (all doubles)
	//	mesh:		filname (std::string)	
	std::string type = attrib_->getValAsStr("type");
	
	if (!type.compare("box")) {
		attrib_->add("length", "1");
		attrib_->add("width", "1");
		attrib_->add("height", "1");
	} else if (!type.compare("ccylinder")) {
		attrib_->add("radius", "1");
		attrib_->add("length", "3");
	} else if (!type.compare("cylinder")) {
		attrib_->add("radius", "1");
		attrib_->add("length", "3");
	} else if (!type.compare("sphere")) {
		attrib_->add("radius", "1");
	} else if (!type.compare("plane")) {
		attrib_->add("normal_x", "0");
		attrib_->add("normal_y", "0");
		attrib_->add("normal_z", "1");
		attrib_->add("d", "0");
	} else if (!type.compare("mesh")) {
		attrib_->add("filename", "_NODATA_");
	} else {
		return;
	}
	
	DOMNodeList* allChildNodes = node_->getChildNodes();

	// Loop over all of the parameters
	for (unsigned int c = 0; c < allChildNodes->getLength(); ++c) {
		DOMNode* thisChildItem = allChildNodes->item(c);
			    			
		if (thisChildItem->getNodeType() == DOMNode::ELEMENT_NODE) {
		
			char* pChildTagName = XMLString::transcode(thisChildItem->getNodeName());
			
			if ( strcmp(pChildTagName, "parameter") == 0 ) {
     			
				if ( thisChildItem->hasAttributes() ) 
				{
					DOMNamedNodeMap* theAttributes = thisChildItem->getAttributes();
					int numAttributes = theAttributes->getLength();
			
					if (numAttributes == 2) { // Parameters can only 1 Name/Value pair
						DOMNode* nodeName = theAttributes->item(0);
						DOMNode* nodeValue = theAttributes->item(1);

						const XMLCh* xmlch_Name = nodeName->getNodeValue();
						char* attrName = XMLString::transcode(xmlch_Name);

						const XMLCh* xmlch_Value = nodeValue->getNodeValue();
						char* attrValue = XMLString::transcode(xmlch_Value);
						
						try {
							attrib_->update(attrName, attrValue);
						} catch (std::runtime_error &ex) {
							std::cerr << ex.what() << std::endl
									<< builderType_ << "::getParameters() - "
									<< "In geom \"" << attrib_->getValAsStr("name")
									<< "\", parameter \"" << attrName << "=" << attrValue
									<< "\" is illegal for this geom type ("
									<< attrib_->getValAsStr("type")
									<< "). Ignoring it." << std::endl;
						};
						
						XMLString::release( &attrName );
						XMLString::release( &attrValue );		
					}
				}
			}
			
			delete [] pChildTagName;
		}
	}
}
Ejemplo n.º 12
0
void SpaceAttributesBuilder::getParameters()
{
	// First set default parameters.
	// The parameters are dependent on the type of space
	//	simple:	No parameters
	//	hash:	center,	dVector3
	//			extents,	dVector3
	//			depth,	int
	//	quatree:	minlevel,	int
	//			maxlevel,	int
	std::string type = attrib_->getValAsStr("type");
	
	if (!type.compare("simple")) return; // No parameters for simple space
	else if (!type.compare("hash")) {
		attrib_->add("center", "0 0 0");
		attrib_->add("extents", "0 0 0");
		attrib_->add("depth", "4");
	} else if (!type.compare("quadtree")) {
		attrib_->add("minlevel", "-1");
		attrib_->add("maxlevel", "8");
	} else {
		return;
	}
	
	DOMNodeList* allChildNodes = node_->getChildNodes();

	// Loop over all of the spaces
	for (unsigned int c = 0; c < allChildNodes->getLength(); ++c) {
		DOMNode* thisChildItem = allChildNodes->item(c);
			    			
		if (thisChildItem->getNodeType() == DOMNode::ELEMENT_NODE) {
		
			char* pChildTagName = XMLString::transcode(thisChildItem->getNodeName());
			
			if ( strcmp(pChildTagName, "parameter") == 0 ) {
     			
				if ( thisChildItem->hasAttributes() ) {
					DOMNamedNodeMap* theAttributes = thisChildItem->getAttributes();
					int numAttributes = theAttributes->getLength();
			
					if (numAttributes == 2) {
						DOMNode* nodeName = theAttributes->item(0);
						DOMNode* nodeValue = theAttributes->item(1);

						const XMLCh* xmlch_Name = nodeName->getNodeValue();
						char* attrName = XMLString::transcode(xmlch_Name);

						const XMLCh* xmlch_Value = nodeValue->getNodeValue();
						char* attrValue = XMLString::transcode(xmlch_Value);

						
						try {
							attrib_->update(attrName, attrValue);
						} catch (std::runtime_error &ex) {
							std::cerr << ex.what() << std::endl
									<< builderType_ << "::getParameters() - "
									<< "In space \"" << attrib_->getValAsStr("name")
									<< "\", parameter \"" << attrName << "=" << attrValue
									<< "\" is illegal for this space type ("
									<< attrib_->getValAsStr("type")
									<< "). Ignoring it." << std::endl;
						}

						XMLString::release( &attrName );
						XMLString::release( &attrValue );
					}
				}
			}
			
			delete [] pChildTagName;
		}
	}
}
Ejemplo n.º 13
0
void FDPLoader::loadFDPItem(DOMNode* pFDPItem)
{
	DOMNamedNodeMap* attrList = pFDPItem->getAttributes();
	FDPItem* pItem = 0;
	// get the name (id)
	DOMNode* attr = attrList->getNamedItem(XercesString("name"));
	if(attr)
	{
		char* name = XMLString::transcode(attr->getNodeValue());
		// create a new item (will be deleted in dtor of FDP class)
		pItem = new FDPItem(name);
		XMLString::release(&name);
	}
	else
		return;
	
	// get the control vertex index
	attr = attrList->getNamedItem(XercesString("index"));
	if(attr)
	{
		char* index = XMLString::transcode(attr->getNodeValue());
		pItem->setControlPoint((unsigned short)atoi(index));
		XMLString::release(&index);
	}

	// get the affecting mesh name
	attr = attrList->getNamedItem(XercesString("affects"));
	if(attr)
	{
		char* affects = XMLString::transcode(attr->getNodeValue());
		pItem->setAffects(affects);
		XMLString::release(&affects);
	}
	
	DOMNodeIterator* iterator = m_pDoc->createNodeIterator(pFDPItem,
		DOMNodeFilter::SHOW_ELEMENT | DOMNodeFilter::SHOW_ATTRIBUTE, NULL, true);
	// use the tree walker to print out the text nodes.
	for ( DOMNode* current = iterator->nextNode(); current != 0; current = iterator->nextNode() )
	{
		if(XercesString(current->getNodeName()) == "indices")
		{
			DOMNodeList* children = current->getChildNodes(); 
			// we should have only one child, text node, just a safety net here
			if ( (children->getLength() == 1) && (children->item(0)->getNodeType() == DOMNode::TEXT_NODE) )//(XercesString(children->item(0)->getNodeName()) == "#text") )
			{
				char* pStr = XMLString::transcode(children->item(0)->getNodeValue());
				std::string str(pStr);
				processIndices(str, pItem);
				XMLString::release(&pStr);
			}
		}
		else if (XercesString(current->getNodeName()) == "influence")	// can have multiple of those
		{
			// sample: <influence weight="0.25" fap="3" type="RaisedCosInfluenceWaveY" />
			DOMNamedNodeMap* influenceAttr = current->getAttributes();
			// get the weight
			float w = toFloat(influenceAttr->getNamedItem(XercesString("weight"))->getNodeValue());
			unsigned short fap = (unsigned short)toFloat(influenceAttr->getNamedItem(XercesString("fap"))->getNodeValue());
			char* typeTmp = XMLString::transcode(influenceAttr->getNamedItem(XercesString("type"))->getNodeValue());
			std::string type;
			type.assign(typeTmp);
			XMLString::release(&typeTmp);
			
			IInfluenceCalculator* pInfluence = InfluenceCalculatorMaker::newInfluenceCalculator(type, w, fap);
			if(pInfluence)
				pItem->addInfluenceCalculator(pInfluence);
		}
	}

	m_pFDP->insertItem(pItem);
}
Ejemplo n.º 14
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;

}
bool CConfigParser::ParseActions(DOMNodeList* actionNodeList, ADeviceListener& configClass)
{
	USES_CONVERSION;
	// Parse all the actions	
	if(actionNodeList != NULL && actionNodeList->getLength() > 0)
	{
		DOMNodeList* actionNodes = actionNodeList->item(0)->getChildNodes();
		for(unsigned long i = 0; i < actionNodes->getLength(); i++)
		{
			DOMNode* actionNode = actionNodes->item(i);
			wstring actionType = actionNode->getNodeName();
			if(actionType.compare(L"#text") == 0)
				continue;
			XMLCh* xmlChNameTxt = L"name";
			wstring actionName;
			if(actionNode->hasAttributes())
			{
				DOMNode* nameAttribute = actionNode->getAttributes()->getNamedItem(xmlChNameTxt);
				actionName = nameAttribute->getNodeValue();
			}			
			if(actionType.compare(L"sendCopyDataWindowMessage") == 0 || actionType.compare(L"sendCommandWindowMessage") == 0)
			{
				wstring message = actionNode->getAttributes()->getNamedItem(L"message")->getNodeValue();
				bool findByClass = FALSE;
				wstring windowAttributeName = L"window";
				if(actionNode->getAttributes()->getNamedItem(L"window") == NULL)
				{
					findByClass = TRUE;
					windowAttributeName = L"windowClass";
				}
				wstring window = actionNode->getAttributes()->getNamedItem(windowAttributeName.c_str())->getNodeValue();

				CSendWindowMessageAction* messageActionToAdd = NULL;
				if(actionType.compare(L"sendCommandWindowMessage") == 0)
				{
					messageActionToAdd = new CSendWindowMessageAction(_wtol(message.c_str()), OLE2T(window.c_str()), findByClass);
				}
				if(actionType.compare(L"sendCopyDataWindowMessage") == 0)
				{
					messageActionToAdd = new CSendWindowMessageAction(OLE2T(message.c_str()), OLE2T(window.c_str()), findByClass);
				}

				if(messageActionToAdd != NULL)
					configClass.AddAction(actionName, messageActionToAdd);
			}
			if(actionType.compare(L"execute") == 0)
			{
				char* executable = XMLString::transcode(
					actionNode->getAttributes()->getNamedItem(L"executable")->getNodeValue());
				char* commandline = XMLString::transcode(
					actionNode->getAttributes()->getNamedItem(L"commandline")->getNodeValue());
				configClass.AddAction(actionName, new CExecuteAction(executable, commandline));
				XMLString::release(&executable);
				XMLString::release(&commandline);
			}
			if(actionType.compare(L"keyPress") == 0)
			{
				TKeyList keys;

				DOMNodeList* keyNodes = actionNode->getChildNodes();
				unsigned long count = keyNodes->getLength();
				for(unsigned long keyIdx=0; keyIdx < keyNodes->getLength(); keyIdx++)
				{
					DOMNode* keyNode = keyNodes->item(keyIdx);
					if(wcscmp(keyNode->getNodeName(), L"#text") == 0)
						continue;
					
					const XMLCh* keyValue = keyNode->getFirstChild()->getNodeValue();
					if(keyValue == NULL)
						continue;

					int test = VK_CONTROL;
					keys.push_back(_wtoi(keyValue));					
				}
				configClass.AddAction(actionName, new CKeyboardAction(keys));
			}
			if(actionType.compare(L"winampPlayPause") == 0)
			{
				configClass.AddAction(actionName, new CWinampPlayPause());
			}
			if(actionType.compare(L"winampMute") == 0)
			{
				configClass.AddAction(actionName, new CWinampMute());
			}
			// We make the assumption that the macros were put at the end of the
			// config file, otherwise the actions they execute may not exist!
			if(actionType.compare(L"macro") == 0)
			{
				wstring type = actionNode->getAttributes()->getNamedItem(L"type")->getNodeValue();
				CMacroAction* actionToAdd = new CMacroAction(type.compare(L"all") == 0 ? true : false);
				DOMNodeList* macroActions = actionNode->getChildNodes();
				unsigned long count = macroActions->getLength();
				for(unsigned long actionIdx=0; actionIdx < count; actionIdx++)
				{
					DOMNode* macroActionNode = macroActions->item(actionIdx);
					if(wcscmp(macroActionNode->getNodeName(), L"#text") == 0)
						continue;

					wstring macroActionName = macroActionNode->getAttributes()->getNamedItem(L"name")->getNodeValue();
					actionToAdd->AddAction(configClass.GetActions()[macroActionName]);
				}
				configClass.AddAction(actionName, actionToAdd);
			}
		}
	}
	return true;
}
Ejemplo n.º 16
0
void parseItemsBranch(DOMNode* listNode, CTibiaTree* parent)
{
	for (int itemNr = 0; itemNr < (int)listNode->getChildNodes()->getLength(); itemNr++)
	{
		int attrNr;
		DOMNode *item = listNode->getChildNodes()->item(itemNr);

		if (item->getNodeType() != 1)
			continue;
		if (!wcscmp(item->getNodeName(), L"item"))
		{
			int objectId     = 0;
			int objectLoot   = 0;
			int type         = 0;
			char *objectName = NULL;

			for (attrNr = 0; attrNr < (int)item->getAttributes()->getLength(); attrNr++)
			{
				DOMNode *attrNode = item->getAttributes()->item(attrNr);

				if (!wcscmp(attrNode->getNodeName(), L"name"))
					objectName = CUtil::wc2c(attrNode->getNodeValue());
				if (!wcscmp(attrNode->getNodeName(), L"id"))
				{
					char *idTmp = CUtil::wc2c(attrNode->getNodeValue());
					sscanf(idTmp, "0x%x", &objectId);
					if (objectId == 0)
						sscanf(idTmp, "%d", &objectId);
					free(idTmp);
				}
				if (!wcscmp(attrNode->getNodeName(), L"looted"))
				{
					char *idTmp = CUtil::wc2c(attrNode->getNodeValue());
					sscanf(idTmp, "%d", &objectLoot);
					free(idTmp);
				}
				if (!wcscmp(attrNode->getNodeName(), L"type"))
				{
					char *idTmp = CUtil::wc2c(attrNode->getNodeValue());
					sscanf(idTmp, "%d", &type);
					free(idTmp);
				}
			}
			if (!objectId || !objectName || !strlen(objectName))
			{
				if (objectName)
					free(objectName);
				continue;
			}
			parent->AddChild(new CTibiaTreeItemData(objectName, objectId, objectLoot != 0, type));
			if (objectName)
				free(objectName);
		}
		if (!wcscmp(item->getNodeName(), L"branch"))
		{
			char *branchName = NULL;

			for (attrNr = 0; attrNr < (int)item->getAttributes()->getLength(); attrNr++)
			{
				DOMNode *attrNode = item->getAttributes()->item(attrNr);
				if (!wcscmp(attrNode->getNodeName(), L"name"))
					branchName = CUtil::wc2c(attrNode->getNodeValue());
			}
			if (!branchName || !strlen(branchName))
			{
				if (branchName)
					free(branchName);
				continue;
			}

			CTibiaTree* child = parent->AddChild(new CTibiaTreeBranchData(branchName));
			parseItemsBranch(item, child);
			if (branchName)
				free(branchName);
		}
	}
}
bool CConfigParser::ParseAxe(DOMNode* node, TActionByNameMap actions, CDeviceContext* device, unsigned char axeIdx)
{
	wstring threshold = node->getAttributes()->getNamedItem(L"threshold")->getNodeValue();

	// We can end this right here if it's a gesture axis
	if(device->IsGesturesContext())
	{
		wstring sendCenter = node->getAttributes()->getNamedItem(L"sendCenter")->getNodeValue();
		if(sendCenter.compare(L"true") == 0)
		{	
			device->AddAxe((IAxis*)new CAxis(_wtoi(threshold.c_str()),
				CMotion::MakePositionAndAxis(EGesturePosition::POSITIVE, axeIdx),
				CMotion::MakePositionAndAxis(EGesturePosition::NEGATIVE, axeIdx),
				&device->_gestureProcessor,
				CMotion::MakePositionAndAxis(EGesturePosition::CENTER, axeIdx)));
		}
		else
		{
			device->AddAxe((IAxis*)new CAxis(_wtoi(threshold.c_str()),
				CMotion::MakePositionAndAxis(EGesturePosition::POSITIVE, axeIdx),
				CMotion::MakePositionAndAxis(EGesturePosition::NEGATIVE, axeIdx),
				&device->_gestureProcessor));
		}
		return true;
	}

	wstring actionType;
	wstring posAction;
	wstring negAction;
	bool mouseX = false;
	bool mouseY = false;
	if(node->getAttributes()->getNamedItem(L"simulateMouseMove") != NULL)
	{
		DOMNode* mouseAxisNode = node->getAttributes()->getNamedItem(L"simulateMouseMove");
		wstring mouseAxisValue = mouseAxisNode->getNodeValue();
		if(mouseAxisValue.compare(L"x") == 0)
			mouseX = true;
		if(mouseAxisValue.compare(L"y") == 0)
			mouseY = true;
	}
	if(!mouseX && !mouseY)
	{
		if(node->getAttributes()->getNamedItem(L"type") != NULL)
			actionType = node->getAttributes()->getNamedItem(L"type")->getNodeValue();			
		else
			actionType = L"binary";
		if(node->getAttributes()->getNamedItem(L"posAction") != NULL)
			posAction = node->getAttributes()->getNamedItem(L"posAction")->getNodeValue();			
		else
			posAction = L"";
		if(node->getAttributes()->getNamedItem(L"negAction") != NULL)
			negAction = node->getAttributes()->getNamedItem(L"negAction")->getNodeValue();
		else
			negAction = L"";
	}
	else
	{
		wstring divisor = node->getAttributes()->getNamedItem(L"divisor")->getNodeValue();
		if(mouseX)
		{
			device->AddAxe((IAxis*)new CMouseXAxis(_wtoi(threshold.c_str()), _wtoi(divisor.c_str())));
			return true;
		}
		else if(mouseY)
		{
			device->AddAxe((IAxis*)new CMouseYAxis(_wtoi(threshold.c_str()), _wtoi(divisor.c_str())));
			return true;
		}
	}
	

	bool pulse = false;
	bool linear = false;
	if(actionType.compare(L"linear") == 0)
	{
		pulse = true;
		linear = true;
	}
	if(actionType.compare(L"exponential") == 0)
	{
		pulse = true;
		linear = false;
	}
	if(pulse)
	{
		wstring startPulse = node->getAttributes()->getNamedItem(L"startPulse")->getNodeValue();
		wstring endPulse = node->getAttributes()->getNamedItem(L"endPulse")->getNodeValue();
		
		device->AddAxe((IAxis*)new CAxis(_wtoi(threshold.c_str()), _wtoi(startPulse.c_str()),
			_wtoi(endPulse.c_str()), linear,
			actions[posAction],actions[negAction]));
		return true;
	}
	else
	{
		device->AddAxe((IAxis*)new CAxis(_wtoi(threshold.c_str()), actions[posAction], actions[negAction]));
		return true;
	}
	return false;
}
Ejemplo n.º 18
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.º 19
0
bool FDPLoader::parseHeader(DOMNode* pHeader)
{
	DOMNodeIterator* iterator = m_pDoc->createNodeIterator(pHeader, 
		DOMNodeFilter::SHOW_ELEMENT | DOMNodeFilter::SHOW_ATTRIBUTE, NULL, true);
	// use the tree walker to print out the text nodes.
	for ( DOMNode* current = iterator->nextNode(); current != 0; current = iterator->nextNode() )
	{
		// there are "file", "model", "fapu", "translation" and "rotation" elements in this chunk
		if (XercesString(current->getNodeName()) == "file")
		{
			// sample: <file version="0.2" />

			DOMNamedNodeMap* attr = current->getAttributes();
			if(!attr) // sth wrong
				return false;
			DOMNode* versionAttr = attr->getNamedItem(XercesString("version"));
			if(XercesString(m_version.c_str()) != versionAttr->getNodeValue())
				// versions not matching, flee!!
				return false;
		}
		else if(XercesString(current->getNodeName()) == "fapu")
		{
			// sample: <fapu ES0="69.9977" IRISD0="16.0424" ENS0="51.8036" MNS0="30.1538" MW0="50.6392" />
			
			DOMNamedNodeMap* attrList = current->getAttributes();
			if(!attrList) // sth wrong
				return false;

			/////////////// ES0
			DOMNode* attr = attrList->getNamedItem(XercesString("ES0"));
			if(attr)
				m_pFDP->setES0(toFloat(attr->getNodeValue()));
			/////////////// IRISD0
			attr = attrList->getNamedItem(XercesString("IRISD0"));
			if(attr)
				m_pFDP->setIRISD0(toFloat(attr->getNodeValue()));
			/////////////// ENS0
			attr = attrList->getNamedItem(XercesString("ENS0"));
			if(attr)
				m_pFDP->setENS0(toFloat(attr->getNodeValue()));
			/////////////// MNS0
			attr = attrList->getNamedItem(XercesString("MNS0"));
			if(attr)
				m_pFDP->setMNS0(toFloat(attr->getNodeValue()));
			/////////////// MW0
			attr = attrList->getNamedItem(XercesString("MW0"));
			if(attr)
				m_pFDP->setMW0(toFloat(attr->getNodeValue()));
			
			// debug << "fapu item" << std::endl;
		}
		else if(XercesString(current->getNodeName()) == "translation")
		{
			// sample: <translation x="0" y="-1" z="-659" />
        
			DOMNamedNodeMap* attrList = current->getAttributes();
			if(!attrList) // sth wrong
				return false;

			float x = 0, y = 0, z = 0;
			/////////////// x translation
			DOMNode* attr = attrList->getNamedItem(XercesString("x"));
			if(attr)
				x = toFloat(attr->getNodeValue());
			
			/////////////// y translation
			attr = attrList->getNamedItem(XercesString("y"));
			if(attr)
				y = toFloat(attr->getNodeValue());
		
			/////////////// z translation
			attr = attrList->getNamedItem(XercesString("z"));
			if(attr)
				z = toFloat(attr->getNodeValue());
		
			m_pFDP->setGlobalTranslation(x, y, z);
		//	debug << "translation item " << x << " " << y << " " << z << std::endl;
		}
		else if(XercesString(current->getNodeName()) == "rotation")
		{
			// sample: <rotation axis_x="-0.998192" axis_y="0.0596591" axis_z="0.00728935" axis_angle="0.444541" />

			DOMNamedNodeMap* attrList = current->getAttributes();
			if(!attrList) // sth wrong
				return false;

			float x = 0, y = 0, z = 0, a = 0;
			/////////////// x rotation
			DOMNode* attr = attrList->getNamedItem(XercesString("axis_x"));
			if(attr)
				x = toFloat(attr->getNodeValue());
			
			/////////////// y rotation
			attr = attrList->getNamedItem(XercesString("axis_y"));
			if(attr)
				y = toFloat(attr->getNodeValue());
		
			/////////////// z rotation
			attr = attrList->getNamedItem(XercesString("axis_z"));
			if(attr)
				z = toFloat(attr->getNodeValue());
		
			/////////////// z rotation
			attr = attrList->getNamedItem(XercesString("axis_angle"));
			if(attr)
				a = toFloat(attr->getNodeValue());
		
			m_pFDP->setGlobalRotation(x, y, z, a);
		}
	}
  
	return true;
}