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;
}
Exemple #2
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 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.";


}
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 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());
    }
}
Exemple #6
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();
    }  
}
Exemple #7
0
/*!
  Binds the result of the query \a query, to a variable by name \a name.

  Evaluation of \a query will be commenced when this function is called.

  If \a query is invalid, behavior is undefined. \a query will be copied.

  \since 4.5
  \sa isValid()
 */
void QXmlQuery::bindVariable(const QXmlName &name, const QXmlQuery &query)
{
    Q_ASSERT_X(query.isValid(), Q_FUNC_INFO, "The query being bound must be valid.");

    const QPatternist::VariableLoader::Ptr vl(d->variableLoader());
    const QVariant variant(QVariant::fromValue(query));

    if(vl->invalidationRequired(name, variant))
        d->recompileRequired();

    vl->addBinding(name, variant);
}
Exemple #8
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();
}
Exemple #10
0
void tst_QXmlSerializer::serializationError() const
{
    QFETCH(QString, queryString);
    QXmlQuery query;
    MessageSilencer silencer;
    query.setMessageHandler(&silencer);

    query.setQuery(queryString);

    QByteArray output;
    QBuffer buffer(&output);
    QVERIFY(buffer.open(QIODevice::WriteOnly));
    QVERIFY(query.isValid());

    QXmlSerializer serializer(query, &buffer);

    QEXPECT_FAIL("Two top elements", "Bug, this is not checked for", Continue);
    QVERIFY(!query.evaluateTo(&serializer));
}
Exemple #11
0
std::vector<SimXmlElement> SimXmlDoc::getElements(const std::string& elementName) const
{
  std::vector<SimXmlElement> result;

  if (isNull()){
    return result;
  }

  QString queryString = simQuery("/SimModel/" + elementName);

  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()) {

    QString junk;

    QXmlResultItems items;

    query.evaluateTo(&items);

    QXmlItem item(items.next());

    while (!item.isNull()) {

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

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

      result.push_back(SimXmlElement(impl, *this));

      // get next item
      item = items.next();
    }
  }

  return result;
}
bool SeLogerHousingDriver::parseSearchRequestData( const QByteArray& data, Announcement::List& announcements, RequestResultProperties* properties ) const
{
    // before parsing the announce, we convert the xml to a standard simple one using xquery
    const QString xpath = xPathQuery();
    QXmlQuery query;
    QString xml;
    
    if ( !query.setFocus( QString::fromUtf8( data ) ) ) {
        if ( properties ) {
            properties->error = tr( "%s: Can't set focus" ).arg( Q_FUNC_INFO );
        }
        
        qWarning( "%s: 1", Q_FUNC_INFO );
        return false;
    }

    query.setQuery( xpath, QUrl( d->webServiceUrl() ) );
    
    if ( !query.isValid() ) {
        if ( properties ) {
            properties->error = tr( "%s: Invalid query" ).arg( Q_FUNC_INFO );
        }
        
        qWarning( "%s: 2", Q_FUNC_INFO );
        return false;
    }
    
    if ( !query.evaluateTo( &xml ) ) {
        if ( properties ) {
            properties->error = tr( "%s: Can't evaluateTo" ).arg( Q_FUNC_INFO );
        }
        
        qWarning( "%s: 3", Q_FUNC_INFO );
        return false;
    }
    
    return parseStandardDomDocument( xml, announcements, properties );
}
void TestSimulationMaker::testXmlQuery()
{
	writeQuery("/simulation/model", 1);
	writeQuery("/simulation//model[@type='LifeCycle']", 2);
	writeQuery("/simulation/model[@name='wasp']/model[@name='egg']/parameter[@name='k']", 3);
	writeQuery("/simulation/output[@name='butterflyOutput']/"
	               "presentation[@name='butterflyPlot']/xyvariables[@name='butterflyXY']", 4);
	
	QXmlQuery query;
	query.setQuery("<e/>, 1, 'two'");
	QXmlResultItems result;
	
	if (query.isValid()) {
		query.evaluateTo(&result);
		QXmlItem item(result.next());
		while (!item.isNull()) {
			// use item
			item = result.next();
		}
		if (result.hasError())
	 /* Runtime error! */;
	}
}
Exemple #14
0
void atlasMap::sHandleAtlas()
{
  _map->clear();

  if (_atlas->text().isEmpty())
    return;

  if (DEBUG)
    qDebug("atlasMap::sHandleAtlas() entered with %s and %s",
           qPrintable(_atlas->text()), qPrintable(_defaultDir));

  if (! _defaultDir.isEmpty() && _atlas->text().startsWith(_defaultDir))
    _atlas->setText(_atlas->text().remove(0, _defaultDir.length() + 1));

  QFile atlasfile;
  if (QFile::exists(_atlas->text()))
    atlasfile.setFileName(_atlas->text());
  else if (QFile::exists(_defaultDir + QDir::separator() + _atlas->text()))
    atlasfile.setFileName(_defaultDir + QDir::separator() + _atlas->text());
  else
  {
    QMessageBox::warning(this, tr("Could not find Atlas"),
                         tr("<p>Could not find the Atlas file to open to look "
                            "for CSV import Maps."));
    return;
  }

  if (! atlasfile.open(QIODevice::ReadOnly))
  {
    QMessageBox::critical(this, tr("Could not open Atlas"),
                          tr("<p>Could not open the Atlas file %1 (error %2).")
                          .arg(atlasfile.fileName(), atlasfile.errorString()));
    return;
  }

  QXmlQuery mapq;
  mapq.setMessageHandler(_msghandler);

  if (! mapq.setFocus(&atlasfile))
  {
    QMessageBox::critical(this, tr("No Focus"),
                          tr("<p>Could not set focus on the Atlas %1")
                          .arg(atlasfile.fileName()));
    return;
  }

  // string() at the end tells the query to generate a sequence of values
  mapq.setQuery("/CSVAtlas/CSVMap/Name/text()/string()");
  if (! mapq.isValid())
  {
    QMessageBox::critical(this, tr("Invalid Query"),
                          tr("<p>The query is not valid for some reason"));
    return;
  }

  QStringList maplist;
  if (! mapq.evaluateTo(&maplist))
  {
    QMessageBox::warning(this, tr("No Maps"),
                         tr("<p>Could not find any Maps in the Atlas %1")
                         .arg(atlasfile.fileName()));
    return;
  }
  else
    for (int i = 0; i < maplist.size(); i++)
      _map->append(i, maplist.at(i));
}
Exemple #15
0
bool qPBReaderEpub::RetrieveOEB(QStringList & olsOpf)
{
   TRSCOPE(epub, "qPBReaderEpub::RetrieveOEB");

   // try settings

   bool b = _pSettings->GetOpf(olsOpf);

   // or analyze container

   if (b && !olsOpf.size())
   {
      TRACE << "Reading container" << endl;

      // create query from file

      QXmlQuery qry;
      b = qry.setFocus(QUrl(_sTempDir + "/" CONTAINER));
      TRACE << "qry.setFocus(...): " << b << endl;

      // prepare query
      // retrieve full-path from container/rootfiles/root elements where media-type=OEBPS_TYPE

      if (b)
      {
         qry.setQuery("declare default element namespace \"" CONTAINERNS "\";"
                      "/container/rootfiles/rootfile[lower-case(@media-type)='" OEBPS_TYPE
                      "']/@full-path/string()");
         b = qry.isValid();
         TRACE << "qry.isValid(): " << b << endl;
      }

      // execute it

      QStringList lsTmp;

      if (b)
      {
         b = qry.evaluateTo(&lsTmp) && lsTmp.size() > 0;
         TRACE << "evaluation " << b << " nbopf=" << lsTmp.size() << endl;
      }

      // get and make results persist

      if (b)
      {
         _pSettings->SaveOpf(lsTmp);
         olsOpf = lsTmp;
      }
   }

   if (!b)
   {
      olsOpf.clear();
   }

   else if (TRACEON)
   {
      for (int idx = 0; idx < olsOpf.size(); idx++)
      {
         TRACE << ENC(olsOpf[idx]) << endl;
      }
   }

   return b;
}
Exemple #16
0
InvoiceData XmlDataLayer::invoiceSelectData(QString name, int type) {
	qDebug() << __FILE__ << __LINE__ << __FUNCTION__;

	InvoiceData o_invData;

	QDomDocument doc(sett().getInoiveDocName());
	QDomElement root;
	QDomElement nabywca;
	QDomElement product;
	QString fName = name;

	QFile file(sett().getInvoicesDir() + fName);
	if (!file.open(QIODevice::ReadOnly)) {
		qDebug("file doesn't exist");
		return o_invData;
	} else {
		QTextStream stream(&file);
		if (!doc.setContent(stream.readAll())) {
			file.close();
			return o_invData;
		}
	}

	root = doc.documentElement();
	o_invData.frNr = root.attribute("no");
	o_invData.sellingDate = QDate::fromString(root.attribute("sellingDate"), sett().getDateFormat());
	o_invData.productDate = QDate::fromString(root.attribute("issueDate"),	sett().getDateFormat());

	QDomNode tmp;
	tmp = root.firstChild();
	tmp = tmp.toElement().nextSibling(); // nabywca
	nabywca = tmp.toElement();
	o_invData.customer = nabywca.attribute("name") + "," + nabywca.attribute(
			"city") + "," + nabywca.attribute("street") + "," + QObject::trUtf8("NIP: ")
			+ nabywca.attribute("tic");
			/* not required
			+ ", " + nabywca.attribute("account")
			+ ", " + nabywca.attribute("phone") + ", " + nabywca.attribute(
			"email") + ", " + nabywca.attribute("www")) */
	// kontrName->setCursorPosition(1);

	tmp = tmp.toElement().nextSibling(); // product
	product = tmp.toElement();

	o_invData.discount = product.attribute("discount").toInt();



	tmp = tmp.toElement().nextSibling();
	QDomElement additional = tmp.toElement();
	o_invData.additText = additional.attribute("text");
	int curPayment = sett().value("payments").toString().split("|").indexOf(additional.attribute("paymentType"));

	if (curPayment == sett().value("payments").toString().split("|").count() - 1) {
	    // disconnect(platCombo, SIGNAL(currentIndexChanged (QString)), this, SLOT(payTextChanged(QString)));

		// platCombo->setCurrentIndex(curPayment);

		// ; //  = new CustomPaymData();
		o_invData.custPaym.payment1 = additional.attribute("payment1");
		o_invData.custPaym.amount1  = additional.attribute("amount1").toDouble();
		o_invData.custPaym.date1    = QDate::fromString(additional.attribute("liabDate1"), sett().getDateFormat());
		o_invData.custPaym.payment2 = additional.attribute("payment2");
		o_invData.custPaym.amount2  = additional.attribute("amount2").toDouble();
		o_invData.custPaym.date2    = QDate::fromString(additional.attribute("liabDate2"), sett().getDateFormat());

		// connect(platCombo, SIGNAL(currentIndexChanged (QString)), this, SLOT(payTextChanged(QString)));
	} else {
		// platCombo->setCurrentIndex(curPayment);
	}

	o_invData.liabDate = QDate::fromString(additional.attribute("liabDate"), sett().getDateFormat());
	int curCurrency = sett().value("waluty").toString().split("|").indexOf(additional.attribute("currency"));
	o_invData.currencyTypeId = curCurrency;


    QFile db(sett().getInvoicesDir() + name);

    if (!db.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qDebug("file doesn't exist");
         return o_invData;
    }

    QXmlQuery query;
    QString res;

    query.setFocus(&db);
    query.setQuery("//product");
    if ( ! query.isValid())
        return o_invData;

    query.evaluateTo(&res);
    db.close();

    QDomDocument productsDOMDocument;
    productsDOMDocument.setContent("" + res + "");
    QDomNodeList products = productsDOMDocument.elementsByTagName("product");

    for (int i = 0; i < products.count(); i++) {
        QDomElement product = products.at(i).toElement();
        o_invData.products[i] =
                ProductData(product.attribute("id").toInt(),
                            product.attribute("name"),
                            product.attribute("code"),
                            product.attribute("PKWiU"),
                            product.attribute("quantity").toDouble(),
                            product.attribute("quantityType"),
                            product.attribute("discount").toDouble(),
                            product.attribute("price").toDouble(),
                            product.attribute("nett").toDouble(),
                            product.attribute("vatBucket").toInt(),
                            product.attribute("gross").toDouble(),
                            additional.attribute("currency"));
    }
    return o_invData;
}
Exemple #17
0
bool AircraftData::import(QProgressDialog &progress, MainObject *mainObject){

	int c = 0;
	int found = 0;

	progress.setRange(0, 2000);
	progress.setWindowTitle("Scanning Aircraft Directories");
	progress.show();
	progress.repaint();

	//= Cache File
	QFile cacheFile( mainObject->data_file("aircraft.txt") );
	if(!cacheFile.open(QIODevice::WriteOnly | QIODevice::Text)){
		//qDebug() << "TODO Open error cachce file=";
		return true;
	}



	QTextStream out(&cacheFile);

	//= Get files Entries from Aircaft/ directory
	QDir aircraftDir( mainObject->X->aircraft_path() );
	aircraftDir.setFilter( QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot);

	QStringList entries = aircraftDir.entryList();
	progress.setRange(0, entries.size() + 20);

	for( QStringList::ConstIterator entry=entries.begin(); entry!=entries.end(); ++entry ){

		// Filter out default dir names, should be a QDir name filter?
		if (*entry != "Instruments" &&  *entry != "Instruments-3d" && *entry != "Generic") {

			progress.setValue(c);
			progress.setLabelText(*entry);
			progress.repaint();

			//** get the List of *-set.xml files in dir
			QDir dir( mainObject->X->aircraft_path(*entry) );
			QStringList filters;
			filters << "*-set.xml";
			QStringList list_xml = dir.entryList(filters);

			if(list_xml.count() > 0){ // << Scan MOdels
				QString directory;
				QString description;
				QString author;
				QString fdm;
				QString xml_file;
				QString aero;

				//** Add Path Node
				directory = QString(*entry);
				//** Add Models
				for (int i = 0; i < list_xml.size(); ++i){

					xml_file = QString(list_xml.at(i));
					aero = QString(xml_file);
					aero.chop(8);

					//*=parse the Xml file - f&*& long winded
					QString file_path =  mainObject->X->aircraft_path(*entry);
					file_path.append("/");
					file_path.append(list_xml.at(i));
					QFile xmlFile( file_path);
					if (xmlFile.open(QIODevice::ReadOnly | QIODevice::Text)){

						/* The file content is converted to UTF-8.
							 Some files are Windows, encoding and throw error with QxmlQuery etc
							 Its a hack and don't quite understand whats happening.. said pedro
						*/
						QString xmlString = QString(xmlFile.readAll()).toUtf8();

						QXmlQuery query;
						query.setFocus(xmlString);
						//query.setFocus(&xmlFile); << Because file is not QTF8 using sting instead
						query.setQuery("PropertyList/sim");
						if (query.isValid()){

							QString res;
							query.evaluateTo(&res);
							xmlFile.close();

							QDomDocument dom;
							dom.setContent("" + res + "");
							QDomNodeList nodes = dom.elementsByTagName("sim");

							QDomNode n = nodes.at(0);
							description = n.firstChildElement("description").text();
							author = n.firstChildElement("author").text().trimmed().replace(("\n"),"");
							fdm = n.firstChildElement("flight-model").text();
						} /* !query.isValid() */
					} /*  xmlFile.open() */

					QStringList lines;
					lines  << directory << aero << xml_file << description << fdm << author << file_path;
					out << lines.join("\t") << "\n";

					found++;

					if(progress.wasCanceled()){
						//qDebug() << "Progress cancelled!";
						progress.hide();
						return true;
					}
					c++;
				}

			} /* list_xml.count() > 0 */
		} /* entry != INstruments etc */
	} /* loop entries.() */

	cacheFile.close();
	return false;
}
Exemple #18
0
checkForUpdates::checkForUpdates(QWidget* parent, Qt::WFlags fl)
    : XWidget(parent, fl)
{
  setupUi(this);

  QUrl updatequrl("http://updates.xtuple.com/checkForUpdates.php");
  updatequrl.addQueryItem("xtuple", _Version);

  XSqlQuery versions;
  versions.exec("SELECT version() AS pgver,"
                "       fetchMetricText('ServerVersion') AS dbver,"
                "       fetchMetricText('Application') AS dbprod;");
  if(versions.first())
  {
    updatequrl.addQueryItem("postgres", versions.value("pgver").toString());
    updatequrl.addQueryItem(versions.value("dbprod").toString(),
                            versions.value("dbver").toString());
  }
  else if (versions.lastError().type() != QSqlError::NoError)
    systemError(this, versions.lastError().text(), __FILE__, __LINE__);
  // no return - let's learn as much as we can

#ifdef Q_WS_MACX
  QString helpdir = QApplication::applicationDirPath() +
                    "/../Resources/helpXTupleGUIClient";
#else
  QString helpdir = QApplication::applicationDirPath() + "helpXTupleGUIClient";
#endif
  QFile helpfile(helpdir + "/index.html");
  QString helpver;
  if (helpfile.exists())
  {
    if (helpfile.open(QIODevice::ReadOnly))
    {
      QXmlQuery helpverq;
      if (helpverq.setFocus(&helpfile))
      {
        helpverq.setQuery("/descendant::p[attribute::class='releaseinfo']/text()/string()");
        if (helpverq.isValid())
        {
          QStringList helpverlist;
          if (helpverq.evaluateTo(&helpverlist) && ! helpverlist.isEmpty())
            helpver = helpverlist.at(0);
          else if (DEBUG)
            qDebug("Could not find the releaseinfo in %s",
                     qPrintable(helpfile.fileName()));
        }
        else if (DEBUG)
          qDebug("The helpver query is not valid for some reason");
      }
      else if (DEBUG)
        qDebug("Could not set focus on the help file %s",
                 qPrintable(helpfile.fileName()));
    }
    else if (DEBUG)
      qDebug("Found the help file %s but could not open it: %s",
               qPrintable(helpfile.fileName()),
               qPrintable(helpfile.errorString()));
  }
  else if (DEBUG)
    qDebug("The help file %s does not exist", qPrintable(helpfile.fileName()));
  updatequrl.addQueryItem("xTupleHelp", helpver);

  QStringList context;
  context << "xTuple" << "openrpt" << "reports"; // duplicated from main.cpp!

  versions.exec("SELECT pkghead_name, pkghead_version"
                "  FROM pkghead"
                " WHERE packageisenabled(pkghead_id);");
  while(versions.next())
  {
    updatequrl.addQueryItem(versions.value("pkghead_name").toString(),
                            versions.value("pkghead_version").toString());
    context << versions.value("pkghead_name").toString();
  }
  if (versions.lastError().type() != QSqlError::NoError)
    systemError(this, versions.lastError().text(), __FILE__, __LINE__);
  // no return - let's learn as much as we can

  // get all of the locales on the system
  versions.exec("SELECT DISTINCT lang_abbr2, country_abbr"
                "  FROM locale"
                "  JOIN lang ON (locale_lang_id=lang_id)"
                "  LEFT OUTER JOIN country ON (locale_country_id=country_id)"
                " ORDER BY lang_abbr2, country_abbr;");
  QStringList locale;
  while(versions.next())
  {
    QString tmp = versions.value("lang_abbr2").toString();
    if (! versions.value("country_abbr").isNull())
      tmp += "_" + versions.value("country_abbr").toString();
    locale.append(tmp);
  }
  if (! locale.isEmpty())
    updatequrl.addQueryItem("locales", locale.join(","));
  else if(versions.lastError().type() != QSqlError::NoError)
    systemError(this, versions.lastError().text(), __FILE__, __LINE__);

  // maybe i want to update just _my_ translation file
  versions.exec("SELECT lang_abbr2, country_abbr"
                "  FROM locale"
                "  JOIN usr ON (locale_id=usr_locale_id)"
                "  JOIN lang ON (locale_lang_id=lang_id)"
                "  LEFT OUTER JOIN country ON (locale_country_id=country_id)"
                " WHERE (usr_username=getEffectiveXtUser());");
  if (versions.first())
  {
    QString tmp = versions.value("lang_abbr2").toString();
    if (! versions.value("country_abbr").isNull())
      tmp += "_" + versions.value("country_abbr").toString();
    updatequrl.addQueryItem("mylocale", tmp);
  }
  else if(versions.lastError().type() != QSqlError::NoError)
    systemError(this, versions.lastError().text(), __FILE__, __LINE__);

  QString qmparam = "qm.%1.%2";
  for (int l = 0; l < locale.length(); l++)
  {
    for (int c = 0; c < context.length(); c++)
    {
      QString version("");
      QString tf = translationFile(locale.at(l), context.at(c), version);
      updatequrl.addQueryItem(qmparam.arg(context.at(c), locale.at(l)), version);
    }
  }

  if (DEBUG)
    qDebug("checkForUpdates::checkForUpdates() sending %s",
           updatequrl.toEncoded().data());

  _view->load(updatequrl);
}
QString F520xmlserializer::avarageQuery(F520Status *f520, QString month, SysError &sysErr) {
    QXmlQuery query;
    QString res;
    QString defaultRes;
    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 + "[@" + 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);

    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(&defaultRes);

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

    xml.close();

    QDomDocument avarageWatt;
    res.prepend("<" +DAYS +">\n");
    res.append("<\\" + DAYS + ">");
    avarageWatt.setContent("" + res + "");
    QDomNodeList entryNodes = avarageWatt.elementsByTagName(DAY);

    QDomDocument defaultWatt;
    defaultWatt.setContent("" + defaultRes + "");
    QDomNodeList entryDefaultNodes = defaultWatt.elementsByTagName(DAY);


    QList<float> avarage;

    qDebug() << "F520xmlserializer::query avarageWatt: " << defaultWatt.toString();
    int i;
    for (i = 0; i < getDayOfMonth(month.toInt()); i++) {
        QDomElement node;
        if(i < entryNodes.count())
            node = entryNodes.at(i).toElement();
        else
            node = entryDefaultNodes.at(0).toElement();

        QStringList tmpList = node.attribute(WATT).split('.');
        if (tmpList.length() != 24) {
            sysErr = SysError(SysError::F520_RESOURCE_ERROR, "F520 Resouce Error");
            return "";
        }
        for (int index = 0; index < tmpList.length(); index++) {
            if (avarage.length() <= index) {
                avarage.append(tmpList.at(index).toFloat()  / getDayOfMonth(month.toInt()));
            } else {
                avarage[index] += (tmpList.at(index).toFloat() / getDayOfMonth(month.toInt()));
            }
        }
    }

    QString rtn;
    foreach (int element, avarage) {
        rtn += QString::number(element) + '.';
    }
Exemple #20
0
int main(int argc, char **argv)
{
    enum ExitCode
    {
        /**
         * We start from 2, because QApplicationArgumentParser
         * uses 1.
         */
        QueryFailure = 2,
        StdOutFailure
    };

    const QCoreApplication app(argc, argv);
    QCoreApplication::setApplicationName(QLatin1String("xmlpatterns"));

    PatternistApplicationParser parser(argc, argv);
    parser.setApplicationDescription(QLatin1String("A tool for running XQuery queries."));
    parser.setApplicationVersion(QLatin1String("0.1"));

    /* Is there a better way to do this? Probably not, but if the class becomes public, we probably
     * want a helper function that wraps this hack. */
    const int parameterType = qVariantFromValue(Parameter()).userType();
    const int outputType = qVariantFromValue(static_cast<QIODevice *>(0)).userType();

    QApplicationArgument param(QLatin1String("param"),
                               QXmlPatternistCLI::tr("Binds an external variable. The value is directly available using the variable reference: $name."),
                               parameterType);
    param.setMaximumOccurrence(-1);
    parser.addArgument(param);

    const QApplicationArgument noformat(QLatin1String("no-format"),
                                        QXmlPatternistCLI::tr("By default output is formatted for readability. When specified, strict serialization is performed."));
    parser.addArgument(noformat);

    const QApplicationArgument isURI(QLatin1String("is-uri"),
                                     QXmlPatternistCLI::tr("If specified, the filename is interpreted as a URI instead of a local filename."));
    parser.addArgument(isURI);

    /* The temporary object is required to compile with g++ 3.3. */
    QApplicationArgument queryURI = QApplicationArgument(QString(), /* Nameless. */
                                                         QXmlPatternistCLI::tr("A local filename pointing to the query to run. "
                                                                               "If the name ends with .xq it's assumed "
                                                                               "to be an XQuery query. (In other cases too, but "
                                                                               "that interpretation may change in a future release of Qt.)"),
                                  QVariant::String);
    queryURI.setMinimumOccurrence(1);
    parser.addArgument(queryURI);

    QApplicationArgument output(QLatin1String("output"),
                                QXmlPatternistCLI::tr("A local file to which the output should be written. The file is overwritten, or if not exist, created. If absent, stdout is used."),
                                outputType);
    parser.addArgument(output);

    if(!parser.parse())
        return parser.exitCode();

    QXmlQuery query;

    /* Bind external variables. */
    {
        const QVariantList parameters(parser.values(param));
        const int len = parameters.count();

        for(int i = 0; i < len; ++i)
        {
            const Parameter p(qVariantValue<Parameter>(parameters.at(i)));
            query.bindVariable(p.first, QXmlItem(p.second));
        }
    }

    /* The final preparations and execute the query. */
    QPatternist::ColoringMessageHandler messageHandler;
    query.setMessageHandler(&messageHandler);

    /* Get the query URI. */
    QUrl userURI;
    {
        const QString stringURI(parser.value(queryURI).toString());

        if(parser.has(isURI))
            userURI = QUrl::fromEncoded(stringURI.toLatin1());
        else
            userURI = QUrl::fromLocalFile(stringURI);
    }
    const QUrl effectiveURI(QUrl::fromLocalFile(QDir::current().absolutePath() + QLatin1Char('/')).resolved(userURI));

    Q_ASSERT_X(userURI.isValid(), Q_FUNC_INFO,
               "QApplicationArgumentParser should promise us this.");

    query.setQuery(effectiveURI);

    QIODevice *const outDevice = qVariantValue<QIODevice *>(parser.value(output));
    Q_ASSERT(outDevice);
    Q_ASSERT(outDevice->isWritable());

    if(query.isValid())
    {
        QAbstractXmlReceiver *receiver = 0;

        if(parser.has(noformat))
            receiver = new QXmlSerializer(query, outDevice);
        else
            receiver = new QXmlFormatter(query, outDevice);

        const bool success = query.evaluateTo(receiver);
        delete outDevice;
        delete receiver;

        if(success)
            return parser.exitCode();
        else
            return QueryFailure;
    }
    else
    {
        delete outDevice;
        return QueryFailure;
    }
}