QT_BEGIN_NAMESPACE QList<QNetworkProxy> QNetworkProxyFactory::systemProxyForQuery(const QNetworkProxyQuery &) { QList<QNetworkProxy> proxyList; QByteArray proxy_env = qgetenv("http_proxy"); if (!proxy_env.isEmpty()) { QUrl url = QUrl(QString::fromLocal8Bit(proxy_env)); if (url.scheme() == QLatin1String("socks5")) { QNetworkProxy proxy(QNetworkProxy::Socks5Proxy, url.host(), url.port() ? url.port() : 1080, url.userName(), url.password()); proxyList << proxy; } else if (url.scheme() == QLatin1String("socks5h")) { QNetworkProxy proxy(QNetworkProxy::Socks5Proxy, url.host(), url.port() ? url.port() : 1080, url.userName(), url.password()); proxy.setCapabilities(QNetworkProxy::HostNameLookupCapability); proxyList << proxy; } else if (url.scheme() == QLatin1String("http") || url.scheme().isEmpty()) { QNetworkProxy proxy(QNetworkProxy::HttpProxy, url.host(), url.port() ? url.port() : 8080, url.userName(), url.password()); proxyList << proxy; } } if (proxyList.isEmpty()) proxyList << QNetworkProxy::NoProxy; return proxyList; }
QList<QNetworkProxy> PackageManagerProxyFactory::queryProxy(const QNetworkProxyQuery &query) { const Settings &settings = m_core->settings(); QList<QNetworkProxy> list; if (settings.proxyType() == Settings::SystemProxy) { #if defined(Q_OS_UNIX) && !defined(Q_OS_OSX) QUrl proxyUrl = QUrl::fromUserInput(QString::fromUtf8(qgetenv("http_proxy"))); if (proxyUrl.isValid()) { return list << QNetworkProxy(QNetworkProxy::HttpProxy, proxyUrl.host(), proxyUrl.port(), proxyUrl.userName(), proxyUrl.password()); } #endif return QNetworkProxyFactory::systemProxyForQuery(query); } if ((settings.proxyType() == Settings::NoProxy)) return list << QNetworkProxy(QNetworkProxy::NoProxy); if (query.queryType() == QNetworkProxyQuery::UrlRequest) { if (query.url().scheme() == QLatin1String("ftp")) return list << settings.ftpProxy(); if ((query.url().scheme() == QLatin1String("http")) || (query.url().scheme() == QLatin1String("https"))) { return list << settings.httpProxy(); } } return list << QNetworkProxy(QNetworkProxy::DefaultProxy); }
bool db_open(QUrl dburl) { QSqlDatabase db; db.removeDatabase("vengeance"); if(dburl.scheme().isEmpty()) db=QSqlDatabase::addDatabase("QMYSQL","vengeance"); else db=QSqlDatabase::addDatabase(dburl.scheme(),"vengeance"); if(dburl.host().isEmpty()) db.setHostName("localhost"); else db.setHostName(dburl.host()); db.setDatabaseName(dburl.path().replace("/","")); db.setUserName(dburl.userName()); db.setPassword(dburl.password()); bool w=db.open(); if(!w) { qDebug()<<db.lastError (); } return w; }
QString QUrlProto::password() const { QUrl *item = qscriptvalue_cast<QUrl*>(thisObject()); if (item) return item->password(); return QString(); }
/*! \a url points to the new WAP gateway. \sa gateway() */ void QWapAccount::setGateway( const QUrl& url ) { d->conf->setValue( QLatin1String("Wap/Gateway"), url.host() ); d->conf->setValue( QLatin1String("Wap/UserName"), url.userName() ); d->conf->setValue( QLatin1String("Wap/Password"), url.password() ); d->conf->setValue( QLatin1String("Wap/Port"), url.port() ); }
/*! Fetch the credential data from the credential cache. If auth is 0 (as it is when called from createRequest()), this will try to look up with an empty realm. That fails in most cases for HTTP (because the realm is seldom empty for HTTP challenges). In any case, QHttpNetworkConnection never sends the credentials on the first attempt: it needs to find out what authentication methods the server supports. For FTP, realm is always empty. */ QNetworkAuthenticationCredential QNetworkAccessAuthenticationManager::fetchCachedCredentials(const QUrl &url, const QAuthenticator *authentication) { if (!url.password().isEmpty()) return QNetworkAuthenticationCredential(); // no need to set credentials if it already has them QString realm; if (authentication) realm = authentication->realm(); QByteArray cacheKey = authenticationKey(url, realm); QMutexLocker mutexLocker(&mutex); if (!authenticationCache.hasEntry(cacheKey)) return QNetworkAuthenticationCredential(); QNetworkAuthenticationCache *auth = static_cast<QNetworkAuthenticationCache *>(authenticationCache.requestEntryNow(cacheKey)); QNetworkAuthenticationCredential *cred = auth->findClosestMatch(url.path()); QNetworkAuthenticationCredential ret; if (cred) ret = *cred; authenticationCache.releaseEntry(cacheKey); return ret; }
void OwncloudHttpCredsPage::initializePage() { WizardCommon::initErrorLabel(_ui.errorLabel); OwncloudWizard* ocWizard = qobject_cast< OwncloudWizard* >(wizard()); AbstractCredentials *cred = ocWizard->account()->credentials(); HttpCredentials *httpCreds = qobject_cast<HttpCredentials*>(cred); if (httpCreds) { const QString user = httpCreds->fetchUser(); if (!user.isEmpty()) { _ui.leUsername->setText(user); } } else { QUrl url = ocWizard->account()->url(); // If the final url does not have a username, check the // user specified url too. Sometimes redirects can lose // the user:pw information. if (url.userName().isEmpty()) { url = ocWizard->ocUrl(); } const QString user = url.userName(); const QString password = url.password(); if(!user.isEmpty()) { _ui.leUsername->setText(user); } if(!password.isEmpty()) { _ui.lePassword->setText(password); } } _ui.leUsername->setFocus(); }
void Transfers::dropSlsk(const QList<QUrl>& l) { QList<QUrl>::const_iterator it = l.begin(); for(; it != l.end(); ++it) { QUrl url = *it; if(url.scheme() == "slsk" && !url.host().isEmpty() && !url.path().isEmpty()) { // Try to find a size qint64 size = 0; bool ok; size = url.password().toLongLong(&ok); if(! ok) size = 0; // Find the user name QString user = url.userName(); if (user.isEmpty()) user = url.host(); // Find the path (folder or file) QString path = url.path().replace("/", "\\"); if(path.right(1) == "\\") museeq->downloadFolder(user, QString(path)); else museeq->downloadFile(user, QString(path), size); } } }
void ClientPrivate::parseCnnString(const QUrl &con) { P_Q(QAMQP::Client); if (con.scheme() == AMQPSCHEME || con.scheme() == AMQPSSCHEME) { q->setSsl(con.scheme() == AMQPSSCHEME); q->setPassword(con.password()); q->setUser(con.userName()); q->setPort(con.port()); q->setHost(con.host()); q->setVirtualHost(con.path()); } }
static void setApplicationProxy(QUrl url) { if ( !url.isEmpty() ) { if ( url.port() == -1 ) url.setPort( 8080 ); QNetworkProxy proxy( QNetworkProxy::HttpProxy, url.host(), url.port(), url.userName(), url.password() ); QNetworkProxy::setApplicationProxy(proxy); } }
void QNetworkAccessManagerPrivate::authenticationRequired(QNetworkAccessBackend *backend, QAuthenticator *authenticator) { Q_Q(QNetworkAccessManager); // FIXME: Add support for domains (i.e., the leading path) QUrl url = backend->reply->url; // don't try the cache for the same URL twice in a row // being called twice for the same URL means the authentication failed // also called when last URL is empty, e.g. on first call if (backend->reply->urlForLastAuthentication.isEmpty() || url != backend->reply->urlForLastAuthentication) { // if credentials are included in the url, then use them if (!url.userName().isEmpty() && !url.password().isEmpty()) { authenticator->setUser(url.userName()); authenticator->setPassword(url.password()); backend->reply->urlForLastAuthentication = url; authenticationManager->cacheCredentials(url, authenticator); return; } QNetworkAuthenticationCredential cred = authenticationManager->fetchCachedCredentials(url, authenticator); if (!cred.isNull()) { authenticator->setUser(cred.user); authenticator->setPassword(cred.password); backend->reply->urlForLastAuthentication = url; return; } } // if we emit a signal here in synchronous mode, the user might spin // an event loop, which might recurse and lead to problems if (backend->isSynchronous()) return; backend->reply->urlForLastAuthentication = url; emit q->authenticationRequired(backend->reply->q_func(), authenticator); authenticationManager->cacheCredentials(url, authenticator); }
void FileDownloader::download(QUrl url) { QHttp::ConnectionMode mode = url.scheme().toLower() == "https" ? QHttp::ConnectionModeHttps : QHttp::ConnectionModeHttp; http->setHost(url.host(), mode, url.port() == -1 ? 0 : url.port()); if (!url.userName().isEmpty()) http->setUser(url.userName(), url.password()); http_request_aborted = false; http_get_id = http->get(url.path(), &buffer); setLabelText(tr("Downloading %1").arg(url.toString())); }
void setUrl(const QUrl &url) { QString hdr; hdr = QString("GET %PATH% HTTP/1.1\r\n" "Host: %HOST%\r\n" "User-Agent: MythMusic/%VERSION%\r\n" "Accept: */*\r\n"); QString path = url.path(); QString host = url.host(); if (path.isEmpty()) path = "/"; if (url.hasQuery()) path += '?' + url.encodedQuery(); if (url.port() != -1) host += QString(":%1").arg(url.port()); hdr.replace("%PATH%", path); hdr.replace("%HOST%", host); hdr.replace("%VERSION%", MYTH_BINARY_VERSION); if (!url.userName().isEmpty() && !url.password().isEmpty()) { QString authstring = url.userName() + ":" + url.password(); QString auth = QCodecs::base64Encode(authstring.toLocal8Bit()); hdr += "Authorization: Basic " + auth + "\r\n"; } hdr += QString("TE: trailers\r\n" "Icy-Metadata: 1\r\n" "\r\n"); LOG(VB_NETWORK, LOG_INFO, QString("ShoutCastRequest: '%1'").arg(hdr)); m_data = hdr.toAscii(); }
void Config::setSystemProxy(bool checked) { ui.proxyPort->setEnabled(!checked); ui.proxyHost->setEnabled(!checked); ui.proxyUser->setEnabled(!checked); ui.proxyPass->setEnabled(!checked); if(checked) { // save values in input box proxy.setScheme("http"); proxy.setUserName(ui.proxyUser->text()); proxy.setPassword(ui.proxyPass->text()); proxy.setHost(ui.proxyHost->text()); proxy.setPort(ui.proxyPort->text().toInt()); // show system values in input box QUrl envproxy = System::systemProxy(); qDebug() << "[Config] setting system proxy" << envproxy; ui.proxyHost->setText(envproxy.host()); ui.proxyPort->setText(QString("%1").arg(envproxy.port())); ui.proxyUser->setText(envproxy.userName()); ui.proxyPass->setText(envproxy.password()); if(envproxy.host().isEmpty() || envproxy.port() == -1) { qDebug() << "[Config] sytem proxy is invalid."; QMessageBox::warning(this, tr("Proxy Detection"), tr("The System Proxy settings are invalid!\n" "Rockbox Utility can't work with this proxy settings. " "Make sure the system proxy is set correctly. Note that " "\"proxy auto-config (PAC)\" scripts are not supported by " "Rockbox Utility. If your system uses this you need " "to use manual proxy settings."), QMessageBox::Ok ,QMessageBox::Ok); // the current proxy settings are invalid. Check the saved proxy // type again. if(RbSettings::value(RbSettings::ProxyType).toString() == "manual") ui.radioManualProxy->setChecked(true); else ui.radioNoProxy->setChecked(true); } } else { ui.proxyHost->setText(proxy.host()); if(proxy.port() > 0) ui.proxyPort->setText(QString("%1").arg(proxy.port())); else ui.proxyPort->setText(""); ui.proxyUser->setText(proxy.userName()); ui.proxyPass->setText(proxy.password()); } }
void setUrl(const QUrl &url) { QString hdr; hdr = QString("GET %1 HTTP/1.1\r\n" "Host: %2\r\n" "User-Agent: mythmusic/svn\r\n" "Keep-Alive:\r\n" "Connection: TE, Keep-Alive\r\n").arg(url.path()).arg(url.host()); if (!url.userName().isEmpty() && !url.password().isEmpty()) { QString authstring = url.userName() + ":" + url.password(); QString auth = QCodecs::base64Encode(authstring.toLocal8Bit()); hdr += "Authorization: Basic " + auth; } hdr += QString("TE: trailers\r\n" "icy-metadata:1\r\n" "\r\n"); m_data = hdr; }
//----------------------------------------------------------------------------- bool CloneDialog::run(QWidget *parent, QUrl &url, QString &repository) { CloneDialog dlg(parent); // Try to parse a url from the clipboard QClipboard *clipboard = QApplication::clipboard(); if(clipboard) { QUrl nurl = QUrl::fromUserInput(clipboard->text()); // If we have a valid url if(nurl.isValid() && !nurl.isEmpty()) { // Fill in dialog dlg.ui->lineUserName->setText(nurl.userName()); dlg.ui->linePassword->setText(nurl.password()); nurl.setUserName(""); nurl.setPassword(""); dlg.ui->lineURL->setText(nurl.toString()); } } if(dlg.exec() != QDialog::Accepted) return false; url.setUrl(dlg.ui->lineURL->text()); if(url.isEmpty() || !url.isValid()) { QMessageBox::critical(parent, tr("Error"), tr("Invalid URL."), QMessageBox::Ok ); return false; } url.setUserName(dlg.ui->lineUserName->text()); url.setPassword(dlg.ui->linePassword->text()); if(dlg.ui->lineRepository->text().isEmpty() ) { QMessageBox::critical(parent, tr("Error"), tr("Invalid Repository File."), QMessageBox::Ok ); return false; } repository = dlg.ui->lineRepository->text(); return true; }
bool QHttpNetworkConnectionChannel::sendRequest() { if (!reply) { // heh, how should that happen! qWarning() << "QHttpNetworkConnectionChannel::sendRequest() called without QHttpNetworkReply"; state = QHttpNetworkConnectionChannel::IdleState; return false; } switch (state) { case QHttpNetworkConnectionChannel::IdleState: { // write the header if (!ensureConnection()) { // wait for the connection (and encryption) to be done // sendRequest will be called again from either // _q_connected or _q_encrypted return false; } written = 0; // excluding the header bytesTotal = 0; QHttpNetworkReplyPrivate *replyPrivate = reply->d_func(); replyPrivate->clear(); replyPrivate->connection = connection; replyPrivate->connectionChannel = this; replyPrivate->autoDecompress = request.d->autoDecompress; replyPrivate->pipeliningUsed = false; // if the url contains authentication parameters, use the new ones // both channels will use the new authentication parameters if (!request.url().userInfo().isEmpty() && request.withCredentials()) { QUrl url = request.url(); QAuthenticator &auth = authenticator; if (url.userName() != auth.user() || (!url.password().isEmpty() && url.password() != auth.password())) { auth.setUser(url.userName()); auth.setPassword(url.password()); connection->d_func()->copyCredentials(connection->d_func()->indexOf(socket), &auth, false); } // clear the userinfo, since we use the same request for resending // userinfo in url can conflict with the one in the authenticator url.setUserInfo(QString()); request.setUrl(url); } // Will only be false if QtWebKit is performing a cross-origin XMLHttpRequest // and withCredentials has not been set to true. if (request.withCredentials()) connection->d_func()->createAuthorization(socket, request); #ifndef QT_NO_NETWORKPROXY QByteArray header = QHttpNetworkRequestPrivate::header(request, (connection->d_func()->networkProxy.type() != QNetworkProxy::NoProxy)); #else QByteArray header = QHttpNetworkRequestPrivate::header(request, false); #endif socket->write(header); // flushing is dangerous (QSslSocket calls transmit which might read or error) // socket->flush(); QNonContiguousByteDevice* uploadByteDevice = request.uploadByteDevice(); if (uploadByteDevice) { // connect the signals so this function gets called again QObject::connect(uploadByteDevice, SIGNAL(readyRead()),this, SLOT(_q_uploadDataReadyRead())); bytesTotal = request.contentLength(); state = QHttpNetworkConnectionChannel::WritingState; // start writing data sendRequest(); //recurse } else { state = QHttpNetworkConnectionChannel::WaitingState; // now wait for response sendRequest(); //recurse } break; } case QHttpNetworkConnectionChannel::WritingState: { // write the data QNonContiguousByteDevice* uploadByteDevice = request.uploadByteDevice(); if (!uploadByteDevice || bytesTotal == written) { if (uploadByteDevice) emit reply->dataSendProgress(written, bytesTotal); state = QHttpNetworkConnectionChannel::WaitingState; // now wait for response sendRequest(); // recurse break; } // only feed the QTcpSocket buffer when there is less than 32 kB in it const qint64 socketBufferFill = 32*1024; const qint64 socketWriteMaxSize = 16*1024; #ifndef QT_NO_OPENSSL QSslSocket *sslSocket = qobject_cast<QSslSocket*>(socket); // if it is really an ssl socket, check more than just bytesToWrite() while ((socket->bytesToWrite() + (sslSocket ? sslSocket->encryptedBytesToWrite() : 0)) <= socketBufferFill && bytesTotal != written) #else while (socket->bytesToWrite() <= socketBufferFill && bytesTotal != written) #endif { // get pointer to upload data qint64 currentReadSize = 0; qint64 desiredReadSize = qMin(socketWriteMaxSize, bytesTotal - written); const char *readPointer = uploadByteDevice->readPointer(desiredReadSize, currentReadSize); if (currentReadSize == -1) { // premature eof happened connection->d_func()->emitReplyError(socket, reply, QNetworkReply::UnknownNetworkError); return false; break; } else if (readPointer == 0 || currentReadSize == 0) { // nothing to read currently, break the loop break; } else { qint64 currentWriteSize = socket->write(readPointer, currentReadSize); if (currentWriteSize == -1 || currentWriteSize != currentReadSize) { // socket broke down connection->d_func()->emitReplyError(socket, reply, QNetworkReply::UnknownNetworkError); return false; } else { written += currentWriteSize; uploadByteDevice->advanceReadPointer(currentWriteSize); emit reply->dataSendProgress(written, bytesTotal); if (written == bytesTotal) { // make sure this function is called once again state = QHttpNetworkConnectionChannel::WaitingState; sendRequest(); break; } } } } break; } case QHttpNetworkConnectionChannel::WaitingState: { QNonContiguousByteDevice* uploadByteDevice = request.uploadByteDevice(); if (uploadByteDevice) { QObject::disconnect(uploadByteDevice, SIGNAL(readyRead()), this, SLOT(_q_uploadDataReadyRead())); } // HTTP pipelining //connection->d_func()->fillPipeline(socket); //socket->flush(); // ensure we try to receive a reply in all cases, even if _q_readyRead_ hat not been called // this is needed if the sends an reply before we have finished sending the request. In that // case receiveReply had been called before but ignored the server reply if (socket->bytesAvailable()) QMetaObject::invokeMethod(this, "_q_receiveReply", Qt::QueuedConnection); break; } case QHttpNetworkConnectionChannel::ReadingState: // ignore _q_bytesWritten in these states // fall through default: break; } return true; }
ServerItem *ServerItem::fromMimeData(const QMimeData *mime, bool default_name, QWidget *p) { if (mime->hasFormat(QLatin1String("OriginatedInMumble"))) return NULL; QUrl url; if (mime->hasUrls() && ! mime->urls().isEmpty()) url = mime->urls().at(0); else if (mime->hasText()) url = QUrl::fromEncoded(mime->text().toUtf8()); QString qsFile = url.toLocalFile(); if (! qsFile.isEmpty()) { QFile f(qsFile); // Make sure we don't accidently read something big the user // happened to have in his clipboard. We only want to look // at small link files. if (f.open(QIODevice::ReadOnly) && f.size() < 10240) { QByteArray qba = f.readAll(); f.close(); url = QUrl::fromEncoded(qba, QUrl::StrictMode); if (! url.isValid()) { QSettings qs(qsFile, QSettings::IniFormat); url = QUrl::fromEncoded(qs.value(QLatin1String("InternetShortcut/URL")).toByteArray(), QUrl::StrictMode); } } } #if QT_VERSION >= 0x050000 QUrlQuery query(url); #endif if (! url.isValid() || (url.scheme() != QLatin1String("mumble"))) return NULL; if (url.userName().isEmpty()) { if (g.s.qsUsername.isEmpty()) { bool ok; QString defUserName = QInputDialog::getText(p, ConnectDialog::tr("Adding host %1").arg(url.host()), ConnectDialog::tr("Enter username"), QLineEdit::Normal, g.s.qsUsername, &ok).trimmed(); if (! ok) return NULL; if (defUserName.isEmpty()) return NULL; g.s.qsUsername = defUserName; } url.setUserName(g.s.qsUsername); } #if QT_VERSION >= 0x050000 if (! query.hasQueryItem(QLatin1String("title")) && default_name) query.addQueryItem(QLatin1String("title"), url.host()); ServerItem *si = new ServerItem(query.queryItemValue(QLatin1String("title")), url.host(), static_cast<unsigned short>(url.port(DEFAULT_MUMBLE_PORT)), url.userName(), url.password()); if (query.hasQueryItem(QLatin1String("url"))) si->qsUrl = query.queryItemValue(QLatin1String("url")); #else if (! url.hasQueryItem(QLatin1String("title")) && default_name) url.addQueryItem(QLatin1String("title"), url.host()); ServerItem *si = new ServerItem(url.queryItemValue(QLatin1String("title")), url.host(), static_cast<unsigned short>(url.port(DEFAULT_MUMBLE_PORT)), url.userName(), url.password()); if (url.hasQueryItem(QLatin1String("url"))) si->qsUrl = url.queryItemValue(QLatin1String("url")); #endif return si; }
int Url::password ( lua_State * L )// const : QString { QUrl* lhs = ValueInstaller2<QUrl>::check( L, 1 ); lua_pushstring(L, lhs->password().toLatin1() ); return 1; }
int main(int argc, char* argv[]) { terrama2::core::initializeTerraMA(); std::cout << "NOT WORKING" << std::endl; return 1; { QUrl uri; uri.setScheme("postgis"); uri.setHost(QString::fromStdString(TERRAMA2_DATABASE_HOST)); uri.setPort(std::stoi(TERRAMA2_DATABASE_PORT)); uri.setUserName(QString::fromStdString(TERRAMA2_DATABASE_USERNAME)); uri.setPassword(QString::fromStdString(TERRAMA2_DATABASE_PASSWORD)); uri.setPath(QString::fromStdString("/"+TERRAMA2_DATABASE_DBNAME)); //DataProvider information terrama2::core::DataProvider* dataProvider = new terrama2::core::DataProvider(); terrama2::core::DataProviderPtr dataProviderPtr(dataProvider); dataProvider->uri = uri.url().toStdString(); dataProvider->intent = terrama2::core::DataProviderIntent::COLLECTOR_INTENT; dataProvider->dataProviderType = "POSTGIS"; dataProvider->active = true; //DataSeries information terrama2::core::DataSeries* dataSeries = new terrama2::core::DataSeries(); terrama2::core::DataSeriesPtr dataSeriesPtr(dataSeries); auto& semanticsManager = terrama2::core::SemanticsManager::getInstance(); dataSeries->semantics = semanticsManager.getSemantics("DCP-postgis"); //DataSet information terrama2::core::DataSetDcp* dataSet = new terrama2::core::DataSetDcp(); dataSet->active = true; dataSet->format.emplace("table_name", "inpe"); dataSet->format.emplace("timestamp_property", "datetime"); dataSeries->datasetList.emplace_back(dataSet); //accessing data terrama2::core::DataAccessorDcpPostGIS accessor(dataProviderPtr, dataSeriesPtr); //empty filter terrama2::core::Filter filter; filter.lastValue = true; terrama2::core::DcpSeriesPtr dcpSeries = accessor.getDcpSeries(filter); std::cout << "\nLast data timestamp: " << accessor.lastDateTime()->toString() << std::endl; assert(dcpSeries->dcpSeriesMap().size() == 1); auto datasetSeries = (*dcpSeries->dcpSeriesMap().begin()).second; std::shared_ptr<te::da::DataSet> teDataSet = datasetSeries.syncDataSet->dataset(); std::string tableName = dataSet->format["table_name"]; // creates a DataSource to the data and filters the dataset, // also joins if the DCP comes from separated files std::shared_ptr<te::da::DataSource> datasource(te::da::DataSourceFactory::make("POSTGIS")); std::map<std::string, std::string> connInfo {{"PG_HOST", uri.host().toStdString()}, {"PG_PORT", std::to_string(uri.port())}, {"PG_USER", uri.userName().toStdString()}, {"PG_PASSWORD", uri.password().toStdString()}, {"PG_DB_NAME", uri.path().section("/", 1, 1).toStdString()}, {"PG_CONNECT_TIMEOUT", "4"}, {"PG_CLIENT_ENCODING", "UTF-8"} }; datasource->setConnectionInfo(connInfo); // RAII for open/closing the datasource terrama2::core::OpenClose<std::shared_ptr<te::da::DataSource>> openClose(datasource); // get a transactor to interact to the data source std::shared_ptr<te::da::DataSourceTransactor> transactor(datasource->getTransactor()); auto primaryKey = datasetSeries.teDataSetType->getPrimaryKey(); assert(primaryKey); assert(!teDataSet->isEmpty()); auto pkName = primaryKey->getName(); std::string sql("DELETE FROM " +tableName+" WHERE "+pkName+" NOT IN ("); auto pos = datasetSeries.teDataSetType->getPropertyPosition(pkName); teDataSet->moveBeforeFirst(); while (teDataSet->moveNext()) { sql+=std::to_string(teDataSet->getInt32(pos))+","; } sql.pop_back(); sql+=")"; transactor->execute(sql); std::cout << "dataset size: " << teDataSet->size() << std::endl; } terrama2::core::finalizeTerraMA(); return 0; }
int main(int argc, char **argv) { QCoreApplication app(argc, argv); CmdOptions options; options.silent = false; options.trustSSL = false; options.useNetrc = false; options.interactive = true; ClientProxy clientProxy; parseOptions( app.arguments(), &options ); QUrl url = QUrl::fromUserInput(options.target_url); // Fetch username and password. If empty, try to retrieve // from URL and strip URL QString user; QString password; if (options.useNetrc) { NetrcParser parser; if (parser.parse()) { NetrcParser::LoginPair pair = parser.find(url.host()); user = pair.first; password = pair.second; } } else { user = options.user; if (user.isEmpty()) { user = url.userName(); } password = options.password; if (password.isEmpty()) { password = url.password(); } if (options.interactive) { if (user.isEmpty()) { std::cout << "Please enter user name: "; std::string s; std::getline(std::cin, s); user = QString::fromStdString(s); } if (password.isEmpty()) { password = queryPassword(user); } } } // ### ensure URL is free of credentials if (url.userName().isEmpty()) { url.setUserName(user); } if (url.password().isEmpty()) { url.setPassword(password); } Account account; // Find the folder and the original owncloud url QStringList splitted = url.path().split(account.davPath()); url.setPath(splitted.value(0)); url.setScheme(url.scheme().replace("owncloud", "http")); QString folder = splitted.value(1); SimpleSslErrorHandler *sslErrorHandler = new SimpleSslErrorHandler; HttpCredentials *cred = new HttpCredentialsText(user, password); account.setUrl(url); account.setCredentials(cred); account.setSslErrorHandler(sslErrorHandler); AccountManager::instance()->setAccount(&account); restart_sync: CSYNC *_csync_ctx; if( csync_create( &_csync_ctx, options.source_dir.toUtf8(), url.toEncoded().constData()) < 0 ) { qFatal("Unable to create csync-context!"); return EXIT_FAILURE; } int rc = ne_sock_init(); if (rc < 0) { qFatal("ne_sock_init failed!"); } csync_set_log_level(options.silent ? 1 : 11); opts = &options; cred->syncContextPreInit(_csync_ctx); if( csync_init( _csync_ctx ) < 0 ) { qFatal("Could not initialize csync!"); return EXIT_FAILURE; } csync_set_module_property(_csync_ctx, "csync_context", _csync_ctx); if( !options.proxy.isNull() ) { QString host; int port = 0; bool ok; // Set as default and let overwrite later csync_set_module_property(_csync_ctx, "proxy_type", (void*) "NoProxy"); QStringList pList = options.proxy.split(':'); if(pList.count() == 3) { // http: //192.168.178.23 : 8080 // 0 1 2 host = pList.at(1); if( host.startsWith("//") ) host.remove(0, 2); port = pList.at(2).toInt(&ok); if( !host.isNull() ) { csync_set_module_property(_csync_ctx, "proxy_type", (void*) "HttpProxy"); csync_set_module_property(_csync_ctx, "proxy_host", host.toUtf8().data()); if( ok && port ) { csync_set_module_property(_csync_ctx, "proxy_port", (void*) &port); } } } } else { clientProxy.setupQtProxyFromConfig(); QString url( options.target_url ); if( url.startsWith("owncloud")) { url.remove(0, 8); url = QString("http%1").arg(url); } clientProxy.setCSyncProxy(QUrl(url), _csync_ctx); } if (!options.exclude.isEmpty()) { csync_add_exclude_list(_csync_ctx, options.exclude.toLocal8Bit()); } cred->syncContextPreStart(_csync_ctx); Cmd cmd; SyncJournalDb db(options.source_dir); SyncEngine engine(_csync_ctx, options.source_dir, QUrl(options.target_url).path(), folder, &db); QObject::connect(&engine, SIGNAL(finished()), &app, SLOT(quit())); QObject::connect(&engine, SIGNAL(transmissionProgress(Progress::Info)), &cmd, SLOT(transmissionProgressSlot())); // Have to be done async, else, an error before exec() does not terminate the event loop. QMetaObject::invokeMethod(&engine, "startSync", Qt::QueuedConnection); app.exec(); csync_destroy(_csync_ctx); ne_sock_exit(); if (engine.isAnotherSyncNeeded()) { qDebug() << "Restarting Sync, because another sync is needed"; goto restart_sync; } return 0; }