Revision 316

View differences:

tags/org.gvsig.gdal-1.0.46/org.gvsig.gdal.prov/org.gvsig.gdal.prov.ogr/src/main/java/org/gvsig/gdal/prov/ogr/OGRLibrary.java
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 org.apache.commons.lang3.StringUtils;
27
import org.gdal.ogr.DataSource;
28
import org.gdal.ogr.FeatureDefn;
29
import org.gdal.ogr.GeomFieldDefn;
30
import org.gdal.ogr.Layer;
31
import org.gdal.ogr.ogr;
32
import org.gvsig.fmap.dal.DALFileLibrary;
33
import org.gvsig.fmap.dal.DALFileLocator;
34
import org.gvsig.fmap.dal.DALLibrary;
35
import org.gvsig.fmap.dal.DALLocator;
36
import org.gvsig.fmap.dal.FileHelper;
37
import org.gvsig.fmap.dal.resource.spi.ResourceManagerProviderServices;
38
import org.gvsig.fmap.dal.spi.DataManagerProviderServices;
39
import org.gvsig.metadata.MetadataLibrary;
40
import org.gvsig.metadata.exceptions.MetadataException;
41
import org.gvsig.tools.ToolsLocator;
42
import org.gvsig.tools.dynobject.DynClass;
43
import org.gvsig.tools.dynobject.DynField;
44
import org.gvsig.tools.dynobject.DynField_v2;
45
import org.gvsig.tools.dynobject.DynField_v2.AvailableValuesProvider;
46
import org.gvsig.tools.dynobject.DynObject;
47
import org.gvsig.tools.dynobject.DynObjectManager;
48
import org.gvsig.tools.dynobject.DynObjectValueItem;
49
import org.gvsig.tools.library.AbstractLibrary;
50
import org.gvsig.tools.library.LibraryException;
51
import org.gvsig.tools.persistence.PersistenceManager;
52

  
53
/**
54
 * 
55
 * @author <a href="mailto:lmarques@disid.com">Lluis Marques</a>
56
 *
57
 */
58
public class OGRLibrary extends AbstractLibrary {
59

  
60
    @Override
61
    public void doRegistration() {
62
        registerAsImplementationOf(OGRLibrary.class);
63
        require(DALLibrary.class);
64
        require(DALFileLibrary.class);
65
        require(MetadataLibrary.class);
66
    }
67

  
68
    @Override
69
    protected void doInitialize() throws LibraryException {
70

  
71
        // Register all drivers
72
        ogr.RegisterAll();
73
    }
74

  
75
    @Override
76
    protected void doPostInitialize() throws LibraryException {
77

  
78
        // Register OGR parameters definition
79
        FileHelper.registerParametersDefinition(OGRDataStoreParameters.PARAMETERS_DEFINITION_NAME,
80
            OGRDataStoreParameters.class, "OGRDataStoreParameters.xml");
81

  
82
        FileHelper.registerParametersDefinition(
83
            OGRNewDataStoreParameters.PARAMETERS_DEFINITION_NAME, OGRNewDataStoreParameters.class,
84
            "OGRNewDataStoreParameters.xml");
85

  
86
        FileHelper.registerParametersDefinition(
87
            OGRDataExplorerParameters.PARAMETERS_DEFINITION_NAME, OGRDataExplorerParameters.class,
88
            "OGRExplorerParameters.xml");
89

  
90
        // Register OGR metadata definition
91
        try {
92
            FileHelper.registerMetadataDefinition(OGRDataStoreProvider.METADATA_DEFINITION_NAME,
93
                OGRDataStoreProvider.class, "OGRMetadata.xml");
94
        } catch (MetadataException e) {
95
            throw new LibraryException(getClass(), e);
96
        }
97

  
98
        // Register OGR provider factory
99
        DataManagerProviderServices dataman =
100
            (DataManagerProviderServices) DALLocator.getDataManager();
101
        if (!dataman.getStoreProviders().contains(OGRDataStoreProvider.NAME)) {
102
            dataman.registerStoreProviderFactory(new BasicOGRDataStoreProviderFactory(
103
                OGRDataStoreProvider.NAME, OGRDataStoreProvider.DESCRIPTION));
104
        }
105

  
106
        // Register OGR data explorer provider
107
        if (!dataman.getExplorerProviders().contains(OGRDataExplorer.NAME)) {
108
            dataman.registerExplorerProvider(OGRDataExplorer.NAME, OGRDataExplorer.class,
109
                OGRDataExplorerParameters.class);
110
        }
111

  
112
        // Register OGR file system server provider
113
        DALFileLocator.getFilesystemServerExplorerManager().registerProvider(
114
            OGRDataStoreProvider.NAME, OGRDataStoreProvider.DESCRIPTION,
115
            OGRFilesystemServerProvider.class);
116

  
117
        DynObjectManager dynMan = ToolsLocator.getDynObjectManager();
118
        DynClass dynClass = dynMan.get(OGRDataStoreProvider.METADATA_DEFINITION_NAME);
119
        if (dynClass == null) {
120
            dynClass = dynMan.add(OGRDataStoreProvider.METADATA_DEFINITION_NAME);
121

  
122
        }
123

  
124
        // Register OGR resource provider
125
        ResourceManagerProviderServices resman =
126
            (ResourceManagerProviderServices) DALLocator.getResourceManager();
127
        if (!resman.getResourceProviders().contains(OGRResource.NAME)) {
128
            resman.register(OGRResource.NAME, OGRResource.DESCRIPTION, OGRResource.class,
129
                OGRResourceParameters.class);
130
        }
131

  
132
        // Register persistence definition of OGR resource parameters
133
        OGRResourceParameters.registerPersistenceDefinition();
134

  
135
        fixDataParameters();
136
    }
137

  
138
    private void fixDataParameters() {
139
        
140
        // XXX: This code is commented because until version of gvSIG tools at
141
        // gvSIG Desktop POM is greater or equal to 3.0.78. If the version is
142
        // greater or equals remove this comment and uncomment code.
143
        
144
        
145
        // DynObjectManager dynObjectManager =
146
        // ToolsLocator.getDynObjectManager();
147
        // DynClass dynClass =
148
        // dynObjectManager.get(PersistenceManager.PERSISTENCE_NAMESPACE,
149
        // OGRDataStoreParameters.PARAMETERS_DEFINITION_NAME);
150
        // DynField_v2 dynField = (DynField_v2)
151
        // dynClass.getDynField("defaultGeometryField");
152
        // dynField.setAvailableValuesProvider(new AvailableValuesProvider() {
153
        //
154
        // @Override
155
        // public DynObjectValueItem[] getValues(DynField field, DynObject
156
        // dynObject) {
157
        //
158
        // if (dynObject instanceof OGRDataStoreParameters) {
159
        //
160
        // DataSource dataSource = null;
161
        // try {
162
        // // Open connection string
163
        // OGRDataStoreParameters ogrParameters = (OGRDataStoreParameters)
164
        // dynObject;
165
        // if (StringUtils.isNotBlank(ogrParameters.getConnectionString())) {
166
        // dataSource = ogr.Open(ogrParameters.getConnectionString());
167
        // } else if (ogrParameters.getFile() != null
168
        // && ogrParameters.getFile().exists()) {
169
        // dataSource = ogr.Open(ogrParameters.getFile().getAbsolutePath());
170
        // }
171
        //
172
        // // Get layer
173
        // Layer layer = null;
174
        // if (StringUtils.isNotBlank(ogrParameters.getLayerName())) {
175
        // layer = dataSource.GetLayerByName(ogrParameters.getLayerName());
176
        // }
177
        //
178
        // // Get geometry fields
179
        // if (layer != null) {
180
        // FeatureDefn layerDefn = layer.GetLayerDefn();
181
        // DynObjectValueItem[] valueItems =
182
        // new DynObjectValueItem[layerDefn.GetGeomFieldCount()];
183
        // for (int i = 0; i < layerDefn.GetGeomFieldCount(); i++) {
184
        // GeomFieldDefn geomFieldDefn = layerDefn.GetGeomFieldDefn(i);
185
        // valueItems[i] = new DynObjectValueItem(geomFieldDefn.GetName());
186
        // }
187
        //
188
        // return valueItems;
189
        // }
190
        // } finally {
191
        // // Free native resources
192
        // dataSource.delete();
193
        // }
194
        // }
195
        // return null;
196
        // }
197
        //
198
        // });
199
    }
200
}
tags/org.gvsig.gdal-1.0.46/org.gvsig.gdal.prov/org.gvsig.gdal.prov.ogr/src/main/java/org/gvsig/gdal/prov/ogr/OGRNewDataStoreParameters.java
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.List;
27
import java.util.Vector;
28

  
29
import org.gvsig.fmap.dal.feature.EditableFeatureType;
30
import org.gvsig.fmap.dal.feature.FeatureType;
31
import org.gvsig.fmap.dal.feature.NewFeatureStoreParameters;
32
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
33
import org.gvsig.tools.ToolsLocator;
34
import org.gvsig.tools.dynobject.DelegatedDynObject;
35

  
36
/**
37
 * 
38
 * @author <a href="mailto:lmarques@disid.com">Lluis Marques</a>
39
 *
40
 */
41
public class OGRNewDataStoreParameters extends OGRDataStoreParameters implements
42
    NewFeatureStoreParameters {
43

  
44
    /**
45
     * 
46
     */
47
    public static final String PARAMETERS_DEFINITION_NAME = "OGRNewDataStoreParameters";
48

  
49
    /**
50
     * 
51
     */
52
    public static final String DRIVER_NAME_PARAMETER_NAME = "driverName";
53

  
54
    /**
55
     * 
56
     */
57
    public static final String DATASET_CREATION_OPTION_PARAMETER_NAME = "datasetCreationOptions";
58

  
59
    /**
60
     * 
61
     */
62
    public OGRNewDataStoreParameters() {
63
        parameters =
64
            (DelegatedDynObject) ToolsLocator.getDynObjectManager().createDynObject(
65
                ToolsLocator.getPersistenceManager().getDefinition(PARAMETERS_DEFINITION_NAME));
66
        this.setDynValue(DataStoreProviderServices.PROVIDER_PARAMTER_NAME,
67
            OGRDataStoreProvider.NAME);
68
    }
69

  
70
    @Override
71
    public void setDefaultFeatureType(FeatureType defaultFeatureType) {
72
        this.setDynValue(FEATURETYPE_PARAMTER_NAME, defaultFeatureType);
73
    }
74

  
75
    @Override
76
    public EditableFeatureType getDefaultFeatureType() {
77
        return (EditableFeatureType) this.getDynValue(FEATURETYPE_PARAMTER_NAME);
78
    }
79

  
80
    /**
81
     * @param driverName
82
     *            Sets driver that will be used to create new stores
83
     */
84
    public void setDriverName(String driverName) {
85
        this.setDynValue(DRIVER_NAME_PARAMETER_NAME, driverName);
86
    }
87

  
88
    /**
89
     * @return Name of driver to create new data stores
90
     */
91
    public String getDriverName() {
92
        return (String) this.getDynValue(DRIVER_NAME_PARAMETER_NAME);
93
    }
94

  
95
    /**
96
     * 
97
     * @param options
98
     *            Set dataset creation options
99
     */
100
    @SuppressWarnings("rawtypes")
101
    public void setDatasetCreationOptions(List options) {
102
        this.setDynValue(DATASET_CREATION_OPTION_PARAMETER_NAME, options);
103
    }
104

  
105
    /**
106
     * @return Dataset creation options
107
     */
108
    @SuppressWarnings("rawtypes")
109
    public List getDatasetCreationOptions() {
110
        return (Vector) this.getDynValue(DATASET_CREATION_OPTION_PARAMETER_NAME);
111
    }
112
}
tags/org.gvsig.gdal-1.0.46/org.gvsig.gdal.prov/org.gvsig.gdal.prov.ogr/src/main/java/org/gvsig/gdal/prov/ogr/OGRFilesystemServerProvider.java
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.io.File;
27
import java.util.List;
28
import java.util.Vector;
29

  
30
import org.apache.commons.lang3.StringUtils;
31
import org.cresques.cts.ICRSFactory;
32
import org.cresques.cts.IProjection;
33
import org.gdal.ogr.DataSource;
34
import org.gdal.ogr.Driver;
35
import org.gdal.ogr.FieldDefn;
36
import org.gdal.ogr.GeomFieldDefn;
37
import org.gdal.ogr.Layer;
38
import org.gdal.ogr.ogr;
39
import org.gdal.ogr.ogrConstants;
40
import org.gdal.osr.SpatialReference;
41
import org.gvsig.fmap.dal.DALLocator;
42
import org.gvsig.fmap.dal.DataStoreParameters;
43
import org.gvsig.fmap.dal.NewDataStoreParameters;
44
import org.gvsig.fmap.dal.exception.CreateException;
45
import org.gvsig.fmap.dal.exception.DataException;
46
import org.gvsig.fmap.dal.exception.InitializeException;
47
import org.gvsig.fmap.dal.exception.RemoveException;
48
import org.gvsig.fmap.dal.feature.EditableFeatureType;
49
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
50
import org.gvsig.fmap.dal.resource.ResourceAction;
51
import org.gvsig.fmap.dal.resource.exception.ResourceExecuteException;
52
import org.gvsig.fmap.dal.resource.file.FileResource;
53
import org.gvsig.fmap.dal.resource.spi.ResourceConsumer;
54
import org.gvsig.fmap.dal.resource.spi.ResourceProvider;
55
import org.gvsig.fmap.dal.serverexplorer.filesystem.impl.AbstractFilesystemServerExplorerProvider;
56
import org.gvsig.fmap.dal.serverexplorer.filesystem.spi.FilesystemServerExplorerProvider;
57
import org.gvsig.fmap.dal.serverexplorer.filesystem.spi.FilesystemServerExplorerProviderServices;
58
import org.slf4j.Logger;
59
import org.slf4j.LoggerFactory;
60

  
61
/**
62
 *
63
 * @author <a href="mailto:lmarques@disid.com">Lluis Marques</a>
64
 *
65
 */
66
public class OGRFilesystemServerProvider extends AbstractFilesystemServerExplorerProvider implements
67
    FilesystemServerExplorerProvider, ResourceConsumer {
68

  
69
    private static final Logger LOG = LoggerFactory.getLogger(OGRFilesystemServerProvider.class);
70

  
71
    private FilesystemServerExplorerProviderServices serverExplorer;
72

  
73
    @Override
74
    public String getDataStoreProviderName() {
75
        return OGRDataStoreProvider.NAME;
76
    }
77

  
78
    @Override
79
    public String getDescription() {
80
        return OGRDataStoreProvider.DESCRIPTION;
81
    }
82

  
83
    @Override
84
    public boolean accept(File pathname) {
85
        if (pathname.isFile() && ogr.Open(pathname.getAbsolutePath(), 1)!=null){
86
            return true;
87
        }
88
        return false;
89
    }
90

  
91
    @Override
92
    public boolean closeResourceRequested(ResourceProvider resource) {
93
        // Do nothing
94
        return true;
95
    }
96

  
97
    @Override
98
    public void resourceChanged(ResourceProvider resource) {
99
        // Do nothing
100
    }
101

  
102
    @Override
103
    public void initialize(FilesystemServerExplorerProviderServices serverExplorer) {
104
        this.serverExplorer = serverExplorer;
105
    }
106

  
107
    @Override
108
    public boolean canCreate() {
109
        throw new UnsupportedOperationException();
110
    }
111

  
112
    @Override
113
    public void create(NewDataStoreParameters parameters, boolean overwrite) throws CreateException {
114

  
115
        if (parameters instanceof OGRNewDataStoreParameters) {
116

  
117
            final OGRNewDataStoreParameters newOGRDataStoreParameters =
118
                (OGRNewDataStoreParameters) parameters;
119

  
120
            final File file = newOGRDataStoreParameters.getFile();
121

  
122
            if (file.isFile() && file.exists()) {
123
                if (overwrite) {
124
                    // Deleting existing file
125
                    try {
126
                        this.remove(newOGRDataStoreParameters);
127
                    } catch (RemoveException e) {
128
                        throw new CreateException("Can not overwrite file", e);
129
                    }
130
                } else {
131
                    throw new CreateException(file.getAbsolutePath(), new IllegalArgumentException(
132
                        String.format("%1s exists and overwrite option is false",
133
                            file.getAbsolutePath())));
134
                }
135
            }
136

  
137
            try {
138
                final FileResource resource =
139
                    (FileResource) serverExplorer.getServerExplorerProviderServices()
140
                        .createResource(FileResource.NAME, new Object[] { file.getAbsolutePath() });
141

  
142
                resource.addConsumer(this);
143
                resource.execute(new ResourceAction() {
144

  
145
                    @Override
146
                    public Object run() throws Exception {
147

  
148
                        String driverName = newOGRDataStoreParameters.getDriverName();
149
                        Driver driver = ogr.GetDriverByName(driverName);
150
                        if (driver == null || StringUtils.isBlank(driverName)) {
151
                            throw new IllegalArgumentException(
152
                                "Driver name can not be blank and driver must exist.");
153
                        }
154

  
155
                        List options = newOGRDataStoreParameters.getDatasetCreationOptions();
156
                        DataSource dataSource = null;
157
                        if (options == null) {
158
                            dataSource =
159
                                driver.CreateDataSource(resource.getFile().getAbsolutePath());
160
                        } else {
161
                            dataSource =
162
                                driver.CreateDataSource(resource.getFile().getAbsolutePath(),
163
                                    new Vector<String>(options));
164
                        }
165

  
166
                        if (dataSource == null) {
167
                            LOG.error("Can not open datasource from {} and {} options", resource
168
                                .getFile().getAbsoluteFile(), options);
169
                            throw new ResourceExecuteException(resource, null);
170
                        }
171

  
172
                        String layerName = newOGRDataStoreParameters.getLayerName();
173
                        if (StringUtils.isBlank(layerName)) {
174
                            layerName = file.getName();
175
                        }
176

  
177
                        // Check if layer already exist at dataSource
178
                        Layer existingLayer = dataSource.GetLayerByName(layerName);
179
                        if (existingLayer != null) {
180
                            for (int i = 0; i < dataSource.GetLayerCount(); i++) {
181
                                if (dataSource.GetLayerByIndex(i).GetName()
182
                                    .equals(existingLayer.GetName())) {
183
                                    dataSource.DeleteLayer(i); // Delete it if
184
                                                               // exist
185
                                    break;
186
                                }
187
                            }
188
                        }
189

  
190
                        OGRConverter converter = new OGRConverter();
191

  
192
                        FeatureAttributeDescriptor geometryAttribute =
193
                            newOGRDataStoreParameters.getDefaultFeatureType()
194
                                .getDefaultGeometryAttribute();
195
                        Integer ogrType = null;
196
                        SpatialReference srs = null;
197

  
198
                        // Determinate if featureType has SRS and geometry type
199
                        // defined
200
                        if (geometryAttribute != null) {
201
                            int type = geometryAttribute.getGeomType().getType();
202
                            ogrType = converter.convertToOGRGeomType(type);
203

  
204
                            IProjection projection = geometryAttribute.getSRS();
205
                            if (projection == null && newOGRDataStoreParameters.getCRS() != null) {
206
                                projection = newOGRDataStoreParameters.getCRS();
207
                                srs =
208
                                    new SpatialReference(projection.export(ICRSFactory.FORMAT_WKT));
209
                            }
210
                        }
211

  
212
                        Layer layer = null;
213
                        if (srs == null) {
214
                            layer = dataSource.CreateLayer(layerName);
215
                        } else if (ogrType == null) {
216
                            layer = dataSource.CreateLayer(layerName, srs);
217
                        } else {
218
                            layer = dataSource.CreateLayer(layerName, srs, ogrType);
219
                        }
220

  
221
                        // Creating fields
222
                        if (layer.TestCapability(ogrConstants.OLCCreateField)) {
223
                            List<FieldDefn> fields =
224
                                converter.convertFields(newOGRDataStoreParameters
225
                                    .getDefaultFeatureType());
226
                            for (FieldDefn fieldDefn : fields) {
227
                                layer.CreateField(fieldDefn);
228
                            }
229
                        } else {
230
                            LOG.warn("{} driver does not support creation of fields",
231
                                driver.getName());
232
                        }
233

  
234
                        // Creating additional geometry fields, skipping default
235
                        // geometry column.
236
                        // When a OGR Layer is created, if feature type has
237
                        // default geometry column
238
                        // it will be set when layer is created
239
                        if (layer.TestCapability(ogrConstants.OLCCreateGeomField)) {
240
                            List<GeomFieldDefn> geomFields =
241
                                converter.convertGeometryFields(
242
                                    newOGRDataStoreParameters.getDefaultFeatureType(), false);
243
                            for (GeomFieldDefn geomFieldDefn : geomFields) {
244
                                layer.CreateGeomField(geomFieldDefn);
245
                            }
246
                        } else {
247
                            LOG.warn(
248
                                "{} driver does not support creation of geometry fields, only default"
249
                                    + " OGR geometry field has been created", driver.getName());
250
                        }
251

  
252
                        // Release native resource to close file
253
                        dataSource.delete();
254
                        return null;
255
                    }
256
                });
257
            } catch (InitializeException e) {
258
                throw new CreateException("Can not create file resource to create it", e);
259
            }
260
        }
261

  
262
    }
263

  
264
    @Override
265
    public NewDataStoreParameters getCreateParameters() throws DataException {
266
        OGRNewDataStoreParameters newParameters = new OGRNewDataStoreParameters();
267
        EditableFeatureType editableFeatureType = DALLocator.getDataManager().createFeatureType();
268
        newParameters.setDefaultFeatureType(editableFeatureType);
269
        return newParameters;
270
    }
271

  
272
    @Override
273
    public void remove(DataStoreParameters parameters) throws RemoveException {
274

  
275
        if (parameters instanceof OGRNewDataStoreParameters) {
276

  
277
            final OGRNewDataStoreParameters newOGRDataStoreParameters =
278
                (OGRNewDataStoreParameters) parameters;
279

  
280
            File file = newOGRDataStoreParameters.getFile();
281

  
282
            if (!file.exists() && !file.canWrite()) {
283
                throw new RemoveException(file.getAbsolutePath(), new IllegalArgumentException(
284
                    String.format("%1s does not exist", file.getAbsolutePath())));
285
            }
286

  
287
            try {
288
                final FileResource resource =
289
                    (FileResource) serverExplorer.getServerExplorerProviderServices()
290
                        .createResource(FileResource.NAME, new Object[] { file.getAbsolutePath() });
291

  
292
                resource.addConsumer(this);
293
                resource.execute(new ResourceAction() {
294

  
295
                    @Override
296
                    public Object run() throws Exception {
297
                        resource.closeRequest();
298
                        String driverName = newOGRDataStoreParameters.getDriverName();
299
                        Driver driver = ogr.GetDriverByName(driverName);
300
                        if (driver == null || StringUtils.isBlank(driverName)) {
301
                            LOG.warn("Driver name is blank or driver null, trying to get it opening datasource of resource");
302
                            DataSource dataSource = ogr.Open(resource.getFile().getAbsolutePath());
303
                            if (dataSource == null) {
304
                                LOG.error("Can not determiante driver to remove resource");
305
                                throw new RemoveException(resource.getName(), null);
306
                            }
307
                            driver = dataSource.GetDriver();
308
                        }
309

  
310
                        if (driver.TestCapability(ogrConstants.ODrCDeleteDataSource)) {
311
                            driver.DeleteDataSource(resource.getFile().getAbsolutePath());
312
                        } else {
313
                            LOG.error("{} driver does not support delete data source",
314
                                driver.getName());
315
                            throw new RemoveException(resource.getFile().getAbsolutePath(), null);
316
                        }
317
                        return null;
318
                    }
319
                });
320
                resource.addConsumer(this);
321
            } catch (InitializeException e) {
322
                throw new RemoveException("Can not create file resource to remove it", e);
323
            }
324
        }
325
    }
326

  
327
    @Override
328
    public boolean canCreate(NewDataStoreParameters parameters) {
329
        if (parameters instanceof OGRNewDataStoreParameters) {
330

  
331
            OGRNewDataStoreParameters newOGRDataStoreParameters =
332
                (OGRNewDataStoreParameters) parameters;
333

  
334
            String driverName = newOGRDataStoreParameters.getDriverName();
335
            Driver driver = null;
336
            if (StringUtils.isNotBlank(driverName)) {
337
                driver = ogr.GetDriverByName(driverName);
338
            } else {
339
                return false;
340
            }
341

  
342
            if (driver.TestCapability(ogrConstants.ODrCCreateDataSource)
343
                && driver.TestCapability(ogrConstants.OLCCreateField)) {
344

  
345
                File file = newOGRDataStoreParameters.getFile();
346
                if (file != null && file.canWrite()) {
347
                    return true;
348
                }
349
            }
350
        }
351
        return false;
352
    }
353
}
tags/org.gvsig.gdal-1.0.46/org.gvsig.gdal.prov/org.gvsig.gdal.prov.ogr/src/main/java/org/gvsig/gdal/prov/ogr/OGRConverter.java
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.Calendar;
28
import java.util.Date;
29
import java.util.List;
30

  
31
import org.apache.commons.lang3.StringUtils;
32
import org.cresques.cts.ICRSFactory;
33
import org.cresques.cts.IProjection;
34
import org.gdal.ogr.DataSource;
35
import org.gdal.ogr.Feature;
36
import org.gdal.ogr.FeatureDefn;
37
import org.gdal.ogr.FieldDefn;
38
import org.gdal.ogr.GeomFieldDefn;
39
import org.gdal.ogr.Layer;
40
import org.gdal.ogr.ogr;
41
import org.gdal.ogr.ogrConstants;
42
import org.gdal.osr.SpatialReference;
43
import org.gvsig.fmap.crs.CRSFactory;
44
import org.gvsig.fmap.dal.DALLocator;
45
import org.gvsig.fmap.dal.DataTypes;
46
import org.gvsig.fmap.dal.feature.EditableFeatureAttributeDescriptor;
47
import org.gvsig.fmap.dal.feature.EditableFeatureType;
48
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
49
import org.gvsig.fmap.dal.feature.FeatureType;
50
import org.gvsig.fmap.dal.feature.spi.DefaultFeatureProvider;
51
import org.gvsig.fmap.dal.feature.spi.FeatureProvider;
52
import org.gvsig.fmap.geom.Geometry;
53
import org.gvsig.fmap.geom.Geometry.SUBTYPES;
54
import org.gvsig.fmap.geom.Geometry.TYPES;
55
import org.gvsig.fmap.geom.GeometryLocator;
56
import org.gvsig.fmap.geom.GeometryManager;
57
import org.gvsig.fmap.geom.operation.GeometryOperationException;
58
import org.gvsig.fmap.geom.operation.GeometryOperationNotSupportedException;
59
import org.gvsig.fmap.geom.type.GeometryType;
60
import org.gvsig.fmap.geom.type.GeometryTypeNotSupportedException;
61
import org.gvsig.fmap.geom.type.GeometryTypeNotValidException;
62
import org.gvsig.tools.exception.BaseException;
63
import org.slf4j.Logger;
64
import org.slf4j.LoggerFactory;
65

  
66
/**
67
 * Converter class used to parse OGR layer defn, feature, types... to gvSIG
68
 * objects and constant.
69
 *
70
 * @author <a href="mailto:lmarques@disid.com">Lluis Marques</a>
71
 *
72
 */
73
public class OGRConverter {
74

  
75
    /**
76
     * Default geometry column name used when the geometry column of layer does
77
     * not have name. This is necessary to create FeatureType and it must take
78
     * into account when feature geometry is requested.
79
     */
80
    private final String DEFAULT_GEOMETRY_COLUMN_NAME = "ogr_geometry";
81

  
82
    private static final Logger LOG = LoggerFactory.getLogger(OGRConverter.class);
83

  
84
    /**
85
     *
86
     */
87
    public OGRConverter() {
88

  
89
    }
90

  
91
    /**
92
     * Converts {@link FeatureDefn} to {@link FeatureType} and sets
93
     * default geometry field to created {@link FeatureType}.
94
     *
95
     * @param featureDefn
96
     *            OGR definition to be converted
97
     * @param defaultGeometryField
98
     *            Default geometry field. If it is not founded, this method will
99
     *            take the first geometry field.
100
     * @return FeatureType Feature type equivalent
101
     * @throws GeometryTypeNotSupportedException
102
     *             If there are problems parsing OGR geometry
103
     * @throws GeometryTypeNotValidException
104
     *             If type of OGR Geometry is not supported
105
     */
106
    public FeatureType convert(FeatureDefn featureDefn, String defaultGeometryField)
107
        throws GeometryTypeNotSupportedException, GeometryTypeNotValidException {
108

  
109
        EditableFeatureType editableFeatureType = DALLocator.getDataManager().createFeatureType();
110
        editableFeatureType.setHasOID(true);
111

  
112
        for (int i = 0; i < featureDefn.GetFieldCount(); i++) {
113
            FieldDefn fieldDefn = featureDefn.GetFieldDefn(i);
114

  
115
            EditableFeatureAttributeDescriptor attributeDescriptor =
116
                editableFeatureType.add(fieldDefn.GetName(),
117
                    this.convertToDataType(fieldDefn.GetFieldType()));
118
            attributeDescriptor.setPrecision(fieldDefn.GetPrecision());
119
        }
120

  
121
        for (int i = 0; i < featureDefn.GetGeomFieldCount(); i++) {
122
            GeomFieldDefn geomFieldDefn = featureDefn.GetGeomFieldDefn(i);
123

  
124
            String name = null;
125
            if (StringUtils.isBlank(geomFieldDefn.GetName())) {
126
                // Set default geometry column name
127
                name = DEFAULT_GEOMETRY_COLUMN_NAME;
128
            } else {
129
                name = geomFieldDefn.GetName();
130
            }
131

  
132
            EditableFeatureAttributeDescriptor attributeDescriptor =
133
                editableFeatureType.add(name, DataTypes.GEOMETRY);
134

  
135
            // GDAL 1.11.2 Only supports 2D geometries
136
            GeometryManager geometryManager = GeometryLocator.getGeometryManager();
137
            GeometryType geometryType =
138
                geometryManager.getGeometryType(
139
                    this.convertToGeomType(geomFieldDefn.GetFieldType()), SUBTYPES.GEOM2D);
140
            attributeDescriptor.setGeometryType(geometryType);
141

  
142
            if (geomFieldDefn.GetSpatialRef() != null) {
143
                IProjection projection =
144
                    CRSFactory.getCRSFactory().get(ICRSFactory.FORMAT_WKT,
145
                        geomFieldDefn.GetSpatialRef().ExportToWkt());
146
                attributeDescriptor.setSRS(projection);
147
            }
148
        }
149

  
150
        if (editableFeatureType.getAttributeDescriptor(defaultGeometryField) != null) {
151
            editableFeatureType.setDefaultGeometryAttributeName(defaultGeometryField);
152
        } else {
153
            FeatureAttributeDescriptor[] attributeDescriptors =
154
                editableFeatureType.getAttributeDescriptors();
155
            for (int i = 0; i < attributeDescriptors.length; i++) {
156

  
157
                if (attributeDescriptors[i].getDataType().getType() != DataTypes.GEOMETRY) {
158
                    continue;
159
                }
160

  
161
                if (attributeDescriptors[i].getGeomType().getType() == convertToGeomType(featureDefn
162
                    .GetGeomType())) {
163
                    editableFeatureType.setDefaultGeometryAttributeName(attributeDescriptors[i]
164
                        .getName());
165
                    LOG.warn(
166
                        "Default geometry field {} has not been found. Setting \"{}\" as default geometry field",
167
                        new Object[] { defaultGeometryField, attributeDescriptors[i].getName() });
168
                    break;
169
                }
170
            }
171

  
172
            if (editableFeatureType.getDefaultGeometryAttributeName() == null) {
173
                LOG.warn("The default geometry field can not be set");
174
            }
175
        }
176

  
177
        return editableFeatureType.getNotEditableCopy();
178
    }
179

  
180
    /**
181
     * Converts {@link FeatureAttributeDescriptor} of {@link FeatureType} to
182
     * {@link FieldDefn}
183
     *
184
     * @param featureType
185
     *            Fields to be converted
186
     * @return FieldDefn list OGR fields
187
     */
188
    public List<FieldDefn> convertFields(FeatureType featureType) {
189

  
190
        List<FieldDefn> fields = new ArrayList<FieldDefn>();
191

  
192
        for (int i = 0; i < featureType.getAttributeDescriptors().length; i++) {
193
            FeatureAttributeDescriptor attributeDescriptor = featureType.getAttributeDescriptor(i);
194
            if (attributeDescriptor.getType() != DataTypes.GEOMETRY) {
195
                fields.add(convertField(attributeDescriptor));
196
            }
197
        }
198
        return fields;
199
    }
200

  
201
    /**
202
     * Converts {@link FeatureAttributeDescriptor} to {@link FieldDefn}
203
     *
204
     * @param attDescriptor
205
     * @return FieldDefn
206
     */
207
    public FieldDefn convertField(FeatureAttributeDescriptor attDescriptor) {
208
        if (attDescriptor != null) {
209
            FieldDefn fieldDefn =
210
                new FieldDefn(attDescriptor.getName(), this.convertToOGRType(attDescriptor
211
                    .getType()));
212
            fieldDefn.SetPrecision(attDescriptor.getPrecision());
213
            return fieldDefn;
214
        }
215
        return null;
216
    }
217

  
218
    /**
219
     * Converts geometry {@link FeatureAttributeDescriptor} of
220
     * {@link FeatureType} to {@link GeomFieldDefn}
221
     *
222
     * @param featureType
223
     *            Geometry fields to be converted
224
     * @param convertDefaultGeometryColumn
225
     *            True if default geometry will be converted, otherwise default
226
     *            geometry field won't be converted.
227
     * @return GeomFieldDefn list OGR Geometry fields
228
     */
229
    public List<GeomFieldDefn> convertGeometryFields(FeatureType featureType,
230
        boolean convertDefaultGeometryColumn) {
231

  
232
        List<GeomFieldDefn> geometryFields = new ArrayList<GeomFieldDefn>();
233

  
234
        for (int i = 0; i < featureType.getAttributeDescriptors().length; i++) {
235
            FeatureAttributeDescriptor attributeDescriptor = featureType.getAttributeDescriptor(i);
236

  
237
            if (attributeDescriptor.getType() == DataTypes.GEOMETRY) {
238
                // Check if default geometry column must be converted too
239
                if (i != featureType.getDefaultGeometryAttributeIndex()
240
                    || (i == featureType.getDefaultGeometryAttributeIndex() && convertDefaultGeometryColumn)) {
241
                    geometryFields.add(convertGeomField(attributeDescriptor));
242
                }
243
            }
244
        }
245
        return geometryFields;
246
    }
247

  
248
    /**
249
     * Converts {@link FeatureAttributeDescriptor} to {@link GeomFieldDefn}
250
     *
251
     * @param attDescriptor
252
     *            Attribute to be converted
253
     * @return GeomFieldDefn OGR Geometry field
254
     */
255
    public GeomFieldDefn convertGeomField(FeatureAttributeDescriptor attDescriptor) {
256

  
257
        String name = attDescriptor.getName();
258
        if (attDescriptor.getName().equals(DEFAULT_GEOMETRY_COLUMN_NAME)) {
259
            name = "";
260
        }
261

  
262
        GeomFieldDefn geomFieldDefn =
263
            new GeomFieldDefn(name,
264
                this.convertToOGRGeomType(attDescriptor.getGeomType().getType()));
265

  
266
        if (attDescriptor.getSRS() != null) {
267
            SpatialReference srs =
268
                new SpatialReference(attDescriptor.getSRS().export(ICRSFactory.FORMAT_WKT));
269
            geomFieldDefn.SetSpatialRef(srs);
270
        }
271

  
272
        return geomFieldDefn;
273
    }
274

  
275
    /**
276
     * Converts {@link Feature} to {@link FeatureProvider}. If
277
     * {@link FeatureProvider} is null, it will be instantiated. This method
278
     * only takes into account the fields of received {@link FeatureType}.
279
     *
280
     * @param featureProvider
281
     *
282
     * @param featureType
283
     *            Type of feature provider
284
     * @param ogrFeature
285
     *            OGR Feature to be converted
286
     * @return FeatureProvider
287
     *         FeatureProvder with OGR Feature values
288
     */
289
    public FeatureProvider convert(FeatureProvider featureProvider, FeatureType featureType,
290
        Feature ogrFeature) {
291

  
292
        int fid = ogrFeature.GetFID();
293
        if (featureProvider == null) {
294
            featureProvider = new DefaultFeatureProvider(featureType, fid);
295
        } else {
296
            featureProvider.setOID(fid);
297
        }
298

  
299
        FeatureDefn defnRef = ogrFeature.GetDefnRef();
300
        FeatureAttributeDescriptor[] attributeDescriptors = featureType.getAttributeDescriptors();
301
        for (int i = 0; i < attributeDescriptors.length; i++) {
302

  
303
            if (attributeDescriptors[i].getDataType().getType() == DataTypes.GEOMETRY) {
304

  
305
                String name = attributeDescriptors[i].getName();
306

  
307
                org.gdal.ogr.Geometry ogrGeometry = null;
308
                int fieldIndex = -1;
309

  
310
                if (name.equals(DEFAULT_GEOMETRY_COLUMN_NAME)) {
311
                    // If geometry column name equals default column name,
312
                    // change it to empty string.
313
                    fieldIndex = defnRef.GetGeomFieldIndex("");
314
                } else {
315
                    fieldIndex = defnRef.GetGeomFieldIndex(name);
316
                }
317

  
318
                ogrGeometry = ogrFeature.GetGeomFieldRef(fieldIndex);
319
                if (ogrGeometry != null) {
320
                    Geometry geometry = null;
321
                    try {
322
                        geometry =
323
                            GeometryLocator.getGeometryManager().createFrom(
324
                                ogrGeometry.ExportToWkb());
325
                    } catch (BaseException e) {
326
                        LOG.warn(
327
                            String
328
                                .format(
329
                                    "Can not create geometry from %1s. Setting null value to geometry field",
330
                                    ogrGeometry.ExportToWkt()), e);
331
                        geometry = null;
332
                    }
333

  
334
                    if (attributeDescriptors[i].getName().equals(
335
                        featureType.getDefaultGeometryAttributeName())) {
336
                        featureProvider.setDefaultGeometry(geometry);
337
                    }
338

  
339
                    featureProvider.set(name, geometry);
340
                }
341

  
342
            } else {
343

  
344
                String name = attributeDescriptors[i].getName();
345
                int fieldIndex = defnRef.GetFieldIndex(name);
346
                FieldDefn fieldDefn = defnRef.GetFieldDefn(fieldIndex);
347
                int dataType = convertToDataType(fieldDefn.GetFieldType());
348

  
349
                Object value = null;
350

  
351
                if (dataType == DataTypes.INT) {
352
                    value = ogrFeature.GetFieldAsInteger(i);
353
                } else if (dataType == DataTypes.DOUBLE) {
354
                    value = ogrFeature.GetFieldAsDouble(i);
355
                } else {
356
                    value = ogrFeature.GetFieldAsString(i);
357
                }
358

  
359
                featureProvider.set(fieldDefn.GetName(), value);
360
            }
361
        }
362
        return featureProvider;
363
    }
364

  
365
    /**
366
     * Converts {@link FeatureProvider} to {@link Feature}.
367
     *
368
     * @param featureProvider
369
     *            Feature provider to be converted
370
     * @return Feature OGR Feature with feature provider values.
371
     * @throws GeometryOperationNotSupportedException
372
     *             If operation used to convert geometries is not supported
373
     * @throws GeometryOperationException
374
     *             If there are some problems converting geometries
375
     */
376
    public Feature convert(FeatureProvider featureProvider)
377
        throws GeometryOperationNotSupportedException, GeometryOperationException {
378

  
379
        if (featureProvider == null) {
380
            return null;
381
        }
382

  
383
        FeatureType featureType = featureProvider.getType();
384
        FeatureDefn featureDefn = new FeatureDefn();
385
        List<FieldDefn> fields = this.convertFields(featureType);
386
        for (FieldDefn fieldDefn : fields) {
387
            featureDefn.AddFieldDefn(fieldDefn);
388
        }
389

  
390
        List<GeomFieldDefn> geometryFields = this.convertGeometryFields(featureType, true);
391
        for (GeomFieldDefn geomFieldDefn : geometryFields) {
392
            featureDefn.AddGeomFieldDefn(geomFieldDefn);
393
        }
394

  
395
        Feature feature = new Feature(featureDefn);
396

  
397
        Integer oid = null;
398
        if (featureProvider.getOID() instanceof Integer) {
399
            oid = (Integer) featureProvider.getOID();
400
        } else if (featureProvider.getOID() instanceof Long) {
401
            oid = ((Long) featureProvider.getOID()).intValue();
402
        }
403

  
404
        feature.SetFID(oid);
405
        FeatureAttributeDescriptor[] attributeDescriptors = featureType.getAttributeDescriptors();
406
        for (int i = 0; i < attributeDescriptors.length; i++) {
407

  
408
            Integer fieldIndex = null;
409
            if (attributeDescriptors[i].getType() == DataTypes.GEOMETRY
410
                && attributeDescriptors[i].getName().equals(DEFAULT_GEOMETRY_COLUMN_NAME)) {
411
                fieldIndex = featureDefn.GetGeomFieldIndex("");
412
            } else if (attributeDescriptors[i].getType() == DataTypes.GEOMETRY) {
413
                fieldIndex = featureDefn.GetGeomFieldIndex(attributeDescriptors[i].getName());
414
            } else {
415
                fieldIndex = featureDefn.GetFieldIndex(attributeDescriptors[i].getName());
416
            }
417

  
418
            Object value = featureProvider.get(i);
419

  
420
            if (value == null) {
421
                continue;
422
            }
423

  
424
            if (attributeDescriptors[i].getType() == DataTypes.STRING) {
425
                feature.SetField(fieldIndex, (String) value);
426
            } else if (attributeDescriptors[i].getType() == DataTypes.DOUBLE) {
427
                feature.SetField(fieldIndex, (Double) value);
428
            } else if (attributeDescriptors[i].getType() == DataTypes.BOOLEAN) {
429
                feature.SetField(fieldIndex, ((Boolean) value).toString());
430
            } else if (attributeDescriptors[i].getType() == DataTypes.DATE) {
431
                Date date = (Date) value;
432
                Calendar calendar = Calendar.getInstance();
433
                calendar.setTime(date);
434
                feature.SetField(i, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
435
                    calendar.get(Calendar.DAY_OF_WEEK), calendar.get(Calendar.HOUR),
436
                    calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND), 0);
437
            } else if (attributeDescriptors[i].getType() == DataTypes.GEOMETRY) {
438
                org.gvsig.fmap.geom.Geometry geometry = (Geometry) value;
439
                if (geometry != null) {
440
                    org.gdal.ogr.Geometry ogrGeometry = null;
441
                    if (attributeDescriptors[i].getSRS() != null) {
442
                        IProjection projection = attributeDescriptors[i].getSRS();
443
                        SpatialReference srs =
444
                            new SpatialReference(projection.export(ICRSFactory.FORMAT_WKT));
445
                        ogrGeometry = ogr.CreateGeometryFromWkt(geometry.convertToWKT(), srs);
446
                        feature.SetGeomField(i, ogrGeometry);
447
                    } else {
448
                        ogrGeometry = ogr.CreateGeometryFromWkt(geometry.convertToWKT());
449
                        feature.SetGeomField(fieldIndex, ogrGeometry);
450
                    }
451
                }
452
            }
453
        }
454

  
455
        return feature;
456
    }
457

  
458
    /**
459
     * Convert gvSIG geometry type to OGR geometry type. See
460
     * {@link ogrConstants}.
461
     *
462
     * @param type
463
     *            A type of {@link TYPES}
464
     * @return int Equivalent type of {@link ogrConstants}
465
     */
466
    public int convertToOGRGeomType(int type) {
467

  
468
        switch (type) {
469
        case TYPES.POINT:
470
            return ogrConstants.wkbPoint;
471

  
472
        case TYPES.CURVE:
473
        case TYPES.LINE:
474
        case TYPES.CIRCLE:
475
        case TYPES.ARC:
476
        case TYPES.ELLIPSE:
477
        case TYPES.SPLINE:
478
        case TYPES.ELLIPTICARC:
479
        case TYPES.CIRCUMFERENCE:
480
        case TYPES.PERIELLIPSE:
481
            return ogrConstants.wkbLineString;
482

  
483
        case TYPES.SURFACE:
484
        case TYPES.POLYGON:
485
        case TYPES.FILLEDSPLINE:
486
            return ogrConstants.wkbPolygon;
487

  
488
        case TYPES.AGGREGATE:
489
            return ogrConstants.wkbGeometryCollection;
490

  
491
        case TYPES.MULTIPOINT:
492
            return ogrConstants.wkbMultiPoint;
493

  
494
        case TYPES.MULTICURVE:
495
        case TYPES.MULTILINE:
496
            return ogrConstants.wkbMultiLineString;
497

  
498
        case TYPES.MULTISURFACE:
499
        case TYPES.MULTIPOLYGON:
500
            return ogrConstants.wkbMultiPolygon;
501

  
502
        case TYPES.NULL:
503
            return ogrConstants.wkbNone;
504

  
505
        case TYPES.GEOMETRY:
506
        case TYPES.MULTISOLID:
507
        case TYPES.SOLID:
508
        case TYPES.COMPLEX:
509
        default:
510
            return ogrConstants.wkbUnknown;
511
        }
512
    }
513

  
514
    /**
515
     * Convert OGR geometry type to gvSIG geometry type. See {@link TYPES}.
516
     *
517
     * @param type
518
     *            A type of {@link ogrConstants}
519
     * @return int Equivalent type of {@link TYPES}
520
     */
521
    public int convertToGeomType(int type) {
522

  
523
        switch (type) {
524
        case ogrConstants.wkbPoint:
525
            return TYPES.POINT;
526

  
527
        case ogrConstants.wkbLineString:
528
            return TYPES.CURVE;
529

  
530
        case ogrConstants.wkbPolygon:
531
            return TYPES.SURFACE;
532

  
533
        case ogrConstants.wkbGeometryCollection:
534
            return TYPES.AGGREGATE;
535

  
536
        case ogrConstants.wkbMultiPoint:
537
            return TYPES.MULTIPOINT;
538

  
539
        case ogrConstants.wkbMultiLineString:
540
            return TYPES.MULTILINE;
541

  
542
        case ogrConstants.wkbMultiPolygon:
543
            return TYPES.MULTISURFACE;
544

  
545
        case ogrConstants.wkbNone:
546
            return TYPES.NULL;
547

  
548
        case ogrConstants.wkbUnknown:
549
        default:
550
            return TYPES.GEOMETRY;
551
        }
552
    }
553

  
554
    /**
555
     * Convert gvSIG type to OGR type. See {@link ogrConstants}.
556
     *
557
     * @param type
558
     *            A type of {@link DataTypes}
559
     * @return int Equivalent type of {@link ogrConstants}
560
     */
561
    public int convertToOGRType(int type) {
562

  
563
        switch (type) {
564
        case DataTypes.DATE:
565
            return ogrConstants.OFTDate;
566
        case DataTypes.DOUBLE:
567
        case DataTypes.FLOAT:
568
            return ogrConstants.OFTReal;
569
        case DataTypes.STRING:
570
            return ogrConstants.OFTString;
571
        case DataTypes.CHAR:
572
            return ogrConstants.OFTString;
573
        case DataTypes.INT:
574
            return ogrConstants.OFTInteger;
575
        case DataTypes.LONG: // There is not LONG type support
576
        default:
577
            return ogrConstants.OFTString;
578
        }
579
    }
580

  
581
    /**
582
     * Convert OGR type to gvSIG type. See {@link DataTypes}.
583
     *
584
     * @param type
585
     *            A type of {@link ogrConstants}
586
     * @return int Equivalent type of {@link DataTypes}
587
     */
588
    public int convertToDataType(int type) {
589

  
590
        switch (type) {
591
        case ogrConstants.OFTDate:
592
            return DataTypes.DATE;
593
        case ogrConstants.OFTReal:
594
            return DataTypes.DOUBLE;
595
        case ogrConstants.OFTInteger:
596
            return DataTypes.INT;
597
        case ogrConstants.OFTTime:
598
            return DataTypes.TIME;
599
        case ogrConstants.OFTString:
600
        default:
601
            return DataTypes.STRING;
602
        }
603

  
604
    }
605

  
606
    /**
607
     * Convert OGR Feature to another OGR Feature. This method take into account
608
     * only {@link FeatureDefn} fields to create new feature. This method is
609
     * useful when OGR {@link Layer} is copied to new {@link DataSource}.
610
     *
611
     * @param layerDefn
612
     *            Definition of new feature
613
     * @param feature
614
     *            OGR feature to be converted
615
     * @return Fixed feature
616
     */
617
    public org.gdal.ogr.Feature convert(FeatureDefn layerDefn, org.gdal.ogr.Feature feature) {
618

  
619
        Feature newFeature = new Feature(layerDefn);
620
        for (int i = 0; i < feature.GetDefnRef().GetFieldCount(); i++) {
621

  
622
            FieldDefn fieldDefn = feature.GetDefnRef().GetFieldDefn(i);
623
            int fieldIndex = newFeature.GetDefnRef().GetFieldIndex(fieldDefn.GetName());
624

  
625
            if (fieldIndex != -1) {
626

  
627
                int fieldType = feature.GetDefnRef().GetFieldDefn(i).GetFieldType();
628

  
629
                switch (fieldType) {
630
                case ogrConstants.OFTDate:
631

  
632
                    int[] year = new int[1];
633
                    int[] month = new int[1];
634
                    int[] day = new int[1];
635
                    int[] hour = new int[1];
636
                    int[] minute = new int[1];
637
                    int[] second = new int[1];
638
                    int[] flags = new int[1];
639
                    feature.GetFieldAsDateTime(i, year, month, day, hour, minute, second, flags);
640
                    newFeature.SetField(i, year[0], month[0], day[0], hour[0], minute[0],
641
                        second[0], flags[0]);
642
                    break;
643
                case ogrConstants.OFTReal:
644
                    newFeature.SetField(i, feature.GetFieldAsDouble(i));
645
                    break;
646
                case ogrConstants.OFTInteger:
647
                    newFeature.SetField(i, feature.GetFieldAsInteger(i));
648
                    break;
649
                case ogrConstants.OFTString:
650
                default:
651
                    newFeature.SetField(i, feature.GetFieldAsString(i));
652
                    break;
653
                }
654
            }
655

  
656
        }
657

  
658
        for (int i = 0; i < feature.GetDefnRef().GetGeomFieldCount(); i++) {
659
            GeomFieldDefn geomFieldDefn = feature.GetDefnRef().GetGeomFieldDefn(i);
660
            int fieldIndex = newFeature.GetDefnRef().GetGeomFieldIndex(geomFieldDefn.GetName());
661

  
662
            if (fieldIndex != -1) {
663

  
664
                if (geomFieldDefn.GetFieldType() == newFeature.GetGeomFieldDefnRef(fieldIndex)
665
                    .GetFieldType()) {
666
                    org.gdal.ogr.Geometry geometry =
667
                        feature.GetGeomFieldRef(geomFieldDefn.GetName());
668
                    newFeature.SetGeomField(fieldIndex, geometry);
669
                } else {
670
                    LOG.warn(
671
                        "Ignoring geometry field. Can not fix {}. Geometry type is not equals",
672
                        geomFieldDefn.GetName());
673
                }
674
            }
675
        }
676

  
677
        return newFeature;
678
    }
679
}
tags/org.gvsig.gdal-1.0.46/org.gvsig.gdal.prov/org.gvsig.gdal.prov.ogr/src/main/java/org/gvsig/gdal/prov/ogr/OGRResource.java
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 org.gvsig.fmap.dal.exception.InitializeException;
27
import org.gvsig.fmap.dal.resource.ResourceParameters;
28
import org.gvsig.fmap.dal.resource.exception.AccessResourceException;
29
import org.gvsig.fmap.dal.resource.exception.ResourceException;
30
import org.gvsig.fmap.dal.resource.spi.AbstractResource;
31

  
32
/**
33
 * 
34
 * @author <a href="mailto:lmarques@disid.com">Lluis Marques</a>
35
 *
36
 */
37
public class OGRResource extends AbstractResource {
38

  
39
    /**
40
     * 
41
     */
42
    public static final String NAME = "OGRResource";
43

  
44
    /**
45
     * 
46
     */
47
    public static final String DESCRIPTION = "Any resource that can be opened by OGR";
48

  
49
    /**
50
     * 
51
     * @param parameters
52
     *            Parameters to open this resource
53
     * @throws InitializeException
54
     *             If there is some error initializating this resource
55
     */
56
    public OGRResource(OGRResourceParameters parameters) throws InitializeException {
57
        super(parameters);
58
    }
59

  
60
    @Override
61
    public boolean isThis(ResourceParameters parameters) throws ResourceException {
62
        if (parameters instanceof OGRResourceParameters) {
63

  
64
            OGRResourceParameters thisParameters = (OGRResourceParameters) getParameters();
65
            OGRResourceParameters otherParameters = (OGRResourceParameters) parameters;
66
            if (thisParameters.getName().equals(otherParameters.getName()) && thisParameters
67
                .getConnectionString().equals(otherParameters.getConnectionString())) {
68
                return true;
69
            }
70
        }
71
        return false;
72
    }
73

  
74
    @Override
75
    public String getName() throws AccessResourceException {
76
        return ((OGRResourceParameters) getParameters()).getName();
77
    }
78

  
79
    @Override
80
    public Object get() throws AccessResourceException {
81
        return ((OGRResourceParameters) getParameters()).getConnectionString();
82
    }
83

  
84
}
tags/org.gvsig.gdal-1.0.46/org.gvsig.gdal.prov/org.gvsig.gdal.prov.ogr/src/main/java/org/gvsig/gdal/prov/ogr/OGRDataStoreProviderFactory.java
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 org.gvsig.fmap.dal.feature.FeatureStoreProviderFactory;
27
import org.gvsig.tools.dynobject.DynObject;
28

  
29
/**
30
 * OGR Provider factory to create parameters to create specific server data
31
 * explorers and specific data store providers.
32
 * 
33
 * @author <a href="mailto:lmarques@disid.com">Lluis Marques</a>
34
 *
35
 */
36
public interface OGRDataStoreProviderFactory extends FeatureStoreProviderFactory {
37

  
38
    /**
39
     * 
40
     * @return Name of driver used to open sources
41
     */
42
    public String getDriver();
43

  
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff