void Polygon::update(const std::string& wkt_or_json, SpatialReference ref) { bool isJson = wkt_or_json.find("{") != wkt_or_json.npos || wkt_or_json.find("}") != wkt_or_json.npos; if (!isJson) { m_geom = GEOSGeomFromWKT_r(m_ctx, wkt_or_json.c_str()); if (!m_geom) throw pdal_error("Unable to create geometry from input WKT"); } else { // Assume it is GeoJSON and try constructing from that OGRGeometryH json = OGR_G_CreateGeometryFromJson(wkt_or_json.c_str()); if (!json) throw pdal_error("Unable to create geometry from " "input GeoJSON"); char* gdal_wkt(0); OGRErr err = OGR_G_ExportToWkt(json, &gdal_wkt); m_geom = GEOSGeomFromWKT_r(m_ctx, gdal_wkt); //ABELL - Why should this ever throw? Is it worth catching if // we don't know why? if (!m_geom) throw pdal_error("Unable to create GEOS geometry from OGR WKT!"); OGRFree(gdal_wkt); OGR_G_DestroyGeometry(json); } prepare(); }
/* OGR_G_ExportToWkt(OGRGeometryH, char **) {ok, DataSource} = lgeo_ogr:open("test/polygon.shp"), {ok, Layer} = lgeo_ogr:ds_get_layer(DataSource, 0), {ok, Feature} = lgeo_ogr:l_get_feature(Layer, 0), {ok, Geometry} = lgeo_ogr:f_get_geometry_ref(Feature), {ok, Wkt} = lgeo_ogr:g_export_to_wkt(Geometry). */ static ERL_NIF_TERM g_export_to_wkt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { EnvGeometry_t **geom; ERL_NIF_TERM eterm; if (argc != 1) { return enif_make_badarg(env); } if (!enif_get_resource(env, argv[0], OGR_G_RESOURCE, (void**)&geom)) { return enif_make_badarg(env); } char *wkt = NULL; OGRErr eErr = OGR_G_ExportToWkt((**geom).obj, &wkt); if (eErr != OGRERR_NONE) { return enif_make_tuple2(env, enif_make_atom(env, "error"), enif_make_int(env, eErr)); } eterm = enif_make_string(env, wkt, ERL_NIF_LATIN1); OGRFree(wkt); return enif_make_tuple2(env, enif_make_atom(env, "ok"), eterm); }
void GDALWPrintRecords(GDALWConnection conn) { char * wkt; int i; OGRFeatureH feature; OGRGeometryH geometry; OGRFeatureDefnH featureDefn; featureDefn = OGR_L_GetLayerDefn(conn.layer); OGR_L_ResetReading(conn.layer); while( (feature = OGR_L_GetNextFeature(conn.layer)) != NULL ) { for(i = 0; i < OGR_FD_GetFieldCount(featureDefn); i++ ) { OGRFieldDefnH hFieldDefn = OGR_FD_GetFieldDefn( featureDefn, i ); if( OGR_Fld_GetType(hFieldDefn) == OFTInteger ) printf( "%d,", OGR_F_GetFieldAsInteger( feature, i ) ); else if( OGR_Fld_GetType(hFieldDefn) == OFTReal ) printf( "%.3f,", OGR_F_GetFieldAsDouble( feature, i) ); else printf( "%s,", OGR_F_GetFieldAsString( feature, i) ); } geometry = OGR_F_GetGeometryRef(feature); OGR_G_ExportToWkt(geometry, &wkt); printf("%s", wkt); printf("\n"); CPLFree(wkt); OGR_F_Destroy(feature); } }
std::string wkt() const { char* p_wkt = 0; OGRErr err = OGR_G_ExportToWkt(m_ref.get(), &p_wkt); return std::string(p_wkt); }
int main( int nArgc, char ** papszArgv ) { NITFFile *psFile; int iSegment, iFile; char szTemp[100]; int bDisplayTRE = FALSE; int bExtractSHP = FALSE, bExtractSHPInMem = FALSE; if( nArgc < 2 ) { printf( "Usage: nitfdump [-tre] [-extractshp | -extractshpinmem] <nitf_filename>*\n" ); exit( 1 ); } for( iFile = 1; iFile < nArgc; iFile++ ) { if ( EQUAL(papszArgv[iFile], "-tre") ) bDisplayTRE = TRUE; else if ( EQUAL(papszArgv[iFile], "-extractshp") ) bExtractSHP = TRUE; else if ( EQUAL(papszArgv[iFile], "-extractshpinmem") ) { bExtractSHP = TRUE; bExtractSHPInMem = TRUE; } } /* ==================================================================== */ /* Loop over all files. */ /* ==================================================================== */ for( iFile = 1; iFile < nArgc; iFile++ ) { int bHasFoundLocationTable = FALSE; if ( EQUAL(papszArgv[iFile], "-tre") ) continue; if ( EQUAL(papszArgv[iFile], "-extractshp") ) continue; if ( EQUAL(papszArgv[iFile], "-extractshpinmem") ) continue; /* -------------------------------------------------------------------- */ /* Open the file. */ /* -------------------------------------------------------------------- */ psFile = NITFOpen( papszArgv[iFile], FALSE ); if( psFile == NULL ) exit( 2 ); printf( "Dump for %s\n", papszArgv[iFile] ); /* -------------------------------------------------------------------- */ /* Dump first TRE list. */ /* -------------------------------------------------------------------- */ if( psFile->pachTRE != NULL ) { int nTREBytes = psFile->nTREBytes; const char *pszTREData = psFile->pachTRE; printf( "File TREs:" ); while( nTREBytes > 10 ) { int nThisTRESize = atoi(NITFGetField(szTemp, pszTREData, 6, 5 )); if (nThisTRESize < 0 || nThisTRESize > nTREBytes - 11) { NITFGetField(szTemp, pszTREData, 0, 6 ); printf(" Invalid size (%d) for TRE %s", nThisTRESize, szTemp); break; } printf( " %6.6s(%d)", pszTREData, nThisTRESize ); pszTREData += nThisTRESize + 11; nTREBytes -= (nThisTRESize + 11); } printf( "\n" ); if (bDisplayTRE) { nTREBytes = psFile->nTREBytes; pszTREData = psFile->pachTRE; while( nTREBytes > 10 ) { char *pszEscaped; int nThisTRESize = atoi(NITFGetField(szTemp, pszTREData, 6, 5 )); if (nThisTRESize < 0 || nThisTRESize > nTREBytes - 11) { break; } pszEscaped = CPLEscapeString( pszTREData + 11, nThisTRESize, CPLES_BackslashQuotable ); printf( "TRE '%6.6s' : %s\n", pszTREData, pszEscaped); CPLFree(pszEscaped); pszTREData += nThisTRESize + 11; nTREBytes -= (nThisTRESize + 11); } } } /* -------------------------------------------------------------------- */ /* Dump Metadata */ /* -------------------------------------------------------------------- */ DumpMetadata( "File Metadata:", " ", psFile->papszMetadata ); /* -------------------------------------------------------------------- */ /* Dump general info about segments. */ /* -------------------------------------------------------------------- */ NITFCollectAttachments( psFile ); NITFReconcileAttachments( psFile ); for( iSegment = 0; iSegment < psFile->nSegmentCount; iSegment++ ) { NITFSegmentInfo *psSegInfo = psFile->pasSegmentInfo + iSegment; printf( "Segment %d (Type=%s):\n", iSegment + 1, psSegInfo->szSegmentType ); printf( " HeaderStart=" CPL_FRMT_GUIB ", HeaderSize=%u, DataStart=" CPL_FRMT_GUIB ", DataSize=" CPL_FRMT_GUIB "\n", psSegInfo->nSegmentHeaderStart, psSegInfo->nSegmentHeaderSize, psSegInfo->nSegmentStart, psSegInfo->nSegmentSize ); printf( " DLVL=%d, ALVL=%d, LOC=C%d,R%d, CCS=C%d,R%d\n", psSegInfo->nDLVL, psSegInfo->nALVL, psSegInfo->nLOC_C, psSegInfo->nLOC_R, psSegInfo->nCCS_C, psSegInfo->nCCS_R ); printf( "\n" ); } /* -------------------------------------------------------------------- */ /* Report details of images. */ /* -------------------------------------------------------------------- */ for( iSegment = 0; iSegment < psFile->nSegmentCount; iSegment++ ) { NITFSegmentInfo *psSegInfo = psFile->pasSegmentInfo + iSegment; NITFImage *psImage; NITFRPC00BInfo sRPCInfo; int iBand; char **papszMD; if( !EQUAL(psSegInfo->szSegmentType,"IM") ) continue; psImage = NITFImageAccess( psFile, iSegment ); if( psImage == NULL ) { printf( "NITFAccessImage(%d) failed!\n", iSegment ); continue; } printf( "Image Segment %d, %dPx%dLx%dB x %dbits:\n", iSegment + 1, psImage->nCols, psImage->nRows, psImage->nBands, psImage->nBitsPerSample ); printf( " PVTYPE=%s, IREP=%s, ICAT=%s, IMODE=%c, IC=%s, COMRAT=%s, ICORDS=%c\n", psImage->szPVType, psImage->szIREP, psImage->szICAT, psImage->chIMODE, psImage->szIC, psImage->szCOMRAT, psImage->chICORDS ); if( psImage->chICORDS != ' ' ) { printf( " UL=(%.15g,%.15g), UR=(%.15g,%.15g) Center=%d\n LL=(%.15g,%.15g), LR=(%.15g,%.15g)\n", psImage->dfULX, psImage->dfULY, psImage->dfURX, psImage->dfURY, psImage->bIsBoxCenterOfPixel, psImage->dfLLX, psImage->dfLLY, psImage->dfLRX, psImage->dfLRY ); } printf( " IDLVL=%d, IALVL=%d, ILOC R=%d,C=%d, IMAG=%s\n", psImage->nIDLVL, psImage->nIALVL, psImage->nILOCRow, psImage->nILOCColumn, psImage->szIMAG ); printf( " %d x %d blocks of size %d x %d\n", psImage->nBlocksPerRow, psImage->nBlocksPerColumn, psImage->nBlockWidth, psImage->nBlockHeight ); if( psImage->pachTRE != NULL ) { int nTREBytes = psImage->nTREBytes; const char *pszTREData = psImage->pachTRE; printf( " Image TREs:" ); while( nTREBytes > 10 ) { int nThisTRESize = atoi(NITFGetField(szTemp, pszTREData, 6, 5 )); if (nThisTRESize < 0 || nThisTRESize > nTREBytes - 11) { NITFGetField(szTemp, pszTREData, 0, 6 ); printf(" Invalid size (%d) for TRE %s", nThisTRESize, szTemp); break; } printf( " %6.6s(%d)", pszTREData, nThisTRESize ); pszTREData += nThisTRESize + 11; nTREBytes -= (nThisTRESize + 11); } printf( "\n" ); if (bDisplayTRE) { nTREBytes = psImage->nTREBytes; pszTREData = psImage->pachTRE; while( nTREBytes > 10 ) { char *pszEscaped; int nThisTRESize = atoi(NITFGetField(szTemp, pszTREData, 6, 5 )); if (nThisTRESize < 0 || nThisTRESize > nTREBytes - 11) { break; } pszEscaped = CPLEscapeString( pszTREData + 11, nThisTRESize, CPLES_BackslashQuotable ); printf( " TRE '%6.6s' : %s\n", pszTREData, pszEscaped); CPLFree(pszEscaped); pszTREData += nThisTRESize + 11; nTREBytes -= (nThisTRESize + 11); } } } /* Report info from location table, if found. */ if( psImage->nLocCount > 0 ) { int i; bHasFoundLocationTable = TRUE; printf( " Location Table\n" ); for( i = 0; i < psImage->nLocCount; i++ ) { printf( " LocName=%s, LocId=%d, Offset=%d, Size=%d\n", GetLocationNameFromId(psImage->pasLocations[i].nLocId), psImage->pasLocations[i].nLocId, psImage->pasLocations[i].nLocOffset, psImage->pasLocations[i].nLocSize ); } printf( "\n" ); } if( strlen(psImage->pszComments) > 0 ) printf( " Comments:\n%s\n", psImage->pszComments ); for( iBand = 0; iBand < psImage->nBands; iBand++ ) { NITFBandInfo *psBandInfo = psImage->pasBandInfo + iBand; printf( " Band %d: IREPBAND=%s, ISUBCAT=%s, %d LUT entries.\n", iBand + 1, psBandInfo->szIREPBAND, psBandInfo->szISUBCAT, psBandInfo->nSignificantLUTEntries ); } if( NITFReadRPC00B( psImage, &sRPCInfo ) ) { DumpRPC( psImage, &sRPCInfo ); } papszMD = NITFReadUSE00A( psImage ); if( papszMD != NULL ) { DumpMetadata( " USE00A TRE:", " ", papszMD ); CSLDestroy( papszMD ); } papszMD = NITFReadBLOCKA( psImage ); if( papszMD != NULL ) { DumpMetadata( " BLOCKA TRE:", " ", papszMD ); CSLDestroy( papszMD ); } papszMD = NITFReadSTDIDC( psImage ); if( papszMD != NULL ) { DumpMetadata( " STDIDC TRE:", " ", papszMD ); CSLDestroy( papszMD ); } DumpMetadata( " Image Metadata:", " ", psImage->papszMetadata ); printf("\n"); } /* ==================================================================== */ /* Report details of graphic segments. */ /* ==================================================================== */ for( iSegment = 0; iSegment < psFile->nSegmentCount; iSegment++ ) { NITFSegmentInfo *psSegInfo = psFile->pasSegmentInfo + iSegment; char achSubheader[298]; int nSTYPEOffset; if( !EQUAL(psSegInfo->szSegmentType,"GR") && !EQUAL(psSegInfo->szSegmentType,"SY") ) continue; /* -------------------------------------------------------------------- */ /* Load the graphic subheader. */ /* -------------------------------------------------------------------- */ if( VSIFSeekL( psFile->fp, psSegInfo->nSegmentHeaderStart, SEEK_SET ) != 0 || VSIFReadL( achSubheader, 1, sizeof(achSubheader), psFile->fp ) < 258 ) { CPLError( CE_Warning, CPLE_FileIO, "Failed to read graphic subheader at " CPL_FRMT_GUIB ".", psSegInfo->nSegmentHeaderStart ); continue; } // NITF 2.0. (also works for NITF 2.1) nSTYPEOffset = 200; if( STARTS_WITH_CI(achSubheader+193, "999998") ) nSTYPEOffset += 40; /* -------------------------------------------------------------------- */ /* Report some standard info. */ /* -------------------------------------------------------------------- */ printf( "Graphic Segment %d, type=%2.2s, sfmt=%c, sid=%10.10s\n", iSegment + 1, achSubheader + 0, achSubheader[nSTYPEOffset], achSubheader + 2 ); printf( " sname=%20.20s\n", achSubheader + 12 ); printf("\n"); } /* ==================================================================== */ /* Report details of text segments. */ /* ==================================================================== */ for( iSegment = 0; iSegment < psFile->nSegmentCount; iSegment++ ) { char *pabyHeaderData; char *pabyTextData; NITFSegmentInfo *psSegment = psFile->pasSegmentInfo + iSegment; if( !EQUAL(psSegment->szSegmentType,"TX") ) continue; printf( "Text Segment %d\n", iSegment + 1); /* -------------------------------------------------------------------- */ /* Load the text header */ /* -------------------------------------------------------------------- */ /* Allocate one extra byte for the NULL terminating character */ pabyHeaderData = (char *) CPLCalloc(1, (size_t) psSegment->nSegmentHeaderSize + 1); if (VSIFSeekL(psFile->fp, psSegment->nSegmentHeaderStart, SEEK_SET) != 0 || VSIFReadL(pabyHeaderData, 1, (size_t) psSegment->nSegmentHeaderSize, psFile->fp) != psSegment->nSegmentHeaderSize) { CPLError( CE_Warning, CPLE_FileIO, "Failed to read %d bytes of text header data at " CPL_FRMT_GUIB ".", psSegment->nSegmentHeaderSize, psSegment->nSegmentHeaderStart); CPLFree(pabyHeaderData); continue; } printf(" Header : %s\n", pabyHeaderData); CPLFree(pabyHeaderData); /* -------------------------------------------------------------------- */ /* Load the raw TEXT data itself. */ /* -------------------------------------------------------------------- */ /* Allocate one extra byte for the NULL terminating character */ pabyTextData = (char *) CPLCalloc(1,(size_t)psSegment->nSegmentSize+1); if( VSIFSeekL( psFile->fp, psSegment->nSegmentStart, SEEK_SET ) != 0 || VSIFReadL( pabyTextData, 1, (size_t)psSegment->nSegmentSize, psFile->fp ) != psSegment->nSegmentSize ) { CPLError( CE_Warning, CPLE_FileIO, "Failed to read " CPL_FRMT_GUIB " bytes of text data at " CPL_FRMT_GUIB ".", psSegment->nSegmentSize, psSegment->nSegmentStart ); CPLFree( pabyTextData ); continue; } printf(" Data : %s\n", pabyTextData); printf("\n"); CPLFree( pabyTextData ); } /* -------------------------------------------------------------------- */ /* Report details of DES. */ /* -------------------------------------------------------------------- */ for( iSegment = 0; iSegment < psFile->nSegmentCount; iSegment++ ) { NITFSegmentInfo *psSegInfo = psFile->pasSegmentInfo + iSegment; NITFDES *psDES; int nOffset = 0; char szTREName[7]; int nThisTRESize; int nRPFDESOffset = -1; if( !EQUAL(psSegInfo->szSegmentType,"DE") ) continue; psDES = NITFDESAccess( psFile, iSegment ); if( psDES == NULL ) { printf( "NITFDESAccess(%d) failed!\n", iSegment ); continue; } printf( "DE Segment %d:\n", iSegment + 1 ); printf( " Segment TREs:" ); nOffset = 0; while (NITFDESGetTRE( psDES, nOffset, szTREName, NULL, &nThisTRESize)) { printf( " %6.6s(%d)", szTREName, nThisTRESize ); if (strcmp(szTREName, "RPFDES") == 0) nRPFDESOffset = nOffset + 11; nOffset += 11 + nThisTRESize; } printf( "\n" ); if (bDisplayTRE) { char* pabyTREData = NULL; nOffset = 0; while (NITFDESGetTRE( psDES, nOffset, szTREName, &pabyTREData, &nThisTRESize)) { char* pszEscaped = CPLEscapeString( pabyTREData, nThisTRESize, CPLES_BackslashQuotable ); printf( " TRE '%6.6s' : %s\n", szTREName, pszEscaped); CPLFree(pszEscaped); nOffset += 11 + nThisTRESize; NITFDESFreeTREData(pabyTREData); } } /* Report info from location table, if found. */ if( !bHasFoundLocationTable && nRPFDESOffset >= 0 ) { int i; int nLocCount = 0; NITFLocation* pasLocations; VSIFSeekL(psFile->fp, psSegInfo->nSegmentStart + nRPFDESOffset, SEEK_SET); pasLocations = NITFReadRPFLocationTable(psFile->fp, &nLocCount); if (pasLocations) { printf( " Location Table\n" ); for( i = 0; i < nLocCount; i++ ) { printf( " LocName=%s, LocId=%d, Offset=%d, Size=%d\n", GetLocationNameFromId(pasLocations[i].nLocId), pasLocations[i].nLocId, pasLocations[i].nLocOffset, pasLocations[i].nLocSize ); } CPLFree(pasLocations); printf( "\n" ); } } DumpMetadata( " DES Metadata:", " ", psDES->papszMetadata ); if ( bExtractSHP && CSLFetchNameValue(psDES->papszMetadata, "NITF_SHAPE_USE") != NULL ) { char szFilename[32]; char szRadix[32]; if (bExtractSHPInMem) snprintf(szRadix, sizeof(szRadix), "/vsimem/nitf_segment_%d", iSegment + 1); else snprintf(szRadix, sizeof(szRadix), "nitf_segment_%d", iSegment + 1); if (NITFDESExtractShapefile(psDES, szRadix)) { OGRDataSourceH hDS; OGRRegisterAll(); snprintf(szFilename, sizeof(szFilename), "%s.SHP", szRadix); hDS = OGROpen(szFilename, FALSE, NULL); if (hDS) { int nGeom = 0; OGRLayerH hLayer = OGR_DS_GetLayer(hDS, 0); if (hLayer) { OGRFeatureH hFeat; printf("\n"); while ( (hFeat = OGR_L_GetNextFeature(hLayer)) != NULL ) { OGRGeometryH hGeom = OGR_F_GetGeometryRef(hFeat); if (hGeom) { char* pszWKT = NULL; OGR_G_ExportToWkt(hGeom, &pszWKT); if (pszWKT) printf(" Geometry %d : %s\n", nGeom ++, pszWKT); CPLFree(pszWKT); } OGR_F_Destroy(hFeat); } } OGR_DS_Destroy(hDS); } } if (bExtractSHPInMem) { snprintf(szFilename, sizeof(szFilename), "%s.SHP", szRadix); VSIUnlink(szFilename); snprintf(szFilename, sizeof(szFilename), "%s.SHX", szRadix); VSIUnlink(szFilename); snprintf(szFilename, sizeof(szFilename), "%s.DBF", szRadix); VSIUnlink(szFilename); } } } /* -------------------------------------------------------------------- */ /* Close. */ /* -------------------------------------------------------------------- */ NITFClose( psFile ); } CPLFinderClean(); CPLCleanupTLS(); VSICleanupFileManager(); OGRCleanupAll(); exit( 0 ); }
bool QgsShapeFile::insertLayer( QString dbname, QString schema, QString primary_key, QString geom_col, QString srid, PGconn * conn, QProgressDialog& pro, bool &fin, QString& errorText ) { connect( &pro, SIGNAL( canceled() ), this, SLOT( cancelImport() ) ); import_canceled = false; bool result = true; QString query = QString( "CREATE TABLE %1.%2(%3 int4 PRIMARY KEY" ) .arg( QgsPgUtil::quotedIdentifier( schema ) ) .arg( QgsPgUtil::quotedIdentifier( table_name ) ) .arg( QgsPgUtil::quotedIdentifier( primary_key ) ); for ( uint n = 0; n < column_names.size() && result; n++ ) { query += QString( ",%1 %2" ) .arg( QgsPgUtil::quotedIdentifier( column_names[n] ) ) .arg( column_types[n] ); } query += " )"; QgsDebugMsg( "Query string is: " + query ); PGresult *res = PQexec( conn, query.toUtf8() ); if ( PQresultStatus( res ) != PGRES_COMMAND_OK ) { // flag error and send query and error message to stdout on debug errorText += tr( "The database gave an error while executing this SQL:" ) + "\n"; errorText += query + '\n'; errorText += tr( "The error was:" ) + "\n"; errorText += PQresultErrorMessage( res ) + '\n'; PQclear( res ); return false; } else { PQclear( res ); } query = QString( "SELECT AddGeometryColumn(%1,%2,%3,%4,%5,2)" ) .arg( QgsPgUtil::quotedValue( schema ) ) .arg( QgsPgUtil::quotedValue( table_name ) ) .arg( QgsPgUtil::quotedValue( geom_col ) ) .arg( srid ) .arg( QgsPgUtil::quotedValue( geom_type ) ); res = PQexec( conn, query.toUtf8() ); if ( PQresultStatus( res ) != PGRES_TUPLES_OK ) { errorText += tr( "The database gave an error while executing this SQL:" ) + "\n"; errorText += query + '\n'; errorText += tr( "The error was:" ) + "\n"; errorText += PQresultErrorMessage( res ) + '\n'; PQclear( res ); return false; } else { PQclear( res ); } if ( isMulti ) { query = QString( "select constraint_name from information_schema.table_constraints where table_schema=%1 and table_name=%2 and constraint_name in ('$2','enforce_geotype_the_geom')" ) .arg( QgsPgUtil::quotedValue( schema ) ) .arg( QgsPgUtil::quotedValue( table_name ) ); QStringList constraints; res = PQexec( conn, query.toUtf8() ); if ( PQresultStatus( res ) == PGRES_TUPLES_OK ) { for ( int i = 0; i < PQntuples( res ); i++ ) constraints.append( PQgetvalue( res, i, 0 ) ); } PQclear( res ); if ( constraints.size() > 0 ) { // drop the check constraint // TODO This whole concept needs to be changed to either // convert the geometries to the same type or allow // multiple types in the check constraint. For now, we // just drop the constraint... query = QString( "alter table %1 drop constraint %2" ) .arg( QgsPgUtil::quotedIdentifier( table_name ) ) .arg( QgsPgUtil::quotedIdentifier( constraints[0] ) ); res = PQexec( conn, query.toUtf8() ); if ( PQresultStatus( res ) != PGRES_COMMAND_OK ) { errorText += tr( "The database gave an error while executing this SQL:" ) + "\n"; errorText += query + '\n'; errorText += tr( "The error was:" ) + "\n"; errorText += PQresultErrorMessage( res ) + '\n'; PQclear( res ); return false; } PQclear( res ); } } //adding the data into the table for ( int m = 0; m < features && result; m++ ) { if ( import_canceled ) { fin = true; break; } OGRFeatureH feat = OGR_L_GetNextFeature( ogrLayer ); if ( feat ) { OGRGeometryH geom = OGR_F_GetGeometryRef( feat ); if ( geom ) { query = QString( "INSERT INTO %1.%2 VALUES(%3" ) .arg( QgsPgUtil::quotedIdentifier( schema ) ) .arg( QgsPgUtil::quotedIdentifier( table_name ) ) .arg( m ); char *geo_temp; // 'GeometryFromText' supports only 2D coordinates // TODO for proper 2.5D support we would need to use 'GeomFromEWkt' if ( hasMoreDimensions ) OGR_G_SetCoordinateDimension( geom, 2 ); OGR_G_ExportToWkt( geom, &geo_temp ); QString geometry( geo_temp ); CPLFree( geo_temp ); for ( uint n = 0; n < column_types.size(); n++ ) { QString val; // FIXME: OGR_F_GetFieldAsString returns junk when called with a 8.255 float field if ( column_types[n] == "float" ) val = QString::number( OGR_F_GetFieldAsDouble( feat, n ) ); else val = codec->toUnicode( OGR_F_GetFieldAsString( feat, n ) ); if ( val.isEmpty() ) val = "NULL"; else val = QgsPgUtil::quotedValue( val ); query += "," + val; } query += QString( ",GeometryFromText(%1,%2))" ) .arg( QgsPgUtil::quotedValue( geometry ) ) .arg( srid ); if ( result ) res = PQexec( conn, query.toUtf8() ); if ( PQresultStatus( res ) != PGRES_COMMAND_OK ) { // flag error and send query and error message to stdout on debug result = false; errorText += tr( "The database gave an error while executing this SQL:" ) + "\n"; // the query string can be quite long. Trim if necessary... if ( query.count() > 100 ) errorText += query.left( 150 ) + tr( "... (rest of SQL trimmed)", "is appended to a truncated SQL statement" ) + "\n"; else errorText += query + '\n'; errorText += tr( "The error was:" ) + "\n"; errorText += PQresultErrorMessage( res ); errorText += '\n'; } else { PQclear( res ); } pro.setValue( pro.value() + 1 ); qApp->processEvents(); } OGR_F_Destroy( feat ); } } // create the GIST index if the the load was successful if ( result ) { // prompt user to see if they want to build the index and warn // them about the potential time-cost } OGR_L_ResetReading( ogrLayer ); return result; }
int main(int argc, const char **argv) { /* initialize apr_getopt_t */ apr_getopt_t *opt; const char *configfile=NULL; #ifndef USE_FORK apr_thread_t **threads; apr_threadattr_t *thread_attrs; #endif const char *tileset_name=NULL; const char *tileset_transfer_name=NULL; const char *grid_name = NULL; int *zooms = NULL;//[2]; double *extent = NULL;//[4]; int optch; int rv,n; const char *old = NULL; const char *optarg; apr_table_t *argdimensions; char *dimkey=NULL, *dimvalue=NULL,*key, *last, *optargcpy=NULL; int keyidx; int *metasizes = NULL;//[2]; int metax=-1,metay=-1; #ifdef USE_CLIPPERS const char *ogr_where = NULL; const char *ogr_layer = NULL; const char *ogr_sql = NULL; const char *ogr_datasource = NULL; #endif apr_initialize(); (void) signal(SIGINT,handle_sig_int); apr_pool_create(&ctx.pool,NULL); mapcache_context_init(&ctx); ctx.process_pool = ctx.pool; #ifndef USE_FORK apr_thread_mutex_create((apr_thread_mutex_t**)&ctx.threadlock,APR_THREAD_MUTEX_DEFAULT,ctx.pool); #else ctx.threadlock = NULL; #endif cfg = mapcache_configuration_create(ctx.pool); ctx.config = cfg; ctx.log= mapcache_context_seeding_log; apr_getopt_init(&opt, ctx.pool, argc, argv); seededtiles=seededtilestot=queuedtilestot=0; mapcache_gettimeofday(&starttime,NULL); lastlogtime=starttime; argdimensions = apr_table_make(ctx.pool,3); /* parse the all options based on opt_option[] */ while ((rv = apr_getopt_long(opt, seed_options, &optch, &optarg)) == APR_SUCCESS) { switch (optch) { case 'h': return usage(argv[0],NULL); break; case 'f': force = 1; break; case 'q': quiet = 1; break; case 'v': verbose = 1; break; case 'c': configfile = optarg; break; case 'g': grid_name = optarg; break; case 't': tileset_name = optarg; break; case 'x': tileset_transfer_name = optarg; break; case 'm': if(!strcmp(optarg,"delete")) { mode = MAPCACHE_CMD_DELETE; } else if(!strcmp(optarg,"transfer")){ mode = MAPCACHE_CMD_TRANSFER; } else if(strcmp(optarg,"seed")){ return usage(argv[0],"invalid mode, expecting \"seed\", \"delete\" or \"transfer\""); } else { mode = MAPCACHE_CMD_SEED; } break; case 'n': nthreads = (int)strtol(optarg, NULL, 10); break; case 'e': if ( MAPCACHE_SUCCESS != mapcache_util_extract_double_list(&ctx, (char*)optarg, ",", &extent, &n) || n != 4 || extent[0] >= extent[2] || extent[1] >= extent[3] ) { return usage(argv[0], "failed to parse extent, expecting comma separated 4 doubles"); } break; case 'z': if ( MAPCACHE_SUCCESS != mapcache_util_extract_int_list(&ctx, (char*)optarg, ",", &zooms, &n) || n != 2 || zooms[0] > zooms[1]) { return usage(argv[0], "failed to parse zooms, expecting comma separated 2 ints"); } else { minzoom = zooms[0]; maxzoom = zooms[1]; } break; case 'M': if ( MAPCACHE_SUCCESS != mapcache_util_extract_int_list(&ctx, (char*)optarg, ",", &metasizes, &n) || n != 2 || metasizes[0] <= 0 || metasizes[1] <=0) { return usage(argv[0], "failed to parse metasize, expecting comma separated 2 positive ints (e.g. -M 8,8"); } else { metax = metasizes[0]; metay = metasizes[1]; } break; case 'o': old = optarg; break; case 'D': optargcpy = apr_pstrdup(ctx.pool,optarg); keyidx = 0; for (key = apr_strtok(optargcpy, "=", &last); key != NULL; key = apr_strtok(NULL, "=", &last)) { if(keyidx == 0) { dimkey = key; } else { dimvalue = key; } keyidx++; } if(keyidx!=2 || !dimkey || !dimvalue || !*dimkey || !*dimvalue) { return usage(argv[0], "failed to parse dimension, expecting DIMNAME=DIMVALUE"); } apr_table_set(argdimensions,dimkey,dimvalue); break; #ifdef USE_CLIPPERS case 'd': ogr_datasource = optarg; break; case 's': ogr_sql = optarg; break; case 'l': ogr_layer = optarg; break; case 'w': ogr_where = optarg; break; #endif } } if (rv != APR_EOF) { return usage(argv[0],"bad options"); } if( ! configfile ) { return usage(argv[0],"config not specified"); } else { mapcache_configuration_parse(&ctx,configfile,cfg,0); if(ctx.get_error(&ctx)) return usage(argv[0],ctx.get_error_message(&ctx)); mapcache_configuration_post_config(&ctx,cfg); if(ctx.get_error(&ctx)) return usage(argv[0],ctx.get_error_message(&ctx)); } #ifdef USE_CLIPPERS if(extent && ogr_datasource) { return usage(argv[0], "cannot specify both extent and ogr-datasource"); } if( ogr_sql && ( ogr_where || ogr_layer )) { return usage(argv[0], "ogr-where or ogr_layer cannot be used in conjunction with ogr-sql"); } if(ogr_datasource) { OGRDataSourceH hDS = NULL; OGRLayerH layer = NULL; OGRRegisterAll(); hDS = OGROpen( ogr_datasource, FALSE, NULL ); if( hDS == NULL ) { printf( "OGR Open failed\n" ); exit( 1 ); } if(ogr_sql) { layer = OGR_DS_ExecuteSQL( hDS, ogr_sql, NULL, NULL); if(!layer) { return usage(argv[0],"aborting"); } } else { int nLayers = OGR_DS_GetLayerCount(hDS); if(nLayers>1 && !ogr_layer) { return usage(argv[0],"ogr datastore contains more than one layer. please specify which one to use with --ogr-layer"); } else { if(ogr_layer) { layer = OGR_DS_GetLayerByName(hDS,ogr_layer); } else { layer = OGR_DS_GetLayer(hDS,0); } if(!layer) { return usage(argv[0],"aborting"); } if(ogr_where) { if(OGRERR_NONE != OGR_L_SetAttributeFilter(layer, ogr_where)) { return usage(argv[0],"aborting"); } } } } if((nClippers=OGR_L_GetFeatureCount(layer, TRUE)) == 0) { return usage(argv[0],"no features in provided ogr parameters, cannot continue"); } initGEOS(notice, log_and_exit); clippers = (const GEOSPreparedGeometry**)malloc(nClippers*sizeof(GEOSPreparedGeometry*)); OGRFeatureH hFeature; GEOSWKTReader *geoswktreader = GEOSWKTReader_create(); OGR_L_ResetReading(layer); extent = apr_pcalloc(ctx.pool,4*sizeof(double)); int f=0; while( (hFeature = OGR_L_GetNextFeature(layer)) != NULL ) { OGRGeometryH geom = OGR_F_GetGeometryRef(hFeature); if(!geom || !OGR_G_IsValid(geom)) continue; char *wkt; OGR_G_ExportToWkt(geom,&wkt); GEOSGeometry *geosgeom = GEOSWKTReader_read(geoswktreader,wkt); free(wkt); clippers[f] = GEOSPrepare(geosgeom); //GEOSGeom_destroy(geosgeom); OGREnvelope ogr_extent; OGR_G_GetEnvelope (geom, &ogr_extent); if(f == 0) { extent[0] = ogr_extent.MinX; extent[1] = ogr_extent.MinY; extent[2] = ogr_extent.MaxX; extent[3] = ogr_extent.MaxY; } else { extent[0] = MAPCACHE_MIN(ogr_extent.MinX, extent[0]); extent[1] = MAPCACHE_MIN(ogr_extent.MinY, extent[1]); extent[2] = MAPCACHE_MAX(ogr_extent.MaxX, extent[2]); extent[3] = MAPCACHE_MAX(ogr_extent.MaxY, extent[3]); } OGR_F_Destroy( hFeature ); f++; } nClippers = f; } #endif if( ! tileset_name ) { return usage(argv[0],"tileset not specified"); } else { tileset = mapcache_configuration_get_tileset(cfg,tileset_name); if(!tileset) { return usage(argv[0], "tileset not found in configuration"); } if( ! grid_name ) { grid_link = APR_ARRAY_IDX(tileset->grid_links,0,mapcache_grid_link*); } else {