Exemple #1
0
void VfkStream::Open(const VectorMap<int, String>& fns)
{
	Close();
	charset = CHARSET_ISO8859_2;
	file_groups <<= fns;
	streams.SetCount(file_groups.GetCount());
	for(int i = 0; i < streams.GetCount(); i++)
		if(!streams[i].Open(file_groups[i]))
			throw Exc(NFormat("cannot open file '%s'", file_groups[i]));
	indexfilename = GetTempFileName("vfk");
	if(!indexfile.Open(indexfilename, FileStream::CREATE))
		throw Exc(NFormat("cannot create indexfile '%s'", indexfilename));
	String hdrname = "X_HEADER";
	Table& hdr = tables.Add(hdrname);
	hdr.name = hdr.rawname = hdrname;
	hdr.header = true;
	hdr.row_count = 0;
	ASSERT(hdr.columns.GetCount() == HDR_ID);
	hdr.AddColumn(Column("ID", STRING_V, 30));
	ASSERT(hdr.columns.GetCount() == HDR_ORD);
	hdr.AddColumn(Column("ORD", INT_V));
	ASSERT(hdr.columns.GetCount() == HDR_STR);
	hdr.AddColumn(Column("STR", STRING_V, 1000));
	ASSERT(hdr.columns.GetCount() == HDR_NUM);
	hdr.AddColumn(Column("NUM", DOUBLE_V));
	ASSERT(hdr.columns.GetCount() == HDR_DTM);
	hdr.AddColumn(Column("DTM", TIME_V));
	ASSERT(hdr.columns.GetCount() == HDR_COUNT);
	Scan();
}
Exemple #2
0
    //
    // Returns the mean value calculated over all the experiments
    //
    double BaseStat::getMean()
    {
        if (!_endOfSim) throw Exc(GET);
        if (!_initFlag) throw Exc(NO_INIT);

        double sum = accumulate(_exper.begin(), _exper.end(), 0.0);
        sum /= _expNum;
  
        return sum;
    }
Exemple #3
0
    double BaseStat::getConfInterval(CONFIDENCE_INTERVAL c)
    {
        double mu;		// the mean
        double s;		// the variance
  
        if (!_endOfSim) throw Exc(GET);
        if (!_initFlag) throw Exc(NO_INIT);
        if (_expNum < 3) throw Exc(NEED_3);

        mu = getMean();
        s = getVariance();
        return t_student(c, (unsigned int) _expNum - 1) * s;
    }
Exemple #4
0
    //
    // Returns the variance for the experimental samples
    //
    double BaseStat::getVariance()
    {
        double sum = 0;
        double mu;		// the mean
  
        if (!_endOfSim) throw Exc(GET);
        if (!_initFlag) throw Exc(NO_INIT);
        if (_expNum < 3) throw Exc(NEED_3);

        mu = getMean();

        sum = accumulate(_exper.begin(), _exper.end(), 0.0, V(mu));
        return sqrt(sum/((_expNum - 1) * _expNum));
    }
Exemple #5
0
 //
 // Collect all the results
 //
 void BaseStat::endRun()
 {
     for_each(_statList.begin(), _statList.end(),
              mem_fun(&BaseStat::collect));
     if (++_expNum >= MAX_RUN)
         throw Exc(TOO_MUCH_RUNS);
 }
Exemple #6
0
String ForceInsertRowid(const String& insert, Sql& cursor)
{
    if(!cursor.Execute(insert + " returning ROWID into ?%s"))
        throw SqlExc(cursor.GetSession());
    if(!cursor.Fetch())
        throw Exc(t_("FETCH internal error (ForceInsertRowid)"));
    ASSERT(!IsNull(cursor[0]));
    return cursor[0];
}
/**
* parse primitve. this method parses the values, that are stored inside the Xml-document
* handled by the XmlParser \p p.
* @param p the parser holding the xml document
* @return the Value contained in the xml document
*/
Value XmlRpcParser::ParsePrimitive(XmlParser& p) {
	Value v,vv;
	if(p.IsText()) {
		return Value(p.ReadText());
	}
	for(int i=0;i<7;i++) {
		if(p.Tag(primitives[i])) {
			switch(i) {
			case 0: //string
				v=Value(p.ReadText());
				break;
			case 1: //int
			case 2: //i4
				v = Value(atoi(p.ReadText()));
				break;
			case 3: //boolean
				v = Value((bool)atoi(p.ReadText()));
				break;
			case 4: //double
				v = Value(atof(p.ReadText()));
				break;
			case 5: //dateTime.iso8601
				p.ReadTextE();
				v=Value(Date(1970,1,1));
				break;
			case 6: //base64
				LoadFromString(vv, p.ReadText());
				v = Value(vv);
				break;
			default:
				throw Exc("unexpected Error");
				break;
			}
			p.PassEnd();
			return Value(v);
		}
	}
	throw Exc("unknown primitive");
}
Exemple #8
0
void RemoteSlaveProcess::Open(const char *host, int port, const char *cmdline, const char *envptr, int to)
{
    SVRLOG("RemoteSlaveProcess(" << host << ":" << port << ")=" << cmdline);
    Kill();

    timeout = to;
    Socket::Init();
    String localhost;
    if(host == 0 || *host == 0)
    {
        localhost = Socket::GetHostName();
        host = localhost;
    }
    if(port == 0)
        port = DEFAULT_PORT;
    terminated = false;
    current_part = 0;
    output[0] = output[1] = output[2] = Null;
    if(!ClientSocket(socket, host, port, true, NULL, REQUEST_TIMEOUT))
        throw Exc(NFormat(t_("Opening host '%s' / port %d failed, error = %s"), host, port, Socket::GetErrorText()));
    int len = (int)strlen(cmdline);
    if(envptr && *envptr) {
        const char *e = envptr;
        while(*e)
            e = e + strlen(e) + 1;
        socket.Write(":");
        socket.Write(ASCII85Encode(String(envptr, e + 1)));
        socket.Write("\n");
    }
    socket.Write("=");
    socket.Write(cmdline, len + 1); // send terminating 0 as well
    Recv(0, timeout);
    if(output[0][0] == '-')
        throw Exc(NFormat(t_("Error running process: %s\nCommand: %s"), output[0].Begin() + 1, cmdline));

    if(output[0] != "+")
        throw Exc(NFormat(t_("Communication error; process = %s"), cmdline));
}
Exemple #9
0
void VfkStream::ScanHeader(const char *b, Table& table)
{
	int colid = 0;
	while(*b && *b != '\n') {
		if(IsAlpha(*b)) {
			const char *id = b;
			while(IsIdent(*++b))
				;
			Column col;
			col.name = String(id, b);
			try {
				while(*b == ' ')
					b++;
				col.vtype = ERROR_V;
				col.width = Null;
				switch(*b++) {
					case 'N': {
						col.vtype = DOUBLE_V;
						break;
					}
					case 'T': {
						col.vtype = STRING_V;
						if(!IsDigit(*b))
							throw Exc("missing string width");
						col.width = ScanInt(b, &b);
						break;
					}
					case 'D': {
						col.vtype = TIME_V;
						break;
					}
					default: {
						throw Exc(NFormat("invalid data type '%c'", *--b));
					}
				}
				if(colid < table.columns.GetCount()) {
					const Column& old = table.columns[colid];
					if(old.name != col.name)
						throw Exc(NFormat("column name mismatch (%s / %s)", old.name, col.name));
					if(old.vtype != col.vtype)
						throw Exc(NFormat("column type mismatch (%d / %d)", old.vtype, col.vtype));
					if(old.width != col.width)
						throw Exc(NFormat("column width mismatch (%~d / %~d)", old.width, col.width));
				}
				else
					table.AddColumn(col);
				colid++;
			}
			catch(Exc e) {
				throw Exc(NFormat("column '%s': %s", colid, e));
			}
		}
		else
			b++;
	}
}
Exemple #10
0
void RichQtfParser::Error(const char *s) {
	RichPara::CharFormat ef;
	(Font&) ef = Arial(84).Bold().Underline();
	ef.ink = Red;
	WString e;
	e << "ERROR: " << s;
	if(*term)
		e << ": " << Filter(String(term, min<int>((int)strlen(term), 20)), NoLow).ToWString();
	else
		e << ".";
	paragraph.Cat(e, ef);
	target.Cat(paragraph);
	FlushStyles();
	throw Exc();
}
Exemple #11
0
void GrabScreen::ButGrab_Push() {
#if defined(PLATFORM_WIN32) 
	FileDelete(editFileNameGrab.GetData().ToString());
	
	bool ret;
	if (swGrabMode.GetData() == 0) 
		ret = Record_Desktop(~editFileNameGrab, editTime, editFrameRate, opGrabMouse);
	else if (swGrabMode.GetData() == 1) 
		ret = Record_Window(~editFileNameGrab, editTime, GetWindowIdFromCaption(~editWindowTitle, false), editFrameRate, opGrabMouse);
	else if (swGrabMode.GetData() == 2) 
		ret = Record_DesktopRectangle(~editFileNameGrab, editTime, editLeft, editTop, editWidth, editHeight, editFrameRate, opGrabMouse);
	else
		throw Exc("Unexpected value");
	if (!ret)
		Exclamation("Error on grabbing");
#endif
}
Exemple #12
0
    /* Output class 
       This class produce formatted output to be read by gnuplot.
       Just call GnuPlotOutput::init() before simulation, and 
       GnuPlotOutput::write("%f", par) after every simulation, where 
       par is a float parameter of the simulation. 
       There can be more than one parameter, and of different types!

       See ex7.ccp for more details.
    */
    void GnuPlotOutput::init()
    {
        BaseStat::List::const_iterator i  = BaseStat::begin();
        while (i != BaseStat::end()) {
            BaseStat* p = *i;
            cout << "Name: " << p->getName() << endl;

            if (p->getName() != "") {
                ofstream f(p->getName().c_str());

                if (!f.is_open())
                    throw Exc("Cannot open file " + p->getName());

                f << "# " << p->getName() << endl;
            }
            ++i;
        }
    }
Exemple #13
0
WString VfkStream::ReadString(const char *b, const char **endptr) const
{
	if(*b++ != '\"')
		throw Exc("'\"' expected");
	StringBuffer out;
	for(;;) {
		const char *b0 = b;
		while(*b && *b != '\"')
			b++;
		out.Cat(b0, b - b0);
		if(*b != '\"' || *++b != '\"')
			break;
		out.Cat(*b++);
	}
	if(endptr)
		*endptr = b;
	return ToUnicode((String)out, charset);
}
Exemple #14
0
One<SlaveProcess> StartProcess(const char *cmdline, const char *envptr, int timeout)
{
    if(*cmdline != '(')
        return StartLocalProcess(cmdline, envptr);
    const char *b = cmdline + 1, *p = b;
    while(*p && *p != ')' && *p != ':')
        p++;
    String host(b, p);
    int port = 0;
    if(*p == ':')
        port = stou(p + 1, &p);
    while(*p && *p++ != ')')
        ;
    if(*p == 0)
        throw Exc(NFormat(t_("Missing command line (host = %s)."), host));
    One<RemoteSlaveProcess> rsp = new RemoteSlaveProcess(host, port, p, envptr, timeout);
    return rsp.Detach();
}
Exemple #15
0
String HelpTopicSave(Vector<String>& saved_files, String text_folder, HelpTopicInfoMap& diff, String out_folder, bool skip_file_write)
{
	Vector<String> drls = HelpTopicListTextFolder(IsNull(out_folder) ? text_folder : String::GetVoid());
	Index<String> used_names;
	HelpTopicInfoMap& map = HelpTopicMap();
	String out;
	bool first = true;
	String dir_dph;
	for(int t = 0; t < drls.GetCount(); t++) {
		String drl = drls[t];
		const HelpTopicInfo& topicinfo = HelpTopicGet(drl);
		String space, nesting, topic;
		HelpParseDPP(drl, space, nesting, topic);
		String outdir = AppendFileName(Nvl(out_folder, text_folder), "doc.dpp");
		String title = HelpTopicTextModuleTitle(space, nesting, topic, used_names);
		for(int l = 0; l < topicinfo.language.GetCount(); l++)
			if(!IsNull(topicinfo.title[l]) || !IsNull(topicinfo.text[l])) {
				String file;
				file << title << '_' << LNGAsTextShort(topicinfo.language[l]) << ".dpx";
				String path = AppendFileName(outdir, file);
				dir_dph << "#include \"" << path << "\"\n";
				if(!skip_file_write) {
					String lng = LNGAsText(topicinfo.language[l]);
					String out;
					out << "HELP_TOPIC(" << AsCString(space)
						<< ", " << AsCString(nesting)
						<< ", " << AsCString(topic)
						<< ", " << AsCString(lng)
						<< ", " << AsCString(topicinfo.title[l]) << ")\n";
					String text = topicinfo.text[l];
					String ctext;
					const char *p = text;
					while(*p) {
						const char *b = p;
						enum { CHUNK = 100 };
						while(*p && *p++ != '\n' && p - b < CHUNK)
							;
						if(!IsNull(ctext))
							ctext << "\n\t";
						ctext << AsCString(String(b, p));
						if(ctext.GetLength() >= 5000)
						{
							out << "HELP_TEXT(\n\t" << ctext << ")\n";
							ctext = Null;
						}
					}
					if(!IsNull(ctext))
						out << "\tHELP_TEXT(\n\t" << ctext << ")\n";
					out << "HELP_END\n";
					if(first) {
						first = false;
						RealizePath(path);
					}
					if(!IsSameTextFile(LoadFile(path), out)) {
						if(!SaveFileBackup(path, out))
							throw Exc(NFormat("Nelze uložit soubor '%s'.", path));
						saved_files.Add(path);
					}
				}
				diff.GetAdd(drl) <<= topicinfo;
			}
	}
	return dir_dph;
}
Exemple #16
0
void SkylarkApp::TemplateError(Http& http, const TemplateExc& e)
{
	InternalError(http, Exc());
}
Exemple #17
0
void LocalSlaveProcess::Open(const char *command, const char *envptr) {
    SVRLOG("LocalSlaveProcess::Open(" << command << ")");

    Kill();

    while(*command && (byte)*command <= ' ')
        command++;

#ifdef PLATFORM_WIN32
    HANDLE hOutputReadTmp, hInputRead;
    HANDLE hInputWriteTmp, hOutputWrite;
    HANDLE hErrorWrite;
    SECURITY_ATTRIBUTES sa;

    sa.nLength = sizeof(SECURITY_ATTRIBUTES);
    sa.lpSecurityDescriptor = NULL;
    sa.bInheritHandle = TRUE;

    HANDLE hp = GetCurrentProcess();

    CreatePipe(&hOutputReadTmp, &hOutputWrite, &sa, 0);
    DuplicateHandle(hp, hOutputWrite, hp, &hErrorWrite, 0, TRUE, DUPLICATE_SAME_ACCESS);
    CreatePipe(&hInputRead, &hInputWriteTmp, &sa, 0);
    DuplicateHandle(hp, hOutputReadTmp, hp, &hOutputRead, 0, FALSE, DUPLICATE_SAME_ACCESS);
    DuplicateHandle(hp, hInputWriteTmp, hp, &hInputWrite, 0, FALSE, DUPLICATE_SAME_ACCESS);
    CloseHandle(hOutputReadTmp);
    CloseHandle(hInputWriteTmp);

    PROCESS_INFORMATION pi;
    STARTUPINFO si;
    ZeroMemory(&si, sizeof(STARTUPINFO));
    si.cb = sizeof(STARTUPINFO);
    si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
    si.wShowWindow = SW_HIDE;
    si.hStdInput  = hInputRead;
    si.hStdOutput = hOutputWrite;
    si.hStdError  = hErrorWrite;
    int n = (int)strlen(command) + 1;
    Buffer<char> cmd(n);
    memcpy(cmd, command, n);
    bool h = CreateProcess(NULL, cmd, &sa, &sa, TRUE,
                           NORMAL_PRIORITY_CLASS, (void *)envptr, NULL, &si, &pi);
    SVRLOG("CreateProcess " << (h ? "succeeded" : "failed"));
    CloseHandle(hErrorWrite);
    CloseHandle(hInputRead);
    CloseHandle(hOutputWrite);
    if(h) {
        hProcess = pi.hProcess;
        CloseHandle(pi.hThread);
    }
    else {
        Free();
        throw Exc(NFormat("Error running process: %s\nCommand: %s", GetErrorMessage(GetLastError()), command));
    }
#endif
#ifdef PLATFORM_POSIX
    // parse command line for execve
    cmd_buf.Alloc(strlen(command) + 1);
    char *cmd_out = cmd_buf;
    const char *p = command;
    const char *b = p;
    while(*p && (byte)*p > ' ')
        if(*p++ == '\"')
            while(*p && *p++ != '\"')
                ;
    const char *app = cmd_out;
    args.Add(cmd_out);
    memcpy(cmd_out, b, p - b);
    cmd_out += p - b;
    *cmd_out++ = '\0';

    while(*p)
        if((byte)*p <= ' ')
            p++;
        else {
            args.Add(cmd_out);
            while(*p && (byte)*p > ' ')
                if(*p == '\\') {
                    if(*++p)
                        *cmd_out++ = *p++;
                }
                else if(*p == '\"') {
                    p++;
                    while(*p && *p != '\"')
                        if(*p == '\\') {
                            if(*++p)
                                *cmd_out++ = *p++;
                        }
                        else
                            *cmd_out++ = *p++;
                    if(*p == '\"')
                        p++;
                }
                else
                    *cmd_out++ = *p++;
            *cmd_out++ = '\0';
        }

    args.Add(NULL);

    String app_full = GetFileOnPath(app, getenv("PATH"), true);
    if(IsNull(app_full))
        throw Exc(Format("Cannot find executable '%s'\n", app));

    if(pipe(rpipe) || pipe(wpipe))
        throw Exc(NFormat(t_("pipe() error; error code = %d"), errno));
    SVRLOG("\nLocalSlaveProcess::Open");
    SVRLOG("rpipe[" << rpipe[0] << ", " << rpipe[1] << "]");
    SVRLOG("wpipe[" << wpipe[0] << ", " << wpipe[1] << "]");
    pid = fork();
    SVRLOG("\tfork, pid = " << (int)pid << ", getpid = " << (int)getpid());
    if(pid < 0)
        throw Exc(NFormat(t_("fork() error; error code = %d"), errno));
    if(pid)
    {   // parent process; clear child pipe endpoints
        SVRLOG("parent process - continue");
//		rpipe[0] = wpipe[1] = -1;
        return;
    }
    SVRLOG("child process - execute application");
//	rpipe[1] = wpipe[0] = -1;
    if(dup2(rpipe[0], 0) < 0)
    {   // stdin
        SVRLOG("dup2(stdin) error: " << errno << ", " << strerror(errno));
    }
    if(dup2(wpipe[1], 1) < 0)
    {   // stdout
        SVRLOG("dup2(stdout) error: " << errno << ", " << strerror(errno));
    }
    if(dup2(wpipe[1], 2) < 0)
    {   // stderr
        SVRLOG("dup2(stderr) error: " << errno << ", " << strerror(errno));
    }

#if DO_SVRLOG
    SVRLOG(args.GetCount() << "arguments:");
    for(int a = 0; a < args.GetCount(); a++)
        SVRLOG("[" << a << "]: <" << (args[a] ? args[a] : "NULL") << ">");
#endif//DO_SVRLOG

    SVRLOG("running execve, app = " << app << ", #args = " << args.GetCount());
    const char *from = envptr;
    Vector<const char *> env;
    while(*from) {
        env.Add(from);
        from += strlen(from) + 1;
    }
    env.Add(NULL);
    execve(app_full, args.Begin(), (char *const *)env.Begin());
    SVRLOG("execve failed, errno = " << errno);
    printf("Error running '%s', error code %d\n", command, errno);
    exit(-errno);
#endif
}
Exemple #18
0
bool Pop3::Login()
{
	try {
		if(host.IsEmpty())
			throw Exc(t_("Hostname is not specified."));
		if(user.IsEmpty())
			throw Exc(t_("Username is not specified."));
		if(pass.IsEmpty())
			throw Exc(t_("Password is nor specified."));
		if(proxy_host.GetCount()) {
			String host_port = host;
			host_port << ':' << Nvl(port, ssl ? 995 : 110);
			String data;
			data << "CONNECT " << host_port << " HTTP/1.1\r\n"
			     << "Host: " << host_port << "\r\n";
			if(!IsNull(proxy_username))
				data << "Proxy-Authorization: Basic "
				     << Base64Encode(proxy_username + ':' + proxy_password) << "\r\n";
			data << "\r\n";
			LLOG("Trying to connect proxy " << proxy_host << ":" << proxy_port);
			if(!Connect(proxy_host, proxy_port))
				throw Exc("Unable to connect the proxy");
			LLOG("About to send proxy request:\n" << data);
			if(!PutAll(data))
				throw Exc("Unable to send request to the proxy");
			String response;
			for(;;) {
				String l = GetLine();
				if(l.GetCount() == 0)
					break;
				LLOG("< " << l);
				if(response.GetCount() == 0)
					response = l;
			}
			LLOG("Proxy response: " << response);
			if(!response.StartsWith("HTTP") || response.Find(" 2") < 0)
				throw Exc("Invalid proxy reply: " + response);
			LLOG("Connected via proxy");
		}
		else
		if(!Connect(host, Nvl(port, ssl ? 995 : 110)))
			throw Exc(GetErrorDesc());
		LLOG(Format(t_("Opening connection to %s:%d."), host, port));
		if(ssl) {
			if(!StartSSL())
				throw Exc(t_("Couldn't start SSL session."));
			LLOG(t_("SSL session successfully started."));
		}
		// Receive server greetings.
		if(!PutGet(Null))
			throw Exc(GetLastError());
		if(!Authenticate())
			throw Exc(GetLastError());
	}
	catch (Exc e) {
		error = e;
		LLOG("-- " + e);
		Logout();
		return false;
	}
	return online = true;
}
Exemple #19
0
void FileCtl::io_err            // THROW I/O ERROR
    ( char const *msg )         // - message
{
    throw Exc( "I/O:", msg, filename(), 0 );
}
Exemple #20
0
void VfkStream::ScanFile(int fx)
{
	RTIMING("VfkStream::ScanFile");
	Stream& strm = streams[fx];
	int64 last_line = strm.GetSize();
	while(last_line > 0) {
		strm.Seek(last_line - 1);
		if(strm.Get() == '\n')
			break;
		last_line--;
	}
	strm.Seek(0);
	try {
		int c;
		int64 rowpos = strm.GetPos();
		while((c = strm.Get()) == '&' && ((c = strm.Get()) == 'H' || c == 'D') && IsAlpha(strm.Term())) {
			char type = c;
			int64 begin = strm.GetPos();
			SkipRow(strm);
			rowpos = strm.GetPos();
			int len = (int)(strm.GetPos() - begin);
			StringBuffer linebuf(len + 1);
			strm.Seek(begin);
			strm.Get(linebuf, len);
			linebuf[len] = 0;
			const char *b = linebuf;
			const char *id = b;
			while(IsIdent(*++b))
				;
			String ident(id, b);
			if(*b++ != ';')
				throw Exc(NFormat("';' expected after '%s' (found: '%c', %2:02x)", ident, *b));
			if(type == 'D') {
				String fident = "X_" + ident;
				int f = tables.Find(fident);
				if(f < 0)
					throw Exc(NFormat("unexpected data for filter table '%s'", ident));
//				b = ScanRow(b, tables[f]);
			}
			else if(IsAlpha(*b)) {
				String fident = "X_" + ident;
				Table& tbl = tables.GetAdd(fident);
				tbl.name = tbl.rawname = fident;
				tbl.row_count = 0;
				ScanHeader(b, tbl);
			}
			else {
				do {
					Vector<Value> row;
					row.SetCount(HDR_COUNT);
					if(*b == '\"') {
						WString text = ReadString(b, &b);
						if(IsDateTime(ident) && !IsNull(text)) {
							Time dt = VfkReadTime(text.ToString(), NULL);
							if(IsNull(dt))
								throw Exc(NFormat("invalid date/time value %s", AsCString(text.ToString())));
							row[HDR_DTM] = dt;
						}
						else {
							row[HDR_STR] = text;
							if(ident == "CODEPAGE")
								if(text == WString("EE8MSWIN1250")) charset = CHARSET_WIN1250;
						}
					}
					else {
						double num = ScanDouble(b, &b);
						if(IsNull(num))
							throw Exc("invalid numeric value");
						row[HDR_NUM] = num;
					}
					int l = header.FindLast(ident);
					row[HDR_ID] = ident;
					row[HDR_ORD] = (l >= 0 ? (int)header[l][HDR_ORD] + 1 : 0);
					header.Add(ident) = row;
				}
				while(*b++ == ';');
				b--;
			}
		}
		strm.Seek(rowpos);
		while(strm.Get() == '&' &&  strm.Get() == 'B' && IsAlpha(strm.Term())) {
			int64 header_offset = strm.GetPos();
			SkipRow(strm);
			int64 begin_offset = strm.GetPos();
			int len = (int)(begin_offset - header_offset);
			Buffer<char> linebuf(len + 1);
			strm.Seek(header_offset);
			strm.Get(linebuf, len);
			linebuf[len] = 0;
			const char *b = linebuf;
			const char *id = b;
			while(IsIdent(*++b))
				;
			int idlen = b - id;
			String ident(id, b);
			if(*b++ != ';')
				throw Exc(NFormat("';' expected after '%s' (found: '%c', %2:02x)", ident, *b));
			String name = ident;
			for(const VFKLongName *ln = vfk_long_names; ln->shortname; ln++)
				if(name == ln->shortname) {
					name = ln->longname;
					break;
				}
			Table& tbl = tables.GetAdd(name);
			tbl.name = name;
			tbl.rawname = ident;
			ScanHeader(b, tbl);
			int64 p = begin_offset, e = last_line;
			Buffer<char> idbuf(idlen + 3);
			while(p < e) {
				int64 m = (p + e) >> 1;
				while(m > p) {
					char part[100];
					int partsize = (int)min<int64>(m - p, sizeof(part));
					strm.Seek(m - partsize);
					strm.Get(part, partsize);
					const char *x = &part[partsize];
					while(x > part && x[-1] != '\n')
						x--;
					int lfpos = x - part;
					if(x > part && --x > part && x[-1] == '\r')
						x--;
					m -= partsize - lfpos;
					if(x <= part)
						continue;
					if(*--x != '\xA4')
						break;
					m -= lfpos - (x - part);
				}
				strm.Seek(m);
				if(strm.Get(idbuf, idlen + 3) != idlen + 3 || idbuf[0] != '&' || idbuf[1] != 'D'
				|| memcmp(~idbuf + 2, id, idlen) || idbuf[idlen + 2] != ';')
					e = m;
				else {
					SkipRow(strm);
					p = strm.GetPos();
				}
			}
			int xgrp = file_groups.GetKey(fx);
			int f;
			for(f = 0; f < tbl.file_index.GetCount(); f++)
				if(file_groups.GetKey(tbl.file_index[f]) == xgrp)
					break;
			if(f >= tbl.file_index.GetCount()) {
				tbl.file_index.Add(fx);
				tbl.begin_offset.Add(begin_offset);
				tbl.end_offset.Add(p);
			}
			strm.Seek(p);
		}
	}
	catch(Exc e) {
		throw Exc(NFormat("%s (offset %n): %s", file_groups[fx], strm.GetPos(), e));
	}
}
unsigned char PacketReader::readChar() {
    if(offset == packetSize) {
        throw Exc("Prekrocena velkost citania paketu");
    }
    return finalPacket[offset++];
}
Exemple #22
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);
}