예제 #1
0
파일: maemo_icd.cpp 프로젝트: RS102839/qt
uint IcdPrivate::statistics(QList<IcdStatisticsResult>& stats_results)
{
    QTimer timer;
    QVariant reply;
    QVariantList vl;
    uint signals_left, total_signals;
    IcdStatisticsResult result;

    clearState();
    reply = mDBus->call(ICD_DBUS_API_STATISTICS_REQ);
    if (reply.type() != QVariant::List)
        return 0;
    vl = reply.toList();
    if (vl.isEmpty())
        return 0;
    reply = vl.first();
    if (reply.type() != QVariant::UInt)
        return 0;
    signals_left = total_signals = reply.toUInt();

    if (!signals_left)
        return 0;

    timer.setSingleShot(true);
    timer.start(timeout);
    stats_results.clear();
    while (signals_left) {
	mInterface.clear();
	while (timer.isActive() && mInterface.isEmpty()) {
	    QCoreApplication::processEvents(QEventLoop::AllEvents, 1000);
	}

	if (!timer.isActive()) {
	    total_signals = 0;
	    break;
	}

	if (mSignal != ICD_DBUS_API_STATISTICS_SIG) {
	    continue;
	}

	if (mError.isEmpty()) {
  	    get_statistics_all_result(mArgs, result);
	    stats_results << result;
	    signals_left--;
	} else {
	    qWarning() << "Error:" << mError;
	    break;
	}
    }
    timer.stop();

    return total_signals;
}
예제 #2
0
파일: debugutil.cpp 프로젝트: RobinWuDev/Qt
bool QQmlDebugTest::waitForSignal(QObject *receiver, const char *member, int timeout) {
    QEventLoop loop;
    QTimer timer;
    timer.setSingleShot(true);
    QObject::connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
    QObject::connect(receiver, member, &loop, SLOT(quit()));
    timer.start(timeout);
    loop.exec();
    if (!timer.isActive())
        qWarning("waitForSignal %s timed out after %d ms", member, timeout);
    return timer.isActive();
}
예제 #3
0
bool Spider::get(NetWorker *instance,QString url){
    QString address1 = "http://192.168.60.131:9200/bcc/_search?q=url:\"";
    QString address2 = "http://192.168.60.132:9200/bcc/_search?q=url:\"";
    QString address3 = "http://192.168.60.133:9200/bcc/_search?q=url:\"";
    QString address4 = "http://192.168.60.134:9200/bcc/_search?q=url:\"";
    //QString url = "http://192.168.60.134:9200/bcc/_search?q=url:\"http://www.lagou.co/jobs/218581.html?source=search\"";
    int count = rand();
    qDebug()<<address1+url+"\"";
    if(count%4==0){
        instance->get(address1+url+"\"");
    }else if(count%4==1){
        instance->get(address2+url+"\"");
    }else if(count%4==2){
        instance->get(address3+url+"\"");
    }else {
        instance->get(address4+url+"\"");
    };
    QEventLoop eventLoop;
    QTimer timer;
    timer.setSingleShot(true);
    QObject::connect(instance, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
    QObject::connect(&timer,SIGNAL(timeout()),&eventLoop,SLOT(quit()));
    timer.start(3000);
    eventLoop.exec();       //block until finish
    if(timer.isActive()){
        timer.stop();
        //return false;
    }
    return instance->flag;
}
예제 #4
0
void Spider::post(const QMap<QString, QVariant> &map,NetWorker *instance){
    QString address1 = "http://192.168.60.131:9200/bcc/1";
    QString address2 = "http://192.168.60.132:9200/bcc/1";
    QString address3 = "http://192.168.60.133:9200/bcc/1";
    QString address4 = "http://192.168.60.134:9200/bcc/1";
    QJsonDocument doc=QJsonDocument::fromVariant(QVariant(map));
    QByteArray j=doc.toJson();
    QString result(j);
    qDebug()<<result;
    int count = rand();
    if(count%4==0){
        instance->post(QUrl(address1),j);
    }else if(count%4==1){
        instance->post(QUrl(address2),j);
    }else if(count%4==2){
        instance->post(QUrl(address3),j);
    }else {
        instance->post(QUrl(address4),j);
    }
    QEventLoop eventLoop;
    QTimer timer;
    timer.setSingleShot(true);
    QObject::connect(instance, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
    QObject::connect(&timer,SIGNAL(timeout()),&eventLoop,SLOT(quit()));
    timer.start(2000);
    eventLoop.exec();       //block until finish
    if(timer.isActive()){
        timer.stop();
    }
}
void StratumClient::stop() {
  QEventLoop waitLoop;
  QTimer disconnectTimer;
  disconnectTimer.setSingleShot(true);
  disconnectTimer.setInterval(RECONNECT_TIMER_INTERVAL);
  connect(m_socket, &QTcpSocket::disconnected, &waitLoop, &QEventLoop::quit);
  connect(&disconnectTimer, &QTimer::timeout, &waitLoop, &QEventLoop::quit);
  m_socket->disconnectFromHost();
  disconnectTimer.start();
  if (m_socket->state() != QTcpSocket::UnconnectedState) {
    waitLoop.exec();
  }

  if (!disconnectTimer.isActive()) {
    m_socket->abort();
    disconnectTimer.stop();
  }

  if (m_reconnectTimerId != -1) {
    killTimer(m_reconnectTimerId);
    m_reconnectTimerId = -1;
  }

  if (m_responseTimerId != -1) {
    killTimer(m_responseTimerId);
    m_responseTimerId = -1;
  }

  m_activeRequestMap.clear();
  m_currentSessionId.clear();
  QWriteLocker lock(&m_jobLock);
  m_currentJob = Job();
}
예제 #6
0
bool QTimerProto::isActive() const
{
  QTimer *item = qscriptvalue_cast<QTimer*>(thisObject());
  if (item)
    return item->isActive();
  return false;
}
예제 #7
0
void ClientBlock::action_forecast_send()
{
    if (client_actions->contains("setforecast")) {
        QNetworkAccessManager* m_manager;
        m_manager = new QNetworkAccessManager(this);
        connect(m_manager, SIGNAL(finished(QNetworkReply*)),
                 this, SLOT(replyFinished(QNetworkReply*)));

        QUrl url = QUrl("http://api.openweathermap.org/data/2.5/weather?q=shebekino&APPID=5437baa043723201a6fb434e5366ec57", QUrl::TolerantMode);
        QNetworkRequest rq=QNetworkRequest(url);
        m_manager->get(rq);

        QTimer timer;
        timer.setSingleShot(true);
        QEventLoop loop;
        connect(m_manager,  SIGNAL(finished(QNetworkReply*)), &loop, SLOT(quit()) );
        connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
        timer.start(5000);
        loop.exec();

        if(timer.isActive()) {
            QTimer::singleShot(1000, &loop, SLOT(quit()));
            loop.exec();
        }

        delete m_manager;
    }
예제 #8
0
bool Utils::sendBlockingNetRequest(const QUrl& theUrl, QString& reply)
{
    QNetworkAccessManager manager;
    QEventLoop q;
    QTimer tT;

    manager.setProxy(M_PREFS->getProxy(QUrl("http://merkaartor.be")));

    tT.setSingleShot(true);
    connect(&tT, SIGNAL(timeout()), &q, SLOT(quit()));
    connect(&manager, SIGNAL(finished(QNetworkReply*)),
            &q, SLOT(quit()));

    QNetworkReply *netReply = manager.get(QNetworkRequest(theUrl));

    tT.start(M_PREFS->getNetworkTimeout());
    q.exec();
    if(tT.isActive()) {
        // download complete
        tT.stop();
    } else {
        return false;
    }

    reply = netReply->readAll();
    return true;
}
예제 #9
0
QFeedbackEffect::State QFeedbackImmersion::updateImmState(const QFeedbackEffect *effect, VibeInt32 effectHandle, VibeInt32 effectState)
{
    // here we detect changes in the state of the effect
    // and make sure any timers are updated
    switch(effectState)
    {
    case VIBE_EFFECT_STATE_PAUSED:
        killTimerForHandle(effectHandle);
        return QFeedbackEffect::Paused;
    case VIBE_EFFECT_STATE_PLAYING: {
        // If the timer existed and is not running, we probably need
        // to reschedule it so the effect state can be up to date
        QTimer *t = effectTimers.value(effectHandle);
        if (t && !t->isActive()) {
            // Well, perhaps the timer fired early.  Trigger it again later
            t->setInterval(50); // XXX arbitrary choice
            t->start();
        }
        return QFeedbackEffect::Running;
    }
    case VIBE_EFFECT_STATE_NOT_PLAYING:
    default:
        killTimerForHandle(effectHandle);
        if (effectHandles.contains(effect)) {
            effectHandles.remove(effect);
            // because we kill the timer before it fires stateChanged, we need to emit stateChanged ourself.
            QMetaObject::invokeMethod(const_cast<QFeedbackEffect*>(effect), "stateChanged");
        }
        return QFeedbackEffect::Stopped;
    }
}
예제 #10
0
void CometClient::postSynchronously(const QString &requestUrlString, const QString &postDataString, int requestIdentifier, int timeoutMilliseconds) {
    QUrl requestUrl(requestUrlString);
    QNetworkRequest request(requestUrl);

    request.setAttribute(QNetworkRequest::User, QVariant(requestIdentifier));
    request.setRawHeader("X-Requested-With", "XMLHttpRequest");
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");

    QByteArray data;
    data.append(postDataString);
    QNetworkReply *reply = nam->post(request, data);
    requestsMade.insert(reply);

    QTimer timer; //the timer handles timeout event
    timer.setSingleShot(true);

    QEventLoop loop;
    QObject::connect(reply, SIGNAL(readyRead()), &loop, SLOT(quit()));
    QObject::connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
    timer.start(timeoutMilliseconds);
    loop.exec(QEventLoop::ExcludeUserInputEvents);
    if(timer.isActive()) {
        timer.stop();
    } else {
        qDebug() << "postSynchronously() timeout occured";
        //reply->abort();
    }
}
예제 #11
0
/**
 * QML wrapper to download an url and returning it as text
 *
 * @param url
 * @return {QString} the content of the downloaded url
 */
QString ScriptingService::downloadUrlToString(QUrl url) {
    QNetworkAccessManager *manager = new QNetworkAccessManager(this);
    QEventLoop loop;
    QTimer timer;

    timer.setSingleShot(true);
    connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
    connect(manager, SIGNAL(finished(QNetworkReply *)), &loop, SLOT(quit()));

    // 10 sec timeout for the request
    timer.start(10000);

    QNetworkRequest networkRequest = QNetworkRequest(url);

#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
    networkRequest.setAttribute(QNetworkRequest::FollowRedirectsAttribute,
                                true);
#endif

    QNetworkReply *reply = manager->get(networkRequest);
    loop.exec();

    // if we didn't get a timeout let us return the content
    if (timer.isActive()) {
        // get the text from the network reply
        QString data = reply->readAll();
        if (data.size() > 0) {
            return data;
        }
    }

    // timer elapsed, no reply from network request or empty data
    return "";
}
예제 #12
0
void PictureFlowAnimator::start(int slide) {
  target = slide;
  if (!animateTimer.isActive() && state) {
    step = (target < state->centerSlide.slideIndex) ? -1 : 1;
    animateTimer.start(30);
  }
}
예제 #13
0
파일: searchbar.cpp 프로젝트: KDE/kdepim
    void triggerTimer()
    {
        if (timer.isActive()) {
            timer.stop();
        }

        timer.start(200);
    }
예제 #14
0
bool InfinityProtocol::doConnect(const Peer& peer)
{
    if ( isConnectedTo(peer) ) {
        return true;
    }

    QEventLoop loop;
    m_connection = QSharedPointer<Kobby::Connection>(new Kobby::Connection(peer.hostname, peer.port, QString(), this));
    m_browserModel = QSharedPointer<QInfinity::BrowserModel>(new QInfinity::BrowserModel( this ));
    m_browserModel->setItemFactory(new Kobby::ItemFactory( this ));
    QObject::connect(m_connection.data(), SIGNAL(ready(Connection*)), &loop, SLOT(quit()));
    QObject::connect(m_connection.data(), SIGNAL(error(Connection*,QString)), &loop, SLOT(quit()));
    m_connection->prepare();

    m_notePlugin = new Kobby::NotePlugin(this);
    m_browserModel->addPlugin(*m_notePlugin);

    QTimer timeout;
    timeout.setSingleShot(true);
    // Give it a bit more time for connecting than usual, our connection method is complicated sometimes
    timeout.setInterval(connectTimeout() * 1000 * 3);
    connect(&timeout, SIGNAL(timeout()), &loop, SLOT(quit()));
    timeout.start();
    loop.exec();
    if ( ! timeout.isActive() || ! m_connection->xmppConnection() ) {
        kDebug() << "failed to look up hostname";
        error(KIO::ERR_UNKNOWN_HOST, peer.hostname);
        return false;
    }
    m_connection->open();
    m_browserModel->addConnection(static_cast<QInfinity::XmlConnection*>(m_connection->xmppConnection()), "kio_root");

    connect(browser(), SIGNAL(connectionEstablished(const QInfinity::Browser*)),
            &loop, SLOT(quit()));
    connect(browser(), SIGNAL(error(const QInfinity::Browser*,QString)),
            &loop, SLOT(quit()));
    loop.exec();
    if ( ! timeout.isActive() || browser()->connectionStatus() != INF_BROWSER_OPEN ) {
        kDebug() << "failed to connect";
        error(KIO::ERR_COULD_NOT_CONNECT, QString("%1:%2").arg(peer.hostname, QString::number(peer.port)));
        return false;
    }

    m_connectedTo = peer;
    return true;
}
예제 #15
0
bool QDeclarativeDebugTest::waitForSignal(QObject *receiver, const char *member, int timeout) {
    QEventLoop loop;
    QTimer timer;
    QObject::connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
    QObject::connect(receiver, member, &loop, SLOT(quit()));
    timer.start(timeout);
    loop.exec();
    return timer.isActive();
}
예제 #16
0
// Core 
bool FilterWebExportVMustPlugin::applyFilter(QAction *filter, MeshDocument &md, RichParameterSet & /*parent*/, vcg::CallBackPos * cb)
{
	if (ID(filter) == FP_WEB_EXPORT)
	{
		CMeshO &m=md.mm()->cm;

		QNetworkAccessManager NAManager;

		// STEP 1: check if the server works (by requesting the list of application templates)
		// (note that this list is not used)
		QUrl urlTest ("http://pipeline.v-must.net/api/v1/bundles");

		QNetworkRequest request1(urlTest);

		QNetworkReply *reply1 = NAManager.get(request1);
		QTimer timer;
		timer.setSingleShot(true);
		timer.start(5000);

		QEventLoop eventLoop;
		connect(reply1, SIGNAL(finished()), &eventLoop, SLOT(quit()));
		connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
		eventLoop.exec();   // block the http request for 5 seconds

		delete reply1;

		if (timer.isActive())
		{
			timer.stop();

			// STEP 2: preparing the bucket for the processing

			QUrl urlBucket("http://pipeline.v-must.net/api/v1/buckets");
			QNetworkRequest request2(urlBucket);
			request2.setRawHeader("Accept", "application/json");
			request2.setRawHeader("Accept-Encoding", "gzip, deflate, compress");
			request2.setRawHeader("Content-Type", "application/octet-stream");
			request2.setRawHeader("Host", "pipelineserver.ltd");
			request2.setRawHeader("X-Filename", "test.ply");

			QNetworkReply *reply2 = NAManager.get(request2);
			connect(reply2, SIGNAL(finished()), &eventLoop, SLOT(quit()));
			eventLoop.exec();   // block the http request

			// STEP 3: launch the processing according to the selected template
		}
		else
		{
			QMessageBox::warning(0, tr("V-Must CIF API"), tr("Server is time out. Please, re-try later."));
		}



	}

	return true;
}
예제 #17
0
void KbManager::fps(int framerate){
    QTimer* timer = eventTimer();
    if(!timer)
        return;
    if(timer->isActive())
        timer->setInterval(1000 / framerate);
    else
        timer->start(1000 / framerate);
}
예제 #18
0
파일: maemo_icd.cpp 프로젝트: RS102839/qt
uint IcdPrivate::state(QString& service_type, uint service_attrs,
		       QString& service_id, QString& network_type,
		       uint network_attrs, QByteArray& network_id,
		       IcdStateResult& state_result)
{
    QTimer timer;
    QVariant reply;
    uint total_signals;
    QVariantList vl;

    clearState();

    reply = mDBus->call(ICD_DBUS_API_STATE_REQ,
			service_type, service_attrs, service_id,
			network_type, network_attrs, network_id);
    if (reply.type() != QVariant::List)
        return 0;
    vl = reply.toList();
    if (vl.isEmpty())
        return 0;
    reply = vl.first();
    total_signals = reply.toUInt();
    if (!total_signals)
        return 0;

    timer.setSingleShot(true);
    timer.start(timeout);

    mInterface.clear();
    while (timer.isActive() && mInterface.isEmpty()) {
        QCoreApplication::processEvents(QEventLoop::AllEvents, 1000);

	if (mSignal != ICD_DBUS_API_STATE_SIG) {
            mInterface.clear();
	    continue;
	}
    }

    timer.stop();

    if (mError.isEmpty()) {
        if (!mArgs.isEmpty()) {
	    if (mArgs.size()>2)
	        get_state_all_result(mArgs, state_result);
	    else {
	        // We are not connected as we did not get the status we asked
	        return 0;
	    }
	}
    } else {
        qWarning() << "Error:" << mError;
    }

    // The returned value should be one because we asked for one state
    return total_signals;
}
bool NetBalanceGetter::get_timeleft(){
	QNetworkReply* reply;

	QTimer timeout;
	QEventLoop waitLoop;
	QObject::connect(&timeout, SIGNAL(timeout()), &waitLoop, SLOT(quit()) );

	timeout.setSingleShot(true);
	timeout.start(timeout_ms);
	reply = manager->get(QNetworkRequest(QUrl("http://cabinet.telecom.mipt.ru/stats/?from=11.05.2012&to=11.05.2013")));
	QObject::connect(reply, SIGNAL(finished()), &waitLoop, SLOT(quit()));
	waitLoop.exec();
	
	if( timeout.isActive() && (reply->error() == QNetworkReply::NoError) ) {
		timeout.stop();

		QString page_body = reply->readAll();
		const QString separator = "<i>";
		QString stat;
		
		int index = 0;
		int pos = page_body.indexOf(separator) + QString(separator).length();
		pos = page_body.indexOf(separator,pos) + QString(separator).length();
		if(pos < 0){
			//emit failed();
			MessageBox(NULL,NULL,NULL,2);
			return false;
		};

		do{
			if( (pos + index) >= page_body.size()){
				emit failed();
				return false;
			}
			stat.append(page_body[pos+index]);
			index++;
		}while(page_body[pos+index] != '<');
		/*stat.append(".");
		stat.append(page_body[pos+index+1]);
		stat.append(page_body[pos+index+2]);
		stat.append(page_body[pos+index+2]);*/
		bool ok = false;
		stat.toDouble(&ok);		
		if(!ok){
			emit failed();
			MessageBox(NULL,stat.toStdWString().data(),NULL,2);
			return false;
		}
		emit new_timeleft(stat.toDouble());
		return true;
	}else
	{
		//emit failed();
		return false;
	}
}
 void waitForEchoMessage(QQuickWorkerScript *worker) {
     QEventLoop loop;
     QVERIFY(connect(worker, SIGNAL(done()), &loop, SLOT(quit())));
     QTimer timer;
     timer.setSingleShot(true);
     connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
     timer.start(10000);
     loop.exec();
     QVERIFY(timer.isActive());
 }
예제 #21
0
void PictureFlowAnimator::start(int slide)
{
  target = slide;
  if(!animateTimer.isActive() && state)
  {
    step = (target < state->centerSlide.slideIndex) ? -1 : 1;
	animateTimer.setSingleShot(true);
    animateTimer.start(30); //TODO comprobar rendimiento, originalmente era 30
	animating = true;
  }
}
예제 #22
0
bool CheckCloudConnection::checkServer()
{
	if (verbose)
		fprintf(stderr, "Checking cloud connection...\n");

	QTimer timer;
	timer.setSingleShot(true);
	QEventLoop loop;
	QNetworkRequest request;
	request.setRawHeader("Accept", "text/plain");
	request.setRawHeader("User-Agent", getUserAgent().toUtf8());
	request.setRawHeader("Client-Id", getUUID().toUtf8());
	request.setUrl(QString(prefs.cloud_base_url) + TEAPOT);
	QNetworkAccessManager *mgr = new QNetworkAccessManager();
	reply = mgr->get(request);
	connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);
	connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
	connect(reply, &QNetworkReply::sslErrors, this, &CheckCloudConnection::sslErrors);
	for (int seconds = 1; seconds <= prefs.cloud_timeout; seconds++) {
		timer.start(1000); // wait the given number of seconds (default 5)
		loop.exec();
		if (timer.isActive()) {
			// didn't time out, did we get the right response?
			timer.stop();
			if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() == HTTP_I_AM_A_TEAPOT &&
			    reply->readAll() == QByteArray(MILK)) {
				reply->deleteLater();
				mgr->deleteLater();
				if (verbose > 1)
					qWarning() << "Cloud storage: successfully checked connection to cloud server";
				git_storage_update_progress(false, "successfully checked cloud connection");
				return true;
			}
		} else if (seconds < prefs.cloud_timeout) {
			QString text = QString("waited %1 sec for cloud connetion").arg(seconds);
			git_storage_update_progress(false, qPrintable(text));
		} else {
			disconnect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
			reply->abort();
		}
	}
	git_storage_update_progress(false, "cloud connection failed");
	prefs.git_local_only = true;
	if (verbose)
		qDebug() << "connection test to cloud server failed" <<
			    reply->error() << reply->errorString() <<
			    reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() <<
			    reply->readAll();
	reply->deleteLater();
	mgr->deleteLater();
	if (verbose)
		qWarning() << "Cloud storage: unable to connect to cloud server";
	return false;
}
예제 #23
0
void TuioReactivisionManualTest::testUpdateFiducial()
{
    qDebug() << "Now please move your fiducial to trigger at least an update event in 20 seconds";
    QEventLoop e;
    QTimer t;
    t.start(20000);
    connect(&t, SIGNAL(timeout()), &e, SLOT(quit()));
    connect(m_outputDevice, SIGNAL(fiducialHasChanged(FiducialObject)), &e, SLOT(quit()));
    e.exec();
    QVERIFY(t.isActive());
    t.stop();
}
예제 #24
0
void TuioReactivisionManualTest::testReleaseFiducial()
{
    qDebug() << "Please remove the fiducial from your client in 20 seconds to complete the test successfully";
    QEventLoop e;
    QTimer t;
    t.start(20000);
    connect(&t, SIGNAL(timeout()), &e, SLOT(quit()));
    connect(m_outputDevice, SIGNAL(fiducialIsOff()), &e, SLOT(quit()));
    e.exec();
    QVERIFY(t.isActive());
    t.stop();
}
예제 #25
0
void TuioReactivisionManualTest::testCatchFiducial()
{
    qDebug() << "Please add the object with ID " << REACTIVISION_OBJECT_ID << "to your reactivision client in 20 seconds.";
    QEventLoop e;
    QTimer t;
    t.start(20000);
    connect(&t, SIGNAL(timeout()), &e, SLOT(quit()));
    connect(m_outputDevice, SIGNAL(fiducialIsOn()), &e, SLOT(quit()));
    e.exec();
    QVERIFY(t.isActive());
    t.stop();
}
bool NetBalanceGetter::get_cabinet_page(){
	QNetworkReply* reply;

	QTimer timeout;
	QEventLoop waitLoop;
	QObject::connect(&timeout, SIGNAL(timeout()), &waitLoop, SLOT(quit()) );

	timeout.setSingleShot(true);
	timeout.start(timeout_ms);
	reply = manager->get(QNetworkRequest(QUrl("http://cabinet.telecom.mipt.ru/")));
	QObject::connect(reply, SIGNAL(finished()), &waitLoop, SLOT(quit()));
	waitLoop.exec();
	
	if( timeout.isActive() && (reply->error() == QNetworkReply::NoError) ) {
		timeout.stop();

		QString page_body = reply->readAll();
		const QString separator = "&nbsp;&mdash;";
		QString balance;
		
		int index = 0;
		int pos = page_body.indexOf(separator) + QString(separator).length();
		if(pos < 0){
			emit failed();
			return false;
		};

		do{
			if( (pos + index) >= page_body.size()){
				emit failed();
				return false;
			}
			if( QString("&nbsp;").indexOf(page_body[pos+index]) < 0 )
				balance.append(page_body[pos+index]);
			index++;
		}while(page_body[pos+index] != '.');
		balance.append(page_body[pos+index]);
		balance.append(page_body[pos+index+1]);
		balance.append(page_body[pos+index+2]);
		bool ok = false;
		balance.toDouble(&ok);		
		if(!ok){
			emit failed();
			return false;
		}
		emit new_balance(balance.toDouble());
		return true;
	}else
	{
		emit failed();
		return false;
	}
}
예제 #27
0
파일: myTimer.cpp 프로젝트: JuarezASF/Code
void myTimer::wait(int  milisecondTime)
{
    QTimer myClock;

    myClock.setInterval(milisecondTime);
    myClock.start();

    while(myClock.isActive())
        {}


    return;
}
예제 #28
0
// http://stackoverflow.com/questions/2629055/qtestlib-qnetworkrequest-not-executed
bool waitForSignal(QObject *sender, const char *signal, int timeout = 1000) {
	QEventLoop loop;
	QTimer timer;
	timer.setInterval(timeout);
	timer.setSingleShot(true);

	loop.connect(sender, signal, SLOT(quit()));
	loop.connect(&timer, SIGNAL(timeout()), SLOT(quit()));
	timer.start();
	loop.exec();

	return timer.isActive();
}
예제 #29
0
void QMLManager::checkCredentialsAndExecute(execute_function_type execute)
{
	// if the cloud credentials are present, we should try to get the GPS Webservice ID
	// and (if we haven't done so) load the dive list
	if (!same_string(prefs.cloud_storage_email, "") &&
	    !same_string(prefs.cloud_storage_password, "")) {
		setAccessingCloud(0);
		setStartPageText(tr("Testing cloud credentials"));
		appendTextToLog("Have credentials, let's see if they are valid");
		CloudStorageAuthenticate *csa = new CloudStorageAuthenticate(this);
		csa->backend(prefs.cloud_storage_email, prefs.cloud_storage_password, cloudPin());
		// let's wait here for the signal to avoid too many more nested functions
		QTimer myTimer;
		myTimer.setSingleShot(true);
		QEventLoop loop;
		connect(csa, &CloudStorageAuthenticate::finishedAuthenticate, &loop, &QEventLoop::quit);
		connect(&myTimer, &QTimer::timeout, &loop, &QEventLoop::quit);
		myTimer.start(5000);
		loop.exec();
		if (!myTimer.isActive()) {
			// got no response from the server
			setStartPageText(RED_FONT + tr("No response from cloud server to validate the credentials") + END_FONT);
			revertToNoCloudIfNeeded();
			return;
		}
		myTimer.stop();
		setCloudPin("");
		if (prefs.cloud_verification_status != CS_VERIFIED) {
			// here we need to enter the PIN
			appendTextToLog(QStringLiteral("Need to verify the email address - enter PIN in desktop app"));
			setStartPageText(RED_FONT + tr("Cannot connect to cloud storage - cloud account not verified") + END_FONT);
			revertToNoCloudIfNeeded();
			setShowPin(true);
			return;
		}
		if (showPin())
			setShowPin(false);

		// now check the redirect URL to make sure everything is set up on the cloud server
		connect(manager(), &QNetworkAccessManager::authenticationRequired, this, &QMLManager::provideAuth, Qt::UniqueConnection);
		QUrl url(CLOUDREDIRECTURL);
		request = QNetworkRequest(url);
		request.setRawHeader("User-Agent", getUserAgent().toUtf8());
		request.setRawHeader("Accept", "text/html");
		reply = manager()->get(request);
		connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(handleError(QNetworkReply::NetworkError)));
		connect(reply, &QNetworkReply::sslErrors, this, &QMLManager::handleSslErrors);
		connect(reply, &QNetworkReply::finished, this, execute, Qt::UniqueConnection);
	}
}
예제 #30
0
void ScriptEngine::timerFired() {
    QTimer* callingTimer = reinterpret_cast<QTimer*>(sender());

    // call the associated JS function, if it exists
    QScriptValue timerFunction = _timerFunctionMap.value(callingTimer);
    if (timerFunction.isValid()) {
        timerFunction.call();
    }

    if (!callingTimer->isActive()) {
        // this timer is done, we can kill it
        delete callingTimer;
    }
}