void ParserXmlVasttrafikSe::parseSearchJourney(QNetworkReply *networkReply)
{
    qDebug() << "ParserXmlVasttrafikSe::parseSearchJourney(networkReply.url()=" << networkReply->url().toString() << ")";

    JourneyResultList *journeyResultList = new JourneyResultList();

    for (QHash<QString, JourneyDetailResultList *>::Iterator it = cachedJourneyDetails.begin(); it != cachedJourneyDetails.end();) {
        JourneyDetailResultList *jdrl = it.value();
        it = cachedJourneyDetails.erase(it);
        delete jdrl;
    }

    /// Use fallback values for empty results (i.e. no connections found)
    journeyResultList->setDepartureStation(m_searchJourneyParameters.departureStation.name);
    journeyResultList->setViaStation(m_searchJourneyParameters.viaStation.name);
    journeyResultList->setArrivalStation(m_searchJourneyParameters.arrivalStation.name);
    journeyResultList->setTimeInfo(tr("%1, %2", "DATE, TIME").arg(m_searchJourneyParameters.dateTime.date().toString(Qt::DefaultLocaleShortDate)).arg(m_searchJourneyParameters.dateTime.time().toString(Qt::DefaultLocaleShortDate)));

    m_earliestArrival = m_latestResultDeparture = QDateTime();

    QTextStream ts(networkReply->readAll());
    ts.setCodec("UTF-8");
    const QString xmlRawtext = ts.readAll();
    QDomDocument doc("result");
    if (doc.setContent(xmlRawtext, false)) {
        QDomNodeList tripNodeList = doc.elementsByTagName("Trip");
        for (unsigned int i = 0; i < tripNodeList.length(); ++i) {
            JourneyResultItem *jritem = new JourneyResultItem();
            JourneyDetailResultList *detailsList = new JourneyDetailResultList();

            /// Set default values for journey's start and end time
            QDateTime journeyStart = QDateTime::currentDateTime();
            QDateTime journeyEnd = QDateTime::currentDateTime();

            QDomNodeList legNodeList = tripNodeList.item(i).childNodes();
            int numStops = 0;
            QStringList trainTypes;
            int tripRtStatus = TRIP_RTDATA_NONE;
            for (unsigned int j = 0; j < legNodeList.length(); ++j) {
                QDomNode legNode = legNodeList.item(j);
                QDomNode originNode = legNode.namedItem("Origin");
                QDomNode destinationNode = legNode.namedItem("Destination");
                if (j == 0) {
                    journeyStart.setDate(QDate::fromString(getAttribute(originNode, "date"), QLatin1String("yyyy-MM-dd")));
                    journeyEnd.setDate(journeyStart.date());
                    const QTime time = QTime::fromString(getAttribute(originNode, "time"), "hh:mm");
                    journeyStart.setTime(time);
                    if (i == 0) {
                        const QDate date = QDate::fromString(getAttribute(originNode, "date"), QLatin1String("yyyy-MM-dd"));
                        journeyResultList->setDepartureStation(getAttribute(originNode, "name"));
                        journeyResultList->setTimeInfo(tr("%1, %2", "DATE, TIME").arg(date.toString(Qt::DefaultLocaleShortDate)).arg(time.toString(Qt::DefaultLocaleShortDate)));
                    }
                }
                if (j == legNodeList.length() - 1) {
                    journeyEnd.setTime(QTime::fromString(getAttribute(destinationNode, "time"), "hh:mm"));
                    if (i == 0)
                        journeyResultList->setArrivalStation(getAttribute(destinationNode, "name"));
                }

                if (getAttribute(legNode, "type") != QLatin1String("WALK") || getAttribute(originNode, "name") != getAttribute(destinationNode, "name")) {
                    ++numStops;
                    trainTypes.append(i18nConnectionType(getAttribute(legNode, "name")));
                }

                JourneyDetailResultItem *jdrItem = new JourneyDetailResultItem();
                jdrItem->setDepartureStation(getAttribute(originNode, "name"));
                const QString depTrack = getAttribute(originNode, "track");
                jdrItem->setDepartureInfo(depTrack.isEmpty() ? QChar(0x2014) : tr("Track %1").arg(depTrack));
                const QDateTime scheduledDepartureTime = QDateTime::fromString(getAttribute(originNode, "date") + getAttribute(originNode, "time"), "yyyy-MM-ddhh:mm");
                jdrItem->setDepartureDateTime(scheduledDepartureTime);
                jdrItem->setArrivalStation(getAttribute(destinationNode, "name"));
                const QString arrTrack = getAttribute(destinationNode, "track");
                jdrItem->setArrivalInfo(arrTrack.isEmpty() ? QChar(0x2014) : tr("Track %1").arg(arrTrack));
                const QDateTime scheduledArrivalTime = QDateTime::fromString(getAttribute(destinationNode, "date") + getAttribute(destinationNode, "time"), "yyyy-MM-ddhh:mm");
                jdrItem->setArrivalDateTime(scheduledArrivalTime);
                const QString direction = getAttribute(legNode, "direction");
                if (!direction.isEmpty())
                    jdrItem->setInfo(tr("to %1").arg(direction));
                if (getAttribute(legNode, "type") == QLatin1String("WALK"))
                    jdrItem->setTrain(tr("Walk"));
                else {
                    const QString connectionName = i18nConnectionType(getAttribute(legNode, "name"));
                    const QString fgColor = getAttribute(legNode, "fgColor");
                    const QString bgColor = getAttribute(legNode, "bgColor");
                    if (!fgColor.isEmpty() && !bgColor.isEmpty())
                        jdrItem->setTrain(QString(QLatin1String("<span style=\"color:%2; background-color: %3;\">%1</span>")).arg(connectionName).arg(fgColor).arg(bgColor));
                    else
                        jdrItem->setTrain(connectionName);
                }
                jdrItem->setInternalData1("NO setInternalData1");
                jdrItem->setInternalData2("NO setInternalData2");

                const QString realTimeDeparture = getAttribute(originNode, "rtTime");
                if (!realTimeDeparture.isEmpty()) {
                    const QTime realTimeTime = QTime::fromString(realTimeDeparture, QLatin1String("hh:mm"));
                    const int minutesTo = scheduledDepartureTime.time().msecsTo(realTimeTime) / 60000;
                    if (minutesTo > 3) {
                        jdrItem->setDepartureInfo(jdrItem->departureInfo() + tr("<br/><span style=\"color:#b30;\">%1 min late</span>").arg(minutesTo));
                        tripRtStatus = TRIP_RTDATA_WARNING;
                    } else {
                        if (tripRtStatus == TRIP_RTDATA_NONE) {
                            tripRtStatus = TRIP_RTDATA_ONTIME;
                        }
                        jdrItem->setDepartureInfo(jdrItem->departureInfo() + tr("<br/><span style=\"color:#093; font-weight: normal;\">on time</span>"));
                    }
                }

                const QString realTimeArrival = getAttribute(destinationNode, "rtTime");
                if (!realTimeArrival.isEmpty()) {
                    const QTime realTimeTime = QTime::fromString(realTimeArrival, QLatin1String("hh:mm"));
                    const int minutesTo = scheduledArrivalTime.time().msecsTo(realTimeTime) / 60000;
                    if (minutesTo > 3)
                        jdrItem->setArrivalInfo(jdrItem->arrivalInfo() + tr("<br/><span style=\"color:#b30;\">%1 min late</span>").arg(minutesTo));
                    else
                        jdrItem->setArrivalInfo(jdrItem->arrivalInfo() + tr("<br/><span style=\"color:#093; font-weight: normal;\">on time</span>"));
                }

                detailsList->appendItem(jdrItem);
            }

            if (journeyStart.time() > journeyEnd.time())
                journeyEnd = journeyEnd.addDays(1);

            jritem->setDate(journeyStart.date());
            jritem->setDepartureTime(journeyStart.time().toString(tr("hh:mm")));
            jritem->setArrivalTime(journeyEnd.time().toString(tr("hh:mm")));
            int diffTime = journeyStart.secsTo(journeyEnd);
            if (diffTime < 0) diffTime += 86400;
            jritem->setDuration(tr("%1:%2").arg(diffTime / 3600).arg(QString::number(diffTime / 60 % 60), 2, '0'));
            jritem->setTransfers(QString::number(legNodeList.length() - 1));
            trainTypes.removeDuplicates();
            jritem->setTrainType(trainTypes.join(", "));
            if (tripRtStatus == TRIP_RTDATA_WARNING)
                jritem->setMiscInfo(tr("<span style=\"color:#b30;\">traffic warning</span>"));
            else if (tripRtStatus == TRIP_RTDATA_ONTIME)
                jritem->setMiscInfo(tr("<span style=\"color:#093; font-weight: normal;\">on time</span>"));

            journeyResultList->appendItem(jritem);

            const QString id = QString::number(i);
            jritem->setId(id);
            detailsList->setId(id);
            detailsList->setDepartureStation(journeyResultList->departureStation());
            detailsList->setViaStation(journeyResultList->viaStation());
            detailsList->setArrivalStation(journeyResultList->arrivalStation());
            detailsList->setDuration(jritem->duration());
            detailsList->setArrivalDateTime(journeyEnd);
            detailsList->setDepartureDateTime(journeyStart);
            cachedJourneyDetails[id] = detailsList;

            if (!m_earliestArrival.isValid() || journeyEnd < m_earliestArrival)
                m_earliestArrival = journeyEnd.addSecs(-60);
            if (!m_latestResultDeparture.isValid() || journeyStart > m_latestResultDeparture)
                m_latestResultDeparture = journeyStart.addSecs(60);
        }
    }

    emit journeyResult(journeyResultList);
}
示例#2
0
void Parser131500ComAu::parseSearchJourney(QNetworkReply *networkReply)
{
    lastJourneyResultList = new JourneyResultList();

    QBuffer *filebuffer = new QBuffer();
    filebuffer->setData(networkReply->readAll());

    QRegExp regexp = QRegExp("<div class=\"midcolumn3\">(.*)</div>(.*)</div>(.*)<div id=\"righttools\">");
    regexp.setMinimal(true);

    regexp.indexIn(filebuffer->buffer());

    QString element = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><html xmlns=\"http://www.w3.org/1999/xhtml\">\n<body>\n" + regexp.cap(0) + "\n</div></body>\n</html>\n";

    QRegExp imgReg = QRegExp("icon_(.*)_s.gif\" />");
    imgReg.setMinimal(true);
    element.replace(imgReg, "icon_" + QString("\\1") + "_s.gif\" />" + QString("\\1"));
    element.replace("am+", "am");
    element.replace("pm+", "pm");

    //qDebug()<<element;

    QBuffer readBuffer;
    readBuffer.setData(element.toAscii());
    readBuffer.open(QIODevice::ReadOnly);

    QXmlQuery query;
    query.bindVariable("path", &readBuffer);
    query.setQuery("declare default element namespace \"http://www.w3.org/1999/xhtml\"; declare variable $path external; doc($path)/html/body/div/div/table/tbody/tr/td[@id='header2']/string()");

    QStringList departResult;
    if (!query.evaluateTo(&departResult))
    {
        qDebug() << "parser131500ComAu::getJourneyData - Query 1 Failed";
    }

    query.setQuery("declare default element namespace \"http://www.w3.org/1999/xhtml\"; declare variable $path external; doc($path)/html/body/div/div/table/tbody/tr/td[@id='header3']/string()");

    QStringList arriveResult;
    if (!query.evaluateTo(&arriveResult))
    {
        qDebug() << "parser131500ComAu::getJourneyData - Query 2 Failed";
    }

    query.setQuery("declare default element namespace \"http://www.w3.org/1999/xhtml\"; declare variable $path external; doc($path)/html/body/div/div/table/tbody/tr/td[@id='header4']/string()");

    QStringList timeResult;
    if (!query.evaluateTo(&timeResult))
    {
        qDebug() << "parser131500ComAu::getJourneyData - Query 3 Failed";
    }

    query.setQuery("declare default element namespace \"http://www.w3.org/1999/xhtml\"; declare variable $path external; doc($path)/html/body/div/div/table/tbody/tr/td[@id='header5']/string()");

    QStringList trainResult;
    if (!query.evaluateTo(&trainResult))
    {
        qDebug() << "parser131500ComAu::getJourneyData - Query 4 Failed";
    }

    query.setQuery("declare default element namespace \"http://www.w3.org/1999/xhtml\"; declare variable $path external; doc($path)/html/body/div/div/div/string()");

    QStringList headerResult;
    if (!query.evaluateTo(&headerResult))
    {
        qDebug() << "parser131500ComAu::getJourneyData - Query 5 Failed";
    }

    for (int i = 0; i < headerResult.count(); i++) {
        QRegExp regexp = QRegExp("(From:|To:|When:)(.*)$");
        regexp.setMinimal(true);
        regexp.indexIn(headerResult[i].trimmed());
        if (regexp.cap(1) == "From:") {
            lastJourneyResultList->setDepartureStation(regexp.cap(2).trimmed());
        }
        if (regexp.cap(1) == "To:") {
            lastJourneyResultList->setArrivalStation(regexp.cap(2).trimmed());
        }
        if (regexp.cap(1) == "When:") {
            lastJourneyResultList->setTimeInfo(regexp.cap(2).trimmed());
        }
    }

    QRegExp regexp2 = QRegExp("(.*), (\\d\\d) (.*) (\\d\\d\\d\\d)");
    regexp2.setMinimal(true);
    regexp2.indexIn(lastJourneyResultList->timeInfo().trimmed());
    QLocale enLocale = QLocale(QLocale::English, QLocale::UnitedStates);
    int month = 1;
    for (month = 1; month < 10; month++) {
        if (regexp2.cap(3).trimmed() == enLocale.standaloneMonthName(month)) {
            break;
        }
    }

    QDate journeydate = QDate::fromString(regexp2.cap(2).trimmed() + " " + QString::number(month) + " " + regexp2.cap(4).trimmed(), "dd M yyyy");

    //Generate Details search results

    QStringList detailsResult;

    regexp = QRegExp("<table class=\"dataTbl widthcol2and3\" cellspacing=\"0\" style=\"margin:0px ! important;border-right:0px none;\" summary=\"Search Results Details\">(.*)</table>");
    regexp.setMinimal(true);
    int pos = 0;

    while ((pos = regexp.indexIn(filebuffer->buffer(), pos)) != -1) {
        QString element = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><html xmlns=\"http://www.w3.org/1999/xhtml\">\n<body><table>\n" + regexp.cap(1) + "\n</table></body>\n</html>\n";
        element.replace("&nbsp;", " ");
        element.replace("bulletin.gif\">", "bulletin.gif\" />");

        QBuffer readBuffer;
        readBuffer.setData(element.toAscii());
        readBuffer.open(QIODevice::ReadOnly);

        QXmlQuery query;
        query.bindVariable("path", &readBuffer);

        query.setQuery("declare default element namespace \"http://www.w3.org/1999/xhtml\"; declare variable $path external; doc($path)/html/body/table/tbody/tr/td[@headers='header2']/string()");

        QStringList detailsContentResult;
        if (!query.evaluateTo(&detailsContentResult))
        {
            qDebug() << "parser131500ComAu::getJourneyData - DetailsQuery 1 Failed";
        }

        detailsResult << detailsContentResult.join("<linesep>");

        pos += regexp.matchedLength();
    }

    //qDebug()<<departResult;

    //Create search result
    for (int i = 0; i < departResult.count(); i++) {

        //Parse transporttypes and changes
        QString tmp = trainResult[i].trimmed();
        tmp.replace("\t", " ");
        tmp.replace("\n", " ");
        tmp.replace("\r", " ");
        QStringList trains = tmp.split(" ", QString::SkipEmptyParts);
        int changes = trains.length() - 1;
        trains.removeDuplicates();

        //Parse travel time
        tmp = timeResult[i].trimmed();
        tmp.replace("mins", "");
        tmp.replace("min", "");
        tmp.replace("hrs ", ":");
        tmp.replace("hr ", ":");
        QStringList durationLst = tmp.split(":", QString::SkipEmptyParts);

        QString durationStr = "";
        if (durationLst.length() == 1) {
            durationStr.sprintf("00: %02d", durationLst[0].toInt());
        }
        if (durationLst.length() == 2) {
            durationStr.sprintf("%02d:%02d", durationLst[0].toInt(), durationLst[1].toInt());
        }

        JourneyResultItem *item = new JourneyResultItem();
        item->setDate(journeydate);
        item->setId(QString::number(i));
        item->setTransfers(QString::number(changes));
        item->setDuration(durationStr);
        item->setTrainType(trains.join(", "));
        item->setDepartureTime(QTime::fromString(departResult[i].trimmed(), "h:map").toString("hh:mm"));
        item->setArrivalTime(QTime::fromString(arriveResult[i].trimmed(), "h:map").toString("hh:mm"));
        item->setInternalData1(detailsResult[i]);

        lastJourneyResultList->appendItem(item);
    }

    emit journeyResult(lastJourneyResultList);
}
示例#3
0
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);
}