void RequestTest::setUp( void )
{
  _req = 0;
  _type.clear();
  _size = 0;
  _body.clear();
}
Example #2
0
	void defaults (void)
	{
		title.clear();
		err.clear();
		line = col = fileMatch = -1;
		searchCol = false;
	}
Example #3
0
bool Path::CreateDirRecursive(String path)
{
	String path1;
	while(!path.empty())
	{
		String segment = path;
		size_t offset = path.find(Path::sep);
		if(offset != -1)
		{
			segment = path.substr(0, offset);
			if(path.size() > (offset + 1))
				path = path.substr(offset + 1);
			else
				path.clear();
		}
		else
		{
			path.clear();
		}

		if(!path1.empty())
			path1 += Path::sep;
		path1 += segment;

		// Create if not existing
		if(IsDirectory(path1) || path1.empty())
			continue;
		if(!CreateDir(path1))
			return false;
	}

	return true;
}
Example #4
0
String
strutil_findurl(String& str, String& url)
{
   static URLDetector s_detector;

   // the return value: the part of the text before the URL
   String before;

   int len;
   int pos = s_detector.FindURL(str, len);

   if ( pos == -1 )
   {
      // no URLs found
      str.swap(before);
      str.clear();
      url.clear();
   }
   else // found an URL
   {
      before = str.substr(0, pos);
      url = str.substr(pos, len);

      str.erase(0, pos + len);
   }

   return before;
}
Example #5
0
	void defaults (void)
	{
		title.clear(); cmd.clear(); compiler.clear();
		enable.clear(); disable.clear();
		saveType = saCurrent;
		jumpType = jtSmart;
		cd = cdNone;
		searchBase = false;
		echo = true;
	}
void Document::loadFileToString( const String& file_name_, String &buffer_ )
{
	FRL_EXCEPT_GUARD();
	if( ! fs::exists( file_name_ ) )
		FRL_THROW_S_CLASS( Document::FileNotFound );
	size_t length = static_cast< size_t >( fs::file_size( file_name_ ) );
	if( length == 0 )
		FRL_THROW_S_CLASS( Document::EmptyFile );
	if( ! buffer_.empty() )
		buffer_.clear();

	static const size_t buffer_size = 4096;
	stream_std::InFile in( file_name_.c_str(), std::ios::binary );
	if( ! in.is_open() )
		FRL_THROW_S_CLASS( Document::UnknownError );
	std::vector< Char > buf( buffer_size );

	buffer_.reserve( length );
	while( in )
	{
		in.read( &buf[ 0 ], buffer_size );
		buffer_.append( &buf[ 0 ], in.gcount() );
	}
	in.close();
}
Example #7
0
	StringList String::split(String splitBy, int limitCount){
		StringList MyStrList;
		unsigned int Iter = 0;
		String MyStr = *this;
		String Current;

		for(unsigned int i = 0; i < MyStr.length(); i++){
			if(MyStr[i] == splitBy[Iter]){
				Iter++;
			}
			else{
				//Break a partial match
				Iter = 0;
			}

			Current += MyStr[i];

			if(Iter == splitBy.length()){
				if(limitCount != 0 && MyStrList.size() == limitCount)
					continue;
				Current.erase(Current.length() - Iter, Current.length());
				MyStrList.push_back(Current);
				Current.clear();
				Iter = 0; 
			}
		}
		Current.erase(Current.length() - Iter, Current.length());
		MyStrList.push_back(Current);

		return MyStrList;

	};
Example #8
0
int String::nextToken(const char* szSep, String& sPart)
{
  if (empty()) { return 0; } // do nothing

  int bFound = 0;

  const char* pSep = findChar(szSep);
  if (pSep != 0) {
    sPart.append(szStr_, pSep - szStr_, 1);
    String sRemain;
    sRemain.append(pSep, nBytes_ - (pSep - szStr_));
    const char* pNext = sRemain.findNotChar(szSep);
    if (pNext == 0) {
      clear();
    } else {
      append(pNext, sRemain.bytes() - (pNext - sRemain.c_str()), 1);
    }
    bFound = 1;
  } else {
    if (nBytes_ > 0) {
      sPart = szStr_;
      clear();
      bFound = 1;
    } else {
      sPart.clear();
    }
  }

  return bFound;
}
Boolean FileSystem::existsNoCase(const String& path, String& realPath)
{
#if !defined(PEGASUS_OS_VMS) && \
    !defined(PEGASUS_OS_TYPE_WINDOWS) && \
    !defined(PEGASUS_OS_DARWIN)

    // If a file exists that has the same case as the path parmater,
    // then we can bypass the expensive directory scanning below.

    if (FileSystem::exists(path))
    {
        realPath = path;
        return true;
    }

#endif

    realPath.clear();
    CString cpath = _clonePath(path);
    const char* p = cpath;

    const char* dirPath;
    const char* fileName;
    char* slash = (char *) strrchr(p, '/');

    if (slash)
    {
        *slash = '\0';
        fileName = slash + 1;
        dirPath = p;

        if (*fileName == '\0')
            return false;
    }
    else
    {
        fileName = p;
        dirPath = ".";
    }


    for (Dir dir(dirPath); dir.more(); dir.next())
    {
        if (System::strcasecmp(fileName, dir.getName()) == 0)
        {
            if (strcmp(dirPath, ".") == 0)
                realPath = dir.getName();
            else
            {
                realPath = dirPath;
                realPath.append('/');
                realPath.append(dir.getName());
            }
            return true;
        }
    }

    return false;
}
Example #10
0
Boolean FileSystem::getCurrentDirectory(String& path)
{
    path.clear();
    char tmp[4096];

    if (!System::getCurrentDirectory(tmp, sizeof(tmp) - 1))
        return false;

    path.append(tmp);
    return true;
}
Example #11
0
	static const String& QuotePath(const StringT& value)
	{
		static String s;
		# ifndef YUNI_OS_WINDOWS
		s = value;
		s.replace(" ", "\\ ");
		# else
		s.clear();
		s << '"' << value << '"';
		# endif
		return s;
	}
Example #12
0
String String::filenameExtension(const char* szText)
{
  String sExt;
  String sText = szText;
  if (sText.findChar(".")) {
    sText.reverseToken(".", sExt);
    if (sText.empty()) {
      sExt.clear();
    }
  }
  return sExt;
}
bool BufferedReader::readLine(String& line) {
    line.clear();
    wchar_t ch = (wchar_t)read();
    while (ch != (wchar_t)READER_EOF && ch != L'\r' && ch != L'\n') {
        line += ch;
        ch = (wchar_t)read();
    }
    if (ch == '\r' && (wchar_t)peek() == L'\n') {
        read();
    }
    return (!line.empty() || ch != (wchar_t)READER_EOF);
}
Example #14
0
	bool TextReader::readLine(String& str)
	{
		if (pImpl->eof())
		{
			return false;
		}

		str.clear();

		pImpl->readLine(str);

		return true;
	}
Example #15
0
void URI::parsePath(const String& path,
                    /* out */ String& dir,
                    /* out */ String& baseName,
                    /* out */ String& extension) {
    // !!!steveT Currently, if we have a file name that begins with a '.', as in
    // ".emacs", that will be treated as having no base name with an extension
    // of ".emacs". We might want to change this behavior, so that the base name
    // is considered ".emacs" and the extension is empty. I think this is more
    // in line with what path parsers in other libraries/languages do, and it
    // more accurately reflects the intended structure of the file name.

    // The following implementation cannot handle paths like this:
    // /tmp/se.3/file
    //static pcrecpp::RE re("(.*/)?([^.]*)?(\\..*)?");
    //dir = baseName = extension = "";
    //re.FullMatch(path, &dir, &baseName, &extension);


    static boost::regex findDir("(.*/)?(.*)?");
    static boost::regex findExt("([^.]*)?(\\.(.*))?");
    String tmpFile;
    dir.clear();
    baseName.clear();
    extension.clear();
    boost::smatch dirMatches;
    if(regex_match(path, dirMatches, findDir))
    {
        setStringFromMatches(dir, dirMatches, 1);
        setStringFromMatches(tmpFile, dirMatches, 2);

        boost::smatch extMatches;
        if(regex_match(tmpFile, extMatches, findExt))
        {
            setStringFromMatches(baseName, extMatches, 1);
            setStringFromMatches(extension, extMatches, 3);
        }
    }
}
Example #16
0
String Path::RemoveBase(String path, String base)
{
	size_t targetOffset = 0;
	while(!base.empty())
	{
		size_t offset = base.find(sep);
		String segment = base;
		if(offset != -1)
		{
			// Cut off folder part
			segment = base.substr(0, offset);
			if(path.size() > (offset + 1))
				base = base.substr(offset + 1);
			else
				base.clear();
		}
		else
		{
			base.clear();
		}

		if(path.compare(targetOffset, segment.size(), segment) == 0)
		{
			if(path.size() > (segment.size()+ targetOffset))
			{
				char followingChar = path[targetOffset+segment.size()];
				if(followingChar != sep && followingChar != '.')
					break;
				targetOffset += 1;
			}
			targetOffset += segment.size();
		}
		else
			break;
	}
	return path.substr(targetOffset);
}
Example #17
0
int String::replaceCore(StringPair* pTable, bool bReverse)
{
  int nReplaced = 0;
  String sNew;
  String sToken;

  const char* szSrc = c_str();
  while (*szSrc != '\0') {
    unsigned int nCharLen = UTF8_CharSize(szSrc);
    if (nCharLen == 0) {
      // Not a start character: skip
      nCharLen = 1;
    }
    sToken.append(szSrc, nCharLen);
    szSrc += nCharLen;
    int nMatch = String_replaceMatch(pTable, sToken, bReverse);
    switch (nMatch) {
      case String_Escape_Match_none:
        sNew += sToken;
        sToken.clear();
        break;
      case String_Escape_Match_partial:
        break;
      default:
        nReplaced++;
        sToken.clear();
        if (bReverse) {
          sNew += pTable[nMatch].szLeft;
        } else {
          sNew += pTable[nMatch].szRight;
        }
    }
  }

  append(sNew.c_str(), sNew.bytes(), 1);
  return nReplaced;
}
Example #18
0
bool readFile(const Path& path, String& data)
{
    FILE* f = fopen(path.nullTerminated(), "r");
    if (!f)
        return false;
    const int sz = fileSize(f);
    if (!sz) {
        data.clear();
        return true;
    }
    data.resize(sz);
    const int r = fread(data.data(), sz, 1, f);
    fclose(f);
    return (r == 1);
}
StringList_struct* loadCompilerWarningList()
{
	String fileContents;
	String filePath = (String)FileTools_getExecutableDirectory() + "/CompilerWarnings.txt";
	
	if(!FileTools::loadFileIntoString(filePath, fileContents))
	{
		return NULL;
	}
	
	String currentLine;
	ArrayList<String>* lines = new ArrayList<String>();
	
	for(int i=0; i<fileContents.length(); i++)
	{
		char c = fileContents.charAt(i);
		if(c<' ')
		{
			if(currentLine.length()>0)
			{
				lines->add(currentLine);
				currentLine.clear();
			}
		}
		else
		{
			currentLine += c;
		}
	}
	
	fileContents.clear();
	
	StringList_struct* list = new StringList_struct();
	list->data = (void*)lines;
	return list;
}
Example #20
0
int String::reverseToken(const char* szSep, String& sPart)
{
  if (empty()) { return 0; } // do nothing

  int bFound = 0;
  String sSep = szSep;

  const char* p = szStr_ + nBytes_;
  int bDone = 0;
  if (p <= szStr_) {
    sPart.clear();
    // !found
  } else {
    do {
      p--;
      if (UTF8_CharSize(p)) {
        if (sSep.findChar(UTF8_Char(p)) != 0) {
          p += UTF8_CharSize(p);
          bDone = 1;
        }
      }
    } while (p > szStr_ && !bDone);
    sPart = p;
    bFound = !sPart.empty();
  }

  const char* q = p;
  bDone = 0;
  if (q <= szStr_) {
    clear();
  } else {
    do {
      q--;
      if (UTF8_CharSize(q)) {
        if (sSep.findChar(UTF8_Char(q)) == 0) {
          q += UTF8_CharSize(q);
          bDone = 1;
        }
      }
    } while (q > szStr_ && !bDone);
    String sTmp;
    sTmp.append(szStr_, q - szStr_);
    append(sTmp.c_str(), sTmp.bytes(), 1);
  }

  return bFound;
}
Example #21
0
void Keyword::prepare(const vector<KeywordParamP>& param_types, bool force) {
	if (!force && !match_re.empty()) return;
	parameters.clear();
	// Prepare regex
	String regex;
	String text; // normal, non-regex, text
	#if USE_CASE_INSENSITIVE_KEYWORDS
		regex = _("(?i)"); // case insensitive matching
	#endif
	// Parse the 'match' string
	for (size_t i = 0 ; i < match.size() ;) {
		Char c = match.GetChar(i);
		if (is_substr(match, i, _("<atom-param"))) {
			// parameter, determine type...
			size_t start = skip_tag(match, i), end = match_close_tag(match, i);
			String type = match.substr(start, end-start);
			// find parameter type 'type'
			KeywordParamP param;
			FOR_EACH_CONST(pt, param_types) {
				if (pt->name == type) {
					param = pt;
					break;
				}
			}
			if (!param) {
				// throwing an error can mean a set will not be loaded!
				// instead, simply disable the keyword
				//throw InternalError(_("Unknown keyword parameter type: ") + type);
				handle_error(_("Unknown keyword parameter type: ") + type);
				valid = false;
				return;
			}
			parameters.push_back(param);
			// modify regex : match text before
			param->compile();
			// remove the separator from the text to prevent duplicates
			param->eat_separator_before(text);
			regex += _("(") + regex_escape(text) + _(")");
			text.clear();
			// modify regex : match parameter
			regex += _("(") + make_non_capturing(param->match) + (param->optional ? _(")?") : _(")"));
			i = skip_tag(match, end);
			// eat separator_after?
			param->eat_separator_after(match, i);
		} else {
Example #22
0
//------------------------------------------------------------------------------
// FUNCTION: getHostAddress
//
// REMARKS: Resolves address servers
//
// PARAMETERS:  [IN] serverName     -> string containing the name server
//                [OUT] serverAddress -> string that will contain the IP server
//
// RETURN: TRUE if valid host name, FALSE otherwise
//------------------------------------------------------------------------------
Boolean NTPService::getHostAddress(String serverName, String & serverAddress) 
{
    Boolean ok = false;
    int ps, value = 0;
    String strValue;
    struct hostent *host;
    struct in_addr ia;
    
    serverAddress.clear();
    host = gethostbyname(serverName.getCString());
    if(host != NULL) 
    {
        ia = *(struct in_addr *)(host->h_addr);
        serverAddress.assign(inet_ntoa(ia));
        ok = true;
    }
    return ok;
}    
Example #23
0
bool FileHelper::ReadAllText(const String & fileName, String & content)
{
    Handle hFile = CreateFileW(StringUtils::Utf8ToUtf16(fileName).c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
    if(hFile == INVALID_HANDLE_VALUE)
        return false;
    unsigned int filesize = GetFileSize(hFile, 0);
    if(!filesize)
    {
        content.clear();
        return true;
    }
    Memory<char*> filedata(filesize + 1, "FileReader::ReadAllText:filedata");
    DWORD read = 0;
    if(!ReadFile(hFile, filedata(), filesize, &read, 0))
        return false;
    content = String(filedata());
    return true;
}
      //-----------------------------------------------------------------------
      size_t HTTP::HTTPQuery::readDataAsString(String &outResultData)
      {
        outResultData.clear();

        AutoRecursiveLock lock(*this);
        CryptoPP::lword available = mBody.MaxRetrievable();
        if (0 == available) return 0;

        SecureByteBlock data;
        data.CleanNew(static_cast<SecureByteBlock::size_type>(available));
        mBody.Get(data.BytePtr(), static_cast<size_t>(available));

        outResultData = (const char *)data.BytePtr();
        auto result = strlen(outResultData);
        ZS_EVENTING_2(
                      x, i, Debug, ServicesHttpQueryReadAsString, os, Http, Receive,
                      puid, id, mID,
                      string, result, outResultData
                      );
        return result;
      }
Example #25
0
    //-----------------------------------------------------------------------
    void StringUtil::splitFilename(const String& qualifiedName, 
        String& outBasename, String& outPath)
    {
        String path = qualifiedName;
        // Replace \ with / first
        std::replace( path.begin(), path.end(), '\\', '/' );
        // split based on final /
        size_t i = path.find_last_of('/');

        if (i == String::npos)
        {
            outPath.clear();
			outBasename = qualifiedName;
        }
        else
        {
            outBasename = path.substr(i+1, path.size() - i - 1);
            outPath = path.substr(0, i+1);
        }

    }
Example #26
0
//------------------------------------------------------------------------------
// FUNCTION: getHostName
//
// REMARKS: Resolves name servers
//
// PARAMETERS:  [IN] serverAddress -> string containing the IP address
//                [OUT] hostName -> string that will contain the name server
//
// RETURN: TRUE if valid host IP, FALSE otherwise
//------------------------------------------------------------------------------
Boolean NTPService::getHostName(String serverAddress, String & hostName) 
{
    Boolean ok = false;
    int ps, value = 0;
    String strValue;
    struct hostent *host;
    struct in_addr ia;
    
    hostName.clear();
    if((ia.s_addr = inet_addr(serverAddress.getCString())) != -1) 
    {
        host = gethostbyaddr((const char *)&ia, 
                              sizeof(struct in_addr),
                               AF_INET);
        if(host != NULL) 
        {
            hostName.assign(host->h_name);
            ok = true;
        }
   }
   return ok;
}    
Example #27
0
bool CHttpServer::parse_startline(String const &line, String &method, String &uri, String &query)
{
    const char *s, *e;
    
    // Find first space
    for(s = line.c_str(), e = s; *e != ' ' && *e != '\0'; ++e);
    if (*e == '\0') {
        RAWLOG_ERROR1("Parse startline (1): syntax error: \"%s\"", line.c_str());
        return false;
    }
    
    method.assign(s, e);
    
    // Skip spaces
    for(s = e; *s == ' '; ++s);
    
    for(e = s; *e != '?' && *e != ' ' && *e != '\0'; ++e);
    if (*e == '\0') {
        RAWLOG_ERROR1("Parse startline (2): syntax error: \"%s\"", line.c_str());
        return false;
    }
    
    uri.assign(s, e);
    uri = URI::urlDecode(uri);
    
    query.clear();
    if (*e == '?') {
        s = ++e;
        for(e = s; *e != ' ' && *e != '\0'; ++e);
        if (*e != '\0')
            query.assign(s, e);
    }

    const char* frag = strrchr(uri.c_str(), '#');
    if (frag)
        uri = uri.substr(0, frag-uri.c_str());

    return true;
}
Example #28
0
void MultipleChoiceValue::normalForm() {
	String val = value->toString();
	// which choices are active?
	vector<bool> seen(field().choices->lastId());
	for (size_t pos = 0 ; pos < val.size() ; ) {
		if (val.GetChar(pos) == _(' ')) {
			++pos; // ingore whitespace
		} else {
			// does this choice match the one asked about?
			size_t end = val.find_first_of(_(','), pos);
			if (end == String::npos) end = val.size();
			// find this choice
			for (size_t i = 0 ; i < seen.size() ; ++i) {
				if (is_substr(val, pos, field().choices->choiceName((int)i))) {
					seen[i] = true;
					break;
				}
			}
			pos = end + 1;
		}
	}
	// now put them back in the right order
	val.clear();
	for (size_t i = 0 ; i < seen.size() ; ++i) {
		if (seen[i]) {
			if (!val.empty()) val += _(", ");
			val += field().choices->choiceName((int)i);
		}
	}
	// empty choice name
	if (val.empty()) {
		val = field().empty_choice;
	}
	// store
	value = with_defaultness_of(value, to_script(val));
}
Example #29
0
void Database::Statement::value(int column, String &v) const
{
	const char *text = reinterpret_cast<const char*>(sqlite3_column_text(mStmt, column));
	if(text) v = text;
	else v.clear();
}
//==============================================================================
void JucerDocument::fillInGeneratedCode (GeneratedCode& code) const
{
    code.className = className;
    code.componentName = componentName;
    code.parentClasses = parentClasses;
    code.constructorParams = constructorParams;
    code.initialisers.addLines (variableInitialisers);

    if (! componentName.isEmpty())
        code.constructorCode << "setName (" + quotedString (componentName, false) + ");\n";

    // call these now, just to make sure they're the first two methods in the list.
    code.getCallbackCode (String::empty, "void", "paint (Graphics& g)", false)
        << "//[UserPrePaint] Add your own custom painting code here..\n//[/UserPrePaint]\n\n";

    code.getCallbackCode (String::empty, "void", "resized()", false)
        << "//[UserPreResize] Add your own custom resize code here..\n//[/UserPreResize]\n\n";

    if (ComponentLayout* l = getComponentLayout())
        l->fillInGeneratedCode (code);

    fillInPaintCode (code);

    ScopedPointer<XmlElement> e (createXml());
    jassert (e != nullptr);
    code.jucerMetadata = e->createDocument ("", false, false);

    resources.fillInGeneratedCode (code);

    code.constructorCode
        << "\n//[UserPreSize]\n"
           "//[/UserPreSize]\n";

    if (initialWidth > 0 || initialHeight > 0)
        code.constructorCode << "\nsetSize (" << initialWidth << ", " << initialHeight << ");\n";

    code.getCallbackCode (String::empty, "void", "paint (Graphics& g)", false)
        << "//[UserPaint] Add your own custom painting code here..\n//[/UserPaint]";

    code.getCallbackCode (String::empty, "void", "resized()", false)
        << "//[UserResized] Add your own custom resize handling here..\n//[/UserResized]";

    // add optional methods
    StringArray baseClasses, returnValues, methods, initialContents;
    getOptionalMethods (baseClasses, returnValues, methods, initialContents);

    for (int i = 0; i < methods.size(); ++i)
    {
        if (isOptionalMethodEnabled (methods[i]))
        {
            String baseClassToAdd (baseClasses[i]);

            if (baseClassToAdd == "Component" || baseClassToAdd == "Button")
                baseClassToAdd.clear();

            String& s = code.getCallbackCode (baseClassToAdd, returnValues[i], methods[i], false);

            if (! s.contains ("//["))
            {
                String userCommentTag ("UserCode_");
                userCommentTag += methods[i].upToFirstOccurrenceOf ("(", false, false).trim();

                s << "\n//[" << userCommentTag << "] -- Add your code here...\n"
                  << initialContents[i];

                if (initialContents[i].isNotEmpty() && ! initialContents[i].endsWithChar ('\n'))
                    s << '\n';

                s << "//[/" << userCommentTag << "]\n";
            }
        }
    }
}