Example #1
0
void DataManagerImpl::parseXml(QDomNode& dataManagerNode, QString rootPath)
{
	// look in the toolmanager, for backwards compatibility (2014-02-21)
	QDomNode toolManagerNode = dataManagerNode.parentNode().namedItem("toolManager");

	QDomNode registrationHistory = dataManagerNode.namedItem("registrationHistory");
	if (registrationHistory.isNull())
		registrationHistory = toolManagerNode.namedItem("registrationHistory");
	m_rMpr_History->parseXml(registrationHistory);

	QDomNode landmarksNode = dataManagerNode.namedItem("landmarkprops");
	QDomElement landmarkNode = landmarksNode.firstChildElement("landmarkprop");
	for (; !landmarkNode.isNull(); landmarkNode = landmarkNode.nextSiblingElement("landmarkprop"))
	{
		LandmarkProperty landmarkProp;
		landmarkProp.parseXml(landmarkNode);
		mLandmarkProperties[landmarkProp.getUid()] = landmarkProp;
		//std::cout << "Loaded landmarkprop with name: " << landmarkProp.getName() << std::endl;
		emit landmarkPropertiesChanged();
	}

	QDomNode patientLandmarksNode = dataManagerNode.namedItem("landmarks");
	if (patientLandmarksNode.isNull())
		patientLandmarksNode = toolManagerNode.namedItem("landmarks");
	mPatientLandmarks->parseXml(patientLandmarksNode);

	// All images must be created from the DataManager, so the image nodes are parsed here
	std::map<DataPtr, QDomNode> datanodes;

	QDomNode child = dataManagerNode.firstChild();
	for (; !child.isNull(); child = child.nextSibling())
	{
		if (child.nodeName() == "data")
		{
			DataPtr data = this->loadData(child.toElement(), rootPath);
			if (data)
				datanodes[data] = child.toElement();
		}
	}

	// parse xml data separately: we want to first load all data
	// because there might be interdependencies (cx::DistanceMetric)
	for (std::map<DataPtr, QDomNode>::iterator iter = datanodes.begin(); iter != datanodes.end(); ++iter)
	{
		iter->first->parseXml(iter->second);
	}

	emit dataAddedOrRemoved();

	//we need to make sure all images are loaded before we try to set an active image
	child = dataManagerNode.firstChild();
	while (!child.isNull())
	{
		if (child.toElement().tagName() == "center")
		{
			const QString centerString = child.toElement().text();
			if (!centerString.isEmpty())
			{
				Vector3D center = Vector3D::fromString(centerString);
				this->setCenter(center);
			}
		}
		child = child.nextSibling();
	}
}
Example #2
0
/*
 * Parses the raw XML contents from the Distro RSS news feed
 * Creates and returns a string containing a HTML code with latest 10 news
 */
QString MainWindow::parseDistroNews()
{
  QString html;

  LinuxDistro distro = UnixCommand::getLinuxDistro();
  if (distro == ectn_ARCHLINUX || distro == ectn_ARCHBANGLINUX)
  {
    html = "<p align=\"center\"><h2>" + StrConstants::getArchLinuxNews() + "</h2></p><ul>";
  }
  else if (distro == ectn_CHAKRA)
  {
    html = "<p align=\"center\"><h2>" + StrConstants::getChakraNews() + "</h2></p><ul>";
  }
  else if (distro == ectn_MANJAROLINUX)
  {
    html = "<p align=\"center\"><h2>" + StrConstants::getManjaroLinuxNews() + "</h2></p><ul>";
  }

  QString lastBuildDate;
  QString rssPath = QDir::homePath() + QDir::separator() + ".config/octopi/distro_rss.xml";
  QDomDocument doc("rss");
  int itemCounter=0;

  QFile file(rssPath);
  if (!file.open(QIODevice::ReadOnly)) return "";
  if (!doc.setContent(&file)) {
      file.close();
      return "";
  }
  file.close();

  QDomElement docElem = doc.documentElement(); //This is rss
  QDomNode n = docElem.firstChild(); //This is channel
  n = n.firstChild();

  while(!n.isNull()) {
    QDomElement e = n.toElement();

    if(!e.isNull())
    {
      if (e.tagName() == "lastBuildDate")
      {
        lastBuildDate = e.text();
      }
      else if(e.tagName() == "item")
      {
        //Let's iterate over the 10 lastest "item" news
        if (itemCounter == 10) break;

        QDomNode text = e.firstChild();

        QString itemTitle;
        QString itemLink;
        QString itemDescription;
        QString itemPubDate;

        while(!text.isNull())
        {
          QDomElement eText = text.toElement();

          if(!eText.isNull())
          {
            if (eText.tagName() == "title")
            {
              itemTitle = "<h3>" + eText.text() + "</h3>";
            }
            else if (eText.tagName() == "link")
            {
              itemLink = Package::makeURLClickable(eText.text());
              if (UnixCommand::getLinuxDistro() == ectn_MANJAROLINUX) itemLink += "<br>";
            }
            else if (eText.tagName() == "description")
            {
              itemDescription = eText.text();
              //itemDescription = itemDescription.remove(QRegExp("\\n"));
              itemDescription += "<br>";
            }
            else if (eText.tagName() == "pubDate")
            {
              itemPubDate = eText.text();
              itemPubDate = itemPubDate.remove(QRegExp("\\n"));
              int pos = itemPubDate.indexOf("+");

              if (pos > -1)
              {
                itemPubDate = itemPubDate.mid(0, pos-1).trimmed() + "<br>";
              }
            }
          }

          text = text.nextSibling();
        }

        html += "<li><p>" + itemTitle + " " + itemPubDate + "<br>" + itemLink + itemDescription + "</p></li>";
        itemCounter++;
      }
    }

    n = n.nextSibling();
  }

  html += "</ul>";
  return html;
}
Example #3
0
/**** BEE ****/
FileList BEE::readSigset(const File &sigset, bool ignoreMetadata)
{
    FileList fileList;

#ifndef BR_EMBEDDED
    QDomDocument doc(sigset.fileName());
    QFile file(sigset.resolved());
    bool success;
    success = file.open(QIODevice::ReadOnly); if (!success) qFatal("Unable to open %s for reading.", qPrintable(sigset));
    success = doc.setContent(&file);

    file.close();

    if (!success) {
        qWarning("Unable to parse %s.", qPrintable(sigset));
        return fileList;
    }

    QDomElement docElem = doc.documentElement();
    if (docElem.nodeName() != "biometric-signature-set")
        return fileList;

    QDomNode subject = docElem.firstChild();
    while (!subject.isNull()) {
        // Looping through subjects
        QDomNode fileNode = subject.firstChild();
        QDomElement d = subject.toElement();
        QString name = d.attribute("name");
        while (!fileNode.isNull()) {
            // Looping through files
            File file("", name);

            QDomElement e = fileNode.toElement();
            QDomNamedNodeMap attributes = e.attributes();
            for (int i=0; i<attributes.length(); i++) {
                const QString key = attributes.item(i).nodeName();
                const QString value = attributes.item(i).nodeValue();
                if      (key == "file-name") file.name = value;
                else if (!ignoreMetadata)    file.set(key, value);
            }

            // add bounding boxes, if they exist (will be child elements of <presentation>)
            if (fileNode.hasChildNodes()) {
                QList<QRectF> rects;
                QDomNodeList bboxes = fileNode.childNodes();
                for (int i=0; i<bboxes.length(); i++) {
                    QDomElement bbox = bboxes.at(i).toElement();
                    qreal x = bbox.attribute("x").toDouble();
                    qreal y = bbox.attribute("y").toDouble();
                    qreal width = bbox.attribute("width").toDouble();
                    qreal height = bbox.attribute("height").toDouble();
                    rects += QRectF(x, y, width, height);
                }
                file.setRects(rects);
            }

            if (file.name.isEmpty()) qFatal("Missing file-name in %s.", qPrintable(sigset));
            fileList.append(file);

            fileNode = fileNode.nextSibling();
        }
        subject = subject.nextSibling();
    }
#else // BR_EMBEDDED
    (void) sigset;
    (void) ignoreMetadata;
#endif // BR_EMBEDDED

    return fileList;
}
Example #4
0
bool Upload::adjustNewstuffFile(const Package &package)
{
    if (m_xml.isNull()) {
        QTemporaryFile tempFile(QDir::tempPath() + "/monav-maps-XXXXXX.xml");
        tempFile.setAutoRemove(false);
        tempFile.open();
        QString monavFilename = tempFile.fileName();
        tempFile.close();
        QProcess wget;
        QStringList const arguments = QStringList() << "http://files.kde.org/marble/newstuff/maps-monav.xml" << "-O" << monavFilename;
        wget.start("wget", arguments);
        wget.waitForFinished(1000 * 60 * 60 * 12); // wait up to 12 hours for download to complete
        if (wget.exitStatus() != QProcess::NormalExit || wget.exitCode() != 0) {
            qDebug() << "Failed to download newstuff file from files.kde.org";
            Logger::instance().setStatus(package.region.id(), package.region.name(), "error", "Failed to sync newstuff file: " + wget.readAllStandardError());
            return false;
        }

        QFile file(monavFilename);
        if (!file.open(QFile::ReadOnly)) {
            qDebug() << "Failed to open newstuff file" << monavFilename;
            Logger::instance().setStatus(package.region.id(), package.region.name(), "error", "Failed to open newstuff file.");
            return false;
        }

        if ( !m_xml.setContent( &file ) ) {
            qDebug() << "Cannot parse newstuff xml file.";
            Logger::instance().setStatus(package.region.id(), package.region.name(), "error", "Failed to parse newstuff .xml file.");
            return false;
        }

        QFile::remove(monavFilename);
    }

    QDomElement root = m_xml.documentElement();
    QDomNodeList regions = root.elementsByTagName( "stuff" );
    for ( unsigned int i = 0; i < regions.length(); ++i ) {
        QDomNode node = regions.item( i );
        if (!node.namedItem("payload").isNull()) {
            QUrl url = node.namedItem("payload").toElement().text();
            QFileInfo fileInfo(url.path());
            if (fileInfo.fileName() == package.file.fileName()) {
                QString removeFile;
                QDomNode dateNode = node.namedItem("releasedate");
                if (!dateNode.isNull()) {
                    dateNode.removeChild(dateNode.firstChild());
                    dateNode.appendChild(m_xml.createTextNode(releaseDate()));
                }
                QDomNode versionNode = node.namedItem("version");
                if (!versionNode.isNull()) {
                    double version = versionNode.toElement().text().toDouble();
                    versionNode.removeChild(versionNode.firstChild());
                    versionNode.appendChild(m_xml.createTextNode(QString::number(version+0.1, 'f', 1)));
                }
                QDomNode payloadNode = node.namedItem("payload");
                payloadNode.removeChild(payloadNode.firstChild());
                if (fileInfo.dir().dirName() != targetDir()) {
                    removeFile = QString("/home/marble/web/monav/%1/%2").arg(fileInfo.dir().dirName()).arg(package.file.fileName());
                    qDebug() << "Going to remove the old file " << removeFile;
                }
                QString payload = "http://files.kde.org/marble/monav/%1/%2";
                payload = payload.arg(targetDir()).arg(package.file.fileName());
                payloadNode.appendChild(m_xml.createTextNode(payload));
                return removeFile.isEmpty() ? uploadNewstuff() : (uploadNewstuff() && deleteRemoteFile(removeFile));
            }
        }
    }

    QDomNode stuff = root.appendChild(m_xml.createElement("stuff"));
    stuff.toElement().setAttribute("category", "marble/routing/monav");
    QDomNode nameNode = stuff.appendChild(m_xml.createElement("name"));
    nameNode.toElement().setAttribute("lang", "en");
    QString name = "%1 / %2 (%3)";
    if (package.region.country().isEmpty()) {
        name = name.arg(package.region.continent()).arg(package.region.name());
        name = name.arg(package.transport);
    } else {
        name = "%1 / %2 / %3 (%4)";
        name = name.arg(package.region.continent()).arg(package.region.country());
        name = name.arg(package.region.name()).arg(package.transport);
    }
    nameNode.appendChild(m_xml.createTextNode(name));

    QDomNode authorNode = stuff.appendChild(m_xml.createElement("author"));
    authorNode.appendChild(m_xml.createTextNode("Automatically created from map data assembled by the OpenStreetMap community"));

    QDomNode licenseNode = stuff.appendChild(m_xml.createElement("license"));
    licenseNode.appendChild(m_xml.createTextNode("Creative Commons by-SA 2.0"));

    QDomNode summaryNode = stuff.appendChild(m_xml.createElement("summary"));
    QString summary = "Requires KDE >= 4.6: Offline Routing in %1, %2";
    summary = summary.arg(package.region.name()).arg(package.region.continent());
    summaryNode.appendChild(m_xml.createTextNode(summary));

    QDomNode versionNode = stuff.appendChild(m_xml.createElement("version"));
    versionNode.appendChild(m_xml.createTextNode("0.1"));

    QDomNode dateNode = stuff.appendChild(m_xml.createElement("releasedate"));
    dateNode.appendChild(m_xml.createTextNode(releaseDate()));

    QDomNode previewNode = stuff.appendChild(m_xml.createElement("preview"));
    QString preview = "http://files.kde.org/marble/monav/previews/%1-preview.png";
    preview = preview.arg(package.region.id());
    previewNode.appendChild(m_xml.createTextNode(preview));

    QDomNode payloadNode = stuff.appendChild(m_xml.createElement("payload"));
    payloadNode.toElement().setAttribute("lang", "en");
    QString payload = "http://files.kde.org/marble/monav/%1/%2";
    payload = payload.arg(targetDir()).arg(package.file.fileName());
    payloadNode.appendChild(m_xml.createTextNode(payload));

    return uploadNewstuff();
}
Example #5
0
void KFFOpt_scenery::searchData( QFile* file )
{
	QDomDocument doc;
	QDomElement root;
	QDomNode parent;
	QDomNode child;
	QDomElement e_parent;
	QDomElement e_child;
	KFFScenarioData scenario;
	QString name;
	QStringList list;
	QStringList::Iterator it;

	if ( doc.setContent( file ) )
	{
		root = doc.documentElement();
		parent = root.firstChild();
		e_parent = parent.toElement();
		if ( !e_parent.isNull() )
		{
			if ( e_parent.tagName() == "description" )
			{
				list = e_parent.text().split("\n");
				for (it = list.begin() ; it != list.end() ; it++ )
				{
					*it = it->simplified();
				}
				scenario.description = list.join("\n");
				parent = parent.nextSibling();
				
			}
		}
		
		parent = parent.firstChild();
		
		name = file->fileName().section( '/', -1, -1 ).remove( ".xml" );

		while ( !parent.isNull() )
		{
			e_parent = parent.toElement();

			if ( !e_parent.isNull() )
			{
				if ( e_parent.tagName() == "entry" )
				{
					child = parent.firstChild();

					while ( !child.isNull() )
					{
						e_child = child.toElement();

						if ( !e_child.isNull() )
						{
							if ( e_child.tagName() == "type" )
							{
								scenario.type = e_child.text();
							}
						}

						child = child.nextSibling();
					}
				}

				if ( e_parent.tagName() == "description" )
				{
					list = e_parent.text().split("\n");
					for (it = list.begin() ; it != list.end() ; it++ )
					{
						*it = it->simplified();
					}
					scenario.description = list.join("\n");
				}
			}

			parent = parent.nextSibling();

		}

		if ( !m_scenarii.contains( name ) )
		{
			m_scenarii[name] = scenario;
		}

	}
	else
	{
		qDebug() << file->fileName() << "is not a valide xml file" ;
	}
}
Example #6
0
int LoadReport::writeToDB(const QByteArray &pdata, const QString pkgname, QString &errMsg)
{
  int errLine = 0;
  int errCol  = 0;
  QDomDocument doc;
  if (! doc.setContent(pdata, &errMsg, &errLine, &errCol))
  {
    errMsg = (TR("<font color=red>Error parsing file %1: %2 on "
                          "line %3 column %4</font>")
                          .arg(_filename).arg(errMsg).arg(errLine).arg(errCol));
    return -1;
  }

  QDomElement root = doc.documentElement();
  if(root.tagName() != "report")
  {
    errMsg = TR("<font color=red>XML Document %1 does not have root"
                         " node of report</font>")
                         .arg(_filename);
    return -2;
  }

  for(QDomNode n = root.firstChild(); !n.isNull(); n = n.nextSibling())
  {
    if(n.nodeName() == "name")
      _name = n.firstChild().nodeValue();
    else if(n.nodeName() == "description")
      _comment = n.firstChild().nodeValue();
  }
  QString report_src = doc.toString();

  if(_filename.isEmpty())
  {
    errMsg = TR("<font color=orange>The document %1 does not have"
                         " a report name defined</font>")
                         .arg(_filename);
    return -3;
  }

  if (_grade == INT_MIN)
  {
    QSqlQuery minOrder;
    minOrder.prepare("SELECT MIN(report_grade) AS min "
                     "FROM report "
                     "WHERE (report_name=:name);");
    minOrder.bindValue(":name", _name);
    minOrder.exec();
    if (minOrder.first())
      _grade = minOrder.value(0).toInt();
    else if (minOrder.lastError().type() != QSqlError::NoError)
    {
      QSqlError err = minOrder.lastError();
      errMsg = _sqlerrtxt.arg(_filename).arg(err.driverText()).arg(err.databaseText());
      return -4;
    }
    else
      _grade = 0;
  }
  else if (_grade == INT_MAX)
  {
    QSqlQuery maxOrder;
    maxOrder.prepare("SELECT MAX(report_grade) AS max "
                     "FROM report "
                     "WHERE (report_name=:name);");
    maxOrder.bindValue(":name", _name);
    maxOrder.exec();
    if (maxOrder.first())
      _grade = maxOrder.value(0).toInt();
    else if (maxOrder.lastError().type() != QSqlError::NoError)
    {
      QSqlError err = maxOrder.lastError();
      errMsg = _sqlerrtxt.arg(_filename).arg(err.driverText()).arg(err.databaseText());
      return -5;
    }
    else
      _grade = 0;
  }

  QSqlQuery select;
  QSqlQuery upsert;

  int reportid  = -1;
  int pkgheadid = -1;
  int pkgitemid = -1;

  /* The following ugliness exists to avoid
      ERROR:  duplicate key violates unique constraint "report_name_grade_idx"
   */
  QString rptselect("SELECT report_id, -1, -1"
                    "  FROM report "
                    " WHERE ((report_name=:name) "
                    "    AND (report_grade=:grade) );");

  if (pkgname.isEmpty())
  {
    select.prepare(rptselect);
    select.bindValue(":name",    _name);
    select.bindValue(":grade",   _grade);
    select.exec();
    if(select.first())
      reportid = select.value(0).toInt();
    else if (select.lastError().type() != QSqlError::NoError)
    {
      QSqlError err = select.lastError();
      errMsg = _sqlerrtxt.arg(_filename).arg(err.driverText()).arg(err.databaseText());
      return -6;
    }
  }
  else 
  {
    select.prepare(_pkgitemQueryStr);
    select.bindValue(":name",    _name);
    select.bindValue(":pkgname", pkgname);
    //select.bindValue(":grade",   _grade); //TODO: add to _pkgitemquerystr?
    select.bindValue(":type",    _pkgitemtype);
    select.exec();
    if(select.first())
    {
      reportid  = select.value(0).toInt();
      pkgheadid = select.value(1).toInt();
      pkgitemid = select.value(2).toInt();
    }
    else if (select.lastError().type() != QSqlError::NoError)
    {
      QSqlError err = select.lastError();
      errMsg = _sqlerrtxt.arg(_filename).arg(err.driverText()).arg(err.databaseText());
      return -7;
    }
    if (reportid < 0)   // select told us there's no report *in* the package
    {
      // if there's a version of the report that's not part of the package
      select.prepare(rptselect);
      select.bindValue(":name",    _name);
      select.bindValue(":grade",   _grade);
      select.exec();
      if(select.first())
      {
        // then insert a new one with a higher grade
        QSqlQuery next;
        next.prepare("SELECT MIN(sequence_value) AS next "
                         "FROM sequence "
                         "WHERE ((sequence_value NOT IN ("
                         "      SELECT report_grade"
                         "      FROM report"
                         "      WHERE (report_name=:name)))"
                         "  AND (sequence_value>=:grade));");
        next.bindValue(":name", _name);
        next.bindValue(":grade",   _grade);
        next.exec();
        if (next.first())
          _grade = next.value(0).toInt();
        else if (next.lastError().type() != QSqlError::NoError)
        {
          QSqlError err = next.lastError();
          errMsg = _sqlerrtxt.arg(_filename).arg(err.driverText()).arg(err.databaseText());
          return -8;
        }
      }
      else if (select.lastError().type() != QSqlError::NoError)
      {
        QSqlError err = select.lastError();
        errMsg = _sqlerrtxt.arg(_filename).arg(err.driverText()).arg(err.databaseText());
        return -9;
      }
    }
  }

  if (reportid >= 0)
    upsert.prepare(QString("UPDATE %1report "
                           "   SET report_descrip=:notes, "
                           "       report_source=:source "
                           " WHERE (report_id=:id);")
                          .arg(_system ? "" : "pkg"));
  else
  {
    upsert.exec("SELECT NEXTVAL('report_report_id_seq');");
    if (upsert.first())
      reportid = upsert.value(0).toInt();
    else if (upsert.lastError().type() != QSqlError::NoError)
    {
      QSqlError err = upsert.lastError();
      errMsg = _sqlerrtxt.arg(_filename).arg(err.driverText()).arg(err.databaseText());
      return -10;
    }

    upsert.prepare(QString("INSERT INTO %1report "
                           "       (report_id, report_name, report_grade, "
                           "        report_source, report_descrip)"
                           "VALUES (:id, :name, :grade, :source, :notes);")
                          .arg(_system ? "" : "pkg"));
    upsert.bindValue(":grade",   _grade);
    upsert.bindValue(":name",    _name);
  }

  upsert.bindValue(":id",      reportid);
  upsert.bindValue(":source",  report_src);
  upsert.bindValue(":notes",   _comment);

  if (!upsert.exec())
  {
    QSqlError err = upsert.lastError();
    errMsg = _sqlerrtxt.arg(_filename).arg(err.driverText()).arg(err.databaseText());
    return -11;
  }

  if (pkgheadid >= 0)
  {
    int tmp = upsertPkgItem(pkgitemid, pkgheadid, reportid, errMsg);
    if (tmp < 0)
      return tmp;
  }

  return 0;
}
Example #7
0
int main(int argc, char *argv[])
{
    QString title;
    title = title + "********************************************************************* \n";
    title = title + " * Create from XML                                                   * \n";
    title = title + " * This tool create a SQL DDL script file from a XML schema file     * \n";
    title = title + " * created by ODKToMySQL.                                            * \n";
    title = title + " *                                                                   * \n";
    title = title + " * This tool is usefull when dealing with multiple versions of an    * \n";
    title = title + " * ODK survey that were combined into a common XML schema using      * \n";
    title = title + " * compareCreateXML.                                                 * \n";
    title = title + " *                                                                   * \n";
    title = title + " * This tool is part of ODK Tools (c) ILRI-RMG, 2015                 * \n";
    title = title + " * Author: Carlos Quiros ([email protected] / [email protected]) * \n";
    title = title + " ********************************************************************* \n";

    TCLAP::CmdLine cmd(title.toUtf8().constData(), ' ', "1.0");

    TCLAP::ValueArg<std::string> inputArg("i","input","Input create XML file",true,"","string");
    TCLAP::ValueArg<std::string> outputArg("o","output","Output SQL file",false,"./create.sql","string");


    cmd.add(inputArg);
    cmd.add(outputArg);

    //Parsing the command lines
    cmd.parse( argc, argv );

    //Getting the variables from the command
    QString input = QString::fromUtf8(inputArg.getValue().c_str());
    QString output = QString::fromUtf8(outputArg.getValue().c_str());
    idx = 0;

    if (input != output)
    {
        if (QFile::exists(input))
        {
            //Openning and parsing input file A
            QDomDocument docA("input");
            QFile fileA(input);
            if (!fileA.open(QIODevice::ReadOnly))
            {
                log("Cannot open input file");
                return 1;
            }
            if (!docA.setContent(&fileA))
            {
                log("Cannot parse input file");
                fileA.close();
                return 1;
            }
            fileA.close();

            QDomElement rootA = docA.documentElement();

            if (rootA.tagName() == "XMLSchemaStructure")
            {
                QFile file(output);
                if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
                {
                    log("Cannot create output file");
                    return 1;
                }

                QDateTime date;
                date = QDateTime::currentDateTime();

                QTextStream out(&file);

                out << "-- Code generated by createFromXML" << "\n";
                out << "-- Created: " + date.toString("ddd MMMM d yyyy h:m:s ap")  << "\n";
                out << "-- by: createFromXML Version 1.0" << "\n";
                out << "-- WARNING! All changes made in this file might be lost when running createFromXML again" << "\n\n";

                QDomNode lkpTables = docA.documentElement().firstChild();
                QDomNode tables = docA.documentElement().firstChild().nextSibling();
                if (!lkpTables.isNull())
                {
                    procLKPTables(lkpTables.firstChild(),out);
                }
                if (!tables.isNull())
                {
                    procTables(tables.firstChild(),out);
                }
            }
            else
            {
                log("Input document is not a XML create file");
                return 1;
            }
        }
        else
        {
            log("Input file does not exists");
            return 1;
        }
    }
    else
    {
        log("Fatal: Input files and output file are the same.");
        return 1;
    }

    return 0;
}
Example #8
0
void Parser3::ParseUserEntry( QDomNode Node, UserPtr Info ) {
    QDomNode Child = Node.firstChild();

    /// Just fill it up with some video feeds, if not already assigned
    if( Info->Favorites.isNull() ) {
        Info->Favorites = new VideoFeed;
        Info->Favorites->Type = VideoFeed::FT_UserFavorites;
        Info->Favorites->ParsedPages = 0;
        Info->Favorites->HasFullFeed = false;
    } if( Info->Uploads.isNull() ) {
        Info->Uploads = new VideoFeed;
        Info->Uploads->Type = VideoFeed::FT_UserUploads;
        Info->Uploads->ParsedPages = 0;
        Info->Uploads->HasFullFeed = false;
    } if( Info->Playlists.isNull() ) {
        Info->Playlists = new PlaylistFeed;
        Info->Playlists->ParsedPages = 0;
        Info->Playlists->HasFullFeed = false;
        Info->Playlists->Type = PlaylistFeed::FT_UserPlaylists;
    }

    while( !Child.isNull() )
    {
        QString NodeName = Child.nodeName();
        if( NodeName == "published" )
        {
            Info->Joined = QDate::fromString( Child.namedItem("#text").nodeValue(), Qt::ISODate );
        }
        else if( NodeName == "title" )
        {
            Info->Title = Child.namedItem("#text").nodeValue();
        }
        else if( NodeName == "author" )
        {
            Info->Author = Child.namedItem("name").namedItem("#text").nodeValue();
        }
        else if( NodeName == "yt:age" )
        {
            Info->Age = Child.namedItem("#text").nodeValue().toInt();
        }
        else if( NodeName == "yt:aboutMe" )
        {
            Info->Description = Child.namedItem("#text").nodeValue();
        }
        else if( NodeName == "gd:feedLink" )
        {
            QString RelValue = Child.attributes().namedItem("rel").nodeValue();
            if( RelValue == "http://gdata.youtube.com/schemas/2007#user.favorites" )
            {
                Info->Favorites->Size = Child.attributes().namedItem("countHint").nodeValue().toInt();
            }
            else if( RelValue == "http://gdata.youtube.com/schemas/2007#user.playlists" )
            {
                Info->Playlists->Size = Child.attributes().namedItem("countHint").nodeValue().toInt();
            }
            else if( RelValue == "http://gdata.youtube.com/schemas/2007#user.uploads" )
            {
                Info->Uploads->Size = Child.attributes().namedItem("countHint").nodeValue().toInt();
                Info->TotalUploads = Info->Uploads->Size;
            }
        }
        else if( NodeName == "yt:firstName" )
        {
            Info->FirstName = Child.namedItem("#text").nodeValue();
        }
        else if( NodeName == "yt:lastName" )
        {
            Info->LastName = Child.namedItem("#text").nodeValue();
        }
        else if( NodeName == "yt:statistics" )
        {
            Info->Subscribers = Child.attributes().namedItem("subscriberCount").nodeValue().toInt();
            Info->ChannelsViews = Child.attributes().namedItem("viewCount").nodeValue().toInt();
            Info->TotalViews = Child.attributes().namedItem("totalUploadViews").nodeValue().toInt();
        }
        else if( NodeName == "media:thumbnail" )
        {
            Info->UrlThumbnail = QUrl( Child.attributes().namedItem("url").nodeValue() );
        }

        Child = Child.nextSibling();
    }

    /// Set some important information about the feeds :)
    Info->Favorites->NextPageInFeed = QUrl(QString("http://gdata.youtube.com/feeds/api/users/%1/favorites?v=2&start-index=1&max-results=50").arg(Info->Author));
    Info->Uploads->NextPageInFeed = QUrl(QString("http://gdata.youtube.com/feeds/api/users/%1/uploads?v=2&start-index=1&max-results=50").arg(Info->Author));
    Info->Playlists->NextPageInFeed = QUrl(QString("http://gdata.youtube.com/feeds/api/users/%1/playlists?v=2&start-index=1&max-results=50").arg(Info->Author));

    Info->Favorites->Author = Info->Author;
    Info->Favorites->Title = QString("%1 Favorites").arg(Info->Author);
    Info->Favorites->UrlThumbnail = Info->UrlThumbnail;
    Info->Favorites->UrlAuthor = QUrl(QString("http://gdata.youtube.com/feeds/api/users/%1?v=2").arg(Info->Author));

    Info->Uploads->Author = Info->Author;
    Info->Uploads->Title = QString("%1 Uploads").arg(Info->Author);
    Info->Uploads->UrlThumbnail = Info->UrlThumbnail;
    Info->Uploads->UrlAuthor = QUrl(QString("http://gdata.youtube.com/feeds/api/users/%1?v=2").arg(Info->Author));

    Info->Playlists->Author = Info->Author;
    Info->Playlists->Title = QString("%1 Playlists").arg(Info->Author);
    Info->Playlists->UrlThumbnail = Info->UrlThumbnail;
    Info->Playlists->UrlAuthor = QUrl(QString("http://gdata.youtube.com/feeds/api/users/%1?v=2").arg(Info->Author));


    /// The ID is const so I have to make a cast :/
    const_cast<QString&>(Info->Favorites->ID) = Info->Author+"/favorites";
    const_cast<QString&>(Info->Uploads->ID) = Info->Author+"/uploads";
    const_cast<QString&>(Info->Playlists->ID) = Info->Author+"/playlists";

    Info->FixInfo();

    return;
}
Example #9
0
int main(int argc, char *argv[])
{
  if (argc > 1)
  {
    QApplication application(argc, argv, FALSE);
    application.addLibraryPath(".");

    QString databaseURL;
    QString username;
    QString passwd;
    QString arguments;

    QString xml_file = QString::null;
    int     report_grade = 0;

    for (int counter = 1; counter < argc; counter++)
    {
      arguments = argv[counter];

      if (arguments.contains("-databaseURL="))
        databaseURL = arguments.right(arguments.length() - 13);
      else if (arguments.contains("-username="******"-passwd="))
        passwd = arguments.right(arguments.length() - 8);
      else if (arguments.contains("-f="))
        xml_file = arguments.right(arguments.length() - 3);
      else if (arguments.contains("-grade="))
        report_grade = (arguments.right(arguments.length() - 7)).toInt();
    }

    QString report_name = QString::null;
    QString report_desc = QString::null;
    QString report_src  = QString::null;

    if(xml_file != "") {
        QFile file(xml_file);
        if(file.open( IO_ReadOnly )) {
            QDomDocument doc;
            QString errMsg;
            int errLine, errCol;
            if(doc.setContent(&file, &errMsg, &errLine, &errCol)) {
                QDomElement root = doc.documentElement();
                if(root.tagName() == "report") {
                    for(QDomNode n = root.firstChild();
                            !n.isNull(); n = n.nextSibling() ) {
                        if(n.nodeName() == "name") {
                            report_name = n.firstChild().nodeValue();
                        } else if(n.nodeName() == "description") {
                            report_desc = n.firstChild().nodeValue();
                        }
                    }
                    report_src  = doc.toString();

                    if(report_name == "") {
                        printf("The document %s does not have a report name defined\n", (const char*)xml_file);
                    }
                } else {
                    printf("XML Document %s does not have root node of report\n",(const char*)xml_file);
                }
            } else {
                printf("Error parsing file %s: %s on line %d column %d\n",
                    (const char*)xml_file, (const char*)errMsg, errLine, errCol);
            }
        } else {
            printf("Could not open the specified file: %s\n", (const char*)xml_file);
        }
    } else {
        printf("You must specify an XML file to load by using the -f= parameter.\n");
    }

    if(report_name == "" || report_src == "") {
        // an error message already should have been displayed to the user
        exit(-1);
    }

    if (  (databaseURL != "") &&
          (username != "")    &&
          (passwd != "")          ) {
      QSqlDatabase *db;
      QString      protocol;
      QString      hostName;
      QString      dbName;
      QString      port;

// Open the Database Driver
      parseDatabaseURL(databaseURL, protocol, hostName, dbName, port);
      if("odbc" == protocol)
        db = QSqlDatabase::addDatabase("QODBC3");  
      else
        db = QSqlDatabase::addDatabase("QPSQL7");
      if (!db)
      {
        printf("Could not load the specified database driver.\n");
        exit(-1);
      }

//  Try to connect to the Database
      bool valport = FALSE;
      int iport = port.toInt(&valport);
      if(!valport) iport = 5432;
      db->setDatabaseName(dbName);
      db->setPort(iport);
      db->setUserName(username);
      db->setPassword(passwd);
      db->setHostName(hostName);
      if (!db->open())
      {
        printf( "Host=%s, Database=%s, port=%s\n",
                (const char *)hostName,
                (const char *)dbName,
                (const char *)port );

        printf( "Could not log into database.  System Error: %s\n",
                (const char *)db->lastError().driverText() );
        exit(-1);
      }

      QSqlQuery().exec("SELECT login();");

      // first we need to determine if there is already a report in the database of the same
      // name and if so then we will perform an update instead of an insert
      QSqlQuery qry;
      qry.prepare("SELECT report_id "
                  "  FROM report "
                  " WHERE ((report_name=:report_name) "
                  "   AND (report_grade=:report_grade));");
      qry.bindValue(":report_name", report_name);
      qry.bindValue(":report_grade", report_grade);
      qry.exec();
      QSqlQuery query;
      if(qry.first()) {
          // update
          query.prepare("UPDATE report "
                        "   SET report_descrip=:report_desc, "
                        "       report_source =:report_src "
                        " WHERE ((report_id=:report_id) "
                        "   AND (report_name=:report_name));");
          query.bindValue(":report_desc", report_desc);
          query.bindValue(":report_src", report_src);
          query.bindValue(":report_id", qry.value(0));
          query.bindValue(":report_name", report_name);
      } else {
          // insert
          query.prepare("INSERT INTO report "
                        "       (report_name, report_descrip, report_source, report_grade) "
                        "VALUES (:report_name, :report_desc, :report_src, :report_grade);");
          query.bindValue(":report_name", report_name);
          query.bindValue(":report_desc", report_desc);
          query.bindValue(":report_src", report_src);
          query.bindValue(":report_grade", report_grade);
      }
      
      if(!query.exec()) {
          QSqlError err = query.lastError();
          printf("Error: %s\n\t%s\n", (const char*)err.driverText(),
                                    (const char*)err.databaseText());
          exit(-1);
      }
      
    }
    else if (databaseURL == "")
      printf("You must specify a Database URL by using the -databaseURL= parameter.\n");
    else if (username == "")
      printf("You must specify a Database Username by using the -username= parameter.\n");
    else if (passwd == "")
      printf("You must specify a Database Password by using the -passwd= parameter.\n");
  }
  else
    printf( "Usage: import -databaseURL='$' -username='******' -passwd='$' -grade=# -f='$'\n");
  return 0;
}
Example #10
0
void QgsWfsCapabilities::capabilitiesReplyFinished()
{
  const QByteArray& buffer = mResponse;

  QgsDebugMsg( "parsing capabilities: " + buffer );

  // parse XML
  QString capabilitiesDocError;
  QDomDocument capabilitiesDocument;
  if ( !capabilitiesDocument.setContent( buffer, true, &capabilitiesDocError ) )
  {
    mErrorCode = QgsWfsRequest::XmlError;
    mErrorMessage = capabilitiesDocError;
    emit gotCapabilities();
    return;
  }

  QDomElement doc = capabilitiesDocument.documentElement();

  // handle exceptions
  if ( doc.tagName() == "ExceptionReport" )
  {
    QDomNode ex = doc.firstChild();
    QString exc = ex.toElement().attribute( "exceptionCode", "Exception" );
    QDomElement ext = ex.firstChild().toElement();
    mErrorCode = QgsWfsRequest::ServerExceptionError;
    mErrorMessage = exc + ": " + ext.firstChild().nodeValue();
    emit gotCapabilities();
    return;
  }

  mCaps.clear();

  //test wfs version
  mCaps.version = doc.attribute( "version" );
  if ( !mCaps.version.startsWith( "1.0" ) &&
       !mCaps.version.startsWith( "1.1" ) &&
       !mCaps.version.startsWith( "2.0" ) )
  {
    mErrorCode = WFSVersionNotSupported;
    mErrorMessage = tr( "WFS version %1 not supported" ).arg( mCaps.version );
    emit gotCapabilities();
    return;
  }

  // WFS 2.0 implementation are supposed to implement resultType=hits, and some
  // implementations (GeoServer) might advertize it, whereas others (MapServer) do not.
  // WFS 1.1 implementation too I think, but in the examples of the GetCapabilites
  // response of the WFS 1.1 standard (and in common implementations), this is
  // explictly advertized
  if ( mCaps.version.startsWith( "2.0" ) )
    mCaps.supportsHits = true;

  // Note: for conveniency, we do not use the elementsByTagNameNS() method as
  // the WFS and OWS namespaces URI are not the same in all versions

  // find <ows:OperationsMetadata>
  QDomElement operationsMetadataElem = doc.firstChildElement( "OperationsMetadata" );
  if ( !operationsMetadataElem.isNull() )
  {
    QDomNodeList contraintList = operationsMetadataElem.elementsByTagName( "Constraint" );
    for ( int i = 0; i < contraintList.size(); ++i )
    {
      QDomElement contraint = contraintList.at( i ).toElement();
      if ( contraint.attribute( "name" ) == "DefaultMaxFeatures" /* WFS 1.1 */ )
      {
        QDomElement value = contraint.firstChildElement( "Value" );
        if ( !value.isNull() )
        {
          mCaps.maxFeatures = value.text().toInt();
          QgsDebugMsg( QString( "maxFeatures: %1" ).arg( mCaps.maxFeatures ) );
        }
      }
      else if ( contraint.attribute( "name" ) == "CountDefault" /* WFS 2.0 (e.g. MapServer) */ )
      {
        QDomElement value = contraint.firstChildElement( "DefaultValue" );
        if ( !value.isNull() )
        {
          mCaps.maxFeatures = value.text().toInt();
          QgsDebugMsg( QString( "maxFeatures: %1" ).arg( mCaps.maxFeatures ) );
        }
      }
      else if ( contraint.attribute( "name" ) == "ImplementsResultPaging" /* WFS 2.0 */ )
      {
        QDomElement value = contraint.firstChildElement( "DefaultValue" );
        if ( !value.isNull() && value.text() == "TRUE" )
        {
          mCaps.supportsPaging = true;
          QgsDebugMsg( "Supports paging" );
        }
      }
      else if ( contraint.attribute( "name" ) == "ImplementsStandardJoins" ||
                contraint.attribute( "name" ) == "ImplementsSpatialJoins" /* WFS 2.0 */ )
      {
        QDomElement value = contraint.firstChildElement( "DefaultValue" );
        if ( !value.isNull() && value.text() == "TRUE" )
        {
          mCaps.supportsJoins = true;
          QgsDebugMsg( "Supports joins" );
        }
      }
    }

    // In WFS 2.0, max features can also be set in Operation.GetFeature (e.g. GeoServer)
    // and we are also interested by resultType=hits for WFS 1.1
    QDomNodeList operationList = operationsMetadataElem.elementsByTagName( "Operation" );
    for ( int i = 0; i < operationList.size(); ++i )
    {
      QDomElement operation = operationList.at( i ).toElement();
      if ( operation.attribute( "name" ) == "GetFeature" )
      {
        QDomNodeList operationContraintList = operation.elementsByTagName( "Constraint" );
        for ( int j = 0; j < operationContraintList.size(); ++j )
        {
          QDomElement contraint = operationContraintList.at( j ).toElement();
          if ( contraint.attribute( "name" ) == "CountDefault" )
          {
            QDomElement value = contraint.firstChildElement( "DefaultValue" );
            if ( !value.isNull() )
            {
              mCaps.maxFeatures = value.text().toInt();
              QgsDebugMsg( QString( "maxFeatures: %1" ).arg( mCaps.maxFeatures ) );
            }
            break;
          }
        }

        QDomNodeList parameterList = operation.elementsByTagName( "Parameter" );
        for ( int j = 0; j < parameterList.size(); ++j )
        {
          QDomElement parameter = parameterList.at( j ).toElement();
          if ( parameter.attribute( "name" ) == "resultType" )
          {
            QDomNodeList valueList = parameter.elementsByTagName( "Value" );
            for ( int k = 0; k < valueList.size(); ++k )
            {
              QDomElement value = valueList.at( k ).toElement();
              if ( value.text() == "hits" )
              {
                mCaps.supportsHits = true;
                QgsDebugMsg( "Support hits" );
                break;
              }
            }
          }
        }

        break;
      }
    }
  }

  //go to <FeatureTypeList>
  QDomElement featureTypeListElem = doc.firstChildElement( "FeatureTypeList" );
  if ( featureTypeListElem.isNull() )
  {
    emit gotCapabilities();
    return;
  }

  // Parse operations supported for all feature types
  bool insertCap, updateCap, deleteCap;
  parseSupportedOperations( featureTypeListElem.firstChildElement( "Operations" ),
                            insertCap,
                            updateCap,
                            deleteCap );

  // get the <FeatureType> elements
  QDomNodeList featureTypeList = featureTypeListElem.elementsByTagName( "FeatureType" );
  for ( int i = 0; i < featureTypeList.size(); ++i )
  {
    FeatureType featureType;
    QDomElement featureTypeElem = featureTypeList.at( i ).toElement();

    //Name
    QDomNodeList nameList = featureTypeElem.elementsByTagName( "Name" );
    if ( nameList.length() > 0 )
    {
      featureType.name = nameList.at( 0 ).toElement().text();
    }
    //Title
    QDomNodeList titleList = featureTypeElem.elementsByTagName( "Title" );
    if ( titleList.length() > 0 )
    {
      featureType.title = titleList.at( 0 ).toElement().text();
    }
    //Abstract
    QDomNodeList abstractList = featureTypeElem.elementsByTagName( "Abstract" );
    if ( abstractList.length() > 0 )
    {
      featureType.abstract = abstractList.at( 0 ).toElement().text();
    }

    //DefaultSRS is always the first entry in the feature srs list
    QDomNodeList defaultCRSList = featureTypeElem.elementsByTagName( "DefaultSRS" );
    if ( defaultCRSList.length() == 0 )
      // In WFS 2.0, this is spelled DefaultCRS...
      defaultCRSList = featureTypeElem.elementsByTagName( "DefaultCRS" );
    if ( defaultCRSList.length() > 0 )
    {
      QString srsname( defaultCRSList.at( 0 ).toElement().text() );
      // Some servers like Geomedia advertize EPSG:XXXX even in WFS 1.1 or 2.0
      if ( srsname.startsWith( "EPSG:" ) )
        mCaps.useEPSGColumnFormat = true;
      featureType.crslist.append( NormalizeSRSName( srsname ) );
    }

    //OtherSRS
    QDomNodeList otherCRSList = featureTypeElem.elementsByTagName( "OtherSRS" );
    if ( otherCRSList.length() == 0 )
      // In WFS 2.0, this is spelled OtherCRS...
      otherCRSList = featureTypeElem.elementsByTagName( "OtherCRS" );
    for ( int i = 0; i < otherCRSList.size(); ++i )
    {
      featureType.crslist.append( NormalizeSRSName( otherCRSList.at( i ).toElement().text() ) );
    }

    //Support <SRS> for compatibility with older versions
    QDomNodeList srsList = featureTypeElem.elementsByTagName( "SRS" );
    for ( int i = 0; i < srsList.size(); ++i )
    {
      featureType.crslist.append( NormalizeSRSName( srsList.at( i ).toElement().text() ) );
    }

    // Get BBox WFS 1.0 way
    QDomElement latLongBB = featureTypeElem.firstChildElement( "LatLongBoundingBox" );
    if ( latLongBB.hasAttributes() )
    {
      // Despite the name LatLongBoundingBox, the coordinates are supposed to
      // be expressed in <SRS>. From the WFS schema;
      // <!-- The LatLongBoundingBox element is used to indicate the edges of
      // an enclosing rectangle in the SRS of the associated feature type.
      featureType.bbox = QgsRectangle(
                           latLongBB.attribute( "minx" ).toDouble(),
                           latLongBB.attribute( "miny" ).toDouble(),
                           latLongBB.attribute( "maxx" ).toDouble(),
                           latLongBB.attribute( "maxy" ).toDouble() );
      featureType.bboxSRSIsWGS84 = false;

      // But some servers do not honour this and systematically reproject to WGS84
      // such as GeoServer. See http://osgeo-org.1560.x6.nabble.com/WFS-LatLongBoundingBox-td3813810.html
      // This is also true of TinyOWS
      if ( !featureType.crslist.isEmpty() &&
           featureType.bbox.xMinimum() >= -180 && featureType.bbox.yMinimum() >= -90 &&
           featureType.bbox.xMaximum() <= 180 && featureType.bbox.yMaximum() < 90 )
      {
        QgsCoordinateReferenceSystem crs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( featureType.crslist[0] );
        if ( !crs.isGeographic() )
        {
          // If the CRS is projected then check that projecting the corner of the bbox, assumed to be in WGS84,
          // into the CRS, and then back to WGS84, works (check that we are in the validity area)
          QgsCoordinateReferenceSystem crsWGS84 = QgsCoordinateReferenceSystem::fromOgcWmsCrs( "CRS:84" );
          QgsCoordinateTransform ct( crsWGS84, crs );

          QgsPoint ptMin( featureType.bbox.xMinimum(), featureType.bbox.yMinimum() );
          QgsPoint ptMinBack( ct.transform( ct.transform( ptMin, QgsCoordinateTransform::ForwardTransform ), QgsCoordinateTransform::ReverseTransform ) );
          QgsPoint ptMax( featureType.bbox.xMaximum(), featureType.bbox.yMaximum() );
          QgsPoint ptMaxBack( ct.transform( ct.transform( ptMax, QgsCoordinateTransform::ForwardTransform ), QgsCoordinateTransform::ReverseTransform ) );

          QgsDebugMsg( featureType.bbox.toString() );
          QgsDebugMsg( ptMinBack.toString() );
          QgsDebugMsg( ptMaxBack.toString() );

          if ( fabs( featureType.bbox.xMinimum() - ptMinBack.x() ) < 1e-5 &&
               fabs( featureType.bbox.yMinimum() - ptMinBack.y() ) < 1e-5 &&
               fabs( featureType.bbox.xMaximum() - ptMaxBack.x() ) < 1e-5 &&
               fabs( featureType.bbox.yMaximum() - ptMaxBack.y() ) < 1e-5 )
          {
            QgsDebugMsg( "Values of LatLongBoundingBox are consistent with WGS84 long/lat bounds, so as the CRS is projected, assume they are indeed in WGS84 and not in the CRS units" );
            featureType.bboxSRSIsWGS84 = true;
          }
        }
      }
    }
    else
    {
      // WFS 1.1 way
      QDomElement WGS84BoundingBox = featureTypeElem.firstChildElement( "WGS84BoundingBox" );
      if ( !WGS84BoundingBox.isNull() )
      {
        QDomElement lowerCorner = WGS84BoundingBox.firstChildElement( "LowerCorner" );
        QDomElement upperCorner = WGS84BoundingBox.firstChildElement( "UpperCorner" );
        if ( !lowerCorner.isNull() && !upperCorner.isNull() )
        {
          QStringList lowerCornerList = lowerCorner.text().split( " ", QString::SkipEmptyParts );
          QStringList upperCornerList = upperCorner.text().split( " ", QString::SkipEmptyParts );
          if ( lowerCornerList.size() == 2 && upperCornerList.size() == 2 )
          {
            featureType.bbox = QgsRectangle(
                                 lowerCornerList[0].toDouble(),
                                 lowerCornerList[1].toDouble(),
                                 upperCornerList[0].toDouble(),
                                 upperCornerList[1].toDouble() );
            featureType.bboxSRSIsWGS84 = true;
          }
        }
      }
    }

    // Parse Operations specific to the type name
    parseSupportedOperations( featureTypeElem.firstChildElement( "Operations" ),
                              featureType.insertCap,
                              featureType.updateCap,
                              featureType.deleteCap );
    featureType.insertCap |= insertCap;
    featureType.updateCap |= updateCap;
    featureType.deleteCap |= deleteCap;

    mCaps.featureTypes.push_back( featureType );
  }

  Q_FOREACH ( const FeatureType& f, mCaps.featureTypes )
  {
    mCaps.setAllTypenames.insert( f.name );
    QString unprefixed( QgsWFSUtils::removeNamespacePrefix( f.name ) );
    if ( !mCaps.setAmbiguousUnprefixedTypename.contains( unprefixed ) )
    {
      if ( mCaps.mapUnprefixedTypenameToPrefixedTypename.contains( unprefixed ) )
      {
        mCaps.setAmbiguousUnprefixedTypename.insert( unprefixed );
        mCaps.mapUnprefixedTypenameToPrefixedTypename.remove( unprefixed );
      }
      else
      {
        mCaps.mapUnprefixedTypenameToPrefixedTypename[unprefixed] = f.name;
      }
    }
  }

  //go to <Filter_Capabilities>
  QDomElement filterCapabilitiesElem = doc.firstChildElement( "Filter_Capabilities" );
  if ( !filterCapabilitiesElem.isNull() )
    parseFilterCapabilities( filterCapabilitiesElem );

  // Hard-coded functions
  Function f_ST_GeometryFromText( "ST_GeometryFromText", 1, 2 );
  f_ST_GeometryFromText.returnType = "gml:AbstractGeometryType";
  f_ST_GeometryFromText.argumentList << Argument( "wkt", "xs:string" );
  f_ST_GeometryFromText.argumentList << Argument( "srsname", "xs:string" );
  mCaps.functionList << f_ST_GeometryFromText;

  Function f_ST_GeomFromGML( "ST_GeomFromGML", 1 );
  f_ST_GeomFromGML.returnType = "gml:AbstractGeometryType";
  f_ST_GeomFromGML.argumentList << Argument( "gml", "xs:string" );
  mCaps.functionList << f_ST_GeomFromGML;

  Function f_ST_MakeEnvelope( "ST_MakeEnvelope", 4, 5 );
  f_ST_MakeEnvelope.returnType = "gml:AbstractGeometryType";
  f_ST_MakeEnvelope.argumentList << Argument( "minx", "xs:double" );
  f_ST_MakeEnvelope.argumentList << Argument( "miny", "xs:double" );
  f_ST_MakeEnvelope.argumentList << Argument( "maxx", "xs:double" );
  f_ST_MakeEnvelope.argumentList << Argument( "maxy", "xs:double" );
  f_ST_MakeEnvelope.argumentList << Argument( "srsname", "xs:string" );
  mCaps.functionList << f_ST_MakeEnvelope;

  emit gotCapabilities();
}
Example #11
0
void Parser3::ParseVideoEntry( QDomNode Node, VideoPtr Info ) {

    QDomNode Child = Node.firstChild();

    if( Info->Releated.isNull() ) {
        Info->Releated = new VideoFeed;
        Info->Releated->Type = VideoFeed::FT_VideoReleated;
        Info->Releated->ParsedPages = 0;
        Info->Releated->HasFullFeed = false;
    } if( Info->Responces.isNull() ) {
        Info->Responces = new VideoFeed;
        Info->Responces->Type = VideoFeed::FT_VideoResponses;
        Info->Responces->ParsedPages = 0;
        Info->Responces->HasFullFeed = false;
    }


    while( !Child.isNull() )
    {
        QString NodeName = Child.nodeName();
        if( NodeName == "published" )
        {
            Info->Uploaded = QDate::fromString( Child.namedItem("#text").nodeValue(), Qt::ISODate );
        }
        else if( NodeName == "title" )
        {
            Info->Title = Child.namedItem("#text").nodeValue();
        }
        else if( NodeName == "link" )
        {
            QString RelValue = Child.attributes().namedItem("rel").nodeValue();
            if( RelValue == "http://gdata.youtube.com/schemas/2007#video.responses" )
            {
                Info->Releated->NextPageInFeed = QUrl( Child.attributes().namedItem("href").nodeValue() );
            }
            else if( RelValue == "http://gdata.youtube.com/schemas/2007#video.related" )
            {
                if( Info->Responces.isNull() )
                {
                Info->Responces->NextPageInFeed = QUrl( Child.attributes().namedItem("href").nodeValue() );
            }
            }
        }
        else if( NodeName == "author" )
        {
            Info->Author = Child.namedItem("name").namedItem("#text").nodeValue();
            Info->UrlAuthor = QUrl( Child.namedItem("uri").namedItem("#text").nodeValue() );
        }
        else if( NodeName == "gd:comments" )
        {
            Info->UrlComments = QUrl( Child.namedItem("gd:feedLink").attributes().namedItem("href").nodeValue() );
            Info->Comments = Child.namedItem("gd:feedLink").attributes().namedItem("countHint").nodeValue().toInt();
        }
        else if( NodeName == "media:group" )
        {
            Info->Description = Child.namedItem("media:description").namedItem("#text").nodeValue();
            Info->KeyWords = Child.namedItem("media:keywords").namedItem("#text").nodeValue();
            Info->Length = Child.namedItem("yt:duration").attributes().namedItem("seconds").nodeValue().toInt();
            /// The ID is const, but here we have to change it :/
            const_cast<QString&>( Info->ID ) = Child.namedItem("yt:videoid").namedItem("#text").nodeValue();
        }
        else if( NodeName == "gd:rating" )
        {
            Info->Rating = Child.attributes().namedItem("average").nodeValue().toFloat();
        }
        else if( NodeName == "yt:statistics" )
        {
            Info->Views = Child.attributes().namedItem("viewCount").nodeValue().toInt();
            Info->Favorites = Child.attributes().namedItem("favoriteCount").nodeValue().toInt();
        }
        else if( NodeName == "yt:rating" )
        {
            Info->Likes = Child.attributes().namedItem("numLikes").nodeValue().toInt();
            Info->DisLikes = Child.attributes().namedItem("numDislikes").nodeValue().toInt();
        }

        Child = Child.nextSibling();
    }

    Info->UrlThumbnail = QUrl( "http://i.ytimg.com/vi/"+Info->ID+"/hqdefault.jpg" );

    Info->FixInfo();
    return;
}
Example #12
0
void QWeather::parcer(QDomDocument doc)
{
    qDebug() << "parcer";
    QDomElement root = doc.documentElement();
    QDomNode n = root.firstChild();
    n = root.firstChild();
    n = n.firstChild();
    while(!n.isNull())
    {
       QDomElement e = n.toElement();

       if(!e.isNull())
       {
          if(e.tagName() == "yweather:location")
          {
             city = e.attribute("city", "");
             region = e.attribute("region", "");
             country = e.attribute("country", "");
          }
          else if(e.tagName() == "yweather:wind")
          {
             temperature = e.attribute("chill", "");
          }
          else if(e.tagName() == "yweather:atmosphere")
          {
             humidity = e.attribute("humidity", "");
             pressure = e.attribute("pressure", "");
          }
          else if(e.tagName() == "item")
          {
             n = n.firstChild();

             while(!n.isNull())
             {
                QDomElement e = n.toElement();

                if(!e.isNull())
                {
                   if(e.tagName() == "yweather:condition")
                   {
                      condition = e.attribute("text", "");
                      today_code = e.attribute("code", "");
                      temperature = e.attribute("temp","");
                      qDebug() << today_code;
                   }
                   if(e.tagName() == "yweather:forecast")
                   {
                       tomorrow_day = e.attribute("day","");
                       temperature_tomorrow_low = e.attribute("low","");
                       temperature_tomorrow_high = e.attribute("high","");
                       temperature_tomorrow_condition = e.attribute("text","");
                       tomorrow_code = e.attribute("code","");

                       n = n.nextSibling();
                       QDomElement e = n.toElement();
                       if(e.tagName() == "yweather:forecast")
                       {
                           d_a_t = e.attribute("day","");
                           d_a_t_low = e.attribute("low","");
                           d_a_t_high = e.attribute("high","");
                           d_a_t_condition = e.attribute("text","");
                           d_a_t_code = e.attribute("code","");
                       }

                   }
                }
                n = n.nextSibling();
             }

             n = n.parentNode();
          }
       }

       n = n.nextSibling();
    }
}
Example #13
0
void Doc_Test::save()
{
	Doc doc(this, m_fixtureDefCache);

	Scene* s = new Scene(&doc);
	doc.addFunction(s);

	Fixture* f1 = new Fixture(&doc);
	f1->setName("One");
	f1->setChannels(5);
	f1->setAddress(0);
	f1->setUniverse(0);
	doc.addFixture(f1);

	Chaser* c = new Chaser(&doc);
	doc.addFunction(c);

	Fixture* f2 = new Fixture(&doc);
	f2->setName("Two");
	f2->setChannels(10);
	f2->setAddress(20);
	f2->setUniverse(1);
	doc.addFixture(f2);

	Collection* o = new Collection(&doc);
	doc.addFunction(o);

	Fixture* f3 = new Fixture(&doc);
	f3->setName("Three");
	f3->setChannels(15);
	f3->setAddress(40);
	f3->setUniverse(2);
	doc.addFixture(f3);

	EFX* e = new EFX(&doc);
	doc.addFunction(e);

	QVERIFY(doc.isModified() == true);

	QDomDocument document;
	QDomElement root = document.createElement("TestRoot");

	QVERIFY(doc.saveXML(&document, &root) == true);

	unsigned int fixtures = 0, functions = 0, buses = 0;
	QDomNode node = root.firstChild();
	QVERIFY(node.toElement().tagName() == "Engine");

	node = node.firstChild();
	while (node.isNull() == false)
	{
		QDomElement tag = node.toElement();
		if (tag.tagName() == "Fixture")
			fixtures++;
		else if (tag.tagName() == "Function")
			functions++;
		else if (tag.tagName() == "Bus")
			buses++;
		else
			QFAIL(QString("Unexpected tag: %1")
					.arg(tag.tagName()).toAscii());

		node = node.nextSibling();
	}

	QVERIFY(fixtures == 3);
	QVERIFY(functions == 4);
	QVERIFY(buses == Bus::count());

	/* Saving doesn't implicitly reset modified status */
	QVERIFY(doc.isModified() == true);
}
Example #14
0
void ImportWindow::sImport()
{
  _log->append(tr("Import Started..."));
  QListWidgetItem * item = 0;
  QList<QListWidgetItem *> list = _reports->selectedItems();
  for(int i = 0; i < list.count(); i++)
  {
    item = list.at(i);
    QString xml_file = item->text();

    QString report_name  = QString::null;
    QString report_desc  = QString::null;
    QString report_src   = QString::null;
    int     report_grade = item->data(Qt::UserRole).toInt();

    if(!xml_file.isEmpty())
    {
      QFile file(xml_file);
      if(file.open(QIODevice::ReadOnly))
      {
        QDomDocument doc;
        QString errMsg;
        int errLine, errCol;
        if(doc.setContent(&file, &errMsg, &errLine, &errCol))
        {
          QDomElement root = doc.documentElement();
          if(root.tagName() == "report")
          {
            for(QDomNode n = root.firstChild();
                  !n.isNull(); n = n.nextSibling())
            {
              if(n.nodeName() == "name")
                report_name = n.firstChild().nodeValue();
              else if(n.nodeName() == "description")
                report_desc = n.firstChild().nodeValue();
            }
            report_src = doc.toString();

            if(!report_name.isEmpty())
            {
              QSqlQuery qry;
              QSqlQuery query;

              qry.prepare(getSqlFromTag("fmt09", QSqlDatabase::database().driverName()));	// MANU
              qry.bindValue(":report_name",  report_name);	// MANU
              qry.bindValue(":report_grade", report_grade);	// MANU
              qry.exec();
              if(qry.first())
              {
                // update
                query.prepare(getSqlFromTag("fmt10", QSqlDatabase::database().driverName()));	// MANU
                query.bindValue(":report_desc", report_desc);		// MANU
                query.bindValue(":report_src",   report_src);		// MANU
                query.bindValue(":report_id", qry.value(0));		// MANU
                query.bindValue(":report_name",  report_name);	// MANU
              }
              else
              {
                // insert
                query.prepare(getSqlFromTag("fmt11", QSqlDatabase::database().driverName()));	// MANU
                query.bindValue(":report_name",  report_name);	// MANU
                query.bindValue(":report_desc", report_desc);		// MANU
                query.bindValue(":report_src",   report_src);		// MANU
                query.bindValue(":report_grade", report_grade);	// MANU
              }
              
              if(!query.exec())
              {
                QSqlError err = query.lastError();
                _log->append(tr("<font color=red>The following error was encountered while trying to import %1 into the database:\n"
                                "\t%2\n\t%3\n</font>")
                              .arg(xml_file)
                              .arg(err.driverText())
                              .arg(err.databaseText()));
              }
              else
                _log->append(tr("Import successful of %1").arg(xml_file));
            }
            else
              _log->append(tr("<font color=orange>The document %1 does not have a report name defined\n</font>")
                            .arg(xml_file));
          }
          else
            _log->append(tr("<font color=red>XML Document %1 does not have root node of report\n</font>")
                          .arg(xml_file));
        }
        else
          _log->append(tr("<font color=red>Error parsing file %1: %2 on line %3 column %4\n</font>")
                        .arg(xml_file).arg(errMsg).arg(errLine).arg(errCol));
      }
      else
        _log->append(tr("<font color=red>Could not open the specified file: %1\n</font>")
                      .arg(xml_file));
    }
    else
      _log->append("<font color=red>Encountered and empty entry: No file name was given.\n</font>");
  }
  _log->append(tr("Import complete!\n\n\n"));
}
// Slot called by the menu manager on user action
void UAVSettingsImportExportFactory::importUAVSettings()
{
    // ask for file name
    QString fileName;
    QString filters = tr("UAVObjects XML files (*.uav);; XML files (*.xml)");

    fileName = QFileDialog::getOpenFileName(0, tr("Import UAV Settings"), "", filters);
    if (fileName.isEmpty()) {
        return;
    }

    // Now open the file
    QFile file(fileName);
    QDomDocument doc("UAVObjects");
    file.open(QFile::ReadOnly | QFile::Text);
    if (!doc.setContent(file.readAll())) {
        QMessageBox msgBox;
        msgBox.setText(tr("File Parsing Failed."));
        msgBox.setInformativeText(tr("This file is not a correct XML file"));
        msgBox.setStandardButtons(QMessageBox::Ok);
        msgBox.exec();
        return;
    }
    file.close();

    // find the root of settings subtree
    emit importAboutToBegin();
    qDebug() << "Import about to begin";

    QDomElement root = doc.documentElement();
    if (root.tagName() == "uavobjects") {
        root = root.firstChildElement("settings");
    }
    if (root.isNull() || (root.tagName() != "settings")) {
        QMessageBox msgBox;
        msgBox.setText(tr("Wrong file contents"));
        msgBox.setInformativeText(tr("This file does not contain correct UAVSettings"));
        msgBox.setStandardButtons(QMessageBox::Ok);
        msgBox.exec();
        return;
    }

    // We are now ok: setup the import summary dialog & update it as we
    // go along.
    ImportSummaryDialog swui((QWidget *)Core::ICore::instance()->mainWindow());

    ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance();
    UAVObjectManager *objManager = pm->getObject<UAVObjectManager>();
    swui.show();

    QDomNode node = root.firstChild();
    while (!node.isNull()) {
        QDomElement e = node.toElement();
        if (e.tagName() == "object") {
            // - Read each object
            QString uavObjectName = e.attribute("name");
            uint uavObjectID = e.attribute("id").toUInt(NULL, 16);

            // Sanity Check:
            UAVObject *obj   = objManager->getObject(uavObjectName);
            if (obj == NULL) {
                // This object is unknown!
                qDebug() << "Object unknown:" << uavObjectName << uavObjectID;
                swui.addLine(uavObjectName, "Error (Object unknown)", false);
            } else {
                // - Update each field
                // - Issue and "updated" command
                bool error     = false;
                bool setError  = false;
                QDomNode field = node.firstChild();
                while (!field.isNull()) {
                    QDomElement f = field.toElement();
                    if (f.tagName() == "field") {
                        UAVObjectField *uavfield = obj->getField(f.attribute("name"));
                        if (uavfield) {
                            QStringList list = f.attribute("values").split(",");
                            if (list.length() == 1) {
                                if (false == uavfield->checkValue(f.attribute("values"))) {
                                    qDebug() << "checkValue returned false on: " << uavObjectName << f.attribute("values");
                                    setError = true;
                                } else {
                                    uavfield->setValue(f.attribute("values"));
                                }
                            } else {
                                // This is an enum:
                                int i = 0;
                                QStringList list = f.attribute("values").split(",");
                                foreach(QString element, list) {
                                    if (false == uavfield->checkValue(element, i)) {
                                        qDebug() << "checkValue(list) returned false on: " << uavObjectName << list;
                                        setError = true;
                                    } else {
                                        uavfield->setValue(element, i);
                                    }
                                    i++;
                                }
                            }
                        } else {
                            error = true;
                        }
                    }
                    field = field.nextSibling();
                }
                obj->updated();

                if (error) {
                    swui.addLine(uavObjectName, "Warning (Object field unknown)", true);
                } else if (uavObjectID != obj->getObjID()) {
                    qDebug() << "Mismatch for Object " << uavObjectName << uavObjectID << " - " << obj->getObjID();
                    swui.addLine(uavObjectName, "Warning (ObjectID mismatch)", true);
                } else if (setError) {
                    swui.addLine(uavObjectName, "Warning (Objects field value(s) invalid)", false);
                } else {
                    swui.addLine(uavObjectName, "OK", true);
                }
            }
Example #16
0
QDomDocument SOAPClient::SendSOAPRequest(const QString &sMethod,
                                         QStringMap    &list,
                                         int           &nErrCode,
                                         QString       &sErrDesc)
{
    QUrl url(m_url);

    url.setPath(m_sControlPath);

    nErrCode = UPnPResult_Success;
    sErrDesc = "";

    QDomDocument xmlResult;
    if (m_sNamespace.isEmpty())
    {
        nErrCode = UPnPResult_MythTV_NoNamespaceGiven;
        sErrDesc = "No namespace given";
        return xmlResult;
    }

    // --------------------------------------------------------------
    // Add appropriate headers
    // --------------------------------------------------------------
    QHash<QByteArray, QByteArray> headers;

    headers.insert("Content-Type", "text/xml; charset=\"utf-8\"");
    QString soapHeader = QString("\"%1#%2\"").arg(m_sNamespace).arg(sMethod);
	headers.insert("SOAPACTION", soapHeader.toUtf8());
    headers.insert("User-Agent", "Mozilla/9.876 (X11; U; Linux 2.2.12-20 i686, en) "
                                 "Gecko/25250101 Netscape/5.432b1");
    // --------------------------------------------------------------
    // Build request payload
    // --------------------------------------------------------------

    QByteArray  aBuffer;
    QTextStream os( &aBuffer );

    os.setCodec("UTF-8");

    os << "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n"; 
    os << "<s:Envelope "
        " s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\""
        " xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">\r\n";
    os << " <s:Body>\r\n";
    os << "  <u:" << sMethod << " xmlns:u=\"" << m_sNamespace << "\">\r\n";

    // --------------------------------------------------------------
    // Add parameters from list
    // --------------------------------------------------------------

    for (QStringMap::iterator it = list.begin(); it != list.end(); ++it)
    {                                                               
        os << "   <" << it.key() << ">";
        os << HTTPRequest::Encode( *it );
        os << "</"   << it.key() << ">\r\n";
    }

    os << "  </u:" << sMethod << ">\r\n";
    os << " </s:Body>\r\n";
    os << "</s:Envelope>\r\n";

    os.flush();

    // --------------------------------------------------------------
    // Perform Request
    // --------------------------------------------------------------

    LOG(VB_UPNP, LOG_DEBUG,
        QString("SOAPClient(%1) sending:\n %2").arg(url.toString()).arg(aBuffer.constData()));

    QString sXml;

    if (!GetMythDownloadManager()->postAuth(url.toString(), &aBuffer, NULL, NULL, &headers))
    {
        LOG(VB_GENERAL, LOG_ERR, QString("SOAPClient::SendSOAPRequest: request failed: %1")
                                         .arg(url.toString()));
    }
    else
        sXml = QString(aBuffer);

    // --------------------------------------------------------------
    // Parse response
    // --------------------------------------------------------------

    LOG(VB_UPNP, LOG_DEBUG, "SOAPClient response:\n" +
                            QString("%1\n").arg(sXml));

    // TODO handle timeout without response correctly.

    list.clear();

    QDomDocument doc;

    if (!doc.setContent(sXml, true, &sErrDesc, &nErrCode))
    {
        LOG(VB_UPNP, LOG_ERR,
            QString("SendSOAPRequest( %1 ) - Invalid response from %2")
                .arg(sMethod).arg(url.toString()) + 
            QString("%1: %2").arg(nErrCode).arg(sErrDesc));

        return xmlResult;
    }

    // --------------------------------------------------------------
    // Is this a valid response?
    // --------------------------------------------------------------

    QString      sResponseName = sMethod + "Response";
    QDomNodeList oNodeList     =
        doc.elementsByTagNameNS(m_sNamespace, sResponseName);

    if (oNodeList.count() == 0)
    {
        // --------------------------------------------------------------
        // Must be a fault... parse it to return reason
        // --------------------------------------------------------------

        nErrCode = GetNodeValue(
            doc, "Envelope/Body/Fault/detail/UPnPError/errorCode", 500);
        sErrDesc = GetNodeValue(
            doc, "Envelope/Body/Fault/detail/UPnPError/errorDescription", "");
        if (sErrDesc.isEmpty())
            sErrDesc = QString("Unknown #%1").arg(nErrCode);

        QDomNode oNode  = FindNode( "Envelope/Body/Fault", doc );

        oNode = xmlResult.importNode( oNode, true );
        xmlResult.appendChild( oNode );

        return xmlResult;
    }

    QDomNode oMethod = oNodeList.item(0);
    if (oMethod.isNull())
        return xmlResult;

    QDomNode oNode = oMethod.firstChild(); 
    for (; !oNode.isNull(); oNode = oNode.nextSibling())
    {
        QDomElement e = oNode.toElement();
        if (e.isNull())
            continue;

        QString sName  = e.tagName();
        QString sValue = "";
    
        QDomText  oText = oNode.firstChild().toText();
    
        if (!oText.isNull())
            sValue = oText.nodeValue();

        list.insert(QUrl::fromPercentEncoding(sName.toUtf8()),
                    QUrl::fromPercentEncoding(sValue.toUtf8()));
    }

    // Create copy of oMethod that can be used with xmlResult.

    oMethod = xmlResult.importNode( oMethod.firstChild(), true  );

    // importNode does not attach the new nodes to the document,
    // do it here.

    xmlResult.appendChild( oMethod );

    return xmlResult;
}
void DebuggerManager::slotNewProjectLoaded(const QString &projectname, const KURL &, const KURL &)
{
  if(m_client)
  {
    
    disconnect(m_client, SIGNAL(updateStatus(DebuggerUI::DebuggerStatus)), m_debuggerui, SLOT(slotStatus(DebuggerUI::DebuggerStatus)));

    delete m_client;
    m_client = NULL;
  }
  enableAction("*", false);
  
  // Remove all breakpoints
  m_breakpointList->clear();
  
  if(m_debuggerui)
  {
    delete m_debuggerui;
    m_debuggerui = NULL;
  }
  //kdDebug(24002) << "DebuggerManager::slotNewProjectLoaded " << projectname << ", " << Project::ref()->debuggerClient << endl;

  // Load new client
  if(!projectname.isEmpty())
  {

    KTrader::OfferList offers = KTrader::self()->query("Quanta/Debugger");
    KTrader::OfferList::ConstIterator iterDbg;
    for(iterDbg = offers.begin(); iterDbg != offers.end(); ++iterDbg)
    {
      KService::Ptr service = *iterDbg;
      if(Project::ref()->debuggerClient() == service->name())
      {
        int errCode = 0;
//Workaround for dynamic_cast not working correctly on SUSE 10, gcc 4.0.2
//The correct way should be a simple:
// m_client = KParts::ComponentFactory::createInstanceFromService<DebuggerClient>(service, this, 0, QStringList(), &errCode);
        QObject* obj = KParts::ComponentFactory::createInstanceFromService<QObject>(service, this, 0, QStringList(), &errCode);
        if (obj && obj->inherits("DebuggerClient"))
          m_client = static_cast<DebuggerClient *>(obj);

        //kdDebug(24002) << service->name() << " (" << m_client << ")" << endl;

        if(!m_client)
        {
          emit hideSplash();
          KMessageBox::error(NULL, i18n("<qt>Unable to load the debugger plugin, error code %1 was returned: <b>%2</b>.</qt>").arg(errCode).arg(KLibLoader::self()->lastErrorMessage()), i18n("Debugger Error"));
        }
        break;
      }
    }
  }

  // Tell client to load its settings
  if (m_client)
  {
    QDomNode nodeThisDbg;
    QDomDocument *dom = Project::ref()->sessionDom();
    QDomNode projectNode = dom->firstChild().firstChild();
    QDomNode nodeDbg  = projectNode.namedItem("debuggers");
    if(nodeDbg.isNull())
    {
      nodeDbg = dom->createElement("debuggers");
      projectNode.appendChild(nodeDbg);
    }

    // Load this project's mapped paths
    m_pathmapper->readConfig();
    
    // Load this projects debugger's settings
    nodeThisDbg = nodeDbg.namedItem(m_client->getName());
    if(nodeThisDbg.isNull())
    {
      nodeThisDbg = dom->createElement(m_client->getName());
      nodeDbg.appendChild(nodeThisDbg);
    }

    m_client->readConfig(nodeThisDbg);

    // recreate UI
    m_debuggerui = new DebuggerUI(this, "debuggerui");
    connect(m_client, SIGNAL(updateStatus(DebuggerUI::DebuggerStatus)), m_debuggerui, SLOT(slotStatus(DebuggerUI::DebuggerStatus)));
    
    // Load saved breakpoints
    if(Project::ref()->debuggerPersistentBreakpoints())
    {
      QDomNode nodeBreakpoints = nodeDbg.namedItem("breakpoints");
      if(!nodeBreakpoints.isNull())
      {
        QDomNode child = nodeBreakpoints.firstChild();
        while(!child.isNull())
        {
          DebuggerBreakpoint* bp = new DebuggerBreakpoint();
          bp->setFilePath( child.attributes().namedItem("filepath").nodeValue());
          bp->setClass( child.attributes().namedItem("class").nodeValue());
          bp->setFunction( child.attributes().namedItem("function").nodeValue());
          bp->setCondition( child.attributes().namedItem("condition").nodeValue());
          bp->setLine( child.attributes().namedItem("line").nodeValue().toLong());
          if(child.attributes().namedItem("type").nodeValue() == "true")
            bp->setType(DebuggerBreakpoint::ConditionalTrue);
          else if(child.attributes().namedItem("type").nodeValue() == "change")
            bp->setType(DebuggerBreakpoint::ConditionalChange);
          else
            bp->setType(DebuggerBreakpoint::LineBreakpoint);
          
          // Update client and ui
          m_client->addBreakpoint(bp);
          m_breakpointList->add(bp);
          
          // loop
          child = child.nextSibling();
        }
      }
    }

    // Load saved Watches
    if(Project::ref()->debuggerPersistentWatches())
    {
      QDomNode nodeWatches = nodeDbg.namedItem("watches");
      if(!nodeWatches.isNull())
      {
        QDomNode child = nodeWatches.firstChild();
        while(!child.isNull())
        {
          QString watch = child.attributes().namedItem("name").nodeValue();
          DebuggerVariable *var = new DebuggerVariable(watch, "", DebuggerVariableTypes::Undefined);
          m_debuggerui->addVariable(var);
          m_client->addWatch(watch);

          child = child.nextSibling();
        }
      }
    }

  }

  initClientActions();

  // Disable all debugactions that need a session (ie not breakpoints, etc)
  slotDebugStartSession();
}
void QgsWFSCapabilities::capabilitiesReplyFinished()
{
  // handle network errors
  if ( mCapabilitiesReply->error() != QNetworkReply::NoError )
  {
    mErrorCode = QgsWFSCapabilities::NetworkError;
    mErrorMessage = mCapabilitiesReply->errorString();
    emit gotCapabilities();
    return;
  }

  // handle HTTP redirects
  QVariant redirect = mCapabilitiesReply->attribute( QNetworkRequest::RedirectionTargetAttribute );
  if ( !redirect.isNull() )
  {
    QgsDebugMsg( "redirecting to " + redirect.toUrl().toString() );
    QNetworkRequest request( redirect.toUrl() );
    request.setAttribute( QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferNetwork );
    request.setAttribute( QNetworkRequest::CacheSaveControlAttribute, true );

    mCapabilitiesReply->deleteLater();
    mCapabilitiesReply = QgsNetworkAccessManager::instance()->get( request );

    connect( mCapabilitiesReply, SIGNAL( finished() ), this, SLOT( capabilitiesReplyFinished() ) );
    return;
  }

  QByteArray buffer = mCapabilitiesReply->readAll();

  QgsDebugMsg( "parsing capabilities: " + buffer );

  // parse XML
  QString capabilitiesDocError;
  QDomDocument capabilitiesDocument;
  if ( !capabilitiesDocument.setContent( buffer, true, &capabilitiesDocError ) )
  {
    mErrorCode = QgsWFSCapabilities::XmlError;
    mErrorMessage = capabilitiesDocError;
    emit gotCapabilities();
    return;
  }

  QDomElement doc = capabilitiesDocument.documentElement();

  // hangle exceptions
  if ( doc.tagName() == "ExceptionReport" )
  {
    QDomNode ex = doc.firstChild();
    QString exc = ex.toElement().attribute( "exceptionCode", "Exception" );
    QDomElement ext = ex.firstChild().toElement();
    mErrorCode = QgsWFSCapabilities::ServerExceptionError;
    mErrorMessage = exc + ": " + ext.firstChild().nodeValue();
    emit gotCapabilities();
    return;
  }

  mCaps.clear();

  // get the <FeatureType> elements
  QDomNodeList featureTypeList = capabilitiesDocument.elementsByTagNameNS( WFS_NAMESPACE, "FeatureType" );
  for ( unsigned int i = 0; i < featureTypeList.length(); ++i )
  {
    FeatureType featureType;
    QDomElement featureTypeElem = featureTypeList.at( i ).toElement();

    //Name
    QDomNodeList nameList = featureTypeElem.elementsByTagNameNS( WFS_NAMESPACE, "Name" );
    if ( nameList.length() > 0 )
    {
      featureType.name = nameList.at( 0 ).toElement().text();
    }
    //Title
    QDomNodeList titleList = featureTypeElem.elementsByTagNameNS( WFS_NAMESPACE, "Title" );
    if ( titleList.length() > 0 )
    {
      featureType.title = titleList.at( 0 ).toElement().text();
    }
    //Abstract
    QDomNodeList abstractList = featureTypeElem.elementsByTagNameNS( WFS_NAMESPACE, "Abstract" );
    if ( abstractList.length() > 0 )
    {
      featureType.abstract = abstractList.at( 0 ).toElement().text();
    }

    //DefaultSRS is always the first entry in the feature srs list
    QDomNodeList defaultCRSList = featureTypeElem.elementsByTagNameNS( WFS_NAMESPACE, "DefaultSRS" );
    if ( defaultCRSList.length() > 0 )
    {
      featureType.crslist.append( defaultCRSList.at( 0 ).toElement().text() );
    }

    //OtherSRS
    QDomNodeList otherCRSList = featureTypeElem.elementsByTagNameNS( WFS_NAMESPACE, "OtherSRS" );
    for ( unsigned int i = 0; i < otherCRSList.length(); ++i )
    {
      featureType.crslist.append( otherCRSList.at( i ).toElement().text() );
    }

    //Support <SRS> for compatibility with older versions
    QDomNodeList srsList = featureTypeElem.elementsByTagNameNS( WFS_NAMESPACE, "SRS" );
    for ( unsigned int i = 0; i < srsList.length(); ++i )
    {
      featureType.crslist.append( srsList.at( i ).toElement().text() );
    }

    mCaps.featureTypes.append( featureType );
  }

  mCapabilitiesReply->deleteLater();
  mCapabilitiesReply = 0;
  emit gotCapabilities();
}
Example #19
0
bool RCCResourceLibrary::interpretResourceFile(QIODevice *inputDevice, QString fname, QString currentPath)
{
    if (!currentPath.isEmpty() && !currentPath.endsWith(QLatin1String("/")))
        currentPath += '/';

    QDomDocument document;
    {
        QString errorMsg;
        int errorLine, errorColumn;
        if(!document.setContent(inputDevice, &errorMsg, &errorLine, &errorColumn)) {
            fprintf(stderr, "pyrcc4 Parse Error:%s:%d:%d [%s]\n", fname.toLatin1().constData(),
                    errorLine, errorColumn, errorMsg.toLatin1().constData());
            return false;
        }
    }
    for(QDomElement root = document.firstChild().toElement(); !root.isNull();
        root = root.nextSibling().toElement()) {
        if (root.tagName() != QLatin1String(TAG_RCC))
            continue;

        for (QDomElement child = root.firstChild().toElement(); !child.isNull();
             child = child.nextSibling().toElement()) {
            if (child.tagName() == QLatin1String(TAG_RESOURCE)) {
                QLocale lang = QLocale::c();
                if (child.hasAttribute(ATTRIBUTE_LANG))
                    lang = QLocale(child.attribute(ATTRIBUTE_LANG));

                QString prefix;
                if (child.hasAttribute(ATTRIBUTE_PREFIX))
                    prefix = child.attribute(ATTRIBUTE_PREFIX);
                if (!prefix.startsWith(QLatin1String("/")))
                    prefix.prepend('/');
                if (!prefix.endsWith(QLatin1String("/")))
                    prefix += '/';


                for (QDomNode res = child.firstChild(); !res.isNull(); res = res.nextSibling()) {
                    if (res.toElement().tagName() == QLatin1String(TAG_FILE)) {

                        QString fileName(res.firstChild().toText().data());
                        if (fileName.isEmpty())
                            fprintf(stderr, "Warning: Null node in XML\n");

                        QString alias;
                        if (res.toElement().hasAttribute(ATTRIBUTE_ALIAS))
                            alias = res.toElement().attribute(ATTRIBUTE_ALIAS);
                        else
                            alias = fileName;

                        int compressLevel = mCompressLevel;
                        if (res.toElement().hasAttribute(ATTRIBUTE_COMPRESS))
                            compressLevel = res.toElement().attribute(ATTRIBUTE_COMPRESS).toInt();
                        int compressThreshold = mCompressThreshold;
                        if (res.toElement().hasAttribute(ATTRIBUTE_THRESHOLD))
                            compressThreshold = res.toElement().attribute(ATTRIBUTE_THRESHOLD).toInt();

                        // Special case for -no-compress. Overrides all other settings.
                        if (mCompressLevel == -2)
                            compressLevel = 0;

                        alias = QDir::cleanPath(alias);
                        while (alias.startsWith("../"))
                            alias.remove(0, 3);
                        alias = prefix + alias;

                        QFileInfo file(currentPath + fileName);
                        if (!file.exists()) {
                            fprintf(stderr, "Cannot find file: %s\n", fileName.toLatin1().constData());
                            continue ;
                        } else if (file.isFile()) {
                            addFile(alias, RCCFileInfo(alias.section('/', -1), file, lang,
                                                       RCCFileInfo::NoFlags, compressLevel, compressThreshold));
                        } else {
                            QDir dir;
                            if(file.isDir()) {
                                dir.setPath(file.filePath());
                            } else {
                                dir.setPath(file.path());
                                dir.setNameFilters(QStringList(file.fileName()));
                                if(alias.endsWith(file.fileName()))
                                    alias = alias.left(alias.length()-file.fileName().length());
                            }
                            if (!alias.endsWith(QLatin1String("/")))
                                alias += '/';
                            QFileInfoList children = dir.entryInfoList();
                            for(int i = 0; i < children.size(); ++i) {
                                if(children[i].fileName() != QLatin1String(".") &&
                                   children[i].fileName() != QLatin1String(".."))
                                    addFile(alias + children[i].fileName(),
                                            RCCFileInfo(children[i].fileName(), children[i], lang,
                                                        RCCFileInfo::NoFlags, compressLevel, compressThreshold));
                            }
                        }
                    }
                }
            }
        }
    }
    if(this->root == 0) {
        fprintf(stderr, "No resources in resource description.\n");
        return false;
    }
    return true;
}
Example #20
0
void Configurator::loadItem( QListWidgetItem* item )
{
	if( 0 == item )
		return;
	
	// searching corresponding section
	QString     sectionName     = item->listWidget()->objectName();
	QDomNode    configurator    = _domDocument.documentElement();
	QDomNode    section         = configurator.firstChild();
	while( false == section.isNull() )
	{
		QDomNamedNodeMap sectionAttributes = section.attributes();
		if( sectionName == sectionAttributes.namedItem(c_attributeName).nodeValue() )
			break;

		section = section.nextSibling();
	}

	// having section, searching for the sectionItem
	QString     sectionItemName = item->data( Qt::UserRole ).toString();
	QDomNode    sectionItem     = section.firstChild();
	while( false == sectionItem.isNull() )
	{
		QDomNamedNodeMap sectionItemAttributes = sectionItem.attributes();

		if( QDomNode::CommentNode != section.nodeType() )
		if( sectionItemName == sectionItemAttributes.namedItem(c_attributeName).nodeValue() )
			break;

		sectionItem = sectionItem.nextSibling();
	}

	// destroying all previous controls from the frame
	QObjectList children = _configOptions->children();
	foreach( QObject* child, children )
		delete child;	

	// vertical-layout all the frame's objects
	QVBoxLayout* verticalLayout = new QVBoxLayout( _configOptions );

	// at this step we have everything to start load data from DOM
	QDomNode control = sectionItem.firstChild();
	while( false == control.isNull() )
	{
		// note: not all the nodes met will have these attributes, speciffic nodes will have some of these
		QDomNamedNodeMap			  controlAttributes = control.attributes();
		QString controlName		= controlAttributes.namedItem( c_attributeName  ).nodeValue();
		QString controlText		= controlAttributes.namedItem( c_attributeText  ).nodeValue();
		QString controlType		= controlAttributes.namedItem( c_attributeType  ).nodeValue();
		QString controlValue		= controlAttributes.namedItem( c_attributeValue ).nodeValue();

		switch( getControlTypeByName(controlType) )
		{
			case	eFontChooser	: verticalLayout->addWidget( createFontChooser(controlName,controlText,controlValue)					);	break;
			case	eColorChooser	: verticalLayout->addWidget( createColorChooser(controlName,controlText,controlValue)					);	break;
			case	ePathChooser	: verticalLayout->addWidget( createPathChooser(controlName,controlText,controlValue)					);	break;
			case	eRadioBoxes	: verticalLayout->addWidget( createRadioBoxes(controlName,controlText,controlValue,control.firstChild())	);	break;
			case	eCheckBoxes	: verticalLayout->addWidget( createCheckBoxes(controlName,controlText,controlValue,control.firstChild())	);	break;
			case	eTextViewer	: verticalLayout->addWidget( createTextViewer(controlName,control)									);	break;
			case	eLineInput	: verticalLayout->addWidget( createLineInput(controlName,controlText,controlValue)						);	break;
			case	ePlugins      : verticalLayout->addWidget( createPlugins(controlName,controlValue)                                      );	break;

			default:
				break;			
		}

		control = control.nextSibling();
	}
}
Example #21
0
//Process a table in the manifest. This fuction is recursive
int procTable(QSqlDatabase db,QVariantMap jsonData, QDomNode table, QList< TfieldDef> parentkeys)
{
    QList< TfieldDef> keys;
    QList< TfieldDef> tkeys;
    QList< TtableKey> tableKeys;
    keys.append(parentkeys);

    QList< TfieldDef> fields;

    bool sqlCreated;
    sqlCreated = false;

    QString tableCode;
    bool tableSeparated;
    tableCode = table.toElement().attribute("mysqlcode");

    int recordIndex;
    int tkindex;


    if (tableCode == "af_rpt_secf_anmlsrcfd")
        log("Table:" + tableCode);

    //log(tableCode);

    QString tableXMLCode;
    tableXMLCode = table.toElement().attribute("xmlcode");

    bool genSQL;

    QDomNode child;
    child = table.firstChild();



    while (!child.isNull())
    {
        if (child.toElement().nodeName() == "field")
        {
            //We not process referenced fields because they come as part of the key
            if (child.toElement().attribute("reference") == "false")
            {
                TfieldDef field;
                field.name = child.toElement().attribute("mysqlcode");
                field.xmlCode = child.toElement().attribute("xmlcode");
                if (child.toElement().attribute("key").toStdString() == "true")
                    field.key = true;
                else
                    field.key = false;
                fields.append(field); //Append the field to the list of fields
            }
            genSQL = true;
        }
        else
        {
            sqlCreated = true; //To control more than one child table
            if ((tableXMLCode == "main") || (table.parentNode().toElement().tagName() == "ODKImportXML"))
            {
                mainTable = tableCode;
                if (genSQL == true)
                {
                    if (tableXMLCode == "main")
                        keys.append(createSQL(db,jsonData,tableCode,fields,keys,true));
                    else
                    {
                        // if we are processing the first table and is not main, this means that a repeat of one was used
                        // to store the cover data. Therefore the insert SQL must use both the information on root (jsonData)
                        // and the information on the repeat of one (map)
                        QVariantList result = jsonData[tableXMLCode].toList();
                        foreach(QVariant record, result)
                        {
                            QVariantMap map = record.toMap();
                            //debugMap(jsonData);
                            //debugMap(map);
                            keys.append(createSQL(db,jsonData,tableCode,fields,keys,true,map));
                        }
                    }
                    genSQL = false;
                }
                procTable(db,jsonData,child,keys); //Recursive call of a table from main
            }
            else
            {
                if (child.toElement().attribute("separated","false") == "true")
Example #22
0
void Configurator::saveItem( QListWidgetItem* item )
{
	if( 0 == item )
		return;

	// searching for the corresponding group-node
    QString     sectionName		= item->listWidget()->objectName();
	QDomNode    configurator    = _domDocument.documentElement();
	QDomNode    section		    = configurator.firstChild();
	while( false == section.isNull() )
	{
		QDomNamedNodeMap sectionAttributes = section.attributes();
		
		if( QDomNode::CommentNode != section.nodeType() )
		if( sectionName == sectionAttributes.namedItem(c_attributeName).nodeValue() )
			break;

		section = section.nextSibling();
	}

	// having section, searching for the sectionItem
	QString     sectionItemName = item->text();
	QDomNode    sectionItem     = section.firstChild();
	while( false == sectionItem.isNull() )
	{
		QDomNamedNodeMap sectionItemAttributes = sectionItem.attributes();
		
		if( QDomNode::CommentNode != section.nodeType() )
		if( sectionItemName == sectionItemAttributes.namedItem(c_attributeText).nodeValue() )
			break;

		sectionItem = sectionItem.nextSibling();
	}

    // at this step we have everything to start save data back to DOM
    QDomNode control = sectionItem.firstChild();
    while( false == control.isNull() )
    {
        QDomNamedNodeMap          controlAttributes = control.attributes();
        QString controlName     = controlAttributes.namedItem(c_attributeName).nodeValue();
        QString controlText     = controlAttributes.namedItem(c_attributeText).nodeValue();
        QString controlType     = controlAttributes.namedItem(c_attributeType).nodeValue();
        QString controlValue    = controlAttributes.namedItem(c_attributeValue).nodeValue();
        
        switch( getControlTypeByName(controlType) )
        {
            case eFontChooser	: saveFontChooser   ( controlName, controlAttributes    ); break;
            case eColorChooser  : saveColorChooser  ( controlName, controlAttributes    ); break;
            case ePathChooser	: savePathChooser   ( controlName, controlAttributes    ); break;
            case eRadioBoxes	: saveRadioBoxes    ( controlName, control.firstChild() ); break;
            case eCheckBoxes	: saveCheckBoxes    ( controlName, control.firstChild() ); break;
            case eLineInput     : saveLineInput     ( controlName, controlAttributes    ); break;
            case ePlugins       : savePlugins       ( controlName, controlAttributes    ); break;
            
            default:
                break;			
        }
        
        // moving to the next control
        control = control.nextSibling();
    }
}
Example #23
0
/*!
    \fn FormActualizacion::analizarGeneral()
        Funcion que analiza el archivo xml de actualizaciones para comprobar las descargas
 */
void FormActualizacion::analizarGeneral()
{
  QDomDocument *docxml = new QDomDocument();
  int linea,columna; QString mensaje;
  if( !docxml->setContent( ftp->readAll(), false, &mensaje, &linea, &columna ) )
  {
   TELog->append( "Error al cargar el contenido del archivo de actualizaciones" );
   qDebug( QString( "Error: f:%1,c:%2; m=%3 " ).arg( linea ).arg(columna ).arg(mensaje ).toLocal8Bit() );
   _continuar_actualizando = false;
   return;
  }
  else
  {
   TELog->append( "Descarga correcta." );
   qDebug( "Descarga Correcta" );
  }

  TELog->append( "Analizando actualizaciones disponibles" );
  QDomElement docElem = docxml->documentElement();
  qDebug( QString( "Primer hijo: %1" ).arg( docElem.tagName() ).toLocal8Bit() );
  if( docElem.tagName() == "actualizacion" )
  {
        qDebug( "Encontrado nodo de actualizacion" );
  }
  if( docElem.attribute( "version", 0 ).toDouble() > VERSION_PROGRAMA )
  {
        TELog->append( "No existen actualizaciones para esta version de Gestotux. Por Favor actualize el programa a una version superior" );
        ftp->clearPendingCommands();
        ftp->close();
        _continuar_actualizando = false;
        return;
  }
  else
  {
        TELog->append( "No se necesita actualizar el programa general." );
        //Ingreso al directorio de la version del programa
        ftp->cd( QString::number( docElem.attribute( "version", 0 ).toDouble() ) );
        qDebug( QString( "entrando en: %1" ).arg( docElem.attribute( "version", 0 ).toDouble() ).toLocal8Bit() );

        // Busco si hay algo dentro de archivos
        /*QDomNode nodo_archivos = docxml->elementsByTagName( "archivos" ).item(0);
        if( nodo_archivos.hasChildNodes() )
        {
                qDebug( "Encontrada etiqueta de archivos generales" );
                ///\todo Esto todavia no defini como lo voy a hacer
        }*/
        qDebug( QString( "Encontrada version :%1" ).arg( docElem.attribute( "version", 0 ) ).toLocal8Bit() );
        // Busco los plugins
        while( docElem.hasChildNodes() )
        {
                if( !_continuar_actualizando )
                { return; }
                QDomNode nodoA = docElem.firstChild();
                if( nodoA.toElement().tagName() == "plugin" )
                {
                        // Tengo instalado el plugin??
                        qDebug( QString( "Encontrado plugin %1" ).arg( nodoA.toElement().attribute( "nombre" ) ).toLocal8Bit() );
                        QString nombre = nodoA.toElement().attribute( "nombre" );
                        if( ERegistroPlugins::getInstancia()->pluginsHash()->find( nombre ) == ERegistroPlugins::getInstancia()->pluginsHash()->end() )
                        {
                                qDebug( QString( "El plugin %1 no se encuentra en este sistema, no se descargara ni actualizar?" ).arg( nombre ).toLocal8Bit() );
                                docElem.removeChild( nodoA );
                                continue;
                        }
                        // ingreso a la carpeta del plugin
                        ftp->cd( nombre );
                        qDebug( QString( "Entrando en la carpeta: %1" ).arg( nombre ).toLocal8Bit() );
                        QMap<double,QDomNode> versiones;
                        // Este nodo debe tener tantos nodos como versiones disponibles
                        while( nodoA.hasChildNodes() )
                        {
                                QDomNode nodoVersion = nodoA.firstChild();
                                if( nodoVersion.toElement().tagName() == "version" )
                                {
                                        //veo que numero de version es
                                        double version  = nodoVersion.toElement().attribute( "numero" ).toDouble();
                                        qDebug( QString( "Encontrada version %1" ).arg( version ).toLocal8Bit() );
                                        if( version >= ERegistroPlugins::getInstancia()->pluginsHash()->value( nombre )->version() )
                                        {
                                                // Lo ingreso a la lista de actualizaciones de forma ordenanda
                                                qDebug( "Version agregada" );
                                                versiones.insert( version, nodoVersion );
                                                nodoA.removeChild( nodoVersion );
                                        }
                                        else
                                        {
                                                // actualizacion vieja, la elimino del arbol
                                                nodoA.removeChild( nodoVersion );
                                                continue;
                                        }
                                }
                                else
                                {
                                        // No puede haber de otro tipo, lo elimino
                                        qDebug( "Encontrado nodo que no es version" );
                                        nodoA.removeChild( nodoVersion );
                                }
                        }
                        // Ejecuto las actualizaciones de forma ordenada
                        qDebug( "Ordenando versiones" );
                        QList<double> lista = versiones.keys();
                        qStableSort( lista.begin(), lista.end() );
                        if( lista.size() == 0 )
                        {
                                qDebug( "La lista de actualizaciones esta vacia" );
                        }
                        while( lista.size() > 0 )
                        {
                                QDomNode nodoB = versiones[lista.first()];
                                // Trabajo con el nodo
                                // Busco los hijos que son archivos
                                TELog->append( QString( "Actualizando plugin %1..." ).arg( nombre ) );
                                // Ingreso al directorio de la version del plugin
                                ftp->cd( QString::number( lista.first() ) );
                                #ifdef Q_WS_WIN32
                                QString nombre_os = "windows";
                                #endif
                                #ifdef Q_WS_X11
                                QString nombre_os = "linux";
                                #endif
                                QDomNode nodo_os = nodoB.toElement().elementsByTagName( nombre_os ).item(0);
                                qDebug( QString( "Nodo OS: %1" ).arg( nodo_os.nodeName() ).toLocal8Bit() );
                                QDomNodeList nodos_archivos = nodo_os.toElement().elementsByTagName( "archivo" );
                                unsigned int posNodo = 0;
                                qDebug( QString( "Encontrado %1 nodos").arg( nodos_archivos.length() ).toLocal8Bit() );
                                while( posNodo < nodos_archivos.length() && _continuar_actualizando )
                                {
                                        QDomNode nodo_archivo = nodos_archivos.item(posNodo);
                                        QPair<QString,QString> tmp;
                                        tmp.first = nodo_archivo.toElement().attribute( "nombre" );
                                        tmp.second = nodo_archivo.toElement().attribute( "directorio_destino" );
                                        qDebug( QString( "Encontrado archivo %1, dir %2" ).arg( tmp.first ).arg( tmp.second ).toLocal8Bit() );
                                        TELog->append( QString( "Descargando archivo %1..." ).arg( tmp.first ) );
                                        int pos = ftp->get( tmp.first );
                                        _arch_dest.insert( pos, tmp );
                                        posNodo++;
                                }
                                //Veo si hay actualizaciones de la base de datos
                                qDebug( "Actualizaciones de base de datos" );
                                QDomNodeList nodos_db = nodoB.toElement().elementsByTagName( "db" );
                                if( nodos_db.length() > 0 && _continuar_actualizando )
                                {
                                        for( unsigned int i=0; i<nodos_db.length(); i++ )
                                        {
                                                if( !_continuar_actualizando )
                                                { return; }
                                                QDomNode nodo = nodos_db.item(i);
                                                // Busco todos los hijos
                                                QDomNodeList nodos_colas = nodo.toElement().elementsByTagName( "cola" );
                                                if( nodos_colas.length() > 0 && _continuar_actualizando )
                                                {
                                                        for( unsigned int j=0; j < nodos_colas.length(); j++ )
                                                        {
                                                                if( !_continuar_actualizando )
                                                                { return;}
                                                                QDomNode nCola = nodos_colas.item(j);
                                                                if( nCola.nodeName() == "cola" )
                                                                {
                                                                        QSqlQuery cola;
                                                                        if( cola.exec( nCola.firstChild().toText().data() ) )
                                                                        {
                                                                                qDebug( QString( "Cola ejecutada correctamente: %1" ).arg( cola.executedQuery() ).toLocal8Bit() );
                                                                        }
                                                                        else
                                                                        {
                                                                                qWarning( QString( "La ejecucion de la actualizacion no fue correcta. Cola: %1" ).arg( cola.executedQuery() ).toLocal8Bit() );
                                                                                qDebug( QString( "Error: %1.\n Cola: %2" ).arg( cola.lastError().text() ).arg( cola.executedQuery() ).toLocal8Bit() );
                                                                        }
                                                                }
                                                                else
                                                                {
                                                                        qDebug( QString("Nodo encontrado: %1").arg(nodo.nodeName() ).toLocal8Bit() );
                                                                }
                                                        } // Fin for colas
                                                }// Fin if nodos_colas
                                        }// Fin for dbs
                                }
                                else
                                {
                                        qDebug( "No hay actualizaciones para la base de datos" );
                                }
                                //////////////////////// Fin de trabajar con el nodo
                                versiones.remove(lista.first());
                                lista.removeFirst();
                                // Salgo del directorio de la version y quedo en el directorio del plugin
                                ftp->cd("..");
                        }
                        qDebug( "Fin bucle Versiones" );
                        // Termino de actualizar el plugin y sus versiones -> salgo al directorio de la version del programa
                        ftp->cd("..");
                        docElem.removeChild( nodoA );
                }
                else if( nodoA.toElement().tagName() == "libreria" )
                {
                        ftp->cd( "librerias" );
                        // Veo el numero de secuencia
                        int num_seq  = preferencias::getInstancia()->value( "Preferencias/General/"+nodoA.toElement().attribute("nombre" ) + "/numseq", 0 ).toInt();
                        int num_nuevo = nodoA.toElement().attribute( "numerosecuencia" ).toInt();
                        if( num_seq <= num_nuevo )
                        {
                                ftp->cd( QString::number( num_nuevo ) );
                                #ifdef Q_WS_WIN32
                                QString nombre_os = "windows";
                                #endif
                                #ifdef Q_WS_X11
                                QString nombre_os = "linux";
                                #endif
                                QDomNode nodo_os = nodoA.toElement().elementsByTagName( nombre_os ).item(0);
                                qDebug( QString( "Nodo OS: %1" ).arg( nodo_os.nodeName() ).toLocal8Bit() );
                                QDomNodeList nodos_archivos = nodo_os.toElement().elementsByTagName( "archivo" );
                                unsigned int posNodo = 0;
                                qDebug( QString( "Encontrado %1 nodos").arg( nodos_archivos.length() ).toLocal8Bit() );
                                while( posNodo < nodos_archivos.length() && _continuar_actualizando )
                                {
                                        QDomNode nodo_archivo = nodos_archivos.item(posNodo);
                                        QPair<QString,QString> tmp;
                                        tmp.first = nodo_archivo.toElement().attribute( "nombre" );
                                        tmp.second = nodo_archivo.toElement().attribute( "directorio_destino" );
                                        qDebug( QString( "Encontrado archivo %1, dir %2" ).arg( tmp.first ).arg( tmp.second ).toLocal8Bit() );
                                        TELog->append( QString( "Descargando archivo %1..." ).arg( tmp.first ) );
                                        int pos = ftp->get( tmp.first );
                                        _arch_dest.insert( pos, tmp );
                                        posNodo++;
                                }
                        }
                        else
                        {
                                // La libreria no necesita actualizacion
                        }
                        ftp->cd("..");
                        //Fin de actualizar la libreria -> regreso a la carpeta de version del programa
                }
                else
                {
                        // El nodo no es plugin
                        /// \todo ver que hacer aca
                        qDebug( QString( "Tipo de nodo desconocido: %1" ).arg( nodoA.toElement().tagName() ).toLocal8Bit() );
                        docElem.removeChild( nodoA );
                }
        } // fin de si actualizacion tiene nodos
  }
 ftp->close();
 TELog->append( "Lista el Analisis" );
 transferencia( 100, 100 );
 qDebug( "Fin" );
}
Example #24
0
void Xmpp::processEvent(Event *event)
{
	/*
	 * WARNING: An event is NOT still the same as before.
	 * Now, an event contains all data from depth = 1 
	 * to depth back to 1.
	 */
	//printf("Elem = %s\n", event->node().localName().toLatin1().constData());
	switch (state)
	{
		case isHandShaking:
			break;
		case PrepareRegistering:
		case waitStream:
			if (event->type() == Event::Stream)
			{
				printf("[XMPP] Ok, received the stream tag.\n");
				if (state != PrepareRegistering)
					state = waitFeatures;
				else
				{
					state = active;
					emit registerReady();
				}
			}
			//else
			//	printf(" ! Didn't receive the stream ! \n");
			break;
		case waitFeatures:
			if (event->node().localName() == "features")
			{
				printf("[XMPP] Ok, received the features tag.\n");
				if (!tlsDone && useTls)
				{
					QDomNode node = event->node().firstChild();
					printf("[XMPP] Next Status : ");
					//state = waitStartTls;
					printf("[XMPP]     %s\n", node.localName().toLatin1().constData());
					if (node.localName() == QString("mechanisms"))
					{
						printf("[XMPP] Must directly switch to SASL authentication\n");
						useTls = false;
						node = node.firstChild();
						// Must directly switch to SASL authentication
						printf("[XMPP]     %s\n", node.localName().toLatin1().constData());
						while(node.localName() == QString("mechanism"))
						{
							printf("[XMPP] Ok, received a mechanism tag.\n");
							if (node.firstChild().toText().data() == QString("PLAIN"))
							{
								plainMech = true;
								printf("[XMPP] Ok, PLAIN mechanism supported\n");

								// Sstartauth method.
								QDomDocument doc("");
								QDomElement e = doc.createElement("auth");
								doc.appendChild(e);
								e.setAttribute(QString("xmlns"), QString("urn:ietf:params:xml:ns:xmpp-sasl"));
								e.setAttribute(QString("mechanism"), QString("PLAIN"));
								QString text = QString("%1%2%3%4").arg('\0').arg(username).arg('\0').arg(password);
								QDomText t = doc.createTextNode(text.toLatin1().toBase64());
								e.appendChild(t);
								QByteArray sData = doc.toString().toLatin1();
								sendData(sData);
								state = waitSuccess;
								
							}
							node = node.nextSibling();
						}
					
					}
					if (node.localName() == QString("starttls"))
					{
						printf("[XMPP] Ok, received the starttls tag.\n");
						// Send starttls tag
						QDomDocument doc("");
						QDomElement e = doc.createElement("starttls");
						doc.appendChild(e);
						e.setAttribute(QString("xmlns"), QString("urn:ietf:params:xml:ns:xmpp-tls"));
						QByteArray sData = doc.toString().toLatin1();
						sendData(sData);
						// Next state
						state = waitProceed;
						// Even if TLS isn't required, I use TLS.
					}
				}
				else
				{
					if (!saslDone)
					{
						//TODO:Must first check that event->node().firstChild() == mechanisms
						QDomNode node = event->node().firstChild().firstChild();
						printf("[XMPP] Tls done or not used. --> sasl\n");
						while(node.localName() == QString("mechanism"))
						{
							printf("[XMPP] Ok, received a mechanism tag.\n");
							if (node.firstChild().toText().data() == QString("PLAIN"))
							{
								plainMech = true;
								printf("[XMPP] Ok, PLAIN mechanism supported\n");

								// Sstartauth method.
								QDomDocument doc("");
								QDomElement e = doc.createElement("auth");
								doc.appendChild(e);
								e.setAttribute(QString("xmlns"), QString("urn:ietf:params:xml:ns:xmpp-sasl"));
								e.setAttribute(QString("mechanism"), QString("PLAIN"));
								QString text = QString("%1%2%3%4").arg('\0').arg(username).arg('\0').arg(password);
								QDomText t = doc.createTextNode(text.toLatin1().toBase64());
								e.appendChild(t);
								QByteArray sData = doc.toString().toLatin1();
								sendData(sData);
								state = waitSuccess;
								
							}
							node = node.nextSibling();
						} //FIXME: this is impemented two times in this function. Another way to do the same ?
					}
					else
					{
				//		printf("Wait Ncessary\n");
				//		state = waitNecessary;
						QDomNode node = event->node().firstChild();
						while(!node.isNull())
						{
							if (node.localName() == QString("bind"))
							{
								printf("[XMPP] Ok, bind needed.\n");
								needBind = true;
							}
							if (node.localName() == QString("session"))
							{
								printf("[XMPP] Ok, session needed.\n");
								needSession = true;
							}
							node = node.nextSibling();
						}
						if (needBind)
						{
							QDomDocument doc("");
							QDomElement e = doc.createElement("iq");
							e.setAttribute("type", "set"); // Trying without id.

							QDomElement e2 = doc.createElement("bind");
							e2.setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-bind");
				
							QDomElement e3 = doc.createElement("resource");
							QDomText t = doc.createTextNode(resource);
				
							e3.appendChild(t);
							e2.appendChild(e3);
							e.appendChild(e2);
							doc.appendChild(e);
							QByteArray sData = doc.toString().toLatin1();
							sendData(sData);
				
							state = waitBind;
						}
					}
				}
			}
			break;
		case waitProceed:
			if (event->node().localName() == QString("proceed"))
			{
				//printf(" * Ok, received the proceed tag.\n");
				printf("[XMPP] Proceeding...\n[XMPP] Enabling TLS connection.\n");
				
				state = isHandShaking;
				tls = new TlsHandler();
				connect(tls, SIGNAL(readyRead()), this, SLOT(clearDataReceived()));
				connect(tls, SIGNAL(readyReadOutgoing()), this, SLOT(sendDataFromTls()));
				connect(tls, SIGNAL(connected()), this, SLOT(tlsIsConnected()));
				tls->connect();
				state = isHandShaking;
				isTlsing = true;
			}
			break;
		case waitSuccess:
			if (event->node().localName() == QString("success"))
			{
				printf("[XMPP] Ok, SASL established.\n");
				saslDone = true;
				start();
			}
			if (event->node().localName() == QString("failure"))
			{
				printf("[XMPP]  ! Check Username and password.\n");
				QByteArray sData = "</stream:stream>";
				sendData(sData);
			}
			break;
		case waitBind:
			if (event->node().localName() == QString("iq"))
			{
				if (event->node().toElement().attribute("type") != QString("result"))
				{
					printf("[XMPP] Authentification Error.\n");
					QByteArray sData = "</stream:stream>";
					sendData(sData);
					return;
				}
				if (event->node().firstChild().localName() == QString("bind"))
				{
					QDomNode node = event->node().firstChild();
					if (node.firstChild().localName() == QString("jid"))
					{
						node = node.firstChild().firstChild();
						QString u, r, s;
						if (!node.toText().data().isEmpty())
						{
							u = node.toText().data().split('@')[0]; // Username
							s = node.toText().data().split('@')[1].split('/')[0]; // Server
							r = node.toText().data().split('/')[1]; // Resource
							printf("[XMPP] '%s'@'%s'/'%s'\n", u.toLatin1().constData(), s.toLatin1().constData(), r.toLatin1().constData());
						}
						if (u == username && s == server)
						{
							printf("[XMPP] Jid OK !\n");
							resource = r;
							jidDone = true;
							j.setResource(r);
						}
					}

					if (needSession && jidDone)
					{
						printf("[XMPP] Launching Session...\n");
						QDomDocument doc("");
						QDomElement e = doc.createElement("iq");
						e.setAttribute("to", server);
						e.setAttribute("type", "set");
						e.setAttribute("id", "sess_1");

						QDomElement e2 = doc.createElement("session");
						e2.setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-session");

						e.appendChild(e2);
						doc.appendChild(e);

						QByteArray sData = doc.toString().toLatin1();
						sendData(sData);

						state = waitSession;
					}
					
				}
			}
			break;
		case waitSession:
			if (event->node().localName() == QString("iq"))
			{
				if (event->node().toElement().attribute("type") == "result")
				{
					printf("[XMPP] Connection is now active !\n");
					
					/*
					 * Presence must be sent after getting the roster
					 * so we already have the contacts to assign their presence
					 * when receiving presence stanza's wich come after
					 * setting the first presence.
					 */

					state = active;
					emit connected(); 

				}
				else
				{
					if (event->node().toElement().attribute("type") == "error")
					{
						printf("[XMPP] An error occured ! \n");
					}
				}

			}
			break;
		case active:
		{
			Stanza *s = new Stanza(event->node());
			QDomDocument doc = event->node().toDocument();
			printf("[XMPP] Xmpp::processEvent : node = %s\n", doc.toString().toLatin1().constData());
			stanzaList << s;
			emit readyRead();
			break;
		}
		default :
			break;
	}
}
Example #25
0
ScriptingArea::ScriptingArea(MapEditor *parent) : QDockWidget(parent) {

    setWindowTitle("Zone de scripting");


    // partie zone de texte

    QsciLexerLua *lexerLua = new QsciLexerLua();
    m_textZone.setLexer(lexerLua);
    m_textZone.setUtf8(true);
    m_textZone.setMarginLineNumbers(1, true); // numérotation des lignes
    m_textZone.setMarginWidth(1, 30); // agrandissement de la marge

    //this->setAutoCompletionSource(AcsAPIs);
    //this->setAutoCompletionThreshold(1);

    QsciLexerLua *lexLua= new QsciLexerLua();
    QsciAPIs *api = new QsciAPIs(lexLua);
    if ( ! api->load(":/ressources/autocompetion.api") ) {
        Log::e("ScriptingArea") << "Erreur chargement autocompletion.api";
    }
    api->prepare();
    m_textZone.setAutoCompletionSource(QsciScintilla::AcsAPIs);
    m_textZone.setLexer(lexLua);
    m_textZone.setAutoCompletionThreshold(1);

    clear();


    // partie arbre des fonctions possibles

    QTreeWidget *treeDoc = new QTreeWidget();
    treeDoc->setHeaderHidden(true);

    QDomDocument doc;

    QFile f(EDITOR_DATA_DIR + "/scriptingFunctions.xml");
    if ( ! f.open(QIODevice::ReadOnly) ) {
        Log::e("Editor") << "erreur ouverture " << f.fileName() << " : " << f.errorString();
    }
    doc.setContent(&f);
    f.close();

    QDomElement root = doc.documentElement();

    QDomNode n = root.firstChild();
    while( ! n.isNull() ) {

        QTreeWidgetItem *item = new QTreeWidgetItem();
        item->setText(0, n.toElement().tagName());
        treeDoc->insertTopLevelItem(0, item);

        QDomNode instance = n.firstChild();
        while ( ! instance.isNull() ) {
            QTreeWidgetItem *item2 = new QTreeWidgetItem();
            item2->setText(0, instance.toElement().attribute("signature"));
            item->addChild(item2);
            instance = instance.nextSibling();
        }

        n = n.nextSibling();
    }


    // ajout dans le layout

    QSplitter *splitter = new QSplitter(Qt::Horizontal);
    splitter->addWidget(&m_textZone);
    splitter->addWidget(treeDoc);

    // on agrandit le premier widget, la zone de texte
    splitter->setStretchFactor(0, 0.75 * width());

    QHBoxLayout *scriptingDockLayout = new QHBoxLayout();
    scriptingDockLayout->addWidget(splitter);

    QWidget *scriptingDockContent = new QWidget();
    setWidget(scriptingDockContent);
    scriptingDockContent->setLayout(scriptingDockLayout);

}
Example #26
0
void configManager::loadConfigFile()
{
	// read the XML file and create DOM tree
	QFile cfg_file( m_lmmsRcFile );
	QDomDocument dom_tree;

	if( cfg_file.open( QIODevice::ReadOnly ) )
	{
		QString errorString;
		int errorLine, errorCol;
		if( dom_tree.setContent( &cfg_file, false, &errorString, &errorLine, &errorCol ) )
		{
			// get the head information from the DOM
			QDomElement root = dom_tree.documentElement();

			QDomNode node = root.firstChild();

			// create the settings-map out of the DOM
			while( !node.isNull() )
			{
				if( node.isElement() &&
					node.toElement().hasAttributes () )
				{
					stringPairVector attr;
					QDomNamedNodeMap node_attr =
						node.toElement().attributes();
					for( int i = 0; i < node_attr.count();
									++i )
					{
		QDomNode n = node_attr.item( i );
		if( n.isAttr() )
		{
			attr.push_back( qMakePair( n.toAttr().name(),
							n.toAttr().value() ) );
		}
					}
					m_settings[node.nodeName()] = attr;
				}
				else if( node.nodeName() == "recentfiles" )
				{
					m_recentlyOpenedProjects.clear();
					QDomNode n = node.firstChild();
					while( !n.isNull() )
					{
		if( n.isElement() && n.toElement().hasAttributes() )
		{
			m_recentlyOpenedProjects <<
					n.toElement().attribute( "path" );
		}
		n = n.nextSibling();
					}
				}
				node = node.nextSibling();
			}

			if( value( "paths", "artwork" ) != "" )
			{
				m_artworkDir = value( "paths", "artwork" );
				if( !QDir( m_artworkDir ).exists() )
				{
					m_artworkDir = defaultArtworkDir();
				}
				if( m_artworkDir.right( 1 ) !=
							QDir::separator() )
				{
					m_artworkDir += QDir::separator();
				}
			}
			setWorkingDir( value( "paths", "workingdir" ) );
			setVSTDir( value( "paths", "vstdir" ) );
			setFLDir( value( "paths", "fldir" ) );
			setLADSPADir( value( "paths", "laddir" ) );
		#ifdef LMMS_HAVE_STK
			setSTKDir( value( "paths", "stkdir" ) );
		#endif
		#ifdef LMMS_HAVE_FLUIDSYNTH
			setDefaultSoundfont( value( "paths", "defaultsf2" ) );
		#endif
			setBackgroundArtwork( value( "paths", "backgroundartwork" ) );
		}
		else
		{
			QMessageBox::warning( NULL, MainWindow::tr( "Configuration file" ),
									MainWindow::tr( "Error while parsing configuration file at line %1:%2: %3" ).
													arg( errorLine ).
													arg( errorCol ).
													arg( errorString ) );
		}
		cfg_file.close();
	}


	if( m_vstDir.isEmpty() || m_vstDir == QDir::separator() ||
			!QDir( m_vstDir ).exists() )
	{
#ifdef LMMS_BUILD_WIN32
		m_vstDir = windowsConfigPath( CSIDL_PROGRAM_FILES ) +
											QDir::separator() + "VstPlugins";
#else
		m_vstDir = ensureTrailingSlash( QDir::home().absolutePath() );
#endif
	}

	if( m_flDir.isEmpty() || m_flDir == QDir::separator() )
	{
		m_flDir = ensureTrailingSlash( QDir::home().absolutePath() );
	}

	if( m_ladDir.isEmpty() || m_ladDir == QDir::separator() ||
			( !m_ladDir.contains( ':' ) && !QDir( m_ladDir ).exists() ) )
	{
#if defined(LMMS_BUILD_WIN32)
		m_ladDir = m_pluginDir + "ladspa" + QDir::separator();
#elif defined(LMMS_BUILD_APPLE)
		m_ladDir = qApp->applicationDirPath() + "/../lib/lmms/ladspa/";
#else
		m_ladDir = qApp->applicationDirPath() + '/' + LIB_DIR + "/ladspa/";
#endif
	}

#ifdef LMMS_HAVE_STK
	if( m_stkDir.isEmpty() || m_stkDir == QDir::separator() ||
			!QDir( m_stkDir ).exists() )
	{
#if defined(LMMS_BUILD_WIN32)
		m_stkDir = m_dataDir + "stk/rawwaves/";
#elif defined(LMMS_BUILD_APPLE)
		m_stkDir = qApp->applicationDirPath() + "/../share/stk/rawwaves/";
#else
		m_stkDir = "/usr/share/stk/rawwaves/";
#endif
	}
#endif


	QDir::setSearchPaths( "resources", QStringList() << artworkDir()
						<< defaultArtworkDir() );

	if( !QDir( m_workingDir ).exists() )
	{
		if( QMessageBox::question( 0,
			MainWindow::tr( "Working directory" ),
			MainWindow::tr( "The LMMS working directory %1 does not "
				"exist. Create it now? You can change the directory "
				"later via Edit -> Settings." ).arg( m_workingDir ),
					QMessageBox::Yes, QMessageBox::No ) ==
								QMessageBox::Yes )
		{
			QDir().mkpath( m_workingDir );
		}
	}
	if( QDir( m_workingDir ).exists() )
	{
		QDir().mkpath( userProjectsDir() );
		QDir().mkpath( userSamplesDir() );
		QDir().mkpath( userPresetsDir() );
	}
}
void KCalResourceSlox::parseRecurrence( const QDomNode &node, Event *event )
{
  QString type;

  int dailyValue = -1;
  KDateTime end;

  int weeklyValue = -1;
  QBitArray days( 7 ); // days, starting with monday
  bool daysSet = false;

  int monthlyValueDay = -1;
  int monthlyValueMonth = -1;

  int yearlyValueDay = -1;
  int yearlyMonth = -1;

  int monthly2Recurrency = 0;
  int monthly2Day = 0;
  int monthly2ValueMonth = -1;

  int yearly2Recurrency = 0;
  int yearly2Day = 0;
  int yearly2Month = -1;

  DateList deleteExceptions;

  QDomNode n;

  for( n = node.firstChild(); !n.isNull(); n = n.nextSibling() ) {
    QDomElement e = n.toElement();
    QString tag = e.tagName();
    QString text = decodeText( e.text() );
    kDebug() << tag << ":" << text;

    if ( tag == fieldName( RecurrenceType ) ) {
      type = text;
    } else if ( tag == "daily_value" ) {
      dailyValue = text.toInt();
    } else if ( tag == fieldName( RecurrenceEnd ) ) {
      end = WebdavHandler::sloxToKDateTime( text );
    } else if ( tag == "weekly_value" ) {
      weeklyValue = text.toInt();
    } else if ( tag.left( 11 ) == "weekly_day_" ) {
      int day = tag.mid( 11, 1 ).toInt();
      int index;
      if ( day == 1 ) index = 0;
      else index = day - 2;
      days.setBit( index );
    } else if ( tag == "monthly_value_day" ) {
      monthlyValueDay = text.toInt();
    } else if ( tag == "monthly_value_month" ) {
      monthlyValueMonth = text.toInt();
    } else if ( tag == "yearly_value_day" ) {
      yearlyValueDay = text.toInt();
    } else if ( tag == "yearly_month" ) {
      yearlyMonth = text.toInt();
    } else if ( tag == "monthly2_recurrency" ) {
      monthly2Recurrency = text.toInt();
    } else if ( tag == "monthly2_day" ) {
      monthly2Day = text.toInt();
    } else if ( tag == "monthly2_value_month" ) {
      monthly2ValueMonth = text.toInt();
    } else if ( tag == "yearly2_reccurency" ) { // this is not a typo, this is what SLOX really sends!
      yearly2Recurrency = text.toInt();
    } else if ( tag == "yearly2_day" ) {
      yearly2Day = text.toInt();
    } else if ( tag == "yearly2_month" ) {
      yearly2Month = text.toInt() + 1;
    // OX recurrence fields
    } else if ( tag == "interval" ) {
      dailyValue = text.toInt();
      weeklyValue = text.toInt();
      monthlyValueMonth = text.toInt();
      monthly2ValueMonth = text.toInt();
    } else if ( tag == "days" ) {
      int tmp = text.toInt();  // OX encodes days binary: 1=Su, 2=Mo, 4=Tu, ...
      for ( int i = 0; i < 7; ++i ) {
        if ( tmp & (1 << i) )
          days.setBit( (i + 6) % 7 );
      }
      daysSet = true;
    } else if ( tag == "day_in_month" ) {
      monthlyValueDay = text.toInt();
      monthly2Recurrency = text.toInt();
      yearlyValueDay = text.toInt();
      yearly2Recurrency = text.toInt();
    } else if ( tag == "month" ) {
      yearlyMonth = text.toInt() + 1; // starts at 0
      yearly2Month = text.toInt() + 1;
    } else if ( tag == fieldName( RecurrenceDelEx ) ) {
      QStringList exdates = text.split( "," );
      QStringList::ConstIterator it;
      for ( it = exdates.constBegin(); it != exdates.constEnd(); ++it )
        deleteExceptions.append( WebdavHandler::sloxToKDateTime( *it ).date() );
    }
  }

  if ( daysSet && type == "monthly" )
    type = "monthly2"; // HACK: OX doesn't cleanly distinguish between monthly and monthly2
  if ( daysSet && type == "yearly" )
    type = "yearly2";

  Recurrence *r = event->recurrence();

  if ( type == "daily" ) {
    r->setDaily( dailyValue );
  } else if ( type == "weekly" ) {
    r->setWeekly( weeklyValue, days );
  } else if ( type == "monthly" ) {
    r->setMonthly( monthlyValueMonth );
    r->addMonthlyDate( monthlyValueDay );
  } else if ( type == "yearly" ) {
    r->setYearly( 1 );
    r->addYearlyDate( yearlyValueDay );
    r->addYearlyMonth( yearlyMonth );
  } else if ( type == "monthly2" ) {
    r->setMonthly( monthly2ValueMonth );
    QBitArray _days( 7 );
    if ( daysSet )
      _days = days;
    else
      _days.setBit( event->dtStart().date().dayOfWeek() );
    r->addMonthlyPos( monthly2Recurrency, _days );
  } else if ( type == "yearly2" ) {
    r->setYearly( 1 );
    r->addYearlyMonth( yearly2Month );
    QBitArray _days( 7 );
    if ( daysSet )
      _days = days;
    else
      _days.setBit( ( yearly2Day + 5 ) % 7 );
    r->addYearlyPos( yearly2Recurrency, _days );
  }
  r->setEndDate( end.date() );
  r->setExDates( deleteExceptions );
}
  void
  CameraParameters::operator <<= (const QDomNode& node)
  {
    if (!node.isNull()) {
      QDomNode n1 = node.firstChild();
      while(!n1.isNull() ) {
	if (n1.nodeName() == "ncx") {
	  QDomNode n2 = n1.firstChild();
	  QDomText t = n2.toText(); // try to convert the node to a text
	  if(!t.isNull() ) { // the node was really an element.
	    ncx = t.data().toDouble();
	  }
	}
	else if (n1.nodeName() == "nfx") {
	  QDomNode n2 = n1.firstChild();
	  QDomText t = n2.toText(); // try to convert the node to a text
	  if(!t.isNull() ) { // the node was really an element.
	    nfx = t.data().toDouble();
	  }
	}
	else if (n1.nodeName() == "dx") {
	  QDomNode n2 = n1.firstChild();
	  QDomText t = n2.toText(); // try to convert the node to a text
	  if(!t.isNull() ) { // the node was really an element.
	    dx = t.data().toDouble();
	  }
	}
	else if (n1.nodeName() == "dy") {
	  QDomNode n2 = n1.firstChild();
	  QDomText t = n2.toText(); // try to convert the node to a text
	  if(!t.isNull() ) { // the node was really an element.
	    dy = t.data().toDouble();
	  }
	}
	else if (n1.nodeName() == "cx") {
	  QDomNode n2 = n1.firstChild();
	  QDomText t = n2.toText(); // try to convert the node to a text
	  if(!t.isNull() ) { // the node was really an element.
	    cx = t.data().toDouble();
	  }
	}
	else if (n1.nodeName() == "cy") {
	  QDomNode n2 = n1.firstChild();
	  QDomText t = n2.toText(); // try to convert the node to a text
	  if(!t.isNull() ) { // the node was really an element.
	    cy = t.data().toDouble();
	  }
	}
	else if (n1.nodeName() == "sx") {
	  QDomNode n2 = n1.firstChild();
	  QDomText t = n2.toText(); // try to convert the node to a text
	  if(!t.isNull() ) { // the node was really an element.
	    sx = t.data().toDouble();
	  }
	}
	else if (n1.nodeName() == "f") {
	  QDomNode n2 = n1.firstChild();
	  QDomText t = n2.toText(); // try to convert the node to a text
	  if(!t.isNull() ) { // the node was really an element.
	    f = t.data().toDouble();
	  }
	}
	else if (n1.nodeName() == "kappa") {
	  QDomNode n2 = n1.firstChild();
	  QDomText t = n2.toText(); // try to convert the node to a text
	  if(!t.isNull() ) { // the node was really an element.
	    kappa = t.data().toDouble();
	  }
	}
	else if (n1.nodeName() == "height") {
	  QDomNode n2 = n1.firstChild();
	  QDomText t = n2.toText(); // try to convert the node to a text
	  if(!t.isNull() ) { // the node was really an element.
	    height = t.data().toDouble();
	  }
	}
	else if (n1.nodeName() == "alpha") {
	  QDomNode n2 = n1.firstChild();
	  QDomText t = n2.toText(); // try to convert the node to a text
	  if(!t.isNull() ) { // the node was really an element.
	    alpha = deg2Rad(t.data().toDouble());
	  }
	}
	else if (n1.nodeName() == "latency") {
	  QDomNode n2 = n1.firstChild();
	  QDomText t = n2.toText(); // try to convert the node to a text
	  if(!t.isNull() ) { // the node was really an element.
	    double d = t.data().toDouble();
	    latency.sec((int)floor(d));
	    latency.usec((int)floor((d - floor(d)) * 1000000.));
	  }
	}
	n1 = n1.nextSibling();
      }
    }
  }
Example #29
0
void Fixture_Test::save()
{
    const QLCFixtureDef* fixtureDef;
    fixtureDef = m_fixtureDefCache.fixtureDef("Martin", "MAC250+");
    Q_ASSERT(fixtureDef != NULL);

    const QLCFixtureMode* fixtureMode;
    fixtureMode = fixtureDef->modes().at(0);
    Q_ASSERT(fixtureMode != NULL);

    Fixture fxi(this);
    fxi.setID(1337);
    fxi.setName("Test Fixture");
    fxi.setUniverse(2);
    fxi.setAddress(438);
    fxi.setFixtureDefinition(fixtureDef, fixtureMode);

    QDomDocument doc;
    QDomElement root = doc.createElement("TestRoot");
    QVERIFY(fxi.saveXML(&doc, &root) == true);
    QDomNode node = root.firstChild();
    QVERIFY(node.toElement().tagName() == "Fixture");

    bool manufacturer = false, model = false, mode = false, name = false,
                                       channels = false, universe = false, address = false, id = false;

    node = node.firstChild();
    while (node.isNull() == false)
    {
        QDomElement e = node.toElement();

        if (e.tagName() == "Manufacturer")
        {
            QVERIFY(e.text() == "Martin");
            manufacturer = true;
        }
        else if (e.tagName() == "Model")
        {
            QVERIFY(e.text() == "MAC250+");
            model = true;
        }
        else if (e.tagName() == "Mode")
        {
            QVERIFY(e.text() == fixtureMode->name());
            mode = true;
        }
        else if (e.tagName() == "ID")
        {
            QVERIFY(e.text() == "1337");
            id = true;
        }
        else if (e.tagName() == "Name")
        {
            QVERIFY(e.text() == "Test Fixture");
            name = true;
        }
        else if (e.tagName() == "Universe")
        {
            QVERIFY(e.text() == "2");
            universe = true;
        }
        else if (e.tagName() == "Address")
        {
            QVERIFY(e.text() == "438");
            address = true;
        }
        else if (e.tagName() == "Channels")
        {
            QVERIFY(e.text().toInt()
                    == fixtureMode->channels().count());
            channels = true;
        }
        else
        {
            QFAIL(QString("Unexpected tag: %1").arg(e.tagName())
                  .toAscii());
        }

        node = node.nextSibling();
    }

    QVERIFY(manufacturer == true);
    QVERIFY(model == true);
    QVERIFY(mode == true);
    QVERIFY(id == true);
    QVERIFY(name == true);
    QVERIFY(universe == true);
    QVERIFY(address == true);
    QVERIFY(channels == true);
}
Example #30
0
void PMLibraryHandle::loadLibraryInfo( )
{
   // 1. Open the information file (library_index.xml)
   QFile file( m_path + "/library_index.xml" );

   if( !file.open( IO_ReadOnly ) )
   {
      kdError( PMArea ) << "Could not find the library index." << endl;
      return;
   }

   // 2. Read the information
   QDomDocument doc( "KPOVLIBINDEX" );
   doc.setContent( &file );

   QDomElement e = doc.documentElement( );

   if( e.tagName( ) != "library" )
   {
      kdError( PMArea ) << "This doesn't appear to be a library index." << endl;
      return;
   }

   // 3. The library entry
   setName( e.attribute( "name", i18n( "Unknown" ) ) );
   setAuthor( e.attribute( "author", i18n( "Unknown" ) ) );
   setDescription( e.attribute( "description", "" ) );
   if( e.attribute( "readonly", "false" ) == "false" )
      m_readOnly = false;
   else
      m_readOnly = true;

   if( e.attribute( "sublibrary", "false" ) == "false" )
      m_subLibrary = false;
   else
      m_subLibrary = true;

   // 4. The object entries
   QDomNode n = e.firstChild( );
   if( !n.isNull( ) )
   {
      if( n.isElement( ) )
      {
         QDomElement c = n.toElement( );
         if( c.tagName( ) == "object_list" )
         {
            n = n.firstChild( );
            while( !n.isNull( ) )
            {
               c = n.toElement( );
               if( c.tagName( ) == "object_entry" )
               {
                  m_objects.insert( c.attribute( "name", i18n( "Unknown" ) ),
                                    new QString( c.attribute( "file", "" ) ) );
               }
               else if( c.tagName( ) == "library_entry" )
               {
                  m_libraries.insert( c.attribute( "name", i18n( "Unknown" ) ),
                                    new QString( c.attribute( "file", "" ) ) );
               }
               n = n.nextSibling( );
            }
         }
      }
   }
}