Package org.gdal.ogr

Examples of org.gdal.ogr.DataSource


         Usage();

      /* -------------------------------------------------------------------- */
      /*      Try to open as an existing dataset for update access.           */
      /* -------------------------------------------------------------------- */
      DataSource poDstDS;
      Layer poDstLayer = null;

      poDstDS = ogr.Open( pszOutputName, true );

      /* -------------------------------------------------------------------- */
      /*      If that failed, find the driver so we can create the tile index.*/
      /* -------------------------------------------------------------------- */
      if( poDstDS == null )
      {       
         Driver poDriver = null;

         for( int iDriver = 0; iDriver < ogr.GetDriverCount() && poDriver == null; iDriver++ )
         {
            poDriver = ogr.GetDriverByName(pszFormat);
         }

         if( poDriver == null )
         {
            System.err.print("Unable to find driver '"+pszFormat+"'.\n");
            System.err.print("The following drivers are available:\n" );

            for( int iDriver = 0; iDriver < ogr.GetDriverCount(); iDriver++ )
            {
               System.err.print("  . '"+ogr.GetDriver(iDriver).GetName()+"'\n");
            }
            return;
         }

         if( !poDriver.TestCapability( ogr.ODrCCreateDataSource ) )
         {
            System.err.print(pszFormat + " driver does not support data source creation.\n");                 
            return;
         }

         /* -------------------------------------------------------------------- */
         /*      Now create it.                                                  */
         /* -------------------------------------------------------------------- */

         poDstDS = poDriver.CreateDataSource( pszOutputName );
         if( poDstDS == null )
         {
            System.err.print(pszFormat + " driver failed to create "+pszOutputName+"\n");
            return;
         }

         if ( poDstDS.GetLayerCount() == 0 )
         {
            FieldDefn oLocation = new FieldDefn( pszTileIndexField, ogr.OFTString );

            oLocation.SetWidth( 200 );

            if( nFirstSourceDataset < args.length-2 && args[nFirstSourceDataset].charAt(0) == '-' )
            {
               nFirstSourceDataset++;
            }

            SpatialReference poSrcSpatialRef = null;

            /* Fetches the SRS of the first layer and use it when creating the tileindex layer */
            if (nFirstSourceDataset < args.length)
            {
               DataSource poDS = ogr.Open( args[nFirstSourceDataset],false );

               if (poDS!=null)
               {
                  for(int iLayer = 0; iLayer < poDS.GetLayerCount(); iLayer++ )
                  {
                     boolean bRequested = bLayersWildcarded;
                     Layer poLayer = poDS.GetLayer(iLayer);

                     for(int iArg = 0; iArg < args.length && !bRequested; iArg++ )
                     {
                        if( args[iArg].equalsIgnoreCase("-lnum")
                              && Integer.parseInt(args[iArg+1]) == iLayer )
                           bRequested = true;
                        else if( args[iArg].equalsIgnoreCase("-lname")
                              && args[iArg+1].equalsIgnoreCase(poLayer.GetLayerDefn().GetName()) )
                           bRequested = true;
                     }

                     if( !bRequested )
                        continue;

                     if ( poLayer.GetSpatialRef() != null)
                        poSrcSpatialRef = poLayer.GetSpatialRef().Clone();
                     break;
                  }
               }

               poDS.delete();
            }

            poDstLayer = poDstDS.CreateLayer( "tileindex", poSrcSpatialRef );
            poDstLayer.CreateField( oLocation, ogr.OFTString );

            /* with the OGR Java bindings, avoid using the delete() methods,
             * except on the datasource objects, where it is necessary to close properly the
             * native file handles.
             */ 
            // poSrcSpatialRef.delete();
         }
      }

      /* -------------------------------------------------------------------- */
      /*      Identify target layer and field.                                */
      /* -------------------------------------------------------------------- */
      int   iTileIndexField;

      poDstLayer = poDstDS.GetLayer(0);
      if( poDstLayer == null )
      {
         System.err.print("Can't find any layer in output tileindex!\n" );
         return;
      }

      iTileIndexField =
         poDstLayer.GetLayerDefn().GetFieldIndex( pszTileIndexField );
      if( iTileIndexField == -1 )
      {
         System.err.print("Can't find "+pszTileIndexField+" field in tile index dataset.\n");
         return;
      }

      FeatureDefn poFeatureDefn = null;

      /* Load in memory existing file names in SHP */
      int nExistingLayers = 0;
      String[] existingLayersTab = null;
      SpatialReference alreadyExistingSpatialRef = null;
      boolean alreadyExistingSpatialRefValid = false;
      nExistingLayers = poDstLayer.GetFeatureCount();
      if (nExistingLayers > 0)
      {
         existingLayersTab = new String[nExistingLayers];
         for(int i=0;i<nExistingLayers;i++)
         {
            Feature feature = poDstLayer.GetNextFeature();
            existingLayersTab[i] = feature.GetFieldAsString( iTileIndexField);
            if (i == 0)
            {
               DataSource       poDS;
               String filename = existingLayersTab[i];
               int j;
               for(j=filename.length()-1;j>=0;j--)
               {
                  if (filename.charAt(j) == ',')
                     break;
               }
               if (j >= 0)
               {
                  int iLayer = Integer.parseInt(filename.substring(j + 1));
                  filename = filename.substring(0, j);
                  poDS = ogr.Open(filename,false );
                  if (poDS!=null)
                  {
                     Layer poLayer = poDS.GetLayer(iLayer);
                     if (poLayer!=null)
                     {
                        alreadyExistingSpatialRefValid = true;
                        alreadyExistingSpatialRef =
                           (poLayer.GetSpatialRef()!=null) ? poLayer.GetSpatialRef().Clone() : null;

                           if (poFeatureDefn == null) {
                              poFeatureDefn = CloneFeatureDefn(poLayer.GetLayerDefn()); // XXX: no Clone supported in java binding!!
                           }
                     }
                     poDS.delete();
                  }
               }
            }
         }
      }

      /* ignore check */
      //if (write_absolute_path)
      //{
      //   current_path = CPLGetCurrentDir();
      //   if (current_path == null)
      //   {
      //      fprintf( stderr, "This system does not support the CPLGetCurrentDir call. "
      //      "The option -write_absolute_path will have no effect\n");
      //      write_absolute_path = false;
      //   }
      //}
      /* ==================================================================== */
      /*      Process each input datasource in turn.                          */
      /* ==================================================================== */

      for(; nFirstSourceDataset < args.length; nFirstSourceDataset++ )
      {
         DataSource       poDS;

         if( args[nFirstSourceDataset].charAt(0) == '-' )
         {
            nFirstSourceDataset++;
            continue;
         }

         String fileNameToWrite;

         //VSIStatBuf sStatBuf;
         // FIXME: handle absolute path check
         //if (write_absolute_path && CPLIsFilenameRelative( args[nFirstSourceDataset] ) &&
         //      VSIStat( args[nFirstSourceDataset], &sStatBuf ) == 0)
         //{
         //   fileNameToWrite = CPLStrdup(CPLProjectRelativeFilename(current_path,args[nFirstSourceDataset]));
         //}
         //else
         //{
         //   fileNameToWrite = args[nFirstSourceDataset];
         //}
         fileNameToWrite = args[nFirstSourceDataset];

         poDS = ogr.Open( args[nFirstSourceDataset], false );

         if( poDS == null )
         {
            System.err.print("Failed to open dataset "+args[nFirstSourceDataset]+", skipping.\n");
            continue;
         }

         /* -------------------------------------------------------------------- */
         /*      Check all layers, and see if they match requests.               */
         /* -------------------------------------------------------------------- */
         for(int iLayer = 0; iLayer < poDS.GetLayerCount(); iLayer++ )
         {
            boolean bRequested = bLayersWildcarded;
            Layer poLayer = poDS.GetLayer(iLayer);

            for(int iArg = 0; iArg < args.length && !bRequested; iArg++ )
            {
               if( args[iArg].equalsIgnoreCase("-lnum")
                     && Integer.parseInt(args[iArg+1]) == iLayer )
                  bRequested = true;
               else if( args[iArg].equalsIgnoreCase("-lname")
                     && args[iArg+1].equalsIgnoreCase(poLayer.GetLayerDefn().GetName()) )
                  bRequested = true;
            }

            if( !bRequested )
               continue;

            /* Checks that the layer is not already in tileindex */
            int i;
            for(i=0;i<nExistingLayers;i++)
            {
               String szLocation = fileNameToWrite+","+iLayer;
               if (szLocation.equalsIgnoreCase(existingLayersTab[i]))
               {
                  System.err.println("Layer "+iLayer+" of "+args[nFirstSourceDataset]+" is already in tileindex. Skipping it.\n");
                  break;
               }
            }
            if (i != nExistingLayers)
            {
               continue;
            }

            SpatialReference spatialRef = poLayer.GetSpatialRef();
            if (alreadyExistingSpatialRefValid)
            {
               if ((spatialRef != null && alreadyExistingSpatialRef != null &&
                     spatialRef.IsSame(alreadyExistingSpatialRef) == 0) ||
                     ((spatialRef != null) != (alreadyExistingSpatialRef != null)))
               {
                  System.err.print("Warning : layer "+iLayer+" of "+args[nFirstSourceDataset]+" is not using the same projection system as "
                        + "other files in the tileindex. This may cause problems when "
                        + "using it in MapServer for example."+((skip_different_projection) ? " Skipping it" : "")+"\n");
                  ;
                  if (skip_different_projection)
                  {
                     continue;
                  }
               }
            }
            else
            {
               alreadyExistingSpatialRefValid = true;
               alreadyExistingSpatialRef = (spatialRef!=null) ? spatialRef.Clone() : null;
            }

            /* -------------------------------------------------------------------- */
            /*    Check if all layers in dataset have the same attributes  schema. */
            /* -------------------------------------------------------------------- */
            if( poFeatureDefn == null )
            {
               poFeatureDefn = CloneFeatureDefn(poLayer.GetLayerDefn()); // XXX: no Clone supported in java binding!!
            }
            else if ( !accept_different_schemas )
            {
               FeatureDefn poFeatureDefnCur = poLayer.GetLayerDefn();
               assert(null != poFeatureDefnCur);

               int fieldCount = poFeatureDefnCur.GetFieldCount();

               if( fieldCount != poFeatureDefn.GetFieldCount())
               {
                  System.err.print("Number of attributes of layer "+poLayer.GetLayerDefn().GetName()+" of "+args[nFirstSourceDataset]+" does not match ... skipping it.\n");

                  if (bFirstWarningForNonMatchingAttributes)
                  {
                     System.err.print("Note : you can override this behaviour with -accept_different_schemas option\n"
                           + "but this may result in a tileindex incompatible with MapServer\n");
                     bFirstWarningForNonMatchingAttributes = false;
                  }
                  continue;
               }

               boolean bSkip = false;
               for( int fn = 0; fn < poFeatureDefnCur.GetFieldCount(); fn++ )
               {
                  FieldDefn poField = poFeatureDefn.GetFieldDefn(fn);
                  FieldDefn poFieldCur = poFeatureDefnCur.GetFieldDefn(fn);

                  /* XXX - Should those pointers be checked against null? */
                  assert(null != poField);
                  assert(null != poFieldCur);

                  if( !poField.GetTypeName().equalsIgnoreCase(poFieldCur.GetTypeName())
                        || poField.GetWidth() != poFieldCur.GetWidth()
                        || poField.GetPrecision() != poFieldCur.GetPrecision()
                        || !poField.GetNameRef().equalsIgnoreCase(poFieldCur.GetNameRef()) )
                  {
                     System.err.print("Schema of attributes of layer "+poLayer.GetLayerDefn().GetName()+" of "+args[nFirstSourceDataset]+" does not match ... skipping it.\n");

                     if (bFirstWarningForNonMatchingAttributes)
                     {
                        System.err.print("Note : you can override this behaviour with -accept_different_schemas option\n"
                              + "but this may result in a tileindex incompatible with MapServer\n");
                        bFirstWarningForNonMatchingAttributes = false;
                     }
                     bSkip = true;
                     break;
                  }
               }

               if (bSkip)
                  continue;
            }


            /* -------------------------------------------------------------------- */
            /*      Get layer extents, and create a corresponding polygon           */
            /*      geometry.                                                       */
            /* -------------------------------------------------------------------- */
            double sExtents[] = poLayer.GetExtent(true);
            Geometry/*Polygon*/ oRegion = new Geometry(ogr.wkbPolygon);
            Geometry/*LinearRing*/ oRing = new Geometry(ogr.wkbLinearRing);
            
            if (sExtents == null) {
               System.err.print("GetExtent() failed on layer "+poLayer.GetLayerDefn().GetName()+" of "+args[nFirstSourceDataset]+", skipping.\n");
               continue;
            }
                                   
            // XXX: sExtents [minX, maxX, minY, maxY]
            //oRing.addPoint( sExtents.MinX, sExtents.MinY );
            //oRing.addPoint( sExtents.MinX, sExtents.MaxY );
            //oRing.addPoint( sExtents.MaxX, sExtents.MaxY );
            //oRing.addPoint( sExtents.MaxX, sExtents.MinY );
            //oRing.addPoint( sExtents.MinX, sExtents.MinY );
            oRing.AddPoint_2D( sExtents[0], sExtents[2] );
            oRing.AddPoint_2D( sExtents[0], sExtents[3] );
            oRing.AddPoint_2D( sExtents[1], sExtents[3] );
            oRing.AddPoint_2D( sExtents[1], sExtents[2] );
            oRing.AddPoint_2D( sExtents[0], sExtents[2] );

            oRegion.AddGeometry( oRing );

            /* -------------------------------------------------------------------- */
            /*      Add layer to tileindex.                                         */
            /* -------------------------------------------------------------------- */
            String        szLocation = fileNameToWrite+","+iLayer;
            Feature  oTileFeat = new Feature( poDstLayer.GetLayerDefn() );

            oTileFeat.SetGeometry( oRegion );
            oTileFeat.SetField( iTileIndexField, szLocation );

            if( poDstLayer.CreateFeature( oTileFeat ) != ogr.OGRERR_NONE )
            {
               System.err.print("Failed to create feature on tile index ... terminating." );
               poDS.delete();
               poDstDS.delete();
               return;
            }
         }

         /* -------------------------------------------------------------------- */
         /*      Cleanup this data source.                                       */
         /* -------------------------------------------------------------------- */
         poDS.delete();
      }

      /* -------------------------------------------------------------------- */
      /*      Close tile index and clear buffers.                             */
      /* -------------------------------------------------------------------- */
 
View Full Code Here


     * returns a collection of read geometries.
     */
    static Geometry LoadGeometry(String srcDS, String srcSQL, String srcLyr,
            String srcWhere) {

        DataSource DS;
        Layer lyr;
        Feature feat;
        Geometry geom = null;

        DS = ogr.Open(srcDS, false);

        if (DS == null) {

            return null;
        }

        if (srcSQL != null) {

            lyr = DS.ExecuteSQL(srcSQL, null, null);
        } else if (srcLyr != null) {

            lyr = DS.GetLayerByName(srcLyr);
        } else {

            lyr = DS.GetLayer(0);
        }

        if (lyr == null) {

            System.err
                    .println("Failed to identify source layer from datasource.");
            DS.delete();
            return null;
        }

        if (srcWhere != null) {

            lyr.SetAttributeFilter(srcWhere);
        }

        while ((feat = lyr.GetNextFeature()) != null) {

            Geometry srcGeom = feat.GetGeometryRef();

            if (srcGeom != null) {

                int srcType = srcGeom.GetGeometryType()
                        & (~ogrConstants.wkb25DBit);

                if (geom == null) {

                    geom = new Geometry(ogr.wkbMultiPolygon);
                }

                if (srcType == ogr.wkbPolygon) {

                    geom.AddGeometry(srcGeom);
                } else if (srcType == ogr.wkbMultiPolygon) {

                    int geomIndex = 0;
                    int geomCount = srcGeom.GetGeometryCount();

                    for (geomIndex = 0; geomIndex < geomCount; geomIndex++) {

                        geom.AddGeometry(srcGeom.GetGeometryRef(geomIndex));
                    }

                } else {

                    System.err
                            .println("FAILURE: Geometry not of polygon type.");

                    if (srcSQL != null) {

                        DS.ReleaseResultSet(lyr);
                    }

                    DS.delete();

                    return null;
                }
            }
        }

        if (srcSQL != null) {

            DS.ReleaseResultSet(lyr);
        }

        DS.delete();

        return geom;
    }
View Full Code Here

        /*
         * Open input datasource.
         */

        DataSource srcDS = ogr.Open(sourceFilename);

        if (srcDS == null) {

            System.out.println("Unable to open input datasource '"
                    + sourceFilename);
            System.out.println(gdal.GetLastErrorMsg());
            System.exit(3);
        }

        /*
         * Create target raster file.
         */

        Dataset dstDS = null;
        String[] layerList = layers.split(":");
        int layerCount = layerList.length;
        int bandCount = layerCount;

        if (SQL != null) {
            bandCount++;
        }

        if (sizeX == 0) {
            sizeX = 256;
        }

        if (sizeY == 0) {
            sizeY = 256;
        }

        String[] optionList = createOptions == null ? null : createOptions
                .split(":");

        dstDS = driver.Create(outputFilename, sizeX, sizeY, 1, outputType,
                optionList);

        if (dstDS == null) {

            System.out.println("Unable to create dataset '" + outputFilename);
            System.out.println(gdal.GetLastErrorMsg());
            System.exit(3);
        }

        /*
         * Use terminal progress report
         */
        if (quiet == false) {

            progressCallback = new TermProgressCallback();
        }

        /*
         * Process SQL request.
         */

        if (SQL != null) {

            Layer srcLayer = srcDS.ExecuteSQL(SQL);

            if (srcLayer != null) {

                ProcessLayer(srcLayer, dstDS, clipSrc, sizeX, sizeY, 1,
                        isXExtentSet, isYExtentSet, minX, maxX, minY, maxY,
                        burnAttribute, outputType, algorithmAndOptions, quiet,
                        progressCallback);
            }
        }

        /*
         * Process each layer.
         */

        for (int i = 0; i < layerList.length; i++) {

            Layer srcLayer = srcDS.GetLayerByName(layerList[i]);

            if (srcLayer == null) {

                System.out.println("Unable to find layer '" + layerList[i]);
                continue;
            }

            if (where != null) {

                if (srcLayer.SetAttributeFilter(where) != gdalconstConstants.CE_None) {
                    break;
                }
            }

            if (spatialFilter != null) {

                srcLayer.SetSpatialFilter(spatialFilter);
            }

            if (outputSRS == null) {

                SpatialReference srs = srcLayer.GetSpatialRef();

                if (srs != null) {

                    outputSRS = srs.ExportToWkt();
                }
            }

            ProcessLayer(srcLayer, dstDS, clipSrc, sizeX, sizeY, i + 1
                    + bandCount - layerCount, isXExtentSet, isYExtentSet, minX,
                    maxX, minY, maxY, burnAttribute, outputType,
                    algorithmAndOptions, quiet, progressCallback);
        }

        /*
         * Apply geotransformation matrix.
         */

        double[] geoTransform = new double[6];

        geoTransform[0] = minX[0];
        geoTransform[1] = (maxX[0] - minX[0]) / sizeX;
        geoTransform[2] = 0.0;
        geoTransform[3] = minY[0];
        geoTransform[4] = 0.0;
        geoTransform[5] = (maxY[0] - minY[0]) / sizeY;

        dstDS.SetGeoTransform(geoTransform);

        /*
         * Apply SRS definition if set.
         */

        if (outputSRS != null) {

            dstDS.SetProjection(outputSRS);
        }

        /*
         * Cleanup.
         */

        srcDS.delete();
        dstDS.delete();

        gdal.GDALDestroyDriverManager();
    }
View Full Code Here

        /*
         * Create the outputfile.
         */

        DataSource dataSource = null;
        Driver driver = ogr.GetDriverByName(outputFormat);
        FieldDefn field = null;
        Layer layer = null;

        if (driver == null) {

            System.err.println("Unable to find format driver named "
                    + outputFormat);
            System.exit(10);
        }

        dataSource = driver.CreateDataSource(outputFilename);

        if (dataSource == null) {
            System.exit(1);
        }

        if (threeDimension) {
            layer = dataSource.CreateLayer(newLayerName, srs,
                    ogr.wkbLineString25D);
        } else {
            layer = dataSource
                    .CreateLayer(newLayerName, srs, ogr.wkbLineString);
        }

        if (layer == null) {
            System.exit(1);
        }

        field = new FieldDefn("ID", ogr.OFTInteger);
        field.SetWidth(8);

        layer.CreateField(field, 0);
        field.delete();

        if (attributName != null) {

            field = new FieldDefn(attributName, ogr.OFTReal);
            field.SetWidth(12);
            field.SetPrecision(3);

            layer.CreateField(field, 0);
            layer.delete();
        }

        /*
         * Use terminal progress report
         */

        if (quiet == false) {
            progressCallback = new ProgressCallback();
        }

        /*
         * Invoke.
         */

        FeatureDefn feature = layer.GetLayerDefn();
       
        gdal.ContourGenerate(band, contourInterval, offset, fixedLevelsDouble,
                (ignoreNodata ? 1 : 0), sourceNodata, layer, feature.GetFieldIndex("ID"),
                (attributName != null ? feature.GetFieldIndex(attributName) : -1),
                progressCallback);
       
        dataSource.delete();
        dataset.delete();
    }
View Full Code Here

            }
        }
    /* -------------------------------------------------------------------- */
    /*      Open data source.                                               */
    /* -------------------------------------------------------------------- */
        DataSource poDS;
           
        poDS = ogr.Open( pszDataSource, false );
   
    /* -------------------------------------------------------------------- */
    /*      Report failure                                                  */
    /* -------------------------------------------------------------------- */
        if( poDS == null )
        {
            System.err.println("FAILURE:\n" +
                    "Unable to open datasource ` " + pszDataSource + "' with the following drivers.");
   
            for( int iDriver = 0; iDriver < ogr.GetDriverCount(); iDriver++ )
            {
                System.err.println("  . " + ogr.GetDriver(iDriver).GetName() );
            }
   
            System.exit( 1 );
        }
   
    /* -------------------------------------------------------------------- */
    /*      Try opening the output datasource as an existing, writable      */
    /* -------------------------------------------------------------------- */
        DataSource       poODS = null;
        Driver poDriver = null;
       
        if( bUpdate )
        {
            poODS = ogr.Open( pszDestDataSource, true );
            if( poODS == null )
            {
                if (bOverwrite || bAppend)
                {
                    poODS = ogr.Open( pszDestDataSource, false );
                    if ( poODS == null )
                    {
                        /* ok the datasource doesn't exist at all */
                        bUpdate = false;
                    }
                    else
                    {
                        poODS.delete();
                        poODS = null;
                    }
                }

                if (bUpdate)
                {
                    System.err.println("FAILURE:\n" +
                            "Unable to open existing output datasource `" + pszDestDataSource + "'.");
                    System.exit( 1 );
                }
            }
   
            else if( papszDSCO.size() > 0 )
            {
                System.err.println("WARNING: Datasource creation options ignored since an existing datasource\n" +
                        "         being updated." );
            }

            if (poODS != null)
                poDriver = poODS.GetDriver();
        }
   
    /* -------------------------------------------------------------------- */
    /*      Find the output driver.                                         */
    /* -------------------------------------------------------------------- */
        if( !bUpdate )
        {
            int                  iDriver;
   
            poDriver = ogr.GetDriverByName(pszFormat);
            if( poDriver == null )
            {
                System.err.println("Unable to find driver `" + pszFormat +"'." );
                System.err.println( "The following drivers are available:" );
           
                for( iDriver = 0; iDriver < ogr.GetDriverCount(); iDriver++ )
                {
                    System.err.println("  . " + ogr.GetDriver(iDriver).GetName() );
                }
                System.exit( 1 );
            }
   
            if( poDriver.TestCapability( ogr.ODrCCreateDataSource ) == false )
            {
                System.err.println( pszFormat + " driver does not support data source creation.");
                System.exit( 1 );
            }

    /* -------------------------------------------------------------------- */
    /*      Special case to improve user experience when translating        */
    /*      a datasource with multiple layers into a shapefile. If the      */
    /*      user gives a target datasource with .shp and it does not exist, */
    /*      the shapefile driver will try to create a file, but this is not */
    /*      appropriate because here we have several layers, so create      */
    /*      a directory instead.                                            */
    /* -------------------------------------------------------------------- */
            if (poDriver.GetName().equalsIgnoreCase("ESRI Shapefile") &&
                pszSQLStatement == null &&
                (papszLayers.size() > 1 ||
                 (papszLayers.size() == 0 && poDS.GetLayerCount() > 1)) &&
                pszNewLayerName == null &&
                (pszDestDataSource.endsWith(".shp") || pszDestDataSource.endsWith(".SHP")))
            {
                File f = new File(pszDestDataSource);
                if (!f.exists())
                {
                    if (!f.mkdir())
                    {
                        System.err.println(
                            "Failed to create directory " + pszDestDataSource + "\n" +
                            "for shapefile datastore.");
                        System.exit(1);
                    }
                }
            }

    /* -------------------------------------------------------------------- */
    /*      Create the output data source.                                  */
    /* -------------------------------------------------------------------- */
            poODS = poDriver.CreateDataSource( pszDestDataSource, papszDSCO );
            if( poODS == null )
            {
                System.err.println( pszFormat + " driver failed to create "+ pszDestDataSource );
                System.exit( 1 );
            }
        }
   
    /* -------------------------------------------------------------------- */
    /*      Parse the output SRS definition if possible.                    */
    /* -------------------------------------------------------------------- */
        if( pszOutputSRSDef != null )
        {
            poOutputSRS = new SpatialReference();
            if( poOutputSRS.SetFromUserInput( pszOutputSRSDef ) != 0 )
            {
                System.err.println( "Failed to process SRS definition: " + pszOutputSRSDef );
                System.exit( 1 );
            }
        }
   
    /* -------------------------------------------------------------------- */
    /*      Parse the source SRS definition if possible.                    */
    /* -------------------------------------------------------------------- */
        if( pszSourceSRSDef != null )
        {
            poSourceSRS = new SpatialReference();
            if( poSourceSRS.SetFromUserInput( pszSourceSRSDef ) != 0 )
            {
                System.err.println( "Failed to process SRS definition: " + pszSourceSRSDef );
                System.exit( 1 );
            }
        }
   
    /* -------------------------------------------------------------------- */
    /*      Special case for -sql clause.  No source layers required.       */
    /* -------------------------------------------------------------------- */
        if( pszSQLStatement != null )
        {
            Layer poResultSet;
   
            if( pszWHERE != null )
                System.err.println( "-where clause ignored in combination with -sql." );
            if( papszLayers.size() > 0 )
                System.err.println( "layer names ignored in combination with -sql." );
           
            poResultSet = poDS.ExecuteSQL( pszSQLStatement, poSpatialFilter,
                                            null );
   
            if( poResultSet != null )
            {
                long nCountLayerFeatures = 0;
                if (bDisplayProgress)
                {
                    if (!poResultSet.TestCapability(ogr.OLCFastFeatureCount))
                    {
                        System.err.println( "Progress turned off as fast feature count is not available.");
                        bDisplayProgress = false;
                    }
                    else
                    {
                        nCountLayerFeatures = poResultSet.GetFeatureCount();
                        pfnProgress = new TermProgressCallback();
                    }
                }

/* -------------------------------------------------------------------- */
/*      Special case to improve user experience when translating into   */
/*      single file shapefile and source has only one layer, and that   */
/*      the layer name isn't specified                                  */
/* -------------------------------------------------------------------- */
                if (poDriver.GetName().equalsIgnoreCase("ESRI Shapefile") &&
                    pszNewLayerName == null)
                {
                    File f = new File(pszDestDataSource);
                    if (f.exists() && f.listFiles() == null)
                    {
                        pszNewLayerName = f.getName();
                        int posPoint = pszNewLayerName.lastIndexOf('.');
                        if (posPoint != -1)
                            pszNewLayerName = pszNewLayerName.substring(0, posPoint);
                    }
                }

                if( !TranslateLayer( poDS, poResultSet, poODS, papszLCO,
                                    pszNewLayerName, bTransform, poOutputSRS,
                                    poSourceSRS, papszSelFields, bAppend, eGType,
                                    bOverwrite, eGeomOp, dfGeomOpParam, papszFieldTypesToString,
                                    nCountLayerFeatures, poClipSrc, poClipDst, bExplodeCollections,
                                    pszZField, pszWHERE, pfnProgress ))
                {
                    System.err.println(
                            "Terminating translation prematurely after failed\n" +
                            "translation from sql statement." );
   
                    System.exit( 1 );
                }
                poDS.ReleaseResultSet( poResultSet );
            }
        }
        else
        {
            int nLayerCount = 0;
            Layer[] papoLayers = null;

    /* -------------------------------------------------------------------- */
    /*      Process each data source layer.                                 */
    /* -------------------------------------------------------------------- */
            if ( papszLayers.size() == 0)
            {
                nLayerCount = poDS.GetLayerCount();
                papoLayers = new Layer[nLayerCount];

                for( int iLayer = 0;
                    iLayer < nLayerCount;
                    iLayer++ )
                {
                    Layer        poLayer = poDS.GetLayer(iLayer);

                    if( poLayer == null )
                    {
                        System.err.println("FAILURE: Couldn't fetch advertised layer " + iLayer + "!");
                        System.exit( 1 );
                    }

                    papoLayers[iLayer] = poLayer;
                }
            }
    /* -------------------------------------------------------------------- */
    /*      Process specified data source layers.                           */
    /* -------------------------------------------------------------------- */
            else
            {
                nLayerCount = papszLayers.size();
                papoLayers = new Layer[nLayerCount];

                for( int iLayer = 0;
                    iLayer < papszLayers.size();
                    iLayer++ )
                {
                    Layer        poLayer = poDS.GetLayerByName((String)papszLayers.get(iLayer));

                    if( poLayer == null )
                    {
                        System.err.println("FAILURE: Couldn't fetch advertised layer " + (String)papszLayers.get(iLayer) + "!");
                        System.exit( 1 );
                    }

                    papoLayers[iLayer] = poLayer;
                }
            }

/* -------------------------------------------------------------------- */
/*      Special case to improve user experience when translating into   */
/*      single file shapefile and source has only one layer, and that   */
/*      the layer name isn't specified                                  */
/* -------------------------------------------------------------------- */
            if (poDriver.GetName().equalsIgnoreCase("ESRI Shapefile") &&
                nLayerCount == 1 && pszNewLayerName == null)
            {
                File f = new File(pszDestDataSource);
                if (f.exists() && f.listFiles() == null)
                {
                    pszNewLayerName = f.getName();
                    int posPoint = pszNewLayerName.lastIndexOf('.');
                    if (posPoint != -1)
                        pszNewLayerName = pszNewLayerName.substring(0, posPoint);
                }
            }

            long[] panLayerCountFeatures = new long[nLayerCount];
            long nCountLayersFeatures = 0;
            long nAccCountFeatures = 0;

            /* First pass to apply filters and count all features if necessary */
            for( int iLayer = 0;
                iLayer < nLayerCount;
                iLayer++ )
            {
                Layer        poLayer = papoLayers[iLayer];

                if( pszWHERE != null )
                {
                    if( poLayer.SetAttributeFilter( pszWHERE ) != ogr.OGRERR_NONE )
                    {
                        System.err.println("FAILURE: SetAttributeFilter(" + pszWHERE + ") failed.");
                        if (!bSkipFailures)
                            System.exit( 1 );
                    }
                }

                if( poSpatialFilter != null )
                    poLayer.SetSpatialFilter( poSpatialFilter );

                if (bDisplayProgress)
                {
                    if (!poLayer.TestCapability(ogr.OLCFastFeatureCount))
                    {
                        System.err.println("Progress turned off as fast feature count is not available.");
                        bDisplayProgress = false;
                    }
                    else
                    {
                        panLayerCountFeatures[iLayer] = poLayer.GetFeatureCount();
                        nCountLayersFeatures += panLayerCountFeatures[iLayer];
                    }
                }
            }

            /* Second pass to do the real job */
            for( int iLayer = 0;
                iLayer < nLayerCount;
                iLayer++ )
            {
                Layer        poLayer = papoLayers[iLayer];

                if (bDisplayProgress)
                {
                    pfnProgress = new GDALScaledProgress(
                            nAccCountFeatures * 1.0 / nCountLayersFeatures,
                            (nAccCountFeatures + panLayerCountFeatures[iLayer]) * 1.0 / nCountLayersFeatures,
                            new TermProgressCallback());
                }

                nAccCountFeatures += panLayerCountFeatures[iLayer];

                if( !TranslateLayer( poDS, poLayer, poODS, papszLCO,
                                    pszNewLayerName, bTransform, poOutputSRS,
                                    poSourceSRS, papszSelFields, bAppend, eGType,
                                    bOverwrite, eGeomOp, dfGeomOpParam, papszFieldTypesToString,
                                    panLayerCountFeatures[iLayer], poClipSrc, poClipDst, bExplodeCollections,
                                    pszZField, pszWHERE, pfnProgress)
                    && !bSkipFailures )
                {
                    System.err.println(
                            "Terminating translation prematurely after failed\n" +
                            "translation of layer " + poLayer.GetLayerDefn().GetName() + " (use -skipfailures to skip errors)");

                    System.exit( 1 );
                }
            }
        }

    /* -------------------------------------------------------------------- */
    /*      Close down.                                                     */
    /* -------------------------------------------------------------------- */
        /* We must explicetely destroy the output dataset in order the file */
        /* to be properly closed ! */
        poODS.delete();
        poDS.delete();
    }
View Full Code Here

    static Geometry LoadGeometry( String pszDS,
                                  String pszSQL,
                                  String pszLyr,
                                  String pszWhere)
    {
        DataSource       poDS;
        Layer            poLyr;
        Feature          poFeat;
        Geometry         poGeom = null;
           
        poDS = ogr.Open( pszDS, false );
        if (poDS == null)
            return null;
   
        if (pszSQL != null)
            poLyr = poDS.ExecuteSQL( pszSQL, null, null );
        else if (pszLyr != null)
            poLyr = poDS.GetLayerByName(pszLyr);
        else
            poLyr = poDS.GetLayer(0);
           
        if (poLyr == null)
        {
            System.err.print("Failed to identify source layer from datasource.\n");
            poDS.delete();
            return null;
        }
       
        if (pszWhere != null)
            poLyr.SetAttributeFilter(pszWhere);
           
        while ((poFeat = poLyr.GetNextFeature()) != null)
        {
            Geometry poSrcGeom = poFeat.GetGeometryRef();
            if (poSrcGeom != null)
            {
                int eType = wkbFlatten(poSrcGeom.GetGeometryType());
               
                if (poGeom == null)
                    poGeom = new Geometry( ogr.wkbMultiPolygon );
   
                if( eType == ogr.wkbPolygon )
                    poGeom.AddGeometry( poSrcGeom );
                else if( eType == ogr.wkbMultiPolygon )
                {
                    int iGeom;
                    int nGeomCount = poSrcGeom.GetGeometryCount();
   
                    for( iGeom = 0; iGeom < nGeomCount; iGeom++ )
                    {
                        poGeom.AddGeometry(poSrcGeom.GetGeometryRef(iGeom) );
                    }
                }
                else
                {
                    System.err.print("ERROR: Geometry not of polygon type.\n" );
                    if( pszSQL != null )
                        poDS.ReleaseResultSet( poLyr );
                    poDS.delete();
                    return null;
                }
            }
        }

        if( pszSQL != null )
            poDS.ReleaseResultSet( poLyr );
        poDS.delete();

        return poGeom;
    }
View Full Code Here

        return new SpatialReference(wkt);
    }

    public static void main(String[] args) throws Exception {
        ogr.RegisterAll();
        DataSource ds = ogr.Open("/Users/jdeolive/Projects/geotools/git/modules/library/sample-data/src/main/resources/org/geotools/test-data/shapes/statepop.shp");
       
        double[] d = ds.GetLayer(0).GetExtent();
        System.out.println(d);
    }
View Full Code Here

TOP

Related Classes of org.gdal.ogr.DataSource

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.