Revision 844

View differences:

tags/org.gvsig.gdal-1.0.151/org.gvsig.gdal.prov/org.gvsig.gdal.prov.ogr/src/main/resources/org/gvsig/gdal/prov/ogr/OGRDataStoreParameters.xml
1
<?xml version="1.0"?>
2
<definitions>
3
	<version>1.0.0</version>
4
	<classes>
5
		<class name="OGRDataStoreParameters">
6
			<extends>
7
				<class namespace="dal" name="ProviderParameters" />
8
			</extends>
9
			<description>Store the parameters needed to open OGR stores
10
			</description>
11
			<fields>
12
				<field name="CRS" type="crs" mandatory="false" group="Basic">
13
					<description>Coordinate reference system used</description>
14
				</field>
15
				<field name="file" type="file" mandatory="false" group="Basic">
16
					<description>Resource file</description>
17
				</field>
18
				<field name="connectionString" type="string" mandatory="false"
19
					group="Basic">
20
					<description>Connection string to open data source</description>
21
				</field>
22
				<field name="layerName" type="string" mandatory="false" group="Basic">
23
					<description>Layer name of data source</description>
24
				</field>
25
				<field name="defaultGeometryField" type="string" mandatory="false"
26
					group="Basic">
27
					<description>Name of default geometry field</description>
28
				</field>
29
        <field name="ignoreSpatialFilter" type="boolean" mandatory="false"
30
          group="Advanced" defaultValue="true">
31
          <description>Ignore spatial filter</description>
32
        </field>
33
			</fields>
34
		</class>
35
	</classes>
36
</definitions>
tags/org.gvsig.gdal-1.0.151/org.gvsig.gdal.prov/org.gvsig.gdal.prov.ogr/src/main/resources/org/gvsig/gdal/prov/ogr/OGRMetadata.xml
1
<?xml version="1.0"?>
2
<!--
3
Definitions of metadata fields of a shp file.  
4
 -->
5
<definitions>
6
  <version>1.0.0</version>
7
  <classes>
8
    
9
    <class name="OGRDataStoreProvider" namespace="Metadata">
10
      <extends>
11
      	<class namespace="Metadata" name="SpatialProvider"/>
12
      </extends>
13
      <description>Metadata of a OGR provider</description>
14
      <fields>
15
      </fields>
16
    </class>
17

  
18
  </classes>
19
</definitions>  
tags/org.gvsig.gdal-1.0.151/org.gvsig.gdal.prov/org.gvsig.gdal.prov.ogr/src/main/resources/org/gvsig/gdal/prov/ogr/OGRExplorerParameters.xml
1
<?xml version="1.0"?>
2
<definitions>
3
	<version>1.0.0</version>
4
	<classes>
5
		<class name="OGRDataExplorerParameters">
6
			<description>Store the parameters needed to create OGR data explorers
7
			</description>
8
			<fields>
9
				<field name="file" type="file" mandatory="false" group="Basic">
10
					<description>Resource file</description>
11
				</field>
12
				<field name="connectionString" type="string" mandatory="false"
13
					group="Basic">
14
					<description>Connection string to open data source</description>
15
				</field>
16
			</fields>
17
		</class>
18
	</classes>
19
</definitions>
tags/org.gvsig.gdal-1.0.151/org.gvsig.gdal.prov/org.gvsig.gdal.prov.ogr/src/main/resources/org/gvsig/gdal/prov/ogr/OGRNewDataStoreParameters.xml
1
<definitions>
2
	<version>1.0.0</version>
3
	<classes>
4
		<class name="OGRNewDataStoreParameters">
5
			<description>Store the parameters needed to create OGR data stores
6
			</description>
7
			<extends>
8
				<class namespace="dal" name="NewProviderParameters" />
9
				<class>OGRDataStoreParameters</class>
10
			</extends>
11
			<fields>
12
				<field name="driverName" type="string" mandatory="false" group="Basic">
13
					<description>Name of driver</description>
14
				</field>
15
				<field name="datasetCreationOptions" type="List" mandatory="false" group="Basic">
16
					<description>Name of driver</description>
17
				</field>
18
			</fields>
19
		</class>
20
	</classes>
21
</definitions>
tags/org.gvsig.gdal-1.0.151/org.gvsig.gdal.prov/org.gvsig.gdal.prov.ogr/src/main/resources/META-INF/services/org.gvsig.tools.library.Library
1
org.gvsig.gdal.prov.ogr.OGRLibrary
tags/org.gvsig.gdal-1.0.151/org.gvsig.gdal.prov/org.gvsig.gdal.prov.ogr/src/main/java/org/gvsig/gdal/prov/ogr/BasicOGRDataStoreProviderFactory.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.List;
28

  
29
import org.gvsig.fmap.dal.DataParameters;
30
import org.gvsig.fmap.dal.DataStoreParameters;
31
import org.gvsig.fmap.dal.DataStoreProvider;
32
import org.gvsig.fmap.dal.DataTypes;
33
import org.gvsig.fmap.dal.exception.InitializeException;
34
import org.gvsig.fmap.dal.feature.spi.AbstractFeatureStoreProviderFactory;
35
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
36
import org.gvsig.fmap.geom.Geometry.SUBTYPES;
37
import org.gvsig.tools.dynobject.DynObject;
38

  
39
/**
40
 * 
41
 * @author <a href="mailto:lmarques@disid.com">Lluis Marques</a>
42
 *
43
 */
44
public class BasicOGRDataStoreProviderFactory extends AbstractFeatureStoreProviderFactory implements
45
    OGRDataStoreProviderFactory {
46

  
47
    /**
48
     * @param name
49
     *            Name of factory
50
     * @param description
51
     *            Description of factory
52
     */
53
    public BasicOGRDataStoreProviderFactory(String name, String description) {
54
        super(name, description);
55
    }
56

  
57
    @Override
58
    public DataStoreProvider createProvider(DataParameters dataParameters,
59
        DataStoreProviderServices providerServices) throws InitializeException {
60
        return new OGRDataStoreProvider((DataStoreParameters) dataParameters, providerServices);
61
    }
62

  
63
    @Override
64
    public DynObject createParameters() {
65
        return new OGRDataStoreParameters();
66
    }
67

  
68
    public int allowMultipleGeometryTypes() {
69
        return UNKNOWN;
70
    }
71

  
72
    public int allowEditableFeatureType() {
73
        return UNKNOWN;
74
    }
75

  
76
    /**
77
     * See {@link OGRConverter#convertToDataType(int)} method. The list of data
78
     * type of OGR. If the list of OGR types changes update this method.
79
     */
80
    @SuppressWarnings("rawtypes")
81
    public List getSupportedDataTypes() {
82

  
83
        List<Integer> supportedDataTypes = new ArrayList<Integer>();
84

  
85
        supportedDataTypes.add(DataTypes.BOOLEAN);
86
        supportedDataTypes.add(DataTypes.DATE);
87
        supportedDataTypes.add(DataTypes.FLOAT);
88
        supportedDataTypes.add(DataTypes.DOUBLE);
89
        supportedDataTypes.add(DataTypes.STRING);
90
        supportedDataTypes.add(DataTypes.INT);
91
        supportedDataTypes.add(DataTypes.LONG);
92
        supportedDataTypes.add(DataTypes.TIME);
93

  
94
        return supportedDataTypes;
95
    }
96

  
97
    @SuppressWarnings("rawtypes")
98
    public List getSupportedGeometryTypesSubtypes() {
99
        List<Integer> supportedSubtypes = new ArrayList<Integer>();
100
        supportedSubtypes.add(SUBTYPES.GEOM2D);
101
        return supportedSubtypes;
102
    }
103

  
104
    public boolean allowsMandatoryAttributes() {
105
        return false;
106
    }
107

  
108
    public boolean allowsPrimaryKeyAttributes() {
109
        return false;
110
    }
111

  
112
    public int useLocalIndexesCanImprovePerformance() {
113
        return UNKNOWN;
114
    }
115

  
116
    @Override
117
    public DynObject createDataExplorerParameters(Object connectionString) {
118
        return new OGRDataExplorerParameters();
119
    }
120

  
121
    @Override
122
    public DynObject createParameters(Object connectionObject) {
123
        return createParameters();
124
    }
125

  
126
    @Override
127
    public String getDriver() {
128
        return null;
129
    }
130

  
131
}
tags/org.gvsig.gdal-1.0.151/org.gvsig.gdal.prov/org.gvsig.gdal.prov.ogr/src/main/java/org/gvsig/gdal/prov/ogr/OGRResourceParameters.java
1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 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 3
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.resource.spi.AbstractResourceParameters;
27
import org.gvsig.tools.ToolsLocator;
28
import org.gvsig.tools.dataTypes.DataTypes;
29
import org.gvsig.tools.dynobject.DelegatedDynObject;
30
import org.gvsig.tools.dynobject.DynClass;
31
import org.gvsig.tools.persistence.PersistenceManager;
32

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

  
40
    /**
41
     * 
42
     */
43
    public static final String DYNCLASS_NAME = "OGRResourceParameters";
44

  
45
    /**
46
     * 
47
     */
48
    private static final String DYNFIELDNAME_NAME = "name";
49

  
50
    /**
51
     * 
52
     */
53
    private static final String DYNFIELDNAME_CONNECTION_STRING = "connectionString";
54

  
55
    private DelegatedDynObject delegatedDynObject;
56

  
57
    /**
58
     * 
59
     */
60
    public OGRResourceParameters() {
61
        super();
62
        PersistenceManager manager = ToolsLocator.getPersistenceManager();
63
        DynClass definition = (DynClass) manager.getDefinition(DYNCLASS_NAME);
64
        this.delegatedDynObject =
65
            (DelegatedDynObject) ToolsLocator.getDynObjectManager().createDynObject(definition);
66
    }
67

  
68
    /**
69
     * 
70
     * @param connectionString
71
     *            Connection string
72
     */
73
    public OGRResourceParameters(String connectionString) {
74
        this();
75
        setDynValue(DYNFIELDNAME_NAME,
76
            String.valueOf(connectionString.hashCode()).concat("@OGResource"));
77
        setDynValue(DYNFIELDNAME_CONNECTION_STRING, connectionString);
78
    }
79

  
80
    /**
81
     * 
82
     * @param params
83
     *            Array with parameter values
84
     */
85
    public OGRResourceParameters(Object[] params) {
86
        this((String) params[0]);
87
    }
88

  
89
    @Override
90
    public String getTypeName() {
91
        return OGRResource.NAME;
92
    }
93

  
94
    @Override
95
    protected DelegatedDynObject getDelegatedDynObject() {
96
        return delegatedDynObject;
97
    }
98

  
99
    /**
100
     * @return String
101
     */
102
    public String getName() {
103
        return (String) this.getDynValue(DYNFIELDNAME_NAME);
104
    }
105

  
106
    /**
107
     * @return String
108
     */
109
    public String getConnectionString() {
110
        return (String) this.getDynValue(DYNFIELDNAME_CONNECTION_STRING);
111
    }
112

  
113
    protected static void registerPersistenceDefinition() {
114
        PersistenceManager manager = ToolsLocator.getPersistenceManager();
115
        DynClass definition = (DynClass) manager.getDefinition(DYNCLASS_NAME);
116
        if (definition == null) {
117
            definition = (DynClass) manager.addDefinition(OGRResourceParameters.class,
118
                DYNCLASS_NAME, DYNCLASS_NAME + " persistence definition", null, null);
119

  
120
            definition.addDynField(DYNFIELDNAME_NAME).setType(DataTypes.STRING)
121
                .setDescription("Name of resource");
122
            definition.addDynField(DYNFIELDNAME_CONNECTION_STRING).setType(DataTypes.STRING)
123
                .setDescription("Connection string");
124
        }
125
    }
126
}
tags/org.gvsig.gdal-1.0.151/org.gvsig.gdal.prov/org.gvsig.gdal.prov.ogr/src/main/java/org/gvsig/gdal/prov/ogr/OGRDataExplorerParameters.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

  
28
import org.gvsig.fmap.dal.DataServerExplorerParameters;
29
import org.gvsig.fmap.dal.spi.AbstractDataParameters;
30
import org.gvsig.tools.ToolsLocator;
31
import org.gvsig.tools.dynobject.DelegatedDynObject;
32

  
33
/**
34
 * 
35
 * @author <a href="mailto:lmarques@disid.com">Lluis Marques</a>
36
 *
37
 */
38
public class OGRDataExplorerParameters extends AbstractDataParameters
39
    implements DataServerExplorerParameters {
40

  
41
    /**
42
     * 
43
     */
44
    public static final String PARAMETERS_DEFINITION_NAME = "OGRDataExplorerParameters";
45

  
46
    /**
47
     * 
48
     */
49
    public static final String FILE_PARAMETER_NAME = "file";
50

  
51
    /**
52
     * 
53
     */
54
    public static final String CONNECTION_STRING_PARAMETER_NAME = "connectionString";
55

  
56
    private DelegatedDynObject parameters;
57

  
58
    /**
59
     * 
60
     */
61
    public OGRDataExplorerParameters() {
62
        this.parameters = (DelegatedDynObject) ToolsLocator.getDynObjectManager().createDynObject(
63
            ToolsLocator.getPersistenceManager().getDefinition(PARAMETERS_DEFINITION_NAME));
64
    }
65

  
66
    @Override
67
    public String getExplorerName() {
68
        return OGRDataExplorer.NAME;
69
    }
70

  
71
    @Override
72
    protected DelegatedDynObject getDelegatedDynObject() {
73
        return this.parameters;
74
    }
75

  
76
    /**
77
     * 
78
     * @return File
79
     */
80
    public File getFile() {
81
        return (File) this.getDynValue(FILE_PARAMETER_NAME);
82
    }
83

  
84
    /**
85
     * 
86
     * @return String
87
     */
88
    public String getConnectionString() {
89
        return (String) this.getDynValue(CONNECTION_STRING_PARAMETER_NAME);
90
    }
91

  
92
    /**
93
     * 
94
     * @param file
95
     *            File
96
     */
97
    public void setFile(File file) {
98
        this.setDynValue(FILE_PARAMETER_NAME, file);
99
    }
100

  
101
    /**
102
     * 
103
     * @param connection
104
     *            Connection string
105
     */
106
    public void setConnectionString(String connection) {
107
        this.setDynValue(CONNECTION_STRING_PARAMETER_NAME, connection);
108
    }
109
}
tags/org.gvsig.gdal-1.0.151/org.gvsig.gdal.prov/org.gvsig.gdal.prov.ogr/src/main/java/org/gvsig/gdal/prov/ogr/OGRUnsupportedFormatException.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.Map;
27

  
28
import org.gvsig.fmap.dal.exception.DataException;
29

  
30
/**
31
 * 
32
 * @author <a href="mailto:lmarques@disid.com">Lluis Marques</a>
33
 *
34
 */
35
@SuppressWarnings("unchecked")
36
public class OGRUnsupportedFormatException extends DataException {
37

  
38
    private static final long serialVersionUID = -2670314598211236837L;
39

  
40
    private final static String MESSAGE =
41
        "Unsupported vectorial format. There are not any OGR driver registered to open %(connectionString)";
42

  
43
    private final static String KEY = "_UnsupportedVectorialFormatException";
44

  
45
    /**
46
     * @param messageFormat
47
     *            Message format
48
     * @param cause
49
     *            Cause
50
     * @param messageKey
51
     *            Message key
52
     * @param code
53
     *            code
54
     * @param values
55
     *            Values
56
     */
57
    public OGRUnsupportedFormatException(String messageFormat, Throwable cause, String messageKey,
58
        long code, Map<Object, Object> values) {
59
        super(messageFormat, cause, messageKey, code);
60
        this.values.putAll(values);
61
    }
62

  
63
    /**
64
     * @param messageFormat
65
     *            Message format
66
     * @param cause
67
     *            Cause
68
     * @param values
69
     *            Values
70
     */
71
    public OGRUnsupportedFormatException(String messageFormat, Throwable cause,
72
        Map<Object, Object> values) {
73
        super(messageFormat, cause, KEY, serialVersionUID);
74
        this.values.putAll(values);
75
    }
76

  
77
    /**
78
     * @param connectionString
79
     *            Conenction string
80
     */
81
    public OGRUnsupportedFormatException(String connectionString) {
82
        super(MESSAGE, KEY, serialVersionUID);
83
        this.values.put("connectionString", connectionString);
84
    }
85

  
86
}
tags/org.gvsig.gdal-1.0.151/org.gvsig.gdal.prov/org.gvsig.gdal.prov.ogr/src/main/java/org/gvsig/gdal/prov/ogr/OGRDataStoreProvider.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.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
}
tags/org.gvsig.gdal-1.0.151/org.gvsig.gdal.prov/org.gvsig.gdal.prov.ogr/src/main/java/org/gvsig/gdal/prov/ogr/OGRFetureSetProvider.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.regex.Matcher;
27
import java.util.regex.Pattern;
28

  
29
import org.cresques.cts.ICRSFactory;
30
import org.cresques.cts.IProjection;
31
import org.gdal.ogr.DataSource;
32
import org.gdal.ogr.Feature;
33
import org.gdal.ogr.Geometry;
34
import org.gdal.ogr.Layer;
35
import org.gdal.ogr.ogr;
36
import org.gdal.ogr.ogrConstants;
37
import org.gdal.osr.SpatialReference;
38
import org.gvsig.fmap.crs.CRSFactory;
39
import org.gvsig.fmap.dal.DataStore;
40
import org.gvsig.fmap.dal.exception.DataException;
41
import org.gvsig.fmap.dal.feature.FeatureQuery;
42
import org.gvsig.fmap.dal.feature.FeatureType;
43
import org.gvsig.fmap.dal.feature.exception.ConcurrentDataModificationException;
44
import org.gvsig.fmap.dal.feature.spi.AbstractFeatureProviderIterator;
45
import org.gvsig.fmap.dal.feature.spi.AbstractFeatureSetProvider;
46
import org.gvsig.fmap.dal.feature.spi.AbstractFeatureStoreProvider;
47
import org.gvsig.fmap.dal.feature.spi.FeatureProvider;
48
import org.gvsig.fmap.dal.feature.spi.FeatureSetProvider;
49
import org.gvsig.fmap.dal.feature.spi.FeatureStoreProvider;
50
import org.gvsig.fmap.dal.resource.spi.ResourceConsumer;
51
import org.gvsig.fmap.dal.resource.spi.ResourceProvider;
52
import org.gvsig.tools.ToolsLocator;
53
import org.gvsig.tools.exception.BaseException;
54
import org.slf4j.Logger;
55
import org.slf4j.LoggerFactory;
56

  
57
/**
58
 *
59
 * @author <a href="mailto:lmarques@disid.com">Lluis Marques</a>
60
 *
61
 */
62
public class OGRFetureSetProvider extends AbstractFeatureSetProvider implements FeatureSetProvider,
63
    ResourceConsumer {
64

  
65
    private static final Logger LOG = LoggerFactory.getLogger(OGRFetureSetProvider.class);
66

  
67
    private static final String regularExpresion =
68
        "\\s*ST_intersects[(]\\s*ST_GeomFromText[(]\\s*'([^']*)'\\s*,\\s*'([^']*)'\\s*[)],\\s*(?s).*";
69

  
70
    /**
71
     * @param store
72
     *            Source of this feature set
73
     * @param query
74
     *            Query
75
     * @param featureType
76
     *            Featuretype requested
77
     */
78
    public OGRFetureSetProvider(AbstractFeatureStoreProvider store, FeatureQuery query,
79
        FeatureType featureType) {
80
        super(store, query, featureType);
81

  
82
        getStore().getResource().addConsumer(this);
83
    }
84

  
85
    @Override
86
    public boolean canFilter() {
87
        return false;
88
    }
89

  
90
    @Override
91
    public boolean canOrder() {
92
        return true;
93
    }
94

  
95
    @Override
96
    public boolean canIterateFromIndex() {
97
        return true;
98
    }
99

  
100
    @Override
101
    public long getSize() throws DataException {
102
        return getStore().getFeatureCount();
103
    }
104

  
105
    @Override
106
    public boolean isEmpty() throws DataException {
107
        return getSize() == 0;
108
    }
109

  
110
    @Override
111
    protected AbstractFeatureProviderIterator createIterator(long index) throws DataException {
112
        return createFastIterator(index);
113
    }
114

  
115
    @Override
116
    protected AbstractFeatureProviderIterator createFastIterator(long index) throws DataException {
117
        String sql =
118
            getOGRStoreProvider().compoundSelect(getFeatureType(), getQuery().getFilter(),
119
                getQuery().getOrder());
120

  
121
        DataSource dataSource = getOGRStoreProvider().getDataSource();
122
        LOG.debug("Running query {} over {}", new Object[] { sql, dataSource.getName() });
123

  
124
        Layer layer = null;
125
        boolean ignoreSpatialFilter = (boolean) getStore().getParameters().getDynValue(OGRDataStoreParameters.IGNORE_SPATIAL_FILTER);
126
        if (!ignoreSpatialFilter && getOGRStoreProvider().getLayer().TestCapability(ogrConstants.OLCFastSpatialFilter)
127
            && getQuery().hasFilter()) {
128

  
129
            String evaluatorSQL = getQuery().getFilter().getSQL();
130
            Pattern pattern = Pattern.compile(regularExpresion);
131
            Matcher matcher = pattern.matcher(evaluatorSQL);
132

  
133
            if (matcher.matches()) {
134
                String wktGeometry = matcher.group(1);
135
                String crsCode = matcher.group(2);
136

  
137
                IProjection projection = CRSFactory.getCRS(crsCode);
138
                SpatialReference srs =
139
                    new SpatialReference(projection.export(ICRSFactory.FORMAT_WKT));
140
                Geometry ogrGeometry = ogr.CreateGeometryFromWkt(wktGeometry, srs);
141

  
142
                if (getOGRStoreProvider().getDynValue(DataStore.METADATA_CRS) != null) {
143

  
144
                    IProjection projectionProvider =
145
                        (IProjection) getOGRStoreProvider().getDynValue(DataStore.METADATA_CRS);
146
                    if (!crsCode.equals(projectionProvider.getAbrev())) {
147
                        SpatialReference srsDst =
148
                            new SpatialReference(projectionProvider.export(ICRSFactory.FORMAT_WKT));
149
                        ogrGeometry.TransformTo(srsDst);
150
                    }
151
                }
152
                layer = dataSource.ExecuteSQL(sql, ogrGeometry);
153
            }
154
        } else {
155
            layer = dataSource.ExecuteSQL(sql);
156
        }
157

  
158
        if(layer == null){
159
            LOG.warn("The result of query is null. SQL {} FeatureType {}", sql, getFeatureType());
160
            LOG.warn("Getting data without SQL filter");
161
            OGRDataStoreParameters ogrParameters = (OGRDataStoreParameters) getOGRStoreProvider().getParameters();
162
            layer = dataSource.ExecuteSQL("SELECT * FROM ".concat(ogrParameters.getLayerName()));
163
        }
164

  
165
        return new OGRFastIterator(getStore(), layer, index);
166
    }
167

  
168
    @Override
169
    protected void doDispose() throws BaseException {
170
        getStore().getResource().removeConsumer(this);
171
    }
172

  
173
    @Override
174
    public boolean closeResourceRequested(ResourceProvider resource) {
175
        return true;
176
    }
177

  
178
    @Override
179
    public void resourceChanged(ResourceProvider resource) {
180
    }
181

  
182
    class OGRFastIterator extends AbstractFeatureProviderIterator implements ResourceConsumer {
183

  
184
        private long index;
185

  
186
        private Layer layer;
187

  
188
        private OGRConverter converter;
189

  
190
        private FeatureProvider featureProvider;
191

  
192
        private Feature currentOgrFeature;
193
        private Feature nextOgrFeature;
194

  
195
        public OGRFastIterator(FeatureStoreProvider storeProvider, Layer layer, long index)
196
            throws OGRUnsupportedFormatException {
197
            super(storeProvider);
198
            ToolsLocator.getDisposableManager().bind(storeProvider);
199
            getResource().addConsumer(this);
200
            this.converter = new OGRConverter();
201
            this.index = index;
202
            this.layer = layer;
203
            this.layer.GetFeatureCount();
204
            this.layer.ResetReading();
205
            if(index!=0){
206
                this.layer.SetNextByIndex((int) index);
207
            }
208
            this.currentOgrFeature = null;
209
            this.nextOgrFeature =  this.layer.GetNextFeature();
210
        }
211

  
212
        @Override
213
        public void remove() {
214
            if (currentOgrFeature != null) {
215
                this.layer.DeleteFeature(currentOgrFeature.GetFID());
216
                currentOgrFeature=null;
217
            }
218
        }
219

  
220
        @Override
221
        protected Object internalNext() {
222
            this.currentOgrFeature = this.nextOgrFeature;
223
            this.featureProvider = null;
224
            this.featureProvider = converter.convert(featureProvider, getFeatureType(), this.nextOgrFeature);
225
            this.nextOgrFeature =  this.layer.GetNextFeature();
226
            return this.featureProvider;
227
        }
228

  
229
        @Override
230
        protected boolean internalHasNext() {
231
            return nextOgrFeature!=null;
232
        }
233

  
234
        @Override
235
        protected void doDispose() throws BaseException {
236
            ToolsLocator.getDisposableManager().release(getStore());
237
            getOGRStoreProvider().getDataSource().ReleaseResultSet(layer);
238
            getResource().removeConsumer(this);
239
            this.converter = null;
240
            this.featureProvider = null;
241
            this.layer = null;
242
        }
243

  
244
        @Override
245
        public boolean closeResourceRequested(ResourceProvider resource) {
246
            this.featureProvider = null;
247
            return true;
248
        }
249

  
250
        @Override
251
        public void resourceChanged(ResourceProvider resource) {
252
            throw new ConcurrentDataModificationException(getOGRStoreProvider().getName());
253
        }
254
    }
255

  
256
    private OGRDataStoreProvider getOGRStoreProvider() {
257
        return (OGRDataStoreProvider) getStore();
258
    }
259
}
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff