Statistics
| Revision:

gvsig-gdal / trunk / org.gvsig.gdal / org.gvsig.gdal.prov / org.gvsig.gdal.prov.ogr / src / main / java / org / gvsig / gdal / prov / ogr / OGRDataStoreProvider.java @ 510

History | View | Annotate | Download (23.4 KB)

1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright ? 2007-2016 gvSIG Association
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 2
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.gdal.prov.ogr;
25

    
26
import java.util.ArrayList;
27
import java.util.Iterator;
28
import java.util.List;
29

    
30
import org.apache.commons.lang3.StringUtils;
31
import org.gdal.ogr.DataSource;
32
import org.gdal.ogr.Feature;
33
import org.gdal.ogr.FeatureDefn;
34
import org.gdal.ogr.FieldDefn;
35
import org.gdal.ogr.GeomFieldDefn;
36
import org.gdal.ogr.Geometry;
37
import org.gdal.ogr.Layer;
38
import org.gdal.ogr.ogr;
39
import org.gdal.ogr.ogrConstants;
40

    
41
import org.gvsig.fmap.dal.DataStore;
42
import org.gvsig.fmap.dal.DataStoreParameters;
43
import org.gvsig.fmap.dal.DataTypes;
44
import org.gvsig.fmap.dal.FileHelper;
45
import org.gvsig.fmap.dal.exception.DataException;
46
import org.gvsig.fmap.dal.exception.InitializeException;
47
import org.gvsig.fmap.dal.exception.OpenException;
48
import org.gvsig.fmap.dal.exception.ReadRuntimeException;
49
import org.gvsig.fmap.dal.feature.EditableFeatureAttributeDescriptor;
50
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
51
import org.gvsig.fmap.dal.feature.FeatureQuery;
52
import org.gvsig.fmap.dal.feature.FeatureQueryOrder;
53
import org.gvsig.fmap.dal.feature.FeatureQueryOrder.FeatureQueryOrderMember;
54
import org.gvsig.fmap.dal.feature.FeatureType;
55
import org.gvsig.fmap.dal.feature.FeatureType.FeatureTypeChanged;
56
import org.gvsig.fmap.dal.feature.spi.AbstractFeatureStoreProvider;
57
import org.gvsig.fmap.dal.feature.spi.DefaultFeatureProvider;
58
import org.gvsig.fmap.dal.feature.spi.FeatureProvider;
59
import org.gvsig.fmap.dal.feature.spi.FeatureReferenceProviderServices;
60
import org.gvsig.fmap.dal.feature.spi.FeatureSetProvider;
61
import org.gvsig.fmap.dal.feature.spi.FeatureStoreProvider;
62
import org.gvsig.fmap.dal.resource.ResourceAction;
63
import org.gvsig.fmap.dal.resource.file.FileResource;
64
import org.gvsig.fmap.dal.resource.spi.ResourceConsumer;
65
import org.gvsig.fmap.dal.resource.spi.ResourceProvider;
66
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
67
import org.gvsig.fmap.geom.Geometry.SUBTYPES;
68
import org.gvsig.fmap.geom.GeometryLocator;
69
import org.gvsig.fmap.geom.primitive.Envelope;
70
import org.gvsig.fmap.geom.type.GeometryTypeNotSupportedException;
71
import org.gvsig.fmap.geom.type.GeometryTypeNotValidException;
72
import org.gvsig.tools.dynobject.DynObject;
73
import org.gvsig.tools.evaluator.Evaluator;
74
import org.gvsig.tools.exception.BaseException;
75

    
76
import org.slf4j.Logger;
77
import org.slf4j.LoggerFactory;
78

    
79
/**
80
 *
81
 * @author <a href="mailto:lmarques@disid.com">Lluis Marques</a>
82
 *
83
 */
84
public class OGRDataStoreProvider extends AbstractFeatureStoreProvider implements
85
    FeatureStoreProvider, ResourceConsumer {
86

    
87
    private static final Logger LOG = LoggerFactory.getLogger(OGRDataStoreProvider.class);
88

    
89
    /**
90
     *
91
     */
92
    public static final String METADATA_DEFINITION_NAME = "OGRDataStoreProvider";
93

    
94
    /**
95
     *
96
     */
97
    public static final String NAME = "OGRDataStoreProvider";
98

    
99
    /**
100
     *
101
     */
102
    public static final String DESCRIPTION = "OGR provider to open vectorial resources";
103

    
104
    protected DataSource dataSource;
105

    
106
    private Envelope envelope;
107

    
108
    private Layer newLayer;
109

    
110
    protected ResourceProvider resourceProvider;
111

    
112
    private Boolean updateSupport;
113

    
114
    private boolean opened = false;
115

    
116
    protected OGRDataStoreProvider(DataStoreParameters dataParameters,
117
        DataStoreProviderServices storeServices, DynObject metadata) throws InitializeException {
118
        super(dataParameters, storeServices, metadata);
119

    
120
        // Set CRS parameter to metadata
121
        this.setDynValue(DataStore.METADATA_CRS, dataParameters.getDynValue(DataStore.METADATA_CRS));
122

    
123
        getResource().addConsumer(this);
124

    
125
        try {
126
            this.open();
127
        } catch (OpenException e) {
128
            throw new InitializeException(NAME, e);
129
        }
130
    }
131

    
132
    protected OGRDataStoreProvider(DataStoreParameters dataParameters,
133
        DataStoreProviderServices storeServices) throws InitializeException {
134
        this(dataParameters, storeServices, FileHelper
135
            .newMetadataContainer(METADATA_DEFINITION_NAME));
136
    }
137

    
138
    /*
139
     * Lazy initialization of data source
140
     */
141
    protected synchronized DataSource getDataSource() throws OGRUnsupportedFormatException {
142
        if (this.dataSource == null) {
143

    
144
            // Prioritize connection string over file
145
            if (StringUtils.isNotBlank(getOGRParameters().getConnectionString())) {
146

    
147
                // Trying to open in update mode
148
                this.dataSource = ogr.Open(getOGRParameters().getConnectionString(), 1);
149

    
150
                if (this.dataSource == null) {
151
                    this.dataSource = ogr.Open(getOGRParameters().getConnectionString());
152
                    updateSupport = false;
153
                } else {
154
                    updateSupport = true;
155
                }
156

    
157
            } else if (getOGRParameters().getFile() != null
158
                && getOGRParameters().getFile().exists()) {
159

    
160
                // Trying to open in update mode
161
                this.dataSource = ogr.Open(getOGRParameters().getFile().getAbsolutePath(), 1);
162

    
163
                if (this.dataSource == null) {
164
                    this.dataSource = ogr.Open(getOGRParameters().getFile().getAbsolutePath());
165
                    updateSupport = false;
166
                } else {
167
                    updateSupport = true;
168
                }
169

    
170
            } else {
171
                throw new IllegalStateException(
172
                    "Invalid parameters. Connection string must not be blank or file must exists");
173
            }
174
        }
175

    
176
        if (this.dataSource == null) {
177

    
178
            if (StringUtils.isNotBlank(getOGRParameters().getConnectionString())) {
179
                throw new OGRUnsupportedFormatException(getOGRParameters().getConnectionString());
180
            }
181
        }
182

    
183
        return this.dataSource;
184
    }
185

    
186
    /*
187
     * Lazy initialization of update support flag
188
     */
189
    private Boolean hasUpdateSupport() throws OGRUnsupportedFormatException {
190
        if (this.updateSupport == null) {
191
            getDataSource();
192
        }
193
        return this.updateSupport;
194
    }
195

    
196
    /*
197
     * Lazy initialization of layer
198
     */
199
    protected Layer getLayer() throws OGRUnsupportedFormatException {
200
        if (this.newLayer == null) {
201
            this.newLayer = getDataSource().GetLayer(getOGRParameters().getLayerName());
202
            // this.layer = getDataSource().GetLayer(0);
203
            if (this.newLayer == null) {
204
                LOG.warn("Can not get layer with {} name. Get first layer of data source",
205
                    getOGRParameters().getLayerName());
206
                this.newLayer = getDataSource().GetLayer(0);
207
                getOGRParameters().setLayerName(this.newLayer.GetName());
208
            }
209
        }
210
        return this.newLayer;
211
    }
212

    
213
    /*
214
     * Lazy envelope initialization
215
     */
216
    @Override
217
    public Envelope getEnvelope() throws DataException {
218
        open();
219
        if (this.envelope == null) {
220
            this.envelope = (Envelope) getResource().execute(new ResourceAction() {
221

    
222
                @Override
223
                public Object run() throws Exception {
224
                    Layer layer = getLayer();
225
                    double[] extent = layer.GetExtent(true);
226
                    if (extent != null) {
227
                        return GeometryLocator.getGeometryManager().createEnvelope(extent[0],
228
                            extent[2], extent[1], extent[3], SUBTYPES.GEOM2D);
229
                    } else {
230
                        Envelope tmpEnvelope =
231
                            GeometryLocator.getGeometryManager().createEnvelope(SUBTYPES.GEOM2D);
232
                        FeatureType featureType = getStoreServices().getDefaultFeatureType();
233
                        layer.ResetReading();
234
                        Feature feature = layer.GetNextFeature();
235
                        while (feature!=null) {
236
                            double[] envelope = new double[4];
237
                            int geomFieldIndex =
238
                                layer.GetLayerDefn().GetGeomFieldIndex(
239
                                    featureType.getDefaultGeometryAttributeName());
240
                            Geometry ogrGeometry = feature.GetGeomFieldRef(geomFieldIndex);
241
                            ogrGeometry.GetEnvelope(envelope);
242
                            tmpEnvelope.add(GeometryLocator.getGeometryManager()
243
                                .createEnvelope(envelope[0], envelope[2], envelope[1], envelope[3],
244
                                    SUBTYPES.GEOM2D));
245
                            feature = layer.GetNextFeature();
246
                        }
247

    
248
                        return tmpEnvelope;
249
                    }
250
                }
251
            });
252
        }
253
        return this.envelope;
254
    }
255

    
256
    @Override
257
    public String getFullName() {
258

    
259
        StringBuilder stb = new StringBuilder();
260
        stb.append(NAME);
261
        stb.append(":");
262
        if (StringUtils.isBlank(getOGRParameters().getConnectionString())) {
263
            stb.append(getOGRParameters().getFile().getAbsolutePath());
264
            stb.append(":");
265
            stb.append(getOGRParameters().getLayerName());
266
        } else {
267
            stb.append(getOGRParameters().getConnectionString());
268
        }
269
        return stb.toString();
270
    }
271

    
272
    @Override
273
    public String getName() {
274
        return getOGRParameters().getLayerName();
275
    }
276

    
277
    @Override
278
    public String getProviderName() {
279
        return NAME;
280
    }
281

    
282
    @Override
283
    public boolean allowWrite() {
284
        try {
285
            return getLayer().TestCapability(ogrConstants.OLCAlterFieldDefn)
286
                && getLayer().TestCapability(ogrConstants.OLCCreateField)
287
                && getLayer().TestCapability(ogrConstants.OLCDeleteField)
288
                && getLayer().TestCapability(ogrConstants.OLCDeleteFeature) && hasUpdateSupport();
289
        } catch (OGRUnsupportedFormatException e) {
290
            LOG.error("Can not determinate if data source allows write", e);
291
            return false;
292
        }
293
    }
294

    
295
    @Override
296
    public ResourceProvider getResource() {
297

    
298
        if (this.resourceProvider == null) {
299
            if (StringUtils.isBlank(getOGRParameters().getConnectionString())) {
300
                try {
301
                    this.resourceProvider =
302
                        this.createResource(FileResource.NAME, new Object[] { getOGRParameters()
303
                            .getFile().getAbsolutePath() });
304
                } catch (InitializeException e) {
305
                    throw new ReadRuntimeException(String.format(
306
                        "Can not create file resource with %1s path", getOGRParameters().getFile()
307
                            .getAbsolutePath()), e);
308
                }
309
            } else {
310
                try {
311
                    this.resourceProvider =
312
                        this.createResource(OGRResource.NAME, new Object[] { getOGRParameters()
313
                            .getConnectionString() });
314
                } catch (InitializeException e) {
315
                    throw new ReadRuntimeException(String.format(
316
                        "Can not create OGR resource with %1s", getOGRParameters()
317
                            .getConnectionString()), e);
318
                }
319
            }
320
        }
321

    
322
        return resourceProvider;
323
    }
324

    
325
    @Override
326
    public Object getSourceId() {
327
        return this.getOGRParameters().getFile();
328
    }
329

    
330
    @Override
331
    public void open() throws OpenException {
332

    
333
        if (opened == false) {
334
            try {
335
                this.opened = loadFeatureType();
336
            } catch (BaseException e) {
337
                LOG.error("Can not load feature type", e);
338
                throw new OpenException(getFullName(), e);
339
            }
340
        }
341
    }
342

    
343
    protected boolean loadFeatureType() throws OGRUnsupportedFormatException,
344
        GeometryTypeNotSupportedException, GeometryTypeNotValidException {
345

    
346
        return (boolean) getResource().execute(new ResourceAction() {
347

    
348
            @Override
349
            public Object run() throws Exception {
350
                FeatureDefn featureDefn = getLayer().GetLayerDefn();
351
                OGRConverter converter = new OGRConverter();
352
                String defaultGeometryField = getOGRParameters().getDefaultGeometryField();
353
                FeatureType featureType = converter.convert(featureDefn, defaultGeometryField);
354

    
355
                if (featureType.getDefaultSRS() != null) {
356
                    setDynValue(DataStore.METADATA_CRS, featureType.getDefaultSRS());
357
                }
358

    
359
                List<FeatureType> featureTypes = new ArrayList<FeatureType>();
360
                featureTypes.add(featureType);
361

    
362
                getStoreServices().setFeatureTypes(featureTypes, featureType);
363
                return true;
364
            }
365
        });
366
    }
367

    
368
    @SuppressWarnings("rawtypes")
369
    @Override
370
    public void performChanges(final Iterator deleteds, final Iterator inserteds,
371
        final Iterator updateds, final Iterator featureTypesChanged) throws DataException {
372

    
373
        getResource().execute(new ResourceAction() {
374

    
375
            @Override
376
            public Object run() throws Exception {
377
                OGRConverter converter = new OGRConverter();
378

    
379
                if (getLayer().TestCapability(ogrConstants.OLCTransactions)) {
380
                    getLayer().StartTransaction();
381
                }
382

    
383
                while (featureTypesChanged.hasNext()) {
384
                    FeatureTypeChanged featureTypeChange =
385
                        (FeatureTypeChanged) featureTypesChanged.next();
386
                    FeatureType source = featureTypeChange.getSource();
387
                    FeatureType target = featureTypeChange.getTarget();
388

    
389
                    for (int i = 0; i < source.getAttributeDescriptors().length; i++) {
390
                        EditableFeatureAttributeDescriptor eAttDescriptor =
391
                            source.getEditable().getEditableAttributeDescriptor(i);
392

    
393
                        if (eAttDescriptor.getOriginalName() != null) {
394
                            int index =
395
                                getLayer().GetLayerDefn().GetFieldIndex(
396
                                    eAttDescriptor.getOriginalName());
397

    
398
                            FieldDefn field = converter.convertField(eAttDescriptor);
399
                            getLayer().AlterFieldDefn(index, field, ogrConstants.ALTER_ALL_FLAG);
400
                        } else if (target.getAttributeDescriptor(eAttDescriptor.getName()) == null) {
401
                            int index = getLayer().FindFieldIndex(eAttDescriptor.getName(), 1);
402
                            getLayer().DeleteField(index);
403
                        }
404
                    }
405

    
406
                    List<FieldDefn> fields = converter.convertFields(target);
407
                    for (FieldDefn fieldDefn : fields) {
408
                        int index = getLayer().GetLayerDefn().GetFieldIndex(fieldDefn.GetName());
409
                        if (index == -1) {
410
                            getLayer().CreateField(fieldDefn);
411
                        } else {
412
                            getLayer()
413
                                .AlterFieldDefn(index, fieldDefn, ogrConstants.ALTER_ALL_FLAG);
414
                        }
415
                    }
416

    
417
                    if (getLayer().TestCapability(ogrConstants.OLCCreateGeomField)) {
418
                        List<GeomFieldDefn> geometryFields =
419
                            converter.convertGeometryFields(target, true);
420
                        for (GeomFieldDefn geomFieldDefn : geometryFields) {
421
                            int index =
422
                                getLayer().GetLayerDefn()
423
                                    .GetGeomFieldIndex(geomFieldDefn.GetName());
424
                            if (index == -1) {
425
                                getLayer().CreateGeomField(geomFieldDefn);
426
                            }
427
                        }
428
                    } else {
429
                        StringBuilder stb = new StringBuilder();
430
                        stb.append("Driver '");
431
                        stb.append(getDataSource().GetDriver().GetName());
432
                        stb.append("' does not support create geometry fields");
433
                        LOG.warn(stb.toString());
434
                    }
435
                }
436

    
437
                while (deleteds.hasNext()) {
438
                    FeatureReferenceProviderServices reference =
439
                        (FeatureReferenceProviderServices) deleteds.next();
440
                    getLayer().DeleteFeature((int) reference.getOID());
441
                }
442

    
443
                while (inserteds.hasNext()) {
444
                    FeatureProvider featureProvider = (FeatureProvider) inserteds.next();
445
                    getLayer().CreateFeature(converter.convert(featureProvider));
446
                }
447

    
448
                while (updateds.hasNext()) {
449
                    FeatureProvider featureProvider = (FeatureProvider) updateds.next();
450
                    Feature ogrFeature = converter.convert(featureProvider);
451
                    getLayer().SetFeature(ogrFeature);
452
                }
453

    
454
                if (getLayer().TestCapability(ogrConstants.OLCTransactions)) {
455
                    getLayer().CommitTransaction();
456
                }
457
                getDataSource().SyncToDisk();
458
                repack();
459
                getResource().notifyChanges();
460

    
461
                return null;
462
            }
463
        });
464
    }
465

    
466
    protected void repack() throws OGRUnsupportedFormatException {
467
        LOG.debug("Running SQL: REPACK ".concat(getLayer().GetName()));
468
        getDataSource().ExecuteSQL("REPACK ".concat(getLayer().GetName()));
469
    }
470

    
471
    @Override
472
    public Object createNewOID() {
473
        try {
474
            return getFeatureCount() + 1;
475
        } catch (DataException e) {
476
            LOG.error("Can't get feature count", e);
477
            throw new ReadRuntimeException(getFullName(), e);
478
        }
479
    }
480

    
481
    @Override
482
    public FeatureSetProvider createSet(FeatureQuery query, FeatureType featureType)
483
        throws DataException {
484
        open();
485
        return new OGRFetureSetProvider(this, query, featureType);
486
    }
487

    
488
    @Override
489
    public long getFeatureCount() throws DataException {
490
        open();
491
        return ((Number) getResource().execute(new ResourceAction() {
492

    
493
            @Override
494
            public Object run() throws Exception {
495

    
496
                int featureCount = getLayer().GetFeatureCount(0);
497
                if( featureCount == -1 ) {
498
                    featureCount = getLayer().GetFeatureCount();
499
                }
500
                return featureCount;
501
            }
502
        })).longValue();
503
    }
504

    
505
    @Override
506
    public int getOIDType() {
507
        return DataTypes.LONG;
508
    }
509

    
510
    @Override
511
    protected FeatureProvider internalGetFeatureProviderByReference(
512
        FeatureReferenceProviderServices providerServices, FeatureType featureType)
513
        throws DataException {
514

    
515
        int oid = (int)providerServices.getOID();
516
        // Parece que hay un bug en el proveedor de SQLite para gdal.
517
        // Cuando se lee la capa, el m?todo GetFID est? indexado empezando por 0,
518
        // pero cuando se busca una ogrFeature a partir de dicho FID
519
        // el m?todo GetFeature(fid) est? indexado empezando por 1.
520
        // Esto es para rodear el problema.
521
        if(this.dataSource.GetDriver().getName().equalsIgnoreCase("SQLite")){
522
            oid++;
523
        }
524
        Feature ogrFeature = getLayer().GetFeature(oid);
525
        int fid = ogrFeature.GetFID();
526
        FeatureProvider featureProvider =
527
            new DefaultFeatureProvider(featureType, fid);
528
        OGRConverter converter = new OGRConverter();
529
        featureProvider = converter.convert(featureProvider, featureType, ogrFeature);
530
        return featureProvider;
531
    }
532

    
533
    private OGRDataStoreParameters getOGRParameters() {
534
        return (OGRDataStoreParameters) this.getParameters();
535
    }
536

    
537
    @SuppressWarnings("rawtypes")
538
    protected String compoundSelect(FeatureType type, Evaluator evaluator,
539
        FeatureQueryOrder featureQueryOrder) {
540

    
541
        StringBuilder query = new StringBuilder();
542
        query.append("SELECT ");
543
        FeatureAttributeDescriptor[] attributeDescriptors = type.getAttributeDescriptors();
544
        for (int i = 0; i < attributeDescriptors.length; i++) {
545
            query.append("\"");
546
            query.append(attributeDescriptors[i].getName());
547
            query.append("\"");
548
            // Don't add the last comma
549
            if (i < attributeDescriptors.length - 1) {
550
                query.append(",");
551
            }
552
        }
553

    
554
        query.append(" FROM ");
555
        query.append("\"");
556
        query.append(getOGRParameters().getLayerName());
557
        query.append("\"");
558

    
559
        if (featureQueryOrder != null && featureQueryOrder.iterator().hasNext()) {
560
            query.append(" ORDER BY ");
561
            Iterator iterator = featureQueryOrder.iterator();
562
            while (iterator.hasNext()) {
563
                FeatureQueryOrderMember member = (FeatureQueryOrderMember) iterator.next();
564

    
565
                if (member.hasEvaluator()) {
566
                    // TODO
567
                } else {
568
                    query.append("\"");
569
                    query.append(member.getAttributeName());
570
                    query.append("\"");
571
                }
572
                if (member.getAscending()) {
573
                    query.append(" ASC");
574
                } else {
575
                    query.append(" DESC");
576
                }
577
                if (iterator.hasNext()) {
578
                    query.append(", ");
579
                } else {
580
                    query.append(' ');
581
                    break;
582
                }
583
            }
584
        }
585

    
586
        return query.toString();
587
    }
588

    
589
    @Override
590
    protected void doDispose() throws BaseException {
591
        super.doDispose();
592
        getResource().removeConsumer(this);
593
        this.resourceProvider = null;
594
        getDataSource().delete();
595
        this.envelope = null;
596
        this.newLayer = null;
597
        this.dataSource = null;
598
        this.opened = false;
599
        this.updateSupport = null;
600
    }
601

    
602
    @Override
603
    public boolean closeResourceRequested(ResourceProvider resource) {
604

    
605
        try {
606
            getDataSource().delete();
607
        } catch (OGRUnsupportedFormatException e) {
608
            LOG.warn(String.format("Can not close resource requested %1s", resource), e);
609
        }
610
        this.envelope = null;
611
        this.newLayer = null;
612
        this.dataSource = null;
613
        this.opened = false;
614
        this.updateSupport = null;
615
        return true;
616
    }
617

    
618
    @Override
619
    public void resourceChanged(ResourceProvider resource) {
620

    
621
        try {
622
            getDataSource().delete();
623
        } catch (OGRUnsupportedFormatException e) {
624
            LOG.warn(String.format("Can not close resource requested %1s", resource), e);
625
        }
626
        this.envelope = null;
627
        this.newLayer = null;
628
        this.dataSource = null;
629
        this.opened = false;
630
        this.updateSupport = null;
631
    }
632
}