Esempio n. 1
1
bool Dropbox::createFolder(QString path)
{
    // do we have a token
    QString token = appsettings->cvalue(context->athlete->cyclist, GC_DROPBOX_TOKEN, "").toString();
    if (token == "") return false;

    // lets connect and get basic info on the root directory
    QString url("https://api.dropboxapi.com/1/fileops/create_folder?root=auto&path=" + path);

    // request using the bearer token
    QNetworkRequest request(url);
    request.setRawHeader("Authorization", (QString("Bearer %1").arg(token)).toLatin1());
    QNetworkReply *reply = nam->get(request);

    // blocking request
    QEventLoop loop;
    connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
    loop.exec();

    // 403 EXISTS, otherwise OK
    return (reply->error() == QNetworkReply::NoError);
}
Esempio n. 2
0
void
StravaDialog::requestSearchRide()
{
    progressBar->setValue(0);
    progressLabel->setText(tr("Searching corresponding Ride"));

    QEventLoop eventLoop;
    QNetworkAccessManager networkMgr;

    connect(&networkMgr, SIGNAL(finished(QNetworkReply*)), this, SLOT(requestSearchRideFinished(QNetworkReply*)));
    connect(&networkMgr, SIGNAL(finished(QNetworkReply *)), &eventLoop, SLOT(quit()));
    QByteArray out;


    QUrl url = QUrl(STRAVA_URL1 + "rides?athleteId="+athleteId+"&startDate="+ride->ride()->startTime().toString("yyyy-MM-dd")+"&endDate="+ride->ride()->startTime().addDays(1).toString("yyyy-MM-dd"));

    QNetworkRequest request = QNetworkRequest(url);
    //request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    networkMgr.get(request);
    eventLoop.exec();
}
Esempio n. 3
0
QImage QgsAmsProvider::getLegendGraphic( double /*scale*/, bool forceRefresh, const QgsRectangle * /*visibleExtent*/ )
{
  if ( mLegendFetcher->haveImage() && !forceRefresh )
  {
    return mLegendFetcher->getImage();
  }
  QEventLoop evLoop;
  connect( mLegendFetcher, &QgsImageFetcher::finish, &evLoop, &QEventLoop::quit );
  connect( mLegendFetcher, &QgsImageFetcher::error, &evLoop, &QEventLoop::quit );
  mLegendFetcher->start();
  evLoop.exec( QEventLoop::ExcludeUserInputEvents );
  if ( !mLegendFetcher->errorTitle().isEmpty() )
  {
    mErrorTitle = mLegendFetcher->errorTitle();
    mError = mLegendFetcher->errorMessage();
    return QImage();
  }
  else
  {
    return mLegendFetcher->getImage();
  }
}
Esempio n. 4
0
void paintSelection()
{
#if 0
    SoAnnotation* hudRoot = new SoAnnotation;
    hudRoot->ref();

    SoOrthographicCamera* hudCam = new SoOrthographicCamera();
    hudCam->viewportMapping = SoCamera::LEAVE_ALONE;
    // Set the position in the window.
    // [0, 0] is in the center of the screen.
    //
    SoTranslation* hudTrans = new SoTranslation;
    hudTrans->translation.setValue(-1.0f, -1.0f, 0.0f);

    QImage image(100,100,QImage::Format_ARGB32_Premultiplied);
    image.fill(0x00000000);
    SoSFImage sfimage;
    Gui::BitmapFactory().convert(image, sfimage);
    SoImage* hudImage = new SoImage();
    hudImage->image = sfimage;

    // Assemble the parts...
    //
    hudRoot->addChild(hudCam);
    hudRoot->addChild(hudTrans);
    hudRoot->addChild(hudImage);

    Gui::View3DInventorViewer* viewer = this->getViewer();
    static_cast<SoGroup*>(viewer->getSceneGraph())->addChild(hudRoot);

    QWidget* gl = viewer->getGLWidget();
    DrawingPlane pln(hudImage->image, viewer, gl);
    gl->installEventFilter(&pln);
    QEventLoop loop;
    QObject::connect(&pln, SIGNAL(emitSelection()), &loop, SLOT(quit()));
    loop.exec();
    static_cast<SoGroup*>(viewer->getSceneGraph())->removeChild(hudRoot);
#endif
}
Esempio n. 5
0
static int doSyncGet(const QString &rootUrl, QByteArray &result)
{
    QNetworkRequest url;
    url.setUrl(rootUrl);

    QScopedPointer<QNetworkAccessManager> connection(new QNetworkAccessManager);
    QScopedPointer<QNetworkReply> reply(connection->get(url));

    qDebug() << "doSyncGet" << rootUrl;
    QEventLoop waitLoop;
    QObject::connect(reply.data(), SIGNAL(finished()), &waitLoop, SLOT(quit()));
    waitLoop.exec();

    int errorCode = reply->error();
    if (errorCode != 0) {
        qWarning() << "get" << url.url() << reply->errorString();
        return errorCode;
    }
    result = reply->readAll();

    return errorCode;
}
Esempio n. 6
0
QVariant parseAPI::search(const QVariant& keyword)
{
    QEventLoop eventLoop;
    QObject::connect(&network, SIGNAL(finished(QNetworkReply* )), &eventLoop, SLOT(quit()));
    qDebug()<<"开始循环事件";
    QNetworkRequest request(QUrl(QString("http://music.163.com/api/search/get/")));
    request.setRawHeader("Referer", "http://music.163.com");
    request.setRawHeader("Cookie", "appver=2.0.2");
    request.setRawHeader("Content-type","application/x-www-form-urlencoded");

    QByteArray parameter;
    parameter.append("s="+keyword.toByteArray());
    parameter.append("&offset=0&limit=24&type=1");

    QNetworkReply* reply=network.post(request, parameter);
    eventLoop.exec();
    if(reply->error() == QNetworkReply::NoError){
        QByteArray json=reply->readAll();
        return QVariant(json);
    }
    return QVariant("");
}
Esempio n. 7
0
// Shutdown the application server
bool shutdownServer(QUrl url)
{
    QNetworkAccessManager manager;
    QEventLoop loop;
    QNetworkReply *reply;
    QVariant redirectUrl;

    url.setPath("/misc/shutdown");

    do
    {
        reply = manager.get(QNetworkRequest(url));

        QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
        loop.exec();

        redirectUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
        url = redirectUrl.toUrl();

        if (!redirectUrl.isNull())
            delete reply;

    } while (!redirectUrl.isNull());

    if (reply->error() != QNetworkReply::NoError)
    {
        return false;
    }

    QString response = reply->readAll();

    if (response != "SHUTDOWN")
    {
        qDebug() << "Failed to connect, server response: " << response;
        return false;
    }

    return true;
}
bool ServerConfigurationDialog::testHttpConnection(ServerConfiguration const& configuration)
{
   bool okay(false);

   try {
      QString hostAddress(configuration.value(ServerConfiguration::HostAddress));
      int port(configuration.port());

      Network::HttpConnection http(hostAddress, port);
      http.open();

      Network::Reply* reply(http.get("index.html"));

      QEventLoop loop;
      QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
      loop.exec();

      okay = reply->status() == Network::Reply::Finished;
      if (okay) {
         QLOG_DEBUG() << "----------------------------";
         QLOG_DEBUG() << reply->message();
         QLOG_DEBUG() << "----------------------------";
      }else {
         QString msg("Connection failed:\n");
         msg += reply->message();
         QMsgBox::warning(this, "IQmol", msg);
      }
      delete reply;

   }catch (Network::AuthenticationError& err) {
      QMsgBox::warning(this, "IQmol", "Invalid username or password");

   }catch (Exception& err) {
      QMsgBox::warning(this, "IQmol", err.what());
   }

   return okay;
}
Esempio n. 9
0
// Delete an image, identified by delete_hash
int ShareOnline::Imgur::deleteImage(QString hash) {

    // Set up the network request
    QNetworkRequest request(QUrl(QString("https://api.imgur.com/3/image/%1").arg(hash)));
    request.setRawHeader("Authorization", QByteArray("Bearer ") + access_token.toLatin1());

    // Send the deletion request
    QNetworkReply *reply = networkManager->deleteResource(request);
    ReplyTimeout::set(reply, 2500);

    // Wait for it to finish
    QEventLoop loop;
    QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
    loop.exec();

    // Get return value
    QString ret = reply->readAll();

    // Success!
    if(ret.contains("\"success\":true"))
        return IMGUR_NOERROR;

    // Error...
    if(ret.contains("\"success\":false")) {
        if(ret.contains("\"error\":\"")) {
            if(debug) {
                QString err = ret.split("\"error\":\"").at(1).split("\"").at(0);
                LOG << CURDATE << "Deletion error: " << err.toStdString() << NL;
            }
            return IMGUR_DELETION_ERROR;
        } else
            return IMGUR_OTHER_ERROR;
    }

    // Not sure what happened
    return IMGUR_OTHER_ERROR;

}
Esempio n. 10
0
QString cloaksend::getCloakedAddress()
{
    socket = new httpsocket(this); //create socket with

    //Add proxy support to socket as neccesary.
    if(this->useProxy==true){
        socket->useProxy = true;
        socket->proxyAddress = this->proxyAddress;
        socket->proxyPort = this->proxyPort;
    }

    QString url = "http://www.cloaksend.com/api/cloaks/";
    url.append(this->fromAddress);// Ex. "CBnkPKapz8U2FKc7EQSeCcSZ3qPD82XpGp");
    url.append("/");
    url.append(this->destinationAddress);//Ex. "C5qKmSjW1K1CiADtnMHMPBjQWybHQ9S8ce");
    url.append("/");
    url.append(this->amount);//Ex. "50.0");

    socket->getUrl(url);

    //Our custom socket will emit the signal finished when its got the data it needs.
    QEventLoop loop;
    QObject::connect(socket, SIGNAL(finished()), &loop, SLOT(quit()));

    loop.exec();//start the loop until socket is done.

    //qDebug()<<"HTML Response="<<socket->response;

    if(socket->response=="Error"){
        qDebug()<<"Error Occured:"<<socket->error;
        return "Error";
    }

    //Clean Output
    socket->response.replace(QString("\""),QString(""));//replace occurences of " with nothing.

    return socket->response;
}
Esempio n. 11
0
void						MainWindows::getHomePageTriggered()
{
	QNetworkRequest			newRequest(QUrl(BOX_BASE_URL_HTTPS));
	QEventLoop				eventLoop;
	QString					replyText;
	QNetworkReply *			reply = nullptr;


	newRequest.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
	newRequest.setSslConfiguration(*this->_sslConfig);


	reply = this->_networkManager->get(newRequest);

	QObject::connect(reply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);
	eventLoop.exec();

	if (reply->error() != QNetworkReply::NoError)
	{
		qDebug() << "Network Error:" << reply->errorString();
		return;
	}

	replyText = reply->readAll();

	if (replyText.isNull() || replyText.isEmpty())
	{
		qDebug() << "Answer for" << BOX_BASE_URL_HTTPS << "was empty or null";
		this->_ui.statusBar->setStatusTip(QString("Answer for ").append(BOX_BASE_URL_HTTPS).append(" was empty or null"));
		return;
	}

	replyText.truncate(replyText.lastIndexOf(XML_META_CRSF_TOKEN_END));
	replyText = replyText.remove(0, sizeof(XML_META_CRSF_TOKEN_BEGIN) + replyText.lastIndexOf(XML_META_CRSF_TOKEN_BEGIN));

	this->_ui.crsfToken->setText(replyText);
	this->_autToken = replyText;
}
Esempio n. 12
0
bool QgsWFSRequest::sendPOST( const QUrl& url, const QString& contentTypeHeader, const QByteArray& data )
{
  abort(); // cancel previous
  mIsAborted = false;

  mErrorMessage.clear();
  mErrorCode = QgsWFSRequest::NoError;
  mForceRefresh = true;
  mResponse.clear();

  if ( url.toEncoded().contains( "fake_qgis_http_endpoint" ) )
  {
    // Hack for testing purposes
    QUrl modifiedUrl( url );
    modifiedUrl.addQueryItem( "POSTDATA", QString::fromUtf8( data ) );
    return sendGET( modifiedUrl, true, true, false );
  }

  QNetworkRequest request( url );
  if ( !mUri.auth().setAuthorization( request ) )
  {
    mErrorCode = QgsWFSRequest::NetworkError;
    mErrorMessage = errorMessageFailedAuth();
    QgsMessageLog::logMessage( mErrorMessage, tr( "WFS" ) );
    return false;
  }
  request.setHeader( QNetworkRequest::ContentTypeHeader, contentTypeHeader );

  mReply = QgsNetworkAccessManager::instance()->post( request, data );
  connect( mReply, SIGNAL( finished() ), this, SLOT( replyFinished() ) );
  connect( mReply, SIGNAL( downloadProgress( qint64, qint64 ) ), this, SLOT( replyProgress( qint64, qint64 ) ) );

  QEventLoop loop;
  connect( this, SIGNAL( downloadFinished() ), &loop, SLOT( quit() ) );
  loop.exec( QEventLoop::ExcludeUserInputEvents );

  return mErrorMessage.isEmpty();
}
Esempio n. 13
0
// Read client id and secret from server
int ShareOnline::Imgur::obtainClientIdSecret() {

    // If we have done it already, no need to do it again
    if(imgurClientID != "" && imgurClientSecret != "")
        return IMGUR_NOERROR;

    // Request text file from server
    QNetworkRequest req(QUrl("https://photoqt.org/oauth2/imgur.php"));
    req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    QNetworkReply *reply =  networkManager->get(req);
    ReplyTimeout::set(reply, 2500);

    // Synchronous connect
    QEventLoop loop;
    connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
    loop.exec();

    // Read reply data
    QString dat = reply->readAll();
    reply->deleteLater();

    // If response invalid
    if(dat.trimmed() == "")
        return IMGUR_NOT_CONNECTED_TO_INET;
    else if(!dat.contains("client_id=") || !dat.contains("client_secret=")) {
        if(debug)
            LOG << CURDATE << "Network reply data: " << dat.toStdString() << NL;
        return IMGUR_NETWORK_REPLY_ERROR;
    }

    // Split client id and secret out of reply data
    imgurClientID = dat.split("client_id=").at(1).split("\n").at(0).trimmed();
    imgurClientSecret = dat.split("client_secret=").at(1).split("\n").at(0).trimmed();

    // success
    return IMGUR_NOERROR;

}
Esempio n. 14
0
/**
 *  Gets access tokens for user entered pin number
 *  @param pin entered pin number
 */
void OAuthTwitter::requestAccessToken(const QString& pin)
{
    Q_ASSERT(m_netManager != 0);

    QUrl url(TWITTER_ACCESS_TOKEN_URL);
	QUrlQuery query;
    query.addQueryItem("oauth_verifier", pin.toLatin1().toPercentEncoding());
	url.setQuery(query);

    QByteArray oauthHeader = generateAuthorizationHeader(url, OAuth::POST);

    QEventLoop q;
    QTimer t;
    t.setSingleShot(true);

    connect(&t, SIGNAL(timeout()), &q, SLOT(quit()));

    QNetworkRequest req(url);
    req.setRawHeader(AUTH_HEADER, oauthHeader);
    req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");

    QNetworkReply *reply = m_netManager->post(req, QByteArray());
    connect(reply, SIGNAL(finished()), &q, SLOT(quit()));
    connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(error()));

    t.start(5000);
    q.exec();

    if(t.isActive()){
        QByteArray response = reply->readAll();
        parseTokens(response);
        reply->deleteLater();

        emit authorizePinFinished();
    } else {
        qDebug() << "Timeout";
    }
}
Esempio n. 15
0
void Server::start() {
  QString sockPath = "/tmp/qeventloop_test";
  QLocalServer* server = new QLocalServer();
  QFile sockFile(sockPath);
  if (sockFile.exists()) {
    sockFile.remove();
  }
  server->listen(sockPath);
  QObject::connect(server, &QLocalServer::newConnection, [this, server]() {
    m_sock = server->nextPendingConnection();
    QObject::connect(m_sock, &QLocalSocket::disconnected, m_sock, &QLocalSocket::deleteLater);
    QObject::connect(m_sock, &QLocalSocket::readyRead, this, &Server::onReadyRead,
                     Qt::QueuedConnection);

    sendData(m_sock, 1);

    QEventLoop loop;
    QObject::connect(&m_result1, &Result::ready, &loop, &QEventLoop::quit);
    qDebug("start event loop to wait for 1");
    loop.exec();
    qDebug("end event loop to wait for 1");
  });
}
Esempio n. 16
0
bool join::validator(QString str)
{
QByteArray arr;
arr.append("$check$"+str+"$");
socket->write(arr);
socket->flush();
socket->waitForBytesWritten();
qDebug()<<"wrote";
QEventLoop loop;
connect(socket,SIGNAL(readyRead()),&loop,SLOT(quit()));
loop.exec();

qDebug()<<"pahunch gaya";
QByteArray a=socket->readAll();
	QString lol(a);

	if(lol=="$nonvalidated$")	
		{qDebug()<<false;return false;}
	if(lol=="$validated$")
		{qDebug()<<true;return true;}
qDebug()<<false;
return false;
}	
Esempio n. 17
0
/**
 * @brief 通过HTTP GET发送URL,因为QNetWorkAccessManager默认不CACHE,所以不必设置
 **/
QByteArray WebUtils::getByUrl(const QUrl &url)
{
  QNetworkReply *reply = qnam.get(QNetworkRequest(url));
  QEventLoop loop;
  connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
  loop.exec();

  QVariant redirectionTarget = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);

  // WARNING: taobao only have once redirect url
  if (reply->error()) {
    qDebug() << reply->errorString();
    return "";
  } else if (!redirectionTarget.isNull()) {
    QUrl newUrl = url.resolved(redirectionTarget.toUrl());
    reply->deleteLater();
    return getByUrl(newUrl);
  }

  QByteArray returnStr = reply->readAll();
  reply->deleteLater();
  return returnStr;
}
Esempio n. 18
0
void MainWindow::chooseVideo()
{
    QString filename = QFileDialog::getOpenFileName(this,
                       tr("Choose Video"), QDesktopServices::storageLocation(
                           QDesktopServices::MoviesLocation), getFileFormats());
    if (filename.isEmpty())
        return;

    stop();
    playOrPauseAction->setEnabled(false);
    stopAction->setEnabled(false);
    mediaObject->setCurrentSource(filename);
    if (!mediaObject->hasVideo()) {
        QEventLoop eventLoop;
        QTimer timer;
        timer.setSingleShot(true);
        timer.setInterval(3 * OneSecond);
        connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
        connect(mediaObject, SIGNAL(hasVideoChanged(bool)),
                &eventLoop, SLOT(quit()));
        timer.start();
        eventLoop.exec();
    }
Esempio n. 19
0
//To connect to the server and post data(username, Password) and file
void ClientHttp::ConnectServer()
{
    m_oNetworkManager = new QNetworkAccessManager(this);
    QUrl m_oUrl(m_sUrlServer);

    QString bound="margin";
    QByteArray m_bDataToSend(QString("--" + bound + "\r\n").toUtf8());

    m_bDataToSend.append("--" + bound + "--\r\n");

    QNetworkRequest m_oRequest = QNetworkRequest(m_oUrl);
    m_oRequest.setRawHeader("User", m_sUserName.toUtf8());
    m_oRequest.setRawHeader("Password", m_sUserPassword.toUtf8());
    m_oRequest.setRawHeader(QString("Content-Type").toUtf8(),QString("multipart/form-data; boundary=" + bound).toUtf8());
    m_oRequest.setRawHeader(QString("Content-Lenght").toUtf8(), QString::number(m_bDataToSend.length()).toUtf8());

    QEventLoop loop;
    m_oReply = m_oNetworkManager->post(m_oRequest, m_bDataToSend);
    connect(m_oNetworkManager, SIGNAL(finished(QNetworkReply*)), &loop, SLOT(quit()));
    loop.exec();

    DataRetrieve(m_oReply);
}
void OsmNominatimRunner::reverseGeocoding( const GeoDataCoordinates &coordinates )
{
    m_coordinates = coordinates;
    QString base = "http://nominatim.openstreetmap.org/reverse?format=xml&addressdetails=1";
    // @todo: Alternative URI with addressdetails=1 could be used for shorther placemark name
    QString query = "&lon=%1&lat=%2&accept-language=%3";
    double lon = coordinates.longitude( GeoDataCoordinates::Degree );
    double lat = coordinates.latitude( GeoDataCoordinates::Degree );
    QString url = QString( base + query ).arg( lon ).arg( lat ).arg( MarbleLocale::languageCode() );

    m_request.setUrl(QUrl(url));
    m_request.setRawHeader("User-Agent", TinyWebBrowser::userAgent("Browser", "OsmNominatimRunner") );

    QEventLoop eventLoop;

    connect( this, SIGNAL( reverseGeocodingFinished( GeoDataCoordinates, GeoDataPlacemark ) ),
             &eventLoop, SLOT( quit() ) );

    // @todo FIXME Must currently be done in the main thread, see bug 257376
    QTimer::singleShot( 0, this, SLOT( startReverseGeocoding() ) );

    eventLoop.exec();
}
void Worker::doMethod2()
{
    qDebug()<<"Starting Method2 in Thread "<<thread()->currentThreadId();

    for (int i = 0; i < 20; i ++) {

        mutex.lock();
        bool abort = _abort;
        bool interrupt = _interrupt;
        mutex.unlock();

        if (abort || interrupt) {
            qDebug()<<"Interrupting Method2 in Thread "<<thread()->currentThreadId();
            break;
        }

        QEventLoop loop;
        QTimer::singleShot(1000, &loop, SLOT(quit()));
        loop.exec();

        emit valueChanged(QString::number(i));
    }
}
Esempio n. 22
0
void Debugger::finish()
{
    QMutexLocker locker( m_mutex );
    if ( hasRunningJobs() ) {
        m_weaver->finish();
        qApp->processEvents();
    }
    while ( hasRunningJobs() ) {
        const QPointer< DebuggerJob > job = currentJob();
        Q_ASSERT( job );
        job->finish();

        if ( job && m_runningJobs.contains(job) ) {
            QEventLoop loop;
            connect( job, SIGNAL(destroyed(QObject*)), &loop, SLOT(quit()) );
            loop.exec();

            if ( m_runningJobs.contains(job) ) {
                kDebug() << "Manually remove done job";
                m_runningJobs.remove( m_runningJobs.indexOf(job) );
            }
        }
    }
Esempio n. 23
0
void ProgressDialog::enterEventLoop( KJob* pJob, const QString& jobInfo )
{
   m_pJob = pJob;
   m_currentJobInfo = jobInfo;
   m_pSlowJobInfo->setText( m_currentJobInfo );
   if ( m_progressDelayTimer )
      killTimer( m_progressDelayTimer );
   m_progressDelayTimer = startTimer( 3000 ); /* 3 s delay */

   // immediately show the progess dialog for KIO jobs, because some KIO jobs require password authentication,
   // but if the progress dialog pops up at a later moment, this might cover the login dialog and hide it from the user.
   if( m_pJob && !m_bStayHidden )
      show();

   // instead of using exec() the eventloop is entered and exited often without hiding/showing the window.
   //qt_enter_modal(this);
   QEventLoop* pEventLoop = new QEventLoop(this);
   m_eventLoopStack.push_back( pEventLoop );
   pEventLoop->exec(); // this function only returns after ProgressDialog::exitEventLoop() is called.
   delete pEventLoop;
   m_eventLoopStack.pop_back();
   //qt_leave_modal(this);
}
Esempio n. 24
0
void Communicator::requestData(QString url, bool& isOk, QString& result) {
    QEventLoop eventLoop;
    QNetworkAccessManager mgr;
    QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));

    // the HTTP request
    QNetworkRequest req;
    req.setUrl(host_+url);
    req.setRawHeader( "User-Agent" , "Mozilla Firefox" );

    QNetworkReply *reply = mgr.get(req);
    eventLoop.exec(); // blocks stack until "finished()" has been called

    if (reply->error() == QNetworkReply::NoError) {
        // Everything is ok => reply->readAll()
        result =  (QString) reply->readAll();
        isOk = true;
    } else {
        result =  reply->errorString();
        isOk = false;
    }
    delete reply;
}
Esempio n. 25
0
void MainWindow::whois(QString ip)
{
    QEventLoop loop;

    QNetworkRequest req( QUrl( QString("http://api.hackertarget.com/whois/?q="+ip) ) );

    QNetworkAccessManager manager;
    connect(&manager, SIGNAL(finished(QNetworkReply*)), &loop, SLOT(quit()));

    QNetworkReply *resposta = manager.get(req);
    loop.exec();

    if (resposta->error() == QNetworkReply::NoError) {
        //qDebug() << "leitura" <<resposta->readAll();
        ui->textEdit_3->setPlainText(resposta->readAll());
        delete resposta;
    }
    else {
        QMessageBox::critical(this,"Error",resposta->errorString());
        delete resposta;
    }

}
bool CWizDocumentEditStatusSyncThread::sendDoneMessage(const QString& strUserAlias, const QString& strObjID)
{
    QString strUrl = WizFormatString5(_T("%1/delete?obj_id=%2&user_id=%3&t=%4&token=%5"),
                                      WizKMGetDocumentEditStatusURL(),
                                      strObjID,
                                      strUserAlias,
                                      ::WizIntToStr(GetTickCount()),
                                      WizService::Token::token());

    if (!m_netManager)
    {
        m_netManager = new QNetworkAccessManager();
    }
    QNetworkReply* reply = m_netManager->get(QNetworkRequest(strUrl));
//    qDebug() << "sendDoneMessage called " <<strUrl;
    qDebug() << "[EditStatus]:Send done status : " << strObjID;

    QEventLoop loop;
    connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
    loop.exec();

    return reply->error() == QNetworkReply::NoError;
}
Esempio n. 27
0
bool SessionServer::waitForNewConnection( int msec, bool * timedOut ) {
	QEventLoop wait;
	QTimer timer;
	timer.setSingleShot( true );
	timer.setInterval( msec );
	wait.connect( &timer, SIGNAL( timeout() ), SLOT( quit() ) );
	wait.connect( this, SIGNAL( newConnection() ), SLOT( quit() ) );
	wait.exec();
	if( !timer.isActive() ) {
		// timer timeout
		if( timedOut != nullptr ) {
			*timedOut = true;
		}
		return false;
	} else {
		// new connections
		if( timedOut != nullptr ) {
			*timedOut = false;
		}
		timer.stop();
		return true;
	}
}
Esempio n. 28
0
/**
 * @brief send - send a packet
 * @param[in] num device to transmit to (zero based)
 * @param[in] buf buffer containing packet to send
 * @param[in] len number of bytes to transmit
 * @param[in] timeout = time to wait, in milliseconds
 * @returns number of bytes sent, or -1 on error
 */
int pjrc_rawhid::send(int, void *buf, int len, int timeout)
{
    // This lock ensures that when closing we don't do it until the
    // write has terminated (and then the device_open flag is set to false)
    QMutexLocker locker(m_writeMutex);
    Q_UNUSED(locker);

    if(!device_open || unplugged) {
        return -1;
    }

    uint8_t *report_buf = (uint8_t *) malloc(len);
    memcpy(&report_buf[0], buf,len);

    QEventLoop el;
    Sender sender(dev, report_buf, len);
    connect(&sender, SIGNAL(finished()), &el, SLOT(quit()));
    sender.start();
    QTimer::singleShot(timeout, &el, SLOT(quit()));
    el.exec();

    return sender.result;
}
Esempio n. 29
0
// This is invoked as BlockingQueuedConnection from QNetworkAccessHttpBackend in the user thread
void QHttpThreadDelegate::startRequestSynchronously()
{
#ifdef QHTTPTHREADDELEGATE_DEBUG
    qDebug() << "QHttpThreadDelegate::startRequestSynchronously() thread=" << QThread::currentThreadId();
#endif
    synchronous = true;

    QEventLoop synchronousRequestLoop;
    this->synchronousRequestLoop = &synchronousRequestLoop;

    // Worst case timeout
    QTimer::singleShot(30*1000, this, SLOT(abortRequest()));

    QMetaObject::invokeMethod(this, "startRequest", Qt::QueuedConnection);
    synchronousRequestLoop.exec();

    connections.localData()->releaseEntry(cacheKey);
    connections.setLocalData(0);

#ifdef QHTTPTHREADDELEGATE_DEBUG
    qDebug() << "QHttpThreadDelegate::startRequestSynchronously() thread=" << QThread::currentThreadId() << "finished";
#endif
}
Esempio n. 30
0
void QtWebKitWebPage::javaScriptAlert(QWebFrame *frame, const QString &message)
{
	if (m_ignoreJavaScriptPopups)
	{
		return;
	}

	if (m_webWidget)
	{
		QMessageBox dialog;
		dialog.setModal(false);
		dialog.setWindowTitle(tr("JavaScript"));
		dialog.setText(message.toHtmlEscaped());
		dialog.setStandardButtons(QMessageBox::Ok);
		dialog.setCheckBox(new QCheckBox(tr("Disable JavaScript popups")));

		QEventLoop eventLoop;

		m_webWidget->showDialog(&dialog);

		connect(&dialog, SIGNAL(finished(int)), &eventLoop, SLOT(quit()));
		connect(this, SIGNAL(destroyed()), &eventLoop, SLOT(quit()));

		eventLoop.exec();

		m_webWidget->hideDialog(&dialog);

		if (dialog.checkBox()->isChecked())
		{
			m_ignoreJavaScriptPopups = true;
		}

		return;
	}

	QWebPage::javaScriptAlert(frame, message);
}