コード例 #1
0
ファイル: qgswcsgetcapabilities.cpp プロジェクト: CS-SI/QGIS
  QDomDocument createGetCapabilitiesDocument( QgsServerInterface *serverIface, const QgsProject *project, const QString &version,
      const QgsServerRequest &request )
  {
    Q_UNUSED( version );

    QDomDocument doc;

    //wcs:WCS_Capabilities element
    QDomElement wcsCapabilitiesElement = doc.createElement( QStringLiteral( "WCS_Capabilities" )/*wcs:WCS_Capabilities*/ );
    wcsCapabilitiesElement.setAttribute( QStringLiteral( "xmlns" ), WCS_NAMESPACE );
    wcsCapabilitiesElement.setAttribute( QStringLiteral( "xmlns:xsi" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema-instance" ) );
    wcsCapabilitiesElement.setAttribute( QStringLiteral( "xsi:schemaLocation" ), WCS_NAMESPACE + " http://schemas.opengis.net/wcs/1.0.0/wcsCapabilities.xsd" );
    wcsCapabilitiesElement.setAttribute( QStringLiteral( "xmlns:gml" ), GML_NAMESPACE );
    wcsCapabilitiesElement.setAttribute( QStringLiteral( "xmlns:xlink" ), QStringLiteral( "http://www.w3.org/1999/xlink" ) );
    wcsCapabilitiesElement.setAttribute( QStringLiteral( "version" ), implementationVersion() );
    wcsCapabilitiesElement.setAttribute( QStringLiteral( "updateSequence" ), QStringLiteral( "0" ) );
    doc.appendChild( wcsCapabilitiesElement );

    //INSERT Service
    wcsCapabilitiesElement.appendChild( getServiceElement( doc, project ) );

    //wcs:Capability element
    QDomElement capabilityElement = doc.createElement( QStringLiteral( "Capability" )/*wcs:Capability*/ );
    wcsCapabilitiesElement.appendChild( capabilityElement );

    //wcs:Request element
    QDomElement requestElement = doc.createElement( QStringLiteral( "Request" )/*wcs:Request*/ );
    capabilityElement.appendChild( requestElement );

    //wcs:GetCapabilities
    QDomElement getCapabilitiesElement = doc.createElement( QStringLiteral( "GetCapabilities" )/*wcs:GetCapabilities*/ );
    requestElement.appendChild( getCapabilitiesElement );

    QDomElement dcpTypeElement = doc.createElement( QStringLiteral( "DCPType" )/*wcs:DCPType*/ );
    getCapabilitiesElement.appendChild( dcpTypeElement );
    QDomElement httpElement = doc.createElement( QStringLiteral( "HTTP" )/*wcs:HTTP*/ );
    dcpTypeElement.appendChild( httpElement );

    //Prepare url
    QString hrefString = serviceUrl( request, project );

    QDomElement getElement = doc.createElement( QStringLiteral( "Get" )/*wcs:Get*/ );
    httpElement.appendChild( getElement );
    QDomElement onlineResourceElement = doc.createElement( QStringLiteral( "OnlineResource" )/*wcs:OnlineResource*/ );
    onlineResourceElement.setAttribute( QStringLiteral( "xlink:type" ), QStringLiteral( "simple" ) );
    onlineResourceElement.setAttribute( QStringLiteral( "xlink:href" ), hrefString );
    getElement.appendChild( onlineResourceElement );

    QDomElement getCapabilitiesDhcTypePostElement = dcpTypeElement.cloneNode().toElement();//this is the same as for 'GetCapabilities'
    getCapabilitiesDhcTypePostElement.firstChild().firstChild().toElement().setTagName( QStringLiteral( "Post" ) );
    getCapabilitiesElement.appendChild( getCapabilitiesDhcTypePostElement );

    QDomElement describeCoverageElement = getCapabilitiesElement.cloneNode().toElement();//this is the same as 'GetCapabilities'
    describeCoverageElement.setTagName( QStringLiteral( "DescribeCoverage" ) );
    requestElement.appendChild( describeCoverageElement );

    QDomElement getCoverageElement = getCapabilitiesElement.cloneNode().toElement();//this is the same as 'GetCapabilities'
    getCoverageElement.setTagName( QStringLiteral( "GetCoverage" ) );
    requestElement.appendChild( getCoverageElement );

    //INSERT ContentMetadata
    wcsCapabilitiesElement.appendChild( getContentMetadataElement( doc, serverIface, project ) );

    return doc;

  }
コード例 #2
0
ファイル: samplerbank.cpp プロジェクト: Alppasa/mixxx
void SamplerBank::slotLoadSamplerBank(double v) {
    if (v == 0.0 || m_pPlayerManager == NULL) {
        return;
    }

    QString samplerBankPath = QFileDialog::getOpenFileName(
            NULL,
            tr("Load Sampler Bank"),
            QString(),
            tr("Mixxx Sampler Banks (*.xml)"));
    if (samplerBankPath.isEmpty()) {
        return;
    }

    // The user has picked a new directory via a file dialog. This means the
    // system sandboxer (if we are sandboxed) has granted us permission to this
    // folder. We don't need access to this file on a regular basis so we do not
    // register a security bookmark.

    QFile file(samplerBankPath);
    if (!file.open(QIODevice::ReadOnly)) {
        QMessageBox::warning(NULL,
                             tr("Error Reading Sampler Bank"),
                             tr("Could not open the sampler bank file '%1'.")
                             .arg(samplerBankPath));
        return;
    }

    QDomDocument doc;

    if (!doc.setContent(file.readAll())) {
        QMessageBox::warning(NULL,
                             tr("Error Reading Sampler Bank"),
                             tr("Could not read the sampler bank file '%1'.")
                             .arg(samplerBankPath));
        return;
    }

    QDomElement root = doc.documentElement();
    if(root.tagName() != "samplerbank") {
        QMessageBox::warning(NULL,
                             tr("Error Reading Sampler Bank"),
                             tr("Could not read the sampler bank file '%1'.")
                             .arg(samplerBankPath));
        return;
    }

    QDomNode n = root.firstChild();

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

        if (!e.isNull()) {
            if (e.tagName() == "sampler") {
                QString group = e.attribute("group", "");
                QString location = e.attribute("location", "");

                if (!group.isEmpty()) {
                    if (location.isEmpty()) {
                        m_pPlayerManager->slotLoadTrackToPlayer(TrackPointer(), group);
                    } else {
                        m_pPlayerManager->slotLoadToPlayer(location, group);
                    }
                }

            }
        }
        n = n.nextSibling();
    }

    file.close();
}
コード例 #3
0
ファイル: KCValidity.cpp プロジェクト: KDE/koffice
QDomElement KCValidity::saveXML(QDomDocument& doc, const KCValueConverter *converter) const
{
    QDomElement validityElement = doc.createElement("validity");

    QDomElement param = doc.createElement("param");
    param.setAttribute("cond", (int)d->cond);
    param.setAttribute("action", (int)d->action);
    param.setAttribute("allow", (int)d->restriction);
    param.setAttribute("valmin", converter->asString(d->minValue).asString());
    param.setAttribute("valmax", converter->asString(d->maxValue).asString());
    param.setAttribute("displaymessage", d->displayMessage);
    param.setAttribute("displayvalidationinformation", d->displayValidationInformation);
    param.setAttribute("allowemptycell", d->allowEmptyCell);
    if (!d->listValidity.isEmpty())
        param.setAttribute("listvalidity", d->listValidity.join(";"));
    validityElement.appendChild(param);
    QDomElement titleElement = doc.createElement("title");
    titleElement.appendChild(doc.createTextNode(d->title));
    validityElement.appendChild(titleElement);
    QDomElement messageElement = doc.createElement("message");
    messageElement.appendChild(doc.createCDATASection(d->message));
    validityElement.appendChild(messageElement);

    QDomElement inputTitle = doc.createElement("inputtitle");
    inputTitle.appendChild(doc.createTextNode(d->titleInfo));
    validityElement.appendChild(inputTitle);

    QDomElement inputMessage = doc.createElement("inputmessage");
    inputMessage.appendChild(doc.createTextNode(d->messageInfo));
    validityElement.appendChild(inputMessage);



    QString tmp;
    if (d->restriction == Time) {
        QDomElement timeMinElement = doc.createElement("timemin");
        tmp = converter->asString(d->minValue).asString();
        timeMinElement.appendChild(doc.createTextNode(tmp));
        validityElement.appendChild(timeMinElement);

        if (d->cond == KCConditional::Between || d->cond == KCConditional::Different) {
            QDomElement timeMaxElement = doc.createElement("timemax");
            tmp = converter->asString(d->maxValue).asString();
            timeMaxElement.appendChild(doc.createTextNode(tmp));
            validityElement.appendChild(timeMaxElement);
        }
    }

    if (d->restriction == Date) {
        QDomElement dateMinElement = doc.createElement("datemin");
        const QDate minDate = d->minValue.asDate(converter->settings());
        QString tmp("%1/%2/%3");
        tmp = tmp.arg(minDate.year()).arg(minDate.month()).arg(minDate.day());
        dateMinElement.appendChild(doc.createTextNode(tmp));
        validityElement.appendChild(dateMinElement);

        if (d->cond == KCConditional::Between || d->cond == KCConditional::Different) {
            QDomElement dateMaxElement = doc.createElement("datemax");
            const QDate maxDate = d->maxValue.asDate(converter->settings());
            QString tmp("%1/%2/%3");
            tmp = tmp.arg(maxDate.year()).arg(maxDate.month()).arg(maxDate.day());
            dateMaxElement.appendChild(doc.createTextNode(tmp));
            validityElement.appendChild(dateMaxElement);
        }
    }
    return validityElement;
}
コード例 #4
0
bool CalculateConfig::getDefaultConfig()
{
	m_Config.clear();

	// start cl-install -v and parse out
	QProcess	cl_install;

	qDebug() << "Start cl-install -v --xml --filter \"os_install|os_locale_lang$|os_disk|os_device|^cl_migrate_user$\"";

	cl_install.start(
		"cl-install -v --xml --filter \"os_install|os_locale_lang|os_disk|os_device|^cl_migrate_user$\""
	);

	if ( !cl_install.waitForStarted() )
		return false;

	if ( !cl_install.waitForFinished() )
		return false;

	QString			outVars = cl_install.readAll();

	qDebug() << endl << outVars;

	QDomDocument	xmlVars;
	QString			errMsg;
	int				errLine;
	int				errColumn;

	if ( xmlVars.setContent(outVars, true, &errMsg, &errLine, &errColumn) )
	{
		QDomElement domRoot = xmlVars.documentElement();
		if (domRoot.tagName() == "variables") {
			parseVariables(domRoot, m_Config);
		} else {
			qDebug() << "Section \"variables\" not found";
			return false;
		}
	}

	// installer settings
	// gui_partitioning - install type: auto, manual
	m_Config["gui_install_language"] = m_Config["os_locale_lang"];

	QStringList	devs = m_Config["os_device_dev"].toStringList();
	m_Config.remove("os_device_dev");
	m_Config["os_device_dev"] = devs;

	if ( !m_Config["os_device_dev"].toStringList().isEmpty() )
		m_Config["gui_os_device_dev"] = m_Config["os_device_dev"].toStringList().at(0);
	m_Config["gui_os_device_dev_def"] = m_Config["gui_os_device_dev"];

	// copy default values
	m_Config["gui_os_install_net_hostname"] = m_Config["os_install_net_hostname"];
	m_Config["gui_os_install_net_domain"] = m_Config["os_install_net_domain"];
	m_Config["gui_os_install_net_domain"] = m_Config["os_install_net_domain"];
	m_Config["gui_os_install_clock_timezone"] = m_Config["os_install_clock_timezone"];
	m_Config["gui_os_install_x11_video_drv"] = m_Config["os_install_x11_video_drv"];
	m_Config["gui_os_install_x11_composite"] = m_Config["os_install_x11_composite"];
	m_Config["gui_os_install_autologin"] = m_Config["os_install_autologin"];
	m_Config["gui_os_install_makeopts"] = m_Config["os_install_makeopts"];
	m_Config["gui_os_install_proxy"] = m_Config["os_install_proxy"];
	m_Config["gui_os_install_ntp"] = m_Config["os_install_ntp"];
	m_Config["gui_os_install_clock_type"] = m_Config["os_install_clock_type"];

	m_Config["def_os_install_disk_format"] = m_Config["os_install_disk_format"];
	m_Config["def_os_install_disk_mount"] = m_Config["os_install_disk_mount"];
	m_Config["def_os_install_disk_perform_format"] = m_Config["os_install_disk_perform_format"];

	m_Config["def_cl_migrate_user"] = m_Config["cl_migrate_user"];

	qDebug() << endl << "Start variables: ";
	MapConfig::ConstIterator	cfgIt = m_Config.constBegin();
	while(cfgIt != m_Config.constEnd())
	{
		qDebug() <<
			cfgIt.key() +
			" = " +
			(( QString(cfgIt.value().typeName()) == "QStringList") ?
				("[" + cfgIt.value().toStringList().join(", ") + "]") :
				( cfgIt.value().toString() ) );
		++cfgIt;
	}


	return true;
}
コード例 #5
0
void QgsDiagramSettings::writeXML( QDomElement& rendererElem, QDomDocument& doc ) const
{
  QDomElement categoryElem = doc.createElement( "DiagramCategory" );
  categoryElem.setAttribute( "font", font.toString() );
  categoryElem.setAttribute( "backgroundColor", backgroundColor.name() );
  categoryElem.setAttribute( "backgroundAlpha", backgroundColor.alpha() );
  categoryElem.setAttribute( "width", QString::number( size.width() ) );
  categoryElem.setAttribute( "height", QString::number( size.height() ) );
  categoryElem.setAttribute( "penColor", penColor.name() );
  categoryElem.setAttribute( "penAlpha", penColor.alpha() );
  categoryElem.setAttribute( "penWidth", QString::number( penWidth ) );
  categoryElem.setAttribute( "minScaleDenominator", QString::number( minScaleDenominator ) );
  categoryElem.setAttribute( "maxScaleDenominator", QString::number( maxScaleDenominator ) );
  categoryElem.setAttribute( "transparency", QString::number( transparency ) );

  // site type (mm vs. map units)
  if ( sizeType == MM )
  {
    categoryElem.setAttribute( "sizeType", "MM" );
  }
  else
  {
    categoryElem.setAttribute( "sizeType", "MapUnits" );
  }

  // label placement method (text diagram)
  if ( labelPlacementMethod == Height )
  {
    categoryElem.setAttribute( "labelPlacementMethod", "Height" );
  }
  else
  {
    categoryElem.setAttribute( "labelPlacementMethod", "XHeight" );
  }

  if ( scaleByArea )
  {
    categoryElem.setAttribute( "scaleDependency", "Area" );
  }
  else
  {
    categoryElem.setAttribute( "scaleDependency", "Diameter" );
  }

  // orientation (histogram)
  switch ( diagramOrientation )
  {
    case Left:
      categoryElem.setAttribute( "diagramOrientation", "Left" );
      break;

    case Right:
      categoryElem.setAttribute( "diagramOrientation", "Right" );
      break;

    case Down:
      categoryElem.setAttribute( "diagramOrientation", "Down" );
      break;

    case Up:
      categoryElem.setAttribute( "diagramOrientation", "Up" );
      break;

    default:
      categoryElem.setAttribute( "diagramOrientation", "Up" );
      break;
  }

  categoryElem.setAttribute( "barWidth", QString::number( barWidth ) );
  categoryElem.setAttribute( "minimumSize", QString::number( minimumSize ) );
  categoryElem.setAttribute( "angleOffset", QString::number( angleOffset ) );

  QString colors;
  for ( int i = 0; i < categoryColors.size(); ++i )
  {
    if ( i > 0 )
    {
      colors.append( "/" );
    }
    colors.append( categoryColors.at( i ).name() );
  }
  categoryElem.setAttribute( "colors", colors );

  QString categories;
  for ( int i = 0; i < categoryIndices.size(); ++i )
  {
    if ( i > 0 )
    {
      categories.append( "/" );
    }
    categories.append( QString::number( categoryIndices.at( i ) ) );
  }
  categoryElem.setAttribute( "categories", categories );

  rendererElem.appendChild( categoryElem );
}
コード例 #6
0
ファイル: plistconfigbackend.cpp プロジェクト: Anderty/qutim
	QDomElement variantToDomElement (const QVariant &v, QDomDocument &root)
	{
		QString result;
		QString type = QLatin1String("string");
		QDomElement element;
		switch (v.type()) {
			case QVariant::StringList:
			case QVariant::List:
			case QVariant::Map: {
				return element;
			}
			case QVariant::Invalid:
				result = QLatin1String("@Invalid()");
				break;

			case QVariant::ByteArray: {
				QByteArray a = v.toByteArray();
				result = a.toBase64();
				type = QLatin1String("data");
				break;
			}

			case QVariant::String: {
				result = v.toString();
				break;
			}
			case QVariant::LongLong:
			case QVariant::ULongLong:
			case QVariant::Int:
			case QVariant::UInt: {
				result = v.toString();
				type = QLatin1String("integer");
				break;
			}
			case QVariant::Bool: {
				element = root.createElement(v.toString());
				return element;
			}
			case QVariant::Double: {
				result = v.toString();
				type = QLatin1String("real");
				break;
			}
			case QVariant::KeySequence: {
				result = v.toString();
				if (result.startsWith(QLatin1Char('@')))
					result.prepend(QLatin1Char('@'));
				break;
			}
			case QVariant::Rect: {
				QRect r = qvariant_cast<QRect>(v);
				result += QLatin1String("@Rect(");
				result += QString::number(r.x());
				result += QLatin1Char(' ');
				result += QString::number(r.y());
				result += QLatin1Char(' ');
				result += QString::number(r.width());
				result += QLatin1Char(' ');
				result += QString::number(r.height());
				result += QLatin1Char(')');
				break;
			}
			case QVariant::Size: {
				QSize s = qvariant_cast<QSize>(v);
				result += QLatin1String("@Size(");
				result += QString::number(s.width());
				result += QLatin1Char(' ');
				result += QString::number(s.height());
				result += QLatin1Char(')');
				break;
			}
			case QVariant::Point: {
				QPoint p = qvariant_cast<QPoint>(v);
				result += QLatin1String("@Point(");
				result += QString::number(p.x());
				result += QLatin1Char(' ');
				result += QString::number(p.y());
				result += QLatin1Char(')');
				break;
			}

			default: {
				QByteArray a;
				{
					QDataStream s(&a, QIODevice::WriteOnly);
					s.setVersion(QDataStream::Qt_4_0);
					s << v;
				}

				result = QLatin1String("@Variant(");
				result += QString::fromLatin1(a.constData(), a.size());
				result += QLatin1Char(')');
				break;
			}
		}
		element = root.createElement(type);
		element.appendChild(root.createTextNode(result));
		return element;
	}
コード例 #7
0
bool CalculateConfig::getNewPartitioning()
{
	// start cl-install -v and parse out
	MapConfig	confDisk;
	QProcess	cl_install;

	qDebug() << "Start cl-install -v --xml --filter (os_disk|os_device|os_install_disk)";
	cl_install.start( "cl-install -v --xml --filter \"(os_disk|os_device|os_install_disk)\" " );

	if ( !cl_install.waitForStarted() )
		return false;

	if ( !cl_install.waitForFinished() )
		return false;

	QString			outVars = cl_install.readAll();

	QDomDocument	xmlVars;
	QString			errMsg;
	int				errLine;
	int				errColumn;

	if ( xmlVars.setContent(outVars, true, &errMsg, &errLine, &errColumn) )
	{
		QDomElement domRoot = xmlVars.documentElement();
		if (domRoot.tagName() == "variables") {
			parseVariables(domRoot, confDisk);
		} else {
			qDebug() << "Section \"variables\" not found";
			return false;
		}
	}

	QStringList	devs = confDisk["os_device_dev"].toStringList();

	m_Config.remove("os_device_dev");
	m_Config["os_device_dev"] = devs;

	m_Config.remove("os_disk_dev");
	m_Config["os_disk_dev"] = confDisk["os_disk_dev"];

	m_Config.remove("os_disk_format");
	m_Config["os_disk_format"] = confDisk["os_disk_format"];

	m_Config.remove("os_disk_name");
	m_Config["os_disk_name"] = confDisk["os_disk_name"];

	m_Config.remove("os_disk_part");
	m_Config["os_disk_part"] = confDisk["os_disk_part"];

	m_Config.remove("os_disk_size");
	m_Config["os_disk_size"] = confDisk["os_disk_size"];

	m_Config.remove("os_disk_mount");
	m_Config["os_disk_mount"] = confDisk["os_disk_mount"];

	m_Config.remove("os_install_disk_perform_format");
	m_Config["os_install_disk_perform_format"] = confDisk["os_install_disk_perform_format"];

	return true;
}
コード例 #8
0
QString QgsMapLayer::saveNamedStyle( const QString theURI, bool & theResultFlag )
{
  QString myErrorMessage;
  QDomDocument myDocument;
  exportNamedStyle( myDocument, myErrorMessage );

  // check if the uri is a file or ends with .qml,
  // which indicates that it should become one
  // everything else goes to the database
  QString filename;

  QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( this );
  if ( vlayer && vlayer->providerType() == "ogr" )
  {
    QStringList theURIParts = theURI.split( "|" );
    filename = theURIParts[0];
  }
  else if ( vlayer && vlayer->providerType() == "delimitedtext" )
  {
    filename = QUrl::fromEncoded( theURI.toAscii() ).toLocalFile();
  }
  else
  {
    filename = theURI;
  }

  QFileInfo myFileInfo( filename );
  if ( myFileInfo.exists() || filename.endsWith( ".qml", Qt::CaseInsensitive ) )
  {
    QFileInfo myDirInfo( myFileInfo.path() );  //excludes file name
    if ( !myDirInfo.isWritable() )
    {
      return tr( "The directory containing your dataset needs to be writable!" );
    }

    // now construct the file name for our .qml style file
    QString myFileName = myFileInfo.path() + QDir::separator() + myFileInfo.completeBaseName() + ".qml";

    QFile myFile( myFileName );
    if ( myFile.open( QFile::WriteOnly | QFile::Truncate ) )
    {
      QTextStream myFileStream( &myFile );
      // save as utf-8 with 2 spaces for indents
      myDocument.save( myFileStream, 2 );
      myFile.close();
      theResultFlag = true;
      return tr( "Created default style file as %1" ).arg( myFileName );
    }
    else
    {
      theResultFlag = false;
      return tr( "ERROR: Failed to created default style file as %1. Check file permissions and retry." ).arg( myFileName );
    }
  }
  else
  {
    QString qml = myDocument.toString();

    // read from database
    sqlite3 *myDatabase;
    sqlite3_stmt *myPreparedStatement;
    const char *myTail;
    int myResult;

    myResult = sqlite3_open( QDir( QgsApplication::qgisSettingsDirPath() ).absoluteFilePath( "qgis.qmldb" ).toUtf8().data(), &myDatabase );
    if ( myResult != SQLITE_OK )
    {
      return tr( "User database could not be opened." );
    }

    QByteArray param0 = theURI.toUtf8();
    QByteArray param1 = qml.toUtf8();

    QString mySql = "create table if not exists tbl_styles(style varchar primary key,qml varchar)";
    myResult = sqlite3_prepare( myDatabase, mySql.toUtf8().data(), mySql.toUtf8().length(), &myPreparedStatement, &myTail );
    if ( myResult == SQLITE_OK )
    {
      if ( sqlite3_step( myPreparedStatement ) != SQLITE_DONE )
      {
        sqlite3_finalize( myPreparedStatement );
        sqlite3_close( myDatabase );
        theResultFlag = false;
        return tr( "The style table could not be created." );
      }
    }

    sqlite3_finalize( myPreparedStatement );

    mySql = "insert into tbl_styles(style,qml) values (?,?)";
    myResult = sqlite3_prepare( myDatabase, mySql.toUtf8().data(), mySql.toUtf8().length(), &myPreparedStatement, &myTail );
    if ( myResult == SQLITE_OK )
    {
      if ( sqlite3_bind_text( myPreparedStatement, 1, param0.data(), param0.length(), SQLITE_STATIC ) == SQLITE_OK &&
           sqlite3_bind_text( myPreparedStatement, 2, param1.data(), param1.length(), SQLITE_STATIC ) == SQLITE_OK &&
           sqlite3_step( myPreparedStatement ) == SQLITE_DONE )
      {
        theResultFlag = true;
        myErrorMessage = tr( "The style %1 was saved to database" ).arg( theURI );
      }
    }

    sqlite3_finalize( myPreparedStatement );

    if ( !theResultFlag )
    {
      QString mySql = "update tbl_styles set qml=? where style=?";
      myResult = sqlite3_prepare( myDatabase, mySql.toUtf8().data(), mySql.toUtf8().length(), &myPreparedStatement, &myTail );
      if ( myResult == SQLITE_OK )
      {
        if ( sqlite3_bind_text( myPreparedStatement, 2, param0.data(), param0.length(), SQLITE_STATIC ) == SQLITE_OK &&
             sqlite3_bind_text( myPreparedStatement, 1, param1.data(), param1.length(), SQLITE_STATIC ) == SQLITE_OK &&
             sqlite3_step( myPreparedStatement ) == SQLITE_DONE )
        {
          theResultFlag = true;
          myErrorMessage = tr( "The style %1 was updated in the database." ).arg( theURI );
        }
        else
        {
          theResultFlag = false;
          myErrorMessage = tr( "The style %1 could not be updated in the database." ).arg( theURI );
        }
      }
      else
      {
        theResultFlag = false;
        myErrorMessage = tr( "The style %1 could not be inserted into database." ).arg( theURI );
      }

      sqlite3_finalize( myPreparedStatement );
    }

    sqlite3_close( myDatabase );
  }

  return myErrorMessage;
}
コード例 #9
0
MetadataLookupList MetadataDownload::readMXML(QString MXMLpath,
                                             MetadataLookup* lookup,
                                             bool passseas)
{
    MetadataLookupList list;

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

    if (lookup->GetType() == kMetadataVideo)
    {
        QByteArray mxmlraw;
        QDomElement item;
        if (MXMLpath.startsWith("myth://"))
        {
            RemoteFile *rf = new RemoteFile(MXMLpath);
            if (rf && rf->Open())
            {
                bool loaded = rf->SaveAs(mxmlraw);
                if (loaded)
                {
                    QDomDocument doc;
                    if (doc.setContent(mxmlraw, true))
                    {
                        lookup->SetStep(kLookupData);
                        QDomElement root = doc.documentElement();
                        item = root.firstChildElement("item");
                    }
                    else
                        LOG(VB_GENERAL, LOG_ERR,
                            QString("Corrupt or invalid MXML file."));
                }
                rf->Close();
            }

            delete rf;
            rf = NULL;
        }
        else
        {
            QFile file(MXMLpath);
            if (file.open(QIODevice::ReadOnly))
            {
                mxmlraw = file.readAll();
                QDomDocument doc;
                if (doc.setContent(mxmlraw, true))
                {
                    lookup->SetStep(kLookupData);
                    QDomElement root = doc.documentElement();
                    item = root.firstChildElement("item");
                }
                else
                    LOG(VB_GENERAL, LOG_ERR,
                        QString("Corrupt or invalid MXML file."));
                file.close();
            }
        }

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

    return list;
}
コード例 #10
0
QDomElement SmartPlaylistEditor::result() {
    QDomDocument doc;
    QDomNode node = doc.namedItem( "smartplaylists" );
    QDomElement nodeE;
    nodeE = node.toElement();

    QDomElement smartplaylist = doc.createElement( "smartplaylist" );

    smartplaylist.setAttribute( "name", name() );

    // Limit
    if ( m_limitCheck->isChecked() )
        smartplaylist.setAttribute( "maxresults", m_limitSpin->value() );

    nodeE.appendChild( smartplaylist );
    // Matches
    if( m_matchAnyCheck->isChecked() ) {
        QDomElement matches = doc.createElement("matches");
        smartplaylist.appendChild( matches );
        // Iterate through all criteria list
        CriteriaEditor *criteriaeditor = m_criteriaEditorAnyList.first();
        for( int i=0; criteriaeditor; criteriaeditor = m_criteriaEditorAnyList.next(), ++i ) {
            matches.appendChild( doc.importNode( criteriaeditor->getDomSearchCriteria( doc ), true ) );
        }
        matches.setAttribute( "glue",  "OR" );
        smartplaylist.appendChild( matches );
    }

    if( m_matchAllCheck->isChecked() ) {
        QDomElement matches = doc.createElement("matches");
        smartplaylist.appendChild( matches );
        // Iterate through all criteria list
        CriteriaEditor *criteriaeditor = m_criteriaEditorAllList.first();
        for( int i=0; criteriaeditor; criteriaeditor = m_criteriaEditorAllList.next(), ++i ) {
            matches.appendChild( doc.importNode( criteriaeditor->getDomSearchCriteria( doc ), true ) );
        }
        matches.setAttribute( "glue",  "AND" );
        smartplaylist.appendChild( matches );
    }

    // Order By
    if( m_orderCheck->isChecked() ) {
        QDomElement orderby = doc.createElement("orderby");
        if (m_orderCombo->currentItem() != m_orderCombo->count()-1) {
            orderby.setAttribute( "field", m_dbFields[ m_orderCombo->currentItem() ] );
            orderby.setAttribute( "order", m_orderTypeCombo->currentItem() == 1 ? "DESC" : "ASC" );
        } else {
            orderby.setAttribute( "field", "random" );
            orderby.setAttribute( "order", m_orderTypeCombo->currentItem() == 1 ? "weighted" : "random" );
        }

        smartplaylist.appendChild( orderby );
    }
    QDomElement Sql = doc.createElement("sqlquery");
    buildQuery();
    Sql.appendChild( doc.createTextNode( m_query ) );
    smartplaylist.appendChild( Sql );

    if( m_expandCheck->isChecked() ) {
        QDomElement expandBy = doc.createElement("expandby");
        expandBy.setAttribute( "field", m_expandableFields[ m_expandCombo->currentItem() ] );
        QDomText t = doc.createTextNode( m_expandQuery );
        expandBy.appendChild( t );
        smartplaylist.appendChild( expandBy );
    }
    return (smartplaylist);
}
コード例 #11
0
bool QgsMapLayer::writeLayerXML( QDomElement& layerElement, QDomDocument& document )
{
  // use scale dependent visibility flag
  layerElement.setAttribute( "hasScaleBasedVisibilityFlag", hasScaleBasedVisibility() ? 1 : 0 );
  layerElement.setAttribute( "minimumScale", QString::number( minimumScale() ) );
  layerElement.setAttribute( "maximumScale", QString::number( maximumScale() ) );

  // ID
  QDomElement layerId = document.createElement( "id" );
  QDomText layerIdText = document.createTextNode( id() );
  layerId.appendChild( layerIdText );

  layerElement.appendChild( layerId );

  // data source
  QDomElement dataSource = document.createElement( "datasource" );

  QString src = source();

  QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( this );
  // TODO: what about postgres, mysql and others, they should not go through writePath()
  if ( vlayer && vlayer->providerType() == "spatialite" )
  {
    QgsDataSourceURI uri( src );
    QString database = QgsProject::instance()->writePath( uri.database() );
    uri.setConnection( uri.host(), uri.port(), database, uri.username(), uri.password() );
    src = uri.uri();
  }
  else if ( vlayer && vlayer->providerType() == "ogr" )
  {
    QStringList theURIParts = src.split( "|" );
    theURIParts[0] = QgsProject::instance()->writePath( theURIParts[0] );
    src = theURIParts.join( "|" );
  }
  else if ( vlayer && vlayer->providerType() == "delimitedtext" )
  {
    QUrl urlSource = QUrl::fromEncoded( src.toAscii() );
    QUrl urlDest = QUrl::fromLocalFile( QgsProject::instance()->writePath( urlSource.toLocalFile() ) );
    urlDest.setQueryItems( urlSource.queryItems() );
    src = QString::fromAscii( urlDest.toEncoded() );
  }
  else
  {
    src = QgsProject::instance()->writePath( src );
  }

  QDomText dataSourceText = document.createTextNode( src );
  dataSource.appendChild( dataSourceText );

  layerElement.appendChild( dataSource );


  // layer name
  QDomElement layerName = document.createElement( "layername" );
  QDomText layerNameText = document.createTextNode( originalName() );
  layerName.appendChild( layerNameText );

  // layer title
  QDomElement layerTitle = document.createElement( "title" ) ;
  QDomText layerTitleText = document.createTextNode( title() );
  layerTitle.appendChild( layerTitleText );

  // layer abstract
  QDomElement layerAbstract = document.createElement( "abstract" );
  QDomText layerAbstractText = document.createTextNode( abstract() );
  layerAbstract.appendChild( layerAbstractText );

  layerElement.appendChild( layerName );
  layerElement.appendChild( layerTitle );
  layerElement.appendChild( layerAbstract );

  // layer keyword list
  QStringList keywordStringList = keywordList().split( "," );
  if ( keywordStringList.size() > 0 )
  {
    QDomElement layerKeywordList = document.createElement( "keywordList" );
    for ( int i = 0; i < keywordStringList.size(); ++i )
    {
      QDomElement layerKeywordValue = document.createElement( "value" );
      QDomText layerKeywordText = document.createTextNode( keywordStringList.at( i ).trimmed() );
      layerKeywordValue.appendChild( layerKeywordText );
      layerKeywordList.appendChild( layerKeywordValue );
    }
    layerElement.appendChild( layerKeywordList );
  }

  // layer metadataUrl
  QString aDataUrl = dataUrl();
  if ( !aDataUrl.isEmpty() )
  {
    QDomElement layerDataUrl = document.createElement( "dataUrl" ) ;
    QDomText layerDataUrlText = document.createTextNode( aDataUrl );
    layerDataUrl.appendChild( layerDataUrlText );
    layerDataUrl.setAttribute( "format", dataUrlFormat() );
    layerElement.appendChild( layerDataUrl );
  }

  // layer attribution
  QString aAttribution = attribution();
  if ( !aAttribution.isEmpty() )
  {
    QDomElement layerAttribution = document.createElement( "attribution" ) ;
    QDomText layerAttributionText = document.createTextNode( aAttribution );
    layerAttribution.appendChild( layerAttributionText );
    layerAttribution.setAttribute( "href", attributionUrl() );
    layerElement.appendChild( layerAttribution );
  }

  // layer metadataUrl
  QString aMetadataUrl = metadataUrl();
  if ( !aMetadataUrl.isEmpty() )
  {
    QDomElement layerMetadataUrl = document.createElement( "metadataUrl" ) ;
    QDomText layerMetadataUrlText = document.createTextNode( aMetadataUrl );
    layerMetadataUrl.appendChild( layerMetadataUrlText );
    layerMetadataUrl.setAttribute( "type", metadataUrlType() );
    layerMetadataUrl.setAttribute( "format", metadataUrlFormat() );
    layerElement.appendChild( layerMetadataUrl );
  }

  // timestamp if supported
  if ( timestamp() > QDateTime() )
  {
    QDomElement stamp = document.createElement( "timestamp" );
    QDomText stampText = document.createTextNode( timestamp().toString( Qt::ISODate ) );
    stamp.appendChild( stampText );
    layerElement.appendChild( stamp );
  }

  layerElement.appendChild( layerName );

  // zorder
  // This is no longer stored in the project file. It is superfluous since the layers
  // are written and read in the proper order.

  // spatial reference system id
  QDomElement mySrsElement = document.createElement( "srs" );
  mCRS->writeXML( mySrsElement, document );
  layerElement.appendChild( mySrsElement );

#if 0
  // <transparencyLevelInt>
  QDomElement transparencyLevelIntElement = document.createElement( "transparencyLevelInt" );
  QDomText    transparencyLevelIntText    = document.createTextNode( QString::number( getTransparency() ) );
  transparencyLevelIntElement.appendChild( transparencyLevelIntText );
  maplayer.appendChild( transparencyLevelIntElement );
#endif

  // now append layer node to map layer node

  writeCustomProperties( layerElement, document );

  return writeXml( layerElement, document );

} // bool QgsMapLayer::writeXML
コード例 #12
0
/**
 * @brief Load contents of the settings file
 * @param string _filename
 * @return bool
 */
bool Settings::load(QString _filename)
{
    if (_filename.isEmpty())
    {
        if (!m_enviro->isPortable() && !QFile(Environment::APPDATA_DIR + APP_CONFIG_FILE).exists() && QFile(APP_CONFIG_FILE).exists())
        {
            moveAppData();
        }

        _filename = Environment::APPDATA_DIR + APP_CONFIG_FILE;
    }

    // open xml file
    QFile file(_filename);

    if (!file.exists() || !file.open(QIODevice::ReadOnly))
    {
        QLOG_ERROR() << "Unable to load config file";
        return false;
    }

    // initialize domdocument
    QDomDocument dom;
    if (!dom.setContent(file.readAll()))
    {
        QLOG_ERROR() << "Unable to load config file";
        return false;
    }

    file.close();

    clearSets();

    // read settings node
    QDomElement settingsNode = dom.documentElement().firstChild().toElement();

    int newHotkey = 0;
    UM::MODE newMode = UM::MODE_NONE;
    bool updated = false;

    while (!settingsNode.isNull())
    {
        // config node
        if (settingsNode.tagName() == "config")
        {
            QDomElement configNode = settingsNode.firstChild().toElement();

            while (!configNode.isNull())
            {
                // migration to 1.3
                if (configNode.tagName() == "hotkey")
                {
                    newHotkey = configNode.text().toInt();
                }
                // migration to 1.9
                else if (configNode.tagName() == "mode")
                {
                    newMode = configNode.text() == "random" ? UM::MODE_RANDOM : UM::MODE_SEQUENTIAL;
                }
                else if (m_options.contains(configNode.tagName()))
                {
                    m_options[ configNode.tagName() ] = configNode.text();
                }

                configNode = configNode.nextSibling().toElement();
            }
        }
        else if (settingsNode.tagName() == "hotkeys")
        {
            QDomElement hotkeyNode = settingsNode.firstChild().toElement();

            while (!hotkeyNode.isNull())
            {
                // 1.3 format
                if (hotkeyNode.hasAttribute("key"))
                {
                    m_hotkeys[ hotkeyNode.tagName() ] =
                                hotkeyNode.attribute("key").toInt() +
                                hotkeyNode.attribute("mod").toInt();
                    updated = true;
                }
                // 1.4 format
                else
                {
                    // stored in string representation since 2.2.1
                    bool isInt;
                    m_hotkeys[ hotkeyNode.tagName() ] = hotkeyNode.text().toInt(&isInt);

                    if (!isInt)
                    {
                        m_hotkeys[ hotkeyNode.tagName() ] = UM::keySequenceToInt(QKeySequence(hotkeyNode.text()));
                    }
                }

                hotkeyNode = hotkeyNode.nextSibling().toElement();
            }
        }
        // sets node
        else if (settingsNode.tagName() == "sets")
        {
            QDomElement setNode = settingsNode.firstChild().toElement();

            while (!setNode.isNull())
            {
                // set node
                if (setNode.tagName() == "set")
                {
                    try {
                        m_sets.append(new Set(&setNode));
                    }
                    catch(const std::exception &e) {
                        QLOG_ERROR()<<e.what();
                    }
                }

                setNode = setNode.nextSibling().toElement();
            }
        }
        // monitors node
        else if (settingsNode.tagName() == "monitors")
        {
            QDomElement monNode = settingsNode.firstChild().toElement();

            m_monitors.clear();

            while (!monNode.isNull())
            {
                UM::Monitor mon;
                mon.enabled = (bool) monNode.attribute("enabled").toInt();
                mon.color = QColor(monNode.attribute("color")).rgb();

                m_monitors.append(mon);

                monNode = monNode.nextSibling().toElement();
            }
        }

        settingsNode = settingsNode.nextSibling().toElement();
    }

    QLOG_TRACE() << "Config loaded from file";

    if (newHotkey > 0)
    {
        QLOG_INFO() << "Need to update hotkeys";
        upgradeHotkeys(newHotkey);
        updated = true;
    }

    if (newMode != UM::MODE_NONE)
    {
        QLOG_INFO() << "Need to update modes";
        upgradeMode(newMode);
        updated = true;
    }

    if (updated)
    {
        QLOG_INFO() << "Settings file format changed";
        save();
    }

    foreach (Set* set, m_sets)
    {
        set->init();
    }

    if (QsLogging::Logger::instance().loggingLevel() != QsLogging::OffLevel)
    {
        log();
    }

    return true;
}
コード例 #13
0
ファイル: AccessCert.cpp プロジェクト: Krabi/idkaart_public
bool AccessCert::download( bool noCard )
{
	if( noCard )
	{
		QDesktopServices::openUrl( QUrl( "http://www.sk.ee/toend/" ) );
		return false;
	}

	QMessageBox d( QMessageBox::Information, tr("Server access certificate"),
		tr("Hereby I agree to terms and conditions of validity confirmation service and "
		   "will use the service in extent of 10 signatures per month. If you going to "
		   "exceed the limit of 10 signatures per month or/and will use the service for "
		   "commercial purposes, please refer to IT support of your company. Additional "
		   "information is available from <a href=\"http://www.sk.ee/kehtivuskinnitus\">"
		   "http://www.sk.ee/kehtivuskinnitus</a> or phone 1777"),
		QMessageBox::Help, m_parent );
	d.addButton( tr("Agree"), QMessageBox::AcceptRole );
	if( QLabel *label = d.findChild<QLabel*>() )
		label->setOpenExternalLinks( true );
	if( d.exec() == QMessageBox::Help )
	{
		QDesktopServices::openUrl( QUrl( "http://www.sk.ee/kehtivuskinnitus" ) );
		return false;
	}

	qApp->signer()->lock();
	QScopedPointer<SSLConnect> ssl( new SSLConnect() );
	ssl->setPKCS11( Application::confValue( Application::PKCS11Module ), false );
	ssl->setCard( qApp->signer()->token().card() );

	bool retry = false;
	do
	{
		retry = false;
		if( ssl->flags() & TokenData::PinLocked )
		{
			showWarning( tr("Error downloading server access certificate!\nPIN1 is blocked" ) );
			qApp->signer()->unlock();
			return false;
		}
		ssl->waitForFinished( SSLConnect::AccessCert );
		switch( ssl->error() )
		{
		case SSLConnect::PinCanceledError:
			qApp->signer()->unlock();
			return false;
		case SSLConnect::PinInvalidError:
			showWarning( ssl->errorString() );
			retry = true;
			break;
		default:
			if( !ssl->errorString().isEmpty() )
			{
				showWarning( tr("Error downloading server access certificate!\n%1").arg( ssl->errorString() ) );
				qApp->signer()->unlock();
				return false;
			}
			break;
		}
	}
	while( retry );

	QByteArray result = ssl->result();
	qApp->signer()->unlock();

	if( result.isEmpty() )
	{
		showWarning( tr("Empty result!") );
		return false;
	}

	QDomDocument domDoc;
	if( !domDoc.setContent( QString::fromUtf8( result ) ) )
	{
		showWarning( tr("Error parsing server access certificate result!") );
		return false;
	}

	QDomElement e = domDoc.documentElement();
	QDomNodeList status = e.elementsByTagName( "StatusCode" );
	if( status.isEmpty() )
	{
		showWarning( tr("Error parsing server access certificate result!") );
		return false;
	}

	switch( status.item(0).toElement().text().toInt() )
	{
	case 1: //need to order cert manually from SK web
		QDesktopServices::openUrl( QUrl( "http://www.sk.ee/toend/" ) );
		return false;
	case 2: //got error, show message from MessageToDisplay element
		showWarning( tr("Error downloading server access certificate!\n%1")
			.arg( e.elementsByTagName( "MessageToDisplay" ).item(0).toElement().text() ) );
		return false;
	default: break; //ok
	}

	QString cert = e.elementsByTagName( "TokenData" ).item(0).toElement().text();
	if ( cert.isEmpty() )
	{
		showWarning( tr("Error reading server access certificate - empty content!") );
		return false;
	}

	QString path = QDesktopServices::storageLocation( QDesktopServices::DataLocation );
	if ( !QDir( path ).exists() )
		QDir().mkpath( path );

	QFile f( QString( "%1/%2.p12" ).arg( path, SslCertificate( qApp->signer()->token().cert() ).subjectInfo( "serialNumber" ) ) );
	if ( !f.open( QIODevice::WriteOnly|QIODevice::Truncate ) )
	{
		showWarning( tr("Failed to save server access certificate file to %1!\n%2")
			.arg( f.fileName() )
			.arg( f.errorString() ) );
		return false;
	}
	f.write( QByteArray::fromBase64( cert.toLatin1() ) );

	Application::setConfValue( Application::PKCS12Cert, m_cert = f.fileName() );
	Application::setConfValue( Application::PKCS12Pass, m_pass = e.elementsByTagName( "TokenPassword" ).item(0).toElement().text() );
	return true;
}
コード例 #14
0
	IAdvancedHTMLEditor::CustomTags_t LJBloggingPlatform::GetCustomTags () const
	{
		IAdvancedHTMLEditor::CustomTags_t tags;

		IAdvancedHTMLEditor::CustomTag ljUserTag;
		ljUserTag.TagName_ = "lj";
		ljUserTag.ToKnown_ = [] (QDomElement& elem) -> void
		{
			const auto& user = elem.attribute ("user");
			elem.setTagName ("span");
			elem.setAttribute ("contenteditable", "false");

			QDomElement linkElem = elem.ownerDocument ().createElement ("a");
			linkElem.setAttribute ("href", QString ("http://%1.livejournal.com/profile").arg (user));
			linkElem.setAttribute ("target", "_blank");

			QDomElement imgElem = elem.ownerDocument ().createElement ("img");
			imgElem.setAttribute ("src", "http://l-stat.livejournal.com/img/userinfo.gif?v=17080");
			linkElem.appendChild (imgElem);

			QDomElement nameElem = elem.ownerDocument ().createElement ("a");
			nameElem.setAttribute ("href", QString ("http://%1.livejournal.com/profile").arg (user));
			nameElem.setAttribute ("target", "_blank");
			nameElem.setAttribute ("id", "nameLink");
			nameElem.setAttribute ("contenteditable", "true");
			nameElem.appendChild (elem.ownerDocument ().createTextNode (user));

			elem.appendChild (linkElem);
			elem.appendChild (nameElem);

			elem.removeAttribute ("user");
		};
		ljUserTag.FromKnown_ = [] (QDomElement& elem) -> bool
		{
			auto aElem = elem.firstChildElement ("a");
			while (!aElem.isNull ())
			{
				if (aElem.attribute ("id") == "nameLink")
					break;

				aElem = aElem.nextSiblingElement ("a");
			}
			if (aElem.isNull ())
				return false;
			const auto& username = aElem.text ();

			const auto& children = elem.childNodes ();
			while (!children.isEmpty ())
				elem.removeChild (children.at (0));

			elem.setTagName ("lj");
			elem.setAttribute ("user", username);

			return true;
		};
		tags << ljUserTag;

		IAdvancedHTMLEditor::CustomTag ljCutTag;
		ljCutTag.TagName_ = "lj-cut";
		ljCutTag.ToKnown_ = [] (QDomElement& elem) -> void
		{
			elem.setTagName ("div");
			const auto& text = elem.attribute ("text");
			elem.removeAttribute ("text");
			elem.setAttribute ("id", "cutTag");
			elem.setAttribute ("style", "overflow:auto;border-width:3px;border-style:dotted;margin-left:3em;padding:2em 2em;");
			elem.setAttribute ("text", text);
		};
		ljCutTag.FromKnown_ = [] (QDomElement& elem) -> bool
		{
			if (!elem.hasAttribute ("id") ||
					elem.attribute ("id") != "cutTag")
				return false;

			elem.removeAttribute ("id");
			elem.removeAttribute ("style");
			const auto& text = elem.attribute ("text");
			elem.removeAttribute ("text");
			elem.setTagName ("lj-cut");
			if (!text.isEmpty ())
				elem.setAttribute ("text", text);

			return true;
		};

		tags << ljCutTag;

		IAdvancedHTMLEditor::CustomTag ljPollTag;
		ljPollTag.TagName_ = "lj-poll";
		ljPollTag.ToKnown_ = [this] (QDomElement& elem) -> void
		{
			const auto& whoView = elem.attribute ("whoview");
			const auto& whoVote = elem.attribute ("whovote");
			const auto& name = elem.attribute ("name");

			auto children = elem.childNodes ();

			elem.setTagName ("div");
			elem.setAttribute ("style", "overflow:auto;border-width:2px;border-style:solid;border-radius:5px;margin-left:3em;padding:2em 2em;");
			elem.setAttribute ("id", "pollDiv");
			elem.setAttribute ("ljPollWhoview", whoView);
			elem.setAttribute ("ljPollWhovote", whoVote);
			elem.setAttribute ("ljPollName", name);
			QString questions;
			for (int i = 0, size = children.size (); i < size; ++i)
			{
				const auto& child = children.at (i);
				QString question;
				QTextStream str (&question);
				child.save (str, 0);

				questions.append (question);
			}
			elem.setAttribute ("ljPollQuestions", QString (questions.toUtf8 ().toBase64 ()));
			while (!children.isEmpty ())
				elem.removeChild (children.at (0));
			auto textElem = elem.ownerDocument ().createTextNode (tr ("Poll: %1").arg (name));
			elem.appendChild (textElem);

		};
		ljPollTag.FromKnown_ = [] (QDomElement& elem) -> bool
		{
			if (!elem.hasAttribute ("id") ||
					elem.attribute ("id") != "pollDiv")
				return false;

			auto whoView = elem.attribute ("ljPollWhoview");
			auto whoVote = elem.attribute ("ljPollWhovote");
			auto name = elem.attribute ("ljPollName");
			auto questions = QByteArray::fromBase64 (elem.attribute ("ljPollQuestions").toUtf8 ());

			elem.removeAttribute ("style");
			elem.removeAttribute ("ljPollWhoview");
			elem.removeAttribute ("ljPollWhovot");
			elem.removeAttribute ("ljPollName");
			elem.removeAttribute ("ljPollQuestions");
			elem.removeAttribute ("id");
			elem.removeChild (elem.firstChild ());

			elem.setTagName ("lj-poll");
			elem.setAttribute ("whoview", whoView);
			elem.setAttribute ("whovote", whoVote);
			elem.setAttribute ("name", name);
			QDomDocument doc;
			doc.setContent (questions);
			elem.appendChild (doc.documentElement ());

			return true;
		};

		tags << ljPollTag;

		IAdvancedHTMLEditor::CustomTag ljEmbedTag;
		ljEmbedTag.TagName_ = "lj-embed";
		ljEmbedTag.ToKnown_ = [this] (QDomElement& elem) -> void
		{
			const auto& id = elem.attribute ("id");
			elem.removeAttribute ("id");

			elem.setTagName ("div");
			elem.setAttribute ("style", "overflow:auto;border-width:2px;border-style:solid;border-radius:5px;margin-left:3em;padding:2em 2em;");
			elem.setAttribute ("id", "embedTag");
			elem.setAttribute ("name", id);
			auto textElem = elem.ownerDocument ().createTextNode (tr ("Embedded: %1")
					.arg (id));
			elem.appendChild (textElem);
		};
		ljEmbedTag.FromKnown_ = [] (QDomElement& elem) -> bool
		{
			if (!elem.hasAttribute ("id") ||
					elem.attribute ("id") != "embedTag")
				return false;

			elem.removeAttribute ("style");
			elem.removeChild (elem.firstChild ());
			const auto& id = elem.attribute ("name");
			elem.removeAttribute ("id");
			elem.setTagName ("lj-embed");
			elem.setAttribute ("id", id);
			return true;
		};

		tags << ljEmbedTag;

		IAdvancedHTMLEditor::CustomTag ljLikeTag;
		ljLikeTag.TagName_ = "lj-like";
		ljLikeTag.ToKnown_ = [this] (QDomElement& elem) -> void
		{
			const auto& buttons = elem.attribute ("buttons");
			elem.removeAttribute ("buttons");

			elem.setTagName ("div");
			elem.setAttribute ("style", "overflow:auto;border-width:2px;border-style:solid;border-radius:5px;margin-left:3em;padding:2em 2em;");
			elem.setAttribute ("likes", buttons);
			auto textElem = elem.ownerDocument ().createTextNode (tr ("Likes: %1")
					.arg (!buttons.isEmpty () ?
						buttons :
						"repost,facebook,twitter,google,vkontakte,surfingbird,tumblr,livejournal"));
			elem.appendChild (textElem);
		};
		ljLikeTag.FromKnown_ = [] (QDomElement& elem) -> bool
		{
			const auto& likes = elem.attribute ("likes");
			if (likes.isEmpty ())
				return false;

			elem.removeAttribute ("likes");
			elem.removeAttribute ("style");
			elem.setTagName ("lj-like");
			elem.setAttribute ("buttons", likes);
			elem.removeChild (elem.firstChild ());
			return true;
		};

		tags << ljLikeTag;

		return tags;
	}
コード例 #15
0
ファイル: formulareditor.cpp プロジェクト: twister9893/home
bool FormularEditor::readFromFile(QString fileName) {
    QString errorString;
    int errorLine;
    int errorColumn;
    QFile file(fileName);
    QDomDocument domDocument;

    if(!file.open(QIODevice::ReadOnly))
        return false;

    if(!domDocument.setContent(&file, true, &errorString, &errorLine, &errorColumn)) {
        qWarning() << "Line " << errorLine << "colunm " << errorColumn << " message ";
        return false;
    }

    QDomElement domRoot = domDocument.documentElement();
    qDebug() << "[Formular editor] Read from file: Root tag name" << domRoot.tagName();

    if(domRoot.tagName() != "formular") {
        qCritical() << "[Formular editor] Read from file: Bad file, incorrect root tag name";
        return false;
    }

    QString inputCheck;
    const uint defaultCapacity = 8;
    inputCheck = domRoot.attribute("capacity", "_err_");
    if(inputCheck == "_err_") {
        qWarning() << "[Formular editor] Read from file: No \"capacity\" attribute. Set default" << defaultCapacity;
        inputCheck = QString::number(defaultCapacity);
    }
    if(inputCheck.toInt()%8) {
        qWarning() << "[Formular editor] Read from file: Bad \"capacity\" attribute. Set default" << defaultCapacity;
        inputCheck = QString::number(defaultCapacity);
    }
    ui->capacityBox->setCurrentIndex(Formular::capacities.indexOf(inputCheck));

    inputCheck = domRoot.attribute("description", "_err_");
    if(inputCheck == "_err_")
    {
        qWarning() << "[Formular editor] Read from file: No \"description\" attribute. Set empty string";
        inputCheck = "";
    }
    ui->descriptionEdit->setText(inputCheck);

    QDomElement domField = domRoot.firstChildElement();
    while(!domField.isNull()) {
        inputCheck = domField.attribute("name", "_err_");
        if(inputCheck == "_err_") {
            qWarning() << "[Formular editor] Read from file: No \"name\" attribute. Set empty string";
            inputCheck = "";
        }
        QString name = inputCheck;

        inputCheck = domField.attribute("description", "_err_");
        if(inputCheck == "_err_") {
            qWarning() << "[Formular editor] Read from file: No \"description\" attribute. Set empty string";
            inputCheck = "";
        }
        QString description = inputCheck;

        const uint defaultFieldSize = 1;
        inputCheck = domField.attribute("size", "_err_");
        if(inputCheck == "_err_") {
            qWarning() << "[Formular editor] Read from file: No \"size\" attribute. Set default" << defaultFieldSize;
            inputCheck = QString::number(defaultFieldSize);
        }
        if(inputCheck.toInt() <= 0) {
            qWarning() << "[Formular editor] Read from file: Bad \"size\" attribute. Set default" << defaultFieldSize;
            inputCheck = QString::number(defaultFieldSize);
        }
        int size = inputCheck.toInt();

        const FieldData::Dimension defaultFieldDimension = FieldData::No;
        inputCheck = domField.attribute("dimension", "_err_");
        if(inputCheck == "_err_") {
            qWarning() << "[Formular editor] Read from file: No \"dimension\" attribute. Set default" << FieldData::dimensions.at(defaultFieldDimension);
            inputCheck = FieldData::dimensions.at(defaultFieldDimension);
        }
        if(FieldData::dimensions.indexOf(inputCheck) == -1) {
            qWarning() << "[Formular editor] Read from file: Bad \"dimension\" attribute. Set default" << FieldData::dimensions.at(defaultFieldDimension);
            inputCheck = FieldData::dimensions.at(defaultFieldDimension);
        }
        FieldData::Dimension dimension = (FieldData::Dimension)FieldData::dimensions.indexOf(inputCheck);

        const FieldData::Type defaultFieldType = FieldData::Integer;
        inputCheck = domField.attribute("type", "_err_");
        if(inputCheck == "_err_") {
            qWarning() << "[Formular editor] Read from file: No \"type\" attribute. Set default" << FieldData::types.at(defaultFieldType);
            inputCheck = FieldData::types.at(defaultFieldType);
        }
        if(FieldData::types.indexOf(inputCheck) == -1) {
            qWarning() << "[Formular editor] Read from file: Bad \"type\" attribute. Set default" << FieldData::types.at(defaultFieldType);
            inputCheck = FieldData::types.at(defaultFieldType);
        }
        FieldData::Type type = (FieldData::Type)FieldData::types.indexOf(inputCheck);

        switch(type) {
            case FieldData::Integer:
            case FieldData::Real:
            case FieldData::Boolean:
            case FieldData::String:
            case FieldData::Unused: {
                FieldData *field = new FieldData(name, description, type, dimension, size);
                m_formularModel->insertRow(m_formularModel->rowCount());
                m_formularModel->setData(m_formularModel->index(m_formularModel->rowCount() - 1), QVariant((long long int)field), Qt::EditRole);
                break;
            }
            case FieldData::Scalable: {
                FieldScalable *field = new FieldScalable(name, description, type, dimension, size);
                const double defaultHighOrderBit = 0.0;
                inputCheck = domField.attribute("highOrderBit", "_err_");
                if(inputCheck == "_err_") {
                    qWarning() << "[Formular editor] Read from file: No \"highOrderBit\" attribute. Set default" << defaultHighOrderBit;
                    inputCheck = QString::number(defaultHighOrderBit);
                }
                field->setHighOrderBit(inputCheck.toDouble());
                const double defaultLowerOrderBit = 0.0;
                inputCheck = domField.attribute("lowerOrderBit", "_err_");
                if(inputCheck == "_err_") {
                    qWarning() << "[Formular editor] Read from file: No \"lowerOrderBit\" attribute. Set default" << defaultLowerOrderBit;
                    inputCheck = QString::number(defaultLowerOrderBit);
                }
                field->setLowerOrderBit(inputCheck.toDouble());
                const bool defaultAdditionalCodeState = false;
                inputCheck = domField.attribute("additionalCode", "_err_");
                if(inputCheck == "_err_") {
                    qWarning() << "[Formular editor] Read from file: No \"additionalCode\" attribute. Set default" << defaultAdditionalCodeState;
                    inputCheck = QString::number(defaultAdditionalCodeState);
                }
                field->setAdditionalCode(inputCheck.toInt());
                const bool defaultHighBitSignState = false;
                inputCheck = domField.attribute("highBitSign", "_err_");
                if(inputCheck == "_err_") {
                    qWarning() << "[Formular editor] Read from file: No \"highBitSign\" attribute. Set default" << defaultHighBitSignState;
                    inputCheck = QString::number(defaultHighBitSignState);
                }
                field->setHighBitSign(inputCheck.toInt());
                m_formularModel->insertRow(m_formularModel->rowCount());
                m_formularModel->setData(m_formularModel->index(m_formularModel->rowCount() - 1), QVariant((long long int)field), Qt::EditRole);
                break;
            }
            case FieldData::Enumeration: {
                FieldEnumeration *field = new FieldEnumeration(name, description, type, dimension, size);
                QDomElement domEnumerationElement = domField.firstChildElement();
                uint code = 0;
                while(!domEnumerationElement.isNull()) {
                    FieldEnumeration::EnumerationElement elem;

                    inputCheck = domEnumerationElement.attribute("code", "_err_");
                    if(inputCheck == "_err_") {
                        qWarning() << "[Formular editor] Read from file: No \"code\" attribute. Set default" << code;
                        inputCheck = QString::number(code);
                    }
                    ++code;
                    elem.setCode(inputCheck);

                    inputCheck = domEnumerationElement.attribute("acronym", "_err_");
                    if(inputCheck == "_err_") {
                        qWarning() << "[Formular editor] Read from file: No \"acronym\" attribute. Set empty string";
                        inputCheck = "";
                    }
                    elem.setAcronym(inputCheck);

                    inputCheck = domEnumerationElement.attribute("transcript", "_err_");
                    if(inputCheck == "_err_") {
                        qWarning() << "[Formular editor] Read from file: No \"transcript\" attribute. Set empty string";
                        inputCheck = "";
                    }
                    elem.setTranscript(inputCheck);
                    domEnumerationElement = domEnumerationElement.nextSiblingElement();

                    field->getElements().append(elem);
                }
                m_formularModel->insertRow(m_formularModel->rowCount());
                m_formularModel->setData(m_formularModel->index(m_formularModel->rowCount() - 1), QVariant((long long int)field), Qt::EditRole);
                break;
            }
            case FieldData::Constant: {
                FieldConstant *field = new FieldConstant(name, description, type, dimension, size);
                inputCheck = domField.attribute("value", "_err_");
                if(inputCheck == "_err_") {
                    qWarning() << "[Formular editor] Read from file: No \"value\" attribute. Set empty string";
                    inputCheck = "";
                }
                field->setValue(inputCheck);
                m_formularModel->insertRow(m_formularModel->rowCount());
                m_formularModel->setData(m_formularModel->index(m_formularModel->rowCount() - 1), QVariant((long long int)field), Qt::EditRole);
                break;
            }
        }
        domField = domField.nextSiblingElement();
    }
    return true;
}
コード例 #16
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;
}
コード例 #17
0
ファイル: waccount.cpp プロジェクト: AlexeyProkhin/qutim
void WAccount::onNetworkReply(QNetworkReply *reply)
{
	reply->deleteLater();
	WContact *contact = qobject_cast<WContact*>(reply->request().originatingObject());
	if (!contact)
		return;
	
	QDomDocument doc;
	if (!doc.setContent(reply->readAll()))
		return;
	bool needMessage = reply->property("needMessage").toBool();
	QDomElement rootElement = doc.documentElement();
	
	QDomElement units = rootElement.namedItem(QLatin1String("units")).toElement();
	QString tempUnit = units.namedItem(QLatin1String("temp")).toElement().text();
	
	QDomElement local = rootElement.namedItem(QLatin1String("local")).toElement();
	QString cityName = local.namedItem(QLatin1String("city")).toElement().text();
	contact->setNameInternal(cityName);
	
	QDomElement current = rootElement.namedItem(QLatin1String("current")).toElement();
	if (!current.isNull()) {
		QString temperature = current.namedItem(QLatin1String("temperature")).toElement().text();
		QString iconId = current.namedItem(QLatin1String("weathericon")).toElement().text();
		QString text = tr("Weather: %1°%2").arg(temperature, tempUnit);
		contact->setStatusInternal(iconId, text);
		if (needMessage) {
			QString text = loadResourceFile(QLatin1String("Current.txt"));
			QString html = loadResourceFile(QLatin1String("Current.html"));
			
			fillStrings(text, html, units, QLatin1String("%units"));
			fillStrings(text, html, current, QLatin1String("%"));
			
			Message message(text);
			message.setHtml(html);
			message.setChatUnit(contact);
			message.setIncoming(true);
			message.setTime(QDateTime::currentDateTime());
			ChatLayer::get(contact, true)->appendMessage(message);
		}
	}
	
	QDomElement forecast = rootElement.namedItem(QLatin1String("forecast")).toElement();
	if (needMessage && !forecast.isNull()) {
		QString textResult = loadResourceFile(QLatin1String("ForecastTitle.txt"));
		QString htmlResult = loadResourceFile(QLatin1String("ForecastTitle.html"));
		QString textBody = loadResourceFile(QLatin1String("ForecastDay.txt"));
		QString htmlBody = loadResourceFile(QLatin1String("ForecastDay.html"));
		
		fillStrings(textBody, htmlBody, units, QLatin1String("%units"));
		
		QDomNodeList days = forecast.elementsByTagName(QLatin1String("day"));
		for (int i = 0; i < days.count(); ++i) {
			if (!days.at(i).isElement())
				continue;
			QDomElement day = days.at(i).toElement();
			QString text = textBody;
			QString html = htmlBody;
			fillStrings(text, html, day, QLatin1String("%"));
			textResult += text;
			htmlResult += html;
		}
		
		Message message(textResult);
		message.setHtml(htmlResult);
		message.setChatUnit(contact);
		message.setIncoming(true);
		message.setTime(QDateTime::currentDateTime());
		ChatLayer::get(contact, true)->appendMessage(message);
	}
}
コード例 #18
0
// if no file is open
void MainWindow::openFile(QString &xmlFileName, QFile &xmlFile, QDomDocument &xmlDomDocument, QDomDocument &xmlDomDocumentOrg, bool createFile)
{

    QString filename;

    // open file diaglog
    if(createFile == OPEN_EXISTING_FILE){
        // Open diaglog to -- open existing file
        filename = QFileDialog::getOpenFileName(this, tr("Open File"),
                                                   "",
                                                   tr("Files (*.xml)"));

    }
    else{
        // Open diaglog to -- create new file
        filename = QFileDialog::getSaveFileName(this, tr("Save File"),
                                                   "",
                                                   tr("Files (*.xml)"));
    }

    // Check if cancel button is pressed in the QFileDialog
    if(filename != "")
    {
        //copy file name to globalobject
        xmlFileName = filename;
        // create new xml file & text stream
        //xmlOpenFile();
        // Add a delay
        xmlLibObject.xmlOpenFile( xmlFileName, xmlFile, xmlStream);

        if(createFile == OPEN_EXISTING_FILE){

            //Load the XML file
            //xmlLoadFile();
            xmlLibObject.xmlLoadFile(xmlDomDocument, xmlFile);

            //close file
            //xmlCloseFile();
            //xmlLibObject.xmlCloseFile(xmlStream, xmlDomDocument, xmlFile);

            //Now again open & truncate the file
            //xmlOpenFileTruncate();
            //xmlLibObject.xmlOpenFileTruncate( xmlFileName, xmlFile, xmlStream);

            //Get the root element
            //xmlGetRoot();
            xmlLibObject.xmlGetRoot(xmlRoot, xmlDomDocument);
            // copy data to the tree view
            // copy data to the text view
            loadXmltoTreeAndTextView();

            //Its not new file
            b_newFileCreationSignal = FALSE;

            //create backup for original xml.
            xmlDomDocumentOrg.clear();
            xmlDomDocumentOrg = xmlDomDocument.cloneNode(true).toDocument();
        }
        else{
            //Add root node
             //xmlAddRoot();            
            xmlLibObject.xmlAddRoot(xmlRoot, xmlDomDocument);

            // File contains new node
            b_fileDoesNotContainsNode = TRUE;

            //New file creation signal
            b_newFileCreationSignal = TRUE;

            //New file created
            xmlDomDocumentOrg.clear();
        }

        // xml file is already open
        b_xmlFileAlreadyOpen = TRUE;

    }
    else {
        // Do nothing cancel presses
    }


}
コード例 #19
0
QDomElement QgsCategorizedSymbolRendererV2::save( QDomDocument& doc )
{
  QDomElement rendererElem = doc.createElement( RENDERER_TAG_NAME );
  rendererElem.setAttribute( "type", "categorizedSymbol" );
  rendererElem.setAttribute( "symbollevels", ( mUsingSymbolLevels ? "1" : "0" ) );
  rendererElem.setAttribute( "forceraster", ( mForceRaster ? "1" : "0" ) );
  rendererElem.setAttribute( "attr", mAttrName );

  // categories
  int i = 0;
  QgsSymbolV2Map symbols;
  QDomElement catsElem = doc.createElement( "categories" );
  QgsCategoryList::const_iterator it = mCategories.constBegin();
  for ( ; it != mCategories.end(); ++it )
  {
    const QgsRendererCategoryV2& cat = *it;
    QString symbolName = QString::number( i );
    symbols.insert( symbolName, cat.symbol() );

    QDomElement catElem = doc.createElement( "category" );
    catElem.setAttribute( "value", cat.value().toString() );
    catElem.setAttribute( "symbol", symbolName );
    catElem.setAttribute( "label", cat.label() );
    catElem.setAttribute( "render", cat.renderState() ? "true" : "false" );
    catsElem.appendChild( catElem );
    i++;
  }

  rendererElem.appendChild( catsElem );

  // save symbols
  QDomElement symbolsElem = QgsSymbolLayerV2Utils::saveSymbols( symbols, "symbols", doc );
  rendererElem.appendChild( symbolsElem );

  // save source symbol
  if ( mSourceSymbol.data() )
  {
    QgsSymbolV2Map sourceSymbols;
    sourceSymbols.insert( "0", mSourceSymbol.data() );
    QDomElement sourceSymbolElem = QgsSymbolLayerV2Utils::saveSymbols( sourceSymbols, "source-symbol", doc );
    rendererElem.appendChild( sourceSymbolElem );
  }

  // save source color ramp
  if ( mSourceColorRamp.data() )
  {
    QDomElement colorRampElem = QgsSymbolLayerV2Utils::saveColorRamp( "[source]", mSourceColorRamp.data(), doc );
    rendererElem.appendChild( colorRampElem );
    QDomElement invertedElem = doc.createElement( "invertedcolorramp" );
    invertedElem.setAttribute( "value", mInvertedColorRamp );
    rendererElem.appendChild( invertedElem );
  }

  QDomElement rotationElem = doc.createElement( "rotation" );
  if ( mRotation.data() )
    rotationElem.setAttribute( "field", QgsSymbolLayerV2Utils::fieldOrExpressionFromExpression( mRotation.data() ) );
  rendererElem.appendChild( rotationElem );

  QDomElement sizeScaleElem = doc.createElement( "sizescale" );
  if ( mSizeScale.data() )
    sizeScaleElem.setAttribute( "field", QgsSymbolLayerV2Utils::fieldOrExpressionFromExpression( mSizeScale.data() ) );
  sizeScaleElem.setAttribute( "scalemethod", QgsSymbolLayerV2Utils::encodeScaleMethod( mScaleMethod ) );
  rendererElem.appendChild( sizeScaleElem );

  if ( mPaintEffect )
    mPaintEffect->saveProperties( doc, rendererElem );

  return rendererElem;
}
コード例 #20
0
SResourcePackage::SResourcePackage() : QDomDocument()
{
	QDomElement root = createElement("Resources");
	appendChild(root);
	
	// Leemos los datos desde un archivo de indices
	QFile rscIndex(HOME+"/data/index.rsc");
	
	if( rscIndex.open( QIODevice::ReadOnly | QIODevice::Text))
	{
		QDomDocument doc;
		if ( doc.setContent( &rscIndex ) )
		{
			QDomElement docElem = doc.documentElement();
			
			QDomNode n = docElem.firstChild();
			
			QDomElement resource;
			
			while(!n.isNull())
			{
				QDomElement e = n.toElement();
				if(!e.isNull())
				{
					dDebug() << e.tagName();
					
					QString path = e.attribute("path");
						
					QString name = e.attribute("name");
						
					if( name.isEmpty() )
					{
						QFileInfo finfo(path);
						name = finfo.fileName();
					}
					
					if ( e.tagName() == "Image" )
					{
						resource = createElement("Image");
						resource.setAttribute("filename", name);
						
						addResource( resource, path );
						
						documentElement().appendChild(resource);
					}
					else if ( e.tagName() == "Svg" )
					{
						resource = createElement("Svg");
						resource.setAttribute("filename", name);
						
						addResource( resource, path );
						
						documentElement().appendChild(resource);
					}
					else if ( e.tagName() == "Sourd" )
					{
						resource = createElement("Sourd");
						resource.setAttribute("filename", name);
						
						addResource( resource, path );
						
						documentElement().appendChild(resource);
					}
					
					
				}
				n = n.nextSibling();
			}

		}
		else
		{
			dError() << "Invalid resource index file: " << rscIndex.fileName();
		}
		
		rscIndex.close();
	}
}
コード例 #21
0
QStringList CalculateConfig::getPasswordUsers()
{
	QStringList	result;

	MapConfig	migrateUser;

	QProcess	cl_install;

	QString usersParam;

	foreach( const QString& user, m_Config["gui_users"].toStringList() )
	{
		usersParam += " --user " + user;
	}

	qDebug() << "Start cl-install" +  usersParam + " -v --xml --filter migrate";
	cl_install.start("cl-install" + usersParam + " -v --xml --filter migrate" );

	if ( !cl_install.waitForStarted() )
	{
		qDebug() << "Process not started";
		return QStringList();
	}

	if ( !cl_install.waitForFinished() )
	{
		qDebug() << "Process finished with error";
		return QStringList();
	}

	QString			outVars = cl_install.readAll();

	QDomDocument	xmlVars;
	QString			errMsg;
	int				errLine;
	int				errColumn;

	if ( xmlVars.setContent(outVars, true, &errMsg, &errLine, &errColumn) )
	{
		QDomElement domRoot = xmlVars.documentElement();
		if (domRoot.tagName() == "variables") {
			parseVariables(domRoot, migrateUser);
		} else {
			qDebug() << "Section \"variables\" not found";
			return QStringList();
		}
	}

	if ( migrateUser["cl_migrate_user"].toStringList().count() !=
		migrateUser["cl_migrate_user_pwd"].toStringList().count()
	)
	{
		qDebug() << "Error result";
		return QStringList();
	}

	for ( int i(0); i != migrateUser["cl_migrate_user"].toStringList().count(); ++i )
	{
		if ( migrateUser["cl_migrate_user_pwd"].toStringList().at(i) == "yes" )
			result << migrateUser["cl_migrate_user"].toStringList().at(i);
	}

	return result;
}
コード例 #22
0
ファイル: importopml.cpp プロジェクト: Akon32/leechcraft
	bool ImportOPML::HandleFile (const QString& filename)
	{
		QFile file (filename);
		if (!file.open (QIODevice::ReadOnly))
		{
			QMessageBox::critical (this,
					tr ("LeechCraft"),
					tr ("Could not open file %1 for reading.")
						.arg (filename));
			return false;
		}
	
		QByteArray data = file.readAll ();
		file.close ();
	
		QString errorMsg;
		int errorLine, errorColumn;
		QDomDocument document;
		if (!document.setContent (data,
					true,
					&errorMsg,
					&errorLine,
					&errorColumn))
		{
			QMessageBox::critical (this,
					tr ("LeechCraft"),
					tr ("XML error, file %1, line %2, column %3, error:<br />%4")
						.arg (filename)
						.arg (errorLine)
						.arg (errorColumn)
						.arg (errorMsg));
			return false;
		}
	
		OPMLParser parser (document);
		if (!parser.IsValid ())
		{
			QMessageBox::critical (this,
					tr ("LeechCraft"),
					tr ("OPML from file %1 is not valid.")
						.arg (filename));
			return false;
		}
	
		OPMLParser::OPMLinfo_t info = parser.GetInfo ();
	
		for (OPMLParser::OPMLinfo_t::const_iterator i = info.begin (),
				end = info.end (); i != end; ++i)
		{
			QString name = i.key ();
			QString value = i.value ();
	
			if (name == "title")
				Ui_.Title_->setText (value);
			else if (name == "dateCreated")
				Ui_.Created_->setText (value);
			else if (name == "dateModified")
				Ui_.Edited_->setText (value);
			else if (name == "ownerName")
				Ui_.Owner_->setText (value);
			else if (name == "ownerEmail")
				Ui_.OwnerEmail_->setText (value);
			else
			{
				QStringList strings;
				strings << name << value;
				new QTreeWidgetItem (Ui_.OtherFields_, strings);
			}
		}
	
		OPMLParser::items_container_t items = parser.Parse ();
		for (OPMLParser::items_container_t::const_iterator i = items.begin (),
				end = items.end (); i != end; ++i)
		{
			QStringList strings;
			strings << i->Title_ << i->URL_;
			QTreeWidgetItem *item =
				new QTreeWidgetItem (Ui_.FeedsToImport_, strings);
			item->setData (0, Qt::CheckStateRole, Qt::Checked);
		}
	
		return true;
	}
コード例 #23
0
ファイル: mymoneystoragexml.cpp プロジェクト: CGenie/kmymoney
bool MyMoneyXmlContentHandler::startElement(const QString& /* namespaceURI */, const QString& /* localName */, const QString& qName, const QXmlAttributes & atts)
{
  if (m_level == 0) {
    QString s = qName.toLower();
    if (s == "transaction"
        || s == "account"
        || s == "price"
        || s == "payee"
        || s == "tag"
        || s == "currency"
        || s == "security"
        || s == "keyvaluepairs"
        || s == "institution"
        || s == "report"
        || s == "budget"
        || s == "fileinfo"
        || s == "user"
        || s == "scheduled_tx"
        || s == "onlinejob") {
      m_baseNode = m_doc.createElement(qName);
      for (int i = 0; i < atts.count(); ++i) {
        m_baseNode.setAttribute(atts.qName(i), atts.value(i));
      }
      m_currNode = m_baseNode;
      m_level = 1;

    } else if (s == "transactions") {
      qDebug("reading transactions");
      if (atts.count()) {
        int count = atts.value(QLatin1String("count")).toInt();
        m_reader->signalProgress(0, count, i18n("Loading transactions..."));
        m_elementCount = 0;
      }
    } else if (s == "accounts") {
      qDebug("reading accounts");
      if (atts.count()) {
        int count = atts.value(QLatin1String("count")).toInt();
        m_reader->signalProgress(0, count, i18n("Loading accounts..."));
        m_elementCount = 0;
      }
    } else if (s == "securities") {
      qDebug("reading securities");
      if (atts.count()) {
        int count = atts.value(QLatin1String("count")).toInt();
        m_reader->signalProgress(0, count, i18n("Loading securities..."));
        m_elementCount = 0;
      }
    } else if (s == "currencies") {
      qDebug("reading currencies");
      if (atts.count()) {
        int count = atts.value(QLatin1String("count")).toInt();
        m_reader->signalProgress(0, count, i18n("Loading currencies..."));
        m_elementCount = 0;
      }
    } else if (s == "reports") {
      qDebug("reading reports");
      if (atts.count()) {
        int count = atts.value(QLatin1String("count")).toInt();
        m_reader->signalProgress(0, count, i18n("Loading reports..."));
        m_elementCount = 0;
      }
    } else if (s == "prices") {
      qDebug("reading prices");
      if (atts.count()) {
        int count = atts.value(QLatin1String("count")).toInt();
        m_reader->signalProgress(0, count, i18n("Loading prices..."));
        m_elementCount = 0;
      }
    } else if (s == "pricepair") {
      if (atts.count()) {
        m_reader->d->m_fromSecurity = atts.value(QLatin1String("from"));
        m_reader->d->m_toSecurity = atts.value(QLatin1String("to"));
      }
    }

  } else {
    m_level++;
    QDomElement node = m_doc.createElement(qName);
    for (int i = 0; i < atts.count(); ++i) {
      node.setAttribute(atts.qName(i), atts.value(i));
    }
    m_currNode.appendChild(node);
    m_currNode = node;
  }
  return true;
}
コード例 #24
0
ファイル: petrel.cpp プロジェクト: plus7/TwApiScraper
void Petrel::replyFinished(QNetworkReply *reply)
{
    QNetworkRequest request = reply->request();
    QString replyStr( reply->readAll() );
    int role = request.attribute( (QNetworkRequest::Attribute)(QNetworkRequest::User + ATTR_ROLE) ).toInt();
    QDomDocument doc;
    doc.setContent(replyStr);
    switch(role){
        //autogenerated choice
        case AVAILABLE_TRENDS:
        {
          locations_t l(doc.documentElement());
          emit availableTrendsReceived(l);
          break;
        }
        case BLOCKING_IDS_BLOCKS:
        {
          ids_t i(doc.documentElement());
          emit blocking_IdsBlocksReceived(i);
          break;
        }
        case CREATE_BLOCK:
        {
          user_t u(doc.documentElement());
          emit createBlockReceived(u);
          break;
        }
        case CREATE_FAVORITE:
        {
          status_t s(doc.documentElement());
          emit createFavoriteReceived(s);
          break;
        }
        case CREATE_FRIENDSHIP:
        {
          user_t u(doc.documentElement());
          emit createFriendshipReceived(u);
          break;
        }
        case CREATE_SAVED_SEARCH:
        {
          saved_search_t s(doc.documentElement());
          emit createSavedSearchReceived(s);
          break;
        }
        case DELETE_LIST_ID:
        {
          list_t l(doc.documentElement());
          emit deleteListIdReceived(l);
          break;
        }
        case DELETE_LIST_MEMBER:
        {
          list_t l(doc.documentElement());
          emit deleteListMemberReceived(l);
          break;
        }
        case DELETE_LIST_SUBSCRIBER:
        {
          list_t l(doc.documentElement());
          emit deleteListSubscriberReceived(l);
          break;
        }
        case DESTROY:
        {
          status_t s(doc.documentElement());
          emit destroyReceived(s);
          break;
        }
        case DESTROY_BLOCK:
        {
          user_t u(doc.documentElement());
          emit destroyBlockReceived(u);
          break;
        }
        case DESTROY_DIRECT_MESSAGE:
        {
          direct_message_t d(doc.documentElement());
          emit destroyDirectMessageReceived(d);
          break;
        }
        case DESTROY_FAVORITE:
        {
          status_t s(doc.documentElement());
          emit destroyFavoriteReceived(s);
          break;
        }
        case DESTROY_FRIENDSHIP:
        {
          user_t u(doc.documentElement());
          emit destroyFriendshipReceived(u);
          break;
        }
        case DESTROY_SAVED_SEARCH:
        {
          saved_search_t s(doc.documentElement());
          emit destroySavedSearchReceived(s);
          break;
        }
        case DIRECT_MESSAGES:
        {
          direct_messages_t d(doc.documentElement());
          emit directMessagesReceived(d);
          break;
        }
        case EXISTS_FRIENDSHIPS:
        {
          friends_t f(doc.documentElement());
          emit existsFriendshipsReceived(f);
          break;
        }
        case FAVORITES:
        {
          statuses_t s(doc.documentElement());
          emit favoritesReceived(s);
          break;
        }
        case FOLLOW_NOTIFICATION:
        {
          user_t u(doc.documentElement());
          emit followNotificationReceived(u);
          break;
        }
        case FOLLOWERS:
        {
          users_t u(doc.documentElement());
          emit followersReceived(u,0,0); // temp
          break;
        }
        case FRIENDS:
        {
          users_t u(doc.documentElement());
          emit friendsReceived(u,0,0); // temp
          break;
        }
        case FRIENDS_TIMELINE:
        {
          statuses_t s(doc.documentElement());
          emit friendsTimelineReceived(s);
          break;
        }
        case GET_LIST_ID:
        {
          list_t l(doc.documentElement());
          emit getListIdReceived(l);
          break;
        }
        case GET_LIST_MEMBERS:
        {
          users_list_t u(doc.documentElement());
          emit getListMembersReceived(u);
          break;
        }
        case GET_LIST_MEMBERS_ID:
        {
          user_t u(doc.documentElement());
          emit getListMembersIdReceived(u);
          break;
        }
        case GET_LIST_MEMBERSHIPS:
        {
          lists_list_t l(doc.documentElement());
          emit getListMembershipsReceived(l);
          break;
        }
        case GET_LIST_STATUSES:
        {
          statuses_t s(doc.documentElement());
          emit getListStatusesReceived(s);
          break;
        }
        case GET_LIST_SUBSCRIBERS:
        {
          users_list_t u(doc.documentElement());
          emit getListSubscribersReceived(u);
          break;
        }
        case GET_LIST_SUBSCRIBERS_ID:
        {
          user_t u(doc.documentElement());
          emit getListSubscribersIdReceived(u);
          break;
        }
        case GET_LIST_SUBSCRIPTIONS:
        {
          lists_list_t l(doc.documentElement());
          emit getListSubscriptionsReceived(l);
          break;
        }
        case GET_LISTS:
        {
          lists_list_t l(doc.documentElement());
          emit getListsReceived(l);
          break;
        }
        case HOME_TIMELINE:
        {
          statuses_t s(doc.documentElement());
          emit homeTimelineReceived(s);
          break;
        }
        case IDS_FOLLOWERS:
        {
          id_list_t i(doc.documentElement());
          emit idsFollowersReceived(i);
          break;
        }
        case IDS_FRIENDS:
        {
          id_list_t i(doc.documentElement());
          emit idsFriendsReceived(i);
          break;
        }
        case LEAVE_NOTIFICATION:
        {
          user_t u(doc.documentElement());
          emit leaveNotificationReceived(u);
          break;
        }
        case LOCATION_TRENDS:
        {
          matching_trends_t m(doc.documentElement());
          emit locationTrendsReceived(m);
          break;
        }
        case MENTIONS:
        {
          statuses_t s(doc.documentElement());
          emit mentionsReceived(s);
          break;
        }
        case NEW_DIRECT_MESSAGE:
        {
          direct_message_t d(doc.documentElement());
          emit newDirectMessageReceived(d);
          break;
        }
        case POST_LIST:
        {
          list_t l(doc.documentElement());
          emit postListReceived(l);
          break;
        }
        case POST_LIST_MEMBER:
        {
          list_t l(doc.documentElement());
          emit postListMemberReceived(l);
          break;
        }
        case POST_LIST_SUBSCRIBER:
        {
          list_t l(doc.documentElement());
          emit postListSubscriberReceived(l);
          break;
        }
        case POST_LISTS_ID:
        {
          list_t l(doc.documentElement());
          emit postListsIdReceived(l);
          break;
        }
        case PUBLIC_TIMELINE:
        {
          statuses_t s(doc.documentElement());
          emit publicTimelineReceived(s);
          break;
        }
        case RATE_LIMIT_STATUS:
        {
          hash_t h(doc.documentElement());
          emit rateLimitStatusReceived(h);
          break;
        }
        case REPORT_SPAM:
        {
          user_t u(doc.documentElement());
          emit reportSpamReceived(u);
          break;
        }
        case RETWEET:
        {
          status_t s(doc.documentElement());
          emit retweetReceived(s);
          break;
        }
        case RETWEETED_BY_ME:
        {
          statuses_t s(doc.documentElement());
          emit retweetedByMeReceived(s);
          break;
        }
        case RETWEETED_TO_ME:
        {
          statuses_t s(doc.documentElement());
          emit retweetedToMeReceived(s);
          break;
        }
        case RETWEETS:
        {
          statuses_t s(doc.documentElement());
          emit retweetsReceived(s);
          break;
        }
        case RETWEETS_OF_ME:
        {
          statuses_t s(doc.documentElement());
          emit retweetsOfMeReceived(s);
          break;
        }
        case SAVED_SEARCHES:
        {
          saved_searches_t s(doc.documentElement());
          emit savedSearchesReceived(s);
          break;
        }
        case SEARCH_USERS:
        {
          users_t u(doc.documentElement());
          emit searchUsersReceived(u);
          break;
        }
        case SENT_DIRECT_MESSAGES:
        {
          direct_messages_t d(doc.documentElement());
          emit sentDirectMessagesReceived(d);
          break;
        }
        case SHOW:
        {
          status_t s(doc.documentElement());
          emit showReceived(s);
          break;
        }
        case SHOW_FRIENDSHIPS:
        {
          relationship_t r(doc.documentElement());
          emit showFriendshipsReceived(r);
          break;
        }
        case SHOW_SAVED_SEARCH:
        {
          saved_search_t s(doc.documentElement());
          emit showSavedSearchReceived(s);
          break;
        }
        case SHOW_USERS:
        {
          user_t u(doc.documentElement());
          emit showUsersReceived(u);
          break;
        }
        case TEST_HELP:
        {
          ok_t o(doc.documentElement());
          emit testHelpReceived(o);
          break;
        }
        case UPDATE:
        {
          status_t s(doc.documentElement());
          emit updateReceived(s);
          break;
        }
        case UPDATE_DELIVERY_DEVICE:
        {
          user_t u(doc.documentElement());
          emit updateDeliveryDeviceReceived(u);
          break;
        }
        case UPDATE_PROFILE:
        {
          user_t u(doc.documentElement());
          emit updateProfileReceived(u);
          break;
        }
        case UPDATE_PROFILE_BACKGROUND_IMAGE:
        {
          user_t u(doc.documentElement());
          emit updateProfileBackgroundImageReceived(u);
          break;
        }
        case UPDATE_PROFILE_COLOR:
        {
          user_t u(doc.documentElement());
          emit updateProfileColorReceived(u);
          break;
        }
        case UPDATE_PROFILE_IMAGE:
        {
          user_t u(doc.documentElement());
          emit updateProfileImageReceived(u);
          break;
        }
        case USER_TIMELINE:
        {
          statuses_t s(doc.documentElement());
          emit userTimelineReceived(s);
          break;
        }
        case VERIFY_CREDENTIALS:
        {
          user_t u(doc.documentElement());
          emit verifyCredentialsReceived(u);
          break;
        }

    }
    reply->deleteLater();
}
コード例 #25
0
void MyMoneyInstitutionTest::testReadXML() {
	MyMoneyInstitution i;
	QString ref_ok = QString(
		"<!DOCTYPE TEST>\n"
		"<INSTITUTION-CONTAINER>\n"
		" <INSTITUTION sortcode=\"sortcode\" id=\"I00001\" manager=\"manager\" name=\"name\" >\n"
		"  <ADDRESS street=\"street\" zip=\"postcode\" city=\"town\" telephone=\"telephone\" />\n"
		"  <ACCOUNTIDS>\n"
		"   <ACCOUNTID id=\"A000001\" />\n"
		"   <ACCOUNTID id=\"A000003\" />\n"
		"  </ACCOUNTIDS>\n"
                "  <KEYVALUEPAIRS>\n"
                "   <PAIR key=\"key\" value=\"value\" />\n"
                "  </KEYVALUEPAIRS>\n"
		" </INSTITUTION>\n"
		"</INSTITUTION-CONTAINER>\n");

	QString ref_false = QString(
		"<!DOCTYPE TEST>\n"
		"<INSTITUTION-CONTAINER>\n"
		" <KINSTITUTION sortcode=\"sortcode\" id=\"I00001\" manager=\"manager\" name=\"name\" >\n"
		"  <ADDRESS street=\"street\" zip=\"postcode\" city=\"town\" telephone=\"telephone\" />\n"
		"  <ACCOUNTIDS>\n"
		"   <ACCOUNTID id=\"A000001\" />\n"
		"   <ACCOUNTID id=\"A000003\" />\n"
		"  </ACCOUNTIDS>\n"
		" </KINSTITUTION>\n"
		"</INSTITUTION-CONTAINER>\n");

	QDomDocument doc;
	QDomElement node;

	doc.setContent(ref_false);
	node = doc.documentElement().firstChild().toElement();
	try {
		i = MyMoneyInstitution(node);
		CPPUNIT_FAIL("Missing expected exception");
	} catch(MyMoneyException *e) {
		delete e;
	}

	i.addAccountId("TEST");

	doc.setContent(ref_ok);
	node = doc.documentElement().firstChild().toElement();
	try {
		QStringList alist;
		alist << "A000001" << "A000003";
		i = MyMoneyInstitution(node);

		CPPUNIT_ASSERT(i.sortcode() == "sortcode");
		CPPUNIT_ASSERT(i.id() == "I00001");
		CPPUNIT_ASSERT(i.manager() == "manager");
		CPPUNIT_ASSERT(i.name() == "name");
		CPPUNIT_ASSERT(i.street() == "street");
		CPPUNIT_ASSERT(i.postcode() == "postcode");
		CPPUNIT_ASSERT(i.city() == "town");
		CPPUNIT_ASSERT(i.telephone() == "telephone");
		CPPUNIT_ASSERT(i.accountList() == alist);
		CPPUNIT_ASSERT(i.value(QString("key")) == "value");

	} catch(MyMoneyException *e) {
		delete e;
		CPPUNIT_FAIL("Unexpected exception");
	}
}
コード例 #26
0
ファイル: xspfloader.cpp プロジェクト: Pritoj/tomahawk
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 ( unsigned 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" )
            {
                url = n.text();
            }
        }

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

        query_ptr q = Tomahawk::Query::get( artist, track, album, uuid(), false );
        q->setDuration( duration.toInt() / 1000 );
        if ( !url.isEmpty() )
            q->setResultHint( url );

        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 )
    {
        m_playlist = Playlist::create( SourceList::instance()->getLocal(),
                                       uuid(),
                                       m_title,
                                       m_info,
                                       m_creator,
                                       false,
                                       m_entries );

        // 10 minute default---for now, no way to change it
        new Tomahawk::XspfUpdater( m_playlist, 6000000, m_autoUpdate, m_url.toString() );
        deleteLater();
    }

    emit ok( m_playlist );
}
コード例 #27
0
void QgsWFSCapabilities::capabilitiesReplyFinished()
{
  QNetworkReply *reply = mCapabilitiesReply;
  reply->deleteLater();
  mCapabilitiesReply = 0;

  // handle network errors
  if ( reply->error() != QNetworkReply::NoError )
  {
    mErrorCode = QgsWFSCapabilities::NetworkError;
    mErrorMessage = reply->errorString();
    emit gotCapabilities();
    return;
  }

  // handle HTTP redirects
  QVariant redirect = reply->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 = QgsNetworkAccessManager::instance()->get( request );

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

  QByteArray buffer = reply->readAll();

  QgsDebugMsg( "parsing capabilities: " + buffer );

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

  QDomElement doc = capabilitiesDocument.documentElement();

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

  mCaps.clear();

  //test wfs version
  QString version = capabilitiesDocument.documentElement().attribute( "version" );
  if ( version != "1.0.0" && version != "1.0" )
  {
    mErrorCode = WFSVersionNotSupported;
    mErrorMessage = tr( "Either the WFS server does not support WFS version 1.0.0 or the WFS url is wrong" );
    emit gotCapabilities();
    return;
  }

  // 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 );
  }

  emit gotCapabilities();
}
コード例 #28
0
ファイル: mainwindow.cpp プロジェクト: idaohang/GPSeg
void MainWindow::tableview_generations_clicked(QModelIndex index)
{
    QStandardItem *item = _modelGenerations->itemFromIndex(index);
    item->column();
    qDebug() << "clicked signal";
    qDebug() << item->text();

    QDomDocument doc;
    QString filename = _strLogDir + "/" + item->text();
    QFile file(filename);
    if (!file.open(QIODevice::ReadOnly))
    {   qDebug() << "Fail to open file...";
        return;
    }
    if (!doc.setContent(&file)) {
        qDebug() << "Fail to populize domdocument...";
        file.close();
        return;
    }
    file.close();

    // clear old model
    _modelIndividuals->clear();
    _genos.clear();

    // initialize view header
    QStringList strList;
    strList.append("Fitness");
    strList.append("Size");
    strList.append("Depth");
    //strList.append("Genotype");
    _modelIndividuals->setHorizontalHeaderLabels(strList);

    // get individuals
    QDomNodeList individuals = doc.elementsByTagName("Individual");

    // for each individual get fitness value and genotype
    for(int i = 0; i < individuals.size(); i++)
    {
        QDomElement individual = individuals.at(i).toElement();
        int indi_size = individual.attribute("size").toInt();

        QDomElement elem = individual.firstChildElement();
        QString fitness = elem.text();

        for (int j = 0; j < indi_size; j++)
        {
            elem = elem.nextSiblingElement();
            // add individual index
            QList<QStandardItem *> items;
            items.append(new QStandardItem( fitness ));
            items.append(new QStandardItem( elem.attribute("size") ));
            items.append(new QStandardItem( elem.attribute("depth") ));
            QString str;
            QTextStream stream(&str);
            stream << elem.firstChildElement();
            stream.flush();

            //items.append(new QStandardItem( str.trimmed() ));
            _genos.append(str);
            _modelIndividuals->appendRow(items);
        }

    }
    ui->tableView_Individuals->resizeColumnsToContents();
    ui->tableView_Individuals->sortByColumn(0);
}
コード例 #29
0
ファイル: osmimport.cpp プロジェクト: lbovard/covise
bool OsmImport::parseDoc(QDomDocument &doc)
{

    QDomNodeList list = doc.elementsByTagName("node");
    for (int i = 0; i < list.count(); i++)
    {
        nodes.append(new osmNode(list.at(i).toElement()));
    }
    list = doc.elementsByTagName("way");
    for (int i = 0; i < list.count(); i++)
    {
        ways.append(new osmWay(list.at(i).toElement(), nodes));
    }
    
    bool importPrimary();
    bool importSecondary();
    bool importTertiary();
    bool importMotorway();
    bool importService();
    bool importPath();
    bool importSteps();
    bool importTrack();
    bool importFootway();
    bool importResidential();
    bool importLiving_street();
    bool importCycleway();
    bool importTurning_circle();
    bool importPedestrian();
    bool importUnclassified();
    bool doPrimary = ImportSettings::instance()->importPrimary();
    bool doSecondary = ImportSettings::instance()->importSecondary();
    bool doTertiary = ImportSettings::instance()->importTertiary();
    bool doMotorway = ImportSettings::instance()->importMotorway();
    bool doService = ImportSettings::instance()->importService();
    bool doPath = ImportSettings::instance()->importPath();
    bool doSteps = ImportSettings::instance()->importSteps();
    bool doTrack = ImportSettings::instance()->importTrack();
    bool doFootpath = ImportSettings::instance()->importFootway();
    bool doResidential = ImportSettings::instance()->importResidential();
    bool doLiving_street = ImportSettings::instance()->importLiving_street();
    bool doCycleway = ImportSettings::instance()->importCycleway();
    bool doTurning_circle = ImportSettings::instance()->importTurning_circle();
    bool doPedestrian = ImportSettings::instance()->importPedestrian();
    bool doUnclassified = ImportSettings::instance()->importUnclassified();
    for (int i = 0; i < ways.count(); i++)
    {
        osmWay *w = ways.at(i);
        osmWay::wayType t = w->type;

        if ((t == osmWay::primary && doPrimary) ||
            (t == osmWay::secondary && doSecondary) ||
            (t == osmWay::tertiary && doTertiary) ||
            (t == osmWay::motorway && doMotorway) ||
            (t == osmWay::service && doService) ||
            (t == osmWay::path && doPath) ||
            (t == osmWay::steps && doSteps) ||
            (t == osmWay::track && doTrack) ||
            (t == osmWay::footway && doFootpath) ||
            (t == osmWay::residential && doResidential) ||
            (t == osmWay::living_street && doLiving_street) ||
            (t == osmWay::cycleway && doCycleway) ||
            (t == osmWay::turning_circle && doTurning_circle) ||
            (t == osmWay::pedestrian && doPedestrian) ||
            (t == osmWay::unclassified && doUnclassified))
        {
            project->XVector = w->XVector;
            project->YVector = w->YVector;
            project->ZVector = w->ZVector;
            if (project->XVector.size() > 0)
            {
                project->addLineStrip(w->name,w->maxSpeed,w->bridge,w->numLanes,w->type);
            }
        }
    }
    qDeleteAll(ways.begin(), ways.end());
    qDeleteAll(nodes.begin(), nodes.end());
    ways.clear();
    nodes.clear();
    // resize
    BoundingBoxVisitor *visitor = new BoundingBoxVisitor();
    project->getProjectData()->getRoadSystem()->accept(visitor);
    project->getProjectData()->getScenerySystem()->accept(visitor);
    QRectF box = visitor->getBoundingBox();
    SetProjectDimensionsCommand *command = new SetProjectDimensionsCommand(project->getProjectData(), box.bottom() + 0.1 * box.height(), box.top() - 0.1 * box.height(), box.right() + 0.1 * box.width(), box.left() - 0.1 * box.width());
    project->getProjectSettings()->executeCommand(command);

    return true;
}
コード例 #30
0
ファイル: qgswcsgetcapabilities.cpp プロジェクト: CS-SI/QGIS
  QDomElement getServiceElement( QDomDocument &doc, const QgsProject *project )
  {
    //Service element
    QDomElement serviceElem = doc.createElement( QStringLiteral( "Service" ) );

    //Service name
    QDomElement nameElem = doc.createElement( QStringLiteral( "name" ) );
    QDomText nameText = doc.createTextNode( "WCS" );
    nameElem.appendChild( nameText );
    serviceElem.appendChild( nameElem );

    QString title = QgsServerProjectUtils::owsServiceTitle( *project );
    if ( !title.isEmpty() )
    {
      QDomElement titleElem = doc.createElement( QStringLiteral( "label" ) );
      QDomText titleText = doc.createTextNode( title );
      titleElem.appendChild( titleText );
      serviceElem.appendChild( titleElem );
    }

    QString abstract = QgsServerProjectUtils::owsServiceAbstract( *project );
    if ( !abstract.isEmpty() )
    {
      QDomElement abstractElem = doc.createElement( QStringLiteral( "description" ) );
      QDomText abstractText = doc.createCDATASection( abstract );
      abstractElem.appendChild( abstractText );
      serviceElem.appendChild( abstractElem );
    }

    QStringList keywords = QgsServerProjectUtils::owsServiceKeywords( *project );
    if ( !keywords.isEmpty() )
    {
      QDomElement keywordsElem = doc.createElement( QStringLiteral( "keywords" ) );
      for ( int i = 0; i < keywords.size(); ++i )
      {
        QDomElement keywordElem = doc.createElement( QStringLiteral( "keyword" ) );
        QDomText keywordText = doc.createTextNode( keywords.at( i ) );
        keywordElem.appendChild( keywordText );
        keywordsElem.appendChild( keywordElem );
      }
      serviceElem.appendChild( keywordsElem );
    }


    QString contactPerson = QgsServerProjectUtils::owsServiceContactPerson( *project );
    QString contactOrganization = QgsServerProjectUtils::owsServiceContactOrganization( *project );
    QString contactPosition = QgsServerProjectUtils::owsServiceContactPosition( *project );
    QString contactMail = QgsServerProjectUtils::owsServiceContactMail( *project );
    QString contactPhone = QgsServerProjectUtils::owsServiceContactPhone( *project );
    QString onlineResource = QgsServerProjectUtils::owsServiceOnlineResource( *project );
    if ( !contactPerson.isEmpty() ||
         !contactOrganization.isEmpty() ||
         !contactPosition.isEmpty() ||
         !contactMail.isEmpty() ||
         !contactPhone.isEmpty() ||
         !onlineResource.isEmpty() )
    {
      QDomElement responsiblePartyElem = doc.createElement( QStringLiteral( "responsibleParty" ) );
      if ( !contactPerson.isEmpty() )
      {
        QDomElement contactPersonElem = doc.createElement( QStringLiteral( "individualName" ) );
        QDomText contactPersonText = doc.createTextNode( contactPerson );
        contactPersonElem.appendChild( contactPersonText );
        responsiblePartyElem.appendChild( contactPersonElem );
      }
      if ( !contactOrganization.isEmpty() )
      {
        QDomElement contactOrganizationElem = doc.createElement( QStringLiteral( "organisationName" ) );
        QDomText contactOrganizationText = doc.createTextNode( contactOrganization );
        contactOrganizationElem.appendChild( contactOrganizationText );
        responsiblePartyElem.appendChild( contactOrganizationElem );
      }
      if ( !contactPosition.isEmpty() )
      {
        QDomElement contactPositionElem = doc.createElement( QStringLiteral( "positionName" ) );
        QDomText contactPositionText = doc.createTextNode( contactPosition );
        contactPositionElem.appendChild( contactPositionText );
        responsiblePartyElem.appendChild( contactPositionElem );
      }
      if ( !contactMail.isEmpty() ||
           !contactPhone.isEmpty() ||
           !onlineResource.isEmpty() )
      {
        QDomElement contactInfoElem = doc.createElement( QStringLiteral( "contactInfo" ) );
        if ( !contactMail.isEmpty() )
        {
          QDomElement contactAddressElem = doc.createElement( QStringLiteral( "address" ) );
          QDomElement contactAddressMailElem = doc.createElement( QStringLiteral( "electronicMailAddress" ) );
          QDomText contactAddressMailText = doc.createTextNode( contactMail );
          contactAddressMailElem.appendChild( contactAddressMailText );
          contactAddressElem.appendChild( contactAddressMailElem );
          contactInfoElem.appendChild( contactAddressElem );
        }
        if ( !contactPhone.isEmpty() )
        {
          QDomElement contactPhoneElem = doc.createElement( QStringLiteral( "phone" ) );
          QDomElement contactVoiceElem = doc.createElement( QStringLiteral( "voice" ) );
          QDomText contactVoiceText = doc.createTextNode( contactPhone );
          contactVoiceElem.appendChild( contactVoiceText );
          contactPhoneElem.appendChild( contactVoiceElem );
          contactInfoElem.appendChild( contactPhoneElem );
        }
        if ( !onlineResource.isEmpty() )
        {
          QDomElement onlineResourceElem = doc.createElement( QStringLiteral( "onlineResource" ) );
          onlineResourceElem.setAttribute( QStringLiteral( "xmlns:xlink" ), QStringLiteral( "http://www.w3.org/1999/xlink" ) );
          onlineResourceElem.setAttribute( QStringLiteral( "xlink:type" ), QStringLiteral( "simple" ) );
          onlineResourceElem.setAttribute( QStringLiteral( "xlink:href" ), onlineResource );
          contactInfoElem.appendChild( onlineResourceElem );
        }
        responsiblePartyElem.appendChild( contactInfoElem );
      }
      serviceElem.appendChild( responsiblePartyElem );
    }

    QDomElement feesElem = doc.createElement( QStringLiteral( "fees" ) );
    QDomText feesText = doc.createTextNode( QStringLiteral( "None" ) ); // default value if fees are unknown
    QString fees = QgsServerProjectUtils::owsServiceFees( *project );
    if ( !fees.isEmpty() )
    {
      feesText = doc.createTextNode( fees );
    }
    feesElem.appendChild( feesText );
    serviceElem.appendChild( feesElem );

    QDomElement accessConstraintsElem = doc.createElement( QStringLiteral( "accessConstraints" ) );
    QDomText accessConstraintsText = doc.createTextNode( QStringLiteral( "None" ) ); // default value if access constraints are unknown
    QString accessConstraints = QgsServerProjectUtils::owsServiceAccessConstraints( *project );
    if ( !accessConstraints.isEmpty() )
    {
      accessConstraintsText = doc.createTextNode( accessConstraints );
    }
    accessConstraintsElem.appendChild( accessConstraintsText );
    serviceElem.appendChild( accessConstraintsElem );

    //End
    return serviceElem;
  }