Beispiel #1
0
QDebug operator<<(QDebug dbg, OGRLayer* layer)
{
    layer->ResetReading();
    OGRFeatureDefn* def = layer->GetLayerDefn();
    FeaturePtr feat;
    while ((feat = FeaturePtr(layer->GetNextFeature())) != nullptr)
    {
        for (int i = 0; i < def->GetFieldCount(); ++i)
        {
            OGRFieldDefn* fdef = def->GetFieldDefn(i);
            switch (fdef->GetType())
            {
            case OFTInteger:
                dbg << fdef->GetNameRef() << feat->GetFieldAsInteger(i);
                break;
            case OFTReal:
                dbg << fdef->GetNameRef() << feat->GetFieldAsDouble(i);
                break;
            case OFTString:
                dbg << fdef->GetNameRef() << feat->GetFieldAsString(i);
                break;
            default:
                dbg << "Unknown type:" << fdef->GetType();
            }
        }
        dbg << "-----";
    }

    return dbg;
}
Beispiel #2
0
OGRErr OGRILI2Layer::ICreateFeature( OGRFeature *poFeature ) {
    char szTempBuffer[80];
    const char* tid;
    int iField = 0;
    if( poFeatureDefn->GetFieldCount() &&
        EQUAL(poFeatureDefn->GetFieldDefn(iField)->GetNameRef(), "TID") )
    {
        tid = poFeature->GetFieldAsString(0);
        ++iField;
    }
    else
    {
        snprintf( szTempBuffer, sizeof(szTempBuffer), CPL_FRMT_GIB,
                  poFeature->GetFID() );
        tid = szTempBuffer;
    }

    VSILFILE* fp = poDS->GetOutputFP();
    if (fp == NULL)
        return OGRERR_FAILURE;

    VSIFPrintfL(fp, "<%s TID=\"%s\">\n", poFeatureDefn->GetName(), tid);

    // Write out Geometries
    for( int iGeomField = 0;
         iGeomField < poFeatureDefn->GetGeomFieldCount();
         iGeomField++ )
    {
        OGRGeomFieldDefn *poFieldDefn
            = poFeatureDefn->GetGeomFieldDefn(iGeomField);
        OGRGeometry* poGeom = poFeature->GetGeomFieldRef(iGeomField);
        if( poGeom != NULL )
        {
            CPLString iliGeomType = GetIliGeomType(poFieldDefn->GetNameRef());
            OGR2ILIGeometryAppend( poGeom, fp, poFieldDefn->GetNameRef(),
                                   iliGeomType );
        }
    }

    // Write all "set" fields.
    for( ; iField < poFeatureDefn->GetFieldCount(); iField++ )
    {

        OGRFieldDefn *poField = poFeatureDefn->GetFieldDefn( iField );

        if( poFeature->IsFieldSet( iField ) )
        {
            const char *pszRaw = poFeature->GetFieldAsString( iField );
            VSIFPrintfL(fp, "<%s>%s</%s>\n", poField->GetNameRef(), pszRaw, poField->GetNameRef());
        }
    }

    VSIFPrintfL(fp, "</%s>\n", poFeatureDefn->GetName());

    return OGRERR_NONE;
}
Beispiel #3
0
//#include "s57.h"
int main(int argc, char **argv)

{
    OGRRegisterAll();

    OGRDataSource       *poDS;
    printf("Opening %s\n",argv[1]);
    poDS = OGRSFDriverRegistrar::Open( argv[1], FALSE );
    if( poDS == NULL )
    {
        printf( "Open failed.\n" );
        exit( 1 );
    }

    OGRLayer  *poLayer;
    int layers = poDS->GetLayerCount();
    for (int layer =0 ; layer< layers; layer++) {
        poLayer = poDS->GetLayer(layer);
        if (poLayer == NULL) continue;
        printf("%d, %s, %s",layer, poLayer->GetName(), OGRGeometryTypeToName(poLayer->GetGeomType()));
        poLayer->ResetReading();
        OGRFeatureDefn *poFDefn = poLayer->GetLayerDefn();  
        int iField;
        for( iField = 0; iField < poFDefn->GetFieldCount(); iField++ )
        {
            OGRFieldDefn *poFieldDefn = poFDefn->GetFieldDefn( iField );
            printf(", %s",poFieldDefn->GetNameRef());
        }
        printf("\n");
    }

}
Beispiel #4
0
//---------------------------------------------------------
CSG_Shapes * COGR_DataSource::Read_Shapes(int iLayer)
{
	OGRLayer	*pLayer	= Get_Layer(iLayer);

	//-----------------------------------------------------
	if( pLayer && Get_Type(iLayer) != SHAPE_TYPE_Undefined )
	{
		int				iField;
		OGRFeature		*pFeature;
		OGRFeatureDefn	*pDef		= pLayer->GetLayerDefn();
		CSG_Shapes		*pShapes	= SG_Create_Shapes(Get_Type(iLayer), CSG_String(pDef->GetName()));

		for(iField=0; iField<pDef->GetFieldCount(); iField++)
		{
			OGRFieldDefn	*pDefField	= pDef->GetFieldDefn(iField);

			pShapes->Add_Field(pDefField->GetNameRef(), COGR_Driver::Get_Type(pDefField->GetType()));
		}

		pLayer->ResetReading();

		//-------------------------------------------------
		while( (pFeature = pLayer->GetNextFeature()) != NULL && SG_UI_Process_Get_Okay(false) )
		{
			OGRGeometry	*pGeometry	= pFeature->GetGeometryRef();

			if( pGeometry != NULL )
			{
				CSG_Shape	*pShape	= pShapes->Add_Shape();

				for(iField=0; iField<pDef->GetFieldCount(); iField++)
				{
					OGRFieldDefn	*pDefField	= pDef->GetFieldDefn(iField);

					switch( pDefField->GetType() )
					{
					default:			pShape->Set_Value(iField, SG_STR_MBTOSG(pFeature->GetFieldAsString (iField)));	break;
					case OFTString:		pShape->Set_Value(iField, SG_STR_MBTOSG(pFeature->GetFieldAsString (iField)));	break;
					case OFTInteger:	pShape->Set_Value(iField, pFeature->GetFieldAsInteger(iField));	break;
					case OFTReal:		pShape->Set_Value(iField, pFeature->GetFieldAsDouble (iField));	break;
					}
				}

				//-----------------------------------------
				if( _Read_Geometry(pShape, pGeometry) == false )
				{
					pShapes->Del_Shape(pShape);
				}
			}

			OGRFeature::DestroyFeature(pFeature);
		}

		return( pShapes );
	}

	//-----------------------------------------------------
	return( NULL );
}
Beispiel #5
0
wxString wxGISTable::GetColLabelValue(int col)
{
    wxString label;
    OGRFieldDefn* pOGRFieldDefn = m_pOGRFeatureDefn->GetFieldDefn(col);
    label = wgMB2WX(pOGRFieldDefn->GetNameRef());
    if(!m_sFIDKeyName.IsEmpty())
    {
        if(label == m_sFIDKeyName);
        label += _(" [*]");
    }
    return label;
}
Beispiel #6
0
json_object* OGRGMEAttributesToGeoJSON( OGRFeature* poFeature )
{
    if ( NULL == poFeature )
        return NULL;
    json_object* pjoProperties = json_object_new_object();
    CPLAssert( NULL != pjoProperties );

    OGRFeatureDefn* poDefn = poFeature->GetDefnRef();
    for( int nField = 0; nField < poDefn->GetFieldCount(); ++nField ) {
        json_object* pjoProperty = NULL;
        OGRFieldDefn* poFieldDefn = poDefn->GetFieldDefn( nField );
        if ( NULL == poFieldDefn )
            continue;
        OGRFieldType eType = poFieldDefn->GetType();

        if( !poFeature->IsFieldSet(nField) )
            pjoProperty = NULL;

        // In GME integers are encoded as strings.
        else if( OFTInteger == eType )
            pjoProperty = json_object_new_string( poFeature->GetFieldAsString( nField ) );

        else if( OFTReal == eType )
            pjoProperty = json_object_new_gme_double( poFeature->GetFieldAsDouble(nField) );

        // Supported types are integer, double and string. So treating everything else as strings
        else
            pjoProperty = json_object_new_string( poFeature->GetFieldAsString(nField) );

        json_object_object_add( pjoProperties, poFieldDefn->GetNameRef(), pjoProperty );
    }
    int nGxId = poFeature->GetFieldIndex("gx_id");
    if (nGxId < 0) {
        json_object* pjoProperty = NULL;
        GIntBig nFID = poFeature->GetFID();

        char acGxId[128];
        snprintf(acGxId, 128, "GDAL-" CPL_FRMT_GIB, nFID);
        CPLDebug("GME", "gx_id is not set, so adding \"gx_id\": \"%s\" field.",
                 acGxId);

        pjoProperty = json_object_new_string( acGxId );
        json_object_object_add( pjoProperties, "gx_id", pjoProperty);
    }

    return pjoProperties;
}
Beispiel #7
0
wxString wxGISGridTable::GetColLabelValue(int col)
{
    wxString label;
    OGRFeatureDefn* pOGRFeatureDefn = m_pGISDataset->GetDefinition();
    if(!pOGRFeatureDefn)
        return wxEmptyString;

	OGRFieldDefn* pOGRFieldDefn = pOGRFeatureDefn->GetFieldDefn(col);
	if(pOGRFieldDefn)
		label = wxString(pOGRFieldDefn->GetNameRef(), wxConvUTF8);

    if(label.IsSameAs(m_pGISDataset->GetFIDColumn(), false))
    {
        label.Append(_(" [*]"));
	}
    return label;
}
Beispiel #8
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;
}
OGRErr OGRGeoJSONWriteLayer::CreateField(OGRFieldDefn* poField, int bApproxOK)
{
    UNREFERENCED_PARAM(bApproxOK);

    for( int i = 0; i < poFeatureDefn_->GetFieldCount(); ++i )
    {
        OGRFieldDefn* poDefn = poFeatureDefn_->GetFieldDefn(i);
        CPLAssert( NULL != poDefn );

        if( EQUAL( poDefn->GetNameRef(), poField->GetNameRef() ) )
        {
            CPLDebug( "GeoJSON", "Field '%s' already present in schema",
                      poField->GetNameRef() );
            
            // TODO - mloskot: Is this return code correct?
            return OGRERR_NONE;
        }
    }

    poFeatureDefn_->AddFieldDefn( poField );

    return OGRERR_NONE;
}
Beispiel #11
0
void OGRFeature::DumpReadable( FILE * fpOut )

{
    fprintf( fpOut, "OGRFeature(%s):%ld\n", poDefn->GetName(), GetFID() );
    for( int iField = 0; iField < GetFieldCount(); iField++ )
    {
        OGRFieldDefn    *poFDefn = poDefn->GetFieldDefn(iField);
        
        fprintf( fpOut, "  %s (%s) = ",
                 poFDefn->GetNameRef(),
                 OGRFieldDefn::GetFieldTypeName(poFDefn->GetType()) );

        if( IsFieldSet( iField ) )
            fprintf( fpOut, "%s\n", GetFieldAsString( iField ) );
        else
            fprintf( fpOut, "(null)\n" );
            
    }
    
    if( poGeometry != NULL )
        poGeometry->dumpReadable( fpOut, "  " );

    fprintf( fpOut, "\n" );
}
Beispiel #12
0
feature_ptr ogr_featureset::next()
{
    OGRFeature *poFeature;
    while ((poFeature = layer_.GetNextFeature()) != NULL)
    {
        // ogr feature ids start at 0, so add one to stay
        // consistent with other mapnik datasources that start at 1
        const int feature_id = (poFeature->GetFID() + 1);
        feature_ptr feature(feature_factory::create(ctx_,feature_id));

        OGRGeometry* geom = poFeature->GetGeometryRef();
        if (geom && ! geom->IsEmpty())
        {
            ogr_converter::convert_geometry(geom, feature);
        }
        else
        {
            MAPNIK_LOG_DEBUG(ogr) << "ogr_featureset: Feature with null geometry="
                << poFeature->GetFID();
            OGRFeature::DestroyFeature( poFeature );
            continue;
        }

        ++count_;

        int fld_count = layerdef_->GetFieldCount();
        for (int i = 0; i < fld_count; i++)
        {
            OGRFieldDefn* fld = layerdef_->GetFieldDefn(i);
            const OGRFieldType type_oid = fld->GetType();
            const std::string fld_name = fld->GetNameRef();

            switch (type_oid)
            {
            case OFTInteger:
            {
                feature->put( fld_name, poFeature->GetFieldAsInteger(i));
                break;
            }

            case OFTReal:
            {
                feature->put( fld_name, poFeature->GetFieldAsDouble(i));
                break;
            }

            case OFTString:
            case OFTWideString:     // deprecated !
            {
                UnicodeString ustr = tr_->transcode(poFeature->GetFieldAsString(i));
                feature->put( fld_name, ustr);
                break;
            }

            case OFTIntegerList:
            case OFTRealList:
            case OFTStringList:
            case OFTWideStringList: // deprecated !
            {
                MAPNIK_LOG_WARN(ogr) << "ogr_featureset: Unhandled type_oid=" << type_oid;
                break;
            }

            case OFTBinary:
            {
                MAPNIK_LOG_WARN(ogr) << "ogr_featureset: Unhandled type_oid=" << type_oid;
                //feature->put(name,feat->GetFieldAsBinary (i, size));
                break;
            }

            case OFTDate:
            case OFTTime:
            case OFTDateTime:       // unhandled !
            {
                MAPNIK_LOG_WARN(ogr) << "ogr_featureset: Unhandled type_oid=" << type_oid;
                break;
            }

            default: // unknown
            {
                MAPNIK_LOG_WARN(ogr) << "ogr_featureset: Unknown type_oid=" << type_oid;
                break;
            }
            }
        }
        OGRFeature::DestroyFeature( poFeature );
        return feature;
    }

    MAPNIK_LOG_DEBUG(ogr) << "ogr_featureset: " << count_ << " features";

    return feature_ptr();
}
Beispiel #13
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 #14
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 );
    }
}
OGRFeature* OGRPLScenesLayer::GetNextRawFeature()
{
    if( bEOF ||
        (!bFilterMustBeClientSideEvaluated && nFeatureCount >= 0 && nNextFID > nFeatureCount) )
        return NULL;

    if( poGeoJSONLayer == NULL )
    {
        if( !GetNextPage() )
            return NULL;
    }

#ifdef notdef
    if( CSLTestBoolean(CPLGetConfigOption("OGR_LIMIT_TOO_MANY_FEATURES", "FALSE")) &&
        nFeatureCount > nPageSize )
    {
        bEOF = TRUE;
        OGRFeature* poFeature = new OGRFeature(poFeatureDefn);
        OGRGeometry* poGeom;
        const char* pszWKT = "MULTIPOLYGON(((-180 90,180 90,180 -90,-180 -90,-180 90)))";
        OGRGeometryFactory::createFromWkt((char**)&pszWKT, poSRS, &poGeom);
        poFeature->SetGeometryDirectly(poGeom);
        return poFeature;
    }
#endif

    OGRFeature* poGeoJSONFeature = poGeoJSONLayer->GetNextFeature();
    if( poGeoJSONFeature == NULL )
    {
        osRequestURL = osNextURL;
        bStillInFirstPage = FALSE;
        if( !GetNextPage() )
            return NULL;
        poGeoJSONFeature = poGeoJSONLayer->GetNextFeature();
        if( poGeoJSONFeature == NULL )
        {
            bEOF = TRUE;
            return NULL;
        }
    }
    OGRFeature* poFeature = new OGRFeature(poFeatureDefn);
    poFeature->SetFID(nNextFID++);

    OGRGeometry* poGeom = poGeoJSONFeature->StealGeometry();
    if( poGeom != NULL )
    {
        if( poGeom->getGeometryType() == wkbPolygon )
        {
            OGRMultiPolygon* poMP = new OGRMultiPolygon();
            poMP->addGeometryDirectly(poGeom);
            poGeom = poMP;
        }
        poGeom->assignSpatialReference(poSRS);
        poFeature->SetGeometryDirectly(poGeom);
    }
    
    for(int i=0;i<poFeatureDefn->GetFieldCount();i++)
    {
        OGRFieldDefn* poFieldDefn = poFeatureDefn->GetFieldDefn(i);
        OGRFieldType eType = poFieldDefn->GetType();
        int iSrcField = poGeoJSONFeature->GetFieldIndex(poFieldDefn->GetNameRef());
        if( iSrcField >= 0 && poGeoJSONFeature->IsFieldSet(iSrcField) )
        {
            if( eType == OFTInteger )
                poFeature->SetField(i,
                    poGeoJSONFeature->GetFieldAsInteger(iSrcField));
            else if( eType == OFTReal )
                poFeature->SetField(i,
                    poGeoJSONFeature->GetFieldAsDouble(iSrcField));
            else
                poFeature->SetField(i,
                    poGeoJSONFeature->GetFieldAsString(iSrcField));
        }
    }

    delete poGeoJSONFeature;

    return poFeature;
}
Beispiel #16
0
void GTMTrackLayer::WriteFeatureAttributes( OGRFeature *poFeature )
{
    char* psztrackname = nullptr;
    int type = 1;
    unsigned int color = 0;
    for (int i = 0; i < poFeatureDefn->GetFieldCount(); ++i)
    {
        OGRFieldDefn *poFieldDefn = poFeatureDefn->GetFieldDefn( i );
        if( poFeature->IsFieldSetAndNotNull( i ) )
        {
            const char* l_pszName = poFieldDefn->GetNameRef();
            /* track name */
            if (STARTS_WITH(l_pszName, "name"))
            {
                CPLFree(psztrackname);
                psztrackname = CPLStrdup( poFeature->GetFieldAsString( i ) );
            }
            /* track type */
            else if (STARTS_WITH(l_pszName, "type"))
            {
                type = poFeature->GetFieldAsInteger( i );
                // Check if it is a valid type
                if (type < 1 || type > 30)
                    type = 1;
            }
            /* track color */
            else if (STARTS_WITH(l_pszName, "color"))
            {
                color = (unsigned int) poFeature->GetFieldAsInteger( i );
                if (color > 0xFFFFFF)
                    color = 0xFFFFFFF;
            }
        }
    }

    if (psztrackname == nullptr)
        psztrackname = CPLStrdup( "" );

    const size_t trackNameLength = strlen(psztrackname);

    const size_t bufferSize = 14 + trackNameLength;
    void* pBuffer = CPLMalloc(bufferSize);
    void* pBufferAux = pBuffer;
    /* Write track string name size to buffer */
    appendUShort(pBufferAux, (unsigned short) trackNameLength);
    pBufferAux = (char*)pBufferAux + 2;

    /* Write track name */
    memcpy((char*)pBufferAux, psztrackname, trackNameLength);
    pBufferAux = (char*)pBufferAux + trackNameLength;

    /* Write track type */
    appendUChar(pBufferAux, (unsigned char) type);
    pBufferAux = (char*)pBufferAux + 1;

    /* Write track color */
    appendInt(pBufferAux, color);
    pBufferAux = (char*)pBufferAux + 4;

    /* Write track scale */
    appendFloat(pBufferAux, 0);
    pBufferAux = (char*)pBufferAux + 4;

    /* Write track label */
    appendUChar(pBufferAux, 0);
    pBufferAux = (char*)pBufferAux + 1;

    /* Write track layer */
    appendUShort(pBufferAux, 0);

    VSIFWriteL(pBuffer, bufferSize, 1, poDS->getTmpTracksFP());
    poDS->incNumTracks();

    CPLFree(psztrackname);
    CPLFree(pBuffer);
}
OGRErr OGRFeatureQuery::Compile(OGRFeatureDefn *poDefn,
                                const char *pszExpression)

{
/* -------------------------------------------------------------------- */
/*      Clear any existing expression.                                  */
/* -------------------------------------------------------------------- */
    if (pSWQExpr != NULL)
    {
        delete (swq_expr_node*) pSWQExpr;
        pSWQExpr = NULL;
    }

/* -------------------------------------------------------------------- */
/*      Build list of fields.                                           */
/* -------------------------------------------------------------------- */
    char           **papszFieldNames;
    swq_field_type *paeFieldTypes;
    int            iField;
    int            nFieldCount = poDefn->GetFieldCount() + SPECIAL_FIELD_COUNT;

    papszFieldNames = (char**)
                      CPLMalloc(sizeof(char*) * nFieldCount);
    paeFieldTypes = (swq_field_type*)
                    CPLMalloc(sizeof(swq_field_type) * nFieldCount);

    for (iField = 0; iField < poDefn->GetFieldCount(); iField++)
    {
        OGRFieldDefn *poField = poDefn->GetFieldDefn(iField);

        papszFieldNames[iField] = (char*) poField->GetNameRef();

        switch (poField->GetType())
        {
        case OFTInteger:
            paeFieldTypes[iField] = SWQ_INTEGER;
            break;

        case OFTReal:
            paeFieldTypes[iField] = SWQ_FLOAT;
            break;

        case OFTString:
            paeFieldTypes[iField] = SWQ_STRING;
            break;

        case OFTDate:
        case OFTTime:
        case OFTDateTime:
            paeFieldTypes[iField] = SWQ_TIMESTAMP;
            break;

        default:
            paeFieldTypes[iField] = SWQ_OTHER;
            break;
        }
    }

    iField = 0;

    while (iField < SPECIAL_FIELD_COUNT)
    {
        papszFieldNames[poDefn->GetFieldCount() + iField] = (char*) SpecialFieldNames[iField];
        paeFieldTypes[poDefn->GetFieldCount() + iField]   = SpecialFieldTypes[iField];
        ++iField;
    }

/* -------------------------------------------------------------------- */
/*      Try to parse.                                                   */
/* -------------------------------------------------------------------- */
    OGRErr eErr = OGRERR_NONE;
    CPLErr eCPLErr;

    poTargetDefn = poDefn;
    eCPLErr      = swq_expr_compile(pszExpression, nFieldCount,
                                    papszFieldNames, paeFieldTypes,
                                    (swq_expr_node**) &pSWQExpr);
    if (eCPLErr != CE_None)
    {
        eErr     = OGRERR_CORRUPT_DATA;
        pSWQExpr = NULL;
    }

    CPLFree(papszFieldNames);
    CPLFree(paeFieldTypes);


    return eErr;
}
Beispiel #18
0
feature_ptr ogr_featureset::next()
{
    if (count_ == 0)
    {
        // Reset the layer reading on the first feature read
        // this is a hack, but needed due to https://github.com/mapnik/mapnik/issues/2048
        // Proper solution is to avoid storing layer state in featureset
        layer_.ResetReading();
    }
    OGRFeature *poFeature;
    while ((poFeature = layer_.GetNextFeature()) != nullptr)
    {
        // ogr feature ids start at 0, so add one to stay
        // consistent with other mapnik datasources that start at 1
        mapnik::value_integer feature_id = (poFeature->GetFID() + 1);
        feature_ptr feature(feature_factory::create(ctx_,feature_id));

        OGRGeometry* geom = poFeature->GetGeometryRef();
        if (geom && ! geom->IsEmpty())
        {
            auto geom_corrected = ogr_converter::convert_geometry(geom);
            mapnik::geometry::correct(geom_corrected);
            feature->set_geometry(std::move(geom_corrected));
        }
        else
        {
            MAPNIK_LOG_DEBUG(ogr) << "ogr_featureset: Feature with null geometry="
                << poFeature->GetFID();
            OGRFeature::DestroyFeature( poFeature );
            continue;
        }

        ++count_;

        int fld_count = layerdef_->GetFieldCount();
        for (int i = 0; i < fld_count; i++)
        {
            OGRFieldDefn* fld = layerdef_->GetFieldDefn(i);
            const OGRFieldType type_oid = fld->GetType();
            const std::string fld_name = fld->GetNameRef();

            switch (type_oid)
            {
            case OFTInteger:
            {
                feature->put<mapnik::value_integer>( fld_name, poFeature->GetFieldAsInteger(i));
                break;
            }
#if GDAL_VERSION_MAJOR >= 2
            case OFTInteger64:
            {
                feature->put<mapnik::value_integer>( fld_name, poFeature->GetFieldAsInteger64(i));
                break;
            }
#endif

            case OFTReal:
            {
                feature->put( fld_name, poFeature->GetFieldAsDouble(i));
                break;
            }

            case OFTString:
            case OFTWideString:     // deprecated !
            {
                feature->put( fld_name, tr_->transcode(poFeature->GetFieldAsString(i)));
                break;
            }

            case OFTIntegerList:
#if GDAL_VERSION_MAJOR >= 2
            case OFTInteger64List:
#endif
            case OFTRealList:
            case OFTStringList:
            case OFTWideStringList: // deprecated !
            {
                MAPNIK_LOG_WARN(ogr) << "ogr_featureset: Unhandled type_oid=" << type_oid;
                break;
            }

            case OFTBinary:
            {
                MAPNIK_LOG_WARN(ogr) << "ogr_featureset: Unhandled type_oid=" << type_oid;
                //feature->put(name,feat->GetFieldAsBinary (i, size));
                break;
            }

            case OFTDate:
            case OFTTime:
            case OFTDateTime:       // unhandled !
            {
                MAPNIK_LOG_WARN(ogr) << "ogr_featureset: Unhandled type_oid=" << type_oid;
                break;
            }

            default: // unknown
            {
                MAPNIK_LOG_WARN(ogr) << "ogr_featureset: Unknown type_oid=" << type_oid;
                break;
            }
            }
        }
        OGRFeature::DestroyFeature( poFeature );
        return feature;
    }

    MAPNIK_LOG_DEBUG(ogr) << "ogr_featureset: " << count_ << " features";

    return feature_ptr();
}
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 #20
0
void ogr_datasource::bind() const
{
    if (is_bound_) return;

    // initialize ogr formats
    OGRRegisterAll();
    
    std::string driver = *params_.get<std::string>("driver","");

    if (! driver.empty())
    {
        OGRSFDriver * ogr_driver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(driver.c_str());
        if (ogr_driver && ogr_driver != NULL)
        {
            dataset_ = ogr_driver->Open((dataset_name_).c_str(), FALSE);
        }
    
    }
    else
    {
        // open ogr driver
        dataset_ = OGRSFDriverRegistrar::Open((dataset_name_).c_str(), FALSE);
    }

    if (! dataset_)
    {
        const std::string err = CPLGetLastErrorMsg();
        if (err.size() == 0)
        {
            throw datasource_exception("OGR Plugin: connection failed: " + dataset_name_ + " was not found or is not a supported format");
        }
        else
        {
            throw datasource_exception("OGR Plugin: " + err);
        }
    }

    // initialize layer
    boost::optional<std::string> layer_by_name = params_.get<std::string>("layer");
    boost::optional<unsigned> layer_by_index = params_.get<unsigned>("layer_by_index");
    boost::optional<std::string> layer_by_sql = params_.get<std::string>("layer_by_sql");

    int passed_parameters = 0;
    passed_parameters += layer_by_name ? 1 : 0;
    passed_parameters += layer_by_index ? 1 : 0;
    passed_parameters += layer_by_sql ? 1 : 0;

    if (passed_parameters > 1)
    {
        throw datasource_exception("OGR Plugin: you can only select an ogr layer by name "
                                   "('layer' parameter), by number ('layer_by_index' parameter), "
                                   "or by sql ('layer_by_sql' parameter), "
                                   "do not supply 2 or more of them at the same time" );
    }

    if (layer_by_name)
    {
        layer_name_ = *layer_by_name;
        layer_.layer_by_name(dataset_, layer_name_);
    }
    else if (layer_by_index)
    {
        const unsigned num_layers = dataset_->GetLayerCount();
        if (*layer_by_index >= num_layers)
        {
            std::ostringstream s;
            s << "OGR Plugin: only ";
            s << num_layers;
            s << " layer(s) exist, cannot find layer by index '" << *layer_by_index << "'";

            throw datasource_exception(s.str());
        }

        layer_.layer_by_index(dataset_, *layer_by_index);
        layer_name_ = layer_.layer_name();
    }
    else if (layer_by_sql)
    {
        layer_.layer_by_sql(dataset_, *layer_by_sql);
        layer_name_ = layer_.layer_name();
    }
    else
    {
        std::ostringstream s;
        s << "OGR Plugin: missing <layer> or <layer_by_index> or <layer_by_sql> "
          << "parameter, available layers are: ";

        unsigned num_layers = dataset_->GetLayerCount();
        bool layer_found = false;
        for (unsigned i = 0; i < num_layers; ++i )
        {
            OGRLayer* ogr_layer = dataset_->GetLayer(i);
            OGRFeatureDefn* ogr_layer_def = ogr_layer->GetLayerDefn();
            if (ogr_layer_def != 0)
            {
                layer_found = true;
                s << " '" << ogr_layer_def->GetName() << "' ";
            }
        }

        if (! layer_found)
        {
            s << "None (no layers were found in dataset)";
        }

        throw datasource_exception(s.str());
    }

    if (! layer_.is_valid())
    {
        std::string s("OGR Plugin: ");

        if (layer_by_name)
        {
            s += "cannot find layer by name '" + *layer_by_name;
        }
        else if (layer_by_index)
        {
            s += "cannot find layer by index number '" + *layer_by_index;
        }
        else if (layer_by_sql)
        {
            s += "cannot find layer by sql query '" + *layer_by_sql;
        }

        s += "' in dataset '" + dataset_name_ + "'";

        throw datasource_exception(s);
    }

    // work with real OGR layer
    OGRLayer* layer = layer_.layer();

    // initialize envelope
    OGREnvelope envelope;
    layer->GetExtent(&envelope);
    extent_.init(envelope.MinX, envelope.MinY, envelope.MaxX, envelope.MaxY);

    // scan for index file
    // TODO - layer names don't match dataset name, so this will break for
    // any layer types of ogr than shapefiles, etc
    // fix here and in ogrindex
    size_t breakpoint = dataset_name_.find_last_of(".");
    if (breakpoint == std::string::npos)
    {
        breakpoint = dataset_name_.length();
    }
    index_name_ = dataset_name_.substr(0, breakpoint) + ".ogrindex";

    std::ifstream index_file(index_name_.c_str(), std::ios::in | std::ios::binary);
    if (index_file)
    {
        indexed_ = true;
        index_file.close();
    }
#if 0
    // TODO - enable this warning once the ogrindex tool is a bit more stable/mature
    else
    {
      std::clog << "### Notice: no ogrindex file found for " << dataset_name_
                << ", use the 'ogrindex' program to build an index for faster rendering"
                << std::endl;
    }
#endif

    // deal with attributes descriptions
    OGRFeatureDefn* def = layer->GetLayerDefn();
    if (def != 0)
    {
        const int fld_count = def->GetFieldCount();
        for (int i = 0; i < fld_count; i++)
        {
            OGRFieldDefn* fld = def->GetFieldDefn(i);

            const std::string fld_name = fld->GetNameRef();
            const OGRFieldType type_oid = fld->GetType();

            switch (type_oid)
            {
            case OFTInteger:
                desc_.add_descriptor(attribute_descriptor(fld_name, mapnik::Integer));
                break;

            case OFTReal:
                desc_.add_descriptor(attribute_descriptor(fld_name, mapnik::Double));
                break;

            case OFTString:
            case OFTWideString: // deprecated
                desc_.add_descriptor(attribute_descriptor(fld_name, mapnik::String));
                break;

            case OFTBinary:
                desc_.add_descriptor(attribute_descriptor(fld_name, mapnik::Object));
                break;

            case OFTIntegerList:
            case OFTRealList:
            case OFTStringList:
            case OFTWideStringList: // deprecated !
#ifdef MAPNIK_DEBUG
                std::clog << "OGR Plugin: unhandled type_oid=" << type_oid << std::endl;
#endif
                break;

            case OFTDate:
            case OFTTime:
            case OFTDateTime: // unhandled !
#ifdef MAPNIK_DEBUG
                std::clog << "OGR Plugin: unhandled type_oid=" << type_oid << std::endl;
#endif
                desc_.add_descriptor(attribute_descriptor(fld_name, mapnik::Object));
                break;

            default: // unknown
#ifdef MAPNIK_DEBUG
                std::clog << "OGR Plugin: unknown type_oid=" << type_oid << std::endl;
#endif
                break;
            }
        }
    }

    is_bound_ = true;
}
OGRErr OGRSQLiteTableLayer::CreateField( OGRFieldDefn *poFieldIn, 
                                         int bApproxOK )

{
    OGRFieldDefn        oField( poFieldIn );

    ResetReading();

    if (!poDS->GetUpdate())
    {
        CPLError( CE_Failure, CPLE_NotSupported,
                  "Can't create fields on a read-only layer.");
        return OGRERR_FAILURE;
    }

/* -------------------------------------------------------------------- */
/*      Do we want to "launder" the column names into SQLite            */
/*      friendly format?                                                */
/* -------------------------------------------------------------------- */
    if( bLaunderColumnNames )
    {
        char    *pszSafeName = poDS->LaunderName( oField.GetNameRef() );

        oField.SetName( pszSafeName );
        CPLFree( pszSafeName );
    }

/* -------------------------------------------------------------------- */
/*      How much space do we need for the list of fields.               */
/* -------------------------------------------------------------------- */
    int iField, nFieldListLen = 100;
    char *pszOldFieldList, *pszNewFieldList;

    for( iField = 0; iField < poFeatureDefn->GetFieldCount(); iField++ )
    {
        nFieldListLen += 
            strlen(poFeatureDefn->GetFieldDefn(iField)->GetNameRef()) + 50;
    }

    nFieldListLen += strlen( oField.GetNameRef() );

    pszOldFieldList = (char *) CPLCalloc(1,nFieldListLen);
    pszNewFieldList = (char *) CPLCalloc(1,nFieldListLen);

/* -------------------------------------------------------------------- */
/*      Build list of old fields, and the list of new fields.           */
/* -------------------------------------------------------------------- */
    const char *pszType;
    sprintf( pszOldFieldList, "%s", "OGC_FID" );
    sprintf( pszNewFieldList, "%s", "OGC_FID INTEGER PRIMARY KEY" );
    
    int iNextOrdinal = 3; /* _rowid_ is 1, OGC_FID is 2 */

    if( poFeatureDefn->GetGeomType() != wkbNone )
    {
        strcat( pszOldFieldList, "," );
        strcat( pszNewFieldList, "," );

        strcat( pszOldFieldList, osGeomColumn );
        strcat( pszNewFieldList, osGeomColumn );

        if ( eGeomFormat == OSGF_WKT )
            strcat( pszNewFieldList, " VARCHAR" );
        else
            strcat( pszNewFieldList, " BLOB" );

        iNextOrdinal++;
    }

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

        // we already added OGC_FID so don't do it again
        if( EQUAL(poFldDefn->GetNameRef(),"OGC_FID") )
            continue;

        if( poFldDefn->GetType() == OFTInteger )
            pszType = "INTEGER";
        else if( poFldDefn->GetType() == OFTReal )
            pszType = "FLOAT";
        else if( poFldDefn->GetType() == OFTBinary )
            pszType = "BLOB";
        else
            pszType = "VARCHAR";
        
        sprintf( pszOldFieldList+strlen(pszOldFieldList), 
                 ", '%s'", poFldDefn->GetNameRef() );

        sprintf( pszNewFieldList+strlen(pszNewFieldList), 
                 ", '%s' %s", poFldDefn->GetNameRef(), pszType );

        iNextOrdinal++;
    }

/* -------------------------------------------------------------------- */
/*      Add the new field.                                              */
/* -------------------------------------------------------------------- */
    if( oField.GetType() == OFTInteger )
        pszType = "INTEGER";
    else if( oField.GetType() == OFTReal )
        pszType = "FLOAT";
    else if( oField.GetType() == OFTBinary )
        pszType = "BLOB";
    else
        pszType = "VARCHAR";
    
    sprintf( pszNewFieldList+strlen(pszNewFieldList), 
             ", '%s' %s", oField.GetNameRef(), pszType );

/* ==================================================================== */
/*      Backup, destroy, recreate and repopulate the table.  SQLite     */
/*      has no ALTER TABLE so we have to do all this to add a           */
/*      column.                                                         */
/* ==================================================================== */

/* -------------------------------------------------------------------- */
/*      Do this all in a transaction.                                   */
/* -------------------------------------------------------------------- */
    poDS->SoftStartTransaction();

/* -------------------------------------------------------------------- */
/*      Save existing related triggers and index                        */
/* -------------------------------------------------------------------- */
    int rc;
    char *pszErrMsg = NULL;
    sqlite3 *hDB = poDS->GetDB();
    CPLString osSQL;

    osSQL.Printf( "SELECT sql FROM sqlite_master WHERE type IN ('trigger','index') AND tbl_name='%s'",
                   pszEscapedTableName );

    int nRowTriggerIndexCount, nColTriggerIndexCount;
    char **papszTriggerIndexResult = NULL;
    rc = sqlite3_get_table( hDB, osSQL.c_str(), &papszTriggerIndexResult, 
                            &nRowTriggerIndexCount, &nColTriggerIndexCount, &pszErrMsg );

/* -------------------------------------------------------------------- */
/*      Make a backup of the table.                                     */
/* -------------------------------------------------------------------- */

    if( rc == SQLITE_OK )
        rc = sqlite3_exec( hDB, 
                       CPLSPrintf( "CREATE TEMPORARY TABLE t1_back(%s)",
                                   pszOldFieldList ),
                       NULL, NULL, &pszErrMsg );

    if( rc == SQLITE_OK )
        rc = sqlite3_exec( hDB, 
                           CPLSPrintf( "INSERT INTO t1_back SELECT %s FROM '%s'",
                                       pszOldFieldList, 
                                       pszEscapedTableName ),
                           NULL, NULL, &pszErrMsg );


/* -------------------------------------------------------------------- */
/*      Drop the original table, and recreate with new field.           */
/* -------------------------------------------------------------------- */
    if( rc == SQLITE_OK )
        rc = sqlite3_exec( hDB, 
                           CPLSPrintf( "DROP TABLE '%s'", 
                                       pszEscapedTableName ),
                           NULL, NULL, &pszErrMsg );

    if( rc == SQLITE_OK )
    {
        const char *pszCmd = 
            CPLSPrintf( "CREATE TABLE '%s' (%s)", 
                        pszEscapedTableName,
                        pszNewFieldList );
        rc = sqlite3_exec( hDB, pszCmd, 
                           NULL, NULL, &pszErrMsg );

        CPLDebug( "OGR_SQLITE", "exec(%s)", pszCmd );
    }

/* -------------------------------------------------------------------- */
/*      Copy backup field values into new table.                        */
/* -------------------------------------------------------------------- */
    
    if( rc == SQLITE_OK )
        rc = sqlite3_exec( hDB, 
                           CPLSPrintf( "INSERT INTO '%s' SELECT %s, NULL FROM t1_back",
                                       pszEscapedTableName,
                                       pszOldFieldList ),
                           NULL, NULL, &pszErrMsg );

    CPLFree( pszOldFieldList );
    CPLFree( pszNewFieldList );

/* -------------------------------------------------------------------- */
/*      Cleanup backup table.                                           */
/* -------------------------------------------------------------------- */
    
    if( rc == SQLITE_OK )
        rc = sqlite3_exec( hDB, 
                           CPLSPrintf( "DROP TABLE t1_back" ),
                           NULL, NULL, &pszErrMsg );

/* -------------------------------------------------------------------- */
/*      Recreate existing related tables, triggers and index            */
/* -------------------------------------------------------------------- */

    if( rc == SQLITE_OK )
    {
        int i;

        for(i = 1; i <= nRowTriggerIndexCount && nColTriggerIndexCount == 1 && rc == SQLITE_OK; i++)
        {
            if (papszTriggerIndexResult[i] != NULL && papszTriggerIndexResult[i][0] != '\0')
                rc = sqlite3_exec( hDB, 
                            papszTriggerIndexResult[i],
                            NULL, NULL, &pszErrMsg );
        }
    }

/* -------------------------------------------------------------------- */
/*      COMMIT on success or ROLLBACK on failuire.                      */
/* -------------------------------------------------------------------- */

    sqlite3_free_table( papszTriggerIndexResult );

    if( rc == SQLITE_OK )
    {
        poDS->SoftCommit();
    }
    else
    {
        CPLError( CE_Failure, CPLE_AppDefined, 
                  "Failed to add field %s to table %s:\n %s",
                  oField.GetNameRef(), poFeatureDefn->GetName(), 
                  pszErrMsg );
        sqlite3_free( pszErrMsg );

        poDS->SoftRollback();

        return OGRERR_FAILURE;
    }

/* -------------------------------------------------------------------- */
/*      Add the field to the OGRFeatureDefn.                            */
/* -------------------------------------------------------------------- */
    int iNewField;

    poFeatureDefn->AddFieldDefn( &oField );

    iNewField = poFeatureDefn->GetFieldCount() - 1;
    panFieldOrdinals = (int *) 
        CPLRealloc(panFieldOrdinals, (iNewField+1) * sizeof(int) );
    panFieldOrdinals[iNewField] = iNextOrdinal;

    return OGRERR_NONE;
}
Beispiel #22
0
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;
}
json_object* OGRGeoJSONWriteAttributes( OGRFeature* poFeature )
{
    CPLAssert( NULL != poFeature );

    json_object* poObjProps = json_object_new_object();
    CPLAssert( NULL != poObjProps );

    OGRFeatureDefn* poDefn = poFeature->GetDefnRef();
    for( int nField = 0; nField < poDefn->GetFieldCount(); ++nField )
    {
        json_object* poObjProp;
        OGRFieldDefn* poFieldDefn = poDefn->GetFieldDefn( nField );
        CPLAssert( NULL != poFieldDefn );
        OGRFieldType eType = poFieldDefn->GetType();
        OGRFieldSubType eSubType = poFieldDefn->GetSubType();

        if( !poFeature->IsFieldSet(nField) )
        {
            poObjProp = NULL;
        }
        else if( OFTInteger == eType )
        {
            if( eSubType == OFSTBoolean )
                poObjProp = json_object_new_boolean( 
                    poFeature->GetFieldAsInteger( nField ) );
            else
                poObjProp = json_object_new_int( 
                    poFeature->GetFieldAsInteger( nField ) );
        }
        else if( OFTInteger64 == eType )
        {
            if( eSubType == OFSTBoolean )
                poObjProp = json_object_new_boolean( 
                    (json_bool)poFeature->GetFieldAsInteger64( nField ) );
            else
                poObjProp = json_object_new_int64( 
                    poFeature->GetFieldAsInteger64( nField ) );
        }
        else if( OFTReal == eType )
        {
            poObjProp = json_object_new_double( 
                poFeature->GetFieldAsDouble(nField) );
        }
        else if( OFTString == eType )
        {
            poObjProp = json_object_new_string( 
                poFeature->GetFieldAsString(nField) );
        }
        else if( OFTIntegerList == eType )
        {
            int nSize = 0;
            const int* panList = poFeature->GetFieldAsIntegerList(nField, &nSize);
            poObjProp = json_object_new_array();
            for(int i=0;i<nSize;i++)
            {
                if( eSubType == OFSTBoolean )
                    json_object_array_add(poObjProp,
                            json_object_new_boolean(panList[i]));
                else
                    json_object_array_add(poObjProp,
                            json_object_new_int(panList[i]));
            }
        }
        else if( OFTInteger64List == eType )
        {
            int nSize = 0;
            const GIntBig* panList = poFeature->GetFieldAsInteger64List(nField, &nSize);
            poObjProp = json_object_new_array();
            for(int i=0;i<nSize;i++)
            {
                if( eSubType == OFSTBoolean )
                    json_object_array_add(poObjProp,
                            json_object_new_boolean((json_bool)panList[i]));
                else
                    json_object_array_add(poObjProp,
                            json_object_new_int64(panList[i]));
            }
        }
        else if( OFTRealList == eType )
        {
            int nSize = 0;
            const double* padfList = poFeature->GetFieldAsDoubleList(nField, &nSize);
            poObjProp = json_object_new_array();
            for(int i=0;i<nSize;i++)
            {
                json_object_array_add(poObjProp,
                            json_object_new_double(padfList[i]));
            }
        }
        else if( OFTStringList == eType )
        {
            char** papszStringList = poFeature->GetFieldAsStringList(nField);
            poObjProp = json_object_new_array();
            for(int i=0; papszStringList && papszStringList[i]; i++)
            {
                json_object_array_add(poObjProp,
                            json_object_new_string(papszStringList[i]));
            }
        }
        else
        {
            poObjProp = json_object_new_string( 
                 poFeature->GetFieldAsString(nField) );
        }

        json_object_object_add( poObjProps,
                                poFieldDefn->GetNameRef(),
                                poObjProp );
    }

    return poObjProps;
}
Beispiel #24
0
CPLString OGRPLScenesLayer::BuildFilter(swq_expr_node* poNode)
{
    if( poNode->eNodeType == SNT_OPERATION )
    {
        if( poNode->nOperation == SWQ_AND && poNode->nSubExprCount == 2 )
        {
            // For AND, we can deal with a failure in one of the branch
            // since client-side will do that extra filtering
            CPLString osFilter1 = BuildFilter(poNode->papoSubExpr[0]);
            CPLString osFilter2 = BuildFilter(poNode->papoSubExpr[1]);
            if( osFilter1.size() && osFilter2.size() )
                return osFilter1 + "&" + osFilter2;
            else if( osFilter1.size() )
                return osFilter1;
            else
                return osFilter2;
        }
        else if( (poNode->nOperation == SWQ_EQ ||
                  poNode->nOperation == SWQ_NE ||
                  poNode->nOperation == SWQ_LT ||
                  poNode->nOperation == SWQ_LE ||
                  poNode->nOperation == SWQ_GT ||
                  poNode->nOperation == SWQ_GE) && poNode->nSubExprCount == 2 &&
                  poNode->papoSubExpr[0]->eNodeType == SNT_COLUMN &&
                  poNode->papoSubExpr[1]->eNodeType == SNT_CONSTANT &&
                  poNode->papoSubExpr[0]->field_index != poFeatureDefn->GetFieldIndex("id") &&
                  poNode->papoSubExpr[0]->field_index < poFeatureDefn->GetFieldCount() )
        {
            OGRFieldDefn *poFieldDefn =
                poFeatureDefn->GetFieldDefn(poNode->papoSubExpr[0]->field_index);

            int nOperation = poNode->nOperation;

            // image_quality supports only gte filters
            // (https://www.planet.com/docs-v0/v0/scenes/planetscope/#metadata)
            if( poNode->papoSubExpr[0]->field_index ==
                    poFeatureDefn->GetFieldIndex("image_statistics.image_quality") &&
                nOperation != SWQ_GE )
            {
                // == target can be safely turned as >= target
                if( poNode->nOperation == SWQ_EQ &&
                    poNode->papoSubExpr[1]->field_type == SWQ_STRING &&
                    strcmp(poNode->papoSubExpr[1]->string_value, "target") == 0 )
                {
                    nOperation = SWQ_GE;
                }
                else
                {
                    if( !bFilterMustBeClientSideEvaluated )
                    {
                        bFilterMustBeClientSideEvaluated = true;
                        CPLDebug("PLSCENES",
                                 "Part or full filter will have to be "
                                 "evaluated on client side.");
                    }
                    return "";
                }
            }

            CPLString osFilter(poFieldDefn->GetNameRef());

            bool bDateTimeParsed = false;
            int nYear = 0;
            int nMonth = 0;
            int nDay = 0;
            int nHour = 0;
            int nMinute = 0;
            int nSecond = 0;
            if( poNode->papoSubExpr[1]->field_type == SWQ_TIMESTAMP )
            {
                if( sscanf(poNode->papoSubExpr[1]->string_value,"%04d/%02d/%02d %02d:%02d:%02d",
                           &nYear, &nMonth, &nDay, &nHour, &nMinute, &nSecond) >= 3 ||
                    sscanf(poNode->papoSubExpr[1]->string_value,"%04d-%02d-%02dT%02d:%02d:%02d",
                           &nYear, &nMonth, &nDay, &nHour, &nMinute, &nSecond) >= 3 )
                    bDateTimeParsed = true;
            }

            osFilter += ".";

            if( nOperation == SWQ_EQ )
            {
                if( bDateTimeParsed )
                    osFilter += "gte";
                else
                    osFilter += "eq";
            }
            else if( nOperation == SWQ_NE )
                osFilter += "neq";
            else if( nOperation == SWQ_LT )
                osFilter += "lt";
            else if( nOperation == SWQ_LE )
                osFilter += "lte";
            else if( nOperation == SWQ_GT )
                osFilter += "gt";
            else if( nOperation == SWQ_GE )
                osFilter += "gte";
            osFilter += "=";

            if (poNode->papoSubExpr[1]->field_type == SWQ_FLOAT)
                osFilter += CPLSPrintf("%.8f", poNode->papoSubExpr[1]->float_value);
            else if (poNode->papoSubExpr[1]->field_type == SWQ_INTEGER)
                osFilter += CPLSPrintf(CPL_FRMT_GIB, poNode->papoSubExpr[1]->int_value);
            else if (poNode->papoSubExpr[1]->field_type == SWQ_STRING)
                osFilter += poNode->papoSubExpr[1]->string_value;
            else if (poNode->papoSubExpr[1]->field_type == SWQ_TIMESTAMP)
            {
                if( bDateTimeParsed )
                {
                    osFilter += CPLSPrintf("%04d-%02d-%02dT%02d:%02d:%02d",
                                           nYear, nMonth, nDay, nHour, nMinute, nSecond);
                    if( nOperation == SWQ_EQ )
                    {
                        osFilter += "&";
                        osFilter += poFieldDefn->GetNameRef();
                        osFilter += ".lt=";
                        nSecond ++;
                        if( nSecond == 60 ) { nSecond = 0; nMinute ++; }
                        if( nMinute == 60 ) { nMinute = 0; nHour ++; }
                        if( nHour == 24 ) { nHour = 0; nDay ++; }
                        osFilter += CPLSPrintf("%04d-%02d-%02dT%02d:%02d:%02d",
                                               nYear, nMonth, nDay, nHour, nMinute, nSecond);
                    }
                }
                else
                    osFilter += poNode->papoSubExpr[1]->string_value;
            }
            return osFilter;
        }
    }
    if( !bFilterMustBeClientSideEvaluated )
    {
        bFilterMustBeClientSideEvaluated = true;
        CPLDebug("PLSCENES",
                 "Part or full filter will have to be evaluated on client side.");
    }
    return "";
}
Beispiel #25
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 #26
0
OGRFeatureDefn *OGRUnionLayer::GetLayerDefn()
{
    if( poFeatureDefn != NULL )
        return poFeatureDefn;

    poFeatureDefn = new OGRFeatureDefn( osName );
    poFeatureDefn->Reference();
    poFeatureDefn->SetGeomType(wkbNone);

    int iCompareFirstIndex = 0;
    if( osSourceLayerFieldName.size() )
    {
        OGRFieldDefn oField(osSourceLayerFieldName, OFTString);
        poFeatureDefn->AddFieldDefn(&oField);
        iCompareFirstIndex = 1;
    }

    if( eFieldStrategy == FIELD_SPECIFIED )
    {
        int i;
        for(i = 0; i < nFields; i++)
            poFeatureDefn->AddFieldDefn(papoFields[i]);
        for(i = 0; i < nGeomFields; i++)
        {
            poFeatureDefn->AddGeomFieldDefn(new OGRUnionLayerGeomFieldDefn(papoGeomFields[i]), FALSE);
            OGRUnionLayerGeomFieldDefn* poGeomFieldDefn =
                (OGRUnionLayerGeomFieldDefn* ) poFeatureDefn->GetGeomFieldDefn(i);

            if( poGeomFieldDefn->bGeomTypeSet == FALSE ||
                poGeomFieldDefn->bSRSSet == FALSE )
            {
                for(int iLayer = 0; iLayer < nSrcLayers; iLayer++)
                {
                    OGRFeatureDefn* poSrcFeatureDefn =
                                papoSrcLayers[iLayer]->GetLayerDefn();
                    int nIndex =
                        poSrcFeatureDefn->GetGeomFieldIndex(poGeomFieldDefn->GetNameRef());
                    if( nIndex >= 0 )
                    {
                        OGRGeomFieldDefn* poSrcGeomFieldDefn =
                            poSrcFeatureDefn->GetGeomFieldDefn(nIndex);
                        if( poGeomFieldDefn->bGeomTypeSet == FALSE )
                        {
                            poGeomFieldDefn->bGeomTypeSet = TRUE;
                            poGeomFieldDefn->SetType(poSrcGeomFieldDefn->GetType());
                        }
                        if( poGeomFieldDefn->bSRSSet == FALSE )
                        {
                            poGeomFieldDefn->bSRSSet = TRUE;
                            poGeomFieldDefn->SetSpatialRef(poSrcGeomFieldDefn->GetSpatialRef());
                            if( i == 0 && poGlobalSRS == NULL )
                            {
                                poGlobalSRS = poSrcGeomFieldDefn->GetSpatialRef();
                                if( poGlobalSRS != NULL )
                                    poGlobalSRS->Reference();
                            }
                        }
                        break;
                    }
                }
            }
        }
    }
    else if( eFieldStrategy == FIELD_FROM_FIRST_LAYER )
    {
        OGRFeatureDefn* poSrcFeatureDefn = papoSrcLayers[0]->GetLayerDefn();
        int i;
        for(i = 0; i < poSrcFeatureDefn->GetFieldCount(); i++)
            poFeatureDefn->AddFieldDefn(poSrcFeatureDefn->GetFieldDefn(i));
        for(i = 0;  nGeomFields != - 1 && i < poSrcFeatureDefn->GetGeomFieldCount(); i++)
        {
            OGRGeomFieldDefn* poFldDefn = poSrcFeatureDefn->GetGeomFieldDefn(i);
            poFeatureDefn->AddGeomFieldDefn(
                new OGRUnionLayerGeomFieldDefn(poFldDefn), FALSE);
        }
    }
    else if (eFieldStrategy == FIELD_UNION_ALL_LAYERS )
    {
        if( nGeomFields == 1 )
        {
            poFeatureDefn->AddGeomFieldDefn(
                        new OGRUnionLayerGeomFieldDefn(papoGeomFields[0]), FALSE);
        }

        for(int iLayer = 0; iLayer < nSrcLayers; iLayer++)
        {
            OGRFeatureDefn* poSrcFeatureDefn =
                                papoSrcLayers[iLayer]->GetLayerDefn();

            /* Add any field that is found in the source layers */
            int i;
            for(i = 0; i < poSrcFeatureDefn->GetFieldCount(); i++)
            {
                OGRFieldDefn* poSrcFieldDefn = poSrcFeatureDefn->GetFieldDefn(i);
                int nIndex =
                    poFeatureDefn->GetFieldIndex(poSrcFieldDefn->GetNameRef());
                if( nIndex < 0 )
                    poFeatureDefn->AddFieldDefn(poSrcFieldDefn);
                else
                {
                    OGRFieldDefn* poFieldDefn =
                                        poFeatureDefn->GetFieldDefn(nIndex);
                    MergeFieldDefn(poFieldDefn, poSrcFieldDefn);
                }
            }

            for(i = 0; nGeomFields != - 1 && i < poSrcFeatureDefn->GetGeomFieldCount(); i++)
            {
                OGRGeomFieldDefn* poSrcFieldDefn = poSrcFeatureDefn->GetGeomFieldDefn(i);
                int nIndex =
                    poFeatureDefn->GetGeomFieldIndex(poSrcFieldDefn->GetNameRef());
                if( nIndex < 0 )
                {
                    poFeatureDefn->AddGeomFieldDefn(
                        new OGRUnionLayerGeomFieldDefn(poSrcFieldDefn), FALSE);
                    if( poFeatureDefn->GetGeomFieldCount() == 1 && nGeomFields == 0 &&
                        GetSpatialRef() != NULL )
                    {
                        OGRUnionLayerGeomFieldDefn* poGeomFieldDefn =
                            (OGRUnionLayerGeomFieldDefn* ) poFeatureDefn->GetGeomFieldDefn(0);
                        poGeomFieldDefn->bSRSSet = TRUE;
                        poGeomFieldDefn->SetSpatialRef(GetSpatialRef());
                    }
                }
                else
                {
                    if( nIndex == 0 && nGeomFields == 1 )
                    {
                        OGRUnionLayerGeomFieldDefn* poGeomFieldDefn =
                            (OGRUnionLayerGeomFieldDefn* ) poFeatureDefn->GetGeomFieldDefn(0);
                        if( poGeomFieldDefn->bGeomTypeSet == FALSE )
                        {
                            poGeomFieldDefn->bGeomTypeSet = TRUE;
                            poGeomFieldDefn->SetType(poSrcFieldDefn->GetType());
                        }
                        if( poGeomFieldDefn->bSRSSet == FALSE )
                        {
                            poGeomFieldDefn->bSRSSet = TRUE;
                            poGeomFieldDefn->SetSpatialRef(poSrcFieldDefn->GetSpatialRef());
                        }
                    }
                    /* TODO: merge type, SRS, extent ? */
                }
            }
        }
    }
    else if (eFieldStrategy == FIELD_INTERSECTION_ALL_LAYERS )
    {
        OGRFeatureDefn* poSrcFeatureDefn = papoSrcLayers[0]->GetLayerDefn();
        int i;
        for(i = 0; i < poSrcFeatureDefn->GetFieldCount(); i++)
            poFeatureDefn->AddFieldDefn(poSrcFeatureDefn->GetFieldDefn(i));
        for(i = 0; i < poSrcFeatureDefn->GetGeomFieldCount(); i++)
        {
            OGRGeomFieldDefn* poFldDefn = poSrcFeatureDefn->GetGeomFieldDefn(i);
            poFeatureDefn->AddGeomFieldDefn(
                new OGRUnionLayerGeomFieldDefn(poFldDefn), FALSE);
        }

        /* Remove any field that is not found in the source layers */
        for(int iLayer = 1; iLayer < nSrcLayers; iLayer++)
        {
            OGRFeatureDefn* l_poSrcFeatureDefn =
                                        papoSrcLayers[iLayer]->GetLayerDefn();
            for(i = iCompareFirstIndex; i < poFeatureDefn->GetFieldCount();)
            {
                OGRFieldDefn* poFieldDefn = poFeatureDefn->GetFieldDefn(i);
                int nSrcIndex = l_poSrcFeatureDefn->GetFieldIndex(
                                                    poFieldDefn->GetNameRef());
                if( nSrcIndex < 0 )
                {
                    poFeatureDefn->DeleteFieldDefn(i);
                }
                else
                {
                    OGRFieldDefn* poSrcFieldDefn =
                        l_poSrcFeatureDefn->GetFieldDefn(nSrcIndex);
                    MergeFieldDefn(poFieldDefn, poSrcFieldDefn);

                    i ++;
                }
            }
            for(i = 0; i < poFeatureDefn->GetGeomFieldCount();)
            {
                OGRGeomFieldDefn* poFieldDefn = poFeatureDefn->GetGeomFieldDefn(i);
                int nSrcIndex = l_poSrcFeatureDefn->GetGeomFieldIndex(
                                                    poFieldDefn->GetNameRef());
                if( nSrcIndex < 0 )
                {
                    poFeatureDefn->DeleteGeomFieldDefn(i);
                }
                else
                {
                    /* TODO: merge type, SRS, extent ? */

                    i ++;
                }
            }
        }
    }

    return poFeatureDefn;
}
Beispiel #27
0
void GTMWaypointLayer::WriteFeatureAttributes( OGRFeature *poFeature, float altitude )
{
    char psNameField[] = "          "; // 10 spaces
    char* pszcomment = nullptr;
    int icon = 48;
    int date = 0;
    for (int i = 0; i < poFeatureDefn->GetFieldCount(); ++i)
    {
        OGRFieldDefn *poFieldDefn = poFeatureDefn->GetFieldDefn( i );
        if( poFeature->IsFieldSetAndNotNull( i ) )
        {
            const char* l_pszName = poFieldDefn->GetNameRef();
            /* Waypoint name */
            if (STARTS_WITH(l_pszName, "name"))
            {
                strncpy (psNameField, poFeature->GetFieldAsString( i ), 10);
                CPLStrlcat (psNameField, "          ", sizeof(psNameField));
            }
            /* Waypoint comment */
            else if (STARTS_WITH(l_pszName, "comment"))
            {
                CPLFree(pszcomment);
                pszcomment = CPLStrdup( poFeature->GetFieldAsString( i ) );
            }
            /* Waypoint icon */
            else if (STARTS_WITH(l_pszName, "icon"))
            {
                icon = poFeature->GetFieldAsInteger( i );
                // Check if it is a valid icon
                if (icon < 1 || icon > 220)
                    icon = 48;
            }
            /* Waypoint date */
            else if (EQUAL(l_pszName, "time"))
            {
                struct tm brokendowndate;
                int year, month, day, hour, min, sec, TZFlag;
                if (poFeature->GetFieldAsDateTime( i, &year, &month, &day, &hour, &min, &sec, &TZFlag))
                {
                    brokendowndate.tm_year = year - 1900;
                    brokendowndate.tm_mon = month - 1;
                    brokendowndate.tm_mday = day;
                    brokendowndate.tm_hour = hour;
                    brokendowndate.tm_min = min;
                    brokendowndate.tm_sec = sec;
                    GIntBig unixTime = CPLYMDHMSToUnixTime(&brokendowndate);
                    if (TZFlag != 0)
                        unixTime -= (TZFlag - 100) * 15;
                    if (unixTime <= GTM_EPOCH || (unixTime - GTM_EPOCH) != (int)(unixTime - GTM_EPOCH))
                    {
                        CPLError(CE_Warning, CPLE_AppDefined,
                                  "%04d/%02d/%02d %02d:%02d:%02d is not a valid datetime for GTM",
                                  year, month, day, hour, min, sec);
                    }
                    else
                    {
                        date = (int)(unixTime - GTM_EPOCH);
                    }
                }
            }
        }
    }

    if (pszcomment == nullptr)
        pszcomment = CPLStrdup( "" );

    const size_t commentLength = strlen(pszcomment);

    const size_t bufferSize = 27 + commentLength;
    void* pBuffer = CPLMalloc(bufferSize);
    void* pBufferAux = pBuffer;
    /* Write waypoint name to buffer */
    memcpy((char*)pBufferAux, psNameField, 10);

    /* Write waypoint string comment size to buffer */
    pBufferAux = (char*)pBuffer+10;
    appendUShort(pBufferAux, (unsigned short) commentLength);

    /* Write waypoint string comment to buffer */
    memcpy((char*)pBuffer+12, pszcomment, commentLength);

    /* Write icon to buffer */
    pBufferAux = (char*)pBuffer+12+commentLength;
    appendUShort(pBufferAux, (unsigned short) icon);

    /* Write dslp to buffer */
    pBufferAux = (char*)pBufferAux + 2;
    appendUChar(pBufferAux, 3);

    /* Date */
    pBufferAux = (char*)pBufferAux + 1;
    appendInt(pBufferAux, date);

    /* wrot */
    pBufferAux = (char*)pBufferAux + 4;
    appendUShort(pBufferAux, 0);

    /* walt */
    pBufferAux = (char*)pBufferAux + 2;
    appendFloat(pBufferAux, altitude);

    /* wlayer */
    pBufferAux = (char*)pBufferAux + 4;
    appendUShort(pBufferAux, 0);

    VSIFWriteL(pBuffer, bufferSize, 1, poDS->getOutputFP());
    poDS->incNumWaypoints();

    CPLFree(pszcomment);
    CPLFree(pBuffer);
}
Beispiel #28
0
void OGRUnionLayer::ConfigureActiveLayer()
{
    AutoWarpLayerIfNecessary(iCurLayer);
    ApplyAttributeFilterToSrcLayer(iCurLayer);
    SetSpatialFilterToSourceLayer(papoSrcLayers[iCurLayer]);
    papoSrcLayers[iCurLayer]->ResetReading();

    /* Establish map */
    GetLayerDefn();
    OGRFeatureDefn* poSrcFeatureDefn = papoSrcLayers[iCurLayer]->GetLayerDefn();
    CPLFree(panMap);
    panMap = (int*) CPLMalloc(poSrcFeatureDefn->GetFieldCount() * sizeof(int));
    for(int i=0; i < poSrcFeatureDefn->GetFieldCount(); i++)
    {
        OGRFieldDefn* poSrcFieldDefn = poSrcFeatureDefn->GetFieldDefn(i);
        if( CSLFindString(papszIgnoredFields,
                          poSrcFieldDefn->GetNameRef() ) == -1 )
        {
            panMap[i] =
                poFeatureDefn->GetFieldIndex(poSrcFieldDefn->GetNameRef());
        }
        else
        {
            panMap[i] = -1;
        }
    }

    if( papoSrcLayers[iCurLayer]->TestCapability(OLCIgnoreFields) )
    {
        char** papszIter = papszIgnoredFields;
        char** papszFieldsSrc = NULL;
        while ( papszIter != NULL && *papszIter != NULL )
        {
            const char* pszFieldName = *papszIter;
            if ( EQUAL(pszFieldName, "OGR_GEOMETRY") ||
                 EQUAL(pszFieldName, "OGR_STYLE") ||
                 poSrcFeatureDefn->GetFieldIndex(pszFieldName) >= 0 ||
                 poSrcFeatureDefn->GetGeomFieldIndex(pszFieldName) >= 0 )
            {
                papszFieldsSrc = CSLAddString(papszFieldsSrc, pszFieldName);
            }
            papszIter++;
        }

        /* Attribute fields */
        int* panSrcFieldsUsed = (int*) CPLCalloc(sizeof(int),
                                          poSrcFeatureDefn->GetFieldCount());
        for(int iField = 0;
                iField < poFeatureDefn->GetFieldCount(); iField++)
        {
            OGRFieldDefn* poFieldDefn = poFeatureDefn->GetFieldDefn(iField);
            int iSrcField =
                    poSrcFeatureDefn->GetFieldIndex(poFieldDefn->GetNameRef());
            if (iSrcField >= 0)
                panSrcFieldsUsed[iSrcField] = TRUE;
        }
        for(int iSrcField = 0;
                iSrcField < poSrcFeatureDefn->GetFieldCount(); iSrcField ++)
        {
            if( !panSrcFieldsUsed[iSrcField] )
            {
                OGRFieldDefn *poSrcDefn =
                        poSrcFeatureDefn->GetFieldDefn( iSrcField );
                papszFieldsSrc =
                        CSLAddString(papszFieldsSrc, poSrcDefn->GetNameRef());
            }
        }
        CPLFree(panSrcFieldsUsed);

        /* geometry fields now */
        panSrcFieldsUsed = (int*) CPLCalloc(sizeof(int),
                                          poSrcFeatureDefn->GetGeomFieldCount());
        for(int iField = 0;
                iField < poFeatureDefn->GetGeomFieldCount(); iField++)
        {
            OGRGeomFieldDefn* poFieldDefn = poFeatureDefn->GetGeomFieldDefn(iField);
            int iSrcField =
                    poSrcFeatureDefn->GetGeomFieldIndex(poFieldDefn->GetNameRef());
            if (iSrcField >= 0)
                panSrcFieldsUsed[iSrcField] = TRUE;
        }
        for(int iSrcField = 0;
                iSrcField < poSrcFeatureDefn->GetGeomFieldCount(); iSrcField ++)
        {
            if( !panSrcFieldsUsed[iSrcField] )
            {
                OGRGeomFieldDefn *poSrcDefn =
                        poSrcFeatureDefn->GetGeomFieldDefn( iSrcField );
                papszFieldsSrc =
                        CSLAddString(papszFieldsSrc, poSrcDefn->GetNameRef());
            }
        }
        CPLFree(panSrcFieldsUsed);

        papoSrcLayers[iCurLayer]->SetIgnoredFields((const char**)papszFieldsSrc);

        CSLDestroy(papszFieldsSrc);
    }
}
feature_ptr ogr_index_featureset<filterT>::next()
{
    if (itr_ != ids_.end())
    {
        int pos = *itr_++;
        layer_.SetNextByIndex (pos);

        ogr_feature_ptr feat (layer_.GetNextFeature());
        if ((*feat) != NULL)
        {
            // ogr feature ids start at 0, so add one to stay
            // consistent with other mapnik datasources that start at 1
            int feature_id = ((*feat)->GetFID() + 1);
            feature_ptr feature(feature_factory::create(feature_id));
            
            OGRGeometry* geom=(*feat)->GetGeometryRef();
            if (geom && !geom->IsEmpty())
            {
                ogr_converter::convert_geometry (geom, feature, multiple_geometries_);
            }
    #ifdef MAPNIK_DEBUG
            else
            {
                std::clog << "### Warning: feature with null geometry: " << (*feat)->GetFID() << "\n";
            }
    #endif
            
            int fld_count = layerdef_->GetFieldCount();
            for (int i = 0; i < fld_count; i++)
            {
                OGRFieldDefn* fld = layerdef_->GetFieldDefn (i);
                OGRFieldType type_oid = fld->GetType ();
                std::string fld_name = fld->GetNameRef ();
            
                switch (type_oid)
                {
                    case OFTInteger:
                    {
                       boost::put(*feature,fld_name,(*feat)->GetFieldAsInteger (i));
                       break;
                    }
                    
                    case OFTReal:
                    {
                       boost::put(*feature,fld_name,(*feat)->GetFieldAsDouble (i));
                       break;
                    }
                           
                    case OFTString:
                    case OFTWideString:     // deprecated !
                    {
                       UnicodeString ustr = tr_->transcode((*feat)->GetFieldAsString (i));
                       boost::put(*feature,fld_name,ustr);
                       break;
                    }
                    
                    case OFTIntegerList:
                    case OFTRealList:
                    case OFTStringList:
                    case OFTWideStringList: // deprecated !
                    {
                    #ifdef MAPNIK_DEBUG
                       std::clog << "OGR Plugin: unhandled type_oid=" << type_oid << std::endl;
                    #endif
                       break;
                    }
                    
                    case OFTBinary:
                    {
                    #ifdef MAPNIK_DEBUG
                       std::clog << "OGR Plugin: unhandled type_oid=" << type_oid << std::endl;
                    #endif
                       //boost::put(*feature,name,feat->GetFieldAsBinary (i, size));
                       break;
                    }
                       
                    case OFTDate:
                    case OFTTime:
                    case OFTDateTime:       // unhandled !
                    {
                    #ifdef MAPNIK_DEBUG
                       std::clog << "OGR Plugin: unhandled type_oid=" << type_oid << std::endl;
                    #endif
                       break;
                    }
                    
                    default: // unknown
                    {
                    #ifdef MAPNIK_DEBUG
                       std::clog << "OGR Plugin: unknown type_oid=" << type_oid << std::endl;
                    #endif
                       break;
                    }
                }
            }
            return feature;
        }
    }
    
    return feature_ptr();
}
CPLString OGRPLScenesLayer::BuildFilter(swq_expr_node* poNode)
{
    if( poNode->eNodeType == SNT_OPERATION )
    {
        if( poNode->nOperation == SWQ_AND && poNode->nSubExprCount == 2 )
        {
            // For AND, we can deal with a failure in one of the branch 
            // since client-side will do that extra filtering
            CPLString osFilter1 = BuildFilter(poNode->papoSubExpr[0]);
            CPLString osFilter2 = BuildFilter(poNode->papoSubExpr[1]);
            if( osFilter1.size() && osFilter2.size() )
                return osFilter1 + "&" + osFilter2;
            else if( osFilter1.size() )
                return osFilter1;
            else
                return osFilter2;
        }
        else if( (poNode->nOperation == SWQ_EQ ||
                  poNode->nOperation == SWQ_NE ||
                  poNode->nOperation == SWQ_LT ||
                  poNode->nOperation == SWQ_LE ||
                  poNode->nOperation == SWQ_GT ||
                  poNode->nOperation == SWQ_GE) && poNode->nSubExprCount == 2 &&
                  poNode->papoSubExpr[0]->eNodeType == SNT_COLUMN &&
                  poNode->papoSubExpr[1]->eNodeType == SNT_CONSTANT &&
                  poNode->papoSubExpr[0]->field_index != poFeatureDefn->GetFieldIndex("id") &&
                  poNode->papoSubExpr[0]->field_index < poFeatureDefn->GetFieldCount() )
        {
            OGRFieldDefn *poFieldDefn;
            poFieldDefn = poFeatureDefn->GetFieldDefn(poNode->papoSubExpr[0]->field_index);

            CPLString osFilter(poFieldDefn->GetNameRef());

            int bDateTimeParsed = FALSE;
            int nYear = 0, nMonth = 0, nDay = 0, nHour = 0, nMinute = 0, nSecond = 0;
            if( poNode->papoSubExpr[1]->field_type == SWQ_TIMESTAMP )
            {
                if( sscanf(poNode->papoSubExpr[1]->string_value,"%04d/%02d/%02d %02d:%02d:%02d",
                           &nYear, &nMonth, &nDay, &nHour, &nMinute, &nSecond) >= 3 ||
                    sscanf(poNode->papoSubExpr[1]->string_value,"%04d-%02d-%02dT%02d:%02d:%02d",
                           &nYear, &nMonth, &nDay, &nHour, &nMinute, &nSecond) >= 3 )
                    bDateTimeParsed = TRUE;
            }

            osFilter += ".";
            if( poNode->nOperation == SWQ_EQ )
            {
                if( bDateTimeParsed )
                    osFilter += "gte";
                else
                    osFilter += "eq";
            }
            else if( poNode->nOperation == SWQ_NE )
                osFilter += "neq";
            else if( poNode->nOperation == SWQ_LT )
                osFilter += "lt";
            else if( poNode->nOperation == SWQ_LE )
                osFilter += "lte";
            else if( poNode->nOperation == SWQ_GT )
                osFilter += "gt";
            else if( poNode->nOperation == SWQ_GE )
                osFilter += "gte";
            osFilter += "=";

            if (poNode->papoSubExpr[1]->field_type == SWQ_FLOAT)
                osFilter += CPLSPrintf("%.8f", poNode->papoSubExpr[1]->float_value);
            else if (poNode->papoSubExpr[1]->field_type == SWQ_INTEGER)
                osFilter += CPLSPrintf(CPL_FRMT_GIB, poNode->papoSubExpr[1]->int_value);
            else if (poNode->papoSubExpr[1]->field_type == SWQ_STRING)
                osFilter += poNode->papoSubExpr[1]->string_value;
            else if (poNode->papoSubExpr[1]->field_type == SWQ_TIMESTAMP)
            {
                if( bDateTimeParsed )
                {
                    osFilter += CPLSPrintf("%04d-%02d-%02dT%02d:%02d:%02d",
                                           nYear, nMonth, nDay, nHour, nMinute, nSecond);
                    if( poNode->nOperation == SWQ_EQ )
                    {
                        osFilter += "&";
                        osFilter += poFieldDefn->GetNameRef();
                        osFilter += ".lt=";
                        nSecond ++;
                        if( nSecond == 60 ) { nSecond = 0; nMinute ++; }
                        if( nMinute == 60 ) { nMinute = 0; nHour ++; }
                        if( nHour == 24 ) { nHour = 0; nDay ++; }
                        osFilter += CPLSPrintf("%04d-%02d-%02dT%02d:%02d:%02d",
                                               nYear, nMonth, nDay, nHour, nMinute, nSecond);
                    }
                }
                else
                    osFilter += poNode->papoSubExpr[1]->string_value;
            }
            return osFilter;
        }
    }
    if( !bFilterMustBeClientSideEvaluated )
    {
        bFilterMustBeClientSideEvaluated = TRUE;
        CPLDebug("PLSCENES",
                 "Part or full filter will have to be evaluated on client side.");
    }
    return "";
}