source: trunk/zoo-services/ogr/ogr2ogr/service.c @ 1

Last change on this file since 1 was 1, checked in by djay, 14 years ago

Initial ZOO SVN Repository Import.

File size: 40.5 KB
Line 
1/******************************************************************************
2 * $Id: ogr2ogr.cpp 15473 2008-10-07 20:59:24Z warmerdam $
3 *
4 * Project:  OpenGIS Simple Features Reference Implementation
5 * Purpose:  Simple client for translating between formats.
6 * Author:   Frank Warmerdam, warmerdam@pobox.com
7 *
8 ******************************************************************************
9 * Copyright (c) 1999, Frank Warmerdam
10 *
11 * Permission is hereby granted, free of charge, to any person obtaining a
12 * copy of this software and associated documentation files (the "Software"),
13 * to deal in the Software without restriction, including without limitation
14 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
15 * and/or sell copies of the Software, and to permit persons to whom the
16 * Software is furnished to do so, subject to the following conditions:
17 *
18 * The above copyright notice and this permission notice shall be included
19 * in all copies or substantial portions of the Software.
20 *
21 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
22 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
24 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
26 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
27 * DEALINGS IN THE SOFTWARE.
28 ****************************************************************************/
29
30#include "ogrsf_frmts.h"
31#include "ogr_p.h"
32#include "cpl_conv.h"
33#include "cpl_string.h"
34#include "ogr_api.h"
35#ifdef ZOO_SERVICE
36#include "service.h"
37#endif
38
39CPL_CVSID("$Id: ogr2ogr.cpp 15473 2008-10-07 20:59:24Z warmerdam $");
40
41#ifdef ZOO_SERVICE
42extern "C" {
43#endif
44
45static void Usage();
46
47static int TranslateLayer( OGRDataSource *poSrcDS, 
48                           OGRLayer * poSrcLayer,
49                           OGRDataSource *poDstDS,
50                           char ** papszLSCO,
51                           const char *pszNewLayerName,
52                           int bTransform, 
53                           OGRSpatialReference *poOutputSRS,
54                           OGRSpatialReference *poSourceSRS,
55                           char **papszSelFields,
56                           int bAppend, int eGType,
57                           int bOverwrite,
58                           double dfMaxSegmentLength);
59
60static int bSkipFailures = FALSE;
61static int nGroupTransactions = 200;
62static int bPreserveFID = FALSE;
63static int nFIDToFetch = OGRNullFID;
64
65/************************************************************************/
66/*                                main()                                */
67/************************************************************************/
68
69#ifdef ZOO_SERVICE
70#ifdef WIN32
71__declspec(dllexport)
72#endif
73int Ogr2Ogr(maps*& conf,maps*& inputs,maps*& outputs)
74#else
75int main( int nArgc, char ** papszArgv )
76#endif
77{
78    const char  *pszFormat = "ESRI Shapefile";
79    const char  *pszDataSource = NULL;
80    const char  *pszDestDataSource = NULL;
81    char        **papszLayers = NULL;
82    char        **papszDSCO = NULL, **papszLCO = NULL;
83    int         bTransform = FALSE;
84    int         bAppend = FALSE, bUpdate = FALSE, bOverwrite = FALSE;
85    const char  *pszOutputSRSDef = NULL;
86    const char  *pszSourceSRSDef = NULL;
87    OGRSpatialReference *poOutputSRS = NULL;
88    OGRSpatialReference *poSourceSRS = NULL;
89    const char  *pszNewLayerName = NULL;
90    const char  *pszWHERE = NULL;
91    OGRGeometry *poSpatialFilter = NULL;
92    const char  *pszSelect;
93    char        **papszSelFields = NULL;
94    const char  *pszSQLStatement = NULL;
95    int         eGType = -2;
96    double       dfMaxSegmentLength = 0;
97
98    /* Check strict compilation and runtime library version as we use C++ API */
99    if (! GDAL_CHECK_VERSION("ogr2ogr"))
100#ifdef ZOO_SERVICE
101        {
102                fprintf(stderr,"Not correct version of the gdal library\n");
103                return SERVICE_FAILED;
104        }
105#else
106        exit(1);
107#endif
108/* -------------------------------------------------------------------- */
109/*      Register format(s).                                             */
110/* -------------------------------------------------------------------- */
111    OGRRegisterAll();
112
113#ifdef ZOO_SERVICE
114        map *tmpMap=NULL;
115    char dataPath[1024];
116    tmpMap=getMapFromMaps(conf,"main","dataPath");
117    if(tmpMap!=NULL)
118      sprintf(dataPath,"%s",tmpMap->value);
119    tmpMap=NULL;
120    char tempPath[1024];
121    tmpMap=getMapFromMaps(conf,"main","tmpPath");
122    if(tmpMap!=NULL){
123      sprintf(tempPath,"%s",tmpMap->value);
124    }
125
126        tmpMap=NULL;
127    tmpMap=getMapFromMaps(inputs,"F","value");
128    if(tmpMap!=NULL){
129      pszFormat=tmpMap->value;
130    }
131
132        tmpMap=NULL;
133    tmpMap=getMapFromMaps(inputs,"DSCO","value");
134    if(tmpMap!=NULL){
135          papszDSCO = CSLAddString(papszDSCO, tmpMap->value );
136    }
137
138        tmpMap=NULL;
139    tmpMap=getMapFromMaps(inputs,"LCO","value");
140    if(tmpMap!=NULL){
141          papszLCO = CSLAddString(papszLCO, tmpMap->value );
142    }
143
144        tmpMap=NULL;
145    tmpMap=getMapFromMaps(inputs,"LCO","value");
146    if(tmpMap!=NULL){
147          papszLCO = CSLAddString(papszLCO, tmpMap->value );
148    }
149
150        tmpMap=NULL;
151    tmpMap=getMapFromMaps(inputs,"preserve_fid","value");
152    if(tmpMap!=NULL){
153          bPreserveFID = TRUE;
154    }
155
156        tmpMap=NULL;
157    tmpMap=getMapFromMaps(inputs,"skipfailure","value");
158    if(tmpMap!=NULL){
159          bPreserveFID = TRUE;
160          bSkipFailures = TRUE;
161          nGroupTransactions = 1; /* #2409 */
162        }
163
164        tmpMap=NULL;
165    tmpMap=getMapFromMaps(inputs,"append","value");
166    if(tmpMap!=NULL){
167          bAppend = TRUE;
168        }
169
170        tmpMap=NULL;
171    tmpMap=getMapFromMaps(inputs,"overwrite","value");
172    if(tmpMap!=NULL){
173          bOverwrite = TRUE;
174        }
175
176        tmpMap=NULL;
177    tmpMap=getMapFromMaps(inputs,"update","value");
178    if(tmpMap!=NULL){
179          bUpdate = TRUE;
180        }
181
182        tmpMap=NULL;
183    tmpMap=getMapFromMaps(inputs,"fid","value");
184    if(tmpMap!=NULL){
185          nFIDToFetch = atoi(tmpMap->value);
186        }
187
188        tmpMap=NULL;
189    tmpMap=getMapFromMaps(inputs,"sql","value");
190    if(tmpMap!=NULL){
191          pszSQLStatement = tmpMap->value;
192        }
193
194        tmpMap=NULL;
195    tmpMap=getMapFromMaps(inputs,"nln","value");
196    if(tmpMap!=NULL){
197          pszNewLayerName = tmpMap->value;
198        }
199
200        tmpMap=NULL;
201    tmpMap=getMapFromMaps(inputs,"nlt","value");
202    if(tmpMap!=NULL){
203          pszNewLayerName = tmpMap->value;
204          if( EQUAL(tmpMap->value,"NONE") )
205                  eGType = wkbNone;
206          else if( EQUAL(tmpMap->value,"GEOMETRY") )
207                  eGType = wkbUnknown;
208          else if( EQUAL(tmpMap->value,"POINT") )
209                  eGType = wkbPoint;
210          else if( EQUAL(tmpMap->value,"LINESTRING") )
211                  eGType = wkbLineString;
212          else if( EQUAL(tmpMap->value,"POLYGON") )
213                  eGType = wkbPolygon;
214          else if( EQUAL(tmpMap->value,"GEOMETRYCOLLECTION") )
215                  eGType = wkbGeometryCollection;
216          else if( EQUAL(tmpMap->value,"MULTIPOINT") )
217                  eGType = wkbMultiPoint;
218          else if( EQUAL(tmpMap->value,"MULTILINESTRING") )
219                  eGType = wkbMultiLineString;
220          else if( EQUAL(tmpMap->value,"MULTIPOLYGON") )
221                  eGType = wkbMultiPolygon;
222          else if( EQUAL(tmpMap->value,"GEOMETRY25D") )
223                  eGType = wkbUnknown | wkb25DBit;
224          else if( EQUAL(tmpMap->value,"POINT25D") )
225                  eGType = wkbPoint25D;
226          else if( EQUAL(tmpMap->value,"LINESTRING25D") )
227                  eGType = wkbLineString25D;
228          else if( EQUAL(tmpMap->value,"POLYGON25D") )
229                  eGType = wkbPolygon25D;
230          else if( EQUAL(tmpMap->value,"GEOMETRYCOLLECTION25D") )
231                  eGType = wkbGeometryCollection25D;
232          else if( EQUAL(tmpMap->value,"MULTIPOINT25D") )
233                  eGType = wkbMultiPoint25D;
234          else if( EQUAL(tmpMap->value,"MULTILINESTRING25D") )
235                  eGType = wkbMultiLineString25D;
236          else if( EQUAL(tmpMap->value,"MULTIPOLYGON25D") )
237                  eGType = wkbMultiPolygon25D;
238          else   
239          {
240                  fprintf( stderr, "-nlt %s: type not recognised.\n", 
241                          tmpMap->value );
242                  exit( 1 );
243          }
244        }
245
246        tmpMap=NULL;
247    tmpMap=getMapFromMaps(inputs,"tg","value");
248    if(tmpMap!=NULL){
249          nGroupTransactions = atoi(tmpMap->value);
250        }
251
252        tmpMap=NULL;
253    tmpMap=getMapFromMaps(inputs,"s_srs","value");
254    if(tmpMap!=NULL){
255          pszSourceSRSDef = tmpMap->value;
256        }
257
258        tmpMap=NULL;
259    tmpMap=getMapFromMaps(inputs,"s_srs","value");
260    if(tmpMap!=NULL){
261          pszSourceSRSDef = tmpMap->value;
262        }
263
264        tmpMap=NULL;
265    tmpMap=getMapFromMaps(inputs,"a_srs","value");
266    if(tmpMap!=NULL){
267          pszOutputSRSDef = tmpMap->value;
268        }
269
270        tmpMap=NULL;
271    tmpMap=getMapFromMaps(inputs,"t_srs","value");
272    if(tmpMap!=NULL){
273          pszOutputSRSDef = tmpMap->value;
274          bTransform = TRUE;
275        }
276
277        tmpMap=NULL;
278    tmpMap=getMapFromMaps(inputs,"SPAT","value");
279    if(tmpMap!=NULL){
280      char *tmp=tmpMap->value;
281      char *t=strtok(tmp,",");
282      int cnt=0;
283      double dfULX, dfULY, dfLRX, dfLRY;
284      while(t!=NULL){
285        switch(cnt){
286        case 0:
287          dfULX = atof(t);
288          break;
289        case 1:
290          dfULY = atof(t);
291          break;
292        case 2:
293          dfLRX = atof(t);
294          break;
295        case 3:
296          dfLRY = atof(t);
297          break;
298        }
299        fprintf(stderr,"%s\n\n",t);
300        fprintf(stderr,"%f - %f - %f - %f\n\n",dfULX,dfULY,dfLRX,dfLRY);
301        t=strtok(NULL,",");
302        cnt++;
303      }
304
305          OGRLinearRing  oRing;
306
307          oRing.addPoint( dfULX, dfULY );
308          oRing.addPoint( dfULX, dfLRY );
309          oRing.addPoint( dfLRX, dfLRY );
310          oRing.addPoint( dfLRX, dfULY );
311          oRing.addPoint( dfULX, dfULY );
312          poSpatialFilter = new OGRPolygon();
313          ((OGRPolygon *) poSpatialFilter)->addRing( &oRing );
314        }
315
316        tmpMap=NULL;
317    tmpMap=getMapFromMaps(inputs,"where","value");
318    if(tmpMap!=NULL){
319          pszWHERE = tmpMap->value;
320        }
321
322        tmpMap=NULL;
323    tmpMap=getMapFromMaps(inputs,"where","value");
324    if(tmpMap!=NULL){
325          pszWHERE = tmpMap->value;
326        }
327
328        tmpMap=NULL;
329    tmpMap=getMapFromMaps(inputs,"select","value");
330    if(tmpMap!=NULL){
331          pszSelect = tmpMap->value;
332          papszSelFields = CSLTokenizeStringComplex(pszSelect, " ,", 
333                  FALSE, FALSE );
334        }
335
336        tmpMap=NULL;
337    tmpMap=getMapFromMaps(inputs,"segmentize","value");
338    if(tmpMap!=NULL){
339          dfMaxSegmentLength = atof(tmpMap->value);
340        }
341
342        tmpMap=NULL;
343    tmpMap=getMapFromMaps(inputs,"segmentize","value");
344    if(tmpMap!=NULL){
345          dfMaxSegmentLength = atof(tmpMap->value);
346        }
347
348    tmpMap=NULL;
349    tmpMap=getMapFromMaps(inputs,"InputDSN","value");
350    if(tmpMap!=NULL){
351      pszDataSource=(char*)malloc(sizeof(char)*(strlen(dataPath)+strlen(tmpMap->value)+1));
352      sprintf((char*)pszDataSource,"%s/%s",dataPath,tmpMap->value);
353    }
354
355    tmpMap=NULL;
356    tmpMap=getMapFromMaps(inputs,"OutputDSN","value");
357    if(tmpMap!=NULL){
358      pszDestDataSource=(char*)malloc(sizeof(char)*(strlen(tempPath)+strlen(tmpMap->value)+4));
359      /*char *ext=new char[4];
360      ext="tif";
361      if(strcmp(mtoupper((char*)pszFormat),"AAIGRID")==0)
362        ext="csv";
363      else
364        if(strcmp(mtoupper((char*)pszFormat),"PNG")==0)
365          ext="png";
366        else
367          if(strcmp(mtoupper((char*)pszFormat),"GIF")==0)
368            ext="gif";
369          else
370            if(strcmp(mtoupper((char*)pszFormat),"JPEG")==0)
371              ext="jpg";*/
372      sprintf((char*)pszDestDataSource,"%s/%s",tempPath,tmpMap->value/*,ext*/);
373    }
374
375#else
376/* -------------------------------------------------------------------- */
377/*      Processing command line arguments.                              */
378/* -------------------------------------------------------------------- */
379    nArgc = OGRGeneralCmdLineProcessor( nArgc, &papszArgv, 0 );
380   
381    if( nArgc < 1 )
382        exit( -nArgc );
383
384    for( int iArg = 1; iArg < nArgc; iArg++ )
385    {
386        if( EQUAL(papszArgv[iArg], "--utility_version") )
387        {
388                                printf("%s was compiled against GDAL %s and is running against GDAL %s\n",
389                   papszArgv[0], GDAL_RELEASE_NAME, GDALVersionInfo("RELEASE_NAME"));
390            return 0;
391        }
392        else if( EQUAL(papszArgv[iArg],"-f") && iArg < nArgc-1 )
393        {
394            pszFormat = papszArgv[++iArg];
395        }
396        else if( EQUAL(papszArgv[iArg],"-dsco") && iArg < nArgc-1 )
397        {
398            papszDSCO = CSLAddString(papszDSCO, papszArgv[++iArg] );
399        }
400        else if( EQUAL(papszArgv[iArg],"-lco") && iArg < nArgc-1 )
401        {
402            papszLCO = CSLAddString(papszLCO, papszArgv[++iArg] );
403        }
404        else if( EQUAL(papszArgv[iArg],"-preserve_fid") )
405        {
406            bPreserveFID = TRUE;
407        }
408        else if( EQUALN(papszArgv[iArg],"-skip",5) )
409        {
410            bSkipFailures = TRUE;
411            nGroupTransactions = 1; /* #2409 */
412        }
413        else if( EQUAL(papszArgv[iArg],"-append") )
414        {
415            bAppend = TRUE;
416        }
417        else if( EQUAL(papszArgv[iArg],"-overwrite") )
418        {
419            bOverwrite = TRUE;
420        }
421        else if( EQUAL(papszArgv[iArg],"-update") )
422        {
423            bUpdate = TRUE;
424        }
425        else if( EQUAL(papszArgv[iArg],"-fid") && papszArgv[iArg+1] != NULL )
426        {
427            nFIDToFetch = atoi(papszArgv[++iArg]);
428        }
429        else if( EQUAL(papszArgv[iArg],"-sql") && papszArgv[iArg+1] != NULL )
430        {
431            pszSQLStatement = papszArgv[++iArg];
432        }
433        else if( EQUAL(papszArgv[iArg],"-nln") && iArg < nArgc-1 )
434        {
435            pszNewLayerName = papszArgv[++iArg];
436        }
437        else if( EQUAL(papszArgv[iArg],"-nlt") && iArg < nArgc-1 )
438        {
439            if( EQUAL(papszArgv[iArg+1],"NONE") )
440                eGType = wkbNone;
441            else if( EQUAL(papszArgv[iArg+1],"GEOMETRY") )
442                eGType = wkbUnknown;
443            else if( EQUAL(papszArgv[iArg+1],"POINT") )
444                eGType = wkbPoint;
445            else if( EQUAL(papszArgv[iArg+1],"LINESTRING") )
446                eGType = wkbLineString;
447            else if( EQUAL(papszArgv[iArg+1],"POLYGON") )
448                eGType = wkbPolygon;
449            else if( EQUAL(papszArgv[iArg+1],"GEOMETRYCOLLECTION") )
450                eGType = wkbGeometryCollection;
451            else if( EQUAL(papszArgv[iArg+1],"MULTIPOINT") )
452                eGType = wkbMultiPoint;
453            else if( EQUAL(papszArgv[iArg+1],"MULTILINESTRING") )
454                eGType = wkbMultiLineString;
455            else if( EQUAL(papszArgv[iArg+1],"MULTIPOLYGON") )
456                eGType = wkbMultiPolygon;
457            else if( EQUAL(papszArgv[iArg+1],"GEOMETRY25D") )
458                eGType = wkbUnknown | wkb25DBit;
459            else if( EQUAL(papszArgv[iArg+1],"POINT25D") )
460                eGType = wkbPoint25D;
461            else if( EQUAL(papszArgv[iArg+1],"LINESTRING25D") )
462                eGType = wkbLineString25D;
463            else if( EQUAL(papszArgv[iArg+1],"POLYGON25D") )
464                eGType = wkbPolygon25D;
465            else if( EQUAL(papszArgv[iArg+1],"GEOMETRYCOLLECTION25D") )
466                eGType = wkbGeometryCollection25D;
467            else if( EQUAL(papszArgv[iArg+1],"MULTIPOINT25D") )
468                eGType = wkbMultiPoint25D;
469            else if( EQUAL(papszArgv[iArg+1],"MULTILINESTRING25D") )
470                eGType = wkbMultiLineString25D;
471            else if( EQUAL(papszArgv[iArg+1],"MULTIPOLYGON25D") )
472                eGType = wkbMultiPolygon25D;
473            else
474            {
475                fprintf( stderr, "-nlt %s: type not recognised.\n", 
476                         papszArgv[iArg+1] );
477                exit( 1 );
478            }
479            iArg++;
480        }
481        else if( (EQUAL(papszArgv[iArg],"-tg") ||
482                  EQUAL(papszArgv[iArg],"-gt")) && iArg < nArgc-1 )
483        {
484            nGroupTransactions = atoi(papszArgv[++iArg]);
485        }
486        else if( EQUAL(papszArgv[iArg],"-s_srs") && iArg < nArgc-1 )
487        {
488            pszSourceSRSDef = papszArgv[++iArg];
489        }
490        else if( EQUAL(papszArgv[iArg],"-a_srs") && iArg < nArgc-1 )
491        {
492            pszOutputSRSDef = papszArgv[++iArg];
493        }
494        else if( EQUAL(papszArgv[iArg],"-t_srs") && iArg < nArgc-1 )
495        {
496            pszOutputSRSDef = papszArgv[++iArg];
497            bTransform = TRUE;
498        }
499        else if( EQUAL(papszArgv[iArg],"-spat") 
500                 && papszArgv[iArg+1] != NULL 
501                 && papszArgv[iArg+2] != NULL 
502                 && papszArgv[iArg+3] != NULL 
503                 && papszArgv[iArg+4] != NULL )
504        {
505            OGRLinearRing  oRing;
506
507            oRing.addPoint( atof(papszArgv[iArg+1]), atof(papszArgv[iArg+2]) );
508            oRing.addPoint( atof(papszArgv[iArg+1]), atof(papszArgv[iArg+4]) );
509            oRing.addPoint( atof(papszArgv[iArg+3]), atof(papszArgv[iArg+4]) );
510            oRing.addPoint( atof(papszArgv[iArg+3]), atof(papszArgv[iArg+2]) );
511            oRing.addPoint( atof(papszArgv[iArg+1]), atof(papszArgv[iArg+2]) );
512
513            poSpatialFilter = new OGRPolygon();
514            ((OGRPolygon *) poSpatialFilter)->addRing( &oRing );
515            iArg += 4;
516        }
517        else if( EQUAL(papszArgv[iArg],"-where") && papszArgv[iArg+1] != NULL )
518        {
519            pszWHERE = papszArgv[++iArg];
520        }
521        else if( EQUAL(papszArgv[iArg],"-select") && papszArgv[iArg+1] != NULL)
522        {
523            pszSelect = papszArgv[++iArg];
524            papszSelFields = CSLTokenizeStringComplex(pszSelect, " ,", 
525                                                      FALSE, FALSE );
526        }
527        else if( EQUAL(papszArgv[iArg],"-segmentize") && iArg < nArgc-1 )
528        {
529            dfMaxSegmentLength = atof(papszArgv[++iArg]);
530        }
531        else if( papszArgv[iArg][0] == '-' )
532        {
533            Usage();
534        }
535        else if( pszDestDataSource == NULL )
536            pszDestDataSource = papszArgv[iArg];
537        else if( pszDataSource == NULL )
538            pszDataSource = papszArgv[iArg];
539        else
540            papszLayers = CSLAddString( papszLayers, papszArgv[iArg] );
541    }
542#endif
543
544    if( pszDataSource == NULL )
545#ifdef ZOO_SERVICE
546        {
547#endif
548        Usage();
549#ifdef ZOO_SERVICE
550                return SERVICE_FAILED;
551        }
552#endif
553
554/* -------------------------------------------------------------------- */
555/*      Open data source.                                               */
556/* -------------------------------------------------------------------- */
557    OGRDataSource       *poDS;
558       
559    poDS = OGRSFDriverRegistrar::Open( pszDataSource, FALSE );
560
561/* -------------------------------------------------------------------- */
562/*      Report failure                                                  */
563/* -------------------------------------------------------------------- */
564    if( poDS == NULL )
565    {
566        OGRSFDriverRegistrar    *poR = OGRSFDriverRegistrar::GetRegistrar();
567       
568        fprintf( stderr, "FAILURE:\n"
569                "Unable to open datasource `%s' with the following drivers.\n",
570                pszDataSource );
571
572        for( int iDriver = 0; iDriver < poR->GetDriverCount(); iDriver++ )
573        {
574            fprintf( stderr, "  -> %s\n", poR->GetDriver(iDriver)->GetName() );
575        }
576#ifdef ZOO_SERVICE
577                return SERVICE_FAILED;
578#else
579        exit( 1 );
580#endif
581    }
582
583/* -------------------------------------------------------------------- */
584/*      Try opening the output datasource as an existing, writable      */
585/* -------------------------------------------------------------------- */
586    OGRDataSource       *poODS;
587   
588    if( bUpdate )
589    {
590        poODS = OGRSFDriverRegistrar::Open( pszDestDataSource, TRUE );
591        if( poODS == NULL )
592        {
593            fprintf( stderr, "FAILURE:\n"
594                    "Unable to open existing output datasource `%s'.\n",
595                    pszDestDataSource );
596#ifdef ZOO_SERVICE
597                return SERVICE_FAILED;
598#else
599        exit( 1 );
600#endif
601        }
602
603        if( CSLCount(papszDSCO) > 0 )
604        {
605            fprintf( stderr, "WARNING: Datasource creation options ignored since an existing datasource\n"
606                    "         being updated.\n" );
607        }
608    }
609
610/* -------------------------------------------------------------------- */
611/*      Find the output driver.                                         */
612/* -------------------------------------------------------------------- */
613    else
614    {
615        OGRSFDriverRegistrar *poR = OGRSFDriverRegistrar::GetRegistrar();
616        OGRSFDriver          *poDriver = NULL;
617        int                  iDriver;
618
619        for( iDriver = 0;
620             iDriver < poR->GetDriverCount() && poDriver == NULL;
621             iDriver++ )
622        {
623            if( EQUAL(poR->GetDriver(iDriver)->GetName(),pszFormat) )
624            {
625                poDriver = poR->GetDriver(iDriver);
626            }
627        }
628
629        if( poDriver == NULL )
630        {
631            fprintf( stderr, "Unable to find driver `%s'.\n", pszFormat );
632            fprintf( stderr,  "The following drivers are available:\n" );
633       
634            for( iDriver = 0; iDriver < poR->GetDriverCount(); iDriver++ )
635            {
636                fprintf( stderr,  "  -> `%s'\n", poR->GetDriver(iDriver)->GetName() );
637            }
638#ifdef ZOO_SERVICE
639                        return SERVICE_FAILED;
640#else
641            exit( 1 );
642#endif
643        }
644
645        if( !poDriver->TestCapability( ODrCCreateDataSource ) )
646        {
647            fprintf( stderr,  "%s driver does not support data source creation.\n",
648                    pszFormat );
649#ifdef ZOO_SERVICE
650                        return SERVICE_FAILED;
651#else
652            exit( 1 );
653#endif
654        }
655
656/* -------------------------------------------------------------------- */
657/*      Create the output data source.                                  */
658/* -------------------------------------------------------------------- */
659        poODS = poDriver->CreateDataSource( pszDestDataSource, papszDSCO );
660        if( poODS == NULL )
661        {
662            fprintf( stderr,  "%s driver failed to create %s\n", 
663                    pszFormat, pszDestDataSource );
664#ifdef ZOO_SERVICE
665                        return SERVICE_FAILED;
666#else
667            exit( 1 );
668#endif
669        }
670    }
671
672/* -------------------------------------------------------------------- */
673/*      Parse the output SRS definition if possible.                    */
674/* -------------------------------------------------------------------- */
675    if( pszOutputSRSDef != NULL )
676    {
677        poOutputSRS = new OGRSpatialReference();
678        if( poOutputSRS->SetFromUserInput( pszOutputSRSDef ) != OGRERR_NONE )
679        {
680            fprintf( stderr,  "Failed to process SRS definition: %s\n", 
681                    pszOutputSRSDef );
682#ifdef ZOO_SERVICE
683                        return SERVICE_FAILED;
684#else
685            exit( 1 );
686#endif
687        }
688    }
689
690/* -------------------------------------------------------------------- */
691/*      Parse the source SRS definition if possible.                    */
692/* -------------------------------------------------------------------- */
693    if( pszSourceSRSDef != NULL )
694    {
695        poSourceSRS = new OGRSpatialReference();
696        if( poSourceSRS->SetFromUserInput( pszSourceSRSDef ) != OGRERR_NONE )
697        {
698            fprintf( stderr,  "Failed to process SRS definition: %s\n", 
699                    pszSourceSRSDef );
700#ifdef ZOO_SERVICE
701                        return SERVICE_FAILED;
702#else
703            exit( 1 );
704#endif
705        }
706    }
707
708/* -------------------------------------------------------------------- */
709/*      Special case for -sql clause.  No source layers required.       */
710/* -------------------------------------------------------------------- */
711    if( pszSQLStatement != NULL )
712    {
713        OGRLayer *poResultSet;
714
715        if( pszWHERE != NULL )
716            fprintf( stderr,  "-where clause ignored in combination with -sql.\n" );
717        if( CSLCount(papszLayers) > 0 )
718            fprintf( stderr,  "layer names ignored in combination with -sql.\n" );
719       
720        poResultSet = poDS->ExecuteSQL( pszSQLStatement, poSpatialFilter, 
721                                        NULL );
722
723        if( poResultSet != NULL )
724        {
725            if( !TranslateLayer( poDS, poResultSet, poODS, papszLCO, 
726                                 pszNewLayerName, bTransform, poOutputSRS,
727                                 poSourceSRS, papszSelFields, bAppend, eGType,
728                                 bOverwrite, dfMaxSegmentLength ))
729            {
730                CPLError( CE_Failure, CPLE_AppDefined, 
731                          "Terminating translation prematurely after failed\n"
732                          "translation from sql statement." );
733
734                exit( 1 );
735            }
736            poDS->ReleaseResultSet( poResultSet );
737        }
738    }
739
740/* -------------------------------------------------------------------- */
741/*      Process each data source layer.                                 */
742/* -------------------------------------------------------------------- */
743    for( int iLayer = 0; 
744         pszSQLStatement == NULL && iLayer < poDS->GetLayerCount(); 
745         iLayer++ )
746    {
747        OGRLayer        *poLayer = poDS->GetLayer(iLayer);
748
749        if( poLayer == NULL )
750        {
751            fprintf( stderr, "FAILURE: Couldn't fetch advertised layer %d!\n",
752                    iLayer );
753#ifdef ZOO_SERVICE
754                        return SERVICE_FAILED;
755#else
756                        exit( 1 );
757#endif
758        }
759
760        if( CSLCount(papszLayers) == 0
761            || CSLFindString( papszLayers,
762                              poLayer->GetLayerDefn()->GetName() ) != -1 )
763        {
764            if( pszWHERE != NULL )
765                poLayer->SetAttributeFilter( pszWHERE );
766           
767            if( poSpatialFilter != NULL )
768                poLayer->SetSpatialFilter( poSpatialFilter );
769           
770            if( !TranslateLayer( poDS, poLayer, poODS, papszLCO, 
771                                 pszNewLayerName, bTransform, poOutputSRS,
772                                 poSourceSRS, papszSelFields, bAppend, eGType,
773                                 bOverwrite, dfMaxSegmentLength ) 
774                && !bSkipFailures )
775            {
776                CPLError( CE_Failure, CPLE_AppDefined, 
777                          "Terminating translation prematurely after failed\n"
778                          "translation of layer %s (use -skipfailures to skip errors)\n", 
779                          poLayer->GetLayerDefn()->GetName() );
780
781#ifdef ZOO_SERVICE
782                                return SERVICE_FAILED;
783#else
784                exit( 1 );
785#endif
786            }
787        }
788    }
789
790/* -------------------------------------------------------------------- */
791/*      Close down.                                                     */
792/* -------------------------------------------------------------------- */
793    delete poOutputSRS;
794    delete poSourceSRS;
795    delete poODS;
796    delete poDS;
797
798    CSLDestroy(papszSelFields);
799#ifndef ZOO_SERVICE
800        CSLDestroy( papszArgv );
801#endif
802    CSLDestroy( papszLayers );
803    CSLDestroy( papszDSCO );
804    CSLDestroy( papszLCO );
805
806    OGRCleanupAll();
807
808#ifdef DBMALLOC
809    malloc_dump(1);
810#endif
811   
812#ifdef ZOO_SERVICE
813        outputs=(maps*)malloc(sizeof(maps*));
814    outputs->name="GeneratedFile";
815    outputs->content=createMap("value",(char*)pszDestDataSource);
816    addMapToMap(&outputs->content,createMap("dataType","string"));
817    outputs->next=NULL;
818    return SERVICE_SUCCEEDED;
819#else
820        return 0;
821#endif
822}
823
824/************************************************************************/
825/*                               Usage()                                */
826/************************************************************************/
827
828static void Usage()
829
830{
831    OGRSFDriverRegistrar        *poR = OGRSFDriverRegistrar::GetRegistrar();
832
833#ifdef ZOO_SERVICE
834        fprintf(stderr,
835#else
836        printf(
837#endif
838                "Usage: ogr2ogr [--help-general] [-skipfailures] [-append] [-update] [-gt n]\n"
839                "               [-select field_list] [-where restricted_where] \n"
840                "               [-sql <sql statement>] \n" 
841                "               [-spat xmin ymin xmax ymax] [-preserve_fid] [-fid FID]\n"
842                "               [-a_srs srs_def] [-t_srs srs_def] [-s_srs srs_def]\n"
843                "               [-f format_name] [-overwrite] [[-dsco NAME=VALUE] ...]\n"
844                "               [-segmentize max_dist]\n"
845                "               dst_datasource_name src_datasource_name\n"
846                "               [-lco NAME=VALUE] [-nln name] [-nlt type] [layer [layer ...]]\n"
847                "\n"
848                " -f format_name: output file format name, possible values are:\n");
849   
850    for( int iDriver = 0; iDriver < poR->GetDriverCount(); iDriver++ )
851    {
852        OGRSFDriver *poDriver = poR->GetDriver(iDriver);
853
854        if( poDriver->TestCapability( ODrCCreateDataSource ) )
855            printf( "     -f \"%s\"\n", poDriver->GetName() );
856    }
857
858#ifdef ZOO_SERVICE
859        fprintf(stderr,
860#else
861        printf(
862#endif
863                " -append: Append to existing layer instead of creating new if it exists\n"
864                " -overwrite: delete the output layer and recreate it empty\n"
865                " -update: Open existing output datasource in update mode\n"
866                " -select field_list: Comma-delimited list of fields from input layer to\n"
867                "                     copy to the new layer (defaults to all)\n" 
868                " -where restricted_where: Attribute query (like SQL WHERE)\n" 
869                " -sql statement: Execute given SQL statement and save result.\n"
870                " -skipfailures: skip features or layers that fail to convert\n"
871                " -gt n: group n features per transaction (default 200)\n"
872                " -spat xmin ymin xmax ymax: spatial query extents\n"
873                " -segmentize max_dist: maximum distance between 2 nodes.\n"
874                "                       Used to create intermediate points\n"
875                " -dsco NAME=VALUE: Dataset creation option (format specific)\n"
876                " -lco  NAME=VALUE: Layer creation option (format specific)\n"
877                " -nln name: Assign an alternate name to the new layer\n"
878                " -nlt type: Force a geometry type for new layer.  One of NONE, GEOMETRY,\n"
879                "      POINT, LINESTRING, POLYGON, GEOMETRYCOLLECTION, MULTIPOINT,\n"
880                "      MULTIPOLYGON, or MULTILINESTRING.  Add \"25D\" for 3D layers.\n"
881                "      Default is type of source layer.\n" );
882
883#ifdef ZOO_SERVICE
884        fprintf(stderr,
885#else
886        printf(
887#endif
888                " -a_srs srs_def: Assign an output SRS\n"
889                " -t_srs srs_def: Reproject/transform to this SRS on output\n"
890                " -s_srs srs_def: Override source SRS\n"
891                "\n" 
892                " Srs_def can be a full WKT definition (hard to escape properly),\n"
893                " or a well known definition (ie. EPSG:4326) or a file with a WKT\n"
894                " definition.\n" );
895
896
897#ifndef ZOO_SERVICE
898        exit( 1 );
899#endif
900}
901
902/************************************************************************/
903/*                           TranslateLayer()                           */
904/************************************************************************/
905
906static int TranslateLayer( OGRDataSource *poSrcDS, 
907                           OGRLayer * poSrcLayer,
908                           OGRDataSource *poDstDS,
909                           char **papszLCO,
910                           const char *pszNewLayerName,
911                           int bTransform, 
912                           OGRSpatialReference *poOutputSRS,
913                           OGRSpatialReference *poSourceSRS,
914                           char **papszSelFields,
915                           int bAppend, int eGType, int bOverwrite,
916                           double dfMaxSegmentLength)
917
918{
919    OGRLayer    *poDstLayer;
920    OGRFeatureDefn *poFDefn;
921    OGRErr      eErr;
922    int         bForceToPolygon = FALSE;
923    int         bForceToMultiPolygon = FALSE;
924
925    if( pszNewLayerName == NULL )
926        pszNewLayerName = poSrcLayer->GetLayerDefn()->GetName();
927
928    if( wkbFlatten(eGType) == wkbPolygon )
929        bForceToPolygon = TRUE;
930    else if( wkbFlatten(eGType) == wkbMultiPolygon )
931        bForceToMultiPolygon = TRUE;
932
933/* -------------------------------------------------------------------- */
934/*      Setup coordinate transformation if we need it.                  */
935/* -------------------------------------------------------------------- */
936    OGRCoordinateTransformation *poCT = NULL;
937
938    if( bTransform )
939    {
940        if( poSourceSRS == NULL )
941            poSourceSRS = poSrcLayer->GetSpatialRef();
942
943        if( poSourceSRS == NULL )
944        {
945            fprintf( stderr, "Can't transform coordinates, source layer has no\n"
946                    "coordinate system.  Use -s_srs to set one.\n" );
947#ifdef ZOO_SERVICE
948            return SERVICE_FAILED;
949#else
950            exit( 1 );
951#endif
952        }
953
954        CPLAssert( NULL != poSourceSRS );
955        CPLAssert( NULL != poOutputSRS );
956
957        poCT = OGRCreateCoordinateTransformation( poSourceSRS, poOutputSRS );
958        if( poCT == NULL )
959        {
960            char        *pszWKT = NULL;
961
962            fprintf( stderr, "Failed to create coordinate transformation between the\n"
963                   "following coordinate systems.  This may be because they\n"
964                   "are not transformable, or because projection services\n"
965                   "(PROJ.4 DLL/.so) could not be loaded.\n" );
966           
967            poSourceSRS->exportToPrettyWkt( &pszWKT, FALSE );
968            fprintf( stderr,  "Source:\n%s\n", pszWKT );
969           
970            poOutputSRS->exportToPrettyWkt( &pszWKT, FALSE );
971            fprintf( stderr,  "Target:\n%s\n", pszWKT );
972#ifdef ZOO_SERVICE
973            return SERVICE_FAILED;
974#else
975            exit( 1 );
976#endif
977        }
978    }
979   
980/* -------------------------------------------------------------------- */
981/*      Get other info.                                                 */
982/* -------------------------------------------------------------------- */
983    poFDefn = poSrcLayer->GetLayerDefn();
984   
985    if( poOutputSRS == NULL )
986        poOutputSRS = poSrcLayer->GetSpatialRef();
987
988/* -------------------------------------------------------------------- */
989/*      Find the layer.                                                 */
990/* -------------------------------------------------------------------- */
991    int iLayer = -1;
992    poDstLayer = NULL;
993
994    for( iLayer = 0; iLayer < poDstDS->GetLayerCount(); iLayer++ )
995    {
996        OGRLayer        *poLayer = poDstDS->GetLayer(iLayer);
997
998        if( poLayer != NULL 
999            && EQUAL(poLayer->GetLayerDefn()->GetName(),pszNewLayerName) )
1000        {
1001            poDstLayer = poLayer;
1002            break;
1003        }
1004    }
1005   
1006/* -------------------------------------------------------------------- */
1007/*      If the user requested overwrite, and we have the layer in       */
1008/*      question we need to delete it now so it will get recreated      */
1009/*      (overwritten).                                                  */
1010/* -------------------------------------------------------------------- */
1011    if( poDstLayer != NULL && bOverwrite )
1012    {
1013        if( poDstDS->DeleteLayer( iLayer ) != OGRERR_NONE )
1014        {
1015            fprintf( stderr, 
1016                     "DeleteLayer() failed when overwrite requested.\n" );
1017            return FALSE;
1018        }
1019        poDstLayer = NULL;
1020    }
1021
1022/* -------------------------------------------------------------------- */
1023/*      If the layer does not exist, then create it.                    */
1024/* -------------------------------------------------------------------- */
1025    if( poDstLayer == NULL )
1026    {
1027        if( eGType == -2 )
1028            eGType = poFDefn->GetGeomType();
1029
1030        if( !poDstDS->TestCapability( ODsCCreateLayer ) )
1031        {
1032            fprintf( stderr, 
1033              "Layer %s not found, and CreateLayer not supported by driver.", 
1034                     pszNewLayerName );
1035            return FALSE;
1036        }
1037
1038        CPLErrorReset();
1039
1040        poDstLayer = poDstDS->CreateLayer( pszNewLayerName, poOutputSRS,
1041                                           (OGRwkbGeometryType) eGType, 
1042                                           papszLCO );
1043
1044        if( poDstLayer == NULL )
1045            return FALSE;
1046
1047        bAppend = FALSE;
1048    }
1049
1050/* -------------------------------------------------------------------- */
1051/*      Otherwise we will append to it, if append was requested.        */
1052/* -------------------------------------------------------------------- */
1053    else if( !bAppend )
1054    {
1055        fprintf( stderr, "FAILED: Layer %s already exists, and -append not specified.\n"
1056                "        Consider using -append, or -overwrite.\n",
1057                pszNewLayerName );
1058        return FALSE;
1059    }
1060    else
1061    {
1062        if( CSLCount(papszLCO) > 0 )
1063        {
1064            fprintf( stderr, "WARNING: Layer creation options ignored since an existing layer is\n"
1065                    "         being appended to.\n" );
1066        }
1067    }
1068
1069/* -------------------------------------------------------------------- */
1070/*      Add fields.  Default to copy all field.                         */
1071/*      If only a subset of all fields requested, then output only      */
1072/*      the selected fields, and in the order that they were            */
1073/*      selected.                                                       */
1074/* -------------------------------------------------------------------- */
1075    int         iField;
1076
1077    if (papszSelFields && !bAppend )
1078    {
1079        for( iField=0; papszSelFields[iField] != NULL; iField++)
1080        {
1081            int iSrcField = poFDefn->GetFieldIndex(papszSelFields[iField]);
1082            if (iSrcField >= 0)
1083                poDstLayer->CreateField( poFDefn->GetFieldDefn(iSrcField) );
1084            else
1085            {
1086                fprintf( stderr, "Field '%s' not found in source layer.\n", 
1087                        papszSelFields[iField] );
1088                if( !bSkipFailures )
1089                    return FALSE;
1090            }
1091        }
1092    }
1093    else if( !bAppend )
1094    {
1095        for( iField = 0; iField < poFDefn->GetFieldCount(); iField++ )
1096            poDstLayer->CreateField( poFDefn->GetFieldDefn(iField) );
1097    }
1098
1099/* -------------------------------------------------------------------- */
1100/*      Transfer features.                                              */
1101/* -------------------------------------------------------------------- */
1102    OGRFeature  *poFeature;
1103    int         nFeaturesInTransaction = 0;
1104   
1105    poSrcLayer->ResetReading();
1106
1107    if( nGroupTransactions )
1108        poDstLayer->StartTransaction();
1109
1110    while( TRUE )
1111    {
1112        OGRFeature      *poDstFeature = NULL;
1113
1114        if( nFIDToFetch != OGRNullFID )
1115        {
1116            // Only fetch feature on first pass.
1117            if( nFeaturesInTransaction == 0 )
1118                poFeature = poSrcLayer->GetFeature(nFIDToFetch);
1119            else
1120                poFeature = NULL;
1121        }
1122        else
1123            poFeature = poSrcLayer->GetNextFeature();
1124       
1125        if( poFeature == NULL )
1126            break;
1127
1128        if( ++nFeaturesInTransaction == nGroupTransactions )
1129        {
1130            poDstLayer->CommitTransaction();
1131            poDstLayer->StartTransaction();
1132            nFeaturesInTransaction = 0;
1133        }
1134
1135        CPLErrorReset();
1136        poDstFeature = OGRFeature::CreateFeature( poDstLayer->GetLayerDefn() );
1137
1138        if( poDstFeature->SetFrom( poFeature, TRUE ) != OGRERR_NONE )
1139        {
1140            if( nGroupTransactions )
1141                poDstLayer->CommitTransaction();
1142           
1143            CPLError( CE_Failure, CPLE_AppDefined,
1144                      "Unable to translate feature %ld from layer %s.\n",
1145                      poFeature->GetFID(), poFDefn->GetName() );
1146           
1147            OGRFeature::DestroyFeature( poFeature );
1148            OGRFeature::DestroyFeature( poDstFeature );
1149            return FALSE;
1150        }
1151
1152        if( bPreserveFID )
1153            poDstFeature->SetFID( poFeature->GetFID() );
1154
1155#ifndef GDAL_1_5_0
1156        if (poDstFeature->GetGeometryRef() != NULL && dfMaxSegmentLength > 0)
1157            poDstFeature->GetGeometryRef()->segmentize(dfMaxSegmentLength);
1158#endif
1159
1160        if( poCT && poDstFeature->GetGeometryRef() != NULL )
1161        {
1162            eErr = poDstFeature->GetGeometryRef()->transform( poCT );
1163            if( eErr != OGRERR_NONE )
1164            {
1165                if( nGroupTransactions )
1166                    poDstLayer->CommitTransaction();
1167
1168                fprintf( stderr, "Failed to reproject feature %d (geometry probably out of source or destination SRS).\n", 
1169                        (int) poFeature->GetFID() );
1170                if( !bSkipFailures )
1171                {
1172                    OGRFeature::DestroyFeature( poFeature );
1173                    OGRFeature::DestroyFeature( poDstFeature );
1174                    return FALSE;
1175                }
1176            }
1177        }
1178
1179        if( poDstFeature->GetGeometryRef() != NULL && bForceToPolygon )
1180        {
1181            poDstFeature->SetGeometryDirectly( 
1182                OGRGeometryFactory::forceToPolygon(
1183                    poDstFeature->StealGeometry() ) );
1184        }
1185                   
1186        if( poDstFeature->GetGeometryRef() != NULL && bForceToMultiPolygon )
1187        {
1188            poDstFeature->SetGeometryDirectly( 
1189                OGRGeometryFactory::forceToMultiPolygon(
1190                    poDstFeature->StealGeometry() ) );
1191        }
1192                   
1193        OGRFeature::DestroyFeature( poFeature );
1194
1195        CPLErrorReset();
1196        if( poDstLayer->CreateFeature( poDstFeature ) != OGRERR_NONE
1197            && !bSkipFailures )
1198        {
1199            if( nGroupTransactions )
1200                poDstLayer->RollbackTransaction();
1201
1202            OGRFeature::DestroyFeature( poDstFeature );
1203            return FALSE;
1204        }
1205
1206        OGRFeature::DestroyFeature( poDstFeature );
1207    }
1208
1209    if( nGroupTransactions )
1210        poDstLayer->CommitTransaction();
1211
1212/* -------------------------------------------------------------------- */
1213/*      Cleaning                                                        */
1214/* -------------------------------------------------------------------- */
1215    delete poCT;
1216
1217    return TRUE;
1218}
1219
1220#ifdef ZOO_SERVICE
1221}
1222#endif
Note: See TracBrowser for help on using the repository browser.

Search

Context Navigation

ZOO Sponsors

http://www.zoo-project.org/trac/chrome/site/img/geolabs-logo.pnghttp://www.zoo-project.org/trac/chrome/site/img/neogeo-logo.png http://www.zoo-project.org/trac/chrome/site/img/apptech-logo.png http://www.zoo-project.org/trac/chrome/site/img/3liz-logo.png http://www.zoo-project.org/trac/chrome/site/img/gateway-logo.png

Become a sponsor !

Knowledge partners

http://www.zoo-project.org/trac/chrome/site/img/ocu-logo.png http://www.zoo-project.org/trac/chrome/site/img/gucas-logo.png http://www.zoo-project.org/trac/chrome/site/img/polimi-logo.png http://www.zoo-project.org/trac/chrome/site/img/fem-logo.png http://www.zoo-project.org/trac/chrome/site/img/supsi-logo.png http://www.zoo-project.org/trac/chrome/site/img/cumtb-logo.png

Become a knowledge partner

Related links

http://zoo-project.org/img/ogclogo.png http://zoo-project.org/img/osgeologo.png