Пример #1
0
//-----------------------------------------------------------------------------------------------------------------------------------------------------
VOID Configuration::LoadConfigFile(LPCTSTR Filename)
{
  TextStream T(File::Open(Filename, FileMode::OPEN));

  while(!T.EndOfStream())
  {
    String L = T.ReadLine();
    if (L.BeginsWith("#"))
      continue;

    String::Iterator i = L.Find('=');
    if (i != L.End())
    {
      String Name = L.Substr(L.Begin(), i);
      String Value = L.Substr(i+1, L.End());

      if (m_Schema.Contains(Name))
      {
        Item I = m_Schema.Get(Name);
        if ((I.m_Source & ConfigurationSource::FILE) == 0)
          continue;
        I.m_Present = TRUE;
      }

      m_ConfigValues.Add(Name,Value);
    }
  }
}
Пример #2
0
bool Contains(const String& text, const String& substr)
{
	for(const char *s = text; s <= text.End() - substr.GetLength(); s++)
		if(strncmp(s, substr, substr.GetLength()) == 0)
			return true;
	return false;
}
Пример #3
0
void EscapeHtml(StringBuffer& out, const String& txt)
{
	const char *s = txt;
	const char *e = txt.End();
	while(s != e) {
		if(*s == 31)
			out.Cat("&nbsp;");
		else
		if(*s == '<')
			out.Cat("&lt;");
		else
		if(*s == '>')
			out.Cat("&gt;");
		else
		if(*s == '&')
			out.Cat("&amp;");
		else
		if(*s == '\"')
			out.Cat("&quot;");
		else
		if((byte)*s < ' ')
			out.Cat(NFormat("&#%d;", (byte)*s));
		else
			out.Cat(*s);
		s++;
	}
}
Пример #4
0
bool SpellWordRaw(const WString& wrd, int lang, Vector<String> *withdia)
{
	Speller *f = sGetSpeller(lang);
	if(!f)
		return true;
	if(f->data.GetCount())
		return f->CheckOld(wrd);
	String awrd = ToUpper(ToAscii(wrd).ToString());
	String t1 = ToUtf8(wrd);
	String t2 = ToUtf8(ToLower(wrd));
	for(int i = 0;; i++) {
		if(i + 1 >= f->block.GetCount() || awrd <= f->block[i + 1].first) {
			for(;;) {
				if(i >= f->block.GetCount())
					return f->user.Find(wrd) >= 0;;
				LLOG("Spell block " << i << ": " << f->block[i].first);
				const SpellBlock& b = f->block[i++];
				if(b.first > awrd) {
					LLOG("  --- end");
					return f->user.Find(wrd) >= 0;;
				}
				FileIn in(f->path);
				String ctrl = sZet(in, b.offset, b.ctrl_len);
				String text = sZet(in, b.offset + b.ctrl_len, b.text_len);
				in.Close();
				String w;
				const char *s = ctrl;
				const char *e = ctrl.End();
				const char *t = text;
				const char *te = text.End();
				while(s < e && t < te) {
					w.Trim(*s++);
					while(*t)
						w.Cat(*t++);
					if(w == t1 || w == t2)
						return true;
					if(withdia && t2 == ToLower(ToAscii(w.ToWString()).ToString()))
						withdia->Add(w);
					t++;
				}
			}
		}
	}
	return f->user.Find(wrd) >= 0;;
}
Пример #5
0
void JSONValue::WriteJSONString(String& dest, const String& str)
{
    dest += '\"';
    
    for (String::ConstIterator it = str.Begin(); it != str.End(); ++it)
    {
        char c = *it;
        
        if (c >= 0x20 && c != '\"' && c != '\\')
            dest += c;
        else
        {
            dest += '\\';
            
            switch (c)
            {
            case '\"':
            case '\\':
                dest += c;
                break;
                
            case '\b':
                dest += 'b';
                break;
                
            case '\f':
                dest += 'f';
                break;
                
            case '\n':
                dest += 'n';
                break;
                
            case '\r':
                dest += 'r';
                break;
                
            case '\t':
                dest += 't';
                break;
                
            default:
                {
                    char buffer[6];
                    sprintf(buffer, "u%04x", c);
                    dest += (const char*)&buffer[0];
                }
                break;
            }
        }
    }
    
    dest += '\"';
}
Пример #6
0
Image RLEToAlpha(const String& rle, Size sz)
{
	ImageBuffer ib(sz);
	const byte *s = rle;
	for(int y = 0; y < sz.cy; y++)
		if((const char *)s < rle.End())
			s = UnpackRLE(ib[y], s, sz.cx) + 1;
		else
			memset(ib[y], 0, sz.cx * sizeof(RGBA));
	return ib;
}
Пример #7
0
bool ShouldPreserve(const String& s)
{
	if(*s == ' ' || *s == '\t' || *s == '\n')
		return true;
	const char *l = s.Last();
	if(*l == ' ' || *l == '\t' || *l == '\n')
		return true;
	l = s.End();
	for(const char *x = s; x < l; x++)
		if(*x == '\t' || *x == '\n' || *x == ' ' && x[1] == ' ')
			return true;
	return false;
}
Пример #8
0
String NormalizePath(const char *path, const char *currdir)
{
	String join_path;
	if(!IsFullPath(path))
		path = join_path = AppendFileName(currdir, path);
	String out;
	if(*path && path[1] == ':') {
		out << path[0] << ":\\";
		path += 3;
	}
	else
	if(path[0] == '\\' && path[1] == '\\') {
		out = "\\\\";
		path += 2;
	}
	else
	if(sDirSep(*path)) {
		if(*currdir)
			out << *currdir << ':';
		out.Cat(DIR_SEP);
		path++;
	}
	int outstart = out.GetLength();
	while(*path) {
		if(sDirSep(*path)) {
			while(sDirSep(*path))
				path++;
			if(*path == '\0')
				break;
			if(out.IsEmpty() || *out.Last() != DIR_SEP)
				out.Cat(DIR_SEP);
		}
		const char *b = path;
		while(*path && !sDirSep(*path))
			path++;
		if(path - b == 1 && *b == '.')
			; //no-op
		else if(path - b == 2 && *b == '.' && b[1] == '.') {
			const char *ob = ~out + outstart, *oe = out.End();
			if(oe - 1 > ob && oe[-1] == DIR_SEP)
				oe--;
			while(oe > ob && oe[-1] != DIR_SEP)
				oe--;
			out.Trim((int)(oe - out.Begin()));
		}
		else
			out.Cat(b, (int)(path - b));
	}
	return out;
}
Пример #9
0
		String String::Concat(const String& str) const
		{
			String result;

			if (HasChars() || str.HasChars())
			{
				result.Allocate(Length() + str.Length());
				
				Iterator dest = Algo::Range::Copy(Begin(), End(), result.MutableBegin());
				Algo::Range::Copy(str.Begin(), str.End(), dest);
			}

			return result;
		}
Пример #10
0
bool Speller::SetOld(const String& _data)
{
	data = _data;
	const char *s = data;
	if(s >= data.End()) {
		data.Clear();
		return false;
	}
	charset = *s++;
	s++;// reserved for prefixes
	dict = *s++;
	for(int i = 0; i < 256 - dict; i++) {
		if(s >= data.End()) {
			data.Clear();
			return false;
		}
		voc[i] = s;
		while(*s) s++;
		s++;
	}
	line.Clear();
	while(s < data.End()) {
		if(s + 8 >= data.End()) {
			data.Clear();
			return false;
		}
		int code = Peek32le(s);
		s += 4;
		int len = Peek32le(s);
		s += 4;
		Line& l = line.Add(code);
		l.begin = (const byte *)s;
		s += len;
		l.end = (const byte *)s;
	};
	return true;
}
Пример #11
0
        bool String::operator>(const String& str) const
        {
			ConstIterator iterLeft = Begin(), iterRight = str.Begin();

            while (iterLeft != End() && iterRight != str.End())
            {
                if (*iterLeft != *iterRight)
                {
                    return *iterLeft > *iterRight;
                }
				++iterLeft;
				++iterRight;
            }

            return (Length() > str.Length());
        }
Пример #12
0
        void String::CreateReference(const String& str, ConstIterator begin, ConstIterator end)
        {
            if (begin < str.Begin() || end > str.End() || begin >= end)
            {
                throw IllegalArgumentException(SAF_SOURCE_LOCATION, String("Invalid substring bounds."));
            }

            if (str.m_buffer->m_refCounter == Type::NumericLimits<Size>::Max())
            {
                throw OverflowException(SAF_SOURCE_LOCATION, String("Reference counter overflow."));
            }

            m_buffer = str.m_buffer;
			m_begin = m_buffer->m_data + (begin - m_buffer->m_data); // Hack to get rid of const
            m_length = end - begin;
            ++m_buffer->m_refCounter;
        }
Пример #13
0
static String DumpSpecial(String s)
{
	String out;
	for(const char *p = s.Begin(), *e = s.End(); p < e; p++)
		if((byte)*p >= ' ' && *p != '\xFF')
			out.Cat(*p);
		else {
			switch(*p) {
				case '\a': out.Cat("[\\a]"); break;
				case '\b': out.Cat("[\\b]"); break;
				case '\f': out.Cat("[\\f]"); break;
				case '\v': out.Cat("[\\v]"); break;
				case '\t': out.Cat("[\\t]"); break;
				case '\r': out.Cat("[\\r]"); break;
				case '\n': out.Cat("[\\n]\n"); break;
				default:   out.Cat(NFormat("[\\x%02x", (byte)*p)); break;
			}
		}
	return out;
}
Пример #14
0
void RemoteSlaveProcess::Recv(int part, int timeout)
{
    if(terminated)
        return;
    if(!socket.IsOpen())
    {
        SVRLOG("-> broken pipe");
        terminated = true;
        return;
    }
//	LOG("RemoteSlaveProcess::Recv(" << part << ")");

    int starttick = GetTickCount();
    while( (IsNull(timeout) || int(GetTickCount())-starttick <= timeout) && (socket.Peek() || current_part <= part))
    {
        String data = socket.Read(0);
        SVRLOG("-> [" << current_part << "] = " << data.GetLength() << " bytes: <" << data << ">");
        if(data.IsVoid())
        {
            SVRLOG("-> broken pipe");
            terminated = true;
            return;
        }
        const char *p = data, *e = data.End();
        ASSERT(current_part >= 0 && current_part < __countof(output));
        for(const char *t; e > p && (t = (const char *)memchr(p, 0, e - p));)
        {
            output[current_part].Cat(p, int(t - p));
            p = t + 1;
            if(++current_part >= __countof(output))
            {
                SVRLOG("-> EOF");
                terminated = true;
                return;
            }
        }
        if(p < e)
            output[current_part].Cat(p, int(e - p));
    }
    SVRLOG("-> finished, current_part = " << current_part);
}
Пример #15
0
Vector<String> GetLineMap(Stream& stream)
{
	Vector<String> out;
	int emp = 0;
	if(stream.IsOpen())
		while(!stream.IsEof()) {
			String s = stream.GetLine();
			const char *p = s, *e = s.End(), *f = e;
			while(e > p && (byte)e[-1] != 9 && (byte)e[-1] < ' ')
				e--;
			if(e == p)
				emp++;
			else
			{
				while(emp-- > 0)
					out.Add(Null);
				if(e != f)
					s.Trim(int(e - p));
				out.Add(s);
				emp = 0;
			}
		}
	return out;
}
Пример #16
0
void DlgSqlExport::Run(Sql& cursor, String command, String tablename)
{
	Title(Nvl(tablename, t_("SQL query")) + t_(" export"));
	object_name <<= tablename;
	if(!cursor.Execute(command)) {
		Exclamation(NFormat(t_("Error executing [* \1%s\1]: \1%s"), command, cursor.GetLastError()));
		return;
	}
	for(int i = 0; i < cursor.GetColumns(); i++) {
		const SqlColumnInfo& sci = cursor.GetColumnInfo(i);
		String type;
		switch(sci.valuetype) {
			case BOOL_V:
			case INT_V: type = t_("integer"); break;
			case DOUBLE_V: type = t_("real number"); break;
			case STRING_V:
			case WSTRING_V: type = t_("string"); break;
			case DATE_V: type = t_("date"); break;
			case TIME_V: type = t_("date/time"); break;
			case /*ORA_BLOB_V*/-1: type = t_("BLOB"); break;
			case /*ORA_CLOB_V*/-2: type = t_("CLOB"); break;
			default: type = FormatInt(sci.valuetype); break;
		}
		columns.Add(sci.name, sci.valuetype, sci.width, 1);
	}
	static String cfg;
	LoadFromString(*this, cfg);
	SyncUI();
	while(TopWindow::Run() == IDOK)
		try {
			String out_table = ~object_name;
			String delim;
			switch((int)~delimiters) {
				case DELIM_TAB: delim = "\t"; break;
				case DELIM_SEMICOLON: delim = ";"; break;
			}
			Vector<int> out;
			String colstr;
			String title;
			for(int i = 0; i < columns.GetCount(); i++)
				if(columns.Get(i, 3)) {
					out.Add(i);
					String cname = cursor.GetColumnInfo(i).name;
					colstr << (i ? ", " : "") << cname;
					if(i) title << delim;
					title << cname;
				}
			if(out.IsEmpty()) {
				throw Exc(t_("No columns selected!"));
				continue;
			}
			String rowbegin, rowend;
			int fmt = ~format;
			FileSel fsel;
			String ext;
			switch(fmt) {
				case FMT_TEXT: {
					rowend = "";
					ext = ".txt";
					fsel.Type(t_("Text files (*.txt)"), "*.txt");
					break;
				}
				case FMT_SQL: {
					if(identity_insert)
						rowbegin << "set identity_insert " << out_table << " on ";
					rowbegin << "insert into " << out_table << "(" << colstr << ") values (";
					rowend = ");";
					ext = ".sql";
					fsel.Type(t_("SQL scripts (*.sql)"), "*.sql");
					break;
				}
			}
			fsel.AllFilesType().DefaultExt(ext.Mid(1));
			if(!IsNull(recent_file))
				fsel <<= ForceExt(recent_file, ext);
			if(!fsel.ExecuteSaveAs(t_("Save export as")))
				continue;
			recent_file = ~fsel;
			FileOut fo;
			if(!fo.Open(recent_file)) {
				Exclamation(NFormat(t_("Error creating file [* \1%s\1]."), recent_file));
				continue;
			}
			if(fmt == FMT_TEXT)
				fo.PutLine(title);
			Progress progress(t_("Exporting row %d"));
			while(cursor.Fetch()) {
				String script = rowbegin;
				for(int i = 0; i < out.GetCount(); i++) {
					Value v = cursor[out[i]];
					switch(fmt) {
						case FMT_TEXT: {
							if(i)
								script.Cat(delim);
							if(IsString(v) && quote) {
								String s = v;
								script << '\"';
								for(const char *p = s, *e = s.End(); p < e; p++)
									if(*p == '\"')
										script.Cat("\"\"");
									else
										script.Cat(*p);
								script << '\"';
							}
							else
								script << StdFormat(v);
							break;
						}
						case FMT_SQL: {
							if(i) script.Cat(", ");
//							script << SqlCompile(SQLD_ORACLE, SqlFormat(v));
							break;
						}
					}
				}
				script << rowend;
				fo.PutLine(script);
/*
				if(autocommit && --left <= 0) {
					fo.PutLine("commit;");
					left = autocommit;
				}
*/
				if(progress.StepCanceled()) {
					Exclamation(t_("Export aborted!"));
					return;
				}
			}
			fo.Close();
			if(fo.IsError())
				throw Exc(NFormat(t_("Error writing file %s."), recent_file));
			break;
		}
		catch(Exc e) {
			ShowExc(e);
		}

	cfg = StoreAsString(*this);
}
Пример #17
0
String SaveIml(const Array<ImlImage>& iml, int format) {
	StringStream out;
	if(format == 1) {
		for(int i = 0; i < iml.GetCount(); i++) {
			const ImlImage& c = iml[i];
			if(c.exp)
				out << "IMAGE_META(\"exp\", \"\")\r\n";
			String name = c.name;
			Image buffer = c.image;
			if(IsNull(name))
				name = "im__" + IntStr(i);
			out.PutLine(NFormat("IMAGE_BEGIN(%s)", name));
			int last = 0;
			for(int i = 0; i < buffer.GetHeight(); i++) {
				String scan = PackRLE(buffer[i], buffer.GetWidth());
				if(!scan.IsEmpty() || i == 0) // force at least 1 scan
				{
					for(; last < i; last++)
						out.PutLine("\tIMAGE_SCAN(\"\")");
					out.Put("\tIMAGE_SCAN(");
					PutOctalString(out, scan.Begin(), scan.End(), true);
					out.Put(")\r\n");
					last = i + 1;
				}
			}
			out.Put("IMAGE_PACKED(");
			out.Put(name);
			out.Put(", ");
			StringStream datastrm;
			Size size = buffer.GetSize();
			Point hotspot = buffer.GetHotSpot();
			int encoding = AlphaImageInfo::COLOR_RLE;
			int version = 1;
			datastrm / version;
			datastrm % size % hotspot % encoding;
			ASSERT(!datastrm.IsError());
			String s = datastrm.GetResult();
			PutOctalString(out, s.Begin(), s.End());
			out.Put(")\r\n");
		}
	}
	else {
		out << "PREMULTIPLIED\r\n";
		for(int i = 0; i < iml.GetCount(); i++) {
			const ImlImage& c = iml[i];
			out << "IMAGE_ID(" << c.name << ")";
			if(c.exp)
				out << " IMAGE_META(\"exp\", \"\")\r\n";
			out << "\r\n";
		}
		int ii = 0;
		while(ii < iml.GetCount()) {
			int bl = 0;
			int bn = 0;
			Vector<Image> bimg;
			while(bl < 4096 && ii < iml.GetCount()) {
				const ImlImage& c = iml[ii++];
				bimg.Add(c.image);
				bl += c.image.GetLength();
				bn++;
			}
			String bs = PackImlData(bimg);
			out << "\r\nIMAGE_BEGIN_DATA\r\n";
			bs.Cat(0, ((bs.GetCount() + 31) & ~31) - bs.GetCount());
			const byte *s = bs;
			for(int n = bs.GetCount() / 32; n--;) {
				out << "IMAGE_DATA(";
				for(int j = 0; j < 32; j++) {
					if(j) out << ',';
					out << (int)*s++;
				}
				out << ")\r\n";
			}
			out << "IMAGE_END_DATA(" << bs.GetCount() << ", " << bn << ")\r\n";
		}
	}
	return out.GetResult();
}
Пример #18
0
void CheckResultReader::ProcessCheckResultFile(const String& path) const
{
	CONTEXT("Processing check result file '" + path + "'");

	String crfile = String(path.Begin(), path.End() - 3); /* Remove the ".ok" extension. */

	std::ifstream fp;
	fp.exceptions(std::ifstream::badbit);
	fp.open(crfile.CStr());

	std::map<String, String> attrs;

	while (fp.good()) {
		std::string line;
		std::getline(fp, line);

		if (line.empty() || line[0] == '#')
			continue; /* Ignore comments and empty lines. */

		size_t pos = line.find_first_of('=');

		if (pos == std::string::npos)
			continue; /* Ignore invalid lines. */

		String key = line.substr(0, pos);
		String value = line.substr(pos + 1);

		attrs[key] = value;
	}

	/* Remove the checkresult files. */
	if (unlink(path.CStr()) < 0)
		BOOST_THROW_EXCEPTION(posix_error()
			<< boost::errinfo_api_function("unlink")
			<< boost::errinfo_errno(errno)
			<< boost::errinfo_file_name(path));

	if (unlink(crfile.CStr()) < 0)
		BOOST_THROW_EXCEPTION(posix_error()
			<< boost::errinfo_api_function("unlink")
			<< boost::errinfo_errno(errno)
			<< boost::errinfo_file_name(crfile));

	Checkable::Ptr checkable;

	Host::Ptr host = Host::GetByName(attrs["host_name"]);

	if (!host) {
		Log(LogWarning, "CheckResultReader")
			<< "Ignoring checkresult file for host '" << attrs["host_name"] << "': Host does not exist.";

		return;
	}

	if (attrs.find("service_description") != attrs.end()) {
		Service::Ptr service = host->GetServiceByShortName(attrs["service_description"]);

		if (!service) {
			Log(LogWarning, "CheckResultReader")
				<< "Ignoring checkresult file for host '" << attrs["host_name"]
				<< "', service '" << attrs["service_description"] << "': Service does not exist.";

			return;
		}

		checkable = service;
	} else
		checkable = host;

	CheckResult::Ptr result = new CheckResult();
	String output = CompatUtility::UnEscapeString(attrs["output"]);
	std::pair<String, Value> co = PluginUtility::ParseCheckOutput(output);
	result->SetOutput(co.first);
	result->SetPerformanceData(PluginUtility::SplitPerfdata(co.second));
	result->SetState(PluginUtility::ExitStatusToState(Convert::ToLong(attrs["return_code"])));

	if (attrs.find("start_time") != attrs.end())
		result->SetExecutionStart(Convert::ToDouble(attrs["start_time"]));
	else
		result->SetExecutionStart(Utility::GetTime());

	if (attrs.find("finish_time") != attrs.end())
		result->SetExecutionEnd(Convert::ToDouble(attrs["finish_time"]));
	else
		result->SetExecutionEnd(result->GetExecutionStart());

	checkable->ProcessCheckResult(result);

	Log(LogDebug, "CheckResultReader")
		<< "Processed checkresult file for object '" << checkable->GetName() << "'";

	/* Reschedule the next check. The side effect of this is that for as long
	 * as we receive check result files for a host/service we won't execute any
	 * active checks. */
	checkable->SetNextCheck(Utility::GetTime() + checkable->GetCheckInterval());
}
Пример #19
0
String DeXml(const String& s, byte charset, bool escapelf)
{
	return DeXml(~s, s.End(), charset, escapelf);
}