示例#1
0
/*!
    Displays a prompt indicating that a ROAP action failed and the \a error, the \a triggerStatus contains the
    details of the ROAP action.
*/
void BSciPrompts::notifyFailure( SBSciRoapStatus *triggerStatus, int error ) const
{
    switch( triggerStatus->event )
    {
    case TT_Register:
        instance()->notifyRegistrationFailure(
                triggerStatus->riAlias,
                triggerStatus->domainAlias,
                formatError( error ) );
        break;
    case TT_JoinDomain:
        instance()->notifyDomainFailure(
                triggerStatus->domainAlias,
                JoinDomain,
                formatError( error ) );
        break;
    case TT_LeaveDomain:
        instance()->notifyDomainFailure(
                triggerStatus->domainAlias,
                LeaveDomain,
                formatError( error ) );
        break;
    default:
        instance()->notifyError( BSciDrm::getError( error ) + QLatin1Char( '\n' ) + formatError( error ) );
    }
}
示例#2
0
// This imports the certificates in a given Windows certificate store into an
// X509_STORE for
// openssl to use during certificate validation.
static int importCertStoreToX509_STORE(
    LPWSTR storeName, DWORD storeLocation, X509_STORE* verifyStore, char* err, size_t err_len) {
    int status = 1;
    X509* x509Cert = NULL;
    HCERTSTORE systemStore =
        CertOpenStore(CERT_STORE_PROV_SYSTEM_W, 0, (HCRYPTPROV)NULL, storeLocation | CERT_STORE_READONLY_FLAG, storeName);
    if (systemStore == NULL) {
	formatError(GetLastError(),"error opening system CA store",err,err_len);
        status = 0;
        goto CLEANUP;
    }

    PCCERT_CONTEXT certCtx = NULL;
    while ((certCtx = CertEnumCertificatesInStore(systemStore, certCtx)) != NULL) {
        const uint8_t * certBytes = (const uint8_t *)(certCtx->pbCertEncoded);
        x509Cert = d2i_X509(NULL, &certBytes, certCtx->cbCertEncoded);
        if (x509Cert == NULL) {
	    // 120 from the SSL documentation for ERR_error_string
            static const size_t msglen = 120;
            char msg[msglen];
            ERR_error_string_n(ERR_get_error(), msg, msglen);
            snprintf(
                err, err_len, "Error parsing X509 object from Windows certificate store %s", msg);
            status = 0;
            goto CLEANUP;
        }

        if (1 != X509_STORE_add_cert(verifyStore, x509Cert)) {
            int store_error_status = checkX509_STORE_error(err, err_len);
            if (!store_error_status) {
                status = 0;
                goto CLEANUP;
            }
        }
    }
    DWORD lastError = GetLastError();
    if (lastError != CRYPT_E_NOT_FOUND) {
	formatError(lastError,"Error enumerating certificates",err,err_len);
        status = 0;
        goto CLEANUP;
    }

CLEANUP:
    if (systemStore != NULL) {
        CertCloseStore(systemStore, 0);
    }
    if (x509Cert != NULL) {
        X509_free(x509Cert);
    }
    return status;
}
示例#3
0
文件: Misc.cpp 项目: Blade2187/armips
void Logger::queueError(ErrorType type, const std::wstring& text)
{
	QueueEntry entry;
	entry.type = type;
	entry.text = formatError(type,text);
	queue.push_back(entry);
}
示例#4
0
//*****************************************************************************
// SMManager::~SMManager
//*****************************************************************************
SMManager::~SMManager()
{
   for (Impl::DllList::iterator i = theImpl->theDlls.begin();
        i != theImpl->theDlls.end();
        ++i)
   {
      if(*i)
      {
#ifdef _WIN32
         if(!FreeLibrary(*i))
         {
            std::cout << "~SMManager:    error: " << formatError(GetLastError())
            << std::endl;
         }
#else
         if (0 != dlclose(*i))
         {
            std::cout << "~SMManager:    error: " << dlerror() << std::endl;
         }
#endif
      }
   }
   
   delete theImpl;
}
示例#5
0
QString QUsbHid::errorString()const
{
    QString res;
#ifdef Q_OS_WIN
    LPTSTR lpMsgBuf = 0;
    DWORD ret = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
                  0,
                  lastErr,
                  MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                  (LPTSTR) &lpMsgBuf, 0, 0);
#ifdef UNICODE
    res = QString::fromWCharArray( (LPTSTR)lpMsgBuf);
#else
    res =  QString::fromLocal8Bit((LPTSTR) lpMsgBuf);
#endif
    res.remove(QChar('\n'));
    LocalFree(lpMsgBuf);
    (void)ret;
#endif

#ifdef Q_OS_UNIX
    res = formatError(lastErr);
#endif
    if(LIBUSB_ERROR_ACCESS == lastErr ){
        res += permissionError;
    }
    return res;
}
BenchmarkTcpClient::BenchmarkTcpClient(
	Socket &socket,
	Event::Manager &eventManager,
	Container &container,
	StatList &stats,
	int requestsCount,
	int requestSize,
	int answerSize
):
	SimpleTcpClient(socket, eventManager),
	eventClose(*this, eventManager, socket.sourceClose),
	container(&container),
	stats(&stats),
	server(requestsCount == 0),
	requestsCount(server ? 0 : requestsCount),
	requestSize(server ? 0 : requestSize),
	answerSize(server ? 0 : answerSize),
	requestsCountRemain(requestsCount),
	requestSizeRemain(),
	answerSizeRemain(),
	currentSeed((unsigned int)Platform::nowUs()%RAND_MAX),
	currentCrc32(),
	beginUs(Platform::nowUs()),
	endUs(-1),
	receviedSize()
{
	container.insert(this);
	eventClose.setTimeRelativeNow();
	if (!server) {
		if (requestsCountRemain <= 0 || requestSize <= 0 || answerSize <= 0)
			formatError(); else buildWriteChunk();
	}
}
示例#7
0
文件: Misc.cpp 项目: Blade2187/armips
void Logger::printError(ErrorType type, const std::wstring& text)
{
	std::wstring errorText = formatError(type,text);
	errors.push_back(errorText);
	printLine(errorText);
	setFlags(type);
}
示例#8
0
void MaClient::timeout(MprTimer *tp)
{
	int			now;

	now = mprGetTime(0);
	if (now >= (timestamp + timeoutPeriod)) {
		mprError(MPR_L, MPR_LOG, "Timeout for %s", url.uri);
		lock();
		if (timer) {
			timer->dispose();
			timer = 0;
		}
		responseCode = 408;
		formatError("Timeout");
		finishRequest(1);
#if BLD_FEATURE_MULTITHREAD
		if (callback == 0) {
			completeCond->signalCond();
		}
#endif
		//
		//	finishRequest will have deleted the timer
		//
		unlock();
		return;
	}
	tp->reschedule(MPR_HTTP_TIMER_PERIOD);
}
void TcpClientManager::slot_sqlError(QString sqlError)
    // Slot ni connecté ni appellé pour l'instant
{
    formatError("Sql", sqlError);

    emit sig_sqlError(sqlError);
    emit sig_finished();
}
示例#10
0
void Handle::setUVError(const std::string& prefix, int errorno)
{
    scy::Error err;
    err.errorno = errorno;
    // err.syserr = uv.sys_errno_;
    err.message = formatError(prefix, errorno);
    setError(err);
}
示例#11
0
static void
throwIfError(HRESULT hr)
{
	if (FAILED(hr)) {
		formatError(hr);
		throw hr;
	}
}
void TcpClientManager::slot_tcpError()
    // Slot connecté au signal error()
    // Emet le signal sig_tcpError(QString)
{
    QString tcpError = errorString();
    formatError("Tcp", tcpError);

    emit sig_tcpError(tcpError);
    emit sig_finished();
}
void BenchmarkTcpClient::buildWriteChunk() {
	if (writeBuffer.empty()) {
		if (server) {
			if (answerSizeRemain > 0) {
				int size = std::min(answerSizeRemain, 1024);
				writeBuffer.reserve(size);
				for(char *c = (char*)writeBuffer.end(), *end = c + size; c != end; ++c)
					*c = (int)random(currentSeed)%256 - 128;
				writeBuffer.push(size);
				answerSizeRemain -= size;
				eventWrite.setTimeRelativeNow();
				if (answerSizeRemain <= 0) {
					requestSize = -1;
					answerSize = -1;
				}
			}
		} else {
			int size = std::min(requestSize + 3*(int)sizeof(int), 1024);
			writeBuffer.reserve(size);
			if (requestsCountRemain == requestsCount) {
				pushInt(requestsCount);
				requestSizeRemain = requestSize;
			}
			if (requestSizeRemain == requestSize) {
				if (requestsCountRemain <= 0 || requestSize <= 0 || answerSize <= 0)
					{ formatError(); return; }
				pushInt(requestSize);
				pushInt(answerSize);
				--requestsCountRemain;
			}
			if (requestSizeRemain > 0) {
				size -= writeBuffer.size();
				size = std::min(requestSizeRemain, size);
				if (size > 0) {
					for(char *c = (char*)writeBuffer.end(), *end = c + size; c != end; ++c)
						*c = (int)random(currentSeed)%256 - 128;
					currentCrc32 = Packet::crc32(writeBuffer.end(), size, currentCrc32);
					writeBuffer.push(size);
					requestSizeRemain -= size;
				}
				if (requestSizeRemain <= 0) {
					answerSizeRemain = answerSize;
					currentSeed = currentCrc32;
					currentCrc32 = 0;
				}
				eventWrite.setTimeRelativeNow();
			}
		}
	}
}
示例#14
0
int MaClient::parseFirst(char *line)
{
	char	*code, *tok;

	mprAssert(line && *line);

	responseProto = mprStrTok(line, " \t", &tok);
	if (responseProto == 0 || responseProto[0] == '\0') {
		formatError("Bad HTTP response");
		responseCode = MPR_HTTP_CLIENT_ERROR;
		finishRequest(1);
		return MPR_ERR_BAD_STATE;
	}
	responseProto = mprStrdup(responseProto);

	if (strncmp(responseProto, "HTTP/1.", 7) != 0) {
		formatError("Unsupported protocol: %s", responseProto);
		responseCode = MPR_HTTP_CLIENT_ERROR;
		finishRequest(1);
		return MPR_ERR_BAD_STATE;
	}

	code = mprStrTok(0, " \t\r\n", &tok);
	if (code == 0 || *code == '\0') {
		formatError("Bad HTTP response");
		responseCode = MPR_HTTP_CLIENT_ERROR;
		finishRequest(1);
		return MPR_ERR_BAD_STATE;
	}
	responseCode = atoi(code);

	responseText = mprStrTok(0, "\r\n", &tok);
	if (responseText && *responseText) {
		responseText = mprStrdup(responseText);
	}
	return 0;
}
示例#15
0
文件: ici.cpp 项目: cor3ntin/Ici
bool ICISettingsPrivate::evaluate(ICI::IncludeStatementNode* node, ICI::StatementListNode* parent){
    currentNode = node;
    if(node->executed)
        return true;
    bool required = true;
    QString path = replace_in_string(node->path);
    if(path.at(0) == '?') {
       required = false;
       path = path.mid(1);
    }
    if(path.isEmpty()){
        errorString = formatError("include() requires a file", node);
        return false;
    }
    QDir dir(QFileInfo(node->file).absolutePath());
    path = dir.absoluteFilePath(path);
    QStringList paths;
    if(QFileInfo(path).isDir()){
        Q_FOREACH(const QFileInfo & file, QDir(path).entryInfoList(QDir::NoDotAndDotDot|QDir::Files)){
            //qDebug() << file.absoluteFilePath();
            paths << file.absoluteFilePath();
        }
    }
示例#16
0
文件: registry.c 项目: Bgods/r-source
SEXP readRegistry(SEXP call, SEXP op, SEXP args, SEXP env)
{
    SEXP ans;
    HKEY hive, hkey;
    LONG res;
    const wchar_t *key;
    int maxdepth, view;
    REGSAM acc = KEY_READ;

    args = CDR(args);
    if(!isString(CAR(args)) || LENGTH(CAR(args)) != 1)
	error(_("invalid '%s' value"),  "key");
    key = filenameToWchar(STRING_ELT(CAR(args), 0), 0);
    if(!isString(CADR(args)) || LENGTH(CADR(args)) != 1)
	error(_("invalid '%s' value"),  "hive");
    maxdepth = asInteger(CADDR(args));
    if(maxdepth == NA_INTEGER || maxdepth < 1)
	error(_("invalid '%s' value"),  "maxdepth");
    hive = find_hive(CHAR(STRING_ELT(CADR(args), 0)));
    view = asInteger(CADDDR(args));
    /* Or KEY_READ with KEY_WOW64_64KEY or KEY_WOW64_32KEY to
       explicitly access the 64- or 32- bit registry view.  See
       http://msdn.microsoft.com/en-us/library/aa384129(VS.85).aspx
    */
    if(view == 2) acc |= KEY_WOW64_32KEY;
    else if(view == 3) acc |= KEY_WOW64_64KEY;

    res = RegOpenKeyExW(hive, key, 0, acc, &hkey);
    if (res == ERROR_FILE_NOT_FOUND)
	error(_("Registry key '%ls' not found"), key);
    if (res != ERROR_SUCCESS)
	error("RegOpenKeyEx error code %d: '%s'", (int) res, formatError(res));
    ans = readRegistryKey(hkey, maxdepth, view);
    RegCloseKey(hkey);
    return ans;
}
示例#17
0
文件: extra.c 项目: csilles/cxxr
	/* GetNativeSystemInfo is XP or later */
	pGNSI = (PGNSI)
	    GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")),
			   "GetNativeSystemInfo");
	if(NULL != pGNSI) pGNSI(&si); else GetSystemInfo(&si);
	if(si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64)
	    strcat(ver, " x64");
    }
    SET_STRING_ELT(ans, 1, mkChar(ver));

    if((int)osvi.dwMajorVersion >= 5) {
	if(osvi.wServicePackMajor > 0)
	    snprintf(ver, 256, "build %d, Service Pack %d",
		     LOWORD(osvi.dwBuildNumber),
		     (int) osvi.wServicePackMajor);
	else snprintf(ver, 256, "build %d", LOWORD(osvi.dwBuildNumber));
    } else
	snprintf(ver, 256, "build %d, %s",
		 LOWORD(osvi.dwBuildNumber), osvi.szCSDVersion);
    SET_STRING_ELT(ans, 2, mkChar(ver));
    GetComputerNameW(name, &namelen);
    wcstoutf8(buf, name, 1000);
    SET_STRING_ELT(ans, 3, mkCharCE(buf, CE_UTF8));
#ifdef WIN64
    SET_STRING_ELT(ans, 4, mkChar("x86-64"));
#else
    SET_STRING_ELT(ans, 4, mkChar("x86"));
#endif
    GetUserNameW(user, &userlen);
    wcstoutf8(buf, user, 1000);
    SET_STRING_ELT(ans, 5, mkCharCE(buf, CE_UTF8));
    SET_STRING_ELT(ans, 6, STRING_ELT(ans, 5));
    SET_STRING_ELT(ans, 7, STRING_ELT(ans, 5));
    PROTECT(ansnames = allocVector(STRSXP, 8));
    SET_STRING_ELT(ansnames, 0, mkChar("sysname"));
    SET_STRING_ELT(ansnames, 1, mkChar("release"));
    SET_STRING_ELT(ansnames, 2, mkChar("version"));
    SET_STRING_ELT(ansnames, 3, mkChar("nodename"));
    SET_STRING_ELT(ansnames, 4, mkChar("machine"));
    SET_STRING_ELT(ansnames, 5, mkChar("login"));
    SET_STRING_ELT(ansnames, 6, mkChar("user"));
    SET_STRING_ELT(ansnames, 7, mkChar("effective_user"));
    setAttrib(ans, R_NamesSymbol, ansnames);
    UNPROTECT(2);
    return ans;
}

SEXP do_syssleep(SEXP call, SEXP op, SEXP args, SEXP rho)
{
    DWORD mtime;
    int ntime;
    double time;

    checkArity(op, args);
    time = asReal(CAR(args));
    if (ISNAN(time) || time < 0)
	errorcall(call, _("invalid '%s' value"), "time");
    ntime = 1000*(time) + 0.5;
    while (ntime > 0) {
	mtime = min(500, ntime);
	ntime -= mtime;
	Sleep(mtime);
	R_ProcessEvents();
    }
    return R_NilValue;
}

#ifdef LEA_MALLOC
#define MALLINFO_FIELD_TYPE size_t
struct mallinfo {
    MALLINFO_FIELD_TYPE arena;    /* non-mmapped space allocated from system */
    MALLINFO_FIELD_TYPE ordblks;  /* number of free chunks */
    MALLINFO_FIELD_TYPE smblks;   /* number of fastbin blocks */
    MALLINFO_FIELD_TYPE hblks;    /* number of mmapped regions */
    MALLINFO_FIELD_TYPE hblkhd;   /* space in mmapped regions */
    MALLINFO_FIELD_TYPE usmblks;  /* maximum total allocated space */
    MALLINFO_FIELD_TYPE fsmblks;  /* space available in freed fastbin blocks */
    MALLINFO_FIELD_TYPE uordblks; /* total allocated space */
    MALLINFO_FIELD_TYPE fordblks; /* total free space */
    MALLINFO_FIELD_TYPE keepcost; /* top-most, releasable (via malloc_trim) space */
};
extern R_size_t R_max_memory;

struct mallinfo mallinfo(void);
#endif 

SEXP in_memsize(SEXP ssize)
{
    SEXP ans;
    int maxmem = NA_LOGICAL;

    if(isLogical(ssize)) 
	maxmem = asLogical(ssize);
    else if(isReal(ssize)) {
	R_size_t newmax;
	double mem = asReal(ssize);
	if (!R_FINITE(mem))
	    error(_("incorrect argument"));
#ifdef LEA_MALLOC
#ifndef WIN64
	if(mem >= 4096)
	    error(_("don't be silly!: your machine has a 4Gb address limit"));
#endif
	newmax = mem * 1048576.0;
	if (newmax < R_max_memory)
	    warning(_("cannot decrease memory limit: ignored"));
	else
	    R_max_memory = newmax;
#endif
    } else
	error(_("incorrect argument"));
	
    PROTECT(ans = allocVector(REALSXP, 1));
#ifdef LEA_MALLOC
    if(maxmem == NA_LOGICAL)
	REAL(ans)[0] = R_max_memory;
    else if(maxmem)
	REAL(ans)[0] = mallinfo().usmblks;
    else
	REAL(ans)[0] = mallinfo().uordblks;
    REAL(ans)[0] /= 1048576.0;
#else
    REAL(ans)[0] = NA_REAL;
#endif
    UNPROTECT(1);
    return ans;
}

SEXP do_dllversion(SEXP call, SEXP op, SEXP args, SEXP rho)
{
    SEXP path = R_NilValue, ans;
    const wchar_t *dll;
    DWORD dwVerInfoSize;
    DWORD dwVerHnd;

    checkArity(op, args);
    path = CAR(args);
    if(!isString(path) || LENGTH(path) != 1)
	errorcall(call, _("invalid '%s' argument"), "path");
    dll = filenameToWchar(STRING_ELT(path, 0), FALSE);
    dwVerInfoSize = GetFileVersionInfoSizeW(dll, &dwVerHnd);
    PROTECT(ans = allocVector(STRSXP, 2));
    SET_STRING_ELT(ans, 0, mkChar(""));
    SET_STRING_ELT(ans, 1, mkChar(""));
    if (dwVerInfoSize) {
	BOOL  fRet;
	LPSTR lpstrVffInfo;
	LPSTR lszVer = NULL;
	UINT  cchVer = 0;

	lpstrVffInfo = (LPSTR) malloc(dwVerInfoSize);
	if (GetFileVersionInfoW(dll, 0L, dwVerInfoSize, lpstrVffInfo)) {

	    fRet = VerQueryValue(lpstrVffInfo,
				 TEXT("\\StringFileInfo\\040904E4\\FileVersion"),
				 (LPVOID)&lszVer, &cchVer);
	    if(fRet) SET_STRING_ELT(ans, 0, mkChar(lszVer));

	    fRet = VerQueryValue(lpstrVffInfo,
				 TEXT("\\StringFileInfo\\040904E4\\R Version"),
				 (LPVOID)&lszVer, &cchVer);
	    if(fRet) SET_STRING_ELT(ans, 1, mkChar(lszVer));
	    else {
		fRet = VerQueryValue(lpstrVffInfo,
				     TEXT("\\StringFileInfo\\040904E4\\Compiled under R Version"),
				     (LPVOID)&lszVer, &cchVer);
		if(fRet) SET_STRING_ELT(ans, 1, mkChar(lszVer));
	    }

	} else ans = R_NilValue;
	free(lpstrVffInfo);
    } else ans = R_NilValue;
    UNPROTECT(1);
    return ans;
}



int Rwin_rename(const char *from, const char *to)
{
    return (MoveFileEx(from, to, MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED | MOVEFILE_WRITE_THROUGH) == 0);
}

int Rwin_wrename(const wchar_t *from, const wchar_t *to)
{
    return (MoveFileExW(from, to, MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED | MOVEFILE_WRITE_THROUGH) == 0);
}


const char *formatError(DWORD res)
{
    static char buf[1000], *p;
    FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
		  NULL, res,
		  MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
		  buf, 1000, NULL);
    p = buf+strlen(buf) -1;
    if(*p == '\n') *p = '\0';
    p = buf+strlen(buf) -1;
    if(*p == '\r') *p = '\0';
    p = buf+strlen(buf) -1;
    if(*p == '.') *p = '\0';
    return buf;
}


void R_UTF8fixslash(char *s); /* from main/util.c */
SEXP do_normalizepath(SEXP call, SEXP op, SEXP args, SEXP rho)
{
    SEXP ans, paths = CAR(args), el, slash;
    int i, n = LENGTH(paths), res;
    char tmp[MAX_PATH], longpath[MAX_PATH], *tmp2;
    wchar_t wtmp[32768], wlongpath[32768], *wtmp2;
    int mustWork, fslash = 0;

    checkArity(op, args);
    if(!isString(paths))
	errorcall(call, _("'path' must be a character vector"));

    slash = CADR(args);
    if(!isString(slash) || LENGTH(slash) != 1)
	errorcall(call, "'winslash' must be a character string");
    const char *sl = CHAR(STRING_ELT(slash, 0));
    if (strcmp(sl, "/") && strcmp(sl, "\\"))
	errorcall(call, "'winslash' must be '/' or '\\\\'");
    if (strcmp(sl, "/") == 0) fslash = 1;
    
    mustWork = asLogical(CADDR(args));

    PROTECT(ans = allocVector(STRSXP, n));
    for (i = 0; i < n; i++) {
    	int warn = 0;
    	SEXP result;
	el = STRING_ELT(paths, i);
	result = el;
	if(getCharCE(el) == CE_UTF8) {
	    if ((res = GetFullPathNameW(filenameToWchar(el, FALSE), 32768, 
					wtmp, &wtmp2)) && res <= 32768) {
		if ((res = GetLongPathNameW(wtmp, wlongpath, 32768))
		    && res <= 32768) {
	    	    wcstoutf8(longpath, wlongpath, wcslen(wlongpath)+1);
		    if(fslash) R_UTF8fixslash(longpath);
	    	    result = mkCharCE(longpath, CE_UTF8);
		} else if(mustWork == 1) {
		    errorcall(call, "path[%d]=\"%s\": %s", i+1, 
			      translateChar(el), 
			      formatError(GetLastError()));	
	    	} else {
	    	    wcstoutf8(tmp, wtmp, wcslen(wtmp)+1);
		    if(fslash) R_UTF8fixslash(tmp);
	    	    result = mkCharCE(tmp, CE_UTF8);
	    	    warn = 1;
	    	}
	    } else if(mustWork == 1) {
		errorcall(call, "path[%d]=\"%s\": %s", i+1, 
			  translateChar(el), 
			  formatError(GetLastError()));	
	    } else {
		if (fslash) {
		    strcpy(tmp, translateCharUTF8(el));
		    R_UTF8fixslash(tmp);
	    	    result = mkCharCE(tmp, CE_UTF8);
		}
	    	warn = 1;
	    }
	    if (warn && (mustWork == NA_LOGICAL))
	    	warningcall(call, "path[%d]=\"%ls\": %s", i+1, 
			    filenameToWchar(el,FALSE), 
			    formatError(GetLastError()));
	} else {
	    if ((res = GetFullPathName(translateChar(el), MAX_PATH, tmp, &tmp2)) 
		&& res <= MAX_PATH) {
	    	if ((res = GetLongPathName(tmp, longpath, MAX_PATH))
		    && res <= MAX_PATH) {
		    if(fslash) R_fixslash(longpath);
	    	    result = mkChar(longpath);
		} else if(mustWork == 1) {
		    errorcall(call, "path[%d]=\"%s\": %s", i+1, 
			      translateChar(el), 
			      formatError(GetLastError()));	
	    	} else {
		    if(fslash) R_fixslash(tmp);
	    	    result = mkChar(tmp);
	    	    warn = 1;
	    	}
	    } else if(mustWork == 1) {
		errorcall(call, "path[%d]=\"%s\": %s", i+1, 
			  translateChar(el), 
			  formatError(GetLastError()));	
	    } else {
		if (fslash) {
		    strcpy(tmp, translateChar(el));
		    R_fixslash(tmp);
		    result = mkChar(tmp);
		}
	    	warn = 1;
	    }
	    if (warn && (mustWork == NA_LOGICAL))
		warningcall(call, "path[%d]=\"%s\": %s", i+1, 
			    translateChar(el), 
			    formatError(GetLastError()));	
	}
	SET_STRING_ELT(ans, i, result);
    }
    UNPROTECT(1);
    return ans;
}
示例#18
0
int MaClient::parseHeader(char *line)
{
	char	*key, *value, *tok, *tp;

	mprAssert(line && *line);

	if ((key = mprStrTok(line, ": \t\n", &tok)) == 0) {
		formatError("Bad HTTP header");
		responseCode = MPR_HTTP_CLIENT_ERROR;
		finishRequest(1);
		return MPR_ERR_BAD_STATE;
	}
	if ((value = mprStrTok(0, "\n", &tok)) == 0) {
		value = "";
	}
	while (isspace((uchar) *value)) {
		value++;
	}

	//	Upper to be consistent with Request?
	mprStrLower(key);
	headerValues->insert(new MprStringHashEntry(key, value));

	if (strcmp("www-authenticate", key) == 0) {
		tp = value;
		while (*value && !isspace((uchar) *value)) {
			value++;
		}
		*value++ = '\0';
		mprStrLower(tp);
		mprFree(serverAuthType);
		serverAuthType = mprStrdup(tp);

		if (parseAuthenticate(value) < 0) {
			formatError("Bad Authenticate header");
			responseCode = MPR_HTTP_CLIENT_ERROR;
			finishRequest(1);
			return MPR_ERR_BAD_STATE;
		}

	} else if (strcmp("content-length", key) == 0) {
		contentLength = atoi(value);
		if (mprStrCmpAnyCase(method, "HEAD") != 0) {
			contentRemaining = atoi(value);
		}

	} else if (strcmp("connection", key) == 0) {
		mprStrLower(value);
		if (strcmp(value, "close") == 0) {
			flags &= ~MPR_HTTP_KEEP_ALIVE;
#if BLD_FEATURE_KEEP_ALIVE
		} else if (strcmp(value, "keep-alive") == 0) {
			if (userFlags & MPR_HTTP_KEEP_ALIVE) {
				flags |= MPR_HTTP_KEEP_ALIVE;
			}
#endif
		}
	} else if (strcmp("transfer-encoding", key) == 0) {
		mprStrLower(value);
		if (strcmp(value, "chunked") == 0) {
			flags |= MPR_HTTP_INPUT_CHUNKED;
		}
	}
	return 0;
}
/*
    Pull operation version of SendResponse.  This adds one additional
    parameter (bodyParamsIn) that contains the parameters.  This is because
    the parameters are added only on the the final segment of a chunk
*/
void CIMOperationResponseEncoder::sendResponsePull(
    CIMResponseMessage* response,
    const String& name,
    Boolean isImplicit,
    Buffer* bodyParams,
    Buffer* bodygiven)
{
    PEG_METHOD_ENTER(TRC_DISPATCHER,
        "CIMOperationResponseEncoder::sendResponse");
    PEG_TRACE((TRC_HTTP, Tracer::LEVEL4,
        "name = %s",
        (const char*)name.getCString()));

    if (! response)
    {
        PEG_METHOD_EXIT();
        return;
    }

    Uint32 queueId = response->queueIds.top();

    Boolean closeConnect = response->getCloseConnect();
    PEG_TRACE((
        TRC_HTTP,
        Tracer::LEVEL4,
        "CIMOperationResponseEncoder::sendResponse()- "
            "response->getCloseConnect() returned %d",
        closeConnect));

    MessageQueue* queue = MessageQueue::lookup(queueId);

    if (!queue)
    {
        PEG_TRACE((TRC_DISCARDED_DATA, Tracer::LEVEL1,
            "ERROR: non-existent queueId = %u, response not sent.", queueId));
        PEG_METHOD_EXIT();
        return;
    }

    HttpMethod httpMethod = response->getHttpMethod();
    String& messageId = response->messageId;
    CIMException& cimException = response->cimException;
    Buffer message;

    // Note: the language is ALWAYS passed empty to the xml formatters because
    // it is HTTPConnection that needs to make the decision of whether to add
    // the languages to the HTTP message.
    ContentLanguageList contentLanguage;

    CIMName cimName(name);
    Uint32 messageIndex = response->getIndex();
    Boolean isFirst = messageIndex == 0 ? true : false;
    Boolean isLast = response->isComplete();
    Buffer bodylocal;
    Buffer& body = bodygiven ? *bodygiven : bodylocal;

    Buffer& bodyParamsBuf = bodyParams ? *bodyParams : bodylocal;

    // STAT_SERVEREND sets the getTotalServerTime() value in the message class
    STAT_SERVEREND

#ifndef PEGASUS_DISABLE_PERFINST
    Uint64 serverTime = response->getTotalServerTime();
#else
    Uint64 serverTime = 0;
#endif

    Buffer (*formatResponse)(
        const CIMName& iMethodName,
        const String& messageId,
        HttpMethod httpMethod,
        const ContentLanguageList& httpContentLanguages,
        const Buffer& bodyParams,
        const Buffer& body,
        Uint64 serverResponseTime,
        Boolean isFirst,
        Boolean isLast);

    Buffer (*formatError)(
        const CIMName& methodName,
        const String& messageId,
        HttpMethod httpMethod,
        const CIMException& cimException);

    if (isImplicit == false)
    {
        formatResponse = XmlWriter::formatSimpleMethodRspMessage;
        formatError = XmlWriter::formatSimpleMethodErrorRspMessage;
    }
    else
    {
        formatError = XmlWriter::formatSimpleIMethodErrorRspMessage;

        if (response->binaryResponse)
        {
            formatResponse = BinaryCodec::formatSimpleIMethodRspMessage;
        }
        else
        {
            formatResponse = XmlWriter::formatSimpleIMethodRspMessage;
        }
    }

    if (cimException.getCode() != CIM_ERR_SUCCESS)
    {
        HTTPConnection* httpQueue = dynamic_cast<HTTPConnection*>(queue);
        Boolean isChunkRequest = false;
        Boolean isFirstError = true;

        // Note:  The WMI Mapper may use a non-HTTPConnection queue here.
        if (httpQueue)
        {
            isChunkRequest = httpQueue->isChunkRequested();
            isFirstError =
                (httpQueue->cimException.getCode() == CIM_ERR_SUCCESS);
        }

        // only process the FIRST error
        if (isFirstError)
        {
            // NOTE: even if this error occurs in the middle, HTTPConnection
            // will flush the entire queued message and reformat.
            if (isChunkRequest == false)
            {
                message =
                    formatError(name, messageId, httpMethod, cimException);
            }

            // uri encode the error (for the http header) only when it is
            // non-chunking or the first error with chunking
            if (isChunkRequest == false ||
                (isChunkRequest == true && isFirst == true))
            {
                String msg =
                    TraceableCIMException(cimException).getDescription();
                String uriEncodedMsg = XmlWriter::encodeURICharacters(msg);
                CIMException cimExceptionUri(
                    cimException.getCode(), uriEncodedMsg);
                cimExceptionUri.setContentLanguages(
                    cimException.getContentLanguages());
                cimException = cimExceptionUri;
            }
        } // if first error in response stream

        // never put the error in chunked response (because it will end up in
        // the trailer), so just use the non-error response formatter to send
        // more data

        if (isChunkRequest == true)
        {
            message = formatResponse(
                cimName,
                messageId,
                httpMethod,
                contentLanguage,
                bodyParamsBuf,
                body,
                serverTime,
                isFirst,
                isLast);
        }
    }
    else
    {
        // else non-error condition
        try
        {
            message = formatResponse(
                cimName,
                messageId,
                httpMethod,
                contentLanguage,
                bodyParamsBuf,
                body,
                serverTime,
                isFirst,
                isLast);
        }
        catch (PEGASUS_STD(bad_alloc)&)
        {
            MessageLoaderParms parms(
                "Server.CIMOperationResponseEncoder.OUT_OF_MEMORY",
                "A System error has occurred. Please retry the CIM Operation "
                    "at a later time.");

            Logger::put_l(
                Logger::ERROR_LOG, System::CIMSERVER, Logger::WARNING,
                parms);

            cimException = PEGASUS_CIM_EXCEPTION_L(CIM_ERR_FAILED, parms);

            // try again with new error and no body
            body.clear();
            sendResponse(response, name, isImplicit);
            PEG_METHOD_EXIT();
            return;
        }

        STAT_BYTESSENT
    }

    AutoPtr<HTTPMessage> httpMessage(
        new HTTPMessage(message, 0, &cimException));
    httpMessage->setComplete(isLast);
    httpMessage->setIndex(messageIndex);
    httpMessage->binaryResponse = response->binaryResponse;

    if (cimException.getCode() != CIM_ERR_SUCCESS)
    {
        httpMessage->contentLanguages = cimException.getContentLanguages();
    }
    else
    {
        const OperationContext::Container& container =
            response->operationContext.get(ContentLanguageListContainer::NAME);
        const ContentLanguageListContainer& listContainer =
            *dynamic_cast<const ContentLanguageListContainer*>(&container);
        contentLanguage = listContainer.getLanguages();
        httpMessage->contentLanguages = contentLanguage;
    }

    httpMessage->setCloseConnect(closeConnect);

    queue->enqueue(httpMessage.release());

    PEG_METHOD_EXIT();
}
void BenchmarkTcpClient::handle(Event &event, long long) {
	if (&event == &eventRead) {
		int prevSize = readBuffer.size();
		readBuffer.reserve(1024);
		readBuffer.push(socket->read(readBuffer.end(), 1024));
		receviedSize += readBuffer.size() - prevSize;
		eventRead.setTimeRelativeNow();

		if (readBuffer.empty()) return;
		if (!writeBuffer.empty())
			{ formatError(); return; }

		if (server) {
			if (hasInt() && !requestsCount) {
				requestsCount = popInt();
				if (requestsCount <= 0)
					{ formatError(); return; }
				requestsCountRemain = requestsCount;
			}
			if (hasInt() && !requestSize) {
				requestSize = popInt();
				if (requestSize <= 0)
					{ formatError(); return; }
				if (requestsCountRemain <= 0)
					{ formatError(); return; }
				--requestsCountRemain;
			}
			if (hasInt() && !answerSize) {
				answerSize = popInt();
				if (answerSize <= 0)
					{ formatError(); return; }
				requestSizeRemain = requestSize;
			}
			if (requestSizeRemain > 0) {
				currentCrc32 = Packet::crc32(readBuffer.begin(), readBuffer.size(), currentCrc32);
				requestSizeRemain -= readBuffer.size();
				readBuffer.clear();
				if (requestSizeRemain < 0)
					{ formatError(); return; }
				if (requestSizeRemain == 0) {
					currentSeed = currentCrc32;
					currentCrc32 = 0;
					answerSizeRemain = answerSize;
					buildWriteChunk();
				}
			}
		} else {
			while(!empty()) {
				if (answerSizeRemain <= 0 || pop() != (char)((int)random(currentSeed)%256 - 128))
					{ formatError(); return; }
				--answerSizeRemain;
			}
			if (answerSizeRemain == 0) {
				if (requestsCountRemain == 0)
					{ socket->close(); return; }
				requestSizeRemain = requestSize;
				buildWriteChunk();
			}
		}
	} else
	if (&event == &eventWrite) {
		if (writeBuffer.empty()) return;
		if (!readBuffer.empty())
			{ formatError(); return ; }

		if (!writeBuffer.empty())
			writeBuffer.pop(socket->write(writeBuffer.begin(), writeBuffer.size()));
		buildWriteChunk();
		if (!writeBuffer.empty())
			eventWrite.setTimeRelativeNow();
	} else
	if (&event == &eventClose) {
		if ( !socket->wasError()
		  && requestsCountRemain == 0
		  && requestSizeRemain == 0
		  && answerSizeRemain == 0
		  && readBuffer.empty()
		  && writeBuffer.empty())
			endUs = Platform::nowUs();
		delete this;
	}
}
示例#21
0
fostlib::string fostlib::formatLastError() {
    return formatError(GetLastError());
}
示例#22
0
void XML_EIDTagHandler::fatalError(const SAXParseException& e)
{
	std::string errMsg;
	formatError(e,m_fileName,errMsg);
	throw e;
}
示例#23
0
TestException::TestException (const char* message, const char* expr, const char* file, int line, qpTestResult result)
	: Exception	(formatError(message, expr, file, line))
	, m_result	(result)
{
}
示例#24
0
Exception::Exception (const char* message, const char* expr, const char* file, int line)
	: std::runtime_error(formatError(message, expr, file, line))
	, m_message			(message ? message : "Runtime check failed")
{
}
示例#25
0
void TRendererError::displayMessage() {
	std::string strCaption;
	DISPLAY_MESSAGE(m_message.c_str(), formatError(strCaption, m_code, m_severity));
}
示例#26
0
文件: registry.c 项目: Bgods/r-source
static SEXP readRegistryKey(HKEY hkey, int depth, int view)
{
    int i, k = 0, size0, *indx;
    SEXP ans, nm, ans0, nm0, tmp, sind;
    DWORD res, nsubkeys, maxsubkeylen, nval, maxvalnamlen, size;
    wchar_t *name;
    HKEY sub;
    REGSAM acc = KEY_READ;

    if (depth <= 0) return mkString("<subkey>");

    if(view == 2) acc |= KEY_WOW64_32KEY;
    else if(view == 3) acc |= KEY_WOW64_64KEY;

    res = RegQueryInfoKey(hkey, NULL, NULL, NULL,
			  &nsubkeys, &maxsubkeylen, NULL, &nval,
			  &maxvalnamlen, NULL, NULL, NULL);
    if (res != ERROR_SUCCESS)
	error("RegQueryInfoKey error code %d: '%s'", (int) res,
	      formatError(res));
    size0 = max(maxsubkeylen, maxvalnamlen) + 1;
    name = (wchar_t *) R_alloc(size0, sizeof(wchar_t));
    PROTECT(ans = allocVector(VECSXP, nval + nsubkeys));
    PROTECT(nm = allocVector(STRSXP, nval+ nsubkeys));
    if (nval > 0) {
	PROTECT(ans0 = allocVector(VECSXP, nval));
	PROTECT(nm0 = allocVector(STRSXP, nval));
	for (i = 0; i < nval; i++) {
	    size = size0;
	    res  = RegEnumValueW(hkey, i, (LPWSTR) name, &size,
				 NULL, NULL, NULL, NULL);
	    if (res != ERROR_SUCCESS) break;
	    SET_VECTOR_ELT(ans0, i, readRegistryKey1(hkey, name));
	    SET_STRING_ELT(nm0, i, mkCharUcs(name));
	}
	/* now sort by name */
	PROTECT(sind = allocVector(INTSXP, nval));  indx = INTEGER(sind);
	for (i = 0; i < nval; i++) indx[i] = i;
	orderVector1(indx, nval, nm0, TRUE, FALSE, R_NilValue);
	for (i = 0; i < nval; i++, k++) {
	    SET_VECTOR_ELT(ans, k, VECTOR_ELT(ans0, indx[i]));
	    if (LENGTH(tmp = STRING_ELT(nm0, indx[i])))
	    	SET_STRING_ELT(nm, k, tmp);
	    else
	    	SET_STRING_ELT(nm, k, mkChar("(Default)"));
	}
	UNPROTECT(3);
    }
    if (nsubkeys > 0) {
	PROTECT(ans0 = allocVector(VECSXP, nsubkeys));
	PROTECT(nm0 = allocVector(STRSXP, nsubkeys));
	for (i = 0; i < nsubkeys; i++) {
	    size = size0;
	    res = RegEnumKeyExW(hkey, i, (LPWSTR) name, &size,
				NULL, NULL, NULL, NULL);
	    if (res != ERROR_SUCCESS) break;
	    res = RegOpenKeyExW(hkey, (LPWSTR) name, 0, acc, &sub);
	    if (res != ERROR_SUCCESS) break;
	    SET_VECTOR_ELT(ans0, i, readRegistryKey(sub, depth-1, view));
	    SET_STRING_ELT(nm0, i, mkCharUcs(name));
	    RegCloseKey(sub);
	}
	/* now sort by name */
	PROTECT(sind = allocVector(INTSXP, nsubkeys));  indx = INTEGER(sind);
	for (i = 0; i < nsubkeys; i++) indx[i] = i;
	orderVector1(indx, nsubkeys, nm0, TRUE, FALSE, R_NilValue);
	for (i = 0; i < nsubkeys; i++, k++) {
	    SET_VECTOR_ELT(ans, k, VECTOR_ELT(ans0, indx[i]));
	    SET_STRING_ELT(nm, k, STRING_ELT(nm0, indx[i]));
	}
	UNPROTECT(3);
    }
    setAttrib(ans, R_NamesSymbol, nm);
    UNPROTECT(2);
    return ans;
}
示例#27
0
void Handle::throwError(const std::string& prefix, int errorno) const
{
    throw std::runtime_error(formatError(prefix, errorno));
}
示例#28
0
bool executeCommand(const UINT cmd, const csWStringList& files)
{
  const csWString parallel  = regReadParallel();
  const DWORD parallelCount = regReadParallelCount();
  const bool    hasParallel = !parallel.empty()  &&  parallelCount > 1;

  const DWORD flags      = regReadFlags();
  const bool  isBatch    = testFlags(flags, CMD_FLAG_BATCH);
  const bool  isParallel = testFlags(flags, CMD_FLAG_PARALLEL)  &&  hasParallel;
  const bool  isUnc      = testFlags(flags, CMD_FLAG_UNC)  &&  cmd != Cmd_List;
  const bool  isUnix     = testFlags(flags, CMD_FLAG_UNIX);

  const csWString  scriptPath = regReadScriptsPath();
  const csWStringList scripts = regReadScripts();

  if(        cmd == Cmd_List                ||
             cmd == Cmd_ListWithPath        ||
             cmd == Cmd_ListWithPathTabular ) {
    int size = 0;
    for(csWStringList::const_iterator it = files.begin(); it != files.end(); it++) {
      wchar_t *uncName = 0;
      if( isUnc  &&  (uncName = resolveUNC(it->c_str())) != 0 ) {
        size += lenFN(csWString(uncName), cmd);
        delete[] uncName;
      } else {
        size += lenFN(*it, cmd);
      }
    }

    wchar_t *text = new wchar_t[size+1];
    if( text == 0 ) {
      return false;
    }

    int pos = 0;
    for(csWStringList::const_iterator it = files.begin(); it != files.end(); it++) {
      wchar_t *uncName = 0;
      if( isUnc  &&  (uncName = resolveUNC(it->c_str())) != 0 ) {
        catFN(text, pos, csWString(uncName), cmd);
        delete[] uncName;
      } else {
        catFN(text, pos, *it, cmd);
      }
    }
    text[size] = L'\0';

    if( files.size() == 1 ) {
      // Overwrite trailing <CR><LF>
      text[size-1] = text[size-2] = L'\0';
    }

    if( isUnix ) {
      replace(text, size, L'\\', L'/');
    }

    setClipboardText(text);
    delete[] text;

    return true;

  } else if( cmd == Cmd_CreateSymbolicLink ) {

    csWString symLink;

    IFileSaveDialog *saveDialog = NULL;
    HRESULT hr = CoCreateInstance(CLSID_FileSaveDialog, NULL, CLSCTX_INPROC_SERVER,
                                  IID_IFileSaveDialog, (LPVOID*)&saveDialog);
    if( hr == S_OK ) {
      saveDialog->SetTitle(L"Create symbolic link");

      const int index = files.front().lastIndexOf(L'\\');
      if( index >= 0 ) {
        const csWString path = files.front().mid(0, index);
        const csWString name = files.front().mid(index+1);

        PIDLIST_ABSOLUTE pidl = NULL;
        SHParseDisplayName(path.c_str(), NULL, &pidl, 0, NULL);
        if( pidl != NULL ) {
          IShellItem *item = NULL;
          SHCreateItemFromIDList(pidl, IID_IShellItem, (LPVOID*)&item);
          if( item != NULL ) {
            saveDialog->SetFolder(item);
            item->Release();
          }
          CoTaskMemFree(pidl);
        }

        saveDialog->SetFileName(name.c_str());
      }

      const COMDLG_FILTERSPEC filterSpec = {
        L"All files", L"*.*"
      };
      saveDialog->SetFileTypes(1, &filterSpec);

      const FILEOPENDIALOGOPTIONS opts
          = FOS_OVERWRITEPROMPT
          | FOS_FORCEFILESYSTEM
          | FOS_PATHMUSTEXIST
          | FOS_CREATEPROMPT
          | FOS_NOREADONLYRETURN
          | FOS_NODEREFERENCELINKS
          | FOS_DONTADDTORECENT;
      saveDialog->SetOptions(opts);

      if( saveDialog->Show(NULL) == S_OK ) {
        IShellItem *item = NULL;
        if( saveDialog->GetResult(&item) == S_OK ) {
          wchar_t *filename = NULL;
          if( item->GetDisplayName(SIGDN_FILESYSPATH, &filename) == S_OK ) {
            symLink = filename;
            CoTaskMemFree(filename);
          }

          item->Release();
        }
      }

      saveDialog->Release();
    }

    if( !symLink.empty() ) {
      if( csFileExists(symLink.c_str()) ) {
        MessageBoxW(NULL, L"Symbolic link target already exists!",
                    L"Error", MB_OK | MB_ICONERROR);
        return false;
      }

      const DWORD linkFlags = csIsDirectory(files.front().c_str())
          ? SYMBOLIC_LINK_FLAG_DIRECTORY
          : 0;

      if( CreateSymbolicLinkW(symLink.c_str(),
                              files.front().c_str(),
                              linkFlags) == 0 ) {
        const DWORD lastError = GetLastError();

        csWString msg(L"ERROR(0x");
        msg += csWString::number(lastError, 16);
        msg += L"): ";
        msg += formatError(lastError);

        MessageBoxW(NULL, msg.c_str(),
                    L"Error", MB_OK | MB_ICONERROR);
        return false;
      }
    }

    return true;

  } else if( cmd == Cmd_CheckBatchProcessing ) {
    regWriteFlags(flags ^ CMD_FLAG_BATCH);
    return true;

  } else if( cmd == Cmd_CheckParallelExecution ) {
    regWriteFlags(flags ^ CMD_FLAG_PARALLEL);
    return true;

  } else if( cmd == Cmd_CheckResolveUncPaths ) {
    regWriteFlags(flags ^ CMD_FLAG_UNC);
    return true;

  } else if( cmd == Cmd_CheckUnixPathSeparators ) {
    regWriteFlags(flags ^ CMD_FLAG_UNIX);
    return true;

  } else if( Cmd_ExecuteScripts <= cmd  &&  cmd < Cmd_ExecuteScripts+scripts.size() ) {
    csWString script(scriptPath + L"\\");
    UINT i = 0;
    for(csWStringList::const_iterator it = scripts.begin(); it != scripts.end(); it++) {
      if( i == cmd-Cmd_ExecuteScripts ) {
        script += *it;
        break;
      }
      i++;
    }

    if( isParallel ) {
      csWStringList args(files);
      args.push_front(script);
      args.push_front(csWString::number(parallelCount));
      ShellExecuteW(NULL, L"open", parallel.c_str(), joinFileNames(args).c_str(),
                    NULL, SW_SHOWNORMAL);
    } else { // DO NOT use parallelizer
      if( isBatch ) {
        const csWString args = joinFileNames(files);
        ShellExecuteW(NULL, L"open", script.c_str(), args.c_str(), NULL, SW_SHOWNORMAL);
      } else { // NO batch processing
        for(csWStringList::const_iterator it = files.begin();
            it != files.end(); it++) {
          ShellExecuteW(NULL, L"open", script.c_str(), quoteFileName(*it).c_str(),
                        NULL, SW_SHOWNORMAL);
        }
      }
    }
    return true;

  }

  return false;
}
示例#29
0
void TRendererError::printMessage() {
	std::string strCaption;
	PRINT_MESSAGE(m_message.c_str(), formatError(strCaption, m_code, m_severity));
}
示例#30
0
QVariant KConfigGroup::convertToQVariant(const char *pKey, const QByteArray& value, const QVariant& aDefault)
{
    // if a type handler is added here you must add a QVConversions definition
    // to conversion_check.h, or ConversionCheck::to_QVariant will not allow
    // readEntry<T> to convert to QVariant.
    switch( aDefault.type() ) {
        case QVariant::Invalid:
            return QVariant();
        case QVariant::String:
            // this should return the raw string not the dollar expanded string.
            // imho if processed string is wanted should call
            // readEntry(key, QString) not readEntry(key, QVariant)
            return QString::fromUtf8(value);
        case QVariant::List:
        case QVariant::StringList:
            return KConfigGroupPrivate::deserializeList(QString::fromUtf8(value));
        case QVariant::ByteArray:
            return value;
        case QVariant::Bool: {
            const QByteArray lower(value.toLower());
            if (lower == "false" || lower == "no" || lower == "off" || lower == "0")
                return false;
            return true;
        }
        case QVariant::Double:
        case QMetaType::Float:
        case QVariant::Int:
        case QVariant::UInt:
        case QVariant::LongLong:
        case QVariant::ULongLong: {
            QVariant tmp = value;
            if ( !tmp.convert(aDefault.type()) )
                tmp = aDefault;
            return tmp;
        }
        case QVariant::Point: {
            const QList<int> list = asIntList(value);

            if ( list.count() != 2 ) {
                qWarning() << errString( pKey, value, aDefault )
                         << formatError( 2, list.count() );
                return aDefault;
            }
            return QPoint(list.at( 0 ), list.at( 1 ));
        }
        case QVariant::PointF: {
            const QList<qreal> list = asRealList(value);

            if ( list.count() != 2 ) {
                qWarning() << errString( pKey, value, aDefault )
                         << formatError( 2, list.count() );
                return aDefault;
            }
            return QPointF(list.at( 0 ), list.at( 1 ));
        }
        case QVariant::Rect: {
            const QList<int> list = asIntList(value);

            if ( list.count() != 4 ) {
                qWarning() << errString( pKey, value, aDefault )
                         << formatError( 4, list.count() );
                return aDefault;
            }
            const QRect rect(list.at( 0 ), list.at( 1 ), list.at( 2 ), list.at( 3 ));
            if ( !rect.isValid() ) {
                qWarning() << errString( pKey, value, aDefault );
                return aDefault;
            }
            return rect;
        }
        case QVariant::RectF: {
            const QList<qreal> list = asRealList(value);

            if ( list.count() != 4 ) {
                qWarning() << errString( pKey, value, aDefault )
                         << formatError( 4, list.count() );
                return aDefault;
            }
            const QRectF rect(list.at( 0 ), list.at( 1 ), list.at( 2 ), list.at( 3 ));
            if ( !rect.isValid() ) {
                qWarning() << errString( pKey, value, aDefault );
                return aDefault;
            }
            return rect;
        }
        case QVariant::Size: {
            const QList<int> list = asIntList(value);

            if ( list.count() != 2 ) {
                qWarning() << errString( pKey, value, aDefault )
                         << formatError( 2, list.count() );
                return aDefault;
            }
            const QSize size(list.at( 0 ), list.at( 1 ));
            if ( !size.isValid() ) {
                qWarning() << errString( pKey, value, aDefault );
                return aDefault;
            }
            return size;
        }
        case QVariant::SizeF: {
            const QList<qreal> list = asRealList(value);

            if ( list.count() != 2 ) {
                qWarning() << errString( pKey, value, aDefault )
                         << formatError( 2, list.count() );
                return aDefault;
            }
            const QSizeF size(list.at( 0 ), list.at( 1 ));
            if ( !size.isValid() ) {
                qWarning() << errString( pKey, value, aDefault );
                return aDefault;
            }
            return size;
        }
        case QVariant::DateTime: {
            const QList<int> list = asIntList(value);
            if ( list.count() != 6 ) {
                qWarning() << errString( pKey, value, aDefault )
                         << formatError( 6, list.count() );
                return aDefault;
            }
            const QDate date( list.at( 0 ), list.at( 1 ), list.at( 2 ) );
            const QTime time( list.at( 3 ), list.at( 4 ), list.at( 5 ) );
            const QDateTime dt( date, time );
            if ( !dt.isValid() ) {
                qWarning() << errString( pKey, value, aDefault );
                return aDefault;
            }
            return dt;
        }
        case QVariant::Date: {
            QList<int> list = asIntList(value);
            if ( list.count() == 6 )
                list = list.mid(0, 3); // don't break config files that stored QDate as QDateTime
            if ( list.count() != 3 ) {
                qWarning() << errString( pKey, value, aDefault )
                         << formatError( 3, list.count() );
                return aDefault;
            }
            const QDate date( list.at( 0 ), list.at( 1 ), list.at( 2 ) );
            if ( !date.isValid() ) {
                qWarning() << errString( pKey, value, aDefault );
                return aDefault;
            }
            return date;
        }
        case QVariant::Color:
        case QVariant::Font:
            qWarning() << "KConfigGroup::readEntry was passed GUI type '"
                    << aDefault.typeName()
                    << "' but kdeui isn't linked! If it is linked to your program, "
                    "this is a platform bug. Please inform the KDE developers";
            break;
        case QVariant::Url:
            return QUrl(QString::fromUtf8(value));

        default:
            break;
    }

    qWarning() << "unhandled type " << aDefault.typeName();
    return QVariant();
}