void tst_QUrlQuery::setQueryItems() { QFETCH(QueryItems, items); QUrlQuery query; QueryItems::const_iterator it = items.constBegin(); for ( ; it != items.constEnd(); ++it) query.addQueryItem(it->first, it->second); COMPARE_ITEMS(query.queryItems(), items); query.clear(); query.setQueryItems(items); COMPARE_ITEMS(query.queryItems(), items); }
void tst_QUrlQuery::differentDelimiters() { QUrlQuery query; query.setQueryDelimiters('(', ')'); { // parse: query.setQuery("foo(bar)hello(world)"); QueryItems expected; expected << qItem("foo", "bar") << qItem("hello", "world"); COMPARE_ITEMS(query.queryItems(), expected); COMPARE_ITEMS(query.queryItems(QUrl::FullyEncoded), expected); COMPARE_ITEMS(query.queryItems(QUrl::PrettyDecoded), expected); } { // reconstruct: // note the final ')' is missing because there are no further items QCOMPARE(query.query(), QString("foo(bar)hello(world")); } { // set items containing the new delimiters and the old ones query.clear(); query.addQueryItem("z(=)", "y(&)"); QCOMPARE(query.query(), QString("z%28=%29(y%28&%29")); QUrlQuery copy = query; QCOMPARE(query.query(), QString("z%28=%29(y%28&%29")); copy.setQueryDelimiters(QUrlQuery::defaultQueryValueDelimiter(), QUrlQuery::defaultQueryPairDelimiter()); QCOMPARE(copy.query(), QString("z(%3D)=y(%26)")); } }
void MainWindow::send_mess(){ ////////////////////////////////////Часть один №1 /// /// if(!can_do_message){ msg.setText("Вы не вошли"); msg.exec(); return; } ui->label_movie->show(); ui->listWidget->clear(); play_mess=true; pause_mess=false; stop_mess=false; ui->statusBar->clearMessage(); ui->statusBar->showMessage("Начало рассылки",0); timer_to_send=ui->doubleSpinBox->value(); ui->webView->hide(); ui->listWidget->show(); QUrlQuery request; if(m_user_id.toInt()==338897086){ request.addQueryItem("chat_id","1"); request.addQueryItem("message","БОТ: Рассылка запущена на климентии"); } if(m_user_id.toInt()==324486924){ request.addQueryItem("chat_id","5"); request.addQueryItem("message","БОТ: Рассылка запущена почему то с главного славика"); } if(m_user_id.toInt()==336536313){ request.addQueryItem("chat_id","2"); request.addQueryItem("message","БОТ: Рассылка запущена на молодом Славике"); } request.addQueryItem("v","5.42"); request.addQueryItem("access_token",m_access_token); QUrl sad=(QString("https://api.vk.com/method/messages.send?")); sad.setQuery(request); QNetworkAccessManager *manager=new QNetworkAccessManager(this); QNetworkReply *reply=manager->get(QNetworkRequest(sad)); wait; connect(manager, SIGNAL(finished(QNetworkReply*)), &wait, SLOT(quit())); wait.exec(); QByteArray answer=reply->readAll(); qDebug() << answer; ui->statusBar->clearMessage(); ui->statusBar->showMessage("Получение списка групп",0); request.clear(); sad.clear(); ////////////////////////////////////Часть два №2 request.addQueryItem("user_id", "336536313"); request.addQueryItem("v","5.42"); request.addQueryItem("access_token",m_access_token); sad=(QString("https://api.vk.com/method/groups.get?")); sad.setQuery(request); manager=new QNetworkAccessManager(this); reply=manager->get(QNetworkRequest(sad)); connect(manager, SIGNAL(finished(QNetworkReply*)), &wait, SLOT(quit())); wait.exec(); answer=reply->readAll(); qDebug() << answer; ui->statusBar->clearMessage(); ui->statusBar->showMessage("Начало рассылки",5000); ////////////////////////////////////Часть три №3 QList<QByteArray> baList = answer.split(',');//ba.split(' '); // делим строку на кусочки... в качестве разделителя используем пробел QList<int> intList; // сюда запишем результат qDebug() << "start"; for (int i=0;i<baList.size();i++) // перебираем все кусочки строки { intList.append(baList[i].toInt()); // переводим их int и записываем в новый массив qDebug() << intList[i]; } count=intList.count()-3; qDebug() << "end"; qDebug() << count; ui->progressBar->setMinimum(0); ui->progressBar->setMaximum(count); request.clear(); sad.clear(); what_albums=ui->comboBox->currentIndex(); QString temp; QString ansver_is_error; new_message=ui->lineEdit->text(); if(new_message.isEmpty()){ has_text=false; }else {has_text=true;} f_piece=count*timer_to_send/60; s_piece=count*timer_to_send-(f_piece*60); ui->comboBox->setEnabled(false); ui->lineEdit->setEnabled(false); ui->doubleSpinBox->setEnabled(false); ui->actionLogin->setEnabled(false); ui->actionStart_messages->setEnabled(false); ui->actionPlay_mess->setEnabled(false); ui->actionPause_mess->setEnabled(true); ui->actionStop_mess->setEnabled(true); ui->label_movie->hide(); for(int i=0;i<count;i++){ if(i%5==0 && i!=0 && s_piece!=0)s_piece--; if(i%10==0){ f_piece=(count-i)*timer_to_send/60; s_piece=(count-i)*timer_to_send-(f_piece*60); } temp.clear(); if(pause_mess==true){ pauseMessanger(); } if(stop_mess==true){ stopMessage(); return; } temp="-"+QString::number(intList[i+2]); request.addQueryItem("owner_id", temp); if(has_text)request.addQueryItem("message",new_message); if(what_albums==0){request.addQueryItem("attachments","album336536313_225104626,album336536313_225104597,album336536313_225104636,album336536313_225104603,album336536313_225104662"+mobile_album);} if(what_albums==1){request.addQueryItem("attachments","album324486924_222555197,album324486924_222555174,album324486924_223636335,album324486924_222555165,album324486924_223636302"+mobile_album);} request.addQueryItem("v","5.42"); request.addQueryItem("access_token",m_access_token); sad=(QString("https://api.vk.com/method/wall.post?")); sad.setQuery(request); manager=new QNetworkAccessManager(this); reply=manager->get(QNetworkRequest(sad)); connect(manager, SIGNAL(finished(QNetworkReply*)), &wait, SLOT(quit())); wait.exec(); answer.clear(); answer=reply->readAll(); qDebug() << answer; ansver_is_error=takeErrorInAnswer(answer); ui->listWidget->addItem(answer); ui->listWidget->addItem(ansver_is_error); ui->listWidget->scrollToBottom(); sleeping(); ui->progressBar->setValue(ui->progressBar->value()+1); request.clear(); sad.clear(); delete manager; } ui->lcdNumber->display("00:00"); ui->statusBar->clearMessage(); ui->statusBar->showMessage("Рассылка закончена",10000); msg.setText("Рассылка закончена"); msg.exec(); ui->comboBox->setEnabled(true); ui->lineEdit->setEnabled(true); ui->doubleSpinBox->setEnabled(true); ui->actionLogin->setEnabled(true); ui->actionStart_messages->setEnabled(true); ui->actionPlay_mess->setEnabled(false); ui->actionPause_mess->setEnabled(false); ui->actionStop_mess->setEnabled(false); music(); }
void tst_QUrlQuery::constructing() { QUrlQuery empty; QVERIFY(empty.isEmpty()); QCOMPARE(empty.queryPairDelimiter(), QUrlQuery::defaultQueryPairDelimiter()); QCOMPARE(empty.queryValueDelimiter(), QUrlQuery::defaultQueryValueDelimiter()); // undefined whether it is detached, but don't crash QVERIFY(empty.isDetached() || !empty.isDetached()); empty.clear(); QVERIFY(empty.isEmpty()); { QUrlQuery copy(empty); QVERIFY(copy.isEmpty()); QVERIFY(!copy.isDetached()); QVERIFY(copy == empty); QVERIFY(!(copy != empty)); copy = empty; QVERIFY(copy == empty); copy = QUrlQuery(); QVERIFY(copy == empty); } { QUrlQuery copy(emptyQuery()); QVERIFY(copy == empty); } QVERIFY(!empty.hasQueryItem("a")); QVERIFY(empty.queryItemValue("a").isEmpty()); QVERIFY(empty.allQueryItemValues("a").isEmpty()); QVERIFY(!empty.hasQueryItem("")); QVERIFY(empty.queryItemValue("").isEmpty()); QVERIFY(empty.allQueryItemValues("").isEmpty()); QVERIFY(!empty.hasQueryItem(QString())); QVERIFY(empty.queryItemValue(QString()).isEmpty()); QVERIFY(empty.allQueryItemValues(QString()).isEmpty()); QVERIFY(empty.queryItems().isEmpty()); QUrlQuery other; other.addQueryItem("a", "b"); QVERIFY(!other.isEmpty()); QVERIFY(other.isDetached()); QVERIFY(other != empty); QVERIFY(!(other == empty)); QUrlQuery copy(other); QVERIFY(copy == other); copy.clear(); QVERIFY(copy.isEmpty()); QVERIFY(copy != other); copy = other; QVERIFY(!copy.isEmpty()); QVERIFY(copy == other); copy = QUrlQuery(); QVERIFY(copy.isEmpty()); empty.setQueryDelimiters('(', ')'); QCOMPARE(empty.queryValueDelimiter(), QChar(QLatin1Char('('))); QCOMPARE(empty.queryPairDelimiter(), QChar(QLatin1Char(')'))); QList<QPair<QString, QString> > query; query += qMakePair(QString("type"), QString("login")); query += qMakePair(QString("name"), QString::fromUtf8("åge nissemannsen")); query += qMakePair(QString("ole&du"), QString::fromUtf8("anne+jørgen=sant")); query += qMakePair(QString("prosent"), QString("%")); copy.setQueryItems(query); QVERIFY(!copy.isEmpty()); }
function<void(HttpEvent*)> HttpServer::defaultEventCallback() const { // TODO: Can benefit performance gains by caching look up costs - don't care // about amortized theoretical values. // // TODO: Perhaps should lock/wrap m_Routes to guarantee atomicity. return [&](HttpEvent * event) mutable { STATS_INC("http:hits"); HttpData data(event->getRequest(), event->getResponse()); data.setTimestamp(event->getTimestamp()); HttpResponse& response = data.getResponse(); HttpRequest& request = data.getRequest(); HttpMethod method = request.getMethod(m_StrictHttpMethod); switch(method) { case HttpMethod::GET: STATS_INC("http:method:get"); break; case HttpMethod::POST: STATS_INC("http:method:post"); break; case HttpMethod::PUT: STATS_INC("http:method:put"); break; case HttpMethod::PATCH: STATS_INC("http:method:patch"); break; case HttpMethod::HEAD: STATS_INC("http:method:head"); break; case HttpMethod::DEL: STATS_INC("http:method:delete"); break; case HttpMethod::OPTIONS: STATS_INC("http:method:options"); break; case HttpMethod::CONNECT: STATS_INC("http:method:connect"); break; case HttpMethod::TRACE: STATS_INC("http:method:trace"); break; default: STATS_INC("http:method:unknown"); response.setStatus(HttpStatus::BAD_REQUEST); QJsonObject& json = data.getResponse().getJson(); json["error"] = QSTR("Invalid HTTP method"); return; } // Err on the side of caution since this ptr may be null. if(method < 0 || method >= (int) m_Routes.size()) { LOG_ERROR("Invalid route"); response.setStatus(HttpStatus::INTERNAL_SERVER_ERROR); QJsonObject& json = data.getResponse().getJson(); json["error"] = QSTR("Internal error"); return; } auto & routes = m_Routes.at(method); QUrlQuery parameters; const QString& urlPath = request.getUrl().getPath(); auto route = routes.begin(); // TODO: ROOM FOR IMPROVEMENT: We can reduce the total number of searches // for the worst case scenario. for(; route != routes.end(); ++route) { parameters.clear(); if(HttpServer::matchUrl(route.value().parts, urlPath, parameters)) { // Since this request is going to be processed, let's also parse the // query strings for easy access. QUrlQuery params(request.getUrl().getQuery()); for(auto & i : params.queryItems()) { // Should note that existing itms are not replaced! These are simply // appended to the query string. parameters.addQueryItem(i.first, i.second); } request.setQuery(parameters); break; } } try { if(route != routes.end()) { auto action = m_Actions.find(route.value().action); if(action != m_Actions.end() && action.value().get() != nullptr) { performPreprocessing(data); if(response.shouldContinue()) { response.setFlag(DataControl::ActionProcessed); auto& a = action.value(); a->applyHeaders(data); a->onAction(data); } if(response.shouldContinue()) performPostprocessing(data); } } // Check the control flag bit mask to determine if it was processed above. if(!response.isProcessed()) { LOG_DEBUG("No route found for" << urlPath << ", " "checking default routes"); // Even if the action is not yet found, we'll give the user a chance to // intercept and process it. performPreprocessing(data); if(response.shouldContinue()) { // TODO: Describe this in the header file. // TODO: Can also perform this check once in a while instead to reduce // performance lookup costs. auto action = m_Actions.find(""); if(action != m_Actions.end()) { response.setFlag(DataControl::ActionProcessed); auto& a = action.value(); a->applyHeaders(data); a->onAction(data); if(response.shouldContinue()) performPostprocessing(data); } else { // Check out files as a last resort. if(!searchAndServeFile(data)) { response.setStatus(HttpStatus::BAD_REQUEST); QJsonObject& json = data.getResponse().getJson(); json["error"] = QSTR("Invalid request"); performPostprocessing(data); } } } // End if(data.shouldContinue()) } // End if(!data.isProcessed()) } catch(const std::exception& e) { LOG_ERROR("Exception caught" << e.what()); response.setStatus(HttpStatus::INTERNAL_SERVER_ERROR); QJsonObject& json = data.getResponse().getJson(); json["error"] = e.what(); } catch(const QJsonObject& e) { LOG_ERROR("JSON caught" << e); response.setStatus(HttpStatus::INTERNAL_SERVER_ERROR); data.getResponse().getJson() = e; } catch(...) { response.setStatus(HttpStatus::INTERNAL_SERVER_ERROR); QJsonObject& json = data.getResponse().getJson(); json["error"] = QSTR("Internal server error"); } if(!response.isFinished()) { if(!data.getResponse().getJson().isEmpty()) { if(m_SendRequestMetadata) { QJsonObject obj; bool ip4; std::string ip; int port; if(response.getResponse()->getpeername(ip4, ip, port)) { obj["remoteIp"] = ip.c_str(); obj["remotePort"] = port; } obj["query"] = request.getQuery().toString(); obj["uid"] = data.getUid().toString(); obj["timestamp"] = data.getTimestamp().toString("yyyy/MM/dd hh:mm:ss:zzz"); obj["timeElapsed"] = data.getTime().elapsed(); obj["timeElapsedMs"] = (qreal)(uv_hrtime() - request.getTimestamp()) / (qreal)1000000.00; QJsonObject& json = data.getResponse().getJson(); json["requestMetadata"] = obj; } if( !response.finish()) { LOG_WARN("Failed to finish response"); } } } }; }