Revision 414

View differences:

tags/org.gvsig.postgresql-2.0.86/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.postgresql</artifactId>
7
  <version>2.0.86</version>
8
  <packaging>pom</packaging>
9
  <name>${project.artifactId}</name>
10
  <description>PostgreSQL support fort DAL and gvSIG</description>
11
  <parent>
12
      <groupId>org.gvsig</groupId>
13
      <artifactId>org.gvsig.desktop</artifactId>
14
      <version>2.0.205</version>
15
  </parent>
16

  
17
  <url>https://devel.gvsig.org/redmine/projects/gvsig-postgresql</url>
18
  <scm>
19
      <connection>scm:svn:https://devel.gvsig.org/svn/gvsig-postgresql/tags/org.gvsig.postgresql-2.0.86</connection>
20
      <developerConnection>scm:svn:https://devel.gvsig.org/svn/gvsig-postgresql/tags/org.gvsig.postgresql-2.0.86</developerConnection>
21
      <url>https://devel.gvsig.org/redmine/projects/gvsig-postgresql/repository/show/tags/org.gvsig.postgresql-2.0.86</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-postgresql/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.postgresql.provider</artifactId>
62
            <version>2.0.86</version>
63
          </dependency>
64
          <dependency>
65
            <groupId>org.gvsig</groupId>
66
            <artifactId>org.gvsig.postgresql.app.mainplugin</artifactId>
67
            <version>2.0.86</version>
68
          </dependency>
69
      </dependencies>
70
  </dependencyManagement>
71

  
72
  <dependencies>
73
        <dependency>
74
            <groupId>org.slf4j</groupId>
75
            <artifactId>slf4j-api</artifactId>
76
            <scope>compile</scope>
77
        </dependency>
78
  </dependencies>
79

  
80
  
81
  <modules>
82
    <module>org.gvsig.postgresql.app</module>
83
    <module>org.gvsig.postgresql.provider</module>
84
  </modules>
85

  
86

  
87
</project>
tags/org.gvsig.postgresql-2.0.86/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/PostgreSQLConnectionParameters.java
1

  
2
package org.gvsig.postgresql.dal;
3

  
4
import org.gvsig.fmap.dal.resource.db.DBParameters;
5
import org.gvsig.fmap.dal.store.jdbc.JDBCConnectionParameters;
6

  
7
public interface PostgreSQLConnectionParameters extends JDBCConnectionParameters, DBParameters {
8
	public static final String USESSL_PARAMTER_NAME = "UseSSL";
9

  
10
	public boolean getUseSSL();    
11
}
tags/org.gvsig.postgresql-2.0.86/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/PostgreSQLConnectionParametersHelper.java
1

  
2
package org.gvsig.postgresql.dal;
3

  
4
import org.apache.commons.lang3.StringUtils;
5
import org.gvsig.fmap.dal.DataParameters;
6
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
7
import org.gvsig.fmap.dal.store.jdbc.JDBCConnectionParameters;
8

  
9

  
10
public class PostgreSQLConnectionParametersHelper {
11

  
12
    private final JDBCConnectionParameters parameters;
13
    
14
    public PostgreSQLConnectionParametersHelper(JDBCConnectionParameters parameters) {
15
        this.parameters = parameters;
16
    }
17

  
18
    public String getUrl() {
19
        String url = (String) this.getDynValue(JDBCConnectionParameters.URL_PARAMTER_NAME);
20
        if( StringUtils.isEmpty(url) ) {
21
            url = PostgreSQLHelper.getConnectionURL((PostgreSQLConnectionParameters) this.parameters);
22
            this.setDynValue(JDBCConnectionParameters.URL_PARAMTER_NAME,url);
23
        }
24
        return url;
25
    }
26
    
27
    public void validate() throws ValidateDataParametersException {
28
        if (this.getDynValue(JDBCConnectionParameters.JDBC_DRIVER_CLASS_PARAMTER_NAME) == null) {
29
            this.setDynValue(
30
                JDBCConnectionParameters.JDBC_DRIVER_CLASS_PARAMTER_NAME,
31
                PostgreSQLHelper.POSTGRESQL_JDBC_DRIVER
32
            );
33
        }
34
        if( this.getDynValue(JDBCConnectionParameters.PORT_PARAMTER_NAME)==null ) {
35
            this.setDynValue(JDBCConnectionParameters.PORT_PARAMTER_NAME, 5432);
36
        }
37
		if ( StringUtils.isEmpty((CharSequence) this.getDynValue(JDBCConnectionParameters.URL_PARAMTER_NAME))) {
38
            String url = PostgreSQLHelper.getConnectionURL(
39
                parameters.getHost(),
40
                parameters.getPort(),
41
                parameters.getDBName()
42
            );
43
            this.setDynValue(JDBCConnectionParameters.URL_PARAMTER_NAME, url);
44
		}
45
    }
46

  
47
    private Object getDynValue(String name) {
48
        return ((DataParameters)this.parameters).getDynValue(name);
49
    }
50
    
51
    private void setDynValue(String name, Object value) {
52
        ((DataParameters)this.parameters).setDynValue(name,value);
53
    }
54
    
55

  
56
    public boolean getUseSSL() {
57
        return (boolean) this.getDynValue(PostgreSQLConnectionParameters.USESSL_PARAMTER_NAME);
58
    }
59

  
60
    public void setUseSSL(boolean v) {
61
        this.setDynValue(PostgreSQLConnectionParameters.USESSL_PARAMTER_NAME, v);
62
    }
63
    
64
}
tags/org.gvsig.postgresql-2.0.86/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/PostgreSQLLibrary.java
1

  
2
package org.gvsig.postgresql.dal;
3

  
4
import org.gvsig.fmap.dal.DALLibrary;
5
import org.gvsig.fmap.dal.DALLocator;
6
import org.gvsig.fmap.dal.spi.DataManagerProviderServices;
7
import org.gvsig.fmap.dal.store.db.DBHelper;
8
import org.gvsig.fmap.dal.store.jdbc2.JDBCLibrary;
9
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCStoreProviderBase;
10
import org.gvsig.metadata.exceptions.MetadataException;
11
import org.gvsig.tools.library.AbstractLibrary;
12
import org.gvsig.tools.library.LibraryException;
13

  
14

  
15
public class PostgreSQLLibrary extends AbstractLibrary {
16

  
17
    public static final String NAME = "PostgreSQL";
18

  
19
    @Override
20
    public void doRegistration() {
21
        registerAsServiceOf(DALLibrary.class);
22
        require(JDBCLibrary.class);
23
    }
24

  
25
    @Override
26
    protected void doInitialize() throws LibraryException {
27
    }
28

  
29
    @Override
30
    protected void doPostInitialize() throws LibraryException {
31
        LibraryException ex = null;
32

  
33
        DataManagerProviderServices dataman = 
34
                (DataManagerProviderServices) DALLocator.getDataManager();
35

  
36
        try {
37
            Class.forName(PostgreSQLHelper.POSTGRESQL_JDBC_DRIVER);
38
        } catch(Throwable th) {
39
            PostgreSQLHelper.logger.warn("Can't load PostgreSQL JDBC Driver.",th);
40
        }
41
        
42
        DBHelper.registerParametersDefinition(
43
                NAME + "StoreParameters",
44
                PostgreSQLStoreParameters.class,
45
                dataman.getResourceAsStream(this, NAME + "Parameters.xml")
46
        );
47
        DBHelper.registerParametersDefinition(
48
                NAME + "NewStoreParameters",
49
                PostgreSQLNewStoreParameters.class,
50
                dataman.getResourceAsStream(this, NAME + "Parameters.xml")
51
        );
52
        DBHelper.registerParametersDefinition(
53
                NAME + "ServerExplorerParameters",
54
                PostgreSQLServerExplorerParameters.class,
55
                dataman.getResourceAsStream(this, NAME + "Parameters.xml")
56
        );
57
//        DBHelper.registerParametersDefinition(
58
//                NAME + "ResourceParameters",
59
//                PostgreSQLResourceParameters.class,
60
//                dataman.getResourceAsStream(this, NAME + "Parameters.xml")
61
//        );
62
        try {
63
            DBHelper.registerMetadataDefinition(
64
                NAME,
65
                JDBCStoreProviderBase.class,
66
                dataman.getResourceAsStream(this, NAME + "Metadata.xml")
67
            );
68
        } catch (MetadataException e) {
69
            ex = new LibraryException(this.getClass(), e);
70
        }
71

  
72
//        ResourceManagerProviderServices resman = (ResourceManagerProviderServices) DALLocator
73
//                .getResourceManager();
74
//
75
//        if (!resman.getResourceProviders().contains(NAME)) {
76
//            resman.register(NAME,
77
//                "Resource for " + NAME,
78
//                PostgreSQLResource.class,
79
//                PostgreSQLResourceParameters.class
80
//            );
81
//        }
82

  
83
        if (!dataman.getStoreProviderRegister().exits(NAME)) {
84
            dataman.registerStoreProviderFactory(new PostgreSQLStoreProviderFactory());
85
        }
86

  
87
        if (!dataman.getServerExplorerRegister().exits(NAME)) {
88
            dataman.registerServerExplorerFactory(new PostgreSQLServerExplorerFactory());
89
        }
90

  
91
        // Por compatibilidad con gvSIG 2.3 registramos otra vez la factoria con
92
        // el nombre que tenia antes.
93
        if (!dataman.getServerExplorerRegister().exits("PostgreSQLExplorer")) {
94
            dataman.registerServerExplorerFactory(new PostgreSQLServerExplorerFactory("PostgreSQLExplorer"));
95
        }
96
        
97
        if (ex != null) {
98
            throw ex;
99
        }
100
    }
101

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

  
25
package org.gvsig.postgresql.dal;
26

  
27
import java.text.MessageFormat;
28
import java.util.ArrayList;
29
import java.util.List;
30
import org.apache.commons.lang3.StringUtils;
31
import org.gvsig.fmap.dal.store.jdbc2.JDBCHelper;
32
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCSQLBuilderBase;
33

  
34
public class PostgreSQLBuilder extends JDBCSQLBuilderBase {
35

  
36
    private final JDBCHelper helper;
37

  
38
    public PostgreSQLBuilder(JDBCHelper helper) {
39
        super();
40
        
41
        this.helper = helper;
42
              
43
        config.set(SQLConfig.default_schema, "public");
44
        config.set(SQLConfig.allowAutomaticValues, true);
45
        config.set(SQLConfig.geometry_type_support, this.helper.getGeometrySupportType());
46
        config.set(SQLConfig.has_spatial_functions, this.helper.hasSpatialFunctions());
47
        config.set(SQLConfig.constant_true, "true");
48
        config.set(SQLConfig.constant_false, "false");
49
            
50
        config.remove_functionality(SQLConfig.DELETE_GEOMETRY_COLUMN_FROM_TABLE_schema_table);
51
        config.remove_functionality(SQLConfig.DELETE_GEOMETRY_COLUMN_FROM_TABLE_table);
52
         
53
        config.set(SQLConfig.UPDATE_TABLE_STATISTICS_table,"ANALYZE {0}");
54

  
55
        config.set(SQLConfig.ST_GeomFromEWKB, "ST_GeomFromEWKB({0}, {1})");
56
        config.set(SQLConfig.ST_AsEWKB, "ST_AsEWKB(({0}))");        
57
        config.set(SQLConfig.ST_ExtentAggregate, "ST_Extent({0})");        
58
        config.set(SQLConfig.ST_UnionAggregate, "ST_Union({0})");
59
        
60
        config.set(SQLConfig.lcase, "lower({0})");
61
        config.set(SQLConfig.ucase, "upper({0})");
62
        config.set(SQLConfig.operator_ILIKE, "({0}) ILIKE ({1})");
63
        config.set(SQLConfig.isNull, "( ({0}) ISNULL )");
64
        config.set(SQLConfig.notIsNull, "( ({0}) NOT NULL )");
65

  
66
    }
67
    
68
    public class PostgreSQLUpdateTableStatisticsBuilderBase extends UpdateTableStatisticsBuilderBase {
69
        @Override
70
        public List<String> toStrings() {
71
            List<String> sqls = new ArrayList<>();
72
            
73
            if( config.has_functionality(SQLConfig.UPDATE_TABLE_STATISTICS_table) ) {
74
                // In postGIS, UpdateLayerStatistics function, don't allow to 
75
                // use the database name in the table name.
76
                String name = identifier(this.table.getName());
77
                if( table.has_schema()) {
78
                    name = identifier(this.table.getSchema()) + "." + name;
79
                }
80
                String sql = MessageFormat.format(
81
                        config.getString(SQLConfig.UPDATE_TABLE_STATISTICS_table),
82
                        name
83
                    );
84
                if( !StringUtils.isEmpty(sql) ) {
85
                    sqls.add(sql);
86
                }
87
            }
88
            return sqls;
89
        }        
90
    }
91
    
92
    protected class PostgreSQLCreateTableBuilder extends CreateTableBuilderBase {
93

  
94
        @Override
95
       public List<String> toStrings() {
96
           // 
97
           // https://www.postgresql.org/docs/9.1/static/sql-createtable.html
98
           //
99
            List<String> sqls = new ArrayList<>();
100
            StringBuilder builder = new StringBuilder();
101

  
102
            builder.append("CREATE TABLE ");
103
            builder.append(this.table.toString());
104
            builder.append(" (");
105
            boolean first = true;
106
            for (ColumnDescriptorBuilder column : columns) {
107
                if( column.isGeometry() ) {
108
                    continue;
109
                }
110
                if (first) {
111
                    first = false;
112
                } else {
113
                    builder.append(", ");
114
                }
115
                builder.append(identifier(column.getName()));
116
                builder.append(" ");
117
                if( column.isAutomatic() ) {
118
                    builder.append(" SERIAL");
119
                } else {
120
                    builder.append(sqltype(column.getType(), column.getPrecision(), column.getSize()));
121
                    if (column.getDefaultValue() == null) {
122
                        if (column.allowNulls()) {
123
                            builder.append(" DEFAULT NULL");
124
                        }
125
                    } else {
126
                        builder.append(" DEFAULT '");
127
                        builder.append(column.getDefaultValue().toString());
128
                        builder.append("'");
129
                    }
130
                    if (column.allowNulls()) {
131
                        builder.append(" NULL");
132
                    } else {
133
                        builder.append(" NOT NULL");
134
                    }
135
                }
136
                if (column.isPrimaryKey()) {
137
                    builder.append(" PRIMARY KEY");
138
                }
139
            }
140
            builder.append(" )");
141
            sqls.add(builder.toString());
142

  
143
            String AddGeometryColumn = "SELECT AddGeometryColumn({0} , {1} , {2}, {3,number,#######} , {4} , {5}, {6})";
144
            for (ColumnDescriptorBuilderBase column : columns) {
145
                if( column.isGeometry() ) {
146
                    String sql = MessageFormat.format(
147
                        AddGeometryColumn,
148
                        constant(this.table.getSchema()),
149
                        constant(this.table.getName()),
150
                        constant(column.getName()),
151
                        column.getGeometrySRSId(),
152
                        constant(sqlgeometrytype(column.getGeometryType(), column.getGeometrySubtype())),
153
                        constant(sqlgeometrydimension(column.getGeometryType(), column.getGeometrySubtype())),
154
                        constant(column.allowNulls())
155
                    );
156
                    sqls.add(sql);
157
                }
158
            }
159
            for (ColumnDescriptorBuilderBase column : columns) {
160
                if( column.isIndexed() ) {
161
                    String sql;
162
                    String name = "idx_" + this.table().getName() + column.getName();
163
                    if( column.isGeometry() ) {
164
                        sql = MessageFormat.format(
165
                            config.getString(SQLConfig.CREATE_INDEX_name_ON_table_USING_GIST_column),
166
                            name,
167
                            this.table().toString(),
168
                            column.getName()
169
                        );
170
                    } else {
171
                        sql = MessageFormat.format(
172
                            config.getString(SQLConfig.CREATE_INDEX_name_ON_table_column),
173
                            name,
174
                            this.table().toString(),
175
                            column.getName()
176
                        );
177
                    }
178
                    sqls.add(sql);
179
                }
180
            }                        
181
            return sqls;
182
        }
183
    }
184

  
185
    public class PostgreSQLSelectBuilderBase extends SelectBuilderBase {
186
        
187
        @Override
188
        protected boolean isValid(StringBuilder message) {
189
            if( message == null ) {
190
                message = new StringBuilder();
191
            }
192
            if( this.has_offset() && !this.has_order_by() ) {
193
                // Algunos gestores de BBDD requieren que se especifique un
194
                // orden para poder usar OFFSET. Como eso parece buena idea para
195
                // asegurar que siempre tengamos los mismo resultados, lo exijimos
196
                // siempre.
197
                message.append("Can't use OFFSET without an ORDER BY.");
198
                return false;
199
            }
200
            return true;
201
        }        
202
        
203
        @Override
204
        public String toString() {
205
            //
206
            // https://www.postgresql.org/docs/9.1/static/sql-select.html
207
            //
208
            StringBuilder builder = new StringBuilder();
209
            if( !isValid(builder) ) {
210
                throw new IllegalStateException(builder.toString());
211
            }
212
            builder.append("SELECT ");
213
            if( this.distinct ) {
214
                builder.append("DISTINCT ");
215
            }
216
            boolean first = true;
217
            for (SelectColumnBuilder column : columns) {
218
                if (first) {
219
                    first = false;
220
                } else {
221
                    builder.append(", ");
222
                }
223
                builder.append(column.toString());
224
            }
225

  
226
            if ( this.has_from() ) {
227
                builder.append(" FROM ");
228
                builder.append(this.from.toString());
229
            }
230
            if ( this.has_where() ) {
231
                builder.append(" WHERE ");
232
                builder.append(this.where.toString());
233
            }
234
            
235
            if( this.has_order_by() ) {
236
                builder.append(" ORDER BY ");
237
                first = true;
238
                for (OrderByBuilder item : this.order_by) {
239
                    if (first) {
240
                        first = false;
241
                    } else {
242
                        builder.append(", ");
243
                    }
244
                    builder.append(item.toString());                    
245
                }   
246
            }
247
            
248
            if ( this.has_limit() && this.has_offset() ) {
249
                builder.append(" OFFSET ");
250
                builder.append(this.offset);
251
                builder.append(" FETCH NEXT ");
252
                builder.append(this.limit);
253
                builder.append(" ROWS ONLY");
254

  
255
            } else if ( this.has_limit()) {
256
                builder.append(" LIMIT ");
257
                builder.append(this.limit);
258

  
259
            } else if ( this.has_offset() ) {
260
                builder.append(" LIMIT ALL OFFSET ");
261
                builder.append(this.offset);    
262
            }
263
            return builder.toString();
264

  
265
        }
266
    }
267

  
268
    @Override
269
    public String bytearray(byte[] data) {
270
        return "decode('"+bytearray_hex(data)+"','hex')";
271
    }
272
    
273
    @Override
274
    protected CreateTableBuilder createCreateTableBuilder() {
275
        return new PostgreSQLCreateTableBuilder();
276
    }
277

  
278
    @Override
279
    protected SelectBuilder createSelectBuilder() {
280
        return new PostgreSQLSelectBuilderBase();
281
    }
282

  
283
    @Override
284
    protected UpdateTableStatisticsBuilder createUpdateTableStatisticsBuilder() {
285
        return new PostgreSQLUpdateTableStatisticsBuilderBase();
286
    }    
287
}
tags/org.gvsig.postgresql-2.0.86/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/PostgreSQLNewStoreParameters.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.postgresql.dal;
23

  
24
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
25
import org.gvsig.fmap.dal.store.jdbc.JDBCNewStoreParameters;
26

  
27
public class PostgreSQLNewStoreParameters 
28
    extends 
29
        JDBCNewStoreParameters 
30
    implements 
31
        PostgreSQLConnectionParameters 
32
    {
33

  
34
    private final PostgreSQLConnectionParametersHelper helper;
35
    
36
    public PostgreSQLNewStoreParameters() {
37
        super(
38
            PostgreSQLLibrary.NAME + "NewStoreParameters", 
39
            PostgreSQLLibrary.NAME
40
        );
41
        this.helper = new PostgreSQLConnectionParametersHelper(this);
42
    }
43

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

  
59
    public void setUseSSL(boolean v) {
60
        this.helper.setUseSSL(v);
61
    }
62

  
63
}
tags/org.gvsig.postgresql-2.0.86/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/PostgreSQLServerExplorerParameters.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.postgresql.dal;
26

  
27
import org.apache.commons.lang3.StringUtils;
28
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
29
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
30
import org.gvsig.fmap.dal.store.jdbc.JDBCServerExplorerParameters;
31

  
32
             
33
public class PostgreSQLServerExplorerParameters extends
34
        JDBCServerExplorerParameters 
35
    implements
36
        PostgreSQLConnectionParameters
37
    {
38
    
39
    private final PostgreSQLConnectionParametersHelper helper;
40

  
41
    public PostgreSQLServerExplorerParameters() {
42
        super(
43
                PostgreSQLLibrary.NAME + "ServerExplorerParameters",
44
                PostgreSQLLibrary.NAME
45
        );
46
        this.helper = new PostgreSQLConnectionParametersHelper(this);
47
    }
48

  
49
    @Override
50
    public String getUrl() {
51
        return this.helper.getUrl();
52
    }
53
    
54
    @Override
55
    public void validate() throws ValidateDataParametersException {
56
        // Esto seria para convertir los parametros de gvSIG 2.3 a 2.4.
57
//        if( !StringUtils.equalsIgnoreCase(PostgreSQLLibrary.NAME, (CharSequence) getDynValue(DataStoreProviderServices.PROVIDER_PARAMTER_NAME)) ) {
58
//            setDynValue(DataStoreProviderServices.PROVIDER_PARAMTER_NAME, PostgreSQLLibrary.NAME);
59
//        }
60
        this.helper.validate();
61
        super.validate();        
62
    }
63

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

  
69
    public void setUseSSL(boolean v) {
70
        this.helper.setUseSSL(v);
71
    }
72
}
tags/org.gvsig.postgresql-2.0.86/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/PostgreSQLHelper.java
1

  
2
package org.gvsig.postgresql.dal;
3

  
4
import java.sql.Connection;
5
import java.sql.PreparedStatement;
6
import java.sql.SQLException;
7
import java.util.ArrayList;
8
import java.util.List;
9
import org.apache.commons.dbcp.BasicDataSource;
10
import org.apache.commons.lang3.BooleanUtils;
11
import org.apache.commons.lang3.StringUtils;
12
import org.gvsig.fmap.dal.DataTypes;
13
import org.gvsig.fmap.dal.ExpressionBuilder;
14
import org.gvsig.fmap.dal.SQLBuilder;
15
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
16
import org.gvsig.fmap.dal.feature.FeatureType;
17
import org.gvsig.fmap.dal.feature.spi.FeatureProvider;
18
import org.gvsig.fmap.dal.resource.exception.AccessResourceException;
19
import org.gvsig.fmap.dal.store.jdbc.JDBCConnectionParameters;
20
import org.gvsig.fmap.dal.store.jdbc.JDBCNewStoreParameters;
21
import org.gvsig.fmap.dal.store.jdbc.JDBCServerExplorerParameters;
22
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParameters;
23
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCDriverClassNotFoundException;
24
import org.gvsig.fmap.dal.store.jdbc2.JDBCUtils;
25
import org.gvsig.fmap.dal.store.jdbc2.OperationsFactory;
26
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCHelperBase;
27
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCSQLBuilderBase;
28
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCSRSsBase;
29
import org.gvsig.fmap.geom.Geometry;
30
import org.gvsig.fmap.geom.aggregate.MultiLine;
31
import org.gvsig.fmap.geom.aggregate.MultiPoint;
32
import org.gvsig.fmap.geom.aggregate.MultiPolygon;
33
import org.gvsig.fmap.geom.exception.CreateGeometryException;
34
import org.gvsig.fmap.geom.primitive.Primitive;
35
import org.gvsig.fmap.geom.type.GeometryType;
36
import org.gvsig.postgresql.dal.operations.PostgreSQLOperationsFactory;
37
import org.slf4j.Logger;
38
import org.slf4j.LoggerFactory;
39

  
40
public class PostgreSQLHelper extends JDBCHelperBase {
41

  
42
    static final Logger logger = LoggerFactory.getLogger(PostgreSQLHelper.class);
43

  
44
    public static final String POSTGRESQL_JDBC_DRIVER = "org.postgresql.Driver";
45
    
46
    public static String getConnectionURL(PostgreSQLConnectionParameters params) {
47
        return getConnectionURL(
48
            params.getHost(),
49
            params.getPort(),
50
            params.getDBName()
51
        );
52
    }
53
    
54
    public static String getConnectionURL(String host, Integer port, String db) {
55
        if( StringUtils.isEmpty(host) ) {
56
            throw new IllegalArgumentException("Parameter 'host' can't be null.");
57
        }
58
        String connectionURL = "jdbc:postgresql://" + host;
59
        if (port != null) {
60
            connectionURL = connectionURL + ":" + port;
61
        }
62
        connectionURL = connectionURL + "/" + db;
63
        logger.debug("connectionURL: {}", connectionURL);
64
        return connectionURL;
65
    }
66

  
67
    private static class ConnectionProvider {
68

  
69
        private static boolean needRegisterDriver = true;
70

  
71
        private BasicDataSource dataSource = null;
72

  
73
        private final PostgreSQLConnectionParameters connectionParameters;
74

  
75
        public ConnectionProvider(PostgreSQLConnectionParameters connectionParameters) {
76
            this.connectionParameters = connectionParameters;
77
        }
78

  
79
        public Connection getConnection() throws SQLException {
80
            if (this.dataSource == null) {
81
                this.dataSource = this.createDataSource();               
82
            }
83
            Connection conn = this.dataSource.getConnection();
84
            return conn;
85
        }
86

  
87
        private BasicDataSource createDataSource() throws SQLException {
88
            if (!this.isRegistered()) {
89
                this.registerDriver();
90
            }
91
            PostgreSQLConnectionParameters params = connectionParameters;
92

  
93
            BasicDataSource ds = new BasicDataSource();
94
            ds.setDriverClassName(params.getJDBCDriverClassName());
95
            if( params.getUseSSL() ) {
96
                String s = BooleanUtils.toStringTrueFalse(params.getUseSSL());
97
                ds.addConnectionProperty("ssl", s );
98
            }
99
            if( !StringUtils.isEmpty(params.getUser()) ) {
100
                ds.setUsername(params.getUser());
101
            }
102
            if( !StringUtils.isEmpty(params.getPassword()) ) {
103
                ds.setPassword(params.getPassword());
104
            }
105
            ds.setUrl(params.getUrl());
106

  
107
            ds.setMaxWait(60L * 1000);
108
            return ds;
109
        }
110

  
111
        private boolean isRegistered() {
112
            return needRegisterDriver;
113
        }
114

  
115
        public void registerDriver() throws SQLException {
116
            String className = this.connectionParameters.getJDBCDriverClassName();
117
            if (className == null) {
118
                return;
119
            }
120
            try {
121
                Class theClass = Class.forName(className);
122
                if (theClass == null) {
123
                    throw new JDBCDriverClassNotFoundException(PostgreSQLLibrary.NAME, className);
124
                }
125
            } catch (Exception e) {
126
                throw new SQLException("Can't register JDBC driver '" + className + "'.", e);
127
            }
128
            needRegisterDriver = false;
129
        }
130

  
131
    }
132

  
133
    private ConnectionProvider connectionProvider = null;
134
   
135
    public PostgreSQLHelper(JDBCConnectionParameters connectionParameters) {
136
        super(connectionParameters);
137
        this.srss = new JDBCSRSsBase(this);
138
    }
139

  
140
    @Override
141
    public Connection getConnection() throws AccessResourceException {
142
        try {
143
            if (this.connectionProvider == null) {
144
                this.connectionProvider = new ConnectionProvider(this.getConnectionParameters());
145
            }
146
            return this.connectionProvider.getConnection();
147
        } catch (SQLException ex) {
148
            throw new AccessResourceException(PostgreSQLLibrary.NAME, ex);
149
        }
150
    }
151
    
152
    @Override
153
    public PostgreSQLConnectionParameters getConnectionParameters() {
154
        return (PostgreSQLConnectionParameters) super.getConnectionParameters();
155
    }
156
    
157
    @Override
158
    public String getConnectionURL() {
159
        return getConnectionURL(this.getConnectionParameters());
160
    }
161

  
162
    @Override
163
    protected String getResourceType() {
164
        return PostgreSQLLibrary.NAME;
165
    }
166

  
167
    @Override
168
    public String getProviderName() {
169
        return PostgreSQLLibrary.NAME;
170
    }
171

  
172
    @Override
173
    public JDBCSQLBuilderBase createSQLBuilder() {
174
        return new PostgreSQLBuilder(this);
175
    }
176
    
177
    @Override
178
    public OperationsFactory getOperations() {
179
        if (this.operationsFactory == null) {
180
            this.operationsFactory = new PostgreSQLOperationsFactory(this);
181
        }
182
        return operationsFactory;
183
    }
184

  
185
    @Override
186
    public SQLBuilder.GeometrySupportType getGeometrySupportType() {
187
        return SQLBuilder.GeometrySupportType.WKB;
188
    }
189

  
190
    @Override
191
    public boolean hasSpatialFunctions() {
192
        return true;
193
    }
194

  
195
    @Override
196
    public boolean canWriteGeometry(int geometryType, int geometrySubtype) {
197
        return true;
198
    }
199

  
200
    @Override
201
    public String getQuoteForIdentifiers() {
202
        return "\"";
203
    }
204

  
205
    @Override
206
    public boolean allowAutomaticValues() {
207
        return true;
208
    }
209

  
210
    @Override
211
    public boolean supportOffsetInSelect() {
212
        return true;
213
    }
214

  
215
    @Override
216
    public String getQuoteForStrings() {
217
        return "'";
218
    }
219
    
220
    @Override
221
    public String getSourceId(JDBCStoreParameters parameters) {
222
        return parameters.getDBName() + "." + 
223
               parameters.getSchema()+ "." + 
224
               parameters.getTable();
225
    }
226

  
227
    @Override
228
    public JDBCNewStoreParameters createNewStoreParameters() {
229
        return new PostgreSQLNewStoreParameters();
230
    }
231

  
232
    @Override
233
    public JDBCStoreParameters createOpenStoreParameters() {
234
        return new PostgreSQLStoreParameters();
235
    }
236

  
237
    @Override
238
    public JDBCServerExplorerParameters createServerExplorerParameters() {
239
        return new PostgreSQLServerExplorerParameters();
240
    }
241

  
242
    public void setPreparedStatementParameters(PreparedStatement st, JDBCSQLBuilderBase sqlbuilder, FeatureType type, FeatureProvider feature) {
243
        try {
244
            List<Object> values = new ArrayList<>();
245
            for (ExpressionBuilder.Parameter parameter : sqlbuilder.getParameters()) {
246
                Object value;
247
                if (parameter.is_constant()) {
248
                    value = parameter.getValue();
249
                } else {
250
                    String name = parameter.getName();
251
                    value = feature.get(name);
252
                    FeatureAttributeDescriptor attr = type.getAttributeDescriptor(name);
253
                    if( attr.getType()==DataTypes.GEOMETRY ) {
254
                        value = forceGeometry(attr.getGeomType(), (Geometry) value);
255
                    }
256
                }
257
                values.add(value);
258
            }
259
            JDBCUtils.setObjects(st, values, sqlbuilder.geometry_support_type());
260
        } catch (Exception ex) {
261
            String f = "unknow";
262
            try {
263
                f = feature.toString();
264
            } catch (Exception ex2) {
265
                // Do nothing
266
            }
267
            throw new RuntimeException("Can't set parameters to prepared statement from the feature (" + f + ")", ex);
268
        }
269
    }
270
    
271
    private Geometry forceGeometry(GeometryType geomtype, Geometry geom) throws CreateGeometryException {
272
        switch( geomtype.getType() ) {
273
        case Geometry.TYPES.MULTIPOLYGON:
274
            if( geom.getType()==Geometry.TYPES.POLYGON ) {
275
                MultiPolygon x = getGeometryManager().createMultiPolygon(geomtype.getSubType());
276
                x.addPrimitive((Primitive) geom);
277
                geom = x;
278
            }
279
            break;
280
        case Geometry.TYPES.MULTILINE:
281
            if( geom.getType()==Geometry.TYPES.LINE ) {
282
                MultiLine x = getGeometryManager().createMultiLine(geomtype.getSubType());
283
                x.addPrimitive((Primitive) geom);
284
                geom = x;
285
            }
286
            break;
287
        case Geometry.TYPES.MULTIPOINT:
288
            if( geom.getType()==Geometry.TYPES.POINT ) {
289
                MultiLine x = getGeometryManager().createMultiLine(geomtype.getSubType());
290
                x.addPrimitive((Primitive) geom);
291
                geom = x;
292
            }
293
            break;
294
        case Geometry.TYPES.POLYGON:
295
            if( geom.getType()==Geometry.TYPES.MULTIPOLYGON ) {
296
                MultiPolygon x = (MultiPolygon) geom;
297
                if( x.getPrimitivesNumber()==1 ) {
298
                    geom = x.getPrimitiveAt(0);
299
                }
300
            }
301
            break;
302
        case Geometry.TYPES.LINE:
303
            if( geom.getType()==Geometry.TYPES.MULTILINE ) {
304
                MultiLine x = (MultiLine) geom;
305
                if( x.getPrimitivesNumber()==1 ) {
306
                    geom = x.getPrimitiveAt(0);
307
                }
308
            }
309
            break;
310
        case Geometry.TYPES.POINT:
311
            if( geom.getType()==Geometry.TYPES.MULTIPOINT ) {
312
                MultiPoint x = (MultiPoint) geom;
313
                if( x.getPrimitivesNumber()==1 ) {
314
                    geom = x.getPrimitiveAt(0);
315
                }
316
            }
317
        }
318
        return geom;
319
    }
320
    
321

  
322
}
tags/org.gvsig.postgresql-2.0.86/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/PostgreSQLServerExplorerFactory.java
1

  
2
package org.gvsig.postgresql.dal;
3

  
4
import org.apache.commons.lang3.StringUtils;
5
import org.gvsig.fmap.dal.DataServerExplorerParameters;
6
import org.gvsig.fmap.dal.exception.InitializeException;
7
import org.gvsig.fmap.dal.spi.DataServerExplorerProviderServices;
8
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
9
import org.gvsig.fmap.dal.store.jdbc.JDBCConnectionParameters;
10
import org.gvsig.fmap.dal.store.jdbc.JDBCServerExplorerParameters;
11
import org.gvsig.fmap.dal.store.jdbc2.JDBCHelper;
12
import org.gvsig.fmap.dal.store.jdbc2.JDBCServerExplorer;
13
import org.gvsig.fmap.dal.store.jdbc2.impl.JDBCServerExplorerFactory;
14

  
15

  
16
public class PostgreSQLServerExplorerFactory extends JDBCServerExplorerFactory {
17

  
18
    private static final String NAME = PostgreSQLLibrary.NAME;
19
    
20
    public PostgreSQLServerExplorerFactory() {
21
        super(
22
            NAME,
23
            "PostgreSQL Server"
24
        );
25
    }
26

  
27
    public PostgreSQLServerExplorerFactory(String name) {
28
        // Cuando se instancia la factoria con un "name" que no es el de por
29
        // defecto, es para declarar "alias" para el ServerExplorer, normalmente
30
        // para mantener compatibilidad con versiones anteriores. 
31
        // Marcaremos la factoria como "hidden" para que no aparezca
32
        // en el interface de usuario.
33
        super(
34
            name,
35
            "PostgreSQL Server (for compatibility)",
36
            true
37
        );
38
    }
39

  
40
    @Override
41
    public JDBCServerExplorer create(
42
            DataServerExplorerParameters parameters, 
43
            DataServerExplorerProviderServices providerServices
44
        ) throws InitializeException {
45
        // Esto seria para convertir los parametros de gvSIG 2.3 a 2.4.
46
//        if( !StringUtils.equalsIgnoreCase(NAME, (CharSequence) parameters.getDynValue(DataStoreProviderServices.PROVIDER_PARAMTER_NAME)) ) {
47
//            parameters.setDynValue(DataStoreProviderServices.PROVIDER_PARAMTER_NAME, NAME);
48
//        }
49
        JDBCHelper helper = new PostgreSQLHelper((JDBCConnectionParameters) parameters);
50
        JDBCServerExplorer server = helper.createServerExplorer(
51
                (JDBCServerExplorerParameters) parameters, 
52
                providerServices
53
        );
54
        return server;
55
    }
56
        
57

  
58
    @Override
59
    public JDBCServerExplorerParameters createParameters() {
60
        JDBCServerExplorerParameters params = new PostgreSQLServerExplorerParameters();
61
        return params;    
62
    }
63
    
64
}
tags/org.gvsig.postgresql-2.0.86/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/PostgreSQLStoreProviderFactory.java
1

  
2
package org.gvsig.postgresql.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 PostgreSQLStoreProviderFactory extends JDBCStoreProviderFactory {
15
    
16
    public PostgreSQLStoreProviderFactory() {
17
        super(
18
                PostgreSQLLibrary.NAME, 
19
                "PostgreSQL store"
20
        );
21
    }
22

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

  
36
    @Override
37
    public JDBCStoreParameters createParameters() {
38
        JDBCStoreParameters params = new PostgreSQLStoreParameters();
39
        return params;
40
    }
41
    
42
}
tags/org.gvsig.postgresql-2.0.86/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/operations/PostgreSQLAppendOperation.java
1

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

  
4
import org.gvsig.fmap.dal.exception.DataException;
5
import org.gvsig.fmap.dal.feature.FeatureType;
6
import org.gvsig.fmap.dal.feature.spi.FeatureProvider;
7
import org.gvsig.fmap.dal.store.jdbc2.JDBCHelper;
8
import org.gvsig.fmap.dal.store.jdbc2.JDBCUtils;
9
import org.gvsig.fmap.dal.store.jdbc2.spi.operations.AppendOperation;
10
import org.gvsig.postgresql.dal.PostgreSQLHelper;
11

  
12

  
13
public class PostgreSQLAppendOperation extends AppendOperation {
14

  
15
    public PostgreSQLAppendOperation(
16
            JDBCHelper helper, 
17
            String database,
18
            String schema, 
19
            String table, 
20
            FeatureType type
21
        ) {
22
        super(helper, database, schema, table, type);
23
    }
24
    
25
    
26
    private PostgreSQLHelper getHelper() {
27
        return (PostgreSQLHelper) this.helper;
28
    }
29

  
30
    @Override
31
    public void append(FeatureProvider feature) throws DataException {
32
        int n;
33
        try {
34
            getHelper().setPreparedStatementParameters(preparedStatement, sqlbuilder, type, feature);
35
            n = JDBCUtils.executeUpdate(this.preparedStatement,this.sql);
36
        } catch(Exception ex) {
37
            throw new RuntimeException("Can't insert feature.", ex);
38
        }
39
        if( n<1 ) {
40
            throw new RuntimeException("Can't insert feature (n="+n+").");
41
        }
42
    }
43
    
44
}
tags/org.gvsig.postgresql-2.0.86/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/operations/PostgreSQLFetchFeatureTypeOperation.java
1

  
2
package org.gvsig.postgresql.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.fmap.dal.DataTypes;
15
import org.gvsig.fmap.dal.exception.DataException;
16
import org.gvsig.fmap.dal.feature.EditableFeatureAttributeDescriptor;
17
import org.gvsig.fmap.dal.feature.EditableFeatureType;
18
import org.gvsig.fmap.dal.store.jdbc2.JDBCHelper;
19
import org.gvsig.fmap.dal.store.jdbc2.JDBCUtils;
20
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCSQLBuilderBase;
21
import org.gvsig.fmap.dal.store.jdbc2.spi.operations.FetchFeatureTypeOperation;
22
import org.gvsig.fmap.geom.Geometry;
23
import org.gvsig.fmap.geom.GeometryLocator;
24
import org.gvsig.fmap.geom.GeometryManager;
25
import org.gvsig.fmap.geom.type.GeometryType;
26

  
27
public class PostgreSQLFetchFeatureTypeOperation extends FetchFeatureTypeOperation {
28

  
29
    private static Map<String,GeometryType>databaseGeometryTypes = null;
30
    
31
    public PostgreSQLFetchFeatureTypeOperation(
32
            JDBCHelper helper
33
        ) {
34
        super(helper);
35
    }
36

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

  
62
    @Override
63
    public void fetch(EditableFeatureType featureType, Connection conn, String dbname, String schema, String table, List<String> pks, String defaultGeometryColumn, IProjection crs) throws DataException {
64
        super.fetch(featureType, conn, dbname, schema, table, pks, defaultGeometryColumn, crs);
65
    }
66

  
67
    @Override
68
    protected int getDataTypeFromMetadata(
69
            ResultSetMetaData rsMetadata,
70
            int colIndex
71
        ) throws SQLException {
72

  
73
        return super.getDataTypeFromMetadata(rsMetadata, colIndex);
74
    }
75
        
76
    @Override
77
    protected void fetchGeometryTypeAndSRS(
78
            EditableFeatureAttributeDescriptor attr,
79
            ResultSetMetaData rsMetadata,
80
            int colIndex
81
        ) {
82
        if( attr.getType()!=DataTypes.GEOMETRY ) {
83
            return;
84
        }
85
        try {
86
            JDBCSQLBuilderBase sqlbuilder = this.createSQLBuilder();
87
            sqlbuilder.select().column().name("f_table_catalog");
88
            sqlbuilder.select().column().name("f_table_schema");
89
            sqlbuilder.select().column().name("f_table_name");
90
            sqlbuilder.select().column().name("f_geometry_column");
91
            sqlbuilder.select().column().name("coord_dimension");
92
            sqlbuilder.select().column().name("srid");
93
            sqlbuilder.select().column().name("type");
94
            sqlbuilder.select().where().set(
95
                    sqlbuilder.eq(
96
                            sqlbuilder.column("f_table_name"),
97
                            sqlbuilder.constant(this.getTablename())
98
                    )
99
            );                
100
            sqlbuilder.select().where().and(
101
                    sqlbuilder.eq(
102
                            sqlbuilder.column("f_geometry_column"),
103
                            sqlbuilder.constant(attr.getName())
104
                    )
105
            );         
106
            sqlbuilder.select().from().table().name("geometry_columns");
107
            Statement st = null;
108
            ResultSet rs = null;
109
            
110
            String srsid = null;
111
            String geometryTypeName = null;
112
            try {
113
                st = this.getConnection().createStatement();
114
                rs = JDBCUtils.executeQuery(st, sqlbuilder.toString());
115
                if (rs.next()) {
116
                    srsid = rs.getString("srid");
117
                    geometryTypeName = rs.getString("type");
118
                }
119
            } finally {
120
                JDBCUtils.closeQuietly(rs);
121
                JDBCUtils.closeQuietly(st);
122
            }
123
            if( !StringUtils.isEmpty(geometryTypeName) ) {
124
                GeometryType gt = getGeometryTypeFromDatabaseTypeName(geometryTypeName);
125
                attr.setGeometryType(gt);
126
            }
127
            if( !StringUtils.isEmpty(srsid) ) {
128
                attr.setSRS(this.helper.getProjectionFromDatabaseCode(srsid));
129
            }
130
        } catch (Exception ex) {
131
            logger.debug("Can't get geometry type and srs from column '"+attr.getName()+"'.",ex);
132
        }
133
    }
134

  
135
    private GeometryType getGeometryTypeFromDatabaseTypeName(String typeName) {
136
        if( databaseGeometryTypes==null ) {
137
            GeometryManager manager = GeometryLocator.getGeometryManager();
138
            databaseGeometryTypes = new HashMap<>();
139
            databaseGeometryTypes.put("POINT", getGT(manager, Geometry.TYPES.POINT,Geometry.SUBTYPES.GEOM2D));
140
            databaseGeometryTypes.put("POINTZ", getGT(manager, Geometry.TYPES.POINT,Geometry.SUBTYPES.GEOM3D));
141
            databaseGeometryTypes.put("POINTM", getGT(manager, Geometry.TYPES.POINT,Geometry.SUBTYPES.GEOM2DM));
142
            databaseGeometryTypes.put("POINTZM", getGT(manager, Geometry.TYPES.POINT,Geometry.SUBTYPES.GEOM3DM));
143
            
144
            databaseGeometryTypes.put("LINESTRING", getGT(manager, Geometry.TYPES.LINE,Geometry.SUBTYPES.GEOM2D));
145
            databaseGeometryTypes.put("LINESTRINGZ", getGT(manager, Geometry.TYPES.LINE,Geometry.SUBTYPES.GEOM3D));
146
            databaseGeometryTypes.put("LINESTRINGM", getGT(manager, Geometry.TYPES.LINE,Geometry.SUBTYPES.GEOM2DM));
147
            databaseGeometryTypes.put("LINESTRINGZM", getGT(manager, Geometry.TYPES.LINE,Geometry.SUBTYPES.GEOM3DM));
148
            
149
            databaseGeometryTypes.put("POLYGON", getGT(manager, Geometry.TYPES.POLYGON,Geometry.SUBTYPES.GEOM2D));
150
            databaseGeometryTypes.put("POLYGONZ", getGT(manager, Geometry.TYPES.POLYGON,Geometry.SUBTYPES.GEOM3D));
151
            databaseGeometryTypes.put("POLYGONM", getGT(manager, Geometry.TYPES.POLYGON,Geometry.SUBTYPES.GEOM2DM));
152
            databaseGeometryTypes.put("POLYGONZM", getGT(manager, Geometry.TYPES.POLYGON,Geometry.SUBTYPES.GEOM3DM));
153

  
154
            databaseGeometryTypes.put("MULTIPOINT", getGT(manager, Geometry.TYPES.MULTIPOINT,Geometry.SUBTYPES.GEOM2D));
155
            databaseGeometryTypes.put("MULTIPOINTZ", getGT(manager, Geometry.TYPES.MULTIPOINT,Geometry.SUBTYPES.GEOM3D));
156
            databaseGeometryTypes.put("MULTIPOINTM", getGT(manager, Geometry.TYPES.MULTIPOINT,Geometry.SUBTYPES.GEOM2DM));
157
            databaseGeometryTypes.put("MULTIPOINTZM", getGT(manager, Geometry.TYPES.MULTIPOINT,Geometry.SUBTYPES.GEOM3DM));
158

  
159
            databaseGeometryTypes.put("MULTILINESTRING", getGT(manager, Geometry.TYPES.MULTILINE,Geometry.SUBTYPES.GEOM2D));
160
            databaseGeometryTypes.put("MULTILINESTRINGZ", getGT(manager, Geometry.TYPES.MULTILINE,Geometry.SUBTYPES.GEOM3D));
161
            databaseGeometryTypes.put("MULTILINESTRINGM", getGT(manager, Geometry.TYPES.MULTILINE,Geometry.SUBTYPES.GEOM2DM));
162
            databaseGeometryTypes.put("MULTILINESTRINGZM", getGT(manager, Geometry.TYPES.MULTILINE,Geometry.SUBTYPES.GEOM3DM));
163

  
164
            databaseGeometryTypes.put("MULTIPOLYGON", getGT(manager, Geometry.TYPES.MULTIPOLYGON,Geometry.SUBTYPES.GEOM2D));
165
            databaseGeometryTypes.put("MULTIPOLYGONZ", getGT(manager, Geometry.TYPES.MULTIPOLYGON,Geometry.SUBTYPES.GEOM3D));
166
            databaseGeometryTypes.put("MULTIPOLYGONM", getGT(manager, Geometry.TYPES.MULTIPOLYGON,Geometry.SUBTYPES.GEOM2DM));
167
            databaseGeometryTypes.put("MULTIPOLYGONZM", getGT(manager, Geometry.TYPES.MULTIPOLYGON,Geometry.SUBTYPES.GEOM3DM));
168

  
169
            databaseGeometryTypes.put("GEOMETRY", getGT(manager, Geometry.TYPES.GEOMETRY,Geometry.SUBTYPES.GEOM2D));
170
            databaseGeometryTypes.put("GEOMETRYZ", getGT(manager, Geometry.TYPES.GEOMETRY,Geometry.SUBTYPES.GEOM3D));
171
            databaseGeometryTypes.put("GEOMETRYM", getGT(manager, Geometry.TYPES.GEOMETRY,Geometry.SUBTYPES.GEOM2DM));
172
            databaseGeometryTypes.put("GEOMETRYZM", getGT(manager, Geometry.TYPES.GEOMETRY,Geometry.SUBTYPES.GEOM3DM));
173
        }
174
        return databaseGeometryTypes.get(typeName);
175
    }
176
    
177
}
tags/org.gvsig.postgresql-2.0.86/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/operations/PostgreSQLOperationsFactory.java
1

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

  
4
import java.util.Iterator;
5
import java.util.List;
6
import org.cresques.cts.IProjection;
7
import org.gvsig.fmap.dal.feature.EditableFeatureType;
8
import org.gvsig.fmap.dal.feature.FeatureType;
9
import org.gvsig.fmap.dal.store.jdbc2.JDBCHelper;
10
import org.gvsig.fmap.dal.store.jdbc2.spi.operations.AppendOperation;
11
import org.gvsig.fmap.dal.store.jdbc2.spi.operations.FetchFeatureTypeOperation;
12
import org.gvsig.fmap.dal.store.jdbc2.spi.operations.OperationsFactoryBase;
13
import org.gvsig.fmap.dal.store.jdbc2.spi.operations.PerformChangesOperation;
14

  
15

  
16
public class PostgreSQLOperationsFactory extends OperationsFactoryBase {
17
    
18
    public PostgreSQLOperationsFactory(JDBCHelper helper) {
19
        super(helper);
20
    }
21

  
22
    @Override
23
    public FetchFeatureTypeOperation createFetchFeatureType(EditableFeatureType type, String database, String schema, String table, List<String> primaryKeys, String defaultGeometryField, IProjection crs) {
24
        return new PostgreSQLFetchFeatureTypeOperation(
25
                helper, type, database, schema, table, primaryKeys, 
26
                defaultGeometryField, crs
27
        );
28
    }  
29

  
30
    @Override
31
    public PerformChangesOperation createPerformChanges(String database, String schema, String table, FeatureType type, Iterator deleteds, Iterator inserteds, Iterator updateds, Iterator featureTypesChanged) {
32
        return new PostgreSQLPerformChangesOperation(
33
            helper, 
34
            database, schema, table, type, 
35
            deleteds, inserteds, updateds, 
36
            featureTypesChanged
37
        ); 
38
    }
39

  
40
    @Override
41
    public AppendOperation createAppend(String database, String schema, String table, FeatureType type) {
42
        return new PostgreSQLAppendOperation(helper, database, schema, table, type); 
43
    }
44
    
45
    
46
}
tags/org.gvsig.postgresql-2.0.86/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/operations/PostgreSQLPerformChangesOperation.java
1
package org.gvsig.postgresql.dal.operations;
2

  
3
import java.sql.Connection;
4
import java.sql.PreparedStatement;
5
import java.sql.SQLException;
6
import java.sql.Statement;
7
import java.util.Iterator;
8
import org.gvsig.fmap.dal.exception.DataException;
9
import org.gvsig.fmap.dal.feature.FeatureType;
10
import org.gvsig.fmap.dal.feature.spi.FeatureProvider;
11
import org.gvsig.fmap.dal.feature.spi.FeatureReferenceProviderServices;
12
import org.gvsig.fmap.dal.feature.spi.FeatureStoreProvider;
13
import org.gvsig.fmap.dal.feature.spi.SQLBuilderBase;
14
import org.gvsig.fmap.dal.store.jdbc2.JDBCHelper;
15
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCExecuteSQLException;
16
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCSQLException;
17
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCUpdateWithoutChangesException;
18
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCSQLBuilderBase;
19
import org.gvsig.fmap.dal.store.jdbc2.JDBCUtils;
20
import org.gvsig.fmap.dal.store.jdbc2.spi.operations.PerformChangesOperation;
21
import org.gvsig.postgresql.dal.PostgreSQLHelper;
22

  
23
public class PostgreSQLPerformChangesOperation extends PerformChangesOperation {
24

  
25
    
26
    public PostgreSQLPerformChangesOperation(JDBCHelper helper) {
27
        this(helper, null, null, null, null, null, null, null, null);
28
    }
29

  
30
    public PostgreSQLPerformChangesOperation(JDBCHelper helper,
31
            String dbName,
32
            String schemaName,
33
            String tableName,
34
            FeatureType featureType,
35
            Iterator<FeatureReferenceProviderServices> deleteds,
36
            Iterator<FeatureProvider> inserteds,
37
            Iterator<FeatureProvider> updateds,
38
            Iterator<FeatureStoreProvider.FeatureTypeChanged> featureTypesChanged) {
39
        super(helper);
40
        this.dbName = dbName;
41
        this.deleteds = deleteds;
42
        this.inserteds = inserteds;
43
        this.updateds = updateds;
44
        this.schemaName = schemaName;
45
        this.tableName = tableName;
46
        this.featureType = featureType;
47
        this.featureTypesChanged = featureTypesChanged;
48
    }
49
    
50
    private PostgreSQLHelper getHelper() {
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff