void ModbusRtu::processPacket() { QMutexLocker lock(&mMutex); quint8 cs = mCurrentSlave; if (mCrc != mCrcBuilder.getValue()) { resetStateEngine(); processPending(); mMutex.unlockInline(); emit errorReceived(CrcError, cs, 0); return; } if ((mFunction & 0x80) != 0) { quint8 errorCode = static_cast<quint8>(mData[0]); resetStateEngine(); processPending(); mMutex.unlockInline(); emit errorReceived(Exception, cs, errorCode); return; } if (mState == Function) { FunctionCode function = mFunction; resetStateEngine(); processPending(); mMutex.unlockInline(); emit errorReceived(Unsupported, cs, function); return; } FunctionCode function = mFunction; switch (function) { case ReadHoldingRegisters: case ReadInputRegisters: { QList<quint16> registers; for (int i=0; i<mData.length(); i+=2) { registers.append(toUInt16(mData, i)); } resetStateEngine(); processPending(); mMutex.unlockInline(); emit readCompleted(function, cs, registers); return; } case WriteSingleRegister: { quint16 value = toUInt16(mData, 0); quint16 startAddress = mStartAddress; resetStateEngine(); processPending(); mMutex.unlockInline(); emit writeCompleted(function, cs, startAddress, value); return; } default: break; } }
LoginWindow::LoginWindow(QWidget * parent, Qt::WindowFlags f):QMainWindow(parent,f) { QWidget *widget = new QWidget(this); m_form.setupUi(widget); setCentralWidget(widget); connect(m_form.m_login, SIGNAL(clicked()), SLOT(okPressed())); connect(&m_query,SIGNAL(responseReceived(QString, QString,QString)),this,SLOT(responseReceived(QString,QString,QString))); connect(&m_query,SLOT(onManagerSslErrors()),&m_query,SIGNAL(errorReceived())); connect(&m_query,SLOT(onReplyError(QNetworkReply::NetworkError)),&m_query,SIGNAL(errorReceived())); connect(&m_query,SIGNAL(errorReceived()),this,SLOT(errorReceived())); }
void Drf1600::processPacket(const QByteArray &dataRead) { Command cmd = mCurrentCommand; resetStateEngine(); switch (cmd) { case GetDeviceType: { int c = toUInt16(dataRead[0], dataRead[2]); switch (c) { case 0x436F: emit deviceTypeRetrieved(ZigbeeCoordinator); break; case 0x5275: emit deviceTypeRetrieved(ZigbeeRouter); break; default: emit errorReceived(Drf1600IncorrectReply); break; } break; } case ReadPanId: emit panIdRead(toUInt16(dataRead[0], dataRead[1])); break; case ReadShortAddress: emit shortAddressRead(toUInt16(dataRead[0], dataRead[1])); break; case SetBaudRate: /// @todo EV Check retrieved data emit baudrateSet(); break; case SetDeviceType: static quint8 MsgCoord[] = { 0x43, 0x6F, 0x6F, 0x72, 0x64, 0x3B, 0x00, 0x19 }; static quint8 MsgRouter[] = { 0x52, 0x6F, 0x75, 0x74, 0x65, 0x3B, 0x00, 0x19 }; if (checkReply(dataRead, MsgCoord, sizeof(MsgCoord)/sizeof(MsgCoord[0])) || checkReply(dataRead, MsgRouter, sizeof(MsgRouter)/sizeof(MsgRouter[0]))) { emit deviceTypeSet(); } else { emit errorReceived(Drf1600IncorrectReply); } break; case TestBaudrate: emit baudrateTested(toUInt16(dataRead[6], dataRead[7])); break; case WritePanId: emit panIdWritten(toUInt16(dataRead[0], dataRead[1])); break; default: break; } }
Smtp::Smtp( const QString &from, const QString &to, const QString &subject, const QString &body ) { socket = new QTcpSocket(this); connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead())); connect(socket, SIGNAL(connected()), this, SLOT(connected())); connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(errorReceived(QAbstractSocket::SocketError))); connect(socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(stateChanged(QAbstractSocket::SocketState))); connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()));; message = "To: " + to + "\n"; message.append("From: " + from + "\n"); message.append("Subject: " + subject + "\n"); message.append(body); message.replace(QString::fromLatin1("\n"), QString::fromLatin1("\r\n")); message.replace(QString::fromLatin1("\r\n.\r\n"), QString::fromLatin1("\r\n..\r\n")); this->from = from; rcpt = to; state = Init; socket->connectToHost("smtp.gmail.com", 587); if(socket->waitForConnected (10000)) { qDebug("connected"); } t = new QTextStream(socket); }
void MessageCarbons::stanzaRequestResult(const Jid &AStreamJid, const Stanza &AStanza) { if (AStanza.type() == "result") { if (FEnableRequests.contains(AStanza.id())) { LogDetaile(QString("[MessageCarbons] Message Carbons enabled for '%1'").arg(AStreamJid.full())); FEnabled[AStreamJid] = true; emit enableChanged(AStreamJid,true); } else if(FDisableRequests.contains(AStanza.id())) { LogDetaile(QString("[MessageCarbons] Message Carbons disabled for '%1'").arg(AStreamJid.full())); FEnabled[AStreamJid] = false; emit enableChanged(AStreamJid,false); } } else { ErrorHandler err(AStanza.element()); LogError(QString("[MessageCarbons] Failed to change Message Carbons state for '%1': %2").arg(AStreamJid.full(),err.message())); emit errorReceived(AStreamJid,err.condition(),err.message()); } FEnableRequests.removeAll(AStanza.id()); FDisableRequests.removeAll(AStanza.id()); }
bool MailSender::send() { _lastError = ""; if (_socket) { delete _socket; } _socket = new QTcpSocket(this); connect(_socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT( errorReceived(QAbstractSocket::SocketError))); _socket->connectToHost(_smtpServer, _port); if (!_socket->waitForConnected(_timeout)) { error("Time out connecting host"); return false; } if (!read("220")) { return false; } if (!sendCommand("EHLO there", "250")) { if (!sendCommand("HELO there", "250")) { return false; } } if (!sendCommand(QString::fromLatin1("MAIL FROM:<") + _from + QString::fromLatin1(">"), "250")) { return false; } QStringList recipients = _to + _cc ; QString strRecipients = ""; for (int i = 0; i < recipients.count(); i++) { strRecipients += recipients.at(i) + ", "; if (!sendCommand(QString::fromLatin1("RCPT TO:<") + recipients.at(i) + QString::fromLatin1(">"), "250")) { qDebug("rcpt error"); return false; } } if (!sendCommand(QString::fromLatin1("DATA"), "354")) { return false; } if (!sendCommand(mailData() + QString::fromLatin1("\r\n."), "250")) { return false; } if (!sendCommand(QString::fromLatin1("QUIT"), "221")) { return false; } _socket->disconnectFromHost(); return true; }
void FbxAPI::requestAuthorizeStatus(int trackId) { QNetworkReply * reply = get(myCreateRequest(QString("login/authorize/%1").arg(trackId))); connect(reply,SIGNAL(finished()),this,SLOT(requestAuthorizeStatusFinished())); connect(reply,SIGNAL(error(QNetworkReply::NetworkError)),this,SLOT(errorReceived(QNetworkReply::NetworkError))); }
void MessageCarbons::stanzaRequestTimeout(const Jid &AStreamJid, const QString &AStanzaId) { FEnableRequests.removeAll(AStanzaId); FDisableRequests.removeAll(AStanzaId); ErrorHandler err(ErrorHandler::REQUEST_TIMEOUT); LogError(QString("[MessageCarbons] Failed to change Message Carbons state for '%1': %2").arg(AStreamJid.full(),err.message())); emit errorReceived(AStreamJid,err.condition(),err.message()); }
void FbxAPI::requestLogin() { qDebug()<<"request Login"; QNetworkReply * reply = get(myCreateRequest("login")); connect(reply,SIGNAL(finished()),this,SLOT(requestLoginFinished())); connect(reply,SIGNAL(error(QNetworkReply::NetworkError)),this,SLOT(errorReceived(QNetworkReply::NetworkError))); }
POP3Client::POP3Client(const QString &email, const QString &password, const QString &host, quint16 port, int timeout) : socket_(new QSslSocket(this)), email_(email), password_(password), host_(host), port_(port), timeout_(timeout), state_(NotConnected) { connect(socket_, SIGNAL(connected()), this, SLOT(connected())); connect(socket_, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(errorReceived(QAbstractSocket::SocketError))); connect(socket_, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(stateChanged(QAbstractSocket::SocketState))); connect(socket_, SIGNAL(disconnected()), this, SLOT(disconnected())); }
void QHelpEngineCorePrivate::init(const QString &collectionFile, QHelpEngineCore *helpEngineCore) { q = helpEngineCore; collectionHandler = new QHelpCollectionHandler(collectionFile, helpEngineCore); connect(collectionHandler, SIGNAL(error(QString)), this, SLOT(errorReceived(QString))); needsSetup = true; }
void ModbusRtu::onTimeout() { QMutexLocker lock(&mMutex); if (mState == Idle || mState == Process) return; quint8 cs = mCurrentSlave; resetStateEngine(); processPending(); mMutex.unlockInline(); emit errorReceived(Timeout, cs, 0); }
// -------------------------------------------------------------------------- QList<QVariantMap> qMidasAPIPrivate::parseResult(const QScriptValue& scriptValue) { Q_Q(qMidasAPI); // e.g. {"stat":"ok","code":"0","message":"","data":[{"p1":"v1","p2":"v2",...}]} QList<QVariantMap> result; QScriptValue stat = scriptValue.property("stat"); if (stat.toString() != "ok") { QString error = QString("Error while parsing outputs:") + " status: " + scriptValue.property("stat").toString() + " code: " + scriptValue.property("code").toInteger() + " msg: " + scriptValue.property("message").toString(); q->emit errorReceived(error); } QScriptValue data = scriptValue.property("data"); if (!data.isObject()) { if (data.toString().isEmpty()) { q->emit errorReceived("No data"); } else { q->emit errorReceived( QString("Bad data: ") + data.toString()); } } if (data.isArray()) { quint32 length = data.property("length").toUInt32(); for(quint32 i = 0; i < length; ++i) { appendScriptValueToVariantMapList(result, data.property(i)); } } else { appendScriptValueToVariantMapList(result, data); } return result; }
// -------------------------------------------------------------------------- void qMidasAPIPrivate::init() { Q_Q(qMidasAPI); this->NetworkManager = new QNetworkAccessManager(q); QObject::connect(this->NetworkManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(processReply(QNetworkReply*))); #if 0 QObject::connect(q, SIGNAL(errorReceived(QString)), this, SLOT(print(QString))); QObject::connect(q, SIGNAL(infoReceived(QString)), this, SLOT(print(QString))); #endif }
// -------------------------------------------------------------------------- QList<QVariantMap> qMidasAPI::synchronousQuery( bool &ok, const QString& midasUrl,const QString& method, const ParametersType& parameters, int maxWaitingTimeInMSecs) { qMidasAPI midasAPI; midasAPI.setMidasUrl(midasUrl); midasAPI.setTimeOut(maxWaitingTimeInMSecs); midasAPI.query(method, parameters); qMidasAPIResult queryResult; QObject::connect(&midasAPI, SIGNAL(resultReceived(QUuid,QList<QVariantMap>)), &queryResult, SLOT(setResult(QUuid,QList<QVariantMap>))); QObject::connect(&midasAPI, SIGNAL(errorReceived(QString)), &queryResult, SLOT(setError(QString))); QEventLoop eventLoop; QObject::connect(&midasAPI, SIGNAL(resultReceived(QUuid,QList<QVariantMap>)), &eventLoop, SLOT(quit())); // Time out will fire an error which will quit the event loop. QObject::connect(&midasAPI, SIGNAL(errorReceived(QString)), &eventLoop, SLOT(quit())); eventLoop.exec(); ok = queryResult.Error.isNull(); if (!ok) { QVariantMap map; map["queryError"] = queryResult.Error; queryResult.Result.push_front(map); } if (queryResult.Result.count() == 0) { // \tbd Q_ASSERT(queryResult.Result.count()); QVariantMap map; map["queryError"] = tr("Unknown error"); queryResult.Result.push_front(map); } return queryResult.Result; }
void ManagerConnection::readError() { QString line, message; while (true) { line = in.readLine(); if (line == "END ERROR") break; message += line + "\n"; } emit errorReceived(message); }
Smtp::Smtp(const QString &serverName, const QString &username, const QString &password, const QString &from, const QStringList &to, const QString &subject, const QString &body) { server = serverName; //your server name user = username; //your SMTP username pass = password; //your SMTP password user = user.toLocal8Bit().toBase64(); pass = pass.toLocal8Bit().toBase64(); x = 1; int recipCount = 0; socket = new QTcpSocket(this); connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead())); connect(socket, SIGNAL(connected()), this, SLOT(connected() ) ); connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(errorReceived(QAbstractSocket::SocketError))); connect(socket, SIGNAL(stateChanged( QAbstractSocket::SocketState)), this, SLOT(stateChanged(QAbstractSocket::SocketState))); connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected())); qDebug() << "Signals created"; for(recipCount = 0; recipCount < to.count(); recipCount++) { message.append("To: " + to.at(recipCount) + "\n"); } message.append("From: " + from + "\n"); message.append("Subject: " + subject + "\n"); message.append("Mime-Version: 1.0;\n"); message.append("Content-Type: text/html; charset=\"utf8\";\n"); message.append("Content-Transfer-Encoding: 8bit;\n"); message.append("\n"); qDebug() << "body is: " << body; message.append(body); message.replace(QString::fromLatin1( "\n" ), QString::fromLatin1( "\r\n")); message.replace(QString::fromLatin1( "\r\n.\r\n" ), QString::fromLatin1( "\r\n..\r\n" ) ); this->from = from; rcpt = to.at(0); recips = to; state = Init; socket->connectToHost(server, 25); if(socket->waitForConnected(30000)) { qDebug("connected"); } t = new QTextStream( socket ); }
void Device::scanServices(const QString &address) { // We need the current device for service discovery. for (int i = 0; i < devices.size(); i++) { if (((DeviceInfo*)devices.at(i))->getAddress() == address ) currentDevice.setDevice(((DeviceInfo*)devices.at(i))->getDevice()); } if (!currentDevice.getDevice().isValid()) { qWarning() << "Not a valid device"; return; } qDeleteAll(m_characteristics); m_characteristics.clear(); emit characteristicsUpdated(); qDeleteAll(m_services); m_services.clear(); emit servicesUpdated(); setUpdate("Back\n(Connecting to device...)"); if (controller && controller->remoteAddress() != currentDevice.getDevice().address()) { controller->disconnectFromDevice(); delete controller; controller = 0; } //! [les-controller-1] if (!controller) { // Connecting signals and slots for connecting to LE services. controller = new QLowEnergyController(currentDevice.getDevice().address()); connect(controller, SIGNAL(connected()), this, SLOT(deviceConnected())); connect(controller, SIGNAL(error(QLowEnergyController::Error)), this, SLOT(errorReceived(QLowEnergyController::Error))); connect(controller, SIGNAL(disconnected()), this, SLOT(deviceDisconnected())); connect(controller, SIGNAL(serviceDiscovered(QBluetoothUuid)), this, SLOT(addLowEnergyService(QBluetoothUuid))); connect(controller, SIGNAL(discoveryFinished()), this, SLOT(serviceScanDone())); } if (isRandomAddress()) controller->setRemoteAddressType(QLowEnergyController::RandomAddress); else controller->setRemoteAddressType(QLowEnergyController::PublicAddress); controller->connectToDevice(); //! [les-controller-1] }
void Session::queryOnError(InboundPkt &inboundPkt, qint64 msgId) { mAsserter.check(inboundPkt.fetchInt() == TL_RpcError); qint32 errorCode = inboundPkt.fetchInt(); QString errorText = inboundPkt.fetchQString(); qCDebug(TG_CORE_SESSION) << "error for query" << QString::number(msgId, 16) << " :" << errorCode << " :" << errorText; Query *q = m_pendingQueries.take(msgId); if (!q) { qCWarning(TG_CORE_SESSION) << "No such query"; } else { q->setAcked(true); Q_EMIT errorReceived(q, errorCode, errorText); } }
void Gateways::stanzaRequestResult(const Jid &AStreamJid, const Stanza &AStanza) { Q_UNUSED(AStreamJid); if (FPromptRequests.contains(AStanza.id())) { if (AStanza.type() == "result") { LOG_STRM_DEBUG(AStreamJid,QString("Legacy user prompt received, id=%1").arg(AStanza.id())); QString desc = AStanza.firstElement("query",NS_JABBER_GATEWAY).firstChildElement("desc").text(); QString prompt = AStanza.firstElement("query",NS_JABBER_GATEWAY).firstChildElement("prompt").text(); emit promptReceived(AStanza.id(),desc,prompt); } else { XmppStanzaError err(AStanza); LOG_STRM_WARNING(AStreamJid,QString("Failed to receive legacy user prompt, id=%1: %2").arg(AStanza.id(),err.condition())); emit errorReceived(AStanza.id(),err); } FPromptRequests.removeAll(AStanza.id()); } else if (FUserJidRequests.contains(AStanza.id())) { if (AStanza.type() == "result") { LOG_STRM_DEBUG(AStreamJid,QString("Legacy user JID received, id=%1").arg(AStanza.id())); Jid userJid = AStanza.firstElement("query",NS_JABBER_GATEWAY).firstChildElement("jid").text(); emit userJidReceived(AStanza.id(),userJid); } else { XmppStanzaError err(AStanza); LOG_STRM_WARNING(AStreamJid,QString("Failed to receive legacy user JID, id=%1: %2").arg(AStanza.id(),err.condition())); emit errorReceived(AStanza.id(),err); } FUserJidRequests.removeAll(AStanza.id()); } }
int MailSender::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QObject::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: errorReceived((*reinterpret_cast< QAbstractSocket::SocketError(*)>(_a[1]))); break; case 1: proxyAuthentication((*reinterpret_cast< const QNetworkProxy(*)>(_a[1])),(*reinterpret_cast< QAuthenticator*(*)>(_a[2]))); break; default: ; } _id -= 2; } return _id; }
void FbxAPI::requestApiInfo() { // doesn't follow API url syntax QNetworkRequest request ; request.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json; charset=utf-8")); request.setUrl(QUrl(QString("http://%1:%2/api_version").arg(mHostName).arg(mPort))); QNetworkReply * reply = get(request); connect(reply,SIGNAL(finished()),this,SLOT(requestApiInfoFinished())); connect(reply,SIGNAL(error(QNetworkReply::NetworkError)),this,SLOT(errorReceived(QNetworkReply::NetworkError))); }
bool Client::connectToServer(const QString &serverName) { if (!m_jsonRpcClient) { m_jsonRpcClient = new JsonRpcClient(this); connect(m_jsonRpcClient, SIGNAL(resultReceived(QJsonObject)), SLOT(processResult(QJsonObject))); connect(m_jsonRpcClient, SIGNAL(notificationReceived(QJsonObject)), SLOT(processNotification(QJsonObject))); connect(m_jsonRpcClient, SIGNAL(errorReceived(QJsonObject)), SLOT(processError(QJsonObject))); connect(m_jsonRpcClient, SIGNAL(connectionStateChanged()), SIGNAL(connectionStateChanged())); } return m_jsonRpcClient->connectToServer(serverName); }
void FbxAPI::requestAuthorize() { QJsonObject json; json.insert("app_id", applicationId()); json.insert("app_name",applicationName()); json.insert("app_version",applicationVersion()); json.insert("device_name", QHostInfo::localHostName()); QNetworkRequest request = myCreateRequest("login/authorize"); QNetworkReply * reply = post(request,QJsonDocument(json).toJson()); connect(reply,SIGNAL(finished()),this,SLOT(requestAuthorizeFinished())); connect(reply,SIGNAL(error(QNetworkReply::NetworkError)),this,SLOT(errorReceived(QNetworkReply::NetworkError))); }
SmtpManager::SmtpManager( const QString &user, const QString &pass, const QString &host, int port, int timeout ) { socket = new QSslSocket(this); connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead())); connect(socket, SIGNAL(connected()), this, SLOT(connected() ) ); connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this,SLOT(errorReceived(QAbstractSocket::SocketError))); connect(socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(stateChanged(QAbstractSocket::SocketState))); connect(socket, SIGNAL(disconnected()), this,SLOT(disconnected())); this->user = user; this->pass = pass; this->host = host; this->port = port; this->timeout = timeout; }
void Client::processError(const QJsonObject &error) { int localId = static_cast<int>(error["id"].toDouble()); int errorCode = -1; QString errorMessage = tr("No message specified."); QJsonValue errorData; const QJsonValue &errorValue = error.value(QLatin1String("error")); if (errorValue.isObject()) { const QJsonObject errorObject = errorValue.toObject(); if (errorObject.value("code").isDouble()) errorCode = static_cast<int>(errorObject.value("code").toDouble()); if (errorObject.value("message").isString()) errorMessage = errorObject.value("message").toString(); if (errorObject.contains("data")) errorData = errorObject.value("data"); } emit errorReceived(localId, errorCode, errorMessage, errorData); }
// -------------------------------------------------------------------------- void qMidasAPIPrivate::processReply(QNetworkReply* reply) { Q_Q(qMidasAPI); QUuid uuid(reply->property("uuid").toString()); if (reply->error() != QNetworkReply::NoError) { q->emit errorReceived(uuid.toString() + ": " + reply->error() + ": " + reply->errorString()); } QScriptValue scriptResult = this->ScriptEngine.evaluate("(" + QString(reply->readAll()) + ")"); q->emit infoReceived(QString("Parse results for ") + uuid); QList<QVariantMap> result = this->parseResult(scriptResult); q->emit infoReceived(QString("Results for ") + uuid.toString() + ": " + q->qVariantMapListToString(result)); q->emit resultReceived(uuid, result); reply->close(); reply->deleteLater(); }
void FbxAPI::requestSession() { QJsonObject json; json.insert("app_id", mApplicationId); json.insert("app_version",mApiInfo.version); json.insert("password",hmacSha1(mApplicationToken.toUtf8(), mChallenge.toUtf8())); QJsonDocument doc(json); QNetworkReply * reply = post(myCreateRequest("login/session"), doc.toJson()); connect(reply,SIGNAL(finished()),this,SLOT(requestSessionFinished())); connect(reply,SIGNAL(error(QNetworkReply::NetworkError)),this,SLOT(errorReceived(QNetworkReply::NetworkError))); qDebug()<<"app Id " <<mApplicationId; qDebug()<<"challenge "<<mChallenge; qDebug()<<reply->url(); qDebug()<<doc.toJson(); }
//---------------------------------------------------------------------// void BmErrorManager::pushError( BmError* anError ) { mErrors.push_back( anError ); emit errorReceived(); }
// -------------------------------------------------------------------------- int qMidasAPITest(int argc, char* argv[]) { QCoreApplication app(argc, argv); bool ok = false; QList<QVariantMap> result; // -------------------------------------------------------------------------- // Check that query associated with local file release file handle // -------------------------------------------------------------------------- QDir tmp = QDir::temp(); QString temporaryDirName = QString("qMidasAPITest1-queryFile.%1").arg(QTime::currentTime().toString("hhmmsszzz")); tmp.mkdir(temporaryDirName); tmp.cd(temporaryDirName); tmp.mkdir("api"); tmp.cd("api"); QFile fileReply(tmp.filePath("json")); if (!fileReply.open(QFile::WriteOnly)) { std::cerr << "Line " << __LINE__ << " - Failed to create temporary file." << qPrintable(tmp.filePath("json")) << std::endl; return EXIT_FAILURE; } fileReply.write( QString("{\"stat\":\"ok\",\"code\":\"0\",\"message\":\"\",\"data\":{" "\"quote\":\"If a day goes past and you do not learn anything, it is a waste of a day.\"," "\"author\" : \"Mike Horn\"}}").toLatin1()); fileReply.close(); ok = false; result = qMidasAPI::synchronousQuery(ok, QUrl::fromLocalFile(QDir::temp().filePath(temporaryDirName)).toString(), "midas.quote.of.the.day"); std::cout << "result: " << qPrintable(qMidasAPI::qVariantMapListToString(result)) << std::endl; if (!ok || result.size() == 0) { std::cout << "Failed to query 'midas.quote.of.the.day'." << std::endl; return EXIT_FAILURE; } // Attempt to delete 'queryFile' if (!QFile::remove(tmp.filePath("json"))) { std::cout << "Failed to remove queryFile. [" << qPrintable(tmp.filePath("json")) << "]" << std::endl; return EXIT_FAILURE; } // -------------------------------------------------------------------------- QString midasUrl("http://slicer.kitware.com/midas3"); qMidasAPI midasAPI; midasAPI.setMidasUrl(midasUrl); if (midasAPI.midasUrl() != midasUrl) { std::cout << "Failed to set Midas Url" << std::endl; return EXIT_FAILURE; } // -------------------------------------------------------------------------- // Successfull query: midas.version // -------------------------------------------------------------------------- QSignalSpy errorSpy(&midasAPI, SIGNAL(errorReceived(QUuid,QString))); QSignalSpy receivedSpy(&midasAPI, SIGNAL(resultReceived(QUuid,QList<QVariantMap>))); QUuid queryUuid = midasAPI.get("midas.version"); // Give 5 seconds for the server to answer wait(5000); if (queryUuid.isNull() || errorSpy.count() > 0|| receivedSpy.count() != 1) { std::cerr << "Failed to query 'midas.version': " << errorSpy.count() << " errors," << receivedSpy.count() << " results." << std::endl; return EXIT_FAILURE; } errorSpy.clear(); receivedSpy.clear(); // -------------------------------------------------------------------------- // Fail query: midas.notafunction // -------------------------------------------------------------------------- queryUuid = midasAPI.get("midas.notafunction"); // Give 5 seconds for the server to answer wait(5000); /// Even if errors are received, an empty result is sent if (queryUuid.isNull() || errorSpy.count() == 0 || receivedSpy.count() != 1) { std::cerr << "Failed to query 'midas.notafunction': " << errorSpy.count() << " errors," << receivedSpy.count() << " results." << std::endl; return EXIT_FAILURE; } // -------------------------------------------------------------------------- // Synchronous query: midas.info // -------------------------------------------------------------------------- ok = false; result = qMidasAPI::synchronousQuery(ok, midasUrl, "midas.info"); std::cout << "result: " << qPrintable(qMidasAPI::qVariantMapListToString(result))<< std::endl; if (!ok || result.size() == 0) { std::cout << "Failed to query 'midas.info'." << std::endl; return EXIT_FAILURE; } // -------------------------------------------------------------------------- // Synchronous fail query: midas.notafunction // -------------------------------------------------------------------------- result= qMidasAPI::synchronousQuery(ok, midasUrl,"midas.notafunction"); std::cout << "result: " << qPrintable(qMidasAPI::qVariantMapListToString(result))<< std::endl; if (ok || result.size() != 1 || result.at(0)["queryError"].isNull()) { std::cout << "Failed to query 'midas.info'." << result.size() << " results." << std::endl; return EXIT_FAILURE; } // -------------------------------------------------------------------------- // Synchronous fail query: midas.login (wrong credentials) // -------------------------------------------------------------------------- qMidasAPI::ParametersType wrongParameters; wrongParameters["appname"] = "qMidasAPITest"; wrongParameters["email"] = "*****@*****.**"; wrongParameters["apikey"] = "123456789"; result= qMidasAPI::synchronousQuery(ok, midasUrl,"midas.login", wrongParameters); std::cout << "result: " << qPrintable(qMidasAPI::qVariantMapListToString(result))<< std::endl; if (ok || result.size() != 1 || result.at(0)["queryError"].isNull()) { std::cout << "Failed to query 'midas.login'." << result.size() << " results." << std::endl; return EXIT_FAILURE; } // -------------------------------------------------------------------------- // Synchronous query: midas.community.list (return array of data) // -------------------------------------------------------------------------- result= qMidasAPI::synchronousQuery(ok, midasUrl,"midas.community.list"); std::cout << "result: " << qPrintable(qMidasAPI::qVariantMapListToString(result))<< std::endl; if (!ok || result.size() == 0) { std::cout << "Failed to query 'midas.community.list'." << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }