void RgLineVectorLayerSettingsWidget::on_mcbLayers_selectItem()
{
  mcbDirection->clear();
  mcbSpeed->clear();

  mcbDirection->insertItem( 0, tr( "Always use default" ) );
  mcbSpeed->insertItem( 0, tr( "Always use default" ) );

  QgsVectorLayer* vl = selectedLayer();
  if ( !vl )
    return;

  QgsVectorDataProvider* provider = vl->dataProvider();
  if ( !provider )
    return;

  const QgsFields& fields = provider->fields();
  for ( int idx = 0; idx < fields.count(); ++idx )
  {
    const QgsField& currentField = fields[idx];
    QVariant currentType = currentField.type();
    if ( currentType == QVariant::Int || currentType == QVariant::String )
    {
      mcbDirection->insertItem( 1, currentField.name() );
    }
    if ( currentType == QVariant::Int || currentType == QVariant::Double )
    {
      mcbSpeed->insertItem( 1, currentField.name() );
    }
  }

} // RgDSettingsDlg::on_mcbLayers_selectItem()
void RgLineVectorLayerSettingsWidget::on_mcbLayers_selectItem()
{
  mcbDirection->clear();
  mcbSpeed->clear();

  mcbDirection->insertItem( 0, tr( "Always use default" ) );
  mcbSpeed->insertItem( 0, tr( "Always use default" ) );

  QgsVectorLayer* vl = selectedLayer();
  if ( !vl )
    return;

  QgsVectorDataProvider* provider = vl->dataProvider();
  if ( !provider )
    return;

  const QgsFieldMap& fields = provider->fields();
  QgsFieldMap::const_iterator it;
  for ( it = fields.constBegin(); it != fields.constEnd(); ++it )
  {
    QgsField currentField = it.value();
    QVariant currentType = currentField.type();
    if ( currentType == QVariant::Int || currentType == QVariant::String )
    {
      mcbDirection->insertItem( 1, currentField.name() );
    }
    if ( currentType == QVariant::Int || currentType == QVariant::Double )
    {
      mcbSpeed->insertItem( 1, currentField.name() );
    }
  }

} // RgDSettingsDlg::on_mcbLayers_selectItem()
bool QgsZonalStatisticsDialog::prefixIsValid( const QString& prefix ) const
{
    QgsVectorLayer* vl = polygonLayer();
    if ( !vl )
    {
        return false;
    }
    QgsVectorDataProvider* dp = vl->dataProvider();
    if ( !dp )
    {
        return false;
    }

    QString currentFieldName;

    Q_FOREACH ( const QgsField& field, dp->fields() )
    {
        currentFieldName = field.name();
        if ( currentFieldName == ( prefix + "mean" ) || currentFieldName == ( prefix + "sum" ) || currentFieldName == ( prefix + "count" ) )
        {
            return false;
        }
    }
    return true;
}
bool QgsZonalStatisticsDialog::prefixIsValid( const QString& prefix ) const
{
  QgsVectorLayer* vl = polygonLayer();
  if ( !vl )
  {
    return false;
  }
  QgsVectorDataProvider* dp = vl->dataProvider();
  if ( !dp )
  {
    return false;
  }

  QgsFieldMap providerFieldMap = dp->fields();
  QgsFieldMap::const_iterator it = providerFieldMap.constBegin();
  QString currentFieldName;

  for ( ; it != providerFieldMap.constEnd(); ++it )
  {
    currentFieldName = it.value().name();
    if ( currentFieldName == ( prefix + "mean" ) || currentFieldName == ( prefix + "sum" ) || currentFieldName == ( prefix + "count" ) )
    {
      return false;
    }
  }
  return true;
}
bool QgsZonalStatisticsDialog::prefixIsValid( const QString& prefix ) const
{
  QgsVectorLayer* vl = polygonLayer();
  if ( !vl )
  {
    return false;
  }
  QgsVectorDataProvider* dp = vl->dataProvider();
  if ( !dp )
  {
    return false;
  }

  const QgsFields& providerFields = dp->fields();
  QString currentFieldName;

  for ( int idx = 0; idx < providerFields.count(); ++idx )
  {
    currentFieldName = providerFields[idx].name();
    if ( currentFieldName == ( prefix + "mean" ) || currentFieldName == ( prefix + "sum" ) || currentFieldName == ( prefix + "count" ) )
    {
      return false;
    }
  }
  return true;
}
Example #6
0
QString QgsZonalStatistics::getUniqueFieldName( const QString &fieldName, const QList<QgsField> &newFields )
{
  QgsVectorDataProvider *dp = mPolygonLayer->dataProvider();

  if ( !dp->storageType().contains( QLatin1String( "ESRI Shapefile" ) ) )
  {
    return fieldName;
  }

  QList<QgsField> allFields = dp->fields().toList();
  allFields.append( newFields );
  QString shortName = fieldName.mid( 0, 10 );

  bool found = false;
  for ( int idx = 0; idx < allFields.count(); ++idx )
  {
    if ( shortName == allFields.at( idx ).name() )
    {
      found = true;
      break;
    }
  }

  if ( !found )
  {
    return shortName;
  }

  int n = 1;
  shortName = QStringLiteral( "%1_%2" ).arg( fieldName.mid( 0, 8 ) ).arg( n );
  found = true;
  while ( found )
  {
    found = false;
    for ( int idx = 0; idx < allFields.count(); ++idx )
    {
      if ( shortName == allFields.at( idx ).name() )
      {
        n += 1;
        if ( n < 9 )
        {
          shortName = QStringLiteral( "%1_%2" ).arg( fieldName.mid( 0, 8 ) ).arg( n );
        }
        else
        {
          shortName = QStringLiteral( "%1_%2" ).arg( fieldName.mid( 0, 7 ) ).arg( n );
        }
        found = true;
      }
    }
  }
  return shortName;
}
Example #7
0
QString QgsZonalStatistics::getUniqueFieldName( const QString& fieldName )
{
  QgsVectorDataProvider* dp = mPolygonLayer->dataProvider();

  if ( !dp->storageType().contains( "ESRI Shapefile" ) )
  {
    return fieldName;
  }

  const QgsFields& providerFields = dp->fields();
  QString shortName = fieldName.mid( 0, 10 );

  bool found = false;
  for ( int idx = 0; idx < providerFields.count(); ++idx )
  {
    if ( shortName == providerFields[idx].name() )
    {
      found = true;
      break;
    }
  }

  if ( !found )
  {
    return shortName;
  }

  int n = 1;
  shortName = QString( "%1_%2" ).arg( fieldName.mid( 0, 8 ) ).arg( n );
  found = true;
  while ( found )
  {
    found = false;
    for ( int idx = 0; idx < providerFields.count(); ++idx )
    {
      if ( shortName == providerFields[idx].name() )
      {
        n += 1;
        if ( n < 9 )
        {
          shortName = QString( "%1_%2" ).arg( fieldName.mid( 0, 8 ) ).arg( n );
        }
        else
        {
          shortName = QString( "%1_%2" ).arg( fieldName.mid( 0, 7 ) ).arg( n );
        }
        found = true;
      }
    }
  }
  return shortName;
}
Example #8
0
int OptVectorLayer::addFeatureWithDefaultValue( OptFeature& f )
{
//{zhangliye2715:api}
  if ( !isEditable() )
  {
    startEditing();
  }

  // add the fields to the QgsFeature
  QgsVectorDataProvider* provider = dataProvider();
  const QgsFieldMap fields = provider->fields();

  for ( QgsFieldMap::const_iterator it = fields.begin(); it != fields.end(); ++it )
  {
    f.addAttribute( it.key(), provider->defaultValue( it.key() ) );
  }

  int id = -1;
  id = OptVectorLayer::addFeature( f );
  if ( id != -1 )
  {
    //add points to other features to keep topology up-to-date
    int topologicalEditing = QgsProject::instance()->readNumEntry( "Digitizing", "/TopologicalEditing", 0 );

    if( topologicalEditing )
    {
      addTopologicalPoints( f.geometry() );
    }
  }
  else
  {
    return -1;
  }

  //vlayer->setModified(true);
  //commit or rollBack the change
  if ( isModified() )
  {
    commitChanges();
  }
  else
  {
    rollBack();
    return -1;
  }

  //make the layer still editable for the next adding operation
  startEditing();

  return id;
}
void QgsInterpolationDialog::on_mInputLayerComboBox_currentIndexChanged( const QString& text )
{
  Q_UNUSED( text );
  mInterpolationAttributeComboBox->clear();
  mUseZCoordCheckBox->setEnabled( false );

  //get current vector layer
  QString currentComboText = mInputLayerComboBox->currentText();
  QgsVectorLayer* theVectorLayer = vectorLayerFromName( currentComboText );

  if ( !theVectorLayer )
  {
    return;
  }

  QgsVectorDataProvider* provider = theVectorLayer->dataProvider();
  if ( !provider )
  {
    return;
  }

  //find out if the layer has 25D type
  QGis::WkbType geomType = provider->geometryType();
  if ( geomType == QGis::WKBPoint25D ||
       geomType == QGis::WKBLineString25D ||
       geomType == QGis::WKBPolygon25D ||
       geomType == QGis::WKBMultiPoint25D ||
       geomType == QGis::WKBMultiLineString25D ||
       geomType == QGis::WKBMultiPolygon25D )
  {
    mUseZCoordCheckBox->setEnabled( true );
  }

  //insert numeric attributes of layer into mInterpolationAttributesComboBox
  const QgsFields& fields = provider->fields();
  for ( int idx = 0; idx < fields.count(); ++idx )
  {
    const QgsField& currentField = fields[idx];
    QVariant::Type currentType = currentField.type();
    if ( currentType == QVariant::Int || currentType == QVariant::Double )
    {
      mInterpolationAttributeComboBox->insertItem( 0, currentField.name() );
    }
  }
}
Example #10
0
QgsAddJoinDialog::QgsAddJoinDialog( QgsVectorLayer* layer, QWidget * parent, Qt::WindowFlags f ): QDialog( parent, f ), mLayer( layer )
{
  setupUi( this );

  if ( !mLayer )
  {
    return;
  }

  //insert possible vector layers into mJoinLayerComboBox

  mJoinLayerComboBox->blockSignals( true );
  const QMap<QString, QgsMapLayer*>& layerList = QgsMapLayerRegistry::instance()->mapLayers();
  QMap<QString, QgsMapLayer*>::const_iterator layerIt = layerList.constBegin();
  for ( ; layerIt != layerList.constEnd(); ++layerIt )
  {
    QgsMapLayer* currentLayer = layerIt.value();
    if ( currentLayer->type() == QgsMapLayer::VectorLayer )
    {
      QgsVectorLayer* currentVectorLayer = dynamic_cast<QgsVectorLayer*>( currentLayer );
      if ( currentVectorLayer && currentVectorLayer != mLayer )
      {
        if ( currentVectorLayer->dataProvider() && currentVectorLayer->dataProvider()->supportsSubsetString() )
          mJoinLayerComboBox->addItem( currentLayer->name(), QVariant( currentLayer->id() ) );
      }
    }
  }
  mJoinLayerComboBox->blockSignals( false );
  on_mJoinLayerComboBox_currentIndexChanged( mJoinLayerComboBox->currentIndex() );

  //insert possible target fields
  QgsVectorDataProvider* provider = mLayer->dataProvider();
  if ( provider )
  {
    const QgsFields& layerFields = provider->fields();
    for ( int idx = 0; idx < layerFields.count(); ++idx )
    {
      mTargetFieldComboBox->addItem( layerFields[idx].name(), idx );
    }
  }

  mCacheInMemoryCheckBox->setChecked( true );
}
QgsUniqueValueDialog::QgsUniqueValueDialog( QgsVectorLayer* vl ): QDialog(), mVectorLayer( vl ), sydialog( vl, true )
{
  setupUi( this );
  setOrientation( Qt::Vertical );

  //find out the fields of mVectorLayer
  if ( mVectorLayer )
  {
    //we cannot use unique values for not-commited fields because QgsVectorLayer has no 'unique values' method...
    QgsVectorDataProvider* provider = mVectorLayer->dataProvider();
    if ( provider )
    {
      const QgsFieldMap & fields = provider->fields();
      QString str;

      for ( QgsFieldMap::const_iterator it = fields.begin(); it != fields.end(); ++it )
      {
        str = ( *it ).name();
        str = mVectorLayer->attributeDisplayName( it.key() );
        mClassificationComboBox->addItem( str, it.key() );
      }
    }
  }


  mClassListWidget->setSelectionMode( QAbstractItemView::ExtendedSelection );
  mClassListWidget->setEditTriggers( QAbstractItemView::DoubleClicked | QAbstractItemView::EditKeyPressed | QAbstractItemView::AnyKeyPressed );
  mClassListWidget->setSortingEnabled( true );

  if ( mVectorLayer )
  {
    const QgsUniqueValueRenderer* renderer = dynamic_cast<const QgsUniqueValueRenderer *>( mVectorLayer->renderer() );

    if ( renderer )
    {
      mClassListWidget->clear();
      QString field = mVectorLayer->attributeDisplayName( renderer->classificationField() );
      mOldClassificationAttribute = field;
      mClassificationComboBox->setCurrentIndex( mClassificationComboBox->findText( field ) );

      const QList<QgsSymbol*> list = renderer->symbols();
      //fill the items of the renderer into mValues
      for ( QList<QgsSymbol*>::const_iterator iter = list.begin(); iter != list.end(); ++iter )
      {
        QgsSymbol* symbol = *iter;
        QString symbolvalue = symbol->lowerValue();
        QgsSymbol* sym = new QgsSymbol( mVectorLayer->geometryType(), symbol->lowerValue(), symbol->upperValue(), symbol->label() );
        sym->setPen( symbol->pen() );
        sym->setCustomTexture( symbol->customTexture() );
        sym->setBrush( symbol->brush() );
        sym->setNamedPointSymbol( symbol->pointSymbolName() );
        sym->setPointSize( symbol->pointSize() );
        sym->setPointSizeUnits( symbol->pointSizeUnits() );
        sym->setScaleClassificationField( symbol->scaleClassificationField() );
        sym->setRotationClassificationField( symbol->rotationClassificationField() );
        mValues.insert( symbolvalue, sym );

        QListWidgetItem *item = new QListWidgetItem( symbolvalue );
        mClassListWidget->addItem( item );
        updateEntryIcon( symbol, item );
        item->setFlags( Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsEnabled );
        item->setData( Qt::UserRole, symbol->lowerValue() );
        item->setToolTip( symbol->label() );
      }
    }
  }

  mDeletePushButton->setEnabled( false );

  connect( mClassifyButton, SIGNAL( clicked() ), this, SLOT( changeClassificationAttribute() ) );
  connect( mAddButton, SIGNAL( clicked() ), this, SLOT( addClass() ) );
  connect( mDeletePushButton, SIGNAL( clicked() ), this, SLOT( deleteSelectedClasses() ) );
  connect( mRandomizeColors, SIGNAL( clicked() ), this, SLOT( randomizeColors() ) );
  connect( mResetColors, SIGNAL( clicked() ), this, SLOT( resetColors() ) );
  connect( mClassListWidget, SIGNAL( itemSelectionChanged() ), this, SLOT( selectionChanged() ) );
  connect( mCommonPropertyLock, SIGNAL( clicked() ), this, SLOT( selectionChanged() ) );
  connect( mClassListWidget, SIGNAL( itemChanged( QListWidgetItem * ) ), this, SLOT( itemChanged( QListWidgetItem * ) ) );
  connect( &sydialog, SIGNAL( settingsChanged() ), this, SLOT( applySymbologyChanges() ) );
  mSymbolWidgetStack->addWidget( &sydialog );
  mSymbolWidgetStack->setCurrentWidget( &sydialog );
}
Example #12
0
bool QgsOverlayAnalyzer::intersection( QgsVectorLayer* layerA, QgsVectorLayer* layerB,
                                       const QString& shapefileName, bool onlySelectedFeatures,
                                       QProgressDialog* p )
{
  if ( !layerA && !layerB )
  {
    return false;
  }

  QgsVectorDataProvider* dpA = layerA->dataProvider();
  QgsVectorDataProvider* dpB = layerB->dataProvider();
  if ( !dpA && !dpB )
  {
    return false;
  }

  QGis::WkbType outputType = dpA->geometryType();
  const QgsCoordinateReferenceSystem crs = layerA->srs();
  QgsFieldMap fieldsA = dpA->fields();
  QgsFieldMap fieldsB = dpB->fields();
  combineFieldLists( fieldsA, fieldsB );

  QgsVectorFileWriter vWriter( shapefileName, dpA->encoding(), fieldsA, outputType, &crs );
  QgsFeature currentFeature;
  QgsSpatialIndex index;

  //take only selection
  if ( onlySelectedFeatures )
  {
    const QgsFeatureIds selectionB = layerB->selectedFeaturesIds();
    QgsFeatureIds::const_iterator it = selectionB.constBegin();
    for ( ; it != selectionB.constEnd(); ++it )
    {
      if ( !layerB->featureAtId( *it, currentFeature, true, true ) )
      {
        continue;
      }
      index.insertFeature( currentFeature );
    }
    //use QgsVectorLayer::featureAtId
    const QgsFeatureIds selectionA = layerA->selectedFeaturesIds();
    if ( p )
    {
      p->setMaximum( selectionA.size() );
    }
    QgsFeature currentFeature;
    int processedFeatures = 0;
    it = selectionA.constBegin();
    for ( ; it != selectionA.constEnd(); ++it )
    {
      if ( p )
      {
        p->setValue( processedFeatures );
      }

      if ( p && p->wasCanceled() )
      {
        break;
      }
      if ( !layerA->featureAtId( *it, currentFeature, true, true ) )
      {
        continue;
      }
      intersectFeature( currentFeature, &vWriter, layerB, &index );
      ++processedFeatures;
    }

    if ( p )
    {
      p->setValue( selectionA.size() );
    }
  }
  //take all features
  else
  {
    layerB->select( layerB->pendingAllAttributesList(), QgsRectangle(), true, false );
    while ( layerB->nextFeature( currentFeature ) )
    {
      index.insertFeature( currentFeature );
    }
    QgsFeature currentFeature;
    layerA->select( layerA->pendingAllAttributesList(), QgsRectangle(), true, false );

    int featureCount = layerA->featureCount();
    if ( p )
    {
      p->setMaximum( featureCount );
    }
    int processedFeatures = 0;

    while ( layerA->nextFeature( currentFeature ) )
    {
      if ( p )
      {
        p->setValue( processedFeatures );
      }
      if ( p && p->wasCanceled() )
      {
        break;
      }
      intersectFeature( currentFeature, &vWriter, layerB, &index );
      ++processedFeatures;
    }
    if ( p )
    {
      p->setValue( featureCount );
    }
  }
  return true;
}
Example #13
0
bool QgsGeometryAnalyzer::simplify( QgsVectorLayer* layer,
                                    const QString& shapefileName,
                                    double tolerance,
                                    bool onlySelectedFeatures,
                                    QProgressDialog *p )
{
  if ( !layer )
  {
    return false;
  }

  QgsVectorDataProvider* dp = layer->dataProvider();
  if ( !dp )
  {
    return false;
  }

  QGis::WkbType outputType = dp->geometryType();
  const QgsCoordinateReferenceSystem crs = layer->crs();

  QgsVectorFileWriter vWriter( shapefileName, dp->encoding(), dp->fields(), outputType, &crs );
  QgsFeature currentFeature;

  //take only selection
  if ( onlySelectedFeatures )
  {
    //use QgsVectorLayer::featureAtId
    const QgsFeatureIds selection = layer->selectedFeaturesIds();
    if ( p )
    {
      p->setMaximum( selection.size() );
    }

    int processedFeatures = 0;
    QgsFeatureIds::const_iterator it = selection.constBegin();
    for ( ; it != selection.constEnd(); ++it )
    {
      if ( p )
      {
        p->setValue( processedFeatures );
      }

      if ( p && p->wasCanceled() )
      {
        break;
      }
      if ( !layer->featureAtId( *it, currentFeature, true, true ) )
      {
        continue;
      }
      simplifyFeature( currentFeature, &vWriter, tolerance );
      ++processedFeatures;
    }

    if ( p )
    {
      p->setValue( selection.size() );
    }
  }
  //take all features
  else
  {
    layer->select( layer->pendingAllAttributesList(), QgsRectangle(), true, false );


    int featureCount = layer->featureCount();
    if ( p )
    {
      p->setMaximum( featureCount );
    }
    int processedFeatures = 0;

    while ( layer->nextFeature( currentFeature ) )
    {
      if ( p )
      {
        p->setValue( processedFeatures );
      }
      if ( p && p->wasCanceled() )
      {
        break;
      }
      simplifyFeature( currentFeature, &vWriter, tolerance );
      ++processedFeatures;
    }
    if ( p )
    {
      p->setValue( featureCount );
    }
  }

  return true;
}
Example #14
0
  QDomDocument createTransactionDocument( QgsServerInterface* serverIface, const QString& version,
                                          const QgsServerRequest& request )
  {
    Q_UNUSED( version );

    QDomDocument doc;

    QgsWfsProjectParser* configParser = getConfigParser( serverIface );
#ifdef HAVE_SERVER_PYTHON_PLUGINS
    QgsAccessControl* accessControl = serverIface->accessControls();
#endif
    const QString requestBody = request.getParameter( QStringLiteral( "REQUEST_BODY" ) );

    QString errorMsg;
    if ( !doc.setContent( requestBody, true, &errorMsg ) )
    {
      throw QgsRequestNotWellFormedException( errorMsg );
    }

    QDomElement docElem = doc.documentElement();
    QDomNodeList docChildNodes = docElem.childNodes();

    // Re-organize the transaction document
    QDomDocument mDoc;
    QDomElement mDocElem = mDoc.createElement( QStringLiteral( "myTransactionDocument" ) );
    mDocElem.setAttribute( QStringLiteral( "xmlns" ), QGS_NAMESPACE );
    mDocElem.setAttribute( QStringLiteral( "xmlns:wfs" ), WFS_NAMESPACE );
    mDocElem.setAttribute( QStringLiteral( "xmlns:gml" ), GML_NAMESPACE );
    mDocElem.setAttribute( QStringLiteral( "xmlns:ogc" ), OGC_NAMESPACE );
    mDocElem.setAttribute( QStringLiteral( "xmlns:qgs" ), QGS_NAMESPACE );
    mDocElem.setAttribute( QStringLiteral( "xmlns:xsi" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema-instance" ) );
    mDoc.appendChild( mDocElem );

    QDomElement actionElem;
    QString actionName;
    QDomElement typeNameElem;
    QString typeName;

    for ( int i = docChildNodes.count(); 0 < i; --i )
    {
      actionElem = docChildNodes.at( i - 1 ).toElement();
      actionName = actionElem.localName();

      if ( actionName == QLatin1String( "Insert" ) )
      {
        QDomElement featureElem = actionElem.firstChild().toElement();
        typeName = featureElem.localName();
      }
      else if ( actionName == QLatin1String( "Update" ) )
      {
        typeName = actionElem.attribute( QStringLiteral( "typeName" ) );
      }
      else if ( actionName == QLatin1String( "Delete" ) )
      {
        typeName = actionElem.attribute( QStringLiteral( "typeName" ) );
      }

      if ( typeName.contains( QLatin1String( ":" ) ) )
        typeName = typeName.section( QStringLiteral( ":" ), 1, 1 );

      QDomNodeList typeNameList = mDocElem.elementsByTagName( typeName );
      if ( typeNameList.count() == 0 )
      {
        typeNameElem = mDoc.createElement( typeName );
        mDocElem.appendChild( typeNameElem );
      }
      else
        typeNameElem = typeNameList.at( 0 ).toElement();

      typeNameElem.appendChild( actionElem );
    }

    // It's time to make the transaction
    // Create the response document
    QDomDocument resp;
    //wfs:WFS_TransactionRespone element
    QDomElement respElem = resp.createElement( QStringLiteral( "WFS_TransactionResponse" )/*wfs:WFS_TransactionResponse*/ );
    respElem.setAttribute( QStringLiteral( "xmlns" ), WFS_NAMESPACE );
    respElem.setAttribute( QStringLiteral( "xmlns:xsi" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema-instance" ) );
    respElem.setAttribute( QStringLiteral( "xsi:schemaLocation" ), WFS_NAMESPACE + " http://schemas.opengis.net/wfs/1.0.0/wfs.xsd" );
    respElem.setAttribute( QStringLiteral( "xmlns:ogc" ), OGC_NAMESPACE );
    respElem.setAttribute( QStringLiteral( "version" ), QStringLiteral( "1.0.0" ) );
    resp.appendChild( respElem );

    // Store the created feature id for WFS
    QStringList insertResults;
    // Get the WFS layers id
    QStringList wfsLayersId = configParser->wfsLayers();;

    QList<QgsMapLayer*> layerList;
    QgsMapLayer* currentLayer = nullptr;

    // Loop through the layer transaction elements
    docChildNodes = mDocElem.childNodes();
    for ( int i = 0; i < docChildNodes.count(); ++i )
    {
      // Get the vector layer
      typeNameElem = docChildNodes.at( i ).toElement();
      typeName = typeNameElem.tagName();

      layerList = configParser->mapLayerFromTypeName( typeName );
      // Could be empty!
      if ( layerList.count() > 0 )
      {
        currentLayer = layerList.at( 0 );
      }
      else
      {
        throw QgsRequestNotWellFormedException( QStringLiteral( "Wrong TypeName: %1" ).arg( typeName ) );
      }

      QgsVectorLayer* layer = qobject_cast<QgsVectorLayer*>( currentLayer );
      // it's a vectorlayer and defined by the administrator as a WFS layer
      if ( layer && wfsLayersId.contains( layer->id() ) )
      {
#ifdef HAVE_SERVER_PYTHON_PLUGINS
        if ( actionName == QLatin1String( "Insert" ) )
        {
          if ( !accessControl->layerInsertPermission( layer ) )
          {
            throw QgsSecurityAccessException( QStringLiteral( "Feature insert permission denied" ) );
          }
        }
        else if ( actionName == QLatin1String( "Update" ) )
        {
          if ( !accessControl->layerUpdatePermission( layer ) )
          {
            throw QgsSecurityAccessException( QStringLiteral( "Feature update permission denied" ) );
          }
        }
        else if ( actionName == QLatin1String( "Delete" ) )
        {
          if ( !accessControl->layerDeletePermission( layer ) )
          {
            throw QgsSecurityAccessException( QStringLiteral( "Feature delete permission denied" ) );
          }
        }
#endif

        // Get the provider and it's capabilities
        QgsVectorDataProvider* provider = layer->dataProvider();
        if ( !provider )
        {
          continue;
        }

        int cap = provider->capabilities();

        // Start the update transaction
        layer->startEditing();
        if (( cap & QgsVectorDataProvider::ChangeAttributeValues ) && ( cap & QgsVectorDataProvider::ChangeGeometries ) )
        {
          // Loop through the update elements for this layer
          QDomNodeList upNodeList = typeNameElem.elementsByTagNameNS( WFS_NAMESPACE, QStringLiteral( "Update" ) );
          for ( int j = 0; j < upNodeList.count(); ++j )
          {
            if ( !configParser->wfstUpdateLayers().contains( layer->id() ) )
            {
              //no wfs permissions to do updates
              QString errorMsg = "No permissions to do WFS updates on layer '" + layer->name() + "'";
              QgsMessageLog::logMessage( errorMsg, QStringLiteral( "Server" ), QgsMessageLog::CRITICAL );
              addTransactionResult( resp, respElem, QStringLiteral( "FAILED" ), QStringLiteral( "Update" ), errorMsg );
              return resp;
            }

            actionElem = upNodeList.at( j ).toElement();

            // Get the Feature Ids for this filter on the layer
            QDomElement filterElem = actionElem.elementsByTagName( QStringLiteral( "Filter" ) ).at( 0 ).toElement();
            QgsFeatureIds fids = getFeatureIdsFromFilter( filterElem, layer );

            // Loop through the property elements
            // Store properties and the geometry element
            QDomNodeList propertyNodeList = actionElem.elementsByTagName( QStringLiteral( "Property" ) );
            QMap<QString, QString> propertyMap;
            QDomElement propertyElem;
            QDomElement nameElem;
            QDomElement valueElem;
            QDomElement geometryElem;

            for ( int l = 0; l < propertyNodeList.count(); ++l )
            {
              propertyElem = propertyNodeList.at( l ).toElement();
              nameElem = propertyElem.elementsByTagName( QStringLiteral( "Name" ) ).at( 0 ).toElement();
              valueElem = propertyElem.elementsByTagName( QStringLiteral( "Value" ) ).at( 0 ).toElement();
              if ( nameElem.text() != QLatin1String( "geometry" ) )
              {
                propertyMap.insert( nameElem.text(), valueElem.text() );
              }
              else
              {
                geometryElem = valueElem;
              }
            }

            // Update the features
            QgsFields fields = provider->fields();
            QMap<QString, int> fieldMap = provider->fieldNameMap();
            QMap<QString, int>::const_iterator fieldMapIt;
            QString fieldName;
            bool conversionSuccess;

            QgsFeatureIds::const_iterator fidIt = fids.constBegin();
            for ( ; fidIt != fids.constEnd(); ++fidIt )
            {
#ifdef HAVE_SERVER_PYTHON_PLUGINS
              QgsFeatureIterator fit = layer->getFeatures( QgsFeatureRequest( *fidIt ) );
              QgsFeature feature;
              while ( fit.nextFeature( feature ) )
              {
                if ( !accessControl->allowToEdit( layer, feature ) )
                {
                  throw QgsSecurityAccessException( QStringLiteral( "Feature modify permission denied" ) );
                }
              }
#endif

              QMap< QString, QString >::const_iterator it = propertyMap.constBegin();
              for ( ; it != propertyMap.constEnd(); ++it )
              {
                fieldName = it.key();
                fieldMapIt = fieldMap.find( fieldName );
                if ( fieldMapIt == fieldMap.constEnd() )
                {
                  continue;
                }
                QgsField field = fields.at( fieldMapIt.value() );
                if ( field.type() == 2 )
                  layer->changeAttributeValue( *fidIt, fieldMapIt.value(), it.value().toInt( &conversionSuccess ) );
                else if ( field.type() == 6 )
                  layer->changeAttributeValue( *fidIt, fieldMapIt.value(), it.value().toDouble( &conversionSuccess ) );
                else
                  layer->changeAttributeValue( *fidIt, fieldMapIt.value(), it.value() );
              }

              if ( !geometryElem.isNull() )
              {
                QgsGeometry g = QgsOgcUtils::geometryFromGML( geometryElem );
                if ( !layer->changeGeometry( *fidIt, g ) )
                {
                  throw QgsRequestNotWellFormedException( QStringLiteral( "Error in change geometry" ) );
                }
              }

#ifdef HAVE_SERVER_PYTHON_PLUGINS
              fit = layer->getFeatures( QgsFeatureRequest( *fidIt ) );
              while ( fit.nextFeature( feature ) )
              {
                if ( !accessControl->allowToEdit( layer, feature ) )
                {
                  layer->rollBack();
                  throw QgsSecurityAccessException( QStringLiteral( "Feature modify permission denied" ) );
                }
              }
#endif
            }
          }
        }
        // Commit the changes of the update elements
        if ( !layer->commitChanges() )
        {
          addTransactionResult( resp, respElem, QStringLiteral( "PARTIAL" ), QStringLiteral( "Update" ), layer->commitErrors().join( QStringLiteral( "\n  " ) ) );
          return resp;
        }
        // Start the delete transaction
        layer->startEditing();
        if (( cap & QgsVectorDataProvider::DeleteFeatures ) )
        {
          // Loop through the delete elements
          QDomNodeList delNodeList = typeNameElem.elementsByTagNameNS( WFS_NAMESPACE, QStringLiteral( "Delete" ) );
          for ( int j = 0; j < delNodeList.count(); ++j )
          {
            if ( !configParser->wfstDeleteLayers().contains( layer->id() ) )
            {
              //no wfs permissions to do updates
              QString errorMsg = "No permissions to do WFS deletes on layer '" + layer->name() + "'";
              QgsMessageLog::logMessage( errorMsg, QStringLiteral( "Server" ), QgsMessageLog::CRITICAL );
              addTransactionResult( resp, respElem, QStringLiteral( "FAILED" ), QStringLiteral( "Delete" ), errorMsg );
              return resp;
            }

            actionElem = delNodeList.at( j ).toElement();
            QDomElement filterElem = actionElem.firstChild().toElement();
            // Get Feature Ids for the Filter element
            QgsFeatureIds fids = getFeatureIdsFromFilter( filterElem, layer );

#ifdef HAVE_SERVER_PYTHON_PLUGINS
            QgsFeatureIds::const_iterator fidIt = fids.constBegin();
            for ( ; fidIt != fids.constEnd(); ++fidIt )
            {
              QgsFeatureIterator fit = layer->getFeatures( QgsFeatureRequest( *fidIt ) );
              QgsFeature feature;
              while ( fit.nextFeature( feature ) )
              {
                if ( !accessControl->allowToEdit( layer, feature ) )
                {
                  throw QgsSecurityAccessException( QStringLiteral( "Feature modify permission denied" ) );
                }
              }
            }
#endif

            layer->selectByIds( fids );
            layer->deleteSelectedFeatures();
          }
        }
        // Commit the changes of the delete elements
        if ( !layer->commitChanges() )
        {
          addTransactionResult( resp, respElem, QStringLiteral( "PARTIAL" ), QStringLiteral( "Delete" ), layer->commitErrors().join( QStringLiteral( "\n  " ) ) );
          return resp;
        }

        // Store the inserted features
        QgsFeatureList inFeatList;
        if ( cap & QgsVectorDataProvider::AddFeatures )
        {
          // Get Layer Field Information
          QgsFields fields = provider->fields();
          QMap<QString, int> fieldMap = provider->fieldNameMap();
          QMap<QString, int>::const_iterator fieldMapIt;

          // Loop through the insert elements
          QDomNodeList inNodeList = typeNameElem.elementsByTagNameNS( WFS_NAMESPACE, QStringLiteral( "Insert" ) );
          for ( int j = 0; j < inNodeList.count(); ++j )
          {
            if ( !configParser->wfstInsertLayers().contains( layer->id() ) )
            {
              //no wfs permissions to do updates
              QString errorMsg = "No permissions to do WFS inserts on layer '" + layer->name() + "'";
              QgsMessageLog::logMessage( errorMsg, QStringLiteral( "Server" ), QgsMessageLog::CRITICAL );
              addTransactionResult( resp, respElem, QStringLiteral( "FAILED" ), QStringLiteral( "Insert" ), errorMsg );
              return resp;
            }

            actionElem = inNodeList.at( j ).toElement();
            // Loop through the feature element
            QDomNodeList featNodes = actionElem.childNodes();
            for ( int l = 0; l < featNodes.count(); l++ )
            {
              // Add the feature to the layer
              // and store it to put it's Feature Id in the response
              inFeatList << QgsFeature( fields );

              // Create feature for this layer
              QDomElement featureElem = featNodes.at( l ).toElement();

              QDomNode currentAttributeChild = featureElem.firstChild();

              while ( !currentAttributeChild.isNull() )
              {
                QDomElement currentAttributeElement = currentAttributeChild.toElement();
                QString attrName = currentAttributeElement.localName();

                if ( attrName != QLatin1String( "boundedBy" ) )
                {
                  if ( attrName != QLatin1String( "geometry" ) ) //a normal attribute
                  {
                    fieldMapIt = fieldMap.find( attrName );
                    if ( fieldMapIt == fieldMap.constEnd() )
                    {
                      continue;
                    }
                    QgsField field = fields.at( fieldMapIt.value() );
                    QString attrValue = currentAttributeElement.text();
                    int attrType = field.type();
                    QgsMessageLog::logMessage( QStringLiteral( "attr: name=%1 idx=%2 value=%3" ).arg( attrName ).arg( fieldMapIt.value() ).arg( attrValue ) );
                    if ( attrType == QVariant::Int )
                      inFeatList.last().setAttribute( fieldMapIt.value(), attrValue.toInt() );
                    else if ( attrType == QVariant::Double )
                      inFeatList.last().setAttribute( fieldMapIt.value(), attrValue.toDouble() );
                    else
                      inFeatList.last().setAttribute( fieldMapIt.value(), attrValue );
                  }
                  else //a geometry attribute
                  {
                    QgsGeometry g = QgsOgcUtils::geometryFromGML( currentAttributeElement );
                    inFeatList.last().setGeometry( g );
                  }
                }
                currentAttributeChild = currentAttributeChild.nextSibling();
              }
            }
          }
        }
#ifdef HAVE_SERVER_PYTHON_PLUGINS
        QgsFeatureList::iterator featureIt = inFeatList.begin();
        while ( featureIt != inFeatList.end() )
        {
          if ( !accessControl->allowToEdit( layer, *featureIt ) )
          {
            throw QgsSecurityAccessException( QStringLiteral( "Feature modify permission denied" ) );
          }
          featureIt++;
        }
#endif

        // add the features
        if ( !provider->addFeatures( inFeatList ) )
        {
          addTransactionResult( resp, respElem, QStringLiteral( "Partial" ), QStringLiteral( "Insert" ), layer->commitErrors().join( QStringLiteral( "\n  " ) ) );
          if ( provider->hasErrors() )
          {
            provider->clearErrors();
          }
          return resp;
        }
        // Get the Feature Ids of the inserted feature
        for ( int j = 0; j < inFeatList.size(); j++ )
        {
          insertResults << typeName + "." + QString::number( inFeatList[j].id() );
        }
      }
    }

    // Put the Feature Ids of the inserted feature
    if ( !insertResults.isEmpty() )
    {
      Q_FOREACH ( const QString &fidStr, insertResults )
      {
        QDomElement irElem = doc.createElement( QStringLiteral( "InsertResult" ) );
        QDomElement fiElem = doc.createElement( QStringLiteral( "ogc:FeatureId" ) );
        fiElem.setAttribute( QStringLiteral( "fid" ), fidStr );
        irElem.appendChild( fiElem );
        respElem.appendChild( irElem );
      }
void QgsSingleSymbolDialog::refreshMarkers()
{
  QgsMarkerListModel *m = new QgsMarkerListModel( lstSymbols );
  lstSymbols->setModel( m );

  connect( lstSymbols->selectionModel(), SIGNAL( currentChanged( const QModelIndex &, const QModelIndex & ) ),
           this, SLOT( symbolChanged( const QModelIndex &, const QModelIndex & ) ) );

  // Find out the numerical fields of mVectorLayer, and populate the ComboBoxes
  QgsVectorDataProvider *provider = mVectorLayer->dataProvider();
  if ( provider )
  {
    const QgsFieldMap & fields = provider->fields();
    QString str;

    mRotationClassificationComboBox->addItem( DO_NOT_USE_STR, -1 );
    mScaleClassificationComboBox->addItem( DO_NOT_USE_STR, -1 );
    mSymbolComboBox->addItem( DO_NOT_USE_STR, -1 );
    for ( QgsFieldMap::const_iterator it = fields.begin();
          it != fields.end();
          ++it )
    {
      QVariant::Type type = ( *it ).type();
      if ( type == QVariant::Int || type == QVariant::Double )
      {
        mRotationClassificationComboBox->addItem( it->name(), it.key() );
        mScaleClassificationComboBox->addItem( it->name(), it.key() );
      }
      else if ( type == QVariant::String )
      {
        mSymbolComboBox->addItem( it->name(), it.key() );
      }
    }
  }
  else
  {
    QgsDebugMsg( "Warning, data provider is null" );
    return;
  }
  //
  //set outline / line style
  //
  cboOutlineStyle->addItem( QIcon( QgsSymbologyUtils::char2LinePixmap( "SolidLine" ) ), "", "SolidLine" );
  cboOutlineStyle->addItem( QIcon( QgsSymbologyUtils::char2LinePixmap( "NoPen" ) ), tr( "None" ), "NoPen" );
  cboOutlineStyle->addItem( QIcon( QgsSymbologyUtils::char2LinePixmap( "DashLine" ) ), "", "DashLine" );
  cboOutlineStyle->addItem( QIcon( QgsSymbologyUtils::char2LinePixmap( "DotLine" ) ), "", "DotLine" );
  cboOutlineStyle->addItem( QIcon( QgsSymbologyUtils::char2LinePixmap( "DashDotLine" ) ), "" , "DashDotLine" );
  cboOutlineStyle->addItem( QIcon( QgsSymbologyUtils::char2LinePixmap( "DashDotDotLine" ) ), "", "DashDotDotLine" );

  //
  //set pattern icons and state
  //
  cboFillStyle->addItem( QIcon( QgsSymbologyUtils::char2PatternPixmap( "SolidPattern" ) ), "", "SolidPattern" );
  cboFillStyle->addItem( QIcon( QgsSymbologyUtils::char2PatternPixmap( "NoBrush" ) ), tr( "None" ), "NoBrush" );
  cboFillStyle->addItem( QIcon( QgsSymbologyUtils::char2PatternPixmap( "HorPattern" ) ), "", "HorPattern" );
  cboFillStyle->addItem( QIcon( QgsSymbologyUtils::char2PatternPixmap( "VerPattern" ) ), "", "VerPattern" );
  cboFillStyle->addItem( QIcon( QgsSymbologyUtils::char2PatternPixmap( "CrossPattern" ) ), "", "CrossPattern" );
  cboFillStyle->addItem( QIcon( QgsSymbologyUtils::char2PatternPixmap( "BDiagPattern" ) ), "", "BDiagPattern" );
  cboFillStyle->addItem( QIcon( QgsSymbologyUtils::char2PatternPixmap( "FDiagPattern" ) ), "", "FDiagPattern" );
  cboFillStyle->addItem( QIcon( QgsSymbologyUtils::char2PatternPixmap( "DiagCrossPattern" ) ), "", "DiagCrossPattern" );
  cboFillStyle->addItem( QIcon( QgsSymbologyUtils::char2PatternPixmap( "Dense1Pattern" ) ), "", "Dense1Pattern" );
  cboFillStyle->addItem( QIcon( QgsSymbologyUtils::char2PatternPixmap( "Dense2Pattern" ) ), "", "Dense2Pattern" );
  cboFillStyle->addItem( QIcon( QgsSymbologyUtils::char2PatternPixmap( "Dense3Pattern" ) ), "", "Dense3Pattern" );
  cboFillStyle->addItem( QIcon( QgsSymbologyUtils::char2PatternPixmap( "Dense4Pattern" ) ), "", "Dense4Pattern" );
  cboFillStyle->addItem( QIcon( QgsSymbologyUtils::char2PatternPixmap( "Dense5Pattern" ) ), "", "Dense5Pattern" );
  cboFillStyle->addItem( QIcon( QgsSymbologyUtils::char2PatternPixmap( "Dense6Pattern" ) ), "", "Dense6Pattern" );
  cboFillStyle->addItem( QIcon( QgsSymbologyUtils::char2PatternPixmap( "Dense7Pattern" ) ), "", "Dense7Pattern" );
  cboFillStyle->addItem( QIcon( QgsSymbologyUtils::char2PatternPixmap( "TexturePattern" ) ), tr( "Texture" ), "TexturePattern" );

  if ( mVectorLayer && mVectorLayer->geometryType() != QGis::Point )
  {
    mGroupPoint->setVisible( false );
    mGroupPoint->setEnabled( false );
    mGroupDrawingByField->setVisible( false );
    mGroupDrawingByField->setEnabled( false );
  }

  if ( mDisabled )
  {
    unset();
  }
  else
  {
    if ( mVectorLayer )
    {
      const QgsSingleSymbolRenderer *renderer = dynamic_cast<const QgsSingleSymbolRenderer *>( mVectorLayer->renderer() );

      if ( renderer )
      {
        // Set from the existing renderer
        set( renderer->symbols().first() );
      }
      else
      {
        // Take values from an example instance
        QgsSingleSymbolRenderer exampleRenderer = QgsSingleSymbolRenderer( mVectorLayer->geometryType() );
        set( exampleRenderer.symbols().first() );
      }
    }
    else
    {
      QgsDebugMsg( "Warning, layer is a null pointer" );
    }
  }

  lstSymbols->blockSignals( false );
}
Example #16
0
bool QgsGeometryAnalyzer::dissolve( QgsVectorLayer* layer, const QString& shapefileName,
                                    bool onlySelectedFeatures, int uniqueIdField, QProgressDialog* p )
{
  if ( !layer )
  {
    return false;
  }
  QgsVectorDataProvider* dp = layer->dataProvider();
  if ( !dp )
  {
    return false;
  }
  bool useField = false;
  if ( uniqueIdField == -1 )
  {
    uniqueIdField = 0;
  }
  else
  {
    useField = true;
  }

  QGis::WkbType outputType = dp->geometryType();
  const QgsCoordinateReferenceSystem crs = layer->crs();

  QgsVectorFileWriter vWriter( shapefileName, dp->encoding(), dp->fields(), outputType, &crs );
  QgsFeature currentFeature;
  QMultiMap<QString, QgsFeatureId> map;

  if ( onlySelectedFeatures )
  {
    //use QgsVectorLayer::featureAtId
    const QgsFeatureIds selection = layer->selectedFeaturesIds();
    QgsFeatureIds::const_iterator it = selection.constBegin();
    for ( ; it != selection.constEnd(); ++it )
    {
      if ( !layer->featureAtId( *it, currentFeature, true, true ) )
      {
        continue;
      }
      map.insert( currentFeature.attributeMap()[ uniqueIdField ].toString(), currentFeature.id() );
    }
  }
  else
  {
    layer->select( layer->pendingAllAttributesList(), QgsRectangle(), true, false );
    while ( layer->nextFeature( currentFeature ) )
    {
      map.insert( currentFeature.attributeMap()[ uniqueIdField ].toString(), currentFeature.id() );
    }
  }

  QgsGeometry *dissolveGeometry = 0; //dissolve geometry
  QMultiMap<QString, QgsFeatureId>::const_iterator jt = map.constBegin();
  QgsFeature outputFeature;
  while ( jt != map.constEnd() )
  {
    QString currentKey = jt.key();
    int processedFeatures = 0;
    bool first = true;
    //take only selection
    if ( onlySelectedFeatures )
    {
      //use QgsVectorLayer::featureAtId
      const QgsFeatureIds selection = layer->selectedFeaturesIds();
      if ( p )
      {
        p->setMaximum( selection.size() );
      }
      while ( jt != map.constEnd() && ( jt.key() == currentKey || !useField ) )
      {
        if ( p && p->wasCanceled() )
        {
          break;
        }
        if ( selection.contains( jt.value() ) )
        {
          if ( p )
          {
            p->setValue( processedFeatures );
          }
          if ( !layer->featureAtId( jt.value(), currentFeature, true, true ) )
          {
            continue;
          }
          if ( first )
          {
            outputFeature.setAttributeMap( currentFeature.attributeMap() );
            first = false;
          }
          dissolveFeature( currentFeature, processedFeatures, &dissolveGeometry );
          ++processedFeatures;
        }
        ++jt;
      }
    }
    //take all features
    else
    {
      int featureCount = layer->featureCount();
      if ( p )
      {
        p->setMaximum( featureCount );
      }
      while ( jt != map.constEnd() && ( jt.key() == currentKey || !useField ) )
      {
        if ( p )
        {
          p->setValue( processedFeatures );
        }

        if ( p && p->wasCanceled() )
        {
          break;
        }
        if ( !layer->featureAtId( jt.value(), currentFeature, true, true ) )
        {
          continue;
        }
        {
          outputFeature.setAttributeMap( currentFeature.attributeMap() );
          first = false;
        }
        dissolveFeature( currentFeature, processedFeatures, &dissolveGeometry );
        ++processedFeatures;
        ++jt;
      }
    }
    outputFeature.setGeometry( dissolveGeometry );
    vWriter.addFeature( outputFeature );
  }
  return true;
}
void QgsProjectFileTransform::transform0110to1000()
{
  if ( ! mDom.isNull() )
  {
    QDomNodeList layerList = mDom.elementsByTagName( "maplayer" );
    for ( int i = 0; i < layerList.size(); ++i )
    {
      QDomElement layerElem = layerList.at( i ).toElement();
      QString typeString = layerElem.attribute( "type" );
      if ( typeString != "vector" )
      {
        continue;
      }

      //datasource
      QDomNode dataSourceNode = layerElem.namedItem( "datasource" );
      if ( dataSourceNode.isNull() )
      {
        return;
      }
      QString dataSource = dataSourceNode.toElement().text();

      //provider key
      QDomNode providerNode = layerElem.namedItem( "provider" );
      if ( providerNode.isNull() )
      {
        return;
      }
      QString providerKey = providerNode.toElement().text();

      //create the layer to get the provider for int->fieldName conversion
      QgsVectorLayer* theLayer = new QgsVectorLayer( dataSource, "", providerKey, false );
      if ( !theLayer->isValid() )
      {
        delete theLayer;
        return;
      }

      QgsVectorDataProvider* theProvider = theLayer->dataProvider();
      if ( !theProvider )
      {
        return;
      }
      QgsFields theFields = theProvider->fields();

      //read classificationfield
      QDomNodeList classificationFieldList = layerElem.elementsByTagName( "classificationfield" );
      for ( int j = 0; j < classificationFieldList.size(); ++j )
      {
        QDomElement classificationFieldElem = classificationFieldList.at( j ).toElement();
        int fieldNumber = classificationFieldElem.text().toInt();
        if ( fieldNumber >= 0 && fieldNumber < theFields.count() )
        {
          QDomText fieldName = mDom.createTextNode( theFields[fieldNumber].name() );
          QDomNode nameNode = classificationFieldElem.firstChild();
          classificationFieldElem.replaceChild( fieldName, nameNode );
        }
      }

    }
  }
}
QgsVectorLayerExporter::QgsVectorLayerExporter( const QString &uri,
    const QString &providerKey,
    const QgsFields &fields,
    QgsWkbTypes::Type geometryType,
    const QgsCoordinateReferenceSystem &crs,
    bool overwrite,
    const QMap<QString, QVariant> &options,
    QgsFeatureSink::SinkFlags sinkFlags )
  : mErrorCount( 0 )
  , mAttributeCount( -1 )

{
  mProvider = nullptr;

  QgsProviderRegistry *pReg = QgsProviderRegistry::instance();

  std::unique_ptr< QLibrary > myLib( pReg->createProviderLibrary( providerKey ) );
  if ( !myLib )
  {
    mError = ErrInvalidProvider;
    mErrorMessage = QObject::tr( "Unable to load %1 provider" ).arg( providerKey );
    return;
  }

  createEmptyLayer_t *pCreateEmpty = reinterpret_cast< createEmptyLayer_t * >( cast_to_fptr( myLib->resolve( "createEmptyLayer" ) ) );
  if ( !pCreateEmpty )
  {
    mError = ErrProviderUnsupportedFeature;
    mErrorMessage = QObject::tr( "Provider %1 has no %2 method" ).arg( providerKey, QStringLiteral( "createEmptyLayer" ) );
    return;
  }

  // create an empty layer
  QString errMsg;
  mError = pCreateEmpty( uri, fields, geometryType, crs, overwrite, &mOldToNewAttrIdx, &errMsg, !options.isEmpty() ? &options : nullptr );
  if ( errorCode() )
  {
    mErrorMessage = errMsg;
    return;
  }

  Q_FOREACH ( int idx, mOldToNewAttrIdx )
  {
    if ( idx > mAttributeCount )
      mAttributeCount = idx;
  }

  mAttributeCount++;

  QgsDebugMsg( QStringLiteral( "Created empty layer" ) );

  QString uriUpdated( uri );
  // HACK sorry...
  if ( providerKey == QLatin1String( "ogr" ) )
  {
    QString layerName;
    if ( options.contains( QStringLiteral( "layerName" ) ) )
      layerName = options.value( QStringLiteral( "layerName" ) ).toString();
    if ( !layerName.isEmpty() )
    {
      uriUpdated += QLatin1String( "|layername=" );
      uriUpdated += layerName;
    }
  }

  QgsDataProvider::ProviderOptions providerOptions;
  QgsVectorDataProvider *vectorProvider = dynamic_cast< QgsVectorDataProvider * >( pReg->createProvider( providerKey, uriUpdated, providerOptions ) );
  if ( !vectorProvider || !vectorProvider->isValid() || ( vectorProvider->capabilities() & QgsVectorDataProvider::AddFeatures ) == 0 )
  {
    mError = ErrInvalidLayer;
    mErrorMessage = QObject::tr( "Loading of layer failed" );

    delete vectorProvider;
    return;
  }

  // If the result is a geopackage layer and there is already a field name FID requested which
  // might contain duplicates, make sure to generate a new field with a unique name instead
  // that will be filled by ogr with unique values.

  // HACK sorry
  const QString path = QgsProviderRegistry::instance()->decodeUri( QStringLiteral( "ogr" ), uri ).value( QStringLiteral( "path" ) ).toString();
  if ( sinkFlags.testFlag( QgsFeatureSink::SinkFlag::RegeneratePrimaryKey ) && path.endsWith( QLatin1String( ".gpkg" ), Qt::CaseInsensitive ) )
  {
    QString fidName = options.value( QStringLiteral( "FID" ), QStringLiteral( "FID" ) ).toString();
    int fidIdx = vectorProvider->fields().lookupField( fidName );
    if ( fidIdx != -1 )
    {
      mOldToNewAttrIdx.remove( fidIdx );
    }
  }

  mProvider = vectorProvider;
  mError = NoError;
}
Example #19
0
bool QgsGeometryAnalyzer::buffer( QgsVectorLayer* layer, const QString& shapefileName, double bufferDistance,
                                  bool onlySelectedFeatures, bool dissolve, int bufferDistanceField, QProgressDialog* p )
{
  if ( !layer )
  {
    return false;
  }

  QgsVectorDataProvider* dp = layer->dataProvider();
  if ( !dp )
  {
    return false;
  }

  QGis::WkbType outputType = QGis::WKBPolygon;
  if ( dissolve )
  {
    outputType = QGis::WKBMultiPolygon;
  }
  const QgsCoordinateReferenceSystem crs = layer->crs();

  QgsVectorFileWriter vWriter( shapefileName, dp->encoding(), dp->fields(), outputType, &crs );
  QgsFeature currentFeature;
  QgsGeometry *dissolveGeometry = 0; //dissolve geometry (if dissolve enabled)

  //take only selection
  if ( onlySelectedFeatures )
  {
    //use QgsVectorLayer::featureAtId
    const QgsFeatureIds selection = layer->selectedFeaturesIds();
    if ( p )
    {
      p->setMaximum( selection.size() );
    }

    int processedFeatures = 0;
    QgsFeatureIds::const_iterator it = selection.constBegin();
    for ( ; it != selection.constEnd(); ++it )
    {
      if ( p )
      {
        p->setValue( processedFeatures );
      }

      if ( p && p->wasCanceled() )
      {
        break;
      }
      if ( !layer->featureAtId( *it, currentFeature, true, true ) )
      {
        continue;
      }
      bufferFeature( currentFeature, processedFeatures, &vWriter, dissolve, &dissolveGeometry, bufferDistance, bufferDistanceField );
      ++processedFeatures;
    }

    if ( p )
    {
      p->setValue( selection.size() );
    }
  }
  //take all features
  else
  {
    layer->select( layer->pendingAllAttributesList(), QgsRectangle(), true, false );


    int featureCount = layer->featureCount();
    if ( p )
    {
      p->setMaximum( featureCount );
    }
    int processedFeatures = 0;

    while ( layer->nextFeature( currentFeature ) )
    {
      if ( p )
      {
        p->setValue( processedFeatures );
      }
      if ( p && p->wasCanceled() )
      {
        break;
      }
      bufferFeature( currentFeature, processedFeatures, &vWriter, dissolve, &dissolveGeometry, bufferDistance, bufferDistanceField );
      ++processedFeatures;
    }
    if ( p )
    {
      p->setValue( featureCount );
    }
  }

  if ( dissolve )
  {
    QgsFeature dissolveFeature;
    if ( !dissolveGeometry )
    {
      QgsDebugMsg( "no dissolved geometry - should not happen" );
      return false;
    }
    dissolveFeature.setGeometry( dissolveGeometry );
    vWriter.addFeature( dissolveFeature );
  }
  return true;
}
Example #20
0
int QgsWFSServer::getFeature( QgsRequestHandler& request, const QString& format )
{
  QgsDebugMsg( "Info format is:" + format );

  //read TYPENAME
  QMap<QString, QString>::const_iterator type_name_it = mParameterMap.find( "TYPENAME" );
  if ( type_name_it != mParameterMap.end() )
  {
    mTypeName = type_name_it.value();
  }
  else
  {
    return 1;
  }

  QStringList wfsLayersId = mConfigParser->wfsLayers();
  QMap< QString, QMap< int, QString > > aliasInfo = mConfigParser->layerAliasInfo();
  QMap< QString, QSet<QString> > hiddenAttributes = mConfigParser->hiddenAttributes();

  QList<QgsMapLayer*> layerList;
  QgsMapLayer* currentLayer = 0;

  layerList = mConfigParser->mapLayerFromStyle( mTypeName, "" );
  currentLayer = layerList.at( 0 );

  QgsVectorLayer* layer = dynamic_cast<QgsVectorLayer*>( currentLayer );
  if ( layer && wfsLayersId.contains( layer->id() ) )
  {
    //is there alias info for this vector layer?
    QMap< int, QString > layerAliasInfo;
    QMap< QString, QMap< int, QString > >::const_iterator aliasIt = aliasInfo.find( currentLayer->id() );
    if ( aliasIt != aliasInfo.constEnd() )
    {
      layerAliasInfo = aliasIt.value();
    }

    //hidden attributes for this layer
    QSet<QString> layerHiddenAttributes;
    QMap< QString, QSet<QString> >::const_iterator hiddenIt = hiddenAttributes.find( currentLayer->id() );
    if ( hiddenIt != hiddenAttributes.constEnd() )
    {
      layerHiddenAttributes = hiddenIt.value();
    }

    //do a select with searchRect and go through all the features
    QgsVectorDataProvider* provider = layer->dataProvider();
    if ( !provider )
    {
      return 2;
    }

    QgsFeature feature;
    QgsAttributeMap featureAttributes;
    const QgsFieldMap& fields = provider->fields();

    //map extent
    QgsRectangle searchRect = layer->extent();

    //read FEATUREDID
    bool fidOk = false;
    QString fid;
    QMap<QString, QString>::const_iterator fidIt = mParameterMap.find( "FEATUREID" );
    if ( fidIt != mParameterMap.end() )
    {
      fidOk = true;
      fid = fidIt.value();
    }

    //read FILTER
    bool filterOk = false;
    QDomDocument filter;
    QMap<QString, QString>::const_iterator filterIt = mParameterMap.find( "FILTER" );
    if ( filterIt != mParameterMap.end() )
    {
      try
      {
        QString errorMsg;
        if ( !filter.setContent( filterIt.value(), true, &errorMsg ) )
        {
          QgsDebugMsg( "soap request parse error" );
          QgsDebugMsg( "error message: " + errorMsg );
          QgsDebugMsg( "the xml string was:" );
          QgsDebugMsg( filterIt.value() );
        }
        else
        {
          filterOk = true;
        }
      }
      catch ( QgsMapServiceException& e )
      {
        Q_UNUSED( e );
        filterOk = false;
      }
    }


    bool conversionSuccess;
    double minx, miny, maxx, maxy;
    bool bboxOk = false;
    //read BBOX
    QMap<QString, QString>::const_iterator bbIt = mParameterMap.find( "BBOX" );
    if ( bbIt == mParameterMap.end() )
    {
      minx = 0; miny = 0; maxx = 0; maxy = 0;
    }
    else
    {
      bboxOk = true;
      QString bbString = bbIt.value();
      minx = bbString.section( ",", 0, 0 ).toDouble( &conversionSuccess );
      if ( !conversionSuccess ) {bboxOk = false;}
      miny = bbString.section( ",", 1, 1 ).toDouble( &conversionSuccess );
      if ( !conversionSuccess ) {bboxOk = false;}
      maxx = bbString.section( ",", 2, 2 ).toDouble( &conversionSuccess );
      if ( !conversionSuccess ) {bboxOk = false;}
      maxy = bbString.section( ",", 3, 3 ).toDouble( &conversionSuccess );
      if ( !conversionSuccess ) {bboxOk = false;}
    }

    //read MAXFEATURES
    long maxFeat = layer->featureCount();
    long featureCounter = 0;
    QMap<QString, QString>::const_iterator mfIt = mParameterMap.find( "MAXFEATURES" );
    if ( mfIt != mParameterMap.end() )
    {
      QString mfString = mfIt.value();
      bool mfOk;
      maxFeat = mfString.toLong( &mfOk, 10 );
      if ( !mfOk ) { maxFeat = layer->featureCount(); }
    }

    //read PROPERTYNAME
    mWithGeom = true;
    QgsAttributeList attrIndexes = provider->attributeIndexes();
    QMap<QString, QString>::const_iterator pnIt = mParameterMap.find( "PROPERTYNAME" );
    if ( pnIt != mParameterMap.end() )
    {
      QStringList attrList = pnIt.value().split( "," );
      if ( attrList.size() > 0 )
      {
        mWithGeom = false;
        QStringList::const_iterator alstIt;
        QList<int> idxList;
        QMap<QString, int> fieldMap = provider->fieldNameMap();
        QMap<QString, int>::const_iterator fieldIt;
        QString fieldName;
        for ( alstIt = attrList.begin(); alstIt != attrList.end(); ++alstIt )
        {
          fieldName = *alstIt;
          fieldIt = fieldMap.find( fieldName );
          if ( fieldIt != fieldMap.end() )
          {
            idxList.append( fieldIt.value() );
          }
          else if ( fieldName == "geometry" )
          {
            mWithGeom = true;
          }
        }
        if ( idxList.size() > 0 || mWithGeom )
        {
          attrIndexes = idxList;
        }
        else
        {
          mWithGeom = true;
        }
      }
    }

    QgsCoordinateReferenceSystem layerCrs = layer->crs();

    startGetFeature( request, format );

    if ( fidOk )
    {
      provider->featureAtId( fid.toInt(), feature, mWithGeom, attrIndexes );
      sendGetFeature( request, format, &feature, 0, layerCrs, fields, layerHiddenAttributes );
    }
    else if ( filterOk )
    {
      provider->select( attrIndexes, searchRect, mWithGeom, true );
      try
      {
        QgsFilter* mFilter = QgsFilter::createFilterFromXml( filter.firstChild().toElement().firstChild().toElement(), layer );
        while ( provider->nextFeature( feature ) && featureCounter < maxFeat )
        {
          if ( mFilter )
          {
            if ( mFilter->evaluate( feature ) )
            {
              sendGetFeature( request, format, &feature, featureCounter, layerCrs, fields, layerHiddenAttributes );
              ++featureCounter;
            }
          }
          else
          {
            sendGetFeature( request, format, &feature, featureCounter, layerCrs, fields, layerHiddenAttributes );
            ++featureCounter;
          }
        }
        delete mFilter;
      }
      catch ( QgsMapServiceException& e )
      {
        Q_UNUSED( e );

        while ( provider->nextFeature( feature ) && featureCounter < maxFeat )
        {
          sendGetFeature( request, format, &feature, featureCounter, layerCrs, fields, layerHiddenAttributes );
          ++featureCounter;
        }
      }
    }
    else
    {
      if ( bboxOk )
        searchRect.set( minx, miny, maxx, maxy );
      provider->select( attrIndexes, searchRect, mWithGeom, true );
      while ( provider->nextFeature( feature ) && featureCounter < maxFeat )
      {
        sendGetFeature( request, format, &feature, featureCounter, layerCrs, fields, layerHiddenAttributes );
        ++featureCounter;
      }
    }

    endGetFeature( request, format );
  }
  else
  {
    return 2;
  }
  return 0;
}
Example #21
0
QDomDocument QgsWFSServer::describeFeatureType()
{
  QgsDebugMsg( "Entering." );
  QDomDocument doc;
  //xsd:schema
  QDomElement schemaElement = doc.createElement( "schema"/*xsd:schema*/ );
  schemaElement.setAttribute( "xmlns", "http://www.w3.org/2001/XMLSchema" );
  schemaElement.setAttribute( "xmlns:xsd", "http://www.w3.org/2001/XMLSchema" );
  schemaElement.setAttribute( "xmlns:ogc", "http://www.opengis.net/ogc" );
  schemaElement.setAttribute( "xmlns:gml", "http://www.opengis.net/gml" );
  schemaElement.setAttribute( "xmlns:qgs", "http://www.qgis.org/gml" );
  schemaElement.setAttribute( "targetNamespace", "http://www.qgis.org/gml" );
  doc.appendChild( schemaElement );

  //xsd:import
  QDomElement importElement = doc.createElement( "import"/*xsd:import*/ );
  importElement.setAttribute( "namespace", "http://www.opengis.net/gml" );
  importElement.setAttribute( "schemaLocation", "http://schemas.opengis.net/gml/2.1.2/feature.xsd" );
  schemaElement.appendChild( importElement );

  //read TYPENAME
  QString typeName;
  QMap<QString, QString>::const_iterator type_name_it = mParameterMap.find( "TYPENAME" );
  if ( type_name_it != mParameterMap.end() )
  {
    typeName = type_name_it.value();
  }
  else
  {
    return doc;
  }

  QStringList wfsLayersId = mConfigParser->wfsLayers();
  QMap< QString, QMap< int, QString > > aliasInfo = mConfigParser->layerAliasInfo();
  QMap< QString, QSet<QString> > hiddenAttributes = mConfigParser->hiddenAttributes();

  QList<QgsMapLayer*> layerList;
  QgsMapLayer* currentLayer = 0;

  layerList = mConfigParser->mapLayerFromStyle( typeName, "" );
  currentLayer = layerList.at( 0 );

  QgsVectorLayer* layer = dynamic_cast<QgsVectorLayer*>( currentLayer );
  if ( layer && wfsLayersId.contains( layer->id() ) )
  {
    //is there alias info for this vector layer?
    QMap< int, QString > layerAliasInfo;
    QMap< QString, QMap< int, QString > >::const_iterator aliasIt = aliasInfo.find( currentLayer->id() );
    if ( aliasIt != aliasInfo.constEnd() )
    {
      layerAliasInfo = aliasIt.value();
    }

    //hidden attributes for this layer
    QSet<QString> layerHiddenAttributes;
    QMap< QString, QSet<QString> >::const_iterator hiddenIt = hiddenAttributes.find( currentLayer->id() );
    if ( hiddenIt != hiddenAttributes.constEnd() )
    {
      layerHiddenAttributes = hiddenIt.value();
    }

    //do a select with searchRect and go through all the features
    QgsVectorDataProvider* provider = layer->dataProvider();
    if ( !provider )
    {
      return doc;
    }

    typeName = typeName.replace( QString( " " ), QString( "_" ) );

    //xsd:element
    QDomElement elementElem = doc.createElement( "element"/*xsd:element*/ );
    elementElem.setAttribute( "name", typeName );
    elementElem.setAttribute( "type", "qgs:" + typeName + "Type" );
    elementElem.setAttribute( "substitutionGroup", "gml:_Feature" );
    schemaElement.appendChild( elementElem );

    //xsd:complexType
    QDomElement complexTypeElem = doc.createElement( "complexType"/*xsd:complexType*/ );
    complexTypeElem.setAttribute( "name", typeName + "Type" );
    schemaElement.appendChild( complexTypeElem );

    //xsd:complexType
    QDomElement complexContentElem = doc.createElement( "complexContent"/*xsd:complexContent*/ );
    complexTypeElem.appendChild( complexContentElem );

    //xsd:extension
    QDomElement extensionElem = doc.createElement( "extension"/*xsd:extension*/ );
    extensionElem.setAttribute( "base", "gml:AbstractFeatureType" );
    complexContentElem.appendChild( extensionElem );

    //xsd:sequence
    QDomElement sequenceElem = doc.createElement( "sequence"/*xsd:sequence*/ );
    extensionElem.appendChild( sequenceElem );

    //xsd:element
    QDomElement geomElem = doc.createElement( "element"/*xsd:element*/ );
    geomElem.setAttribute( "name", "geometry" );
    geomElem.setAttribute( "type", "gml:GeometryPropertyType" );
    geomElem.setAttribute( "minOccurs", "0" );
    geomElem.setAttribute( "maxOccurs", "1" );
    sequenceElem.appendChild( geomElem );

    const QgsFieldMap& fields = provider->fields();
    for ( QgsFieldMap::const_iterator it = fields.begin(); it != fields.end(); ++it )
    {

      QString attributeName = it.value().name();
      //skip attribute if it has edit type 'hidden'
      if ( layerHiddenAttributes.contains( attributeName ) )
      {
        continue;
      }

      //xsd:element
      QDomElement geomElem = doc.createElement( "element"/*xsd:element*/ );
      geomElem.setAttribute( "name", attributeName );
      if ( it.value().type() == 2 )
        geomElem.setAttribute( "type", "integer" );
      else if ( it.value().type() == 6 )
        geomElem.setAttribute( "type", "double" );
      else
        geomElem.setAttribute( "type", "string" );

      sequenceElem.appendChild( geomElem );

      //check if the attribute name should be replaced with an alias
      QMap<int, QString>::const_iterator aliasIt = layerAliasInfo.find( it.key() );
      if ( aliasIt != layerAliasInfo.constEnd() )
      {
        geomElem.setAttribute( "alias", aliasIt.value() );
      }

    }
  }

  return doc;
}