Exemple #1
0
 void parse (const std::string& s, T& out) {
   StringParser p (s);
   parse (p, out);
   p.skipWs ();
   if (!p.eof ())
     throw ParseException (typeid (T), p.value (), 0, p.pos (), "Got garbage at end of string");
 }
Exemple #2
0
bool SelectionParser::parse(vespalib::stringref s)
{
    bool retval(false);
    IdSpecParser id(_bucketIdFactory);
    if (id.parse(s)) {
        OperatorParser op;
        if (op.parse(id.getRemaining())) {
            if (id.isUserSpec()) {
                IntegerParser v;
                if (v.parse(op.getRemaining())) {
                    setNode(Node::UP(new Compare(id.stealValue(), *op.getOperator(), v.stealValue(), _bucketIdFactory)));
                    retval = true;
                }
                setRemaining(v.getRemaining());
            } else {
                StringParser v;
                if (v.parse(op.getRemaining())) {
                    setNode(Node::UP(new Compare(id.stealValue(), *op.getOperator(), v.stealValue(), _bucketIdFactory)));
                    retval = true;
                }
                setRemaining(v.getRemaining());
            }
        } else {
            setRemaining(op.getRemaining());
        }
    } else {
        setRemaining(id.getRemaining());
    }
    return retval;
}
Exemple #3
0
string mergeServerDbTable(const StringParser & parser)
{
	string ret = d_makeWithQuotes(parser.getServer());
	if (!parser.getDbName().empty())
	{
		ret += string(",") + d_makeWithQuotes(parser.getDbName()) + ',' +
			d_makeWithQuotes(parser.getTableName());
	}
	return ret;
}
Exemple #4
0
 void parse (StringParser& p, Math::Vector3<T>& out) {
   size_t start = p.pos ();
   p.expect (typeid (Math::Vector3<T>), start, '(');
   parse (p, out.x ());
   p.expect (typeid (Math::Vector3<T>), start, ',');
   parse (p, out.y ());
   p.expect (typeid (Math::Vector3<T>), start, ',');
   parse (p, out.z ());
   p.expect (typeid (Math::Vector3<T>), start, ')');
 }
Exemple #5
0
    void ExprParser::parseArguments (const std::string& arguments, Scanner& scanner,
        std::vector<Interpreter::Type_Code>& code, bool invert)
    {
        ExprParser parser (getErrorHandler(), getContext(), mLocals, mLiterals, true);
        StringParser stringParser (getErrorHandler(), getContext(), mLiterals);
        
        std::stack<std::vector<Interpreter::Type_Code> > stack;
        
        for (std::string::const_iterator iter (arguments.begin()); iter!=arguments.end();
            ++iter)
        {
            if (*iter=='S' || *iter=='c')
            {
                stringParser.reset();
                if (*iter=='c') stringParser.smashCase();
                scanner.scan (stringParser);            
                
                if (invert)
                {
                    std::vector<Interpreter::Type_Code> tmp;
                    stringParser.append (tmp);
                    
                    stack.push (tmp);
                }
                else
                    stringParser.append (code);
            }
            else
            {
                parser.reset();    
                scanner.scan (parser);

                std::vector<Interpreter::Type_Code> tmp;

                char type = parser.append (tmp);

                if (type!=*iter)
                    Generator::convert (tmp, type, *iter);
                    
                if (invert)
                    stack.push (tmp);
                else
                    std::copy (tmp.begin(), tmp.end(), std::back_inserter (code));
            }
        }
        
        while (!stack.empty())
        {
            std::vector<Interpreter::Type_Code>& tmp = stack.top();
        
            std::copy (tmp.begin(), tmp.end(), std::back_inserter (code));
        
            stack.pop();
        }
    }    
FontPtr ResourceConfig::SafeReadFont(StringParser &theVal)
{
	std::string aFace;
	theVal.ReadString(aFace); EnsureComma(theVal);
	int aStyle = SafeReadFontStyle(theVal); EnsureComma(theVal);
	
	int aSize;
	if(!theVal.ReadValue(aSize) || aSize<=0)
		throw ConfigObjectException("Invalid font size.");

	return Window::GetDefaultWindow()->GetFont(FontDescriptor(aFace,aStyle,aSize));
}
Exemple #7
0
ErrorCode _CCONV FSBase::backupIncremental(const char * path, unsigned * amountChanged)
{
	if (path == nullptr)
		return INVALIDARG;

	StringParser otherParser;
	if (!otherParser.initialize(path))
		otherParser.setServer(path);
	if (otherParser.getServer().empty())
		return INVALIDARG;

	if (!createDir(otherParser.getServer()))
		return FAILEDTOGETWINDIR;
	fstream file;
	string data;
	ErrorCode retVal = getLogFileData(otherParser.getServer(), file, data);
	if (failed(retVal))
		return retVal;
	PathTimeLog log(parser.getServer(), data);
	if (log.isCorrupted())
		return LOG_CORRUPTED;
	unsigned amountBackup = 0;
	retVal = backupAux(parser.getServer(), otherParser.getServer(), &log.getLastBackupTime(), amountBackup);
	if (failed(retVal))
		return retVal;
	replaceRecordInData(parser.getServer(), log.getNowTime(), data);
	retVal = setLogFileData(otherParser.getServer(), file, data);
	if (amountChanged != nullptr)
		*amountChanged = amountBackup;
	return retVal;
}
bool LobbyConfig::HandleKeyVal(ConfigParser &theParser, const std::string &theKey, StringParser &theVal)
{
	if(theKey=="LOBBYDEFINE")
	{
		std::string aKey, aVal;
		theVal.ReadString(aKey,true);
		theVal.ReadString(aVal);
		if(!aKey.empty())
			mDefineMap[aKey] = aVal;
	}
	else
		return ConfigObject::HandleKeyVal(theParser,theKey,theVal);

	return true;
}
static bool ResourceConfig_AddToMap(const char *theName, StringParser &theVal, Map &theMap, int theParseCount, Type* &theType)
{
	std::string aKey;
	theVal.ReadValue(aKey,true);
	if(aKey.empty())
		throw ConfigObjectException("Invalid resource key.");
	
	std::pair<Map::iterator,bool> aRet;
	aRet = theMap.insert(Map::value_type(aKey,Map::referent_type(Type(),theParseCount)));

	int &aParseCount = aRet.first->second.second;

	if(aRet.second)
	{
		theType = &aRet.first->second.first;		
		return true;
	}
	else if(aParseCount==theParseCount)
	{
		char aBuf[512];
		sprintf(aBuf,"%s resource already exists: %s",theName,aKey.c_str());
		throw ConfigObjectException(aBuf);
	}

	return false;
}
Exemple #10
0
 void parse (StringParser& p, T& out) {
   size_t start = p.pos ();
   std::istringstream stream (p.value ().substr (start));
   std::istream& stream2 (stream);
   stream2 >> out;
   if (stream.fail ()) {
     stream.clear ();
     std::streampos pos = stream.tellg ();
     ASSERT (pos >= 0);
     throw ParseException (typeid (T), p.value (), start, start + (size_t) pos, "operator>> failed");
   }
   stream.clear (); // Needed (for clearing EOF bit?), otherwise stream.tellg() fails (returns -1)
   std::streampos pos = stream.tellg ();
   ASSERT (pos >= 0);
   p.skip ((size_t) pos);
 }
Exemple #11
0
SQLRETURN connectToDb(HENV henv, const StringParser & parser, HDBC & hdbc)
{
	SQLRETURN retcode = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);
	check_rc(retcode, retcode);
	//for massive copy
	//retcode = SQLSetConnectAttr(hdbc, SQL_COPT_SS_BCP, (void *)SQL_BCP_ON, SQL_IS_INTEGER);
	//check_rc(retcode, "SQLSetConnectAttr(hdbc1) Failed\n\n");
	string szDSN = "Driver={SQL Server Native Client 11.0};Server=" + parser.getServer() + ";Database=" +
		parser.getDbName() + ";UID=" + parser.getLogin() + ";PWD=" + parser.getPass();
	retcode = connect(hdbc, (SQLCHAR*)szDSN.c_str());
	if (!MYSQLSUCCESS(retcode))
	{
		SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
		return retcode;
	}
	//retcode = SQLSetConnectAttr(hdbc, SQL_ATTR_AUTOCOMMIT, (SQLPOINTER)TRUE, 0);
	return retcode;
}
ImagePtr ResourceConfig::SafeReadImage(StringParser &theVal)
{
	std::string aPath;
	theVal.ReadString(aPath);

	ImagePtr anImage = WindowManager::GetDefaultWindowManager()->DecodeDelayImage(ComponentConfig::GetResourceFile(aPath).c_str());
	if(anImage.get()==NULL)
		throw ConfigObjectException("Failed to decode image: " + aPath);

	return anImage;
}
Exemple #13
0
//returns: StatusLineTooLong, SyntaxError, BadMethod
QTSS_Error RTSPRequest::ParseFirstLine(StringParser &parser)
{   
    //first get the method
    StrPtrLen theParsedData;
    parser.ConsumeWord(&theParsedData);
    this->SetVal(qtssRTSPReqMethodStr, theParsedData.Ptr, theParsedData.Len);
    
    
    //THIS WORKS UNDER THE ASSUMPTION THAT:
    //valid HTTP/1.1 headers are: GET, HEAD, POST, PUT, OPTIONS, DELETE, TRACE
    fMethod = RTSPProtocol::GetMethod(theParsedData);
    if (fMethod == qtssIllegalMethod)
        return QTSSModuleUtils::SendErrorResponse(this, qtssClientBadRequest, qtssMsgBadRTSPMethod, &theParsedData);
    
    //no longer assume this is a space... instead, just consume whitespace
    parser.ConsumeWhitespace();

    //now parse the uri
    QTSS_Error err = ParseURI(parser);
    if (err != QTSS_NoErr)
        return err;

    //no longer assume this is a space... instead, just consume whitespace
    parser.ConsumeWhitespace();

    //if there is a version, consume the version string
    StrPtrLen versionStr;
    parser.ConsumeUntil(&versionStr, StringParser::sEOLMask);
    
    //check the version
    if (versionStr.Len > 0)
        fVersion = RTSPProtocol::GetVersion(versionStr);

    //go past the end of line
    if (!parser.ExpectEOL())
        return QTSSModuleUtils::SendErrorResponse(this, qtssClientBadRequest, qtssMsgNoRTSPVersion,&theParsedData);
    return QTSS_NoErr;
}
bool ResourceConfig::HandleInt(StringParser &theVal)
{
	int *anInt;
	std::string aRefName;
	if(ResourceConfig_AddToMap("Int",theVal,mIntMap,mParseCount,anInt))
	{
		ResourceConfig *aRef = CheckResourceReference(theVal,aRefName);
		if(aRef!=NULL)
			*anInt = aRef->SafeGetInt(aRefName);
		else
		{
			if(!theVal.ReadValue(*anInt))
				throw ConfigObjectException("Invalid integer value.");
		}
	}

	return true;
}
bool ResourceConfig::HandleString(StringParser &theVal)
{
	GUIString *aString;
	std::string aRefName;
	if(ResourceConfig_AddToMap("String",theVal,mStringMap,mParseCount,aString))
	{

		ResourceConfig *aRef = CheckResourceReference(theVal,aRefName);
		if(aRef!=NULL)
			*aString = aRef->SafeGetString(aRefName);
		else
		{
			std::wstring aVal;
			theVal.ReadValue(aVal,false);
			*aString = aVal;
		}
	}

	return true;
}
Exemple #16
0
 void parse (StringParser& p, Math::DiagMatrix3<T>& out) {
   size_t start = p.pos ();
   if (p.peek () == '(') {
     p.expect (typeid (Math::DiagMatrix3<T>), start, '(');
     parse (p, out.m11 ());
     p.expect (typeid (Math::DiagMatrix3<T>), start, ',');
     parse (p, out.m22 ());
     p.expect (typeid (Math::DiagMatrix3<T>), start, ',');
     parse (p, out.m33 ());
     p.expect (typeid (Math::DiagMatrix3<T>), start, ')');
   } else {
     T value;
     parse (p, value);
     out = Math::DiagMatrix3<T> (value, value, value);
   }
 }
Background ResourceConfig::SafeReadBackground(StringParser &theVal)
{
	std::string aType;
	theVal.ReadString(aType);

	if(stricmp(aType.c_str(),"COLOR")==0)
	{
		EnsureComma(theVal);
		return SafeReadColor(theVal);
	}
	else if(stricmp(aType.c_str(),"IMAGE")==0)
	{
		EnsureComma(theVal);
		return SafeReadImage(theVal).get();
	}
	else if(stricmp(aType.c_str(),"STRETCHIMAGE")==0)
	{
		EnsureComma(theVal);
		Background aBackground(SafeReadImage(theVal));
		aBackground.SetStretchImage(true);
		return aBackground;
	}
	else if(stricmp(aType.c_str(),"WATERMARK")==0)
	{
		EnsureComma(theVal);
		Background aBackground(SafeReadImage(theVal));
		aBackground.SetUseOffsets(false);
		return aBackground;
	}
	else if(stricmp(aType.c_str(),"NONE")==0)
		return -1;
	else if(stricmp(aType.c_str(),"TRANSPARENT")==0)
	{
		Background aBackground(-1);
		aBackground.SetWantGrabBG(true);
		return aBackground;
	}
	else
		throw ConfigObjectException("Invalid background specification");
}
Exemple #18
0
ErrorCode _CCONV FSBase::backupFull(const char * path, unsigned * amountChanged)
{
	if (path == nullptr)
		return INVALIDARG;
	StringParser otherParser;
	if (!otherParser.initialize(path))
		otherParser.setServer(path);
	if (otherParser.getServer().empty())
		return INVALIDARG;
	if (!createDir(otherParser.getServer()))
		return FAILEDTOGETWINDIR;
	unsigned amountBackup = 0;
	ErrorCode res = backupAux(parser.getServer(), otherParser.getServer(), NULL, amountBackup);
	if (amountChanged != nullptr)
		*amountChanged = amountBackup;
	return res;
}
int ResourceConfig::SafeReadFontStyle(StringParser &theVal)
{
	std::string aStyleStr;
	int aStyle = 0;
	while(true)
	{
		theVal.ReadString(aStyleStr,true);
		if(aStyleStr.empty())
			break;

		if(stricmp(aStyleStr.c_str(),"Bold")==0)
			aStyle |= FontStyle_Bold;
		else if(stricmp(aStyleStr.c_str(),"Italic")==0)
			aStyle |= FontStyle_Italic;
		else if(stricmp(aStyleStr.c_str(),"Plain")==0)
			aStyle |= FontStyle_Plain;
		else if(stricmp(aStyleStr.c_str(),"Underline")==0)
			aStyle |= FontStyle_Underline;
		else 
			throw ConfigObjectException("Unknown font style: " + aStyleStr);
	}
	
	return aStyle;
}
SoundPtr ResourceConfig::SafeReadSound(StringParser &theVal)
{
	theVal.SkipWhitespace();
	
	SoundDescriptor aDesc;
	std::string aName;
	if(theVal.GetChar()=='(')
	{
		theVal.IncrementPos();
		theVal.ReadString(aName); EnsureComma(theVal);
		int aFlags = 0;
		while(true)
		{
			std::string aFlagStr;
			theVal.ReadString(aFlagStr,true);
			if(aFlagStr.empty())
				break;

			if(stricmp(aFlagStr.c_str(),"Preload")==0)
				aFlags |= SoundFlag_Preload;
			else if(stricmp(aFlagStr.c_str(),"Music")==0)
				aFlags |= SoundFlag_Music;
			else if(stricmp(aFlagStr.c_str(),"Muted")==0)
				aFlags |= SoundFlag_Muted;
			else 
				throw ConfigObjectException("Unknown sound flag: " + aFlagStr);
		}

		aDesc.SetSoundFlags(aFlags,true);
		EnsureCloseParen(theVal);
	}
	else
		theVal.ReadString(aName);

	aDesc.mFilePath = ComponentConfig::GetResourceFile(aName);

	SoundPtr aSound = WindowManager::GetDefaultWindowManager()->DecodeSound(aDesc);
	if(aSound.get()==NULL)
		throw ConfigObjectException("Failed to decode sound: " + aDesc.mFilePath);

	return aSound;
}
Exemple #21
0
    int ExprParser::parseArguments (const std::string& arguments, Scanner& scanner,
        std::vector<Interpreter::Type_Code>& code)
    {
        bool optional = false;
        int optionalCount = 0;

        ExprParser parser (getErrorHandler(), getContext(), mLocals, mLiterals, true);
        StringParser stringParser (getErrorHandler(), getContext(), mLiterals);

        std::stack<std::vector<Interpreter::Type_Code> > stack;

        for (std::string::const_iterator iter (arguments.begin()); iter!=arguments.end();
            ++iter)
        {
            if (*iter=='/')
            {
                optional = true;
            }
            else if (*iter=='S' || *iter=='c' || *iter=='x')
            {
                stringParser.reset();

                if (optional || *iter=='x')
                    stringParser.setOptional (true);

                if (*iter=='c') stringParser.smashCase();
                scanner.scan (stringParser);

                if (optional && stringParser.isEmpty())
                    break;

                if (*iter!='x')
                {
                    std::vector<Interpreter::Type_Code> tmp;
                    stringParser.append (tmp);

                    stack.push (tmp);

                    if (optional)
                        ++optionalCount;
                }
            }
            else
            {
                parser.reset();

                if (optional || *iter == 'X')
                    parser.setOptional (true);

                scanner.scan (parser);

                if (optional && parser.isEmpty())
                    break;

                if (*iter != 'X')
                {
                    std::vector<Interpreter::Type_Code> tmp;

                    char type = parser.append (tmp);

                    if (type!=*iter)
                        Generator::convert (tmp, type, *iter);

                    stack.push (tmp);

                    if (optional)
                        ++optionalCount;
                }
            }
        }

        while (!stack.empty())
        {
            std::vector<Interpreter::Type_Code>& tmp = stack.top();

            std::copy (tmp.begin(), tmp.end(), std::back_inserter (code));

            stack.pop();
        }

        return optionalCount;
    }
Exemple #22
0
bool Configuration::Load(char * data, int size)
{
	TextFileStream textFileStream(data,size);
	TokenizerStream streamIterator(textFileStream);
	streamIterator.Separators.Append(new Path("\r"));
	streamIterator.Separators.Append(new Path("\n"));

	System::Section * section = 0;
	Iterand< Reason::Structure::Mapped<String,String> > iterand;

	bool continued=false;
	for (streamIterator.Forward();streamIterator.Has();streamIterator.Move())
	{

		StringParser parser;
		parser.Assign(*streamIterator());
		parser.ParseWhitespace();

		if (continued)
		{
			parser.Mark();
			while (!parser.Eof() && !parser.Is("\\")) parser.Next();
			parser.Trap();
			continued = (parser.Is("\\"))?true:false;
			iterand().Value().Append(parser.Token);
		}
		else
		if (parser.Is("#") || parser.Is("!") || parser.Is(";") || parser.Is("//"))
		{

		}
		else
		if (parser.Is("["))
		{
			parser.Mark();
			while (!parser.Eof() && !parser.Is("]"))
				parser.Next();
			parser.Trap();

			if (parser.Is("]"))
			{
				if (section) Sections.Append(section);
				section = new System::Section();

				section->Name = parser.Token;
				parser.Next();
			}
			else
			{
				OutputError("Properties::Load","Missing \"]\" after section name, line %d column %d\n",parser.Line(),parser.Column());
			}

		}
		else
		if (!parser.Eof())
		{
			parser.Mark();
			while (!parser.Eof() && !parser.IsWhitespace() && !parser.Is("="))
				parser.Next();
			parser.Trap();

			Substring name(parser.Token);

			if (parser.Is("="))
			{
				parser.Next();
				parser.Mark();
				while (!parser.Eof() && !parser.Is("\\")) parser.Next();
				parser.Trap();
				continued = (parser.Is("\\"))?true:false;

				Substring value(parser.Token);

				if (!section)
				{
					section = new System::Section();
				}

				iterand = section->Properties.Insert(name,value);
			}
			else
			{
				OutputError("Configuration::Load","Missing \"=\" after attribute name, line %d column %d\n",parser.Line(),parser.Column());
			}
		}
	}

	if (section)
		Sections.Append(section);

	return true;
}
Exemple #23
0
 void parse (StringParser& p, std::complex<F>& out) {
   size_t start = p.pos ();
   F real, imag;
   parse (p, real);
   size_t pos = p.pos ();
   p.skipWs ();
   size_t pos2 = p.pos ();
   char sign = p.read ();
   if (sign == '+' || sign == '-') {
     p.skipWs ();
     if (p.peek () == 'i' || p.peek () == 'I') {
       p.read ();
       imag = sign == '+' ? 1 : -1;
     } else {
       p.seek (pos2);
       parse (p, imag);
       p.skipWs ();
       char c = p.read ();
       if (c != 'i' && c != 'I') {
         throw ParseException (typeid (std::complex<F>), p.value (), start, p.pos () - 1, "Expected `i' oder `I' after imaginary part");
       }
     }
     out = std::complex<F> (real, imag);
   } else {
     p.seek (pos);
     out = std::complex<F> (real, 0);
   }
 }
Exemple #24
0
bool Arguments::Construct(char * data, int size)
{
	String::Construct(data,size);

	StringParser parser;
	parser.Assign(*this);
	bool error = false;
	while ( !error && !parser.Eof() )
	{
		if (parser.Is('-'))
		{
			parser.Next();
			if (parser.Is('-'))
				parser.Next();

			Path * path = new Path();
			Append(path);

			if (parser.ParseWord())
			{
				if (parser.Eof() || parser.SkipWhitespace())
				{	
					Path * name = new Path();
					Path * value = new Path();
					path->Append(name);
					path->Append(value);
					name->Assign(parser.Token);

					if (!parser.Is('-'))
					{
						parser.Mark();
						while (!parser.Eof() && !parser.IsWhitespace()) parser.Next();
						parser.Trap();

						if (!parser.Token.IsEmpty())
							value->Assign(parser.Token);
					}
				}
				else
				{
					error = true;
				}
			}
			else
			{
				error = true;
			}
		}
		else
		{
			parser.Mark();
			while (!parser.Eof() && !parser.IsWhitespace())
				parser.Next();
			parser.Trap();

			if (!parser.Token.IsEmpty())
			{
				Path * path = new Path();
				path->Assign(parser.Token);
				Append(path);
			}
		}

		if ( !error && !parser.Eof() && !parser.SkipWhitespace() && !parser.Is('-'))
			error = true;
	}

	if (error)
	{
		Release(false);
		OutputError("Arguments::Construct - Invalid token in arguments at column %d.",parser.Column());
		return false;
	}
	else
	{
		return true;
	}
}
Exemple #25
0
//returns: SyntaxError if there was an error in the uri. Or InternalServerError
QTSS_Error RTSPRequest::ParseURI(StringParser &parser)
{
    //read in the complete URL, set it to be the qtssAbsoluteURLParam
    StrPtrLen theAbsURL;

    //  RTSPRequestInterface::sPathURLStopConditions stop on ? as well as sURLStopConditions
    parser.ConsumeUntil(&theAbsURL, sURLStopConditions );

    // set qtssRTSPReqAbsoluteURL to the URL throught the path component; will be : <protocol>://<host-addr>/<path>
    this->SetVal(qtssRTSPReqAbsoluteURL, &theAbsURL);
    
    StringParser urlParser(&theAbsURL);
    
    //we always should have a slash before the uri.
    //If not, that indicates this is a full URI. Also, this could be a '*' OPTIONS request
    if ((*theAbsURL.Ptr != '/') && (*theAbsURL.Ptr != '*'))
    {
        //if it is a full URL, store the host name off in a separate parameter
        StrPtrLen theRTSPString;
        urlParser.ConsumeLength(&theRTSPString, 7); //consume "rtsp://"
        //assign the host field here to the proper QTSS param
        StrPtrLen theHost;
        urlParser.ConsumeUntil(&theHost, '/');
        fHeaderDictionary.SetVal(qtssHostHeader, &theHost);
    }
    
    // don't allow non-aggregate operations indicated by a url/media track=id
// might need this for rate adapt   if (qtssSetupMethod != fMethod && qtssOptionsMethod != fMethod && qtssSetParameterMethod != fMethod) // any method not a setup, options, or setparameter is not allowed to have a "/trackID=" in the url.
    if (qtssSetupMethod != fMethod) // any method not a setup is not allowed to have a "/trackID=" in the url.
    {
        StrPtrLenDel tempCStr(theAbsURL.GetAsCString()); 
        StrPtrLen nonaggregate(tempCStr.FindString("/trackID="));
        if (nonaggregate.Len > 0) // check for non-aggregate method and return error
            return QTSSModuleUtils::SendErrorResponse(this, qtssClientAggregateOptionAllowed, qtssMsgBadRTSPMethod, &theAbsURL);
    }

    // don't allow non-aggregate operations like a setup on a playing session
    if (qtssSetupMethod == fMethod) // if it is a setup but we are playing don't allow it
    {
        RTSPSession*  theSession =  (RTSPSession*)this->GetSession();
        if (theSession != NULL && theSession->IsPlaying())
            return QTSSModuleUtils::SendErrorResponse(this, qtssClientAggregateOptionAllowed, qtssMsgBadRTSPMethod, &theAbsURL);
    }

    //
    // In case there is no URI at all... we have to fake it.
    static char* sSlashURI = "/";
        
    //whatever is in this position in the URL must be the URI. Store that
    //in the qtssURLParam. Confused?
    UInt32 uriLen = urlParser.GetDataReceivedLen() - urlParser.GetDataParsedLen();
    if (uriLen > 0)
        this->SetVal(qtssRTSPReqURI, urlParser.GetCurrentPosition(), urlParser.GetDataReceivedLen() - urlParser.GetDataParsedLen());
    else
        //
        // This might happen if there is nothing after the host at all, not even
        // a '/'. This is legal (RFC 2326, Sec 3.2). If so, just pretend that there
        // is a '/'
        this->SetVal(qtssRTSPReqURI, sSlashURI, 1);

    // parse the query string from the url if present.
    // init qtssRTSPReqQueryString dictionary to an empty string
    StrPtrLen queryString;
    this->SetVal(qtssRTSPReqQueryString, queryString.Ptr, queryString.Len);
    
    if ( parser.GetDataRemaining() > 0 )
    {   
        if ( parser.PeekFast() == '?' )
        {       
            // we've got some CGI param
            parser.ConsumeLength(&queryString, 1); // toss '?'
            
            // consume the rest of the line..
            parser.ConsumeUntilWhitespace(&queryString);
            
            this->SetVal(qtssRTSPReqQueryString, queryString.Ptr, queryString.Len);
        }
    }
 
 
    //
    // If the is a '*', return right now because '*' is not a path
    // so the below functions don't make any sense.
    if ((*theAbsURL.Ptr == '*') && (theAbsURL.Len == 1))
    {
		this->SetValue(qtssRTSPReqFilePath, 0, theAbsURL.Ptr, theAbsURL.Len, QTSSDictionary::kDontObeyReadOnly);
		
        return QTSS_NoErr;
    }
    
    //path strings are statically allocated. Therefore, if they are longer than
    //this length we won't be able to handle the request.
    StrPtrLen* theURLParam = this->GetValue(qtssRTSPReqURI);
    if (theURLParam->Len > RTSPRequestInterface::kMaxFilePathSizeInBytes)
        return QTSSModuleUtils::SendErrorResponse(this, qtssClientBadRequest, qtssMsgURLTooLong, theURLParam);

    //decode the URL, put the result in the separate buffer for the file path,
    //set the file path StrPtrLen to the proper value
    SInt32 theBytesWritten = StringTranslator::DecodeURL(theURLParam->Ptr, theURLParam->Len,
                                                fFilePath, RTSPRequestInterface::kMaxFilePathSizeInBytes);
    //if negative, an error occurred, reported as an QTSS_Error
    //we also need to leave room for a terminator.
    if ((theBytesWritten < 0) || (theBytesWritten == RTSPRequestInterface::kMaxFilePathSizeInBytes))
    {
        return QTSSModuleUtils::SendErrorResponse(this, qtssClientBadRequest, qtssMsgURLInBadFormat, theURLParam);
    }

    // Convert from a / delimited path to a local file system path
    StringTranslator::DecodePath(fFilePath, theBytesWritten);
    
    //setup the proper QTSS param
    fFilePath[theBytesWritten] = '\0';
    //this->SetVal(qtssRTSPReqFilePath, fFilePath, theBytesWritten);
	this->SetValue(qtssRTSPReqFilePath, 0, fFilePath, theBytesWritten, QTSSDictionary::kDontObeyReadOnly);



    return QTSS_NoErr;
}
Exemple #26
0
//storage,db,table, params[bcp ~ storage/table], elapsed_time, comment([local,global],[hierarhy],[amount backuped])
//params for export files ~ amount of exported files
void makeLogRecord(const char * init, const char * params, const unsigned indexStorage, const char method,
	const double time_elapsed, const char * comment)
{
	if (indexStorage > 6) return;
	const char * methodNames[] = { "FSStorage", "SMBStorage", "FTPStorage", "MsSQLStorage",
		"PostgreSQLStorage", "SQLiteStorage", "MongoDB" };
	string rel_path = methodNames[indexStorage];
	if (!createDir(rel_path))
	{
		cout << "Can't create dir";
		return;
	}
	string method_name, method_params;
	switch (tolower(method))
	{
	case 'a':
		method_name = "add";
		method_params = d_makeWithQuotes(string(params));
		break;
	case 'g':
		method_name = "get";
		method_params = d_makeWithQuotes(string(params));
		break;
	case 'e':
		method_name = "export";
		method_params = d_makeWithQuotes(string(comment));
		comment = nullptr;
		break;
	case 'f':
	case 'i':
	{
		method_name = tolower(method) == 'f' ? "backupFull" : "backupIncremental";
		StringParser parser(params);
		method_params = mergeServerDbTable(parser);
		break;
	}
	default:
		cout << "Can't log unknown method";
		return;
	}
	StringParser parser;
	//for FSStorage
	if (!parser.initialize(init))
		parser.setServer(init);
	//1 column: storage/db/table
	string new_record = mergeServerDbTable(parser) + ',';
	//2 column: params
	new_record += method_params + ',';
	//3 column: time
	string s_time(30,'\0');
	sprintf_s(&s_time[0], 30, "%f", time_elapsed);
	s_time.resize(s_time.find('\0'));
	new_record += s_time;
	//4 column[opt]: comment
	if (comment != nullptr && strlen(comment)>0)
	{
		new_record += ',' + string(comment);
	}

	rel_path = makePathFile(rel_path, method_name + ".csv");
	ofstream f(rel_path, ofstream::app | ofstream::out);
	if (!f.is_open())
	{
		cout << "Can't create/open log file" << endl;
		return;
	}
	f.write(new_record.data(), new_record.size());
	f << endl;

}
Exemple #27
0
//throws eHTTPNoMoreData and eHTTPOutOfBuffer
QTSS_Error RTSPRequest::ParseHeaders(StringParser& parser)
{
    StrPtrLen theKeyWord;
    Bool16 isStreamOK;
    
    //Repeat until we get a \r\n\r\n, which signals the end of the headers
    
    while ((parser.PeekFast() != '\r') && (parser.PeekFast() != '\n')) 
    {
        //First get the header identifier
        
        isStreamOK = parser.GetThru(&theKeyWord, ':');
        if (!isStreamOK)
            return QTSSModuleUtils::SendErrorResponse(this, qtssClientBadRequest, qtssMsgNoColonAfterHeader, this->GetValue(qtssRTSPReqFullRequest));
                            
         theKeyWord.TrimWhitespace();
        
        //Look up the proper header enumeration based on the header string.
        //Use the enumeration to look up the dictionary ID of this header,
        //and set that dictionary attribute to be whatever is in the body of the header
        
        UInt32 theHeader = RTSPProtocol::GetRequestHeader(theKeyWord);
        StrPtrLen theHeaderVal;
		parser.ConsumeUntil(&theHeaderVal, StringParser::sEOLMask);
	
		StrPtrLen theEOL;
		if ((parser.PeekFast() == '\r') || (parser.PeekFast() == '\n'))
		{
			isStreamOK = true;
			parser.ConsumeEOL(&theEOL);
		}
		else
			isStreamOK = false;
			
		while((parser.PeekFast() == ' ') || (parser.PeekFast() == '\t'))
		{
			theHeaderVal.Len += theEOL.Len;
			StrPtrLen temp;
			parser.ConsumeUntil(&temp, StringParser::sEOLMask);
			theHeaderVal.Len += temp.Len;
			
			if ((parser.PeekFast() == '\r') || (parser.PeekFast() == '\n'))
			{
				isStreamOK = true;
				parser.ConsumeEOL(&theEOL);
			}
			else
				isStreamOK = false;			
		}

        // If this is an unknown header, ignore it. Otherwise, set the proper
        // dictionary attribute
        if (theHeader != qtssIllegalHeader)
        {
            Assert(theHeader < qtssNumHeaders);
            theHeaderVal.TrimWhitespace();
            fHeaderDictionary.SetVal(theHeader, &theHeaderVal);
        }
        if (!isStreamOK)
            return QTSSModuleUtils::SendErrorResponse(this, qtssClientBadRequest, qtssMsgNoEOLAfterHeader);
        
        //some headers require some special processing. If this code begins
        //to get out of control, we made need to come up with a function pointer table
        switch (theHeader)
        {
            case qtssSessionHeader:             ParseSessionHeader(); break;
            case qtssTransportHeader:           ParseTransportHeader(); break;
            case qtssRangeHeader:               ParseRangeHeader();     break;
            case qtssIfModifiedSinceHeader:     ParseIfModSinceHeader();break;
            case qtssXRetransmitHeader:         ParseRetransmitHeader();break;
            case qtssContentLengthHeader:       ParseContentLengthHeader();break;
            case qtssSpeedHeader:               ParseSpeedHeader();     break;
            case qtssXTransportOptionsHeader:   ParseTransportOptionsHeader();break;
            case qtssXPreBufferHeader:          ParsePrebufferHeader();break;
			case qtssXDynamicRateHeader:		ParseDynamicRateHeader(); break;
			case qtssXRandomDataSizeHeader:		ParseRandomDataSizeHeader(); break;
			case qtss3GPPAdaptationHeader:      fRequest3GPP.ParseAdpationHeader(&fHeaderDictionary); break;
			case qtss3GPPLinkCharHeader:        fRequest3GPP.ParseLinkCharHeader(&fHeaderDictionary); break;
			case qtssBandwidthHeader:           ParseBandwidthHeader(); break;
            default:    break;
        }
    }

    // Tell the session what the request body length is for this request
    // so that it can prevent people from reading past the end of the request.
    StrPtrLen* theContentLengthBody = fHeaderDictionary.GetValue(qtssContentLengthHeader);
    if (theContentLengthBody->Len > 0)
    {
        StringParser theHeaderParser(fHeaderDictionary.GetValue(qtssContentLengthHeader));
        theHeaderParser.ConsumeWhitespace();
        this->GetSession()->SetRequestBodyLength(theHeaderParser.ConsumeInteger(NULL));
    }
    
    isStreamOK = parser.ExpectEOL();
    Assert(isStreamOK);
    return QTSS_NoErr;
}
Exemple #28
0
int main (int argc, char** argv)
{
	
  StringParser sp;
	sp.setVariables({"x", "y", "z"});
	//Pol p1 = sp.parseMultivariatePolynomial<Rational>("x^2*y^4*z^5*3 + x^3*10*y^4 + 20*z^6*y^2 + 21*x^9*z^2 + 4*x*y");
	Pol p1 = sp.parseMultivariatePolynomial<Rational>("x*y + x*z + 2*x");
  //Pol p1 = sp.parseMultivariatePolynomial<Rational>("12*x +13*x^2+3*x ");
  //Pol p1 = sp.parseMultivariatePolynomial<Rational>("2184*x^17+15708*z+(-126672)*x^2+643384*z^3+(-2306444)*z^4+4162512*x^13+(-10186920)*z^12+18820800*x^11+(-27118448)*x^10+31123477*x^9+6199788*x^5+(-12956461)*x^6+21524503*x^7+(-28784511)*x^8+(-1226048)*x^14+245224*y^15+(-31192)*y^16+(-924)");


	std::set<Variable> allVarInPolynome;
	p1.gatherVariables(allVarInPolynome);
	std::map<Variable, Interval<double>> map;

	for(auto i : allVarInPolynome) {
  	  if (i.getId() == 1)
  	  {
  	  	Interval<double> ix (-2, 2);
  	  	map[i] = ix;
  	  }
  	  if (i.getId() == 2)
  	  {
  	  	Interval<double> iy (0, 1);
  	  	map[i] = iy;
  	  }
  	  if (i.getId() == 3)
  	  {
  	  	Interval<double> iz (0, 1);
  	  	map[i] = iz;
  	  }
  	}

	std::cout << "\n Polynom       :" << p1 << std::endl;

	MultivariateHorner< Pol, strategy > peterPolynom (std::move(p1));
  //MultivariateHorner< Pol, GREEDY_IIs > peterPolynom2 (p1,map);

	std::cout << "\n GREEDY_Is        :" << peterPolynom << std::endl;
  //std::cout << " GREEDY_IIs       :" << peterPolynom2 << std::endl;

	Interval<double> testInterval = IntervalEvaluation::evaluate(peterPolynom ,map);
  //Interval<Rational> testInterval2 = evaluate(peterPolynom2 , map);

	std::cout << "\n Evaluate Horner :" << testInterval << std::endl;
  //std::cout << " Evaluate Horner2:" << testInterval2 << std::endl;
  
  
  /*
  Rational u_a;
  Rational l_a;
  Rational u_b;
  Rational l_b;
  Rational u_c;
  Rational l_c;

  std::map<Variable, Interval<Rational>> map;
  VariablePool& vpool = VariablePool::getInstance();
  Variable a = vpool.getFreshVariable();
  vpool.setName(a, "a");
  Variable b = vpool.getFreshVariable();
  vpool.setName(b, "b");
  Variable c = vpool.getFreshVariable();
  vpool.setName(c, "c");

  int l = 0;
  int n = 0;

  for (int i = 1; i <= 6; i++)
  {

    switch (i) 
      {
        case 1 : l_a = -200; u_a = -100;
        break;
        case 2 : l_a = -100; u_a = 0;
        break;
        case 3 : l_a = -100; u_a = 100;
        break;
        case 4 : l_a = 0; u_a = 0;
        break;
        case 5 : l_a = 0; u_a = 100;
        break;
        case 6 : l_a = 100; u_a = 200;
        break;
      }
    for (int j = 1; j <= 6; j++)
    {
      switch (j) 
        {
          case 1 : l_b = -201; u_b = -101;
          break;
          case 2 : l_b = -101; u_b = 0;
          break;
          case 3 : l_b = -101; u_b = 101;
          break;
          case 4 : l_b = 0; u_b = 0;
          break;
          case 5 : l_b = 0; u_b = 101;
          break;
          case 6 : l_b = 101; u_b = 201;
          break;
        }
      for (int k = 1; k <= 6; k++)
      {
        switch (k) 
        {
          case 1 : l_c = -202; u_c = -102;
          break;
          case 2 : l_c = -102; u_c = 0;
          break;
          case 3 : l_c = -102; u_c = 102;
          break;
          case 4 : l_c = 0; u_c = 0;
          break;
          case 5 : l_c = 0; u_c = 102;
          break;
          case 6 : l_c = 102; u_c = 202; 
          break;
        }

        Interval<Rational> ia( l_a, u_a );
        Interval<Rational> ib( l_b, u_b );
        Interval<Rational> ic( l_c, u_c );

        Interval<Rational> iR1 = ib + ic;
        iR1 *= ia;

        Interval<Rational> iR2 = ia * ib;
        Interval<Rational> iR3 = ia * ic;
        iR2 += iR3;

        //std::cout << "[" << i << j << k << "] : "<< iR1 << " - " << iR2;
        n++;
        //std::cout << n;
        if (iR1.diameter() < iR2.diameter()) {
          l++;
          //std::cout << "[" << i << j << k << "] : "<< iR1 << " - " << iR2;
          
          std::cout << l << " &   $";

          switch (i) 
          {
            case 1 : std::cout << "a_1 < a_2 < 0";
            break;
            case 2 : std::cout << "a_1 < a_2 = 0";
            break;
            case 3 : std::cout << "a_1 < 0 < a_2";
            break;
            case 4 : std::cout << "a_1 = a_2 = 0";
            break;
            case 5 : std::cout << "a_1 = 0 < a_2";
            break;
            case 6 : std::cout << "0 < a_1 < a_2";
            break;
          }

          std::cout << " $ &  $ ";

          switch (j) 
          {
            case 1 : std::cout << "b_1 < b_2 < 0";
            break;
            case 2 : std::cout << "b_1 < b_2 = 0";
            break;
            case 3 : std::cout << "b_1 < 0 < b_2";
            break;
            case 4 : std::cout << "b_1 = b_2 = 0";
            break;
            case 5 : std::cout << "b_1 = 0 < b_2";
            break;
            case 6 : std::cout << "0 < b_1 < b_2";
            break;
          }

          std::cout << "$  &  $";

          switch (k) 
          {
            case 1 : std::cout << "c_1 < c_2 < 0";
            break;
            case 2 : std::cout << "c_1 < c_2 = 0";
            break;
            case 3 : std::cout << "c_1 < 0 < c_2";
            break;
            case 4 : std::cout << "c_1 = c_2 = 0";
            break;
            case 5 : std::cout << "c_1 = 0 < c_2";
            break;
            case 6 : std::cout << "0 < c_1 < c_2";
            break;
          }


          std::cout << " $ \\\\ " << std::endl;
        }
        if (iR1.diameter() == iR2.diameter()) {
          //std::cout << "& SAME" << std::endl;
        }
        if (iR1.diameter() > iR2.diameter()) {
          // std::cout << "& GREATER" << std::endl;
        }


        assert (iR1 == iR2);


      }
    }
  }
*/
} 
int ResourceConfig::SafeReadColor(StringParser &theVal)
{
	theVal.SkipWhitespace();
	if(theVal.GetChar()=='(')
	{
		// special color (std or dec)
		std::string aType;
		theVal.IncrementPos();
		theVal.ReadString(aType);
		int aColor = 0;
		if(stricmp(aType.c_str(),"STD")==0) // standard color
		{
			EnsureComma(theVal);
			std::string aName;
			theVal.ReadString(aName); 
			const char *aPtr = aName.c_str();

			if(stricmp(aPtr,"3DDarkShadow")==0) aColor = ColorScheme::GetColorRef(StandardColor_3DDarkShadow); 
			else if(stricmp(aPtr,"3DFace")==0) aColor = ColorScheme::GetColorRef(StandardColor_3DFace); 
			else if(stricmp(aPtr,"3DHilight")==0) aColor = ColorScheme::GetColorRef(StandardColor_3DHilight); 
			else if(stricmp(aPtr,"3DShadow")==0) aColor = ColorScheme::GetColorRef(StandardColor_3DShadow); 
			else if(stricmp(aPtr,"Scrollbar")==0) aColor = ColorScheme::GetColorRef(StandardColor_Scrollbar); 
			else if(stricmp(aPtr,"ButtonText")==0) aColor = ColorScheme::GetColorRef(StandardColor_ButtonText); 
			else if(stricmp(aPtr,"GrayText")==0) aColor = ColorScheme::GetColorRef(StandardColor_GrayText); 
			else if(stricmp(aPtr,"Hilight")==0) aColor = ColorScheme::GetColorRef(StandardColor_Hilight); 
			else if(stricmp(aPtr,"HilightText")==0) aColor = ColorScheme::GetColorRef(StandardColor_HilightText); 
			else if(stricmp(aPtr,"ToolTipBack")==0) aColor = ColorScheme::GetColorRef(StandardColor_ToolTipBack); 
			else if(stricmp(aPtr,"ToolTipText")==0) aColor = ColorScheme::GetColorRef(StandardColor_ToolTipText); 
			else if(stricmp(aPtr,"MenuBack")==0) aColor = ColorScheme::GetColorRef(StandardColor_MenuBack); 
			else if(stricmp(aPtr,"MenuText")==0) aColor = ColorScheme::GetColorRef(StandardColor_MenuText); 
			else if(stricmp(aPtr,"Back")==0) aColor = ColorScheme::GetColorRef(StandardColor_Back); 
			else if(stricmp(aPtr,"Text")==0) aColor = ColorScheme::GetColorRef(StandardColor_Text); 
			else if(stricmp(aPtr,"Link")==0) aColor = ColorScheme::GetColorRef(StandardColor_Link); 
			else if(stricmp(aPtr,"LinkDown")==0) aColor = ColorScheme::GetColorRef(StandardColor_LinkDown); 
			else
				throw ConfigObjectException("Invalid standard color: " + aType);
		}
		else if(stricmp(aType.c_str(),"DEC")==0)
		{
			EnsureComma(theVal); 
			int r,g,b;
			theVal.ReadValue(r); EnsureComma(theVal);
			theVal.ReadValue(g); EnsureComma(theVal);
			theVal.ReadValue(b); 
			aColor = ((r&0xff)<<16) | ((g&0xff)<<8) | (b&0xff);
		}

		EnsureCloseParen(theVal);
		return aColor;
	}

	int aColor = 0;
	for(int i=0; i<6; i++)
	{
		aColor<<=4;
		int aDigit = ResourceConfig_GetHexDigit(theVal.GetChar());
		if(aDigit<0)
			throw ConfigObjectException("Invalid color specification.");

		aColor |= aDigit;
		theVal.IncrementPos();
	}
	
	return aColor;
}
void ResourceConfig::EnsureCloseParen(StringParser &theVal)
{
	if(!theVal.CheckNextChar(')'))
		throw ConfigObjectException("Expecting ')'");
}