Revision 260

View differences:

tags/org.gvsig.spatialite-1.0.40/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.40</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.259</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.40</connection>
20
        <developerConnection>scm:svn:https://devel.gvsig.org/svn/gvsig-sqlite/tags/org.gvsig.spatialite-1.0.40</developerConnection>
21
        <url>https://devel.gvsig.org/redmine/projects/gvsig-sqlite/repository/show/tags/org.gvsig.spatialite-1.0.40</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
                </configuration>
51
            </plugin>                     
52
        </plugins>
53
    </build>
54

  
55

  
56
    <dependencyManagement>
57
        <dependencies>
58
            <dependency>
59
                <groupId>org.gvsig</groupId>
60
                <artifactId>org.gvsig.spatialite.provider</artifactId>
61
                <version>1.0.40</version>
62
            </dependency>
63
            <dependency>
64
                <groupId>org.gvsig</groupId>
65
                <artifactId>org.gvsig.spatialite.app.mainplugin.common</artifactId>
66
                <version>1.0.40</version>
67
                <type>zip</type>
68
            </dependency>
69
            <dependency>
70
                <groupId>org.xerial</groupId>
71
                <artifactId>sqlite-jdbc</artifactId>
72
                <version>3.21.0</version>
73
            </dependency>
74
                    
75
        </dependencies>
76
    </dependencyManagement>
77
  
78
    <modules>
79
        <module>org.gvsig.spatialite.app</module>
80
        <module>org.gvsig.spatialite.provider</module>
81
    </modules>
82

  
83

  
84
</project>
tags/org.gvsig.spatialite-1.0.40/org.gvsig.spatialite.provider/src/main/resources/META-INF/services/org.gvsig.tools.library.Library
1
org.gvsig.spatialite.dal.SpatiaLiteLibrary
tags/org.gvsig.spatialite-1.0.40/org.gvsig.spatialite.provider/src/main/resources/org/gvsig/spatialite/dal/SpatiaLiteMetadata.xml
1
<?xml version="1.0"?>
2
<definitions>
3
  <version>1.0.0</version>
4
  <classes>
5
    <class name="SpatiaLite" namespace="Metadata">
6
      <extends>
7
      	<class name="JDBC2" namespace="Metadata"/>
8
      </extends>
9
      <description>Metadata for SpatiaLite</description>
10
      <fields>
11
      </fields>
12
    </class>
13

  
14
  </classes>
15
</definitions>  
tags/org.gvsig.spatialite-1.0.40/org.gvsig.spatialite.provider/src/main/resources/org/gvsig/spatialite/dal/SpatiaLiteParameters.xml
1
<?xml version="1.0"?>
2
<definitions>
3
  <version>1.0.0</version>
4
  <classes>
5
    <class name="SpatiaLiteResourceParameters">
6
      <extends>
7
        <class>JDBC2ResourceParameters</class>
8
      </extends>
9
      <fields>
10
        <field name="JDBCDriverClass" type="string" mandatory="true"
11
          defaultValue="org.sqlite.JDBC" group="Advanced">
12
          <description>JDBC driver class for SpatiaLite</description>
13
        </field>        
14
        <field name="url_format" type="string" mandatory="true"
15
          defaultValue="jdbc:sqlite:%s" group="Advanced">
16
          <description></description>
17
        </field>
18
        <field name="port" type="integer" mandatory="false"
19
          defaultValue="0" group="Connection" hidden="true">
20
          <description></description>
21
        </field>
22
        <field name="host" type="string" mandatory="false" 
23
            defaultValue="" group="Connection" hidden="true">
24
          <description></description>
25
        </field>
26
        <field name="dbname" type="string" mandatory="false" hidden="true" defaultValue="" group="Basic">
27
          <description></description>
28
        </field>
29
        <field name="schema" type="string" mandatory="false" hidden="true" defaultValue="" group="Basic">
30
          <description></description>
31
        </field>
32
        <field name="catalog" type="string" mandatory="false" hidden="true" defaultValue="" group="Basic">
33
          <description></description>
34
        </field>
35
        <field name="url" type="string" mandatory="false" hidden="true" defaultValue="" group="Basic">
36
          <description></description>
37
        </field>
38
        <field name="dbuser" type="string" mandatory="false" defaultValue="" group="Basic">
39
          <description></description>
40
        </field>
41
        <field name="password" type="string" mandatory="false" defaultValue="" group="Basic">
42
          <description></description>
43
        </field>           
44
        <field name="database_file" label="Database file" type="file" mandatory="true" defaultValue="" group="Basic">
45
          <description></description>
46
        </field>            
47
        <field name="enable_shared_cache" label="Enable shared cache" type="boolean" mandatory="false" defaultValue="true" group="Advanced">
48
          <description></description>
49
        </field>
50
        <field name="enable_load_extension" label="Enable load extension" type="boolean" mandatory="false" defaultValue="true" group="Advanced">
51
          <description></description>
52
        </field>
53
        <field name="enable_spatialite" label="Enable spatialite" type="boolean" mandatory="false" defaultValue="true" group="Advanced">
54
          <description></description>
55
        </field>
56
      </fields>
57
    </class>
58

  
59
    <class name="SpatiaLiteStoreParameters">
60
      <extends>
61
        <class>JDBC2StoreParameters</class>
62
        <class>SpatiaLiteResourceParameters</class>
63
      </extends>
64
      <fields/>
65
    </class>
66

  
67
    <class name="SpatiaLiteNewStoreParameters">
68
      <extends>
69
        <class>JDBC2NewStoreParameters</class>
70
        <class>SpatiaLiteResourceParameters</class>
71
      </extends>
72
      <fields/>
73
    </class>
74

  
75

  
76
    <class name="SpatiaLiteServerExplorerParameters">
77
      <extends>
78
        <class>SpatiaLiteResourceParameters</class>
79
        <class>JDBC2ServerExplorerParameters</class>
80
      </extends>
81
      <fields/>
82
    </class>
83

  
84

  
85
  </classes>
86
</definitions>  
tags/org.gvsig.spatialite-1.0.40/org.gvsig.spatialite.provider/src/main/resources/org/gvsig/spatialite/dal/SpatiaLiteConfig.xml
1
<?xml version="1.0"?>
2
<definitions>
3
  <version>1.0.0</version>
4
  <classes>
5
    <class name="JDBC2">
6
      <extends>
7
      </extends>
8
      <fields>
9
        <field name="function_ST_AsWKB" type="string" group="functions" 
10
          defaultValue="ST_AsWKB({0})" >
11
          <description></description>
12
        </field>
13
        <field name="function_ST_envelope" type="string" group="functions" 
14
          defaultValue="ST_envelope({0})" >
15
          <description></description>
16
        </field>
17
        <field name="function_ST_Extent" type="string" group="functions" 
18
          defaultValue="ST_Extent({0})" >
19
          <description></description>
20
        </field>
21
        <field name="function_ST_intersects" type="string" group="functions" 
22
          defaultValue="ST_intersects({0}, {1})" >
23
          <description></description>
24
        </field>
25
        <field name="function_ST_GeomFromText" type="string" group="functions" 
26
          defaultValue="ST_GeomFromText({0}, {1})" >
27
          <description></description>
28
        </field>
29
        <field name="function_ST_GeomFromWKB" type="string" group="functions" 
30
          defaultValue="ST_GeomFromWKB({0}, {1})" >
31
          <description></description>
32
        </field>
33
        <field name="function_ST_GeomFromEWKB" type="string" group="functions" 
34
          defaultValue="ST_GeomFromEWKB({0}, {1})" >
35
          <description></description>
36
        </field>
37
        <field name="function_current_schema" type="string" group="functions" 
38
          defaultValue="current_schema()" >
39
          <description></description>
40
        </field>
41
        <field name="function_lcase" type="string" group="functions" 
42
          defaultValue="LCASE({0})" >
43
          <description></description>
44
        </field>
45
        <field name="function_count" type="string" group="functions" 
46
          defaultValue="count({0})" >
47
          <description></description>
48
        </field>
49
        <field name="function_crs" type="string" group="functions" 
50
          defaultValue="{0}" >
51
          <description>Use {0} for the abbreviature, {1} for the autority name and {2} for the autority code</description>
52
        </field>
53
        
54
        <!-- operators -->
55
        <field name="operator_isnull" type="string" group="operators" 
56
          defaultValue="{0} is null" >
57
          <description></description>
58
        </field>
59
        <field name="operator_eq" type="string" group="operators" 
60
          defaultValue="{0} = {1}" >
61
          <description></description>
62
        </field>
63
        <field name="operator_neq" type="string" group="operators" 
64
          defaultValue="{0} &lt;&gt; {1}" >
65
          <description></description>
66
        </field>
67
        <field name="operator_lt" type="string" group="operators" 
68
          defaultValue="{0} &lt; {1}" >
69
          <description></description>
70
        </field>
71
        <field name="operator_le" type="string" group="operators" 
72
          defaultValue="{0} &lt;= {1}" >
73
          <description></description>
74
        </field>
75
        <field name="operator_gt" type="string" group="operators" 
76
          defaultValue="{0} &gt; {1}" >
77
          <description></description>
78
        </field>
79
        <field name="operator_ge" type="string" group="operators" 
80
          defaultValue="{0} &gt;= {1}" >
81
          <description></description>
82
        </field>
83
        <field name="operator_and" type="string" group="operators" 
84
          defaultValue="{0} AND {1}" >
85
          <description></description>
86
        </field>
87
        <field name="operator_or" type="string" group="operators" 
88
          defaultValue="{0} OR {1}" >
89
          <description></description>
90
        </field>
91
        <field name="operator_like" type="string" group="operators" 
92
          defaultValue="{0} LIKE {1}" >
93
          <description></description>
94
        </field>
95
        <field name="operator_ilike" type="string" group="operators" 
96
          defaultValue="{0} ILIKE {1}" >
97
          <description></description>
98
        </field>
99
        
100
        <!-- properties -->
101
        <field name="AllowAutomaticValues" type="boolean" group="properties" 
102
          defaultValue="true" >
103
          <description></description>
104
        </field>
105
        <field name="QuoteForStrings" type="string" group="properties" 
106
          defaultValue="'" >
107
          <description></description>
108
        </field>
109
        <field name="QuoteForIdentifiers" type="string" group="properties" 
110
          defaultValue="" >
111
          <description></description>
112
        </field>
113
        <field name="GeometrySupportType" type="string" group="properties" 
114
            defaultValue="WKB" >
115
            <description></description>
116
            <availableValues>
117
                <value label="WKT">WKT</value>
118
                <value label="WKB">WKB</value>
119
                <value label="EWKB">EWKB</value>
120
            </availableValues>          
121
        </field>
122

  
123

  
124

  
125
      </fields>
126
    </class>
127
    
128
    
129
    <class name="SpatiaLite">
130
      <extends>
131
          <class>JDBC2</class>
132
      </extends>
133
      <fields>
134
        <field name="function_ST_AsWKB" type="string" group="functions" 
135
          defaultValue="({0}).STAsWKB" >
136
          <description></description>
137
        </field>
138
        <field name="function_ST_envelope" type="string" group="functions" 
139
          defaultValue="({0}).STEnvelope" >
140
          <description></description>
141
        </field>
142
        <field name="function_ST_Extent" type="string" group="functions" 
143
          defaultValue="({0}).STEnvelope" >
144
          <description></description>
145
        </field>
146
        <field name="function_ST_intersects" type="string" group="functions" 
147
          defaultValue="({0}).STIntersects({1})" >
148
          <description></description>
149
        </field>
150
        <field name="function_ST_GeomFromText" type="string" group="functions" 
151
          defaultValue="geometry::STGeomFromText({0}, {1})" >
152
          <description></description>
153
        </field>
154
        <field name="function_ST_GeomFromWKB" type="string" group="functions" 
155
          defaultValue="geometry::STGeomFromWKB({0}, {1})" >
156
          <description></description>
157
        </field>
158
        <field name="function_ST_GeomFromEWKB" type="string" group="functions" 
159
          defaultValue="geometry::STGeomFromWKB({0}, {1})" >
160
          <description></description>
161
        </field>
162
        <field name="function_current_schema" type="string" group="functions" 
163
          defaultValue="current_schema()" >
164
          <description></description>
165
        </field>
166
        <field name="function_crs" type="string" group="functions" 
167
          defaultValue="{2}" >
168
          <description>Use {0} for the abbreviature, {1} for the autority name and {2} for the autority code</description>
169
        </field>
170
        <field name="function_lcase" type="string" group="functions" 
171
          defaultValue="LOWER({0})" >
172
          <description></description>
173
        </field>
174
        
175
        <!-- operators -->
176
        <field name="operator_ilike" type="string" group="operators" 
177
          defaultValue="{0} ILIKE {1}" >
178
          <description></description>
179
        </field>
180
    
181
    
182
  </classes>
183
</definitions>  
tags/org.gvsig.spatialite-1.0.40/org.gvsig.spatialite.provider/src/main/java/org/gvsig/spatialite/dal/SpatiaLiteExplorer.java
1
package org.gvsig.spatialite.dal;
2

  
3
import org.apache.commons.io.FilenameUtils;
4
import org.gvsig.fmap.dal.DataStore;
5
import org.gvsig.fmap.dal.exception.InitializeException;
6
import org.gvsig.fmap.dal.spi.DataServerExplorerProviderServices;
7
import org.gvsig.fmap.dal.spi.ZipResourcesStorage;
8
import org.gvsig.fmap.dal.store.jdbc.JDBCServerExplorerParameters;
9
import org.gvsig.fmap.dal.store.jdbc2.JDBCHelper;
10
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCServerExplorerBase;
11
import org.gvsig.tools.resourcesstorage.EmptyResourcesStorage;
12
import org.gvsig.tools.resourcesstorage.ResourcesStorage;
13

  
14
/**
15
 *
16
 * @author jjdelcerro
17
 */
18
@SuppressWarnings("UseSpecificCatch")
19
public class SpatiaLiteExplorer extends JDBCServerExplorerBase {
20
    
21
    public SpatiaLiteExplorer(JDBCServerExplorerParameters parameters, DataServerExplorerProviderServices services, JDBCHelper helper) throws InitializeException {
22
        super(parameters, services, helper);
23
    }
24

  
25
    @Override
26
    public SpatiaLiteExplorerParameters getParameters() {
27
        return (SpatiaLiteExplorerParameters) super.getParameters(); 
28
    }
29

  
30
    @Override
31
    public ResourcesStorage getResourcesStorage(DataStore dataStore) {
32
        ResourcesStorage ress = super.getResourcesStorage(dataStore);
33
        if( ress instanceof EmptyResourcesStorage ) {
34
            String zipPath = this.getParameters().getFile().getAbsolutePath();
35
            String zipPathName = FilenameUtils.removeExtension(zipPath);
36
            ress = new ZipResourcesStorage(zipPathName, dataStore.getName());
37
        }
38
        return ress;
39
    }
40
    
41
}
tags/org.gvsig.spatialite-1.0.40/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
    @Override
98
    public String getURLFormat() {
99
        return this.helper.getURLFormat();
100
    }
101

  
102
}
tags/org.gvsig.spatialite-1.0.40/org.gvsig.spatialite.provider/src/main/java/org/gvsig/spatialite/dal/SpatiaLiteConnections.java
1
package org.gvsig.spatialite.dal;
2

  
3
import java.io.File;
4
import java.sql.Connection;
5
import java.sql.DriverManager;
6
import java.sql.SQLException;
7
import java.sql.Statement;
8
import java.util.HashMap;
9
import java.util.Map;
10
import org.apache.commons.io.FilenameUtils;
11
import org.apache.commons.lang3.StringUtils;
12
import org.gvsig.fmap.dal.store.jdbc2.JDBCUtils;
13
import static org.gvsig.spatialite.dal.SpatiaLiteHelper.LOGGER;
14
import org.slf4j.Logger;
15
import org.slf4j.LoggerFactory;
16
import org.sqlite.SQLiteConfig;
17

  
18
/**
19
 *
20
 * @author jjdelcerro
21
 */
22
@SuppressWarnings("UseSpecificCatch")
23
public class SpatiaLiteConnections {
24

  
25
    private static final Logger LOGGER = LoggerFactory.getLogger(SpatiaLiteConnections.class);
26

  
27
    public static final String SPATIALITE_JDBC_DRIVER = "org.sqlite.JDBC";
28
    public static final String URL_FORMAT = "jdbc:sqlite:%s";
29

  
30
    private static class ConnectionEntry {
31

  
32
        public ConnectionEntry(File f) {
33
            this.f = f;
34
            this.refCount = 1;
35
            this.metadataInitialized = false;
36
        }
37
        
38
        private Connection conn;
39
        private File f;
40
        private int refCount;
41
        private boolean metadataInitialized;
42
    }
43

  
44
    private static Map<File, ConnectionEntry> CONNECTIONS;
45

  
46
    public static synchronized Connection getConnection(File f) {
47
        if (f == null) {
48
            LOGGER.warn("Can't get connection for null file.");
49
            return null;
50
        }
51
        if (CONNECTIONS == null) {
52
            registerDriver();
53
        }
54
        try {
55
            ConnectionEntry entry = CONNECTIONS.get(f);
56
            if (entry == null) {
57
                entry = new ConnectionEntry(f);
58
            } else {
59
                if( entry.conn==null ) {
60
                    entry.refCount = 1;
61
                } else if( !entry.conn.isClosed()) {
62
                    entry.refCount += 1;
63
                    LOGGER.debug("Reuse connection "+ entry.conn.hashCode() + " (refs "+entry.refCount+", "+entry.conn.toString()+")");
64
                    return entry.conn;
65
                }
66
            }
67

  
68
            SQLiteConfig config = new SQLiteConfig();
69
            config.setSharedCache(true);
70
            config.enableLoadExtension(true);
71
            config.setTransactionMode(SQLiteConfig.TransactionMode.IMMEDIATE);
72

  
73
            entry.conn = DriverManager.getConnection(
74
                    getConnectionURL(entry.f),
75
                    config.toProperties()
76
            );
77
            loadExtension(entry);
78
            if( !entry.metadataInitialized ) {
79
                initSpatialMetadata(entry);
80
                entry.metadataInitialized = true;
81
            }
82
            CONNECTIONS.put(f, entry);
83
            LOGGER.debug("Open connection "+ entry.conn.hashCode() + " (refs "+entry.refCount+", "+entry.conn.toString()+")");
84
            return entry.conn;
85
        } catch (SQLException ex) {
86
            LOGGER.warn("Can't get connection for file '" + f + "'.");
87
            return null;
88
        }
89
    }
90

  
91
    public static synchronized void close(Connection conn) {
92
        for (ConnectionEntry entry : CONNECTIONS.values()) {
93
            if (conn == entry.conn) {
94
                entry.refCount -= 1;
95
                if (entry.refCount < 1) {
96
                    JDBCUtils.closeQuietly(entry.conn);
97
                    entry.conn = null;
98
                    entry.refCount = 0;
99
                    return;
100
                }
101
                LOGGER.debug("Skip close connection "+ entry.conn.hashCode() + " (refs "+entry.refCount+", "+entry.conn.toString()+")");
102
                break;
103
            }
104
        }
105
    }
106

  
107
    public static String getConnectionURL(File f) {
108
        String fname = f.getAbsolutePath().replace("\\", "/");
109
        if (StringUtils.isEmpty(FilenameUtils.getExtension(fname))) {
110
            fname = fname + ".sqlite";
111
        }
112
        String connectionURL = String.format(URL_FORMAT, fname);
113
        LOGGER.debug("connectionURL: {}", connectionURL);
114
        return connectionURL;
115
    }
116

  
117
    public static void registerDriver() {
118
        Class theClass = null;
119
        try {
120
            theClass = Class.forName(SPATIALITE_JDBC_DRIVER);
121
        } catch (Exception e) {
122
            LOGGER.warn("Can't register JDBC driver '" + SPATIALITE_JDBC_DRIVER + "'.", e);
123
            throw new SpatiaLiteDriverNotFound(e);
124
        }
125
        if (theClass == null) {
126
            LOGGER.warn("Can't register JDBC driver '" + SPATIALITE_JDBC_DRIVER + "'.");
127
            throw new SpatiaLiteDriverNotFound();
128
        }
129
        if (CONNECTIONS == null) {
130
            CONNECTIONS = new HashMap<>();
131
        }
132
    }
133

  
134
    private static void loadExtension(ConnectionEntry entry) {
135
        Statement st = null;
136
        try {
137
            st = entry.conn.createStatement();
138
            JDBCUtils.execute(st, "SELECT load_extension('mod_spatialite')");
139

  
140
        } catch (Exception ex) {
141
            LOGGER.warn("Can't load mod_spatialite extension module for SQLite (" +
142
                    entry.f.getAbsolutePath() + ").", ex);
143

  
144
        } finally {
145
            JDBCUtils.closeQuietly(st);
146
        }
147
    }
148

  
149
    private static void initSpatialMetadata(ConnectionEntry entry) {
150
        Statement st = null;
151
        try {
152
            st = entry.conn.createStatement();
153
            JDBCUtils.execute(st, "SELECT InitSpatialMetaData(1)");
154
        } catch (Exception ex) {
155
            LOGGER.warn("Can't initialize spatial metatada in SQLite database (" + 
156
                    entry.f.getAbsolutePath() + ").", ex);
157

  
158
        } finally {
159
            JDBCUtils.closeQuietly(st);
160
        }
161
    }
162

  
163
    private static class SpatiaLiteDriverNotFound extends RuntimeException {
164

  
165
        public SpatiaLiteDriverNotFound() {
166
            super("Can't locate the SpatiaLite JDBC driver '" + SPATIALITE_JDBC_DRIVER + "'.");
167
        }
168

  
169
        public SpatiaLiteDriverNotFound(Throwable cause) {
170
            this();
171
            this.initCause(cause);
172
        }
173
    }
174
}
tags/org.gvsig.spatialite-1.0.40/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

  
20
    public String getURLFormat();
21
}
tags/org.gvsig.spatialite-1.0.40/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

  
14

  
15
public class SpatiaLiteConnectionParametersHelper {
16

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

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

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

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

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

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

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

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

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

  
106
    public Properties getProperties() {
107
        Properties props = new Properties();
108
        props.setProperty("enable_shared_cache", BooleanUtils.toStringTrueFalse(getEnableSharedCache()));
109
        props.setProperty("enable_load_extension", BooleanUtils.toStringTrueFalse(getEnableLoadExtension()));
110
        props.setProperty("enable_spatialite", BooleanUtils.toStringTrueFalse(getEnableSpatiaLite()));
111
        return props;
112
    }    
113
}
tags/org.gvsig.spatialite-1.0.40/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 org.apache.commons.lang3.StringUtils;
13
import org.cresques.cts.IProjection;
14
import org.gvsig.expressionevaluator.ExpressionBuilder;
15
import org.gvsig.fmap.dal.DataTypes;
16
import org.gvsig.fmap.dal.exception.DataException;
17
import org.gvsig.fmap.dal.feature.EditableFeatureAttributeDescriptor;
18
import org.gvsig.fmap.dal.feature.EditableFeatureType;
19
import org.gvsig.fmap.dal.store.jdbc2.JDBCHelper;
20
import org.gvsig.fmap.dal.store.jdbc2.JDBCUtils;
21
import org.gvsig.fmap.dal.store.jdbc2.OperationsFactory.TableReference;
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
@SuppressWarnings("UseSpecificCatch")
30
public class SpatiaLiteFetchFeatureTypeOperation extends FetchFeatureTypeOperation {
31

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

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

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

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

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

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

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

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

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

  
211
            spatialiteGeometryTypes.put("GEOMETRY", getGT(manager, Geometry.TYPES.GEOMETRY,Geometry.SUBTYPES.GEOM2D));
212
            spatialiteGeometryTypes.put("GEOMETRYZ", getGT(manager, Geometry.TYPES.GEOMETRY,Geometry.SUBTYPES.GEOM3D));
213
            spatialiteGeometryTypes.put("GEOMETRYM", getGT(manager, Geometry.TYPES.GEOMETRY,Geometry.SUBTYPES.GEOM2DM));
214
            spatialiteGeometryTypes.put("GEOMETRYZM", getGT(manager, Geometry.TYPES.GEOMETRY,Geometry.SUBTYPES.GEOM3DM));
215
        }
216
        return spatialiteGeometryTypes.get(typeName);
217
    }
218
    
219
}
tags/org.gvsig.spatialite-1.0.40/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, TableReference table, List<String> primaryKeys, String defaultGeometryField, IProjection crs) {
20
        return new SpatiaLiteFetchFeatureTypeOperation(
21
                helper, type, table, primaryKeys, 
22
                defaultGeometryField, crs
23
        );
24
    }  
25
    
26
}
tags/org.gvsig.spatialite-1.0.40/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
    @Override
105
    public String getURLFormat() {
106
        return this.helper.getURLFormat();
107
    }
108

  
109
}
tags/org.gvsig.spatialite-1.0.40/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
        SpatiaLiteConnections.registerDriver();
56
//        try {
57
//            Class.forName(SpatiaLiteHelper.SPATIALITE_JDBC_DRIVER);
58
//        } catch(Throwable th) {
59
//            SpatiaLiteHelper.LOGGER.warn("Can't load SpatiaLite JDBC Driver.",th);
60
//        }
61
        
62
        DBHelper.registerParametersDefinition(
63
                NAME + "StoreParameters",
64
                SpatiaLiteStoreParameters.class,
65
                dataman.getResourceAsStream(this, NAME + "Parameters.xml")
66
        );
67
        DBHelper.registerParametersDefinition(
68
                NAME + "NewStoreParameters",
69
                SpatiaLiteNewStoreParameters.class,
70
                dataman.getResourceAsStream(this, NAME + "Parameters.xml")
71
        );
72
        DBHelper.registerParametersDefinition(
73
                NAME + "ServerExplorerParameters",
74
                SpatiaLiteExplorerParameters.class,
75
                dataman.getResourceAsStream(this, NAME + "Parameters.xml")
76
        );
77
//        DBHelper.registerParametersDefinition(
78
//                NAME + "ResourceParameters",
79
//                SpatiaLiteResourceParameters.class,
80
//                dataman.getResourceAsStream(this, NAME + "Parameters.xml")
81
//        );
82
        try {
83
            DBHelper.registerMetadataDefinition(
84
                NAME,
85
                JDBCStoreProviderBase.class,
86
                dataman.getResourceAsStream(this, NAME + "Metadata.xml")
87
            );
88
        } catch (MetadataException e) {
89
            ex = new LibraryException(this.getClass(), e);
90
        }
91

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

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

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

  
115
}
tags/org.gvsig.spatialite-1.0.40/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.spi.JDBCSQLBuilderBase;
13
import org.gvsig.fmap.geom.Geometry;
14
import org.gvsig.tools.dispose.Disposable;
15
import org.apache.commons.lang3.tuple.Pair;
16
import org.gvsig.expressionevaluator.ExpressionBuilder.Parameter;
17
import org.gvsig.expressionevaluator.Formatter;
18
import org.gvsig.fmap.dal.SQLBuilder.ColumnDescriptor;
19
import org.gvsig.spatialite.dal.expressionbuilderformatter.SpatiaLiteFormatter;
20

  
21
@SuppressWarnings("UseSpecificCatch")
22
public class SpatiaLiteSQLBuilder extends JDBCSQLBuilderBase {
23

  
24
    protected Formatter formatter = null;
25

  
26
    public SpatiaLiteSQLBuilder(SpatiaLiteHelper helper) {
27
        super(helper);
28

  
29
        //
30
        // SpatiaLite 4.3.0, SQL functions reference list
31
        //
32
        // http://www.gaia-gis.it/gaia-sins/spatialite-sql-4.3.0.html
33
        //
34
        // https://sqlite.org/lang.html
35
        //
36
        this.defaultSchema = "";
37
        this.supportSchemas = false;
38
        this.allowAutomaticValues = true;
39
        this.geometrySupportType = this.helper.getGeometrySupportType();
40
        this.hasSpatialFunctions = this.helper.hasSpatialFunctions();
41

  
42
        this.STMT_DELETE_GEOMETRY_COLUMN_FROM_TABLE_schema_table = null;
43
        this.STMT_DELETE_GEOMETRY_COLUMN_FROM_TABLE_table = null;
44

  
45
        this.STMT_UPDATE_TABLE_STATISTICS_table = "SELECT UpdateLayerStatistics({0})";
46

  
47
        this.type_boolean = "INTEGER";
48
        this.type_byte = "INTEGER";
49
        this.type_bytearray = "";
50
        this.type_geometry = "BLOB";
51
        this.type_char = "TEXT";
52
        this.type_date = "INTEGER";
53
        this.type_double = "REAL";
54
        this.type_numeric_p = "REAL";
55
        this.type_numeric_ps = "REAL";
56
        this.type_bigdecimal = "REAL";
57
        this.type_float = "REAL";
58
        this.type_int = "INTEGER";
59
        this.type_long = "INTEGER";
60
        this.type_string = "TEXT";
61
        this.type_string_p = "TEXT";
62
        this.type_time = "INTEGER";
63
        this.type_timestamp = "INTEGER";
64
        this.type_version = "TEXT";
65
        this.type_URI = "TEXT";
66
        this.type_URL = "TEXT";
67
        this.type_FILE = "TEXT";
68
        this.type_FOLDER = "TEXT";
69
    }
70

  
71
    @Override
72
    protected Formatter formatter() {
73
        if (this.formatter == null) {
74
            this.formatter = new SpatiaLiteFormatter(this);
75
        }
76
        return this.formatter;
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(Formatter formatter) {
97
            //
98
            // Respecto al base cambia la declaracion de campo automaticos:
99
            // - Los campos se crean autom?ticamente como SERIAL si son INTEGER PRIMARY KEY.
100
            // - Existe la palabra clave AUTOINCREMENT que se puede usar
101
            // en los campos INTEGER PRIMARY KEY, pero no se recomienda su uso (penaliza el rendimiento).
102
            // - Spatialite no permite definir SERIALs para el resto de campos.
103
            // - Hay que usar la funcion AddGeometryColumn para a?adir las columnas de tipo geometria
104
            // - El orden en el que hay que declarar las constrains tambien cambia
105
            // respecto al que hay por defecto.
106
            //
107
            List<String> sqls = new ArrayList<>();
108
            StringBuilder builder = new StringBuilder();
109

  
110
            builder.append("CREATE TABLE ");
111
            builder.append(this.table.toString(formatter));
112
            builder.append(" (");
113
            boolean first = true;
114
            for (ColumnDescriptor column : columns) {
115
                if (column.isGeometry()) {
116
                    continue;
117
                }
118
                if (first) {
119
                    first = false;
120
                } else {
121
                    builder.append(", ");
122
                }
123
                builder.append(as_identifier(column.getName()));
124
                builder.append(" ");
125
                builder.append(sqltype(column.getType(), column.getPrecision(), column.getSize(), column.getGeometryType(), column.getGeometrySubtype()));
126
                if (column.isPrimaryKey()) {
127
                    builder.append(" PRIMARY KEY");
128
                }
129
                if (column.getDefaultValue() == null) {
130
                    if (column.allowNulls()) {
131
                        builder.append(" DEFAULT NULL");
132
                    }
133
                } else {
134
                    if (column.getType() == DataTypes.DATE) {
135
                        builder.append(" DEFAULT ( date('");
136
                        builder.append(column.getDefaultValue().toString());
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff