jstring getProxyOption(JNIEnv* env, const jobject& jobj, const int flags) { log_debug("In getProxy"); INTERNET_PER_CONN_OPTION_LIST list; INTERNET_PER_CONN_OPTION options[1]; unsigned long nSize = sizeof(INTERNET_PER_CONN_OPTION_LIST); options[0].dwOption = flags; list.dwSize = sizeof(INTERNET_PER_CONN_OPTION_LIST); list.pszConnection = NULL; list.dwOptionCount = 1; list.dwOptionError = 0; list.pOptions = options; if(!InternetQueryOption(NULL, INTERNET_OPTION_PER_CONNECTION_OPTION, &list, &nSize)) { return lastError(env); } if (options[0].Value.pszValue != NULL) { const jstring ret = env->NewStringUTF(options[0].Value.pszValue); GlobalFree(options[0].Value.pszValue); log_debug("Returning actual value"); return ret; } log_debug("Returning new string utf"); return env->NewStringUTF(""); }
int SocketImpl::receiveBytes(void* buffer, int length, int flags) { #if defined(POCO_BROKEN_TIMEOUTS) if (_recvTimeout.totalMicroseconds() != 0) { if (!poll(_recvTimeout, SELECT_READ)) throw TimeoutException(); } #endif int rc; do { if (_sockfd == POCO_INVALID_SOCKET) throw InvalidSocketException(); rc = ::recv(_sockfd, reinterpret_cast<char*>(buffer), length, flags); } while (_blocking && rc < 0 && lastError() == POCO_EINTR); if (rc < 0) { int err = lastError(); if (err == POCO_EAGAIN && !_blocking) ; else if (err == POCO_EAGAIN || err == POCO_ETIMEDOUT) throw TimeoutException(err); else error(err); } return rc; }
/*! \fn MGasto::agregarGasto( QString descripcion, double costo, QDate Fecha, int categoria ) */ bool MGasto::agregarGasto( QString descripcion, double costo, QDate Fecha, int categoria ) { QSqlTableModel::EditStrategy modo = this->editStrategy(); this->setEditStrategy( QSqlTableModel::OnManualSubmit ); QSqlRecord registro = this->record(); registro.setValue( "descripcion", descripcion ); registro.setValue( "costo", costo ); registro.setValue( "fecha", Fecha ); registro.setValue( "id_categoria", categoria ); registro.remove( 0 ); if( this->insertRecord( -1, registro ) == false ) { qDebug( "Error al insertar registro de gasto" ); qDebug() << "Detalles: tipo: " << lastError().type() << ", errno:" << lastError().number() << ", descripcion: " << lastError().text(); this->setEditStrategy( modo ); return false; } else { if( submitAll() ) { qDebug( "Gasto agregado correctamente" ); this->setEditStrategy( modo ); return true; } else { qDebug( "Error al insertar registro de gasto" ); qDebug() << "Detalles: tipo: " << lastError().type() << ", errno:" << lastError().number() << ", descripcion: " << lastError().text(); this->setEditStrategy( modo ); return false; } } }
bool SQLiteDatabase::turnOnIncrementalAutoVacuum() { SQLiteStatement statement(*this, "PRAGMA auto_vacuum"); int autoVacuumMode = statement.getColumnInt(0); int error = lastError(); // Check if we got an error while trying to get the value of the auto_vacuum flag. // If we got a SQLITE_BUSY error, then there's probably another transaction in // progress on this database. In this case, keep the current value of the // auto_vacuum flag and try to set it to INCREMENTAL the next time we open this // database. If the error is not SQLITE_BUSY, then we probably ran into a more // serious problem and should return false (to log an error message). if (error != SQLITE_ROW) return false; switch (autoVacuumMode) { case AutoVacuumIncremental: return true; case AutoVacuumFull: return executeCommand("PRAGMA auto_vacuum = 2"); case AutoVacuumNone: default: if (!executeCommand("PRAGMA auto_vacuum = 2")) return false; runVacuumCommand(); error = lastError(); return (error == SQLITE_OK); } }
bool Discovery::initBroadcast(int port) { m_receiver = SimpleUdpReceiver::create(port, true); if (!m_receiver) { LOG(logERROR) << ("Error: could not create receiver socket!") << lastError(); return false; } SOCKET soc = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (soc == -1) { LOG(logERROR) << ("Error: could not create broadcast socket!") << lastError(); return false; } #ifdef _WIN32 char yes = 1; #else int yes = 1; #endif // allow broadcast int rv = setsockopt(soc, SOL_SOCKET, SO_BROADCAST, &yes, sizeof(yes)); if (rv == -1) { LOG(logERROR) << ("Error: could not set broadcast socket options!") << lastError(); return false; } m_socBroadcast4 = soc; return true; }
QNetworkReply::NetworkError OwnCloudNetworkFactory::triggerFeedUpdate(int feed_id) { if (userId().isEmpty()) { // We need to get user ID first. OwnCloudUserResponse info = userInfo(); if (lastError() != QNetworkReply::NoError) { return lastError(); } else { // We have new user ID, set it up. setUserId(info.userId()); } } // Now, we can trigger the update. QByteArray raw_output; NetworkResult network_reply = NetworkFactory::performNetworkOperation(m_urlFeedsUpdate.arg(userId(), QString::number(feed_id)), qApp->settings()->value(GROUP(Feeds), SETTING(Feeds::UpdateTimeout)).toInt(), QByteArray(), QString(), raw_output, QNetworkAccessManager::GetOperation, true, m_authUsername, m_authPassword, true); if (network_reply.first != QNetworkReply::NoError) { qWarning("ownCloud: Feeds update failed with error %d.", network_reply.first); } return (m_lastError = network_reply.first); }
bool Table::setData(const QModelIndex &index, const QVariant &value, int role) { bool ret = QSqlTableModel::setData(index,value, role); if(ret) database()->setDirty(true); else if(lastError().isValid()) qWarning() << lastError(); return ret; }
Soprano::Error::ErrorCode Soprano::Client::DBusModel::addStatement( const Statement &statement ) { QDBusReply<int> reply = d->interface->addStatement( statement, d->callMode ); setError( DBus::convertError( reply.error() ) ); if ( lastError() ) { return Error::convertErrorCode( lastError().code() ); } else { return ( Error::ErrorCode )reply.value(); } }
bool Table::setData(int row, int column, const QVariant &data) { QSqlRecord r = record(row); r.setValue(column, data); bool ret = setRecord(row, r); if(!ret && lastError().isValid()) qWarning() << lastError(); return ret; }
std::string Path::toUTF8() const { #ifdef OSX CFRange myRange = CFRangeMake(0, CFStringGetLength(_myString)); CFIndex myBufferSize = 0; std::string myResult; CFIndex myCharCount = CFStringGetBytes(_myString, myRange, kCFStringEncodingUTF8, '?', FALSE, 0, 0, &myBufferSize); if (myCharCount) { myResult.resize(myBufferSize); CFIndex myExCharCount = CFStringGetBytes(_myString, myRange, kCFStringEncodingUTF8, '?', FALSE, (UInt8*)&(*(myResult.begin())), myBufferSize, &myBufferSize); ASSURE_WITH(AssurePolicy::Throw, myExCharCount == myCharCount); } return myResult; #elif _WIN32 if (_myLocaleChars == 0) { return std::string(); } // convert from active codepage to WideChars AC_SIZE_TYPE myWCharSize = MultiByteToWideChar(CP_ACP, getMultibyteToWideCharFlags(), _myLocaleChars, -1, 0, 0); if (myWCharSize == 0) { throw UnicodeException(errorDescription(lastError()), PLUS_FILE_LINE); } LPWSTR myWChars = new WCHAR[myWCharSize]; MultiByteToWideChar(CP_ACP, getMultibyteToWideCharFlags(), _myLocaleChars, -1, myWChars, myWCharSize); // convert from WideChars to UTF8 AC_SIZE_TYPE myUTF8Size = WideCharToMultiByte(CP_UTF8, 0, myWChars, -1, 0, 0, 0, 0); if (myUTF8Size == 0) { throw UnicodeException(errorDescription(lastError()), PLUS_FILE_LINE); } char * myUTF8Chars = new char[myUTF8Size]; WideCharToMultiByte(CP_UTF8, 0, myWChars, -1, myUTF8Chars, myUTF8Size, 0, 0); std::string myUTF8String(myUTF8Chars); delete [] myWChars; delete [] myUTF8Chars; return myUTF8String; #else if (_myLocaleChars == 0) { return std::string(); } gchar * myUTF = g_filename_to_utf8(_myLocaleChars, -1, 0, 0, 0); if ( ! myUTF) { throw UnicodeException(std::string("Failed to convert filename '") + _myLocaleChars + "' to UTF8.", PLUS_FILE_LINE); } std::string myUTF8String(myUTF); g_free(myUTF); return myUTF8String; #endif }
void Datenmodell::AbfrageStarten(QString welche) { QSqlDatabase DB=QSqlDatabase::database(DBVERBINDUNG,false); if(!DB.isOpen()) return; setQuery(welche,DB); if(lastError().isValid()) { FehlerAufgetreten(lastError().text()); return; } setHeaderData(0,Qt::Horizontal,tr("Zeichen")); setHeaderData(1,Qt::Horizontal,tr("Wort")); }
bool SqliteDriver::tryConnect(const QString &db, const QString &user, const QString &password, const QString &host, int port) { if (!open(db, user, password, host, port, QString::null)) { if (lastError().type() == QSqlError::Connection) { QMessageBox::critical(0, tr("Conexión fallida"), tr("No se pudo conectar con la base de datos %1.").arg(db), QMessageBox::Ok, 0, 0); QMessageBox::critical(0, tr("Error"), QString(lastError().driverText().utf8()) + "\n" + QString(lastError().databaseText().utf8()), QMessageBox::Ok, 0, 0); return false; } } return true; }
QString NCSqlQuery::getErrorMsg( ) { QString errmsg = lastError().text(); if ( errmsg.isEmpty() && !isActive() ) errmsg = QString("Database connection lost!"); return errmsg; }
RDSqlQuery::RDSqlQuery (const QString &query, QSqlDatabase *dbase): QSqlQuery (query,dbase) { //printf("lastQuery: %s\n",(const char *)lastQuery()); // With any luck, by the time we get here, we have already done the biz... unsigned schema; if (!isActive()){ //DB Offline? QString err=QObject::tr("invalid SQL or failed DB connection")+ +"["+lastError().text()+"]: "+query; fprintf(stderr,"%s\n",(const char *)err); #ifndef WIN32 syslog(LOG_ERR,(const char *)err); #endif // WIN32 QSqlDatabase *ldb = QSqlDatabase::database(); // Something went wrong with the DB, trying a reconnect ldb->removeDatabase(RDConfiguration()->mysqlDbname()); ldb->close(); db = NULL; RDInitDb (&schema); QSqlQuery::prepare (query); QSqlQuery::exec (); if (RDDbStatus()){ if (isActive()){ RDDbStatus()->sendRecon(); } else { RDDbStatus()->sendDiscon(query); } } } else { RDDbStatus()->sendRecon(); } }
bool GameLibraryModel::select() { const QString query = selectStatement(); if (query.isEmpty()) return false; beginResetModel(); // d->clearCache(); QSqlQuery qu(database()); qu.prepare(query); for (auto &val : params) { qu.addBindValue(val); } qu.exec(); setQuery(qu); if (!qu.isActive() || lastError().isValid()) { setTable(tableName()); // resets the record & index endResetModel(); return false; } endResetModel(); return true; }
//------------------------------------------------------------------------------------------ bool DatabaseMgrSQLite::insertCategory(const QString &aqstrCategory, const QString &aqstrObjectType) { if(m_QSqlDatabase.open()) { QString qry; QSqlQuery tempQuery; //Check if the Category defined via the argument is already in the table QString tqry = QString("SELECT CategoryID FROM Category WHERE CategoryName = '%1'").arg(aqstrCategory); tempQuery.exec(tqry); if(tempQuery.last() == '\0') { //Category not found and should be inserted qry = QString("INSERT INTO Category(CategoryName, ObjectTypeID) " "SELECT '%1', ObjectTypeID FROM ObjectType WHERE ObjectTypeName = '%2'").arg(aqstrCategory).arg(aqstrObjectType); QSqlQuery query(qry); } else { qDebug() << QString("Category %1 already in the database.").arg(aqstrCategory); } return true; } else { std::cout << "Error opening: " << lastError().text().toStdString() << std::endl; return false; } }
// bool QmvSqlTuple::loadForeign( const QString & att_name ) // { // QmvTupleAttribute * bool QmvSqlTuple::purge() { QString query; const QString & cn = parent_class->relationName(); const QString & pk = parent_class->serialKey(); const QString & pkv = this->attributeValue(pk); int rows; if (pkv) // This tuple exists in persistent storage. { query = QString("DELETE FROM %1 WHERE %2 = '%3'::%4") .arg(cn) .arg(pk) .arg(pkv) .arg(parent_class->attAttValue(pk, QString("mtat_type"))); rows = sql_exec(query); if (rows < 0 ) { qDebug("QmvSqlTuple::purge():lastError = <%s>", lastError().latin1() ); return(FALSE); } else return(TRUE); } return(TRUE); }
bool LLUdpQWave::onBlockingTimeoutChanged(uint64_t timeoutUs) { if (m_socketRx == -1) return true; bool nonBlock = (timeoutUs == 0); // 0 means async! // set timeout #ifndef _WIN32 struct timeval tv; tv.tv_sec = timeoutUs / 1000000UL; tv.tv_usec = timeoutUs % 1000000UL; // 0 means no timeout (block forever) #else int tv = (timeoutUs < 1000 ? 1UL : (timeoutUs / 1000UL)); #endif if (setsockopt(m_socketRx, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof(tv)) < 0) { LOG(logERROR) << "Cannot set recvtimeo to " << timeoutUs << "us! " << lastError(); return false; } LOG(logDEBUG3) << "Set SO_RCVTIMEO of socket (" << m_socketRx << ") to " << timeoutUs << "us"; if (!socketSetBlocking(m_socketRx, !nonBlock)) return false; return true; }
returnValue PIDcontroller::determineControlAction( const Vector& error, Vector& output ) { uint i; double tmp; output.init( getNumOutputs() ); output.setZero( ); // update integral value for( i=0; i<getNumInputs(); ++i ) iValue(i) += error(i) * getSamplingTime( ); // determine outputs for( i=0; i<getNumInputs(); ++i ) { tmp = pWeights(i) * error(i); tmp += iWeights(i) * iValue(i); tmp += dWeights(i) * (error(i) - lastError(i)) / getSamplingTime( ); if ( getNumOutputs( ) > 1 ) output(i) = tmp; else output(0) += tmp; } // update last error lastError = error; return SUCCESSFUL_RETURN; }
void SocketImpl::connect(const SocketAddress& address, const Poco::Timespan& timeout) { if (_sockfd == POCO_INVALID_SOCKET) { init(address.af()); } setBlocking(false); try { #if defined(POCO_VXWORKS) int rc = ::connect(_sockfd, (sockaddr*) address.addr(), address.length()); #else int rc = ::connect(_sockfd, address.addr(), address.length()); #endif if (rc != 0) { int err = lastError(); if (err != POCO_EINPROGRESS && err != POCO_EWOULDBLOCK) error(err, address.toString()); if (!poll(timeout, SELECT_READ | SELECT_WRITE | SELECT_ERROR)) throw Poco::TimeoutException("connect timed out", address.toString()); err = socketError(); if (err != 0) error(err); } } catch (Poco::Exception&) { setBlocking(true); throw; } setBlocking(true); }
void ComputerRepository::remove(Computer &comp) { auto query = SQLConnection::getInstance()->getQuery(); query->prepare("DELETE FROM computers WHERE id = ?"); query->addBindValue(comp.getID()); if(!query->exec()) throw std::runtime_error(query->lastError().text().toStdString()); query->clear(); // Also clean all relations to other computers query->prepare("DELETE FROM scientist_computer WHERE computer_id = ?"); query->addBindValue(comp.getID()); if(!query->exec()) throw std::runtime_error(query->lastError().text().toStdString()); }
/*! \fn MPeluqueria::agregarServicio( QVariant desc, QVariant precio, QVariant fecha, QVariant id_mascota ) */ bool MPeluqueria::agregarServicio( QVariant desc, QVariant precio, QVariant fecha, QVariant id_mascota ) { /* if( !mascota.isValid() ) { qDebug( "Inidce Mascota es invalido" ); return false; } QVariant id_mascota = relationModel( 1 )->data( mascota, 0 ); if( id_mascota.isValid() && id_mascota.toInt() <= 0 ) {return false;}*/ QSqlRecord registro = record(); registro.setValue( 1, id_mascota ); registro.setValue( 2, desc ); registro.setValue( 3, precio ); registro.setValue( 4, fecha ); for( int i = 0; i<registro.count(); i++ ) { qDebug( QString( "Campo: %1, generado? %2, null? %3, valor? |%4|" ).arg( registro.fieldName( i ) ).arg( registro.isGenerated( i ) ).arg( registro.isNull( i ) ).arg( registro.value( i ).toString() ).toLocal8Bit() ); } if( insertRecord( -1, registro ) ) { qDebug( "Registro de servicio agregado correctamente" ); return true; } else { qDebug( "Error al insertar registro de servicio de mascota" ); qDebug( QString( "Detalles: tipo: %1, errno: %2, descripcion: %3" ).arg( lastError().type() ).arg( lastError().number() ).arg( lastError().text() ).toLocal8Bit() ); return false; } }
Nequeo::Net::Sockets::HostEntry Nequeo::Net::Sockets::DNS::hostByAddress(const IPAddress& address) { NetworkInitializer networkInitializer; SocketAddress sa(address, 0); static char fqname[1024]; int rc = getnameinfo(sa.addr(), sa.length(), fqname, sizeof(fqname), NULL, 0, NI_NAMEREQD); if (rc == 0) { struct addrinfo* pAI; struct addrinfo hints; std::memset(&hints, 0, sizeof(hints)); hints.ai_flags = AI_CANONNAME | AI_ADDRCONFIG; rc = getaddrinfo(fqname, NULL, &hints, &pAI); if (rc == 0) { HostEntry result(pAI); freeaddrinfo(pAI); return result; } else { aierror(rc, address.toString()); } } else { aierror(rc, address.toString()); } int err = lastError(); error(err, address.toString()); // will throw an appropriate exception throw Nequeo::Exceptions::Net::NetException(); // to silence compiler }
bool AbstractDocument::isValidDocumentFromProvod() { if (lastError().isValid()) return false; if (_isProvod) { _error = QSqlError("transactDocument",tr("Документ уже проведен! ") ,QSqlError::UnknownError,100); return false; } QSqlQuery sql; sql.exec(QString("SELECT COUNT(*) FROM document_detail WHERE dd_doc = %1") .arg(_id)); if (!sql.next()) { _error = sql.lastError(); return false; } if (sql.value(0).toInt() == 0) { _error = QSqlError("transactDocument", tr("Нет позиций для проводки! "), QSqlError::UnknownError,100); return false; } return true; }
//--------------------------------------------------------------------------------------------- bool DatabaseMgrSQLite::insertProductCodeImage(const QString &aqstrProductCodeNumber, const QString &aqstrProductCodeImage) { if(m_QSqlDatabase.open()) { QString qry; QSqlQuery tempQuery; //Check if the Product code image defined via the argument is already in the table QString tqry = QString("SELECT ProductCodeImageID FROM ProductCodeImage WHERE ProductCodeImageName = '%1'").arg(aqstrProductCodeImage); tempQuery.exec(tqry); if(tempQuery.last() == '\0') { //Product not found and should be inserted qry = QString("INSERT INTO ProductCodeImage(ProductCodeImageName, ProductCodeID) " "SELECT '%1', ProductCodeID FROM ProductCode WHERE ProductCodeNumber = '%2'").arg(aqstrProductCodeImage).arg(aqstrProductCodeNumber); QSqlQuery query(qry); } else { //Product code Image already in the database. qDebug() << QString("Product Code Image %1 already in the database.").arg(aqstrProductCodeImage); } return true; } else { std::cout << "Error opening: " << lastError().text().toStdString() << std::endl; return false; } }
bool DatabaseMgrSQLite::insertProduct(const QString &aqstrProduct, const QString &aqstrCategory) { if(m_QSqlDatabase.open()) { QString qry; QSqlQuery tempQuery; //Check if the Product defined via the argument is already in the table QString tqry = QString("SELECT ProductID FROM Product WHERE ProductName = '%1'").arg(aqstrProduct); tempQuery.exec(tqry); if(tempQuery.last() == '\0') { //Product not found and should be inserted qry = QString("INSERT INTO Product(ProductName, CategoryID) " "SELECT '%1', CategoryID FROM Category WHERE CategoryName = '%2'").arg(aqstrProduct).arg(aqstrCategory); QSqlQuery query(qry); } else { qDebug() << QString("Product %1 already in the database").arg(aqstrProduct); } return true; } else { std::cout << "Error opening: " << lastError().text().toStdString() << std::endl; return false; } }
void DNS::aierror(int code, const std::string& arg) { #if defined(POCO_HAVE_IPv6) switch (code) { case EAI_AGAIN: throw DNSException("Temporary DNS error while resolving", arg); case EAI_FAIL: throw DNSException("Non recoverable DNS error while resolving", arg); #if !defined(_WIN32) // EAI_NODATA and EAI_NONAME have the same value case EAI_NODATA: throw NoAddressFoundException(arg); #endif case EAI_NONAME: throw HostNotFoundException(arg); #if defined(EAI_SYSTEM) case EAI_SYSTEM: error(lastError(), arg); break; #endif #if defined(_WIN32) case WSANO_DATA: // may happen on XP throw HostNotFoundException(arg); #endif default: throw DNSException("EAI", NumberFormatter::format(code)); } #endif // POCO_HAVE_IPv6 }
bool XSqlQuery::exec() { qApp->setOverrideCursor(Qt::WaitCursor); bool returnValue = false; if(_data && _data->_emulatePrepare) { // In 4.4.1 Qt started supporting true prepared queries on the PostgreSQL driver and this // caused several problems with all our code and the way it worked so this is a modified copy // of their code to use the implemented prepare if we have that option set so we can use the method // that works best in the case we are using it for. if (lastError().isValid()) ((XSqlResultHelper*)result())->setLastError(QSqlError()); returnValue = ((XSqlResultHelper*)result())->XSqlResultHelper::exec(); } else returnValue = QSqlQuery::exec(); qApp->restoreOverrideCursor(); if (_data) _data->_currRecord = record(); if(false == returnValue) notifyErrorListeners(this); return returnValue; }
void XModel::submitAll(){ bool b = QSqlRelationalTableModel::submitAll(); if(b == false){ QSqlError err = lastError(); yERROR(err.text()); } }
const HostEntry& DNS::hostByName(const std::string& hostname) { FastMutex::ScopedLock lock(_mutex); DNSCache::const_iterator it = _cache.find(hostname); if (it != _cache.end()) { return it->second; } else { #if defined(_WIN32) && defined(POCO_HAVE_IPv6) struct addrinfo* pAI; struct addrinfo hints; memset(&hints, 0, sizeof(hints)); hints.ai_flags = AI_CANONNAME; if (getaddrinfo(hostname.c_str(), NULL, &hints, &pAI) == 0) { std::pair<DNSCache::iterator, bool> res = _cache.insert(std::pair<std::string, HostEntry>(hostname, HostEntry(pAI))); freeaddrinfo(pAI); return res.first->second; } #else struct hostent* he = gethostbyname(hostname.c_str()); if (he) { std::pair<DNSCache::iterator, bool> res = _cache.insert(std::pair<std::string, HostEntry>(hostname, HostEntry(he))); return res.first->second; } #endif } error(lastError(), hostname); // will throw an appropriate exception throw NetException(); // to silence compiler }