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

Last change on this file since 40 was 40, checked in by djay, 13 years ago

Remove uneeded or redundant part.

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

Search

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