void QNetworkAccessAuthenticationManager::cacheCredentials(const QUrl &url, const QAuthenticator *authenticator) { Q_ASSERT(authenticator); QString domain = QString::fromLatin1("/"); // FIXME: make QAuthenticator return the domain QString realm = authenticator->realm(); QMutexLocker mutexLocker(&mutex); // Set two credentials actually: one with and one without the username in the URL QUrl copy = url; copy.setUserName(authenticator->user()); do { QByteArray cacheKey = authenticationKey(copy, realm); if (authenticationCache.hasEntry(cacheKey)) { QNetworkAuthenticationCache *auth = static_cast<QNetworkAuthenticationCache *>(authenticationCache.requestEntryNow(cacheKey)); auth->insert(domain, authenticator->user(), authenticator->password()); authenticationCache.releaseEntry(cacheKey); } else { QNetworkAuthenticationCache *auth = new QNetworkAuthenticationCache; auth->insert(domain, authenticator->user(), authenticator->password()); authenticationCache.addEntry(cacheKey, auth); } if (copy.userName().isEmpty()) { break; } else { copy.setUserName(QString()); } } while (true); }
void TsDataRetrieverFTP::TestFailLoginInvalid() { try { QUrl url; url.setHost("ftp.dgi.inpe.br"); url.setPath("/focos_operacao/"); url.setScheme("FTP"); url.setPort(21); url.setUserName("queimadas"); url.setUserName("2012"); curl_global_init(CURL_GLOBAL_ALL); //DataProvider information terrama2::core::DataProvider* dataProvider = new terrama2::core::DataProvider(); terrama2::core::DataProviderPtr dataProviderPtr(dataProvider); dataProvider->uri = url.url().toStdString(); dataProvider->intent = terrama2::core::DataProviderIntent::COLLECTOR_INTENT; dataProvider->dataProviderType = "FTP"; dataProvider->active = true; //empty filter terrama2::core::Filter filter; MockCurlWrapper mock_; ON_CALL(mock_, verifyURL(_)).WillByDefault(Return(CURLE_LOGIN_DENIED)); try { terrama2::core::DataRetrieverFTP retrieverFTP(dataProviderPtr, std::move(mock_)); QFAIL("Exception expected!"); } catch(const terrama2::core::DataRetrieverException& e) { } curl_global_cleanup(); } catch(const terrama2::Exception& e) { QFAIL(boost::get_error_info< terrama2::ErrorDescription >(e)->toStdString().c_str()); } catch(...) { QFAIL("Unexpected exception!"); } return; }
Song & MagnatuneService::fixPath(Song &s) const { s.type=Song::OnlineSvrTrack; if (MB_None!=membership) { QUrl url; #if QT_VERSION < 0x050000 url.setEncodedUrl(s.file.toLocal8Bit()); #else url=QUrl(s.file); #endif url.setScheme("http"); url.setHost(MB_Streaming==membership ? constStreamingHostname : constDownloadHostname); url.setUserName(username); url.setPassword(password); // And remove the commercial QString path = url.path(); path.insert(path.lastIndexOf('.'), "_nospeech"); url.setPath(path); s.file=url.toString(); // TODO: Magnatune downloads! // if (MB_Download==membership) { // s.genre=downloadTypeStr(download); // } } s.setIsFromOnlineService(name()); return encode(s); }
void MumbleDBus::getCurrentUrl(const QDBusMessage &msg) { if (!g.sh || !g.sh->isRunning() || ! g.uiSession) { QDBusConnection::sessionBus().send(msg.createErrorReply(QLatin1String("net.sourceforge.mumble.Error.connection"), QLatin1String("Not connected"))); return; } QString host, user, pw; unsigned short port; QUrl u; g.sh->getConnectionInfo(host, port, user, pw); u.setScheme(QLatin1String("mumble")); u.setHost(host); u.setPort(port); u.setUserName(user); #if QT_VERSION >= 0x050000 QUrlQuery query; query.addQueryItem(QLatin1String("version"), QLatin1String("1.2.0")); u.setQuery(query); #else u.addQueryItem(QLatin1String("version"), QLatin1String("1.2.0")); #endif QStringList path; Channel *c = ClientUser::get(g.uiSession)->cChannel; while (c->cParent) { path.prepend(c->qsName); c = c->cParent; } u.setPath(path.join(QLatin1String("/"))); QDBusConnection::sessionBus().send(msg.createReply(QString::fromLatin1(u.toEncoded()))); }
void MagnatuneDownloadDialog::DownloadFinished() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender()); reply->deleteLater(); // Close any open file download_file_.reset(); QUrl redirect = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); if (redirect.isValid()) { // Open the output file QString output_filename = GetOutputFilename(); download_file_.reset(new QFile(output_filename)); if (!download_file_->open(QIODevice::WriteOnly)) { ShowError(tr("Couldn't open output file %1").arg(output_filename)); return; } // Round and round we go redirect.setUserName(service_->username()); redirect.setPassword(service_->password()); current_reply_ = network_->get(QNetworkRequest(redirect)); connect(current_reply_, SIGNAL(error(QNetworkReply::NetworkError)), SLOT(Error(QNetworkReply::NetworkError))); connect(current_reply_, SIGNAL(finished()), SLOT(DownloadFinished())); connect(current_reply_, SIGNAL(downloadProgress(qint64,qint64)), SLOT(DownloadProgress(qint64,qint64))); connect(current_reply_, SIGNAL(readyRead()), SLOT(DownloadReadyRead())); return; } next_row_ ++; DownloadNext(); }
void DrawpileApp::openUrl(QUrl url) { // See if there is an existing replacable window MainWindow *win = nullptr; for(QWidget *widget : topLevelWidgets()) { MainWindow *mw = qobject_cast<MainWindow*>(widget); if(mw && mw->canReplace()) { win = mw; break; } } // No? Create a new one if(!win) win = new MainWindow; if(url.scheme() == "drawpile") { // Our own protocol: connect to a session if(url.userName().isEmpty()) { // Set username if not specified QSettings cfg; url.setUserName(cfg.value("history/username").toString()); } win->joinSession(url); } else { // Other protocols: load image win->openUrl(url); } }
static QUrl getApiUrl(BtsApi_private *p, const QString &method, const QueryList &querylist = QueryList()) { assertClient(p); QUrl res; res.setScheme("http"); res.setHost(p->client->getHost()); res.setPort(p->client->getPort()); if(!p->client->getUserName().isEmpty()) res.setUserName(p->client->getUserName()); if(!p->client->getPassword().isEmpty()) res.setPassword(p->client->getPassword()); res.setPath("/api"); QUrlQuery urlQuery; urlQuery.addQueryItem("method", method); for(const QueryPair &qp: querylist) { if(qp.second.isNull()) urlQuery.addQueryItem(qp.first, ""); else urlQuery.addQueryItem(qp.first, qp.second); } res.setQuery(urlQuery); return res; }
int Url::setUserName ( lua_State * L )// ( const QString & userName ) { QUrl* lhs = ValueInstaller2<QUrl>::check( L, 1 ); //QString* userName = ValueInstaller2<QString>::check( L, 2 ); lhs->setUserName( Util::toString( L, 2 ) ); return 0; }
QString DNSUpdater::getUpdateUrl() const { QUrl url; #ifdef QT_NO_OPENSSL url.setScheme("http"); #else url.setScheme("https"); #endif url.setUserName(m_username); url.setPassword(m_password); Q_ASSERT(!m_lastIP.isNull()); // Service specific switch (m_service) { case DNS::DYNDNS: url.setHost("members.dyndns.org"); break; case DNS::NOIP: url.setHost("dynupdate.no-ip.com"); break; default: qWarning() << "Unrecognized Dynamic DNS service!"; Q_ASSERT(0); } url.setPath("/nic/update"); QUrlQuery urlQuery(url); urlQuery.addQueryItem("hostname", m_domain); urlQuery.addQueryItem("myip", m_lastIP.toString()); url.setQuery(urlQuery); Q_ASSERT(url.isValid()); qDebug() << Q_FUNC_INFO << url.toString(); return url.toString(); }
void DataFetcher::fetch(QString urlString, QString username, QString password) { QUrl url = QUrl::fromUserInput(urlString + "/api/xml?depth=2"); m_errorMessage = "fetching " + url.toString() + "\n"; url.setUserName(username); url.setPassword(password); if (!url.isValid()) { emit finished(true, "invalid URL"); return; } if (url.scheme() == "file") { QString filename = url.toLocalFile(); QFile file(filename); if (file.open(QFile::ReadOnly)) { parseXml(QXmlStreamReader(file.readAll())); } else { emit finished(true, "Unable to read the file: " + filename); } file.close(); return; } QNetworkRequest request(url); request.setRawHeader("User-Agent", QString("Qt-Creator/%1 (QHttp %2; %3; %4; %5 bit)") .arg(Core::Constants::IDE_VERSION_LONG).arg(qVersion()) .arg(getOsString()).arg(QLocale::system().name()) .arg(QSysInfo::WordSize).toLocal8Bit()); request.setRawHeader("Accept", "text/xml,application/xml; charset=UTF-8"); request.setRawHeader("Authorization", "Basic " + QByteArray(QString("%1:%2").arg(username).arg(password).toAscii()).toBase64()); mNetworkAccess.proxyFactory()->setUseSystemConfiguration(true); mNetworkAccess.get( request ); }
void TsFactory::TestMakeParser() { try { //test postgis uri QUrl postgisUri; postgisUri.setScheme("postgis"); postgisUri.setHost("localhost"); postgisUri.setPort(5432); postgisUri.setUserName("postgres"); postgisUri.setPassword("postgres"); postgisUri.setPath("/basedeteste"); terrama2::core::DataSetItem unknownTypeItem(terrama2::core::DataSetItem::UNKNOWN_TYPE); //FIXME: create a DataSetItem kind for ParserPostgis // terrama2::collector::ParserPtr parser = terrama2::collector::Factory::makeParser(unknownTypeItem); // terrama2::collector::ParserPostgis* parserPostgis = dynamic_cast<terrama2::collector::ParserPostgis*>(parser.get()); // QVERIFY(parserPostgis); QUrl fileUri; fileUri.setScheme("file"); fileUri.setPath("/tmp"); terrama2::collector::ParserPtr parser = terrama2::collector::Factory::makeParser(unknownTypeItem); terrama2::collector::ParserOGR* parserOGR = dynamic_cast<terrama2::collector::ParserOGR*>(parser.get()); QVERIFY(parserOGR); terrama2::core::DataSetItem pcdInpeTypeItem(terrama2::core::DataSetItem::PCD_INPE_TYPE); parser = terrama2::collector::Factory::makeParser(pcdInpeTypeItem); terrama2::collector::ParserPcdInpe* parserPdcInpe = dynamic_cast<terrama2::collector::ParserPcdInpe*>(parser.get()); QVERIFY(parserPdcInpe); terrama2::core::DataSetItem pcdToaTypeItem(terrama2::core::DataSetItem::PCD_TOA5_TYPE); parser = terrama2::collector::Factory::makeParser(pcdToaTypeItem); terrama2::collector::ParserPcdToa5* parserPdctoa5 = dynamic_cast<terrama2::collector::ParserPcdToa5*>(parser.get()); QVERIFY(parserPdctoa5); terrama2::core::DataSetItem firePointTypeItem(terrama2::core::DataSetItem::FIRE_POINTS_TYPE); parser = terrama2::collector::Factory::makeParser(firePointTypeItem); terrama2::collector::ParserFirePoint* parserFirePoint = dynamic_cast<terrama2::collector::ParserFirePoint*>(parser.get()); QVERIFY(parserFirePoint); try { terrama2::core::DataSetItem diseaseTypeItem(terrama2::core::DataSetItem::DISEASE_OCCURRENCE_TYPE); parser = terrama2::collector::Factory::makeParser(diseaseTypeItem); QFAIL(NO_EXCEPTION_THROWN); } catch(terrama2::collector::ConflictingParserTypeSchemeException& e) { } } catch(...) { QFAIL(NO_EXCEPTION_EXPECTED); } }
void TsDataRetrieverFTP::TestOKDownloadFile() { try { QUrl url; url.setHost("ftp.dgi.inpe.br"); url.setPath("/focos_operacao/"); url.setScheme("FTP"); url.setPort(21); url.setUserName("queimadas"); url.setPassword("inpe_2012"); curl_global_init(CURL_GLOBAL_ALL); //DataProvider information terrama2::core::DataProvider* dataProvider = new terrama2::core::DataProvider(); terrama2::core::DataProviderPtr dataProviderPtr(dataProvider); dataProvider->uri = url.url().toStdString(); dataProvider->intent = terrama2::core::DataProviderIntent::COLLECTOR_INTENT; dataProvider->dataProviderType = "FTP"; dataProvider->active = true; //empty filter terrama2::core::Filter filter; std::string path; std::string mask = "exporta_20160501_0230.csv"; MockCurlWrapper mock_; ON_CALL(mock_, verifyURL(_)).WillByDefault(Return(CURLE_OK)); ON_CALL(mock_, getDownloadFiles(_,_,_)).WillByDefault(Return(CURLE_OK)); try { terrama2::core::DataRetrieverFTP retrieverFTP(dataProviderPtr, std::move(mock_)); auto remover = std::make_shared<terrama2::core::FileRemover>(); path = retrieverFTP.retrieveData(mask, filter, remover); } catch(...) { QFAIL("Unexpected exception!"); } curl_global_cleanup(); } catch(const terrama2::Exception& e) { QFAIL(boost::get_error_info< terrama2::ErrorDescription >(e)->toStdString().c_str()); } catch(...) { QFAIL("Unexpected exception!"); } return; }
void MagnatuneDownloadDialog::MetadataFinished() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender()); reply->deleteLater(); // The reply isn't valid XML so we can't use QtXML to parse it :( QString data = QString::fromUtf8(reply->readAll()); // Check for errors if (data.contains("<ERROR>")) { ShowError(tr("There was a problem fetching the metadata from Magnatune")); return; } // Work out what format we want QString type; switch (ui_->format->currentIndex()) { case MagnatuneService::Format_Ogg: type = "URL_OGGZIP"; break; case MagnatuneService::Format_Flac: type = "URL_FLACZIP"; break; case MagnatuneService::Format_Wav: type = "URL_WAVZIP"; break; case MagnatuneService::Format_MP3_VBR: type = "URL_VBRZIP"; break; case MagnatuneService::Format_MP3_128: type = "URL_128KMP3ZIP"; break; } // Parse the XML (lol) to find the URL QRegExp re(QString("<%1>([^<]+)</%2>").arg(type, type)); if (re.indexIn(data) == -1) { ShowError(tr("This album is not available in the requested format")); return; } // Munge the URL a bit QString url_text = Utilities::DecodeHtmlEntities(re.cap(1)); QUrl url = QUrl(url_text); url.setUserName(service_->username()); url.setPassword(service_->password()); qLog(Debug) << "Downloading" << url; // Start the actual download current_reply_ = network_->get(QNetworkRequest(url)); connect(current_reply_, SIGNAL(error(QNetworkReply::NetworkError)), SLOT(Error(QNetworkReply::NetworkError))); connect(current_reply_, SIGNAL(finished()), SLOT(DownloadFinished())); connect(current_reply_, SIGNAL(downloadProgress(qint64,qint64)), SLOT(DownloadProgress(qint64,qint64))); connect(current_reply_, SIGNAL(readyRead()), SLOT(DownloadReadyRead())); // Close any open file download_file_.reset(); // Open the output file QString output_filename = GetOutputFilename(); download_file_.reset(new QFile(output_filename)); if (!download_file_->open(QIODevice::WriteOnly)) { ShowError(tr("Couldn't open output file %1").arg(output_filename)); } }
//----------------------------------------------------------------------------- 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; }
/*! Returns the URL of the WAP gateway (including port, login and password). \code QWapAccount acc(...) ... QUrl gateway = acc.gateway(); QString password = gateway.password(); QString username = gateway.userName(); \endcode \sa setGateway(), QUrl */ QUrl QWapAccount::gateway() const { QUrl url; url.setHost( d->conf->value( QLatin1String("Wap/Gateway") ).toString()); url.setUserName( d->conf->value( QLatin1String("Wap/UserName") ).toString() ); url.setPassword( d->conf->value( QLatin1String("Wap/Password") ).toString() ); url.setPort( d->conf->value( QLatin1String("Wap/Port")).toInt() ); return url; }
/*! Returns a new QNetworkReply object to handle the operation \a op and request \a req. The device \a outgoingData is always 0 for Get and Head requests, but is the value passed to post() and put() in those operations (the QByteArray variants will pass a QBuffer object). The default implementation calls QNetworkCookieJar::cookiesForUrl() on the cookie jar set with setCookieJar() to obtain the cookies to be sent to the remote server. The returned object must be in an open state. */ QNetworkReply *QNetworkAccessManager::createRequest(QNetworkAccessManager::Operation op, const QNetworkRequest &req, QIODevice *outgoingData) { Q_D(QNetworkAccessManager); QNetworkRequest request = req; if (!request.header(QNetworkRequest::ContentLengthHeader).isValid() && outgoingData && !outgoingData->isSequential()) { // request has no Content-Length // but the data that is outgoing is random-access request.setHeader(QNetworkRequest::ContentLengthHeader, outgoingData->size()); } if (d->cookieJar) { QList<QNetworkCookie> cookies = d->cookieJar->cookiesForUrl(request.url()); if (!cookies.isEmpty()) request.setHeader(QNetworkRequest::CookieHeader, qVariantFromValue(cookies)); } // first step: create the reply QUrl url = request.url(); QNetworkReplyImpl *reply = new QNetworkReplyImpl(this); QNetworkReplyImplPrivate *priv = reply->d_func(); priv->manager = this; // second step: fetch cached credentials QNetworkAuthenticationCredential *cred = d->fetchCachedCredentials(url); if (cred) { url.setUserName(cred->user); url.setPassword(cred->password); priv->urlForLastAuthentication = url; } // third step: setup the reply priv->setup(op, request, outgoingData); if (request.attribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferNetwork).toInt() != QNetworkRequest::AlwaysNetwork) priv->setNetworkCache(d->networkCache); #ifndef QT_NO_NETWORKPROXY QList<QNetworkProxy> proxyList = d->queryProxy(QNetworkProxyQuery(request.url())); priv->proxyList = proxyList; #endif // fourth step: find a backend priv->backend = d->findBackend(op, request); if (priv->backend) { priv->backend->setParent(reply); priv->backend->reply = priv; } #ifndef QT_NO_OPENSSL reply->setSslConfiguration(request.sslConfiguration()); #endif return reply; }
QUrl ServicesDbTestUtils::getDbModifyUrl() { // read the DB values from the DB config file. Settings s = _readDbConfig(); QUrl result; result.setScheme("hootapidb"); result.setHost(s.get("DB_HOST").toString()); result.setPort(s.get("DB_PORT").toInt()); result.setUserName(s.get("DB_USER").toString()); result.setPassword(s.get("DB_PASSWORD").toString()); result.setPath("/" + s.get("DB_NAME").toString() + "/testMap"); return result; }
QVariantHash ChooseSamba::values() const { QVariantHash ret = m_args; QString address = ui->addressLE->text().trimmed(); QUrl url; if (address.startsWith(QLatin1String("//"))) { url = QUrl(QLatin1String("smb:") % address); } else if (address.startsWith(QLatin1String("/"))) { url = QUrl(QLatin1String("smb:/") % address); } else if (address.startsWith(QLatin1String("://"))) { url = QUrl(QLatin1String("smb") % address); } else if (address.startsWith(QLatin1String("smb://"))) { url = QUrl(address); } else if (!QUrl::fromUserInput(address).scheme().isEmpty() && QUrl::fromUserInput(address).scheme() != QStringLiteral("smb")) { url = QUrl::fromUserInput(address); url.setScheme(QStringLiteral("smb")); } else { url = QUrl(QStringLiteral("smb://") % address); } qDebug() << 1 << url; if (!ui->usernameLE->text().isEmpty()) { url.setUserName(ui->usernameLE->text()); } if (!ui->passwordLE->text().isEmpty()) { url.setPassword(ui->passwordLE->text()); } qDebug() << 2 << url; qDebug() << 3 << url.url() << url.path().section(QLatin1Char('/'), -1, -1);// same as url.fileName() qDebug() << 4 << url.fileName(); qDebug() << 5 << url.host() << url.url().section(QLatin1Char('/'), 3, 3).toLower(); ret[KCUPS_DEVICE_URI] = url.url(); ret[KCUPS_DEVICE_INFO] = url.fileName(); // if there is 4 '/' means the url is like // smb://group/host/printer, so the location is at a different place if (url.url().count(QLatin1Char('/') == 4)) { ret[KCUPS_DEVICE_LOCATION] = url.url().section(QLatin1Char('/'), 3, 3).toLower(); } else { ret[KCUPS_DEVICE_LOCATION] = url.host(); } return ret; }
static QByteArray makeCacheKey(QUrl &url, QNetworkProxy *proxy) { QString result; QUrl copy = url; QString scheme = copy.scheme().toLower(); bool isEncrypted = scheme == QLatin1String("https"); copy.setPort(copy.port(isEncrypted ? 443 : 80)); if (scheme == QLatin1String("preconnect-http")) { copy.setScheme(QLatin1String("http")); } else if (scheme == QLatin1String("preconnect-https")) { copy.setScheme(QLatin1String("https")); } result = copy.toString(QUrl::RemoveUserInfo | QUrl::RemovePath | QUrl::RemoveQuery | QUrl::RemoveFragment | QUrl::FullyEncoded); #ifndef QT_NO_NETWORKPROXY if (proxy && proxy->type() != QNetworkProxy::NoProxy) { QUrl key; switch (proxy->type()) { case QNetworkProxy::Socks5Proxy: key.setScheme(QLatin1String("proxy-socks5")); break; case QNetworkProxy::HttpProxy: case QNetworkProxy::HttpCachingProxy: key.setScheme(QLatin1String("proxy-http")); break; default: break; } if (!key.scheme().isEmpty()) { key.setUserName(proxy->user()); key.setHost(proxy->hostName()); key.setPort(proxy->port()); key.setQuery(result); result = key.toString(QUrl::FullyEncoded); } } #else Q_UNUSED(proxy) #endif return "http-connection:" + result.toLatin1(); }
QUrl JoinDialog::getUrl() const { QString address = getAddress(); QString username = getUserName(); QString scheme; if(address.startsWith("drawpile://")==false) scheme = "drawpile://"; QUrl url = QUrl(scheme + address, QUrl::TolerantMode); if(!url.isValid() || url.host().isEmpty() || username.isEmpty()) return QUrl(); url.setUserName(username); return url; }
void MagnatuneDownloadDialog::MetadataFinished() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender()); reply->deleteLater(); // The reply isn't valid XML so we can't use QtXML to parse it :( QString data = QString::fromUtf8(reply->readAll()); // Check for errors if (data.contains("<ERROR>")) { ShowError(tr("There was a problem fetching the metadata from Magnatune")); return; } // Work out what format we want QString type; switch (ui_->format->currentIndex()) { case MagnatuneService::Format_Ogg: type = "URL_OGGZIP"; break; case MagnatuneService::Format_Flac: type = "URL_FLACZIP"; break; case MagnatuneService::Format_Wav: type = "URL_WAVZIP"; break; case MagnatuneService::Format_MP3_VBR: type = "URL_VBRZIP"; break; case MagnatuneService::Format_MP3_128: type = "URL_128KMP3ZIP"; break; } // Parse the XML (lol) to find the URL QRegExp re(QString("<%1>([^<]+)</%2>").arg(type, type)); if (re.indexIn(data) == -1) { ShowError(tr("This album is not available in the requested format")); return; } // Munge the URL a bit QString url_text = re.cap(1); url_text.replace("&", "&"); QUrl url = QUrl(url_text); url.setUserName(service_->username()); url.setPassword(service_->password()); // Start the actual download current_reply_ = network_->get(QNetworkRequest(url)); connect(current_reply_, SIGNAL(error(QNetworkReply::NetworkError)), SLOT(Error(QNetworkReply::NetworkError))); connect(current_reply_, SIGNAL(finished()), SLOT(DownloadFinished())); // No DownloadProgress connection because the first one is a redirect }
void addOutput(std::shared_ptr<terrama2::services::collector::core::DataManager> dataManager) { /////////////////////////////////////////////// // output 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* outputDataProvider = new terrama2::core::DataProvider(); terrama2::core::DataProviderPtr outputDataProviderPtr(outputDataProvider); outputDataProvider->id = 2; outputDataProvider->name = "DataProvider queimadas postgis"; outputDataProvider->uri = uri.url().toStdString(); outputDataProvider->intent = terrama2::core::DataProviderIntent::COLLECTOR_INTENT; outputDataProvider->dataProviderType = "POSTGIS"; outputDataProvider->active = true; dataManager->add(outputDataProviderPtr); // DataSeries information terrama2::core::DataSeries* outputDataSeries = new terrama2::core::DataSeries(); terrama2::core::DataSeriesPtr outputDataSeriesPtr(outputDataSeries); outputDataSeries->id = 2; outputDataSeries->name = "DataProvider queimadas postgis"; auto& semanticsManager = terrama2::core::SemanticsManager::getInstance(); outputDataSeries->semantics = semanticsManager.getSemantics("OCCURRENCE-postgis"); outputDataSeries->dataProviderId = outputDataProviderPtr->id; dataManager->add(outputDataSeriesPtr); // DataSet information terrama2::core::DataSetOccurrence* outputDataSet = new terrama2::core::DataSetOccurrence(); outputDataSet->active = true; outputDataSet->id = 2; outputDataSet->dataSeriesId = outputDataSeries->id; outputDataSet->format.emplace("table_name", "queimadas_test_table"); outputDataSeries->datasetList.emplace_back(outputDataSet); }
void QPushbulletHandler::postRequest(QUrl url, const QByteArray &data) { qDebug() << "Post Request: " << QString(data); QNetworkRequest request(url); if (m_CurrentOperation == CURRENT_OPERATION::UPLOAD_FILE) { request.setRawHeader(QString("Content-Type").toUtf8(), QString("multipart/form-data; boundary=margin").toUtf8()); } else { url.setUserName(m_APIKey); request.setUrl(url); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); } if (m_CurrentOperation == CURRENT_OPERATION::DELETE_CONTACT || m_CurrentOperation == CURRENT_OPERATION::DELETE_DEVICE || m_CurrentOperation == CURRENT_OPERATION::DELETE_PUSH) m_NetworkManager.deleteResource(QNetworkRequest(url)); else m_NetworkManager.post(request, data); }
terrama2::core::DataProviderPtr inputDataProvider() { 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->name = "PostGIS provider"; dataProvider->uri = uri.url().toStdString(); dataProvider->intent = terrama2::core::DataProviderIntent::COLLECTOR_INTENT; dataProvider->dataProviderType = "POSTGIS"; dataProvider->active = true; dataProvider->id = 1; return dataProviderPtr; }
static QByteArray makeCacheKey(QNetworkAccessHttpBackend *backend, QNetworkProxy *proxy) { QByteArray result; QUrl copy = backend->url(); bool isEncrypted = copy.scheme().toLower() == QLatin1String("https"); copy.setPort(copy.port(isEncrypted ? DefaultHttpsPort : DefaultHttpPort)); result = copy.toEncoded(QUrl::RemovePassword | QUrl::RemovePath | QUrl::RemoveQuery | QUrl::RemoveFragment); #ifndef QT_NO_NETWORKPROXY if (proxy->type() != QNetworkProxy::NoProxy) { QUrl key; switch (proxy->type()) { case QNetworkProxy::Socks5Proxy: key.setScheme(QLatin1String("proxy-socks5")); break; case QNetworkProxy::HttpProxy: case QNetworkProxy::HttpCachingProxy: key.setScheme(QLatin1String("proxy-http")); break; default: break; } if (!key.scheme().isEmpty()) { key.setUserName(proxy->user()); key.setHost(proxy->hostName()); key.setPort(proxy->port()); key.setEncodedQuery(result); result = key.toEncoded(); } } #endif return "http-connection:" + result; }
QUrl SieveEditorUtil::SieveServerConfig::url() const { QUrl u; u.setHost(serverName); u.setUserName(userName); u.setPassword(password); u.setPort(port); QString authStr; switch (authenticationType) { case MailTransport::Transport::EnumAuthenticationType::CLEAR: case MailTransport::Transport::EnumAuthenticationType::PLAIN: authStr = QStringLiteral("PLAIN"); break; case MailTransport::Transport::EnumAuthenticationType::LOGIN: authStr = QStringLiteral("LOGIN"); break; case MailTransport::Transport::EnumAuthenticationType::CRAM_MD5: authStr = QStringLiteral("CRAM-MD5"); break; case MailTransport::Transport::EnumAuthenticationType::DIGEST_MD5: authStr = QStringLiteral("DIGEST-MD5"); break; case MailTransport::Transport::EnumAuthenticationType::GSSAPI: authStr = QStringLiteral("GSSAPI"); break; case MailTransport::Transport::EnumAuthenticationType::ANONYMOUS: authStr = QStringLiteral("ANONYMOUS"); break; default: authStr = QStringLiteral("PLAIN"); break; } QUrlQuery query; query.addQueryItem(QStringLiteral("x-mech"), authStr); u.setQuery(query); return u; }
static QByteArray proxyAuthenticationKey(const QNetworkProxy &proxy, const QString &realm) { QUrl key; switch (proxy.type()) { case QNetworkProxy::Socks5Proxy: key.setScheme(QLatin1String("proxy-socks5")); break; case QNetworkProxy::HttpProxy: case QNetworkProxy::HttpCachingProxy: key.setScheme(QLatin1String("proxy-http")); break; case QNetworkProxy::FtpCachingProxy: key.setScheme(QLatin1String("proxy-ftp")); break; case QNetworkProxy::DefaultProxy: case QNetworkProxy::NoProxy: // shouldn't happen return QByteArray(); // no default: // let there be errors if a new proxy type is added in the future } if (key.scheme().isEmpty()) // proxy type not handled return QByteArray(); key.setUserName(proxy.user()); key.setHost(proxy.hostName()); key.setPort(proxy.port()); key.setFragment(realm); return "auth:" + key.toEncoded(); }
void MagnatuneDownloadDialog::DownloadNext() { // We have to download an XML file first that gives us the URLs of the actual // zipped album. if (next_row_ >= ui_->albums->topLevelItemCount()) { AllFinished(false); return; } QTreeWidgetItem* item = ui_->albums->topLevelItem(next_row_); QString sku = item->data(0, Qt::UserRole).toString(); item->setData(1, Qt::DisplayRole, tr("Starting...")); QUrl url = QString(MagnatuneService::kDownloadUrl); url.setUserName(service_->username()); url.setPassword(service_->password()); url.addQueryItem("id", MagnatuneService::kPartnerId); url.addQueryItem("sku", sku); current_reply_ = network_->get(QNetworkRequest(url)); connect(current_reply_, SIGNAL(error(QNetworkReply::NetworkError)), SLOT(Error(QNetworkReply::NetworkError))); connect(current_reply_, SIGNAL(finished()), SLOT(MetadataFinished())); }
void KWebKitPart::slotLinkHovered(const QString& _link, const QString& /*title*/, const QString& /*content*/) { QString message; if (_link.isEmpty()) { message = QL1S(""); emit m_browserExtension->mouseOverInfo(KFileItem()); } else { QUrl linkUrl (_link); const QString scheme = linkUrl.scheme(); // Protect the user against URL spoofing! linkUrl.setUserName(QString()); const QString link (linkUrl.toString()); if (QString::compare(scheme, QL1S("mailto"), Qt::CaseInsensitive) == 0) { message += i18nc("status bar text when hovering email links; looks like \"Email: [email protected] - CC: [email protected] -BCC: [email protected] - Subject: Hi translator\"", "Email: "); // Workaround: for QUrl's parsing deficiencies of "mailto:[email protected]". if (!linkUrl.hasQuery()) linkUrl = QUrl(scheme + '?' + linkUrl.path()); QMap<QString, QStringList> fields; QList<QPair<QString, QString> > queryItems = linkUrl.queryItems(); const int count = queryItems.count(); for(int i = 0; i < count; ++i) { const QPair<QString, QString> queryItem (queryItems.at(i)); //kDebug() << "query: " << queryItem.first << queryItem.second; if (queryItem.first.contains(QL1C('@')) && queryItem.second.isEmpty()) fields["to"] << queryItem.first; if (QString::compare(queryItem.first, QL1S("to"), Qt::CaseInsensitive) == 0) fields["to"] << queryItem.second; if (QString::compare(queryItem.first, QL1S("cc"), Qt::CaseInsensitive) == 0) fields["cc"] << queryItem.second; if (QString::compare(queryItem.first, QL1S("bcc"), Qt::CaseInsensitive) == 0) fields["bcc"] << queryItem.second; if (QString::compare(queryItem.first, QL1S("subject"), Qt::CaseInsensitive) == 0) fields["subject"] << queryItem.second; } if (fields.contains(QL1S("to"))) message += fields.value(QL1S("to")).join(QL1S(", ")); if (fields.contains(QL1S("cc"))) message += i18nc("status bar text when hovering email links; looks like \"Email: [email protected] - CC: [email protected] -BCC: [email protected] - Subject: Hi translator\"", " - CC: ") + fields.value(QL1S("cc")).join(QL1S(", ")); if (fields.contains(QL1S("bcc"))) message += i18nc("status bar text when hovering email links; looks like \"Email: [email protected] - CC: [email protected] -BCC: [email protected] - Subject: Hi translator\"", " - BCC: ") + fields.value(QL1S("bcc")).join(QL1S(", ")); if (fields.contains(QL1S("subject"))) message += i18nc("status bar text when hovering email links; looks like \"Email: [email protected] - CC: [email protected] -BCC: [email protected] - Subject: Hi translator\"", " - Subject: ") + fields.value(QL1S("subject")).join(QL1S(" ")); } else if (scheme == QL1S("javascript")) { message = KStringHandler::rsqueeze(link, 150); if (link.startsWith(QL1S("javascript:window.open"))) message += i18n(" (In new window)"); } else { message = link; QWebFrame* frame = page() ? page()->currentFrame() : 0; if (frame) { QWebHitTestResult result = frame->hitTestContent(page()->view()->mapFromGlobal(QCursor::pos())); QWebFrame* target = result.linkTargetFrame(); if (frame->parentFrame() && target == frame->parentFrame()) { message += i18n(" (In parent frame)"); } else if (!target || target != frame) { message += i18n(" (In new window)"); } } KFileItem item (linkUrl, QString(), KFileItem::Unknown); emit m_browserExtension->mouseOverInfo(item); } } emit setStatusBarText(message); }
int main(int argc, char* argv[]) { terrama2::core::initializeTerraMA(); { 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("OCCURRENCE-postgis"); //DataSet information terrama2::core::DataSetOccurrence* dataSet = new terrama2::core::DataSetOccurrence(); dataSet->active = true; dataSet->format.emplace("table_name", "fires"); dataSet->format.emplace("timestamp_property", "data_pas"); dataSet->format.emplace("geometry_property", "geom"); dataSeries->datasetList.emplace_back(dataSet); //accessing data terrama2::core::DataAccessorOccurrencePostGis accessor(dataProviderPtr, dataSeriesPtr); //empty filter terrama2::core::Filter filter; boost::local_time::time_zone_ptr zone(new boost::local_time::posix_time_zone("+00")); filter.lastValue = true; std::string boundingBoxWkt = "POLYGON((-51.11 -17.74, -41.11 -17.74, -41.11 -20.83, -51.11 -20.83, -51.11 -17.74))"; te::gm::Geometry* geometry = te::gm::WKTReader::read(boundingBoxWkt.c_str()); geometry->setSRID(4326); filter.region = std::shared_ptr<te::gm::Geometry>(geometry); terrama2::core::OccurrenceSeriesPtr occurrenceSeries = accessor.getOccurrenceSeries(filter); assert(occurrenceSeries->occurrencesMap().size() == 1); auto teDataSet = (*occurrenceSeries->occurrencesMap().begin()).second.syncDataSet->dataset(); //Print column names and types (DateTime/Double) int dateColumn = -1; int geomColumn = -1; std::string names, types; for(int i = 0; i < teDataSet->getNumProperties(); ++i) { std::string name = teDataSet->getPropertyName(i); names+= name + "\t"; if(name == "data_pas") { types+= "DataTime\t"; dateColumn = i; } else if(name == "geom") { types+= "Geometry\t"; geomColumn = i; } else types+= "Int\t"; } std::cout << names << std::endl; std::cout << types << std::endl; //Print values teDataSet->moveBeforeFirst(); while(teDataSet->moveNext()) { for(int i = 0; i < teDataSet->getNumProperties(); ++i) { if(teDataSet->isNull(i)) { std::cout << "NULL"; continue; } if(i == dateColumn) { std::shared_ptr<te::dt::DateTime> dateTime = teDataSet->getDateTime(i); std::cout << dateTime->toString(); } else if(i == geomColumn) { std::cout << "<<Geometry>>"; } else { std::cout << teDataSet->getInt32(i); } std::cout << "\t"; } std::cout << std::endl; } std::cout << "\ndataset size: " << teDataSet->size() << std::endl; } terrama2::core::finalizeTerraMA(); return 0; }