void BaseConnection::onTransportPacketReceived(const QByteArray &payload) { qCDebug(c_baseConnectionCategory) << CALL_INFO << payload.size(); if (payload.size() == ConnectionError::packetSize()) { const ConnectionError e(payload.constData()); qCDebug(c_baseConnectionCategory) << "Error:" << e.description(); if (status() == Status::Failed) { // We still can get replies to already sent message even if the connection // is already failed, but it makes no sense to shout them out. return; } emit errorOccured(payload); setStatus(Status::Failed, StatusReason::Remote); return; } if (payload.size() < 8) { qCWarning(c_baseConnectionCategory) << CALL_INFO << "Received package is too small to process:" << payload.toHex(); return; } const quint64 *authKeyIdBytes = reinterpret_cast<const quint64*>(payload.constData()); if (*authKeyIdBytes) { if (!processAuthKey(*authKeyIdBytes)) { qCDebug(c_baseConnectionCategory) << CALL_INFO << "Received incorrect auth id."; return; } if (!m_rpcLayer->processPackage(payload)) { qCDebug(c_baseConnectionCategory) << CALL_INFO << "Unable to process RPC packet:" << payload.toHex(); } } else { if (!m_dhLayer->processPlainPackage(payload)) { qCDebug(c_baseConnectionCategory) << CALL_INFO << "Unable to process plain packet:" << payload.toHex(); } } }
void TrackingService::startTracking(QString name, QString password, QString authToken, QString serverUrl) { qDebug() << "startTracking url: " << serverUrl; m_period = m_settings.getTrackingPeriod() * 60; if (m_writeTagQuery != 0) m_writeTagQuery->deleteLater(); m_writeTagQuery = new WriteTagQuery(this); m_writeTagQuery->setTag(m_dataMark); connect(m_writeTagQuery, SIGNAL(tagAdded()), this, SLOT(onMarkSent())); connect(m_writeTagQuery, SIGNAL(errorOccured(QString)), this, SLOT(onError(QString))); m_user = QSharedPointer<JsonUser>(new JsonUser(name, password, authToken)); m_channel = QSharedPointer<Channel>(new Channel(name, name + "'s channel", "")); m_dataMark->setUser(m_user); m_dataMark->setChannel(m_channel); m_writeTagQuery->setUrl(serverUrl); sendMark(); }
void SM_QDropbox::parseSharedLink(QString response) { #ifdef SM_QTDROPBOX_DEBUG qDebug() << "== shared link ==" << response << "== shared link end =="; #endif //SM_Dropbox_Json json; //json.parseString(response); _tempJson.parseString(response); if(!_tempJson.isValid()) { errorState = SM_QDropbox::APIError; errorText = "Dropbox API did not send correct answer for file/directory shared link."; #ifdef SM_QTDROPBOX_DEBUG qDebug() << "error: " << errorText << endl; #endif emit errorOccured(errorState); stopEventLoop(); return; } emit sharedLinkReceived(response); }
void Parser131500ComAu::getJourneyDetails(const QString &id) { if (currentRequestState != FahrplanNS::noneRequest) { return; } //Some hafasxml backend provide the detailsdata inline //if so our parser already stored them if (lastJourneyResultList->itemcount() > 0 ) { for (int i = 0; i < lastJourneyResultList->itemcount(); i++) { JourneyResultItem *item = lastJourneyResultList->getItem(i); if (item->id() == id) { emit journeyDetailsResult(parseDetails(item)); return; } } } emit errorOccured(tr("Internal error occured: JourneyResultdata not present!")); return; }
void mdtTcpSocketThread::writeToSocket() { char *bufferCursor; qint64 toWrite; qint64 written; // Check if we have something to transmit if(pvWriteCurrentFrame == 0){ pvWriteCurrentFrame = getNewFrameWrite(); if(pvWriteCurrentFrame != 0){ // New frame to transmit bufferCursor = pvWriteCurrentFrame->data(); toWrite = pvWriteCurrentFrame->size(); } } if(pvWriteCurrentFrame != 0){ // Write data to port written = pvPort->write(bufferCursor, toWrite); if(written < 0){ emit(errorOccured(MDT_TCP_IO_ERROR)); written = 0; // Sleep a bit to prevent crazy ressources consumtion msleep(100); } pvWriteCurrentFrame->take(written); // Check if current frame was completly sent if(pvWriteCurrentFrame->isEmpty()){ pvPort->writeFramesPool().enqueue(pvWriteCurrentFrame); ///emit frameWritten(); pvWriteCurrentFrame = 0; }else{ bufferCursor = pvWriteCurrentFrame->data(); Q_ASSERT(bufferCursor < (pvWriteCurrentFrame->data() + pvWriteCurrentFrame->size())); toWrite -= written; Q_ASSERT(toWrite >= 0); } } }
void SM_QDropbox::parseAccountInfo(QString response) { #ifdef SM_QTDROPBOX_DEBUG qDebug() << "== account info ==" << response << "== account info end =="; #endif SM_Dropbox_Json json; json.parseString(response); _tempJson.parseString(response); if(!json.isValid()) { errorState = SM_QDropbox::APIError; errorText = "Dropbox API did not send correct answer for account information."; #ifdef SM_QTDROPBOX_DEBUG qDebug() << "error: " << errorText << endl; #endif emit errorOccured(errorState); return; } emit accountInfoReceived(response); return; }
void ParserHafasXml::searchJourneyEarlier() { if (hafasContext.seqNr.isEmpty()) { emit errorOccured(tr("Internal error occured, going earlier is not possible")); return; } if (currentRequestState != FahrplanNS::noneRequest) { return; } currentRequestState = FahrplanNS::searchJourneyEarlierRequest; QByteArray postData = ""; postData.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?><ReqC accessId=\"" + hafasHeader.accessid + "\" ver=\"" + hafasHeader.ver + "\" prod=\"" + hafasHeader.prod + "\" lang=\"EN\">"); postData.append("<ConScrReq scrDir=\"B\" nrCons=\"5\">"); postData.append("<ConResCtxt>"); postData.append(hafasContext.seqNr); postData.append("</ConResCtxt>"); postData.append("</ConScrReq>"); postData.append("</ReqC>"); sendHttpRequest(QUrl(baseXmlUrl), postData); }
void DownloadItem::startDownloadingFromFtp(const QUrl &url) { if (!m_outputFile.isOpen() && !m_outputFile.open(QIODevice::WriteOnly)) { stop(false); ui->downloadInfo->setText(tr("Error: Cannot write to file!")); return; } m_ftpDownloader = new FtpDownloader(this); connect(m_ftpDownloader, SIGNAL(finished()), this, SLOT(finished())); connect(m_ftpDownloader, SIGNAL(dataTransferProgress(qint64,qint64)), this, SLOT(downloadProgress(qint64,qint64))); connect(m_ftpDownloader, SIGNAL(errorOccured(QFtp::Error)), this, SLOT(error())); connect(m_ftpDownloader, SIGNAL(ftpAuthenticationRequierd(QUrl,QAuthenticator*)), mApp->networkManager(), SLOT(ftpAuthentication(QUrl,QAuthenticator*))); m_ftpDownloader->download(url, &m_outputFile); m_downloading = true; m_timer.start(1000, this); QTimer::singleShot(200, this, SLOT(updateDownload())); if (m_ftpDownloader->error() != QFtp::NoError) { error(); } }
TourCaptureDialog::TourCaptureDialog(MarbleWidget *widget, QWidget *parent) : QDialog(parent), ui(new Ui::TourCaptureDialog), m_recorder(new MovieCapture(widget, parent)), m_playback(0), m_writingPossible( true ), m_current_position( 0.0 ) { ui->setupUi(this); m_recorder->setSnapshotMethod(MovieCapture::DataDriven); ui->progressBar->setValue(0); connect(ui->fpsSlider, SIGNAL(valueChanged(int)), ui->fpsSpin, SLOT(setValue(int))); connect(ui->fpsSpin, SIGNAL(valueChanged(int)), ui->fpsSlider, SLOT(setValue(int))); connect(ui->fpsSlider, SIGNAL(valueChanged(int)), m_recorder, SLOT(setFps(int))); connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(close())); connect(ui->startButton, SIGNAL(clicked()), this, SLOT(startRecording())); connect(ui->openButton, SIGNAL(clicked()), this, SLOT(loadDestinationFile())); connect(m_recorder, SIGNAL(rateCalculated(double)), this, SLOT(setRate(double))) ; connect(m_recorder, SIGNAL(errorOccured()), this, SLOT(handleError()) ); }
void SM_QDropbox::parseDelta(QString response) { #ifdef SM_QTDROPBOX_DEBUG qDebug() << "== metadata ==" << response << "== metadata end =="; #endif SM_Dropbox_Json json; json.parseString(response); _tempJson.parseString(response); if(!json.isValid()) { errorState = SM_QDropbox::APIError; errorText = "Dropbox API did not send correct answer for delta."; #ifdef SM_QTDROPBOX_DEBUG qDebug() << "error: " << errorText << endl; #endif emit errorOccured(errorState); stopEventLoop(); return; } emit deltaReceived(response); return; }
void ParserHafasBinary::parseSearchJourney(QNetworkReply *networkReply) { lastJourneyResultList = new JourneyResultList(); journeyDetailInlineData.clear(); QByteArray tmpBuffer = networkReply->readAll(); QByteArray buffer = gzipDecompress(tmpBuffer); /* QFile file("f://out.txt"); file.open(QIODevice::WriteOnly); file.write(buffer); file.close(); */ QDataStream hafasData(buffer); hafasData.setByteOrder(QDataStream::LittleEndian); qint16 hafasVersion; hafasData >> hafasVersion; if (hafasVersion != 5 && hafasVersion != 6) { qWarning()<<"Wrong version of hafas binary data"; emit errorOccured(tr("An error ocurred with the backend")); return; } qDebug()<<"Binary-Data Version: "<<hafasVersion; //Basic data offsets qint32 serviceDaysTablePtr; qint32 stringTablePtr; qint32 stationTablePtr; qint32 commentTablePtr; qint32 extensionHeaderPtr; qint32 extensionHeaderLength; qint16 errorCode; hafasData.device()->seek(0x20); hafasData >> serviceDaysTablePtr; hafasData >> stringTablePtr; hafasData.device()->seek(0x36); hafasData >> stationTablePtr; hafasData >> commentTablePtr; hafasData.device()->seek(0x46); hafasData >> extensionHeaderPtr; hafasData.device()->seek(extensionHeaderPtr); hafasData >> extensionHeaderLength; hafasData.device()->seek(extensionHeaderPtr + 16); hafasData >> errorCode; //Debug data offsets qDebug()<<serviceDaysTablePtr<<stringTablePtr; qDebug()<<stationTablePtr<<commentTablePtr; qDebug()<<extensionHeaderPtr<<extensionHeaderLength; qDebug()<<errorCode; //Read strings hafasData.device()->seek(stringTablePtr); QMap<int, QString> strings; QString tmpString; for (int num = 0; num < (serviceDaysTablePtr - stringTablePtr); num++) { qint8 c; hafasData>>c; if (c == 0) { strings.insert((num - tmpString.length()), tmpString.trimmed()); tmpString.clear(); } else { tmpString.append((char)c); } } //Looks ok, parsing if (errorCode == 0) { hafasData.device()->seek(extensionHeaderPtr + 0x8); qint16 seqNr; qint16 requestIdPtr; qint16 encodingPtr; qint32 connectionDetailsPtr; qint32 attrsOffset; qint16 ldPtr; hafasData >> seqNr; hafasData >> requestIdPtr; hafasData >> connectionDetailsPtr; hafasData.device()->seek(hafasData.device()->pos() + 16); hafasData >> encodingPtr; hafasData >> ldPtr; hafasData >> attrsOffset; QString encoding = strings[encodingPtr]; QString requestId = strings[requestIdPtr]; QString ld = strings[ldPtr]; qint32 connectionAttrsPtr; if (extensionHeaderLength >= 0x30) { if (extensionHeaderLength < 0x32) { qWarning()<<"too short: " + extensionHeaderLength; return; } hafasData.device()->seek(extensionHeaderPtr + 0x2c); hafasData >> connectionAttrsPtr; } else {
void SM_QDropbox::requestFinished(int nr, QNetworkReply *rply) { rply->deleteLater(); #ifdef SM_QTDROPBOX_DEBUG int resp_bytes = rply->bytesAvailable(); #endif QByteArray buff = rply->readAll(); QString response = QString(buff); #ifdef SM_QTDROPBOX_DEBUG qDebug() << "request " << nr << "finished." << endl; qDebug() << "request was: " << rply->url().toString() << endl; #endif #ifdef SM_QTDROPBOX_DEBUG qDebug() << "response: " << resp_bytes << "bytes" << endl; qDebug() << "status code: " << rply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toString() << endl; qDebug() << "== begin response ==" << endl << response << endl << "== end response ==" << endl; qDebug() << "req#" << nr << " is of type " << requestMap[nr].type << endl; #endif // drop box error handling based on return codes switch(rply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt()) { case SM_DROPBOX_ERROR_BAD_INPUT: errorState = SM_QDropbox::BadInput; errorText = ""; emit errorOccured(errorState); checkReleaseEventLoop(nr); return; break; case SM_DROPBOX_ERROR_EXPIRED_TOKEN: errorState = SM_QDropbox::TokenExpired; errorText = ""; emit tokenExpired(); checkReleaseEventLoop(nr); return; break; case SM_DROPBOX_ERROR_BAD_OAUTH_REQUEST: errorState = SM_QDropbox::BadOAuthRequest; errorText = ""; emit errorOccured(errorState); checkReleaseEventLoop(nr); return; break; case SM_DROPBOX_ERROR_FILE_NOT_FOUND: emit fileNotFound(); checkReleaseEventLoop(nr); return; break; case SM_DROPBOX_ERROR_WRONG_METHOD: errorState = SM_QDropbox::WrongHttpMethod; errorText = ""; emit errorOccured(errorState); checkReleaseEventLoop(nr); return; break; case SM_DROPBOX_ERROR_REQUEST_CAP: errorState = SM_QDropbox::MaxRequestsExceeded; errorText = ""; emit errorOccured(errorState); checkReleaseEventLoop(nr); return; break; case SM_DROPBOX_ERROR_USER_OVER_QUOTA: errorState = SM_QDropbox::UserOverQuota; errorText = ""; emit errorOccured(errorState); checkReleaseEventLoop(nr); return; break; default: break; } if(rply->error() != QNetworkReply::NoError) { errorState = SM_QDropbox::CommunicationError; errorText = QString("%1 - %2").arg(rply->error()).arg(rply->errorString()); #ifdef SM_QTDROPBOX_DEBUG qDebug() << "error " << errorState << "(" << errorText << ") in request" << endl; #endif emit errorOccured(errorState); checkReleaseEventLoop(nr); return; } // ignore connection requests if(requestMap[nr].type == SM_DROPBOX_REQ_CONNECT) { #ifdef SM_QTDROPBOX_DEBUG qDebug() << "- answer to connection request ignored" << endl; #endif removeRequestFromMap(nr); return; } bool delayed_finish = false; int delayed_nr; if(rply->attribute(QNetworkRequest::HttpStatusCodeAttribute) == 302) { #ifdef SM_QTDROPBOX_DEBUG qDebug() << "redirection received" << endl; #endif // redirection handling QUrl newlocation(rply->header(QNetworkRequest::LocationHeader).toString(), QUrl::StrictMode); #ifdef SM_QTDROPBOX_DEBUG qDebug() << "new url: " << newlocation.toString() << endl; #endif int oldnr = nr; nr = sendRequest(newlocation, requestMap[nr].method, 0, requestMap[nr].host); requestMap[nr].type = SM_DROPBOX_REQ_REDIREC; requestMap[nr].linked = oldnr; return; } else { if(requestMap[nr].type == SM_DROPBOX_REQ_REDIREC) { // change values if this is the answert to a redirect SM_DROPBOX_request redir = requestMap[nr]; SM_DROPBOX_request orig = requestMap[redir.linked]; requestMap[nr] = orig; removeRequestFromMap(nr); nr = redir.linked; } // standard handling depending on message type switch(requestMap[nr].type) { case SM_DROPBOX_REQ_CONNECT: // was only a connect request - so drop it break; case SM_DROPBOX_REQ_RQTOKEN: // requested a tiken responseTokenRequest(response); break; case SM_DROPBOX_REQ_RQBTOKN: responseBlockedTokenRequest(response); break; case SM_DROPBOX_REQ_AULOGIN: delayed_nr = responseDropboxLogin(response, nr); delayed_finish = true; break; case SM_DROPBOX_REQ_ACCTOKN: responseAccessToken(response); break; case SM_DROPBOX_REQ_METADAT: parseMetadata(response); break; case SM_DROPBOX_REQ_BMETADA: parseBlockingMetadata(response); break; case SM_DROPBOX_REQ_BACCTOK: responseBlockingAccessToken(response); break; case SM_DROPBOX_REQ_ACCINFO: parseAccountInfo(response); break; case SM_DROPBOX_REQ_BACCINF: parseBlockingAccountInfo(response); break; case SM_DROPBOX_REQ_SHRDLNK: parseSharedLink(response); break; case SM_DROPBOX_REQ_BSHRDLN: parseBlockingSharedLink(response); break; case SM_DROPBOX_REQ_REVISIO: parseRevisions(response); break; case SM_DROPBOX_REQ_BREVISI: parseBlockingRevisions(response); break; case SM_DROPBOX_REQ_DELTA: parseDelta(response); break; case SM_DROPBOX_REQ_BDELTA: parseBlockingDelta(response); break; default: errorState = SM_QDropbox::ResponseToUnknownRequest; errorText = "Received a response to an unknown request"; emit errorOccured(errorState); break; } } if(delayed_finish) delayMap[delayed_nr] = nr; else { if(delayMap[nr]) { int drq = delayMap[nr]; while(drq!=0) { emit operationFinished(delayMap[drq]); delayMap.remove(drq); drq = delayMap[drq]; } } removeRequestFromMap(nr); emit operationFinished(nr); } return; }
void ParserHafasXml::parseTimeTableMode1(QNetworkReply *networkReply) { TimetableEntriesList result; QString data = QString::fromLatin1(networkReply->readAll()); //Add a root element, because its sometimes missing if (data.indexOf("StationTable") == -1) { data.prepend("<StationTable>"); data.append("</StationTable>"); } QXmlStreamReader xml; xml.addData(data); while (!xml.atEnd()) { xml.readNext(); if (xml.isStartElement() && (xml.name() == "Err")) { QString errorMsg = xml.attributes().value("text").toString().simplified(); emit errorOccured(tr("Backend returns an error: ") + errorMsg); qWarning()<<"ParserHafasXml::parseTimeTableMode1: "<<errorMsg; } if (xml.isStartElement() && (xml.name() == "Journey")) { TimetableEntry item; QString dest = xml.attributes().value("dir").toString().simplified(); QString station = xml.attributes().value("depStation").toString().simplified(); QString train = xml.attributes().value("hafasname").toString().simplified(); if (dest.isEmpty()) { dest = xml.attributes().value("targetLoc").toString().simplified(); } if (train.isEmpty()) { train = xml.attributes().value("prod").toString().simplified(); if (train.indexOf("#")) { train = train.left(train.indexOf("#")); } } //get delay infos, QString txtDelay = xml.attributes().value("delay").toString().simplified(); //QString intDelay = xml.attributes().value("e_delay").toString().simplified(); QString reasonDelay = xml.attributes().value("delayReason").toString().simplified(); QString miscInfo = ""; if (!txtDelay.isEmpty()) { if (txtDelay == "-") { miscInfo = ""; } else if (txtDelay == "0") { miscInfo = tr("On-Time"); } else { miscInfo = txtDelay; } } if (!reasonDelay.isEmpty()) { if (!miscInfo.isEmpty()) { miscInfo.append(": "); } miscInfo.append(reasonDelay); } item.currentStation = station; item.destinationStation = dest; item.trainType = train; item.platform = xml.attributes().value("platform").toString().simplified(); item.time = QTime::fromString(xml.attributes().value("fpTime").toString(), "hh:mm"); item.miscInfo = miscInfo; result << item; } } emit timetableResult(result); }
JourneyDetailResultList* ParserHafasXml::internalParseJourneyDetails(QByteArray data) { qDebug() << ";;;;;;;;;;;;;;;" << data; JourneyDetailResultList *results = new JourneyDetailResultList(); QBuffer readBuffer; readBuffer.setData(data); readBuffer.open(QIODevice::ReadOnly); QXmlQuery query; query.bindVariable("path", &readBuffer); query.setQuery("doc($path)/ResC/Err//@text/string()"); QStringList errorResult; if (!query.evaluateTo(&errorResult)) { qDebug() << "parserHafasXml::ErrorTest - Query Failed"; return results; } if (errorResult.count() > 0 ) { emit errorOccured(errorResult.join("").trimmed()); qWarning()<<"ParserHafasXml::internalParseJourneyDetails:"<<errorResult.join(""); return results; } query.setQuery("doc($path)/ResC/ConRes//Connection[@id='" + journeyDetailRequestData.id + "']/ConSectionList/ConSection/Departure/BasicStop/Station/@name/string()"); QStringList departureResults; if (!query.evaluateTo(&departureResults)) { qDebug() << "parserHafasXml::parseJourneyDataDetails - Query 1 Failed"; } query.setQuery("doc($path)/ResC/ConRes//Connection[@id='" + journeyDetailRequestData.id + "']/ConSectionList/ConSection/Arrival/BasicStop/Station/@name/string()"); QStringList arrivalResults; if (!query.evaluateTo(&arrivalResults)) { qDebug() << "parserHafasXml::parseJourneyDataDetails - Query 2 Failed"; } query.setQuery("doc($path)/ResC/ConRes//Connection[@id='" + journeyDetailRequestData.id + "']/ConSectionList/ConSection/Departure/BasicStop/Location/Station/HafasName/Text/string()"); QStringList departure2Results; if (!query.evaluateTo(&departure2Results)) { qDebug() << "parserHafasXml::parseJourneyDataDetails - Query 1b Failed"; } query.setQuery("doc($path)/ResC/ConRes//Connection[@id='" + journeyDetailRequestData.id + "']/ConSectionList/ConSection/Arrival/BasicStop/Location/Station/HafasName/Text/string()"); QStringList arrival2Results; if (!query.evaluateTo(&arrival2Results)) { qDebug() << "parserHafasXml::parseJourneyDataDetails - Query 2b Failed"; } query.setQuery("doc($path)/ResC/ConRes//Connection[@id='" + journeyDetailRequestData.id + "']/ConSectionList/ConSection/Departure/BasicStop/Dep/Time/string()"); QStringList depTimeResult; if (!query.evaluateTo(&depTimeResult)) { qDebug() << "parserHafasXml::parseJourneyDataDetails - Query 3 Failed"; } query.setQuery("doc($path)/ResC/ConRes//Connection[@id='" + journeyDetailRequestData.id + "']/ConSectionList/ConSection/Departure/BasicStop/Dep/Platform/Text/string()"); QStringList depPlatResult; if (!query.evaluateTo(&depPlatResult)) { qDebug() << "parserHafasXml::parseJourneyDataDetails - Query 4 Failed"; } query.setQuery("doc($path)/ResC/ConRes//Connection[@id='" + journeyDetailRequestData.id + "']/ConSectionList/ConSection/Arrival/BasicStop/Arr/Time/string()"); QStringList arrTimeResult; if (!query.evaluateTo(&arrTimeResult)) { qDebug() << "parserHafasXml::parseJourneyDataDetails - Query 5 Failed"; } query.setQuery("doc($path)/ResC/ConRes//Connection[@id='" + journeyDetailRequestData.id + "']/ConSectionList/ConSection/Arrival/BasicStop/Arr/Platform/Text/string()"); QStringList arrPlatResult; if (!query.evaluateTo(&arrPlatResult)) { qDebug() << "parserHafasXml::parseJourneyDataDetails - Query 6 Failed"; } //It is possible, that the stationname is in two seperate fields if (departureResults.count() == 0 && departure2Results.count() > 0) { departureResults = departure2Results; arrivalResults = arrival2Results; } if (departureResults.count() == arrivalResults.count()) { for(int i = 0; i < departureResults.count(); i++) { JourneyDetailResultItem *item = new JourneyDetailResultItem(); /* qDebug()<<" "<<"Journey "<<i; qDebug()<<" DepartureSt:"<<departureResults[i].trimmed(); qDebug()<<" DepartureTime:"<<depTimeResult[i].trimmed(); qDebug()<<" DeparturePlatform:"<<depPlatResult[i].trimmed(); qDebug()<<" ArrivalSt:"<<arrivalResults[i].trimmed(); qDebug()<<" ArrivalTime:"<<arrTimeResult[i].trimmed(); qDebug()<<" ArrivalPlatform:"<<arrPlatResult[i].trimmed(); */ item->setDepartureDateTime(cleanHafasDateTime(depTimeResult[i].trimmed(), journeyDetailRequestData.date)); item->setArrivalDateTime(cleanHafasDateTime(arrTimeResult[i].trimmed(), journeyDetailRequestData.date)); item->setDepartureStation(departureResults[i].trimmed()); item->setArrivalStation(arrivalResults[i].trimmed()); if (depPlatResult[i].trimmed() != "") { item->setDepartureInfo(tr("Pl.") + " " + depPlatResult[i].trimmed()); } if (arrPlatResult[i].trimmed() != "") { item->setArrivalInfo(tr("Pl.") + " " + arrPlatResult[i].trimmed()); } //Check for train or if walking query.setQuery("doc($path)/ResC/ConRes//Connection[@id='" + journeyDetailRequestData.id + "']/ConSectionList/ConSection[" + QString::number(i + 1) + "]/Journey/JourneyAttributeList/JourneyAttribute/Attribute[@type='NAME']/AttributeVariant/Text/string()"); QStringList trainResult; if (!query.evaluateTo(&trainResult)) { qDebug() << "parserHafasXml::parseJourneyDataDetails - Query 7 Failed"; } if (trainResult.count() > 0) { //qDebug()<<" Train:"<<trainResult.join("").trimmed(); item->setTrain(trainResult.join("").trimmed()); } else { query.setQuery("doc($path)/ResC/ConRes//Connection[@id='" + journeyDetailRequestData.id + "']/ConSectionList/ConSection[" + QString::number(i + 1) + "]/Walk/Duration/Time/string()"); QStringList walkResult; if (!query.evaluateTo(&walkResult)) { qDebug() << "parserHafasXml::parseJourneyDataDetails - Query 8 Failed"; } //Maybe its a transfer? QStringList transferResult; if (walkResult.count() == 0) { query.setQuery("doc($path)/ResC/ConRes//Connection[@id='" + journeyDetailRequestData.id + "']/ConSectionList/ConSection[" + QString::number(i + 1) + "]/Transfer/Duration/Time/string()"); if (!query.evaluateTo(&transferResult)) { qDebug() << "parserHafasXml::parseJourneyDataDetails - Query 8b Failed"; } } //Maybe its gisroute? if (walkResult.count() == 0 && transferResult.count() == 0) { query.setQuery("doc($path)/ResC/ConRes//Connection[@id='" + journeyDetailRequestData.id + "']/ConSectionList/ConSection[" + QString::number(i + 1) + "]/GisRoute/Duration/Time/string()"); QStringList gisrouteResult; if (!query.evaluateTo(&gisrouteResult)) { qDebug() << "parserHafasXml::parseJourneyDataDetails - Query 9 Failed"; } //Ok its a gisroute if (gisrouteResult.count() > 0) { query.setQuery("doc($path)/ResC/ConRes//Connection[@id='" + journeyDetailRequestData.id + "']/ConSectionList/ConSection[" + QString::number(i + 1) + "]/GisRoute/@type/string()"); QStringList gisroutetypeResult; if (!query.evaluateTo(&gisroutetypeResult)) { qDebug() << "parserHafasXml::parseJourneyDataDetails - Query 10 Failed"; } QString gisrouteType = gisroutetypeResult.join("").trimmed(); int minutes = cleanHafasDate(gisrouteResult.join("").trimmed()).toInt(); if (gisrouteType == "FOOT") { item->setInfo(tr("Walk for %n min", "", minutes)); } else if (gisrouteType == "BIKE") { item->setInfo(tr("Use a Bike for %n min", "", minutes)); } else if (gisrouteType == "CAR") { item->setInfo(tr("Use a car for %n min", "", minutes)); } else if (gisrouteType == "TAXI") { item->setInfo(tr("Take a taxi for %n min", "", minutes)); } } } else { if (transferResult.count() > 0) { item->setInfo(tr("Transfer for %n min", "", cleanHafasDate(transferResult.join("").trimmed()).toInt())); } if (walkResult.count() > 0) { item->setInfo(tr("Walk for %n min", "", cleanHafasDate(walkResult.join("").trimmed()).toInt())); } } } results->appendItem(item); } if (results->itemcount() > 0) { results->setDepartureStation(results->getItem(0)->departureStation()); results->setArrivalStation(results->getItem(results->itemcount() - 1)->arrivalStation()); for (int i=0; i < results->itemcount(); i++) { if (!results->getItem(i)->departureDateTime().isNull()) { results->setDepartureDateTime(results->getItem(i)->departureDateTime()); break; } } for (int i=results->itemcount() -1; i >= 0; i--) { if (!results->getItem(i)->arrivalDateTime().isNull()) { results->setArrivalDateTime(results->getItem(i)->arrivalDateTime()); break; } } results->setDuration(journeyDetailRequestData.duration); results->setId(journeyDetailRequestData.id); } return results; } emit errorOccured(tr("Internal error occured, Error parsing details data")); return results; }
void Connection::onError(SignalException error) { Q_EMIT errorOccured(error); }
void ParserHafasXml::parseSearchJourney(QNetworkReply *networkReply) { lastJourneyResultList = new JourneyResultList(); journeyDetailInlineData.clear(); QBuffer readBuffer; readBuffer.setData(networkReply->readAll()); readBuffer.open(QIODevice::ReadOnly); QXmlQuery query; query.bindVariable("path", &readBuffer); query.setQuery("doc($path)/ResC/Err//@text/string()"); QStringList errorResult; if (!query.evaluateTo(&errorResult)) { qDebug() << "parserHafasXml::ErrorTest - Query Failed"; } if (errorResult.count() > 0 ) { emit errorOccured(errorResult.join("").trimmed()); qWarning()<<"ParserHafasXml::parseSearchJourneyPart2:"<<errorResult.join(""); return; } //Query for station infos query.setQuery("doc($path)/ResC/ConRes/ConnectionList/Connection/@id/string()"); QStringList resultIds; if (!query.evaluateTo(&resultIds)) { qDebug() << "parserHafasXml::getJourneyData 2 - Query Failed"; } if (resultIds.count() <= 0) { emit journeyResult(lastJourneyResultList); return; } for(int i = 0;i<resultIds.count(); i++) { //qDebug()<<"Connection:"<<resultIds[i]; query.setQuery("doc($path)/ResC/ConRes/ConnectionList/Connection[@id='" + resultIds[i] + "']/Overview/Date/string()"); QStringList dateResult; if (!query.evaluateTo(&dateResult)) { qDebug() << "parserHafasXml::getJourneyData 3 - Query Failed"; } query.setQuery("doc($path)/ResC/ConRes/ConnectionList/Connection[@id='" + resultIds[i] + "']/Overview/Transfers/string()"); QStringList transfersResult; if (!query.evaluateTo(&transfersResult)) { qDebug() << "parserHafasXml::getJourneyData 4 - Query Failed"; } query.setQuery("doc($path)/ResC/ConRes/ConnectionList/Connection[@id='" + resultIds[i] + "']/Overview/Duration/Time/string()"); QStringList durationResult; if (!query.evaluateTo(&durationResult)) { qDebug() << "parserHafasXml::getJourneyData 5 - Query Failed"; } query.setQuery("doc($path)/ResC/ConRes/ConnectionList/Connection[@id='" + resultIds[i] + "']/Overview/Products/Product/@cat/string()"); QStringList trainsResult; if (!query.evaluateTo(&trainsResult)) { qDebug() << "parserHafasXml::getJourneyData 6 - Query Failed"; } query.setQuery("doc($path)/ResC/ConRes/ConnectionList/Connection[@id='" + resultIds[i] + "']/Overview/Departure/BasicStop/Station/@name/string()"); QStringList depResult; if (!query.evaluateTo(&depResult)) { qDebug() << "parserHafasXml::getJourneyData 7 - Query Failed"; } query.setQuery("doc($path)/ResC/ConRes/ConnectionList/Connection[@id='" + resultIds[i] + "']/Overview/Arrival/BasicStop/Station/@name/string()"); QStringList arrResult; if (!query.evaluateTo(&arrResult)) { qDebug() << "parserHafasXml::getJourneyData 8 - Query Failed"; } query.setQuery("doc($path)/ResC/ConRes/ConnectionList/Connection[@id='" + resultIds[i] + "']/Overview/Departure/BasicStop/Dep/Time/string()"); QStringList depTimeResult; if (!query.evaluateTo(&depTimeResult)) { qDebug() << "parserHafasXml::getJourneyData 9 - Query Failed"; } query.setQuery("doc($path)/ResC/ConRes/ConnectionList/Connection[@id='" + resultIds[i] + "']/Overview/Departure/BasicStop/Dep/Platform/Text/string()"); QStringList depPlatResult; if (!query.evaluateTo(&depPlatResult)) { qDebug() << "parserHafasXml::getJourneyData 10 - Query Failed"; } query.setQuery("doc($path)/ResC/ConRes/ConnectionList/Connection[@id='" + resultIds[i] + "']/Overview/Arrival/BasicStop/Arr/Time/string()"); QStringList arrTimeResult; if (!query.evaluateTo(&arrTimeResult)) { qDebug() << "parserHafasXml::getJourneyData 11 - Query Failed"; } query.setQuery("doc($path)/ResC/ConRes/ConnectionList/Connection[@id='" + resultIds[i] + "']/Overview/Arrival/BasicStop/Arr/Platform/Text/string()"); QStringList arrPlatResult; if (!query.evaluateTo(&arrPlatResult)) { qDebug() << "parserHafasXml::getJourneyData 12 - Query Failed"; } query.setQuery("doc($path)/ResC/ConRes/ConnectionList/Connection[@id='" + resultIds[i] + "']/Overview/XMLHandle/@url/string()"); QStringList xmlHandleResult; if (!query.evaluateTo(&xmlHandleResult)) { qDebug() << "parserHafasXml::getJourneyData 13 - Query Failed"; } QDate date = QDate::fromString(dateResult.join("").trimmed(), "yyyyMMdd"); for (int j = 0; j < trainsResult.count(); j++) { trainsResult[j] = trainsResult[j].trimmed(); } JourneyResultItem *item = new JourneyResultItem(); item->setDate(date); item->setId(resultIds[i]); item->setTransfers(transfersResult.join("").trimmed()); item->setDuration(cleanHafasDate(durationResult.join("").trimmed())); item->setMiscInfo(""); item->setTrainType(trainsResult.join(", ").trimmed()); item->setDepartureTime(cleanHafasDate(depTimeResult.join("").trimmed())); item->setArrivalTime(cleanHafasDate(arrTimeResult.join("").trimmed())); bool hasInline = false; QString internalData1 = xmlHandleResult.join("").trimmed(); if (internalData1.count() > 0 && internalData1.indexOf("extxml.exe")) { hasInline = true; } if (internalData1.count() > 0) { internalData1.remove(0, internalData1.indexOf("query.exe") + 9); internalData1.prepend(baseUrl); item->setInternalData1(internalData1); } else { hasInline = true; } if (hasInline){ journeyDetailRequestData.id = item->id(); journeyDetailRequestData.date = item->date(); journeyDetailRequestData.duration = item->duration(); QByteArray data = readBuffer.buffer(); JourneyDetailResultList *results = internalParseJourneyDetails(data); journeyDetailInlineData.append(results); } lastJourneyResultList->setDepartureStation(depResult.join("").trimmed()); lastJourneyResultList->setArrivalStation(arrResult.join("").trimmed()); lastJourneyResultList->setTimeInfo(date.toString()); lastJourneyResultList->appendItem(item); } //Query for next and prev stuff query.setQuery("doc($path)/ResC/ConRes/ConResCtxt/string()"); QStringList ConResCtxtResult; if (!query.evaluateTo(&ConResCtxtResult)) { qDebug() << "parserHafasXml::getJourneyData 14 - Query Failed"; } hafasContext.seqNr = ConResCtxtResult.join(""); emit journeyResult(lastJourneyResultList); }
void RecursiveDirJob::slotErrorOccured(RecursiveDirJob::Error e) { //d->m_exceptions.append(e); emit errorOccured(e.message()); }
Post::Post(QObject *parent) : QObject(parent), d_ptr(new PostPrivate(this)) { Q_D(Post); ins = this; setObjectName("Post"); auto avProcess = [this](QNetworkReply *reply){ Q_D(Post); Task &task = d->queue.head(); switch (task.state){ case None:{ QString api("http://interface.%1/dmpost"); api = api.arg(Utils::customUrl(Utils::Bilibili)); task.request.setUrl(api); task.request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); const Comment &c = task.comment; QUrlQuery params; params.addQueryItem("cid", QFileInfo(task.target->source).baseName()); params.addQueryItem("date", QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")); params.addQueryItem("pool", "0"); params.addQueryItem("playTime", QString::number(c.time / 1000.0, 'f', 4)); params.addQueryItem("color", QString::number(c.color)); params.addQueryItem("fontsize", QString::number(c.font)); params.addQueryItem("message", c.string); params.addQueryItem("rnd", QString::number(qrand())); params.addQueryItem("mode", QString::number(c.mode)); task.data = QUrl::toPercentEncoding(params.query(QUrl::FullyEncoded), "%=&", "-.~_"); emit stateChanged(task.state = Code); forward(); break; } case Code:{ int code = QString(reply->readAll()).toInt(); if (code > 0){ emit stateChanged(task.state = None); } else{ emit stateChanged(task.state = code); } dequeue(); break; } } }; auto avRegular = [](QString code){ static QRegularExpression r("a(v(\\d+([#_])?(\\d+)?)?)?"); r.setPatternOptions(QRegularExpression::CaseInsensitiveOption); return r.match(code).capturedLength() == code.length(); }; d->pool.append({ avRegular, 0, avProcess }); auto ddProcess = [this](QNetworkReply *reply){ Q_D(Post); Task &task = d->queue.head(); switch (task.state){ case None:{ QString api("http://api.%1/api/v1/comment/%2"); api = api.arg(Utils::customUrl(Utils::AcPlay)); api = api.arg(QFileInfo(task.target->source).baseName()); task.request.setUrl(api); task.request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); const Comment &c = task.comment; QJsonObject params; params["Token"] = 0; params["Time"] = c.time / 1000.0; params["Mode"] = c.mode; params["Color"] = c.color; params["TimeStamp"] = QDateTime::currentMSecsSinceEpoch(); params["Pool"] = 0; params["UId"] = 0; params["CId"] = 0; params["Message"] = c.string; task.data= QJsonDocument(params).toJson(); emit stateChanged(task.state = Code); forward(); break; } case Code:{ const QJsonObject &result = QJsonDocument::fromJson(reply->readAll()).object(); if (result["Success"].toBool()){ emit stateChanged(task.state = None); } else{ emit stateChanged(task.state = QNetworkReply::UnknownNetworkError); } dequeue(); break; } } }; auto ddRegular = [](QString code){ static QRegularExpression r("d(d\\d*)?"); r.setPatternOptions(QRegularExpression::CaseInsensitiveOption); return r.match(code).capturedLength() == code.length(); }; d->pool.append({ ddRegular, 0, ddProcess }); connect(this, &Post::stateChanged, [this](int code){ switch (code){ case None: case Code: break; default:{ Q_D(Post); if (!d->tryNext()){ emit errorOccured(code); } break; } } }); }
void DefaultQuery::handleError() { DEBUG() << "Network error occured while sending request"; m_errno = NETWORK_ERROR; Q_EMIT errorOccured("network error occcured"); }
void YahooFinanceNetworkRequest::handleError() { stop(); emit errorOccured(mQueryIdentifier); }
void GnuPGConnector::gpgFinished(int _retVal) { qDebug() << "GnuPGConnector::gpgFinished(" << _retVal << ")"; this->processIsRunning = false; QString output = this->process_gpg->readAllStandardOutput().simplified(); QString error = this->process_gpg->readAllStandardError().simplified(); qDebug() << "GnuPGConnector::gpgFinished(): State finished: " << this->currentState; qDebug() << "GnuPGConnector::gpgFinished(): stdout: " << output; qDebug() << "GnuPGConnector::gpgFinished(): stderr: " << error; if(this->currentState == GPG_KEYS) { // Key listing finished: parse output this->myKeyReader->parseGnuPGOutput(output); } else if(this->currentState == GPG_SECRET_KEYS) { // All keys are now available. Compare secret keys with public keys this->myKeyReader->parseGnuPGPrivateKeysOutput(output); } else if(this->currentState == GPG_KEYS_GEN) { // Nothing to do: just check retval } else if(this->currentState == GPG_GET_VERSION) { // Set GnuPG version this->gpgStdOutput = output; if(_retVal != 0) this->gpgVersionString = "-1"; else this->gpgVersionString = output.left(55) + "..."; } else if(this->currentState == GPG_ENCRYPT) { // Enrypted content from out file this->gpgStdOutput = this->readFromTmpFile(0); } else if(this->currentState == GPG_IMPORT) { // Import command output this->gpgStdOutput = output; } else if(this->currentState == GPG_DELETE) { // Delete command output this->gpgStdOutput = output; } else if(this->currentState == GPG_SEARCH) { this->gpgStdOutput = output; this->myKeyReader->parseGnuPGServerSearchOutput(output); // Hack: ignore errors _retVal = 0; } else if(this->currentState == GPG_SET_TRUST) { this->gpgStdOutput = output; } else if(this->currentState == GPG_SIGN) { this->gpgStdOutput = output; } else if(this->currentState == GPG_EXPORT) { this->gpgStdOutput = output; } else { // Decrypted content form StdOut this->gpgStdOutput = this->readFromTmpFile(1); } // Remove tmp files QFile::remove(QString(TMPFILE) + ".asc"); QFile::remove(QString(TMPFILE) + ".txt"); QFile::remove(QString(TMPFILE)); this->gpgHistory.append("stdout: " + output); this->gpgHistory.append("stderr: " + error); this->currentState = GPG_IDLE; if(_retVal != 0) { this->gpgErrOutput = QString("[") + QString::number(_retVal) + "] " + error; emit errorOccured(); } else { emit ready(); } }
void ParserAbstract::networkReplyTimedOut() { cancelRequest(); emit errorOccured(tr("Request timed out.")); }
void RecursiveDirJobHelper::recursiveCpDir(const QString & sourcePath, const QString & destPath, RecursiveDirJob::CopyOptions options) { QDir source(sourcePath); if ( !source.exists() ) { emit errorOccured(Error(Error::NoSuchFileOrDirectory, sourcePath)); return; } QDir dest(destPath); if ( dest.exists() ) { if ( options & RecursiveDirJob::RemoveDestination ) { //in case the destination is a symlink to another directory, we remove first //the symlink target (returned by dest.canonicalPath()) and then the symlink itself. recursiveRmDir(dest.canonicalPath()); if ( QFileInfo(destPath).isSymLink() ) { QFile::remove(destPath); } } else if ( !(options & RecursiveDirJob::OverWrite) ) { emit errorOccured(Error(Error::FileOrDirectoryExists, destPath)); return; } } if ( dest.mkdir(dest.absolutePath()) ) { QFile::setPermissions(destPath, QFile::permissions(sourcePath)); } QFileInfoList currentList = source.entryInfoList(dirFilters); QFileInfo currentItem; QStack<QFileInfoList> stack; QString currentName; quint64 bytesCopied = 0; if ( m_reportProgress ) { quint64 dirSize = calculateDirSize(sourcePath); emit setLabelText(tr("Copying files from \"%1\" to \"%2\"...").arg(sourcePath).arg(destPath)); if (dirSize > 0) { emit setMaximum(dirSize); //the directory special file is already (almost) copied in dest.mkdir() above bytesCopied += stat_size(sourcePath); emit setValue(bytesCopied); } else { //no files to be copied, so set the progressbar to 100% emit setMaximum(1); emit setValue(1); } } while(1) { if ( !currentList.isEmpty() ) { currentItem = currentList.takeFirst(); currentName = currentItem.fileName(); if ( currentItem.isSymLink() ) { if ( options & RecursiveDirJob::OverWrite ) { if ( !QFile::remove(dest.absoluteFilePath(currentName)) ) emit errorOccured(Error(Error::RmFail, dest.absoluteFilePath(currentName))); } if ( !QFile::link( DirOperations::relativeSymLinkTarget(source.absoluteFilePath(currentName)), dest.absoluteFilePath(currentName) ) ) emit errorOccured(Error(Error::CopyFail, source.absoluteFilePath(currentName))); } else if ( currentItem.isDir() ) { bool ok = false; QFile::Permissions sourcePermissions = QFile::permissions(source.absoluteFilePath(currentName)); if ( !(ok = source.cd(currentName)) ) { emit errorOccured(Error(Error::AccessDenied, source.absoluteFilePath(currentName))); } if ( ok && !dest.cd(currentName) ) { //if the target dir doesn't exist, create it and try again. if ( !dest.mkdir(currentName) ) { emit errorOccured(Error(Error::MkdirFail, dest.absoluteFilePath(currentName))); } //preserve permissions of the directory QFile::setPermissions(dest.absoluteFilePath(currentName), sourcePermissions); if ( !dest.cd(currentName) ) { //quite impossible to happen emit errorOccured(Error(Error::AccessDenied, dest.absoluteFilePath(currentName))); ok = false; source.cdUp(); //revert the state of source, as we are not going to copy this dir. } } if (ok) { stack.push(currentList); currentList = source.entryInfoList(dirFilters); } } else if ( currentItem.isFile() ) { if ( options & RecursiveDirJob::OverWrite ) { if ( !QFile::remove(dest.absoluteFilePath(currentName)) ) emit errorOccured(Error(Error::RmFail, dest.absoluteFilePath(currentName))); } if ( !internal_copy( source.absoluteFilePath(currentName), dest.absoluteFilePath(currentName), options & RecursiveDirJob::ReplaceKde4InFiles ) ) emit errorOccured(Error(Error::CopyFail, source.absoluteFilePath(currentName))); } else { if ( currentItem.exists() ) { qDebug() << "Ignoring special file" << source.absoluteFilePath(currentName); } else { //this can happen with filename encoding bugs emit errorOccured(Error(Error::NoSuchFileOrDirectory, source.absoluteFilePath(currentName))); } } if ( m_reportProgress ) { bytesCopied += stat_size(currentItem.absoluteFilePath()); emit setValue(bytesCopied); } } else // list is empty { if ( !stack.isEmpty() ) { currentList = stack.pop(); source.cdUp(); dest.cdUp(); } else break; } } }
void mdtTcpSocketThread::run() { Q_ASSERT(pvPort != 0); mdtTcpSocket *socket; pvPort->lockMutex(); // Init write frame pvWriteCurrentFrame = 0; // Get a RX frame pvReadCurrentFrame = getNewFrameRead(); if(pvReadCurrentFrame == 0){ mdtError e(MDT_TCP_IO_ERROR, "No frame available in read frames pool, stopping thread", mdtError::Error); MDT_ERROR_SET_SRC(e, "mdtTcpSocketThread"); e.commit(); pvRunning = false; pvPort->unlockMutex(); return; } // Alloc the local buffer pvReadBufferSize = pvReadCurrentFrame->capacity(); pvReadBuffer = new char[pvReadBufferSize]; if(pvReadBuffer == 0){ mdtError e(MDT_TCP_IO_ERROR, "Cannot allocate memory for local read buffer" , mdtError::Error); MDT_ERROR_SET_SRC(e, "mdtTcpSocketThread"); e.commit(); pvRunning = false; pvReadBufferSize = 0; pvPort->unlockMutex(); return; } //bufferCursor = buffer; // Create a Tcp socket pvSocket = new QTcpSocket; Q_ASSERT(pvSocket != 0); // We must pass this socket object to pvPort // pvPort must be a instance of mdtTcpSocket socket = dynamic_cast<mdtTcpSocket*>(pvPort); Q_ASSERT(socket != 0); socket->setThreadObjects(pvSocket, this); // Set the running flag pvRunning = true; // Run... while(1){ // Read thread state if(!pvRunning){ break; } // Check if a connection was requested if(pvPeerPort == 0){ socket->waitForNewTransaction(); } if(pvSocket->state() == QAbstractSocket::ConnectedState){ // Wait on write ready event if(!pvPort->waitEventWriteReady()){ emit(errorOccured(MDT_TCP_IO_ERROR)); /// NOTE: sleep ? } // Read thread state if(!pvRunning){ break; } // ********************** // Event occured, send the data to port - Check timeout state first if(!pvPort->writeTimeoutOccured()){ // Write data to send writeToSocket(); } // Wait until data is available for read if(!pvPort->waitForReadyRead()){ emit(errorOccured(MDT_TCP_IO_ERROR)); /// NOTE: sleep ? } // Read thread state if(!pvRunning){ break; } // ********************** // Event occured, get the data from port - Check timeout state first if(!pvPort->readTimeoutOccured()){ // We received data , read it readFromSocket(); } }else{ // Try to (Re-)connect if(!reconnectToHost()){ qDebug() << "TCP THD: SIGNAL: Cannot reconnect - Retry at next transaction ..."; socket->waitForNewTransaction(); } } } // Put current frame into pool if(pvReadCurrentFrame != 0){ pvPort->readFramesPool().enqueue(pvReadCurrentFrame); } // End connection if(pvSocket->state() == QAbstractSocket::ConnectedState){ pvSocket->disconnectFromHost(); if(pvSocket->state() != QAbstractSocket::UnconnectedState){ // Wait on disconnected if(!pvSocket->waitForDisconnected(500)){ mdtError e(MDT_TCP_IO_ERROR, "Cannot wait for disconnected" , mdtError::Error); e.setSystemError(pvSocket->error(), pvSocket->errorString()); MDT_ERROR_SET_SRC(e, "mdtTcpSocketThread"); e.commit(); } } } // Free memory Q_ASSERT(pvReadBuffer != 0); delete pvReadBuffer; pvPort->unlockMutex(); }
void RecursiveDirJobHelper::recursiveRmDir(const QString & dir) { QDir currentDir(dir); if ( !currentDir.exists() ) { qWarning() << "recursiveRmDir: trying to remove non-existent directory" << dir; if (m_reportProgress) { //no files to be removed, so set the progressbar to 100% emit setMaximum(1); emit setValue(1); } return; // directory gone, no work to do } QFileInfoList currentList = currentDir.entryInfoList(dirFilters); QFileInfo currentItem; QStack<QFileInfoList> stack; quint64 bytesRemoved = 0; if (m_reportProgress) { quint64 dirSize = calculateDirSize(dir); emit setLabelText(tr("Removing directory \"%1\"...").arg(dir)); if (dirSize > 0) { emit setMaximum(dirSize); //start with the size of the directory to be removed. //we do this before starting removing files, because on some filesystems //(like reiserfs) the directory size is variable and will be smaller //when all files have been removed bytesRemoved += stat_size(dir); emit setValue(bytesRemoved); } else { //no files to be removed, so set the progressbar to 100% emit setMaximum(1); emit setValue(1); } } while(1) { if ( !currentList.isEmpty() ){ currentItem = currentList.takeFirst(); if ( m_reportProgress ) { bytesRemoved += stat_size(currentItem.absoluteFilePath()); emit setValue(bytesRemoved); } if ( currentItem.isDir() && !currentItem.isSymLink() ) { if ( !currentDir.cd(currentItem.fileName()) ) { emit errorOccured(Error(Error::AccessDenied, currentItem.absoluteFilePath())); } else { stack.push(currentList); currentList = currentDir.entryInfoList(dirFilters); } } else { if ( !currentDir.remove(currentItem.fileName()) ) emit errorOccured(Error(Error::RmFail, currentItem.absoluteFilePath())); } } else // list is empty { bool quit = false; if ( !stack.isEmpty() ) currentList = stack.pop(); else quit = true; //if quit == true, we remove the original dir itself, now that it is empty for sure... QString tmpname = currentDir.dirName(); currentDir.cdUp(); if ( !currentDir.rmdir(tmpname) ) emit errorOccured(Error(Error::RmFail, currentDir.absoluteFilePath(tmpname))); if ( quit ) break; } } }
int GnuPGConnector::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QDeclarativeItem::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: ready(); break; case 1: errorOccured(); break; case 2: gpgFinished((*reinterpret_cast< int(*)>(_a[1]))); break; case 3: gpgError((*reinterpret_cast< QProcess::ProcessError(*)>(_a[1]))); break; case 4: { QString _r = encrypt((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2]))); if (_a[0]) *reinterpret_cast< QString*>(_a[0]) = _r; } break; case 5: { QString _r = decrypt((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2]))); if (_a[0]) *reinterpret_cast< QString*>(_a[0]) = _r; } break; case 6: { QString _r = showKeys(); if (_a[0]) *reinterpret_cast< QString*>(_a[0]) = _r; } break; case 7: { QString _r = showSecretKeys(); if (_a[0]) *reinterpret_cast< QString*>(_a[0]) = _r; } break; case 8: { QString _r = getData((*reinterpret_cast< bool(*)>(_a[1]))); if (_a[0]) *reinterpret_cast< QString*>(_a[0]) = _r; } break; case 9: { QString _r = getFromClipboard(); if (_a[0]) *reinterpret_cast< QString*>(_a[0]) = _r; } break; case 10: setToClipboard((*reinterpret_cast< QString(*)>(_a[1]))); break; case 11: { QString _r = getKey((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); if (_a[0]) *reinterpret_cast< QString*>(_a[0]) = _r; } break; case 12: { QString _r = getKey((*reinterpret_cast< int(*)>(_a[1]))); if (_a[0]) *reinterpret_cast< QString*>(_a[0]) = _r; } break; case 13: { QString _r = getKeyByID((*reinterpret_cast< QString(*)>(_a[1]))); if (_a[0]) *reinterpret_cast< QString*>(_a[0]) = _r; } break; case 14: { QString _r = getPrivateKeyIDs((*reinterpret_cast< bool(*)>(_a[1]))); if (_a[0]) *reinterpret_cast< QString*>(_a[0]) = _r; } break; case 15: { QString _r = getPrivateKeyIDs(); if (_a[0]) *reinterpret_cast< QString*>(_a[0]) = _r; } break; case 16: { int _r = getNumOfPubKeys((*reinterpret_cast< int(*)>(_a[1]))); if (_a[0]) *reinterpret_cast< int*>(_a[0]) = _r; } break; case 17: { int _r = getNumOfPubKeys(); if (_a[0]) *reinterpret_cast< int*>(_a[0]) = _r; } break; case 18: { bool _r = generateKeyPair((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2])),(*reinterpret_cast< QString(*)>(_a[3])),(*reinterpret_cast< QString(*)>(_a[4]))); if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = _r; } break; case 19: { bool _r = setOwnerTrust((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2]))); if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = _r; } break; case 20: { bool _r = checkGPGVersion((*reinterpret_cast< QString(*)>(_a[1]))); if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = _r; } break; case 21: { QString _r = getGPGVersionString(); if (_a[0]) *reinterpret_cast< QString*>(_a[0]) = _r; } break; case 22: { bool _r = importKeysFromFile((*reinterpret_cast< QString(*)>(_a[1]))); if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = _r; } break; case 23: { bool _r = importKeysFromClipboard(); if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = _r; } break; case 24: { bool _r = searchKeysOnKeyserver((*reinterpret_cast< QString(*)>(_a[1]))); if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = _r; } break; case 25: { bool _r = importKeysFromKeyserver((*reinterpret_cast< QString(*)>(_a[1]))); if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = _r; } break; case 26: { bool _r = deleteKey((*reinterpret_cast< QString(*)>(_a[1]))); if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = _r; } break; case 27: { bool _r = signKey((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2])),(*reinterpret_cast< QString(*)>(_a[3]))); if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = _r; } break; case 28: { bool _r = exportKeys((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2]))); if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = _r; } break; case 29: { QString _r = getHistory(); if (_a[0]) *reinterpret_cast< QString*>(_a[0]) = _r; } break; case 30: { bool _r = saveHistory((*reinterpret_cast< QString(*)>(_a[1]))); if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = _r; } break; case 31: settingsSetValue((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2]))); break; case 32: { QString _r = settingsGetValue((*reinterpret_cast< QString(*)>(_a[1]))); if (_a[0]) *reinterpret_cast< QString*>(_a[0]) = _r; } break; case 33: settingsReset(); break; default: ; } _id -= 34; } return _id; }
int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; QPixmap pixmap(":/app/icons/splash.png"); SplashScreen *s = new SplashScreen(pixmap); s->show(); s->showMessage("Event Music Machine starten..."); QString path = Configuration::getStorageLocation(); if (path == "") { QFileDialog dia(s); dia.setViewMode(QFileDialog::List); dia.setFileMode(QFileDialog::Directory); dia.setAcceptMode(QFileDialog::AcceptOpen); dia.setOptions(QFileDialog::ShowDirsOnly); dia.setWindowTitle(QObject::tr("Bitte selektieren Sie einen Ordner in dem die Konfigurations-Dateien abgelegt werden sollen.")); if (dia.exec() == 1) { path = dia.selectedFiles().at(0); Configuration::setStorageLocation(path); } } s->showMessage("Slotspeicher verbinden..."); if (!QFile(Configuration::getStorageLocation() + "/slotstore.emm").exists()) { QMessageBox::information(s,"Slot-Speicher anlegen",QObject::tr("Es wurde keine gültige Slot-Datenbank gefunden. Sie wurde jetzt angelegt.")); QFile::copy(":/slot-store.sqlite", Configuration::getStorageLocation() + "/slotstore.emm"); QFile::setPermissions(Configuration::getStorageLocation() + "/slotstore.emm",QFile::ReadOther | QFile::WriteOther); } QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName(Configuration::getStorageLocation() + "/slotstore.emm"); if (!db.open()) { QMessageBox::warning(s,QObject::tr("Keine Verbindung zum Slot-Speicher"),QObject::tr("Es konnte keine Verbindung zum Slot-Speicher hergestellt werden!")); } s->showMessage("Verbindung zur Tastatur herstellen..."); KeyboardController *keyController = KeyboardController::getInstance(); QObject::connect(keyController, SIGNAL(errorOccured(QString)), s, SLOT(showErrorMessage(QString))); QObject::connect(keyController, SIGNAL(keyPressed(int,int)), &w, SLOT(keyboardSignal(int,int))); keyController->initializeKeyboardController(); s->showMessage("Audiogeräte initialisieren..."); AudioProcessor::getInstance()->initDevices(&w); s->showMessage("Audio-Plugins laden..."); PluginLoader::loadPlugins(); s->showMessage("Slots laden und überprüfen..."); int number = 1; Configuration *config = Configuration::getInstance(); for (int i=0;i<config->getLayer();i++) { for (int j=0;j<config->getVerticalSlots();j++) { for (int k=0;k<config->getHorizontalSlots();k++) { CartSlot *slot = AudioProcessor::getInstance()->getCartSlotWithNumber(number); s->showMessage("Slots laden und überprüfen...\r\n"+slot->getText1()); if (slot->isMissing()) { QMessageBox::information(s,"Datei wurde nicht gefunden","Slot "+QString::number(slot->getNumber())+" ("+slot->getText1()+") konnte nicht geladen werden, weil die Datei nicht gefunden wurde!"); } number++; } } } s->showMessage("Benutzeroberfläche initialisieren..."); w.init(); s->close(); w.show(); return a.exec(); }
void TrackingService::onError(QString error) { qDebug() << "TrackingService::onErrorOccured error: " << error; emit errorOccured(error); QTimer::singleShot(m_period * 1000, this, SLOT(sendMark())); }
bool Application::configure() { if ( !QSystemTrayIcon::isSystemTrayAvailable() ) { LOG_ERROR( "application", tr( "No system tray available!" ) ); QMessageBox::critical( 0, tr( "Error" ), tr( "No system tray available!" ) ); return false; } if ( !QSystemTrayIcon::supportsMessages() ) { LOG_ERROR( "application", tr( "System tray not support messages!" ) ); QMessageBox::critical( 0, tr( "Error" ), tr( "System tray not support messages!" ) ); return false; } // Tray icons set. trayIconList.append( ":/images/radio-active-2.png" ); trayIconList.append( ":/images/radio-active-1.png" ); trayIconList.append( ":/images/radio-active.png" ); currTrayIcon = 0; // Setup player. connect( &player, SIGNAL( playerTick( quint64 ) ), SLOT( animateIcon( quint64 ) ) ); connect( &player, SIGNAL( playing() ), SLOT( onPlayerPlay() ) ); connect( &player, SIGNAL( paused() ), SLOT( onPlayerPause() ) ); connect( &player, SIGNAL( stopped() ), SLOT( onPlayerStop() ) ); connect( &player, SIGNAL( errorOccured() ), SLOT( onPlayerError() ) ); connect( &player, SIGNAL( buffering( int ) ), SLOT( onPlayerBuffering( int ) ) ); connect( &player, SIGNAL( volumeChanged( int ) ), SLOT( onPlayerVolumeChanged( int ) ) ); connect( &player, SIGNAL( metaDataChanged( const QMultiMap< QString, QString > ) ), SLOT ( onMetaDataChange( const QMultiMap< QString, QString > ) ) ); // Setup global shortcuts. QxtGlobalShortcut * globalShortcut; globalShortcut = new QxtGlobalShortcut( &trayItem ); if ( globalShortcut ) { globalShortcut->setShortcut( QKeySequence( pauseHotkey ) ); connect( globalShortcut, SIGNAL( activated() ), &player, SLOT( playOrPause() ) ); } globalShortcut = new QxtGlobalShortcut( &trayItem ); if ( globalShortcut ) { globalShortcut->setShortcut( QKeySequence( stopHotkey ) ); connect( globalShortcut, SIGNAL( activated() ), &player, SLOT( stopPlay() ) ); } globalShortcut = new QxtGlobalShortcut( &trayItem ); if ( globalShortcut ) { globalShortcut->setShortcut( QKeySequence( volumeUpHotkey ) ); connect( globalShortcut, SIGNAL( activated() ), &player, SLOT( volumeUp() ) ); } globalShortcut = new QxtGlobalShortcut( &trayItem ); if ( globalShortcut ) { globalShortcut->setShortcut( QKeySequence( volumeDownHotkey ) ); connect( globalShortcut, SIGNAL( activated() ), &player, SLOT( volumeDown() ) ); } globalShortcut = new QxtGlobalShortcut( &trayItem ); if ( globalShortcut ) { globalShortcut->setShortcut( QKeySequence( quitHotkey ) ); connect( globalShortcut, SIGNAL( activated() ), this, SLOT( quit()) ); } // Create stations menu. stationsMenu.setTitle( tr( "Stations" ) ); stationsMenu.setIcon( QIcon( ":/images/radio-passive.png" ) ); stationsGroup = new QActionGroup( &stationsMenu ); if ( stationsGroup ) { stationsGroup->setExclusive( true ); updateStationsMenu(); connect( stationsGroup, SIGNAL( triggered( QAction * ) ), SLOT( processStationAction( QAction * ) ) ); } // Create base menu. trayMenu.addMenu( &stationsMenu ); trayMenu.addSeparator(); QAction * action; action = new QAction( &trayMenu ); if ( action ) { action->setIcon( QIcon( ":/images/audio-volume-up.png" ) ); action->setText( tr( "Volume up" ) ); action->setShortcut( QKeySequence( volumeUpHotkey ) ); connect( action, SIGNAL( triggered() ), &player, SLOT( volumeUp() ) ); trayMenu.addAction( action ); } action = new QAction( &trayMenu ); if ( action ) { action->setIcon( QIcon( ":/images/audio-volume-down.png" ) ); action->setText( tr( "Volume down" ) ); action->setShortcut( QKeySequence( volumeDownHotkey ) ); connect( action, SIGNAL( triggered() ), &player, SLOT( volumeDown() ) ); trayMenu.addAction( action ); } trayMenu.addSeparator(); action = new QAction( &trayMenu ); if ( action ) { action->setIcon( QIcon( ":/images/media-playback-start.png" ) ); action->setText( tr( "Play|Pause" ) ); action->setShortcut( QKeySequence( pauseHotkey ) ); connect( action, SIGNAL( triggered() ), &player, SLOT( playOrPause() ) ); trayMenu.addAction( action ); } action = new QAction( &trayMenu ); if ( action ) { action->setIcon( QIcon( ":/images/media-playback-stop.png" ) ); action->setText( tr( "Stop" ) ); action->setShortcut( QKeySequence( stopHotkey ) ); connect( action, SIGNAL( triggered() ), &player, SLOT( stopPlay() ) ); trayMenu.addAction( action ); } trayMenu.addSeparator(); action = new QAction( &trayMenu ); if ( action ) { action->setIcon( QIcon( ":/images/application-info.png" ) ); action->setText( tr( "Info" ) ); action->setMenuRole( QAction::AboutRole ); connect( action, SIGNAL( triggered() ), this, SLOT( about() ) ); trayMenu.addAction( action ); } action = new QAction( &trayMenu ); if ( action ) { action->setIcon( QIcon( ":/images/application-exit.png" ) ); action->setText( tr( "Exit" ) ); action->setShortcut( QKeySequence( quitHotkey ) ); action->setMenuRole( QAction::QuitRole ); connect( action, SIGNAL( triggered() ), this, SLOT( quit() ) ); trayMenu.addAction( action ); } // Create settings menu. action = new QAction( &trayMenu ); if ( action ) { action->setIcon( QIcon( ":/images/application-settings.png" ) ); action->setText( tr( "Settings" ) ); action->setMenuRole( QAction::PreferencesRole ); connect( action, SIGNAL( triggered() ), this, SLOT( manageSettings() ) ); settingsMenu.addAction( action ); } action = new QAction( &trayMenu ); if ( action ) { action->setIcon( QIcon( ":/images/application-exit.png" ) ); action->setText( tr( "Exit" ) ); action->setShortcut( QKeySequence( quitHotkey ) ); action->setMenuRole( QAction::QuitRole ); connect( action, SIGNAL( triggered() ), this, SLOT( quit() ) ); settingsMenu.addAction( action ); } // Setup tray item. trayItem.setIcon( QIcon( ":/images/radio-passive.png" ) ); trayItem.show(); trayItem.showMessage( tr( "QRadioTray" ), tr( "Program started!" ), QSystemTrayIcon::Information ); connect( &trayItem, SIGNAL( activated( QSystemTrayIcon::ActivationReason ) ), SLOT( processTrayActivation( QSystemTrayIcon::ActivationReason ) ) ); return true; }
void FahrplanParserThread::run() { ParserAbstract *m_parser; switch (i_parser) { default: case 0: m_parser = new ParserMobileBahnDe(); break; case 1: m_parser = new ParserXmlOebbAt(); break; case 2: m_parser = new ParserXmlRejseplanenDk(); break; case 3: m_parser = new ParserXmlSbbCh(); break; case 4: m_parser = new ParserXmlNri(); break; case 5: m_parser = new ParserXmlVasttrafikSe(); break; case 6: m_parser = new ParserPTVVicGovAu(); break; case 7: m_parser = new ParserSydneyEFA(); break; case 8: m_parser = new ParserSFBayEFA(); break; case 9: m_parser = new ParserIrelandEFA(); break; case 10: m_parser = new ParserDubaiEFA(); break; case 11: m_parser = new ParserNinetwo(); break; case 12: m_parser = new ParserMunichEFA(); break; case 13: m_parser = new ParserSalzburgEFA(); break; case 14: m_parser = new ParserResRobot(); break; case 15: m_parser = new ParserFinlandMatka(); break; } m_name = m_parser->name(); m_short_name = m_parser->shortName(); m_uid = m_parser->uid(); m_trainrestrictions = m_parser->getTrainRestrictions(); m_supports_gps = m_parser->supportsGps(); m_supports_via = m_parser->supportsVia(); m_supports_timetable = m_parser->supportsTimeTable(); m_supports_timetabledirection = m_parser->supportsTimeTableDirection(); qRegisterMetaType<ParserAbstract::Mode>("ParserAbstract::Mode"); //Connect thread requests with actual parser connect(this, SIGNAL(requestCancelRequest()), m_parser, SLOT(cancelRequest()), Qt::QueuedConnection); connect(this, SIGNAL(requestFindStationsByName(QString)), m_parser, SLOT(findStationsByName(QString)), Qt::QueuedConnection); connect(this, SIGNAL(requestFindStationsByCoordinates(qreal,qreal)), m_parser, SLOT(findStationsByCoordinates(qreal,qreal)), Qt::QueuedConnection); connect(this, SIGNAL(requestGetJourneyDetails(QString)), m_parser, SLOT(getJourneyDetails(QString)), Qt::QueuedConnection); connect(this, SIGNAL(requestGetTimeTableForStation(Station,Station,QDateTime,ParserAbstract::Mode,int)), m_parser, SLOT(getTimeTableForStation(Station,Station,QDateTime,ParserAbstract::Mode,int)), Qt::QueuedConnection); connect(this, SIGNAL(requestSearchJourney(Station,Station,Station,QDateTime,ParserAbstract::Mode,int)), m_parser, SLOT(searchJourney(Station,Station,Station,QDateTime,ParserAbstract::Mode,int)), Qt::QueuedConnection); connect(this, SIGNAL(requestSearchJourneyEarlier()), m_parser, SLOT(searchJourneyEarlier()), Qt::QueuedConnection); connect(this, SIGNAL(requestSearchJourneyLater()), m_parser, SLOT(searchJourneyLater()), Qt::QueuedConnection); //Connect parser responses with threads corresponding results connect(m_parser, SIGNAL(errorOccured(QString)), this, SIGNAL(errorOccured(QString)), Qt::QueuedConnection); connect(m_parser, SIGNAL(journeyDetailsResult(JourneyDetailResultList*)), this, SIGNAL(journeyDetailsResult(JourneyDetailResultList*)), Qt::QueuedConnection); connect(m_parser, SIGNAL(journeyResult(JourneyResultList*)), this, SIGNAL(journeyResult(JourneyResultList*)), Qt::QueuedConnection); connect(m_parser, SIGNAL(stationsResult(StationsList)), this, SIGNAL(stationsResult(StationsList)), Qt::QueuedConnection); connect(m_parser, SIGNAL(timetableResult(TimetableEntriesList)), this, SIGNAL(timeTableResult(TimetableEntriesList)), Qt::QueuedConnection); m_ready = true; // Autodelete after thread finishes. connect(this, SIGNAL(finished()), SLOT(deleteLater())); exec(); delete m_parser; }