示例#1
0
        void MeshGraph2D::ReadElements(TiXmlDocument &doc)
        {
            /// We know we have it since we made it this far.
            TiXmlHandle docHandle(&doc);
            TiXmlElement* mesh = docHandle.FirstChildElement("NEKTAR").FirstChildElement("GEOMETRY").Element();
            TiXmlElement* field = NULL;

            /// Look for elements in ELEMENT block.
            field = mesh->FirstChildElement("ELEMENT");

            ASSERTL0(field, "Unable to find ELEMENT tag in file.");

            // Set up curve map for curved elements on an embedded manifold.
            map<int, int> faceCurves;
            map<int,int>::iterator x;
            for (int i = 0; i < m_curvedFaces.size(); ++i)
            {
                faceCurves[m_curvedFaces[i]->m_curveID] = i;
            }

            int nextElementNumber = -1;

            /// All elements are of the form: "<? ID="#"> ... </?>", with
            /// ? being the element type.

            TiXmlElement *element = field->FirstChildElement();

                while (element)
                {
                    std::string elementType(element->ValueStr());

                    ASSERTL0(elementType == "Q" || elementType == "T",
                             (std::string("Unknown 2D element type: ") + elementType).c_str());

                    /// These should be ordered.
                    nextElementNumber++;

                    /// Read id attribute.
                    int indx;
                    int err = element->QueryIntAttribute("ID", &indx);
                    ASSERTL0(err == TIXML_SUCCESS, "Unable to read element attribute ID.");
//                    ASSERTL0(indx == nextElementNumber, "Element IDs must begin with zero and be sequential.");

                    /// Read text element description.
                    TiXmlNode* elementChild = element->FirstChild();
                    std::string elementStr;
                    while(elementChild)
                    {
                        if (elementChild->Type() == TiXmlNode::TEXT)
                        {
                            elementStr += elementChild->ToText()->ValueStr();
                        }
                        elementChild = elementChild->NextSibling();
                    }

                    ASSERTL0(!elementStr.empty(), "Unable to read element description body.");

                    /// Parse out the element components corresponding to type of element.
                    if (elementType == "T")
                    {
                        // Read three edge numbers
                        int edge1, edge2, edge3;
                        std::istringstream elementDataStrm(elementStr.c_str());

                        try
                        {
                            elementDataStrm >> edge1;
                            elementDataStrm >> edge2;
                            elementDataStrm >> edge3;

                            ASSERTL0(!elementDataStrm.fail(), (std::string("Unable to read element data for TRIANGLE: ") + elementStr).c_str());

                            /// Create a TriGeom to hold the new definition.
                            SegGeomSharedPtr edges[TriGeom::kNedges] =
                        {
                            GetSegGeom(edge1),
                            GetSegGeom(edge2),
                            GetSegGeom(edge3)
                        };

                            StdRegions::Orientation edgeorient[TriGeom::kNedges] =
                        {
                            SegGeom::GetEdgeOrientation(*edges[0], *edges[1]),
                            SegGeom::GetEdgeOrientation(*edges[1], *edges[2]),
                            SegGeom::GetEdgeOrientation(*edges[2], *edges[0])
                        };

                            TriGeomSharedPtr trigeom;
                            if ((x = faceCurves.find(indx)) == faceCurves.end())
                            {
                                trigeom = MemoryManager<TriGeom>
                                            ::AllocateSharedPtr(indx,
                                                    edges,
                                                    edgeorient);
                            }
                            else
                            {
                                trigeom = MemoryManager<TriGeom>
                                            ::AllocateSharedPtr(indx,
                                                    edges,
                                                    edgeorient,
                                                    m_curvedFaces[x->second]);
                            }
                            trigeom->SetGlobalID(indx);

                            m_triGeoms[indx] = trigeom;
                        }
                        catch(...)
                        {
                            NEKERROR(ErrorUtil::efatal, (std::string("Unable to read element data for TRIANGLE: ") + elementStr).c_str());
                        }
                    }
                    else if (elementType == "Q")
示例#2
0
void duXmlStatic::ParseTextParam()
{
	LPCTSTR lpszText = GetText();
	if (lpszText == NULL || *lpszText == 0)
		return;
	
	TiXmlDocument *pXmlDoc = new TiXmlDocument;
	pXmlDoc->Parse(lpszText, NULL);
	
	TiXmlElement *pTextElement = pXmlDoc->FirstChildElement(_T("text"));
	if (pTextElement == NULL)
	{
		delete pXmlDoc;
		return;
	}
	
	Destroy();
	
	m_nParagraphSpace = ReadXmlAttributeInt(pTextElement, _T("ParagraphSpace"));
	ReadXmlAttributeText(pTextElement, _T("Font"), m_szDefaultFont, MAX_NAME);
	m_clrDefault = ReadXmlAttributeColor(pTextElement, _T("Color"));

	TiXmlNode *pChildNode = pTextElement->FirstChild();
	while (pChildNode)
	{
		if (pChildNode->Type() == TiXmlNode::ELEMENT)
		{
			TiXmlElement *pThis = pChildNode->ToElement();
			if (lstrcmpi(pThis->Value(), _T("br")) == 0)
			{
				XMLTEXTHEAD *pBrText = ParseBrText(pThis);
				if (pBrText)
					m_vtXmlText.push_back(pBrText);
			}
			else if (lstrcmpi(pThis->Value(), _T("text")) == 0)
			{
				XMLTEXTHEAD *pFormatText = ParseFormatText(pThis);
				if (pFormatText)
					m_vtXmlText.push_back(pFormatText);
			}
		}
		else if (pChildNode->Type() == TiXmlNode::TEXT)
		{
			TiXmlText *pThis = pChildNode->ToText();
			XMLTEXTHEAD *pNormalText = ParseNormalText(pThis);
			if (pNormalText)
				m_vtXmlText.push_back(pNormalText);
		}
		
		pChildNode = pChildNode->NextSibling();
	}
	
	//////////////////////////////////////////////////////////////////
	duRect rectStatic;
	Plugin_GetRect(this, &rectStatic);
	rectStatic.OffsetRect(-rectStatic.left, -rectStatic.top);
	
	int nTextCount = (int)m_vtXmlText.size();
	int i;
	int nCurrentLineWidth = 0;
	int nMaxHeight = 0;
	
	XMLSTATICLINE *pThisLine = NULL;
	for (i = 0;i < nTextCount; i++)
	{
		XMLTEXTHEAD *pTextHead = m_vtXmlText[i];
		MeasureString(pTextHead);
		
		if (pTextHead->size.cy > nMaxHeight)
			nMaxHeight = pTextHead->size.cy;

		if (pTextHead->enType == BRTEXT)
		{
			XMLSTATICLINESEGMENT *pLineSegment = new XMLSTATICLINESEGMENT;
			pLineSegment->pTextHead = pTextHead;
			pLineSegment->lpString = g_emptyString;
			pLineSegment->nStringWidth = 0;
			pLineSegment->nStringPosInTextHead = 0;
			pLineSegment->nWidth = pTextHead->size.cx;
			pLineSegment->nHeight = pTextHead->size.cy;

			if (pThisLine == NULL)
			{
				pThisLine = new XMLSTATICLINE;
				pThisLine->nWidth = 0;
				pThisLine->nHeight = 0;
				pThisLine->vtLineSegment.clear();
				m_vtLine.push_back(pThisLine);
			}

			pThisLine->nWidth = nCurrentLineWidth;
			pThisLine->nHeight = nMaxHeight;
			pThisLine->vtLineSegment.push_back(pLineSegment);

			pThisLine = NULL;
			nCurrentLineWidth = 0;
		}
		else
		{
			nCurrentLineWidth += pTextHead->size.cx;
			if (nCurrentLineWidth > rectStatic.Width())
			{
				XMLSTATICLINESEGMENT *pLineSegment = MeasureStringBreakPos(pTextHead, 0, nCurrentLineWidth - pTextHead->size.cx, rectStatic.Width());
				if (pLineSegment == NULL)
					_TRACE(_T("Error: pLineSegment is NULL\n"));
				
				if (pThisLine == NULL)
				{
					pThisLine = new XMLSTATICLINE;
					pThisLine->nWidth = 0;
					pThisLine->nHeight = 0;
					pThisLine->vtLineSegment.clear();
					m_vtLine.push_back(pThisLine);
				}

				pThisLine->nWidth = nCurrentLineWidth - pTextHead->size.cx + pLineSegment->nWidth;
				pThisLine->nHeight = nMaxHeight;
				pThisLine->vtLineSegment.push_back(pLineSegment);
				
				nMaxHeight = 0;
				
				int nRemainWidth = nCurrentLineWidth - pThisLine->nWidth;
				XMLSTATICLINESEGMENT *pLineSegment2 = pLineSegment;
				while (nRemainWidth > rectStatic.Width())
				{
					pLineSegment2 = MeasureStringBreakPos(pTextHead, pLineSegment2->nStringPosInTextHead + pLineSegment2->nStringWidth, 0, rectStatic.Width());
					if (pLineSegment2 == NULL)
						_TRACE(_T("Error: pLineSegment2 is NULL\n"));

					pThisLine = new XMLSTATICLINE;
					pThisLine->nWidth = pLineSegment2->nWidth;
					pThisLine->nHeight = pLineSegment2->nHeight;
					pThisLine->vtLineSegment.push_back(pLineSegment2);
					m_vtLine.push_back(pThisLine);

					nRemainWidth -= pLineSegment2->nWidth;
				}
				
				if (pLineSegment2->nStringPosInTextHead + pLineSegment2->nStringWidth < pLineSegment2->pTextHead->strText.length())
				{
					pThisLine = new XMLSTATICLINE;
					XMLSTATICLINESEGMENT *pLineSegment3 = new XMLSTATICLINESEGMENT;
					pLineSegment3->pTextHead = pTextHead;
					pLineSegment3->lpString = pLineSegment2->lpString + pLineSegment2->nStringWidth;
					pLineSegment3->nStringPosInTextHead = pLineSegment2->nStringPosInTextHead + pLineSegment2->nStringWidth ;
					pLineSegment3->nStringWidth = pLineSegment2->pTextHead->strText.length() - pLineSegment3->nStringPosInTextHead;
					pLineSegment3->nWidth = nRemainWidth;
					pLineSegment3->nHeight = pTextHead->size.cy;
					pThisLine->vtLineSegment.push_back(pLineSegment3);
					pThisLine->nWidth = 0;
					pThisLine->nHeight = 0;
					
					nMaxHeight = pTextHead->size.cy;
					m_vtLine.push_back(pThisLine);
				}

				nCurrentLineWidth = nRemainWidth;
			}
			else
			{
				XMLSTATICLINESEGMENT *pLineSegment = new XMLSTATICLINESEGMENT;
				pLineSegment->pTextHead = pTextHead;
				pLineSegment->lpString = pTextHead->strText.c_str();
				pLineSegment->nStringWidth = pTextHead->strText.length();
				pLineSegment->nStringPosInTextHead = 0;
				pLineSegment->nWidth = pTextHead->size.cx;
				pLineSegment->nHeight = pTextHead->size.cy;
				
				if (pThisLine == NULL)
				{
					pThisLine = new XMLSTATICLINE;
					pThisLine->nWidth = 0;
					pThisLine->nHeight = 0;
					m_vtLine.push_back(pThisLine);
				}
				
				pThisLine->vtLineSegment.push_back(pLineSegment);
			}
		}
	}
	
	if (pThisLine->nHeight == 0)
		pThisLine->nHeight = nMaxHeight;

	delete pXmlDoc;
}
示例#3
0
const wchar_t* TiXmlElement::ReadValue( const wchar_t* p, TiXmlParsingData* data, TiXmlEncoding encoding )
{
	TiXmlDocument* document = GetDocument();

	// Read in text and elements in any order.
	const wchar_t* pWithWhiteSpace = p;
	p = SkipWhiteSpace( p, encoding );

	while ( p && *p )
	{
		if ( *p != '<' )
		{
			// Take what we have, make a text element.
			TiXmlText* textNode = new TiXmlText( L"" );

			if ( !textNode )
			{
				if ( document ) document->SetError( TIXML_ERROR_OUT_OF_MEMORY, 0, 0, encoding );
				    return 0;
			}

			if ( TiXmlBase::IsWhiteSpaceCondensed() )
			{
				p = textNode->Parse( p, data, encoding );
			}
			else
			{
				// Special case: we want to keep the white space
				// so that leading spaces aren't removed.
				p = textNode->Parse( pWithWhiteSpace, data, encoding );
			}

			if ( !textNode->Blank() )
				LinkEndChild( textNode );
			else
				delete textNode;
		} 
		else 
		{
			// We hit a '<'
			// Have we hit a new element or an end tag? This could also be
			// a TiXmlText in the L"CDATA" style.
			if ( StringEqual( p, L"</", false, encoding ) )
			{
				return p;
			}
			else
			{
				TiXmlNode* node = Identify( p, encoding );
				if ( node )
				{
					p = node->Parse( p, data, encoding );
					LinkEndChild( node );
				}				
				else
				{
					return 0;
				}
			}
		}
		pWithWhiteSpace = p;
		//p = SkipWhiteSpace( p, encoding );
	}

	if ( !p )
	{
		if ( document ) document->SetError( TIXML_ERROR_READING_ELEMENT_VALUE, 0, 0, encoding );
	}	
	return p;
}
示例#4
0
文件: xmltest.cpp 项目: E-LLP/europa
int main()
{
	//
	// We start with the 'demoStart' todo list. Process it. And
	// should hopefully end up with the todo list as illustrated.
	//
	const char* demoStart =
		"<?xml version=\"1.0\"  standalone='no' >\n"
		"<!-- Our to do list data -->"
		"<ToDo>\n"
		"<!-- Do I need a secure PDA? -->\n"
		"<Item priority=\"1\" distance='close'> Go to the <bold>Toy store!</bold></Item>"
		"<Item priority=\"2\" distance='none'> Do bills   </Item>"
		"<Item priority=\"2\" distance='far &amp; back'> Look for Evil Dinosaurs! </Item>"
		"</ToDo>";

#ifdef TIXML_USE_STL
	/*	What the todo list should look like after processing.
		In stream (no formatting) representation. */
	const char* demoEnd =
		"<?xml version=\"1.0\" standalone=\"no\" ?>"
		"<!-- Our to do list data -->"
		"<ToDo>"
		"<!-- Do I need a secure PDA? -->"
		"<Item priority=\"2\" distance=\"close\">Go to the"
		"<bold>Toy store!"
		"</bold>"
		"</Item>"
		"<Item priority=\"1\" distance=\"far\">Talk to:"
		"<Meeting where=\"School\">"
		"<Attendee name=\"Marple\" position=\"teacher\" />"
		"<Attendee name=\"Vo&#x82;\" position=\"counselor\" />"
		"</Meeting>"
		"<Meeting where=\"Lunch\" />"
		"</Item>"
		"<Item priority=\"2\" distance=\"here\">Do bills"
		"</Item>"
		"</ToDo>";
#endif

	// The example parses from the character string (above):
	#if defined( WIN32 ) && defined( TUNE )
	QueryPerformanceCounter( (LARGE_INTEGER*) (&start) );
	#endif

	{
		// Write to a file and read it back, to check file I/O.

		TiXmlDocument doc( "demotest.xml" );
		doc.Parse( demoStart );

		if ( doc.Error() )
		{
			printf( "Error in %s: %s\n", doc.Value(), doc.ErrorDesc() );
			exit( 1 );
		}
		doc.SaveFile();
	}
	ostringstream outputStream( ostringstream::out );
        {
          TiXmlDocument doc( "demotest.xml" );
          bool loadOkay = doc.LoadFile();
          
          if ( !loadOkay )
          {
            printf( "Could not load test file 'demotest.xml'. Error='%s'. Exiting.\n", doc.ErrorDesc() );
            exit( 1 );
          }

          printf( "** Demo doc read from disk: ** \n\n" );
          doc.Print( stdout );

          TiXmlNode* node = 0;
          TiXmlElement* todoElement = 0;
          TiXmlElement* itemElement = 0;


          // --------------------------------------------------------
          // An example of changing existing attributes, and removing
          // an element from the document.
          // --------------------------------------------------------
          
          // Get the "ToDo" element.
          // It is a child of the document, and can be selected by name.
          node = doc.FirstChild( "ToDo" );
          assert( node );
          todoElement = node->ToElement();
          assert( todoElement  );
          
          // Going to the toy store is now our second priority...
          // So set the "priority" attribute of the first item in the list.
          node = todoElement->FirstChildElement();	// This skips the "PDA" comment.
          assert( node );
          itemElement = node->ToElement();
          assert( itemElement  );
          itemElement->SetAttribute( "priority", 2 );
          
          // Change the distance to "doing bills" from
          // "none" to "here". It's the next sibling element.
          itemElement = itemElement->NextSiblingElement();
          assert( itemElement );
          itemElement->SetAttribute( "distance", "here" );
          
          // Remove the "Look for Evil Dinosours!" item.
          // It is 1 more sibling away. We ask the parent to remove
          // a particular child.
          itemElement = itemElement->NextSiblingElement();
          todoElement->RemoveChild( itemElement );
          
          itemElement = 0;
          
          // --------------------------------------------------------
          // What follows is an example of created elements and text
          // nodes and adding them to the document.
          // --------------------------------------------------------
          
          // Add some meetings.
          TiXmlElement item( "Item" );
          item.SetAttribute( "priority", "1" );
          item.SetAttribute( "distance", "far" );
          
          TiXmlText text( "Talk to:" );
          
          TiXmlElement meeting1( "Meeting" );
          meeting1.SetAttribute( "where", "School" );
          
          TiXmlElement meeting2( "Meeting" );
          meeting2.SetAttribute( "where", "Lunch" );
          
          TiXmlElement attendee1( "Attendee" );
          attendee1.SetAttribute( "name", "Marple" );
          attendee1.SetAttribute( "position", "teacher" );
          
          TiXmlElement attendee2( "Attendee" );
          attendee2.SetAttribute( "name", "Vo&#x82;" );
          attendee2.SetAttribute( "position", "counselor" );
          
          // Assemble the nodes we've created:
          meeting1.InsertEndChild( attendee1 );
          meeting1.InsertEndChild( attendee2 );
          
          item.InsertEndChild( text );
          item.InsertEndChild( meeting1 );
          item.InsertEndChild( meeting2 );
          
          // And add the node to the existing list after the first child.
          node = todoElement->FirstChild( "Item" );
          assert( node );
          itemElement = node->ToElement();
          assert( itemElement );
          
          todoElement->InsertAfterChild( itemElement, item );
          
          printf( "\n** Demo doc processed: ** \n\n" );
          doc.Print( stdout );
          
          
#ifdef TIXML_USE_STL
          printf( "** Demo doc processed to stream: ** \n\n" );
          cout << doc << endl << endl;
#endif

	// --------------------------------------------------------
	// Different tests...do we have what we expect?
	// --------------------------------------------------------

	int count = 0;
	TiXmlElement*	element;

	//////////////////////////////////////////////////////

#ifdef TIXML_USE_STL
	cout << "** Basic structure. **\n";
	outputStream << doc;
	XmlTest( "Output stream correct.",	string( demoEnd ).c_str(),
                 outputStream.str().c_str(), true );
#endif
        
	node = doc.RootElement();
	XmlTest( "Root element exists.", true, ( node != 0 && node->ToElement() ) );
	XmlTest ( "Root element value is 'ToDo'.", "ToDo",  node->Value());

	node = node->FirstChild();
	XmlTest( "First child exists & is a comment.", true, ( node != 0 && node->ToComment() ) );
	node = node->NextSibling();
	XmlTest( "Sibling element exists & is an element.", true, ( node != 0 && node->ToElement() ) );
	XmlTest ( "Value is 'Item'.", "Item", node->Value() );

	node = node->FirstChild();
	XmlTest ( "First child exists.", true, ( node != 0 && node->ToText() ) );
	XmlTest ( "Value is 'Go to the'.", "Go to the", node->Value() );


	//////////////////////////////////////////////////////
	printf ("\n** Iterators. **\n");

	// Walk all the top level nodes of the document.
	count = 0;
	for( node = doc.FirstChild();
		 node;
		 node = node->NextSibling() )
	{
		count++;
	}
	XmlTest( "Top level nodes, using First / Next.", 3, count );

	count = 0;
	for( node = doc.LastChild();
		 node;
		 node = node->PreviousSibling() )
	{
		count++;
	}
	XmlTest( "Top level nodes, using Last / Previous.", 3, count );

	// Walk all the top level nodes of the document,
	// using a different sytax.
	count = 0;
	for( node = doc.IterateChildren( 0 );
		 node;
		 node = doc.IterateChildren( node ) )
	{
		count++;
	}
	XmlTest( "Top level nodes, using IterateChildren.", 3, count );

	// Walk all the elements in a node.
	count = 0;
	for( element = todoElement->FirstChildElement();
		 element;
		 element = element->NextSiblingElement() )
	{
		count++;
	}
	XmlTest( "Children of the 'ToDo' element, using First / Next.",
		3, count );

	// Walk all the elements in a node by value.
	count = 0;
	for( node = todoElement->FirstChild( "Item" );
		 node;
		 node = node->NextSibling( "Item" ) )
	{
		count++;
	}
	XmlTest( "'Item' children of the 'ToDo' element, using First/Next.", 3, count );

	count = 0;
	for( node = todoElement->LastChild( "Item" );
		 node;
		 node = node->PreviousSibling( "Item" ) )
	{
		count++;
	}
	XmlTest( "'Item' children of the 'ToDo' element, using Last/Previous.", 3, count );

#ifdef TIXML_USE_STL
	{
		cout << "\n** Parsing. **\n";
		istringstream parse0( "<Element0 attribute0='foo0' attribute1= noquotes attribute2 = '&gt;' />" );
		TiXmlElement element0( "default" );
		parse0 >> element0;

		XmlTest ( "Element parsed, value is 'Element0'.", "Element0", element0.Value() );
		XmlTest ( "Reads attribute 'attribute0=\"foo0\"'.", "foo0", element0.Attribute( "attribute0" ));
		XmlTest ( "Reads incorrectly formatted 'attribute1=noquotes'.", "noquotes", element0.Attribute( "attribute1" ) );
		XmlTest ( "Read attribute with entity value '>'.", ">", element0.Attribute( "attribute2" ) );
	}
#endif
        }
	{
          const char* error =	"<?xml version=\"1.0\" standalone=\"no\" ?>\n"
              "<passages count=\"006\" formatversion=\"20020620\">\n"
              "    <wrong error>\n"
              "</passages>";
          
          TiXmlDocument doc;
          doc.Parse( error );
          XmlTest( "Error row", doc.ErrorRow(), 3 );
          XmlTest( "Error column", doc.ErrorCol(), 17 );
          //printf( "error=%d id='%s' row %d col%d\n", (int) doc.Error(), doc.ErrorDesc(), doc.ErrorRow()+1, doc.ErrorCol() + 1 );
	}
	{
		const char* str =	"\t<?xml version=\"1.0\" standalone=\"no\" ?>\t<room doors='2'>\n"
							"  <!-- Silly example -->\n"
							"    <door wall='north'>A great door!</door>\n"
							"\t<door wall='east'/>"
							"</room>";

        TiXmlDocument doc;
		doc.Parse( str );

		TiXmlHandle docHandle( &doc );
		TiXmlHandle roomHandle = docHandle.FirstChildElement( "room" );
		TiXmlHandle commentHandle = docHandle.FirstChildElement( "room" ).FirstChild();
		TiXmlHandle textHandle = docHandle.FirstChildElement( "room" ).ChildElement( "door", 0 ).FirstChild();
		TiXmlHandle door0Handle = docHandle.FirstChildElement( "room" ).ChildElement( 0 );
		TiXmlHandle door1Handle = docHandle.FirstChildElement( "room" ).ChildElement( 1 );

		assert( docHandle.Node() );
		assert( roomHandle.Element() );
		assert( commentHandle.Node() );
		assert( textHandle.Text() );
		assert( door0Handle.Element() );
		assert( door1Handle.Element() );

		TiXmlDeclaration* declaration = doc.FirstChild()->ToDeclaration();
		assert( declaration );
		TiXmlElement* room = roomHandle.Element();
		assert( room );
		TiXmlAttribute* doors = room->FirstAttribute();
		assert( doors );
		TiXmlText* text = textHandle.Text();
		TiXmlComment* comment = commentHandle.Node()->ToComment();
		assert( comment );
		TiXmlElement* door0 = door0Handle.Element();
		TiXmlElement* door1 = door1Handle.Element();

		XmlTest( "Location tracking: Declaration row", declaration->Row(), 1 );
		XmlTest( "Location tracking: Declaration col", declaration->Column(), 5 );
		XmlTest( "Location tracking: room row", room->Row(), 1 );
		XmlTest( "Location tracking: room col", room->Column(), 45 );
		XmlTest( "Location tracking: doors row", doors->Row(), 1 );
		XmlTest( "Location tracking: doors col", doors->Column(), 51 );
		XmlTest( "Location tracking: Comment row", comment->Row(), 2 );
		XmlTest( "Location tracking: Comment col", comment->Column(), 3 );
		XmlTest( "Location tracking: text row", text->Row(), 3 ); 
		XmlTest( "Location tracking: text col", text->Column(), 24 );
		XmlTest( "Location tracking: door0 row", door0->Row(), 3 );
		XmlTest( "Location tracking: door0 col", door0->Column(), 5 );
		XmlTest( "Location tracking: door1 row", door1->Row(), 4 );
		XmlTest( "Location tracking: door1 col", door1->Column(), 5 );
	}
	{
		const char* str =	"\t<?xml version=\"1.0\" standalone=\"no\" ?>\t<room doors='2'>\n"
							"</room>";

        TiXmlDocument doc;
		doc.SetTabSize( 8 );
		doc.Parse( str );

		TiXmlHandle docHandle( &doc );
		TiXmlHandle roomHandle = docHandle.FirstChildElement( "room" );

		assert( docHandle.Node() );
		assert( roomHandle.Element() );

		TiXmlElement* room = roomHandle.Element();
		assert( room );
		TiXmlAttribute* doors = room->FirstAttribute();
		assert( doors );

		XmlTest( "Location tracking: Tab 8: room row", room->Row(), 1 );
		XmlTest( "Location tracking: Tab 8: room col", room->Column(), 49 );
		XmlTest( "Location tracking: Tab 8: doors row", doors->Row(), 1 );
		XmlTest( "Location tracking: Tab 8: doors col", doors->Column(), 55 );
	}

	{
		const char* str = "<doc attr0='1' attr1='2.0' attr2='foo' />";

		TiXmlDocument doc;
		doc.Parse( str );

		TiXmlElement* ele = doc.FirstChildElement();

		int iVal, result;
		double dVal;

		result = ele->QueryDoubleAttribute( "attr0", &dVal );
		XmlTest( "Query attribute: int as double", result, TIXML_SUCCESS );
		XmlTest( "Query attribute: int as double", static_cast<int>(dVal), 1 );
		result = ele->QueryDoubleAttribute( "attr1", &dVal );
		XmlTest( "Query attribute: double as double", static_cast<int>(dVal), 2 );
		result = ele->QueryIntAttribute( "attr1", &iVal );
		XmlTest( "Query attribute: double as int", result, TIXML_SUCCESS );
		XmlTest( "Query attribute: double as int", iVal, 2 );
		result = ele->QueryIntAttribute( "attr2", &iVal );
		XmlTest( "Query attribute: not a number", result, TIXML_WRONG_TYPE );
		result = ele->QueryIntAttribute( "bar", &iVal );
		XmlTest( "Query attribute: does not exist", result, TIXML_NO_ATTRIBUTE );
	}

#ifdef TIXML_USE_STL
	{
		//////////////////////////////////////////////////////
		cout << "\n** Streaming. **\n";

		// Round trip check: stream in, then stream back out to verify. The stream
		// out has already been checked, above. We use the output

		istringstream inputStringStream( outputStream.str() );
		TiXmlDocument document0;

		inputStringStream >> document0;

		ostringstream outputStream0( ostringstream::out );
		outputStream0 << document0;

		XmlTest( "Stream round trip correct.",	string( demoEnd ).c_str(), 
												outputStream0.str().c_str(), true );

		std::string str;
		str << document0;

		XmlTest( "String printing correct.", string( demoEnd ).c_str(), 
											 str.c_str(), true );
	}
#endif

	//////////////////////////////////////////////////////
#ifdef TIXML_USE_STL
	printf ("\n** Parsing, no Condense Whitespace **\n");
	TiXmlBase::SetCondenseWhiteSpace( false );

	istringstream parse1( "<start>This  is    \ntext</start>" );
	TiXmlElement text1( "text" );
	parse1 >> text1;

	XmlTest ( "Condense white space OFF.", "This  is    \ntext",
				text1.FirstChild()->Value(),
				true );
#endif

	//////////////////////////////////////////////////////
	printf ("\n** Bug regression tests **\n");

	// InsertBeforeChild and InsertAfterChild causes crash.
	{
		TiXmlElement parent( "Parent" );
		TiXmlElement childText0( "childText0" );
		TiXmlElement childText1( "childText1" );
		TiXmlNode* childNode0 = parent.InsertEndChild( childText0 );
		TiXmlNode* childNode1 = parent.InsertBeforeChild( childNode0, childText1 );

		XmlTest( "Test InsertBeforeChild on empty node.", ( childNode1 == parent.FirstChild() ), true );
	}

	{
		// InsertBeforeChild and InsertAfterChild causes crash.
		TiXmlElement parent( "Parent" );
		TiXmlElement childText0( "childText0" );
		TiXmlElement childText1( "childText1" );
		TiXmlNode* childNode0 = parent.InsertEndChild( childText0 );
		TiXmlNode* childNode1 = parent.InsertAfterChild( childNode0, childText1 );

		XmlTest( "Test InsertAfterChild on empty node. ", ( childNode1 == parent.LastChild() ), true );
	}

	// Reports of missing constructors, irregular string problems.
	{
		// Missing constructor implementation. No test -- just compiles.
		TiXmlText text( "Missing" );

		#ifdef TIXML_USE_STL
			// Missing implementation:
			TiXmlDocument doc;
			string name = "missing";
			doc.LoadFile( name );

			TiXmlText textSTL( name );
		#else
			// verifing some basic string functions:
			TiXmlString a;
			TiXmlString b = "Hello";
			TiXmlString c = "ooga";

			c = " World!";
			a = b;
			a += c;
			a = a;

			XmlTest( "Basic TiXmlString test. ", "Hello World!", a.c_str() );
		#endif
 	}

	// Long filenames crashing STL version
	{
		TiXmlDocument doc( "midsummerNightsDreamWithAVeryLongFilenameToConfuseTheStringHandlingRoutines.xml" );
		doc.LoadFile();
		// Won't pass on non-dev systems. Just a "no crash" check.
		//XmlTest( "Long filename. ", true, loadOkay );
	}

	{
		// Entities not being written correctly.
		// From Lynn Allen

		const char* passages =
			"<?xml version=\"1.0\" standalone=\"no\" ?>"
			"<passages count=\"006\" formatversion=\"20020620\">"
				"<psg context=\"Line 5 has &quot;quotation marks&quot; and &apos;apostrophe marks&apos;."
				" It also has &lt;, &gt;, and &amp;, as well as a fake &#xA9;.\"> </psg>"
			"</passages>";

		TiXmlDocument doc( "passages.xml" );
		doc.Parse( passages );
		TiXmlElement* psg = doc.RootElement()->FirstChildElement();
		const char* context = psg->Attribute( "context" );

		XmlTest( "Entity transformation: read. ",
					"Line 5 has \"quotation marks\" and 'apostrophe marks'."
					" It also has <, >, and &, as well as a fake \xA9.",
					context,
					true );

		FILE* textfile = fopen( "textfile.txt", "w" );
		if ( textfile )
		{
			psg->Print( textfile, 0 );
			fclose( textfile );
		}
		textfile = fopen( "textfile.txt", "r" );
		assert( textfile );
		if ( textfile )
		{
			char buf[ 1024 ];
			fgets( buf, 1024, textfile );
			XmlTest( "Entity transformation: write. ",
					 "<psg context=\'Line 5 has &quot;quotation marks&quot; and &apos;apostrophe marks&apos;."
					 " It also has &lt;, &gt;, and &amp;, as well as a fake &#xA9;.' />",
					 buf,
					 true );
		}
		fclose( textfile );
	}

    {
		FILE* textfile = fopen( "test5.xml", "w" );
		if ( textfile )
		{
            fputs("<?xml version='1.0'?><a.elem xmi.version='2.0'/>", textfile);
            fclose(textfile);

			TiXmlDocument doc;
            doc.LoadFile( "test5.xml" );
            XmlTest( "dot in element attributes and names", doc.Error(), 0);
		}
    }

	{
		FILE* textfile = fopen( "test6.xml", "w" );
		if ( textfile )
		{
            fputs("<element><Name>1.1 Start easy ignore fin thickness&#xA;</Name></element>", textfile );
            fclose(textfile);

            TiXmlDocument doc;
            bool result = doc.LoadFile( "test6.xml" );
            XmlTest( "Entity with one digit.", result, true );

			TiXmlText* text = doc.FirstChildElement()->FirstChildElement()->FirstChild()->ToText();
			XmlTest( "Entity with one digit.",
						text->Value(), "1.1 Start easy ignore fin thickness\n" );
		}
    }


	#if defined( WIN32 ) && defined( TUNE )
	QueryPerformanceCounter( (LARGE_INTEGER*) (&end) );
	QueryPerformanceFrequency( (LARGE_INTEGER*) (&freq) );
	printf( "Time for run: %f\n", ( double )( end-start ) / (double) freq );
	#endif

	printf ("\nPass %d, Fail %d\n", gPass, gFail);
	return gFail;
}
示例#5
0
KmlPastebufferType Kml::ParsePasteBuffer() {
    if( !wxTheClipboard->IsOpened() )
        if( ! wxTheClipboard->Open() ) return KML_PASTE_INVALID;

    wxTextDataObject data;
    wxTheClipboard->GetData( data );
    kmlText = data.GetText();
    wxTheClipboard->Close();

    if( kmlText.Find( _T("<kml") ) == wxNOT_FOUND ) return KML_PASTE_INVALID;

    TiXmlDocument doc;
    if( ! doc.Parse( kmlText.mb_str( wxConvUTF8 ), 0, TIXML_ENCODING_UTF8 ) ) {
		wxLogError( wxString( doc.ErrorDesc(), wxConvUTF8 ) );
		return KML_PASTE_INVALID;
	}
    if( 0 != strncmp( doc.RootElement()->Value(), "kml", 3 ) ) return KML_PASTE_INVALID;

    TiXmlHandle docHandle( doc.RootElement() );

	// We may or may not have a <document> depending on what the user copied.
    TiXmlElement* placemark = docHandle.FirstChild( "Document" ).FirstChild( "Placemark" ).ToElement();
    if( ! placemark ) {
        placemark = docHandle.FirstChild( "Placemark" ).ToElement();
	}
    if( ! placemark ) {
        wxString msg( _T("KML Parser found no <Placemark> tag in the KML.") );
        wxLogMessage( msg );
        return KML_PASTE_INVALID;
    }

    int pointCounter = 0;
    wxString name;
    for( ; placemark; placemark=placemark->NextSiblingElement() ) {
        TiXmlElement* e = placemark->FirstChildElement( "name" );
        if( e ) name = wxString( e->GetText(),wxConvUTF8 );
        pointCounter++;
    }

    if( pointCounter == 1 ) {

        // Is it a single waypoint?
        TiXmlNode* element = docHandle.FirstChild( "Document" ).FirstChild( "Placemark" ).FirstChild( "Point" ).ToNode();
        if( ! element ) element = docHandle.FirstChild( "Placemark" ).FirstChild( "Point" ).ToNode();
        if( element ) return ParseOnePlacemarkPoint( element, name );

        // Is it a dumb <LineString> track?
        element = docHandle.FirstChild( "Document" ).FirstChild( "Placemark" ).FirstChild( "LineString" ).ToNode();
        if( ! element ) element = docHandle.FirstChild( "Placemark" ).FirstChild( "LineString" ).ToNode();
        if( element ) return ParseTrack( element, name );

        // Is it a smart extended <gx:track> track?
        element = docHandle.FirstChild( "Document" ).FirstChild( "Placemark" ).FirstChild( "gx:Track" ).ToNode();
        if( ! element ) element = docHandle.FirstChild( "Placemark" ).FirstChild( "gx:Track" ).ToNode();
        if( element ) return ParseTrack( element, name );

        wxString msg( _T("KML Parser found a single <Placemark> in the KML, but no useable data in it.") );
        wxLogMessage( msg );
        return KML_PASTE_INVALID;
    }

    // Here we go with a full route.

    parsedRoute = new Route();
    bool foundPoints = false;
    bool foundTrack = false;
    TiXmlElement* element = docHandle.FirstChild( "Document" ).FirstChild( "name" ).ToElement();
    if( element )
        parsedRoute->m_RouteNameString = wxString( element->GetText(), wxConvUTF8 );

    RoutePoint* rp = NULL;
    placemark = docHandle.FirstChild( "Document" ).FirstChild( "Placemark" ).ToElement();
    for( ; placemark; placemark=placemark->NextSiblingElement() ) {

        TiXmlNode* n = placemark->FirstChild( "Point" );
        if( n ) {
            if( ParseOnePlacemarkPoint( n->ToElement(), name ) == KML_PASTE_WAYPOINT ) {
                parsedRoute->AddPoint( new RoutePoint( parsedRoutePoint ) );
                delete parsedRoutePoint;
                parsedRoutePoint = 0;
                foundPoints = true;
            }
        }

        n = placemark->FirstChild( "LineString" );
        if( n ) {
            ParseTrack( n->ToElement(), name );
            foundTrack = true;
        }
        n = placemark->FirstChild( "gx:Track" );
        if( n ) {
            ParseTrack( n->ToElement(), name );
            foundTrack = true;
        }
    }

    if( foundPoints && parsedRoute->GetnPoints() < 2 ) {
        wxString msg( _T("KML Parser did not find enough <Point>s to make a route.") );
        wxLogMessage( msg );
        foundPoints = false;
    }

    if( foundPoints && ! foundTrack ) return KML_PASTE_ROUTE;
    if( foundPoints && foundTrack ) return KML_PASTE_ROUTE_TRACK;
    if( ! foundPoints && foundTrack ) return KML_PASTE_TRACK;
    return KML_PASTE_INVALID;
}
示例#6
0
bool CMediaSettings::Save(TiXmlNode *settings) const
{
  if (settings == NULL)
    return false;

  CSingleLock lock(m_critical);
  // default video settings
  TiXmlElement videoSettingsNode("defaultvideosettings");
  TiXmlNode *pNode = settings->InsertEndChild(videoSettingsNode);
  if (pNode == NULL)
    return false;

  XMLUtils::SetInt(pNode, "deinterlacemode", m_defaultVideoSettings.m_DeinterlaceMode);
  XMLUtils::SetInt(pNode, "interlacemethod", m_defaultVideoSettings.m_InterlaceMethod);
  XMLUtils::SetInt(pNode, "scalingmethod", m_defaultVideoSettings.m_ScalingMethod);
  XMLUtils::SetFloat(pNode, "noisereduction", m_defaultVideoSettings.m_NoiseReduction);
  XMLUtils::SetBoolean(pNode, "postprocess", m_defaultVideoSettings.m_PostProcess);
  XMLUtils::SetFloat(pNode, "sharpness", m_defaultVideoSettings.m_Sharpness);
  XMLUtils::SetInt(pNode, "viewmode", m_defaultVideoSettings.m_ViewMode);
  XMLUtils::SetFloat(pNode, "zoomamount", m_defaultVideoSettings.m_CustomZoomAmount);
  XMLUtils::SetFloat(pNode, "pixelratio", m_defaultVideoSettings.m_CustomPixelRatio);
  XMLUtils::SetFloat(pNode, "verticalshift", m_defaultVideoSettings.m_CustomVerticalShift);
  XMLUtils::SetFloat(pNode, "volumeamplification", m_defaultVideoSettings.m_VolumeAmplification);
  XMLUtils::SetBoolean(pNode, "outputtoallspeakers", m_defaultVideoSettings.m_OutputToAllSpeakers);
  XMLUtils::SetBoolean(pNode, "showsubtitles", m_defaultVideoSettings.m_SubtitleOn);
  XMLUtils::SetFloat(pNode, "brightness", m_defaultVideoSettings.m_Brightness);
  XMLUtils::SetFloat(pNode, "contrast", m_defaultVideoSettings.m_Contrast);
  XMLUtils::SetFloat(pNode, "gamma", m_defaultVideoSettings.m_Gamma);
  XMLUtils::SetFloat(pNode, "audiodelay", m_defaultVideoSettings.m_AudioDelay);
  XMLUtils::SetFloat(pNode, "subtitledelay", m_defaultVideoSettings.m_SubtitleDelay);
  XMLUtils::SetBoolean(pNode, "autocrop", m_defaultVideoSettings.m_Crop); 
  XMLUtils::SetBoolean(pNode, "nonlinstretch", m_defaultVideoSettings.m_CustomNonLinStretch);

  // mymusic
  pNode = settings->FirstChild("mymusic");
  if (pNode == NULL)
  {
    TiXmlElement videosNode("mymusic");
    pNode = settings->InsertEndChild(videosNode);
    if (pNode == NULL)
      return false;
  }

  TiXmlElement musicPlaylistNode("playlist");
  TiXmlNode *playlistNode = pNode->InsertEndChild(musicPlaylistNode);
  if (playlistNode == NULL)
    return false;
  XMLUtils::SetBoolean(playlistNode, "repeat", m_musicPlaylistRepeat);
  XMLUtils::SetBoolean(playlistNode, "shuffle", m_musicPlaylistShuffle);

  XMLUtils::SetInt(pNode, "needsupdate", m_musicNeedsUpdate);

  // myvideos
  pNode = settings->FirstChild("myvideos");
  if (pNode == NULL)
  {
    TiXmlElement videosNode("myvideos");
    pNode = settings->InsertEndChild(videosNode);
    if (pNode == NULL)
      return false;
  }

  XMLUtils::SetInt(pNode, "watchmodemovies", m_watchedModes.find("movies")->second);
  XMLUtils::SetInt(pNode, "watchmodetvshows", m_watchedModes.find("tvshows")->second);
  XMLUtils::SetInt(pNode, "watchmodemusicvideos", m_watchedModes.find("musicvideos")->second);

  TiXmlElement videoPlaylistNode("playlist");
  playlistNode = pNode->InsertEndChild(videoPlaylistNode);
  if (playlistNode == NULL)
    return false;
  XMLUtils::SetBoolean(playlistNode, "repeat", m_videoPlaylistRepeat);
  XMLUtils::SetBoolean(playlistNode, "shuffle", m_videoPlaylistShuffle);

  XMLUtils::SetInt(pNode, "needsupdate", m_videoNeedsUpdate);

  return true;
}
bool AutoCompletion::setLanguage(LangType language) {
	if (_curLang == language)
		return true;
	_curLang = language;

	TCHAR path[MAX_PATH];
	::GetModuleFileName(NULL, path, MAX_PATH);
	PathRemoveFileSpec(path);
	lstrcat(path, TEXT("\\plugins\\APIs\\"));
	lstrcat(path, getApiFileName());
	lstrcat(path, TEXT(".xml"));

	if (_pXmlFile)
		delete _pXmlFile;

	_pXmlFile = new TiXmlDocument(path);
	_funcCompletionActive = _pXmlFile->LoadFile();

	TiXmlNode * pAutoNode = NULL;
	if (_funcCompletionActive) {
		_funcCompletionActive = false;	//safety
		TiXmlNode * pNode = _pXmlFile->FirstChild(TEXT("NotepadPlus"));
		if (!pNode)
			return false;
		pAutoNode = pNode = pNode->FirstChildElement(TEXT("AutoComplete"));
		if (!pNode)
			return false;
		pNode = pNode->FirstChildElement(TEXT("KeyWord"));
		if (!pNode)
			return false;
		_pXmlKeyword = reinterpret_cast<TiXmlElement *>(pNode);
		if (!_pXmlKeyword)
			return false;
		_funcCompletionActive = true;
	}

	if(_funcCompletionActive) //try setting up environment
    {
		//setup defaults
		_ignoreCase = true;
		_funcCalltip._start = '(';
		_funcCalltip._stop = ')';
		_funcCalltip._param = ',';
		_funcCalltip._terminal = ';';
		_funcCalltip._ignoreCase = true;
        _funcCalltip._additionalWordChar.clear();

		TiXmlElement * pElem = pAutoNode->FirstChildElement(TEXT("Environment"));
		if (pElem)
        {
			const TCHAR * val = 0;
			val = pElem->Attribute(TEXT("ignoreCase"));
			if (val && !lstrcmp(val, TEXT("no"))) {
				_ignoreCase = false;
				_funcCalltip._ignoreCase = false;
			}
			val = pElem->Attribute(TEXT("startFunc"));
			if (val && val[0])
				_funcCalltip._start = val[0];
			val = pElem->Attribute(TEXT("stopFunc"));
			if (val && val[0])
				_funcCalltip._stop = val[0];
			val = pElem->Attribute(TEXT("paramSeparator"));
			if (val && val[0])
				_funcCalltip._param = val[0];
			val = pElem->Attribute(TEXT("terminal"));
			if (val && val[0])
				_funcCalltip._terminal = val[0];
			val = pElem->Attribute(TEXT("additionalWordChar"));
			if (val && val[0])
                _funcCalltip._additionalWordChar = val;
		}
	}

	if (_funcCompletionActive) {
		_funcCalltip.setLanguageXML(_pXmlKeyword);
	} else {
		_funcCalltip.setLanguageXML(NULL);
	}

	_keyWords.clear();
	_keyWordArray.clear();

	if (_funcCompletionActive)
	{
		//Cache the keywords
		//Iterate through all keywords
		TiXmlElement *funcNode = _pXmlKeyword;

		for (; funcNode; funcNode = funcNode->NextSiblingElement(TEXT("KeyWord")) )
		{
			const TCHAR *name = funcNode->Attribute(TEXT("name"));
			if (name)
			{
				size_t len = lstrlen(name);
				if (len)
				{
					_keyWordArray.push_back(name);
					if (len > _keyWordMaxLen)
						_keyWordMaxLen = len;
				}
			}
		}

		sort(_keyWordArray.begin(), _keyWordArray.end());

		for (size_t i = 0, len = _keyWordArray.size(); i < len; ++i)
		{
			_keyWords.append(_keyWordArray[i]);
			_keyWords.append(TEXT(" "));
		}
	}
	return _funcCompletionActive;
}
示例#8
0
//修改结点struNote。或返回结点struNode的值
bool CSimpleXml::AccessXmlNode( XMLNODEINFO &struNote, int nType)
{
    int nEnd = 0;
    if(m_pDoc == NULL || m_pRoot == NULL)
    {
        return false;
    }
    TiXmlText* pText = NULL; // 一个指向Text的指针
    pText = new TiXmlText(struNote.strData.c_str()) ;
    string strNodeName = struNote.strNodeName;
    nEnd = strNodeName.find("/");
    string strNode = strNodeName.substr(0, nEnd);
    strNodeName = strNodeName.substr(nEnd + 1, strNodeName.length() - nEnd);

    TiXmlNode *node = m_pRoot;
    TiXmlNode *destnode = NULL;
    while(node)
    {
        string strchildnode = node->Value();
        if(strNode != strchildnode)
        {
            node = node->NextSibling();
            continue;//此子结点非我们要的子结点,跳到下一个子结点
        }
        if((strNode == strNodeName) && (strNode == node->Value()))//Node就是我们访问的结点。
        {
            destnode = node->FirstChild();
            if(destnode && destnode->Type() == TiXmlNode::TEXT)//是叶子结点,修改为我们的值
            {
                if(nType == QUERY)
                {
                    struNote.strData = destnode->Value();//查询结点的值
                }
                else
                {
                    destnode->SetValue(struNote.strData.c_str());//修改为我们的值
                }
            }
            else if(destnode && destnode->Type() == TiXmlNode::ELEMENT)//不是叶子结点,加上我们的值
            {
                node->InsertBeforeChild(destnode, *pText);
            }
            else if(!destnode)//要写的结点原值为空,加上我们的值
            {
                node->InsertEndChild(*pText);
            }
            return true;
        }
        node = node->FirstChild();//Node不是我们访问的结点,开始遍历Node的子结点
        nEnd = strNodeName.find("/");
        strNode = strNodeName.substr(0, nEnd);
        strNodeName = strNodeName.substr(nEnd + 1, strNodeName.length() - nEnd);
        if(node && (strNode == strNodeName) && (strNode == node->Value()))//Node就是我们访问的结点
        {
            destnode = node->FirstChild();
            if(destnode && destnode->Type() == TiXmlNode::TEXT)//是叶子结点,加上我们的值
            {
                if(nType == QUERY)
                {
                    struNote.strData = destnode->Value();//查询结点的值
                }
                else
                {
                    destnode->SetValue(struNote.strData.c_str());//修改为我们的值
                }
            }
            else if(destnode && destnode->Type() == TiXmlNode::ELEMENT)//不是叶子结点,加上我们的值
            {
                node->InsertBeforeChild(destnode, *pText);
            }
            else if(!destnode)//要写的结点原值为空,加上我们的值
            {
                node->InsertEndChild(*pText);
            }
            return true;
        }
    }
    return false;
}
示例#9
0
文件: Lagom.cpp 项目: jaschmid/Lagom
void Lagom::loadSettings()
{
	_effectVolume = defaultSoundVolume;
	_musicVolume = defaultMusicVolume;
	_xResolution = defaultXResolution;
	_yResolution = defaultYResolution;
	_FSAA = defaultFSAA;
	_SSAO = defaultSSAO;
	_fullscreen = defaultFullscreen;
	_dataFile = defaultDataFile;
	_playerColor = defaultPlayerColor;
	_challengeStage = defaultChallengeStage;
	_endless = defaultEndlessMode;
	
	TiXmlDocument	settings(sConfigFilename);
	bool loadOkay = settings.LoadFile();
	if(!loadOkay)
	{
		saveSettings();
		return;
	}
	
	if(!TryReadBool(settings,sPropFullscreen,&_fullscreen))loadOkay=false;
	if(!TryReadBool(settings,sPropEndlessMode,&_endless))loadOkay=false;
	if(!TryReadBool(settings,sPropSSAO,&_SSAO))loadOkay=false;
	if(!TryReadInt(settings,sPropFSAA,&_FSAA))loadOkay=false;
	if(!TryReadInt(settings,sPropXResolution,&_xResolution))loadOkay=false;
	if(!TryReadInt(settings,sPropYResolution,&_yResolution))loadOkay=false;
	if(!TryReadFloat(settings,sPropSoundVolume,&_effectVolume))loadOkay=false;
	if(!TryReadFloat(settings,sPropMusicVolume,&_musicVolume))loadOkay=false;
	if(!TryReadString(settings,sPropDataFile,&_dataFile))loadOkay=false;
	if(!TryReadString(settings,sPropDataFile,&_dataFile))loadOkay=false;
	if(!TryReadColourValue(settings,sPropPlayerColor,&_playerColor))loadOkay=false;
	if(!TryReadInt(settings,sPropChallengeStage,&_challengeStage))loadOkay=false;

	//load highscores
	TiXmlNode* highScoresNode = settings.RootElement()->FirstChild(sPropHighScores);

	if(!highScoresNode)
		loadOkay=false;
	else
	{
		_highScores.clear();

		TiXmlNode* highScore = highScoresNode->FirstChild(sPropHighScoresEntry);
		while(highScore && _highScores.size() < MaxNumHighScores )
		{
			TiXmlElement* highScoreElement = highScore->ToElement();
			if(highScoreElement)
			{
				bool bEntryOk = true;
				HighScoreEntry entry;
				if(!highScoreElement->Attribute(sPropHighScoresScore,&entry._score))bEntryOk=false;
				if(!highScoreElement->Attribute(sPropHighScoresStage,&entry._stage))bEntryOk=false;

				const std::string* pstr= highScoreElement->Attribute(std::string(sPropHighScoresName));

				if(pstr == nullptr)
					bEntryOk=false;
				else 
					entry._name = *pstr;

				if(bEntryOk)
					_highScores.insert(entry);
				else
					loadOkay=false;
			}
			highScore = highScore->NextSibling(sPropHighScoresEntry);
		}
	}

	_playerColor.a = 1.0f;

	if(!loadOkay)
		saveSettings();

	return;
}
示例#10
0
bool CDAVDirectory::GetDirectory(const CStdString& strPath, CFileItemList &items)
{
  CFileCurl dav;
  CURL url(strPath);
  CStdString strRequest = "PROPFIND";

  dav.SetCustomRequest(strRequest);
  dav.SetMimeType("text/xml; charset=\"utf-8\"");
  dav.SetRequestHeader("depth", 1);
  dav.SetPostData(
    "<?xml version=\"1.0\" encoding=\"utf-8\" ?>"
    " <D:propfind xmlns:D=\"DAV:\">"
    "   <D:prop>"
    "     <D:resourcetype/>"
    "     <D:getcontentlength/>"
    "     <D:getlastmodified/>"
    "     <D:creationdate/>"
    "     <D:displayname/>"
    "    </D:prop>"
    "  </D:propfind>");

  if (!dav.Open(url))
  {
    CLog::Log(LOGERROR, "%s - Unable to get dav directory (%s)", __FUNCTION__, strPath.c_str());
    return false;
  }

  char buffer[MAX_PATH + 1024];
  CStdString strResponse;
  CStdString strHeader;
  while (dav.ReadString(buffer, sizeof(buffer)))
  {
    if (strstr(buffer, "<D:response") != NULL)
    {
      // The header should contain the xml version/utf encoding line
      // followed by the <multistatus> tag
      if (strHeader.IsEmpty())
        strHeader = strResponse;
      
      strResponse = strHeader;
    }
    strResponse.append(buffer, strlen(buffer));

    if (strstr(buffer, "</D:response") != NULL)
    {
      // Close the multistatus tag from the header
      if (strHeader.Find("<D:multistatus"))
        strResponse+="</D:multistatus>\n";
      
      TiXmlDocument davResponse;

      if (!davResponse.Parse(strResponse))
      {
        CLog::Log(LOGERROR, "%s - Unable to process dav directory (%s)", __FUNCTION__, strPath.c_str());
        dav.Close();
        return false;
      }

      TiXmlNode *pChild;
      // Iterate over all responses
      for (pChild = davResponse.RootElement()->FirstChild(); pChild != 0; pChild = pChild->NextSibling())
      {
        if (ValueWithoutNamespace(pChild, "response"))
        {
          CFileItem item;
          ParseResponse(pChild->ToElement(), item);
          CURL url2(strPath);
          CURL url3(item.m_strPath);

          URIUtils::AddFileToFolder(url2.GetWithoutFilename(), url3.GetFileName(), item.m_strPath);

          if (item.GetLabel().IsEmpty())
          {
            CStdString name(item.m_strPath);
            URIUtils::RemoveSlashAtEnd(name);
            CURL::Decode(name);
            item.SetLabel(URIUtils::GetFileName(name));
          }

          if (item.m_bIsFolder)
            URIUtils::AddSlashAtEnd(item.m_strPath);

          // Add back protocol options
          if (!url2.GetProtocolOptions().IsEmpty())
            item.m_strPath += "|" + url2.GetProtocolOptions();

          if (!item.m_strPath.Equals(strPath))
          {
            CFileItemPtr pItem(new CFileItem(item));
            items.Add(pItem);
          }
        }
      }
      strResponse.clear();
    }
  }

  dav.Close();

  return true;
}
示例#11
0
// 将指定节点下的节点装入map,strNode只支持第一层
void CSimpleXml::GetSpecifyNode(const string &strNode, map<string, string> &mapNode, TiXmlNode *begin/* = NULL*/)
{
    TiXmlNode *node = NULL;
    if (NULL == begin)
    {
        node = m_pRoot;
    }
    else
    {
        node = begin;
    }

    while(NULL != node)
    {
        if (strNode == node->Value())
        {
            TiXmlNode *destnode = node->FirstChild();
            while (NULL != destnode)
            {
                if(destnode->Type() == TiXmlNode::ELEMENT)
                {
                    string strKey = destnode->Value();
                    TiXmlNode *nodechild = destnode->FirstChild();
                    if (NULL != nodechild)
                    {
                        if (NULL != nodechild->FirstChild())
                        {
                            while (NULL != nodechild)
                            {
                                TiXmlNode *grandson = nodechild->FirstChild();
                                string strKey = nodechild->Value();
                                if (NULL != grandson)
                                {
                                    mapNode.insert(make_pair(strKey, grandson->Value()));
                                }

                                nodechild = nodechild->NextSibling();
                            }

                        }
                        else
                        {
                            mapNode.insert(make_pair(strKey, nodechild->Value()));
                        }
                    }
                }
                destnode = destnode->NextSibling();
            }
        }
        node = node->NextSibling();
    }
}
示例#12
0
void ToolBar::initTheme(TiXmlDocument *toolIconsDocRoot)
{
    _toolIcons =  toolIconsDocRoot->FirstChild(TEXT("NotepadPlus"));
	if (_toolIcons)
	{
		_toolIcons = _toolIcons->FirstChild(TEXT("ToolBarIcons"));
		if (_toolIcons)
		{
			_toolIcons = _toolIcons->FirstChild(TEXT("Theme"));
			if (_toolIcons)
			{
				const TCHAR *themeDir = (_toolIcons->ToElement())->Attribute(TEXT("pathPrefix"));

				for (TiXmlNode *childNode = _toolIcons->FirstChildElement(TEXT("Icon"));
					 childNode ;
					 childNode = childNode->NextSibling(TEXT("Icon")))
				{
					int iIcon;
					const TCHAR *res = (childNode->ToElement())->Attribute(TEXT("id"), &iIcon);
					if (res)
					{
						TiXmlNode *grandChildNode = childNode->FirstChildElement(TEXT("normal"));
						if (grandChildNode)
						{
							TiXmlNode *valueNode = grandChildNode->FirstChild();
							//putain, enfin!!!
							if (valueNode)
							{
								generic_string locator = themeDir?themeDir:TEXT("");
								
								locator += valueNode->Value();
								_customIconVect.push_back(iconLocator(0, iIcon, locator));
							}
						}

						grandChildNode = childNode->FirstChildElement(TEXT("hover"));
						if (grandChildNode)
						{
							TiXmlNode *valueNode = grandChildNode->FirstChild();
							//putain, enfin!!!
							if (valueNode)
							{
								generic_string locator = themeDir?themeDir:TEXT("");
								
								locator += valueNode->Value();
								_customIconVect.push_back(iconLocator(1, iIcon, locator));
							}
						}

						grandChildNode = childNode->FirstChildElement(TEXT("disabled"));
						if (grandChildNode)
						{
							TiXmlNode *valueNode = grandChildNode->FirstChild();
							//putain, enfin!!!
							if (valueNode)
							{
								generic_string locator = themeDir?themeDir:TEXT("");
								
								locator += valueNode->Value();
								_customIconVect.push_back(iconLocator(2, iIcon, locator));
							}
						}
					}
				}
			}
		}
	}
}
示例#13
0
bool CLastFmManager::RequestRadioTracks()
{
  unsigned int start = XbmcThreads::SystemClockMillis();
  CStdString url;
  CStdString html;
  url.Format("http://" + m_RadioBaseUrl + m_RadioBasePath + "/xspf.php?sk=%s&discovery=0&desktop=", m_RadioSession);
  {
    CFileCurl http;
    if (!http.Get(url, html))
    {
      m_RadioSession.empty();
      CLog::Log(LOGERROR, "LastFmManager: Connect to Last.fm to request tracks failed.");
      return false;
    }
  }
  //CLog::Log(LOGDEBUG, "RequestRadioTracks: %s", html.c_str());

  //parse playlist
  CXBMCTinyXML xmlDoc;

  xmlDoc.Parse(html);
  if (xmlDoc.Error())
  {
    m_RadioSession.empty();
    CLog::Log(LOGERROR, "LastFmManager: Unable to parse tracklist Error: %s", xmlDoc.ErrorDesc());
    return false;
  }

  TiXmlElement* pRootElement = xmlDoc.RootElement();
  if (!pRootElement )
  {
    CLog::Log(LOGWARNING, "LastFmManager: No more tracks received");
    m_RadioSession.empty();
    return false;
  }

  TiXmlElement* pBodyElement = pRootElement->FirstChildElement("trackList");
  if (!pBodyElement )
  {
    CLog::Log(LOGWARNING, "LastFmManager: No more tracks received, no tracklist");
    m_RadioSession.empty();
    return false;
  }

  TiXmlElement* pTrackElement = pBodyElement->FirstChildElement("track");

  if (!pTrackElement)
  {
    CLog::Log(LOGWARNING, "LastFmManager: No more tracks received, empty tracklist");
    m_RadioSession.empty();
    return false;
  }
  while (pTrackElement)
  {
    CFileItemPtr newItem(new CFileItem);

    TiXmlElement* pElement = pTrackElement->FirstChildElement("location");
    if (pElement)
    {
      TiXmlNode* child = pElement->FirstChild();
      if (child)
      {
        CStdString url = child->Value();
        url.Replace("http:", "lastfm:");
        newItem->SetPath(url);
      }
    }
    pElement = pTrackElement->FirstChildElement("title");
    if (pElement)
    {
      TiXmlNode* child = pElement->FirstChild();
      if (child)
      {
        newItem->SetLabel(child->Value());
        newItem->GetMusicInfoTag()->SetTitle(child->Value());
      }
    }
    pElement = pTrackElement->FirstChildElement("creator");
    if (pElement)
    {
      TiXmlNode* child = pElement->FirstChild();
      if (child)
      {
        newItem->GetMusicInfoTag()->SetArtist(child->Value());
      }
    }
    pElement = pTrackElement->FirstChildElement("album");
    if (pElement)
    {
      TiXmlNode* child = pElement->FirstChild();
      if (child)
      {
        newItem->GetMusicInfoTag()->SetAlbum(child->Value());
      }
    }

    pElement = pTrackElement->FirstChildElement("duration");
    if (pElement)
    {
      TiXmlNode* child = pElement->FirstChild();
      if (child)
      {
        int iDuration = atoi(child->Value())/1000;
        newItem->GetMusicInfoTag()->SetDuration(iDuration);
      }
    }
    newItem->FillInDefaultIcon();
    pElement = pTrackElement->FirstChildElement("image");
    if (pElement)
    {
      TiXmlNode* child = pElement->FirstChild();
      if (child)
      {
        CStdString coverUrl = child->Value();
        if ((coverUrl != "") && (coverUrl.Find("noimage") == -1) && (coverUrl.Right(1) != "/"))
        {
          newItem->SetThumbnailImage(coverUrl);
        }
      }
    }
    //trackauth is needed for validating the track when scrobbling
    pElement = pTrackElement->FirstChildElement("lastfm:trackauth");
    if (pElement)
    {
      TiXmlNode* child = pElement->FirstChild();
      if (child)
      {
        CStdString trackAuth = child->Value();
        //abuse comment field for the track authcode
        newItem->GetMusicInfoTag()->SetComment(trackAuth);
      }
    }

    {
      CSingleLock lock(m_lockCache);
      m_RadioTrackQueue->Add(newItem);
    }
    pTrackElement = pTrackElement->NextSiblingElement();
  }
  //end parse
  CSingleLock lock(m_lockCache);
  int iNrCachedTracks = m_RadioTrackQueue->size();
  CLog::Log(LOGDEBUG, "%s: Done (time: %i ms)", __FUNCTION__, (int)(XbmcThreads::SystemClockMillis() - start));
  return iNrCachedTracks > 0;
}
示例#14
0
        void MeshGraph2D::ReadEdges(TiXmlDocument &doc)
        {
            /// We know we have it since we made it this far.
            TiXmlHandle docHandle(&doc);
            TiXmlElement* mesh = docHandle.FirstChildElement("NEKTAR").FirstChildElement("GEOMETRY").Element();
            TiXmlElement* field = NULL;

            /// Look for elements in ELEMENT block.
            field = mesh->FirstChildElement("EDGE");

            ASSERTL0(field, "Unable to find EDGE tag in file.");

            /// All elements are of the form: "<E ID="#"> ... </E>", with
            /// ? being the element type.
            /// Read the ID field first.
            TiXmlElement *edge = field->FirstChildElement("E");

            /// Since all edge data is one big text block, we need to
            /// accumulate all TEXT data and then parse it.  This
            /// approach effectively skips all comments or other node
            /// types since we only care about the edge list.  We
            /// cannot handle missing edge numbers as we could with
            /// missing element numbers due to the text block format.
            std::string edgeStr;
            int i,indx;
            int nextEdgeNumber = -1;

            // Curved Edges
            map<int, int> edge_curved;
            for(i = 0; i < m_curvedEdges.size(); ++i)
            {
                edge_curved[m_curvedEdges[i]->m_curveID] = i;
            }

            while(edge)
            {
                nextEdgeNumber++;

                int err = edge->QueryIntAttribute("ID",&indx);
                ASSERTL0(err == TIXML_SUCCESS, "Unable to read edge attribute ID.");
//                ASSERTL0(indx == nextEdgeNumber, "Edge IDs must begin with zero and be sequential.");

                TiXmlNode *child = edge->FirstChild();
                edgeStr.clear();
                if (child->Type() == TiXmlNode::TEXT)
                {
                    edgeStr += child->ToText()->ValueStr();
                }

                /// Now parse out the edges, three fields at a time.
                int vertex1, vertex2;
                std::istringstream edgeDataStrm(edgeStr.c_str());

                try
                {
                    while (!edgeDataStrm.fail())
                    {
                        edgeDataStrm >> vertex1 >> vertex2;

                        // Must check after the read because we may be
                        // at the end and not know it.  If we are at
                        // the end we will add a duplicate of the last
                        // entry if we don't check here.
                        if (!edgeDataStrm.fail())
                        {
                            PointGeomSharedPtr vertices[2] = {GetVertex(vertex1), GetVertex(vertex2)};

                            SegGeomSharedPtr edge;

                            if(edge_curved.count(indx) == 0)
                            {
                                edge = MemoryManager<SegGeom>::AllocateSharedPtr(indx, m_spaceDimension, vertices);
                                edge->SetGlobalID(indx); // Set global mesh id
                            }
                            else
                            {
                                edge = MemoryManager<SegGeom>::AllocateSharedPtr(indx, m_spaceDimension, vertices, m_curvedEdges[edge_curved.find(indx)->second]);
                                edge->SetGlobalID(indx); //Set global mesh id
                            }

                            m_segGeoms[indx] = edge;
                        }
                    }
                }
                catch(...)
                {
                    NEKERROR(ErrorUtil::efatal, (std::string("Unable to read edge data: ") + edgeStr).c_str());
                }

                edge = edge->NextSiblingElement("E");
            }

        }
示例#15
0
bool CSettings::Open(CString strPath, bool bCreate, bool bSave, bool bClient)
{
	// Flag we are not allowed to save the file by default
	m_bSave = false;

	// Load the default settings
	LoadDefaults(bClient);

	// Does the settings file not exist?
	bool bExists = true;

	if(!SharedUtility::Exists(strPath.Get()))
	{
		if(!bCreate)
		{
			CLogFile::Printf("ERROR: Settings file %s does not exist.", strPath.Get());
			return false;
		}
		else
		{
			CLogFile::Printf("WARNING: Settings file %s does not exist, it will now be created.", strPath.Get());

			// Attempt to open the file for write
			FILE * fFile = fopen(strPath.Get(), "w");

			// Ensure the file was opened
			if(!fFile)
			{
				CLogFile::Printf("WARNING: Failed to create settings file %s, no settings will be loaded or saved.", strPath.Get());

				// Flag the settings file as does not exist
				bExists = false;
			}
			else
			{
				// Write the default contents to the file
				fprintf(fFile, "<settings />");

				// Close the file
				fclose(fFile);
			}
		}
	}

	// Load the settings file
	if(bExists)
	{
		// Attempt to load the XML file
		if(m_XMLDocument.LoadFile(strPath.Get()))
		{
			// Flag ourselves as open
			m_bOpen = true;

			// Loop through all XML nodes
			for(TiXmlNode * pNode = m_XMLDocument.RootElement()->FirstChildElement(); pNode; pNode = pNode->NextSibling())
			{
				// Is this not an element node?
				if(pNode->Type() != TiXmlNode::ELEMENT)
					continue;

				// Get the setting and value
				CString strSetting = pNode->Value();
				CString strValue = pNode->ToElement()->GetText();

				// Does the setting not exist?
				if(!Exists(strSetting))
					CLogFile::Printf("WARNING: Log file setting %s does not exist.", strSetting.Get());
				else
					SetEx(strSetting, strValue);
			}

			// Flag if we are allowed to save the file
			m_bSave = bSave;

			// Save the XML file
			Save();
		}
		else
		{
			if(bCreate)
			{
				CLogFile::Printf("ERROR: Failed to open settings file %s.", strPath.Get());
				return false;
			}
			else
				CLogFile::Printf("WARNING: Failed to open settings file %s, no settings will be loaded or saved.", strPath.Get());
		}
	}

	return true;
}
示例#16
0
bool ParserMessageXML::_Parser(TiXmlDocument& xmlTiny)
{
    TiXmlElement* msg = xmlTiny.RootElement();
    std::string sRootName = msg->Value();
    if (sRootName != MsgDataObject_XML_Root)
    {
        return false;
    }
    TiXmlNode* msgNode = xmlTiny.FirstChild(MsgDataObject_XML_Root);
    if (msgNode == NULL)
    {
        return false;
    }
    for (msg = msgNode->FirstChildElement();
        msg != NULL;
        msg = msg->NextSiblingElement())
    {
        if (strcmp(msg->Value(),MsgDataObject_XML_Msg) == 0)
        {
            const char* pName = msg->Attribute(MsgDataObject_XML_Name);
            const char* pId = msg->Attribute(MsgDataObject_XML_Id);
            if (!pName || !pId)
            {
                continue;
            }
            int nId = atoi(pId);
            XMLObject objXML(pName, nId);
            m_MsgIdList[std::string(pName)] = nId;
            TiXmlNode* tmpNode = msg->FirstChild();
            if (tmpNode == NULL)
            {
                continue;
            }

            TiXmlElement* msgItem = NULL;
            for (msgItem = tmpNode->ToElement();
                msgItem != NULL;
                msgItem = msgItem->NextSiblingElement())
            {
                XMLItem ItemXML;
                if (msgItem->Attribute(MsgDataObject_XML_MType) != NULL)
                {
                    std::string strMType = msgItem->Attribute(MsgDataObject_XML_MType);
                    if (strMType == MsgDataMType_XML_Data)
                    {
                        ItemXML.SetMType(MsgDataMType_Data);
                    }
                    if (strMType == MsgDataMType_XML_List)
                    {
                        ItemXML.SetMType(MsgDataMType_List);
                    }
                }
                if (msgItem->Attribute(MsgDataObject_XML_Name) != NULL)
                {
                    ItemXML.SetName(msgItem->Attribute(MsgDataObject_XML_Name));
                }
                if (msgItem->Attribute(MsgDataObject_XML_Type) != NULL )
                {
                    std::string strType = msgItem->Attribute(MsgDataObject_XML_Type);
                    if (strType == MsgDataType_XML_Uint32)
                    {
                        ItemXML.SetType(MsgDataType_Uint32);
                    }
                    else if (strType == MsgDataType_XML_Uint16)
                    {
                        ItemXML.SetType(MsgDataType_Uint16);
                    }
                    else if (strType == MsgDataType_XML_Uint8)
                    {
                        ItemXML.SetType(MsgDataType_Uint8);
                    }
                    else if (strType == MsgDataType_XML_String)
                    {
                        ItemXML.SetType(MsgDataType_String);
                    }
                }
                objXML.SetItem(ItemXML.GetName(), ItemXML);
            }
            m_MsgObjectList.insert(std::make_pair(objXML.GetId(), objXML));
        }
    }
    return true;
}
示例#17
0
OsStatus
UserForwardDB::load()
{
    // Critical Section here
    OsLock lock( sLockMutex );
    OsStatus result = OS_SUCCESS;

    if ( m_pFastDB != NULL ) 
    {
        // Clean out the existing DB rows before loading
        // a new set from persistent storage
        removeAllRows ();

        UtlString fileName = mDatabaseName + ".xml";
        OsPath pathName = SipXecsService::Path(SipXecsService::DatabaseDirType,fileName.data());

        OsSysLog::add(FAC_DB, PRI_DEBUG, "UserForwardDB::load loading \"%s\"",
                    pathName.data());

        TiXmlDocument doc ( pathName );

        // Verify that we can load the file (i.e it must exist)
        if( doc.LoadFile() )
        {
            // the checksum is used to determine if the db changed between reloads
            int loadChecksum = 0;
            TiXmlNode * rootNode = doc.FirstChild ("items");
            if (rootNode != NULL)
            {
                // the folder node contains at least the name/displayname/
                // and autodelete elements, it may contain others
                for( TiXmlNode *itemNode = rootNode->FirstChild( "item" );
                     itemNode; 
                     itemNode = itemNode->NextSibling( "item" ) )
                {
                    // Create a hash dictionary for element attributes
                    UtlHashMap nvPairs;

                    for( TiXmlNode *elementNode = itemNode->FirstChild();
                         elementNode; 
                         elementNode = elementNode->NextSibling() )
                    {
                        // Bypass comments and other element types only interested
                        // in parsing element attributes
                        if ( elementNode->Type() == TiXmlNode::ELEMENT )
                        {
                            UtlString elementName = elementNode->Value();
                            UtlString elementValue;
                            result = SIPDBManager::getAttributeValue (
                                *itemNode, elementName, elementValue);
                            // update the load checksum
                            loadChecksum += ( elementName.hash() + elementValue.hash() );
                            if (result == OS_SUCCESS)
                            {
                                UtlString* collectableKey = 
                                    new UtlString( elementName ); 
                                UtlString* collectableValue = 
                                    new UtlString( elementValue ); 
                                nvPairs.insertKeyAndValue ( 
                                    collectableKey, collectableValue );
                            } else if ( elementNode->FirstChild() == NULL )
                            {
                                // NULL Element value create a special 
                                // char string we have key and value so insert
                                UtlString* collectableKey = 
                                    new UtlString( elementName ); 
                                UtlString* collectableValue = 
                                    new UtlString( SPECIAL_IMDB_NULL_VALUE ); 
                                nvPairs.insertKeyAndValue ( 
                                    collectableKey, collectableValue );
                            }
                        }
                    }
                    // Insert the item row into the IMDB
                    insertRow ( nvPairs );
                }
            }
        } else 
        {
            OsSysLog::add(FAC_DB, PRI_WARNING, "UserForwardDB::load failed to load \"%s\"",
                    pathName.data());
            result = OS_FAILED;
        }
    } else 
    {
        OsSysLog::add(FAC_DB, PRI_ERR, "UserForwardDB::load failed - no DB");
        result = OS_FAILED;
    }
    return result;
}
示例#18
0
Catoms2DSimulator::Catoms2DSimulator(int argc, char *argv[], Catoms2DBlockCode *(*catoms2DBlockCodeBuildingFunction)(Catoms2DBlock*)) : BaseSimulator::Simulator(argc, argv) {
	OUTPUT << "\033[1;34m" << "Catoms2DSimulator constructor" << "\033[0m" << endl;

	int currentID = 1;
	Catoms2DWorld *world = NULL;
	buildNewBlockCode = catoms2DBlockCodeBuildingFunction;
	float blockSize[3];

	testMode = false;

	/* reading the xml file */
	TiXmlNode *node = xmlDoc->FirstChild("world");
	if (node) {
		TiXmlElement* worldElement = node->ToElement();
		const char *attr= worldElement->Attribute("gridSize");
		int lx,ly,lz;
		if (attr) {
			string str=attr;
			int pos = str.find_first_of(',');
			lx = atoi(str.substr(0,pos).c_str());
			ly = 1;
			lz = atoi(str.substr(pos+1,str.length()-pos-1).c_str());
			OUTPUT << "grid size : " << lx << " x " << ly << " x " << lz << endl;
		} else {
			OUTPUT << "WARNING No grid size in XML file" << endl;
		}
		attr=worldElement->Attribute("windowSize");
		if (attr) {
			string str=attr;
	 		int pos = str.find_first_of(',');
			GlutContext::initialScreenWidth = atoi(str.substr(0,pos).c_str());
			GlutContext::initialScreenHeight = atoi(str.substr(pos+1,str.length()-pos-1).c_str());
			GlutContext::screenWidth = GlutContext::initialScreenWidth;
			GlutContext::screenHeight = GlutContext::initialScreenHeight;
		}

		createWorld(lx, ly, lz, argc, argv);
		world = getWorld();
		world->loadTextures("../../simulatorCore/catoms2DTextures");

	} else {
		ERRPUT << "ERROR : NO world in XML file" << endl;
		exit(1);
	}

	createScheduler();

	// loading the camera parameters
	TiXmlNode *nodeConfig = node->FirstChild("camera");
	if (nodeConfig) {
		TiXmlElement* cameraElement = nodeConfig->ToElement();
		const char *attr=cameraElement->Attribute("target");
		double def_near=1,def_far=1500;
		float angle=45.0;
		if (attr) {
			string str(attr);
			int pos = str.find_first_of(',');
			Vecteur target;
			target.pt[0] = atof(str.substr(0,pos).c_str());
			target.pt[1] = 1;
			target.pt[2] = atoi(str.substr(pos+1,str.length()-pos-1).c_str());
			world->getCamera()->setTarget(target);
		}
		attr=cameraElement->Attribute("angle");
		if (attr) {
			angle = atof(attr);
			world->getCamera()->setAngle(angle);
		}
		attr=cameraElement->Attribute("directionSpherical");
		if (attr) {
			string str(attr);
			int pos1 = str.find_first_of(','),
			pos2 = str.find_last_of(',');
			float az,ele,dist;
			az = -90.0+atof(str.substr(0,pos1).c_str());
			ele = atof(str.substr(pos1+1,pos2-pos1-1).c_str());
			dist = atof(str.substr(pos2+1,str.length()-pos1-1).c_str());
			world->getCamera()->setDirection(az,ele);
			world->getCamera()->setDistance(dist);
			az = dist*sin(angle*M_PI/180.0);
			def_near = dist-az;
			def_far = dist+az;
		}
		attr=cameraElement->Attribute("near");
		if (attr) {
			def_near = atof(attr);
		}
		attr=cameraElement->Attribute("far");
		if (attr) {
			def_far = atof(attr);
		}
		world->getCamera()->setNearFar(def_near,def_far);
	}

	// loading the spotlight parameters
	nodeConfig = node->FirstChild("spotlight");
	if (nodeConfig) {
		Vecteur target;
		float az=0,ele=60,dist=1000,angle=50;
		TiXmlElement* lightElement = nodeConfig->ToElement();
		const char *attr=lightElement->Attribute("target");
		if (attr) {
			string str(attr);
			int pos1 = str.find_first_of(','),
			pos2 = str.find_last_of(',');
			target.pt[0] = atof(str.substr(0,pos1).c_str());
			target.pt[1] = atof(str.substr(pos1+1,pos2-pos1-1).c_str());
			target.pt[2] = atof(str.substr(pos2+1,str.length()-pos1-1).c_str());
		}
		attr=lightElement->Attribute("directionSpherical");
		if (attr) {
			string str(attr);
			int pos1 = str.find_first_of(','),
			pos2 = str.find_last_of(',');
			az = -90.0+atof(str.substr(0,pos1).c_str());
			ele = atof(str.substr(pos1+1,pos2-pos1-1).c_str());
			dist = atof(str.substr(pos2+1,str.length()-pos1-1).c_str());
		}
		attr=lightElement->Attribute("angle");
		if (attr) {
			angle = atof(attr);
		}
		float farplane=2.0*dist*tan(angle*M_PI/180.0);
		world->getCamera()->setLightParameters(target,az,ele,dist,angle,10.0,farplane);

	}

	TiXmlNode *nodeBlock = node->FirstChild("blockList");
	if (nodeBlock) {
		Color defaultColor=DARKGREY;
		TiXmlElement* element = nodeBlock->ToElement();
		const char *attr= element->Attribute("color");
		if (attr) {
			string str(attr);
			int pos1 = str.find_first_of(','),
			pos2 = str.find_last_of(',');
			defaultColor.rgba[0] = atof(str.substr(0,pos1).c_str())/255.0;
			defaultColor.rgba[1] = atof(str.substr(pos1+1,pos2-pos1-1).c_str())/255.0;
			defaultColor.rgba[2] = atof(str.substr(pos2+1,str.length()-pos1-1).c_str())/255.0;
			OUTPUT << "new default color :" << defaultColor << endl;
		}
		attr= element->Attribute("blocksize");
        if (attr) {
             string str(attr);
             int pos1 = str.find_first_of(','),
              pos2 = str.find_last_of(',');
             blockSize[0] = atof(str.substr(0,pos1).c_str());
             blockSize[1] = atof(str.substr(pos1+1,pos2-pos1-1).c_str());
             blockSize[2] = atof(str.substr(pos2+1,str.length()-pos1-1).c_str());
             OUTPUT << "blocksize =" << blockSize[0] << "," << blockSize[1] << "," << blockSize[2] << endl;
             world->setBlocksSize(blockSize);
		}

	/* Reading a robotblock */
		TiXmlNode *block = nodeBlock->FirstChild("block");
		Vecteur position;
		Color color;
		bool master;
		while (block) {
		   element = block->ToElement();
		   color=defaultColor;
		   master=false;
		   attr = element->Attribute("color");
		   if (attr) {
			   string str(attr);
			   int pos1 = str.find_first_of(','),
		   		   pos2 = str.find_last_of(',');
			   color.set(atof(str.substr(0,pos1).c_str())/255.0,
                         atof(str.substr(pos1+1,pos2-pos1-1).c_str())/255.0,
                         atof(str.substr(pos2+1,str.length()-pos1-1).c_str())/255.0);
			   OUTPUT << "new color :" << defaultColor << endl;
			}
			attr = element->Attribute("position");
			if (attr) {
                string str(attr);
                int pos = str.find_first_of(',');
                int ix = atof(str.substr(0,pos).c_str()),
                    iy = atoi(str.substr(pos+1,str.length()-pos-1).c_str());
				//position.pt[0] = (ix+(iy%2)*0.5)*blockSize[0];
				//position.pt[1] = 0.5;
				//position.pt[2] = M_SQRT3_2*iy*blockSize[2];
				  position.pt[0] = ix;
				  position.pt[1] = 0;
				  position.pt[2] = iy;
			}
			attr = element->Attribute("master");
			if (attr) {
                string str(attr);
                if (str.compare("true")==0 || str.compare("1")==0) {
                            master=true;
                }
                OUTPUT << "master : " << master << endl;
			}
			world->addBlock(currentID++,Catoms2DSimulator::buildNewBlockCode,position,color,master);
			block = block->NextSibling("block");
		} // end while (block)
/*
		block = nodeBlock->FirstChild("blocksLine");
		int line,plane;
		while (block) {
			element = block->ToElement();
			color=defaultColor;
			attr = element->Attribute("color");
			if (attr) {
				string str(attr);
				int pos1 = str.find_first_of(','),
					pos2 = str.find_last_of(',');
				color.rgba[0] = atof(str.substr(0,pos1).c_str())/255.0;
				color.rgba[1] = atof(str.substr(pos1+1,pos2-pos1-1).c_str())/255.0;
				color.rgba[2] = atof(str.substr(pos2+1,str.length()-pos1-1).c_str())/255.0;
				OUTPUT << "line color :" << color << endl;

			}
			attr = element->Attribute("line");
			if (attr) {
				line = atoi(attr);
			}
			attr = element->Attribute("plane");
			if (attr) {
				plane = atoi(attr);
			}
			attr = element->Attribute("values");
			if (attr) {
				string str(attr);
				position.pt[2] = plane;
				position.pt[1] = line;
				int n = str.length();
				for(int i=0; i<n; i++) {
			    	if  (str[i]=='1') {
			    		position.pt[0]=i;
			    		world->addBlock(currentID++,Catoms2DSimulator::buildNewBlockCode,position,color);
			    	}
			    }
			}
			block = block->NextSibling("blocksLine");
		} // end while (nodeBlock)*/
	} else // end if(nodeBlock)
	{ cerr << "no Block List" << endl;
	}

	TiXmlNode *nodeGrid = node->FirstChild("targetGrid");
	if (nodeGrid) {
		world->initTargetGrid();
		TiXmlNode *block = nodeGrid->FirstChild("block");
		Vecteur position;
		const char *attr;
		TiXmlElement* element;
		while (block) {
		   	element = block->ToElement();
			attr = element->Attribute("position");
			if (attr) {
                string str(attr);
                int pos = str.find_first_of(',');
                int ix = atof(str.substr(0,pos).c_str()),
                    iy = atoi(str.substr(pos+1,str.length()-pos-1).c_str());
				position.pt[0] = ix;
				position.pt[1] = 0;
				position.pt[2] = iy;
			}
			world->setTargetGrid(fullCell,position[0],position[1],position[2]);
			block = block->NextSibling("block");
		}
		/*
		TiXmlNode *block = nodeGrid->FirstChild("targetLine");
		int line,plane;
		while (block) {
			TiXmlElement* element = block->ToElement();
			const char *attr = element->Attribute("line");
	 		if (attr) {
	 			line = atoi(attr);
	 		}
	 		attr = element->Attribute("plane");
	 		if (attr) {
	 			plane = atoi(attr);
	 		}
	 		attr = element->Attribute("values");
	 		if (attr) {
	 			string str(attr);
	 			int n = str.length();
	 			for(int i=0; i<n; i++) {
	 		    	world->setTargetGrid((str[i]=='1')?fullCell:emptyCell,i,line,plane);
	 		    }
	 		}
	 		block = block->NextSibling("targetLine");
	 	}*/
	 } else {
	 	ERRPUT << "No target grid" << endl;
	 }

    TiXmlNode *nodeCapa = node->FirstChild("capabilities");
	if (nodeCapa) {
        world->setCapabilities(new Catoms2DCapabilities(nodeCapa));
    }

    world->linkBlocks();

//	getScheduler()->sem_schedulerStart->post();
//	getScheduler()->setState(Scheduler::NOTSTARTED);

	if (!testMode) {
      GlutContext::mainLoop();
   }
}
示例#19
0
	CStdString *ThumbStore::getFanart(const char *artistName) {

		if (!Settings::getInstance()->getUseHTFanarts())
			return m_stdFanart;

		//Logger::printOut("Looking for fanart");

		//check if we got the fanart
		string artistNameString = artistName;
		stringMap::iterator it = m_fanarts.find(artistNameString);
		if (it == m_fanarts.end()) {
			//we dont have it so we need to to a search for it

			CCurlFile http;
			CStdString artistString = artistName;
			artistString.Replace(' ', '+');
			CStdString urlString;
			urlString.Format(
					"http://htbackdrops.org/api/afb0f6cdbd412a7888005de34f86e4a5/searchXML?keywords=%s&default_operator=and&aid=1&fields=title,keywords,caption,mb_name,mb_alias&inc=keywords,caption,mb_name,mb_aliases&limit=1",
					artistString);

			CURL url(urlString);

			if (http.Open(url)) {
				Logger::printOut("Looking for fanart, need to fetch a new address");
				Logger::printOut(artistNameString);
				//try to parse the resulting file for a fanart image
				CStdString data;
				http.ReadData(data);

				TiXmlDocument xmlDoc;
				xmlDoc.Parse(data);
				TiXmlNode* element = xmlDoc.RootElement();
				//get the images child
				element = element->FirstChild("images");
				if (element) {

					//get the first image child, (should only be one)
					element = element->FirstChild();
					if (element) {
						//get the id
						TiXmlNode* idElement = element->FirstChild("id");
						CStdString id = idElement->ToElement()->GetText();
						//get the filename
						TiXmlNode* fileNameElement = element->FirstChild("filename");
						CStdString name = fileNameElement->ToElement()->GetText();

						CStdString *fanartUrl = new CStdString();
						fanartUrl->Format(
								"http://htbackdrops.org/api/afb0f6cdbd412a7888005de34f86e4a5/download/%s/fullsize/%s",
								id, name);
						//Logger::printOut("Adding online fanart");

						m_fanarts.insert(
								stringMap::value_type(artistNameString, fanartUrl));

						//save the fanart url to the cachefile
						string path = Settings::getInstance()->getCachePath() + "fanarts.txt";
						Logger::printOut("saving fanart list");
						ofstream file(path.c_str(), ios::app);
						if (file.is_open()) {
							file << artistNameString << "\n" << *fanartUrl << "\n";
						}

						file.close();

						return fanartUrl;
					}
				}
			}
			//Logger::printOut("Adding standard fanart");
			m_fanarts.insert(stringMap::value_type(artistNameString, m_stdFanart));

			//save the fanart url to the cachefile
			string path = Settings::getInstance()->getCachePath() + "fanarts.txt";
			Logger::printOut("saving fanart list");
			ofstream file(path.c_str(), ios::app);
			if (file.is_open()) {
				file << artistNameString << "\n" << *m_stdFanart << "\n";
			}

			file.close();

			return m_stdFanart;
		}
		//Logger::printOut("Returning cached fanart");
		return it->second;
	}
示例#20
0
bool XmlRpcDispatch::parseXmlRpcRequest(const UtlString& requestContent,
                                        XmlRpcMethodContainer*& methodContainer,
                                        UtlSList& params,
                                        XmlRpcResponse& response)
{
   bool result = false;

   // Parse the XML-RPC response
   TiXmlDocument doc("XmlRpcRequest.xml");
   
   doc.Parse(requestContent);   
   if (!doc.Error())
   {
      TiXmlNode* rootNode = doc.FirstChild ("methodCall");
      
      if (rootNode != NULL)
      {
         // Positive response example
         // 
         // <methodCall>
         //   <methodName>examples.getStateName</methodName>
         //   <params>
         //     <param>
         //       <value><i4>41</i4></value>
         //     </param>
         //   </params>
         // </methodCall>
                  
         TiXmlNode* methodNode = rootNode->FirstChild("methodName");
         
         if (methodNode)
         {
            // Check whether the method exists or not. If not, send back a fault response
            UtlString methodCall = methodNode->FirstChild()->Value();
            methodContainer = (XmlRpcMethodContainer*) mMethods.findValue(&methodCall);
            if (methodContainer)
            {
               /*
                * Since params are optional,
                * assume all is well until proven otherwise now
                */
               result = true; 
               TiXmlNode* paramsNode = rootNode->FirstChild("params");
               
               if (paramsNode)
               {
                  int index = 0;
                  for (TiXmlNode* paramNode = paramsNode->FirstChild("param");
                       result /* stop if any error */ && paramNode /* or no more param nodes */; 
                       paramNode = paramNode->NextSibling("param"))
                  {
                     TiXmlNode* subNode = paramNode->FirstChild("value");
                     
                     if (subNode)
                     {
                        UtlString parseErrorMsg;
                        UtlContainable* param = XmlRpcBody::parseValue(subNode, 0, parseErrorMsg);
                        if (param)
                        {
                           params.append(param);
                           index++;
                        }
                        else
                        {
                           char errorLoc[200];
                           sprintf(errorLoc," in param %d",
                                   index);
                           OsSysLog::add(FAC_XMLRPC, PRI_ERR,
                                         "XmlRpcDispatch::parseXmlRpcRequest"
                                         " invalid <value> contents %s of %s",
                                         errorLoc, requestContent.data());
                           parseErrorMsg.append(errorLoc);
                           response.setFault(EMPTY_PARAM_VALUE_FAULT_CODE,
                                             parseErrorMsg.data());
                           result=false;
                        }
                     }
                     else
                     {
                        char errorLoc[200];
                        sprintf(errorLoc,"no <value> element in param %d.",
                                index);
                        OsSysLog::add(FAC_XMLRPC, PRI_ERR,
                                      "XmlRpcDispatch::parseXmlRpcRequest %s of: %s",
                                      errorLoc, requestContent.data());
                        response.setFault(EMPTY_PARAM_VALUE_FAULT_CODE,
                                          errorLoc);
                        result=false;
                     }
                  }
               }
               else
               {
                  OsSysLog::add(FAC_XMLRPC, PRI_ERR,
                                "XmlRpcDispatch::parseXmlRpcRequest no <params> element found");
                  response.setMethod(methodCall);
                  response.setFault(ILL_FORMED_CONTENTS_FAULT_CODE, "no <params> element");
                  result = false;
               }
            }
            else
            {
               OsSysLog::add(FAC_XMLRPC, PRI_ERR,
                             "XmlRpcDispatch::parseXmlRpcRequest no method '%s' registered",
                             methodCall.data());
               response.setMethod(methodCall);
               response.setFault(UNREGISTERED_METHOD_FAULT_CODE, UNREGISTERED_METHOD_FAULT_STRING);
               result = false;
            }
         }
         else
         {
            UtlString faultMsg(INVALID_ELEMENT_FAULT_STRING);
            faultMsg.append("methodName not found");
            OsSysLog::add(FAC_XMLRPC, PRI_ERR,
                          "XmlRpcDispatch::parseXmlRpcRequest %s", faultMsg.data());
            response.setFault(INVALID_ELEMENT, faultMsg.data());
            result = false;
         }
      }
      else
      {
         UtlString faultMsg(INVALID_ELEMENT_FAULT_STRING);
         faultMsg.append("methodCall not found");
         OsSysLog::add(FAC_XMLRPC, PRI_ERR,
                       "XmlRpcDispatch::parseXmlRpcRequest %s", faultMsg.data());
         response.setFault(INVALID_ELEMENT, faultMsg.data());
         result = false;
      }
   }
   else
   {
      OsSysLog::add(FAC_XMLRPC, PRI_ERR,
                    "XmlRpcDispatch::parseXmlRpcRequest"
                    " ill-formed XML contents in %s. Parsing error = %s",
                     requestContent.data(), doc.ErrorDesc());
      response.setFault(ILL_FORMED_CONTENTS_FAULT_CODE, ILL_FORMED_CONTENTS_FAULT_STRING);
      result = false;
   }
   
   return result;   
}
示例#21
0
void LoaderImagenetDet::LoadAnnotationFile(const string& annotation_file,
                                           vector<Annotation>* image_annotations) {
  // Open the annotation file.
  TiXmlDocument document(annotation_file.c_str());
  document.LoadFile();

  // Read the top-level element.
  TiXmlHandle docHandle( &document );
  TiXmlElement* annotations = docHandle.FirstChild().ToElement();
  if (!annotations) {
    printf("No annotations!\n");
    return;
  }

  // Get the folder and filename for the image corresponding to this annotation.
  const string& folder = annotations->FirstChildElement("folder")->GetText();
  //printf("Folder: %s\n", folder);

  const string& filename = annotations->FirstChildElement("filename")->GetText();
  //printf("File: %s\n", filename);

  // Get the relative image size that was displayed to the annotater (may have been downsampled).
  TiXmlNode* size = annotations->FirstChild("size");
  if (!size) {
    printf("Error - no size!\n");
    return;
  }
  const int display_width = atoi(size->FirstChildElement("width")->GetText());
  const int display_height = atoi(size->FirstChildElement("height")->GetText());
  //printf("Size: %d %d\n", display_width, display_height);

  // Get all of the bounding boxes in this image.
  for(TiXmlNode* object = annotations->FirstChild("object"); object; object = object->NextSibling("object")) {
    // Get the boudning box coordinates.
    TiXmlElement* bbox = object->FirstChildElement("bndbox");
    const int xmin = atoi(bbox->FirstChildElement("xmin")->GetText());
    const int xmax = atoi(bbox->FirstChildElement("xmax")->GetText());
    const int ymin = atoi(bbox->FirstChildElement("ymin")->GetText());
    const int ymax = atoi(bbox->FirstChildElement("ymax")->GetText());

    const double width = xmax - xmin;
    const double height = ymax - ymin;

    // If this object occupies almost the entire image, then ignore it,
    // since we will not be able to simulate object motion.
    if (width > kMaxRatio * display_width || height > kMaxRatio * display_height) {
      continue;
    }

    // Convert the annotation to bounding box format.
    Annotation annotation;
    annotation.image_path = folder + "/" + filename;
    annotation.bbox.x1_ = xmin;
    annotation.bbox.x2_ = xmax;
    annotation.bbox.y1_ = ymin;
    annotation.bbox.y2_ = ymax;
    annotation.display_width_ = display_width;
    annotation.display_height_ = display_height;

    // Check if the annotation is outside of the border of the image or otherwise invalid.
    if (xmin < 0 || ymin < 0 || xmax <= xmin || ymax <= ymin) {
      printf("Skipping invalid annotation from file: %s\n", annotation_file.c_str());
      printf("Annotation: %d, %d, %d, %d\n", xmin, xmax, ymin, ymax);
      printf("Image path: %s\n", annotation.image_path.c_str());
      printf("Display: %d, %d\n", display_width, display_height);
      continue;
    }

    // Save the annotation.
    image_annotations->push_back(annotation);

    //printf("Path: %s\n", annotation.image_path.c_str());
    //printf("bbox: %d %d %d %d\n", xmin, xmax, ymin, ymax);
  }
}
示例#22
0
    void xmlStructure::copy_to_SGMLDocument ( SGMLDocument* sgmlDoc, TiXmlNode* pParent, unsigned int indent )
    {
        if ( !pParent )
            return;

        TiXmlNode* pChild;
        TiXmlText* pText;
        int t = pParent->Type();
//         printf ( "%s", getIndent ( indent ) );
//         int num;
        string elementValue;
	bool unknownTag=false;
	if ( xmlParams.debugMode )
        {
            cerr << "DEBUG tercpp : xmlStructure::copy_to_SGMLDocument : " << endl << " TiXmlNode: " << t << endl << "END DEBUG" << endl;
            cerr << "DEBUG tercpp : xmlStructure::copy_to_SGMLDocument : " << endl << " indent: " << indent << endl << "END DEBUG" << endl;
        }
        switch ( t )
        {
        case TiXmlNode::DOCUMENT:

            if ( xmlParams.debugMode )
            {
                cerr << "DEBUG tercpp : xmlStructure::copy_to_SGMLDocument : " << endl << " Document" << endl << "END DEBUG" << endl;
            }//                 printf ( "Document" );
            break;

        case TiXmlNode::ELEMENT:
//                 printf ( "Element [%s]", pParent->Value() );
            elementValue = Tools::lowerCase ( pParent->Value() );

            if ( xmlParams.debugMode )
            {
                cerr << "DEBUG tercpp : xmlStructure::copy_to_SGMLDocument : " << endl << " elementValue: " << elementValue << endl << "END DEBUG" << endl;
            }

            if ( ( ( int ) elementValue.compare ( "refset" ) == 0 ) || ( ( int ) elementValue.compare ( "tstset" ) == 0 ) )
            {
                sgmlDoc->setDocType ( elementValue );
            }
            else
                if (( ( int ) elementValue.compare ( "doc" ) == 0 ) || ( ( int ) elementValue.compare ( "DOC" ) == 0 ))
                {
                    documentStructure tmp_doc;
                    sgmlDoc->addDocument ( tmp_doc );
                }
                else
                    if ( ( ( int ) elementValue.compare ( "seg" ) == 0 ) || ( ( int ) elementValue.compare ( "SEG" ) == 0 ) )
                    {
                        segmentStructure tmp_seg;
                        ( sgmlDoc->getLastDocument() )->addSegments ( tmp_seg );
                    }
		    else
		    {
			unknownTag=true;
		    }

            if ( xmlParams.debugMode )
            {
                cerr << "DEBUG tercpp : xmlStructure::copy_to_SGMLDocument : " << endl << " Calling dump_attribs_to_SGMLDocuments with indent :" << indent + 1 << endl << "END DEBUG" << endl;
            }
            if (!unknownTag)
	    {
		dump_attribs_to_SGMLDocuments ( sgmlDoc, pParent->ToElement(), indent + 1 );
	    }
//                 num = dump_attribs_to_stdout ( pParent->ToElement(), indent + 1 );
//                 switch ( num )
//                 {
//                     case 0:
//                         printf ( " (No attributes)" );
//                         break;
//                     case 1:
//                         printf ( "%s1 attribute", getIndentAlt ( indent ) );
//                         break;
//                     default:
//                         printf ( "%s%d attributes", getIndentAlt ( indent ), num );
//                         break;
//                 }
            break;

//             case TiXmlNode::COMMENT:
//                 printf ( "Comment: [%s]", pParent->Value() );
//                 break;
//
//             case TiXmlNode::UNKNOWN:
//                 printf ( "Unknown" );
//                 break;

        case TiXmlNode::TEXT:
            pText = pParent->ToText();
//                 printf ( "Text: [%s]", pText->Value() );
            if ( indent >= 2 )
            {
                documentStructure * l_tmp_doc = sgmlDoc->getLastDocument();
                segmentStructure * l_tmp_seg = l_tmp_doc->getLastSegments();
                string l_text = pText->Value();
                string line_mod = l_text;
                if ( !xmlParams.tercomLike )
                {
                    if ( xmlParams.debugMode )
                    {
                        cerr << "DEBUG xmlStructure::copy_to_SGMLDocument : line NOT tokenized |" << line_mod << "|" << endl << "END DEBUG" << endl;
                    }
                    if ( xmlParams.debugMode )
                    {
                        cerr << "DEBUG tercpp : xmlStructure::copy_to_SGMLDocument : " << endl << "TERCOM AT FALSE " << endl << "END DEBUG" << endl;
                    }

                    line_mod = tokenizePunct ( line_mod );
                }
                if ( !xmlParams.caseOn )
                {
                    if ( xmlParams.debugMode )
                    {
                        cerr << "DEBUG tercpp : xmlStructure::copy_to_SGMLDocument : " << endl << "CASEON AT FALSE " << endl << "END DEBUG" << endl;
                    }
                    line_mod = lowerCase ( line_mod );
                }
                if ( xmlParams.noPunct )
                {
                    if ( xmlParams.debugMode )
                    {
                        cerr << "DEBUG tercpp : xmlStructure::copy_to_SGMLDocument : " << endl << "NOPUNCT AT TRUE " << endl << "END DEBUG" << endl;
                    }
                    if ( !xmlParams.tercomLike )
                    {
                        line_mod = removePunctTercom ( line_mod );
                    }
                    else
                    {
                        line_mod = removePunct ( line_mod );
                    }
                }
                if ( xmlParams.debugMode )
                {
                    cerr << "DEBUG xmlStructure::copy_to_SGMLDocument : line tokenized |" << line_mod << "|" << endl << "END DEBUG" << endl;
                }
                l_tmp_seg->addContent ( line_mod );
            }
            break;

//             case TiXmlNode::DECLARATION:
//                 printf ( "Declaration" );
//                 break;
        default:
            cerr << "DEBUG tercpp : xmlStructure::copy_to_SGMLDocument : " << endl << "Default TiXmlNode: " << t << endl << "END DEBUG" << endl;
            break;
        }
//         printf ( "\n" );
        for ( pChild = pParent->FirstChild(); pChild != 0; pChild = pChild->NextSibling() )
        {
            copy_to_SGMLDocument ( sgmlDoc, pChild, indent + 1 );
        }
    }
示例#23
0
bool GetServer(TiXmlElement *node, CServer& server)
{
	wxASSERT(node);

	wxString host = GetTextElement(node, "Host");
	if (host.empty())
		return false;

	int port = GetTextElementInt(node, "Port");
	if (port < 1 || port > 65535)
		return false;

	if (!server.SetHost(host, port))
		return false;

	int const protocol = GetTextElementInt(node, "Protocol");
	if (protocol < 0 || protocol > ServerProtocol::MAX_VALUE) {
		return false;
	}
	server.SetProtocol(static_cast<ServerProtocol>(protocol));

	int type = GetTextElementInt(node, "Type");
	if (type < 0 || type >= SERVERTYPE_MAX)
		return false;

	server.SetType((enum ServerType)type);

	int logonType = GetTextElementInt(node, "Logontype");
	if (logonType < 0)
		return false;

	server.SetLogonType((enum LogonType)logonType);

	if (server.GetLogonType() != ANONYMOUS) {
		wxString user = GetTextElement(node, "User");

		wxString pass;
		if ((long)NORMAL == logonType || (long)ACCOUNT == logonType) {
			TiXmlElement* passElement = node->FirstChildElement("Pass");
			if (passElement) {
				pass = GetTextElement(passElement);

				wxString encoding = GetTextAttribute(passElement, "encoding");

				if (encoding == _T("base64")) {
					wxMemoryBuffer buf = wxBase64Decode(pass);
					if (!buf.IsEmpty()) {
						pass = wxString::FromUTF8(static_cast<const char*>(buf.GetData()), buf.GetDataLen());
					}
					else {
						pass.clear();
					}
				}
				else if (!encoding.empty()) {
					pass.clear();
					server.SetLogonType(ASK);
				}
			}
		}

		if (!server.SetUser(user, pass))
			return false;

		if ((long)ACCOUNT == logonType) {
			wxString account = GetTextElement(node, "Account");
			if (account.empty())
				return false;
			if (!server.SetAccount(account))
				return false;
		}
	}

	int timezoneOffset = GetTextElementInt(node, "TimezoneOffset");
	if (!server.SetTimezoneOffset(timezoneOffset))
		return false;

	wxString pasvMode = GetTextElement(node, "PasvMode");
	if (pasvMode == _T("MODE_PASSIVE"))
		server.SetPasvMode(MODE_PASSIVE);
	else if (pasvMode == _T("MODE_ACTIVE"))
		server.SetPasvMode(MODE_ACTIVE);
	else
		server.SetPasvMode(MODE_DEFAULT);

	int maximumMultipleConnections = GetTextElementInt(node, "MaximumMultipleConnections");
	server.MaximumMultipleConnections(maximumMultipleConnections);

	wxString encodingType = GetTextElement(node, "EncodingType");
	if (encodingType == _T("Auto"))
		server.SetEncodingType(ENCODING_AUTO);
	else if (encodingType == _T("UTF-8"))
		server.SetEncodingType(ENCODING_UTF8);
	else if (encodingType == _T("Custom")) {
		wxString customEncoding = GetTextElement(node, "CustomEncoding");
		if (customEncoding.empty())
			return false;
		if (!server.SetEncodingType(ENCODING_CUSTOM, customEncoding))
			return false;
	}
	else
		server.SetEncodingType(ENCODING_AUTO);

	if (CServer::SupportsPostLoginCommands(server.GetProtocol())) {
		std::vector<wxString> postLoginCommands;
		TiXmlElement* pElement = node->FirstChildElement("PostLoginCommands");
		if (pElement) {
			TiXmlElement* pCommandElement = pElement->FirstChildElement("Command");
			while (pCommandElement) {
				TiXmlNode* textNode = pCommandElement->FirstChild();
				if (textNode && textNode->ToText()) {
					wxString command = ConvLocal(textNode->Value());
					if (!command.empty())
						postLoginCommands.push_back(command);
				}

				pCommandElement = pCommandElement->NextSiblingElement("Command");
			}
		}
		if (!server.SetPostLoginCommands(postLoginCommands))
			return false;
	}

	server.SetBypassProxy(GetTextElementInt(node, "BypassProxy", false) == 1);
	server.SetName(GetTextElement_Trimmed(node, "Name"));

	if (server.GetName().empty())
		server.SetName(GetTextElement_Trimmed(node));

	return true;
}
示例#24
0
    void xmlStructure::dump_to_stdout ( TiXmlNode* pParent, unsigned int indent = 0 )
    {
        if ( !pParent )
            return;
// 	cerr << pParent->Value()<< endl;
        TiXmlNode* pChild;
        TiXmlText* pText;
        int t = pParent->Type();
        printf ( "%s", getIndent ( indent ) );
        int num;
        switch ( t )
        {
        case TiXmlNode::DOCUMENT:
            printf ( "Document" );
            break;

        case TiXmlNode::ELEMENT:
            printf ( "Element [%s]", pParent->Value() );
            num = dump_attribs_to_stdout ( pParent->ToElement(), indent + 1 );
            switch ( num )
            {
            case 0:
                printf ( " (No attributes)" );
                break;
            case 1:
                printf ( "%s1 attribute", getIndentAlt ( indent ) );
                break;
            default:
                printf ( "%s%d attributes", getIndentAlt ( indent ), num );
                break;
            }
            break;

        case TiXmlNode::COMMENT:
            printf ( "Comment: [%s]", pParent->Value() );
            break;

        case TiXmlNode::UNKNOWN:
            printf ( "Unknown" );
            break;

        case TiXmlNode::TEXT:
            pText = pParent->ToText();
            printf ( "Text: [%s]", pText->Value() );
            break;

        case TiXmlNode::DECLARATION:
            printf ( "Declaration" );
            break;
        default:
            break;
        }
        printf ( "\n" );
        for ( pChild = pParent->FirstChild(); pChild != 0; pChild = pChild->NextSibling() )
        {
            dump_to_stdout ( pChild, indent + 1 );
        }
        if ( pChild == 0 )
        {
            /*	    pChild = pParent->NextSibling();
            	    for ( pChild = pParent->FirstChild(); pChild != 0; pChild = pChild->NextSibling() )
            	    {
            		dump_to_stdout ( pChild, indent + 1 );
            	    }*/
        }
    }
示例#25
0
bool PVRDemoData::LoadDemoData(void)
{
  TiXmlDocument xmlDoc;
  string strSettingsFile = GetSettingsFile();

  if (!xmlDoc.LoadFile(strSettingsFile))
  {
    XBMC->Log(LOG_ERROR, "invalid demo data (no/invalid data file found at '%s')", strSettingsFile.c_str());
    return false;
  }

  TiXmlElement *pRootElement = xmlDoc.RootElement();
  if (strcmp(pRootElement->Value(), "demo") != 0)
  {
    XBMC->Log(LOG_ERROR, "invalid demo data (no <demo> tag found)");
    return false;
  }

  /* load channels */
  int iUniqueChannelId = 0;
  TiXmlElement *pElement = pRootElement->FirstChildElement("channels");
  if (pElement)
  {
    TiXmlNode *pChannelNode = NULL;
    while ((pChannelNode = pElement->IterateChildren(pChannelNode)) != NULL)
    {
      CStdString strTmp;
      PVRDemoChannel channel;
      channel.iUniqueId = ++iUniqueChannelId;

      /* channel name */
      if (!XMLUtils::GetString(pChannelNode, "name", strTmp))
        continue;
      channel.strChannelName = strTmp;

      /* radio/TV */
      XMLUtils::GetBoolean(pChannelNode, "radio", channel.bRadio);

      /* channel number */
      if (!XMLUtils::GetInt(pChannelNode, "number", channel.iChannelNumber))
        channel.iChannelNumber = iUniqueChannelId;

      /* sub channel number */
      if (!XMLUtils::GetInt(pChannelNode, "subnumber", channel.iSubChannelNumber))
        channel.iSubChannelNumber = 0;

      /* CAID */
      if (!XMLUtils::GetInt(pChannelNode, "encryption", channel.iEncryptionSystem))
        channel.iEncryptionSystem = 0;

      /* icon path */
      if (!XMLUtils::GetString(pChannelNode, "icon", strTmp))
        channel.strIconPath = m_strDefaultIcon;
      else
        channel.strIconPath = strTmp;

      /* stream url */
      if (!XMLUtils::GetString(pChannelNode, "stream", strTmp))
        channel.strStreamURL = m_strDefaultMovie;
      else
        channel.strStreamURL = strTmp;

      m_channels.push_back(channel);
    }
  }

  /* load channel groups */
  int iUniqueGroupId = 0;
  pElement = pRootElement->FirstChildElement("channelgroups");
  if (pElement)
  {
    TiXmlNode *pGroupNode = NULL;
    while ((pGroupNode = pElement->IterateChildren(pGroupNode)) != NULL)
    {
      CStdString strTmp;
      PVRDemoChannelGroup group;
      group.iGroupId = ++iUniqueGroupId;

      /* group name */
      if (!XMLUtils::GetString(pGroupNode, "name", strTmp))
        continue;
      group.strGroupName = strTmp;

      /* radio/TV */
      XMLUtils::GetBoolean(pGroupNode, "radio", group.bRadio);

      /* members */
      TiXmlNode* pMembers = pGroupNode->FirstChild("members");
      TiXmlNode *pMemberNode = NULL;
      while (pMembers != NULL && (pMemberNode = pMembers->IterateChildren(pMemberNode)) != NULL)
      {
        int iChannelId = atoi(pMemberNode->FirstChild()->Value());
        if (iChannelId > -1)
          group.members.push_back(iChannelId);
      }

      m_groups.push_back(group);
    }
  }

  /* load EPG entries */
  pElement = pRootElement->FirstChildElement("epg");
  if (pElement)
  {
    TiXmlNode *pEpgNode = NULL;
    while ((pEpgNode = pElement->IterateChildren(pEpgNode)) != NULL)
    {
      CStdString strTmp;
      int iTmp;
      PVRDemoEpgEntry entry;

      /* broadcast id */
      if (!XMLUtils::GetInt(pEpgNode, "broadcastid", entry.iBroadcastId))
        continue;

      /* channel id */
      if (!XMLUtils::GetInt(pEpgNode, "channelid", iTmp))
        continue;
      PVRDemoChannel &channel = m_channels.at(iTmp - 1);
      entry.iChannelId = channel.iUniqueId;

      /* title */
      if (!XMLUtils::GetString(pEpgNode, "title", strTmp))
        continue;
      entry.strTitle = strTmp;

      /* start */
      if (!XMLUtils::GetInt(pEpgNode, "start", iTmp))
        continue;
      entry.startTime = iTmp;

      /* end */
      if (!XMLUtils::GetInt(pEpgNode, "end", iTmp))
        continue;
      entry.endTime = iTmp;

      /* plot */
      if (XMLUtils::GetString(pEpgNode, "plot", strTmp))
        entry.strPlot = strTmp;

      /* plot outline */
      if (XMLUtils::GetString(pEpgNode, "plotoutline", strTmp))
        entry.strPlotOutline = strTmp;

      /* icon path */
      if (XMLUtils::GetString(pEpgNode, "icon", strTmp))
        entry.strIconPath = strTmp;

      /* genre type */
      XMLUtils::GetInt(pEpgNode, "genretype", entry.iGenreType);

      /* genre subtype */
      XMLUtils::GetInt(pEpgNode, "genresubtype", entry.iGenreSubType);

      XBMC->Log(LOG_DEBUG, "loaded EPG entry '%s' channel '%d' start '%d' end '%d'", entry.strTitle.c_str(), entry.iChannelId, entry.startTime, entry.endTime);
      channel.epg.push_back(entry);
    }
  }

  /* load recordings */
  iUniqueGroupId = 0; // reset unique ids
  pElement = pRootElement->FirstChildElement("recordings");
  if (pElement)
  {
    TiXmlNode *pRecordingNode = NULL;
    while ((pRecordingNode = pElement->IterateChildren(pRecordingNode)) != NULL)
    {
      CStdString strTmp;
      PVRDemoRecording recording;

      /* recording title */
      if (!XMLUtils::GetString(pRecordingNode, "title", strTmp))
        continue;
      recording.strTitle = strTmp;

      /* recording url */
      if (!XMLUtils::GetString(pRecordingNode, "url", strTmp))
        recording.strStreamURL = m_strDefaultMovie;
      else
        recording.strStreamURL = strTmp;

      /* recording path */
      if (XMLUtils::GetString(pRecordingNode, "directory", strTmp))
        recording.strDirectory = strTmp;

      iUniqueGroupId++;
      strTmp.Format("%d", iUniqueGroupId);
      recording.strRecordingId = strTmp;

      /* channel name */
      if (XMLUtils::GetString(pRecordingNode, "channelname", strTmp))
        recording.strChannelName = strTmp;

      /* plot */
      if (XMLUtils::GetString(pRecordingNode, "plot", strTmp))
        recording.strPlot = strTmp;

      /* plot outline */
      if (XMLUtils::GetString(pRecordingNode, "plotoutline", strTmp))
        recording.strPlotOutline = strTmp;

      /* genre type */
      XMLUtils::GetInt(pRecordingNode, "genretype", recording.iGenreType);

      /* genre subtype */
      XMLUtils::GetInt(pRecordingNode, "genresubtype", recording.iGenreSubType);

      /* duration */
      XMLUtils::GetInt(pRecordingNode, "duration", recording.iDuration);

      /* recording time */
      if (XMLUtils::GetString(pRecordingNode, "time", strTmp))
      {
        time_t timeNow = time(NULL);
        struct tm* now = localtime(&timeNow);

        CStdString::size_type delim = strTmp.Find(':');
        if (delim != CStdString::npos)
        {
          now->tm_hour = (int)strtol(strTmp.Left(delim), NULL, 0);
          now->tm_min  = (int)strtol(strTmp.Mid(delim + 1), NULL, 0);
          now->tm_mday--; // yesterday

          recording.recordingTime = mktime(now);
        }
      }

      m_recordings.push_back(recording);
    }
  }

  /* load deleted recordings */
  pElement = pRootElement->FirstChildElement("recordingsdeleted");
  if (pElement)
  {
    TiXmlNode *pRecordingNode = NULL;
    while ((pRecordingNode = pElement->IterateChildren(pRecordingNode)) != NULL)
    {
      CStdString strTmp;
      PVRDemoRecording recording;

      /* recording title */
      if (!XMLUtils::GetString(pRecordingNode, "title", strTmp))
        continue;
      recording.strTitle = strTmp;

      /* recording url */
      if (!XMLUtils::GetString(pRecordingNode, "url", strTmp))
        recording.strStreamURL = m_strDefaultMovie;
      else
        recording.strStreamURL = strTmp;

      /* recording path */
      if (XMLUtils::GetString(pRecordingNode, "directory", strTmp))
        recording.strDirectory = strTmp;

      iUniqueGroupId++;
      strTmp.Format("%d", iUniqueGroupId);
      recording.strRecordingId = strTmp;

      /* channel name */
      if (XMLUtils::GetString(pRecordingNode, "channelname", strTmp))
        recording.strChannelName = strTmp;

      /* plot */
      if (XMLUtils::GetString(pRecordingNode, "plot", strTmp))
        recording.strPlot = strTmp;

      /* plot outline */
      if (XMLUtils::GetString(pRecordingNode, "plotoutline", strTmp))
        recording.strPlotOutline = strTmp;

      /* genre type */
      XMLUtils::GetInt(pRecordingNode, "genretype", recording.iGenreType);

      /* genre subtype */
      XMLUtils::GetInt(pRecordingNode, "genresubtype", recording.iGenreSubType);

      /* duration */
      XMLUtils::GetInt(pRecordingNode, "duration", recording.iDuration);

      /* recording time */
      if (XMLUtils::GetString(pRecordingNode, "time", strTmp))
      {
        time_t timeNow = time(NULL);
        struct tm* now = localtime(&timeNow);

        CStdString::size_type delim = strTmp.Find(':');
        if (delim != CStdString::npos)
        {
          now->tm_hour = (int)strtol(strTmp.Left(delim), NULL, 0);
          now->tm_min  = (int)strtol(strTmp.Mid(delim + 1), NULL, 0);
          now->tm_mday--; // yesterday

          recording.recordingTime = mktime(now);
        }
      }

      m_recordingsDeleted.push_back(recording);
    }
  }

  /* load timers */
  pElement = pRootElement->FirstChildElement("timers");
  if (pElement)
  {
    TiXmlNode *pTimerNode = NULL;
    while ((pTimerNode = pElement->IterateChildren(pTimerNode)) != NULL)
    {
      CStdString strTmp;
      int iTmp;
      PVRDemoTimer timer;
      time_t timeNow = time(NULL);
      struct tm* now = localtime(&timeNow);

      /* channel id */
      if (!XMLUtils::GetInt(pTimerNode, "channelid", iTmp))
        continue;
      PVRDemoChannel &channel = m_channels.at(iTmp - 1);
      timer.iChannelId = channel.iUniqueId;

      /* state */
      if (XMLUtils::GetInt(pTimerNode, "state", iTmp))
        timer.state = (PVR_TIMER_STATE) iTmp;

      /* title */
      if (!XMLUtils::GetString(pTimerNode, "title", strTmp))
        continue;
      timer.strTitle = strTmp;

      /* summary */
      if (!XMLUtils::GetString(pTimerNode, "summary", strTmp))
        continue;
      timer.strSummary = strTmp;

      /* start time */
      if (XMLUtils::GetString(pTimerNode, "starttime", strTmp))
      {
        CStdString::size_type delim = strTmp.Find(':');
        if (delim != CStdString::npos)
        {
          now->tm_hour = (int)strtol(strTmp.Left(delim), NULL, 0);
          now->tm_min  = (int)strtol(strTmp.Mid(delim + 1), NULL, 0);

          timer.startTime = mktime(now);
        }
      }

      /* end time */
      if (XMLUtils::GetString(pTimerNode, "endtime", strTmp))
      {
        CStdString::size_type delim = strTmp.Find(':');
        if (delim != CStdString::npos)
        {
          now->tm_hour = (int)strtol(strTmp.Left(delim), NULL, 0);
          now->tm_min  = (int)strtol(strTmp.Mid(delim + 1), NULL, 0);

          timer.endTime = mktime(now);
        }
      }

      XBMC->Log(LOG_DEBUG, "loaded timer '%s' channel '%d' start '%d' end '%d'", timer.strTitle.c_str(), timer.iChannelId, timer.startTime, timer.endTime);
      m_timers.push_back(timer);
    }
  }

  return true;
}
示例#26
0
void CRssReader::GetNewsItems(TiXmlElement* channelXmlNode, int iFeed)
{
  HTML::CHTMLUtil html;

  TiXmlElement * itemNode = channelXmlNode->FirstChildElement("item");
  map <std::string, std::wstring> mTagElements;
  typedef pair <std::string, std::wstring> StrPair;
  list <std::string>::iterator i;

  // Add the title tag in if we didn't pass any tags in at all
  // Represents default behaviour before configurability

  if (m_tagSet.empty())
    AddTag("title");

  while (itemNode > 0)
  {
    TiXmlNode* childNode = itemNode->FirstChild();
    mTagElements.clear();
    while (childNode > 0)
    {
      std::string strName = childNode->ValueStr();

      for (i = m_tagSet.begin(); i != m_tagSet.end(); ++i)
      {
        if (!childNode->NoChildren() && *i == strName)
        {
          std::string htmlText = childNode->FirstChild()->ValueStr();

          // This usually happens in right-to-left languages where they want to
          // specify in the RSS body that the text should be RTL.
          // <title>
          //  <div dir="RTL">��� ����: ���� �� �����</div>
          // </title>
          if (htmlText == "div" || htmlText == "span")
            htmlText = childNode->FirstChild()->FirstChild()->ValueStr();

          std::wstring unicodeText, unicodeText2;

          g_charsetConverter.utf8ToW(htmlText, unicodeText2, m_rtlText);
          html.ConvertHTMLToW(unicodeText2, unicodeText);

          mTagElements.insert(StrPair(*i, unicodeText));
        }
      }
      childNode = childNode->NextSibling();
    }

    int rsscolour = RSS_COLOR_HEADLINE;
    for (i = m_tagSet.begin(); i != m_tagSet.end(); ++i)
    {
      map <std::string, std::wstring>::iterator j = mTagElements.find(*i);

      if (j == mTagElements.end())
        continue;

      std::wstring& text = j->second;
      AddString(text, rsscolour, iFeed);
      rsscolour = RSS_COLOR_BODY;
      text = L" - ";
      AddString(text, rsscolour, iFeed);
    }
    itemNode = itemNode->NextSiblingElement("item");
  }
}
示例#27
0
void TiXmlElement::StreamIn (std::istream * in, TIXML_STRING * tag)
{
	// We're called with some amount of pre-parsing. That is, some of "this"
	// element is in "tag". Go ahead and stream to the closing ">"
	while( in->good() )
	{
		int c = in->get();
		if ( c <= 0 )
		{
			TiXmlDocument* document = GetDocument();
			if ( document )
				document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN );
			return;
		}
		(*tag) += (char) c ;
		
		if ( c == '>' )
			break;
	}

	if ( tag->length() < 3 ) return;

	// Okay...if we are a "/>" tag, then we're done. We've read a complete tag.
	// If not, identify and stream.

	if (    tag->at( tag->length() - 1 ) == '>' 
		 && tag->at( tag->length() - 2 ) == '/' )
	{
		// All good!
		return;
	}
	else if ( tag->at( tag->length() - 1 ) == '>' )
	{
		// There is more. Could be:
		//		text
		//		cdata text (which looks like another node)
		//		closing tag
		//		another node.
		for ( ;; )
		{
			StreamWhiteSpace( in, tag );

			// Do we have text?
			if ( in->good() && in->peek() != '<' ) 
			{
				// Yep, text.
				TiXmlText text( "" );
				text.StreamIn( in, tag );

				// What follows text is a closing tag or another node.
				// Go around again and figure it out.
				continue;
			}

			// We now have either a closing tag...or another node.
			// We should be at a "<", regardless.
			if ( !in->good() ) return;
			assert( in->peek() == '<' );
			int tagIndex = (int) tag->length();

			bool closingTag = false;
			bool firstCharFound = false;

			for( ;; )
			{
				if ( !in->good() )
					return;

				int c = in->peek();
				if ( c <= 0 )
				{
					TiXmlDocument* document = GetDocument();
					if ( document )
						document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN );
					return;
				}
				
				if ( c == '>' )
					break;

				*tag += (char) c;
				in->get();

				// Early out if we find the CDATA id.
				if ( c == '[' && tag->size() >= 9 )
				{
					size_t len = tag->size();
					const char* start = tag->c_str() + len - 9;
					if ( strcmp( start, "<![CDATA[" ) == 0 ) {
						assert( !closingTag );
						break;
					}
				}

				if ( !firstCharFound && c != '<' && !IsWhiteSpace( c ) )
				{
					firstCharFound = true;
					if ( c == '/' )
						closingTag = true;
				}
			}
			// If it was a closing tag, then read in the closing '>' to clean up the input stream.
			// If it was not, the streaming will be done by the tag.
			if ( closingTag )
			{
				if ( !in->good() )
					return;

				int c = in->get();
				if ( c <= 0 )
				{
					TiXmlDocument* document = GetDocument();
					if ( document )
						document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN );
					return;
				}
				assert( c == '>' );
				*tag += (char) c;

				// We are done, once we've found our closing tag.
				return;
			}
			else
			{
				// If not a closing tag, id it, and stream.
				const char* tagloc = tag->c_str() + tagIndex;
				TiXmlNode* node = Identify( tagloc, TIXML_DEFAULT_ENCODING );
				if ( !node )
					return;
				node->StreamIn( in, tag );
				delete node;
				node = 0;

				// No return: go around from the beginning: text, closing tag, or node.
			}
		}
	}
}
示例#28
0
bool CSettings::Save()
{
	// Are we not flagged as open?
	if(!m_bOpen)
		return false;

	// Are we not flagged as allowed to save the file?
	if(!m_bSave)
		return false;

	// Loop through all values
	for(std::map<CString, SettingsValue *>::iterator iter = m_values.begin(); iter != m_values.end(); iter++)
	{
		// Get the setting pointer
		SettingsValue * setting = iter->second;

		// Find all nodes for this value
		bool bFoundNode = false;

		for(TiXmlNode * pNode = m_XMLDocument.RootElement()->FirstChildElement(iter->first.Get()); pNode; pNode = pNode->NextSibling())
		{
			// Is this not an element node?
			if(pNode->Type() != TiXmlNode::ELEMENT)
				continue;

			// Is this not the node we are looking for?
			if(iter->first.Compare(pNode->Value()))
				continue;

			// Is this a list node?
			if(setting->IsList())
			{
				// Remove the node
				m_XMLDocument.RootElement()->RemoveChild(pNode);
			}
			else
			{
				// Clear the node
				pNode->Clear();

				// Get the node value
				CString strValue = GetEx(iter->first);

				// Create a new node value
				TiXmlText * pNewNodeValue = new TiXmlText(strValue.Get());

				// Add the new node value to the new node
				pNode->LinkEndChild(pNewNodeValue);
			}

			// Flag as found a node
			bFoundNode = true;
			break;
		}

		// Is this a list value?
		if(setting->IsList())
		{
			// Loop through each list item
			for(std::list<CString>::iterator iter2 = setting->listValue.begin(); iter2 != setting->listValue.end(); iter2++)
			{
				// Create a new node
				TiXmlElement * pNewNode = new TiXmlElement(iter->first.Get());

				// Create a new node value
				TiXmlText * pNewNodeValue = new TiXmlText((*iter2).Get());

				// Add the new node value to the new node
				pNewNode->LinkEndChild(pNewNodeValue);

				// Add the new node to the XML document
				m_XMLDocument.RootElement()->LinkEndChild(pNewNode);
			}
		}
		else
		{
			// Do we need to create a new node?
			if(!bFoundNode)
			{
				// Create a new node
				TiXmlElement * pNewNode = new TiXmlElement(iter->first.Get());

				// Get the node value
				CString strValue = GetEx(iter->first);

				// Create a new node value
				TiXmlText * pNewNodeValue = new TiXmlText(strValue.Get());

				// Add the new node value to the new node
				pNewNode->LinkEndChild(pNewNodeValue);

				// Add the new node to the XML document
				m_XMLDocument.RootElement()->LinkEndChild(pNewNode);
			}
		}
	}

	// Save the XML document
	return m_XMLDocument.SaveFile();
}
示例#29
0
const wchar_t* TiXmlDocument::Parse( const wchar_t* p, TiXmlParsingData* prevData, TiXmlEncoding encoding )
{
	ClearError();

	// Parse away, at the document level. Since a document
	// contains nothing but other tags, most of what happens
	// here is skipping white space.
	if ( !p || !*p )
	{
		SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN );
		return 0;
	}

	// Note that, for a document, this needs to come
	// before the while space skip, so that parsing
	// starts from the pointer we are given.
	location.Clear();
	if ( prevData )
	{
		location.row = prevData->cursor.row;
		location.col = prevData->cursor.col;
	}
	else
	{
		location.row = 0;
		location.col = 0;
	}
	TiXmlParsingData data( p, TabSize(), location.row, location.col );
	location = data.Cursor();

	if ( encoding == TIXML_ENCODING_UNKNOWN )
	{
		// Check for the Microsoft UTF-8 lead bytes.
		const wchar_t* pU = (const wchar_t*)p;
		if (	*(pU+0) && *(pU+0) == TIXML_UTF_LEAD_0
			 && *(pU+1) && *(pU+1) == TIXML_UTF_LEAD_1
			 && *(pU+2) && *(pU+2) == TIXML_UTF_LEAD_2 )
		{
			encoding = TIXML_ENCODING_UTF8;
			useMicrosoftBOM = true;
		}
	}

    p = SkipWhiteSpace( p, encoding );
	if ( !p )
	{
		SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN );
		return 0;
	}

	while ( p && *p )
	{
		TiXmlNode* node = Identify( p, encoding );
		if ( node )
		{
			p = node->Parse( p, &data, encoding );
			LinkEndChild( node );
		}
		else
		{
			break;
		}

		// Did we get encoding info?
		if (    encoding == TIXML_ENCODING_UNKNOWN
			 && node->ToDeclaration() )
		{
			TiXmlDeclaration* dec = node->ToDeclaration();
			const wchar_t* enc = dec->Encoding();
			assert( enc );

			if ( *enc == 0 )
				encoding = TIXML_ENCODING_UTF8;
			else if ( StringEqual( enc, L"UTF-8", true, TIXML_ENCODING_UNKNOWN ) )
				encoding = TIXML_ENCODING_UTF8;
			else if ( StringEqual( enc, L"UTF8", true, TIXML_ENCODING_UNKNOWN ) )
				encoding = TIXML_ENCODING_UTF8;	// incorrect, but be nice
			else 
				encoding = TIXML_ENCODING_LEGACY;
		}

		p = SkipWhiteSpace( p, encoding );
	}

	// Was this empty?
	if ( !firstChild ) {
		SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, encoding );
		return 0;
	}

	// All is well.
	return p;
}
示例#30
0
//-------------------------------------------------------------------------------------
bool ServerConfig::loadConfig(std::string fileName)
{
	TiXmlNode* node = NULL, *rootNode = NULL;
	XmlPlus* xml = new XmlPlus(Resmgr::getSingleton().matchRes(fileName).c_str());

	if(!xml->isGood())
	{
		ERROR_MSG(boost::format("ServerConfig::loadConfig: load %1% is failed!\n") %
			fileName.c_str());

		SAFE_RELEASE(xml);
		return false;
	}
	
	std::string email_service_config;
	rootNode = xml->getRootNode("email_service_config");
	if(rootNode != NULL)
	{
		email_service_config = xml->getValStr(rootNode);
	}

	rootNode = xml->getRootNode("packetAlwaysContainLength");
	if(rootNode != NULL){
		Mercury::g_packetAlwaysContainLength = xml->getValInt(rootNode) != 0;
	}

	rootNode = xml->getRootNode("trace_packet");
	if(rootNode != NULL)
	{
		TiXmlNode* childnode = xml->enterNode(rootNode, "debug_type");
		if(childnode)
			Mercury::g_trace_packet = xml->getValInt(childnode);

		if(Mercury::g_trace_packet > 3)
			Mercury::g_trace_packet = 0;

		childnode = xml->enterNode(rootNode, "use_logfile");
		if(childnode)
			Mercury::g_trace_packet_use_logfile = (xml->getValStr(childnode) == "true");

		childnode = xml->enterNode(rootNode, "disables");
		if(childnode)
		{
			do																				
			{	
				if(childnode->FirstChild() != NULL)
				{
					std::string c = childnode->FirstChild()->Value();
					c = strutil::kbe_trim(c);
					if(c.size() > 0)
					{
						Mercury::g_trace_packet_disables.push_back(c);
					}
				}
			}while((childnode = childnode->NextSibling()));												
		}
	}

	rootNode = xml->getRootNode("debugEntity");
	if(rootNode != NULL)
	{
		g_debugEntity = xml->getValInt(rootNode) > 0;
	}

	rootNode = xml->getRootNode("app_publish");
	if(rootNode != NULL)
	{
		g_appPublish = xml->getValInt(rootNode);
	}

	rootNode = xml->getRootNode("shutdown_time");
	if(rootNode != NULL)
	{
		shutdown_time_ = float(xml->getValFloat(rootNode));
	}
	
	rootNode = xml->getRootNode("shutdown_waittick");
	if(rootNode != NULL)
	{
		shutdown_waitTickTime_ = float(xml->getValFloat(rootNode));
	}

	rootNode = xml->getRootNode("callback_timeout");
	if(rootNode != NULL)
	{
		callback_timeout_ = float(xml->getValFloat(rootNode));
		if(callback_timeout_ < 5.f)
			callback_timeout_ = 5.f;
	}
	
	rootNode = xml->getRootNode("thread_pool");
	if(rootNode != NULL)
	{
		TiXmlNode* childnode = xml->enterNode(rootNode, "timeout");
		if(childnode)
		{
			thread_timeout_ = float(KBE_MAX(1.0, xml->getValFloat(childnode)));
		}

		childnode = xml->enterNode(rootNode, "init_create");
		if(childnode)
		{
			thread_init_create_ = KBE_MAX(1, xml->getValInt(childnode));
		}

		childnode = xml->enterNode(rootNode, "pre_create");
		if(childnode)
		{
			thread_pre_create_ = KBE_MAX(1, xml->getValInt(childnode));
		}

		childnode = xml->enterNode(rootNode, "max_create");
		if(childnode)
		{
			thread_max_create_ = KBE_MAX(1, xml->getValInt(childnode));
		}
	}

	rootNode = xml->getRootNode("channelCommon");
	if(rootNode != NULL)
	{
		TiXmlNode* childnode = xml->enterNode(rootNode, "timeout");
		if(childnode)
		{
			TiXmlNode* childnode1 = xml->enterNode(childnode, "internal");
			if(childnode1)
			{
				channelCommon_.channelInternalTimeout = KBE_MAX(1.f, float(xml->getValFloat(childnode1)));
				Mercury::g_channelInternalTimeout = channelCommon_.channelInternalTimeout;
			}

			childnode1 = xml->enterNode(childnode, "external");
			if(childnode)
			{
				channelCommon_.channelExternalTimeout = KBE_MAX(1.f, float(xml->getValFloat(childnode1)));
				Mercury::g_channelExternalTimeout = channelCommon_.channelExternalTimeout;
			}
		}

		childnode = xml->enterNode(rootNode, "readBufferSize");
		if(childnode)
		{
			TiXmlNode* childnode1 = xml->enterNode(childnode, "internal");
			if(childnode1)
				channelCommon_.intReadBufferSize = KBE_MAX(0, xml->getValInt(childnode1));

			childnode1 = xml->enterNode(childnode, "external");
			if(childnode1)
				channelCommon_.extReadBufferSize = KBE_MAX(0, xml->getValInt(childnode1));
		}

		childnode = xml->enterNode(rootNode, "writeBufferSize");
		if(childnode)
		{
			TiXmlNode* childnode1 = xml->enterNode(childnode, "internal");
			if(childnode1)
				channelCommon_.intWriteBufferSize = KBE_MAX(0, xml->getValInt(childnode1));

			childnode1 = xml->enterNode(childnode, "external");
			if(childnode1)
				channelCommon_.extWriteBufferSize = KBE_MAX(0, xml->getValInt(childnode1));
		}

		childnode = xml->enterNode(rootNode, "receiveWindowOverflow");
		if(childnode)
		{
			TiXmlNode* childnode1 = xml->enterNode(childnode, "messages");
			if(childnode1)
			{
				TiXmlNode* childnode2 = xml->enterNode(childnode1, "internal");
				if(childnode2)
					Mercury::g_intReceiveWindowMessagesOverflow = KBE_MAX(0, xml->getValInt(childnode2));

				childnode2 = xml->enterNode(childnode1, "external");
				if(childnode2)
					Mercury::g_extReceiveWindowMessagesOverflow = KBE_MAX(0, xml->getValInt(childnode2));

				childnode2 = xml->enterNode(childnode1, "critical");
				if(childnode2)
					Mercury::g_receiveWindowMessagesOverflowCritical = KBE_MAX(0, xml->getValInt(childnode2));
			}

			childnode1 = xml->enterNode(childnode, "bytes");
			if(childnode1)
			{
				TiXmlNode* childnode2 = xml->enterNode(childnode1, "internal");
				if(childnode2)
					Mercury::g_intReceiveWindowBytesOverflow = KBE_MAX(0, xml->getValInt(childnode2));
				
				childnode2 = xml->enterNode(childnode1, "external");
				if(childnode2)
					Mercury::g_extReceiveWindowBytesOverflow = KBE_MAX(0, xml->getValInt(childnode2));
			}
		};

		childnode = xml->enterNode(rootNode, "encrypt_type");
		if(childnode)
		{
			Mercury::g_channelExternalEncryptType = xml->getValInt(childnode);
		}
	}

	rootNode = xml->getRootNode("gameUpdateHertz");
	if(rootNode != NULL){
		gameUpdateHertz_ = xml->getValInt(rootNode);
	}

	rootNode = xml->getRootNode("bitsPerSecondToClient");
	if(rootNode != NULL){
		bitsPerSecondToClient_ = xml->getValInt(rootNode);
	}

	rootNode = xml->getRootNode("billingSystem");
	if(rootNode != NULL)
	{
		TiXmlNode* childnode = xml->enterNode(rootNode, "accountType");
		if(childnode)
		{
			billingSystem_accountType_ = xml->getValStr(childnode);
			if(billingSystem_accountType_.size() == 0)
				billingSystem_accountType_ = "normal";
		}

		childnode = xml->enterNode(rootNode, "chargeType");
		if(childnode)
		{
			billingSystem_chargeType_ = xml->getValStr(childnode);
			if(billingSystem_chargeType_.size() == 0)
				billingSystem_chargeType_ = "normal";
		}

		std::string ip = "";
		childnode = xml->enterNode(rootNode, "host");
		if(childnode)
		{
			ip = xml->getValStr(childnode);
			if(ip.size() == 0)
				ip = "localhost";

			Mercury::Address addr(ip, ntohs(billingSystemAddr_.port));
			billingSystemAddr_ = addr;
		}

		uint16 port = 0;
		childnode = xml->enterNode(rootNode, "port");
		if(childnode)
		{
			port = xml->getValInt(childnode);

			if(port <= 0)
				port = KBE_BILLING_TCP_PORT;

			Mercury::Address addr(inet_ntoa((struct in_addr&)billingSystemAddr_.ip), port);
			billingSystemAddr_ = addr;
		}

		childnode = xml->enterNode(rootNode, "thirdpartyAccountService_addr");
		if(childnode)
		{
			billingSystem_thirdpartyAccountServiceAddr_ = xml->getValStr(childnode);
		}

		childnode = xml->enterNode(rootNode, "thirdpartyAccountService_port");
		if(childnode)
		{
			billingSystem_thirdpartyAccountServicePort_ = xml->getValInt(childnode);
		}
		
		childnode = xml->enterNode(rootNode, "thirdpartyChargeService_addr");
		if(childnode)
		{
			billingSystem_thirdpartyChargeServiceAddr_ = xml->getValStr(childnode);
		}

		childnode = xml->enterNode(rootNode, "thirdpartyChargeService_port");
		if(childnode)
		{
			billingSystem_thirdpartyChargeServicePort_ = xml->getValInt(childnode);
		}

		childnode = xml->enterNode(rootNode, "thirdpartyService_cbport");
		if(childnode)
		{
			billingSystem_thirdpartyServiceCBPort_ = xml->getValInt(childnode);
		}

		node = xml->enterNode(rootNode, "SOMAXCONN");
		if(node != NULL){
			_billingInfo.tcp_SOMAXCONN = xml->getValInt(node);
		}

		node = xml->enterNode(rootNode, "orders_timeout");
		if(node != NULL){
			billingSystem_orders_timeout_ = xml->getValInt(node);
		}
	}

	rootNode = xml->getRootNode("cellapp");
	if(rootNode != NULL)
	{
		node = xml->enterNode(rootNode, "internalInterface");	
		if(node != NULL)
			strncpy((char*)&_cellAppInfo.internalInterface, xml->getValStr(node).c_str(), MAX_NAME);

		node = xml->enterNode(rootNode, "entryScriptFile");	
		if(node != NULL)
			strncpy((char*)&_cellAppInfo.entryScriptFile, xml->getValStr(node).c_str(), MAX_NAME);
		
		TiXmlNode* aoiNode = xml->enterNode(rootNode, "defaultAoIRadius");
		if(aoiNode != NULL)
		{
			node = NULL;
			node = xml->enterNode(aoiNode, "radius");
			if(node != NULL)
				_cellAppInfo.defaultAoIRadius = float(xml->getValFloat(node));
					
			node = xml->enterNode(aoiNode, "hysteresisArea");
			if(node != NULL)
				_cellAppInfo.defaultAoIHysteresisArea = float(xml->getValFloat(node));
		}
			
		node = xml->enterNode(rootNode, "ids");
		if(node != NULL)
		{
			TiXmlNode* childnode = xml->enterNode(node, "criticallyLowSize");
			if(childnode)
			{
				_cellAppInfo.criticallyLowSize = xml->getValInt(childnode);
				if(_cellAppInfo.criticallyLowSize < 100)
					_cellAppInfo.criticallyLowSize = 100;
			}
		}
		
		node = xml->enterNode(rootNode, "profiles");
		if(node != NULL)
		{
			TiXmlNode* childnode = xml->enterNode(node, "cprofile");
			if(childnode)
			{
				_cellAppInfo.profiles.open_cprofile = (xml->getValStr(childnode) == "true");
			}

			childnode = xml->enterNode(node, "pyprofile");
			if(childnode)
			{
				_cellAppInfo.profiles.open_pyprofile = (xml->getValStr(childnode) == "true");
			}

			childnode = xml->enterNode(node, "eventprofile");
			if(childnode)
			{
				_cellAppInfo.profiles.open_eventprofile = (xml->getValStr(childnode) == "true");
			}

			childnode = xml->enterNode(node, "mercuryprofile");
			if(childnode)
			{
				_cellAppInfo.profiles.open_mercuryprofile = (xml->getValStr(childnode) == "true");
			}
		}

		node = xml->enterNode(rootNode, "SOMAXCONN");
		if(node != NULL){
			_cellAppInfo.tcp_SOMAXCONN = xml->getValInt(node);
		}

		node = xml->enterNode(rootNode, "ghostDistance");
		if(node != NULL){
			_cellAppInfo.ghostDistance = (float)xml->getValFloat(node);
		}

		node = xml->enterNode(rootNode, "ghostingMaxPerCheck");
		if(node != NULL){
			_cellAppInfo.ghostingMaxPerCheck = xml->getValInt(node);
		}

		node = xml->enterNode(rootNode, "ghostUpdateHertz");
		if(node != NULL){
			_cellAppInfo.ghostUpdateHertz = xml->getValInt(node);
		}

		node = xml->enterNode(rootNode, "coordinate_system");
		if(node != NULL)
		{
			TiXmlNode* childnode = xml->enterNode(node, "enable");
			if(childnode)
			{
				_cellAppInfo.use_coordinate_system = (xml->getValStr(childnode) == "true");
			}
			
			childnode = xml->enterNode(node, "rangemgr_y");
			if(childnode)
			{
				_cellAppInfo.rangelist_hasY = (xml->getValStr(childnode) == "true");
			}
		}

		node = xml->enterNode(rootNode, "telnet_service");
		if(node != NULL)
		{
			TiXmlNode* childnode = xml->enterNode(node, "port");
			if(childnode)
			{
				_cellAppInfo.telnet_port = xml->getValInt(childnode);
			}

			childnode = xml->enterNode(node, "password");
			if(childnode)
			{
				_cellAppInfo.telnet_passwd = xml->getValStr(childnode);
			}

			childnode = xml->enterNode(node, "default_layer");
			if(childnode)
			{
				_cellAppInfo.telnet_deflayer = xml->getValStr(childnode);
			}
		}

		node = xml->enterNode(rootNode, "shutdown");
		if(node != NULL)
		{
			TiXmlNode* childnode = xml->enterNode(node, "perSecsDestroyEntitySize");
			if(childnode)
			{
				_cellAppInfo.perSecsDestroyEntitySize = uint32(xml->getValInt(childnode));
			}
		}
	}
	
	rootNode = xml->getRootNode("baseapp");
	if(rootNode != NULL)
	{
		node = xml->enterNode(rootNode, "entryScriptFile");	
		if(node != NULL)
			strncpy((char*)&_baseAppInfo.entryScriptFile, xml->getValStr(node).c_str(), MAX_NAME);

		node = xml->enterNode(rootNode, "internalInterface");	
		if(node != NULL)
			strncpy((char*)&_baseAppInfo.internalInterface, xml->getValStr(node).c_str(), MAX_NAME);

		node = xml->enterNode(rootNode, "externalInterface");	
		if(node != NULL)
			strncpy((char*)&_baseAppInfo.externalInterface, xml->getValStr(node).c_str(), MAX_NAME);

		node = xml->enterNode(rootNode, "externalPorts_min");
		if(node != NULL)	
			_baseAppInfo.externalPorts_min = xml->getValInt(node);

		node = xml->enterNode(rootNode, "externalPorts_max");
		if(node != NULL)	
			_baseAppInfo.externalPorts_max = xml->getValInt(node);

		if(_baseAppInfo.externalPorts_min < 0)
			_baseAppInfo.externalPorts_min = 0;
		if(_baseAppInfo.externalPorts_max < _baseAppInfo.externalPorts_min)
			_baseAppInfo.externalPorts_max = _baseAppInfo.externalPorts_min;

		node = xml->enterNode(rootNode, "archivePeriod");
		if(node != NULL)
			_baseAppInfo.archivePeriod = float(xml->getValFloat(node));
				
		node = xml->enterNode(rootNode, "backupPeriod");
		if(node != NULL)
			_baseAppInfo.backupPeriod = float(xml->getValFloat(node));
		
		node = xml->enterNode(rootNode, "backUpUndefinedProperties");
		if(node != NULL)
			_baseAppInfo.backUpUndefinedProperties = xml->getValInt(node) > 0;
			
		node = xml->enterNode(rootNode, "loadSmoothingBias");
		if(node != NULL)
			_baseAppInfo.loadSmoothingBias = float(xml->getValFloat(node));
		
		node = xml->enterNode(rootNode, "ids");
		if(node != NULL)
		{
			TiXmlNode* childnode = xml->enterNode(node, "criticallyLowSize");
			if(childnode)
			{
				_baseAppInfo.criticallyLowSize = xml->getValInt(childnode);
				if(_baseAppInfo.criticallyLowSize < 100)
					_baseAppInfo.criticallyLowSize = 100;
			}
		}
		
		node = xml->enterNode(rootNode, "downloadStreaming");
		if(node != NULL)
		{
			TiXmlNode* childnode = xml->enterNode(node, "bitsPerSecondTotal");
			if(childnode)
				_baseAppInfo.downloadBitsPerSecondTotal = xml->getValInt(childnode);

			childnode = xml->enterNode(node, "bitsPerSecondPerClient");
			if(childnode)
				_baseAppInfo.downloadBitsPerSecondPerClient = xml->getValInt(childnode);
		}
	
		node = xml->enterNode(rootNode, "profiles");
		if(node != NULL)
		{
			TiXmlNode* childnode = xml->enterNode(node, "cprofile");
			if(childnode)
			{
				_baseAppInfo.profiles.open_cprofile = (xml->getValStr(childnode) == "true");
			}

			childnode = xml->enterNode(node, "pyprofile");
			if(childnode)
			{
				_baseAppInfo.profiles.open_pyprofile = (xml->getValStr(childnode) == "true");
			}

			childnode = xml->enterNode(node, "eventprofile");
			if(childnode)
			{
				_baseAppInfo.profiles.open_eventprofile = (xml->getValStr(childnode) == "true");
			}

			childnode = xml->enterNode(node, "mercuryprofile");
			if(childnode)
			{
				_baseAppInfo.profiles.open_mercuryprofile = (xml->getValStr(childnode) == "true");
			}
		}

		node = xml->enterNode(rootNode, "SOMAXCONN");
		if(node != NULL){
			_baseAppInfo.tcp_SOMAXCONN = xml->getValInt(node);
		}

		node = xml->enterNode(rootNode, "entityRestoreSize");
		if(node != NULL){
			_baseAppInfo.entityRestoreSize = xml->getValInt(node);
		}
		
		if(_baseAppInfo.entityRestoreSize <= 0)
			_baseAppInfo.entityRestoreSize = 32;

		node = xml->enterNode(rootNode, "telnet_service");
		if(node != NULL)
		{
			TiXmlNode* childnode = xml->enterNode(node, "port");
			if(childnode)
			{
				_baseAppInfo.telnet_port = xml->getValInt(childnode);
			}

			childnode = xml->enterNode(node, "password");
			if(childnode)
			{
				_baseAppInfo.telnet_passwd = xml->getValStr(childnode);
			}

			childnode = xml->enterNode(node, "default_layer");
			if(childnode)
			{
				_baseAppInfo.telnet_deflayer = xml->getValStr(childnode);
			}
		}

		node = xml->enterNode(rootNode, "shutdown");
		if(node != NULL)
		{
			TiXmlNode* childnode = xml->enterNode(node, "perSecsDestroyEntitySize");
			if(childnode)
			{
				_baseAppInfo.perSecsDestroyEntitySize = uint32(xml->getValInt(childnode));
			}
		}

		node = xml->enterNode(rootNode, "respool");
		if(node != NULL)
		{
			TiXmlNode* childnode = xml->enterNode(node, "buffer_size");
			if(childnode)
				_baseAppInfo.respool_buffersize = xml->getValInt(childnode);

			childnode = xml->enterNode(node, "timeout");
			if(childnode)
				_baseAppInfo.respool_timeout = uint64(xml->getValInt(childnode));

			childnode = xml->enterNode(node, "checktick");
			if(childnode)
				Resmgr::respool_checktick = xml->getValInt(childnode);

			Resmgr::respool_timeout = _baseAppInfo.respool_timeout;
			Resmgr::respool_buffersize = _baseAppInfo.respool_buffersize;
		}
	}

	rootNode = xml->getRootNode("dbmgr");
	if(rootNode != NULL)
	{
		node = xml->enterNode(rootNode, "internalInterface");	
		if(node != NULL)
			strncpy((char*)&_dbmgrInfo.internalInterface, xml->getValStr(node).c_str(), MAX_NAME);

		node = xml->enterNode(rootNode, "dbAccountEntityScriptType");	
		if(node != NULL)
			strncpy((char*)&_dbmgrInfo.dbAccountEntityScriptType, xml->getValStr(node).c_str(), MAX_NAME);

		node = xml->enterNode(rootNode, "type");	
		if(node != NULL)
			strncpy((char*)&_dbmgrInfo.db_type, xml->getValStr(node).c_str(), MAX_NAME);

		node = xml->enterNode(rootNode, "host");	
		if(node != NULL)
			strncpy((char*)&_dbmgrInfo.db_ip, xml->getValStr(node).c_str(), MAX_IP);

		node = xml->enterNode(rootNode, "port");	
		if(node != NULL)
			_dbmgrInfo.db_port = xml->getValInt(node);	

		node = xml->enterNode(rootNode, "auth");	
		if(node != NULL)
		{
			TiXmlNode* childnode = xml->enterNode(node, "password");
			if(childnode)
			{
				strncpy((char*)&_dbmgrInfo.db_password, xml->getValStr(childnode).c_str(), MAX_BUF * 10);
			}

			childnode = xml->enterNode(node, "username");
			if(childnode)
			{
				strncpy((char*)&_dbmgrInfo.db_username, xml->getValStr(childnode).c_str(), MAX_NAME);
			}

			childnode = xml->enterNode(node, "encrypt");
			if(childnode)
			{
				_dbmgrInfo.db_passwordEncrypt = xml->getValStr(childnode) == "true";
			}
		}
		
		node = xml->enterNode(rootNode, "databaseName");	
		if(node != NULL)
			strncpy((char*)&_dbmgrInfo.db_name, xml->getValStr(node).c_str(), MAX_NAME);

		node = xml->enterNode(rootNode, "numConnections");	
		if(node != NULL)
			_dbmgrInfo.db_numConnections = xml->getValInt(node);
		
		node = xml->enterNode(rootNode, "unicodeString");
		if(node != NULL)
		{
			TiXmlNode* childnode = xml->enterNode(node, "characterSet");
			if(childnode)
			{
				_dbmgrInfo.db_unicodeString_characterSet = xml->getValStr(childnode);
			}

			childnode = xml->enterNode(node, "collation");
			if(childnode)
			{
				_dbmgrInfo.db_unicodeString_collation = xml->getValStr(childnode);
			}
		}

		node = xml->enterNode(rootNode, "SOMAXCONN");
		if(node != NULL){
			_dbmgrInfo.tcp_SOMAXCONN = xml->getValInt(node);
		}

		node = xml->enterNode(rootNode, "notFoundAccountAutoCreate");
		if(node != NULL){
			_dbmgrInfo.notFoundAccountAutoCreate = (xml->getValStr(node) == "true");
		}
		
		node = xml->enterNode(rootNode, "allowEmptyDigest");
		if(node != NULL){
			_dbmgrInfo.allowEmptyDigest = (xml->getValStr(node) == "true");
		}

		node = xml->enterNode(rootNode, "accountDefaultFlags");	
		if(node != NULL)
			_dbmgrInfo.accountDefaultFlags = xml->getValInt(node);	

		node = xml->enterNode(rootNode, "accountDefaultDeadline");	
		if(node != NULL)
			_dbmgrInfo.accountDefaultDeadline = xml->getValInt(node);	
	}

	if(_dbmgrInfo.db_unicodeString_characterSet.size() == 0)
		_dbmgrInfo.db_unicodeString_characterSet = "utf8";

	if(_dbmgrInfo.db_unicodeString_collation.size() == 0)
		_dbmgrInfo.db_unicodeString_collation = "utf8_bin";

	rootNode = xml->getRootNode("loginapp");
	if(rootNode != NULL)
	{
		node = xml->enterNode(rootNode, "internalInterface");	
		if(node != NULL)
			strncpy((char*)&_loginAppInfo.internalInterface, xml->getValStr(node).c_str(), MAX_NAME);

		node = xml->enterNode(rootNode, "externalInterface");	
		if(node != NULL)
			strncpy((char*)&_loginAppInfo.externalInterface, xml->getValStr(node).c_str(), MAX_NAME);

		node = xml->enterNode(rootNode, "externalPorts_min");
		if(node != NULL)	
			_loginAppInfo.externalPorts_min = xml->getValInt(node);

		node = xml->enterNode(rootNode, "externalPorts_max");
		if(node != NULL)	
			_loginAppInfo.externalPorts_max = xml->getValInt(node);

		if(_loginAppInfo.externalPorts_min < 0)
			_loginAppInfo.externalPorts_min = 0;
		if(_loginAppInfo.externalPorts_max < _loginAppInfo.externalPorts_min)
			_loginAppInfo.externalPorts_max = _loginAppInfo.externalPorts_min;

		node = xml->enterNode(rootNode, "SOMAXCONN");
		if(node != NULL){
			_loginAppInfo.tcp_SOMAXCONN = xml->getValInt(node);
		}

		node = xml->enterNode(rootNode, "encrypt_login");
		if(node != NULL){
			_loginAppInfo.encrypt_login = xml->getValInt(node);
		}

		node = xml->enterNode(rootNode, "account_type");
		if(node != NULL){
			_loginAppInfo.account_type = xml->getValInt(node);
		}

		node = xml->enterNode(rootNode, "http_cbhost");
		if(node)
			_loginAppInfo.http_cbhost = xml->getValStr(node);

		node = xml->enterNode(rootNode, "http_cbport");
		if(node)
			_loginAppInfo.http_cbport = xml->getValInt(node);
	}
	
	rootNode = xml->getRootNode("cellappmgr");
	if(rootNode != NULL)
	{
		node = xml->enterNode(rootNode, "internalInterface");	
		if(node != NULL)
			strncpy((char*)&_cellAppMgrInfo.internalInterface, xml->getValStr(node).c_str(), MAX_NAME);

		node = xml->enterNode(rootNode, "SOMAXCONN");
		if(node != NULL){
			_cellAppMgrInfo.tcp_SOMAXCONN = xml->getValInt(node);
		}
	}
	
	rootNode = xml->getRootNode("baseappmgr");
	if(rootNode != NULL)
	{
		node = xml->enterNode(rootNode, "internalInterface");	
		if(node != NULL)
			strncpy((char*)&_baseAppMgrInfo.internalInterface, xml->getValStr(node).c_str(), MAX_NAME);

		node = xml->enterNode(rootNode, "SOMAXCONN");
		if(node != NULL){
			_baseAppMgrInfo.tcp_SOMAXCONN = xml->getValInt(node);
		}
	}
	
	rootNode = xml->getRootNode("kbmachine");
	if(rootNode != NULL)
	{
		node = xml->enterNode(rootNode, "internalInterface");	
		if(node != NULL)
			strncpy((char*)&_kbMachineInfo.internalInterface, xml->getValStr(node).c_str(), MAX_NAME);

		node = xml->enterNode(rootNode, "externalInterface");	
		if(node != NULL)
			strncpy((char*)&_kbMachineInfo.externalInterface, xml->getValStr(node).c_str(), MAX_NAME);

		node = xml->enterNode(rootNode, "externalPorts_min");
		if(node != NULL)	
			_kbMachineInfo.externalPorts_min = xml->getValInt(node);

		node = xml->enterNode(rootNode, "externalPorts_max");
		if(node != NULL)	
			_kbMachineInfo.externalPorts_max = xml->getValInt(node);

		if(_kbMachineInfo.externalPorts_min < 0)
			_kbMachineInfo.externalPorts_min = 0;
		if(_kbMachineInfo.externalPorts_max < _kbMachineInfo.externalPorts_min)
			_kbMachineInfo.externalPorts_max = _kbMachineInfo.externalPorts_min;

		node = xml->enterNode(rootNode, "SOMAXCONN");
		if(node != NULL){
			_kbMachineInfo.tcp_SOMAXCONN = xml->getValInt(node);
		}
	}

	rootNode = xml->getRootNode("kbcenter");
	if(rootNode != NULL)
	{
		node = xml->enterNode(rootNode, "internalInterface");	
		if(node != NULL)
			strncpy((char*)&_kbCenterInfo.internalInterface, xml->getValStr(node).c_str(), MAX_NAME);

		node = xml->enterNode(rootNode, "SOMAXCONN");
		if(node != NULL){
			_kbCenterInfo.tcp_SOMAXCONN = xml->getValInt(node);
		}
	}
	
	rootNode = xml->getRootNode("bots");
	if(rootNode != NULL)
	{
		node = xml->enterNode(rootNode, "bots");	
		if(node != NULL)
			strncpy((char*)&_botsInfo.internalInterface, xml->getValStr(node).c_str(), MAX_NAME);

		node = xml->enterNode(rootNode, "host");	
		if(node != NULL)
			strncpy((char*)&_botsInfo.login_ip, xml->getValStr(node).c_str(), MAX_IP);

		node = xml->enterNode(rootNode, "port");	
		if(node != NULL)
			_botsInfo.login_port = xml->getValInt(node);

		node = xml->enterNode(rootNode, "defaultAddBots");
		if(node != NULL)
		{
			TiXmlNode* childnode = xml->enterNode(node, "totalcount");
			if(childnode)
			{
				_botsInfo.defaultAddBots_totalCount = xml->getValInt(childnode);
			}

			childnode = xml->enterNode(node, "tickcount");
			if(childnode)
			{
				_botsInfo.defaultAddBots_tickCount = xml->getValInt(childnode);
			}

			childnode = xml->enterNode(node, "ticktime");
			if(childnode)
			{
				_botsInfo.defaultAddBots_tickTime = (float)xml->getValFloat(childnode);
			}
		}

		node = xml->enterNode(rootNode, "SOMAXCONN");
		if(node != NULL){
			_botsInfo.tcp_SOMAXCONN = xml->getValInt(node);
		}
	}

	rootNode = xml->getRootNode("messagelog");
	if(rootNode != NULL)
	{
		node = xml->enterNode(rootNode, "messagelog");	
		if(node != NULL)
			strncpy((char*)&_messagelogInfo.internalInterface, xml->getValStr(node).c_str(), MAX_NAME);

		node = xml->enterNode(rootNode, "SOMAXCONN");
		if(node != NULL){
			_messagelogInfo.tcp_SOMAXCONN = xml->getValInt(node);
		}
	}

	rootNode = xml->getRootNode("resourcemgr");
	if(rootNode != NULL)
	{
		node = xml->enterNode(rootNode, "resourcemgr");	
		if(node != NULL)
			strncpy((char*)&_resourcemgrInfo.internalInterface, xml->getValStr(node).c_str(), MAX_NAME);

		node = xml->enterNode(rootNode, "SOMAXCONN");
		if(node != NULL){
			_resourcemgrInfo.tcp_SOMAXCONN = xml->getValInt(node);
		}

		node = xml->enterNode(rootNode, "respool");
		if(node != NULL)
		{
			TiXmlNode* childnode = xml->enterNode(node, "buffer_size");
			if(childnode)
				_resourcemgrInfo.respool_buffersize = xml->getValInt(childnode);

			childnode = xml->enterNode(node, "timeout");
			if(childnode)
				_resourcemgrInfo.respool_timeout = uint64(xml->getValInt(childnode));

			childnode = xml->enterNode(node, "checktick");
			if(childnode)
				Resmgr::respool_checktick = xml->getValInt(childnode);

			Resmgr::respool_timeout = _resourcemgrInfo.respool_timeout;
			Resmgr::respool_buffersize = _resourcemgrInfo.respool_buffersize;
		}
	}

	SAFE_RELEASE(xml);

	if(email_service_config.size() > 0)
	{
		xml = new XmlPlus(Resmgr::getSingleton().matchRes(email_service_config).c_str());

		if(!xml->isGood())
		{
			ERROR_MSG(boost::format("ServerConfig::loadConfig: load %1% is failed!\n") %
				email_service_config.c_str());

			SAFE_RELEASE(xml);
			return false;
		}

		TiXmlNode* childnode = xml->getRootNode("smtp_server");
		if(childnode)
			emailServerInfo_.smtp_server = xml->getValStr(childnode);

		childnode = xml->getRootNode("smtp_port");
		if(childnode)
			emailServerInfo_.smtp_port = xml->getValInt(childnode);

		childnode = xml->getRootNode("username");
		if(childnode)
			emailServerInfo_.username = xml->getValStr(childnode);

		childnode = xml->getRootNode("password");
		if(childnode)
			emailServerInfo_.password = xml->getValStr(childnode);

		childnode = xml->getRootNode("smtp_auth");
		if(childnode)
			emailServerInfo_.smtp_auth = xml->getValInt(childnode);

		TiXmlNode* rootNode1 = xml->getRootNode("email_activation");
		if(rootNode1 != NULL)
		{
			TiXmlNode* childnode1 = xml->enterNode(rootNode1, "subject");
			if(childnode1)
				emailAtivationInfo_.subject = childnode1->ToText()->Value();

			childnode1 = xml->enterNode(rootNode1, "message");
			if(childnode1)
				emailAtivationInfo_.message = childnode1->ToText()->Value();

			childnode1 = xml->enterNode(rootNode1, "deadline");
			if(childnode1)
				emailAtivationInfo_.deadline = xml->getValInt(childnode1);

			childnode1 = xml->enterNode(rootNode1, "backlink_success_message");
			if(childnode1)
				emailAtivationInfo_.backlink_success_message = childnode1->ToText()->Value();

			childnode1 = xml->enterNode(rootNode1, "backlink_fail_message");
			if(childnode1)
				emailAtivationInfo_.backlink_fail_message = childnode1->ToText()->Value();

			childnode1 = xml->enterNode(rootNode1, "backlink_hello_message");
			if(childnode1)
				emailAtivationInfo_.backlink_hello_message = childnode1->ToText()->Value();
		}

		rootNode1 = xml->getRootNode("email_resetpassword");
		if(rootNode1 != NULL)
		{
			TiXmlNode* childnode1 = xml->enterNode(rootNode1, "subject");
			if(childnode1)
				emailResetPasswordInfo_.subject = childnode1->ToText()->Value();

			childnode1 = xml->enterNode(rootNode1, "message");
			if(childnode1)
				emailResetPasswordInfo_.message = childnode1->ToText()->Value();

			childnode1 = xml->enterNode(rootNode1, "deadline");
			if(childnode1)
				emailResetPasswordInfo_.deadline = xml->getValInt(childnode1);

			childnode1 = xml->enterNode(rootNode1, "backlink_success_message");
			if(childnode1)
				emailResetPasswordInfo_.backlink_success_message = childnode1->ToText()->Value();

			childnode1 = xml->enterNode(rootNode1, "backlink_fail_message");
			if(childnode1)
				emailResetPasswordInfo_.backlink_fail_message = childnode1->ToText()->Value();

			childnode1 = xml->enterNode(rootNode1, "backlink_hello_message");
			if(childnode1)
				emailResetPasswordInfo_.backlink_hello_message = childnode1->ToText()->Value();
		}

		rootNode1 = xml->getRootNode("email_bind");
		if(rootNode1 != NULL)
		{
			TiXmlNode* childnode1 = xml->enterNode(rootNode1, "subject");
			if(childnode1)
				emailBindInfo_.subject = childnode1->ToText()->Value();

			childnode1 = xml->enterNode(rootNode1, "message");
			if(childnode1)
				emailBindInfo_.message = childnode1->ToText()->Value();

			childnode1 = xml->enterNode(rootNode1, "deadline");
			if(childnode1)
				emailBindInfo_.deadline = xml->getValInt(childnode1);

			childnode1 = xml->enterNode(rootNode1, "backlink_success_message");
			if(childnode1)
				emailBindInfo_.backlink_success_message = childnode1->ToText()->Value();

			childnode1 = xml->enterNode(rootNode1, "backlink_fail_message");
			if(childnode1)
				emailBindInfo_.backlink_fail_message = childnode1->ToText()->Value();

			childnode1 = xml->enterNode(rootNode1, "backlink_hello_message");
			if(childnode1)
				emailBindInfo_.backlink_hello_message = childnode1->ToText()->Value();
		}
	}

	SAFE_RELEASE(xml);
	return true;
}