Revision 40

View differences:

tags/org.gvsig.spatialite-1.0.5/pom.xml
1
<?xml version="1.0" encoding="UTF-8"?>
2

  
3
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4

  
5
    <modelVersion>4.0.0</modelVersion>
6
    <artifactId>org.gvsig.spatialite</artifactId>
7
    <version>1.0.5</version>
8
    <packaging>pom</packaging>
9
    <name>${project.artifactId}</name>
10
    <description>SpatiaLite support for DAL and gvSIG</description>
11
    <parent>
12
        <groupId>org.gvsig</groupId>
13
        <artifactId>org.gvsig.desktop</artifactId>
14
        <version>2.0.195</version>
15
    </parent>
16

  
17
    <url>https://devel.gvsig.org/redmine/projects/gvsig-sqlite</url>
18
    <scm>
19
        <connection>scm:svn:https://devel.gvsig.org/svn/gvsig-sqlite/tags/org.gvsig.spatialite-1.0.5</connection>
20
        <developerConnection>scm:svn:https://devel.gvsig.org/svn/gvsig-sqlite/tags/org.gvsig.spatialite-1.0.5</developerConnection>
21
        <url>https://devel.gvsig.org/redmine/projects/gvsig-sqlite/repository/show/tags/org.gvsig.spatialite-1.0.5</url>
22
    </scm>
23

  
24
    <repositories>
25
        <repository>
26
            <id>gvsig-public-http-repository</id>
27
            <name>gvSIG maven public HTTP repository</name>
28
            <url>http://devel.gvsig.org/m2repo/j2se</url>
29
            <releases>
30
                <enabled>true</enabled>
31
                <updatePolicy>daily</updatePolicy>
32
                <checksumPolicy>warn</checksumPolicy>
33
            </releases>
34
            <snapshots>
35
                <enabled>true</enabled>
36
                <updatePolicy>daily</updatePolicy>
37
                <checksumPolicy>warn</checksumPolicy>
38
            </snapshots>
39
        </repository>
40
    </repositories>
41

  
42

  
43
    <build>
44
        <plugins>
45
            <plugin>
46
                <groupId>org.apache.maven.plugins</groupId>
47
                <artifactId>maven-release-plugin</artifactId>
48
                <configuration>
49
                    <tagBase>https://devel.gvsig.org/svn/gvsig-sqlite/tags/</tagBase>
50
                    <goals>deploy</goals>
51
                </configuration>
52
            </plugin>                     
53
        </plugins>
54
    </build>
55

  
56

  
57
    <dependencyManagement>
58
        <dependencies>
59
            <dependency>
60
                <groupId>org.gvsig</groupId>
61
                <artifactId>org.gvsig.spatialite.provider</artifactId>
62
                <version>1.0.5</version>
63
            </dependency>
64
            <dependency>
65
                <groupId>org.gvsig</groupId>
66
                <artifactId>org.gvsig.spatialite.app.mainplugin</artifactId>
67
                <version>1.0.5</version>
68
            </dependency>
69
            <dependency>
70
                <groupId>org.hdm</groupId>
71
                <artifactId>spatialite-jdbc</artifactId>
72
                <version>4.3.0a</version>
73
            </dependency>
74
            
75
            <dependency>
76
                <groupId>org.gvsig</groupId>
77
                <artifactId>org.gvsig.fmap.dal.file.lib</artifactId>
78
                <version>2.0.164</version>
79
            </dependency>
80
                    
81
        </dependencies>
82
    </dependencyManagement>
83
  
84
    <modules>
85
        <module>org.gvsig.spatialite.app</module>
86
        <module>org.gvsig.spatialite.provider</module>
87
    </modules>
88

  
89

  
90
</project>
tags/org.gvsig.spatialite-1.0.5/org.gvsig.spatialite.provider/src/main/java/org/gvsig/spatialite/dal/SpatiaLiteHelper.java
1
/* gvSIG. Geographic Information System of the Valencian Government
2
 *
3
 * Copyright (C) 2007-2016 Infrastructures and Transports Department
4
 * of the Valencian Government (CIT)
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
 */
22
package org.gvsig.spatialite.dal;
23

  
24
import java.io.File;
25
import org.gvsig.spatialite.dal.operations.SpatiaLiteOperationsFactory;
26
import java.sql.Connection;
27
import java.sql.SQLException;
28
import java.sql.Statement;
29
import java.util.Map;
30
import org.apache.commons.dbcp.BasicDataSource;
31
import org.apache.commons.io.FilenameUtils;
32
import org.apache.commons.lang3.StringUtils;
33
import org.cresques.cts.IProjection;
34
import org.gvsig.fmap.dal.SQLBuilder;
35
import org.gvsig.fmap.dal.resource.exception.AccessResourceException;
36
import org.gvsig.fmap.dal.store.jdbc.JDBCConnectionParameters;
37
import org.gvsig.fmap.dal.store.jdbc.JDBCNewStoreParameters;
38
import org.gvsig.fmap.dal.store.jdbc.JDBCServerExplorerParameters;
39
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParameters;
40
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCDriverClassNotFoundException;
41
import org.gvsig.fmap.dal.store.jdbc2.JDBCUtils;
42
import org.gvsig.fmap.dal.store.jdbc2.OperationsFactory;
43
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCHelperBase;
44
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCSQLBuilderBase;
45
import org.gvsig.fmap.geom.Geometry;
46
import org.gvsig.fmap.geom.aggregate.MultiLine;
47
import org.gvsig.fmap.geom.aggregate.MultiPoint;
48
import org.gvsig.fmap.geom.aggregate.MultiPolygon;
49
import org.gvsig.fmap.geom.exception.CreateGeometryException;
50
import org.gvsig.fmap.geom.primitive.Primitive;
51
import org.gvsig.fmap.geom.type.GeometryType;
52
import org.slf4j.Logger;
53
import org.slf4j.LoggerFactory;
54
import org.spatialite.SQLiteConfig;
55
import org.spatialite.SQLiteConfig.TransactionMode;
56

  
57
public class SpatiaLiteHelper extends JDBCHelperBase {
58

  
59
    static final Logger logger = LoggerFactory.getLogger(SpatiaLiteHelper.class);
60

  
61
    public static final String NAME = "SpatiaLite";
62
    public static final String SpatiaLiteJDBCDriver = "org.spatialite.JDBC";
63
    
64
    public static String getConnectionURL(SpatiaLiteConnectionParameters params) {
65
        String fname = params.getFile().getAbsolutePath().replace("\\","/");
66
        if( StringUtils.isEmpty(FilenameUtils.getExtension(fname)) ) {
67
            fname = fname + ".sqlite";
68
            params.setFile(new File(fname));
69
        }
70
        String connectionURL = "jdbc:spatialite:" + fname;
71
        logger.debug("connectionURL: {}", connectionURL);
72
        return connectionURL;
73
    }
74

  
75
    private static class ConnectionProvider {
76

  
77
        private static boolean needRegisterDriver = true;
78

  
79
        private BasicDataSource dataSource = null;
80

  
81
        private final SpatiaLiteConnectionParameters connectionParameters;
82

  
83
        public ConnectionProvider(SpatiaLiteConnectionParameters connectionParameters) {
84
            this.connectionParameters = connectionParameters;
85
        }
86

  
87
        public Connection getConnection() throws SQLException {
88
            if (this.dataSource == null) {
89
                this.dataSource = this.createDataSource();               
90
            }
91
            Connection conn = this.dataSource.getConnection();
92
            try {
93
                Statement st = conn.createStatement();
94
                st.execute("SELECT srid FROM spatial_ref_sys WHERE srid=0 LIMIT 1");
95
                JDBCUtils.closeQuietly(st);
96
            } catch(Exception ex) {
97
                Statement st = conn.createStatement();
98
                JDBCUtils.executeQuery(st, "SELECT InitSpatialMetaData(1)");
99
                JDBCUtils.closeQuietly(st);
100
            }
101
            return conn;
102
        }
103

  
104
        private BasicDataSource createDataSource() throws SQLException {
105
            if (!this.isRegistered()) {
106
                this.registerDriver();
107
            }
108
            SpatiaLiteConnectionParameters params = connectionParameters;
109

  
110
            BasicDataSource ds = new BasicDataSource();
111
            ds.setDriverClassName(params.getJDBCDriverClassName());
112
            if( !StringUtils.isEmpty(params.getUser()) ) {
113
                ds.setUsername(params.getUser());
114
            }
115
            if( !StringUtils.isEmpty(params.getPassword()) ) {
116
                ds.setPassword(params.getPassword());
117
            }
118
            ds.setUrl(params.getUrl());
119
            SQLiteConfig config = new SQLiteConfig();
120
            config.setSharedCache(true);
121
            config.enableLoadExtension(true);
122
            config.enableSpatiaLite(true);
123
            config.setTransactionMode(TransactionMode.IMMEDIATE);
124
            for (Map.Entry e : config.toProperties().entrySet()) {
125
                ds.addConnectionProperty((String)e.getKey(), (String)e.getValue());
126
            }
127
            ds.setMaxWait(60L * 1000);
128
            return ds;
129
        }
130

  
131
        private boolean isRegistered() {
132
            return needRegisterDriver;
133
        }
134

  
135
        public void registerDriver() throws SQLException {
136
            String className = this.connectionParameters.getJDBCDriverClassName();
137
            if (className == null) {
138
                return;
139
            }
140
            try {
141
                Class theClass = Class.forName(className);
142
                if (theClass == null) {
143
                    throw new JDBCDriverClassNotFoundException(NAME, className);
144
                }
145
            } catch (Exception e) {
146
                throw new SQLException("Can't register JDBC driver '" + className + "'.", e);
147
            }
148
            needRegisterDriver = false;
149
        }
150

  
151
    }
152

  
153
    private ConnectionProvider connectionProvider = null;
154
   
155
    public SpatiaLiteHelper(JDBCConnectionParameters connectionParameters) {
156
        super(connectionParameters);
157
    }
158

  
159
    @Override
160
    public synchronized Connection  getConnection() throws AccessResourceException {
161
        try {
162
            if (this.connectionProvider == null) {
163
                this.connectionProvider = new ConnectionProvider(this.getConnectionParameters());
164
            }
165
            Connection connection = this.connectionProvider.getConnection();
166
            logger.debug("getConnection: connection = "+connection.hashCode());
167
            return connection;
168
        } catch (SQLException ex) {
169
            throw new AccessResourceException(SpatiaLiteLibrary.NAME, ex);
170
        }
171
    }
172
    
173
    @Override
174
    public SpatiaLiteConnectionParameters getConnectionParameters() {
175
        return (SpatiaLiteConnectionParameters) super.getConnectionParameters();
176
    }
177
    
178
    @Override
179
    public String getConnectionURL() {
180
        return getConnectionURL(this.getConnectionParameters());
181
    }
182

  
183
    @Override
184
    protected String getResourceType() {
185
        return SpatiaLiteLibrary.NAME;
186
    }
187

  
188
    @Override
189
    public String getProviderName() {
190
        return SpatiaLiteLibrary.NAME;
191
    }
192

  
193
    @Override
194
    public JDBCSQLBuilderBase createSQLBuilder() {
195
        return new SpatiaLiteSQLBuilder(this);
196
    }
197
    
198
    @Override
199
    public OperationsFactory getOperations() {
200
        if (this.operationsFactory == null) {
201
            this.operationsFactory = new SpatiaLiteOperationsFactory(this);
202
        }
203
        return operationsFactory;
204
    }
205

  
206
    @Override
207
    public SQLBuilder.GeometrySupportType getGeometrySupportType() {
208
        return SQLBuilder.GeometrySupportType.WKB;
209
    }
210

  
211
    @Override
212
    public boolean hasSpatialFunctions() {
213
        return true;
214
    }
215

  
216
    @Override
217
    public boolean canWriteGeometry(int geometryType, int geometrySubtype) {
218
        return true;
219
    }
220

  
221
    @Override
222
    public String getQuoteForIdentifiers() {
223
        return "\"";
224
    }
225

  
226
    @Override
227
    public boolean allowAutomaticValues() {
228
        return true;
229
    }
230

  
231
    @Override
232
    public boolean supportOffsetInSelect() {
233
        return true;
234
    }
235

  
236
    @Override
237
    public String getQuoteForStrings() {
238
        return "'";
239
    }
240

  
241
    @Override
242
    public int getSRSCode(IProjection crs) {
243
        // TODO: ir a buscarlo a la BBDD a ver donde puede estar
244
        return super.getSRSCode(crs);
245
    }
246
    
247
    @Override
248
    public IProjection getProjectionFromSRSId(int srsid) {
249
        // TODO: ir a buscarlo a la BBDD a ver donde puede estar
250
        return super.getProjectionFromSRSId(srsid);
251
    }
252

  
253
    @Override
254
    public String getSourceId(JDBCStoreParameters parameters) {
255
        return parameters.getDBName() + "." + 
256
               parameters.getSchema()+ "." + 
257
               parameters.getTable();
258
    }
259

  
260
    @Override
261
    public JDBCNewStoreParameters createNewStoreParameters() {
262
        return new SpatiaLiteNewStoreParameters();
263
    }
264

  
265
    @Override
266
    public JDBCStoreParameters createOpenStoreParameters() {
267
        return new SpatiaLiteStoreParameters();
268
    }
269

  
270
    @Override
271
    public JDBCServerExplorerParameters createServerExplorerParameters() {
272
        return new SpatiaLiteExplorerParameters();
273
    }
274

  
275
    public Geometry forceGeometryType(GeometryType geomtype, Geometry geom) throws CreateGeometryException {
276
        switch( geomtype.getType() ) {
277
        case Geometry.TYPES.MULTIPOLYGON:
278
            if( geom.getType()==Geometry.TYPES.POLYGON ) {
279
                MultiPolygon x = getGeometryManager().createMultiPolygon(geomtype.getSubType());
280
                x.addPrimitive((Primitive) geom);
281
                geom = x;
282
            }
283
            break;
284
        case Geometry.TYPES.MULTILINE:
285
            if( geom.getType()==Geometry.TYPES.LINE ) {
286
                MultiLine x = getGeometryManager().createMultiLine(geomtype.getSubType());
287
                x.addPrimitive((Primitive) geom);
288
                geom = x;
289
            }
290
            break;
291
        case Geometry.TYPES.MULTIPOINT:
292
            if( geom.getType()==Geometry.TYPES.POINT ) {
293
                MultiLine x = getGeometryManager().createMultiLine(geomtype.getSubType());
294
                x.addPrimitive((Primitive) geom);
295
                geom = x;
296
            }
297
            break;
298
        case Geometry.TYPES.POLYGON:
299
            if( geom.getType()==Geometry.TYPES.MULTIPOLYGON ) {
300
                MultiPolygon x = (MultiPolygon) geom;
301
                if( x.getPrimitivesNumber()==1 ) {
302
                    geom = x.getPrimitiveAt(0);
303
                }
304
            }
305
            break;
306
        case Geometry.TYPES.LINE:
307
            if( geom.getType()==Geometry.TYPES.MULTILINE ) {
308
                MultiLine x = (MultiLine) geom;
309
                if( x.getPrimitivesNumber()==1 ) {
310
                    geom = x.getPrimitiveAt(0);
311
                }
312
            }
313
            break;
314
        case Geometry.TYPES.POINT:
315
            if( geom.getType()==Geometry.TYPES.MULTIPOINT ) {
316
                MultiPoint x = (MultiPoint) geom;
317
                if( x.getPrimitivesNumber()==1 ) {
318
                    geom = x.getPrimitiveAt(0);
319
                }
320
            }
321
        }
322
        return geom;
323
    }
324
    
325
}
tags/org.gvsig.spatialite-1.0.5/org.gvsig.spatialite.provider/src/main/java/org/gvsig/spatialite/dal/SpatiaLiteStoreProviderFactory.java
1

  
2
package org.gvsig.spatialite.dal;
3

  
4
import org.gvsig.fmap.dal.DataParameters;
5
import org.gvsig.fmap.dal.exception.InitializeException;
6
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
7
import org.gvsig.fmap.dal.store.jdbc.JDBCConnectionParameters;
8
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParameters;
9
import org.gvsig.fmap.dal.store.jdbc2.JDBCHelper;
10
import org.gvsig.fmap.dal.store.jdbc2.JDBCStoreProvider;
11
import org.gvsig.fmap.dal.store.jdbc2.impl.JDBCStoreProviderFactory;
12

  
13

  
14
public class SpatiaLiteStoreProviderFactory extends JDBCStoreProviderFactory {
15

  
16
    private static final String NAME = SpatiaLiteLibrary.NAME;
17
    
18
    public SpatiaLiteStoreProviderFactory() {
19
        super(
20
                NAME, 
21
                "SpatiaLite store"
22
        );
23
    }
24

  
25
    @Override
26
    public JDBCStoreProvider createProvider(
27
            DataParameters parameters,
28
            DataStoreProviderServices providerServices
29
    ) throws InitializeException {
30
        JDBCHelper helper = new SpatiaLiteHelper((JDBCConnectionParameters) parameters);
31
        JDBCStoreProvider provider = helper.createProvider(
32
                (JDBCStoreParameters) parameters, 
33
                providerServices
34
        );
35
        return provider;
36
    }
37

  
38
    @Override
39
    public JDBCStoreParameters createParameters() {
40
        JDBCStoreParameters params = new SpatiaLiteStoreParameters();
41
        return params;
42
    }
43
    
44
}
tags/org.gvsig.spatialite-1.0.5/org.gvsig.spatialite.provider/src/main/java/org/gvsig/spatialite/dal/SpatiaLiteStoreParameters.java
1
/* gvSIG. Geographic Information System of the Valencian Government
2
*
3
* Copyright (C) 2007-2008 Infrastructures and Transports Department
4
* of the Valencian Government (CIT)
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
 */
22
package org.gvsig.spatialite.dal;
23

  
24
import java.io.File;
25
import java.util.Properties;
26
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
27
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParameters;
28

  
29
public class SpatiaLiteStoreParameters extends JDBCStoreParameters implements SpatiaLiteConnectionParameters {
30

  
31
    private final SpatiaLiteConnectionParametersHelper helper;
32
    
33
    public SpatiaLiteStoreParameters() {
34
        super(
35
                SpatiaLiteLibrary.NAME + "StoreParameters",
36
                SpatiaLiteLibrary.NAME
37
        );
38
        this.helper = new SpatiaLiteConnectionParametersHelper(this);
39
    }
40

  
41
    @Override
42
    public String getUrl() {
43
        return this.helper.getUrl();
44
    }
45
    
46
    @Override
47
    public void validate() throws ValidateDataParametersException {
48
        this.helper.validate();
49
        super.validate();
50
    }
51
    
52
    @Override
53
    public boolean getEnableSpatiaLite() {
54
        return this.helper.getEnableSpatiaLite();
55
    }
56

  
57
    @Override
58
    public boolean getEnableLoadExtension() {
59
        return this.helper.getEnableLoadExtension();
60
    }
61

  
62
    @Override
63
    public boolean getEnableSharedCache() {
64
        return this.helper.getEnableSharedCache();
65
    }
66

  
67
    @Override
68
    public void setEnableSpatiaLite(boolean v) {
69
        this.helper.setEnableSpatiaLite(v);
70
    }
71

  
72
    @Override
73
    public void setEnableLoadExtension(boolean v) {
74
        this.helper.setEnableLoadExtension(v);
75
    }
76

  
77
    @Override
78
    public void setEnableSharedCache(boolean v) {
79
        this.helper.setEnableSharedCache(v);
80
    }
81

  
82
    @Override
83
    public Properties getProperties() {
84
        return this.helper.getProperties();
85
    }
86

  
87
    @Override
88
    public File getFile() {
89
        return this.helper.getFile();
90
    }
91
    
92
    @Override
93
    public void setFile(File database) {
94
        this.helper.setFile(database);
95
    }
96

  
97
}
tags/org.gvsig.spatialite-1.0.5/org.gvsig.spatialite.provider/src/main/java/org/gvsig/spatialite/dal/SpatiaLiteConnectionParameters.java
1

  
2
package org.gvsig.spatialite.dal;
3

  
4
import java.util.Properties;
5
import org.gvsig.fmap.dal.serverexplorer.filesystem.FilesystemStoreParameters;
6
import org.gvsig.fmap.dal.store.jdbc.JDBCConnectionParameters;
7

  
8
public interface SpatiaLiteConnectionParameters extends JDBCConnectionParameters, FilesystemStoreParameters {
9
    
10
    public boolean getEnableSpatiaLite();
11
    public boolean getEnableLoadExtension();
12
    public boolean getEnableSharedCache();
13

  
14
    public void setEnableSpatiaLite(boolean v);
15
    public void setEnableLoadExtension(boolean v);
16
    public void setEnableSharedCache(boolean v);
17
    
18
    public Properties getProperties();
19
}
tags/org.gvsig.spatialite-1.0.5/org.gvsig.spatialite.provider/src/main/java/org/gvsig/spatialite/dal/SpatiaLiteConnectionParametersHelper.java
1

  
2
package org.gvsig.spatialite.dal;
3

  
4
import java.io.File;
5
import java.util.Properties;
6
import org.apache.commons.io.FilenameUtils;
7
import org.apache.commons.lang3.BooleanUtils;
8
import org.apache.commons.lang3.StringUtils;
9
import org.gvsig.fmap.dal.DataParameters;
10
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
11
import org.gvsig.fmap.dal.resource.db.DBParameters;
12
import org.gvsig.fmap.dal.store.jdbc.JDBCConnectionParameters;
13
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParameters;
14

  
15

  
16
public class SpatiaLiteConnectionParametersHelper {
17

  
18
    private final JDBCConnectionParameters parameters;
19
    
20
    private static final String ENABLE_SHARED_CACHE = "enable_shared_cache";
21
    private static final String ENABLE_LOAD_EXTENSION = "enable_load_extension";
22
    private static final String ENABLE_SPATIALITE = "enable_spatialite";
23
    private static final String DATABASE_FILE = "database_file";
24
    
25
    public SpatiaLiteConnectionParametersHelper(JDBCConnectionParameters parameters) {
26
        this.parameters = parameters;
27
    }
28

  
29
    public String getUrl() {
30
        String url = (String) this.getDynValue(JDBCConnectionParameters.URL_PARAMTER_NAME);
31
        if( StringUtils.isEmpty(url) ) {
32
            url = SpatiaLiteHelper.getConnectionURL((SpatiaLiteConnectionParameters) this.parameters);
33
            this.setDynValue(JDBCConnectionParameters.URL_PARAMTER_NAME,url);
34
        }
35
        return url;
36
    }
37
    
38
    public void validate() throws ValidateDataParametersException {
39
        if (this.getDynValue(JDBCConnectionParameters.JDBC_DRIVER_CLASS_PARAMTER_NAME) == null) {
40
            this.setDynValue(
41
                JDBCConnectionParameters.JDBC_DRIVER_CLASS_PARAMTER_NAME,
42
                SpatiaLiteHelper.SpatiaLiteJDBCDriver
43
            );
44
        }
45
        if (getFile() == null) {
46
            throw new ValidateDataParametersException();
47
        }
48
    }
49

  
50
    private Object getDynValue(String name) {
51
        return ((DataParameters)this.parameters).getDynValue(name);
52
    }
53
    
54
    private void setDynValue(String name, Object value) {
55
        ((DataParameters)this.parameters).setDynValue(name,value);
56
    }
57
    
58
    public boolean getEnableSpatiaLite() {
59
        return (boolean) this.getDynValue(ENABLE_SPATIALITE);
60
    }
61

  
62
    public boolean getEnableLoadExtension() {
63
        return (boolean) this.getDynValue(ENABLE_LOAD_EXTENSION);
64
    }
65

  
66
    public boolean getEnableSharedCache() {
67
        return (boolean) this.getDynValue(ENABLE_SHARED_CACHE);
68
    }
69

  
70
    public void setEnableSpatiaLite(boolean v) {
71
        this.setDynValue(ENABLE_SPATIALITE, v);
72
    }
73

  
74
    public void setEnableLoadExtension(boolean v) {
75
        this.setDynValue(ENABLE_LOAD_EXTENSION, v);
76
    }
77

  
78
    public void setEnableSharedCache(boolean v) {
79
        this.setDynValue(ENABLE_SHARED_CACHE, v);
80
    }
81

  
82
    public File getFile() {
83
        File f = (File) this.getDynValue(DATABASE_FILE);
84
        if( this.getDynValue(DBParameters.DBNAME_PARAMTER_NAME)==null &&
85
            f != null ) {
86
            String dbname = FilenameUtils.getBaseName(f.getName());
87
            this.setDynValue(DBParameters.DBNAME_PARAMTER_NAME, dbname);
88
        }
89
        return f;
90
    }
91
    
92
    public void setFile(File database) {
93
        this.setDynValue(DATABASE_FILE, database);
94
        if( this.getDynValue(DBParameters.DBNAME_PARAMTER_NAME)==null &&
95
            database != null ) {
96
            String dbname = FilenameUtils.getBaseName(database.getName());
97
            this.setDynValue(DBParameters.DBNAME_PARAMTER_NAME, dbname);
98
        }
99
    }
100

  
101
    public Properties getProperties() {
102
        Properties props = new Properties();
103
        props.setProperty("enable_shared_cache", BooleanUtils.toStringTrueFalse(getEnableSharedCache()));
104
        props.setProperty("enable_load_extension", BooleanUtils.toStringTrueFalse(getEnableLoadExtension()));
105
        props.setProperty("enable_spatialite", BooleanUtils.toStringTrueFalse(getEnableSpatiaLite()));
106
        return props;
107
    }    
108
}
tags/org.gvsig.spatialite-1.0.5/org.gvsig.spatialite.provider/src/main/java/org/gvsig/spatialite/dal/operations/SpatiaLiteOperationsFactory.java
1

  
2
package org.gvsig.spatialite.dal.operations;
3

  
4
import java.util.List;
5
import org.cresques.cts.IProjection;
6
import org.gvsig.fmap.dal.feature.EditableFeatureType;
7
import org.gvsig.fmap.dal.store.jdbc2.JDBCHelper;
8
import org.gvsig.fmap.dal.store.jdbc2.spi.operations.FetchFeatureTypeOperation;
9
import org.gvsig.fmap.dal.store.jdbc2.spi.operations.OperationsFactoryBase;
10

  
11

  
12
public class SpatiaLiteOperationsFactory extends OperationsFactoryBase {
13
    
14
    public SpatiaLiteOperationsFactory(JDBCHelper helper) {
15
        super(helper);
16
    }
17

  
18
    @Override
19
    public FetchFeatureTypeOperation createFetchFeatureType(EditableFeatureType type, String database, String schema, String table, List<String> primaryKeys, String defaultGeometryField, IProjection crs) {
20
        return new SpatiaLiteFetchFeatureTypeOperation(
21
                helper, type, database, schema, table, primaryKeys, 
22
                defaultGeometryField, crs
23
        );
24
    }  
25
    
26
}
tags/org.gvsig.spatialite-1.0.5/org.gvsig.spatialite.provider/src/main/java/org/gvsig/spatialite/dal/operations/SpatiaLiteFetchFeatureTypeOperation.java
1

  
2
package org.gvsig.spatialite.dal.operations;
3

  
4
import java.sql.Connection;
5
import java.sql.ResultSet;
6
import java.sql.ResultSetMetaData;
7
import java.sql.SQLException;
8
import java.sql.Statement;
9
import java.util.HashMap;
10
import java.util.List;
11
import java.util.Map;
12
import java.util.logging.Level;
13
import java.util.logging.Logger;
14
import org.apache.commons.lang3.StringUtils;
15
import org.cresques.cts.IProjection;
16
import org.gvsig.fmap.dal.DataTypes;
17
import org.gvsig.fmap.dal.exception.DataException;
18
import org.gvsig.fmap.dal.feature.EditableFeatureAttributeDescriptor;
19
import org.gvsig.fmap.dal.feature.EditableFeatureType;
20
import org.gvsig.fmap.dal.store.jdbc2.JDBCHelper;
21
import org.gvsig.fmap.dal.store.jdbc2.JDBCUtils;
22
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCSQLBuilderBase;
23
import org.gvsig.fmap.dal.store.jdbc2.spi.operations.FetchFeatureTypeOperation;
24
import org.gvsig.fmap.geom.Geometry;
25
import org.gvsig.fmap.geom.GeometryLocator;
26
import org.gvsig.fmap.geom.GeometryManager;
27
import org.gvsig.fmap.geom.type.GeometryType;
28

  
29
public class SpatiaLiteFetchFeatureTypeOperation extends FetchFeatureTypeOperation {
30

  
31
    private static Map<String,GeometryType>spatialiteGeometryTypes = null;
32
    private Map<String,String> columns_def;
33
    
34
    public SpatiaLiteFetchFeatureTypeOperation(
35
            JDBCHelper helper
36
        ) {
37
        super(helper);
38
    }
39

  
40
    private GeometryType getGT(
41
            GeometryManager manager, 
42
            int type, 
43
            int subtype
44
        ) {
45
        try {
46
            return manager.getGeometryType(type, subtype);
47
        } catch (Exception ex) {
48
            return null;
49
        }
50
    }
51
    
52
    public SpatiaLiteFetchFeatureTypeOperation(
53
            JDBCHelper helper,
54
            EditableFeatureType featureType,
55
            String dbname,
56
            String schema,
57
            String table,
58
            List<String> primaryKeys,
59
            String defaultGeometryColumn,
60
            IProjection crs
61
        ) {
62
        super(helper, featureType, dbname, schema, table, primaryKeys, defaultGeometryColumn, crs);
63
    }            
64

  
65
    @Override
66
    public void fetch(EditableFeatureType featureType, Connection conn, String dbname, String schema, String table, List<String> pks, String defaultGeometryColumn, IProjection crs) throws DataException {
67
        columns_def = new HashMap<>();
68
        try {
69
            ResultSet dbmetadata = this.getConnection().getMetaData().getColumns(null, null, table, null);
70
            while( dbmetadata.next() ) {
71
                columns_def.put(dbmetadata.getString("COLUMN_NAME"), StringUtils.defaultString(dbmetadata.getString("COLUMN_DEF")));
72
            }
73
        } catch (SQLException ex) {
74
            logger.warn("Can't read metadata from table '"+table+"'.",ex);
75
        }
76
        super.fetch(featureType, conn, dbname, schema, table, pks, defaultGeometryColumn, crs);
77
    }
78
    
79
    @Override
80
    protected boolean isInPrimaryKeys(List<String> pks, EditableFeatureAttributeDescriptor attr) {
81
        // En SpatiaLite, los nombres obtenidos de las pks de los metadados no 
82
        // coinciden conlos nombres de los campos ya que unos estan en mayusculas 
83
        // y otros en minusculas, asi que comparamos con IgnoreCase.
84
        for (String pk : pks) {
85
            if( StringUtils.equalsIgnoreCase(pk, attr.getName()) ) {
86
                return true;
87
            }
88
        }
89
        return false;
90
    }
91

  
92
    @Override
93
    protected int getDataTypeFromMetadata(
94
            ResultSetMetaData rsMetadata,
95
            int colIndex
96
        ) throws SQLException {
97
        // En SpatiaLite no existe el tipo de dato Geometria, las geometrias
98
        // se guardan en un BLOB, y en getColumnTypeName se indica el tipo
99
        // de la geometria.
100
        String columnTypeName = rsMetadata.getColumnTypeName(colIndex);
101
        GeometryType gt = getGeometryTypeFromSpatiaLiteTypeName(columnTypeName);
102
        if( gt!=null ) {
103
            return DataTypes.GEOMETRY;
104
        }
105
        int columnType = rsMetadata.getColumnType(colIndex);
106
        String columnName = rsMetadata.getColumnName(colIndex);
107
        String column_def = this.columns_def.getOrDefault(columnName,"").trim();
108
        if( columnType == java.sql.Types.INTEGER && (
109
            StringUtils.startsWithIgnoreCase(column_def, "date(") || 
110
            StringUtils.startsWithIgnoreCase(column_def, "datetime(") || 
111
            StringUtils.startsWithIgnoreCase(column_def, "strftime(") )
112
            ) {
113
            return DataTypes.DATE;
114
        }
115
        return super.getDataTypeFromMetadata(rsMetadata, colIndex);
116
    }
117
        
118
    @Override
119
    protected void fetchGeometryTypeAndSRS(
120
            EditableFeatureAttributeDescriptor attr,
121
            ResultSetMetaData rsMetadata,
122
            int colIndex
123
        ) {
124
        if( attr.getType()!=DataTypes.GEOMETRY ) {
125
            return;
126
        }
127
        try {
128
            String typeName = rsMetadata.getColumnTypeName(colIndex);
129
            GeometryType gt = getGeometryTypeFromSpatiaLiteTypeName(typeName);
130
            if( gt != null ) {
131
                attr.setGeometryType(gt);
132

  
133
                JDBCSQLBuilderBase sqlbuilder = this.createSQLBuilder();
134
                sqlbuilder.select().column().name("f_table_name");
135
                sqlbuilder.select().column().name("f_geometry_column");
136
                sqlbuilder.select().column().name("geometry_type");
137
                sqlbuilder.select().column().name("coord_dimension");
138
                sqlbuilder.select().column().name("srid");
139
                sqlbuilder.select().column().name("spatial_index_enabled");
140
                sqlbuilder.select().where().set(
141
                        sqlbuilder.eq(
142
                                sqlbuilder.column("f_table_name"),
143
                                sqlbuilder.constant(this.getTablename())
144
                        )
145
                );                
146
                sqlbuilder.select().where().and(
147
                        sqlbuilder.eq(
148
                                sqlbuilder.column("f_geometry_column"),
149
                                sqlbuilder.constant(attr.getName())
150
                        )
151
                );         
152
                sqlbuilder.select().from().table().name("geometry_columns");
153
                Statement st = null;
154
                ResultSet rs = null;
155
                int srsid = -1;
156
                try {
157
                    st = this.getConnection().createStatement();
158
                    rs = JDBCUtils.executeQuery(st, sqlbuilder.toString());
159
                    if (rs.next()) {
160
                        srsid = rs.getInt("srid");
161
                    }
162
                } finally {
163
                    JDBCUtils.closeQuietly(rs);
164
                    JDBCUtils.closeQuietly(st);
165
                }
166
                if( srsid > 0 ) {
167
                    attr.setSRS(this.helper.getProjectionFromSRSId(srsid));
168
                }
169
            }
170
        } catch (Exception ex) {
171
            logger.debug("Can't get geometry type and srs from column '"+attr.getName()+"'.",ex);
172
        }
173
    }
174

  
175
    private GeometryType getGeometryTypeFromSpatiaLiteTypeName(String typeName) {
176
        if( spatialiteGeometryTypes==null ) {
177
            GeometryManager manager = GeometryLocator.getGeometryManager();
178
            spatialiteGeometryTypes = new HashMap<>();
179
            spatialiteGeometryTypes.put("POINT", getGT(manager, Geometry.TYPES.POINT,Geometry.SUBTYPES.GEOM2D));
180
            spatialiteGeometryTypes.put("POINTZ", getGT(manager, Geometry.TYPES.POINT,Geometry.SUBTYPES.GEOM3D));
181
            spatialiteGeometryTypes.put("POINTM", getGT(manager, Geometry.TYPES.POINT,Geometry.SUBTYPES.GEOM2DM));
182
            spatialiteGeometryTypes.put("POINTZM", getGT(manager, Geometry.TYPES.POINT,Geometry.SUBTYPES.GEOM3DM));
183
            
184
            spatialiteGeometryTypes.put("LINESTRING", getGT(manager, Geometry.TYPES.LINE,Geometry.SUBTYPES.GEOM2D));
185
            spatialiteGeometryTypes.put("LINESTRINGZ", getGT(manager, Geometry.TYPES.LINE,Geometry.SUBTYPES.GEOM3D));
186
            spatialiteGeometryTypes.put("LINESTRINGM", getGT(manager, Geometry.TYPES.LINE,Geometry.SUBTYPES.GEOM2DM));
187
            spatialiteGeometryTypes.put("LINESTRINGZM", getGT(manager, Geometry.TYPES.LINE,Geometry.SUBTYPES.GEOM3DM));
188
            
189
            spatialiteGeometryTypes.put("POLYGON", getGT(manager, Geometry.TYPES.POLYGON,Geometry.SUBTYPES.GEOM2D));
190
            spatialiteGeometryTypes.put("POLYGONZ", getGT(manager, Geometry.TYPES.POLYGON,Geometry.SUBTYPES.GEOM3D));
191
            spatialiteGeometryTypes.put("POLYGONM", getGT(manager, Geometry.TYPES.POLYGON,Geometry.SUBTYPES.GEOM2DM));
192
            spatialiteGeometryTypes.put("POLYGONZM", getGT(manager, Geometry.TYPES.POLYGON,Geometry.SUBTYPES.GEOM3DM));
193

  
194
            spatialiteGeometryTypes.put("MULTIPOINT", getGT(manager, Geometry.TYPES.MULTIPOINT,Geometry.SUBTYPES.GEOM2D));
195
            spatialiteGeometryTypes.put("MULTIPOINTZ", getGT(manager, Geometry.TYPES.MULTIPOINT,Geometry.SUBTYPES.GEOM3D));
196
            spatialiteGeometryTypes.put("MULTIPOINTM", getGT(manager, Geometry.TYPES.MULTIPOINT,Geometry.SUBTYPES.GEOM2DM));
197
            spatialiteGeometryTypes.put("MULTIPOINTZM", getGT(manager, Geometry.TYPES.MULTIPOINT,Geometry.SUBTYPES.GEOM3DM));
198

  
199
            spatialiteGeometryTypes.put("MULTILINESTRING", getGT(manager, Geometry.TYPES.MULTILINE,Geometry.SUBTYPES.GEOM2D));
200
            spatialiteGeometryTypes.put("MULTILINESTRINGZ", getGT(manager, Geometry.TYPES.MULTILINE,Geometry.SUBTYPES.GEOM3D));
201
            spatialiteGeometryTypes.put("MULTILINESTRINGM", getGT(manager, Geometry.TYPES.MULTILINE,Geometry.SUBTYPES.GEOM2DM));
202
            spatialiteGeometryTypes.put("MULTILINESTRINGZM", getGT(manager, Geometry.TYPES.MULTILINE,Geometry.SUBTYPES.GEOM3DM));
203

  
204
            spatialiteGeometryTypes.put("MULTIPOLYGON", getGT(manager, Geometry.TYPES.MULTIPOLYGON,Geometry.SUBTYPES.GEOM2D));
205
            spatialiteGeometryTypes.put("MULTIPOLYGONZ", getGT(manager, Geometry.TYPES.MULTIPOLYGON,Geometry.SUBTYPES.GEOM3D));
206
            spatialiteGeometryTypes.put("MULTIPOLYGONM", getGT(manager, Geometry.TYPES.MULTIPOLYGON,Geometry.SUBTYPES.GEOM2DM));
207
            spatialiteGeometryTypes.put("MULTIPOLYGONZM", getGT(manager, Geometry.TYPES.MULTIPOLYGON,Geometry.SUBTYPES.GEOM3DM));
208

  
209
            spatialiteGeometryTypes.put("GEOMETRY", getGT(manager, Geometry.TYPES.GEOMETRY,Geometry.SUBTYPES.GEOM2D));
210
            spatialiteGeometryTypes.put("GEOMETRYZ", getGT(manager, Geometry.TYPES.GEOMETRY,Geometry.SUBTYPES.GEOM3D));
211
            spatialiteGeometryTypes.put("GEOMETRYM", getGT(manager, Geometry.TYPES.GEOMETRY,Geometry.SUBTYPES.GEOM2DM));
212
            spatialiteGeometryTypes.put("GEOMETRYZM", getGT(manager, Geometry.TYPES.GEOMETRY,Geometry.SUBTYPES.GEOM3DM));
213
        }
214
        return spatialiteGeometryTypes.get(typeName);
215
    }
216
    
217
}
tags/org.gvsig.spatialite-1.0.5/org.gvsig.spatialite.provider/src/main/java/org/gvsig/spatialite/dal/SpatiaLiteExplorerParameters.java
1
/* gvSIG. Geographic Information System of the Valencian Government
2
*
3
* Copyright (C) 2007-2008 Infrastructures and Transports Department
4
* of the Valencian Government (CIT)
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
 */
22
/**
23
 *
24
 */
25
package org.gvsig.spatialite.dal;
26

  
27
import java.io.File;
28
import java.util.Properties;
29
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
30
import org.gvsig.fmap.dal.store.jdbc.JDBCServerExplorerParameters;
31

  
32
public class SpatiaLiteExplorerParameters extends
33
        JDBCServerExplorerParameters 
34
    implements
35
        SpatiaLiteConnectionParameters
36
    {
37
    
38
    private final SpatiaLiteConnectionParametersHelper helper;
39

  
40
    public SpatiaLiteExplorerParameters() {
41
        super(
42
                SpatiaLiteLibrary.NAME + "ServerExplorerParameters",
43
                SpatiaLiteLibrary.NAME
44
        );
45
        this.helper = new SpatiaLiteConnectionParametersHelper(this);
46
    }
47

  
48
    @Override
49
    public String getUrl() {
50
        return this.helper.getUrl();
51
    }
52
    
53
    @Override
54
    public void validate() throws ValidateDataParametersException {
55
        this.helper.validate();
56
        super.validate();
57
    }
58

  
59
    @Override
60
    public boolean getEnableSpatiaLite() {
61
        return this.helper.getEnableSpatiaLite();
62
    }
63

  
64
    @Override
65
    public boolean getEnableLoadExtension() {
66
        return this.helper.getEnableLoadExtension();
67
    }
68

  
69
    @Override
70
    public boolean getEnableSharedCache() {
71
        return this.helper.getEnableSharedCache();
72
    }
73

  
74
    @Override
75
    public void setEnableSpatiaLite(boolean v) {
76
        this.helper.setEnableSpatiaLite(v);
77
    }
78

  
79
    @Override
80
    public void setEnableLoadExtension(boolean v) {
81
        this.helper.setEnableLoadExtension(v);
82
    }
83

  
84
    @Override
85
    public void setEnableSharedCache(boolean v) {
86
        this.helper.setEnableSharedCache(v);
87
    }
88

  
89
    @Override
90
    public Properties getProperties() {
91
        return this.helper.getProperties();
92
    }
93

  
94
    @Override
95
    public File getFile() {
96
        return this.helper.getFile();
97
    }
98
    
99
    @Override
100
    public void setFile(File database) {
101
        this.helper.setFile(database);
102
    }
103

  
104

  
105
}
tags/org.gvsig.spatialite-1.0.5/org.gvsig.spatialite.provider/src/main/java/org/gvsig/spatialite/dal/SpatiaLiteLibrary.java
1
/* gvSIG. Geographic Information System of the Valencian Government
2
 *
3
 * Copyright (C) 2007-2008 Infrastructures and Transports Department
4
 * of the Valencian Government (CIT)
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
 */
22
package org.gvsig.spatialite.dal;
23

  
24
import org.gvsig.fmap.dal.DALLibrary;
25
import org.gvsig.fmap.dal.DALLocator;
26
import org.gvsig.fmap.dal.spi.DataManagerProviderServices;
27
import org.gvsig.fmap.dal.store.db.DBHelper;
28
import org.gvsig.fmap.dal.store.jdbc2.JDBCLibrary;
29
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCStoreProviderBase;
30
import org.gvsig.metadata.exceptions.MetadataException;
31
import org.gvsig.tools.library.AbstractLibrary;
32
import org.gvsig.tools.library.LibraryException;
33

  
34
public class SpatiaLiteLibrary extends AbstractLibrary {
35

  
36
    public static final String NAME = "SpatiaLite";
37

  
38
    @Override
39
    public void doRegistration() {
40
        registerAsServiceOf(DALLibrary.class);
41
        require(JDBCLibrary.class);
42
    }
43

  
44
    @Override
45
    protected void doInitialize() throws LibraryException {
46
    }
47

  
48
    @Override
49
    protected void doPostInitialize() throws LibraryException {
50
        LibraryException ex = null;
51

  
52
        DataManagerProviderServices dataman = 
53
                (DataManagerProviderServices) DALLocator.getDataManager();
54

  
55
        try {
56
            Class.forName(SpatiaLiteHelper.SpatiaLiteJDBCDriver);
57
        } catch(Throwable th) {
58
            SpatiaLiteHelper.logger.warn("Can't load SpatiaLite JDBC Driver.",th);
59
        }
60
        
61
        DBHelper.registerParametersDefinition(
62
                NAME + "StoreParameters",
63
                SpatiaLiteStoreParameters.class,
64
                dataman.getResourceAsStream(this, NAME + "Parameters.xml")
65
        );
66
        DBHelper.registerParametersDefinition(
67
                NAME + "NewStoreParameters",
68
                SpatiaLiteNewStoreParameters.class,
69
                dataman.getResourceAsStream(this, NAME + "Parameters.xml")
70
        );
71
        DBHelper.registerParametersDefinition(
72
                NAME + "ServerExplorerParameters",
73
                SpatiaLiteExplorerParameters.class,
74
                dataman.getResourceAsStream(this, NAME + "Parameters.xml")
75
        );
76
//        DBHelper.registerParametersDefinition(
77
//                NAME + "ResourceParameters",
78
//                SpatiaLiteResourceParameters.class,
79
//                dataman.getResourceAsStream(this, NAME + "Parameters.xml")
80
//        );
81
        try {
82
            DBHelper.registerMetadataDefinition(
83
                NAME,
84
                JDBCStoreProviderBase.class,
85
                dataman.getResourceAsStream(this, NAME + "Metadata.xml")
86
            );
87
        } catch (MetadataException e) {
88
            ex = new LibraryException(this.getClass(), e);
89
        }
90

  
91
//        ResourceManagerProviderServices resman = (ResourceManagerProviderServices) DALLocator
92
//                .getResourceManager();
93
//
94
//        if (!resman.getResourceProviders().contains(NAME)) {
95
//            resman.register(NAME,
96
//                "Resource for " + NAME,
97
//                SpatiaLiteResource.class,
98
//                SpatiaLiteResourceParameters.class
99
//            );
100
//        }
101

  
102
        if (!dataman.getStoreProviderRegister().exits(NAME)) {
103
            dataman.registerStoreProviderFactory(new SpatiaLiteStoreProviderFactory());
104
        }
105

  
106
        if (!dataman.getServerExplorerRegister().exits(NAME)) {
107
            dataman.registerServerExplorerFactory(new SpatiaLiteExplorerFactory());
108
        }
109
        if (ex != null) {
110
            throw ex;
111
        }
112
    }
113

  
114
}
tags/org.gvsig.spatialite-1.0.5/org.gvsig.spatialite.provider/src/main/java/org/gvsig/spatialite/dal/SpatiaLiteSQLBuilder.java
1
package org.gvsig.spatialite.dal;
2

  
3
import java.sql.PreparedStatement;
4
import java.text.MessageFormat;
5
import java.util.ArrayList;
6
import java.util.Date;
7
import java.util.List;
8
import org.gvsig.fmap.dal.DataTypes;
9
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
10
import org.gvsig.fmap.dal.feature.FeatureType;
11
import org.gvsig.fmap.dal.feature.spi.FeatureProvider;
12
import org.gvsig.fmap.dal.store.jdbc2.JDBCUtils;
13
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCSQLBuilderBase;
14
import org.gvsig.fmap.geom.Geometry;
15

  
16
public class SpatiaLiteSQLBuilder extends JDBCSQLBuilderBase {
17

  
18
    private final SpatiaLiteHelper helper;
19

  
20
    public SpatiaLiteSQLBuilder(SpatiaLiteHelper helper) {
21
        super();
22
        
23
        this.helper = helper;
24
        
25
        //
26
        // SpatiaLite 4.3.0, SQL functions reference list
27
        //
28
        // http://www.gaia-gis.it/gaia-sins/spatialite-sql-4.3.0.html
29
        //
30
        // https://sqlite.org/lang.html
31
        //
32
        
33
        config.set(SQLConfig.default_schema, "");
34
        config.set(SQLConfig.support_schemas, false);
35
        config.set(SQLConfig.allowAutomaticValues, true);
36
        config.set(SQLConfig.geometry_type_support, this.helper.getGeometrySupportType());
37
        config.set(SQLConfig.has_spatial_functions, this.helper.hasSpatialFunctions());
38

  
39
        config.remove_functionality(SQLConfig.DELETE_GEOMETRY_COLUMN_FROM_TABLE_schema_table);
40
        config.remove_functionality(SQLConfig.DELETE_GEOMETRY_COLUMN_FROM_TABLE_table);
41
         
42
        config.set(SQLConfig.UPDATE_TABLE_STATISTICS_table,"SELECT UpdateLayerStatistics({0})");
43

  
44
        config.set(SQLConfig.ST_GeomFromEWKB, "GeomFromWKB({0}, {1})");
45
        config.set(SQLConfig.ST_AsEWKB, "AsEWKB(({0}))");        
46
        config.set(SQLConfig.ST_ExtentAggregate, "Extent({0})");        
47
        config.set(SQLConfig.ST_UnionAggregate, "ST_Union({0})");
48
        
49
        config.set(SQLConfig.lcase, "lower({0})");
50
        config.set(SQLConfig.ucase, "upper({0})");
51
        config.set(SQLConfig.operator_ILIKE, "lower({0}) LIKE lower({1})");
52
        config.set(SQLConfig.isNull, "( ({0}) ISNULL )");
53
        config.set(SQLConfig.notIsNull, "( ({0}) NOT NULL )");
54

  
55
        config.set(SQLConfig.type_boolean, "INTEGER");
56
        config.set(SQLConfig.type_byte, "INTEGER");
57
        config.set(SQLConfig.type_bytearray, "");
58
        config.set(SQLConfig.type_geometry, "BLOB");
59
        config.set(SQLConfig.type_char, "TEXT");
60
        config.set(SQLConfig.type_date, "INTEGER");
61
        config.set(SQLConfig.type_double, "REAL"); 
62
        config.set(SQLConfig.type_numeric_p, "REAL");
63
        config.set(SQLConfig.type_numeric_ps, "REAL");
64
        config.set(SQLConfig.type_bigdecimal, "REAL");
65
        config.set(SQLConfig.type_float, "REAL");
66
        config.set(SQLConfig.type_int, "INTEGER");
67
        config.set(SQLConfig.type_long, "INTEGER");
68
        config.set(SQLConfig.type_string, "TEXT");
69
        config.set(SQLConfig.type_string_p, "TEXT");
70
        config.set(SQLConfig.type_time, "INTEGER");
71
        config.set(SQLConfig.type_timestamp, "INTEGER");
72
        config.set(SQLConfig.type_version, "TEXT");
73
        config.set(SQLConfig.type_URI, "TEXT");
74
        config.set(SQLConfig.type_URL, "TEXT");
75
        config.set(SQLConfig.type_FILE, "TEXT");
76
        config.set(SQLConfig.type_FOLDER, "TEXT");        
77
    }
78

  
79
    public class SpatiaLiteTableNameBuilderBase extends TableNameBuilderBase {
80

  
81
        @Override
82
        public boolean has_schema() {
83
            return false;
84
        }
85

  
86
        @Override
87
        public boolean has_database() {
88
            return false;
89
        }
90
        
91
    }
92
    
93
    protected class SpatiaLiteCreateTableBuilder extends CreateTableBuilderBase {
94

  
95
        @Override
96
        public List<String> toStrings() {
97
            //
98
            // Respecto al base cambia la declaracion de campo automaticos
99
            // SpatiaLite usa AUTOINCREMENT en lugar de SERIAL y que hay que usar
100
            // la funcion AddGeometryColumn para a?adir las columnas de tipo
101
            // geometria.
102
            // El orden en el que hay que declarar las constrains tambien cambia
103
            // respecto al que hay por defecto.
104
            //
105
            List<String> sqls = new ArrayList<>();
106
            StringBuilder builder = new StringBuilder();
107

  
108
            builder.append("CREATE TABLE ");
109
            builder.append(this.table.toString());
110
            builder.append(" (");
111
            boolean first = true;
112
            for (ColumnDescriptorBuilder column : columns) {
113
                if( column.isGeometry() ) {
114
                    continue;
115
                }
116
                if (first) {
117
                    first = false;
118
                } else {
119
                    builder.append(", ");
120
                }
121
                builder.append(identifier(column.getName()));
122
                builder.append(" ");
123
                builder.append(sqltype(column.getType(), column.getPrecision(), column.getSize()));
124
                if (column.isPrimaryKey()) {
125
                    builder.append(" PRIMARY KEY");
126
                }
127
                if( column.isAutomatic() ) {
128
                    builder.append(" AUTOINCREMENT");
129
                }
130
                if (column.getDefaultValue() == null) {
131
                    if (column.allowNulls()) {
132
                        builder.append(" DEFAULT NULL");
133
                    }
134
                } else {
135
                    if( column.getType() == DataTypes.DATE ) {
136
                        builder.append(" DEFAULT ( date('");
137
                        builder.append(column.getDefaultValue().toString());
138
                        builder.append("') )");
139
                    } else {
140
                        builder.append(" DEFAULT '");
141
                        builder.append(column.getDefaultValue().toString());
142
                        builder.append("'");
143
                    }
144
                }
145
                if (!column.allowNulls()) {
146
                    builder.append(" NOT NULL");
147
                }
148
            }
149
            builder.append(" )");
150
            sqls.add(builder.toString());
151

  
152
            String AddGeometryColumn = "SELECT AddGeometryColumn({0} , {1} , {2,number,#######} , {3}, {4}, {5})";
153
            for (ColumnDescriptorBuilderBase column : columns) {
154
                if( column.isGeometry() ) {
155
                    String sql = MessageFormat.format(
156
                        AddGeometryColumn,
157
                        this.table.toString(),
158
                        identifier(column.getName()),
159
                        column.getGeometrySRSId(),
160
                        constant(sqlgeometrytype(column.getGeometryType(), column.getGeometrySubtype())),
161
                        constant(sqlgeometrydimension(column.getGeometryType(), column.getGeometrySubtype())),
162
                        column.allowNulls()? 1:0
163
                    );
164
                    sqls.add(sql);
165
                }
166
            }
167
            
168
            return sqls;
169
        }
170
    }
171

  
172
    public class SpatiaLiteSelectBuilderBase extends SelectBuilderBase {
173
        
174
        protected boolean isValid(StringBuilder message) {
175
            if( message == null ) {
176
                message = new StringBuilder();
177
            }
178
            if( this.has_offset() && !this.has_order_by() ) {
179
                // Algunos gestores de BBDD requieren que se especifique un
180
                // orden para poder usar OFFSET. Como eso parece buena idea para
181
                // asegurar que siempre tengamos los mismo resultados, lo exijimos
182
                // siempre.
183
                message.append("Can't use OFFSET without an ORDER BY.");
184
                return false;
185
            }
186
            return true;
187
        }        
188
        
189
        @Override
190
        public String toString() {
191
            // SpatiaLite requiere que si se especifica OFFSET deba especificarse
192
            // LIMIT obligatoriamente. Se le puede poner un LIMIT -1 cuando 
193
            // queramos un OFFSET sin especificar un LIMIT.
194
            StringBuilder builder = new StringBuilder();
195
            if( !isValid(builder) ) {
196
                throw new IllegalStateException(builder.toString());
197
            }
198
            builder.append("SELECT ");
199
            if( this.distinct ) {
200
                builder.append("DISTINCT ");
201
            }
202
            boolean first = true;
203
            for (SelectColumnBuilder column : columns) {
204
                if (first) {
205
                    first = false;
206
                } else {
207
                    builder.append(", ");
208
                }
209
                builder.append(column.toString());
210
            }
211

  
212
            if ( this.has_from() ) {
213
                builder.append(" FROM ");
214
                builder.append(this.from.toString());
215
            }
216
            if ( this.has_where() ) {
217
                builder.append(" WHERE ");
218
                builder.append(this.where.toString());
219
            }
220
            
221
            if( this.has_order_by() ) {
222
                builder.append(" ORDER BY ");
223
                first = true;
224
                for (OrderByBuilder item : this.order_by) {
225
                    if (first) {
226
                        first = false;
227
                    } else {
228
                        builder.append(", ");
229
                    }
230
                    builder.append(item.toString());                    
231
                }   
232
            }
233
            
234
            if ( this.has_limit() && this.has_offset() ) {
235
                builder.append(" LIMIT ");
236
                builder.append(this.limit);
237
                builder.append(" OFFSET ");
238
                builder.append(this.offset);
239
                
240
            } else if ( this.has_limit()) {
241
                builder.append(" LIMIT ");
242
                builder.append(this.limit);
243

  
244
            } else if ( this.has_offset() ) {
245
                builder.append(" LIMIT -1 OFFSET ");
246
                builder.append(this.offset);    
247
            }
248
            return builder.toString();
249

  
250
        }
251
    }
252

  
253
    @Override
254
    public String bytearray(byte[] data) {
255
        // SpatiaLite usa un formato diferencte para especificar un array de 
256
        // bytes. En lugar de 0x... usa x'...' .
257
        StringBuilder builder = new StringBuilder();
258
        builder.append("x'");
259
        for (byte abyte : data) {
260
            int v = abyte & 0xff;
261
            builder.append(String.format("%02x", v));
262
        }
263
        builder.append("'");
264
        return builder.toString();
265
    }
266

  
267
    @Override
268
    public Object sqlgeometrydimension(int type, int subtype) {
269
        //'XY' or 2: 2D points, identified by X and Y coordinates
270
        //'XYM': 2D points, identified by X and Y coordinates. Each point stores an M-value (measure) as well
271
        //'XYZ' or 3: 3D points, identified by X, Y and Z coordinates
272
        //'XYZM' or 4: 3D points, identified by X, Y and Z coordinates. Each point stores an M-value (measure) as well
273
        switch(subtype) {
274
            case Geometry.SUBTYPES.GEOM2D:
275
            default:
276
                return "XY";
277
            case Geometry.SUBTYPES.GEOM2DM:
278
                return "XYM";
279
            case Geometry.SUBTYPES.GEOM3D:
280
                return "XYZ";
281
            case Geometry.SUBTYPES.GEOM3DM:
282
                return "XYZM";
283
        }
284
    }
285

  
286
    public SpatiaLiteHelper getHelper() {
287
        return this.helper;
288
    }
289
    
290
    @Override
291
    public void setParameters(PreparedStatement st, FeatureProvider feature) {
292
        try {
293
            FeatureType featureType = feature.getType();
294
            List<Object> values = new ArrayList<>();
295
            for (Parameter parameter : this.getParameters()) {
296
                if (parameter.is_constant()) {
297
                    values.add(parameter.getValue());
298
                } else {
299
                    String name = parameter.getName();
300
                    FeatureAttributeDescriptor descriptor = featureType.getAttributeDescriptor(name);
301
                    switch( descriptor.getType() ) {
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff