Beispiel #1
0
static void ReportOnLayer( OGRLayer * poLayer )

{
    OGRFeatureDefn      *poDefn = poLayer->GetLayerDefn();

    printf( "\n" );
    
    printf( "Layer name: %s\n", poDefn->GetName() );

    printf( "Feature Count: %d\n", poLayer->GetFeatureCount() );

    if( bVerbose )
    {
        char    *pszWKT;
        
        if( poLayer->GetSpatialRef() == NULL )
            pszWKT = CPLStrdup( "(NULL)" );
        else
            poLayer->GetSpatialRef()->exportToWkt( &pszWKT );

        printf( "Layer SRS WKT: %s\n", pszWKT );
        CPLFree( pszWKT );
    }
    
    for( int iAttr = 0; iAttr < poDefn->GetFieldCount(); iAttr++ )
    {
        OGRFieldDefn    *poField = poDefn->GetFieldDefn( iAttr );

        printf( "%s: %s (%d.%d)\n",
                poField->GetNameRef(),
                poField->GetFieldTypeName( poField->GetType() ),
                poField->GetWidth(),
                poField->GetPrecision() );
    }

/* -------------------------------------------------------------------- */
/*      Read, and dump features.                                        */
/* -------------------------------------------------------------------- */
    OGRFeature  *poFeature;
    while( (poFeature = poLayer->GetNextFeature()) != NULL )
    {
        poFeature->DumpReadable( stdout );
        delete poFeature;
    }
}
OGRErr      OGRLayerWithTransaction::AlterFieldDefn( int iField,
        OGRFieldDefn* poNewFieldDefn,
        int nFlags )
{
    if( !m_poDecoratedLayer ) return OGRERR_FAILURE;
    OGRErr eErr = m_poDecoratedLayer->AlterFieldDefn(iField, poNewFieldDefn, nFlags);
    if( m_poFeatureDefn && eErr == OGRERR_NONE )
    {
        OGRFieldDefn* poSrcFieldDefn = m_poDecoratedLayer->GetLayerDefn()->GetFieldDefn(iField);
        OGRFieldDefn* poDstFieldDefn = m_poFeatureDefn->GetFieldDefn(iField);
        poDstFieldDefn->SetName(poSrcFieldDefn->GetNameRef());
        poDstFieldDefn->SetType(poSrcFieldDefn->GetType());
        poDstFieldDefn->SetSubType(poSrcFieldDefn->GetSubType());
        poDstFieldDefn->SetWidth(poSrcFieldDefn->GetWidth());
        poDstFieldDefn->SetPrecision(poSrcFieldDefn->GetPrecision());
        poDstFieldDefn->SetDefault(poSrcFieldDefn->GetDefault());
        poDstFieldDefn->SetNullable(poSrcFieldDefn->IsNullable());
    }
    return eErr;
}
int main( int nArgc, char ** papszArgv )

{
    int   nFirstSourceDataset = -1, bLayersWildcarded = TRUE, iArg;
    const char *pszFormat = "ESRI Shapefile";
    const char *pszTileIndexField = "LOCATION";
    const char *pszOutputName = NULL;
    int write_absolute_path = FALSE;
    int skip_different_projection = FALSE;
    char* current_path = NULL;
    int accept_different_schemas = FALSE;
    int bFirstWarningForNonMatchingAttributes = TRUE;
    
    /* Check strict compilation and runtime library version as we use C++ API */
    if (! GDAL_CHECK_VERSION(papszArgv[0]))
        exit(1);
/* -------------------------------------------------------------------- */
/*      Register format(s).                                             */
/* -------------------------------------------------------------------- */
    OGRRegisterAll();
    
/* -------------------------------------------------------------------- */
/*      Processing command line arguments.                              */
/* -------------------------------------------------------------------- */
    for( iArg = 1; iArg < nArgc; iArg++ )
    {
        if( EQUAL(papszArgv[iArg], "--utility_version") )
        {
            printf("%s was compiled against GDAL %s and is running against GDAL %s\n",
                   papszArgv[0], GDAL_RELEASE_NAME, GDALVersionInfo("RELEASE_NAME"));
            return 0;
        }
        else if( EQUAL(papszArgv[iArg],"-f") && iArg < nArgc-1 )
        {
            pszFormat = papszArgv[++iArg];
        }
        else if( EQUAL(papszArgv[iArg],"-write_absolute_path"))
        {
            write_absolute_path = TRUE;
        }
        else if( EQUAL(papszArgv[iArg],"-skip_different_projection"))
        {
            skip_different_projection = TRUE;
        }
        else if( EQUAL(papszArgv[iArg],"-accept_different_schemas"))
        {
            accept_different_schemas = TRUE;
        }
        else if( EQUAL(papszArgv[iArg],"-tileindex") && iArg < nArgc-1 )
        {
            pszTileIndexField = papszArgv[++iArg];
        }
        else if( EQUAL(papszArgv[iArg],"-lnum") 
                 || EQUAL(papszArgv[iArg],"-lname") )
        {
            iArg++;
            bLayersWildcarded = FALSE;
        }
        else if( papszArgv[iArg][0] == '-' )
            Usage();
        else if( pszOutputName == NULL )
            pszOutputName = papszArgv[iArg];
        else if( nFirstSourceDataset == -1 )
            nFirstSourceDataset = iArg;
    }

    if( pszOutputName == NULL || nFirstSourceDataset == -1 )
        Usage();

/* -------------------------------------------------------------------- */
/*      Try to open as an existing dataset for update access.           */
/* -------------------------------------------------------------------- */
    OGRDataSource *poDstDS;
    OGRLayer *poDstLayer = NULL;

    poDstDS = OGRSFDriverRegistrar::Open( pszOutputName, TRUE );

/* -------------------------------------------------------------------- */
/*      If that failed, find the driver so we can create the tile index.*/
/* -------------------------------------------------------------------- */
    if( poDstDS == NULL )
    {
        OGRSFDriverRegistrar     *poR = OGRSFDriverRegistrar::GetRegistrar();
        OGRSFDriver              *poDriver = NULL;
        int                      iDriver;

        for( iDriver = 0;
             iDriver < poR->GetDriverCount() && poDriver == NULL;
             iDriver++ )
        {
            if( EQUAL(poR->GetDriver(iDriver)->GetName(),pszFormat) )
            {
                poDriver = poR->GetDriver(iDriver);
            }
        }

        if( poDriver == NULL )
        {
            fprintf( stderr, "Unable to find driver `%s'.\n", pszFormat );
            fprintf( stderr, "The following drivers are available:\n" );
        
            for( iDriver = 0; iDriver < poR->GetDriverCount(); iDriver++ )
            {
                fprintf( stderr, "  -> `%s'\n", poR->GetDriver(iDriver)->GetName() );
            }
            exit( 1 );
        }

        if( !poDriver->TestCapability( ODrCCreateDataSource ) )
        {
            fprintf( stderr, "%s driver does not support data source creation.\n",
                    pszFormat );
            exit( 1 );
        }

/* -------------------------------------------------------------------- */
/*      Now create it.                                                  */
/* -------------------------------------------------------------------- */
        
        poDstDS = poDriver->CreateDataSource( pszOutputName, NULL );
        if( poDstDS == NULL )
        {
            fprintf( stderr, "%s driver failed to create %s\n", 
                    pszFormat, pszOutputName );
            exit( 1 );
        }

        if( poDstDS->GetLayerCount() == 0 )
        {
            OGRFieldDefn oLocation( pszTileIndexField, OFTString );
            
            oLocation.SetWidth( 200 );
            
            if( nFirstSourceDataset < nArgc && papszArgv[nFirstSourceDataset][0] == '-' )
            {
                nFirstSourceDataset++;
            }
            
            OGRSpatialReference* poSrcSpatialRef = NULL;
            
            /* Fetches the SRS of the first layer and use it when creating the tileindex layer */
            if (nFirstSourceDataset < nArgc)
            {
                OGRDataSource* poDS = OGRSFDriverRegistrar::Open( papszArgv[nFirstSourceDataset], 
                                           FALSE );
                                           
                if (poDS)
                {
                    int iLayer;

                    for( iLayer = 0; iLayer < poDS->GetLayerCount(); iLayer++ )
                    {
                        int bRequested = bLayersWildcarded;
                        OGRLayer *poLayer = poDS->GetLayer(iLayer);

                        for( iArg = 1; iArg < nArgc && !bRequested; iArg++ )
                        {
                            if( EQUAL(papszArgv[iArg],"-lnum") 
                                && atoi(papszArgv[iArg+1]) == iLayer )
                                bRequested = TRUE;
                            else if( EQUAL(papszArgv[iArg],"-lname") 
                                     && EQUAL(papszArgv[iArg+1],
                                              poLayer->GetLayerDefn()->GetName()) )
                                bRequested = TRUE;
                        }

                        if( !bRequested )
                            continue;
                            
                        if ( poLayer->GetSpatialRef() )
                            poSrcSpatialRef = poLayer->GetSpatialRef()->Clone();
                        break;
                    }
                }
                
                OGRDataSource::DestroyDataSource( poDS );
            }

            poDstLayer = poDstDS->CreateLayer( "tileindex", poSrcSpatialRef );
            poDstLayer->CreateField( &oLocation, OFTString );
            
            OGRSpatialReference::DestroySpatialReference( poSrcSpatialRef );
        }
    }

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

    poDstLayer = poDstDS->GetLayer(0);
    if( poDstLayer == NULL )
    {
        fprintf( stderr, "Can't find any layer in output tileindex!\n" );
        exit( 1 );
    }

    iTileIndexField = 
        poDstLayer->GetLayerDefn()->GetFieldIndex( pszTileIndexField );
    if( iTileIndexField == -1 )
    {
        fprintf( stderr, "Can't find %s field in tile index dataset.\n", 
                pszTileIndexField );
        exit( 1 );
    }

    OGRFeatureDefn* poFeatureDefn = NULL;

    /* Load in memory existing file names in SHP */
    int nExistingLayers = 0;
    char** existingLayersTab = NULL;
    OGRSpatialReference* alreadyExistingSpatialRef = NULL;
    int alreadyExistingSpatialRefValid = FALSE;
    nExistingLayers = poDstLayer->GetFeatureCount();
    if (nExistingLayers)
    {
        int i;
        existingLayersTab = (char**)CPLMalloc(nExistingLayers * sizeof(char*));
        for(i=0;i<nExistingLayers;i++)
        {
            OGRFeature* feature = poDstLayer->GetNextFeature();
            existingLayersTab[i] = CPLStrdup(feature->GetFieldAsString( iTileIndexField));
            if (i == 0)
            {
                OGRDataSource       *poDS;
                char* filename = CPLStrdup(existingLayersTab[i]);
                int j;
                for(j=strlen(filename)-1;j>=0;j--)
                {
                    if (filename[j] == ',')
                        break;
                }
                if (j >= 0)
                {
                    int iLayer = atoi(filename + j + 1);
                    filename[j] = 0;
                    poDS = OGRSFDriverRegistrar::Open(filename, 
                                                    FALSE );
                    if (poDS)
                    {
                        OGRLayer *poLayer = poDS->GetLayer(iLayer);
                        if (poLayer)
                        {
                            alreadyExistingSpatialRefValid = TRUE;
                            alreadyExistingSpatialRef =
                                    (poLayer->GetSpatialRef()) ? poLayer->GetSpatialRef()->Clone() : NULL;
                                    
                            if (poFeatureDefn == NULL)
                                poFeatureDefn = poLayer->GetLayerDefn()->Clone();
                        }
                        OGRDataSource::DestroyDataSource( poDS );
                    }
                }
            }
        }
    }


    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 < nArgc; nFirstSourceDataset++ )
    {
        int i;
        OGRDataSource       *poDS;

        if( papszArgv[nFirstSourceDataset][0] == '-' )
        {
            nFirstSourceDataset++;
            continue;
        }
        
        char* fileNameToWrite;
        VSIStatBuf sStatBuf;

        if (write_absolute_path && CPLIsFilenameRelative( papszArgv[nFirstSourceDataset] ) &&
            VSIStat( papszArgv[nFirstSourceDataset], &sStatBuf ) == 0)
        {
            fileNameToWrite = CPLStrdup(CPLProjectRelativeFilename(current_path,papszArgv[nFirstSourceDataset]));
        }
        else
        {
            fileNameToWrite = CPLStrdup(papszArgv[nFirstSourceDataset]);
        }

        poDS = OGRSFDriverRegistrar::Open( papszArgv[nFirstSourceDataset], 
                                           FALSE );

        if( poDS == NULL )
        {
            fprintf( stderr, "Failed to open dataset %s, skipping.\n", 
                    papszArgv[nFirstSourceDataset] );
            CPLFree(fileNameToWrite);
            continue;
        }

/* -------------------------------------------------------------------- */
/*      Check all layers, and see if they match requests.               */
/* -------------------------------------------------------------------- */
        int iLayer;

        for( iLayer = 0; iLayer < poDS->GetLayerCount(); iLayer++ )
        {
            int bRequested = bLayersWildcarded;
            OGRLayer *poLayer = poDS->GetLayer(iLayer);

            for( iArg = 1; iArg < nArgc && !bRequested; iArg++ )
            {
                if( EQUAL(papszArgv[iArg],"-lnum") 
                    && atoi(papszArgv[iArg+1]) == iLayer )
                    bRequested = TRUE;
                else if( EQUAL(papszArgv[iArg],"-lname") 
                         && EQUAL(papszArgv[iArg+1],
                                  poLayer->GetLayerDefn()->GetName()) )
                    bRequested = TRUE;
            }

            if( !bRequested )
                continue;

            /* Checks that the layer is not already in tileindex */
            for(i=0;i<nExistingLayers;i++)
            {
                char        szLocation[5000];
                sprintf( szLocation, "%s,%d", 
                        fileNameToWrite, iLayer );
                if (EQUAL(szLocation, existingLayersTab[i]))
                {
                    fprintf(stderr, "Layer %d of %s is already in tileindex. Skipping it.\n",
                            iLayer, papszArgv[nFirstSourceDataset]);
                    break;
                }
            }
            if (i != nExistingLayers)
            {
                continue;
            }

            OGRSpatialReference* spatialRef = poLayer->GetSpatialRef();
            if (alreadyExistingSpatialRefValid)
            {
                if ((spatialRef != NULL && alreadyExistingSpatialRef != NULL &&
                     spatialRef->IsSame(alreadyExistingSpatialRef) == FALSE) ||
                    ((spatialRef != NULL) != (alreadyExistingSpatialRef != NULL)))
                {
                    fprintf(stderr, "Warning : layer %d of %s is not using the same projection system as "
                                "other files in the tileindex. This may cause problems when "
                                "using it in MapServer for example.%s\n", iLayer, papszArgv[nFirstSourceDataset],
                                (skip_different_projection) ? " Skipping it" : "");
                    if (skip_different_projection)
                    {
                        continue;
                    }
                }
            }
            else
            {
                alreadyExistingSpatialRefValid = TRUE;
                alreadyExistingSpatialRef = (spatialRef) ? spatialRef->Clone() : NULL;
            }

/* -------------------------------------------------------------------- */
/*		Check if all layers in dataset have the same attributes	schema. */
/* -------------------------------------------------------------------- */
			if( poFeatureDefn == NULL )
			{
				poFeatureDefn = poLayer->GetLayerDefn()->Clone();
			}
			else if ( !accept_different_schemas )
			{
				OGRFeatureDefn* poFeatureDefnCur = poLayer->GetLayerDefn();
				assert(NULL != poFeatureDefnCur);

				int fieldCount = poFeatureDefnCur->GetFieldCount();

				if( fieldCount != poFeatureDefn->GetFieldCount())
				{
					fprintf( stderr, "Number of attributes of layer %s of %s does not match ... skipping it.\n",
                             poLayer->GetLayerDefn()->GetName(), papszArgv[nFirstSourceDataset]);
                    if (bFirstWarningForNonMatchingAttributes)
                    {
                        fprintf( stderr, "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;
				}
				
                int bSkip = FALSE;
				for( int fn = 0; fn < poFeatureDefnCur->GetFieldCount(); fn++ )
				{
 					OGRFieldDefn* poField = poFeatureDefn->GetFieldDefn(fn);
 					OGRFieldDefn* poFieldCur = poFeatureDefnCur->GetFieldDefn(fn);

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

					if( poField->GetType() != poFieldCur->GetType() 
						|| poField->GetWidth() != poFieldCur->GetWidth() 
						|| poField->GetPrecision() != poFieldCur->GetPrecision() 
						|| !EQUAL( poField->GetNameRef(), poFieldCur->GetNameRef() ) )
					{
						fprintf( stderr, "Schema of attributes of layer %s of %s does not match ... skipping it.\n",
                                 poLayer->GetLayerDefn()->GetName(), papszArgv[nFirstSourceDataset]);
                        if (bFirstWarningForNonMatchingAttributes)
                        {
                            fprintf( stderr, "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.                                                       */
/* -------------------------------------------------------------------- */
            OGREnvelope sExtents;
            OGRPolygon oRegion;
            OGRLinearRing oRing;

            if( poLayer->GetExtent( &sExtents, TRUE ) != OGRERR_NONE )
            {
                fprintf( stderr, "GetExtent() failed on layer %s of %s, skipping.\n", 
                        poLayer->GetLayerDefn()->GetName(), 
                        papszArgv[nFirstSourceDataset] );
                continue;
            }
            
            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 );

            oRegion.addRing( &oRing );

/* -------------------------------------------------------------------- */
/*      Add layer to tileindex.                                         */
/* -------------------------------------------------------------------- */
            char        szLocation[5000];
            OGRFeature  oTileFeat( poDstLayer->GetLayerDefn() );

            sprintf( szLocation, "%s,%d", 
                     fileNameToWrite, iLayer );
            oTileFeat.SetGeometry( &oRegion );
            oTileFeat.SetField( iTileIndexField, szLocation );

            if( poDstLayer->CreateFeature( &oTileFeat ) != OGRERR_NONE )
            {
                fprintf( stderr, "Failed to create feature on tile index ... terminating." );
                OGRDataSource::DestroyDataSource( poDstDS );
                exit( 1 );
            }
        }

/* -------------------------------------------------------------------- */
/*      Cleanup this data source.                                       */
/* -------------------------------------------------------------------- */
        CPLFree(fileNameToWrite);
        OGRDataSource::DestroyDataSource( poDS );
    }

/* -------------------------------------------------------------------- */
/*      Close tile index and clear buffers.                             */
/* -------------------------------------------------------------------- */
    OGRDataSource::DestroyDataSource( poDstDS );
	OGRFeatureDefn::DestroyFeatureDefn( poFeatureDefn );
  
    if (alreadyExistingSpatialRef != NULL)
        OGRSpatialReference::DestroySpatialReference( alreadyExistingSpatialRef );
  
    CPLFree(current_path);
    
    if (nExistingLayers)
    {
        int i;
        for(i=0;i<nExistingLayers;i++)
        {
            CPLFree(existingLayersTab[i]);
        }
        CPLFree(existingLayersTab);
    }

    return 0;
}
Beispiel #4
0
/**********************************************************************
 *                          Tab2Tab()
 *
 * Copy features from source dataset to a new dataset
 **********************************************************************/
static int Tab2Tab(const char *pszSrcFname, const char *pszDstFname,
                   int nMaxFeatures, 
                   GBool bQuickSpatialIndexMode, GBool bOptSpatialIndexMode)
{
    IMapInfoFile *poSrcFile = NULL, *poDstFile = NULL;
    int      nFeatureId, iField, numFeatures=0;
    TABFeature *poFeature;
    double dXMin, dYMin, dXMax, dYMax;

    /*---------------------------------------------------------------------
     * If there is a "micdsys.txt" in current directory then load it
     *--------------------------------------------------------------------*/
    MITABLoadCoordSysTable("micdsys.txt");

    /*---------------------------------------------------------------------
     * Try to open source file
     *--------------------------------------------------------------------*/
    if ((poSrcFile = IMapInfoFile::SmartOpen(pszSrcFname)) == NULL)
    {
        printf("Failed to open %s\n", pszSrcFname);
        return -1;
    }

    OGRFeatureDefn *poDefn = poSrcFile->GetLayerDefn();

    /*---------------------------------------------------------------------
     * The extension of the output filename tells us if we should create
     * a MIF or a TAB file for output.
     *--------------------------------------------------------------------*/
    if (EQUAL(".mif", pszDstFname + strlen(pszDstFname)-4) ||
        EQUAL(".mid", pszDstFname + strlen(pszDstFname)-4) )
    {
        // Create a MIF file
        poDstFile = new MIFFile;
    }
    else
    {
        /*-----------------------------------------------------------------
         * Create a TAB dataset.
         * Find out if the file contains at least 1 unique field... if so we
         * will create a TABView instead of a TABFile
         *----------------------------------------------------------------*/
        GBool    bFoundUniqueField = FALSE;
        for(iField=0; iField< poDefn->GetFieldCount(); iField++)
        {
            if (poSrcFile->IsFieldUnique(iField))
                bFoundUniqueField = TRUE;
        }

        if (bFoundUniqueField)
            poDstFile = new TABView;
        else
            poDstFile = new TABFile;
    }

    /*---------------------------------------------------------------------
     * Try to open destination file
     *--------------------------------------------------------------------*/
    if (poDstFile->Open(pszDstFname, "wb") != 0)
    {
        printf("Failed to open %s\n", pszDstFname);
        poSrcFile->Close();
        delete poSrcFile;
        delete poDstFile;
        return -1;
    }

    if ( (bQuickSpatialIndexMode && 
          poDstFile->SetQuickSpatialIndexMode(TRUE) != 0) ||
         (bOptSpatialIndexMode && 
          poDstFile->SetQuickSpatialIndexMode(FALSE) != 0) )
    {
        printf("Failed setting Quick Spatial Index Mode (-q|-o) on %s\n", pszDstFname);
        poSrcFile->Close();
        delete poSrcFile;
        poDstFile->Close();
        delete poDstFile;
        return -1;
    }

    // Pass Proj. info directly
    // TABProjInfo sProjInfo;
    // if (poSrcFile->GetProjInfo(&sProjInfo) == 0)
    //     poDstFile->SetProjInfo(&sProjInfo);

    OGRSpatialReference *poSR;

    poSR = poSrcFile->GetSpatialRef();
    if( poSR != NULL )
    {
        poDstFile->SetSpatialRef( poSR );
    }

    //  Set bounds (must be done after setting spatialref)
    if (poSrcFile->GetBounds(dXMin, dYMin, dXMax, dYMax) == 0)
        poDstFile->SetBounds(dXMin, dYMin, dXMax, dYMax);

    /*---------------------------------------------------------------------
     * Pass compplete fields information
     *--------------------------------------------------------------------*/
    for(iField=0; iField< poDefn->GetFieldCount(); iField++)
    {
        OGRFieldDefn *poFieldDefn = poDefn->GetFieldDefn(iField);

        poDstFile->AddFieldNative(poFieldDefn->GetNameRef(),
                                  poSrcFile->GetNativeFieldType(iField),
                                  poFieldDefn->GetWidth(),
                                  poFieldDefn->GetPrecision(),
                                  poSrcFile->IsFieldIndexed(iField),
                                  poSrcFile->IsFieldUnique(iField));
    }

    /*---------------------------------------------------------------------
     * Copy objects until EOF is reached
     *--------------------------------------------------------------------*/
    nFeatureId = -1;
    while ( (nFeatureId = poSrcFile->GetNextFeatureId(nFeatureId)) != -1 &&
            (nMaxFeatures < 1 || numFeatures++ < nMaxFeatures ))
    {
        poFeature = poSrcFile->GetFeatureRef(nFeatureId);
        if (poFeature)
        {
//            poFeature->DumpReadable(stdout);
//            poFeature->DumpMIF();
            poDstFile->CreateFeature(poFeature);
        }
        else
        {
            printf( "Failed to read feature %d.\n",
                    nFeatureId );
            return -1;      // GetFeatureRef() failed: Error
        }
    }

    /*---------------------------------------------------------------------
     * Cleanup and exit.
     *--------------------------------------------------------------------*/
    poDstFile->Close();
    delete poDstFile;

    poSrcFile->Close();
    delete poSrcFile;

    MITABFreeCoordSysTable();

    return 0;
}
Beispiel #5
0
static void ReportOnLayer( OGRLayer * poLayer, const char *pszWHERE, 
                           OGRGeometry *poSpatialFilter )

{
    OGRFeatureDefn      *poDefn = poLayer->GetLayerDefn();

/* -------------------------------------------------------------------- */
/*      Set filters if provided.                                        */
/* -------------------------------------------------------------------- */
    if( pszWHERE != NULL )
        poLayer->SetAttributeFilter( pszWHERE );

    if( poSpatialFilter != NULL )
        poLayer->SetSpatialFilter( poSpatialFilter );

/* -------------------------------------------------------------------- */
/*      Report various overall information.                             */
/* -------------------------------------------------------------------- */
    printf( "\n" );
    
    printf( "Layer name: %s\n", poDefn->GetName() );

    if( bVerbose )
    {
        printf( "Geometry: %s\n", 
                OGRGeometryTypeToName( poDefn->GetGeomType() ) );
        
        printf( "Feature Count: %d\n", poLayer->GetFeatureCount() );
        
        OGREnvelope oExt;
        if (poLayer->GetExtent(&oExt, TRUE) == OGRERR_NONE)
        {
            printf("Extent: (%f, %f) - (%f, %f)\n", 
                   oExt.MinX, oExt.MinY, oExt.MaxX, oExt.MaxY);
        }

        char    *pszWKT;
        
        if( poLayer->GetSpatialRef() == NULL )
            pszWKT = CPLStrdup( "(unknown)" );
        else
        {
            poLayer->GetSpatialRef()->exportToPrettyWkt( &pszWKT );
        }            

        printf( "Layer SRS WKT:\n%s\n", pszWKT );
        CPLFree( pszWKT );
    
        if( strlen(poLayer->GetFIDColumn()) > 0 )
            printf( "FID Column = %s\n", 
                    poLayer->GetFIDColumn() );
    
        if( strlen(poLayer->GetGeometryColumn()) > 0 )
            printf( "Geometry Column = %s\n", 
                    poLayer->GetGeometryColumn() );

        for( int iAttr = 0; iAttr < poDefn->GetFieldCount(); iAttr++ )
        {
            OGRFieldDefn    *poField = poDefn->GetFieldDefn( iAttr );
            
            printf( "%s: %s (%d.%d)\n",
                    poField->GetNameRef(),
                    poField->GetFieldTypeName( poField->GetType() ),
                    poField->GetWidth(),
                    poField->GetPrecision() );
        }
    }

/* -------------------------------------------------------------------- */
/*      Read, and dump features.                                        */
/* -------------------------------------------------------------------- */
    OGRFeature  *poFeature = NULL;

    if( nFetchFID == OGRNullFID && !bSummaryOnly )
    {
        while( (poFeature = poLayer->GetNextFeature()) != NULL )
        {
            poFeature->DumpReadable( NULL, papszOptions );
            OGRFeature::DestroyFeature( poFeature );
        }
    }
    else if( nFetchFID != OGRNullFID )
    {
        poFeature = poLayer->GetFeature( nFetchFID );
        if( poFeature == NULL )
        {
            printf( "Unable to locate feature id %d on this layer.\n", 
                    nFetchFID );
        }
        else
        {
            poFeature->DumpReadable( NULL, papszOptions );
            OGRFeature::DestroyFeature( poFeature );
        }
    }
}
Beispiel #6
0
static void ReportOnLayer( OGRLayer * poLayer, int bVerbose )

{
    OGRFeatureDefn      *poDefn = poLayer->GetLayerDefn();


/* -------------------------------------------------------------------- */
/*      Report various overall information.                             */
/* -------------------------------------------------------------------- */
    printf( "\n" );

    printf( "Layer name: %s\n", poLayer->GetName() );

    if( bVerbose )
    {
        int nGeomFieldCount =
            poLayer->GetLayerDefn()->GetGeomFieldCount();
        if( nGeomFieldCount > 1 )
        {
            for(int iGeom = 0;iGeom < nGeomFieldCount; iGeom ++ )
            {
                OGRGeomFieldDefn* poGFldDefn =
                    poLayer->GetLayerDefn()->GetGeomFieldDefn(iGeom);
                printf( "Geometry (%s): %s\n", poGFldDefn->GetNameRef(),
                    OGRGeometryTypeToName( poGFldDefn->GetType() ) );
            }
        }
        else
        {
            printf( "Geometry: %s\n",
                    OGRGeometryTypeToName( poLayer->GetGeomType() ) );
        }

        printf( "Feature Count: " CPL_FRMT_GIB "\n", poLayer->GetFeatureCount() );

        OGREnvelope oExt;
        if( nGeomFieldCount > 1 )
        {
            for(int iGeom = 0;iGeom < nGeomFieldCount; iGeom ++ )
            {
                if (poLayer->GetExtent(iGeom, &oExt, TRUE) == OGRERR_NONE)
                {
                    OGRGeomFieldDefn* poGFldDefn =
                        poLayer->GetLayerDefn()->GetGeomFieldDefn(iGeom);
                    CPLprintf("Extent (%s): (%f, %f) - (%f, %f)\n",
                           poGFldDefn->GetNameRef(),
                           oExt.MinX, oExt.MinY, oExt.MaxX, oExt.MaxY);
                }
            }
        }
        else if ( poLayer->GetExtent(&oExt, TRUE) == OGRERR_NONE)
        {
            CPLprintf("Extent: (%f, %f) - (%f, %f)\n",
                   oExt.MinX, oExt.MinY, oExt.MaxX, oExt.MaxY);
        }

        char    *pszWKT;

        if( nGeomFieldCount > 1 )
        {
            for(int iGeom = 0;iGeom < nGeomFieldCount; iGeom ++ )
            {
                OGRGeomFieldDefn* poGFldDefn =
                    poLayer->GetLayerDefn()->GetGeomFieldDefn(iGeom);
                OGRSpatialReference* poSRS = poGFldDefn->GetSpatialRef();
                if( poSRS == NULL )
                    pszWKT = CPLStrdup( "(unknown)" );
                else
                {
                    poSRS->exportToPrettyWkt( &pszWKT );
                }

                printf( "SRS WKT (%s):\n%s\n",
                        poGFldDefn->GetNameRef(), pszWKT );
                CPLFree( pszWKT );
            }
        }
        else
        {
            if( poLayer->GetSpatialRef() == NULL )
                pszWKT = CPLStrdup( "(unknown)" );
            else
            {
                poLayer->GetSpatialRef()->exportToPrettyWkt( &pszWKT );
            }

            printf( "Layer SRS WKT:\n%s\n", pszWKT );
            CPLFree( pszWKT );
        }

        if( strlen(poLayer->GetFIDColumn()) > 0 )
            printf( "FID Column = %s\n",
                    poLayer->GetFIDColumn() );

        for(int iGeom = 0;iGeom < nGeomFieldCount; iGeom ++ )
        {
            OGRGeomFieldDefn* poGFldDefn =
                poLayer->GetLayerDefn()->GetGeomFieldDefn(iGeom);
            if( nGeomFieldCount == 1 &&
                EQUAL(poGFldDefn->GetNameRef(), "")  && poGFldDefn->IsNullable() )
                break;
            printf( "Geometry Column ");
            if( nGeomFieldCount > 1 )
                printf("%d ", iGeom + 1);
            if( !poGFldDefn->IsNullable() )
                printf("NOT NULL ");
            printf("= %s\n", poGFldDefn->GetNameRef() );
        }

        for( int iAttr = 0; iAttr < poDefn->GetFieldCount(); iAttr++ )
        {
            OGRFieldDefn    *poField = poDefn->GetFieldDefn( iAttr );
            const char* pszType = (poField->GetSubType() != OFSTNone) ?
                CPLSPrintf("%s(%s)",
                           poField->GetFieldTypeName( poField->GetType() ),
                           poField->GetFieldSubTypeName(poField->GetSubType())) :
                poField->GetFieldTypeName( poField->GetType() );
            printf( "%s: %s (%d.%d)",
                    poField->GetNameRef(),
                    pszType,
                    poField->GetWidth(),
                    poField->GetPrecision() );
            if( !poField->IsNullable() )
                printf(" NOT NULL");
            if( poField->GetDefault() != NULL )
                printf(" DEFAULT %s", poField->GetDefault() );
            printf( "\n" );
        }
    }

/* -------------------------------------------------------------------- */
/*      Read, and dump features.                                        */
/* -------------------------------------------------------------------- */
    OGRFeature  *poFeature = NULL;
    while( (poFeature = poLayer->GetNextFeature()) != NULL )
    {
        poFeature->DumpReadable( NULL );
        OGRFeature::DestroyFeature( poFeature );
    }
}
static CPLString OGRPGTableLayerGetType(OGRFieldDefn& oField,
                                        int bPreservePrecision,
                                        int bApproxOK)
{
    char                szFieldType[256];

    /* -------------------------------------------------------------------- */
    /*      Work out the PostgreSQL type.                                   */
    /* -------------------------------------------------------------------- */
    if( oField.GetType() == OFTInteger )
    {
        if( oField.GetWidth() > 0 && bPreservePrecision )
            sprintf( szFieldType, "NUMERIC(%d,0)", oField.GetWidth() );
        else
            strcpy( szFieldType, "INTEGER" );
    }
    else if( oField.GetType() == OFTReal )
    {
        if( oField.GetWidth() > 0 && oField.GetPrecision() > 0
                && bPreservePrecision )
            sprintf( szFieldType, "NUMERIC(%d,%d)",
                     oField.GetWidth(), oField.GetPrecision() );
        else
            strcpy( szFieldType, "FLOAT8" );
    }
    else if( oField.GetType() == OFTString )
    {
        if (oField.GetWidth() > 0 &&  bPreservePrecision )
            sprintf( szFieldType, "VARCHAR(%d)",  oField.GetWidth() );
        else
            strcpy( szFieldType, "VARCHAR");
    }
    else if( oField.GetType() == OFTIntegerList )
    {
        strcpy( szFieldType, "INTEGER[]" );
    }
    else if( oField.GetType() == OFTRealList )
    {
        strcpy( szFieldType, "FLOAT8[]" );
    }
    else if( oField.GetType() == OFTStringList )
    {
        strcpy( szFieldType, "varchar[]" );
    }
    else if( oField.GetType() == OFTDate )
    {
        strcpy( szFieldType, "date" );
    }
    else if( oField.GetType() == OFTTime )
    {
        strcpy( szFieldType, "time" );
    }
    else if( oField.GetType() == OFTDateTime )
    {
        strcpy( szFieldType, "timestamp with time zone" );
    }
    else if( oField.GetType() == OFTBinary )
    {
        strcpy( szFieldType, "bytea" );
    }
    else if( bApproxOK )
    {
        CPLError( CE_Warning, CPLE_NotSupported,
                  "Can't create field %s with type %s on PostgreSQL layers.  Creating as VARCHAR.",
                  oField.GetNameRef(),
                  OGRFieldDefn::GetFieldTypeName(oField.GetType()) );
        strcpy( szFieldType, "VARCHAR" );
    }
    else
    {
        CPLError( CE_Failure, CPLE_NotSupported,
                  "Can't create field %s with type %s on PostgreSQL layers.",
                  oField.GetNameRef(),
                  OGRFieldDefn::GetFieldTypeName(oField.GetType()) );
        strcpy( szFieldType, "");
    }

    return szFieldType;
}
Beispiel #8
0
OGRErr OGROCILoaderLayer::WriteFeatureVariableMode( OGRFeature *poFeature )

{
    OGROCIStringBuf oLine;

    if( fpData == NULL )
        return OGRERR_FAILURE;

/* -------------------------------------------------------------------- */
/*      Write the FID.                                                  */
/* -------------------------------------------------------------------- */
    oLine.Append( "00000000" );
    oLine.Appendf( 32, " %d|", poFeature->GetFID() );

/* -------------------------------------------------------------------- */
/*      Set the geometry                                                */
/* -------------------------------------------------------------------- */
    if( poFeature->GetGeometryRef() != NULL)
    {
        char szSRID[128];
        int  nGType;
        int  i;

        if( nSRID == -1 )
            strcpy( szSRID, "NULL" );
        else
            sprintf( szSRID, "%d", nSRID );

        if( TranslateToSDOGeometry( poFeature->GetGeometryRef(), &nGType )
            == OGRERR_NONE )
        {
            oLine.Appendf( 32, "%d|", nGType );
            for( i = 0; i < nElemInfoCount; i++ )
            {
                oLine.Appendf( 32, "%d|", panElemInfo[i] );
            }
            oLine.Append( "/" );

            for( i = 0; i < nOrdinalCount; i++ )
            {
                oLine.Appendf( 32, "%.16g|", padfOrdinals[i] );
            }
            oLine.Append( "/" );
        }
        else
        {
            oLine.Append( "0|/|/" );
        }
    }
    else
    {
        oLine.Append( "0|/|/" );
    }

/* -------------------------------------------------------------------- */
/*      Set the other fields.                                           */
/* -------------------------------------------------------------------- */
    int i;

    for( i = 0; i < poFeatureDefn->GetFieldCount(); i++ )
    {
        OGRFieldDefn *poFldDefn = poFeatureDefn->GetFieldDefn(i);

        if( !poFeature->IsFieldSet( i ) )
        {
            if( poFldDefn->GetType() != OFTInteger 
                && poFldDefn->GetType() != OFTReal )
                oLine.Append( "0000" );
            else
                oLine.Append( "|" );
            continue;
        }

        const char *pszStrValue = poFeature->GetFieldAsString(i);

        if( poFldDefn->GetType() == OFTInteger 
            || poFldDefn->GetType() == OFTReal )
        {
            if( poFldDefn->GetWidth() > 0 && bPreservePrecision
                && (int) strlen(pszStrValue) > poFldDefn->GetWidth() )
            {
                ReportTruncation( poFldDefn );
                oLine.Append( "|" );
            }
            else
            {
                oLine.Append( pszStrValue );
                oLine.Append( "|" );
            }
        }
        else 
        {
            int nLength = strlen(pszStrValue);

            if( poFldDefn->GetWidth() > 0 && nLength > poFldDefn->GetWidth() )
            {
                ReportTruncation( poFldDefn );
                nLength = poFldDefn->GetWidth();
                ((char *) pszStrValue)[nLength] = '\0';
            }

            oLine.Appendf( 5, "%04d", nLength );
            oLine.Append( pszStrValue );
        }
    }

    oLine.Appendf( 3, "\n" );

/* -------------------------------------------------------------------- */
/*      Update the line's length, and write to disk.                    */
/* -------------------------------------------------------------------- */
    char szLength[9]; 
    size_t  nStringLen = strlen(oLine.GetString());

    sprintf( szLength, "%08d", (int) (nStringLen-8) );
    strncpy( oLine.GetString(), szLength, 8 );

    if( VSIFWrite( oLine.GetString(), 1, nStringLen, fpData ) != nStringLen )
    {
        CPLError( CE_Failure, CPLE_FileIO, 
                  "Write to loader file failed, likely out of disk space." );
        return OGRERR_FAILURE;
    }
    else
        return OGRERR_NONE;
}
Beispiel #9
0
OGRErr OGROCILoaderLayer::WriteFeatureStreamMode( OGRFeature *poFeature )

{
/* -------------------------------------------------------------------- */
/*      Write the FID.                                                  */
/* -------------------------------------------------------------------- */
    VSIFPrintf( fpLoader, " %ld|", poFeature->GetFID() );

/* -------------------------------------------------------------------- */
/*      Set the geometry                                                */
/* -------------------------------------------------------------------- */
    int  nLineLen = 0;
    if( poFeature->GetGeometryRef() != NULL)
    {
        char szSRID[128];
        int  nGType;
        int  i;

        if( nSRID == -1 )
            strcpy( szSRID, "NULL" );
        else
            sprintf( szSRID, "%d", nSRID );

        if( TranslateToSDOGeometry( poFeature->GetGeometryRef(), &nGType )
            == OGRERR_NONE )
        {
            VSIFPrintf( fpLoader, "%d|", nGType );
            for( i = 0; i < nElemInfoCount; i++ )
            {
                VSIFPrintf( fpLoader, "%d|", panElemInfo[i] );
                if( ++nLineLen > 18 && i < nElemInfoCount-1 )
                {
                    VSIFPrintf( fpLoader, "\n#" );
                    nLineLen = 0;
                }
            }
            VSIFPrintf( fpLoader, "/" );

            for( i = 0; i < nOrdinalCount; i++ )
            {
                VSIFPrintf( fpLoader, "%.16g|", padfOrdinals[i] );
                if( ++nLineLen > 6 && i < nOrdinalCount-1 )
                {
                    VSIFPrintf( fpLoader, "\n#" );
                    nLineLen = 0;
                }
            }
            VSIFPrintf( fpLoader, "/" );
        }
        else
        {
            VSIFPrintf( fpLoader, "0|/|/" );
        }
    }
    else
    {
        VSIFPrintf( fpLoader, "0|/|/" );
    }

/* -------------------------------------------------------------------- */
/*      Set the other fields.                                           */
/* -------------------------------------------------------------------- */
    int i;

    nLineLen = 0;
    VSIFPrintf( fpLoader, "\n#" );

    for( i = 0; i < poFeatureDefn->GetFieldCount(); i++ )
    {
        OGRFieldDefn *poFldDefn = poFeatureDefn->GetFieldDefn(i);

        if( !poFeature->IsFieldSet( i ) )
        {
            if( poFldDefn->GetType() != OFTInteger 
                && poFldDefn->GetType() != OFTReal )
                VSIFPrintf( fpLoader, "%04d", 0 );
            continue;
        }

        const char *pszStrValue = poFeature->GetFieldAsString(i);

        if( nLineLen > 70 )
        {
            VSIFPrintf( fpLoader, "\n#" );
            nLineLen = 0;
        }

        nLineLen += strlen(pszStrValue);

        if( poFldDefn->GetType() == OFTInteger 
            || poFldDefn->GetType() == OFTReal )
        {
            if( poFldDefn->GetWidth() > 0 && bPreservePrecision
                && (int) strlen(pszStrValue) > poFldDefn->GetWidth() )
            {
                ReportTruncation( poFldDefn );
                VSIFPrintf( fpLoader, "|" );
            }
            else
                VSIFPrintf( fpLoader, "%s|", pszStrValue );
        }
        else 
        {
            int nLength = strlen(pszStrValue);

            if( poFldDefn->GetWidth() > 0 && nLength > poFldDefn->GetWidth() )
            {
                ReportTruncation( poFldDefn );
                nLength = poFldDefn->GetWidth();
            }

            VSIFPrintf( fpLoader, "%04d", nLength );
            VSIFWrite( (void *) pszStrValue, 1, nLength, fpLoader );
        }
    }

    if( VSIFPrintf( fpLoader, "\n" ) == 0 )
    {
        CPLError( CE_Failure, CPLE_FileIO, 
                  "Write to loader file failed, likely out of disk space." );
        return OGRERR_FAILURE;
    }
    else
        return OGRERR_NONE;
}
Beispiel #10
0
static void ReportOnLayer( OGRLayer * poLayer, const char *pszWHERE, 
                           OGRGeometry *poSpatialFilter )

{
    OGRFeatureDefn      *poDefn = poLayer->GetLayerDefn();

/* -------------------------------------------------------------------- */
/*      Set filters if provided.                                        */
/* -------------------------------------------------------------------- */
    if( pszWHERE != NULL )
        poLayer->SetAttributeFilter( pszWHERE );

    if( poSpatialFilter != NULL )
        poLayer->SetSpatialFilter( poSpatialFilter );

/* -------------------------------------------------------------------- */
/*      Report various overall information.                             */
/* -------------------------------------------------------------------- */
    printf( "\n" );
    
    printf( "Layer name: %s\n", poDefn->GetName() );

    printf( "Geometry: %s\n", 
            OGRGeometryTypeToName( poDefn->GetGeomType() ) );

    printf( "Feature Count: %d\n", poLayer->GetFeatureCount() );

    OGREnvelope oExt;
    if (poLayer->GetExtent(&oExt, TRUE) == OGRERR_NONE)
    {
        printf("Extent: (%f, %f) - (%f, %f)\n", 
               oExt.MinX, oExt.MinY, oExt.MaxX, oExt.MaxY);
    }

    if( bVerbose )
    {
        char    *pszWKT;
        
        if( poLayer->GetSpatialRef() == NULL )
            pszWKT = CPLStrdup( "(NULL)" );
        else
            poLayer->GetSpatialRef()->exportToWkt( &pszWKT );

        printf( "Layer SRS WKT: %s\n", pszWKT );
        CPLFree( pszWKT );
    }
    
    for( int iAttr = 0; iAttr < poDefn->GetFieldCount(); iAttr++ )
    {
        OGRFieldDefn    *poField = poDefn->GetFieldDefn( iAttr );

        printf( "%s: %s (%d.%d)\n",
                poField->GetNameRef(),
                poField->GetFieldTypeName( poField->GetType() ),
                poField->GetWidth(),
                poField->GetPrecision() );
    }

/* -------------------------------------------------------------------- */
/*      Read, and dump features.                                        */
/* -------------------------------------------------------------------- */
    OGRFeature  *poFeature;

    while( (poFeature = poLayer->GetNextFeature()) != NULL )
    {
        poFeature->DumpReadable( stdout );
        delete poFeature;
    }

/* -------------------------------------------------------------------- */
/*      Read, and dump features.                                        */
/* -------------------------------------------------------------------- */
#ifdef notdef
    OGRFeature  *poFeature;
    int         nId = -1;

    while( (nId = poTF->GetNextFeatureId_Spatial(nId)) != -1 )
    {
        poFeature = poTF->GetFeatureRef( nId );
    }
#endif
}
Beispiel #11
0
/**********************************************************************
 *                          CreateIndex()
 *
 * Create index for specified field in an existing TAB dataset.
 **********************************************************************/
static int CreateIndex(const char *pszSrcFname, const char *pszField)
{
    IMapInfoFile *poSrcFile = NULL;
    int         nFeatureId, iField;
    TABFeature *poFeature;
    TABINDFile *poINDFile;

    /*---------------------------------------------------------------------
     * Try to open source file
     *--------------------------------------------------------------------*/
    if ((poSrcFile = IMapInfoFile::SmartOpen(pszSrcFname)) == NULL)
    {
        printf("Failed to open %s\n", pszSrcFname);
        return -1;
    }

    if (poSrcFile->GetFileClass() != TABFC_TABFile)
    {
        printf("Indexes cannot be added to this type of TAB datasets\n");
        poSrcFile->Close();
        delete poSrcFile;
        return -1;
    }

    /*---------------------------------------------------------------------
     * Make sure field exists and is not already indexed
     *--------------------------------------------------------------------*/
    OGRFeatureDefn *poDefn = poSrcFile->GetLayerDefn();
    if ( poDefn == NULL ||
         (iField = poDefn->GetFieldIndex(pszField)) == -1 ||
         poSrcFile->IsFieldIndexed(iField))
    {
        printf("Cannot create index: field '%s' not found or is already indexed.\n", 
               pszField);
        poSrcFile->Close();
        delete poSrcFile;
        return -1;
    }

    /*---------------------------------------------------------------------
     * Things seem OK... open IND file for update
     * (Note that TABINDFile automagically adjusts file extension)
     *--------------------------------------------------------------------*/
    poINDFile = new TABINDFile; 
    if ( poINDFile->Open(pszSrcFname, "r+", TRUE) != 0 &&
         poINDFile->Open(pszSrcFname, "w", TRUE) != 0)
    {
        printf("Unable to create IND file for %s.\n", pszSrcFname);
        delete poINDFile;
        poSrcFile->Close();
        delete poSrcFile;
        return -1;
    }

    int nNewIndexNo = -1;
    OGRFieldDefn *poFieldDefn = poDefn->GetFieldDefn(iField);
    TABFieldType eFieldType = poSrcFile->GetNativeFieldType(iField);
    if (poFieldDefn == NULL ||
        (nNewIndexNo = poINDFile->CreateIndex(eFieldType,
                                              poFieldDefn->GetWidth()) ) < 1)
    {
        // Failed... an error has already been reported.
        delete poINDFile;
        poSrcFile->Close();
        delete poSrcFile;
        return -1;
    }

    printf("Index number %d will be created for field %s...\n\n"
           "This program does not update the TAB header file (yet!) so you \n"
           "should edit %s and add 'Index %d' at the end of the definition \n"
           "of field %s.\n\n",
           nNewIndexNo, pszField, pszSrcFname, nNewIndexNo, pszField);

    /*---------------------------------------------------------------------
     * Add index entries until we reach EOF
     *--------------------------------------------------------------------*/
    nFeatureId = -1;
    while ( (nFeatureId = poSrcFile->GetNextFeatureId(nFeatureId)) != -1 )
    {
        poFeature = poSrcFile->GetFeatureRef(nFeatureId);
        if (poFeature)
        {
            GByte *pKey = NULL;
            switch(eFieldType)
            {
              case TABFChar:
                pKey = poINDFile->BuildKey(nNewIndexNo, 
                                        poFeature->GetFieldAsString(iField));
                break;
              case TABFInteger:
              case TABFSmallInt:
                pKey = poINDFile->BuildKey(nNewIndexNo, 
                                        poFeature->GetFieldAsInteger(iField));
                break;
              case TABFDecimal:
              case TABFFloat:
              case TABFLogical:
                pKey = poINDFile->BuildKey(nNewIndexNo, 
                                        poFeature->GetFieldAsDouble(iField));
                break;
              default:
              case TABFDate:
                CPLAssert(FALSE); // Unsupported for now.
            }

            if (poINDFile->AddEntry(nNewIndexNo, pKey, nFeatureId) != 0)
                return -1;
        }
        else
            break;      // GetFeatureRef() failed: Abort the loop
    }

    /*---------------------------------------------------------------------
     * Cleanup and exit.
     *--------------------------------------------------------------------*/
    poINDFile->Close();
    delete poINDFile;

    poSrcFile->Close();
    delete poSrcFile;

    MITABFreeCoordSysTable();

    return 0;
}
Beispiel #12
0
static void ReportOnLayer( OGRLayer * poLayer, const char *pszWHERE,
                           const char* pszGeomField,
                           OGRGeometry *poSpatialFilter,
                           bool bListMDD,
                           bool bShowMetadata,
                           char** papszExtraMDDomains,
                           bool bFeatureCount,
                           bool bExtent,
                           const char* pszWKTFormat )
{
    OGRFeatureDefn      *poDefn = poLayer->GetLayerDefn();

/* -------------------------------------------------------------------- */
/*      Set filters if provided.                                        */
/* -------------------------------------------------------------------- */
    if( pszWHERE != nullptr )
    {
        if( poLayer->SetAttributeFilter(pszWHERE) != OGRERR_NONE )
        {
            printf("FAILURE: SetAttributeFilter(%s) failed.\n", pszWHERE);
            exit(1);
        }
    }

    if( poSpatialFilter != nullptr )
    {
        if( pszGeomField != nullptr )
        {
            const int iGeomField = poDefn->GetGeomFieldIndex(pszGeomField);
            if( iGeomField >= 0 )
                poLayer->SetSpatialFilter(iGeomField, poSpatialFilter);
            else
                printf("WARNING: Cannot find geometry field %s.\n",
                       pszGeomField);
        }
        else
        {
            poLayer->SetSpatialFilter(poSpatialFilter);
        }
    }

/* -------------------------------------------------------------------- */
/*      Report various overall information.                             */
/* -------------------------------------------------------------------- */
    if( !bSuperQuiet )
    {
        printf("\n");
        printf("Layer name: %s\n", poLayer->GetName());
    }

    GDALInfoReportMetadata(static_cast<GDALMajorObjectH>(poLayer),
                           bListMDD,
                           bShowMetadata,
                           papszExtraMDDomains);

    if( bVerbose )
    {
        const int nGeomFieldCount =
            poLayer->GetLayerDefn()->GetGeomFieldCount();
        if( nGeomFieldCount > 1 )
        {
            for(int iGeom = 0;iGeom < nGeomFieldCount; iGeom ++ )
            {
                OGRGeomFieldDefn* poGFldDefn =
                    poLayer->GetLayerDefn()->GetGeomFieldDefn(iGeom);
                printf("Geometry (%s): %s\n", poGFldDefn->GetNameRef(),
                       OGRGeometryTypeToName(poGFldDefn->GetType()));
            }
        }
        else
        {
            printf("Geometry: %s\n",
                   OGRGeometryTypeToName(poLayer->GetGeomType()));
        }

        if( bFeatureCount )
            printf("Feature Count: " CPL_FRMT_GIB "\n",
                   poLayer->GetFeatureCount());

        OGREnvelope oExt;
        if( bExtent && nGeomFieldCount > 1 )
        {
            for( int iGeom = 0;iGeom < nGeomFieldCount; iGeom ++ )
            {
                if( poLayer->GetExtent(iGeom, &oExt, TRUE) == OGRERR_NONE )
                {
                    OGRGeomFieldDefn* poGFldDefn =
                        poLayer->GetLayerDefn()->GetGeomFieldDefn(iGeom);
                    CPLprintf("Extent (%s): (%f, %f) - (%f, %f)\n",
                              poGFldDefn->GetNameRef(),
                              oExt.MinX, oExt.MinY, oExt.MaxX, oExt.MaxY);
                }
            }
        }
        else if( bExtent && poLayer->GetExtent(&oExt, TRUE) == OGRERR_NONE )
        {
            CPLprintf("Extent: (%f, %f) - (%f, %f)\n",
                      oExt.MinX, oExt.MinY, oExt.MaxX, oExt.MaxY);
        }

        const auto displayDataAxisMapping = [](const OGRSpatialReference* poSRS) {
            const auto mapping = poSRS->GetDataAxisToSRSAxisMapping();
            printf("Data axis to CRS axis mapping: ");
            for( size_t i = 0; i < mapping.size(); i++ )
            {
                if( i > 0 )
                {
                    printf(",");
                }
                printf("%d", mapping[i]);
            }
            printf("\n");
        };

        if( nGeomFieldCount > 1 )
        {
            for(int iGeom = 0;iGeom < nGeomFieldCount; iGeom ++ )
            {
                OGRGeomFieldDefn* poGFldDefn =
                    poLayer->GetLayerDefn()->GetGeomFieldDefn(iGeom);
                OGRSpatialReference* poSRS = poGFldDefn->GetSpatialRef();
                char *pszWKT = nullptr;
                if( poSRS == nullptr )
                {
                    pszWKT = CPLStrdup("(unknown)");
                }
                else
                {
                    CPLString osWKTFormat("FORMAT=");
                    osWKTFormat += pszWKTFormat;
                    const char* const apszWKTOptions[] =
                        { osWKTFormat.c_str(), "MULTILINE=YES", nullptr };
                    poSRS->exportToWkt(&pszWKT, apszWKTOptions);
                }

                printf("SRS WKT (%s):\n%s\n",
                       poGFldDefn->GetNameRef(), pszWKT);
                CPLFree(pszWKT);
                if( poSRS )
                {
                    displayDataAxisMapping(poSRS);
                }
            }
        }
        else
        {
            char *pszWKT = nullptr;
            auto poSRS = poLayer->GetSpatialRef();
            if( poSRS == nullptr )
            {
                pszWKT = CPLStrdup("(unknown)");
            }
            else
            {
                poSRS->exportToPrettyWkt(&pszWKT);
            }

            printf("Layer SRS WKT:\n%s\n", pszWKT);
            CPLFree(pszWKT);
            if( poSRS )
            {
                displayDataAxisMapping(poSRS);
            }
        }

        if( strlen(poLayer->GetFIDColumn()) > 0 )
            printf("FID Column = %s\n",
                   poLayer->GetFIDColumn());

        for(int iGeom = 0;iGeom < nGeomFieldCount; iGeom ++ )
        {
            OGRGeomFieldDefn* poGFldDefn =
                poLayer->GetLayerDefn()->GetGeomFieldDefn(iGeom);
            if( nGeomFieldCount == 1 &&
                EQUAL(poGFldDefn->GetNameRef(), "") &&
                poGFldDefn->IsNullable() )
                break;
            printf("Geometry Column ");
            if( nGeomFieldCount > 1 )
                printf("%d ", iGeom + 1);
            if( !poGFldDefn->IsNullable() )
                printf("NOT NULL ");
            printf("= %s\n", poGFldDefn->GetNameRef());
        }

        for( int iAttr = 0; iAttr < poDefn->GetFieldCount(); iAttr++ )
        {
            OGRFieldDefn *poField = poDefn->GetFieldDefn(iAttr);
            const char* pszType = (poField->GetSubType() != OFSTNone)
                ? CPLSPrintf(
                      "%s(%s)",
                      poField->GetFieldTypeName(poField->GetType()),
                      poField->GetFieldSubTypeName(poField->GetSubType()))
                : poField->GetFieldTypeName(poField->GetType());
            printf("%s: %s (%d.%d)",
                   poField->GetNameRef(),
                   pszType,
                   poField->GetWidth(),
                   poField->GetPrecision());
            if( !poField->IsNullable() )
                printf(" NOT NULL");
            if( poField->GetDefault() != nullptr )
                printf(" DEFAULT %s", poField->GetDefault());
            printf("\n");
        }
    }

/* -------------------------------------------------------------------- */
/*      Read, and dump features.                                        */
/* -------------------------------------------------------------------- */

    if( nFetchFID == OGRNullFID && !bSummaryOnly )
    {
        OGRFeature *poFeature = nullptr;
        while( (poFeature = poLayer->GetNextFeature()) != nullptr )
        {
            if( !bSuperQuiet )
                poFeature->DumpReadable(nullptr, papszOptions);
            OGRFeature::DestroyFeature(poFeature);
        }
    }
    else if( nFetchFID != OGRNullFID )
    {
        OGRFeature *poFeature = poLayer->GetFeature(nFetchFID);
        if( poFeature == nullptr )
        {
            printf("Unable to locate feature id " CPL_FRMT_GIB
                   " on this layer.\n",
                   nFetchFID);
        }
        else
        {
            poFeature->DumpReadable(nullptr, papszOptions);
            OGRFeature::DestroyFeature(poFeature);
        }
    }
}
Beispiel #13
0
// extern "C" {
SEXP ogrInfo(SEXP ogrsourcename, SEXP Layer) {
    // return FIDs, nFields, fieldInfo

    SEXP ans, vec1, vec2, vec3,/*mat,*/drv, dvec;
    SEXP itemlist, itemnames, itemwidth, itemtype, itemTypeNames;
    SEXP itemlistmaxcount;
#ifdef GDALV2
    SEXP dFIDs;
#endif
    /*SEXP geotype;*/

    int nFIDs, nFields, iField, *nCount, pc=0;

#ifdef GDALV2
    GDALDriver *poDriver;
    GDALDataset *poDS;
#else
    OGRDataSource *poDS;
    OGRSFDriver *poDriver;
#endif
    OGRLayer *poLayer;
    OGRFeature *poFeature;
    OGRFeatureDefn *poDefn;
    /*  OGRGeometry *poGeom;*/

    installErrorHandler();
#ifdef GDALV2
    poDS=(GDALDataset*) GDALOpenEx(CHAR(STRING_ELT(ogrsourcename, 0)), GDAL_OF_VECTOR, NULL, NULL, NULL);
    if(poDS==NULL) {
        uninstallErrorHandlerAndTriggerError();
        error("Cannot open data source");
    }
    poDriver = poDS->GetDriver();
#else
    poDS=OGRSFDriverRegistrar::Open(CHAR(STRING_ELT(ogrsourcename, 0)),
                                    FALSE, &poDriver);
#endif
    uninstallErrorHandlerAndTriggerError();

    if(poDS==NULL) {
        installErrorHandler();
#ifdef GDALV2
        GDALClose( poDS );
#else
        OGRDataSource::DestroyDataSource( poDS );
#endif
        uninstallErrorHandlerAndTriggerError();
//    delete poDS;
        error("Cannot open file");
    }

    installErrorHandler();
    poLayer = poDS->GetLayerByName(CHAR(STRING_ELT(Layer, 0)));
    uninstallErrorHandlerAndTriggerError();

    if(poLayer == NULL) {
        installErrorHandler();
#ifdef GDALV2
        GDALClose( poDS );
#else
        OGRDataSource::DestroyDataSource( poDS );
#endif
        uninstallErrorHandlerAndTriggerError();
//    delete poDS;
        error("Cannot open layer");
    }

    // allocate a list for return values
    PROTECT(ans=allocVector(VECSXP,6));
    pc++;

    PROTECT(drv=allocVector(STRSXP,1));
    pc++;
    installErrorHandler();
#ifdef GDALV2
    SET_STRING_ELT(drv, 0, mkChar(poDriver->GetDescription()));
#else
    SET_STRING_ELT(drv, 0, mkChar(poDriver->GetName()));
#endif
    uninstallErrorHandlerAndTriggerError();
    SET_VECTOR_ELT(ans,3,drv);

    PROTECT(vec1=allocVector(INTSXP,1));
    pc++;
    installErrorHandler();
#ifdef GDALV2
    GIntBig nFIDs64 = poLayer->GetFeatureCount();
    nFIDs = (nFIDs64 > INT_MAX) ? INT_MAX :
            (nFIDs64 < INT_MIN) ? INT_MIN : (int) nFIDs64;
    if ((GIntBig) nFIDs != nFIDs64) {
        warning("ogrInfo: feature count overflow");
        INTEGER(vec1)[0]=NA_INTEGER;
        PROTECT(dFIDs=NEW_NUMERIC(1));
        pc++;
        NUMERIC_POINTER(dFIDs)[0] = (double) nFIDs64;
        setAttrib(vec1, install("dFIDs"), dFIDs);
    } else {
        // store number of FIDs
        INTEGER(vec1)[0]=nFIDs;
    }
#else
    nFIDs   = poLayer->GetFeatureCount();
    // store number of FIDs
    INTEGER(vec1)[0]=nFIDs;
#endif
    uninstallErrorHandlerAndTriggerError();

    if (nFIDs == -1) {
        int i=0;
        installErrorHandler();
        while( ((poFeature = poLayer->GetNextFeature()) != NULL) && i <= INT_MAX) {
            i++;
            OGRFeature::DestroyFeature( poFeature );
//    delete poFeature;
        }
        uninstallErrorHandlerAndTriggerError();
        if (i == INT_MAX) {
            error("ogrInfo: undeclared feature count overflow");
        } else {
            nFIDs = i;
            warning("ogrInfo: feature count not given; %d counted", nFIDs);
        }
        installErrorHandler();
        poLayer->ResetReading();
        uninstallErrorHandlerAndTriggerError();

        INTEGER(vec1)[0]=nFIDs;
    }

    SET_VECTOR_ELT(ans,0,vec1);



    // store other stuff....
    installErrorHandler();
    poDefn = poLayer->GetLayerDefn();
    nFields =  poDefn->GetFieldCount();
    uninstallErrorHandlerAndTriggerError();

    // store number of fields
    PROTECT(vec2=allocVector(INTSXP,1));
    pc++;
    INTEGER(vec2)[0]=nFields;
    SET_VECTOR_ELT(ans,1,vec2);
    installErrorHandler();
    OGREnvelope oExt;
    if (poLayer->GetExtent(&oExt, TRUE) == OGRERR_NONE) {
        PROTECT(dvec=allocVector(REALSXP,4));
        pc++;
        REAL(dvec)[0] = oExt.MinX;
        REAL(dvec)[1] = oExt.MinY;
        REAL(dvec)[2] = oExt.MaxX;
        REAL(dvec)[3] = oExt.MaxY;
        SET_VECTOR_ELT(ans,4,dvec);
    }
    uninstallErrorHandlerAndTriggerError();

    PROTECT(itemnames=allocVector(STRSXP,nFields));
    pc++;
    PROTECT(itemtype=allocVector(INTSXP,nFields));
    pc++;
    PROTECT(itemwidth=allocVector(INTSXP,nFields));
    pc++;
// try List types
    PROTECT(itemlistmaxcount=allocVector(INTSXP,nFields));
    pc++;
    PROTECT(itemTypeNames=allocVector(STRSXP,nFields));
    pc++;
    int listFieldCount=0;

    installErrorHandler();
    for(iField=0; iField<nFields; iField++) {
        OGRFieldDefn *poField = poDefn->GetFieldDefn(iField);
        SET_STRING_ELT(itemnames,iField,mkChar(poField->GetNameRef()));
        INTEGER(itemtype)[iField]=poField->GetType();
        if (INTEGER(itemtype)[iField] == OFTIntegerList ||
                INTEGER(itemtype)[iField] == OFTRealList ||
                INTEGER(itemtype)[iField] == OFTStringList) listFieldCount++;
        INTEGER(itemwidth)[iField]=poField->GetWidth();
        SET_STRING_ELT(itemTypeNames,iField,mkChar(poField->GetFieldTypeName(
                           poField->GetType())));
        INTEGER(itemlistmaxcount)[iField] = 0;
    }
    uninstallErrorHandlerAndTriggerError();

    PROTECT(vec3=allocVector(INTSXP,1));
    pc++;
    INTEGER(vec3)[0]=listFieldCount;
    SET_VECTOR_ELT(ans,5,vec3);
    PROTECT(itemlist=allocVector(VECSXP,5));
    pc++;
    SET_VECTOR_ELT(itemlist,0,itemnames);
    SET_VECTOR_ELT(itemlist,1,itemtype);
    SET_VECTOR_ELT(itemlist,2,itemwidth);
    SET_VECTOR_ELT(itemlist,3,itemTypeNames);
// try List types
    if (listFieldCount > 0) {

        poLayer->ResetReading();
        OGRFeature* poFeature;

        nCount = (int *) R_alloc((size_t) nFields, sizeof(int));
        for (iField=0; iField<nFields; iField++) nCount[iField] = 0;
        installErrorHandler();
        OGRField* psField;
        while( (poFeature = poLayer->GetNextFeature()) != NULL ) {
            for(iField=0; iField<nFields; iField++) {
                psField = poFeature->GetRawFieldRef(iField);
                if (INTEGER(itemtype)[iField] == OFTIntegerList) {
                    nCount[iField] = psField->IntegerList.nCount;
                    if (nCount[iField] > INTEGER(itemlistmaxcount)[iField])
                        INTEGER(itemlistmaxcount)[iField] = nCount[iField];
                } else if (INTEGER(itemtype)[iField] == OFTRealList) {
                    nCount[iField] = psField->RealList.nCount;
                    if (nCount[iField] > INTEGER(itemlistmaxcount)[iField])
                        INTEGER(itemlistmaxcount)[iField] = nCount[iField];
                } else if (INTEGER(itemtype)[iField] == OFTStringList) {
                    nCount[iField] = psField->StringList.nCount;
                    if (nCount[iField] > INTEGER(itemlistmaxcount)[iField])
                        INTEGER(itemlistmaxcount)[iField] = nCount[iField];
                }
            }
            OGRFeature::DestroyFeature( poFeature );
//    delete poFeature;
        }
        uninstallErrorHandlerAndTriggerError();

    }
    SET_VECTOR_ELT(itemlist,4,itemlistmaxcount);
    SET_VECTOR_ELT(ans,2,itemlist);

    UNPROTECT(pc);

    installErrorHandler();
#ifdef GDALV2
    GDALClose( poDS );
#else
    OGRDataSource::DestroyDataSource( poDS );
#endif
    uninstallErrorHandlerAndTriggerError();
//    delete poDS;
    return(ans);

}
void OGRGMLDataSource::InsertHeader()

{
    FILE        *fpSchema;
    int         nSchemaStart = 0;

    if( fpOutput == NULL || fpOutput == stdout )
        return;

/* -------------------------------------------------------------------- */
/*      Do we want to write the schema within the GML instance doc      */
/*      or to a separate file?  For now we only support external.       */
/* -------------------------------------------------------------------- */
    const char *pszSchemaURI = CSLFetchNameValue(papszCreateOptions,
                                                 "XSISCHEMAURI");
    const char *pszSchemaOpt = CSLFetchNameValue( papszCreateOptions, 
                                                  "XSISCHEMA" );

    if( pszSchemaURI != NULL )
        return;

    if( pszSchemaOpt == NULL || EQUAL(pszSchemaOpt,"EXTERNAL") )
    {
        const char *pszXSDFilename = CPLResetExtension( pszName, "xsd" );

        fpSchema = VSIFOpen( pszXSDFilename, "wt" );
        if( fpSchema == NULL )
        {
            CPLError( CE_Failure, CPLE_OpenFailed, 
                      "Failed to open file %.500s for schema output.", 
                      pszXSDFilename );
            return;
        }
        fprintf( fpSchema, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" );
    }
    else if( EQUAL(pszSchemaOpt,"INTERNAL") )
    {
        nSchemaStart = VSIFTell( fpOutput );
        fpSchema = fpOutput;
    }
    else                                                               
        return;

/* ==================================================================== */
/*      Write the schema section at the end of the file.  Once          */
/*      complete, we will read it back in, and then move the whole      */
/*      file "down" enough to insert the schema at the beginning.       */
/* ==================================================================== */

/* -------------------------------------------------------------------- */
/*      Emit the start of the schema section.                           */
/* -------------------------------------------------------------------- */
    const char *pszTargetNameSpace = "http://ogr.maptools.org/";
    const char *pszPrefix = "ogr";

    VSIFPrintf( fpSchema, 
                "<xs:schema targetNamespace=\"%s\" xmlns:%s=\"%s\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:gml=\"http://www.opengis.net/gml\" elementFormDefault=\"qualified\" version=\"1.0\">\n", 
                pszTargetNameSpace, pszPrefix, pszTargetNameSpace );
    
    VSIFPrintf( fpSchema, 
                "<xs:import namespace=\"http://www.opengis.net/gml\" schemaLocation=\"http://schemas.opengeospatial.net/gml/2.1.2/feature.xsd\"/>" );

/* -------------------------------------------------------------------- */
/*      Define the FeatureCollection                                    */
/* -------------------------------------------------------------------- */
    VSIFPrintf( fpSchema, 
                "<xs:element name=\"FeatureCollection\" type=\"%s:FeatureCollectionType\" substitutionGroup=\"gml:_FeatureCollection\"/>\n", 
                pszPrefix );

    VSIFPrintf( 
        fpSchema, 
        "<xs:complexType name=\"FeatureCollectionType\">\n"
        "  <xs:complexContent>\n"
        "    <xs:extension base=\"gml:AbstractFeatureCollectionType\">\n"
        "      <xs:attribute name=\"lockId\" type=\"xs:string\" use=\"optional\"/>\n"
        "      <xs:attribute name=\"scope\" type=\"xs:string\" use=\"optional\"/>\n"
        "    </xs:extension>\n"
        "  </xs:complexContent>\n"
        "</xs:complexType>\n" );

/* ==================================================================== */
/*      Define the schema for each layer.                               */
/* ==================================================================== */
    int iLayer;

    for( iLayer = 0; iLayer < GetLayerCount(); iLayer++ )
    {
        OGRFeatureDefn *poFDefn = GetLayer(iLayer)->GetLayerDefn();
        
/* -------------------------------------------------------------------- */
/*      Emit initial stuff for a feature type.                          */
/* -------------------------------------------------------------------- */
        VSIFPrintf( 
            fpSchema,
            "<xs:element name=\"%s\" type=\"%s:%s_Type\" substitutionGroup=\"gml:_Feature\"/>\n",
            poFDefn->GetName(), pszPrefix, poFDefn->GetName() );

        VSIFPrintf( 
            fpSchema, 
            "<xs:complexType name=\"%s_Type\">\n"
            "  <xs:complexContent>\n"
            "    <xs:extension base=\"gml:AbstractFeatureType\">\n"
            "      <xs:sequence>\n",
            poFDefn->GetName() );

/* -------------------------------------------------------------------- */
/*      Define the geometry attribute.  For now I always use the        */
/*      generic geometry type, but eventually we should express         */
/*      particulars if available.                                       */
/* -------------------------------------------------------------------- */
        VSIFPrintf( 
            fpSchema,
            "<xs:element name=\"geometryProperty\" type=\"gml:GeometryPropertyType\" nillable=\"true\" minOccurs=\"1\" maxOccurs=\"1\"/>\n" );
            
/* -------------------------------------------------------------------- */
/*      Emit each of the attributes.                                    */
/* -------------------------------------------------------------------- */
        for( int iField = 0; iField < poFDefn->GetFieldCount(); iField++ )
        {
            OGRFieldDefn *poFieldDefn = poFDefn->GetFieldDefn(iField);

            if( poFieldDefn->GetType() == OFTInteger )
            {
                int nWidth;

                if( poFieldDefn->GetWidth() > 0 )
                    nWidth = poFieldDefn->GetWidth();
                else
                    nWidth = 16;

                VSIFPrintf( fpSchema, 
                            "    <xs:element name=\"%s\" nillable=\"true\" minOccurs=\"0\" maxOccurs=\"1\">\n"
                            "      <xs:simpleType>\n"
                            "        <xs:restriction base=\"xs:integer\">\n"
                            "          <xs:totalDigits value=\"%d\"/>\n"
                            "        </xs:restriction>\n"
                            "      </xs:simpleType>\n"
                            "    </xs:element>\n",
                            poFieldDefn->GetNameRef(), nWidth );
            }
            else if( poFieldDefn->GetType() == OFTReal )
            {
                int nWidth, nDecimals;

                if( poFieldDefn->GetPrecision() == 0 )
                    nDecimals = 0;
                else
                    nDecimals = poFieldDefn->GetPrecision();

                if( poFieldDefn->GetWidth() > 0 )
                    nWidth = poFieldDefn->GetWidth();
                else
                    nWidth = 33;

                VSIFPrintf( fpSchema, 
                            "    <xs:element name=\"%s\" nillable=\"true\" minOccurs=\"0\" maxOccurs=\"1\">\n"
                            "      <xs:simpleType>\n"
                            "        <xs:restriction base=\"xs:decimal\">\n"
                            "          <xs:totalDigits value=\"%d\"/>\n"
                            "          <xs:fractionDigits value=\"%d\"/>\n"
                            "        </xs:restriction>\n"
                            "      </xs:simpleType>\n"
                            "    </xs:element>\n",
                            poFieldDefn->GetNameRef(), nWidth, nDecimals );
            }
            else if( poFieldDefn->GetType() == OFTString )
            {
                char szMaxLength[48];

                if( poFieldDefn->GetWidth() == 0 )
                    sprintf( szMaxLength, "unbounded" );
                else
                    sprintf( szMaxLength, "%d", poFieldDefn->GetWidth() );

                VSIFPrintf( fpSchema, 
                            "    <xs:element name=\"%s\" nillable=\"true\" minOccurs=\"0\" maxOccurs=\"1\">\n"
                            "      <xs:simpleType>\n"
                            "        <xs:restriction base=\"xs:string\">\n"
                            "          <xs:maxLength value=\"%s\"/>\n"
                            "        </xs:restriction>\n"
                            "      </xs:simpleType>\n"
                            "    </xs:element>\n",
                            poFieldDefn->GetNameRef(), szMaxLength );
            }
            else if( poFieldDefn->GetType() == OFTDate || poFieldDefn->GetType() == OFTDateTime )
            {
                VSIFPrintf( fpSchema, 
                            "    <xs:element name=\"%s\" nillable=\"true\" minOccurs=\"0\" maxOccurs=\"1\">\n"
                            "      <xs:simpleType>\n"
                            "        <xs:restriction base=\"xs:string\">\n"
                            "          <xs:maxLength value=\"unbounded\"/>\n"
                            "        </xs:restriction>\n"
                            "      </xs:simpleType>\n"
                            "    </xs:element>\n",
                            poFieldDefn->GetNameRef() );
            }
            else
            {
                /* TODO */
            }
        } /* next field */

/* -------------------------------------------------------------------- */
/*      Finish off feature type.                                        */
/* -------------------------------------------------------------------- */
        VSIFPrintf( fpSchema, 
                    "      </xs:sequence>\n"
                    "    </xs:extension>\n"
                    "  </xs:complexContent>\n"
                    "</xs:complexType>\n" );
    } /* next layer */

    VSIFPrintf( fpSchema, "</xs:schema>\n" );

/* ==================================================================== */
/*      Move schema to the start of the file.                           */
/* ==================================================================== */
    if( fpSchema == fpOutput )
    {
/* -------------------------------------------------------------------- */
/*      Read the schema into memory.                                    */
/* -------------------------------------------------------------------- */
        int nSchemaSize = VSIFTell( fpOutput ) - nSchemaStart;
        char *pszSchema = (char *) CPLMalloc(nSchemaSize+1);
    
        VSIFSeek( fpOutput, nSchemaStart, SEEK_SET );

        VSIFRead( pszSchema, 1, nSchemaSize, fpOutput );
        pszSchema[nSchemaSize] = '\0';
    
/* -------------------------------------------------------------------- */
/*      Move file data down by "schema size" bytes from after <?xml>    */
/*      header so we have room insert the schema.  Move in pretty       */
/*      big chunks.                                                     */
/* -------------------------------------------------------------------- */
        int nChunkSize = MIN(nSchemaStart-nSchemaInsertLocation,250000);
        char *pszChunk = (char *) CPLMalloc(nChunkSize);
        int nEndOfUnmovedData = nSchemaStart;

        for( nEndOfUnmovedData = nSchemaStart;
             nEndOfUnmovedData > nSchemaInsertLocation; )
        {
            int nBytesToMove = 
                MIN(nChunkSize, nEndOfUnmovedData - nSchemaInsertLocation );

            VSIFSeek( fpOutput, nEndOfUnmovedData - nBytesToMove, SEEK_SET );
            VSIFRead( pszChunk, 1, nBytesToMove, fpOutput );
            VSIFSeek( fpOutput, nEndOfUnmovedData - nBytesToMove + nSchemaSize, 
                      SEEK_SET );
            VSIFWrite( pszChunk, 1, nBytesToMove, fpOutput );
        
            nEndOfUnmovedData -= nBytesToMove;
        }

        CPLFree( pszChunk );

/* -------------------------------------------------------------------- */
/*      Write the schema in the opened slot.                            */
/* -------------------------------------------------------------------- */
        VSIFSeek( fpOutput, nSchemaInsertLocation, SEEK_SET );
        VSIFWrite( pszSchema, 1, nSchemaSize, fpOutput );

        VSIFSeek( fpOutput, 0, SEEK_END );

        nBoundedByLocation += nSchemaSize;
    }
/* -------------------------------------------------------------------- */
/*      Close external schema files.                                    */
/* -------------------------------------------------------------------- */
    else
        VSIFClose( fpSchema );
}
CPLXMLNode *OGRFMELayerCached::SerializeToXML()

{
    CPLXMLNode      *psLayer;
    char            szGeomType[64];

    psLayer = CPLCreateXMLNode( NULL, CXT_Element, "OGRLayer" );
    
/* -------------------------------------------------------------------- */
/*      Handle various layer values.                                    */
/* -------------------------------------------------------------------- */
    CPLCreateXMLElementAndValue( psLayer, "Name", poFeatureDefn->GetName());
    sprintf( szGeomType, "%d", (int) poFeatureDefn->GetGeomType() );
    CPLCreateXMLElementAndValue( psLayer, "GeomType", szGeomType );    

    CPLCreateXMLElementAndValue( psLayer, "SpatialCacheName", 
                                 pszIndexBase );
    
/* -------------------------------------------------------------------- */
/*      Handle spatial reference if available.                          */
/* -------------------------------------------------------------------- */
    if( GetSpatialRef() != NULL )
    {
        char *pszWKT = NULL;
        OGRSpatialReference *poSRS = GetSpatialRef();
        
        poSRS->exportToWkt( &pszWKT );

        if( pszWKT != NULL )
        {
            CPLCreateXMLElementAndValue( psLayer, "SRS", pszWKT );
            CPLFree( pszWKT );
        }
    }

/* -------------------------------------------------------------------- */
/*      Handle extents if available.                                    */
/* -------------------------------------------------------------------- */
    OGREnvelope sEnvelope;
    if( GetExtent( &sEnvelope, FALSE ) == OGRERR_NONE )
    {
        char szExtent[512];

        sprintf( szExtent, "%24.15E,%24.15E,%24.15E,%24.15E", 
                 sEnvelope.MinX, sEnvelope.MinY, 
                 sEnvelope.MaxX, sEnvelope.MaxY );
        CPLCreateXMLElementAndValue( psLayer, "Extent", szExtent );
    }

/* -------------------------------------------------------------------- */
/*      Emit the field schemas.                                         */
/* -------------------------------------------------------------------- */
    CPLXMLNode *psSchema = CPLCreateXMLNode( psLayer, CXT_Element, "Schema" );
    
    for( int iField = 0; iField < poFeatureDefn->GetFieldCount(); iField++ )
    {
        OGRFieldDefn *poFieldDef = poFeatureDefn->GetFieldDefn( iField );
        const char *pszType;
        char szWidth[32], szPrecision[32];
        CPLXMLNode *psXMLFD;

        sprintf( szWidth, "%d", poFieldDef->GetWidth() );
        sprintf( szPrecision, "%d", poFieldDef->GetPrecision() );
        
        if( poFieldDef->GetType() == OFTInteger )
            pszType = "Integer";
        else if( poFieldDef->GetType() == OFTIntegerList )
            pszType = "IntegerList";
        else if( poFieldDef->GetType() == OFTReal )
            pszType = "Real";
        else if( poFieldDef->GetType() == OFTRealList )
            pszType = "RealList";
        else if( poFieldDef->GetType() == OFTString )
            pszType = "String";
        else if( poFieldDef->GetType() == OFTStringList )
            pszType = "StringList";
        else if( poFieldDef->GetType() == OFTBinary )
            pszType = "Binary";
        else
            pszType = "Unsupported";

        psXMLFD = CPLCreateXMLNode( psSchema, CXT_Element, "OGRFieldDefn" );
        CPLCreateXMLElementAndValue( psXMLFD, "Name",poFieldDef->GetNameRef());
        CPLCreateXMLElementAndValue( psXMLFD, "Type", pszType );
        CPLCreateXMLElementAndValue( psXMLFD, "Width", szWidth );
        CPLCreateXMLElementAndValue( psXMLFD, "Precision", szPrecision );
    }

    return psLayer;
}
Beispiel #16
0
const char *OGRFeature::GetFieldAsString( int iField )

{
    OGRFieldDefn        *poFDefn = poDefn->GetFieldDefn( iField );
    static char         szTempBuffer[80];

    CPLAssert( poFDefn != NULL || iField == -1 );
    if( poFDefn == NULL )
        return "";
    
    if( !IsFieldSet(iField) )
        return "";
    
    if( poFDefn->GetType() == OFTString )
    {
        if( pauFields[iField].String == NULL )
            return "";
        else
            return pauFields[iField].String;
    }
    else if( poFDefn->GetType() == OFTInteger )
    {
        sprintf( szTempBuffer, "%d", pauFields[iField].Integer );
        return szTempBuffer;
    }
    else if( poFDefn->GetType() == OFTReal )
    {
        char    szFormat[64];

        if( poFDefn->GetWidth() != 0 )
        {
            sprintf( szFormat, "%%%d.%df",
                     poFDefn->GetWidth(), poFDefn->GetPrecision() );
        }
        else
            strcpy( szFormat, "%.16g" );
        
        sprintf( szTempBuffer, szFormat, pauFields[iField].Real );
        
        return szTempBuffer;
    }
    else if( poFDefn->GetType() == OFTIntegerList )
    {
        char    szItem[32];
        int     i, nCount = pauFields[iField].IntegerList.nCount;

        sprintf( szTempBuffer, "(%d:", nCount );
        for( i = 0; i < nCount; i++ )
        {
            sprintf( szItem, "%d", pauFields[iField].IntegerList.paList[i] );
            if( strlen(szTempBuffer) + strlen(szItem) + 6
                > sizeof(szTempBuffer) )
            {
                break;
            }
            
            if( i > 0 )
                strcat( szTempBuffer, "," );
            
            strcat( szTempBuffer, szItem );
        }

        if( i < nCount )
            strcat( szTempBuffer, ",...)" );
        else
            strcat( szTempBuffer, ")" );
        
        return szTempBuffer;
    }
    else if( poFDefn->GetType() == OFTRealList )
    {
        char    szItem[40];
        char    szFormat[64];
        int     i, nCount = pauFields[iField].RealList.nCount;

        if( poFDefn->GetWidth() != 0 )
        {
            sprintf( szFormat, "%%%d.%df",
                     poFDefn->GetWidth(), poFDefn->GetPrecision() );
        }
        else
            strcpy( szFormat, "%.16g" );
        
        sprintf( szTempBuffer, "(%d:", nCount );
        for( i = 0; i < nCount; i++ )
        {
            sprintf( szItem, szFormat, pauFields[iField].RealList.paList[i] );
            if( strlen(szTempBuffer) + strlen(szItem) + 6
                > sizeof(szTempBuffer) )
            {
                break;
            }
            
            if( i > 0 )
                strcat( szTempBuffer, "," );
            
            strcat( szTempBuffer, szItem );
        }

        if( i < nCount )
            strcat( szTempBuffer, ",...)" );
        else
            strcat( szTempBuffer, ")" );
        
        return szTempBuffer;
    }
    else if( poFDefn->GetType() == OFTStringList )
    {
        int     i, nCount = pauFields[iField].StringList.nCount;

        sprintf( szTempBuffer, "(%d:", nCount );
        for( i = 0; i < nCount; i++ )
        {
            const char  *pszItem = pauFields[iField].StringList.paList[i];
            
            if( strlen(szTempBuffer) + strlen(pszItem)  + 6
                > sizeof(szTempBuffer) )
            {
                break;
            }

            if( i > 0 )
                strcat( szTempBuffer, "," );
            
            strcat( szTempBuffer, pszItem );
        }

        if( i < nCount )
            strcat( szTempBuffer, ",...)" );
        else
            strcat( szTempBuffer, ")" );
        
        return szTempBuffer;
    }
    else
        return "";
}