Example #1
0
bool SVNCommitLog::parseCommit(RCommit& commit) {

    //fprintf(stderr,"parsing svn log\n");

    std::string line;

    if(!getNextLine(line)) return false;

    //start of log entry
    if(!svn_logentry_start.match(line)) {

        //is this the start of the document
        if(!svn_xml_tag.match(line)) return false;

        //fprintf(stderr,"found xml tag\n");

        //if so find the first logentry tag

        bool found_logentry = false;

        while(getNextLine(line)) {
            if(svn_logentry_start.match(line)) {
                found_logentry = true;
                break;
            }
        }

        if(!found_logentry) return false;
    }

    //fprintf(stderr,"found logentry\n");

    logentry.clear();

    logentry.append(line);
    logentry.append("\n");

    //fprintf(stderr,"found opening tag\n");

    bool endfound = false;

    while(getNextLine(line)) {
        logentry.append(line);
        logentry.append("\n");
        if(svn_logentry_end.match(line)) {
            //fprintf(stderr,"found closing tag\n");
            endfound=true;
            break;
        }
    }

    //incomplete commit
    if(!endfound) return false;

    //fprintf(stderr,"read logentry\n");

    TiXmlDocument doc;

    if(!doc.Parse(logentry.c_str())) return false;

    //fprintf(stderr,"try to parse logentry: %s\n", logentry.c_str());

    TiXmlElement* leE = doc.FirstChildElement( "logentry" );

    std::vector<std::string> entries;

    if(!leE) return false;

    //parse date
    TiXmlElement* dateE = leE->FirstChildElement( "date" );

    if(!dateE) return false;

    std::string timestamp_str(dateE->GetText());

    if(!svn_logentry_timestamp.match(timestamp_str, &entries))
        return false;

    struct tm time_str;

    time_str.tm_year  = atoi(entries[0].c_str()) - 1900;
    time_str.tm_mon   = atoi(entries[1].c_str()) - 1;
    time_str.tm_mday  = atoi(entries[2].c_str());
    time_str.tm_hour  = atoi(entries[3].c_str());
    time_str.tm_min   = atoi(entries[4].c_str());
    time_str.tm_sec   = atoi(entries[5].c_str());
    time_str.tm_isdst = -1;

#ifdef HAVE_TIMEGM
    commit.timestamp = timegm(&time_str);
#else
    commit.timestamp = __timegm_hack(&time_str);
#endif

    //parse author
    TiXmlElement* authorE = leE->FirstChildElement("author");

    if(authorE != 0) {
        // GetText() may return NULL, causing author instantiation to crash.
        std::string author;
        if(authorE->GetText()) author = authorE->GetText();
        if(author.empty()) author = "Unknown";

        commit.username = author;
    }

    TiXmlElement* pathsE = leE->FirstChildElement( "paths" );

    //log entries sometimes dont have any paths
    if(!pathsE) return true;

    //parse changes

    for(TiXmlElement* pathE = pathsE->FirstChildElement("path"); pathE != 0; pathE = pathE->NextSiblingElement()) {
        //parse path

        const char* kind   = pathE->Attribute("kind");
        const char* action = pathE->Attribute("action");

        //check for action
        if(action == 0) continue;

        bool is_dir = false;

        //if has the 'kind' attribute (old versions of svn dont have this), check if it is a dir
        if(kind != 0 && strcmp(kind,"dir") == 0) {

            //accept only deletes for directories
            if(strcmp(action, "D") != 0) continue;

            is_dir = true;
        }

        std::string file(pathE->GetText());
        std::string status(action);

        if(file.empty()) continue;
        if(status.empty()) continue;

        //append trailing slash if is directory
        if(is_dir && file[file.size()-1] != '/') {
            file = file + std::string("/");
        }

        commit.addFile(file, status);
    }

    //fprintf(stderr,"parsed logentry\n");

    //read files

    return true;
}
Example #2
0
bool IMContactXMLSerializer1::unserialize(const std::string & data) {
	TiXmlDocument doc;

	doc.Parse(data.c_str());

	TiXmlHandle docHandle(&doc);
	TiXmlHandle im = docHandle.FirstChild("im");

	// Retrieving associated account
	EnumIMProtocol::IMProtocol protocol;

	TiXmlElement * lastChildElt = im.Element();
	if (lastChildElt) {
		protocol = EnumIMProtocol::toIMProtocol(lastChildElt->Attribute("protocol"));
	} else {
		return false;
	}

	TiXmlText * login = im.FirstChild("account").FirstChild().Text();
	if (login) {		
		const IMAccount *imAccount = NULL;
		std::string loginValue = std::string(login->Value());

		//VOXOX - JRT - 2009.04.09 
		//for (IMAccountList::const_iterator it = _imAccountList.begin();
		//	it != _imAccountList.end();
		//	++it) {
		//	if ((it->getLogin() == loginValue) &&		
		//		(it->getProtocol() == protocol) ) {
		//		imAccount = &(*it);
		//	}
		//}
		imAccount = _imAccountList.findByLoginInfo( loginValue, protocol );
		//End VOXOX

		if (imAccount) {
			_imContact.setIMAccount(imAccount);
		} else {
			LOG_ERROR("this IMAccount does not exist in IMAccountList: " + std::string(login->Value()));
			return false;
		}
		////
	} else {
		_imContact._imAccount = NULL;
		_imContact._protocol = protocol;
	}
	////

	//Retrieving contactId
	TiXmlText * contactId = im.FirstChild("id").FirstChild().Text();
	if (contactId) {
	
		// wengo or sip account should have a domain
		// (unfortunately not saved before 2.1rc2...
		String completeLogin(contactId->Value());
		if (!completeLogin.contains("@")) 
		{
			if (protocol == EnumIMProtocol::IMProtocolWengo) {
				completeLogin += "@voip.wengo.fr";
			} 
			//else if (protocol == EnumIMProtocol::IMProtocolSIP) {
			//	// TO DO ?
			//}
		}
		////
	
		_imContact._contactId = completeLogin;
	}
	////

	// Retrieving alias
	TiXmlText * alias = im.FirstChild("alias").FirstChild().Text();
	if (alias) {
		_imContact._alias = alias->Value();
	}
	////
	
	//VOXOX CHANGE CJC ADD SUPPORT FOR STATUS MESSAGE
	// Retrieving statusMessage
	TiXmlText * statusMessage = im.FirstChild("statusMessage").FirstChild().Text();
	if (statusMessage) {
		_imContact._statusMessage = statusMessage->Value();
	}

	///VOXOX CHANGE Marin Block option when right clicking contact 4/24/2009
	TiXmlText * blocked = im.FirstChild("blocked").FirstChild().Text();
	if (blocked) {
		String strBlocked = blocked->Value();
		_imContact._blocked = strBlocked.toBoolean();
	}

	// Retrieving icon
	TiXmlText * photo = im.FirstChild("photo").FirstChild().Text();
	if (photo) {
		OWPicture picture = OWPicture::pictureFromData(Base64::decode(photo->Value()));
		_imContact.setIcon(picture);
	}
	////

	return true;
}
IndexTimeRef::IndexTimeRef(TiXmlNode* xmlNode)
: ISerialized(xmlNode)
{
    #ifdef ConsolePrint
        std::string initialtap_ = FileManager::instance().tap_;
        FileManager::instance().tap_.append("   ");
    #endif 
   //underlyingIndexRefNode ----------------------------------------------------------------------------------------------------------------------
   TiXmlElement* underlyingIndexRefNode = xmlNode->FirstChildElement("underlyingIndexRef");

   if(underlyingIndexRefNode){underlyingIndexRefIsNull_ = false;}
   else{underlyingIndexRefIsNull_ = true;}

   #ifdef ConsolePrint
      FileManager::instance().outFile_ << FileManager::instance().tap_.c_str() << "- underlyingIndexRefNode , address : " << underlyingIndexRefNode << std::endl;
   #endif
   if(underlyingIndexRefNode)
   {
      if(underlyingIndexRefNode->Attribute("href") || underlyingIndexRefNode->Attribute("id"))
      {
          if(underlyingIndexRefNode->Attribute("id"))
          {
             underlyingIndexRefIDRef_ = underlyingIndexRefNode->Attribute("id");
             underlyingIndexRef_ = boost::shared_ptr<UnderlyingIndex>(new UnderlyingIndex(underlyingIndexRefNode));
             underlyingIndexRef_->setID(underlyingIndexRefIDRef_);
             IDManager::instance().setID(underlyingIndexRefIDRef_,underlyingIndexRef_);
          }
          else if(underlyingIndexRefNode->Attribute("href")) { underlyingIndexRefIDRef_ = underlyingIndexRefNode->Attribute("href");}
          else { QL_FAIL("id or href error"); }
      }
      else { underlyingIndexRef_ = boost::shared_ptr<UnderlyingIndex>(new UnderlyingIndex(underlyingIndexRefNode));}
   }

   //fixingDaysNode ----------------------------------------------------------------------------------------------------------------------
   TiXmlElement* fixingDaysNode = xmlNode->FirstChildElement("fixingDays");

   if(fixingDaysNode){fixingDaysIsNull_ = false;}
   else{fixingDaysIsNull_ = true;}

   #ifdef ConsolePrint
      FileManager::instance().outFile_ << FileManager::instance().tap_.c_str() << "- fixingDaysNode , address : " << fixingDaysNode << std::endl;
   #endif
   if(fixingDaysNode)
   {
      if(fixingDaysNode->Attribute("href") || fixingDaysNode->Attribute("id"))
      {
          if(fixingDaysNode->Attribute("id"))
          {
             fixingDaysIDRef_ = fixingDaysNode->Attribute("id");
             fixingDays_ = boost::shared_ptr<FixingDays>(new FixingDays(fixingDaysNode));
             fixingDays_->setID(fixingDaysIDRef_);
             IDManager::instance().setID(fixingDaysIDRef_,fixingDays_);
          }
          else if(fixingDaysNode->Attribute("href")) { fixingDaysIDRef_ = fixingDaysNode->Attribute("href");}
          else { QL_FAIL("id or href error"); }
      }
      else { fixingDays_ = boost::shared_ptr<FixingDays>(new FixingDays(fixingDaysNode));}
   }

    #ifdef ConsolePrint
        FileManager::instance().tap_ = initialtap_;
    #endif 
}
Example #4
0
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=\"Voel\" 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 )
		_CrtMemCheckpoint( &startMemState );
		#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();
		}

		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" );
		printf( "** Printing via doc.Print **\n" );
		doc.Print( stdout );

		{
			printf( "** Printing via TiXmlPrinter **\n" );
			TiXmlPrinter printer;
			doc.Accept( &printer );
			fprintf( stdout, "%s", printer.CStr() );
		}
		#ifdef TIXML_USE_STL	
		{
			printf( "** Printing via operator<< **\n" );
			std::cout << doc;
		}
		#endif
		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 Dinosaurs!" 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", "Voel" );
		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";
		ostringstream outputStream( ostringstream::out );
		outputStream << doc;
		XmlTest( "Output stream correct.",	string( demoEnd ).c_str(),
											outputStream.str().c_str(), true );
	#endif

		node = doc.RootElement();
		assert( node );
		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 syntax.
		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 docTest;
			docTest.Parse( error );
			XmlTest( "Error row", docTest.ErrorRow(), 3 );
			XmlTest( "Error column", docTest.ErrorCol(), 17 );
			//printf( "error=%d id='%s' row %d col%d\n", (int) doc.Error(), doc.ErrorDesc(), doc.ErrorRow()+1, doc.ErrorCol() + 1 );

		}

	#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
	}
	
	{
		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", (int)dVal, 1 );
		result = ele->QueryDoubleAttribute( "attr1", &dVal );
		XmlTest( "Query attribute: double as double", (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 );
	}
	
	{
		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 =	"\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 );
	}


	// --------------------------------------------------------
	// UTF-8 testing. It is important to test:
	//	1. Making sure name, value, and text read correctly
	//	2. Row, Col functionality
	//	3. Correct output
	// --------------------------------------------------------
	printf ("\n** UTF-8 **\n");
	{
		TiXmlDocument doc( "utf8test.xml" );
		doc.LoadFile();
		if ( doc.Error() && doc.ErrorId() == TiXmlBase::TIXML_ERROR_OPENING_FILE ) {
			printf( "WARNING: File 'utf8test.xml' not found.\n"
					"(Are you running the test from the wrong directory?)\n"
				    "Could not test UTF-8 functionality.\n" );
		}
		else
		{
			TiXmlHandle docH( &doc );
			// Get the attribute "value" from the "Russian" element and check it.
			TiXmlElement* element = docH.FirstChildElement( "document" ).FirstChildElement( "Russian" ).Element();
			const unsigned char correctValue[] = {	0xd1U, 0x86U, 0xd0U, 0xb5U, 0xd0U, 0xbdU, 0xd0U, 0xbdU, 
													0xd0U, 0xbeU, 0xd1U, 0x81U, 0xd1U, 0x82U, 0xd1U, 0x8cU, 0 };

			XmlTest( "UTF-8: Russian value.", (const char*)correctValue, element->Attribute( "value" ), true );
			XmlTest( "UTF-8: Russian value row.", 4, element->Row() );
			XmlTest( "UTF-8: Russian value column.", 5, element->Column() );

			const unsigned char russianElementName[] = {	0xd0U, 0xa0U, 0xd1U, 0x83U,
															0xd1U, 0x81U, 0xd1U, 0x81U,
															0xd0U, 0xbaU, 0xd0U, 0xb8U,
															0xd0U, 0xb9U, 0 };
			const char russianText[] = "<\xD0\xB8\xD0\xBC\xD0\xB5\xD0\xB5\xD1\x82>";

			TiXmlText* text = docH.FirstChildElement( "document" ).FirstChildElement( (const char*) russianElementName ).Child( 0 ).Text();
			XmlTest( "UTF-8: Browsing russian element name.",
					 russianText,
					 text->Value(),
					 true );
			XmlTest( "UTF-8: Russian element name row.", 7, text->Row() );
			XmlTest( "UTF-8: Russian element name column.", 47, text->Column() );

			TiXmlDeclaration* dec = docH.Child( 0 ).Node()->ToDeclaration();
			XmlTest( "UTF-8: Declaration column.", 1, dec->Column() );
			XmlTest( "UTF-8: Document column.", 1, doc.Column() );

			// Now try for a round trip.
			doc.SaveFile( "utf8testout.xml" );

			// Check the round trip.
			char savedBuf[256];
			char verifyBuf[256];
			int okay = 1;

			FILE* saved  = fopen( "utf8testout.xml", "r" );
			FILE* verify = fopen( "utf8testverify.xml", "r" );
			if ( saved && verify )
			{
				while ( fgets( verifyBuf, 256, verify ) )
				{
					fgets( savedBuf, 256, saved );
					if ( strcmp( verifyBuf, savedBuf ) )
					{
						okay = 0;
						break;
					}
				}
				fclose( saved );
				fclose( verify );
			}
			XmlTest( "UTF-8: Verified multi-language round trip.", 1, okay );

			// On most Western machines, this is an element that contains
			// the word "resume" with the correct accents, in a latin encoding.
			// It will be something else completely on non-wester machines,
			// which is why TinyXml is switching to UTF-8.
			const char latin[] = "<element>r\x82sum\x82</element>";

			TiXmlDocument latinDoc;
			latinDoc.Parse( latin, 0, TIXML_ENCODING_LEGACY );

			text = latinDoc.FirstChildElement()->FirstChild()->ToText();
			XmlTest( "Legacy encoding: Verify text element.", "r\x82sum\x82", text->Value() );
		}
	}		

	//////////////////////
	// Copy and assignment
	//////////////////////
	printf ("\n** Copy and Assignment **\n");
	{
		TiXmlElement element( "foo" );
		element.Parse( "<element name='value' />", 0, TIXML_ENCODING_UNKNOWN );

		TiXmlElement elementCopy( element );
		TiXmlElement elementAssign( "foo" );
		elementAssign.Parse( "<incorrect foo='bar'/>", 0, TIXML_ENCODING_UNKNOWN );
		elementAssign = element;

		XmlTest( "Copy/Assign: element copy #1.", "element", elementCopy.Value() );
		XmlTest( "Copy/Assign: element copy #2.", "value", elementCopy.Attribute( "name" ) );
		XmlTest( "Copy/Assign: element assign #1.", "element", elementAssign.Value() );
		XmlTest( "Copy/Assign: element assign #2.", "value", elementAssign.Attribute( "name" ) );
		XmlTest( "Copy/Assign: element assign #3.", true, ( 0 == elementAssign.Attribute( "foo" )) );

		TiXmlComment comment;
		comment.Parse( "<!--comment-->", 0, TIXML_ENCODING_UNKNOWN );
		TiXmlComment commentCopy( comment );
		TiXmlComment commentAssign;
		commentAssign = commentCopy;
		XmlTest( "Copy/Assign: comment copy.", "comment", commentCopy.Value() );
		XmlTest( "Copy/Assign: comment assign.", "comment", commentAssign.Value() );

		TiXmlUnknown unknown;
		unknown.Parse( "<[unknown]>", 0, TIXML_ENCODING_UNKNOWN );
		TiXmlUnknown unknownCopy( unknown );
		TiXmlUnknown unknownAssign;
		unknownAssign.Parse( "incorrect", 0, TIXML_ENCODING_UNKNOWN );
		unknownAssign = unknownCopy;
		XmlTest( "Copy/Assign: unknown copy.", "[unknown]", unknownCopy.Value() );
		XmlTest( "Copy/Assign: unknown assign.", "[unknown]", unknownAssign.Value() );
		
		TiXmlText text( "TextNode" );
		TiXmlText textCopy( text );
		TiXmlText textAssign( "incorrect" );
		textAssign = text;
		XmlTest( "Copy/Assign: text copy.", "TextNode", textCopy.Value() );
		XmlTest( "Copy/Assign: text assign.", "TextNode", textAssign.Value() );

		TiXmlDeclaration dec;
		dec.Parse( "<?xml version='1.0' encoding='UTF-8'?>", 0, TIXML_ENCODING_UNKNOWN );
		TiXmlDeclaration decCopy( dec );
		TiXmlDeclaration decAssign;
		decAssign = dec;

		XmlTest( "Copy/Assign: declaration copy.", "UTF-8", decCopy.Encoding() );
		XmlTest( "Copy/Assign: text assign.", "UTF-8", decAssign.Encoding() );

		TiXmlDocument doc;
		elementCopy.InsertEndChild( textCopy );
		doc.InsertEndChild( decAssign );
		doc.InsertEndChild( elementCopy );
		doc.InsertEndChild( unknownAssign );

		TiXmlDocument docCopy( doc );
		TiXmlDocument docAssign;
		docAssign = docCopy;

		#ifdef TIXML_USE_STL
		std::string original, copy, assign;
		original << doc;
		copy << docCopy;
		assign << docAssign;
		XmlTest( "Copy/Assign: document copy.", original.c_str(), copy.c_str(), true );
		XmlTest( "Copy/Assign: document assign.", original.c_str(), assign.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 );
	}
	TiXmlBase::SetCondenseWhiteSpace( true );
#endif

	//////////////////////////////////////////////////////
	// GetText();
	{
		const char* str = "<foo>This is text</foo>";
		TiXmlDocument doc;
		doc.Parse( str );
		const TiXmlElement* element = doc.RootElement();

		XmlTest( "GetText() normal use.", "This is text", element->GetText() );

		str = "<foo><b>This is text</b></foo>";
		doc.Clear();
		doc.Parse( str );
		element = doc.RootElement();

		XmlTest( "GetText() contained element.", element->GetText() == 0, true );

		str = "<foo>This is <b>text</b></foo>";
		doc.Clear();
		TiXmlBase::SetCondenseWhiteSpace( false );
		doc.Parse( str );
		TiXmlBase::SetCondenseWhiteSpace( true );
		element = doc.RootElement();

		XmlTest( "GetText() partial.", "This is ", element->GetText() );
	}


	//////////////////////////////////////////////////////
	// CDATA
	{
		const char* str =	"<xmlElement>"
								"<![CDATA["
									"I am > the rules!\n"
									"...since I make symbolic puns"
								"]]>"
							"</xmlElement>";
		TiXmlDocument doc;
		doc.Parse( str );
		doc.Print();

		XmlTest( "CDATA parse.", doc.FirstChildElement()->FirstChild()->Value(), 
								 "I am > the rules!\n...since I make symbolic puns",
								 true );

		#ifdef TIXML_USE_STL
		//cout << doc << '\n';

		doc.Clear();

		istringstream parse0( str );
		parse0 >> doc;
		//cout << doc << '\n';

		XmlTest( "CDATA stream.", doc.FirstChildElement()->FirstChild()->Value(), 
								 "I am > the rules!\n...since I make symbolic puns",
								 true );
		#endif

		TiXmlDocument doc1 = doc;
		//doc.Print();

		XmlTest( "CDATA copy.", doc1.FirstChildElement()->FirstChild()->Value(), 
								 "I am > the rules!\n...since I make symbolic puns",
								 true );
	}
	{
		// [ 1482728 ] Wrong wide char parsing
		char buf[256];
		buf[255] = 0;
		for( int i=0; i<255; ++i ) {
			buf[i] = (char)((i>=32) ? i : 32);
		}
		TIXML_STRING str( "<xmlElement><![CDATA[" );
		str += buf;
		str += "]]></xmlElement>";

		TiXmlDocument doc;
		doc.Parse( str.c_str() );

		TiXmlPrinter printer;
		printer.SetStreamPrinting();
		doc.Accept( &printer );

		XmlTest( "CDATA with all bytes #1.", str.c_str(), printer.CStr(), true );

		#ifdef TIXML_USE_STL
		doc.Clear();
		istringstream iss( printer.Str() );
		iss >> doc;
		std::string out;
		out << doc;
		XmlTest( "CDATA with all bytes #2.", out.c_str(), printer.CStr(), true );
		#endif
	}
	{
		// [ 1480107 ] Bug-fix for STL-streaming of CDATA that contains tags
		// CDATA streaming had a couple of bugs, that this tests for.
		const char* str =	"<xmlElement>"
								"<![CDATA["
									"<b>I am > the rules!</b>\n"
									"...since I make symbolic puns"
								"]]>"
							"</xmlElement>";
		TiXmlDocument doc;
		doc.Parse( str );
		doc.Print();

		XmlTest( "CDATA parse. [ 1480107 ]", doc.FirstChildElement()->FirstChild()->Value(), 
								 "<b>I am > the rules!</b>\n...since I make symbolic puns",
								 true );

		#ifdef TIXML_USE_STL

		doc.Clear();

		istringstream parse0( str );
		parse0 >> doc;

		XmlTest( "CDATA stream. [ 1480107 ]", doc.FirstChildElement()->FirstChild()->Value(), 
								 "<b>I am > the rules!</b>\n...since I make symbolic puns",
								 true );
		#endif

		TiXmlDocument doc1 = doc;
		//doc.Print();

		XmlTest( "CDATA copy. [ 1480107 ]", doc1.FirstChildElement()->FirstChild()->Value(), 
								 "<b>I am > the rules!</b>\n...since I make symbolic puns",
								 true );
	}
	//////////////////////////////////////////////////////
	// Visit()



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

	const int FUZZ_ITERATION = 300;

	// The only goal is not to crash on bad input.
	int len = (int) strlen( demoStart );
	for( int i=0; i<FUZZ_ITERATION; ++i ) 
	{
		char* demoCopy = new char[ len+1 ];
		strcpy( demoCopy, demoStart );

		demoCopy[ i%len ] = (char)((i+1)*3);
		demoCopy[ (i*7)%len ] = '>';
		demoCopy[ (i*11)%len ] = '<';

		TiXmlDocument xml;
		xml.Parse( demoCopy );

		delete [] demoCopy;
	}
	printf( "** Fuzzing Complete. **\n" );
	
	//////////////////////////////////////////////////////
	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
			// verifying 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" );
		bool loadOkay = doc.LoadFile();
		loadOkay = true;	// get rid of compiler warning.
		// 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 copyright &#xA9;.\"> </psg>"
			"</passages>";

		TiXmlDocument doc( "passages.xml" );
		doc.Parse( passages );
		TiXmlElement* psg = doc.RootElement()->FirstChildElement();
		const char* context = psg->Attribute( "context" );
		const char* expected = "Line 5 has \"quotation marks\" and 'apostrophe marks'. It also has <, >, and &, as well as a fake copyright \xC2\xA9.";

		XmlTest( "Entity transformation: read. ", expected, 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 copyright \xC2\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" );
		}
    }

	{
		// DOCTYPE not preserved (950171)
		// 
		const char* doctype =
			"<?xml version=\"1.0\" ?>"
			"<!DOCTYPE PLAY SYSTEM 'play.dtd'>"
			"<!ELEMENT title (#PCDATA)>"
			"<!ELEMENT books (title,authors)>"
			"<element />";

		TiXmlDocument doc;
		doc.Parse( doctype );
		doc.SaveFile( "test7.xml" );
		doc.Clear();
		doc.LoadFile( "test7.xml" );
		
		TiXmlHandle docH( &doc );
		TiXmlUnknown* unknown = docH.Child( 1 ).Unknown();
		XmlTest( "Correct value of unknown.", "!DOCTYPE PLAY SYSTEM 'play.dtd'", unknown->Value() );
		#ifdef TIXML_USE_STL
		TiXmlNode* node = docH.Child( 2 ).Node();
		std::string str;
		str << (*node);
		XmlTest( "Correct streaming of unknown.", "<!ELEMENT title (#PCDATA)>", str.c_str() );
		#endif
	}

	{
		// [ 791411 ] Formatting bug
		// Comments do not stream out correctly.
		const char* doctype = 
			"<!-- Somewhat<evil> -->";
		TiXmlDocument doc;
		doc.Parse( doctype );

		TiXmlHandle docH( &doc );
		TiXmlComment* comment = docH.Child( 0 ).Node()->ToComment();

		XmlTest( "Comment formatting.", " Somewhat<evil> ", comment->Value() );
		#ifdef TIXML_USE_STL
		std::string str;
		str << (*comment);
		XmlTest( "Comment streaming.", "<!-- Somewhat<evil> -->", str.c_str() );
		#endif
	}

	{
		// [ 870502 ] White space issues
		TiXmlDocument doc;
		TiXmlText* text;
		TiXmlHandle docH( &doc );
	
		const char* doctype0 = "<element> This has leading and trailing space </element>";
		const char* doctype1 = "<element>This has  internal space</element>";
		const char* doctype2 = "<element> This has leading, trailing, and  internal space </element>";

		TiXmlBase::SetCondenseWhiteSpace( false );
		doc.Clear();
		doc.Parse( doctype0 );
		text = docH.FirstChildElement( "element" ).Child( 0 ).Text();
		XmlTest( "White space kept.", " This has leading and trailing space ", text->Value() );

		doc.Clear();
		doc.Parse( doctype1 );
		text = docH.FirstChildElement( "element" ).Child( 0 ).Text();
		XmlTest( "White space kept.", "This has  internal space", text->Value() );

		doc.Clear();
		doc.Parse( doctype2 );
		text = docH.FirstChildElement( "element" ).Child( 0 ).Text();
		XmlTest( "White space kept.", " This has leading, trailing, and  internal space ", text->Value() );

		TiXmlBase::SetCondenseWhiteSpace( true );
		doc.Clear();
		doc.Parse( doctype0 );
		text = docH.FirstChildElement( "element" ).Child( 0 ).Text();
		XmlTest( "White space condensed.", "This has leading and trailing space", text->Value() );

		doc.Clear();
		doc.Parse( doctype1 );
		text = docH.FirstChildElement( "element" ).Child( 0 ).Text();
		XmlTest( "White space condensed.", "This has internal space", text->Value() );

		doc.Clear();
		doc.Parse( doctype2 );
		text = docH.FirstChildElement( "element" ).Child( 0 ).Text();
		XmlTest( "White space condensed.", "This has leading, trailing, and internal space", text->Value() );
	}

	{
		// Double attributes
		const char* doctype = "<element attr='red' attr='blue' />";

		TiXmlDocument doc;
		doc.Parse( doctype );
		
		XmlTest( "Parsing repeated attributes.", 0, (int)doc.Error() );	// not an  error to tinyxml
		XmlTest( "Parsing repeated attributes.", "blue", doc.FirstChildElement( "element" )->Attribute( "attr" ) );
	}

	{
		// Embedded null in stream.
		const char* doctype = "<element att\0r='red' attr='blue' />";

		TiXmlDocument doc;
		doc.Parse( doctype );
		XmlTest( "Embedded null throws error.", true, doc.Error() );

		#ifdef TIXML_USE_STL
		istringstream strm( doctype );
		doc.Clear();
		doc.ClearError();
		strm >> doc;
		XmlTest( "Embedded null throws error.", true, doc.Error() );
		#endif
	}

    {
            // Legacy mode test. (This test may only pass on a western system)
            const char* str =
                        "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>"
                        "<ä>"
                        "CöntäntßäöüÄÖÜ"
                        "</ä>";

            TiXmlDocument doc;
            doc.Parse( str );

            TiXmlHandle docHandle( &doc );
            TiXmlHandle aHandle = docHandle.FirstChildElement( "ä" );
            TiXmlHandle tHandle = aHandle.Child( 0 );
            assert( aHandle.Element() );
            assert( tHandle.Text() );
            XmlTest( "ISO-8859-1 Parsing.", "CöntäntßäöüÄÖÜ", tHandle.Text()->Value() );
    }

	{
		// Empty documents should return TIXML_ERROR_PARSING_EMPTY, bug 1070717
		const char* str = "    ";
		TiXmlDocument doc;
		doc.Parse( str );
		XmlTest( "Empty document error TIXML_ERROR_DOCUMENT_EMPTY", TiXmlBase::TIXML_ERROR_DOCUMENT_EMPTY, doc.ErrorId() );
	}
	#ifndef TIXML_USE_STL
	{
		// String equality. [ 1006409 ] string operator==/!= no worky in all cases
		TiXmlString temp;
		XmlTest( "Empty tinyxml string compare equal", ( temp == "" ), true );

		TiXmlString    foo;
		TiXmlString    bar( "" );
		XmlTest( "Empty tinyxml string compare equal", ( foo == bar ), true );
	}

	#endif
	{
		// Bug [ 1195696 ] from marlonism
		TiXmlBase::SetCondenseWhiteSpace(false); 
		TiXmlDocument xml; 
		xml.Parse("<text><break/>This hangs</text>"); 
		XmlTest( "Test safe error return.", xml.Error(), false );
	}

	{
		// Bug [ 1243992 ] - another infinite loop
		TiXmlDocument doc;
		doc.SetCondenseWhiteSpace(false);
		doc.Parse("<p><pb></pb>test</p>");
	} 
	{
		// Low entities
		TiXmlDocument xml;
		xml.Parse( "<test>&#x0e;</test>" );
		const char result[] = { 0x0e, 0 };
		XmlTest( "Low entities.", xml.FirstChildElement()->GetText(), result );
		xml.Print();
	}
	{
		// Bug [ 1451649 ] Attribute values with trailing quotes not handled correctly
		TiXmlDocument xml;
		xml.Parse( "<foo attribute=bar\" />" );
		XmlTest( "Throw error with bad end quotes.", xml.Error(), true );
	}
	#ifdef TIXML_USE_STL
	{
		// Bug [ 1449463 ] Consider generic query
		TiXmlDocument xml;
		xml.Parse( "<foo bar='3' barStr='a string'/>" );

		TiXmlElement* ele = xml.FirstChildElement();
		double d;
		int i;
		float f;
		bool b;
		//std::string str;

		XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "bar", &d ), TIXML_SUCCESS );
		XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "bar", &i ), TIXML_SUCCESS );
		XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "bar", &f ), TIXML_SUCCESS );
		XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "bar", &b ), TIXML_WRONG_TYPE );
		XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "nobar", &b ), TIXML_NO_ATTRIBUTE );
		//XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "barStr", &str ), TIXML_SUCCESS );

		XmlTest( "QueryValueAttribute", (d==3.0), true );
		XmlTest( "QueryValueAttribute", (i==3), true );
		XmlTest( "QueryValueAttribute", (f==3.0f), true );
		//XmlTest( "QueryValueAttribute", (str==std::string( "a string" )), true );
	}
	#endif

	#ifdef TIXML_USE_STL
	{
		// [ 1505267 ] redundant malloc in TiXmlElement::Attribute
		TiXmlDocument xml;
		xml.Parse( "<foo bar='3' />" );
		TiXmlElement* ele = xml.FirstChildElement();
		double d;
		int i;

		std::string bar = "bar";

		const std::string* atrrib = ele->Attribute( bar );
		ele->Attribute( bar, &d );
		ele->Attribute( bar, &i );

		XmlTest( "Attribute", atrrib->empty(), false );
		XmlTest( "Attribute", (d==3.0), true );
		XmlTest( "Attribute", (i==3), true );
	}
	#endif

	{
		// [ 1356059 ] Allow TiXMLDocument to only be at the top level
		TiXmlDocument xml, xml2;
		xml.InsertEndChild( xml2 );
		XmlTest( "Document only at top level.", xml.Error(), true );
		XmlTest( "Document only at top level.", xml.ErrorId(), TiXmlBase::TIXML_ERROR_DOCUMENT_TOP_ONLY );
	}

	{
		// [ 1663758 ] Failure to report error on bad XML
		TiXmlDocument xml;
		xml.Parse("<x>");
		XmlTest("Missing end tag at end of input", xml.Error(), true);
		xml.Parse("<x> ");
		XmlTest("Missing end tag with trailing whitespace", xml.Error(), true);
	} 

	{
		// [ 1635701 ] fail to parse files with a tag separated into two lines
		// I'm not sure this is a bug. Marked 'pending' for feedback.
		TiXmlDocument xml;
		xml.Parse( "<title><p>text</p\n><title>" );
		//xml.Print();
		//XmlTest( "Tag split by newline", xml.Error(), false );
	}

	#ifdef TIXML_USE_STL
	{
		// [ 1475201 ] TinyXML parses entities in comments
		TiXmlDocument xml;
		istringstream parse1( "<!-- declarations for <head> & <body> -->"
						      "<!-- far &amp; away -->" );
		parse1 >> xml;

		TiXmlNode* e0 = xml.FirstChild();
		TiXmlNode* e1 = e0->NextSibling();
		TiXmlComment* c0 = e0->ToComment();
		TiXmlComment* c1 = e1->ToComment();

		XmlTest( "Comments ignore entities.", " declarations for <head> & <body> ", c0->Value(), true );
		XmlTest( "Comments ignore entities.", " far &amp; away ", c1->Value(), true );
	}
	#endif

	{
		// [ 1475201 ] TinyXML parses entities in comments
		TiXmlDocument xml;
		xml.Parse("<!-- declarations for <head> & <body> -->"
				  "<!-- far &amp; away -->" );

		TiXmlNode* e0 = xml.FirstChild();
		TiXmlNode* e1 = e0->NextSibling();
		TiXmlComment* c0 = e0->ToComment();
		TiXmlComment* c1 = e1->ToComment();

		XmlTest( "Comments ignore entities.", " declarations for <head> & <body> ", c0->Value(), true );
		XmlTest( "Comments ignore entities.", " far &amp; away ", c1->Value(), true );
	}
	/*
	{
		TiXmlDocument xml;
		xml.Parse( "<tag>/</tag>" );
		xml.Print();
		xml.FirstChild()->Print( stdout, 0 );
		xml.FirstChild()->Type();
	}
	*/
	
	/*  1417717 experiment
	{
		TiXmlDocument xml;
		xml.Parse("<text>Dan & Tracie</text>");
		xml.Print(stdout);
	}
	{
		TiXmlDocument xml;
		xml.Parse("<text>Dan &foo; Tracie</text>");
		xml.Print(stdout);
	}
	*/
	#if defined( WIN32 ) && defined( TUNE )
	_CrtMemCheckpoint( &endMemState );
	//_CrtMemDumpStatistics( &endMemState );

	_CrtMemState diffMemState;
	_CrtMemDifference( &diffMemState, &startMemState, &endMemState );
	_CrtMemDumpStatistics( &diffMemState );
	#endif

	printf ("\nPass %d, Fail %d\n", gPass, gFail);
	return gFail;
}
Example #5
0
//test GetEntryList. passed
BOOL GDocsAPITest::GetEntryListTest()
{
	login();
	
	TiXmlDocument * pXmlDoc = new TiXmlDocument();

	//lastest 100 items
	//m_pGDocsApi->GetEntryList("https://docs.google.com/feeds/default/private/full?showfolders=true", pXmlDoc);


	//get trashed items
	m_pGDocsApi->GetEntryList("https://docs.google.com/feeds/default/private/full/-/trashed?showfolders=true",pXmlDoc);
	
	//entrylist for aaaa folder
	//m_pGDocsApi->GetEntryList("https://docs.google.com/feeds/default/private/full/folder%3A0B7CmbVXdOi7mYzhlM2NjODgtNzlkZC00ZGZlLWFhN2EtMWJlODA3NmY0YjIy/contents", pXmlDoc);

	//get all documetn
	//m_pGDocsApi->GetEntryList("https://docs.google.com/feeds/default/private/full/-/document?max-results=5", pXmlDoc);
	//m_pGDocsApi->GetEntryList("https://docs.google.com/feeds/default/private/full/-/-mine/folder", pXmlDoc);

	pXmlDoc->SaveFile("d:/trashed.xml");
	
	if (pXmlDoc)
	{
		TiXmlElement* pFeedElement = pXmlDoc->FirstChildElement("feed");
		
		for (TiXmlElement* pElement = pFeedElement->FirstChildElement("entry"); pElement; pElement = pElement->NextSiblingElement("entry"))
		{
			GDocsEntry* pDocsEntry = new GDocsEntry(pElement);

			cout<<"The information of the entry" <<endl<<endl;
			wcout<<L" GDEtag :"	<< pDocsEntry->m_pszGDEtag<<endl;
			wcout<<L" IDURL :"		<< pDocsEntry->m_pszIDUrl <<endl;
			wcout<<L" Published :" << pDocsEntry->m_pszPublished <<endl;
			wcout<<L" Updated :"	<< pDocsEntry->m_pszUpdated<<endl;
			wcout<<L" AppEdited :" << pDocsEntry->m_pszAppEdited<<endl;
			wcout<<L" IsStarred :" << pDocsEntry->m_bIsStarred<<endl;
			wcout<<L" IsHidden :" << pDocsEntry->m_bIsHidden<<endl;
			wcout<<L" IsViewed :" << pDocsEntry->m_bIsViewed<<endl;
			wcout<<L" Title :"		<< pDocsEntry->m_pszTitle<<endl;
			wcout<<L" ContentType :" << pDocsEntry->m_pszContentType<<endl;
			wcout<<L" Content Src :" << pDocsEntry->m_pszContentSrc<<endl;
			wcout<<L" LinkAlternate :" << pDocsEntry->m_pszLinkAlternate<<endl;
			wcout<<L" ResumeableEditMedia :"	<< (pDocsEntry->m_pszLinkResumableEditMedia?pDocsEntry->m_pszLinkResumableEditMedia:L"")<<endl;
			wcout<<L" AuthorName :"	<< pDocsEntry->m_pszAuthorName<<endl;
			wcout<<L" AuthorEmail :"	<< pDocsEntry->m_pszAuthorEmail<<endl;
			wcout<<L" ResourceID :"	<< pDocsEntry->m_pszResourceId<<endl;
			wcout<<L" Type :"	<< pDocsEntry->m_pszType<<endl;
			wcout<<L" ID :"	<< pDocsEntry->m_pszID<<endl;
			wcout<<L" LastModifiedName :"	<< pDocsEntry->m_pszLastModifiedByName<<endl;
			wcout<<L" LastModifiedEmail :"	<< pDocsEntry->m_pszLastModifiedByEmail<<endl;
			wcout<<L" QuotaByteUsed :"	<< (pDocsEntry->m_pszQuotaBytesUsed?pDocsEntry->m_pszQuotaBytesUsed:L"")<<endl;
			wcout<<L" QuotaByteUsedFormat :"	<<(pDocsEntry->m_pszQuotaBytesUsed? pDocsEntry->m_pszQuotaBytesUsedFormated:L"")<<endl;
			wcout<<L" ACL Link :"	<< pDocsEntry->m_pszFeedLinkACL<<endl;
			wcout<<L" Revision Link :"	<< (pDocsEntry->m_pszFeedLinkRevisions?pDocsEntry->m_pszFeedLinkRevisions:L"")<<endl;
			wcout<<L" MD5CheckSum :"	<< (pDocsEntry->m_pszMD5Checksum? pDocsEntry->m_pszMD5Checksum:L"")<<endl;
	
			wcout<<"................................................................................"<<endl;
		}
	}


	delete pXmlDoc;
	return TRUE;
}
Example #6
0
void TiXmlElement::operator=( const TiXmlElement& base )
{
	ClearThis();
	base.CopyTo( this );
}
Example #7
0
bool ETHEntityProperties::WriteToXMLFile(TiXmlElement *pHeadRoot) const
{
	TiXmlElement *pRoot = new TiXmlElement(GS_L("Entity"));
	pHeadRoot->LinkEndChild(pRoot); 

	TiXmlElement *pElement;

	if (emissiveColor != ETH_DEFAULT_EMISSIVE_COLOR)
	{
		pElement = new TiXmlElement(GS_L("EmissiveColor"));
		pRoot->LinkEndChild(pElement); 
		pElement->SetDoubleAttribute(GS_L("r"), emissiveColor.x);
		pElement->SetDoubleAttribute(GS_L("g"), emissiveColor.y);
		pElement->SetDoubleAttribute(GS_L("b"), emissiveColor.z);
		pElement->SetDoubleAttribute(GS_L("a"), emissiveColor.w);
	}

	if (spriteCut != ETH_DEFAULT_SPRITE_CUT)
	{
		pElement = new TiXmlElement(GS_L("SpriteCut"));
		pRoot->LinkEndChild(pElement);
		pElement->SetDoubleAttribute(GS_L("x"), spriteCut.x);
		pElement->SetDoubleAttribute(GS_L("y"), spriteCut.y);
	}

	if (scale != ETH_DEFAULT_SCALE)
	{
		pElement = new TiXmlElement(GS_L("Scale"));
		pRoot->LinkEndChild(pElement);
		pElement->SetDoubleAttribute(GS_L("x"), scale.x);
		pElement->SetDoubleAttribute(GS_L("y"), scale.y);
	}

	if (pivotAdjust != ETH_DEFAULT_PIVOT_ADJUST)
	{
		pElement = new TiXmlElement(GS_L("PivotAdjust"));
		pRoot->LinkEndChild(pElement);
		pElement->SetDoubleAttribute(GS_L("x"), pivotAdjust.x);
		pElement->SetDoubleAttribute(GS_L("y"), pivotAdjust.y);
	}

	if (spriteFile != GS_L(""))
	{
		pElement = new TiXmlElement(GS_L("Sprite"));
		pElement->LinkEndChild(new TiXmlText(spriteFile));
		pRoot->LinkEndChild(pElement);
	}

	if (normalFile != GS_L(""))
	{
		pElement = new TiXmlElement(GS_L("Normal"));
		pElement->LinkEndChild(new TiXmlText(normalFile));
		pRoot->LinkEndChild(pElement);
	}

	if (glossFile != GS_L(""))
	{
		pElement = new TiXmlElement(GS_L("Gloss"));
		pElement->LinkEndChild(new TiXmlText(glossFile));
		pRoot->LinkEndChild(pElement);
	}

	if (!particleSystems.empty())
	{
		TiXmlElement *pParticles = new TiXmlElement(GS_L("Particles"));
		pRoot->LinkEndChild(pParticles);
		for (unsigned int t=0; t<particleSystems.size(); t++)
		{
			if (particleSystems[t]->nParticles > 0)
				particleSystems[t]->WriteToXMLFile(pParticles);
		}
	}

	if (light)
	{
		light->WriteToXMLFile(pRoot);
	}

	if (collision)
	{
		TiXmlElement *pCollisionRoot = collision->WriteToXMLFile(pRoot);
		if (pCollisionRoot)
		{
			// Write polygon data
			if (polygon)
			{
				pElement = new TiXmlElement(GS_L("Polygon"));
				TiXmlText* text = new TiXmlText(polygon->GetENMLDeclaration());
				text->SetCDATA(true);
				pElement->LinkEndChild(text);
				pCollisionRoot->LinkEndChild(pElement);
			}
			else if (shape == BS_POLYGON) // it the polygon data is empty, write sample data into it
			{
				pElement = new TiXmlElement(GS_L("Polygon"));
				TiXmlText* text = new TiXmlText(POLYGON_ENML_SAMPLE);
				text->SetCDATA(true);
				pElement->LinkEndChild(text);
				pCollisionRoot->LinkEndChild(pElement);
			}

			// Write compound shape data
			if (compoundShape)
			{
				pElement = new TiXmlElement(GS_L("Compound"));
				TiXmlText* text = new TiXmlText(compoundShape->GetENMLDeclaration());
				text->SetCDATA(true);
				pElement->LinkEndChild(text);
				pCollisionRoot->LinkEndChild(pElement);
			}
			else if (shape == BS_COMPOUND) // it the compound data is empty, write sample data into it
			{
				pElement = new TiXmlElement(GS_L("Compound"));
				TiXmlText* text = new TiXmlText(COMPOUND_SHAPE_ENML_SAMPLE);
				text->SetCDATA(true);
				pElement->LinkEndChild(text);
				pCollisionRoot->LinkEndChild(pElement);
			}

			// Write joint data
			if (enmlJointDefinitions != GS_L(""))
			{
				pElement = new TiXmlElement(GS_L("Joints"));
				pElement->LinkEndChild(new TiXmlText(enmlJointDefinitions));
				pCollisionRoot->LinkEndChild(pElement);
			}
		}
	}

	pRoot->SetAttribute(GS_L("shape"), shape);
	if (shape != BS_NONE)
	{
		pRoot->SetAttribute(GS_L("sensor"), sensor);
		pRoot->SetAttribute(GS_L("bullet"), bullet);
		pRoot->SetAttribute(GS_L("fixedRotation"), fixedRotation);
		pRoot->SetDoubleAttribute(GS_L("friction"), friction);
		pRoot->SetDoubleAttribute(GS_L("density"), density);
		pRoot->SetDoubleAttribute(GS_L("restitution"), restitution);
		pRoot->SetDoubleAttribute(GS_L("gravityScale"), gravityScale);
	}

	pRoot->SetAttribute(GS_L("applyLight"), applyLight);
	if (applyLight)
	{
		pRoot->SetDoubleAttribute(GS_L("specularPower"), specularPower);
		pRoot->SetDoubleAttribute(GS_L("specularBrightness"), specularBrightness);
	}

	pRoot->SetAttribute(GS_L("castShadow"), castShadow);
	if (castShadow)
	{
		pRoot->SetDoubleAttribute(GS_L("shadowScale"), shadowScale);
		pRoot->SetDoubleAttribute(GS_L("shadowLengthScale"), shadowLengthScale);
		pRoot->SetDoubleAttribute(GS_L("shadowOpacity"), shadowOpacity);
	}

	pRoot->SetAttribute(GS_L("type"), type);
	if (type == ET_LAYERABLE)
	{
		pRoot->SetDoubleAttribute(GS_L("layerDepth"), layerDepth);
	}

	if (soundVolume != ETH_DEFAULT_SOUND_VOLUME)
	{
		pRoot->SetDoubleAttribute(GS_L("soundVolume"), soundVolume);
	}

	if (parallaxIntensity != ETH_DEFAULT_PARALLAX_INTENS)
	{
		pRoot->SetDoubleAttribute(GS_L("parallaxIntensity"), parallaxIntensity);
	}

	if (hideFromSceneEditor != ETH_FALSE)
	{
		pRoot->SetAttribute(GS_L("hideFromSceneEditor"), hideFromSceneEditor);
	}

	pRoot->SetAttribute(GS_L("static"), staticEntity);
	pRoot->SetAttribute(GS_L("blendMode"), blendMode);

	WriteDataToFile(pRoot);
	return true;
}
Example #8
0
bool TransFunc1DKeys::loadOsirixCLUT(const std::string& filename) {
    LINFO("Opening Osirix CLUT: " << filename);

    TiXmlDocument doc(filename.c_str());

    //TODO: this loader is much to specific to a certain order of XML tags and will crash if
    // anything is missing (#276).
    if (doc.LoadFile()) {
        // read and check version of plist file
        TiXmlNode* currNode = doc.FirstChild("plist");
        TiXmlElement* currElement = currNode->ToElement();

        currNode = currNode->FirstChild("dict");
        currNode = currNode->FirstChild("key");
        currElement = currNode->ToElement();

        // get reference to red, green and blue channel
        TiXmlElement* blueElement = 0;
        TiXmlElement* greenElement = 0;
        TiXmlElement* redElement = 0;
        TiXmlNode* blueNode = currElement->NextSibling();
        TiXmlNode* greenNode = ((blueNode->NextSibling())->NextSibling());
        TiXmlNode* redNode = ((greenNode->NextSibling())->NextSibling());
        blueNode = blueNode->FirstChild("integer");
        greenNode = greenNode->FirstChild("integer");
        redNode = redNode->FirstChild("integer");

        unsigned char* data = new unsigned char[256*4];

        for (int i = 0; i < 256; ++i) {
            data[4*i + 0] = 0;
            data[4*i + 1] = 0;
            data[4*i + 2] = 0;
            data[4*i + 3] = 0;

            blueNode = blueNode->NextSibling("integer");
            greenNode = greenNode->NextSibling("integer");
            redNode = redNode->NextSibling("integer");

            if (blueNode == 0 || greenNode == 0 || redNode == 0)
                continue;

            blueElement = blueNode->ToElement();
            greenElement = greenNode->ToElement();
            redElement = redNode->ToElement();

            data[4*i + 0] = atoi(redElement->GetText());
            data[4*i + 1] = atoi(greenElement->GetText());
            data[4*i + 2] = atoi(blueElement->GetText());
            data[4*i + 3] = (char)(255);
        }

        dimensions_ = tgt::ivec3(256, 1, 1);
        generateKeys(data);
        delete[] data;

        return true;
    }
    else
        return false;
}
Example #9
0
int main(int argc, char *argv[], char *env[])
{

  if (argc < 4)
  {
    cout
        << "Syntax: mdproject2mardyn <inputfile.cfg> <inputfile.inp> <outputfile.xml>"
        << endl;
    exit(1);
  }
  // define the output filename
  string outfile_name = "new-";
  outfile_name.append(argv[2]);

  TiXmlDocument doc;
  TiXmlDeclaration * decl = new TiXmlDeclaration( "1.0", "UTF-8", "" );
  TiXmlElement * root = new TiXmlElement( "mardyncfg" );
  TiXmlElement * header = new TiXmlElement( "header" );
  TiXmlElement * version = new TiXmlElement( "version" );

  // apply the current date instead because we supposedly up to date
  time_t rawtime;
  struct tm * timeinfo;
  char datestr [10];
  time( &rawtime);
  timeinfo = localtime( &rawtime);
  strftime(datestr, 10, "%Y%m%d", timeinfo);
  TiXmlText * version_text = new TiXmlText( datestr );

  TiXmlElement * required_plugins = new TiXmlElement( "required-plugins" );
  TiXmlElement * experiment = new TiXmlElement( "experiment" );
  TiXmlElement * timestep_length = new TiXmlElement( "timestep-length" );
  TiXmlElement * cutoff_radius = new TiXmlElement( "cutoff-radius" );
  TiXmlElement * temperature = new TiXmlElement( "temperature" );
  TiXmlElement * current_time = new TiXmlElement( "current-time" );
  TiXmlElement * length = new TiXmlElement( "length" );
  TiXmlElement * lengthx = new TiXmlElement( "x" );
  TiXmlElement * lengthy = new TiXmlElement( "y" );
  TiXmlElement * lengthz = new TiXmlElement( "z" );
  TiXmlElement * phase_space = new TiXmlElement( "phase-space" );
  TiXmlElement * components = new TiXmlElement( "components" );
  TiXmlElement * components_data = new TiXmlElement( "data" );
  TiXmlElement * data_structure = new TiXmlElement( "data-structure" );

  root->LinkEndChild(header);
  header->LinkEndChild(version);
  version->LinkEndChild(version_text);
  header->LinkEndChild(required_plugins);
  root->LinkEndChild(experiment);
  experiment->LinkEndChild(timestep_length);
  experiment->LinkEndChild(cutoff_radius);
  experiment->LinkEndChild(temperature);
  experiment->LinkEndChild(current_time);
  experiment->LinkEndChild(length);
  length->LinkEndChild(lengthx);
  length->LinkEndChild(lengthy);
  length->LinkEndChild(lengthz);
  experiment->LinkEndChild(phase_space);
  experiment->LinkEndChild(components);
  components->LinkEndChild(components_data);
  experiment->LinkEndChild(data_structure);

  // Frist parse the .cfg file
  string token;
  fstream inputfstream;
  inputfstream.open(argv[1]);
  if (!inputfstream.is_open())
  {
    cout << "Error opening file " << argv[1] << " for reading.";
    exit(1);
  }
  string output_format, output_freq, output_file = "";

  while (inputfstream)
  {
    token.clear();
    inputfstream >> token;
    if (token.substr(0, 1)=="#")
    {
      inputfstream.ignore(INT_MAX, '\n');
    } else if (token.substr(0, 1)=="")
    {
      inputfstream.ignore(INT_MAX, '\n');
    } else if (token == "MDProjectConfig")
    {
      inputfstream.ignore(INT_MAX, '\n');
    } else if (token == "timestepLength")
    {
      inputfstream >> token;
      TiXmlText * timestep_length_text = new TiXmlText( token.c_str() );
      timestep_length->LinkEndChild(timestep_length_text);
    } else if (token == "cutoffRadius")
void CScraperParser::ParseExpression(const CStdString& input, CStdString& dest, TiXmlElement* element, bool bAppend)
{
  CStdString strOutput = element->Attribute("output");

  TiXmlElement* pExpression = element->FirstChildElement("expression");
  if (pExpression)
  {
    bool bInsensitive=true;
    const char* sensitive = pExpression->Attribute("cs");
    if (sensitive)
      if (stricmp(sensitive,"yes") == 0)
        bInsensitive=false; // match case sensitive

    CRegExp reg(bInsensitive);
    CStdString strExpression;
    if (pExpression->FirstChild())
      strExpression = pExpression->FirstChild()->Value();
    else
      strExpression = "(.*)";
    ReplaceBuffers(strExpression);
    ReplaceBuffers(strOutput);

    if (!reg.RegComp(strExpression.c_str()))
    {
      return;
    }

    bool bRepeat = false;
    const char* szRepeat = pExpression->Attribute("repeat");
    if (szRepeat)
      if (stricmp(szRepeat,"yes") == 0)
        bRepeat = true;

    const char* szClear = pExpression->Attribute("clear");
    if (szClear)
      if (stricmp(szClear,"yes") == 0)
        dest=""; // clear no matter if regexp fails

    bool bClean[MAX_SCRAPER_BUFFERS];
    GetBufferParams(bClean,pExpression->Attribute("noclean"),true);

    bool bTrim[MAX_SCRAPER_BUFFERS];
    GetBufferParams(bTrim,pExpression->Attribute("trim"),false);

    bool bFixChars[MAX_SCRAPER_BUFFERS];
    GetBufferParams(bFixChars,pExpression->Attribute("fixchars"),false);

    bool bEncode[MAX_SCRAPER_BUFFERS];
    GetBufferParams(bEncode,pExpression->Attribute("encode"),false);

    int iOptional = -1;
    pExpression->QueryIntAttribute("optional",&iOptional);

    int iCompare = -1;
    pExpression->QueryIntAttribute("compare",&iCompare);
    if (iCompare > -1)
      m_param[iCompare-1].ToLower();
    CStdString curInput = input;
    for (int iBuf=0;iBuf<MAX_SCRAPER_BUFFERS;++iBuf)
    {
      if (bClean[iBuf])
        InsertToken(strOutput,iBuf+1,"!!!CLEAN!!!");
      if (bTrim[iBuf])
        InsertToken(strOutput,iBuf+1,"!!!TRIM!!!");
      if (bFixChars[iBuf])
        InsertToken(strOutput,iBuf+1,"!!!FIXCHARS!!!");
      if (bEncode[iBuf])
        InsertToken(strOutput,iBuf+1,"!!!ENCODE!!!");
    }
    int i = reg.RegFind(curInput.c_str());
    while (i > -1 && (i < (int)curInput.size() || curInput.size() == 0))
    {
      if (!bAppend)
      {
        dest = "";
        bAppend = true;
      }
      CStdString strCurOutput=strOutput;

      if (iOptional > -1) // check that required param is there
      {
        char temp[4];
        sprintf(temp,"\\%i",iOptional);
        char* szParam = reg.GetReplaceString(temp);
        CRegExp reg2;
        reg2.RegComp("(.*)(\\\\\\(.*\\\\2.*)\\\\\\)(.*)");
        int i2=reg2.RegFind(strCurOutput.c_str());
        while (i2 > -1)
        {
          char* szRemove = reg2.GetReplaceString("\\2");
          int iRemove = strlen(szRemove);
          int i3 = strCurOutput.find(szRemove);
          if (szParam && strcmp(szParam,""))
          {
            strCurOutput.erase(i3+iRemove,2);
            strCurOutput.erase(i3,2);
          }
          else
            strCurOutput.replace(strCurOutput.begin()+i3,strCurOutput.begin()+i3+iRemove+2,"");

          free(szRemove);

          i2 = reg2.RegFind(strCurOutput.c_str());
        }
        free(szParam);
      }

      int iLen = reg.GetFindLen();
      // nasty hack #1 - & means \0 in a replace string
      strCurOutput.Replace("&","!!!AMPAMP!!!");
      char* result = reg.GetReplaceString(strCurOutput.c_str());
      if (result && strlen(result))
      {
        CStdString strResult(result);
        strResult.Replace("!!!AMPAMP!!!","&");
        Clean(strResult);
        ReplaceBuffers(strResult);
        if (iCompare > -1)
        {
          CStdString strResultNoCase = strResult;
          strResultNoCase.ToLower();
          if (strResultNoCase.Find(m_param[iCompare-1]) != -1)
            dest += strResult;
        }
        else
          dest += strResult;

        free(result);
      }
      if (bRepeat && iLen > 0)
      {
        curInput.erase(0,i+iLen>(int)curInput.size()?curInput.size():i+iLen);
        i = reg.RegFind(curInput.c_str());
      }
      else
        i = -1;
    }
  }
}
Example #11
0
void CSlingboxFile::LoadSettings(const CStdString& strHostname)
{
  // Load default settings
  m_sSlingboxSettings.strHostname = strHostname;
  m_sSlingboxSettings.iVideoWidth = 320;
  m_sSlingboxSettings.iVideoHeight = 240;
  m_sSlingboxSettings.iVideoResolution = (int)CSlingbox::RESOLUTION320X240;
  m_sSlingboxSettings.iVideoBitrate = 704;
  m_sSlingboxSettings.iVideoFramerate = 30;
  m_sSlingboxSettings.iVideoSmoothing = 50;
  m_sSlingboxSettings.iAudioBitrate = 64;
  m_sSlingboxSettings.iIFrameInterval = 10;
  m_sSlingboxSettings.uiCodeChannelUp = 0;
  m_sSlingboxSettings.uiCodeChannelDown = 0;
  for (unsigned int i = 0; i < 10; i++)
    m_sSlingboxSettings.uiCodeNumber[i] = 0;

  // Check if a SlingboxSettings.xml file exists
  CStdString slingboxXMLFile = CProfilesManager::Get().GetUserDataItem("SlingboxSettings.xml");
  if (!CFile::Exists(slingboxXMLFile))
  {
    CLog::Log(LOGNOTICE, "No SlingboxSettings.xml file (%s) found - using default settings",
      slingboxXMLFile.c_str());
    return;
  }

  // Load the XML file
  CXBMCTinyXML slingboxXML;
  if (!slingboxXML.LoadFile(slingboxXMLFile))
  {
    CLog::Log(LOGERROR, "%s - Error loading %s - line %d\n%s", __FUNCTION__, 
      slingboxXMLFile.c_str(), slingboxXML.ErrorRow(), slingboxXML.ErrorDesc());
    return;
  }

  // Check to make sure layout is correct
  TiXmlElement * pRootElement = slingboxXML.RootElement();
  if (!pRootElement || strcmpi(pRootElement->Value(), "slingboxsettings") != 0)
  {
    CLog::Log(LOGERROR, "%s - Error loading %s - no <slingboxsettings> node found",
      __FUNCTION__, slingboxXMLFile.c_str());
    return;
  }

  // Success so far
  CLog::Log(LOGNOTICE, "Loaded SlingboxSettings.xml from %s", slingboxXMLFile.c_str());

  // Search for the first settings that specify no hostname or match our hostname
  TiXmlElement *pElement;
  for (pElement = pRootElement->FirstChildElement("slingbox"); pElement;
    pElement = pElement->NextSiblingElement("slingbox"))
  {
    const char *hostname = pElement->Attribute("hostname");
    if (!hostname || StringUtils::EqualsNoCase(m_sSlingboxSettings.strHostname, hostname))
    {
      // Load setting values
      XMLUtils::GetInt(pElement, "width", m_sSlingboxSettings.iVideoWidth, 0, 640);
      XMLUtils::GetInt(pElement, "height", m_sSlingboxSettings.iVideoHeight, 0, 480);
      XMLUtils::GetInt(pElement, "videobitrate", m_sSlingboxSettings.iVideoBitrate, 50, 8000);
      XMLUtils::GetInt(pElement, "framerate", m_sSlingboxSettings.iVideoFramerate, 1, 30);
      XMLUtils::GetInt(pElement, "smoothing", m_sSlingboxSettings.iVideoSmoothing, 0, 100);
      XMLUtils::GetInt(pElement, "audiobitrate", m_sSlingboxSettings.iAudioBitrate, 16, 96);
      XMLUtils::GetInt(pElement, "iframeinterval", m_sSlingboxSettings.iIFrameInterval, 1, 30);

      // Load any button code values
      TiXmlElement * pCodes = pElement->FirstChildElement("buttons");
      if (pCodes)
      {
        XMLUtils::GetHex(pCodes, "channelup", m_sSlingboxSettings.uiCodeChannelUp);
        XMLUtils::GetHex(pCodes, "channeldown", m_sSlingboxSettings.uiCodeChannelDown);
        XMLUtils::GetHex(pCodes, "zero", m_sSlingboxSettings.uiCodeNumber[0]);
        XMLUtils::GetHex(pCodes, "one", m_sSlingboxSettings.uiCodeNumber[1]);
        XMLUtils::GetHex(pCodes, "two", m_sSlingboxSettings.uiCodeNumber[2]);
        XMLUtils::GetHex(pCodes, "three", m_sSlingboxSettings.uiCodeNumber[3]);
        XMLUtils::GetHex(pCodes, "four", m_sSlingboxSettings.uiCodeNumber[4]);
        XMLUtils::GetHex(pCodes, "five", m_sSlingboxSettings.uiCodeNumber[5]);
        XMLUtils::GetHex(pCodes, "six", m_sSlingboxSettings.uiCodeNumber[6]);
        XMLUtils::GetHex(pCodes, "seven", m_sSlingboxSettings.uiCodeNumber[7]);
        XMLUtils::GetHex(pCodes, "eight", m_sSlingboxSettings.uiCodeNumber[8]);
        XMLUtils::GetHex(pCodes, "nine", m_sSlingboxSettings.uiCodeNumber[9]);
      }

      break;
    }
  }

  // Prepare our resolution enum mapping array
  const struct
  {
    unsigned int uiWidth;
    unsigned int uiHeight;
    CSlingbox::Resolution eEnum;
  } m_resolutionMap[11] = {
    {0, 0, CSlingbox::NOVIDEO},
    {128, 96, CSlingbox::RESOLUTION128X96},
    {160, 120, CSlingbox::RESOLUTION160X120},
    {176, 120, CSlingbox::RESOLUTION176X120},
    {224, 176, CSlingbox::RESOLUTION224X176},
    {256, 192, CSlingbox::RESOLUTION256X192},
    {320, 240, CSlingbox::RESOLUTION320X240},
    {352, 240, CSlingbox::RESOLUTION352X240},
    {320, 480, CSlingbox::RESOLUTION320X480},
    {640, 240, CSlingbox::RESOLUTION640X240},
    {640, 480, CSlingbox::RESOLUTION640X480}
  };

  // See if the specified resolution matches something in our mapping array and
  // setup things accordingly
  for (unsigned int i = 0; i < 11; i++)
  {
    if (m_sSlingboxSettings.iVideoWidth == (int)m_resolutionMap[i].uiWidth &&
      m_sSlingboxSettings.iVideoHeight == (int)m_resolutionMap[i].uiHeight)
    {
      m_sSlingboxSettings.iVideoResolution = (int)m_resolutionMap[i].eEnum;
      return;
    }
  }

  // If it didn't match anything setup safe defaults
  CLog::Log(LOGERROR, "%s - Defaulting to 320x240 resolution due to invalid "
    "resolution specified in SlingboxSettings.xml for Slingbox: %s",
    __FUNCTION__, m_sSlingboxSettings.strHostname.c_str());
  m_sSlingboxSettings.iVideoWidth = 320;
  m_sSlingboxSettings.iVideoHeight = 240;
  m_sSlingboxSettings.iVideoResolution = (int)CSlingbox::RESOLUTION320X240;
}
ConfirmationDisputed::ConfirmationDisputed(TiXmlNode* xmlNode)
: ResponseMessage(xmlNode)
{
    #ifdef ConsolePrint
        std::string initialtap_ = FileManager::instance().tap_;
        FileManager::instance().tap_.append("   ");
    #endif 
   //originatingEventNode ----------------------------------------------------------------------------------------------------------------------
   TiXmlElement* originatingEventNode = xmlNode->FirstChildElement("originatingEvent");

   if(originatingEventNode){originatingEventIsNull_ = false;}
   else{originatingEventIsNull_ = true;}

   #ifdef ConsolePrint
      FileManager::instance().outFile_ << FileManager::instance().tap_.c_str() << "- originatingEventNode , address : " << originatingEventNode << std::endl;
   #endif
   if(originatingEventNode)
   {
      if(originatingEventNode->Attribute("href") || originatingEventNode->Attribute("id"))
      {
          if(originatingEventNode->Attribute("id"))
          {
             originatingEventIDRef_ = originatingEventNode->Attribute("id");
             originatingEvent_ = boost::shared_ptr<OriginatingEvent>(new OriginatingEvent(originatingEventNode));
             originatingEvent_->setID(originatingEventIDRef_);
             IDManager::instance().setID(originatingEventIDRef_,originatingEvent_);
          }
          else if(originatingEventNode->Attribute("href")) { originatingEventIDRef_ = originatingEventNode->Attribute("href");}
          else { QL_FAIL("id or href error"); }
      }
      else { originatingEvent_ = boost::shared_ptr<OriginatingEvent>(new OriginatingEvent(originatingEventNode));}
   }

   //tradeNode ----------------------------------------------------------------------------------------------------------------------
   TiXmlElement* tradeNode = xmlNode->FirstChildElement("trade");

   if(tradeNode){tradeIsNull_ = false;}
   else{tradeIsNull_ = true;}

   #ifdef ConsolePrint
      FileManager::instance().outFile_ << FileManager::instance().tap_.c_str() << "- tradeNode , address : " << tradeNode << std::endl;
   #endif
   if(tradeNode)
   {
      if(tradeNode->Attribute("href") || tradeNode->Attribute("id"))
      {
          if(tradeNode->Attribute("id"))
          {
             tradeIDRef_ = tradeNode->Attribute("id");
             trade_ = boost::shared_ptr<Trade>(new Trade(tradeNode));
             trade_->setID(tradeIDRef_);
             IDManager::instance().setID(tradeIDRef_,trade_);
          }
          else if(tradeNode->Attribute("href")) { tradeIDRef_ = tradeNode->Attribute("href");}
          else { QL_FAIL("id or href error"); }
      }
      else { trade_ = boost::shared_ptr<Trade>(new Trade(tradeNode));}
   }

   //amendmentNode ----------------------------------------------------------------------------------------------------------------------
   TiXmlElement* amendmentNode = xmlNode->FirstChildElement("amendment");

   if(amendmentNode){amendmentIsNull_ = false;}
   else{amendmentIsNull_ = true;}

   #ifdef ConsolePrint
      FileManager::instance().outFile_ << FileManager::instance().tap_.c_str() << "- amendmentNode , address : " << amendmentNode << std::endl;
   #endif
   if(amendmentNode)
   {
      if(amendmentNode->Attribute("href") || amendmentNode->Attribute("id"))
      {
          if(amendmentNode->Attribute("id"))
          {
             amendmentIDRef_ = amendmentNode->Attribute("id");
             amendment_ = boost::shared_ptr<TradeAmendmentContent>(new TradeAmendmentContent(amendmentNode));
             amendment_->setID(amendmentIDRef_);
             IDManager::instance().setID(amendmentIDRef_,amendment_);
          }
          else if(amendmentNode->Attribute("href")) { amendmentIDRef_ = amendmentNode->Attribute("href");}
          else { QL_FAIL("id or href error"); }
      }
      else { amendment_ = boost::shared_ptr<TradeAmendmentContent>(new TradeAmendmentContent(amendmentNode));}
   }

   //increaseNode ----------------------------------------------------------------------------------------------------------------------
   TiXmlElement* increaseNode = xmlNode->FirstChildElement("increase");

   if(increaseNode){increaseIsNull_ = false;}
   else{increaseIsNull_ = true;}

   #ifdef ConsolePrint
      FileManager::instance().outFile_ << FileManager::instance().tap_.c_str() << "- increaseNode , address : " << increaseNode << std::endl;
   #endif
   if(increaseNode)
   {
      if(increaseNode->Attribute("href") || increaseNode->Attribute("id"))
      {
          if(increaseNode->Attribute("id"))
          {
             increaseIDRef_ = increaseNode->Attribute("id");
             increase_ = boost::shared_ptr<TradeNotionalChange>(new TradeNotionalChange(increaseNode));
             increase_->setID(increaseIDRef_);
             IDManager::instance().setID(increaseIDRef_,increase_);
          }
          else if(increaseNode->Attribute("href")) { increaseIDRef_ = increaseNode->Attribute("href");}
          else { QL_FAIL("id or href error"); }
      }
      else { increase_ = boost::shared_ptr<TradeNotionalChange>(new TradeNotionalChange(increaseNode));}
   }

   //terminatingEventNode ----------------------------------------------------------------------------------------------------------------------
   TiXmlElement* terminatingEventNode = xmlNode->FirstChildElement("terminatingEvent");

   if(terminatingEventNode){terminatingEventIsNull_ = false;}
   else{terminatingEventIsNull_ = true;}

   #ifdef ConsolePrint
      FileManager::instance().outFile_ << FileManager::instance().tap_.c_str() << "- terminatingEventNode , address : " << terminatingEventNode << std::endl;
   #endif
   if(terminatingEventNode)
   {
      if(terminatingEventNode->Attribute("href") || terminatingEventNode->Attribute("id"))
      {
          if(terminatingEventNode->Attribute("id"))
          {
             terminatingEventIDRef_ = terminatingEventNode->Attribute("id");
             terminatingEvent_ = boost::shared_ptr<TerminatingEvent>(new TerminatingEvent(terminatingEventNode));
             terminatingEvent_->setID(terminatingEventIDRef_);
             IDManager::instance().setID(terminatingEventIDRef_,terminatingEvent_);
          }
          else if(terminatingEventNode->Attribute("href")) { terminatingEventIDRef_ = terminatingEventNode->Attribute("href");}
          else { QL_FAIL("id or href error"); }
      }
      else { terminatingEvent_ = boost::shared_ptr<TerminatingEvent>(new TerminatingEvent(terminatingEventNode));}
   }

   //terminationNode ----------------------------------------------------------------------------------------------------------------------
   TiXmlElement* terminationNode = xmlNode->FirstChildElement("termination");

   if(terminationNode){terminationIsNull_ = false;}
   else{terminationIsNull_ = true;}

   #ifdef ConsolePrint
      FileManager::instance().outFile_ << FileManager::instance().tap_.c_str() << "- terminationNode , address : " << terminationNode << std::endl;
   #endif
   if(terminationNode)
   {
      if(terminationNode->Attribute("href") || terminationNode->Attribute("id"))
      {
          if(terminationNode->Attribute("id"))
          {
             terminationIDRef_ = terminationNode->Attribute("id");
             termination_ = boost::shared_ptr<TradeNotionalChange>(new TradeNotionalChange(terminationNode));
             termination_->setID(terminationIDRef_);
             IDManager::instance().setID(terminationIDRef_,termination_);
          }
          else if(terminationNode->Attribute("href")) { terminationIDRef_ = terminationNode->Attribute("href");}
          else { QL_FAIL("id or href error"); }
      }
      else { termination_ = boost::shared_ptr<TradeNotionalChange>(new TradeNotionalChange(terminationNode));}
   }

   //novationNode ----------------------------------------------------------------------------------------------------------------------
   TiXmlElement* novationNode = xmlNode->FirstChildElement("novation");

   if(novationNode){novationIsNull_ = false;}
   else{novationIsNull_ = true;}

   #ifdef ConsolePrint
      FileManager::instance().outFile_ << FileManager::instance().tap_.c_str() << "- novationNode , address : " << novationNode << std::endl;
   #endif
   if(novationNode)
   {
      if(novationNode->Attribute("href") || novationNode->Attribute("id"))
      {
          if(novationNode->Attribute("id"))
          {
             novationIDRef_ = novationNode->Attribute("id");
             novation_ = boost::shared_ptr<TradeNovationContent>(new TradeNovationContent(novationNode));
             novation_->setID(novationIDRef_);
             IDManager::instance().setID(novationIDRef_,novation_);
          }
          else if(novationNode->Attribute("href")) { novationIDRef_ = novationNode->Attribute("href");}
          else { QL_FAIL("id or href error"); }
      }
      else { novation_ = boost::shared_ptr<TradeNovationContent>(new TradeNovationContent(novationNode));}
   }

   //optionExerciseNode ----------------------------------------------------------------------------------------------------------------------
   TiXmlElement* optionExerciseNode = xmlNode->FirstChildElement("optionExercise");

   if(optionExerciseNode){optionExerciseIsNull_ = false;}
   else{optionExerciseIsNull_ = true;}

   #ifdef ConsolePrint
      FileManager::instance().outFile_ << FileManager::instance().tap_.c_str() << "- optionExerciseNode , address : " << optionExerciseNode << std::endl;
   #endif
   if(optionExerciseNode)
   {
      if(optionExerciseNode->Attribute("href") || optionExerciseNode->Attribute("id"))
      {
          if(optionExerciseNode->Attribute("id"))
          {
             optionExerciseIDRef_ = optionExerciseNode->Attribute("id");
             optionExercise_ = boost::shared_ptr<OptionExercise>(new OptionExercise(optionExerciseNode));
             optionExercise_->setID(optionExerciseIDRef_);
             IDManager::instance().setID(optionExerciseIDRef_,optionExercise_);
          }
          else if(optionExerciseNode->Attribute("href")) { optionExerciseIDRef_ = optionExerciseNode->Attribute("href");}
          else { QL_FAIL("id or href error"); }
      }
      else { optionExercise_ = boost::shared_ptr<OptionExercise>(new OptionExercise(optionExerciseNode));}
   }

   //optionExpiryNode ----------------------------------------------------------------------------------------------------------------------
   TiXmlElement* optionExpiryNode = xmlNode->FirstChildElement("optionExpiry");

   if(optionExpiryNode){optionExpiryIsNull_ = false;}
   else{optionExpiryIsNull_ = true;}

   if(optionExpiryNode)
   {
      for(optionExpiryNode; optionExpiryNode; optionExpiryNode = optionExpiryNode->NextSiblingElement("optionExpiry")){
          #ifdef ConsolePrint
              FileManager::instance().outFile_ << FileManager::instance().tap_.c_str() << "- optionExpiryNode , address : " << optionExpiryNode << std::endl;
          #endif
          if(optionExpiryNode->Attribute("href") || optionExpiryNode->Attribute("id"))
          {
              if(optionExpiryNode->Attribute("id"))
              {
                  optionExpiryIDRef_ = optionExpiryNode->Attribute("id");
                  optionExpiry_.push_back(boost::shared_ptr<OptionExpiry>(new OptionExpiry(optionExpiryNode)));
                  optionExpiry_.back()->setID(optionExpiryIDRef_);
                  IDManager::instance().setID(optionExpiryIDRef_, optionExpiry_.back());
              }
              else if(optionExpiryNode->Attribute("href")) { optionExpiryIDRef_ = optionExpiryNode->Attribute("href");}
              else { QL_FAIL("id or href error"); }
          }
          else { optionExpiry_.push_back(boost::shared_ptr<OptionExpiry>(new OptionExpiry(optionExpiryNode)));}
      }
   }
   else {
       #ifdef ConsolePrint
           FileManager::instance().outFile_ << FileManager::instance().tap_.c_str() << "- optionExpiryNode , address : " << optionExpiryNode << std::endl;
       #endif
   }

   //deClearNode ----------------------------------------------------------------------------------------------------------------------
   TiXmlElement* deClearNode = xmlNode->FirstChildElement("deClear");

   if(deClearNode){deClearIsNull_ = false;}
   else{deClearIsNull_ = true;}

   #ifdef ConsolePrint
      FileManager::instance().outFile_ << FileManager::instance().tap_.c_str() << "- deClearNode , address : " << deClearNode << std::endl;
   #endif
   if(deClearNode)
   {
      if(deClearNode->Attribute("href") || deClearNode->Attribute("id"))
      {
          if(deClearNode->Attribute("id"))
          {
             deClearIDRef_ = deClearNode->Attribute("id");
             deClear_ = boost::shared_ptr<DeClear>(new DeClear(deClearNode));
             deClear_->setID(deClearIDRef_);
             IDManager::instance().setID(deClearIDRef_,deClear_);
          }
          else if(deClearNode->Attribute("href")) { deClearIDRef_ = deClearNode->Attribute("href");}
          else { QL_FAIL("id or href error"); }
      }
      else { deClear_ = boost::shared_ptr<DeClear>(new DeClear(deClearNode));}
   }

   //withdrawalNode ----------------------------------------------------------------------------------------------------------------------
   TiXmlElement* withdrawalNode = xmlNode->FirstChildElement("withdrawal");

   if(withdrawalNode){withdrawalIsNull_ = false;}
   else{withdrawalIsNull_ = true;}

   #ifdef ConsolePrint
      FileManager::instance().outFile_ << FileManager::instance().tap_.c_str() << "- withdrawalNode , address : " << withdrawalNode << std::endl;
   #endif
   if(withdrawalNode)
   {
      if(withdrawalNode->Attribute("href") || withdrawalNode->Attribute("id"))
      {
          if(withdrawalNode->Attribute("id"))
          {
             withdrawalIDRef_ = withdrawalNode->Attribute("id");
             withdrawal_ = boost::shared_ptr<Withdrawal>(new Withdrawal(withdrawalNode));
             withdrawal_->setID(withdrawalIDRef_);
             IDManager::instance().setID(withdrawalIDRef_,withdrawal_);
          }
          else if(withdrawalNode->Attribute("href")) { withdrawalIDRef_ = withdrawalNode->Attribute("href");}
          else { QL_FAIL("id or href error"); }
      }
      else { withdrawal_ = boost::shared_ptr<Withdrawal>(new Withdrawal(withdrawalNode));}
   }

   //additionalEventNode ----------------------------------------------------------------------------------------------------------------------
   TiXmlElement* additionalEventNode = xmlNode->FirstChildElement("additionalEvent");

   if(additionalEventNode){additionalEventIsNull_ = false;}
   else{additionalEventIsNull_ = true;}

   #ifdef ConsolePrint
      FileManager::instance().outFile_ << FileManager::instance().tap_.c_str() << "- additionalEventNode , address : " << additionalEventNode << std::endl;
   #endif
   if(additionalEventNode)
   {
      if(additionalEventNode->Attribute("href") || additionalEventNode->Attribute("id"))
      {
          if(additionalEventNode->Attribute("id"))
          {
             additionalEventIDRef_ = additionalEventNode->Attribute("id");
             additionalEvent_ = boost::shared_ptr<AdditionalEvent>(new AdditionalEvent(additionalEventNode));
             additionalEvent_->setID(additionalEventIDRef_);
             IDManager::instance().setID(additionalEventIDRef_,additionalEvent_);
          }
          else if(additionalEventNode->Attribute("href")) { additionalEventIDRef_ = additionalEventNode->Attribute("href");}
          else { QL_FAIL("id or href error"); }
      }
      else { additionalEvent_ = boost::shared_ptr<AdditionalEvent>(new AdditionalEvent(additionalEventNode));}
   }

   //partyNode ----------------------------------------------------------------------------------------------------------------------
   TiXmlElement* partyNode = xmlNode->FirstChildElement("party");

   if(partyNode){partyIsNull_ = false;}
   else{partyIsNull_ = true;}

   if(partyNode)
   {
      for(partyNode; partyNode; partyNode = partyNode->NextSiblingElement("party")){
          #ifdef ConsolePrint
              FileManager::instance().outFile_ << FileManager::instance().tap_.c_str() << "- partyNode , address : " << partyNode << std::endl;
          #endif
          if(partyNode->Attribute("href") || partyNode->Attribute("id"))
          {
              if(partyNode->Attribute("id"))
              {
                  partyIDRef_ = partyNode->Attribute("id");
                  party_.push_back(boost::shared_ptr<Party>(new Party(partyNode)));
                  party_.back()->setID(partyIDRef_);
                  IDManager::instance().setID(partyIDRef_, party_.back());
              }
              else if(partyNode->Attribute("href")) { partyIDRef_ = partyNode->Attribute("href");}
              else { QL_FAIL("id or href error"); }
          }
          else { party_.push_back(boost::shared_ptr<Party>(new Party(partyNode)));}
      }
   }
   else {
       #ifdef ConsolePrint
           FileManager::instance().outFile_ << FileManager::instance().tap_.c_str() << "- partyNode , address : " << partyNode << std::endl;
       #endif
   }

   //accountNode ----------------------------------------------------------------------------------------------------------------------
   TiXmlElement* accountNode = xmlNode->FirstChildElement("account");

   if(accountNode){accountIsNull_ = false;}
   else{accountIsNull_ = true;}

   if(accountNode)
   {
      for(accountNode; accountNode; accountNode = accountNode->NextSiblingElement("account")){
          #ifdef ConsolePrint
              FileManager::instance().outFile_ << FileManager::instance().tap_.c_str() << "- accountNode , address : " << accountNode << std::endl;
          #endif
          if(accountNode->Attribute("href") || accountNode->Attribute("id"))
          {
              if(accountNode->Attribute("id"))
              {
                  accountIDRef_ = accountNode->Attribute("id");
                  account_.push_back(boost::shared_ptr<Account>(new Account(accountNode)));
                  account_.back()->setID(accountIDRef_);
                  IDManager::instance().setID(accountIDRef_, account_.back());
              }
              else if(accountNode->Attribute("href")) { accountIDRef_ = accountNode->Attribute("href");}
              else { QL_FAIL("id or href error"); }
          }
          else { account_.push_back(boost::shared_ptr<Account>(new Account(accountNode)));}
      }
   }
   else {
       #ifdef ConsolePrint
           FileManager::instance().outFile_ << FileManager::instance().tap_.c_str() << "- accountNode , address : " << accountNode << std::endl;
       #endif
   }

   //reasonNode ----------------------------------------------------------------------------------------------------------------------
   TiXmlElement* reasonNode = xmlNode->FirstChildElement("reason");

   if(reasonNode){reasonIsNull_ = false;}
   else{reasonIsNull_ = true;}

   if(reasonNode)
   {
      for(reasonNode; reasonNode; reasonNode = reasonNode->NextSiblingElement("reason")){
          #ifdef ConsolePrint
              FileManager::instance().outFile_ << FileManager::instance().tap_.c_str() << "- reasonNode , address : " << reasonNode << std::endl;
          #endif
          if(reasonNode->Attribute("href") || reasonNode->Attribute("id"))
          {
              if(reasonNode->Attribute("id"))
              {
                  reasonIDRef_ = reasonNode->Attribute("id");
                  reason_.push_back(boost::shared_ptr<Reason>(new Reason(reasonNode)));
                  reason_.back()->setID(reasonIDRef_);
                  IDManager::instance().setID(reasonIDRef_, reason_.back());
              }
              else if(reasonNode->Attribute("href")) { reasonIDRef_ = reasonNode->Attribute("href");}
              else { QL_FAIL("id or href error"); }
          }
          else { reason_.push_back(boost::shared_ptr<Reason>(new Reason(reasonNode)));}
      }
   }
   else {
       #ifdef ConsolePrint
           FileManager::instance().outFile_ << FileManager::instance().tap_.c_str() << "- reasonNode , address : " << reasonNode << std::endl;
       #endif
   }

    #ifdef ConsolePrint
        FileManager::instance().tap_ = initialtap_;
    #endif 
}
Example #13
0
string Edge305Device::getDeviceDescription() const {

    if (Log::enabledDbg()) Log::dbg("GpsDevice::getDeviceDescription() "+this->displayName);
    /*

    <?xml version="1.0" encoding="UTF-8" standalone="no" ?>
    <Device xmlns="http://www.garmin.com/xmlschemas/GarminDevice/v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.garmin.com/xmlschemas/GarminDevice/v2 http://www.garmin.com/xmlschemas/GarminDevicev2.xsd">

      <Model>
        <PartNumber>006-B0450-00</PartNumber>
        <SoftwareVersion>320</SoftwareVersion>
        <Description>EDGE305 Software Version 3.20</Description>
      </Model>

      <Id>3305091776</Id>
      <DisplayName>Your name</DisplayName>

      <MassStorageMode>
        <DataType>
          <Name>GPSData</Name>
          <File>
            <Specification>
              <Identifier>http://www.topografix.com/GPX/1/1</Identifier>
              <Documentation>http://www.topografix.com/GPX/1/1/gpx.xsd</Documentation>
            </Specification>
            <Location>
              <FileExtension>GPX</FileExtension>
            </Location>
            <TransferDirection>InputOutput</TransferDirection>
          </File>
        </DataType>
        <DataType>
          <Name>FitnessHistory</Name>
          <File>
            <Specification>
              <Identifier>http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2</Identifier>
              <Documentation>http://www.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd</Documentation>
            </Specification>
            <Location>
              <FileExtension>TCX</FileExtension>
            </Location>
            <TransferDirection>OutputFromUnit</TransferDirection>
          </File>
        </DataType>
        <DataType>
          <Name>FitnessUserProfile</Name>
          <File>
            <Specification>
              <Identifier>http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2</Identifier>
              <Documentation>http://www.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd</Documentation>
            </Specification>
            <Location>
              <BaseName>UserProfile</BaseName>
              <FileExtension>TCX</FileExtension>
            </Location>
            <TransferDirection>InputOutput</TransferDirection>
          </File>
        </DataType>
        <DataType>
          <Name>FitnessCourses</Name>
          <File>
            <Specification>
              <Identifier>http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2</Identifier>
              <Documentation>http://www.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd</Documentation>
            </Specification>
            <Location>
              <FileExtension>TCX</FileExtension>
            </Location>
            <TransferDirection>InputOutput</TransferDirection>
          </File>
        </DataType>
        <DataType>
          <Name>FitnessWorkouts</Name>
          <File>
            <Specification>
              <Identifier>http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2</Identifier>
              <Documentation>http://www.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd</Documentation>
            </Specification>
            <Location>
              <FileExtension>TCX</FileExtension>
            </Location>
            <TransferDirection>InputOutput</TransferDirection>
          </File>
        </DataType>
        <UpdateFile>
          <PartNumber>006-B0450-00</PartNumber>
          <Version>
            <Major>0</Major>
            <Minor>0</Minor>
          </Version>
          <Description>Missing</Description>
        </UpdateFile>
        <UpdateFile>
          <PartNumber>006-B0478-00</PartNumber>
          <Version>
            <Major>0</Major>
            <Minor>0</Minor>
          </Version>
          <Description>Missing</Description>
        </UpdateFile>
      </MassStorageMode>

      <GarminMode>
        <Protocols>
          <Application Id="918">
            <DataType>918</DataType>
          </Application>
        </Protocols>
        <Extensions>
          <GarminModeExtension xmlns="http://www.garmin.com/xmlschemas/GarminDeviceExtensions/v3">
            <MemoryRegion>
              <Id>5</Id>
              <Version>
                <Major>0</Major>
                <Minor>0</Minor>
              </Version>
              <Description>Missing</Description>
              <ExpectedPartNumber>006-B0450-00</ExpectedPartNumber>
              <CurrentPartNumber>006-B0450-00</CurrentPartNumber>
              <IsErased>true</IsErased>
              <IsUserUpdateable>true</IsUserUpdateable>
            </MemoryRegion>
            <MemoryRegion>
              <Id>14</Id>
              <Version>
                <Major>3</Major>
                <Minor>20</Minor>
              </Version>
              <Description>EDGE305</Description>
              <ExpectedPartNumber>006-B0450-00</ExpectedPartNumber>
              <CurrentPartNumber>006-B0450-00</CurrentPartNumber>
              <IsUserUpdateable>true</IsUserUpdateable>
            </MemoryRegion>
            <MemoryRegion>
              <Id>246</Id>
              <Version>
                <Major>0</Major>
                <Minor>0</Minor>
              </Version>
              <Description>Missing</Description>
              <ExpectedPartNumber>006-B0478-00</ExpectedPartNumber>
              <CurrentPartNumber>006-B0478-00</CurrentPartNumber>
              <IsErased>true</IsErased>
              <IsUserUpdateable>true</IsUserUpdateable>
            </MemoryRegion>
          </GarminModeExtension>
        </Extensions>
      </GarminMode>

    </Device>


    */
    garmin_unit garmin;
    if ( garmin_init(&garmin,0) != 0 ) {
        garmin_close(&garmin);
    } else {
        Log::err("Opening of garmin device failed. No longer attached!?");
        return "";
    }


    TiXmlDocument doc;
    TiXmlDeclaration * decl = new TiXmlDeclaration( "1.0", "UTF-8", "no" );
    doc.LinkEndChild( decl );

    /*<Device xmlns="http://www.garmin.com/xmlschemas/GarminDevice/v2"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.garmin.com/xmlschemas/GarminDevice/v2 http://www.garmin.com/xmlschemas/GarminDevicev2.xsd">*/

    TiXmlElement * device = new TiXmlElement( "Device" );
    device->SetAttribute("xmlns", "http://www.garmin.com/xmlschemas/GarminDevice/v2");
    device->SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
    device->SetAttribute("xsi:schemaLocation", "http://www.garmin.com/xmlschemas/GarminDevice/v2 http://www.garmin.com/xmlschemas/GarminDevicev2.xsd");
    doc.LinkEndChild( device );

    /*<Model>
        <PartNumber>006-B0450-00</PartNumber>
        <SoftwareVersion>320</SoftwareVersion>
        <Description>EDGE305 Software Version 3.20</Description>
      </Model> */
    TiXmlElement * model = new TiXmlElement( "Model" );
    TiXmlElement * partnumber = new TiXmlElement( "PartNumber" );
    partnumber->LinkEndChild(new TiXmlText("006-B0450-00"));
    TiXmlElement * version = new TiXmlElement( "SoftwareVersion" );
    std::stringstream ss;
    ss << garmin.product.software_version;
    version->LinkEndChild(new TiXmlText( ss.str() ));
    TiXmlElement * descr = new TiXmlElement( "Description" );
    descr->LinkEndChild(new TiXmlText(this->displayName));
    model->LinkEndChild(partnumber);
    model->LinkEndChild(version);
    model->LinkEndChild(descr);
    device->LinkEndChild( model );

    /*  <Id>3333333333</Id> */
    TiXmlElement * id = new TiXmlElement( "Id" );
    ss.str(""); // empty stringstream
    ss << garmin.id;
    id->LinkEndChild(new TiXmlText(ss.str()));
    device->LinkEndChild(id);
    /*  <DisplayName>Your name</DisplayName>*/
    TiXmlElement * dispName = new TiXmlElement( "DisplayName" );
    dispName->LinkEndChild(new TiXmlText(this->displayName));
    device->LinkEndChild(dispName);

    TiXmlElement * massStorage = new TiXmlElement( "MassStorageMode" );
    device->LinkEndChild(massStorage);

    /*
        <DataType>
          <Name>GPSData</Name>
          <File>
            <Specification>
              <Identifier>http://www.topografix.com/GPX/1/1</Identifier>
              <Documentation>http://www.topografix.com/GPX/1/1/gpx.xsd</Documentation>
            </Specification>
            <Location>
              <FileExtension>GPX</FileExtension>
            </Location>
            <TransferDirection>InputOutput</TransferDirection>
          </File>
        </DataType>
    */

    TiXmlElement * dataTypes = new TiXmlElement( "DataType" );
    massStorage->LinkEndChild(dataTypes);
    TiXmlElement * name = new TiXmlElement( "Name" );
    name->LinkEndChild(new TiXmlText("GPSData"));
    dataTypes->LinkEndChild(name);

    TiXmlElement * file = new TiXmlElement( "File" );
    dataTypes->LinkEndChild(file);
    TiXmlElement * spec = new TiXmlElement( "Specification" );
    file->LinkEndChild(spec);

    TiXmlElement * identifier = new TiXmlElement( "Identifier" );
    identifier->LinkEndChild(new TiXmlText("http://www.topografix.com/GPX/1/1"));
    spec->LinkEndChild(identifier);

    TiXmlElement * docu = new TiXmlElement( "Documentation" );
    docu->LinkEndChild(new TiXmlText("http://www.topografix.com/GPX/1/1/gpx.xsd"));
    spec->LinkEndChild(docu);

    TiXmlElement * loc = new TiXmlElement( "Location" );
    file->LinkEndChild(loc);

    TiXmlElement * fileEx = new TiXmlElement( "FileExtension" );
    fileEx->LinkEndChild(new TiXmlText("GPX"));
    loc->LinkEndChild(fileEx);

    TiXmlElement * transferDir = new TiXmlElement( "TransferDirection" );
    transferDir->LinkEndChild(new TiXmlText("InputOutput"));
    file->LinkEndChild(transferDir);


    /*
    <DataType>
      <Name>FitnessHistory</Name>
      <File>
        <Specification>
          <Identifier>http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2</Identifier>
          <Documentation>http://www.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd</Documentation>
        </Specification>
        <Location>
          <FileExtension>TCX</FileExtension>
        </Location>
        <TransferDirection>OutputFromUnit</TransferDirection>
      </File>
    </DataType>
    */
    dataTypes = new TiXmlElement( "DataType" );
    massStorage->LinkEndChild(dataTypes);
    name = new TiXmlElement( "Name" );
    name->LinkEndChild(new TiXmlText("FitnessHistory"));
    dataTypes->LinkEndChild(name);

    file = new TiXmlElement( "File" );
    dataTypes->LinkEndChild(file);

    spec = new TiXmlElement( "Specification" );
    file->LinkEndChild(spec);

    identifier = new TiXmlElement( "Identifier" );
    identifier->LinkEndChild(new TiXmlText("http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2"));
    spec->LinkEndChild(identifier);

    docu = new TiXmlElement( "Documentation" );
    docu->LinkEndChild(new TiXmlText("http://www.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd"));
    spec->LinkEndChild(docu);

    loc = new TiXmlElement( "Location" );
    file->LinkEndChild(loc);

    fileEx = new TiXmlElement( "FileExtension" );
    fileEx->LinkEndChild(new TiXmlText("TCX"));
    loc->LinkEndChild(fileEx);

    transferDir = new TiXmlElement( "TransferDirection" );
    transferDir->LinkEndChild(new TiXmlText("InputOutput"));
    file->LinkEndChild(transferDir);




    TiXmlPrinter printer;
    printer.SetIndent( "\t" );
    doc.Accept( &printer );
    string str = printer.Str();

    if (Log::enabledDbg()) Log::dbg("GpsDevice::getDeviceDescription() Done: "+this->displayName );
    return str;


}
Example #14
0
bool final_xml_file(const char* xml_name, cat_items_mgr& mgr)
{
	if(xml_name == NULL)return false;
	TiXmlDocument* pdoc = new TiXmlDocument;

	TiXmlElement* root = new TiXmlElement("Items");
	pdoc->LinkEndChild(root);
	
	std::map<int, cat_items>::iterator pItr = mgr.cat_items_map.begin();
	for(; pItr != mgr.cat_items_map.end(); ++pItr)
	{
		cat_items* p_cat = &(pItr->second);
		TiXmlElement* pCat = new TiXmlElement("Cat");
		pCat->SetAttribute("ID",  p_cat->cat_id);
		pCat->SetAttribute("DbCatID", p_cat->db_cat_id);
		pCat->SetAttribute("Name", p_cat->name);
		pCat->SetAttribute("Max", p_cat->max);
		
		map<int, item_attire_data>::iterator pItr2 = p_cat->item_map.begin();
		for(; pItr2 != p_cat->item_map.end(); ++pItr2)
		{
			item_attire_data* p_data= &(pItr2->second);
			TiXmlElement* pData = new TiXmlElement("Item");	
			pData->SetAttribute("ID", p_data->id);
			pData->SetAttribute("Name", p_data->name);
			pData->SetAttribute("DropLv", p_data->droplv);
			pData->SetAttribute("QualityLevel", p_data->quality_level);
			pData->SetAttribute("EquipPart", p_data->equip_part);
			pData->SetAttribute("Price", p_data->price);
			pData->SetAttribute("SellPrice", p_data->sell_price);
			pData->SetAttribute("RepairPrice", p_data->repair_price);
			pData->SetAttribute("UseLv", p_data->uselv);
			pData->SetAttribute("Strength", p_data->strength);
			pData->SetAttribute("Agility", p_data->agility);
			pData->SetAttribute("BodyQuality", p_data->body_quality);
			pData->SetAttribute("Stamina", p_data->stamina);
			if(strlen(p_data->atk) > 0)
			{
				pData->SetAttribute("Atk", p_data->atk);
			}
			pData->SetAttribute("Def", p_data->def);
			pData->SetAttribute("Duration", p_data->duration);
			pData->SetAttribute("Hit", p_data->hit);
			pData->SetAttribute("Dodge", p_data->dodge);
			pData->SetAttribute("Crit", p_data->crit);
			pData->SetAttribute("Hp", p_data->hp);
			pData->SetAttribute("Mp", p_data->mp);
			pData->SetAttribute("AddHp", p_data->add_hp);
			pData->SetAttribute("AddMp", p_data->add_mp);
			pData->SetAttribute("Slot",  p_data->slot);
			pData->SetAttribute("Tradability", p_data->trade_ability);
			pData->SetAttribute("VipTradability", p_data->vip_trade_ability);
			pData->SetAttribute("Tradable", p_data->trade_able);
			pData->SetAttribute("ExploitValue", p_data->exploit_value);
			pData->SetAttribute("SetID", p_data->setid);
			pData->SetAttribute("honorLevel", p_data->honor_level);
			pData->SetAttribute("LifeTime", p_data->life_time);
			pData->SetAttribute("VipOnly", p_data->vip_only);
			pData->SetAttribute("DailyId", p_data->dailyid);
			pData->SetAttribute("decompose", p_data->decompose);
			pData->SetAttribute("Shop", p_data->shop);
			pData->SetAttribute("UnStorage", p_data->un_storage);
			pData->SetAttribute("resID", p_data->res_id);
			if(strlen(p_data->descipt) > 0)
			{
				TiXmlElement* pdescipt = new TiXmlElement("descript");
				TiXmlText *pText = new TiXmlText(p_data->descipt);
				pText->SetCDATA(true);
				pdescipt->InsertEndChild(*pText);
				pData->InsertEndChild(*pdescipt);
			}
	
			pCat->InsertEndChild(*pData);	
		}
		root->InsertEndChild(*pCat);
	}
	return pdoc->SaveFile(xml_name);
}
Example #15
0
	xdl_int XdevLFTDI::readInfoFromXMLFile() {
		if(getMediator()->getXmlFilename() == nullptr)
			return RET_FAILED;

		TiXmlDocument xmlDocument;
		if(!xmlDocument.LoadFile(getMediator()->getXmlFilename())) {
			XDEVL_MODULE_ERROR("Could not parse xml file: " << getMediator()->getXmlFilename() << std::endl);
			return RET_FAILED;
		}

		TiXmlHandle docHandle(&xmlDocument);
		TiXmlElement* root = docHandle.FirstChild(XdevLCorePropertiesName.c_str()).FirstChildElement("XdevLSerial").ToElement();
		if(!root) {
			XDEVL_MODULE_WARNING("<XdevLSerial> section not found. Using default values for the device.\n");
			return RET_SUCCESS;
		}

		while(root != nullptr) {
			if(root->Attribute("id")) {
				XdevLID id(root->Attribute("id"));
				if(getID() == id) {
					if(root->Attribute("device")) {
						m_deviceName = XdevLString(root->Attribute("device"));
					}
					if(root->Attribute("usb_in_size")) {
						std::istringstream ss(root->Attribute("usb_in_size"));
						ss >> m_usbInSize;
					}
					if(root->Attribute("usb_out_size")) {
						std::istringstream ss(root->Attribute("usb_out_size"));
						ss >> m_usbOutSize;
					}
					if(root->Attribute("latency_timer")) {
						std::istringstream ss(root->Attribute("latency_timer"));
						ss >> m_latencyTimer;
					}
AdjustableOrRelativeDates::AdjustableOrRelativeDates(TiXmlNode* xmlNode)
: ISerialized(xmlNode)
{
    #ifdef ConsolePrint
        std::string initialtap_ = FileManager::instance().tap_;
        FileManager::instance().tap_.append("   ");
    #endif 
   //adjustableDatesNode ----------------------------------------------------------------------------------------------------------------------
   TiXmlElement* adjustableDatesNode = xmlNode->FirstChildElement("adjustableDates");

   if(adjustableDatesNode){adjustableDatesIsNull_ = false;}
   else{adjustableDatesIsNull_ = true;}

   #ifdef ConsolePrint
      FileManager::instance().outFile_ << FileManager::instance().tap_.c_str() << "- adjustableDatesNode , address : " << adjustableDatesNode << std::endl;
   #endif
   if(adjustableDatesNode)
   {
      if(adjustableDatesNode->Attribute("href") || adjustableDatesNode->Attribute("id"))
      {
          if(adjustableDatesNode->Attribute("id"))
          {
             adjustableDatesIDRef_ = adjustableDatesNode->Attribute("id");
             adjustableDates_ = boost::shared_ptr<AdjustableDates>(new AdjustableDates(adjustableDatesNode));
             adjustableDates_->setID(adjustableDatesIDRef_);
             IDManager::instance().setID(adjustableDatesIDRef_,adjustableDates_);
          }
          else if(adjustableDatesNode->Attribute("href")) { adjustableDatesIDRef_ = adjustableDatesNode->Attribute("href");}
          else { QL_FAIL("id or href error"); }
      }
      else { adjustableDates_ = boost::shared_ptr<AdjustableDates>(new AdjustableDates(adjustableDatesNode));}
   }

   //relativeDatesNode ----------------------------------------------------------------------------------------------------------------------
   TiXmlElement* relativeDatesNode = xmlNode->FirstChildElement("relativeDates");

   if(relativeDatesNode){relativeDatesIsNull_ = false;}
   else{relativeDatesIsNull_ = true;}

   #ifdef ConsolePrint
      FileManager::instance().outFile_ << FileManager::instance().tap_.c_str() << "- relativeDatesNode , address : " << relativeDatesNode << std::endl;
   #endif
   if(relativeDatesNode)
   {
      if(relativeDatesNode->Attribute("href") || relativeDatesNode->Attribute("id"))
      {
          if(relativeDatesNode->Attribute("id"))
          {
             relativeDatesIDRef_ = relativeDatesNode->Attribute("id");
             relativeDates_ = boost::shared_ptr<RelativeDates>(new RelativeDates(relativeDatesNode));
             relativeDates_->setID(relativeDatesIDRef_);
             IDManager::instance().setID(relativeDatesIDRef_,relativeDates_);
          }
          else if(relativeDatesNode->Attribute("href")) { relativeDatesIDRef_ = relativeDatesNode->Attribute("href");}
          else { QL_FAIL("id or href error"); }
      }
      else { relativeDates_ = boost::shared_ptr<RelativeDates>(new RelativeDates(relativeDatesNode));}
   }

    #ifdef ConsolePrint
        FileManager::instance().tap_ = initialtap_;
    #endif 
}
Example #17
0
TiXmlElement::TiXmlElement( const TiXmlElement& copy)
	: TiXmlNode( TiXmlNode::ELEMENT )
{
	firstChild = lastChild = 0;
	copy.CopyTo( this );	
}
Clearing::Clearing(TiXmlNode* xmlNode)
: ISerialized(xmlNode)
{
    #ifdef ConsolePrint
        std::string initialtap_ = FileManager::instance().tap_;
        FileManager::instance().tap_.append("   ");
    #endif 
   //submittedNode ----------------------------------------------------------------------------------------------------------------------
   TiXmlElement* submittedNode = xmlNode->FirstChildElement("submitted");

   if(submittedNode){submittedIsNull_ = false;}
   else{submittedIsNull_ = true;}

   #ifdef ConsolePrint
      FileManager::instance().outFile_ << FileManager::instance().tap_.c_str() << "- submittedNode , address : " << submittedNode << std::endl;
   #endif
   if(submittedNode)
   {
      if(submittedNode->Attribute("href") || submittedNode->Attribute("id"))
      {
          if(submittedNode->Attribute("id"))
          {
             submittedIDRef_ = submittedNode->Attribute("id");
             submitted_ = boost::shared_ptr<TradeWrapper>(new TradeWrapper(submittedNode));
             submitted_->setID(submittedIDRef_);
             IDManager::instance().setID(submittedIDRef_,submitted_);
          }
          else if(submittedNode->Attribute("href")) { submittedIDRef_ = submittedNode->Attribute("href");}
          else { QL_FAIL("id or href error"); }
      }
      else { submitted_ = boost::shared_ptr<TradeWrapper>(new TradeWrapper(submittedNode));}
   }

   //clearedNode ----------------------------------------------------------------------------------------------------------------------
   TiXmlElement* clearedNode = xmlNode->FirstChildElement("cleared");

   if(clearedNode){clearedIsNull_ = false;}
   else{clearedIsNull_ = true;}

   if(clearedNode)
   {
      for(clearedNode; clearedNode; clearedNode = clearedNode->NextSiblingElement("cleared")){
          #ifdef ConsolePrint
              FileManager::instance().outFile_ << FileManager::instance().tap_.c_str() << "- clearedNode , address : " << clearedNode << std::endl;
          #endif
          if(clearedNode->Attribute("href") || clearedNode->Attribute("id"))
          {
              if(clearedNode->Attribute("id"))
              {
                  clearedIDRef_ = clearedNode->Attribute("id");
                  cleared_.push_back(boost::shared_ptr<TradeWrapper>(new TradeWrapper(clearedNode)));
                  cleared_.back()->setID(clearedIDRef_);
                  IDManager::instance().setID(clearedIDRef_, cleared_.back());
              }
              else if(clearedNode->Attribute("href")) { clearedIDRef_ = clearedNode->Attribute("href");}
              else { QL_FAIL("id or href error"); }
          }
          else { cleared_.push_back(boost::shared_ptr<TradeWrapper>(new TradeWrapper(clearedNode)));}
      }
   }
   else {
       #ifdef ConsolePrint
           FileManager::instance().outFile_ << FileManager::instance().tap_.c_str() << "- clearedNode , address : " << clearedNode << std::endl;
       #endif
   }

    #ifdef ConsolePrint
        FileManager::instance().tap_ = initialtap_;
    #endif 
}
Example #19
0
bool ETHEntityProperties::ReadFromXMLFile(TiXmlElement *pElement)
{
	pElement->QueryIntAttribute(GS_L("type"), (int*)&type);

	int nStaticEntity = static_cast<int>(staticEntity);
	pElement->QueryIntAttribute(GS_L("static"), &nStaticEntity);
	staticEntity = static_cast<ETH_BOOL>(nStaticEntity);

	int nApplyLight = static_cast<int>(applyLight);
	pElement->QueryIntAttribute(GS_L("applyLight"), &nApplyLight);
	applyLight = static_cast<ETH_BOOL>(nApplyLight);

	int nCastShadow = static_cast<int>(castShadow);
	pElement->QueryIntAttribute(GS_L("castShadow"), &nCastShadow);
	castShadow = static_cast<ETH_BOOL>(nCastShadow);

	int nHideFromSceneEditor = static_cast<int>(hideFromSceneEditor);
	pElement->QueryIntAttribute(GS_L("hideFromSceneEditor"), &nHideFromSceneEditor);
	hideFromSceneEditor = static_cast<ETH_BOOL>(nHideFromSceneEditor);

	pElement->QueryIntAttribute(GS_L("shape"), (int*)&shape);
	pElement->QueryIntAttribute(GS_L("blendMode"), (int*)&blendMode);
	pElement->QueryFloatAttribute(GS_L("layerDepth"), &layerDepth);
	pElement->QueryFloatAttribute(GS_L("soundVolume"), &soundVolume);
	pElement->QueryFloatAttribute(GS_L("parallaxIntensity"), &parallaxIntensity);

	if (applyLight)
	{
		pElement->QueryFloatAttribute(GS_L("specularPower"), &specularPower);
		pElement->QueryFloatAttribute(GS_L("specularBrightness"), &specularBrightness);
	}

	if (castShadow)
	{
		pElement->QueryFloatAttribute(GS_L("shadowScale"), &shadowScale);
		pElement->QueryFloatAttribute(GS_L("shadowLengthScale"), &shadowLengthScale);
		pElement->QueryFloatAttribute(GS_L("shadowOpacity"), &shadowOpacity);
	}

	if (shape != BS_NONE)
	{
		int nSensor = static_cast<int>(sensor);
		pElement->QueryIntAttribute(GS_L("sensor"), &nSensor);
		sensor = static_cast<ETH_BOOL>(nSensor);

		int nFixedRotation = static_cast<int>(fixedRotation);
		pElement->QueryIntAttribute(GS_L("fixedRotation"), &nFixedRotation);
		fixedRotation = static_cast<ETH_BOOL>(nFixedRotation);

		int nBullet = static_cast<int>(bullet);
		pElement->QueryIntAttribute(GS_L("bullet"), &nBullet);
		bullet = static_cast<ETH_BOOL>(nBullet);

		pElement->QueryFloatAttribute(GS_L("friction"), &friction);
		pElement->QueryFloatAttribute(GS_L("density"), &density);
		pElement->QueryFloatAttribute(GS_L("gravityScale"), &gravityScale);
		pElement->QueryFloatAttribute(GS_L("restitution"), &restitution);
	}

	TiXmlElement *pIter;
	TiXmlNode *pNode;

	pNode = pElement->FirstChild(GS_L("EmissiveColor"));
	if (pNode)
	{
		pIter = pNode->ToElement();
		if (pIter)
		{
			pIter->QueryFloatAttribute(GS_L("r"), &emissiveColor.x);
			pIter->QueryFloatAttribute(GS_L("g"), &emissiveColor.y);
			pIter->QueryFloatAttribute(GS_L("b"), &emissiveColor.z);
			pIter->QueryFloatAttribute(GS_L("a"), &emissiveColor.w);
		}
	}

	pNode = pElement->FirstChild(GS_L("SpriteCut"));
	if (pNode)
	{
		pIter = pNode->ToElement();
		if (pIter)
		{
			pIter->QueryIntAttribute(GS_L("x"), &spriteCut.x);
			pIter->QueryIntAttribute(GS_L("y"), &spriteCut.y);
		}
	}

	pNode = pElement->FirstChild(GS_L("Scale"));
	if (pNode)
	{
		pIter = pNode->ToElement();
		if (pIter)
		{
			pIter->QueryFloatAttribute(GS_L("x"), &scale.x);
			pIter->QueryFloatAttribute(GS_L("y"), &scale.y);
		}
	}

	pNode = pElement->FirstChild(GS_L("PivotAdjust"));
	if (pNode)
	{
		pIter = pNode->ToElement();
		if (pIter)
		{
			pIter->QueryFloatAttribute(GS_L("x"), &pivotAdjust.x);
			pIter->QueryFloatAttribute(GS_L("y"), &pivotAdjust.y);
		}
	}

	pNode = pElement->FirstChild(GS_L("Sprite"));
	if (pNode)
	{
		pIter = pNode->ToElement();
		if (pIter)
		{
			spriteFile = pIter->GetText();
		}
	}

	pNode = pElement->FirstChild(GS_L("Normal"));
	if (pNode)
	{
		pIter = pNode->ToElement();
		if (pIter)
		{
			normalFile = pIter->GetText();
		}
	}

	pNode = pElement->FirstChild(GS_L("Gloss"));
	if (pNode)
	{
		pIter = pNode->ToElement();
		if (pIter)
		{
			glossFile = pIter->GetText();
		}
	}

	pNode = pElement->FirstChild(GS_L("Particles"));
	if (pNode)
	{
		TiXmlElement *pParticles = pNode->ToElement();
		if (pParticles)
		{
			pNode = pParticles->FirstChild(GS_L("ParticleSystem"));
			if (pNode)
			{
				TiXmlElement *pParticleIter = pNode->ToElement();
				if (pParticleIter)
				{
					// TODO: use unlimited amount of systems 
					for (std::size_t t = 0; t < ETH_MAX_PARTICLE_SYS_PER_ENTITY; t++)
					{
						if (pParticleIter)
						{
							boost::shared_ptr<ETHParticleSystem> newSystem = boost::shared_ptr<ETHParticleSystem>(new ETHParticleSystem);
							newSystem->ReadFromXMLFile(pParticleIter);
							if (newSystem->nParticles > 0)
							{
								particleSystems.push_back(newSystem);
							}
							pParticleIter = pParticleIter->NextSiblingElement();
						}
					}
				}
			}
		}
	}

	pNode = pElement->FirstChild(GS_L("Light"));
	if (pNode)
	{
		TiXmlElement *pLight = pNode->ToElement();
		if (pLight)
		{
			boost::shared_ptr<ETHLight> newLight = boost::shared_ptr<ETHLight>(new ETHLight(true));
			newLight->ReadFromXMLFile(pLight);
			if (newLight->IsActive() && newLight->range > 0.0f)
			{
				light = newLight;
				// forces the light 'static' flag to be the same as its owner's
				light->staticLight = staticEntity;
			}
		}
	}

	{
		int nCollidable = 1;
		const int r = pElement->QueryIntAttribute(GS_L("collidable"), &nCollidable);
		if (nCollidable || r == TIXML_NO_ATTRIBUTE)
		{
			pNode = pElement->FirstChild(GS_L("Collision"));
			if (pNode)
			{
				collision = boost::shared_ptr<ETHCollisionBox>(new ETHCollisionBox);
				TiXmlElement *pCollision = pNode->ToElement();
				if (pCollision)
				{
					collision->ReadFromXMLFile(pCollision);
				}

				// if it's a legacy entity, it may have a collision body in its XML even though it is not collidable
				if (collision->size == Vector3(0, 0, 0))
				{
					collision.reset();
				}
				
				{
					TiXmlNode *pPolygonNode = pNode->FirstChild(GS_L("Polygon"));
					if (pPolygonNode)
					{
						pIter = pPolygonNode->ToElement();
						if (pIter)
						{
							polygon = ETHPolygonPtr(new ETHPolygon(pIter->GetText()));
						}
					}
					else
					{
						TiXmlNode *pCompoundNode = pNode->FirstChild(GS_L("Compound"));
						if (pCompoundNode)
						{
							pIter = pCompoundNode->ToElement();
							if (pIter)
							{
								compoundShape = ETHCompoundShapePtr(new ETHCompoundShape(pIter->GetText()));
							}
						}
					}
				}
				{
					TiXmlNode *pJointsNode = pNode->FirstChild(GS_L("Joints"));
					if (pJointsNode)
					{
						pIter = pJointsNode->ToElement();
						if (pIter)
						{
							enmlJointDefinitions = pIter->GetText();
						}
					}

				}
			}
		}
	}
	ReadDataFromXMLFile(pElement);
	return true;
}
Example #20
0
//*********************************************************************************************
bool CRTVDirectory::GetDirectory(const CStdString& strPath, CFileItemList &items)
{
    CURL url(strPath);

    CStdString strRoot = strPath;
    URIUtils::AddSlashAtEnd(strRoot);

    // Host name is "*" so we try to discover all ReplayTVs.  This requires some trickery but works.
    if (url.GetHostName() == "*")
    {
        // Check to see whether the URL's path is blank or "Video"
        if (url.GetFileName() == "" || url.GetFileName() == "Video")
        {
            int iOldSize=items.Size();
            struct RTV * rtv = NULL;
            int numRTV;

            // Request that all ReplayTVs on the LAN identify themselves.  Each ReplayTV
            // is given 3000ms to respond to the request.  rtv_discovery returns an array
            // of structs containing the IP and friendly name of all ReplayTVs found on the LAN.
            // For some reason, DVArchive doesn't respond to this request (probably only responds
            // to requests from an IP address of a real ReplayTV).
            numRTV = rtv_discovery(&rtv, 3000);

            // Run through the array and add the ReplayTVs found as folders in XBMC.
            // We must add the IP of each ReplayTV as if it is a file name at the end of a the
            // auto-discover URL--e.g. rtv://*/192.168.1.100--because XBMC does not permit
            // dyamically added shares and will not play from them.  This little trickery is
            // the best workaround I could come up with.
            for (int i = 0; i < numRTV; i++)
            {
                CFileItemPtr pItem(new CFileItem(rtv[i].friendlyName));
                // This will keep the /Video or / and allow one to set up an auto ReplayTV
                // share of either type--simple file listing or ReplayGuide listing.
                pItem->m_strPath = strRoot + rtv[i].hostname;
                pItem->m_bIsFolder = true;
                pItem->SetLabelPreformated(true);
                items.Add(pItem);
            }
            free(rtv);
            return (items.Size()>iOldSize);
            // Else the URL's path should be an IP address of the ReplayTV
        }
        else
        {
            CStdString strURL, strRTV;
            int pos;

            // Isolate the IP from the URL and replace the "*" with the real IP
            // of the ReplayTV.  E.g., rtv://*/Video/192.168.1.100/ becomes
            // rtv://192.168.1.100/Video/ .  This trickery makes things work.
            strURL = strRoot.TrimRight('/');
            pos = strURL.ReverseFind('/');
            strRTV = strURL.Left(pos + 1);
            strRTV.Replace("*", strURL.Mid(pos + 1));
            CURL tmpURL(strRTV);

            // Force the newly constructed share into the right variables to
            // be further processed by the remainder of GetDirectory.
            url = tmpURL;
            strRoot = strRTV;
        }
    }

    // Allow for ReplayTVs on ports other than 80
    CStdString strHostAndPort;
    strHostAndPort = url.GetHostName();
    if (url.HasPort())
    {
        char buffer[10];
        strHostAndPort += ':';
        strHostAndPort += itoa(url.GetPort(), buffer, 10);
    }

    // No path given, list shows from ReplayGuide
    if (url.GetFileName() == "")
    {
        unsigned char * data = NULL;

        // Get the RTV guide data in XML format
        rtv_get_guide_xml(&data, strHostAndPort.c_str());

        // Begin parsing the XML data
        TiXmlDocument xmlDoc;
        xmlDoc.Parse( (const char *) data );
        if ( xmlDoc.Error() )
        {
            free(data);
            return false;
        }
        TiXmlElement* pRootElement = xmlDoc.RootElement();
        if (!pRootElement)
        {
            free(data);
            return false;
        }

        const TiXmlNode *pChild = pRootElement->FirstChild();
        while (pChild > 0)
        {
            CStdString strTagName = pChild->Value();

            if ( !strcmpi(strTagName.c_str(), "ITEM") )
            {
                const TiXmlNode *nameNode = pChild->FirstChild("DISPLAYNAME");
                const TiXmlNode *qualityNode = pChild->FirstChild("QUALITY");
                const TiXmlNode *recordedNode = pChild->FirstChild("RECORDED");
                const TiXmlNode *pathNode = pChild->FirstChild("PATH");
                const TiXmlNode *durationNode = pChild->FirstChild("DURATION");
                const TiXmlNode *sizeNode = pChild->FirstChild("SIZE");
                const TiXmlNode *atrbNode = pChild->FirstChild("ATTRIB");

                SYSTEMTIME dtDateTime;
                DWORD dwFileSize = 0;
                memset(&dtDateTime, 0, sizeof(dtDateTime));

                // DISPLAYNAME
                const char* szName = NULL;
                if (nameNode)
                {
                    szName = nameNode->FirstChild()->Value() ;
                }
                else
                {
                    // Something went wrong, the recording has no name
                    free(data);
                    return false;
                }

                // QUALITY
                const char* szQuality = NULL;
                if (qualityNode)
                {
                    szQuality = qualityNode->FirstChild()->Value() ;
                }

                // RECORDED
                if (recordedNode)
                {
                    CStdString strRecorded = recordedNode->FirstChild()->Value();
                    int iYear, iMonth, iDay;

                    iYear = atoi(strRecorded.Left(4).c_str());
                    iMonth = atoi(strRecorded.Mid(5, 2).c_str());
                    iDay = atoi(strRecorded.Mid(8, 2).c_str());
                    dtDateTime.wYear = iYear;
                    dtDateTime.wMonth = iMonth;
                    dtDateTime.wDay = iDay;

                    int iHour, iMin, iSec;
                    iHour = atoi(strRecorded.Mid(11, 2).c_str());
                    iMin = atoi(strRecorded.Mid(14, 2).c_str());
                    iSec = atoi(strRecorded.Mid(17, 2).c_str());
                    dtDateTime.wHour = iHour;
                    dtDateTime.wMinute = iMin;
                    dtDateTime.wSecond = iSec;
                }

                // PATH
                const char* szPath = NULL;
                if (pathNode)
                {
                    szPath = pathNode->FirstChild()->Value() ;
                }
                else
                {
                    // Something went wrong, the recording has no filename
                    free(data);
                    return false;
                }

                // DURATION
                const char* szDuration = NULL;
                if (durationNode)
                {
                    szDuration = durationNode->FirstChild()->Value() ;
                }

                // SIZE
                // NOTE: Size here is actually just duration in minutes because
                // filesize is not reported by the stripped down GuideParser I use
                if (sizeNode)
                {
                    dwFileSize = atol( sizeNode->FirstChild()->Value() );
                }

                // ATTRIB
                // NOTE: Not currently reported in the XML guide data, nor is it particularly
                // needed unless someone wants to add the ability to sub-divide the recordings
                // into categories, as on a real RTV.
                int attrib = 0;
                if (atrbNode)
                {
                    attrib = atoi( atrbNode->FirstChild()->Value() );
                }

                bool bIsFolder(false);
                if (attrib & FILE_ATTRIBUTE_DIRECTORY)
                    bIsFolder = true;

                CFileItemPtr pItem(new CFileItem(szName));
                pItem->m_dateTime=dtDateTime;
                pItem->m_strPath = strRoot + szPath;
                // Hack to show duration of show in minutes as KB in XMBC because
                // it doesn't currently permit showing duration in minutes.
                // E.g., a 30 minute show will show as 29.3 KB in XBMC.
                pItem->m_dwSize = dwFileSize * 1000;
                pItem->m_bIsFolder = bIsFolder;
                pItem->SetLabelPreformated(true);
                items.Add(pItem);
            }

            pChild = pChild->NextSibling();
        }

        free(data);

        // Path given (usually Video), list filenames only
    }
    else
    {

        unsigned char * data;
        char * p, * q;
        unsigned long status;

        // Return a listing of all files in the given path
        status = rtv_list_files(&data, strHostAndPort.c_str(), url.GetFileName().c_str());
        if (status == 0)
        {
            return false;
        }

        // Loop through the file list using pointers p and q, where p will point to the current
        // filename and q will point to the next filename
        p = (char *) data;
        while (p)
        {
            // Look for the end of the current line of the file listing
            q = strchr(p, '\n');
            // If found, replace the newline character with the NULL terminator
            if (q)
            {
                *q = '\0';
                // Increment q so that it points to the next filename
                q++;
                // *p should be the current null-terminated filename in the list
                if (*p)
                {
                    // Only display MPEG files in XBMC (but not circular.mpg, as that is the RTV
                    // video buffer and XBMC may cause problems if it tries to play it)
                    if (strstr(p, ".mpg") && !strstr(p, "circular"))
                    {
                        CFileItemPtr pItem(new CFileItem(p));
                        pItem->m_strPath = strRoot + p;
                        pItem->m_bIsFolder = false;
                        // The list returned by the RTV doesn't include file sizes, unfortunately
                        //pItem->m_dwSize = atol(szSize);
                        pItem->SetLabelPreformated(true);
                        items.Add(pItem);
                    }
                }
            }
            // Point p to the next filename in the list and loop
            p = q;
        }

        free(data);
    }

    return true;
}
Example #21
0
bool CPlayerCoreFactory::LoadConfiguration(TiXmlElement* pConfig, bool clear)
{
  if (clear)
  {
    for(std::vector<CPlayerCoreConfig *>::iterator it = s_vecCoreConfigs.begin(); it != s_vecCoreConfigs.end(); it++)
      delete *it;
    s_vecCoreConfigs.clear();
    // Builtin players; hard-coded because re-ordering them would break scripts
    CPlayerCoreConfig* dvdplayer = new CPlayerCoreConfig("DVDPlayer", EPC_DVDPLAYER, NULL);
    dvdplayer->m_bPlaysAudio = dvdplayer->m_bPlaysVideo = true;
    s_vecCoreConfigs.push_back(dvdplayer);

     // Don't remove this, its a placeholder for the old MPlayer core, it would break scripts
    CPlayerCoreConfig* mplayer = new CPlayerCoreConfig("oldmplayercore", EPC_DVDPLAYER, NULL);
    s_vecCoreConfigs.push_back(mplayer);

    CPlayerCoreConfig* paplayer = new CPlayerCoreConfig("PAPlayer", EPC_PAPLAYER, NULL);
    paplayer->m_bPlaysAudio = true;
    s_vecCoreConfigs.push_back(paplayer);

    for(std::vector<CPlayerSelectionRule *>::iterator it = s_vecCoreSelectionRules.begin(); it != s_vecCoreSelectionRules.end(); it++)
      delete *it;
    s_vecCoreSelectionRules.clear();
  }

  if (!pConfig || strcmpi(pConfig->Value(),"playercorefactory") != 0)
  {
    CLog::Log(LOGERROR, "Error loading configuration, no <playercorefactory> node");
    return false;
  }

  TiXmlElement *pPlayers = pConfig->FirstChildElement("players");
  if (pPlayers)
  {
    TiXmlElement* pPlayer = pPlayers->FirstChildElement("player");
    while (pPlayer)
    {
      CStdString name = pPlayer->Attribute("name");
      CStdString type = pPlayer->Attribute("type");
      if (type.length() == 0) type = name;
      type.ToLower();

      EPLAYERCORES eCore = EPC_NONE;
      if (type == "dvdplayer" || type == "mplayer") eCore = EPC_DVDPLAYER;
      if (type == "paplayer" ) eCore = EPC_PAPLAYER;
      if (type == "externalplayer" ) eCore = EPC_EXTPLAYER;

      if (eCore != EPC_NONE)
      {
        s_vecCoreConfigs.push_back(new CPlayerCoreConfig(name, eCore, pPlayer));
      }

      pPlayer = pPlayer->NextSiblingElement("player");
    }
  }

  TiXmlElement *pRule = pConfig->FirstChildElement("rules");
  while (pRule)
  {
    const char* szAction = pRule->Attribute("action");
    if (szAction)
    {
      if (stricmp(szAction, "append") == 0)
      {
        s_vecCoreSelectionRules.push_back(new CPlayerSelectionRule(pRule));
      }
      else if (stricmp(szAction, "prepend") == 0)
      {
        s_vecCoreSelectionRules.insert(s_vecCoreSelectionRules.begin(), 1, new CPlayerSelectionRule(pRule));
      }
      else
      {
        s_vecCoreSelectionRules.clear();
        s_vecCoreSelectionRules.push_back(new CPlayerSelectionRule(pRule));
      }
    }
    else
    {
      s_vecCoreSelectionRules.push_back(new CPlayerSelectionRule(pRule));
    }

    pRule = pRule->NextSiblingElement("rules");
  }

  // succeeded - tell the user it worked
  CLog::Log(LOGNOTICE, "Loaded playercorefactory configuration");

  return true;
}
Example #22
0
bool MantisBot::CheckForGoogleCodeChanges(const __ConfigProject& conf)
{
    char tmp[HTTP_BUFFER_SIZE];
    std::string buffer;
    ssize_t len;

    // Download the feed from the specified Google Code URL
    HTTPClient http(m_config.data.googlecode.address, m_httpGoogleCodeAddr, m_httpGoogleCodeBindAddr, false);
    http.Connect(conf.path);
    http.Send();

    if (!http.Ok()) return false;

    if (http.ResponseStatus() != 200)
    {
        printf("Unable to connect to the web page (%s%s): %d %s\n",
                m_config.data.googlecode.address, conf.path,
                http.ResponseStatus(), http.StatusText());
        return false;
    }

    // Grab the feed data
    HTTPStream& stream = http.GetStream();
    if (!stream.Ok()) return false;
    while (stream.Eof() == false)
    {
        len = stream.Read(tmp, HTTP_BUFFER_SIZE);
        if ( len > 0 )
            buffer.append(tmp, len);
    }
    
    // We got the feed, now start processing it's XML contents
    TiXmlDocument xml;
    TiXmlNode *feed, *node;
    xml.Parse(buffer.c_str());
    if (xml.Error())
    {
        printf("Unable to parse XML feed in %s: %s\n", xml.Value(), xml.ErrorDesc());
        return false;
    }
    feed = xml.FirstChild("feed");
    if (!feed) return false;
    node = feed->FirstChild("entry");

    // Loop through the entry nodes
    size_t index;
    int currentId, newestId = -1;
    std::string strAuthor, strDescription, strLink;
    const char *attr;
    while (node)
    {
        TiXmlNode *data = node->FirstChild("title");
        if (!data) return false;
        TiXmlElement *elem = data->ToElement ();
        if (!elem) return false;

        std::string strText = elem->GetText ();

        // Revision
        index = strText.find("Revision ") + 9;
        currentId = atoi(strText.substr(index, strText.find(":",index) - index).c_str());

        // Description
        index = strText.find(":",index) + 2;
        strDescription = strText.substr(index);
        TrimSpaces(strDescription);

        // Author
        data = node->FirstChild("author");
        if (!data) return false;
        data = data->FirstChild("name");
        if (!data) return false;
        elem = data->ToElement ();
        if (!elem) return false;
        strAuthor = elem->GetText ();
        
        // Link
        data = node->FirstChild("link");
        if (!data) return false;
        elem = data->ToElement ();
        if (!elem) return false;
        attr = elem->Attribute ("href");
        if (!attr) return false;
        strLink = std::string ( attr );

        // First entry will always be the newest
        if (newestId == -1) {
            newestId = currentId;
            // If this is our first run, store the newest entry id
            if ( m_lastGoogleCodeId.find(conf.alias) == m_lastGoogleCodeId.end() )
                m_lastGoogleCodeId[conf.alias] = newestId;
        }

        // If this entry is newer than the last stored id
        if (currentId > m_lastGoogleCodeId[conf.alias])
        {   // This is a new entry
            SendTextToChannels(
                IRCText(
                    "[%U%s%U] %C02%Br%d%B%C %C12(%s)%C %C10%s%C %C03-%C "
                    "%C14%s%C",
                    conf.alias, currentId, strAuthor.c_str (), strDescription.c_str (),
                    strLink.c_str ()
                )
            );
            if ( conf.autofix )
              CheckForAutofixIssue ( strAuthor, strDescription, strLink );
        }
        // Advance to next sibling
        node = node->NextSiblingElement ();
    }
    m_lastGoogleCodeId[conf.alias] = newestId;
    
    return true;
}
Example #23
0
bool CSettings::LoadSettings(const CStdString& strSettingsFile)
{
    // load the xml file
    CXBMCTinyXML xmlDoc;

    if (!xmlDoc.LoadFile(strSettingsFile))
    {
        CLog::Log(LOGERROR, "%s, Line %d\n%s", strSettingsFile.c_str(), xmlDoc.ErrorRow(), xmlDoc.ErrorDesc());
        return false;
    }

    TiXmlElement *pRootElement = xmlDoc.RootElement();
    if (strcmpi(pRootElement->Value(), "settings") != 0)
    {
        CLog::Log(LOGERROR, "%s\nDoesn't contain <settings>", strSettingsFile.c_str());
        return false;
    }

    // mymusic settings
    TiXmlElement *pElement = pRootElement->FirstChildElement("mymusic");
    if (pElement)
    {
        TiXmlElement *pChild = pElement->FirstChildElement("playlist");
        if (pChild)
        {
            XMLUtils::GetBoolean(pChild, "repeat", m_bMyMusicPlaylistRepeat);
            XMLUtils::GetBoolean(pChild, "shuffle", m_bMyMusicPlaylistShuffle);
        }
        GetInteger(pElement, "startwindow", m_iMyMusicStartWindow, WINDOW_MUSIC_FILES, WINDOW_MUSIC_FILES, WINDOW_MUSIC_NAV); //501; view songs
        XMLUtils::GetBoolean(pElement, "songinfoinvis", m_bMyMusicSongInfoInVis);
        XMLUtils::GetBoolean(pElement, "songthumbinvis", m_bMyMusicSongThumbInVis);
        GetInteger(pElement, "needsupdate", m_musicNeedsUpdate, 0, 0, INT_MAX);
        GetPath(pElement, "defaultlibview", m_defaultMusicLibSource);
    }

    // myvideos settings
    pElement = pRootElement->FirstChildElement("myvideos");
    if (pElement)
    {
        GetInteger(pElement, "startwindow", m_iVideoStartWindow, WINDOW_VIDEO_FILES, WINDOW_VIDEO_FILES, WINDOW_VIDEO_NAV);
        XMLUtils::GetBoolean(pElement, "stackvideos", m_videoStacking);
        XMLUtils::GetBoolean(pElement, "flatten", m_bMyVideoNavFlatten);
        GetInteger(pElement, "needsupdate", m_videoNeedsUpdate, 0, 0, INT_MAX);

        TiXmlElement *pChild = pElement->FirstChildElement("playlist");
        if (pChild)
        {   // playlist
            XMLUtils::GetBoolean(pChild, "repeat", m_bMyVideoPlaylistRepeat);
            XMLUtils::GetBoolean(pChild, "shuffle", m_bMyVideoPlaylistShuffle);
        }
    }

    // general settings
    pElement = pRootElement->FirstChildElement("general");
    if (pElement)
    {
        GetInteger(pElement, "systemtotaluptime", m_iSystemTimeTotalUp, 0, 0, INT_MAX);
        XMLUtils::GetBoolean(pElement, "addonautoupdate", m_bAddonAutoUpdate);
        XMLUtils::GetBoolean(pElement, "addonnotifications", m_bAddonNotifications);
        XMLUtils::GetBoolean(pElement, "addonforeignfilter", m_bAddonForeignFilter);
    }

    // audio settings
    pElement = pRootElement->FirstChildElement("audio");
    if (pElement)
    {
        XMLUtils::GetBoolean(pElement, "mute", m_bMute);
        GetFloat(pElement, "fvolumelevel", m_fVolumeLevel, VOLUME_MAXIMUM, VOLUME_MINIMUM, VOLUME_MAXIMUM);
    }

    LoadCalibration(pRootElement, strSettingsFile);
    g_guiSettings.LoadXML(pRootElement);

    // load any ISubSettings implementations
    return Load(pRootElement);
}
Example #24
0
void IPXMenic::getIPXFilteringParams()
{
	TiXmlElement *element;

	element = filter_params->FirstChildElement("local_mac_address");
	if (element != NULL)
		SrcMAC = element->GetText();

	element = filter_params->FirstChildElement("remote_mac_address");
	if (element != NULL)
		DstMAC = element->GetText();

	element = filter_params->FirstChildElement("transport_control");
	if (element != NULL)
		transControl = element->GetText();

	element = filter_params->FirstChildElement("protocol_type");
	if (element != NULL)
		type = element->GetText();

	element = filter_params->FirstChildElement("remote_net_address");
	if (element != NULL)
		DstNetwork = element->GetText();

	element = filter_params->FirstChildElement("remote_mac_address");
	if (element != NULL)
		DstNode = element->GetText();

	element = filter_params->FirstChildElement("remote_socket_address");
	if (element != NULL)
		DstSocket = element->GetText();
	/*********************************************************************/
	element = filter_params->FirstChildElement("local_net_address");
	if (element != NULL)
		SrcNetwork = element->GetText();

	element = filter_params->FirstChildElement("local_mac_address");
	if (element != NULL)
		SrcNode = element->GetText();

	element = filter_params->FirstChildElement("local_socket_address");
	if (element != NULL)
		SrcSocket = element->GetText();

	


}
Example #25
0
BOOL GDocsAPITest::CopyConstructorTest()
{
	login();
	
		GDocsEntry* ppp ;

	TiXmlDocument * pXmlDoc = new TiXmlDocument();

	m_pGDocsApi->GetEntryList("https://docs.google.com/feeds/default/private/full/", pXmlDoc);

	TiXmlElement* pFeedElement = pXmlDoc->FirstChildElement("feed");

	TiXmlElement* pElement = pFeedElement->FirstChildElement("entry");


//		pElement = pElement->NextSiblingElement("entry");


		GDocsEntry*  docsEntry= new GDocsEntry(pElement);

		{
   	
		GDocsEntry*  copyEntry = new GDocsEntry(*docsEntry);



		ppp= copyEntry;

		if ( wcscmp(copyEntry->m_pszGDEtag,  docsEntry->m_pszGDEtag) != 0)
		{
			cout<< "Wrong!!!!!!"<<endl;
		}

		if (wcscmp(copyEntry->m_pszIDUrl, docsEntry->m_pszIDUrl) != 0)
		{
			cout<< "Wrong!!!!!!"<<endl;
		}

		if (wcscmp(copyEntry->m_pszPublished, docsEntry->m_pszPublished) != 0)
		{
			cout<< "Wrong!!!!!!"<<endl;
		}

		if (wcscmp(copyEntry->m_pszUpdated, docsEntry->m_pszUpdated) != 0)
		{
			cout<< "Wrong!!!!!!"<<endl;
		}


		if (wcscmp(copyEntry->m_pszAppEdited, docsEntry->m_pszAppEdited) != 0)
		{
			cout<< "Wrong!!!!!!"<<endl;
		}

		if (copyEntry->m_bIsStarred != docsEntry->m_bIsStarred)
		{
			cout<< "Wrong!!!!!!"<<endl;
		}

		if (copyEntry->m_bIsHidden != docsEntry->m_bIsHidden)
		{
			cout<< "Wrong!!!!!!"<<endl;
		}

		if (copyEntry->m_bIsViewed != docsEntry->m_bIsViewed)
		{
			cout<< "Wrong!!!!!!"<<endl;
		}

		if (wcscmp(copyEntry->m_pszTitle, docsEntry->m_pszTitle) != 0)
		{
			cout<< "Wrong!!!!!!"<<endl;
		}

		if (wcscmp(copyEntry->m_pszContentType, docsEntry->m_pszContentType) != 0)
		{
			cout<< "Wrong!!!!!!"<<endl;
		}

		if (wcscmp(copyEntry->m_pszContentSrc, docsEntry->m_pszContentSrc) != 0)
		{
			cout<< "Wrong!!!!!!"<<endl;
		}

		if (copyEntry->m_vecParents.size() != docsEntry->m_vecParents.size() )
		{
			cout<< "Wrong!!!!!!"<<endl;
		}

		vector<LinkParent>::const_iterator  iter1 	= docsEntry->m_vecParents.begin();

		for (vector<LinkParent>::const_iterator  iter2 = copyEntry->m_vecParents.begin(); iter2 != copyEntry->m_vecParents.end(); iter2++)
		{

			if (wcscmp(iter1->lpszParentHref, iter2->lpszParentHref) != 0)
				cout<< "Wrong!!!!!!"<<endl;

			if (wcscmp(iter1->lpszParentTitle, iter2->lpszParentTitle) != 0)
				cout<< "Wrong!!!!!!"<<endl;

			iter1++;
		}


		if (wcscmp(copyEntry->m_pszLinkAlternate, docsEntry->m_pszLinkAlternate) != 0)
		{
			cout<< "Wrong!!!!!!"<<endl;
		}

		if (wcscmp(copyEntry->m_pszLinkSelf, docsEntry->m_pszLinkSelf) != 0)
		{
			cout<< "Wrong!!!!!!"<<endl;
		}

		if (wcscmp(copyEntry->m_pszLinkEdit, docsEntry->m_pszLinkEdit) != 0)
		{
			cout<< "Wrong!!!!!!"<<endl;
		}


		if (wcscmp(copyEntry->m_pszLinkResumableEditMedia, docsEntry->m_pszLinkResumableEditMedia) != 0)
		{
			cout<< "Wrong!!!!!!"<<endl;
		}


		if (docsEntry->m_pszLinkThumbNail)
		{
			if (wcscmp(copyEntry->m_pszLinkThumbNail, docsEntry->m_pszLinkThumbNail) != 0)
			{
				cout<< "Wrong!!!!!!"<<endl;
			}
		}

		if (wcscmp(copyEntry->m_pszAuthorName, docsEntry->m_pszAuthorName) != 0)
		{
			cout<< "Wrong!!!!!!"<<endl;
		}


		if (wcscmp(copyEntry->m_pszAuthorEmail, docsEntry->m_pszAuthorEmail) != 0)
		{
			cout<< "Wrong!!!!!!"<<endl;
		}


		if (wcscmp(copyEntry->m_pszResourceId, docsEntry->m_pszResourceId) != 0)
		{
			cout<< "Wrong!!!!!!"<<endl;
		}





		if (wcscmp(copyEntry->m_pszType, docsEntry->m_pszType) != 0)
		{
			cout<< "Wrong!!!!!!"<<endl;
		}



		if (wcscmp(copyEntry->m_pszID, docsEntry->m_pszID) != 0)
		{
			cout<< "Wrong!!!!!!"<<endl;
		}



		if (wcscmp(copyEntry->m_pszLastModifiedByName, docsEntry->m_pszLastModifiedByName) != 0)
		{
			cout<< "Wrong!!!!!!"<<endl;
		}



		if (wcscmp(copyEntry->m_pszLastModifiedByEmail, docsEntry->m_pszLastModifiedByEmail) != 0)
		{
			cout<< "Wrong!!!!!!"<<endl;
		}

		if (wcscmp(copyEntry->m_pszQuotaBytesUsed, docsEntry->m_pszQuotaBytesUsed) != 0)
		{
			cout<< "Wrong!!!!!!"<<endl;
		}

		if (wcscmp(copyEntry->m_pszQuotaBytesUsedFormated, docsEntry->m_pszQuotaBytesUsedFormated) != 0)
		{
			cout<< "Wrong!!!!!!"<<endl;
		}


		if ( copyEntry->m_bIsWritersCanInvite != docsEntry->m_bIsWritersCanInvite)
		{
			cout<< "Wrong!!!!!!"<<endl;
		}

		if (wcscmp(copyEntry->m_pszFeedLinkACL, docsEntry->m_pszFeedLinkACL) != 0)
		{
			cout<< "Wrong!!!!!!"<<endl;
		}

		if (wcscmp(copyEntry->m_pszFeedLinkRevisions, docsEntry->m_pszFeedLinkRevisions) != 0)
		{
			cout<< "Wrong!!!!!!"<<endl;
		}

		cout<<"done"<<endl;


		if (docsEntry->m_pszMD5Checksum)
		{
			if (wcscmp(copyEntry->m_pszMD5Checksum, docsEntry->m_pszMD5Checksum) != 0)
			{
				cout<< "Wrong!!!!!!"<<endl;
			}
		}

		delete docsEntry;

	
	}

	/*pElement = pElement->NextSiblingElement("entry");

	docsEntry(pElement);
*/

int i=0;



return TRUE;

}
Example #26
0
void KeyboardShortcuts::importFile(TiXmlElement* rootElement, KeySource source)
{
  // <keyboard><commands><key>
  TiXmlHandle handle(rootElement);
  TiXmlElement* xmlKey = handle
    .FirstChild("commands")
    .FirstChild("key").ToElement();
  while (xmlKey) {
    const char* command_name = xmlKey->Attribute("command");
    const char* command_key = get_shortcut(xmlKey);
    bool removed = bool_attr_is_true(xmlKey, "removed");

    if (command_name) {
      Command* command = CommandsModule::instance()->getCommandByName(command_name);
      if (command) {
        // Read context
        KeyContext keycontext = KeyContext::Any;
        const char* keycontextstr = xmlKey->Attribute("context");
        if (keycontextstr) {
          if (strcmp(keycontextstr, "Selection") == 0)
            keycontext = KeyContext::SelectionTool;
          else if (strcmp(keycontextstr, "Normal") == 0)
            keycontext = KeyContext::Normal;
        }

        // Read params
        Params params;

        TiXmlElement* xmlParam = xmlKey->FirstChildElement("param");
        while (xmlParam) {
          const char* param_name = xmlParam->Attribute("name");
          const char* param_value = xmlParam->Attribute("value");

          if (param_name && param_value)
            params.set(param_name, param_value);

          xmlParam = xmlParam->NextSiblingElement();
        }

        // add the keyboard shortcut to the command
        Key* key = this->command(command_name, params, keycontext);
        if (key && command_key) {
          Accelerator accel(command_key);

          if (!removed) {
            key->add(accel, source);

            // Add the shortcut to the menuitems with this command
            // (this is only visual, the
            // "CustomizedGuiManager::onProcessMessage" is the only
            // one that process keyboard shortcuts)
            if (key->accels().size() == 1) {
              AppMenus::instance()->applyShortcutToMenuitemsWithCommand(
                command, params, key);
            }
          }
          else
            key->disableAccel(accel);
        }
      }
    }

    xmlKey = xmlKey->NextSiblingElement();
  }

  // Load keyboard shortcuts for tools
  // <gui><keyboard><tools><key>
  xmlKey = handle
    .FirstChild("tools")
    .FirstChild("key").ToElement();
  while (xmlKey) {
    const char* tool_id = xmlKey->Attribute("tool");
    const char* tool_key = get_shortcut(xmlKey);
    bool removed = bool_attr_is_true(xmlKey, "removed");

    if (tool_id) {
      tools::Tool* tool = App::instance()->getToolBox()->getToolById(tool_id);
      if (tool) {
        Key* key = this->tool(tool);
        if (key && tool_key) {
          LOG(" - Shortcut for tool `%s': <%s>\n", tool_id, tool_key);
          Accelerator accel(tool_key);

          if (!removed)
            key->add(accel, source);
          else
            key->disableAccel(accel);
        }
      }
    }
    xmlKey = xmlKey->NextSiblingElement();
  }

  // Load keyboard shortcuts for quicktools
  // <gui><keyboard><quicktools><key>
  xmlKey = handle
    .FirstChild("quicktools")
    .FirstChild("key").ToElement();
  while (xmlKey) {
    const char* tool_id = xmlKey->Attribute("tool");
    const char* tool_key = get_shortcut(xmlKey);
    bool removed = bool_attr_is_true(xmlKey, "removed");

    if (tool_id) {
      tools::Tool* tool = App::instance()->getToolBox()->getToolById(tool_id);
      if (tool) {
        Key* key = this->quicktool(tool);
        if (key && tool_key) {
          LOG(" - Shortcut for quicktool `%s': <%s>\n", tool_id, tool_key);
          Accelerator accel(tool_key);

          if (!removed)
            key->add(accel, source);
          else
            key->disableAccel(accel);
        }
      }
    }
    xmlKey = xmlKey->NextSiblingElement();
  }

  // Load special keyboard shortcuts for sprite editor customization
  // <gui><keyboard><spriteeditor>
  xmlKey = handle
    .FirstChild("actions")
    .FirstChild("key").ToElement();
  while (xmlKey) {
    const char* tool_action = xmlKey->Attribute("action");
    const char* tool_key = get_shortcut(xmlKey);
    bool removed = bool_attr_is_true(xmlKey, "removed");

    if (tool_action) {
      KeyAction action = base::convert_to<KeyAction, std::string>(tool_action);
      if (action != KeyAction::None) {
        Key* key = this->action(action);
        if (key && tool_key) {
          LOG(" - Shortcut for action '%s': <%s>\n", tool_action, tool_key);
          Accelerator accel(tool_key);

          if (!removed)
            key->add(accel, source);
          else
            key->disableAccel(accel);
        }
      }
    }
    xmlKey = xmlKey->NextSiblingElement();
  }
}
Example #27
0
void OnlineSearchState::doSearchServers()
{
	// Get the serverlist
	try
	{
		BlobNet::Layer::Http http("blobby.sourceforge.net", 80);

		std::stringstream serverListXml;
		http.request("server.php", serverListXml);

		// this trows an exception if the file could not be opened for writing
		FileWrite file("onlineserver.xml");

		file.write(serverListXml.str());

		file.close();
	} catch (std::exception& e) {
		std::cout << "Can't get onlineserver.xml: " << e.what() << std::endl;
	} catch (...) {
		std::cout << "Can't get onlineserver.xml. Unknown error." << std::endl;
	}

	std::vector< std::pair<std::string, int> > serverList;

	// Get the serverlist
	try {
		boost::shared_ptr<TiXmlDocument> serverListXml = FileRead::readXMLDocument("onlineserver.xml");

		if (serverListXml->Error())
		{
			std::cerr << "Warning: Parse error in " << "onlineserver.xml";
			std::cerr << "!" << std::endl;
		}

		TiXmlElement* onlineserverElem = serverListXml->FirstChildElement("onlineserver");

		if (onlineserverElem == NULL)
		{
			std::cout << "Can't read onlineserver.xml" << std::endl;
			return;
		}

		for (TiXmlElement* serverElem = onlineserverElem->FirstChildElement("server");
		     serverElem != NULL;
		     serverElem = serverElem->NextSiblingElement("server"))
		{
			std::string host;
			int port;
			for (TiXmlElement* varElem = serverElem->FirstChildElement("var");
			     varElem != NULL;
			     varElem = varElem->NextSiblingElement("var"))
			{
				const char* tmp;
				tmp = varElem->Attribute("host");
				if(tmp)
				{
					host = tmp;
					continue;
				}

				tmp = varElem->Attribute("port");
				if(tmp)
				{
					try
					{
						port = boost::lexical_cast<int>(tmp);
					}
					catch (boost::bad_lexical_cast)
					{
						port = BLOBBY_PORT;
					}
					if ((port <= 0) || (port > 65535))
					{
						port = BLOBBY_PORT;
					}
					continue;
				}
			}
			std::pair<std::string, int> pairs(host, port);
			serverList.push_back(pairs);
		}
	} catch (...) {
		std::cout << "Can't read onlineserver.xml" << std::endl;
	}

	/// \todo check if we already try to connect to this one!
	std::string address = IUserConfigReader::createUserConfigReader("config.xml")->getString("additional_network_server");
	std::string server = address;
	int port = BLOBBY_PORT;
	std::size_t found = address.find(':');
	if (found != std::string::npos)
	{
		server = address.substr(0, found);

		try
		{
			port = boost::lexical_cast<int>(address.substr(found+1));
		}
		 catch (boost::bad_lexical_cast)
		{
			/// \todo inform the user that default port was selected
		}
		if ((port <= 0) || (port > 65535))
			port = BLOBBY_PORT;
	}

	std::pair<std::string, int> pairs(server.c_str(), port);
	serverList.push_back(pairs);

	mScannedServers.clear();
	mPingClient->Initialize( serverList.size() + 2, 0, 10 );

	for( auto& server : serverList )
	{
		// if we receive the cancel signal from the main thread, we leave as soon as possible
		if(mCancelPing)
			break;

		std::cout << "ping" << server.first << "\n";
		mPingClient->Ping(server.first.c_str(), server.second, true);
	}
}
Example #28
0
void KeyboardShortcuts::exportAccel(TiXmlElement& parent, Key* key, const ui::Accelerator& accel, bool removed)
{
  TiXmlElement elem("key");

  switch (key->type()) {

    case KeyType::Command: {
      const char* keycontextStr = NULL;

      elem.SetAttribute("command", key->command()->id().c_str());

      switch (key->keycontext()) {
        case KeyContext::Any:
          // Without "context" attribute
          break;
        case KeyContext::Normal:
          keycontextStr = "Normal";
          break;
        case KeyContext::SelectionTool:
          keycontextStr = "Selection";
          break;
        case KeyContext::TranslatingSelection:
          keycontextStr = "TranslatingSelection";
          break;
        case KeyContext::ScalingSelection:
          keycontextStr = "ScalingSelection";
          break;
        case KeyContext::RotatingSelection:
          keycontextStr = "RotatingSelection";
          break;
        case KeyContext::MoveTool:
          keycontextStr = "MoveTool";
          break;
        case KeyContext::FreehandTool:
          keycontextStr = "FreehandTool";
          break;
        case KeyContext::ShapeTool:
          keycontextStr = "ShapeTool";
          break;
      }

      if (keycontextStr)
        elem.SetAttribute("context", keycontextStr);

      for (const auto& param : key->params()) {
        if (param.second.empty())
          continue;

        TiXmlElement paramElem("param");
        paramElem.SetAttribute("name", param.first.c_str());
        paramElem.SetAttribute("value", param.second.c_str());
        elem.InsertEndChild(paramElem);
      }
      break;
    }

    case KeyType::Tool:
    case KeyType::Quicktool:
      elem.SetAttribute("tool", key->tool()->getId().c_str());
      break;

    case KeyType::Action:
      elem.SetAttribute("action",
        base::convert_to<std::string>(key->action()).c_str());
      break;
  }

  elem.SetAttribute("shortcut", accel.toString().c_str());

  if (removed)
    elem.SetAttribute("removed", "true");

  parent.InsertEndChild(elem);
}
PayoffBase::PayoffBase(TiXmlNode* xmlNode)
: ISerialized(xmlNode)
{
    #ifdef ConsolePrint
        std::string initialtap_ = FileManager::instance().tap_;
        FileManager::instance().tap_.append("   ");
    #endif 
   //payoffDateNode ----------------------------------------------------------------------------------------------------------------------
   TiXmlElement* payoffDateNode = xmlNode->FirstChildElement("payoffDate");

   if(payoffDateNode){payoffDateIsNull_ = false;}
   else{payoffDateIsNull_ = true;}

   #ifdef ConsolePrint
      FileManager::instance().outFile_ << FileManager::instance().tap_.c_str() << "- payoffDateNode , address : " << payoffDateNode << std::endl;
   #endif
   if(payoffDateNode)
   {
      if(payoffDateNode->Attribute("href") || payoffDateNode->Attribute("id"))
      {
          if(payoffDateNode->Attribute("id"))
          {
             payoffDateIDRef_ = payoffDateNode->Attribute("id");
             payoffDate_ = boost::shared_ptr<XsdTypeToken>(new XsdTypeToken(payoffDateNode));
             payoffDate_->setID(payoffDateIDRef_);
             IDManager::instance().setID(payoffDateIDRef_,payoffDate_);
          }
          else if(payoffDateNode->Attribute("href")) { payoffDateIDRef_ = payoffDateNode->Attribute("href");}
          else { QL_FAIL("id or href error"); }
      }
      else { payoffDate_ = boost::shared_ptr<XsdTypeToken>(new XsdTypeToken(payoffDateNode));}
   }

   //constPayoffNode ----------------------------------------------------------------------------------------------------------------------
   TiXmlElement* constPayoffNode = xmlNode->FirstChildElement("constPayoff");

   if(constPayoffNode){constPayoffIsNull_ = false;}
   else{constPayoffIsNull_ = true;}

   #ifdef ConsolePrint
      FileManager::instance().outFile_ << FileManager::instance().tap_.c_str() << "- constPayoffNode , address : " << constPayoffNode << std::endl;
   #endif
   if(constPayoffNode)
   {
      if(constPayoffNode->Attribute("href") || constPayoffNode->Attribute("id"))
      {
          if(constPayoffNode->Attribute("id"))
          {
             constPayoffIDRef_ = constPayoffNode->Attribute("id");
             constPayoff_ = boost::shared_ptr<ConstPayoff>(new ConstPayoff(constPayoffNode));
             constPayoff_->setID(constPayoffIDRef_);
             IDManager::instance().setID(constPayoffIDRef_,constPayoff_);
          }
          else if(constPayoffNode->Attribute("href")) { constPayoffIDRef_ = constPayoffNode->Attribute("href");}
          else { QL_FAIL("id or href error"); }
      }
      else { constPayoff_ = boost::shared_ptr<ConstPayoff>(new ConstPayoff(constPayoffNode));}
   }

   //nullPayoffNode ----------------------------------------------------------------------------------------------------------------------
   TiXmlElement* nullPayoffNode = xmlNode->FirstChildElement("nullPayoff");

   if(nullPayoffNode){nullPayoffIsNull_ = false;}
   else{nullPayoffIsNull_ = true;}

   #ifdef ConsolePrint
      FileManager::instance().outFile_ << FileManager::instance().tap_.c_str() << "- nullPayoffNode , address : " << nullPayoffNode << std::endl;
   #endif
   if(nullPayoffNode)
   {
      if(nullPayoffNode->Attribute("href") || nullPayoffNode->Attribute("id"))
      {
          if(nullPayoffNode->Attribute("id"))
          {
             nullPayoffIDRef_ = nullPayoffNode->Attribute("id");
             nullPayoff_ = boost::shared_ptr<NullPayoff>(new NullPayoff(nullPayoffNode));
             nullPayoff_->setID(nullPayoffIDRef_);
             IDManager::instance().setID(nullPayoffIDRef_,nullPayoff_);
          }
          else if(nullPayoffNode->Attribute("href")) { nullPayoffIDRef_ = nullPayoffNode->Attribute("href");}
          else { QL_FAIL("id or href error"); }
      }
      else { nullPayoff_ = boost::shared_ptr<NullPayoff>(new NullPayoff(nullPayoffNode));}
   }

   //averPayoffNode ----------------------------------------------------------------------------------------------------------------------
   TiXmlElement* averPayoffNode = xmlNode->FirstChildElement("averPayoff");

   if(averPayoffNode){averPayoffIsNull_ = false;}
   else{averPayoffIsNull_ = true;}

   #ifdef ConsolePrint
      FileManager::instance().outFile_ << FileManager::instance().tap_.c_str() << "- averPayoffNode , address : " << averPayoffNode << std::endl;
   #endif
   if(averPayoffNode)
   {
      if(averPayoffNode->Attribute("href") || averPayoffNode->Attribute("id"))
      {
          if(averPayoffNode->Attribute("id"))
          {
             averPayoffIDRef_ = averPayoffNode->Attribute("id");
             averPayoff_ = boost::shared_ptr<AverPayoff>(new AverPayoff(averPayoffNode));
             averPayoff_->setID(averPayoffIDRef_);
             IDManager::instance().setID(averPayoffIDRef_,averPayoff_);
          }
          else if(averPayoffNode->Attribute("href")) { averPayoffIDRef_ = averPayoffNode->Attribute("href");}
          else { QL_FAIL("id or href error"); }
      }
      else { averPayoff_ = boost::shared_ptr<AverPayoff>(new AverPayoff(averPayoffNode));}
   }

   //exprPayoffNode ----------------------------------------------------------------------------------------------------------------------
   TiXmlElement* exprPayoffNode = xmlNode->FirstChildElement("exprPayoff");

   if(exprPayoffNode){exprPayoffIsNull_ = false;}
   else{exprPayoffIsNull_ = true;}

   #ifdef ConsolePrint
      FileManager::instance().outFile_ << FileManager::instance().tap_.c_str() << "- exprPayoffNode , address : " << exprPayoffNode << std::endl;
   #endif
   if(exprPayoffNode)
   {
      if(exprPayoffNode->Attribute("href") || exprPayoffNode->Attribute("id"))
      {
          if(exprPayoffNode->Attribute("id"))
          {
             exprPayoffIDRef_ = exprPayoffNode->Attribute("id");
             exprPayoff_ = boost::shared_ptr<ExprPayoff>(new ExprPayoff(exprPayoffNode));
             exprPayoff_->setID(exprPayoffIDRef_);
             IDManager::instance().setID(exprPayoffIDRef_,exprPayoff_);
          }
          else if(exprPayoffNode->Attribute("href")) { exprPayoffIDRef_ = exprPayoffNode->Attribute("href");}
          else { QL_FAIL("id or href error"); }
      }
      else { exprPayoff_ = boost::shared_ptr<ExprPayoff>(new ExprPayoff(exprPayoffNode));}
   }

   //preFixPayoffNode ----------------------------------------------------------------------------------------------------------------------
   TiXmlElement* preFixPayoffNode = xmlNode->FirstChildElement("preFixPayoff");

   if(preFixPayoffNode){preFixPayoffIsNull_ = false;}
   else{preFixPayoffIsNull_ = true;}

   #ifdef ConsolePrint
      FileManager::instance().outFile_ << FileManager::instance().tap_.c_str() << "- preFixPayoffNode , address : " << preFixPayoffNode << std::endl;
   #endif
   if(preFixPayoffNode)
   {
      if(preFixPayoffNode->Attribute("href") || preFixPayoffNode->Attribute("id"))
      {
          if(preFixPayoffNode->Attribute("id"))
          {
             preFixPayoffIDRef_ = preFixPayoffNode->Attribute("id");
             preFixPayoff_ = boost::shared_ptr<PreFixPayoff>(new PreFixPayoff(preFixPayoffNode));
             preFixPayoff_->setID(preFixPayoffIDRef_);
             IDManager::instance().setID(preFixPayoffIDRef_,preFixPayoff_);
          }
          else if(preFixPayoffNode->Attribute("href")) { preFixPayoffIDRef_ = preFixPayoffNode->Attribute("href");}
          else { QL_FAIL("id or href error"); }
      }
      else { preFixPayoff_ = boost::shared_ptr<PreFixPayoff>(new PreFixPayoff(preFixPayoffNode));}
   }

    #ifdef ConsolePrint
        FileManager::instance().tap_ = initialtap_;
    #endif 
}
Example #30
0
ReaclibVer::ReaclibVer(TiXmlElement *pElement){
	// set the default values
	m_Q = 0;
	m_pstrModified = NULL;
	m_bCurrent = false;
	m_version = 1;
	m_id = 0;
	
	// keep track of this
	m_pVer = pElement;
	// loop through all the elements children
	for(TiXmlNode *pNode = m_pVer->FirstChild(); pNode; pNode=pNode->NextSibling()){
		// check to see if this is another node
		if(pNode->Type() == TiXmlNode::ELEMENT){
			// convert this to a type
			TiXmlElement *pElement = pNode->ToElement();
			
			// check to see if this is a known type
			if(strcmp(pElement->Value(),"set") ==0){
				// create the new version
				ReaclibSet* newSet = new ReaclibSet(pElement);
				
				// add the version to the listing
				addSet(newSet, true);
			}
		}
	}
	
	// load the attributes
	// the modified date
	const char *pstrValue;
	if((pstrValue = m_pVer->Attribute("modified"))){
		setModified(pstrValue);
	} 
	
	// the id value
	if(m_pVer->Attribute("id")){
		// try to convert the id to the new value
		if(EOF == sscanf(m_pVer->Attribute("id"), "%d", &m_id)){
			cerr << "Unable to convert id " << m_pVer->Attribute("id") << " to an integer." << endl;
			return;
		}
	}
	
	// the version number
	if(m_pVer->Attribute("num")){
		if(EOF == sscanf(m_pVer->Attribute("num"), "%d", &m_version)){
			cerr << "Unable to convert version number " << m_pVer->Attribute("num") << " to an integer." << endl;
		}
	}
	
	// the Q value
	if(m_pVer->Attribute("q")){
		if(EOF == sscanf(m_pVer->Attribute("q"), "%e", &m_Q)){
			cerr << "Unable to convert version Q " << m_pVer->Attribute("q") << " to a float." << endl;
		}
	}
	
	// the current value
	if(m_pVer->Attribute("current")){
		// check to see if this is the current value
		if(strcmp(m_pVer->Attribute("current"), "1") == 0){
			m_bCurrent = true;
		}
	}
		
	return;
}