Esempio n. 1
0
void CSystemCreateStats::AddStationTable (CSystem *pSystem, const CString &sStationCriteria, const CString &sLocationAttribs, TArray<CStationTableCache::SEntry> &Table)

//	AddStationTable
//
//	Adds the station table.

	{
	int i;

	//	See if we already have an entry for this table.
	//	If we don't we add it.

	SEncounterTable *pEntry;
	if (!FindEncounterTable(Table, &pEntry))
		{
		pEntry = m_EncounterTables.Insert();
		pEntry->iLevel = pSystem->GetLevel();
		pEntry->pSystemType = pSystem->GetType();
		pEntry->sStationCriteria = sStationCriteria;
		pEntry->iCount = 1;

		ParseAttributes(sLocationAttribs, &pEntry->LabelAttribs);

		pEntry->bHasStation = false;
		for (i = 0; i < Table.GetCount(); i++)
			{
			pEntry->Table.Insert(Table[i].pType, Table[i].iChance);
			if (Table[i].pType->GetScale() == scaleStructure
					|| Table[i].pType->GetScale() == scaleShip)
				pEntry->bHasStation = true;
			}

		return;
		}

	//	If we already have the table we need to aggregate the entry. We start
	//	by incrementing the count.

	pEntry->iCount++;

	//	Next we remove any location/label attributes that are not common to 
	//	both tables. [We assume that if we have two identical tables then only
	//	the attributes in common count to make the table unique.]

	TArray<CString> NewAttribs;
	ParseAttributes(sLocationAttribs, &NewAttribs);
	for (i = 0; i < pEntry->LabelAttribs.GetCount(); i++)
		{
		if (!NewAttribs.Find(pEntry->LabelAttribs[i]))
			{
			pEntry->LabelAttribs.Delete(i);
			i--;
			}
		}
	}
Esempio n. 2
0
wxSimpleHtmlTag* wxSimpleHtmlParser::ParseTagHeader()
{
    if (IsTagStartBracket(GetChar(m_pos)))
    {
        m_pos ++;
        EatWhitespace();

        wxString word;
        ReadWord(word, TRUE);

        EatWhitespace();

        wxSimpleHtmlTag* tag = new wxSimpleHtmlTag(word, wxSimpleHtmlTag_Open);

        ParseAttributes(tag);

        EatWhitespace();

        if (IsTagEndBracket(GetChar(m_pos)))
            m_pos ++;

        return tag;
    }
    else
        return NULL;
}
Esempio n. 3
0
void CSystemCreateStats::AddLabelExpansion (const CString &sAttributes, const CString &sPrefix)

//	AddLabelExpansion
//
//	Expands and adds the given attributes to the label counter

	{
	int i;

	TArray<CString> Attribs;
	ParseAttributes(sAttributes, &Attribs);

	//	Add each of the attributes alone (and make a list of permutations)

	TArray<CString> Permutable;
	for (i = 0; i < Attribs.GetCount(); i++)
		{
		if (m_PermuteAttribs.Find(Attribs[i]))
			Permutable.Insert(Attribs[i]);
		else
			AddEntry(Attribs[i]);
		}

	//	Now add all permutations

	if (Permutable.GetCount() >= 1)
		AddEntryPermutations(NULL_STR, Permutable, 0);
	}
Esempio n. 4
0
	//
	//	<ele></ele>
	//	<ele>foo<b>bar</b></ele>
	//
	char* XMLElement::ParseDeep( char* p, StrPair* strPair )
	{
		// Read the element name.
		p = XMLUtil::SkipWhiteSpace( p );
		if ( !p ) {
			return 0;
		}

		// The closing element is the </element> form. It is
		// parsed just like a regular element then deleted from
		// the DOM.
		if ( *p == '/' ) {
			_closingType = CLOSING;
			++p;
		}

		p = _value.ParseName( p );
		if ( _value.Empty() ) {
			return 0;
		}

		p = ParseAttributes( p );
		if ( !p || !*p || _closingType ) {
			return p;
		}

		p = XMLNode::ParseDeep( p, strPair );
		return p;
	}
Esempio n. 5
0
bool LinkPartition::ParsePartitionSpec(LinkManager *manager, CmdFiles &files, LinkTokenizer &spec)
{
    if (!ParseOverlays(manager, files, spec))
        return false;
    if (!ParseName(spec))
        return false;
    return ParseAttributes(spec);
}
HRESULT MaterialDatabaseReader::ElementBegin( const WCHAR* strName, UINT NameLen, const XMLAttribute *pAttributes, UINT NumAttributes )
{
    ProcessElementBeginContent();

    CopyString( strName, NameLen, m_strCurrentElementName, ARRAYSIZE(m_strCurrentElementName) );
    m_bCurrentElementEndTag = false;

    ParseAttributes( pAttributes, NumAttributes );

    return S_OK;
}
Esempio n. 7
0
void OutputByAttribute (SItemTableCtx &Ctx, const SItemTypeList &ItemList)
	{
	int i, j;

	//	Make a categorized list by attribute

	SByAttributeTypeList ByAttributeTable;
	for (i = 0; i < ItemList.GetCount(); i++)
		{
		const CString &sKey = ItemList.GetKey(i);
		CItemType *pType = ItemList[i];

		//	Loop over all attributes

		TArray<CString> Attribs;
		ParseAttributes(pType->GetAttributes(), &Attribs);
		for (j = 0; j < Attribs.GetCount(); j++)
			{
			bool bNew;
			SAttributeEntry *pEntry = ByAttributeTable.SetAt(Attribs[j], &bNew);
			if (bNew)
				pEntry->sAttribute = Attribs[j];

			pEntry->ItemTable.Insert(sKey, pType);
			}

		//	If no attribute

		if (Attribs.GetCount() == 0)
			{
			bool bNew;
			SAttributeEntry *pEntry = ByAttributeTable.SetAt(CONSTLIT("(none)"), &bNew);
			if (bNew)
				pEntry->sAttribute = CONSTLIT("(none)");

			pEntry->ItemTable.Insert(sKey, pType);
			}
		}

	//	Now loop over all attributes

	for (i = 0; i < ByAttributeTable.GetCount(); i++)
		{
		const SAttributeEntry &Entry = ByAttributeTable[i];
		printf("%s\n\n", Entry.sAttribute.GetASCIIZPointer());

		OutputHeader(Ctx);
		OutputTable(Ctx, Entry.ItemTable);
		printf("\n");
		}
	}
Esempio n. 8
0
void ASTConsumer::AddDecl(clang::NamedDecl* decl, const std::string& parent_name, const clang::ASTRecordLayout* layout)
{
	// Skip decls with errors and those marked by the Reflection Spec pass to ignore
	if (decl->isInvalidDecl())
		return;

	// Gather all attributes associated with this primitive
	std::string name = decl->getQualifiedNameAsString(*m_PrintingPolicy);
	ParseAttributesResult result = ParseAttributes(*this, decl, name, m_AllowReflect);

	// Return immediately if 'noreflect' is specified, ignoring all children
	if (result == PAR_NoReflect)
		return;

	// If 'reflect' is specified, backup the allow reflect state and set it to true for this
	// declaration and all of its children.
	int old_allow_reflect = -1;
	if (result == PAR_Reflect)
	{
		old_allow_reflect = m_AllowReflect;
		m_AllowReflect = true;
	}

	// Reflect only if the allow reflect state has been inherited or the 'reflect_part'
	// attribute is specified
	if (m_AllowReflect || result == PAR_ReflectPartial)
	{
		clang::Decl::Kind kind = decl->getKind();
		switch (kind)
		{
		case (clang::Decl::Namespace): AddNamespaceDecl(decl, name, parent_name); break;
		case (clang::Decl::CXXRecord): AddClassDecl(decl, name, parent_name); break;
		case (clang::Decl::Enum): AddEnumDecl(decl, name, parent_name); break;
		case (clang::Decl::Function): AddFunctionDecl(decl, name, parent_name); break;
		case (clang::Decl::CXXMethod): AddMethodDecl(decl, name, parent_name); break;
		case (clang::Decl::Field): AddFieldDecl(decl, name, parent_name, layout); break;
		case (clang::Decl::ClassTemplate): AddClassTemplateDecl(decl, name, parent_name); break;
		default: break;
		}
	}

	// Restore any previously changed allow reflect state
	if (old_allow_reflect != -1)
		m_AllowReflect = old_allow_reflect != 0;

	// if m_ReflectPrimitives was changed, restore it
}
Esempio n. 9
0
// e.g. <!DOCTYPE ....>
wxSimpleHtmlTag* wxSimpleHtmlParser::ParseDirective()
{
    Matches(wxT("<!"), TRUE);

    EatWhitespace();

    wxString word;
    ReadWord(word, TRUE);

    EatWhitespace();

    wxSimpleHtmlTag* tag = new wxSimpleHtmlTag(word, wxSimpleHtmlTag_Directive);

    ParseAttributes(tag);

    EatWhitespace();

    if (IsTagEndBracket(GetChar(m_pos)))
        m_pos ++;

    return tag;
}
Esempio n. 10
0
// parse xml tag information i.e. extract tag name and attributes
// until closing '>'. We've already consumed opening '<' in the caller.
static bool ParseTag(char *& s, XmlTagInfo& tagInfo)
{
    tagInfo.type = TAG_OPEN;
    if (*s == '/') { // '</foo>
        ++s;
        tagInfo.type = TAG_CLOSE;
    }
    tagInfo.name = s;
    SkipIdentifier(s);
    if (!*s)
        return false;
    char *e = FindTagClose(s);
    if (!e)
        return false;
    *e = 0;
    char *tmp = s;
    s = e + 1;
    if (e[-1] == '/') { // <foo/>
        if (tagInfo.type != TAG_OPEN) // but not </foo/>
            return false;
        tagInfo.type = TAG_OPEN_CLOSE;
        e[-1] = 0;
    }
    if (NULL != tagInfo.attributes) {
        delete tagInfo.attributes;
        return false;
    }

    bool ok = ParseAttributes(tmp, &tagInfo);
    *tmp = 0;
    if (ok && (TAG_CLOSE == tagInfo.type) && tagInfo.attributes) {
        delete tagInfo.attributes;
        return false;
    }
    return ok;
}
Esempio n. 11
0
/*--------
 *	ConfigDSN
 *
 *	Description:	ODBC Setup entry point
 *				This entry point is called by the ODBC Installer
 *				(see file header for more details)
 *	Input	 :	hwnd ----------- Parent window handle
 *				fRequest ------- Request type (i.e., add, config, or remove)
 *				lpszDriver ----- Driver name
 *				lpszAttributes - data source attribute string
 *	Output	 :	TRUE success, FALSE otherwise
 *--------
 */
BOOL		CALLBACK
ConfigDSN(HWND hwnd,
		  WORD fRequest,
		  LPCSTR lpszDriver,
		  LPCSTR lpszAttributes)
{
	BOOL		fSuccess;		/* Success/fail flag */
	GLOBALHANDLE hglbAttr;
	LPSETUPDLG	lpsetupdlg;


	/* Allocate attribute array */
	hglbAttr = GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT, sizeof(SETUPDLG));
	if (!hglbAttr)
		return FALSE;
	lpsetupdlg = (LPSETUPDLG) GlobalLock(hglbAttr);
	/* Parse attribute string */
	if (lpszAttributes)
		ParseAttributes(lpszAttributes, lpsetupdlg);

	/* Save original data source name */
	if (lpsetupdlg->ci.dsn[0])
		lstrcpy(lpsetupdlg->szDSN, lpsetupdlg->ci.dsn);
	else
		lpsetupdlg->szDSN[0] = '\0';

	/* Remove data source */
	if (ODBC_REMOVE_DSN == fRequest)
	{
		/* Fail if no data source name was supplied */
		if (!lpsetupdlg->ci.dsn[0])
			fSuccess = FALSE;

		/* Otherwise remove data source from ODBC.INI */
		else
			fSuccess = SQLRemoveDSNFromIni(lpsetupdlg->ci.dsn);
	}
	/* Add or Configure data source */
	else
	{
		/* Save passed variables for global access (e.g., dialog access) */
		lpsetupdlg->hwndParent = hwnd;
		lpsetupdlg->lpszDrvr = lpszDriver;
		lpsetupdlg->fNewDSN = (ODBC_ADD_DSN == fRequest);
		lpsetupdlg->fDefault = !lstrcmpi(lpsetupdlg->ci.dsn, INI_DSN);

		/*
		 * Display the appropriate dialog (if parent window handle
		 * supplied)
		 */
		if (hwnd)
		{
			/* Display dialog(s) */
			fSuccess = (IDOK == DialogBoxParam(s_hModule,
											 MAKEINTRESOURCE(DLG_CONFIG),
											   hwnd,
											   ConfigDlgProc,
											 (LONG) (LPSTR) lpsetupdlg));
		}
		else if (lpsetupdlg->ci.dsn[0])
			fSuccess = SetDSNAttributes(hwnd, lpsetupdlg, NULL);
		else
			fSuccess = FALSE;
	}

	GlobalUnlock(hglbAttr);
	GlobalFree(hglbAttr);

	return fSuccess;
}
Esempio n. 12
0
eCzXmlParseError CzXmlParser::Parse(CzXmlNode* parent)
{
	CzXmlNodeList* parent_stack = new CzXmlNodeList();
  
	parent_stack->push_back(parent);
	int		count = NextFreePoolTagIndex;
	int		tag_index = 0;
	char*	c_data = m_pDataInput->getData();
  

	parent = parent_stack->back();
  
  //debug std::cout << "*********************************************************** STARTING PARSING NOW" << std::endl;
  //debug std::cout << "*****      MarkerCount is " << MarkerCount << std::endl;


	while (tag_index < MarkerCount)
	{
      //debug std::cout << "*****      Beginning of the while loop. tag_index = " << tag_index << std::endl;
      
		if (parent == NULL)
			break;

		CzXmlTagMarker* marker = Marker + tag_index;

		const char* data = c_data + marker->Start;

		int len = marker->Length;
      
      //debug std::cout << "*****      The position of the tag I'm loking for is " <<  marker->Start << " and the length of this tag is " << marker->Length << std::endl;


      //if (marker->Line > 20000 || marker->Line < -1000000) {std::cout << "BREAKING - MARCO'S HACK" << std::endl; break;/*tag_index++;continue;*/} // marco hack


		if (*data == '<' && *(data + len - 1) == '>')
		{
          //debug std::cout << "Found a < >."<< std::endl;
			if (*(data + 1) == '/')
			{
              //debug std::cout << "It is and end tag."<< std::endl;

				// Found an end tag, check that name matches parents
				int et_offset = 0;
				int et_len = getNextWord(data + 2, et_offset);
				if (et_len <= 0)
				{
/*					CzString error = "CzXmlParser::Parse - Invalid close tag - ";
					error += parent->Name.c_str();
					error += " - at line ";
					error += CzString(marker->Line);
					CzDebug::Log(error.c_str());*/
					ShowError(XmlErrorInvalidTag, marker->Line);
					return XmlErrorInvalidTag;
				}
				if (!parent->Name.Compare(data + et_offset + 2, et_len))
				{

/*					CzString error = "CzXmlParser::Parse - Mismatched end tag - ";
					error += parent->Name.c_str();
					error += " - at line ";
					error += CzString(marker->Line);
					CzDebug::Log(error.c_str());
					CzDebug::Log(CZ_DEBUG_CHANNEL_INFO, "CzXmlParser::Parse - Instead found - ", CzString(data, et_offset + 2, et_len).c_str());*/
					ShowError(XmlErrorMismatchedEndTag, marker->Line);
					return XmlErrorMismatchedEndTag; 
				}
				for (CzXmlNodeList::iterator it = parent_stack->begin(); it != parent_stack->end(); it++)
				{

					CzXmlNode* node = *it;
					if (node == parent)
					{
						parent_stack->erase(it);
						parent = parent_stack->back();
						break;
					}
				}
				tag_index++;

			}
			else
			{

				// Create a node
                //debug std::cout << "Creating a node for tag_index " << tag_index << std::endl;
				CzXmlNode* node = AllocNode();
				node->Line = marker->Line + 1;
				int offset;
				int nlen = getNextWord(data + 1, offset);
				if (nlen <= 0)
				{
//					CzString error = "CzXmlParser::Parse - Invalid tag at line ";
//					error += CzString(marker->Line);
//					CzDebug::Log(error.c_str());
					ShowError(XmlErrorInvalidTag, marker->Line);
					return XmlErrorInvalidTag;
				}

				node->Name.setString(data + offset + 1, nlen);
              //debug std::cout << "This node has name: " << node->Name.getString() << std::endl;
				if ((len - 2) > nlen)
				{
					eCzXmlParseError error = ParseAttributes(data + offset + nlen + 1, len - nlen - offset - 1, node);
					if (error != XmlErrorNone)
					{
						ShowError(error, marker->Line);
						return error;
					}
				}
              //debug std::cout << "Adding this node to parent.Name " << parent->Name.getString() << std::endl;
				parent->AddChild(node);

				if (*(data + len - 2) != '/')		// Self closing tags dont get added as parents
				{
					parent_stack->push_back(node);	// Found an inner tag so push parent
					parent = parent_stack->back();
				}

				// Check next line to see if it is a tag or a value
              //debug std::cout << "I will now check if next line is a tag or a value." << std::endl;

				tag_index++;
              //debug std::cout << "tag_index is " << tag_index << "   NextFreePoolTagIndex - 1 is " << NextFreePoolTagIndex - 1 << std::endl;
				if (tag_index != (NextFreePoolTagIndex - 1))
				{
					CzXmlTagMarker* marker2 = Marker + tag_index;
                  //debug std::cout << "marker2->Start is " << marker2->Start << std::endl;

					const char* data2 = c_data + marker2->Start;
					int len2 = marker2->Length;

					if (*data2 != '<')
					{
						// Found a value
						node->Value.setString(data2, len2);
						node->HasValue = true;
                      //debug std::cout << "I've found a value.\nThis node has value: " << node->Value.getString() << std::endl;
					}
				}
              // Marco: also look if I have a value without the < >. So go to the next character and see if it doesn't have a <.
              const char* mydata = c_data + marker->Start + marker->Length;
              CzXmlTagMarker* marker2 = Marker + tag_index;
              bool flag = true;
              if (*(mydata-2) != '/') { // if we are not after an end tag
                for (int h = 0; flag; h++) { // explore the chars after this tag
                  if (*(mydata+h) != '\n') { // only those different then newline
                    if (*(mydata+h) == '<'){
                      // Found a new tag. It is not a value
                      flag = false;
                      //debug std::cout << "Found a new tag. It is not a value *(mydata+h) = " << *(mydata+h) << std::endl;
                    }
                    if (*(mydata+h) != '<') {
                      // Found a char after an end tag which is not a new tag. It must be a value
                      flag = false;
                      //debug std::cout << "Found a char after an end tag which is not a new tag. It must be a value. *(mydata+h) = " << *(mydata+h) << std::endl;
                      //debug std::cout << "Found a char after an end tag which is not a new tag. It must be a value. *(mydata+h) = " << *(c_data + marker2->Start -1) << std::endl;
                      //debug std::cout << "My estimated size is: "<< (c_data + marker2->Start -1) - (mydata+h) << std::endl;
                      // Found a value
                      int mylen = (c_data + marker2->Start) - (mydata+h);
                      node->Value.setString(mydata+h, mylen);
                      node->HasValue = true;
                      //debug std::cout << "I've found a value.\nThis node has value: " << node->Value.getString() << std::endl;
                    }
                  }
                }
                
              }
              /* debug
              std::cout << "Printing *(mydata-2): "<<*(mydata-2)<<std::endl;
              std::cout << "Printing *(mydata-1): "<<*(mydata-1)<<std::endl;
              std::cout << "Printing *(mydata): "<<*(mydata)<<std::endl;
              std::cout << "Printing *(mydata+1): "<<*(mydata+1)<<std::endl;
              std::cout << "Printing *(mydata+2): "<<*(mydata+2)<<std::endl;
               */
			}
		}
        else {
          //debug std::cout << "NOT Found a < >. \nIncrementing tag_index++ and going on."<< std::endl;
			tag_index++;
        }
	}
  
  //CzDebug::Log(CZ_DEBUG_CHANNEL_INFO, "MARCO in CzXmlParser::Parse(CzFile *file, bool decrypt). size is ", "MARCO in CzXmlParser::Parse(CzFile *file, bool decrypt). size is ", "MARCO in CzXmlParser::Parse(CzFile *file, bool decrypt). size is ", 3);


	parent_stack->clear();
	delete parent_stack;
  
  //CzDebug::Log(CZ_DEBUG_CHANNEL_INFO, "MARCO in CzXmlParser::Parse(CzFile *file, bool decrypt). size is ", "MARCO in CzXmlParser::Parse(CzFile *file, bool decrypt). size is ", "MARCO in CzXmlParser::Parse(CzFile *file, bool decrypt). size is ", 4);


	return XmlErrorNone;
}
Esempio n. 13
0
PXMLTag CXMLParser::ParseString(const std::string& sXmlString)
{
	std::stack<PXMLTag> m_openTags;
	std::stack<PXMLTag> m_openTagParent;

	PXMLTag xParent, xRoot;
	bool bEnding = false;

	std::string::size_type pos = sXmlString.find("<");
	std::string::size_type iTextStartPos = std::string::npos;
	unsigned int iIteration = 0, iTextStartPosIteration = 0;

	while(pos != std::string::npos)
	{
		if(bEnding)
		{
			throw CXMLException("Multiple root tags?", pos);
		}

		iIteration++;
		std::string::size_type tagendpos = sXmlString.find(">", pos + 1);

		if(tagendpos == std::string::npos)
		{
			throw CXMLException("No terminating > for open <", pos);
		}

		if(tagendpos == pos + 1)
		{
			throw CXMLException("Empty tag", pos);
		}

		std::string sTagContents = sXmlString.substr(pos + 1, tagendpos - pos - 1);
		sTagContents = CUtil::StrReplace("\r", "", sTagContents);
		sTagContents = CUtil::StrReplace("\n", "", sTagContents);
		CUtil::StrTrim(sTagContents);

		std::string::size_type posTagName = sTagContents.find(' ');
		if(posTagName == std::string::npos) posTagName = sTagContents.size();
		std::string sTagName = sTagContents.substr(0, posTagName);

		if(sTagName.substr(0, 3) == "!--")
		{
			// skip comments.
			tagendpos = sXmlString.find("-->", pos) + 2;

			if(tagendpos == std::string::npos)
			{
				throw CXMLException("Unterminated comment", pos);
			}
		}
		else if(sTagName[0] == '?')
		{
			// skip <?xml stuff without any further checks.
		}
		else if(sTagName.substr(0, 8) == "![CDATA[")
		{
			std::string::size_type posCDataEnd = sXmlString.find("]]>", pos);

			if(posCDataEnd == std::string::npos)
			{
				throw CXMLException("Unterminated CDATA section", pos);
			}
			else if(m_openTags.empty())
			{
				throw CXMLException("CDATA section outside of a tag", pos);
			}

			PXMLTag xOpenTag = m_openTags.top();

			xOpenTag->m_text = sXmlString.substr(pos + 1 + 8, posCDataEnd - pos - 9);
			CUtil::StrTrim(xOpenTag->m_text);

			tagendpos = posCDataEnd + 2;
		}
		else if(sTagName[0] != '/')
		{
			// found start tag
			PXMLTag xNew(new CXMLTag());
			xNew->m_name = sTagName;

			ParseAttributes(sTagContents, xNew->m_attributes);

			// look out for <img /> style tags:
			if(sTagContents[sTagContents.size() - 1] != '/')
			{
				m_openTags.push(xNew);
				if(xParent) m_openTagParent.push(xParent);
				xParent = xNew;

				// save the position in case this tag has no child tags
				// and we want to extract text from it.
				iTextStartPos = tagendpos + 1;
				iTextStartPosIteration = iIteration;
			}
			else if(xParent)
			{
				xParent->m_children.push_back(xNew);
			}
			else
			{
				xRoot = xNew;
			}
		}
		else
		{
			// found end tag
			sTagName.erase(0, 1);

			if(m_openTags.size() == 0 || _stricmp(m_openTags.top()->m_name.c_str(), sTagName.c_str()) != 0)
			{
				throw CXMLException("Ending tag for '" + std::string(sTagName) + "', which is not open", pos);
			}

			// take the now-closed tag off the stack:
			PXMLTag xClosedTag = m_openTags.top();

			m_openTags.pop();

			// if no other tags have been found in between, extract text:
			if(iIteration == iTextStartPosIteration + 1)
			{
				xClosedTag->m_text = sXmlString.substr(iTextStartPos, pos - iTextStartPos);
				xClosedTag->m_text = XmlDecode(xClosedTag->m_text);
			}

			// no parent = root tag. if this happens, we've walked the tree and are done.
			if(m_openTagParent.empty())
			{
				xRoot = xClosedTag;
				bEnding = true;
			}
			else
			{
				// re-set old parent:
				xParent = m_openTagParent.top();
				m_openTagParent.pop();

				// otherwise, save the new child and to the next tag...
				xParent->m_children.push_back(xClosedTag);
			}
		}

		pos = sXmlString.find("<", tagendpos + 1);
	}

	if(m_openTags.size() != 0)
	{
		throw CXMLException("Found unclosed tags", 0);
	}

	return xRoot;
}
Esempio n. 14
0
File: ipp.c Progetto: Cbrdiv/xplico
static packet* IppDissector(packet *pkt)
{
    http_msg *msg;
    pei *ppei;
    pei_component *cmpn;
    int ind, fd;
    unsigned char buff[IPP_BUFFER_SIZE];
    char *pcl_file, *pdf_file;
    char cmd[IPP_FILENAME_PATH_SIZE*2];
    ssize_t len;
    unsigned int offset;
    ipp_ver ver;
    FILE *pcl;
    struct stat fst;

    ppei = NULL;

    /* display info */
    msg = (http_msg *)pkt->data;
    LogPrintf(LV_DEBUG, "IPP Dissector");
    
#ifdef XPL_CHECK_CODE
    if (msg->serial == 0) {
        LogPrintf(LV_FATAL, "IPP Dissector serial error");
        exit(-1);
    }
#endif

    /* check if post and if PCL file */
    if (msg->mtd != HTTP_MT_POST || msg->req_body_size == 0) {
        /* free memory */
        HttpMsgRemove(msg);
        HttpMsgFree(msg);
        PktFree(pkt);
        
        return NULL;
    }
    
    /* open body file */
    fd = open(msg->req_body_file, O_RDONLY);
    if (fd == 0) {
        LogPrintf(LV_ERROR, "Can't open file:%s", msg->req_body_file);
        /* free memory */
        HttpMsgRemove(msg);
        HttpMsgFree(msg);
        PktFree(pkt);
        
        return NULL;
    }
    len = read(fd, buff, IPP_BUFFER_SIZE);
    offset = 0;

    /* IPP version */
    if (buff[0] == 1) {
        if (buff[1] == 0) {
            ver = IPP_1_0;
        }
        else if (buff[1] == 1) {
            ver = IPP_1_1;
        }
        else {
            LogPrintf(LV_WARNING, "Unknow version: %u.%u", buff[0], buff[1]);
            close(fd);
            /* free memory */
            HttpMsgRemove(msg);
            HttpMsgFree(msg);
            PktFree(pkt);
            
            return NULL;
        }
    }
    else {
        LogPrintf(LV_WARNING, "Unknow version: %u.%u", buff[0], buff[1]);
        close(fd);
        /* free memory */
        HttpMsgRemove(msg);
        HttpMsgFree(msg);
        PktFree(pkt);
        
        return NULL;
    }
    offset += 2;
    /* check if print job */
    if (ntohs(*((unsigned short *)(buff+offset))) != PRINT_JOB) {
        close(fd);
        /* free memory */
        HttpMsgRemove(msg);
        HttpMsgFree(msg);
        PktFree(pkt);
        
        return NULL;
    }
    offset += 2;
    offset += 4; /* skeep request id */
#warning "to improve"
    offset = ParseAttributes(buff, offset, len); /* i hope that IPP_BUFFER_SIZE is alwayse correct */

    /* create PCL file */
    pcl_file = DMemMalloc(IPP_FILENAME_PATH_SIZE);
    pdf_file = DMemMalloc(IPP_FILENAME_PATH_SIZE);
    sprintf(pcl_file, "%s/%s/ipp_%lu_%p_%i.pcl", ProtTmpDir(), IPP_TMP_DIR,
            time(NULL), msg, incr);
    sprintf(pdf_file, "%s/%s/ipp_%lu_%p_%i.pdf", ProtTmpDir(), IPP_TMP_DIR,
            time(NULL), msg, incr);
    incr++;
               
    pcl = fopen(pcl_file, "w+");
    fwrite(buff+offset, 1, len-offset, pcl);
    len = read(fd, buff, IPP_BUFFER_SIZE);
    while (len != 0) {
        fwrite(buff, 1, len, pcl);
        len = read(fd, buff, IPP_BUFFER_SIZE);
    }
    fclose(pcl);
    close(fd);

    /* pdf conversion */
    sprintf(cmd, "%s -dNOPAUSE -sDEVICE=pdfwrite -sOutputFile=%s %s", pcl6_path, pdf_file, pcl_file);
    system(cmd);
    fst.st_size = 0;
    stat(pdf_file, &fst);

    /* compose pei */
    ppei = DMemMalloc(sizeof(pei));
    PeiInit(ppei);
    ppei->prot_id = prot_id;
    ppei->serial = pkt->serial;
    ppei->time_cap = pkt->cap_sec;
    ppei->stack = ProtCopyFrame(pkt->stk, TRUE);
    /*   url */
    ind = 0;
    cmpn = DMemMalloc(sizeof(pei_component));
    memset(cmpn, 0, sizeof(pei_component));
    cmpn->eid = pei_url_id;
    cmpn->id = ind;
    cmpn->time_cap = msg->start_cap;
    cmpn->time_cap_end = msg->end_cap;
    cmpn->strbuf = msg->uri;
    msg->uri = NULL;
    ppei->components = cmpn;
    /*   pdf */
    ind++;
    cmpn->next = DMemMalloc(sizeof(pei_component));
    cmpn = cmpn->next;
    memset(cmpn, 0, sizeof(pei_component));
    cmpn->eid = pei_pdffile_id;
    cmpn->id = ind;
    cmpn->time_cap = msg->start_cap;
    cmpn->time_cap_end = msg->end_cap;
    cmpn->file_path = pdf_file;
    cmpn->file_size = fst.st_size;
    if (msg->error)
        cmpn->err = ELMT_ER_PARTIAL;
    /*   pcl */
    ind++;
    cmpn->next = DMemMalloc(sizeof(pei_component));
    cmpn = cmpn->next;
    memset(cmpn, 0, sizeof(pei_component));
    cmpn->eid = pei_pclfile_id;
    cmpn->id = ind;
    cmpn->time_cap = msg->start_cap;
    cmpn->time_cap_end = msg->end_cap;
    cmpn->file_path = pcl_file;
    cmpn->file_size = msg->req_body_size - offset;
    if (msg->error)
        cmpn->err = ELMT_ER_PARTIAL;

    /* free memory */
    HttpMsgRemove(msg);
    HttpMsgFree(msg);
    PktFree(pkt);
    
    /* insert pei */
    PeiIns(ppei);

    return NULL;
}
Esempio n. 15
0
HRESULT
ParseNode
(
   IXmlReader * pReader,
   Node ** ppNode
)
{
   HRESULT hr;

   XmlNodeType nodeType;
   Char * nodeName = nullptr;

   Attribute * attrList = nullptr;

   Node * childList = nullptr;
   Node * childLast = nullptr;

   const WCHAR * tmpString;

#define APPEND_CHILD(childNode) \
   if (childLast == nullptr) \
   { \
       childList = childLast = childNode; \
   } \
   else \
   { \
       childLast->Next = childNode; \
       childLast = childNode; \
   }

   // This call won't fail we make sure the reader is positioned at a valid
   // node before ParseNode() is called.
   pReader->GetNodeType(&nodeType);

   do
   {
      switch (nodeType)
      {
      case XmlNodeType_Element:
      {
         bool inOpenElement = nodeName != nullptr;
         if (inOpenElement)
         {
            Node * childNode;
            hr = ParseNode(pReader, &childNode);
            if (hr == S_OK)
            {
               APPEND_CHILD(childNode);
            }
            else
            {
               return hr;
            }
         }
         else
         {
            pReader->GetLocalName(&tmpString, nullptr);
            nodeName = ConvertWCHAR(tmpString);

            hr = ParseAttributes(pReader, &attrList);
            if (FAILED(hr))
            {
               *ppNode = nullptr;
               return hr;
            }

            *ppNode = new Node(nodeName, attrList);

            if (pReader->IsEmptyElement())
            {
               return S_OK;
            }
         }

         break;
      }

      case XmlNodeType_EndElement:
      {
         Node * node = *ppNode;

         // If we have a single child with data called "#text", then pull the data up to this node.
         if (childList != nullptr
             && childList == childLast
             && (childList->Data != nullptr)
             && (_stricmp(childList->Name, "#text") == 0))
         {
            node->Data = childList->Data;
            node->ChildList = nullptr;
         }
         else
         {
            node->ChildList = childList;
         }

         return S_OK;
      }

      case XmlNodeType_Attribute:
         // Need to manually move to attributes when at an element node.
         break;

      case XmlNodeType_CDATA:
      case XmlNodeType_Text:
      {
         pReader->GetValue(&tmpString, nullptr);
         Node * node = new Node("#text", nullptr);
         node->Data = ConvertWCHAR(tmpString);
         APPEND_CHILD(node);

         break;
      }

      case XmlNodeType_Comment:
      case XmlNodeType_DocumentType:
      case XmlNodeType_None:
      case XmlNodeType_ProcessingInstruction:
      case XmlNodeType_Whitespace:
      case XmlNodeType_XmlDeclaration:
         // Ignored.
         break;
      }
   }
   while (S_OK == (hr = pReader->Read(&nodeType)));

   return hr;

#undef APPEND_CHILD
}
Esempio n. 16
0
mxArray* ParseChildNodes(pugi::xml_node& node)
{
    mxArray *children = NULL;
    pugi::xml_attribute tempAttr = node.first_attribute();

    if (HasChildNodes(node) || tempAttr != NULL)
    {
        mxArray *attributes = ParseAttributes(node);

        std::vector<std::string> distinctNames;
        std::vector<std::string> allChildNodeNames;
        std::vector<pugi::xml_node> childNodes;
        std::size_t numChildNodes;

        childNodes = GetChildNodes(node);
        numChildNodes = childNodes.size();

        for (int i = 0; i < numChildNodes; i++)
        {
            allChildNodeNames.push_back(childNodes.at(i).name());
        }

        distinctNames = GetDistinctNodeNames(allChildNodeNames);
        
        /* Patch for bypassing the variable-length arrays problems of modern C++ compilers */
        std::vector<const char*> distinctChildNodeNames;
        std::transform(distinctNames.begin(), distinctNames.end(), std::back_inserter(distinctChildNodeNames), [](const std::string & str) {
            // initialize empty char array
            char *output = new char[str.size()+1];
            std::strcpy(output, str.c_str());
            return output;
        });        

        std::vector<std::string> processedNames;

        children = mxCreateStructMatrix(1, 1, (int)distinctNames.size(), &distinctChildNodeNames[0]);

        for (int idx = 0; idx < childNodes.size(); idx++)
        {
            pugi::xml_node theChild = childNodes.at(idx);
            std::string type = node_types[theChild.type()];
            std::string temp = theChild.name();
            std::string val = theChild.value();

            const char *namey[1] = {};
            namey[0] = temp.c_str();
            mxArray *glhf = mxGetField(children, 0, namey[0]);
            int indexOfMatchingItem = mxGetFieldNumber(children,  namey[0]);

            if (!(strcmp(type.c_str(), "pcdata") == 0) && !(strcmp(type.c_str(), "comment") == 0) && !(strcmp(type.c_str(), "cdata") == 0))
            {
                //XML allows the same elements to be defined multiple times, put each in a different cell
                if (std::find(processedNames.begin(), processedNames.end(), temp) != processedNames.end())
                {
                    if ( glhf != NULL )
                    {
                        if (!mxIsCell(glhf))
                        {
                            mxArray *temp = glhf;
                            glhf = mxCreateCellMatrix(1, 2);
                            mxSetCell(glhf, 0, temp);
                            mxSetCell(glhf, 1, ParseChildNodes(theChild));
                            mxSetCell(children, indexOfMatchingItem, glhf);
                        }
                        else
                        {
                            std::size_t numberItemsInCell = mxGetN(glhf);
                            mxArray *temp = glhf;
                            glhf = mxCreateCellMatrix(1, numberItemsInCell + 1);

                            for (int i = 0; i < numberItemsInCell; i++)
                            {
                                mxSetCell(glhf, i, mxGetCell(temp, i));
                            }

                            mxSetCell(glhf, numberItemsInCell, ParseChildNodes(theChild));
                            mxSetCell(children, indexOfMatchingItem, glhf);
                        }
                    }
                }
                //add previously unknown (new) element to the structure
                else
                {
                    mxSetCell(children, indexOfMatchingItem, ParseChildNodes(theChild));
                }

                processedNames.push_back(temp);
            }
            else
            {
                const char *typeFieldNames[1] = {"Text"};
                std::string value  = theChild.value();
                mxArray *matValue  = mxCreateString(value.c_str());

                if (strcmp(type.c_str(), "cdata") == 0)
                {
                    typeFieldNames[0] = "CDATA";
                }
                else if (strcmp(type.c_str(), "comment") == 0)
                {
                    typeFieldNames[0] = "Comment";
                }

                children = mxCreateStructMatrix(1, 1, 1, typeFieldNames);
                mxSetFieldByNumber(children, 0, 0, matValue);

                processedNames.push_back(temp);
            }
        }

        if (attributes != NULL)
        {
            const char *attrFieldName = "Attributes";
            mxAddField(children, attrFieldName);
            mxSetField(children, 0, attrFieldName, attributes);
        }

    }

    return children;
}
Esempio n. 17
0
eXMLParserError CIwGameXmlParser::Parse(CIwGameXmlNode* parent)
{
	CIwList<CIwGameXmlNode*>* parent_stack = new CIwList<CIwGameXmlNode*>();
	
	parent_stack->push_back(parent);
	int		count = NextFreePoolTagIndex;
	int		tag_index = 0;
	char*	c_data = m_pDataInput->getData();

	parent = parent_stack->back();

	while (tag_index < MarkerCount)
	{
		if (parent == NULL)
			break;
		CIwGameXmlTagMarker* marker = Marker + tag_index;
		const char* data = c_data + marker->Start;
		int len = marker->Length;

		if (*data == '<' && *(data + len - 1) == '>')
		{
			if (*(data + 1) == '/')
			{
				// Found an end tag, check that name matches parents
				int et_offset = 0;
				int et_len = GetNextWord(data + 2, et_offset);
				if (et_len <= 0)
				{
					CIwGameError::LogError("CIwGameXmlParser::Parse - Invalid close tag");
					return eXMLParserError_InvalidTag;
				}
				if (!parent->Name.Compare(data + et_offset + 2, et_len))
				{
					CIwGameError::LogError("CIwGameXmlParser::Parse - Mismatched end tag - ", parent->Name.c_str());
					CIwGameError::LogError("CIwGameXmlParser::Parse - Instead found - ", CIwGameString(data, et_offset + 2, et_len).c_str());
					return eXMLParserError_MismatchedEndTag;
				}
				for (CIwList<CIwGameXmlNode*>::iterator it = parent_stack->begin(); it != parent_stack->end(); it++)
				{
					CIwGameXmlNode* node = *it;
					if (node == parent)
					{
						parent_stack->erase(it);
						parent = parent_stack->back();
						break;
					}
				}
				tag_index++;
			}
			else
			{
				// Create a node
				CIwGameXmlNode* node = AllocNode();
				int offset;
				int nlen = GetNextWord(data + 1, offset);
				if (nlen <= 0)
					return eXMLParserError_InvalidTag;
				node->Name.setString(data + offset + 1, nlen);
				if ((len - 2) > nlen)
					ParseAttributes(data + offset + nlen + 1, len - nlen - offset - 1, node);
				parent->AddChild(node);

				if (*(data + len - 2) != '/')		// Self closing tags dont get added as parents
				{
					parent_stack->push_back(node);	// Found an inner tag so push parent
					parent = parent_stack->back();
				}

				// Check next line to see if it is a tag or a value
				tag_index++;
				if (tag_index != (NextFreePoolTagIndex - 1))
				{
					CIwGameXmlTagMarker* marker2 = Marker + tag_index;
					const char* data2 = c_data + marker2->Start;
					int len2 = marker2->Length;

					if (*data2 != '<')
					{
						// Found a value
						node->Value.setString(data2, len2);
						node->HasValue = true;
					}
				}
			}
		}
		else
			tag_index++;
	}

	parent_stack->clear();
	delete parent_stack;

	return eXMLParserError_None;
}
Esempio n. 18
0
eXMLParserError CIwGameXmlParser::Parse(CIwGameXmlNode* pParent, int range, int &num_tags_found)
{
	char* pBuffer = (char *)m_pDataInput->getData();
	
	while (1)
	{
		if (m_pDataInput->IsEOF())
			break;
	
		// Search for a tag
		int old_pos = m_pDataInput->GetPos();
		int tag_pos;
		int tag_len = m_pDataInput->GetNextTag('<', '>', range, tag_pos);
		if (tag_len >= 0)
		{
			if (*(pBuffer + tag_pos) == '/')
			{
				// Close tag was found so return to parent
				m_pDataInput->SetPos(old_pos);
				return eXMLParserError_None;
			}
			else
			{
				// Set node name
				int ws = CIwGameXmlTools::GetFirstWhitespaceIndex(pBuffer + tag_pos, tag_len);

				// Create a new node
				CIwGameXmlNode* new_node = AllocNode();
				new_node->SetName(pBuffer + tag_pos, ws <= 0 ? tag_len : ws);

				// Create new node and add it to parent
				if (pParent != NULL)
				{
					pParent->AddChild(new_node);
				}
						
				num_tags_found++;

				// Get attributes
				int op = m_pDataInput->GetPos();
				m_pDataInput->SetPos(tag_pos);
				eXMLParserError pe = ParseAttributes(new_node);
				if (pe != eXMLParserError_None)
					return pe;
				m_pDataInput->SetPos(op);

				// If not short tag then check for inner tags
				char ec = *(pBuffer + tag_pos + tag_len - 1);
				if (ec != '/')
				{
					// Parse inner tags
					int num_tags = 0;
					eXMLParserError error = Parse(new_node, range, num_tags);
					if (error != eXMLParserError_None)
						return error;
						
					// Check closing tag matches
					int close_tag_pos;
					int close_tag_len = m_pDataInput->GetNextTag('<', '>', range, close_tag_pos);
					if (close_tag_len >= 0)
					{
						// If close tag was only tag found then get value from between tags
						if (num_tags == 0)
						{
							int value_len = close_tag_pos - (tag_pos + tag_len) - 2;
							new_node->SetValue(pBuffer + tag_pos + tag_len + 1, value_len);
						}

						// Check to ensure that close tag matches open tag
						if (new_node->Name.GetLength() != (close_tag_len - 1) || !new_node->Name.Compare(pBuffer + close_tag_pos + 1, close_tag_len - 1))
						{
//								ShowError(eXMLParserError_MismatchedEndTag, close_tag_pos);
//								return eXMLParserError_MismatchedEndTag;
						}
					}
					else
					{
						ShowError(eXMLParserError_MissingEndTag, tag_pos);
						return eXMLParserError_MissingEndTag;
					}
				}
				else
				{
					new_node->SetValue("", 0);
				}
			}
		}
		else
		{
			ShowError(eXMLParserError_InvalidTag, tag_pos);
			return eXMLParserError_InvalidTag;
		}
	}
	
	return eXMLParserError_NoTagFound;
}
Esempio n. 19
0
void GenerateTopology (CUniverse &Universe, CXMLElement *pCmdLine)
	{
	int i, j, k;

	int iCount = pCmdLine->GetAttributeIntegerBounded(COUNT_SWITCH, 1, -1, 1);

	STopologyStats Stats;

	for (k = 0; k < iCount; k++)
		{
		if (iCount > 1)
			printf("sample %d", k+1);

		TSortMap<CString, SNodeInfo> NodeData;
		TSortMap<CString, int> AttribCount;

		//	Initialize the topology

		CString sError;
		Universe.GetFirstTopologyNode();

		//	Loop over all nodes

		for (i = 0; i < Universe.GetTopologyNodeCount(); i++)
			{
			CTopologyNode *pNode = Universe.GetTopologyNode(i);

			SNodeInfo *pNewNode = NodeData.Insert(pNode->GetID());
			pNewNode->sID = pNode->GetID();
			pNewNode->sName = pNode->GetSystemName();
			pNewNode->dwSystemUNID = pNode->GetSystemDescUNID();
			pNewNode->sAttribs = pNode->GetAttributes();

			//	Add the attributes in this node to the list of 
			//	attributes for this try.

			TArray<CString> Attribs;
			ParseAttributes(pNewNode->sAttribs, &Attribs);
			for (j = 0; j < Attribs.GetCount(); j++)
				{
				int *pCount = AttribCount.GetAt(Attribs[j]);
				if (pCount == NULL)
					{
					pCount = AttribCount.Insert(Attribs[j]);
					*pCount = 0;
					}

				*pCount = (*pCount) + 1;
				}
			}

		//	Compute topology stats
		//	Add the node count for this try

		Stats.NodeCount.Insert(NodeData.GetCount());

		//	Loop over all attributes that we know about. If one doesn't
		//	exist in this try, then we set its min to 0

		if (k > 0)
			{
			for (i = 0; i < Stats.Attribs.GetCount(); i++)
				{
				if (AttribCount.GetAt(Stats.Attribs.GetKey(i)) == NULL)
					Stats.Attribs[i].SetMin(0);
				}
			}

		//	Loop over all attributes in this try and add them to the stats

		SStat *pAttribStat;
		for (i = 0; i < AttribCount.GetCount(); i++)
			{
			//	If we have some attributes that no other try had, then
			//	that means that the minimum value is 0.

			if (pAttribStat = Stats.Attribs.GetAt(AttribCount.GetKey(i)))
				pAttribStat->Insert(AttribCount[i]);
			else
				{
				pAttribStat = Stats.Attribs.Insert(AttribCount.GetKey(i));
				pAttribStat->Insert(AttribCount[i]);
				if (k > 0)
					pAttribStat->SetMin(0);
				}
			}

		//	Output all the nodes

		if (iCount == 1)
			{
			printf("Node\tSystemType\tName\tStargates\tAttributes\n");
			for (i = 0; i < NodeData.GetCount(); i++)
				{
				SNodeInfo *pNode = &NodeData.GetValue(i);
				printf("%s\t%08x\t%s\t%d\t%s\n",
						pNode->sID.GetASCIIZPointer(),
						pNode->dwSystemUNID,
						pNode->sName.GetASCIIZPointer(),
						pNode->Stargates.GetCount(),
						pNode->sAttribs.GetASCIIZPointer());
				}
			}
		else
			{
			Universe.Reinit();
			printf("\n");
			}
		}

	//	Output stats

	if (iCount > 0)
		{
		printf("\n");
		printf("STATS\n\n");
		Stats.NodeCount.Print(CONSTLIT("Nodes"), iCount, Stats.NodeCount.GetAverage(iCount));
		printf("\n");

		printf("ATTRIBS\n\n");
		for (i = 0; i < Stats.Attribs.GetCount(); i++)
			Stats.Attribs[i].Print(Stats.Attribs.GetKey(i), iCount, Stats.NodeCount.GetAverage(iCount));
		printf("\n");
		}
	}