//! [1]
TimeInformation::List TimeQuery::queryInternal(const QString &stationId, const QDateTime &dateTime)
{
    const QString timesQueryUrl = QString("doc('http://wap.trafikanten.no/F.asp?f=%1&t=%2&m=%3&d=%4&start=1')/wml/card/p/small/a[fn:starts-with(@href, 'Rute')]/string()")
                                         .arg(stationId)
                                         .arg(dateTime.time().hour())
                                         .arg(dateTime.time().minute())
                                         .arg(dateTime.toString("dd.MM.yyyy"));
    const QString directionsQueryUrl = QString("doc('http://wap.trafikanten.no/F.asp?f=%1&t=%2&m=%3&d=%4&start=1')/wml/card/p/small/text()[matches(., '[0-9].*')]/string()")
                                              .arg(stationId)
                                              .arg(dateTime.time().hour())
                                              .arg(dateTime.time().minute())
                                              .arg(dateTime.toString("dd.MM.yyyy"));

    QStringList times;
    QStringList directions;

    QXmlQuery query;
    query.setQuery(timesQueryUrl);
    query.evaluateTo(&times);

    query.setQuery(directionsQueryUrl);
    query.evaluateTo(&directions);

    if (times.count() != directions.count()) // something went wrong...
        return TimeInformation::List();

    TimeInformation::List information;
    for (int i = 0; i < times.count(); ++i)
        information.append(TimeInformation(times.at(i).simplified(), directions.at(i).simplified()));

    return information;
}
Exemple #2
0
//! [0]
StationInformation::List StationQuery::query(const QString &name)
{
    const QString stationIdQueryUrl = QString("doc(concat('http://wap.trafikanten.no/FromLink1.asp?fra=', $station))/wml/card/p/small/a[@title='Velg']/substring(@href,18)");
    const QString stationNameQueryUrl = QString("doc(concat('http://wap.trafikanten.no/FromLink1.asp?fra=', $station))/wml/card/p/small/a[@title='Velg']/string()");

    QStringList stationIds;
    QStringList stationNames;

    QXmlQuery query;

    query.bindVariable("station", QVariant(QString::fromLatin1(QUrl::toPercentEncoding(name))));
    query.setQuery(stationIdQueryUrl);
    query.evaluateTo(&stationIds);

    query.bindVariable("station", QVariant(QString::fromLatin1(QUrl::toPercentEncoding(name))));
    query.setQuery(stationNameQueryUrl);
    query.evaluateTo(&stationNames);

    if (stationIds.count() != stationNames.count()) // something went wrong...
        return StationInformation::List();

    StationInformation::List information;
    for (int i = 0; i < stationIds.count(); ++i)
        information.append(StationInformation(stationIds.at(i), stationNames.at(i)));

    return information;
}
void LastFmContext::readContextReply() {
    qDebug("Got reply!");
    QString replyString = QString::fromUtf8(contextReply->readAll());

    if (replyString.isEmpty()) {
        emit contextError();
        return; // Avoid empty parsing of XML
    }

    // Parametres
    QString status;
    QString artistName;
    QString artistPicture;
    QString artistSummary;
    QString artistProfile;

    QXmlQuery query;
    query.setFocus(replyString);
    query.setQuery("lfm[@status = 'ok']/count(artist)");
    query.evaluateTo(&status);
    status = status.trimmed();
    qDebug("Status: " + status.toUtf8());

    /*
     * If we got the data successfully, let's read it.
     * I hate XML.
     */
    if (status == "1") {
        query.setQuery("lfm/artist/name/text()");
        query.evaluateTo(&artistName);
        artistName = artistName.trimmed();

        query.setQuery("lfm/artist/url/text()");
        query.evaluateTo(&artistProfile);
        artistProfile = artistProfile.trimmed();

        query.setQuery("lfm/artist/image[@size=\"extralarge\"]/text()");
        query.evaluateTo(&artistPicture);
        artistPicture = artistPicture.trimmed();

        // Summary has HTML entities that must be un-replaced.
        query.setQuery("lfm/artist/bio/summary/text()");
        query.evaluateTo(&artistSummary);
        artistSummary = artistSummary.trimmed().replace("&lt;","<").replace("&gt;",">");

        // Store the context data into... contextData. Nice!
        contextData.clear();
        contextData.insert("artist", artistName);
        contextData.insert("picture", artistPicture);
        contextData.insert("summary", artistSummary);
        contextData.insert("profile", artistProfile);

        // Emit the signal
        emit contextUpdated(contextData);
    }
    else {
        qDebug("FAIL!");
        emit contextError();
    }
}
void MasterConfiguration::loadMasterSettings()
{
    QXmlQuery query;
    if(!query.setFocus(QUrl(filename_)))
    {
        put_flog(LOG_FATAL, "failed to load %s", filename_.toLatin1().constData());
        exit(-1);
    }

    QString queryResult;

    // dock start directory
    query.setQuery("string(/configuration/dock/@directory)");
    if (query.evaluateTo(&queryResult))
        dockStartDir_ = queryResult.remove(QRegExp("[\\n\\t\\r]"));
    if( dockStartDir_.isEmpty( ))
        dockStartDir_ = QDir::homePath();

    // WebService server port
    query.setQuery("string(/configuration/webservice/@port)");
    if (query.evaluateTo(&queryResult))
    {
        if (queryResult.isEmpty())
            dcWebServicePort_ = DEFAULT_WEBSERVICE_PORT;
        else
            dcWebServicePort_ = queryResult.toInt();
    }
}
QString F520xmlserializer::query(F520Status *f520, QString day, QString month, SysError &sysErr) {
    QXmlQuery query;
    QString res;
    QFile xml(f520->getXmlPath());
    if ( ! xml.exists()) {
        xml.setFileName(f520->getXmlPath());
        if ( ! xml.exists()) {
            sysErr = SysError(SysError::F520_CAN_NOT_OPEN_FILE, "F520 Rasource file not exist");
            return "";
        }
    }

    if (!xml.open(QIODevice::ReadOnly | QIODevice::Text)) {
        sysErr = SysError(SysError::F520_RESOUCES_NOT_EXIST, "F520 can not open xml resource file");
        return "";
    }

    QString queryStr = CARICO + "/" + DAYS + "/" + DAY + "[@" + DAY_VALUE + "='" + day + "'][@" + MONTH_VALUE + "='" + month + "']";
    qDebug() << "F520xmlserializer::query: " << queryStr;

    query.setFocus(&xml);
    query.setQuery(queryStr);
    if ( ! query.isValid()) {
        qDebug() << "F520xmlserializer::query query not valid";
        sysErr = SysError(SysError::F520_QUERY_ERROR, "F520 Query is invalid: " + queryStr);
        return "";
    }

    query.evaluateTo(&res);

    if (!(res.length() > 1)) {
        queryStr = CARICO + "/" + DAYS + "/" + DAY + "[@" + NAME + "='" + DEFAULT_DAY + "']";
        qDebug() << "F520xmlserializer::query: " << queryStr;
        query.setQuery(queryStr);
        if (!query.isValid()) {
            qDebug() << "F520xmlserializer::query query not valid";
            sysErr = SysError(SysError::F520_QUERY_ERROR, "F520 Query is invalid: " + queryStr);
            return "";
        }
        query.evaluateTo(&res);
    }

    xml.close();

    qDebug() << "F520xmlserializer::query " << res;

    QDomDocument watt;
    watt.setContent("" + res + "");
    QDomNodeList entryNodes = watt.elementsByTagName(DAY);

    QString rtn;
    for (int i = 0; i < entryNodes.count(); i++) {
        QDomElement node = entryNodes.at(i).toElement();
        rtn = node.attribute(WATT);
        break;
    }
    qDebug() << "F520xmlserializer::query " << rtn;
    return rtn;
}
void Configuration::load()
{
    QXmlQuery query;
    if(!query.setFocus(QUrl(filename_)))
        throw std::runtime_error("Invalid configuration file: " + filename_.toStdString());

    QString queryResult;

    // get screen / mullion dimensions
    query.setQuery("string(/configuration/dimensions/@numTilesWidth)");
    if(query.evaluateTo(&queryResult))
        totalScreenCountX_ = queryResult.toInt();

    query.setQuery("string(/configuration/dimensions/@numTilesHeight)");
    if(query.evaluateTo(&queryResult))
        totalScreenCountY_ = queryResult.toInt();

    query.setQuery("string(/configuration/dimensions/@screenWidth)");
    if(query.evaluateTo(&queryResult))
        screenWidth_ = queryResult.toInt();

    query.setQuery("string(/configuration/dimensions/@screenHeight)");
    if(query.evaluateTo(&queryResult))
        screenHeight_ = queryResult.toInt();

    query.setQuery("string(/configuration/dimensions/@mullionWidth)");
    if(query.evaluateTo(&queryResult))
        mullionWidth_ = queryResult.toInt();

    query.setQuery("string(/configuration/dimensions/@mullionHeight)");
    if(query.evaluateTo(&queryResult))
        mullionHeight_ = queryResult.toInt();

    // check for fullscreen mode flag
    query.setQuery("string(/configuration/dimensions/@fullscreen)");
    if(query.evaluateTo(&queryResult))
        fullscreen_ = queryResult.toInt() != 0;

    // Background content URI
    query.setQuery("string(/configuration/background/@uri)");
    if(query.evaluateTo(&queryResult))
        backgroundUri_ = queryResult.remove(QRegExp("[\\n\\t\\r]"));

    // Background color
    query.setQuery("string(/configuration/background/@color)");
    if (query.evaluateTo(&queryResult))
    {
        queryResult.remove(QRegExp("[\\n\\t\\r]"));

        QColor newColor( queryResult );
        if( newColor.isValid( ))
            backgroundColor_ = newColor;
    }
}
void tst_QXmlResultItems::evaluate() const
{
    QFETCH(QString, queryString);

    QXmlQuery query;
    query.setQuery(queryString);

    QVERIFY(query.isValid());

    QXmlResultItems result;
    query.evaluateTo(&result);
    QXmlItem item(result.next());

    while(!item.isNull())
    {
        QVERIFY(!result.current().isNull());
        QVERIFY(!result.hasError());
        item = result.next();
    }

    /* Now, stress beyond the end. */
    for(int i = 0; i < 3; ++i)
    {
        QVERIFY(result.current().isNull());
        QVERIFY(result.next().isNull());
    }
}
void NetFlixQueueProxy::getQueueRequestCompleted(int retCode, QString body){
    qDebug() << "queue request completed!!";
    qDebug() << retCode;

    QXmlQuery query;
    QString result;

    QBuffer device;
    device.setData(body.toUtf8());
    device.open(QIODevice::ReadOnly);

    query.bindVariable("netflix_queue",&device);
    query.setQuery(QUrl("qrc:/queries/queue.xq"));
    if (query.isValid())
    {
        if (query.evaluateTo(&result))
            qDebug() << result;
        else
            qDebug() << "Evaluate failed";
    }
    else
        qDebug() << "setQuery Failed.";


}
Exemple #9
0
SimXmlElement SimXmlDoc::findElement(const std::string& elementName, const std::string& refId) const
{
  SimXmlElement result(QSharedPointer<QDomElement>(), *this);

  if (isNull()){
    return result;
  }

  QString queryString = simQuery("/SimModel/" + elementName + "[@RefId='" + refId + "'][1]");

  QXmlQuery query;
  QDomNodeModel model(query.namePool(), *(impl()));
  query.setFocus(QXmlItem(model.fromDomNode(impl()->documentElement())));
  query.setQuery(queryString, QUrl(QString::fromStdString(this->path())));

  if (query.isValid()) {

    QXmlResultItems items;

    query.evaluateTo(&items);

    QXmlItem item(items.next());

    if(!item.isNull()) {

      QDomElement elem = model.toDomNode(item.toNodeModelIndex()).toElement();

      QSharedPointer<QDomElement> impl(new QDomElement(elem));

      result = SimXmlElement(impl, *this);
    }
  }

  return result;
}
void QueryMainWindow::evaluate(const QString &str)
{
    /* This function takes the input string and displays the
     * appropriate output using QXmlQuery.
     */
    QXmlQuery query;

    QFile sourceDocument;
    sourceDocument.setFileName(":/files/cookbook.xml");
    sourceDocument.open(QIODevice::ReadOnly);
    query.bindVariable("inputDocument", &sourceDocument);

    query.setQuery(str);

    if(!query.isValid())
        return;

    QByteArray outArray;
    QBuffer buffer(&outArray);
    buffer.open(QIODevice::ReadWrite);
    
    QXmlFormatter formatter(query, &buffer);

    if(!query.evaluateTo(&formatter))
        return;
 
    buffer.close();
    qFindChild<QTextEdit*>(this, "outputTextEdit")->setPlainText(QString::fromUtf8(outArray.constData()));
    
}
void ShoutcastFetcher::newStationsAvailable(QIODevice * openInputDevice, const QString & keyWord)
{
	// Using read() putting the content into a QBuffer to workaround
	// some strange hang if passing IO device directly into
	// QXmlQuery object.
	QByteArray content = openInputDevice->read(maxSize);
	QBuffer buf(&content);
	buf.open(QIODevice::ReadOnly);
	QXmlQuery q;
	q.bindVariable("stations", &buf);
	q.setQuery("for $i in doc($stations)/stationlist/station " \
			   "let $tunein := doc($stations)/stationlist/tunein/@base " \
			   "return (string($i/@name), string($i/@id), string($i/@br), string($i/@genre)," \
			   "        string($i/@lc), string($i/@mt), string($i/@ct), string($tunein))");
	QStringList strings;
	q.evaluateTo(&strings);
	m_keywordStationMapping[keyWord].clear();
	ShoutcastStationList & sl = m_keywordStationMapping[keyWord];
	for (QStringList::const_iterator iter = strings.constBegin(); iter != strings.constEnd(); iter += 8)
	{
		QString tuneIn = stationsURL + *(iter + 1);
		ShoutcastStation s(*iter, (*(iter + 1)).toInt(), (*(iter + 2)).toInt(),
						   *(iter + 3), (*(iter + 4)).toInt(), *(iter + 5), *(iter + 6),
						   tuneIn);
		sl.append(s);
	}
	emit newStationsAvailable(keyWord);
}
void AVRStudioXMLParser::Parse(QString configDirPath, Part *pPart)
{
    QXmlQuery query;
    QString result;
    query.bindVariable("partName", QVariant(configDirPath));
    query.setQuery(GetXQuery());
    query.evaluateTo(&result);

    // for future use
    QString errorMsg;
    int line;
    int col;

    QDomDocument doc;
    if(!doc.setContent(result, &errorMsg, &line, &col))
        return;

    QDomNode root = doc.firstChild();
    QDomNode fuses = root.firstChild();
    QDomNode locks = fuses.nextSibling();
    QDomNode interfaces = locks.nextSibling();

    pPart->SetFuseBits(GetBits(fuses.firstChild()));
    pPart->SetLockBits(GetBits(locks.firstChild()));
    pPart->SetProgrammingInterfaces(GetInterfaces(interfaces.firstChild()));
}
void JobEventList::setContent(const QString &content, const QString &userName,
                              QList<qint64> jobIds)
{
  m_xml = content;
  m_valid = true;

  MessageHandler handler;
  QXmlQuery query;
  query.setMessageHandler(&handler);
  JobEventListXmlReceiver receiver(query.namePool());
  query.setFocus(m_xml);

  if (jobIds.isEmpty()) {
    query.setQuery("/list/JobEvent");
  }
  else {
    QString xpath = "/list/JobEvent/jobID[";
    QListIterator<qint64> iter(jobIds);

    while (iter.hasNext()) {
      qint64 jobId = iter.next();
      xpath += QString("starts-with(text(), '%1')").arg(jobId);
      if (iter.hasNext())
        xpath += " or ";
    }

    xpath += "]/parent::node()";

    query.setQuery(xpath);
  }

  m_valid = query.evaluateTo(&receiver);

  m_jobEvents = receiver.jobEvents();
}
Exemple #14
0
std::string parserxml::getAnyValue(std::string pNodeDirectionValue)
{
    if( !_file.open(QIODevice::ReadOnly))
    {
        qDebug() << "No se pudo abrir el XML para lectura.";
    }
    else
    {
        QXmlQuery query;
        query.bindVariable("document", &_file);
        std::string stringdocument = "doc($document)";
        std::string finalstring = std::string(stringdocument) + std::string(pNodeDirectionValue);
        query.setQuery(QString::fromStdString(finalstring));
        if(!query.isValid()) 
        {
           qDebug()<< "Xpath invalido.";
        }
        QString queryresult;
        query.evaluateTo(&queryresult);
        if (queryresult == "\n")
        {
            queryresult = "";
        }
        _file.close();
        return queryresult.toStdString();
    }  
}
void PtzManagement::getNode(Node *node)
{
    Message *msg = newMessage();
    msg->appendToBody(node->toxml());
    MessageParser *result = sendMessage(msg);
    if(result != NULL){
        QXmlQuery *query = result->query();
        QDomNodeList itemNodeList;
        QDomNode node1;
        QDomDocument doc;
        QString value,xml;
        query->setQuery(result->nameSpace()+"doc($inputDocument)//tptz:PTZNode");
        query->evaluateTo(&xml);
        doc.setContent(xml);
        itemNodeList = doc.elementsByTagName("tptz:PTZNode");
        for(int i=0; i<itemNodeList.size();i++)
        {
            node1= itemNodeList.at(i);
            value = node1.toElement().attribute("token");
            node->setPtzNodeToken(value.trimmed());
        }

        node->setName(result->getValue("//tt:Name").trimmed());
        node->setAbsolutePanTiltPositionSpaceUri(result->getValue("//tt:SupportedPTZSpaces/tt:AbsolutePanTiltPositionSpace/tt:URI").trimmed());
        node->setAbsolutePanTiltPositionSpaceXRangeMin(result->getValue("//tt:SupportedPTZSpaces/tt:AbsolutePanTiltPositionSpace/tt:XRange/tt:Min").trimmed().toInt());
        node->setAbsolutePanTiltPositionSpaceXRangeMax(result->getValue("//tt:SupportedPTZSpaces/tt:AbsolutePanTiltPositionSpace/tt:XRange/tt:Max").trimmed().toInt());
        node->setAbsolutePanTiltPositionSpaceYRangeMin(result->getValue("//tt:SupportedPTZSpaces/tt:AbsolutePanTiltPositionSpace/tt:YRange/tt:Min").trimmed().toInt());
        node->setAbsolutePanTiltPositionSpaceYRangeMax(result->getValue("//tt:SupportedPTZSpaces/tt:AbsolutePanTiltPositionSpace/tt:YRange/tt:Max").trimmed().toInt());
        node->setAbsoluteZoomPositionSpaceUri(result->getValue("//tt:SupportedPTZSpaces/tt:AbsoluteZoomPositionSpace/tt:URI").trimmed());
        node->setAbsoluteZoomPositionSpaceXRangeMin(result->getValue("//tt:SupportedPTZSpaces/tt:AbsoluteZoomPositionSpace/tt:XRange/tt:Min").trimmed().toInt());
        node->setAbsoluteZoomPositionSpaceXRangeMax(result->getValue("//tt:SupportedPTZSpaces/tt:AbsoluteZoomPositionSpace/tt:XRange/tt:Max").trimmed().toInt());
        node->setRelativePanTiltTranslationSpaceUri(result->getValue("//tt:SupportPTZSpaces/tt:RelativePanTiltTranslationSpaces/tt:URI").trimmed());
        node->setRelativePanTiltTranslationSpaceXRangeMin(result->getValue("//tt:SupportPTZSpace/tt:RelativePanTiltTranslationSpaces/tt:XRange/tt:Min").trimmed().toInt());
        node->setRelativePanTiltTranslationSpaceXRangeMax(result->getValue("//tt:SupportPTZSpace/tt:RelativePanTiltTranslationSpaces/tt:XRange/tt:Max").trimmed().toInt());
        node->setRelativePanTiltTranslationSpaceYRangeMin(result->getValue("//tt:SupportPTZSpace/tt:RelativePanTiltTranslationSpaces/tt:YRange/tt:Min").trimmed().toInt());
        node->setRelativePanTiltTranslationSpaceYRangeMax(result->getValue("//tt:SupportPTZSpace/tt:RelativePanTiltTranslationSpaces/tt:YRange/tt:Max").trimmed().toInt());
        node->setRelativeZoomTranslationSpaceUri(result->getValue("//tt:SupportPTZSpace/tt:RelativePanTiltTranslationSpaces/tt:URI").trimmed());
        node->setRelativeZoomTranslationSpaceXRangeMin(result->getValue("//tt:SupportPTZSpace/tt:RelativePanTiltTranslationSpaces/tt:XRange/tt:Min").trimmed().toInt());
        node->setRelativeZoomTranslationSpaceXRangeMax(result->getValue("//tt:SupportPTZSpace/tt:RelativePanTiltTranslationSpaces/tt:XRange/tt:Max").trimmed().toInt());
        node->setContinuousPanTiltVelocityUri(result->getValue("//tt:SupportPTZSpace/tt:ContinuousPanTiltVelocitySpace/tt:URI").trimmed());
        node->setContinuousPanTiltVelocityXRangeMin(result->getValue("//tt:SupportPTZSpace/tt:ContinuousPanTiltVelocitySpace/tt:XRange/tt:Min").trimmed().toInt());
        node->setContinuousPanTiltVelocityXRangeMax(result->getValue("//tt:SupportPTZSpace/tt:ContinuousPanTiltVelocitySpace/tt:XRange/tt:Max").trimmed().toInt());
        node->setContinuousPanTiltVelocityYRangeMin(result->getValue("//tt:SupportPTZSpace/tt:ContinuousPanTiltVelocitySpace/tt:YRange/tt:Min").trimmed().toInt());
        node->setContinuousPanTiltVelocityYRangeMax(result->getValue("//tt:SupportPTZSpace/tt:ContinuousPanTiltVelocitySpace/tt:YRange/tt:Max").trimmed().toInt());
        node->setContinuousZoomVelocitySpaceUri(result->getValue("//tt:SupportPTZSpace/tt:ContinuousZoomVelocitySpace/tt:URI").trimmed());
        node->setContinuousZoomVelocitySpaceXRangeMin(result->getValue("//tt:SupportPTZSpace/tt:ContinuousZoomVelocitySpace/tt:XRange/tt:Min").toInt());
        node->setContinuousZoomVelocitySpaceXRangeMax(result->getValue("//tt:SupportPTZSpace/tt:ContinuousZoomVelocitySpace/tt:XRange/tt:Max").toInt());
        node->setPanTiltSpeedSpaceUri(result->getValue("//tt:SupportPTZSpace/tt:PanTiltSpeedSpace/tt:URI").trimmed());
        node->setPanTiltSpeedSpaceXRangeMin(result->getValue("//tt:SupportPTZSpace/tt:PanTiltSpeedSpace/XRange/tt:Min").trimmed().toInt());
        node->setPanTiltSpeedSpaceXRangeMax(result->getValue("//tt:SupportPTZSpace/tt:PanTiltSpeedSpace/XRange/tt:Max").trimmed().toInt());
        node->setZoomSpeedSpaceUri(result->getValue("//tt:SupportPTZSpace/tt:ZoomSpeedSpace/tt:URI").trimmed());
        node->setZoomSpeedSpaceXRangeMin(result->getValue("//tt:SupportPTZSpace/tt:ZoomSpeedSpace/tt:Min").trimmed().toInt());
        node->setZoomSpeedSpaceXRangeMax(result->getValue("//tt:SupportPTZSpace/tt:ZoomSpeedSpace/tt:Max").trimmed().toInt());
        node->setMaximumNumberOfPresets(result->getValue("//tt:MaximumNumberOfPresets").trimmed().toInt());
        node->setHomeSupport(result->getValue("//tt:HomeSupported").trimmed() == "true"?true:false);
    }
    delete msg;
    delete result;
}
void RssFeedNode::render(Grantlee::OutputStream* stream, Grantlee::Context* c)
{
  QNetworkAccessManager *mgr = new QNetworkAccessManager(this);
  QUrl url(Grantlee::getSafeString(m_url.resolve(c)));
  QNetworkReply *reply = mgr->get(QNetworkRequest(url));
  QEventLoop eLoop;
  connect( mgr, SIGNAL( finished( QNetworkReply * ) ), &eLoop, SLOT( quit() ) );
  eLoop.exec( QEventLoop::ExcludeUserInputEvents );

  c->push();
  foreach(Grantlee::Node *n, m_childNodes) {
    if (!n->inherits(XmlNamespaceNode::staticMetaObject.className()))
      continue;
    Grantlee::OutputStream _dummy;
    n->render(&_dummy, c);
  }

  QXmlQuery query;
  QByteArray ba = reply->readAll();

  QBuffer buffer;
  buffer.setData(ba);
  buffer.open(QIODevice::ReadOnly);
  query.bindVariable("inputDocument", &buffer);
  QString ns;
  QHash<QString, QVariant> h = c->lookup("_ns").toHash();
  QHash<QString, QVariant>::const_iterator it = h.constBegin();
  const QHash<QString, QVariant>::const_iterator end = h.constEnd();
  for ( ; it != end; ++it ) {
    if (it.key().isEmpty()) {
      ns += QLatin1Literal( "declare default element namespace " ) + QLatin1Literal( " \"" ) + it.value().toString() + QLatin1Literal( "\";\n" );
    } else {
      ns += QLatin1Literal( "declare namespace " ) + it.key() + QLatin1Literal( " = \"" ) + it.value().toString() + QLatin1Literal( "\";\n" );
    }
  }
  query.setQuery(ns + "doc($inputDocument)" + Grantlee::getSafeString(m_query.resolve(c)).get());

  QXmlResultItems result;
  query.evaluateTo(&result);

  QXmlItem item(result.next());
  int count = 0;
  while (!item.isNull()) {
      if (count++ > 20)
        break;
      query.setFocus(item);
      c->push();
      foreach(Grantlee::Node *n, m_childNodes) {
        if (n->inherits(XmlNamespaceNode::staticMetaObject.className()))
          continue;
        c->insert("_q", QVariant::fromValue(query));
        n->render(stream, c);
      }
      c->pop();
      item = result.next();
  }
  c->pop();
}
Presets *PtzManagement::getPresets()
{
    Presets *presets = NULL;
    Message *msg = newMessage();
    QDomElement getPresets = newElement("wsdl:GetPresets");
    QDomElement profileToken = newElement("wsdl:ProfileToken","profile_CIF");
    getPresets.appendChild(profileToken);
    msg->appendToBody(getPresets);
    MessageParser *result = sendMessage(msg);
    if(result != NULL){
        presets = new Presets();
        QXmlQuery *query = result->query();
        QXmlResultItems items;
        QXmlItem item;
        QString value,xml;
        QDomDocument doc;
        QDomNodeList itemNodeList;
        QDomNode node;
        query->setQuery(result->nameSpace()+"doc($inputDocument)//tptz:Preset");
        query->evaluateTo(&items);
        item = items.next();
        while(!item.isNull()){
            query->setFocus(item);
            query->setQuery(result->nameSpace()+".");
            query->evaluateTo(&xml);
            doc.setContent(xml);
            itemNodeList = doc.elementsByTagName("tptz:Preset");
            for(int i=0; i<itemNodeList.size(); i++)
            {
                node = itemNodeList.at(i);
                value = node.toElement().attribute("token");
                presets->setToken(value.trimmed());
            }
            query->setQuery(result->nameSpace()+"./tt:Name/string()");
            query->evaluateTo(&value);
            presets->setName(value.trimmed());
            item = items.next();
        }
    }
    delete msg;
    delete result;
    return presets;
}
void MasterConfiguration::loadWebBrowserStartURL(QXmlQuery& query)
{
    QString queryResult;

    query.setQuery("string(/configuration/webbrowser/@defaultURL)");
    if (query.evaluateTo(&queryResult))
        webBrowserDefaultURL_ = queryResult.remove(QRegExp(TRIM_REGEX));
    if (webBrowserDefaultURL_.isEmpty())
        webBrowserDefaultURL_ = DEFAULT_URL;
}
Exemple #19
0
void tst_QXmlResultItems::evalateWithQueryError() const
{
    /* This query is invalid. */
    const QXmlQuery query;

    QXmlResultItems result;
    query.evaluateTo(&result);

    QVERIFY(result.hasError());
    QVERIFY(result.next().isNull());
}
void MasterConfiguration::loadDockStartDirectory(QXmlQuery& query)
{
    QString queryResult;

    query.setQuery("string(/configuration/dock/@directory)");
    if (query.evaluateTo(&queryResult))
        dockStartDir_ = queryResult.remove(QRegExp(TRIM_REGEX));
    if (dockStartDir_.isEmpty())
        dockStartDir_ = QDir::homePath();

    // WebService server port
    query.setQuery("string(/configuration/webservice/@port)");
    if (query.evaluateTo(&queryResult))
    {
        if (queryResult.isEmpty())
            dcWebServicePort_ = DEFAULT_WEBSERVICE_PORT;
        else
            dcWebServicePort_ = queryResult.toInt();
    }
}
void YandexNarodUploadJob::onDirectoryChecked()
{
	QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
	Q_ASSERT(reply);
	reply->deleteLater();

	const int code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

	if (code == 404) {
		// Directory is not created yet, so be a god
		YandexRequest request(reply->url());
		QNetworkReply *reply = YandexNarodFactory::networkManager()
							   ->sendCustomRequest(request, "MKCOL");
		connect(reply, SIGNAL(finished()), this, SLOT(onDirectoryCreated()));
		return;
	}

	const QString xmlData = QString::fromUtf8(reply->readAll());
	QStringList files;

	QXmlQuery query;
	query.setFocus(xmlData);
	query.setQuery(QLatin1String("declare default element namespace \"DAV:\";"
								 "/multistatus/response/href/text()/string()"));
	query.evaluateTo(&files);

	if (files.contains(QLatin1String("/qutim-filetransfer"))) {
		// Oops... May be check another directories?
		setState(Error);
		setError(NetworkError);
		setErrorString(QT_TR_NOOP("Can't create directory \"/qutim-filetransfer/\""));
		return;
	}

	const QString fileName = YandexNarodUploadJob::fileName();
	QUrl url = reply->url();
	QString path = url.path();
	QString filePath = path + fileName;
	if (files.contains(filePath)) {
		const QString basename = fileName.section(QLatin1Char('.'), 0, 0);
		const QString suffix = fileName.section(QLatin1Char('.'), 1);

		for (int i = 1; ; ++i) {
			filePath = path % basename
					   % QLatin1Char('(') % QString::number(i) % QLatin1Char(')')
					   % (suffix.isEmpty() ? QLatin1Literal("") : QLatin1Literal("."))
					   % suffix;
			if (!files.contains(filePath))
				break;
		}
	}

	uploadFile(reply->url().resolved(QUrl(filePath)));
}
// Notes: my biggest issue with this design is that the different pieces of
//        each rate are pulled out separately. I would prefer one query that
//        pulled them out in sets.
void readRatesUsingXQuery(const QFileInfo file) {
    const QString queryUrl = QString("doc('%1')//rate/%2/string()").arg(file.absoluteFilePath());

    typedef QPair<QStringList &, QString> QueryPair;
    QList<QueryPair> queries;
    QStringList from, to, conversion;
    queries << QueryPair(from, "from") << QueryPair(to, "to") << QueryPair(conversion, "conversion");
    QXmlQuery query;
    foreach (QueryPair pair, queries) {
        query.setQuery(queryUrl.arg(pair.second));
        query.evaluateTo(&pair.first);
    }
void DirListingInfo::setContent(const QString &content)
{
  m_xml = content;
  m_valid = true;

  MessageHandler handler;
  QXmlQuery query;
  query.setMessageHandler(&handler);
  query.setFocus(m_xml);

  QString dir;
  query.setQuery("/DirListingInfo/currentDirectory/string()");
  m_valid = query.evaluateTo(&dir);

  if (!m_valid)
    return;

  m_currentDirectory = dir.trimmed();

  // Get the directories;
  FileInfoXmlReceiver dirReceiver(query.namePool());
  query.setQuery("/DirListingInfo/directories");
  m_valid = query.evaluateTo(&dirReceiver);

  if (!m_valid)
    return;

  m_directories = dirReceiver.fileInfos();

  // Get the files
  FileInfoXmlReceiver fileReceiver(query.namePool());
  query.setQuery("/DirListingInfo/files");
  m_valid = query.evaluateTo(&fileReceiver);

  if (!m_valid)
    return;

  m_files = fileReceiver.fileInfos();
}
Exemple #24
0
ContentPtr State::loadContent_( QXmlQuery& query, const int index ) const
{
    char string[1024];
    sprintf( string, "string(//state/ContentWindow[%i]/URI)", index );
    query.setQuery( string );

    QString qstring;
    if( !query.evaluateTo( &qstring ))
        return ContentPtr();

    const QString uri = qstring.trimmed(); // remove any whitespace
    return ContentFactory::getContent( uri );
}
void writeQuery(QString q, int number)
{
    QXmlQuery query;
    query.setQuery("doc('" + local::testFilePath() +"')" + q);
  	
    QString queryResultFilePath = local::testFolder() + "/test_UniSim_query_" + QString::number(number) + ".xml";
  	QFile file(queryResultFilePath);
    file.open(QIODevice::WriteOnly | QIODevice::Text);
    QCOMPARE(file.error(), QFile::NoError);

  	QXmlSerializer serializer(query, &file);
  	query.evaluateTo(&serializer);
}
Exemple #26
0
void FeedEntryListModel::initFeedEntryList()
{
    QFile queryFile(":/cxReader/xquery/feedEntryList.xq");
    queryFile.open(QIODevice::ReadOnly);

    QXmlQuery query;
    query.setNetworkAccessManager(this->config->manager());
    query.bindVariable("file", QVariant(this->config->baseUrl() + "/feeds/"+this->id));
    query.setQuery(&queryFile);
    this->namePool = query.namePool();
    query.evaluateTo(this);

    queryFile.close();
}
void ShoutcastFetcher::genresAvailable(QIODevice * openInputDevice)
{
	// Using read() putting the content into a QBuffer to workaround
	// some strange hang if passing IO device directly into
	// QXmlQuery object.
	m_genres.clear();
	QByteArray content = openInputDevice->read(maxSize);
	QBuffer buf(&content);
	buf.open(QIODevice::ReadOnly);
	QXmlQuery q;
	q.bindVariable("glist", &buf);
	q.setQuery("for $i in doc($glist)/genrelist/genre/@name return string($i)");
	m_success = q.evaluateTo(&m_genres);
	emit genresAvailable();
}
	bool FotoBilderAccount::IsErrorReply (const QByteArray& content)
	{
		QXmlQuery query;
		query.setFocus (content);

		QString code;
		query.setQuery ("/FBResponse/Error/@code/data(.)");
		if (!query.evaluateTo (&code))
		{
			query.setQuery ("/FBResponse/CreateGalsResponse/Error/@code/data(.)");
			if (!query.evaluateTo (&code))
				return false;
		}
		code = code.simplified ();

		QString string;
		query.setQuery ("/FBResponse/Error/text()");
		if (!query.evaluateTo (&string))
		{
			query.setQuery ("/FBResponse/CreateGalsResponse/Error/text()");
			if (!query.evaluateTo (&string))
				return false;
		}
		string = string.simplified ();

		if (code.isEmpty () || string.isEmpty ())
			return false;

		Proxy_->GetEntityManager ()->HandleEntity (Util::MakeNotification ("Blasq DeathNote",
				tr ("%1 (original message: %2)")
						.arg (LocalizedErrorFromCode (code.toInt ()))
						.arg (string),
				Priority::PWarning_));

		return true;
	}
Exemple #29
0
QString Server::commandForPlayer(QString aPlayerName)
{
    mCommands->reset();
    QXmlQuery* xmlQuery = new QXmlQuery;
    xmlQuery->bindVariable(KXmlFileName,mCommands);

    xmlQuery->bindVariable(KPlayer,QVariant(aPlayerName));
    xmlQuery->setQuery(KXqReadCommandForPlayer);
    QString result = QString();
    if(xmlQuery->isValid())
    {
        xmlQuery->evaluateTo(&result);
    }
    delete xmlQuery;
    return result;
}
QString runXmlQuerry(QFile *file, QString querry)
{
    F_TRACE;
    QXmlQuery query;
    QString res;

    file->seek(0);
    query.setFocus(file);
    query.setQuery(querry);
    if ( ! query.isValid())
    {
        qDebug() << "Invalid querry" << querry;
    }

    query.evaluateTo(&res);
    return res.simplified();
}