Ejemplo n.º 1
0
	PackageInfo ParsePackage (const QByteArray& data,
			const QUrl& baseUrl,
			const QString& packageName,
			const QStringList& packageVersions)
	{
		QDomDocument doc;
		QString msg;
		int line = 0;
		int column = 0;
		if (!doc.setContent (data, &msg, &line, &column))
		{
			qWarning () << Q_FUNC_INFO
					<< "erroneous document with msg"
					<< msg
					<< line
					<< column
					<< data;
			throw std::runtime_error ("Unagle to parse package description.");
		}

		PackageInfo packageInfo;

		QDomElement package = doc.documentElement ();

		QString type = package.attribute ("type");
		if (type == "iconset")
			packageInfo.Type_ = PackageInfo::TIconset;
		else if (type == "translation")
			packageInfo.Type_ = PackageInfo::TTranslation;
		else if (type == "plugin")
			packageInfo.Type_ = PackageInfo::TPlugin;
		else if (type == "theme")
			packageInfo.Type_ = PackageInfo::TTheme;
		else
			packageInfo.Type_ = PackageInfo::TData;

		packageInfo.Language_ = package.attribute ("language");
		packageInfo.Name_ = packageName;
		packageInfo.Versions_ = packageVersions;
		packageInfo.Description_ = package.firstChildElement ("description").text ();
		packageInfo.LongDescription_ = package.firstChildElement ("long").text ();

		QDomElement images = package.firstChildElement ("images");
		QDomElement imageNode = images.firstChildElement ("thumbnail");
		while (!imageNode.isNull ())
		{
			Image image =
			{
				Image::TThumbnail,
				MakeProperURL (imageNode.attribute ("url"), baseUrl)
			};
			packageInfo.Images_ << image;
			imageNode = imageNode.nextSiblingElement ("thumbnail");
		}
		imageNode = images.firstChildElement ("screenshot");
		while (!imageNode.isNull ())
		{
			Image image =
			{
				Image::TScreenshot,
				MakeProperURL (imageNode.attribute ("url"), baseUrl)
			};
			packageInfo.Images_ << image;
			imageNode = imageNode.nextSiblingElement ("screenshot");
		}
		packageInfo.IconURL_ = images.firstChildElement ("icon").attribute ("url");

		QDomElement tags = package.firstChildElement ("tags");
		QDomElement tagNode = tags.firstChildElement ("tag");
		while (!tagNode.isNull ())
		{
			packageInfo.Tags_ << tagNode.text ();
			tagNode = tagNode.nextSiblingElement ("tag");
		}

		QDomElement verNode = package.firstChildElement ("versions")
				.firstChildElement ("version");
		while (!verNode.isNull ())
		{
			if (verNode.hasAttribute ("size"))
			{
				bool ok = false;
				qint64 size = verNode.attribute ("size").toLong (&ok);
				if (ok)
					packageInfo.PackageSizes_ [verNode.text ()] = size;
			}

			packageInfo.VersionArchivers_ [verNode.text ()] =
					verNode.attribute ("archiver", "gz");

			verNode = verNode.nextSiblingElement ("version");
		}

		QDomElement maintNode = package.firstChildElement ("maintainer");
		packageInfo.MaintName_ = maintNode.firstChildElement ("name").text ();
		packageInfo.MaintEmail_ = maintNode.firstChildElement ("email").text ();

		QDomElement depends = package.firstChildElement ("depends");
		QDomElement dependNode = depends.firstChildElement ("depend");
		while (!dependNode.isNull ())
		{
			Dependency dep;
			if (dependNode.attribute ("type") == "depends" ||
					!dependNode.hasAttribute ("type"))
				dep.Type_ = Dependency::TRequires;
			else
				dep.Type_ = Dependency::TProvides;
			dep.Name_ = dependNode.attribute ("name");
			dep.Version_ = dependNode.attribute ("version");

			packageInfo.Deps_ [dependNode.attribute ("thisVersion")] << dep;

			dependNode = dependNode.nextSiblingElement ("depend");
		}

		return packageInfo;
	}
Ejemplo n.º 2
0
void QgsWFSConnection::capabilitiesReplyFinished()
{
  // handle network errors
  if ( mCapabilitiesReply->error() != QNetworkReply::NoError )
  {
    mErrorCode = QgsWFSConnection::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 = QgsWFSConnection::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 = QgsWFSConnection::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();
}
Ejemplo n.º 3
0
bool QgsLegendModel::dropMimeData( const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent )
{
  Q_UNUSED( action );
  Q_UNUSED( column );

  if ( !data->hasFormat( "text/xml" ) )
  {
    return false;
  }

  QStandardItem* dropIntoItem = 0;
  if ( parent.isValid() )
  {
    dropIntoItem = itemFromIndex( parent );
  }
  else
  {
    dropIntoItem = invisibleRootItem();
  }

  //get XML doc
  QByteArray encodedData = data->data( "text/xml" );
  QDomDocument xmlDoc;
  xmlDoc.setContent( encodedData );

  QDomElement dragDataElem = xmlDoc.documentElement();
  if ( dragDataElem.tagName() != "LegendModelDragData" )
  {
    return false;
  }

  QDomNodeList nodeList = dragDataElem.childNodes();
  int nChildNodes = nodeList.size();
  QDomElement currentElem;
  QString currentTagName;
  QgsComposerLegendItem* currentItem = 0;

  for ( int i = 0; i < nChildNodes; ++i )
  {
    currentElem = nodeList.at( i ).toElement();
    if ( currentElem.isNull() )
    {
      continue;
    }
    currentTagName = currentElem.tagName();
    if ( currentTagName == "LayerItem" )
    {
      currentItem = new QgsComposerLayerItem();
    }
    else if ( currentTagName == "GroupItem" )
    {
      currentItem = new QgsComposerGroupItem();
    }
    else
    {
      continue;
    }
    currentItem->readXML( currentElem );
    if ( row < 0 )
    {
      dropIntoItem->insertRow( dropIntoItem->rowCount(), currentItem );
    }
    else
    {
      dropIntoItem->insertRow( row + i, currentItem );
    }
  }
  emit layersChanged();
  return true;
}
Ejemplo n.º 4
0
void Rss::parseTracks(QNetworkReply *reply) {
    if (!reply) {
        std::cout << qPrintable(QString("{\"error\": \"%1\"}").arg(tr("Network error")));
        QCoreApplication::exit(1);
        return;
    }
    
    if (reply->error() != QNetworkReply::NoError) {
        reply->deleteLater();
        std::cout << qPrintable(QString("{\"error\": \"%1: %2\"}").arg(tr("Network error")).arg(reply->errorString()));
        QCoreApplication::exit(1);
        return;
    }
    
    QVariant redirect = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
    
    if (!redirect.isNull()) {
        reply->deleteLater();
        
        if (m_redirects < MAX_REDIRECTS) {
            followRedirect(redirect.toString());
        }
        else {
            std::cout << qPrintable(QString("{\"error\": \"%1: %2\"}").arg(tr("Network error"))
                                                                .arg(tr("Maximum redirects reached")));
            QCoreApplication::exit(1);
        }
        
        return;
    }
    
    QDomDocument doc;    
    
    if (!doc.setContent(reply->readAll(), true)) {
        reply->deleteLater();
        std::cout << qPrintable(QString("{\"error\": \"%1\"}").arg(tr("Unable to parse XML")));
        QCoreApplication::exit(1);
        return;
    }
    
    QDomElement docElem = doc.documentElement();
    QDomNodeList items = docElem.elementsByTagName("item");
    QDomNode channelElem = docElem.firstChildElement("channel");
    QString thumbnailUrl = channelElem.firstChildElement("image").attribute("href");
    QString genre = channelElem.firstChildElement("category").attribute("text");
    
    for (int i = 0; i < items.size(); i++) {
        QDomElement item = items.at(i).toElement();
        QDateTime dt = QDateTime::fromString(item.firstChildElement("pubDate").text().section(' ', 0, -2),
                                               "ddd, dd MMM yyyy hh:mm:ss");
        QString streamUrl = item.firstChildElement("enclosure").attribute("url");
        
        QVariantMap result;
        result["_dt"] = dt;
        result["artist"] = item.firstChildElement("author").text();
        result["date"] = dt.toString("dd MMM yyyy");
        result["description"] = item.firstChildElement("description").text();
        result["duration"] = item.firstChildElement("duration").text();
        result["format"] = streamUrl.mid(streamUrl.lastIndexOf('.') + 1).toUpper();
        result["genre"] = genre;
        result["id"] = reply->url();
        result["largeThumbnailUrl"] = thumbnailUrl;
        result["streamUrl"] = streamUrl;
        result["thumbnailUrl"] = thumbnailUrl;
        result["title"] = item.firstChildElement("title").text();
        result["url"] = item.firstChildElement("link").text();
        m_results << result;
    }
    
    reply->deleteLater();
    
    if (m_urls.isEmpty()) {
        printResult();
    }
    else {
        listTracks(m_urls.takeFirst());
    }
}
///
/// Download and update the drumkit list
///
void SoundLibraryImportDialog::on_UpdateListBtn_clicked()
{
	QApplication::setOverrideCursor(Qt::WaitCursor);
	DownloadWidget drumkitList( this, trUtf8( "Updating SoundLibrary list..." ), repositoryCombo->currentText() );
	drumkitList.exec();

	m_soundLibraryList.clear();

	QString sDrumkitXML = drumkitList.get_xml_content();

	QDomDocument dom;
	dom.setContent( sDrumkitXML );
	QDomNode drumkitNode = dom.documentElement().firstChild();
	while ( !drumkitNode.isNull() ) {
		if( !drumkitNode.toElement().isNull() ) {

			if ( drumkitNode.toElement().tagName() == "drumkit" || drumkitNode.toElement().tagName() == "song" || drumkitNode.toElement().tagName() == "pattern" ) {

				SoundLibraryInfo soundLibInfo;
			
				if ( drumkitNode.toElement().tagName() =="song" ) {
					soundLibInfo.setType( "song" );
				}

				if ( drumkitNode.toElement().tagName() =="drumkit" ) {
					soundLibInfo.setType( "drumkit" );
				}

				if ( drumkitNode.toElement().tagName() =="pattern" ) {
					soundLibInfo.setType( "pattern" );
				}

				QDomElement nameNode = drumkitNode.firstChildElement( "name" );
				if ( !nameNode.isNull() ) {
					soundLibInfo.setName( nameNode.text() );
				}

				QDomElement urlNode = drumkitNode.firstChildElement( "url" );
				if ( !urlNode.isNull() ) {
					soundLibInfo.setUrl( urlNode.text() );
				}

				QDomElement infoNode = drumkitNode.firstChildElement( "info" );
				if ( !infoNode.isNull() ) {
					soundLibInfo.setInfo( infoNode.text() );
				}

				QDomElement authorNode = drumkitNode.firstChildElement( "author" );
				if ( !authorNode.isNull() ) {
					soundLibInfo.setAuthor( authorNode.text() );
				}

				QDomElement licenseNode = drumkitNode.firstChildElement( "license" );
				if ( !licenseNode.isNull() ) {
					soundLibInfo.setLicense( licenseNode.text() );
				}

				m_soundLibraryList.push_back( soundLibInfo );
			}
		}
		drumkitNode = drumkitNode.nextSibling();
	}

	updateSoundLibraryList();
	QApplication::restoreOverrideCursor();
}
Ejemplo n.º 6
0
//!
//! Loads the XML description of a widget type from the file with the given
//! name.
//!
//! \param filename The name of an XML file describing a widget type.
//!
bool WidgetFactory::registerType ( const QString &filename )
{
	QFile file (filename);
    if (!file.exists()) {
        Log::error(QString("widget plugin file not found: \"%1\"").arg(filename), "WidgetFactory::registerType");
        return false;
    }
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        Log::error(QString("Error loading widget plugin file \"%1\".").arg(filename), "WidgetFactory::registerType");
        return false;
    }

    // read the content of the file using a simple XML reader
    QDomDocument description;
    QXmlInputSource source (&file);
    QXmlSimpleReader xmlReader;
    QString errorMessage;
    int errorLine = 0;
    int errorColumn = 0;
    if (!description.setContent(&source, &xmlReader, &errorMessage, &errorLine, &errorColumn)) {
        Log::error(QString("Error parsing \"%1\": %2, line %3, char %4").arg(filename).arg(errorMessage).arg(errorLine).arg(errorColumn), "WidgetFactory::registerType");
        return false;
    }

    // obtain node type information from attributes
    QDomElement rootElement = description.documentElement();
    QString PluginName = rootElement.attribute("name");
    QString PluginDLL = rootElement.attribute("plugin");
	QString PluginCall = rootElement.attribute("call");


	//// decode the full filename into its path and base file name
    QString filePath = file.fileName().mid(0, file.fileName().lastIndexOf('/') + 1);
    QString baseFilename = file.fileName().mid(file.fileName().lastIndexOf('/') + 1);
    Log::debug(QString("Parsing \"%1\"...").arg(baseFilename), "WidgetFactory::registerType");

    // load plugin if a plugin filename is given
    if (filename != "") {
        QString pluginFilename =  filePath  + PluginDLL;

#ifdef _DEBUG
        // adjust the plugin filename to load the debug version of the DLL
        pluginFilename = pluginFilename.replace(".dll", "_d.dll");
#endif
        if (QFile::exists(pluginFilename)) {
            Log::debug(QString("Loading plugin \"%1\"...").arg(pluginFilename), "WidgetFactory::registerType");
            QPluginLoader loader (pluginFilename);
            WidgetTypeInterface *widgetTypeInterface = qobject_cast<WidgetTypeInterface *>(loader.instance());
            if (!widgetTypeInterface) {
                Log::error(QString("Plugin \"%1\" could not be loaded: %2").arg(pluginFilename).arg(loader.errorString()), "WidgetFactory::registerType");
                return false;
            }
			if(!m_widgetTypeMap.contains(PluginCall)){
				m_widgetTypeMap[PluginCall] = widgetTypeInterface;
			}
        } else {
            Log::error(QString("Plugin file \"%1\" could not be found.").arg(pluginFilename), "WidgetFactory::registerType");
            return false;
        }
    }

    return true;
}
Ejemplo n.º 7
0
QgsRectangle QgsServerProjectParser::layerBoundingBoxInProjectCRS( const QDomElement& layerElem, const QDomDocument &doc ) const
{
  QgsRectangle BBox;
  if ( layerElem.isNull() )
  {
    return BBox;
  }

  //read box coordinates and layer auth. id
  QDomElement boundingBoxElem = layerElem.firstChildElement( "BoundingBox" );
  if ( boundingBoxElem.isNull() )
  {
    return BBox;
  }

  double minx, miny, maxx, maxy;
  bool conversionOk;
  minx = boundingBoxElem.attribute( "minx" ).toDouble( &conversionOk );
  if ( !conversionOk )
  {
    return BBox;
  }
  miny = boundingBoxElem.attribute( "miny" ).toDouble( &conversionOk );
  if ( !conversionOk )
  {
    return BBox;
  }
  maxx = boundingBoxElem.attribute( "maxx" ).toDouble( &conversionOk );
  if ( !conversionOk )
  {
    return BBox;
  }
  maxy = boundingBoxElem.attribute( "maxy" ).toDouble( &conversionOk );
  if ( !conversionOk )
  {
    return BBox;
  }


  QString version = doc.documentElement().attribute( "version" );

  //create layer crs
  const QgsCoordinateReferenceSystem& layerCrs = QgsCRSCache::instance()->crsByAuthId( boundingBoxElem.attribute( version == "1.1.1" ? "SRS" : "CRS" ) );
  if ( !layerCrs.isValid() )
  {
    return BBox;
  }

  BBox.setXMinimum( minx );
  BBox.setXMaximum( maxx );
  BBox.setYMinimum( miny );
  BBox.setYMaximum( maxy );

  if ( version != "1.1.1" && layerCrs.axisInverted() )
  {
    BBox.invert();
  }

  //get project crs
  const QgsCoordinateReferenceSystem& projectCrs = projectCRS();
  QgsCoordinateTransform t( layerCrs, projectCrs );

  //transform
  BBox = t.transformBoundingBox( BBox );
  return BBox;
}
Ejemplo n.º 8
0
bool OpenCLTraceOptions::setProjectSettingsXML(const gtString& projectAsXMLString)
{
    QString qtStr = acGTStringToQString(projectAsXMLString);

    QDomDocument doc;
    doc.setContent(qtStr.toUtf8());

    QDomElement rootElement = doc.documentElement();
    QDomNode rootNode = rootElement.firstChild();
    QDomNode childNode = rootNode.firstChild();

    QString nodeVal;
    bool val;

    while (!childNode.isNull())
    {
        val = false;
        nodeVal = childNode.firstChild().nodeValue();

        if (nodeVal == "T")
        {
            val = true;
        }

        if (childNode.nodeName() == acGTStringToQString(GPU_STR_ProjectSettingsGenerateOccupancy))
        {
            m_currentSettings.m_generateKernelOccupancy = val;
        }
        else if (childNode.nodeName() == acGTStringToQString(GPU_STR_ProjectSettingsShowErrorCode))
        {
            m_currentSettings.m_alwaysShowAPIErrorCode = val;
        }
        else if (childNode.nodeName() == acGTStringToQString(GPU_STR_ProjectSettingsCollapseClGetEventInfo))
        {
            m_currentSettings.m_collapseClGetEventInfo = val;
        }
        else if (childNode.nodeName() == acGTStringToQString(GPU_STR_ProjectSettingsEnableNavigation))
        {
            m_currentSettings.m_generateSymInfo = val;
        }
        else if (childNode.nodeName() == acGTStringToQString(GPU_STR_ProjectSettingsGenerateSummaryPage))
        {
            m_currentSettings.m_generateSummaryPage = val;
        }
        else if (childNode.nodeName() == acGTStringToQString(GPU_STR_ProjectSettingsAPIsToFilter))
        {
            m_currentSettings.m_filterAPIsToTrace = val;
        }
        else if (childNode.nodeName() == acGTStringToQString(GPU_STR_ProjectSettingsMaxAPIs))
        {
            m_currentSettings.m_maxAPICalls = nodeVal.toInt();
        }
        else if (childNode.nodeName() == acGTStringToQString(GPU_STR_ProjectSettingsWriteDataTimeOut))
        {
            m_currentSettings.m_writeDataTimeOut = val;
        }
        else if (childNode.nodeName() == acGTStringToQString(GPU_STR_ProjectSettingsTimeOutInterval))
        {
            m_currentSettings.m_timeoutInterval = nodeVal.toInt();
        }
        else if (childNode.nodeName() == acGTStringToQString(GPU_STR_ProjectSettingsAPIType))
        {
            if (nodeVal == acGTStringToQString(GPU_STR_ProjectSettingsAPITypeOpenCL))
            {
                m_currentSettings.m_apiToTrace = APIToTrace_OPENCL;
            }
            else if (nodeVal == acGTStringToQString(GPU_STR_ProjectSettingsAPITypeHSA))
            {
                m_currentSettings.m_apiToTrace = APIToTrace_HSA;
            }
            else
            {
                m_currentSettings.m_apiToTrace = APIToTrace_OPENCL;
                GT_ASSERT_EX(false, L"Invalid project settings option");
            }
        }
        else if (childNode.nodeName() == acGTStringToQString(GPU_STR_ProjectSettingsRulesTree))
        {
            if (childNode.hasChildNodes())
            {
                UpdateTreeWidgetFromXML(childNode, m_pAPIRulesTW, false);
            }
            else
            {
                if (m_pAPIRulesTW != nullptr)
                {
                    Util::SetCheckState(m_pAPIRulesTW, true);
                }
            }

            UpdateRuleList();
        }
        else if (childNode.nodeName() == acGTStringToQString(GPU_STR_ProjectSettingsAPIsFilterTree))
        {
            if (childNode.hasChildNodes())
            {
                UpdateTreeWidgetFromXML(childNode, m_pAPIsToTraceTW, true);
            }
            else
            {
                if (m_pAPIsToTraceTW != nullptr)
                {
                    Util::SetCheckState(m_pAPIsToTraceTW, true);
                }
            }

            UpdateAPIFilterList();
        }

        childNode = childNode.nextSibling();
    }

    return true;
}
Ejemplo n.º 9
0
/**
* Slot called when pbtnLoadPredefinedQueries button is pressed. The method will open a file dialog and then
* try to parse through an XML file of predefined queries.
*/
void eVisDatabaseConnectionGui::on_pbtnLoadPredefinedQueries_clicked()
{
  //There probably needs to be some more error checking, but works for now.

  //Select the XML file to parse
  QString myFilename = QFileDialog::getOpenFileName( this, tr( "Open File" ), ".", "XML ( *.xml )" );
  if ( myFilename != "" )
  {
    //Display the name of the file being parsed
    lblPredefinedQueryFilename->setText( myFilename );

    //If the file exists load it into a QDomDocument
    QFile myInputFile( myFilename );
    if ( myInputFile.open( QIODevice::ReadOnly | QIODevice::Text ) )
    {
      QString errorString;
      int errorLine;
      int errorColumn;
      QDomDocument myXmlDoc;
      if ( myXmlDoc.setContent( &myInputFile, &errorString, &errorLine, &errorColumn ) )
      {
        //clear any existing query descrptions
        cboxPredefinedQueryList->clear();
        if ( !mQueryDefinitionMap->empty() )
        {
          delete( mQueryDefinitionMap );
          mQueryDefinitionMap = new QMap<int, eVisQueryDefinition>;
        }

        //Loop through each child looking for a query tag
        int myQueryCount = 0;
        QDomNode myNode = myXmlDoc.documentElement().firstChild();
        while ( !myNode.isNull() )
        {
          if ( myNode.toElement().tagName() == "query" )
          {
            bool insert = false;
            eVisQueryDefinition myQueryDefinition;
            QDomNode myChildNodes = myNode.toElement().firstChild();
            while ( !myChildNodes.isNull() )
            {
              QDomNode myDataNode = myChildNodes.toElement().firstChild();
              QString myDataNodeContent = "";
              if ( !myDataNode.isNull() )
              {
                myDataNodeContent = myDataNode.toText().data();
              }

              if ( myChildNodes.toElement().tagName() == "shortdescription" )
              {
                if ( myDataNodeContent != "" )
                {
                  myQueryDefinition.setShortDescription( myDataNodeContent );
                  myQueryCount++;
                  insert = true;
                }
              }
              else if ( myChildNodes.toElement().tagName() == "description" )
              {
                myQueryDefinition.setDescription( myDataNodeContent );
              }
              else if ( myChildNodes.toElement().tagName() == "databasetype" )
              {
                myQueryDefinition.setDatabaseType( myDataNodeContent );
              }
              else if ( myChildNodes.toElement().tagName() == "databasehost" )
              {
                myQueryDefinition.setDatabaseHost( myDataNodeContent );
              }
              else if ( myChildNodes.toElement().tagName() == "databaseport" )
              {
                myQueryDefinition.setDatabasePort( myDataNodeContent.toInt() );
              }
              else if ( myChildNodes.toElement().tagName() == "databasename" )
              {
                myQueryDefinition.setDatabaseName( myDataNodeContent );
              }
              else if ( myChildNodes.toElement().tagName() == "databaseusername" )
              {
                myQueryDefinition.setDatabaseUsername( myDataNodeContent );
              }
              else if ( myChildNodes.toElement().tagName() == "databasepassword" )
              {
                myQueryDefinition.setDatabasePassword( myDataNodeContent );
              }
              else if ( myChildNodes.toElement().tagName() == "sqlstatement" )
              {
                myQueryDefinition.setSqlStatement( myDataNodeContent );
              }

              myChildNodes = myChildNodes.nextSibling();
            } //end  while( !myChildNodes.isNull() )

            if ( insert )
            {
              mQueryDefinitionMap->insert( myQueryCount - 1, myQueryDefinition );
              cboxPredefinedQueryList->insertItem( myQueryCount - 1, myQueryDefinition.shortDescription() );
            }
          } //end if( myNode.toElement().tagName() == "query" )
          myNode = myNode.nextSibling();
        } // end  while( !myNode.isNull() )
      }
      else
      {
        teditConsole->append( tr( "Error: Parse error at line %1, column %2: %3" ).arg( errorLine ).arg( errorColumn ).arg( errorString ) );
      }
    }
    else
    {
      teditConsole->append( tr( "Error: Unabled to open file [%1]" ).arg( myFilename ) );
    }
  }
}
Ejemplo n.º 10
0
 QDomElement metadataElement( const QDomDocument& document )
 {
     QDomElement root = document.documentElement();
     return root.firstChildElement( "metadata" );
 }
Ejemplo n.º 11
0
bool QgsStyleV2::load( QString filename )
{
  mErrorString.clear();

  // Open the sqlite database
  if ( !openDB( filename ) )
  {
    mErrorString = "Unable to open database file specified";
    QgsDebugMsg( mErrorString );
    return false;
  }

  // Make sure there are no Null fields in parenting symbols ang groups
  char *query = sqlite3_mprintf( "UPDATE symbol SET groupid=0 WHERE groupid IS NULL;"
                                 "UPDATE colorramp SET groupid=0 WHERE groupid IS NULL;"
                                 "UPDATE symgroup SET parent=0 WHERE parent IS NULL;" );
  runEmptyQuery( query );

  // First create all the main symbols
  query = sqlite3_mprintf( "SELECT * FROM symbol" );

  sqlite3_stmt *ppStmt;
  int nError = sqlite3_prepare_v2( mCurrentDB, query, -1, &ppStmt, NULL );
  while ( nError == SQLITE_OK && sqlite3_step( ppStmt ) == SQLITE_ROW )
  {
    QDomDocument doc;
    QString symbol_name = QString::fromUtf8(( const char * ) sqlite3_column_text( ppStmt, SymbolName ) );
    QString xmlstring = QString::fromUtf8(( const char * ) sqlite3_column_text( ppStmt, SymbolXML ) );
    if ( !doc.setContent( xmlstring ) )
    {
      QgsDebugMsg( "Cannot open symbol " + symbol_name );
      continue;
    }

    QDomElement symElement = doc.documentElement();
    QgsSymbolV2 *symbol = QgsSymbolLayerV2Utils::loadSymbol( symElement );
    if ( symbol != NULL )
      mSymbols.insert( symbol_name, symbol );
  }

  sqlite3_finalize( ppStmt );

  query = sqlite3_mprintf( "SELECT * FROM colorramp" );
  nError = sqlite3_prepare_v2( mCurrentDB, query, -1, &ppStmt, NULL );
  while ( nError == SQLITE_OK && sqlite3_step( ppStmt ) == SQLITE_ROW )
  {
    QDomDocument doc;
    QString ramp_name = QString::fromUtf8(( const char * ) sqlite3_column_text( ppStmt, ColorrampName ) );
    QString xmlstring = QString::fromUtf8(( const char * ) sqlite3_column_text( ppStmt, ColorrampXML ) );
    if ( !doc.setContent( xmlstring ) )
    {
      QgsDebugMsg( "Cannot open symbol " + ramp_name );
      continue;
    }
    QDomElement rampElement = doc.documentElement();
    QgsVectorColorRampV2 *ramp = QgsSymbolLayerV2Utils::loadColorRamp( rampElement );
    if ( ramp )
      mColorRamps.insert( ramp_name, ramp );
  }

  mFileName = filename;
  return true;
}
Ejemplo n.º 12
0
    QDomElement reportElement( const QDomDocument& document )
    {
        QDomElement root = document.documentElement();
        return root.firstChildElement( "report" );

    }
Ejemplo n.º 13
0
QString EventDispatcher::GetOSDisplayString()
{
        QStringList key;
    QStringList string;
    QFile xmlFile("/System/Library/CoreServices/SystemVersion.plist");
    if(xmlFile.open(QIODevice::ReadOnly))
    {
        QString content=xmlFile.readAll();
        xmlFile.close();
        QString errorStr;
        int errorLine;
        int errorColumn;
        QDomDocument domDocument;
        if (!domDocument.setContent(content, false, &errorStr,&errorLine,&errorColumn))
            return "Mac OS X";
        else
        {
            QDomElement root = domDocument.documentElement();
            if(root.tagName()!="plist")
                return "Mac OS X";
            else
            {
                if(root.isElement())
                {
                    QDomElement SubChild=root.firstChildElement("dict");
                    while(!SubChild.isNull())
                    {
                        if(SubChild.isElement())
                        {
                            QDomElement SubChild2=SubChild.firstChildElement("key");
                            while(!SubChild2.isNull())
                            {
                                if(SubChild2.isElement())
                                    key << SubChild2.text();
                                else
                                    return "Mac OS X";
                                SubChild2 = SubChild2.nextSiblingElement("key");
                            }
                            SubChild2=SubChild.firstChildElement("string");
                            while(!SubChild2.isNull())
                            {
                                if(SubChild2.isElement())
                                    string << SubChild2.text();
                                else
                                    return "Mac OS X";
                                SubChild2 = SubChild2.nextSiblingElement("string");
                            }
                        }
                        else
                            return "Mac OS X";
                        SubChild = SubChild.nextSiblingElement("property");
                    }
                }
                else
                    return "Mac OS X";
            }
        }
    }
    if(key.size()!=string.size())
        return "Mac OS X";
    int index=0;
    while(index<key.size())
    {
        if(key.at(index)=="ProductVersion")
            return "Mac OS X "+string.at(index);
        index++;
    }
    return "Mac OS X";
}
Ejemplo n.º 14
0
void GLBox::drawObject(const QDomDocument &doc)
{
	QDomElement root = doc.documentElement().toElement();

	QDomElement texture1 = root.elementsByTagName("textures").item(0).toElement();

	for (QDomNode i = texture1.firstChild(); !i.isNull(); i = i.nextSibling())
	{
		QDomElement e = i.toElement();

		QString name = e.attribute("name");
		QString file = e.attribute("file");
		QString color = e.attribute("color", "0xFFFFFF");
		QString xscale = e.attribute("xscale", "1.0");
		QString yscale = e.attribute("yscale", "1.0");

		qDebug()<<"Adding Texture:"<<name<<color<<file<<xscale<<yscale;
		textures[name] = Texture(color.toUInt(0, 16), file, xscale.toFloat(), yscale.toFloat());
	}

	QDomElement item = root.elementsByTagName("items").item(0).toElement();

	for (QDomNode i = item.firstChild(); !i.isNull(); i = i.nextSibling())
	{
		QDomElement e = i.toElement();

		QString x = e.attribute("x");
		QString y = e.attribute("y");
		QString z = e.attribute("z");
		QString rotation = e.attribute("rotation", "0.0");
		QString type = e.attribute("type");

		if (type == "wall")
		{
			QString length = e.attribute("length");
			QString innerTexture = e.attribute("innerTexture");
			QString outerTexture = e.attribute("outerTexture");
			QString height = e.attribute("height", "10.0");
			QString thickness = e.attribute("thickness", "0.5");

			qDebug()<<"Adding Wall:"<<x<<y<<z<<rotation<<length<<innerTexture<<outerTexture<<height<<thickness;

			Wall *wall = new Wall(x.toFloat(), y.toFloat(), z.toFloat(), rotation.toFloat(), length.toFloat(), textures[innerTexture], textures[outerTexture], height.toFloat(), thickness.toFloat());

			// now we start parsing the windows
			for (QDomNode w = e.firstChild(); !w.isNull(); w = w.nextSibling()) {
				QDomElement tmp = w.toElement();

				if (tmp.tagName() == "window") {
					QString position = tmp.attribute("position");
					QString length = tmp.attribute("length");
					QString texture = tmp.attribute("texture");
					QString lowerHeight = tmp.attribute("lowerHeight", "3.0");
					QString upperHeight = tmp.attribute("upperHeight", "7.0");
					wall->addWindow(position.toFloat(), length.toFloat(), textures[texture], lowerHeight.toFloat(), upperHeight.toFloat());
					qDebug()<<"Added Window:"<<position<<length<<texture<<lowerHeight<<upperHeight;
				}
				else if (tmp.tagName() == "door") {
					QString position = tmp.attribute("position");
					QString length = tmp.attribute("length");
					QString texture = tmp.attribute("texture");
					QString height = tmp.attribute("height", "7.0");
					wall->addDoor(position.toFloat(), length.toFloat(), textures[texture], height.toFloat());
					qDebug()<<"Added Door:"<<position<<length<<texture<<height;
				}
			}

			addObject(wall);
		} else if (type == "floor") {
			QString texture = e.attribute("texture");
			qDebug()<<"Adding Floor:"<<x<<y<<z<<rotation;
			Floor *floor = new Floor(x.toFloat(), y.toFloat(), z.toFloat(), rotation.toFloat(), textures[texture]);

			// now we start parsing the windows
			for (QDomNode w = e.firstChild(); !w.isNull(); w = w.nextSibling()) {
				QDomElement tmp = w.toElement();

				if (tmp.tagName() == "point") {
					QString x = tmp.attribute("x");
					QString y = tmp.attribute("y");
					floor->addPoint(x.toFloat(), y.toFloat());

					qDebug()<<"Added Point:"<<x<<y;
				}
			}

			addObject(floor);
		}
	}
}
Ejemplo n.º 15
0
QTextDocument* Converter::convert(const QString &fileName)
{
    firstTime = true;
    Document oooDocument(fileName);
    if (!oooDocument.open())
    {
        return 0;
    }
    m_TextDocument = new QTextDocument;
    m_Cursor = new QTextCursor(m_TextDocument);

    /**
     * Create the dom of the content
     */
    QXmlSimpleReader reader;

    QXmlInputSource source;
    source.setData(oooDocument.content());
    QString errorMsg;
    QDomDocument document;
    if (!document.setContent(&source, &reader, &errorMsg))
    {
        setError(QString("Invalid XML document: %1").arg(errorMsg), -1);
        delete m_Cursor;
        return m_TextDocument;
    }

    /**
     * Read the style properties, so the are available when
     * parsing the content.
     */

    m_StyleInformation = new StyleInformation();

    if (oooDocument.content().size() == 0)
    {
        setError("Empty document", -1);
    }

    StyleParser styleParser(&oooDocument, document, m_StyleInformation);
    if (!styleParser.parse())
    {
        setError("Unable to read style information", -1);
        delete m_Cursor;
        return 0;
    }

    /**
    * Add all images of the document to resource framework
    */

    QMap<QString, QByteArray> imageLIST = oooDocument.images();
    QMapIterator<QString, QByteArray> it(imageLIST);
    while (it.hasNext())
    {
        it.next();
        m_TextDocument->addResource(QTextDocument::ImageResource, QUrl(it.key()), QImage::fromData(it.value()));
    }

    /**
     * Set the correct page size
     */

    const QString masterLayout = m_StyleInformation->masterPageName();

    if (m_StyleInformation->pagePropertyExists(masterLayout))
    {
        const int DPX = 231; /// im.logicalDpiX(); // 231
        const int DPY = 231; // im.logicalDpiY(); // 231
        const int A4Width = MM_TO_POINT(210); /// A4 210 x297 mm
        const int A4Height = MM_TO_POINT(297);

        const PageFormatProperty property = m_StyleInformation->pageProperty(masterLayout);
        int pageWidth = qRound(property.width() / 72.0 * DPX);
        if (pageWidth < 1) {
            pageWidth = A4Width;
        }
        int pageHeight = qRound(property.height() / 72.0 * DPY);
        if (pageHeight < 1) {
            pageHeight = A4Height;
        }
        m_TextDocument->setPageSize(QSize(pageWidth, pageHeight));

        QTextFrameFormat frameFormat;
        frameFormat.setMargin(qRound(property.margin()));

        QTextFrame *rootFrame = m_TextDocument->rootFrame();
        rootFrame->setFrameFormat(frameFormat);
    }

    /**
     * Parse the content of the document
     */
    const QDomElement documentElement = document.documentElement();

    QDomElement element = documentElement.firstChildElement();
    while (!element.isNull())
    {
        if (element.tagName() == QLatin1String("body"))
        {
            if (!convertBody(element))
            {
                setError("Unable to convert document content", -1);
                delete m_Cursor;
                return 0;
            }
        }

        element = element.nextSiblingElement();
    }

    return m_TextDocument;
}
Ejemplo n.º 16
0
void MainWindowTask::loadMarks(const QString fileName)
{
    QDomDocument workXml;
    QFile f(fileName);
    if  (!f.open(QIODevice::ReadOnly))
    {
        QMessageBox::information( 0, "", trUtf8("Ошибка открытия файла: ") + fileName, 0,0,0);
        return;

    };
if(f.atEnd())
    {
    QMessageBox::information( 0, "", trUtf8("Ошибка открытия файла ,файл пуст: ") + fileName, 0,0,0);
    return;
    };
cursWorkFile.setFileName(f.fileName());
QString error;
int str,pos;
workXml.setContent(f.readAll(),true,&error,&str,&pos);
qDebug()<<"File parce:"<<error<<"str"<<str<<" pos"<<pos;

QDomElement root=workXml.documentElement ();
if(root.tagName()!="COURSE")
  {
        QMessageBox::information( 0, "", trUtf8("Ошибка загрузки файла: ") + fileName, 0,0,0);
        return;
  };
QDomElement fileEl=root.firstChildElement("FILE");
loadCourseData(fileEl.attribute("fileName"));//Gruzim kurs

QString fileN=fileEl.attribute("fileName");
qDebug()<<"KURS ZAGRUZILI";
if(cursFile!=fileEl.attribute("fileName")){
    QMessageBox::information( 0, "", trUtf8("Не наеден файл курса:") + fileEl.attribute("fileName"), 0,0,0);
    fileN=getFileName(fileEl.attribute("fileName"));
    loadCourseData(fileN);
    if(cursFile!=fileN)return;
    }
QFileInfo fi_kurs=QFileInfo(fileN);
curDir=fi_kurs.absolutePath();
QDomNodeList marksElList=root.elementsByTagName("MARK"); //Оценки
qDebug()<<"Loading marks "<<marksElList.count();
for(int i=0;i<marksElList.count();i++)
 {
 int taskId=marksElList.at(i).toElement().attribute("testId").toInt();
 int mark=marksElList.at(i).toElement().attribute("mark").toInt();
 qDebug()<<"task:"<<taskId<<" mark:"<<mark;
 course->setMark(taskId,mark);
 changes.setMark(taskId,mark);
 };

qDebug()<<"Loading user prgs...";
QDomNodeList prgElList=root.elementsByTagName("USER_PRG");//Программы
for(int i=0;i<prgElList.count();i++)
 {
 int taskId=prgElList.at(i).toElement().attribute("testId").toInt();
 qDebug()<<"Tassk id"<<taskId;
 QString prg =prgElList.at(i).toElement().attribute("prg");
 QModelIndex tIdx=course->getIndexById(taskId);

 if(progChange.indexOf(taskId)==-1){

     progChange.append(taskId);
      };
 course->setUserText(taskId,prg);
ui->treeView->setSelectionMode(QAbstractItemView::ExtendedSelection);
 };

};
Ejemplo n.º 17
0
void
XSPFLoader::gotBody()
{
    QDomDocument xmldoc;
    bool namespaceProcessing = true;
    xmldoc.setContent( m_body, namespaceProcessing );
    QDomElement docElement( xmldoc.documentElement() );

    QString origTitle;
    QDomNodeList tracklist;
    QDomElement n = docElement.firstChildElement();
    for ( ; !n.isNull(); n = n.nextSiblingElement() )
    {
        if ( n.namespaceURI() == m_NS && n.localName() == "title" )
        {
            origTitle = n.text();
        }
        else if ( n.namespaceURI() == m_NS && n.localName() == "creator" )
        {
            m_creator = n.text();
        }
        else if ( n.namespaceURI() == m_NS && n.localName() == "info" )
        {
            m_info = n.text();
        }
        else if ( n.namespaceURI() == m_NS && n.localName() == "trackList" )
        {
            tracklist = n.childNodes();
        }
    }

    m_title = origTitle;
    if ( m_title.isEmpty() )
        m_title = tr( "New Playlist" );
    if ( !m_overrideTitle.isEmpty() )
        m_title = m_overrideTitle;

    bool shownError = false;
    for ( int i = 0; i < tracklist.length(); i++ )
    {
        QDomNode e = tracklist.at( i );

        QString artist, album, track, duration, annotation, url;
        QDomElement n = e.firstChildElement();
        for ( ; !n.isNull(); n = n.nextSiblingElement() )
        {
            if ( n.namespaceURI() == m_NS && n.localName() == "duration" )
            {
                duration = n.text();
            }
            else if ( n.namespaceURI() == m_NS && n.localName() == "annotation" )
            {
                annotation = n.text();
            }
            else if ( n.namespaceURI() == m_NS && n.localName() == "creator" )
            {
                artist = n.text();
            }
            else if ( n.namespaceURI() == m_NS && n.localName() == "album" )
            {
                album = n.text();
            }
            else if ( n.namespaceURI() == m_NS && n.localName() == "title" )
            {
                track = n.text();
            }
            else if ( n.namespaceURI() == m_NS && n.localName() == "url" )
            {
                if ( !n.text().startsWith( "http" ) || TomahawkUtils::whitelistedHttpResultHint( n.text() ) )
                    url = n.text();
            }
            else if ( n.namespaceURI() == m_NS && n.localName() == "location" )
            {
                if ( !n.text().startsWith( "http" ) || TomahawkUtils::whitelistedHttpResultHint( n.text() ) )
                    url = n.text();
            }
        }

        if ( artist.isEmpty() || track.isEmpty() )
        {
            if ( !shownError )
            {
                emit error( InvalidTrackError );
                shownError = true;
            }
            continue;
        }

        track_ptr t = Tomahawk::Track::get( artist, track, album, duration.toInt() / 1000 );
        query_ptr q = Tomahawk::Query::get( t );
        if ( q.isNull() )
            continue;

        if ( !url.isEmpty() )
        {
            q->setResultHint( url );
            q->setSaveHTTPResultHint( true );
        }

        m_entries << q;
    }

    if ( m_autoResolve )
    {
        for ( int i = m_entries.size() - 1; i >= 0; i-- )
            Pipeline::instance()->resolve( m_entries[ i ] );
    }

    if ( origTitle.isEmpty() && m_entries.isEmpty() )
    {
        emit error( ParseError );
        if ( m_autoCreate )
            deleteLater();
        return;
    }

    if ( m_autoCreate )
    {
        emit ok( getPlaylistForRecentUrl() );
    }
    else
    {
        if ( !m_entries.isEmpty() )
            emit tracks( m_entries );
    }

    if ( m_autoDelete )
        deleteLater();
}
Ejemplo n.º 18
0
void RSSEditPopup::SlotSave(QNetworkReply* reply)
{
    QDomDocument document;
    document.setContent(reply->read(reply->bytesAvailable()), true);

    QString text = document.toString();

    QString title = m_titleEdit->GetText();
    QString description = m_descEdit->GetText();
    QString author = m_authorEdit->GetText();
    QString file = m_thumbImage->GetFilename();

    LOG(VB_GENERAL, LOG_DEBUG, QString("Text to Parse: %1").arg(text));

    QDomElement root = document.documentElement();
    QDomElement channel = root.firstChildElement ("channel");
    if (!channel.isNull())
    {
        Parse parser;
        if (title.isEmpty())
            title = channel.firstChildElement("title").text().trimmed();
        if (description.isEmpty())
            description = channel.firstChildElement("description").text();
        if (author.isEmpty())
            author = parser.GetAuthor(channel);
        if (author.isEmpty())
            author = channel.firstChildElement("managingEditor").text();
        if (author.isEmpty())
            author = channel.firstChildElement("webMaster").text();

        QString thumbnailURL =
            channel.firstChildElement("image").attribute("url");
        if (thumbnailURL.isEmpty())
        {
            QDomElement thumbElem = channel.firstChildElement("image");
            if (!thumbElem.isNull())
                thumbnailURL = thumbElem.firstChildElement("url").text();
        }
        if (thumbnailURL.isEmpty())
        {
            QDomNodeList nodes = channel.elementsByTagNameNS(
                           "http://www.itunes.com/dtds/podcast-1.0.dtd",
                           "image");
            if (nodes.size())
            {
                thumbnailURL =
                    nodes.at(0).toElement().attributeNode("href").value();
                if (thumbnailURL.isEmpty())
                    thumbnailURL = nodes.at(0).toElement().text();
            }
        }

        bool download;
        if (m_download->GetCheckState() == MythUIStateType::Full)
            download = true;
        else
            download = false;

        QDateTime updated = MythDate::current();
        QString filename("");

        if (!file.isEmpty())
            filename = file;
        else if (!thumbnailURL.isEmpty())
            filename = thumbnailURL;

        QString link = m_urlEdit->GetText();

        RSSSite site(title, filename, VIDEO_PODCAST, description, link,
                     author, download, MythDate::current());
        if (insertInDB(&site))
            emit Saving();
    }

    Close();
}
Ejemplo n.º 19
0
void QgsServerProjectParser::serviceCapabilities( QDomElement& parentElement, QDomDocument& doc, const QString& service, bool sia2045 ) const
{
  QDomElement propertiesElement = propertiesElem();
  if ( propertiesElement.isNull() )
  {
    QgsConfigParserUtils::fallbackServiceCapabilities( parentElement, doc );
    return;
  }
  QDomElement serviceElem = doc.createElement( "Service" );

  QDomElement serviceCapabilityElem = propertiesElement.firstChildElement( "WMSServiceCapabilities" );
  if ( serviceCapabilityElem.isNull() || serviceCapabilityElem.text().compare( "true", Qt::CaseInsensitive ) != 0 )
  {
    QgsConfigParserUtils::fallbackServiceCapabilities( parentElement, doc );
    return;
  }

  //Service name
  QDomElement wmsNameElem = doc.createElement( "Name" );
  QDomText wmsNameText = doc.createTextNode( service );
  wmsNameElem.appendChild( wmsNameText );
  serviceElem.appendChild( wmsNameElem );

  //WMS title
  //why not use project title ?
  QDomElement titleElem = propertiesElement.firstChildElement( "WMSServiceTitle" );
  if ( !titleElem.isNull() )
  {
    QDomElement wmsTitleElem = doc.createElement( "Title" );
    QDomText wmsTitleText = doc.createTextNode( titleElem.text() );
    wmsTitleElem.appendChild( wmsTitleText );
    serviceElem.appendChild( wmsTitleElem );
  }

  //WMS abstract
  QDomElement abstractElem = propertiesElement.firstChildElement( "WMSServiceAbstract" );
  if ( !abstractElem.isNull() )
  {
    QDomElement wmsAbstractElem = doc.createElement( "Abstract" );
    QDomText wmsAbstractText = doc.createTextNode( abstractElem.text() );
    wmsAbstractElem.appendChild( wmsAbstractText );
    serviceElem.appendChild( wmsAbstractElem );
  }

  //keyword list
  QDomElement keywordListElem = propertiesElement.firstChildElement( "WMSKeywordList" );
  if ( service.compare( "WMS", Qt::CaseInsensitive ) == 0 )
  {
    QDomElement wmsKeywordElem = doc.createElement( "KeywordList" );
    //add default keyword
    QDomElement keywordElem = doc.createElement( "Keyword" );
    keywordElem.setAttribute( "vocabulary", "ISO" );
    QDomText keywordText = doc.createTextNode( "infoMapAccessService" );
    /* If WFS and WCS 2.0 is implemented
    if ( service.compare( "WFS", Qt::CaseInsensitive ) == 0 )
      keywordText = doc.createTextNode( "infoFeatureAccessService" );
    else if ( service.compare( "WCS", Qt::CaseInsensitive ) == 0 )
      keywordText = doc.createTextNode( "infoCoverageAccessService" );*/
    keywordElem.appendChild( keywordText );
    wmsKeywordElem.appendChild( keywordElem );
    serviceElem.appendChild( wmsKeywordElem );
    //add config keywords
    if ( !keywordListElem.isNull() && !keywordListElem.text().isEmpty() )
    {
      QDomNodeList keywordList = keywordListElem.elementsByTagName( "value" );
      for ( int i = 0; i < keywordList.size(); ++i )
      {
        keywordElem = doc.createElement( "Keyword" );
        keywordText = doc.createTextNode( keywordList.at( i ).toElement().text() );
        keywordElem.appendChild( keywordText );
        if ( sia2045 )
        {
          keywordElem.setAttribute( "vocabulary", "SIA_Geo405" );
        }
        wmsKeywordElem.appendChild( keywordElem );
      }
    }
  }
  else if ( !keywordListElem.isNull() && !keywordListElem.text().isEmpty() )
  {
    QDomNodeList keywordNodeList = keywordListElem.elementsByTagName( "value" );
    QStringList keywordList;
    for ( int i = 0; i < keywordNodeList.size(); ++i )
    {
      keywordList.push_back( keywordNodeList.at( i ).toElement().text() );
    }
    QDomElement wmsKeywordElem = doc.createElement( "Keywords" );
    if ( service.compare( "WCS", Qt::CaseInsensitive ) == 0 )
      wmsKeywordElem = doc.createElement( "keywords" );
    QDomText keywordText = doc.createTextNode( keywordList.join( ", " ) );
    wmsKeywordElem.appendChild( keywordText );
    serviceElem.appendChild( wmsKeywordElem );
  }

  //OnlineResource element is mandatory according to the WMS specification
  QDomElement wmsOnlineResourceElem = propertiesElement.firstChildElement( "WMSOnlineResource" );
  if ( !wmsOnlineResourceElem.isNull() )
  {
    QDomElement onlineResourceElem = doc.createElement( "OnlineResource" );
    if ( service.compare( "WFS", Qt::CaseInsensitive ) == 0 )
    {
      QDomText onlineResourceText = doc.createTextNode( wmsOnlineResourceElem.text() );
      onlineResourceElem.appendChild( onlineResourceText );
    }
    else
    {
      onlineResourceElem.setAttribute( "xmlns:xlink", "http://www.w3.org/1999/xlink" );
      onlineResourceElem.setAttribute( "xlink:type", "simple" );
      onlineResourceElem.setAttribute( "xlink:href", wmsOnlineResourceElem.text() );
    }
    serviceElem.appendChild( onlineResourceElem );
  }

  if ( service.compare( "WMS", Qt::CaseInsensitive ) == 0 ) //no contact information in WFS 1.0 and WCS 1.0
  {
    //Contact information
    QDomElement contactInfoElem = doc.createElement( "ContactInformation" );

    //Contact person primary
    QDomElement contactPersonPrimaryElem = doc.createElement( "ContactPersonPrimary" );

    //Contact person
    QDomElement contactPersonElem = propertiesElement.firstChildElement( "WMSContactPerson" );
    QString contactPersonString;
    if ( !contactPersonElem.isNull() )
    {
      contactPersonString = contactPersonElem.text();
    }
    QDomElement wmsContactPersonElem = doc.createElement( "ContactPerson" );
    QDomText contactPersonText = doc.createTextNode( contactPersonString );
    wmsContactPersonElem.appendChild( contactPersonText );
    contactPersonPrimaryElem.appendChild( wmsContactPersonElem );


    //Contact organisation
    QDomElement contactOrganizationElem = propertiesElement.firstChildElement( "WMSContactOrganization" );
    QString contactOrganizationString;
    if ( !contactOrganizationElem.isNull() )
    {
      contactOrganizationString = contactOrganizationElem.text();
    }
    QDomElement wmsContactOrganizationElem = doc.createElement( "ContactOrganization" );
    QDomText contactOrganizationText = doc.createTextNode( contactOrganizationString );
    wmsContactOrganizationElem.appendChild( contactOrganizationText );
    contactPersonPrimaryElem.appendChild( wmsContactOrganizationElem );

    //Contact position
    QDomElement contactPositionElem = propertiesElement.firstChildElement( "WMSContactPosition" );
    QString contactPositionString;
    if ( !contactPositionElem.isNull() )
    {
      contactPositionString = contactPositionElem.text();
    }
    QDomElement wmsContactPositionElem = doc.createElement( "ContactPosition" );
    QDomText contactPositionText = doc.createTextNode( contactPositionString );
    wmsContactPositionElem.appendChild( contactPositionText );
    contactPersonPrimaryElem.appendChild( wmsContactPositionElem );
    contactInfoElem.appendChild( contactPersonPrimaryElem );

    //phone
    QDomElement phoneElem = propertiesElement.firstChildElement( "WMSContactPhone" );
    if ( !phoneElem.isNull() )
    {
      QDomElement wmsPhoneElem = doc.createElement( "ContactVoiceTelephone" );
      QDomText wmsPhoneText = doc.createTextNode( phoneElem.text() );
      wmsPhoneElem.appendChild( wmsPhoneText );
      contactInfoElem.appendChild( wmsPhoneElem );
    }

    //mail
    QDomElement mailElem = propertiesElement.firstChildElement( "WMSContactMail" );
    if ( !mailElem.isNull() )
    {
      QDomElement wmsMailElem = doc.createElement( "ContactElectronicMailAddress" );
      QDomText wmsMailText = doc.createTextNode( mailElem.text() );
      wmsMailElem.appendChild( wmsMailText );
      contactInfoElem.appendChild( wmsMailElem );
    }

    serviceElem.appendChild( contactInfoElem );
  }

  //Fees
  QDomElement feesElem = propertiesElement.firstChildElement( "WMSFees" );
  QDomElement wmsFeesElem = doc.createElement( "Fees" );
  QDomText wmsFeesText = doc.createTextNode( "conditions unknown" ); // default value if access conditions are unknown
  if ( !feesElem.isNull() && !feesElem.text().isEmpty() )
  {
    wmsFeesText = doc.createTextNode( feesElem.text() );
  }
  wmsFeesElem.appendChild( wmsFeesText );
  serviceElem.appendChild( wmsFeesElem );

  //AccessConstraints
  QDomElement accessConstraintsElem = propertiesElement.firstChildElement( "WMSAccessConstraints" );
  QDomElement wmsAccessConstraintsElem = doc.createElement( "AccessConstraints" );
  QDomText wmsAccessConstraintsText = doc.createTextNode( "None" ); // default value if access constraints are unknown
  if ( !accessConstraintsElem.isNull() && !accessConstraintsElem.text().isEmpty() )
  {
    wmsAccessConstraintsText = doc.createTextNode( accessConstraintsElem.text() );
  }
  wmsAccessConstraintsElem.appendChild( wmsAccessConstraintsText );
  serviceElem.appendChild( wmsAccessConstraintsElem );

  //max width, max height for WMS
  if ( service.compare( "WMS", Qt::CaseInsensitive ) == 0 )
  {
    QString version = doc.documentElement().attribute( "version" );
    if ( version != "1.1.1" )
    {
      //max width
      QDomElement mwElem = propertiesElement.firstChildElement( "WMSMaxWidth" );
      if ( !mwElem.isNull() )
      {
        QDomElement maxWidthElem = doc.createElement( "MaxWidth" );
        QDomText maxWidthText = doc.createTextNode( mwElem.text() );
        maxWidthElem.appendChild( maxWidthText );
        serviceElem.appendChild( maxWidthElem );
      }
      //max height
      QDomElement mhElem = propertiesElement.firstChildElement( "WMSMaxHeight" );
      if ( !mhElem.isNull() )
      {
        QDomElement maxHeightElem = doc.createElement( "MaxHeight" );
        QDomText maxHeightText = doc.createTextNode( mhElem.text() );
        maxHeightElem.appendChild( maxHeightText );
        serviceElem.appendChild( maxHeightElem );
      }
    }
  }
  parentElement.appendChild( serviceElem );
}
Ejemplo n.º 20
0
void Qtfe::load()
{
	QString name = QFileDialog::getOpenFileName(0, QString(), QString(), "*.xml");
	if(name.isEmpty())
		return;
	filename = name;
	fileLabel->setText(filename);
	QFile file(filename);
	if (!file.open(QIODevice::ReadOnly))
		return;

	QDomDocument doc;
	if (!doc.setContent(&file))
	{
		file.close();
		return;
	}
	file.close();

	// block functionChanged() signal while loading
	blockSignals(true);

	for(int i=0 ; i < canals.size() ; ++i)
		delete canals[i];
	for(int i=0 ; i < outputs.size() ; ++i)
		delete outputs[i];

	canals.clear();
	outputs.clear();

	QDomElement root = doc.documentElement();
	QDomNode node = root.firstChild();

	while(!node.isNull())
	{
		QDomElement element = node.toElement();
		if (element.tagName() == "Function")
		{
			addCanal(1, "Red");
			QtfeCanal * canal = canals.back();
			QDomNodeList points = element.childNodes();
			canal->setFirstPoint(points.item(0).toElement().attributeNode("y").value().toDouble());
			canal->setLastPoint(points.item(points.length()-1).toElement().attributeNode("y").value().toDouble());

			for(int i=1;i<points.length()-1;i++)
			{
				QDomNode point = points.item(i);

				qreal x = point.toElement().attributeNode("x").value().toDouble();
				qreal y = point.toElement().attributeNode("y").value().toDouble();
		
				canal->insertPoint(QPointF(x,y));
			}
		}
		if (element.tagName() == "Output")
		{
			QtfeOutput * output = new QtfeOutput(this);
			output->bindCanaltoR(element.attributeNode("R").value().toInt());	
			output->bindCanaltoG(element.attributeNode("G").value().toInt());
			output->bindCanaltoB(element.attributeNode("B").value().toInt());
			output->bindCanaltoA(element.attributeNode("A").value().toInt());
			outputs.push_back(output);
			this->layout()->addWidget(output);
		}

		node = node.nextSibling();
	}

	// unblock functionChanged() signal and emit
	blockSignals(false);
	emit functionChanged();
}
Ejemplo n.º 21
0
void MyMoneyAccountTest::testReadXML()
{
  MyMoneyAccount a;
  QString ref_ok = QString(
                     "<!DOCTYPE TEST>\n"
                     "<ACCOUNT-CONTAINER>\n"
                     " <ACCOUNT parentaccount=\"Parent\" lastmodified=\"%1\" lastreconciled=\"\" institution=\"B000001\" number=\"465500\" opened=\"%2\" type=\"9\" id=\"A000001\" name=\"AccountName\" description=\"Desc\" >\n"
                     "  <SUBACCOUNTS>\n"
                     "   <SUBACCOUNT id=\"A000002\" />\n"
                     "   <SUBACCOUNT id=\"A000003\" />\n"
                     "  </SUBACCOUNTS>\n"
                     "  <KEYVALUEPAIRS>\n"
                     "   <PAIR key=\"key\" value=\"value\" />\n"
                     "   <PAIR key=\"Key\" value=\"Value\" />\n"
                     "   <PAIR key=\"reconciliationHistory\" value=\"2011-01-01:123/100;2011-02-01:114/25\"/>\n"
                     "  </KEYVALUEPAIRS>\n"
                     " </ACCOUNT>\n"
                     "</ACCOUNT-CONTAINER>\n").
                   arg(QDate::currentDate().toString(Qt::ISODate)).arg(QDate::currentDate().toString(Qt::ISODate));

  QString ref_false = QString(
                        "<!DOCTYPE TEST>\n"
                        "<ACCOUNT-CONTAINER>\n"
                        " <KACCOUNT parentaccount=\"Parent\" lastmodified=\"%1\" lastreconciled=\"\" institution=\"B000001\" number=\"465500\" opened=\"%2\" type=\"9\" id=\"A000001\" name=\"AccountName\" description=\"Desc\" >\n"
                        "  <SUBACCOUNTS>\n"
                        "   <SUBACCOUNT id=\"A000002\" />\n"
                        "   <SUBACCOUNT id=\"A000003\" />\n"
                        "  </SUBACCOUNTS>\n"
                        "  <KEYVALUEPAIRS>\n"
                        "   <PAIR key=\"key\" value=\"value\" />\n"
                        "   <PAIR key=\"Key\" value=\"Value\" />\n"
                        "  </KEYVALUEPAIRS>\n"
                        " </KACCOUNT>\n"
                        "</ACCOUNT-CONTAINER>\n").
                      arg(QDate::currentDate().toString(Qt::ISODate)).arg(QDate::currentDate().toString(Qt::ISODate));

  QDomDocument doc;
  QDomElement node;
  doc.setContent(ref_false);
  node = doc.documentElement().firstChild().toElement();

  try {
    a = MyMoneyAccount(node);
    QFAIL("Missing expected exception");
  } catch (const MyMoneyException &) {
  }

  doc.setContent(ref_ok);
  node = doc.documentElement().firstChild().toElement();

  a.addAccountId("TEST");
  a.setValue("KEY", "VALUE");

  try {
    a = MyMoneyAccount(node);
    QVERIFY(a.id() == "A000001");
    QVERIFY(a.m_name == "AccountName");
    QVERIFY(a.m_parentAccount == "Parent");
    QVERIFY(a.m_lastModified == QDate::currentDate());
    QVERIFY(a.m_lastReconciliationDate == QDate());
    QVERIFY(a.m_institution == "B000001");
    QVERIFY(a.m_number == "465500");
    QVERIFY(a.m_openingDate == QDate::currentDate());
    QVERIFY(a.m_accountType == MyMoneyAccount::Asset);
    QVERIFY(a.m_description == "Desc");
    QVERIFY(a.accountList().count() == 2);
    QVERIFY(a.accountList()[0] == "A000002");
    QVERIFY(a.accountList()[1] == "A000003");
    QVERIFY(a.pairs().count() == 4);
    QVERIFY(a.value("key") == "value");
    QVERIFY(a.value("Key") == "Value");
    QVERIFY(a.value("lastStatementDate").isEmpty());
    QVERIFY(a.reconciliationHistory().count() == 2);
    QVERIFY(a.reconciliationHistory()[QDate(2011, 1, 1)] == MyMoneyMoney(123, 100));
    QVERIFY(a.reconciliationHistory()[QDate(2011, 2, 1)] == MyMoneyMoney(456, 100));
  } catch (const MyMoneyException &) {
    QFAIL("Unexpected exception");
  }
}
Ejemplo n.º 22
0
/*!
   This function re-reads the Packages.xml file and updates itself. Changes to \ref targetName
   and \ref targetVersion are lost after this function returns. The function emits a reset()
   signal after completion.
*/
void PackagesInfo::refresh()
{
    // First clear internal variables
    d->targetName.clear();
    d->targetVersion.clear();
    d->packageInfoList.clear();
    d->modified = false;

    QFile file( d->fileName );

    // if the file does not exist then we just skip the reading
    if( !file.exists() )
    {
        d->error = NoError;
        d->errorMessage.clear();
        emit reset();
        return;
    }

    // Open Packages.xml
    if( !file.open(QFile::ReadOnly) )
    {
        d->error = CouldNotReadPackageFileError;
        d->errorMessage = tr("Could not read \"%1\"").arg(d->fileName);
        emit reset();
        return;
    }

    // Parse the XML document
    QDomDocument doc;
    QString parseErrorMessage;
    int parseErrorLine;
    int parseErrorColumn;
    if( !doc.setContent( &file, &parseErrorMessage, &parseErrorLine, &parseErrorColumn ) )
    {
        d->error = InvalidXmlError;
        d->errorMessage = tr("Parse error in %1 at %2, %3: %4")
                          .arg(d->fileName,
                               QString::number(parseErrorLine),
                               QString::number(parseErrorColumn),
                               parseErrorMessage);
        emit reset();
        return;
    }
    file.close();

    // Now populate information from the XML file.
    const QDomElement rootE = doc.documentElement();
    if( rootE.tagName() != QLatin1String( "Packages" ) )
    {
        d->setInvalidContentError(tr("root element %1 unexpected, should be \"Packages\"").arg(rootE.tagName()));
        emit reset();
        return;
    }

    for( QDomNode childNode = rootE.firstChild(); !childNode.isNull(); childNode = childNode.nextSiblingElement() )
    {
        const QDomElement childNodeE = childNode.toElement();
        if( childNodeE.isNull() )
            continue;

        if ( childNodeE.tagName() == QLatin1String( "TargetName" ) ||
                childNodeE.tagName() == QLatin1String( "ApplicationName" ) ) // backwards compat
            d->targetName = childNodeE.text();
        else if ( childNodeE.tagName() == QLatin1String( "TargetVersion" ) ||
                  childNodeE.tagName() == QLatin1String( "ApplicationVersion" ) )
            d->targetVersion = childNodeE.text();
        else if( childNodeE.tagName() == QLatin1String( "Package" ) )
            d->addPackageFrom( childNodeE );
        else if( childNodeE.tagName() == QLatin1String( "CompatLevel" ) )
            d->compatLevel = childNodeE.text().toInt();
    }

    d->error = NoError;
    d->errorMessage.clear();
    emit reset();
}
Ejemplo n.º 23
0
bool ThemeInfo::parseThemeInfo()
{

    QDomDocument doc;

    if ((m_themeurl.startsWith("http://")) ||
        (m_themeurl.startsWith("https://")) ||
        (m_themeurl.startsWith("ftp://")))
    {
        QByteArray data;
        bool ok = GetMythDownloadManager()->download(m_themeurl +
                                                     "/themeinfo.xml", &data);
        if (!ok)
            return false;

        if (!doc.setContent(data))
        {
            VERBOSE(VB_IMPORTANT, LOC_ERR +
                    QString("Unable to parse themeinfo.xml "
                            "for %1").arg(m_themeurl));
            return false;
        }
    }
    else
    {
        QFile f(m_themeurl + "/themeinfo.xml");

        if (!f.open(QIODevice::ReadOnly))
        {
            VERBOSE(VB_IMPORTANT, LOC_WARN +
                    QString("Unable to open themeinfo.xml "
                            "for %1").arg(f.fileName()));
            return false;
        }

        if (!doc.setContent(&f))
        {
            VERBOSE(VB_IMPORTANT, LOC_ERR +
                    QString("Unable to parse themeinfo.xml "
                            "for %1").arg(f.fileName()));

            f.close();
            return false;
        }
        f.close();
    }

    QDomElement docElem = doc.documentElement();

    for (QDomNode n = docElem.firstChild(); !n.isNull();
            n = n.nextSibling())
    {
        QDomElement e = n.toElement();
        if (!e.isNull())
        {
            if (e.tagName() == "name")
            {
                m_name = getFirstText(e);
            }
            else if (e.tagName() == "aspect")
            {
                m_aspect = getFirstText(e);
            }
            else if (e.tagName() == "baseres")
            {
                    QString size = getFirstText(e);
                    m_baseres = QSize(size.section('x', 0, 0).toInt(),
                                            size.section('x', 1, 1).toInt());
            }
            else if (e.tagName() == "types")
            {
                for (QDomNode child = e.firstChild(); !child.isNull();
                        child = child.nextSibling())
                {
                    QDomElement ce = child.toElement();
                    if (!ce.isNull())
                    {
                        if (ce.tagName() == "type")
                        {
                            QString type = getFirstText(ce);

                            if (type == "UI")
                            {
                                m_type |= THEME_UI;
                            }
                            else if (type == "OSD")
                            {
                                m_type |= THEME_OSD;
                            }
                            else if (type == "Menu")
                            {
                                m_type |= THEME_MENU;
                            }
                            else
                            {
                                VERBOSE_XML(VB_IMPORTANT,
                                            m_theme.fileName(),
                                            ce, LOC_ERR + "Invalid theme type");
                            }
                        }
                    }
                }
            }
            else if (e.tagName() == "version")
            {
                for (QDomNode child = e.firstChild(); !child.isNull();
                        child = child.nextSibling())
                {
                    QDomElement ce = child.toElement();
                    if (!ce.isNull())
                    {
                        if (ce.tagName() == "major")
                        {
                            m_majorver = getFirstText(ce).toInt();
                        }
                        else if (ce.tagName() == "minor")
                        {
                            m_minorver = getFirstText(ce).toInt();
                        }
                    }
                }
            }
            else if (e.tagName() == "author")
            {
                for (QDomNode child = e.firstChild(); !child.isNull();
                        child = child.nextSibling())
                {
                    QDomElement ce = child.toElement();
                    if (!ce.isNull())
                    {
                        if (ce.tagName() == "name")
                        {
                            m_authorName = getFirstText(ce);
                        }
                        else if (ce.tagName() == "email")
                        {
                            m_authorEmail = getFirstText(ce);
                        }
                    }
                }
            }
            else if (e.tagName() == "detail")
            {
                for (QDomNode child = e.firstChild(); !child.isNull();
                        child = child.nextSibling())
                {
                    QDomElement ce = child.toElement();
                    if (!ce.isNull())
                    {
                        if (ce.tagName() == "thumbnail")
                        {
                            if (ce.attribute("name") == "preview")
                            {
                                QString thumbnail = getFirstText(ce);
                                m_previewpath = m_themeurl + '/' + thumbnail;
                            }
                        }
                        else if (ce.tagName() == "description")
                        {
                            m_description = qApp->translate("ThemeUI",
                                                 parseText(ce).toUtf8(), NULL,
                                                 QCoreApplication::UnicodeUTF8);
                        }
                        else if (ce.tagName() == "errata")
                        {
                            m_errata = qApp->translate("ThemeUI",
                                                parseText(ce).toUtf8(), NULL,
                                                QCoreApplication::UnicodeUTF8);
                        }
                        else if (ce.tagName() == "downloadurl")
                        {
                            m_downloadurl = getFirstText(ce);
                        }
                        else if (ce.tagName() == "themesite")
                        {
                            m_themesite = getFirstText(ce);
                        }
                    }
                }
            }
        }
    }

    return true;
}
Ejemplo n.º 24
0
bool filePick()
{
    //Read XSD
    file.setFileName("FACTORY.XSD");
    if (!readFile(file.fileName())) return false;

    QXmlSchema schema;
    schema.load(&file);
    if (!schema.isValid())
    {
        QMessageBox::information(NULL, QWidget::tr("XSDRead")
                                 ,QWidget::tr("This is not a valid XSD File!"));
        return false;
    }

    file.close();

    file.setFileName("FACTORY.XML");
    if (!readFile(file.fileName())) return false;

    //DOM Read-In
    QString errorStr;
    int errorLine, errorColumn;
    if (!doc.setContent(&file, true, &errorStr, &errorLine,
                                &errorColumn)) {
        QMessageBox::information(NULL, QWidget::tr("XSDRead"),
                                 QWidget::tr("Parse error at line %1, column %2:\n%3")
                                 .arg(errorLine)
                                 .arg(errorColumn)
                                 .arg(errorStr));
        return false;
    }

    //Reset the file pointer
    file.reset();

    //XSD Validator
    QXmlSchemaValidator validator(schema);
    if (!validator.validate(&file))
    {
        QMessageBox::information(NULL,QWidget::tr("XSDRead"),
                                 QWidget::tr("This is not a valid XML File!"));
        return false;
    }

    //building Treeroot
    QDomElement node = doc.documentElement();
    nodeData* temp = NULL;
    Treeroot = new nodeData;
    Treeroot->name = node.tagName();
    QDomElement child = node.firstChildElement();

    //parsing child elements (if there is)
    while (!child.isNull())
    {
        temp = new nodeData;
        Treeroot->child.append(temp);
        parseElement(temp,child);
        temp->parent = Treeroot;
        child = child.nextSiblingElement();
    }

    return true;
}
Ejemplo n.º 25
0
void TestKHTML::setupActions()
{
    QDomDocument document = m_part->domDocument();
    QDomElement fileMenu = document.documentElement().firstChild().childNodes().item( 0 ).toElement();

    QDomElement quitElement = document.createElement("action");
    quitElement.setAttribute("name",
                             KStandardAction::name(KStandardAction::Quit));
    fileMenu.appendChild(quitElement);

    QDomElement viewMenu = document.documentElement().firstChild().childNodes().item( 2 ).toElement();

    QDomElement element = document.createElement("action");
    element.setAttribute("name", "debugRenderTree");
    viewMenu.appendChild(element);

    element = document.createElement("action");
    element.setAttribute("name", "debugDOMTree");
    viewMenu.appendChild(element);

    QDomElement toolBar = document.documentElement().firstChild().nextSibling().toElement();
    element = document.createElement("action");
    element.setAttribute("name", "editable");
    toolBar.insertBefore(element, toolBar.firstChild());

    element = document.createElement("action");
    element.setAttribute("name", "navigable");
    toolBar.insertBefore(element, toolBar.firstChild());

    element = document.createElement("action");
    element.setAttribute("name", "reload");
    toolBar.insertBefore(element, toolBar.firstChild());

    element = document.createElement("action");
    element.setAttribute("name", "print");
    toolBar.insertBefore(element, toolBar.firstChild());

    KAction *action = new KAction(KIcon("view-refresh"), "Reload", this );
    m_part->actionCollection()->addAction( "reload", action );
    connect(action, SIGNAL(triggered(bool)), this, SLOT(reload()));
    action->setShortcut(Qt::Key_F5);

    KAction *kprint = new KAction(KIcon("document-print"), "Print", this );
    m_part->actionCollection()->addAction( "print", kprint );
    connect(kprint, SIGNAL(triggered(bool)), m_part->browserExtension(), SLOT(print()));
    kprint->setEnabled(true);

    KToggleAction *ta = new KToggleAction( KIcon("edit-rename"), "Navigable", this );
    actionCollection()->addAction( "navigable", ta );
    ta->setShortcuts( KShortcut() );
    ta->setChecked(m_part->isCaretMode());
    connect(ta, SIGNAL(toggled(bool)), this, SLOT(toggleNavigable(bool)));

    ta = new KToggleAction( KIcon("document-properties"), "Editable", this );
    actionCollection()->addAction( "editable", ta );
    ta->setShortcuts( KShortcut() );
    ta->setChecked(m_part->isEditable());
    connect(ta, SIGNAL(toggled(bool)), this, SLOT(toggleEditable(bool)));

    KStandardAction::quit( kapp, SLOT(quit()), m_part->actionCollection() );

    guiFactory()->addClient(m_part);
}
Ejemplo n.º 26
0
bool QgsLayoutManager::readXml( const QDomElement &element, const QDomDocument &doc )
{
  clear();

  QDomElement layoutsElem = element;
  if ( element.tagName() != QStringLiteral( "Layouts" ) )
  {
    layoutsElem = element.firstChildElement( QStringLiteral( "Layouts" ) );
  }
  if ( layoutsElem.isNull() )
  {
    // handle legacy projects
    layoutsElem = doc.documentElement();
  }

  //restore each composer
  bool result = true;
  QDomNodeList composerNodes = element.elementsByTagName( QStringLiteral( "Composer" ) );
  for ( int i = 0; i < composerNodes.size(); ++i )
  {
    // This legacy title is the Composer "title" (that can be overridden by the Composition "name")
    QString legacyTitle = composerNodes.at( i ).toElement().attribute( QStringLiteral( "title" ) );
    // Convert compositions to layouts
    QDomNodeList compositionNodes = composerNodes.at( i ).toElement().elementsByTagName( QStringLiteral( "Composition" ) );
    for ( int j = 0; j < compositionNodes.size(); ++j )
    {
      std::unique_ptr< QgsPrintLayout > l( QgsCompositionConverter::createLayoutFromCompositionXml( compositionNodes.at( j ).toElement(), mProject ) );
      if ( l )
      {
        if ( l->name().isEmpty() )
          l->setName( legacyTitle );

        // some 2.x projects could end in a state where they had duplicated layout names. This is strictly forbidden in 3.x
        // so check for duplicate name in layouts already added
        int id = 2;
        bool isDuplicateName = false;
        QString originalName = l->name();
        do
        {
          isDuplicateName = false;
          for ( QgsMasterLayoutInterface *layout : qgis::as_const( mLayouts ) )
          {
            if ( l->name() == layout->name() )
            {
              isDuplicateName = true;
              break;
            }
          }
          if ( isDuplicateName )
          {
            l->setName( QStringLiteral( "%1 %2" ).arg( originalName ).arg( id ) );
            id++;
          }
        }
        while ( isDuplicateName );

        bool added = addLayout( l.release() );
        result = added && result;
      }
    }
  }

  QgsReadWriteContext context;
  context.setPathResolver( mProject->pathResolver() );

  // restore layouts
  const QDomNodeList layoutNodes = layoutsElem.childNodes();
  for ( int i = 0; i < layoutNodes.size(); ++i )
  {
    if ( layoutNodes.at( i ).nodeName() != QStringLiteral( "Layout" ) )
      continue;

    std::unique_ptr< QgsPrintLayout > l = qgis::make_unique< QgsPrintLayout >( mProject );
    l->undoStack()->blockCommands( true );
    if ( !l->readLayoutXml( layoutNodes.at( i ).toElement(), doc, context ) )
    {
      result = false;
      continue;
    }
    l->undoStack()->blockCommands( false );
    if ( addLayout( l.get() ) )
    {
      ( void )l.release(); // ownership was transferred successfully
    }
    else
    {
      result = false;
    }
  }
  //reports
  const QDomNodeList reportNodes = element.elementsByTagName( QStringLiteral( "Report" ) );
  for ( int i = 0; i < reportNodes.size(); ++i )
  {
    std::unique_ptr< QgsReport > r = qgis::make_unique< QgsReport >( mProject );
    if ( !r->readLayoutXml( reportNodes.at( i ).toElement(), doc, context ) )
    {
      result = false;
      continue;
    }
    if ( addLayout( r.get() ) )
    {
      ( void )r.release(); // ownership was transferred successfully
    }
    else
    {
      result = false;
    }
  }
  return result;
}
Ejemplo n.º 27
0
OldSoundThemeProvider::OldSoundThemeProvider(const QString &name, const QString &path, QString variant)
{
	m_themeName = name;
	const Notification::Type xmlEventTypes[] = {
		Notification::IncomingMessage,
		Notification::OutgoingMessage,
		Notification::AppStartup,
		Notification::BlockedMessage,
		Notification::ChatUserJoined,
		Notification::ChatUserLeft,
		Notification::ChatIncomingMessage,
		Notification::ChatOutgoingMessage,
		Notification::FileTransferCompleted,
		Notification::UserOnline,
		Notification::UserOffline,
		Notification::UserChangedStatus,
		Notification::UserHasBirthday,
		Notification::UserTyping,
		Notification::System,
	    // And again some of them for legacy names
		Notification::UserOnline,
		Notification::UserOffline,
		Notification::UserChangedStatus,
		Notification::UserHasBirthday,
		Notification::AppStartup,
		Notification::IncomingMessage,
		Notification::ChatIncomingMessage,
		Notification::OutgoingMessage,
		Notification::ChatOutgoingMessage,
		Notification::System,
		Notification::UserTyping,
		Notification::BlockedMessage
	};
	const char* const xmlEventNames[] = {
		"IncomingMessage",
		"OutgoingMessage",
		"AppStartup",
		"BlockedMessage",
		"ChatUserJoined",
		"ChatUserLeft",
		"ChatIncomingMessage",
		"ChatOutgoingMessage",
		"FileTransferCompleted",
		"UserOnline",
		"UserOffline",
		"UserChangedStatus",
		"UserHasBirthday",
		"UserTyping",
		"System",
		"c_online",
		"c_offline",
		"c_changed_status",
		"c_birth",
		"start",
		"m_get",
		"m_chat_get",
		"m_send",
		"m_chat_send",
		"sys_event",
		"c_typing",
		"c_blocked_message"
	};
	const int eventsCount = sizeof(xmlEventTypes) / sizeof(xmlEventTypes[0]);

	Q_ASSERT(sizeof(xmlEventTypes) / sizeof(xmlEventTypes[0]) == sizeof(xmlEventNames) / sizeof(xmlEventNames[0]));

	QDir dir(path);
	if (variant.isEmpty())
		variant = dir.entryList(QStringList("*.xml"), QDir::Files).value(0);
	else
		variant += ".xml";
	QFile file(dir.filePath(variant));
	if (file.open(QIODevice::ReadOnly)) {
		QDomDocument doc;
		doc.setContent(&file);
		if (doc.doctype().name() != QLatin1String("qutimsounds"))
			return;
		QDomElement rootElement = doc.documentElement();
		QDomNodeList soundsNodeList = rootElement.elementsByTagName("sounds");
		if (soundsNodeList.count() != 1)
			return;
		QDomElement soundsElement = soundsNodeList.at(0).toElement();
		soundsNodeList = soundsElement.elementsByTagName("sound");
		QDomElement soundElement;
		QString eventName, soundFileName;

		for (int i = 0; i < soundsNodeList.count(); i++) {
			soundElement = soundsNodeList.at(i).toElement();
			eventName = soundElement.attribute("event");
			if (eventName.isEmpty() || !soundElement.elementsByTagName("file").count())
				continue;
			soundFileName = dir.filePath(soundElement.elementsByTagName("file").at(0).toElement().text());
			if (!QFile::exists(soundFileName)) 
				continue;
			for (int i = 0; i < eventsCount; i++) {
				if (eventName == QLatin1String(xmlEventNames[i])) {
					m_map.insert(xmlEventTypes[i], soundFileName);
					break;
				}
			}
		}
		m_filePath = file.fileName();
	}
}
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    BacnetNetworkLayerHandler *netHandler = new BacnetNetworkLayerHandler();
    BacnetApplicationLayerHandler *appHandler = new BacnetApplicationLayerHandler(netHandler);
    InternalObjectsHandler *intHandler = appHandler->internalHandler();
    ExternalObjectsHandler *extHandler = appHandler->externalHandler();

    ///////Not bacnet thing
    QVariant test;
    test.setValue((double)72.3);
    AsynchOwner *proto2 = new AsynchOwner();
    PropertySubject *subject = DataModel::instance()->createPropertySubject(1, QVariant::Double);
    subject->setValue(test);
    proto2->addProperty(subject);

    PropertySubject *subject2 = DataModel::instance()->createPropertySubject(2, QVariant::Double);
    subject2->setValue(test);
    proto2->addProperty(subject2);

    PropertySubject *subject3 = DataModel::instance()->createPropertySubject(3, QVariant::Double);
    subject3->setValue(test);

    //////END of Not bacnet thing

    QFile f("bacnet-test-config.xml");
    if (!f.open(QIODevice::ReadOnly)) {
        qDebug("Can't open test file!");
        return 1;
    }
    QDomDocument doc;
    doc.setContent(&f);

    QDomElement docEl = doc.documentElement();
    QDomElement appLayerEl = docEl.firstChildElement(BacnetApplicationLayerTag);

    QDomElement el = docEl.firstChildElement(InternalHandlerTagName);
    BacnetConfigurator::instance()->configureInternalHandler(el, DataModel::instance(), intHandler);

    el = appLayerEl.firstChildElement(ExternalHandlerTagName);
    BacnetConfigurator::instance()->configureExternalHandler(el, DataModel::instance(), appHandler);

    el = appLayerEl.firstChildElement(DeviceMappingsTagName);
    BacnetConfigurator::instance()->configureDeviceMappings(el, appHandler);

    BacnetConfigurator::releaseInstance();

    InternalAddress extObjHandlerAddress = 32;
    extHandler->addRegisteredAddress(extObjHandlerAddress);

    BacnetAddress srcAddr;
    QHostAddress sa("192.168.1.70");
    BacnetBipAddressHelper::setMacAddress(sa, 12, &srcAddr);

    InternalAddress intAddr = 123;
    appHandler->externalHandler()->addRegisteredAddress(intAddr);

    quint32 destAddrInt(0x00000001);
    BacnetAddress destAddr = BacnetInternalAddressHelper::toBacnetAddress(destAddrInt);

    //    BacnetDeviceObject *device = new BacnetDeviceObject(1, destAddr);
    //    HelperCoder::printArray(destAddr.macPtr(), destAddr.macAddrLength(), "Device 1 address");
    //    device->setObjectName("BacnetTestDevice");
    //    PropertyObserver *obs = DataModel::instance()->createPropertyObserver(1);
    //    ProxyInternalProperty propProxy(obs, AppTags::Real, QVariant::Double, device);
    //    device->addProperty(BacnetPropertyNS::PresentValue, &propProxy);
    //    intHandler->addDevice(device->address(), device);


    //    PropertyObserver *obs2 = DataModel::instance()->createPropertyObserver(2);
    //    BacnetObject *aio = new BacnetObject(BacnetObjectTypeNS::AnalogInput, 5, device);
    //    AnalogInputObject *aio = new AnalogInputObject(5, device);
    //    aio->setObjectName("OATemp");
    //    ProxyInternalProperty propProxy2(obs2, AppTags::Real, QVariant::Double, aio);
    //    aio->addProperty(BacnetPropertyNS::PresentValue, &propProxy2);

    quint32 addr(0x00000003);
    BacnetAddress bAddr;
    BacnetInternalAddressHelper::macAddressFromRaw((quint8*)&addr, &bAddr);
    //    BacnetDeviceObject *device1 = new BacnetDeviceObject(8, bAddr);
    //    intHandler->addDevice(device1->address(), device1);
    //    device1->setObjectName("BestDeviceEver");

    //    BacnetObject *aio1 = new BacnetObject(BacnetObjectTypeNS::AnalogInput, 3, device1);
    ////    AnalogInputObject *aio1 = new AnalogInputObject(3, device1);
    //    aio1->setObjectName("OATemp");

    //    PropertySubject *extSubject = DataModel::instance()->createProperty(3, QVariant::Double);
    //    extHandler->addMappedProperty(extSubject, BacnetObjectType::AnalogValue << 22 | 0x01,
    //                                  BacnetProperty::PresentValue, ArrayIndexNotPresent,
    //                                  0x00000001,
    //                                  BacnetExternalObjects::Access_ReadRequest);

    //    PropertyObserver *extObserver = DataModel::instance()->createPropertyObserver(3);
    //    proto2->addProperty(extObserver);

    //    //READ PROPERTY ENCODED
    //        quint8 readPropertyService[] = {
    //            0x00,
    //            0x00,
    //            0x01,
    //            0x0C,
    //            0x0C,
    //            0x00, 0x00, 0x00, 0x05,
    //            0x19,
    //            0x55
    //        };

    //        HelperCoder::printArray(destAddr.macPtr(), destAddr.macAddrLength(), "Addressed device:");
    //        appHandler->indication(readPropertyService, sizeof(readPropertyService), srcAddr, destAddr);

//    //WRITE PROEPRTY ENCODED
//    quint8 wpService[] = {
//        0x00,
//        0x04,
//        0x59,
//        0x0F,

//        0x0c,
//        0x00, 0x00/*0x80*/, 0x00, /*0x01*/0x05, //analog input instance number 5
//        0x19,
//        0x55,
//        0x3e,
//        0x44,
//        0x43, 0x34, 0x00, 0x00,
//        0x3f
//    };
//    appHandler->indication(wpService, sizeof(wpService), srcAddr, destAddr);

//            //WHO IS//device instance 03
//            quint8 wiService[] = {
//                0x10,
//                0x08,
//                0x09, 0x01,//find device
//                0x19, 0x0a
//            };
//            appHandler->indication(wiService, sizeof(wiService), srcAddr, destAddr);

    //    //WHO IS//device instance 03
    //    quint8 wiService[] = {
    //        0x10,
    //        0x08,
    //        0x09, 0x01,//find device
    //        0x19, 0x01
    //    };
    //    appHandler->indication(wiService, sizeof(wiService), srcAddr, destAddr);

//    //WHO HAS - object name is known
//    quint8 whoHasService[] = {
//        0x10,
//        0x07,
//        0x3d,
//        0x07,
//        0x00,
//        0x4F, 0x41, 0x54, 0x65, 0x6D, 0x70
//    };
//    appHandler->indication(whoHasService, sizeof(whoHasService), srcAddr, destAddr);

    BacnetAddress broadAddr;
    broadAddr.setGlobalBroadcast();
    ////        bHndlr->getBytes(whoHasService, sizeof(whoHasService), srcAddr, broadAddr);

//            //WHO HAS - object id is known
//            quint8 whoHasService2[] = {
//                0x10,
//                0x07,
//                0x2c,
//                0x00, 0x00, 0x00, 0x05
//            };
//            appHandler->indication(whoHasService2, sizeof(whoHasService2), srcAddr, broadAddr);

    //    //I-HAVE
    //    quint8 iHaveData[] = {
    //        0x10,
    //        0x01,
    //        0xc4,
    //        0x02, 0x00, 0x00, 0x08,
    //        0xc4,
    //        0x00, 0x00, 0x00, 0x03,
    //        0x75,
    //        0x07,
    //        0x00,
    //        0x4f, 0x41, 0x54, 0x65, 0x6d, 0x70
    //    };
    //    const quint16 iHaveDataSize = sizeof(iHaveData);
    //    BacnetAddress broadAddr;
    //    broadAddr.setGlobalBroadcast();

    //    appHandler->indication(iHaveData, iHaveDataSize, srcAddr, broadAddr);

    //    //I-AM
    //    quint8 iAmData[] = {
    //        0x10,
    //        0x00,
    //        0xc4,
    //        0x02, 0x00, 0x00, 0x01,
    //        0x22,
    //        0x01, 0xe0,
    //        0x91,
    //        0x01,
    //        0x21,
    //        0x63
    //    };
    //    const quint16 iAmDataSize = sizeof(iAmData);
    //    BacnetAddress broadAddr;
    //    broadAddr.setGlobalBroadcast();

    //    appHandler->indication(iAmData, iAmDataSize, srcAddr, broadAddr);

    ///////////////////////////////////////////////////////////////////
    /////////////////ExternalObjectsHndlr tests////////////////////////
    ///////////////////////////////////////////////////////////////////

//    ObjectIdentifier covDeviceIdentifier(BacnetObjectTypeNS::Device, 2);

//#define EXT_COV_TEST
#ifdef EXT_COV_TEST
    //To run COV test with externalObjHandler uncomment //#define EXT_COV_TEST in TSM and Externalobjects handler, and set config below

//    QHostAddress cobAddr("192.168.2.109");
//    quint16 port(0xbac0);
//    BacnetAddress covDeviceAddress;
//    BacnetBipAddressHelper::setMacAddress(cobAddr, port, &covDeviceAddress);
//
//    BacnetAddress extHandlerAddress = extHandler->oneOfAddresses();
//    CovAnswerer *covAns = new CovAnswerer(15, covDeviceAddress, extHandlerAddress, appHandler);
//    QTimer timer;
//    QObject::connect(&timer, SIGNAL(timeout()), covAns, SLOT(answer()));
//    timer.start(987);
//
//    <appLayer>
//            <internalHandler dummy="first">
//            </internalHandler>
//            <externalHandler int-address="14" >
//                    <devices>
//                            <device dev-instance-number="64" >
//                                    <childObjects>
//                                            <object instance-number="10" obj-type="analog-input">
//                                                    <properties>
//                                                                    <property id="85" prop-type="internal" read-strategy="cov-poll" read-interval="10000" write-strategy="simple" int-var-type="float" int-id="5"/>
//                                                    </properties>
//                                            </object>
//                                    </childObjects>
//                            </device>
//                    </devices>
//            </externalHandler>
//            <deviceMappings>
//                    <device dev-instance-number="64" bac-address="c0:a8:2:6d:ba:c0" bac-network="2" bac-max-apdu="128" bac-segmentation="segmented-not" bac-vendor-id="99" />
//            </deviceMappings>
//    </appLayer>


#endif
#undef EXT_COV_TEST

//#define EXT_RP_TEST
#ifdef EXT_RP_TEST
    //to make it work, define EXT_RP_TEST in BacnetTsm2.cpp

    QHostAddress cobAddr("192.168.2.109");
    quint16 port(0xbac0);
    BacnetAddress rpDeviceAddress;
    BacnetBipAddressHelper::setMacAddress(cobAddr, port, &rpDeviceAddress);

    BacnetAddress extHandlerAddress = extHandler->oneOfAddresses();
    RpAnswerer *rpAns = new RpAnswerer(1, rpDeviceAddress, extHandlerAddress, appHandler);
    QTimer timer;
    timer.setSingleShot(true);
    QObject::connect(&timer, SIGNAL(timeout()), rpAns, SLOT(answer()));
    timer.start(987);

//    <appLayer>
//            <internalHandler dummy="first">
//            </internalHandler>
//            <externalHandler int-address="14" >
//                    <devices>
//                            <device dev-instance-number="64" >
//                                    <childObjects>
//                                            <object instance-number="5" obj-type="analog-input">
//                                                    <properties>
//                                                                    <property id="85" prop-type="internal" read-strategy="simple-time" read-interval="10000" write-strategy="simple" int-var-type="float" int-id="5"/>
//                                                    </properties>
//                                            </object>
//                                    </childObjects>
//                            </device>
//                    </devices>
//            </externalHandler>
//            <deviceMappings>
//                    <device dev-instance-number="64" bac-address="c0:a8:2:6d:ba:c0" bac-network="2" bac-max-apdu="128" bac-segmentation="segmented-not" bac-vendor-id="99" />
//            </deviceMappings>
//    </appLayer>

#endif
#undef EXT_RP_TEST

//#define EXT_WP_TEST
#ifdef EXT_WP_TEST
    //to make it work, define EXT_RP_TEST in BacnetTsm2.cpp
    Property *wpObserver = DataModel::instance()->createPropertyObserver(5);
    Q_CHECK_PTR(wpObserver);

    //    SimpleWithTimeReadStrategy *creadStrategy = new SimpleWithTimeReadStrategy(60000);

    BacnetAddress extHandlerAddress = extHandler->oneOfAddresses();
    QVariant value = (float)180.0;
    WpRequester *wpReq = new WpRequester(wpObserver, value);

    QHostAddress cobAddr("192.168.2.109");
    quint16 port(0xbac0);
    BacnetAddress wpDeviceAddress;
    BacnetBipAddressHelper::setMacAddress(cobAddr, port, &wpDeviceAddress);


    QTimer timer;
    timer.setSingleShot(true);
    QObject::connect(&timer, SIGNAL(timeout()), wpReq, SLOT(writeValue()));
    timer.start(987);

    QTimer timer2;
    timer2.setSingleShot(true);
    WpAcknowledger *wpAcknowledger = new WpAcknowledger(0x01, wpDeviceAddress, extHandlerAddress, appHandler);
    QObject::connect(&timer2, SIGNAL(timeout()), wpAcknowledger, SLOT(answer()));
    timer2.start(1500);

//    <appLayer>
//            <internalHandler dummy="first">
//            </internalHandler>
//            <externalHandler int-address="14" >
//                    <devices>
//                            <device dev-instance-number="64" >
//                                    <childObjects>
//                                            <object instance-number="1" obj-type="analog-input">
//                                                    <properties>
//                                                                    <property id="85" prop-type="internal" read-strategy="simple-time" read-interval="10000" write-strategy="simple" int-var-type="float" int-id="5"/>
//                                                    </properties>
//                                            </object>
//                                    </childObjects>
//                            </device>
//                    </devices>
//            </externalHandler>
//            <deviceMappings>
//                    <device dev-instance-number="64" bac-address="c0:a8:2:6d:ba:c0" bac-network="2" bac-max-apdu="128" bac-segmentation="segmented-not" bac-vendor-id="99" />
//            </deviceMappings>
//    </appLayer>
#endif

    return a.exec();
}
Ejemplo n.º 29
0
void DB::load()
{
    QFile* file = new QFile("../database.xml");
        if(file->exists()){
            if(!file->open(QFile::ReadOnly | QFile::Text)){
                QMessageBox err;
                err.setText("Errore nell'apertura del file");
                err.exec();
            }
            else{
                /*
                  The QDomDocument class represents an XML document.
                  The QDomDocument class represents the entire XML document.
                  Conceptually, it is the root of the document tree, and provides the
                  primary access to the document's data.
                */
                QDomDocument doc;
                /*
                  This is an overloaded function.
                  This function reads the XML document from the IO device dev,
                  returning true if the content was successfully parsed; otherwise returns false.
                */
                if(!doc.setContent(file)){
                    return;
                }
                //The QDomElement class represents one element in the DOM tree.
                QDomElement docElem = doc.documentElement();
                /*
                  The QDomNodeList class is a list of QDomNode objects.
                  Lists can be obtained by QDomDocument::elementsByTagName() and QDomNode::childNodes().
                  The Document Object Model (DOM) requires these lists to be "live": whenever you change
                  the underlying document, the contents of the list will get updated.
                */
                QDomNodeList nodes = docElem.elementsByTagName("utente");
                for(int i=0; i<nodes.count(); ++i)
                {
                    QDomElement el = nodes.at(i).toElement();
                    QDomNode nodo = el.firstChild();
                    QString n, c, u, e, esp, comp, l, tit, tu, cont;
                    while (!nodo.isNull()) {
                        QDomElement elemento = nodo.toElement();
                        QString tagName = elemento.tagName();

                        if(tagName=="nome")
                        {
                            n=elemento.text();
                        }
                        if(tagName=="cognome")
                        {
                            c=elemento.text();
                        }
                        if(tagName=="username")
                        {
                            u=elemento.text();
                        }
                        if(tagName=="email")
                        {
                            e=elemento.text();
                        }
                        if(tagName=="tipoutente")
                        {
                            tu=elemento.text();
                        }
                        if(tagName=="esperienze")
                        {
                            esp=elemento.text();
                        }
                        if(tagName=="competenze")
                        {
                            comp=elemento.text();
                        }
                        if(tagName=="lingue")
                        {
                            l=elemento.text();
                        }
                        if(tagName=="titolistudio")
                        {
                            tit=elemento.text();
                        }
                        if(tagName=="contatti")
                        {
                            cont=elemento.text();
                        }
                        nodo=nodo.nextSibling();
                    }
                    Utente* ut = 0;
                    if(tu == "Utente Basic")
                    {
                        Profilo prof(n.toStdString(), c.toStdString(), e.toStdString());
                        Username us(u.toStdString());
                        ut=new UtenteBasic(prof, us);

                        if(esp.size()!=0)
                           ut->loadEsperienze(esp.toStdString());
                        if(comp.size()!=0)
                           ut->loadCompetenze(comp.toStdString());
                        if(l.size()!=0)
                           ut->loadLingue(l.toStdString());
                        if(tit.size()!=0)
                           ut->loadTitoliStudio(tit.toStdString());
                        if(cont.size()!=0)
                           ut->loadContatti(cont.toStdString());
                    }
                    if( tu == "Utente Business")
                    {
                        Profilo prof(n.toStdString(), c.toStdString(), e.toStdString());
                        Username us(u.toStdString());
                        ut=new UtenteBusiness(prof, us);

                        if(esp.size()!=0)
                           ut->loadEsperienze(esp.toStdString());
                        if(comp.size()!=0)
                           ut->loadCompetenze(comp.toStdString());
                        if(l.size()!=0)
                           ut->loadLingue(l.toStdString());
                        if(tit.size()!=0)
                           ut->loadTitoliStudio(tit.toStdString());
                        if(cont.size()!=0)
                           ut->loadContatti(cont.toStdString());
                    }
                    if( tu == "Utente Executive")
                    {
                        Profilo prof(n.toStdString(), c.toStdString(), e.toStdString());
                        Username us(u.toStdString());
                        ut=new UtenteExecutive(prof, us);

                        if(esp.size()!=0)
                           ut->loadEsperienze(esp.toStdString());
                        if(comp.size()!=0)
                           ut->loadCompetenze(comp.toStdString());
                        if(l.size()!=0)
                           ut->loadLingue(l.toStdString());
                        if(tit.size()!=0)
                           ut->loadTitoliStudio(tit.toStdString());
                        if(cont.size()!=0)
                           ut->loadContatti(cont.toStdString());
                    }

                    db.push_back(ut);
                }
                file->close();
            }
      }
}
Ejemplo n.º 30
0
MetadataLookupList MetadataDownload::readNFO(QString NFOpath,
                                             MetadataLookup* lookup)
{
    MetadataLookupList list;

    LOG(VB_GENERAL, LOG_INFO,
        QString("Matching NFO file found. Parsing %1 for metadata...")
               .arg(NFOpath));

    if (lookup->GetType() == kMetadataVideo)
    {
        QByteArray nforaw;
        QDomElement item;
        if (NFOpath.startsWith("myth://"))
        {
            RemoteFile *rf = new RemoteFile(NFOpath);
            if (rf && rf->Open())
            {
                bool loaded = rf->SaveAs(nforaw);
                if (loaded)
                {
                    QDomDocument doc;
                    if (doc.setContent(nforaw, true))
                    {
                        lookup->SetStep(kLookupData);
                        item = doc.documentElement();
                    }
                    else
                        LOG(VB_GENERAL, LOG_ERR,
                            QString("PIRATE ERROR: Invalid NFO file found."));
                }
                rf->Close();
            }

            delete rf;
            rf = NULL;
        }
        else
        {
            QFile file(NFOpath);
            if (file.open(QIODevice::ReadOnly))
            {
                nforaw = file.readAll();
                QDomDocument doc;
                if (doc.setContent(nforaw, true))
                {
                    lookup->SetStep(kLookupData);
                    item = doc.documentElement();
                }
                else
                    LOG(VB_GENERAL, LOG_ERR,
                        QString("PIRATE ERROR: Invalid NFO file found."));
                file.close();
            }
        }

        MetadataLookup *tmp = ParseMetadataMovieNFO(item, lookup);
        list.append(tmp);
    }

    return list;
}