Пример #1
0
DOMAttr *DOMNodeIDMap::find(const XMLCh *id)
{
    //
    //  Get the hashcode for the supplied string.
    //
	XMLSize_t initalHash = XMLString::hash(id, fSize-1, ((DOMDocumentImpl *)fDoc)->getMemoryManager());
	initalHash++;
	XMLSize_t currentHash = initalHash;

	//
	// Loop looking for a slot pointing to an attr with this id.
    //
    while (true)
	{
		DOMAttr *tableSlot = fTable[currentHash];
		if (tableSlot == 0)
        {
            // There is no matching entry in the table
            return 0;
        }


        if ((tableSlot != (DOMAttr *)-1) && XMLString::equals(tableSlot->getValue(), id))
            return tableSlot;

        currentHash += initalHash;  // rehash
        if (currentHash >= fSize)
            currentHash = currentHash % fSize;
    }
    return 0;  // Never gets here, but keeps some compilers happy.
}
std::string getAttributeByName (DOMNode* node, std::string attrName) {
	cdebug << "getAttr " << attrName << std::endl;
	assert (node->getNodeType () == DOMNode::ELEMENT_NODE);
	
	std::string value = "";
	
	if (node->hasAttributes()) {
		DOMNamedNodeMap *pAttributes = node->getAttributes ();
		
		for (unsigned int i = 0; i < pAttributes->getLength (); i++) {
			DOMAttr* pAttributeNode = (DOMAttr*) pAttributes->item(i);
			char* name = XMLString::transcode(pAttributeNode->getName());
			if (name == attrName) {
				char* tmpValue = XMLString::transcode(pAttributeNode->getValue());
				value = tmpValue;
				XMLString::release(&tmpValue);
			}
			XMLString::release(&name);
		}
	} else {
		cdebug << "Error in file to parse" << std::endl;
		throw ("Error in file to parse attributes");
	}
	cdebug << value << std::endl;
	return value;
} /* std::string getAttributeByName (DOMNode* node, std::string attrName) */
Пример #3
0
DOMAttr *DOMNodeIDMap::find(const XMLCh *id)
{
    //
    //  Get the hashcode for the supplied string.
    //
    XMLSize_t initalHash = XMLString::hash(id, fSize-1);
	initalHash++;
	XMLSize_t currentHash = initalHash;

	//
	// Loop looking for a slot pointing to an attr with this id.
    //
	DOMAttr *tableSlot;
    while ((tableSlot= fTable[currentHash])!=0)
	{
        if ((tableSlot != (DOMAttr *)-1) && XMLString::equals(tableSlot->getValue(), id))
            return tableSlot;

        currentHash += initalHash;  // rehash
        if (currentHash >= fSize)
            currentHash = currentHash % fSize;
    }
    // There is no matching entry in the table
    return 0;
}
Пример #4
0
const char* SYSTEM::CConfigItem::GetProperties(const char * propName)
{
	if(!propName)
	{
		return NULL;
	}
	if(((DOMElement*)itemElement)->hasAttributes())		//判断当前节点是否存在属性
	{
		DOMNamedNodeMap *pAttributes = ((DOMElement*)itemElement)->getAttributes();
		XMLCh *t = XMLString::transcode(propName);
		DOMAttr *pAttributeNode = (DOMAttr*)pAttributes->getNamedItem(t);
		XMLString::release(&t);
		if( m_curValue != NULL )
			XMLString::release(&m_curValue);
		if(!pAttributeNode)		//属性名称不存在
			m_curValue = NULL;
		else
			m_curValue = XMLString::transcode(pAttributeNode->getValue());
		return m_curValue;
	}
	else
	{
		return NULL;
	}	
}
Пример #5
0
const char *SkinElementsMgr::getElementAlias(const char *id)  {
  if(m_doc) {   
    DOMElement * node = m_doc->getElementById(id);
    if (node && !STRCMP(node->getNodeName(),"elementalias")) {
      DOMAttr * attr = node->getAttributeNode("target");
      if( attr && attr->getSpecified() )
        return attr->getValue();
    }
  }
  return NULL;
}
Пример #6
0
XMLNode *JobXML::deepCopyElement( XMLNode **copy, const XMLNode *original )
{
   // add the element to the copy
   char *nodeName = XMLString::transcode( original->getNodeName() );
   XMLNode *newElement = AddElement( (*copy), nodeName );
   XMLString::release( &nodeName );

   // add its attributes
   if ( original->hasAttributes() )
   {
      DOMNamedNodeMap *attributes = original->getAttributes();
      for( unsigned int i=0; i<attributes->getLength(); i++ )
      {
         DOMAttr *attr = (DOMAttr*)attributes->item( i );
         char *key = XMLString::transcode( attr->getName() );
         char *val = XMLString::transcode( attr->getValue() );
         SetAttribute( newElement, key, val );
         XMLString::release( &key );
         XMLString::release( &val );
      }
   }

   // recursively copy all child elements
   int childElementCount=0;
   XMLNode *itr = original->getFirstChild();
   for ( ; itr != NULL; itr = itr->getNextSibling() )
   {      
      if ( itr->getNodeType() == XMLNode::ELEMENT_NODE )
      {
         deepCopyElement( &newElement, itr );
         childElementCount++;
      }
   }

   // if no child elements, copy this element's text content and we are done
   if ( childElementCount == 0 )
   {
      char *content = XMLString::transcode( original->getTextContent() );
      SetContent( newElement, content );
      XMLString::release( &content );
   }

   return newElement;
}
Пример #7
0
// ---------------------------------------------------------------------------
//
//  Recursively Count up the total number of child Elements under the specified Node.
//  Process attributes of the node, if any.
//
// ---------------------------------------------------------------------------
static int countChildElements(DOMNode *n, bool printOutEncounteredEles)
{
    DOMNode *child;
    int count = 0;
    if (n) {
        if (n->getNodeType() == DOMNode::ELEMENT_NODE)
        {
            if(printOutEncounteredEles) {
                char *name = XMLString::transcode(n->getNodeName());
                cout <<"----------------------------------------------------------"<<endl;
                cout <<"Encountered Element : "<< name << endl;

                XMLString::release(&name);

                if(n->hasAttributes()) {
                    // get all the attributes of the node
                    DOMNamedNodeMap *pAttributes = n->getAttributes();
                    int nSize = pAttributes->getLength();
                    cout <<"\tAttributes" << endl;
                    cout <<"\t----------" << endl;
                    for(int i=0; i<nSize; ++i) {
                        DOMAttr *pAttributeNode = (DOMAttr*) pAttributes->item(i);
                        // get attribute name
                        char *name = XMLString::transcode(pAttributeNode->getName());

                        cout << "\t" << name << "=";
                        XMLString::release(&name);

                        // get attribute type
                        name = XMLString::transcode(pAttributeNode->getValue());
                        cout << name << endl;
                        XMLString::release(&name);
                    }
                }
            }
            ++count;
        }
        for (child = n->getFirstChild(); child != 0; child=child->getNextSibling())
            count += countChildElements(child, printOutEncounteredEles);
    }
    return count;
}
Пример #8
0
// ---------------------------------------------------------------------------
// utility func to extract a DOMNodes Base attr value if present
// ---------------------------------------------------------------------------
static const XMLCh *
getBaseAttrValue(DOMNode *node){
    if (node->getNodeType() == DOMNode::ELEMENT_NODE){
        DOMElement *elem = (DOMElement *)node;
        if(elem->hasAttributes()) {
            /* get all the attributes of the node */
            DOMNamedNodeMap *pAttributes = elem->getAttributes();
            XMLSize_t nSize = pAttributes->getLength();
            for(XMLSize_t i=0;i<nSize;++i) {
                DOMAttr *pAttributeNode = (DOMAttr*) pAttributes->item(i);
                /* get attribute name */
                if (XMLString::equals(pAttributeNode->getName(), XIncludeUtils::fgXIBaseAttrName)){
                    /*if (namespace == XMLUni::fgXMLString){

                    }*/
                    return pAttributeNode->getValue();
                }
            }
        }
    }
    return NULL;
}
Пример #9
0
void XmlTag::construct(XmlTag * parent, DOMNode * n, bool logging)
{
    this->parent = parent;
    this->name = "unknown";
    if (parent == NULL)
    {
        if (logging)
        {
            pLogEngine l (LogEngine::create (LOG_DEVELOPER, "XmlTag"));
            this->log = l;
        }
    }
    else
    {
        if (logging) this->log = parent->log;
    }

    if (n == NULL)
    {
        if (logging) log->__format(LOG_ERROR, "Empty tag (%s)!", getFullName().c_str());
        return;
    }
    if (n->getNodeType() != DOMNode::ELEMENT_NODE)
    {
        if (logging) log->__format(LOG_ERROR, "This (%s) is not a tag!", getFullName().c_str());
    }
    assignXmlString (name, n->getNodeName());

    //fill tag attributes map
    if (!n->hasAttributes())
    {
        if (logging) log->__format(LOG_WARNING, "No attributes in this tag (%s)!", getFullName().c_str() );
    }
    else
    {
        std::string attributeName = "";
        std::string attributeData = "";
        DOMNamedNodeMap *attList = n->getAttributes ();
        int size = attList->getLength ();
        for (int i = 0; i < size; ++i)
        {
            DOMAttr *attNode = (DOMAttr *) attList->item (i);
            assignXmlString (attributeName, attNode->getName ());
            assignXmlString (attributeData, attNode->getValue ());
            if ( (attributeName != "") && (attributeData != "") )
            {
                attributes[attributeName] = attributeData;
                attributesRead[attributeName] = false;
            }
        }
    }
    //fill child tags map
    if (n->hasChildNodes())
    {
        std::string childTagName;
        for (n = n->getFirstChild (); n != 0; n = n->getNextSibling ())
        {
            if (n) if (n->getNodeType() == DOMNode::ELEMENT_NODE)
                {
                    assignXmlString (childTagName, n->getNodeName());
                    //XmlTag * tmpTag = new XmlTag(this, n, logging);
                    XmlTag * tmpTag = new XmlTag(this, n);
                    tags.push_back(tmpTag);
                }
        }
    }
}
Пример #10
0
// ---------------------------------------------------------------------------
//  This method assumes that currentNode is an xinclude element and parses
//   it accordingly, acting on what it finds.
// ---------------------------------------------------------------------------
bool
XIncludeUtils::doDOMNodeXInclude(DOMNode *xincludeNode, DOMDocument *parsedDocument, XMLEntityHandler* entityResolver){
    bool modifiedNode = false;
    /* the relevant attributes to look for */
    const XMLCh *href = NULL;
    const XMLCh *parse = NULL;
    const XMLCh *xpointer = NULL;
    const XMLCh *encoding = NULL;
    const XMLCh *accept = NULL;
    const XMLCh *acceptlanguage = NULL;
    DOMNode *includeParent = xincludeNode->getParentNode();


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

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

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

    }

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

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

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

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

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

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

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

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

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

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

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

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

    if (includedDoc)
        includedDoc->release();

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

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

	BatchItem item( m_NextItem );

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

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

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

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

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

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

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

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

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

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

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

						string attributeName = localForm( attribute->getName() );
						string attributeValue = localForm( attribute->getValue() );
					
						string attributeValueToLog = ( attributeValue.length() > 100 ) ? attributeValue.substr( 0, 100 ) + string( "..." ) : attributeValue;
						DEBUG( "Attribute [" << attributeName << "] = [" << attributeValueToLog << "]" );
						m_NextItem.setPayload( attributeValue );
					}
				}
			}
		}
		if ( outputData != NULL )
		{
			outputData->release();
			outputData = NULL;
		}
	}
	catch( ... )
	{
		if ( outputData != NULL )
		{
			outputData->release();
			outputData = NULL;
		}
		throw;
	}
	return item;
}
Пример #12
0
void XMLData::parseDOMElement(DOMElement* element) {
	string name(XMLString::transcode(element->getTagName()));

	DOMNamedNodeMap* map = element->getAttributes();
	for (XMLSize_t i = 0; i < map->getLength(); i++) {
		DOMAttr* attr = static_cast<DOMAttr*>(map->item(i));
		string attr_name(XMLString::transcode(attr->getName()));
		string attr_value(XMLString::transcode(attr->getValue()));
		int value;
		try {
			value = stoi(attr_value);
			if(name == "hairiness") {
				if(attr_name == "typesMax") {
					hairTypeLength = nbBitsMin(value-1);
				}
			}
			else if(name == "limbs") {
				if(attr_name == "nbMax") {
					limbNbLength = nbBitsMin(value);
				}
				else if(attr_name == "sizeMax") {
					limbSizeLength = nbBitsMin(value);
				}
				else if(attr_name == "typesMax") {
					limbTypeLength = nbBitsMin(value-1);
				}
			}
			else if(name == "ears") {
				if(attr_name == "nbMax") {
					earNbLength = nbBitsMin(value);
				}
			}
			else if(name == "eyes") {
				if(attr_name == "nbMax") {
					eyeNbLength = nbBitsMin(value);
				}
			}
			else if(name == "nostrils") {
				if(attr_name == "nbMax") {
					nostrilNbLength = nbBitsMin(value);
				}
			}
			else if(name == "width") {
				if(attr_name == "typesMax") {
					mouthWidthTypeLength = nbBitsMin(value-1);
				}
			}
			else if(name == "teeth") {
				if(attr_name == "nbMax") {
					teethNbLength = nbBitsMin(value);
				}
				else if(attr_name == "typesMax") {
					teethTypeLength = nbBitsMin(value-1);
				}
			}
		}
		catch(invalid_argument& e) {
			if(name == "type") {
				string parentName(XMLString::transcode(static_cast<DOMElement*>(element->getParentNode())->getTagName()));
				if(parentName == "hairiness") {
					hairTypes.push_back(attr_value);
				}
				else if(parentName == "limbs") {
					limbTypes.push_back(attr_value);
				}
				else if(parentName == "width") {
					mouthWidthTypes.push_back(attr_value);
				}
				else if(parentName == "teeth") {
					teethTypes.push_back(attr_value);
				}
			}
		}
		/*
		cout << "\t" << attr_name << ": "<< attr_value << endl;
		*/
	}
}
void XmlSchemaGenerator::generateData ( const wxString &elementName,
		size_t nIndent /*= 0*/)
{
	ElmtData &data = mElements[elementName];
	std::set<const DOMElement *>::iterator elmtItr;

	data.name = elementName;

	//Content
	std::map<wxString, ChildData> &childMap = data.children;
	std::map<wxString, ChildData>::iterator itr;
	std::set<wxString> previous;
	elmtItr = data.nodes.begin();
	for ( ; elmtItr != data.nodes.end(); ++elmtItr )
	{
		previous.clear();

		std::map<wxString, size_t> countMap;
		DOMElement *child = ( **elmtItr ).getFirstElementChild();
		for ( ; child != NULL; child = child->getNextElementSibling() )
		{
			wxString name = WrapXerces::toString ( child->getTagName() );
			childMap[name].prevSiblings.insert ( previous.begin(), previous.end() );
			childMap[name].prevSiblings.erase ( name ); // Don't depend on oneself
			previous.insert ( name );
			countMap[name] += 1;
		}
		std::map<wxString, size_t>::iterator countItr = countMap.begin();
		for ( ; countItr != countMap.end(); ++countItr )
		{
			if ( childMap[countItr->first].maxOccurs < countItr->second )
				childMap[countItr->first].maxOccurs = countItr->second;
		}
		if ( childMap.size() == countMap.size() )
			continue;
		for ( itr = childMap.begin(); itr != childMap.end(); ++itr )
		{
			if ( countMap.find ( itr->first ) != countMap.end() )
				continue;
			itr->second.minOccurs = 0;
		}
	}
	// Attribute
	std::map<wxString, const XMLCh *> &attrMap = data.attrMap;
	std::set<wxString> &optAttrs = data.optAttrs;
	std::map<wxString, const XMLCh *>::iterator attrItr;
	elmtItr = data.nodes.begin();
	for ( ; elmtItr != data.nodes.end(); ++elmtItr )
	{
		if ( ! ( **elmtItr ).hasAttributes() )
			continue;

		wxString name;
		DOMAttr *attr;
		DOMNamedNodeMap *attrs = ( **elmtItr ).getAttributes();
		size_t i = attrs->getLength();
		while ( i-- > 0 )
		{
			attr = ( DOMAttr* ) attrs->item ( i );
			name = WrapXerces::toString ( attr->getName() );
			if ( attr->getPrefix() != NULL )
			{
				wxLogDebug ( _T("Ignore: %s"), name.c_str() );
				continue;
			}
			if ( attr->getSpecified() )
				attrMap[name]; // Initialize attribute map
			else
				attrMap[name] = attr->getValue();
		}
		if ( attrMap.size() == optAttrs.size() )
			continue;
		for ( attrItr = attrMap.begin(); attrItr != attrMap.end(); ++attrItr )
		{
			if ( attrs->getNamedItem ( ( const XMLCh * )
					WrapXerces::toString ( attrItr->first ).GetData() ) == NULL )
			{
				optAttrs.insert ( attrItr->first );
			}
		}
	}

	// Deal with sequence
	wxLogDebug ( _T("%s:"), elementName.c_str() );
	data.useSequence = getSequence ( data.sequence, childMap );

	// Now we have the data of the element
	if ( mGrammarType == Grammar::DTDGrammarType )
	{
		generateDTD ( data, nIndent );
		mSchema << data.schema;
	}
	else if ( !mInlineSimpleType )
	{ // Or wait until all data are available
		generateSchema ( data, nIndent );
		mSchema << data.schema;
	}
}