Revision 548

View differences:

tags/org.gvsig.postgresql-2.0.110/org.gvsig.postgresql.app/org.gvsig.postgresql.app.mainplugin/buildNumber.properties
1
#Tue Oct 15 23:51:13 CEST 2019
2
buildNumber=2167
tags/org.gvsig.postgresql-2.0.110/org.gvsig.postgresql.app/org.gvsig.postgresql.app.mainplugin/src/main/resources-plugin/config.xml
1
<?xml version="1.0" encoding="ISO-8859-1"?>
2
<plugin-config>
3
  <libraries library-dir="lib/"/>
4
  <depends plugin-name="org.gvsig.app.mainplugin"/>
5
  <resourceBundle name="text"/>
6
  <extensions>
7
     <extension class-name="org.gvsig.andami.LibraryExtension" active="false"/>
8
  </extensions>    
9
</plugin-config>
tags/org.gvsig.postgresql-2.0.110/org.gvsig.postgresql.app/org.gvsig.postgresql.app.mainplugin/src/main/assembly/gvsig-plugin-package.xml
1
<assembly>
2
  <id>gvsig-plugin-package</id>
3
  <formats>
4
    <format>zip</format>
5
  </formats>
6
  <baseDirectory>${project.artifactId}</baseDirectory>
7
  <includeBaseDirectory>true</includeBaseDirectory>
8
  <files>
9
    <file>
10
      <source>target/${project.artifactId}-${project.version}.jar</source>
11
      <outputDirectory>lib</outputDirectory>
12
    </file>
13
    <file>
14
      <source>target/package.info</source>
15
    </file>
16
    <file>
17
      <source>src/main/resources-plugin/config.xml</source>
18
    </file>
19
  </files>
20

  
21
  <dependencySets>
22
  
23
    <dependencySet>
24
      <useProjectArtifact>false</useProjectArtifact>
25
      <useTransitiveDependencies>false</useTransitiveDependencies>
26
      <outputDirectory>lib</outputDirectory>
27
      <includes>
28
        <include>org.gvsig:org.gvsig.postgresql.provider</include>
29
      </includes>
30
    </dependencySet>
31
    
32
    <dependencySet>
33
      <useProjectArtifact>false</useProjectArtifact>
34
      <useTransitiveDependencies>false</useTransitiveDependencies>
35
      <outputDirectory>lib</outputDirectory>
36
      <includes>
37
		<include>org.postgresql:postgresql</include>
38
		<include>commons-dbcp:commons-dbcp</include>
39
		<include>commons-pool:commons-pool</include>
40
      </includes>
41
    </dependencySet>
42
    
43
  </dependencySets>
44

  
45
</assembly>
46

  
47

  
48

  
49

  
tags/org.gvsig.postgresql-2.0.110/org.gvsig.postgresql.app/org.gvsig.postgresql.app.mainplugin/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.app.mainplugin</artifactId>
7
  <packaging>jar</packaging>
8
  <name>${project.artifactId}</name>
9
  <description>PostgreSQL file format support</description>
10

  
11
  <parent>
12
      <groupId>org.gvsig</groupId>
13
      <artifactId>org.gvsig.postgresql.app</artifactId>
14
      <version>2.0.110</version>
15
  </parent>
16

  
17
  <dependencies>
18
    <dependency>
19
        <groupId>org.gvsig</groupId>
20
        <artifactId>org.gvsig.tools.lib</artifactId>
21
        <scope>compile</scope>
22
    </dependency>
23
    <dependency>
24
        <groupId>org.gvsig</groupId>
25
        <artifactId>org.gvsig.andami</artifactId>
26
        <scope>compile</scope>
27
    </dependency>
28
    <dependency>
29
        <groupId>org.gvsig</groupId>
30
        <artifactId>org.gvsig.postgresql.provider</artifactId>
31
        <scope>compile</scope>
32
    </dependency>
33
    
34
    <dependency>
35
      <groupId>org.postgresql</groupId>
36
      <artifactId>postgresql</artifactId>
37
      <scope>runtime</scope>
38
    </dependency>
39
    <dependency>
40
      <groupId>commons-dbcp</groupId>
41
      <artifactId>commons-dbcp</artifactId>
42
      <scope>runtime</scope>
43
    </dependency>
44
    <dependency>
45
      <groupId>commons-pool</groupId>
46
      <artifactId>commons-pool</artifactId>
47
      <scope>runtime</scope>
48
    </dependency>
49
    
50
  </dependencies>
51
  
52
    <properties>
53
        <!-- Package info property values -->
54
        <!-- Default values in org.gvsig.desktop -->
55
        <gvsig.package.info.name>Formats: PostgreSQL support</gvsig.package.info.name>
56
        <gvsig.package.info.state>testing</gvsig.package.info.state>
57
        <gvsig.package.info.official>true</gvsig.package.info.official>
58
        <gvsig.package.info.dependencies>required: org.gvsig.app.mainplugin -ge 2.0.1</gvsig.package.info.dependencies>
59
        <gvsig.package.info.categories>Formats,Vector,Database</gvsig.package.info.categories>
60
        <gvsig.package.info.poolURL>https://devel.gvsig.org/download/projects/gvsig-postgresql/pool/</gvsig.package.info.poolURL>
61
    </properties>
62
  
63

  
64
</project>
0 65

  
tags/org.gvsig.postgresql-2.0.110/org.gvsig.postgresql.app/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.app</artifactId>
7
  <packaging>pom</packaging>
8
  <name>${project.artifactId}</name>
9
  <parent>
10
      <groupId>org.gvsig</groupId>
11
      <artifactId>org.gvsig.postgresql</artifactId>
12
      <version>2.0.110</version>
13
  </parent>
14

  
15
  <modules>
16
    <module>org.gvsig.postgresql.app.mainplugin</module>
17
    <!--
18
    <module>org.gvsig.postgresql.app.export</module>
19
    -->
20
  </modules>
21

  
22
</project>
tags/org.gvsig.postgresql-2.0.110/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.110</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.250</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.110</connection>
20
      <developerConnection>scm:svn:https://devel.gvsig.org/svn/gvsig-postgresql/tags/org.gvsig.postgresql-2.0.110</developerConnection>
21
      <url>https://devel.gvsig.org/redmine/projects/gvsig-postgresql/repository/show/tags/org.gvsig.postgresql-2.0.110</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.110</version>
63
          </dependency>
64
          <dependency>
65
            <groupId>org.gvsig</groupId>
66
            <artifactId>org.gvsig.postgresql.app.mainplugin</artifactId>
67
            <version>2.0.110</version>
68
          </dependency>
69
        <dependency>
70
            <groupId>org.postgresql</groupId>
71
            <artifactId>postgresql</artifactId>
72
            <version>42.2.6</version>
73
        </dependency>
74
      </dependencies>
75
  </dependencyManagement>
76
 
77
  <modules>
78
    <module>org.gvsig.postgresql.app</module>
79
    <module>org.gvsig.postgresql.provider</module>
80
  </modules>
81

  
82
</project>
tags/org.gvsig.postgresql-2.0.110/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.sql.Connection;
28
import java.sql.DatabaseMetaData;
29
import java.text.MessageFormat;
30
import java.util.ArrayList;
31
import java.util.List;
32
import org.apache.commons.lang3.StringUtils;
33
import org.gvsig.expressionevaluator.Formatter;
34
import org.gvsig.fmap.dal.store.jdbc2.JDBCHelper;
35
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCSQLBuilderBase;
36
import org.gvsig.postgresql.dal.expressionbuilderformatter.PostgreSQLFormatter;
37

  
38
public class PostgreSQLBuilder extends JDBCSQLBuilderBase {
39

  
40
    protected Formatter formatter = null;
41
    
42
    public static class Version {
43

  
44
        private final int major;
45
        private final int minor;
46
        
47
        public Version(int major, int minor) {
48
            this.major = major;
49
            this.minor = minor;
50
        }
51

  
52
        public int getMajor() {
53
            return major;
54
        }
55

  
56
        public int getMinor() {
57
            return minor;
58
        }
59
        
60
    }
61
    private Version databaseVersion = null;
62
    
63
    public Version getDatabaseVersion() {
64
        if( databaseVersion == null ) {
65
            Connection conn = null;
66
            try {
67
                conn = this.getHelper().getConnection();
68
                DatabaseMetaData metadata = conn.getMetaData();
69
                databaseVersion = new Version(
70
                    metadata.getDatabaseMajorVersion(),
71
                    metadata.getDatabaseMinorVersion()
72
                );
73
            } catch (Exception ex) {
74
                databaseVersion = new Version(0,0);
75
            } finally {
76
                this.getHelper().closeConnectionQuietly(conn);
77
            }
78
        }
79
        return databaseVersion;
80
    }
81
    
82
    public PostgreSQLBuilder(JDBCHelper helper) {
83
        super(helper);
84
        this.defaultSchema = "public";
85
        this.supportSchemas = true;
86
        this.allowAutomaticValues = true;
87
        this.geometrySupportType = this.helper.getGeometrySupportType();
88
        this.hasSpatialFunctions = this.helper.hasSpatialFunctions();
89

  
90
        this.STMT_DELETE_GEOMETRY_COLUMN_FROM_TABLE_schema_table = null;
91
        this.STMT_DELETE_GEOMETRY_COLUMN_FROM_TABLE_table = null;
92

  
93
        this.STMT_UPDATE_TABLE_STATISTICS_table = "ANALYZE {0}";
94

  
95
//        config.set(SQLConfig.ST_GeomFromEWKB, "ST_GeomFromEWKB({0}, {1})");
96
//        config.set(SQLConfig.ST_AsEWKB, "ST_AsEWKB(({0}))");        
97
//        config.set(SQLConfig.ST_ExtentAggregate, "ST_Extent({0})");        
98
//        config.set(SQLConfig.ST_UnionAggregate, "ST_Union({0})");
99
        
100
//        config.set(SQLConfig.isNull, "( ({0}) ISNULL )");
101
//        config.set(SQLConfig.notIsNull, "( ({0}) NOT NULL )");
102

  
103
    }
104
    
105
    public class PostgreSQLUpdateTableStatisticsBuilderBase extends UpdateTableStatisticsBuilderBase {
106
        @Override
107
        public List<String> toStrings() {
108
            List<String> sqls = new ArrayList<>();
109
            
110
            if( !StringUtils.isBlank(STMT_UPDATE_TABLE_STATISTICS_table) ) {
111
                // In postGIS, UpdateLayerStatistics function, don't allow to 
112
                // use the database name in the table name.
113
                String name = as_identifier(this.table.getName());
114
                if( table.has_schema()) {
115
                    name = as_identifier(this.table.getSchema()) + "." + name;
116
                }
117
                String sql = MessageFormat.format(
118
                        STMT_UPDATE_TABLE_STATISTICS_table,
119
                        name
120
                    );
121
                if( !StringUtils.isEmpty(sql) ) {
122
                    sqls.add(sql);
123
                }
124
            }
125
            return sqls;
126
        }        
127
    }
128
    protected class PostgreSQLCreateIndexBuilder extends CreateIndexBuilderBase {
129

  
130
        @Override
131
        public List<String> toStrings(Formatter formatter) {
132
            StringBuilder builder = new StringBuilder();
133
            builder.append("CREATE ");
134
//            if( this.isUnique ) {
135
//                builder.append("UNIQUE ");
136
//            }
137
            builder.append("INDEX ");
138
            if( this.ifNotExist ) {
139
                Version version = getDatabaseVersion();
140
                if( version.getMajor()>=9 && version.getMinor()>=5 ) {
141
                    builder.append("IF NOT EXISTS ");
142
                }
143
            }
144
            builder.append(as_identifier(this.indexName));
145
            builder.append(" ON ");
146
            builder.append(this.table.toString(formatter));
147
            if( this.isSpatial ) {
148
                builder.append(" USING GIST ");
149
            }
150
            builder.append(" ( ");
151
            boolean is_first_column = true;
152
            for( String column : this.columns) {
153
                if( is_first_column ) {
154
                    is_first_column = false;
155
                } else {
156
                    builder.append(", ");
157
                }
158
                builder.append(as_identifier(column));
159
            }
160
            builder.append(" )");
161
            
162
            List<String> sqls = new ArrayList<>();
163
            sqls.add(builder.toString());
164
            return sqls;
165
        }
166
        
167
    }
168
    
169
    protected class PostgreSQLCreateTableBuilder extends CreateTableBuilderBase {
170

  
171
        @Override
172
       public List<String> toStrings(Formatter formatter) {
173
           // 
174
           // https://www.postgresql.org/docs/9.1/static/sql-createtable.html
175
           //
176
            List<String> sqls = new ArrayList<>();
177
            StringBuilder builder = new StringBuilder();
178

  
179
            builder.append("CREATE TABLE ");
180
            builder.append(this.table.toString(formatter));
181
            builder.append(" (");
182
            boolean first = true;
183
            for (ColumnDescriptor column : columns) {
184
                if( column.isGeometry() ) {
185
                    continue;
186
                }
187
                if (first) {
188
                    first = false;
189
                } else {
190
                    builder.append(", ");
191
                }
192
                builder.append(as_identifier(column.getName()));
193
                builder.append(" ");
194
                if( column.isAutomatic() ) {
195
                    builder.append(" SERIAL");
196
                } else {
197
                    builder.append(sqltype(
198
                            column.getType(), 
199
                            column.getPrecision(), 
200
                            column.getSize(),
201
                            column.getGeometryType(),
202
                            column.getGeometrySubtype()
203
                    ));
204
                    if (column.getDefaultValue() == null) {
205
                        if (column.allowNulls()) {
206
                            builder.append(" DEFAULT NULL");
207
                        }
208
                    } else {
209
                        builder.append(" DEFAULT '");
210
                        builder.append(column.getDefaultValue().toString());
211
                        builder.append("'");
212
                    }
213
                    if (column.allowNulls()) {
214
                        builder.append(" NULL");
215
                    } else {
216
                        builder.append(" NOT NULL");
217
                    }
218
                }
219
                if (column.isPrimaryKey()) {
220
                    builder.append(" PRIMARY KEY");
221
                }
222
            }
223
            builder.append(" )");
224
            sqls.add(builder.toString());
225

  
226
            String AddGeometryColumn = "SELECT AddGeometryColumn({0} , {1} , {2}, {3,number,#######} , {4} , {5}, {6})";
227
            for (ColumnDescriptor column : columns) {
228
                if( column.isGeometry() ) {
229
                    String sql = MessageFormat.format(
230
                        AddGeometryColumn,
231
                        as_string(this.table.has_schema()?this.table.getSchema():"public"),
232
                        as_string(this.table.getName()),
233
                        as_string(column.getName()),
234
                        column.getGeometrySRSId(),
235
                        as_string(sqlgeometrytype(column.getGeometryType(), column.getGeometrySubtype())),
236
                        as_string(sqlgeometrydimension(column.getGeometryType(), column.getGeometrySubtype())),
237
                        as_string(column.allowNulls())
238
                    );
239
                    sqls.add(sql);
240
                }
241
            }
242
            return sqls;
243
        }
244
    }
245

  
246
    public class PostgreSQLSelectBuilderBase extends SelectBuilderBase {
247
        
248
        @Override
249
        protected boolean isValid(StringBuilder message) {
250
            if( message == null ) {
251
                message = new StringBuilder();
252
            }
253
            if( this.has_offset() && !this.has_order_by() ) {
254
                // Algunos gestores de BBDD requieren que se especifique un
255
                // orden para poder usar OFFSET. Como eso parece buena idea para
256
                // asegurar que siempre tengamos los mismo resultados, lo exijimos
257
                // siempre.
258
                message.append("Can't use OFFSET without an ORDER BY.");
259
                return false;
260
            }
261
            return true;
262
        }        
263
        
264
        @Override
265
        public String toString(Formatter formatter) {
266
            //
267
            // https://www.postgresql.org/docs/9.1/static/sql-select.html
268
            //
269
            StringBuilder builder = new StringBuilder();
270
            if( !isValid(builder) ) {
271
                throw new IllegalStateException(builder.toString());
272
            }
273
            builder.append("SELECT ");
274
            if( this.distinct ) {
275
                builder.append("DISTINCT ");
276
            }
277
            boolean first = true;
278
            for (SelectColumnBuilder column : columns) {
279
                if (first) {
280
                    first = false;
281
                } else {
282
                    builder.append(", ");
283
                }
284
                builder.append(column.toString(formatter));
285
            }
286

  
287
            if ( this.has_from() ) {
288
                builder.append(" FROM ");
289
                builder.append(this.from.toString(formatter));
290
            }
291
            if( this.has_group_by() ) {
292
                builder.append(" GROUP BY ");
293
                builder.append(this.groupColumn.get(0).toString(formatter));
294
                for (int i = 1; i < groupColumn.size(); i++) {
295
                    builder.append(", ");
296
                    builder.append(this.groupColumn.get(i).toString(formatter));
297
                }
298
            }            
299
            if ( this.has_where() ) {
300
                builder.append(" WHERE ");
301
                builder.append(this.where.toString(formatter));
302
            }
303
            
304
            if( this.has_order_by() ) {
305
                builder.append(" ORDER BY ");
306
                first = true;
307
                for (OrderByBuilder item : this.order_by) {
308
                    if (first) {
309
                        first = false;
310
                    } else {
311
                        builder.append(", ");
312
                    }
313
                    builder.append(item.toString(formatter));
314
                }   
315
            }
316
            
317
            if ( this.has_limit() && this.has_offset() ) {
318
                builder.append(" OFFSET ");
319
                builder.append(this.offset);
320
                builder.append(" FETCH NEXT ");
321
                builder.append(this.limit);
322
                builder.append(" ROWS ONLY");
323

  
324
            } else if ( this.has_limit()) {
325
                builder.append(" LIMIT ");
326
                builder.append(this.limit);
327

  
328
            } else if ( this.has_offset() ) {
329
                builder.append(" LIMIT ALL OFFSET ");
330
                builder.append(this.offset);    
331
            }
332
            return builder.toString();
333

  
334
        }
335
    }
336

  
337
    @Override
338
    protected Formatter formatter() {
339
        if( this.formatter==null ) {
340
            this.formatter = new PostgreSQLFormatter(this);
341
        }
342
        return this.formatter;
343
    }
344

  
345
    @Override
346
    public PostgreSQLHelper getHelper() {
347
        return (PostgreSQLHelper) helper;
348
    }
349
    
350
    @Override
351
    protected CreateTableBuilder createCreateTableBuilder() {
352
        return new PostgreSQLCreateTableBuilder();
353
    }
354

  
355
    @Override
356
    protected CreateIndexBuilder createCreateIndexBuilder() {
357
        return new PostgreSQLCreateIndexBuilder();
358
    }
359

  
360
    @Override
361
    protected SelectBuilder createSelectBuilder() {
362
        return new PostgreSQLSelectBuilderBase();
363
    }
364

  
365
    @Override
366
    protected UpdateTableStatisticsBuilder createUpdateTableStatisticsBuilder() {
367
        return new PostgreSQLUpdateTableStatisticsBuilderBase();
368
    }       
369
   
370
}
tags/org.gvsig.postgresql-2.0.110/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/expressionbuilderformatter/Decode.java
1
package org.gvsig.postgresql.dal.expressionbuilderformatter;
2

  
3
import java.util.List;
4
import java.util.Objects;
5
import org.apache.commons.lang3.StringUtils;
6
import org.gvsig.expressionevaluator.ExpressionBuilder;
7
import static org.gvsig.expressionevaluator.ExpressionBuilder.FUNCTION_DECODE;
8
import org.gvsig.expressionevaluator.ExpressionBuilder.Function;
9
import org.gvsig.expressionevaluator.ExpressionBuilder.Value;
10
import org.gvsig.expressionevaluator.Formatter;
11
import org.gvsig.fmap.dal.SQLBuilder;
12

  
13
/**
14
 *
15
 * @author jjdelcerro
16
 */
17
public class Decode implements Formatter<Value> {
18
    
19
    private final SQLBuilder sqlbuilder;
20
    private final Formatter<Value> formatter;
21
    
22
    public Decode(SQLBuilder sqlbuilder, Formatter<Value> formatter) {
23
        this.sqlbuilder = sqlbuilder;
24
        this.formatter = formatter;
25
    }
26
    
27
    @Override
28
    public boolean canApply(ExpressionBuilder.Value value) {
29
        if (value instanceof ExpressionBuilder.Function) {
30
            if( StringUtils.equalsIgnoreCase(FUNCTION_DECODE, ((Function) value).name()) ) {
31
                List<Value> parameters = ((Function) value).parameters();
32
                if( parameters.size()==2) {
33
                    Value p1 = parameters.get(0);
34
                    Value p2 = parameters.get(1);
35
                    if( p1 instanceof ExpressionBuilder.Constant && 
36
                        p2 instanceof ExpressionBuilder.Constant &&
37
                        ((ExpressionBuilder.Constant)p1).value() instanceof String &&
38
                        ((ExpressionBuilder.Constant)p2).value() instanceof String 
39
                        ) {
40
                        String p2value = ((ExpressionBuilder.Constant)p2).value().toString();
41
                        if( StringUtils.equalsIgnoreCase(p2value, "hex") ) {
42
                            return true;
43
                        }
44
                    }
45
                    
46
                }
47
            }
48
        }
49
        return false;
50
    }
51

  
52
    @Override
53
    public String format(Value function) {
54
        ExpressionBuilder builder = this.sqlbuilder.expression();
55
        List<Value> parameters = ((Function) function).parameters();
56
        Value p1 = parameters.get(0);
57
        String p1value = Objects.toString(((ExpressionBuilder.Constant)p1).value(), "");
58
        String r = builder.string("\\x"+p1value)+"::bytea";
59
        return r;
60
    }
61
    
62
}
tags/org.gvsig.postgresql-2.0.110/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/expressionbuilderformatter/ST_ExtentAggregate.java
1
package org.gvsig.postgresql.dal.expressionbuilderformatter;
2

  
3
import java.text.MessageFormat;
4
import java.util.List;
5
import org.apache.commons.lang3.StringUtils;
6
import org.gvsig.expressionevaluator.ExpressionBuilder;
7
import static org.gvsig.expressionevaluator.ExpressionBuilder.FUNCTION_ST_EXTENTAGGREGATE;
8
import org.gvsig.expressionevaluator.ExpressionBuilder.Function;
9
import org.gvsig.expressionevaluator.ExpressionBuilder.Value;
10
import org.gvsig.expressionevaluator.Formatter;
11
import org.gvsig.fmap.dal.SQLBuilder;
12

  
13
/**
14
 *
15
 * @author jjdelcerro
16
 */
17
public class ST_ExtentAggregate implements Formatter<Value> {
18
    
19
    private final SQLBuilder sqlbuilder;
20
    private final Formatter<Value> formatter;
21
    
22
    public ST_ExtentAggregate(SQLBuilder sqlbuilder, Formatter<Value> formatter) {
23
        this.sqlbuilder = sqlbuilder;
24
        this.formatter = formatter;
25
    }
26
    @Override
27
    public boolean canApply(ExpressionBuilder.Value value) {
28
        if (value instanceof ExpressionBuilder.Function) {
29
            return StringUtils.equalsIgnoreCase(FUNCTION_ST_EXTENTAGGREGATE, ((Function) value).name());
30
        }
31
        return false;
32
    }
33

  
34
    @Override
35
    public String format(Value function) {
36
        List<Value> parameters = ((Function) function).parameters();
37
        String p1 = parameters.get(0).toString(formatter);
38
        String r = MessageFormat.format("ST_Extent({0})", p1);
39
        return r;
40
    }
41
    
42
}
tags/org.gvsig.postgresql-2.0.110/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/expressionbuilderformatter/ST_GeomFromWKB.java
1
package org.gvsig.postgresql.dal.expressionbuilderformatter;
2

  
3
import java.text.MessageFormat;
4
import java.util.List;
5
import org.apache.commons.lang3.StringUtils;
6
import org.gvsig.expressionevaluator.ExpressionBuilder;
7
import org.gvsig.expressionevaluator.ExpressionBuilder.Function;
8
import org.gvsig.expressionevaluator.ExpressionBuilder.Value;
9
import org.gvsig.expressionevaluator.Formatter;
10
import org.gvsig.fmap.dal.SQLBuilder;
11
import org.gvsig.fmap.dal.feature.FeatureType;
12
import static org.gvsig.fmap.dal.store.jdbc2.spi.JDBCSQLBuilderBase.PROP_FEATURE_TYPE;
13

  
14
/**
15
 *
16
 * @author jjdelcerro
17
 */
18
public class ST_GeomFromWKB implements Formatter<Value> {
19
    
20
    private final SQLBuilder sqlbuilder;
21
    private final Formatter<Value> formatter;
22
    
23
    public ST_GeomFromWKB(SQLBuilder sqlbuilder, Formatter<Value> formatter) {
24
        this.sqlbuilder = sqlbuilder;
25
        this.formatter = formatter;
26
    }
27
    @Override
28
    public boolean canApply(ExpressionBuilder.Value value) {
29
        if (value instanceof ExpressionBuilder.Function) {
30
            return StringUtils.equalsIgnoreCase(ExpressionBuilder.FUNCTION_ST_GEOMFROMWKB, ((Function) value).name());
31
        }
32
        return false;
33
    }
34

  
35
    @Override
36
    public String format(Value function) {
37
        String r;
38
        String wkb;
39
        String srid;
40
        List<Value> parameters = ((Function) function).parameters();
41
        switch(parameters.size()) {
42
            case 1:
43
                wkb = parameters.get(0).toString(formatter);
44
                r = MessageFormat.format("ST_GeomFromWKB({0})", wkb);
45
                break;
46
            case 2:
47
                wkb = parameters.get(0).toString(formatter);
48
                srid = parameters.get(1).toString(formatter);
49
                if( StringUtils.equals("0", srid) ) {
50
                    r = MessageFormat.format("ST_GeomFromWKB({0})", wkb);
51
                } else {
52
                    FeatureType ftype = (FeatureType) function.getProperty(PROP_FEATURE_TYPE);
53
                    if( ftype == null || ftype.getDefaultSRS()!=null ) {
54
                        r = MessageFormat.format("ST_GeomFromWKB({0},{1})", wkb, srid);
55
                    } else {
56
                        r = MessageFormat.format("ST_GeomFromWKB({0})", wkb);
57
                    }
58
                }
59
                break;
60
            default:
61
                throw new IllegalArgumentException("Wrong number of arguments ("+parameters.size()+") in function ST_GeomFromWKB; requiered 1 or 2 arguments.");
62
        }
63
        return r;
64
    }
65
    
66
}
tags/org.gvsig.postgresql-2.0.110/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/expressionbuilderformatter/IsNull.java
1
package org.gvsig.postgresql.dal.expressionbuilderformatter;
2

  
3
import java.text.MessageFormat;
4
import java.util.List;
5
import org.apache.commons.lang3.StringUtils;
6
import org.gvsig.expressionevaluator.Code.Constant;
7
import org.gvsig.expressionevaluator.ExpressionBuilder.Function;
8
import static org.gvsig.expressionevaluator.ExpressionBuilder.OPERATOR_IS;
9
import org.gvsig.expressionevaluator.ExpressionBuilder.Value;
10
import org.gvsig.expressionevaluator.Formatter;
11
import org.gvsig.fmap.dal.SQLBuilder;
12

  
13
/**
14
 *
15
 * @author jjdelcerro
16
 */
17
class IsNull implements Formatter<Value> {
18

  
19
    private final Formatter<Value> formatter;
20
    private final SQLBuilder builder;
21
    
22
    public IsNull(SQLBuilder builder, Formatter<Value> formatter) {
23
        this.builder = builder;
24
        this.formatter = formatter;
25
    }
26
    
27
    @Override
28
    public boolean canApply(Value value) {
29
        if (value instanceof Function) {
30
            if( StringUtils.equalsIgnoreCase(OPERATOR_IS, ((Function) value).name()) ) {
31
                List<Value> parameters = ((Function) value).parameters();
32
                Value p2 = parameters.get(1);
33
                if( p2 instanceof Constant && ((Constant)p2).value()==null ) {
34
                    return true;
35
                }
36
            }
37
        }
38
        return false;
39
    }
40

  
41
    @Override
42
    public String format(Value function) {
43
        List<Value> parameters = ((Function) function).parameters();
44
        String p1 = parameters.get(0).toString(formatter);
45
        String r = MessageFormat.format("( ({0}) ISNULL )", p1);
46
        return r;
47
    }
48
    
49
}
tags/org.gvsig.postgresql-2.0.110/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/expressionbuilderformatter/ST_GeomFromText.java
1
package org.gvsig.postgresql.dal.expressionbuilderformatter;
2

  
3
import java.text.MessageFormat;
4
import java.util.List;
5
import org.apache.commons.lang3.StringUtils;
6
import org.gvsig.expressionevaluator.ExpressionBuilder;
7
import org.gvsig.expressionevaluator.ExpressionBuilder.Function;
8
import org.gvsig.expressionevaluator.ExpressionBuilder.Value;
9
import org.gvsig.expressionevaluator.Formatter;
10
import org.gvsig.fmap.dal.SQLBuilder;
11
import org.gvsig.fmap.dal.feature.FeatureType;
12
import static org.gvsig.fmap.dal.store.jdbc2.spi.JDBCSQLBuilderBase.PROP_FEATURE_TYPE;
13

  
14
/**
15
 *
16
 * @author jjdelcerro
17
 */
18
public class ST_GeomFromText implements Formatter<Value> {
19
    
20
    private final SQLBuilder sqlbuilder;
21
    private final Formatter<Value> formatter;
22
    
23
    public ST_GeomFromText(SQLBuilder sqlbuilder, Formatter<Value> formatter) {
24
        this.sqlbuilder = sqlbuilder;
25
        this.formatter = formatter;
26
    }
27
    @Override
28
    public boolean canApply(ExpressionBuilder.Value value) {
29
        if (value instanceof ExpressionBuilder.Function) {
30
            return StringUtils.equalsIgnoreCase(ExpressionBuilder.FUNCTION_ST_GEOMFROMTEXT, ((Function) value).name());
31
        }
32
        return false;
33
    }
34

  
35
    @Override
36
    public String format(Value function) {
37
        String r;
38
        String wkt;
39
        String srid;
40
        List<Value> parameters = ((Function) function).parameters();
41
        switch(parameters.size()) {
42
            case 1:
43
                wkt = parameters.get(0).toString(formatter);
44
                r = MessageFormat.format("ST_GeomFromText({0})", wkt);
45
                break;
46
            case 2:
47
                wkt = parameters.get(0).toString(formatter);
48
                srid = parameters.get(1).toString(formatter);
49
                if( StringUtils.equals("0", srid) ) {
50
                    r = MessageFormat.format("ST_GeomFromText({0})", wkt);
51
                } else {
52
                    FeatureType ftype = (FeatureType) function.getProperty(PROP_FEATURE_TYPE);
53
                    if( ftype == null || ftype.getDefaultSRS()!=null ) {
54
                        r = MessageFormat.format("ST_GeomFromText({0},{1})", wkt, srid);
55
                    } else {
56
                        r = MessageFormat.format("ST_GeomFromText({0})", wkt);
57
                    }
58
                }
59
                break;
60
            default:
61
                throw new IllegalArgumentException("Wrong number of arguments ("+parameters.size()+") in function ST_GeomFromText; requiered 1 or 2 arguments.");
62
        }
63
        return r;
64
    }
65
    
66
}
tags/org.gvsig.postgresql-2.0.110/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/expressionbuilderformatter/PostgreSQLFormatter.java
1
package org.gvsig.postgresql.dal.expressionbuilderformatter;
2

  
3
import org.gvsig.expressionevaluator.ExpressionBuilder;
4
import org.gvsig.expressionevaluator.ExpressionBuilder.Value;
5
import org.gvsig.expressionevaluator.Formatter;
6
import org.gvsig.fmap.dal.SQLBuilder;
7

  
8
/**
9
 *
10
 * @author jjdelcerro
11
 */
12
public class PostgreSQLFormatter implements Formatter<Value> {
13

  
14
    private final SQLBuilder builder;
15
    private final Formatter<ExpressionBuilder.Value>[] formatters;
16

  
17
    public PostgreSQLFormatter(SQLBuilder builder) {
18

  
19
        this.builder = builder;
20
        this.formatters = new Formatter[]{
21
            new Decode(this.builder, this),
22
            new Constant(this.builder, this),
23
            new ILike(this.builder, this),
24
            new IsNull(this.builder, this),
25
//            new ST_AsEWKB(this.builder, this),
26
            new ST_ExtentAggregate(this.builder, this),
27
            new ST_GeomFromWKB(this.builder, this),
28
            new ST_GeomFromText(this.builder, this),
29
//            new ST_GeomFromEWKB(this.builder, this),
30
//            new ST_Intersects(this.builder, this),
31
//            new ST_UnionAggregate(this.builder, this)
32
        };
33
    }
34

  
35
    @Override
36
    public boolean canApply(Value value) {
37
        for (Formatter<Value> formatter : formatters) {
38
            if (formatter.canApply(value)) {
39
                return true;
40
            }
41
        }
42
        return false;
43
    }
44

  
45
    @Override
46
    public String format(Value value) {
47
        for (Formatter<Value> formatter : formatters) {
48
            if (formatter.canApply(value)) {
49
                return formatter.format(value);
50
            }
51
        }
52
        return value.toString(this);
53
    }
54
    
55
}
tags/org.gvsig.postgresql-2.0.110/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/expressionbuilderformatter/Constant.java
1
package org.gvsig.postgresql.dal.expressionbuilderformatter;
2

  
3
import java.text.MessageFormat;
4
import org.gvsig.expressionevaluator.ExpressionBuilder;
5
import org.gvsig.expressionevaluator.ExpressionBuilder.Value;
6
import org.gvsig.expressionevaluator.Formatter;
7
import org.gvsig.fmap.dal.SQLBuilder;
8
import org.gvsig.fmap.geom.Geometry;
9
import org.gvsig.fmap.geom.GeometryUtils;
10

  
11
/**
12
 *
13
 * @author jjdelcerro
14
 */
15
public class Constant implements Formatter<Value> {
16
    
17
    private static final String FORMAT_ST_GEOMFROMWKB = "ST_GeomFromWKB(({0}), ({1}))";
18
    private static final String FORMAT_ST_GEOMFROMEWKB = "ST_GeomFromEWKB(({0}), ({1}))";
19
    private static final String FORMAT_ST_GEOMFROMTEXT = "ST_GeomFromText(({0}), ({1}))";
20

  
21
    private final SQLBuilder sqlbuilder;
22
    private final Formatter<Value> formatter;
23
    
24
    public Constant(SQLBuilder sqlbuilder, Formatter<Value> formatter) {
25
        this.sqlbuilder = sqlbuilder;
26
        this.formatter = formatter;
27
    }
28
    
29
    @Override
30
    public boolean canApply(ExpressionBuilder.Value value) {
31
        if (value instanceof ExpressionBuilder.Constant) {
32
            Object x = ((ExpressionBuilder.Constant)value).value();
33
            if( x instanceof byte[] ) {
34
                return true;
35
            }
36
            if( x instanceof Geometry ) {
37
                return true;
38
            }
39
        }
40
        return false;
41
    }
42

  
43
    @Override
44
    public String format(Value constant) {
45
        Object x = ((ExpressionBuilder.Constant)constant).value();
46
        ExpressionBuilder builder = this.sqlbuilder.expression();
47
        if( x instanceof byte[] ) {
48
            return builder.string("\\x"+builder.bytearray_hex((byte[]) x))+"::bytea";
49
        }
50
        if( x instanceof Geometry ) {
51
            Geometry geometry = (Geometry) x;
52
            switch (builder.geometry_support_type()) {
53
                case EWKB:
54
                    return MessageFormat.format(
55
                            FORMAT_ST_GEOMFROMEWKB,
56
                            builder.string("\\x"+builder.bytearray_hex(GeometryUtils.toEWKB(geometry)))+"::bytea",
57
                            String.valueOf(builder.srs_id(geometry.getProjection()))
58
                    );
59
                case WKB:
60
                    return MessageFormat.format(
61
                            FORMAT_ST_GEOMFROMWKB,
62
                            builder.string("\\x"+builder.bytearray_hex(GeometryUtils.toWKB(geometry)))+"::bytea",
63
                            String.valueOf(builder.srs_id(geometry.getProjection()))
64
                    );
65
                case WKT:
66
                default:
67
                    return MessageFormat.format(
68
                            FORMAT_ST_GEOMFROMTEXT,
69
                            builder.string(GeometryUtils.toWKT(geometry)),
70
                            String.valueOf(builder.srs_id(geometry.getProjection()))
71
                    );
72
            }
73
            
74
        }
75
        return null;
76
    }
77
    
78
}
tags/org.gvsig.postgresql-2.0.110/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/expressionbuilderformatter/ILike.java
1
package org.gvsig.postgresql.dal.expressionbuilderformatter;
2

  
3
import java.text.MessageFormat;
4
import java.util.List;
5
import org.apache.commons.lang3.StringUtils;
6
import org.gvsig.expressionevaluator.ExpressionBuilder.Function;
7
import static org.gvsig.expressionevaluator.ExpressionBuilder.OPERATOR_ILIKE;
8
import org.gvsig.expressionevaluator.ExpressionBuilder.Value;
9
import org.gvsig.expressionevaluator.Formatter;
10
import org.gvsig.fmap.dal.SQLBuilder;
11

  
12
/**
13
 *
14
 * @author jjdelcerro
15
 */
16
class ILike implements Formatter<Value> {
17

  
18
    private final Formatter<Value> formatter;
19
    private final SQLBuilder builder;
20
    
21
    public ILike(SQLBuilder builder, Formatter<Value> formatter) {
22
        this.builder = builder;
23
        this.formatter = formatter;
24
    }
25
    
26
    @Override
27
    public boolean canApply(Value value) {
28
        if (value instanceof Function) {
29
            return StringUtils.equalsIgnoreCase(OPERATOR_ILIKE, ((Function) value).name());
30
        }
31
        return false;
32
    }
33

  
34
    @Override
35
    public String format(Value function) {
36
        List<Value> parameters = ((Function) function).parameters();
37
        String p1 = parameters.get(0).toString(formatter);
38
        String p2 = parameters.get(1).toString(formatter);
39
        String r = MessageFormat.format("(({0}).LOWER() LIKE ({1}).LOWER())", p1, p2);
40
        return r;
41
    }
42
    
43
}
tags/org.gvsig.postgresql-2.0.110/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
    @Override
60
    public int getMaxIdle() {
61
        return this.helper.getMaxIdle();
62
    }
63

  
64
    public void setUseSSL(boolean v) {
65
        this.helper.setUseSSL(v);
66
    }
67

  
68
}
tags/org.gvsig.postgresql-2.0.110/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
    @Override
70
    public int getMaxIdle() {
71
        return this.helper.getMaxIdle();
72
    }
73

  
74
    public void setUseSSL(boolean v) {
75
        this.helper.setUseSSL(v);
76
    }
77
}
tags/org.gvsig.postgresql-2.0.110/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.SQLException;
6
import org.apache.commons.dbcp.BasicDataSource;
7
import org.apache.commons.lang3.BooleanUtils;
8
import org.apache.commons.lang3.StringUtils;
9
import org.gvsig.expressionevaluator.ExpressionBuilder.GeometrySupportType;
10
import org.gvsig.fmap.dal.SQLBuilder;
11
import org.gvsig.fmap.dal.resource.exception.AccessResourceException;
12
import org.gvsig.fmap.dal.store.jdbc.JDBCConnectionParameters;
13
import org.gvsig.fmap.dal.store.jdbc.JDBCNewStoreParameters;
14
import org.gvsig.fmap.dal.store.jdbc.JDBCServerExplorerParameters;
15
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParameters;
16
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCDriverClassNotFoundException;
17
import org.gvsig.fmap.dal.store.jdbc2.OperationsFactory;
18
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCHelperBase;
19
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCSQLBuilderBase;
20
import org.gvsig.fmap.dal.store.jdbc2.spi.SRSSolverBase;
21
import org.gvsig.postgresql.dal.operations.PostgreSQLOperationsFactory;
22
import org.slf4j.Logger;
23
import org.slf4j.LoggerFactory;
24

  
25
public class PostgreSQLHelper extends JDBCHelperBase {
26

  
27
    static final Logger logger = LoggerFactory.getLogger(PostgreSQLHelper.class);
28

  
29
    public static final String POSTGRESQL_JDBC_DRIVER = "org.postgresql.Driver";
30
    
31
    public static String getConnectionURL(PostgreSQLConnectionParameters params) {
32
        return getConnectionURL(
33
            params.getHost(),
34
            params.getPort(),
35
            params.getDBName()
36
        );
37
    }
38
    
39
    public static String getConnectionURL(String host, Integer port, String db) {
40
        if( StringUtils.isEmpty(host) ) {
41
            throw new IllegalArgumentException("Parameter 'host' can't be null.");
42
        }
43
        String connectionURL = "jdbc:postgresql://" + host;
44
        if (port != null) {
45
            connectionURL = connectionURL + ":" + port;
46
        }
47
        connectionURL = connectionURL + "/" + db;
48
        logger.debug("connectionURL: {}", connectionURL);
49
        return connectionURL;
50
    }
51

  
52
    private static class ConnectionProvider {
53

  
54
        private static boolean needRegisterDriver = true;
55

  
56
        private BasicDataSource dataSource = null;
57

  
58
        private final PostgreSQLConnectionParameters connectionParameters;
59

  
60
        public ConnectionProvider(PostgreSQLConnectionParameters connectionParameters) {
61
            this.connectionParameters = connectionParameters;
62
        }
63

  
64
        public Connection getConnection() throws SQLException {
65
            if (this.dataSource == null) {
66
                this.dataSource = this.createDataSource();               
67
            }
68
            if( logger.isDebugEnabled() ) {
69
                logger.debug("getConnection:\n" + getStatusInformation());
70
            }
71
            Connection conn;
72
            try {
73
                conn = this.dataSource.getConnection();
74
            } catch(Throwable ex) {
75
                logger.debug("Error getting connection from pool.",ex);
76
                throw ex;
77
            }
78
            if( logger.isDebugEnabled() ) {
79
                logger.debug("Created connection: {}\n  NumActive: {}\n  NumIdle: {}",
80
                    new Object[] {
81
                        conn.hashCode(), 
82
                        this.dataSource.getNumActive(),
83
                        this.dataSource.getNumIdle()
84
                    }
85
                );
86
            }
87
            return conn;
88
        }
89
        
90
        public void closeConnection(Connection connection) {
91
            if( connection != null ) {
92
                int connectionId = connection.hashCode();
93
                try {
94
                    connection.close();
95
                } catch(Throwable ex) {
96
                    logger.warn("Can't close connection.", ex);
97
                }
98
                if( logger.isDebugEnabled() ) {
99
                    Boolean isClosed;
100
                    try {
101
                        isClosed = connection.isClosed();
102
                    } catch(Throwable th) {
103
                        isClosed = null;
104
                    }
105
                    logger.debug("Closed connection: {}\n  isClosed: {}\n  NumActive: {}\n  NumIdle: {}",
106
                        new Object[] {
107
                            connectionId, 
108
                            isClosed,
109
                            this.dataSource.getNumActive(),
110
                            this.dataSource.getNumIdle()
111
                        }
112
                    );
113
                }
114
           } else if( logger.isDebugEnabled() ) {
115
               logger.debug("Close connection: null");
116
           }
117
        }
118
        
119
        public String getStatusInformation() {
120
            StringBuilder builder = new StringBuilder();
121
            builder.append("BasicDataSource pool status:\n");
122
            builder.append("  Connection URL: '").append(this.dataSource.getUrl()).append("'\n");
123
            if( this.dataSource.getInitialSize()>0 ) {
124
                builder.append("  InitialSize: ").append(this.dataSource.getInitialSize()).append(" (The initial number of connections that are created when the pool is started)\n");
125
            }
126
            if( this.dataSource.isPoolPreparedStatements() ) {
127
                builder.append("  PoolPreparedStatements: ").append(this.dataSource.isPoolPreparedStatements()).append("\n");
128
                builder.append("  MaxOpenPreparedStatements: ").append(this.dataSource.getMaxOpenPreparedStatements()).append(" (The maximum number of open statements that can be allocated from the statement pool at the same time, or non-positive for no limit)\n");
129
            }
130
            builder.append("  MaxActive: ").append(this.dataSource.getMaxActive()).append(" (The maximum number of active connections that can be allocated from this pool at the same time)\n");
131
            builder.append("  MaxIdle: ").append(this.dataSource.getMaxIdle()).append(" (The maximum number of connections that can remain idle in the pool)\n");
132
            builder.append("  NumActive:").append(this.dataSource.getNumActive()).append(" (the current number of active connections)\n");
133
            builder.append("  NumIdle:").append(this.dataSource.getNumIdle()).append(" (the current number of idle connections)\n");
134
            return builder.toString();
135
        }
136

  
137
        private BasicDataSource createDataSource() throws SQLException {
138
            if (!this.isRegistered()) {
139
                this.registerDriver();
140
            }
141
            PostgreSQLConnectionParameters params = connectionParameters;
142

  
143
            BasicDataSource ds = new BasicDataSource();
144
            ds.setMaxIdle(params.getMaxIdle());
145
            ds.setDriverClassName(params.getJDBCDriverClassName());
146
            if( params.getUseSSL() ) {
147
                String s = BooleanUtils.toStringTrueFalse(params.getUseSSL());
148
                ds.addConnectionProperty("ssl", s );
149
            }
150
            if( !StringUtils.isEmpty(params.getUser()) ) {
151
                ds.setUsername(params.getUser());
152
            }
153
            if( !StringUtils.isEmpty(params.getPassword()) ) {
154
                ds.setPassword(params.getPassword());
155
            }
156
            ds.setUrl(params.getUrl());
157

  
158
            ds.setMaxWait(60L * 1000);
159
            return ds;
160
        }
161

  
162
        private boolean isRegistered() {
163
            return needRegisterDriver;
164
        }
165

  
166
        public void registerDriver() throws SQLException {
167
            String className = this.connectionParameters.getJDBCDriverClassName();
168
            if (className == null) {
169
                return;
170
            }
171
            try {
172
                Class theClass = Class.forName(className);
173
                if (theClass == null) {
174
                    throw new JDBCDriverClassNotFoundException(PostgreSQLLibrary.NAME, className);
175
                }
176
            } catch (Exception e) {
177
                throw new SQLException("Can't register JDBC driver '" + className + "'.", e);
178
            }
179
            needRegisterDriver = false;
180
        }
181

  
182
    }
183

  
184
    private ConnectionProvider connectionProvider = null;
185
   
186
    public PostgreSQLHelper(JDBCConnectionParameters connectionParameters) {
187
        super(connectionParameters);
188
        this.srssolver = new SRSSolverBase(this);
189
    }
190

  
191
    @Override
192
    public Connection getConnection() throws AccessResourceException {
193
        try {
194
            if (this.connectionProvider == null) {
195
                this.connectionProvider = new ConnectionProvider(this.getConnectionParameters());
196
            }
197
            return this.connectionProvider.getConnection();
198
        } catch (SQLException ex) {
199
            throw new AccessResourceException(PostgreSQLLibrary.NAME, ex);
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff