Revision 1275

View differences:

tags/org.gvsig.postgresql-2.0.245/org.gvsig.postgresql.provider/src/main/resources/META-INF/services/org.gvsig.tools.library.Library
1
org.gvsig.postgresql.dal.PostgreSQLLibrary
tags/org.gvsig.postgresql-2.0.245/org.gvsig.postgresql.provider/src/main/resources/org/gvsig/postgresql/dal/PostgreSQLMetadata.xml
1
<?xml version="1.0"?>
2
<definitions>
3
  <version>1.0.0</version>
4
  <classes>
5
    <class name="PostgreSQL" namespace="Metadata">
6
      <extends>
7
      	<class name="JDBC2" namespace="Metadata"/>
8
      </extends>
9
      <description>Metadata of a PostgreSQL store</description>
10
      <fields>
11
      </fields>
12
    </class>
13

  
14
  </classes>
15
</definitions>  
tags/org.gvsig.postgresql-2.0.245/org.gvsig.postgresql.provider/src/main/resources/org/gvsig/postgresql/dal/PostgreSQLParameters.xml
1
<?xml version="1.0"?>
2
<definitions>
3
  <version>1.0.0</version>
4
  <classes>
5
    <class name="PostgreSQLResourceParameters">
6
      <extends>
7
        <class>JDBC2ResourceParameters</class>
8
      </extends>
9
      <description>_PostgreSQL_loading_parameters</description>
10
      <fields>
11
        <field name="JDBCDriverClass" type="string" mandatory="true"
12
          defaultValue="org.postgresql.Driver" group="Advanced">
13
          <description>JDBC Driver class</description>
14
        </field>
15
	<field name="port" type="integer" mandatory="false"
16
          defaultValue="5432" group="Connection">
17
          <description></description>
18
        </field>
19
        <field name="host" type="string" mandatory="false" 
20
            defaultValue="127.0.0.1" group="Connection">
21
          <description></description>
22
        </field>
23
        <field name="UseSSL" type="boolean" mandatory="false"
24
          defaultValue="false" group="Basic">
25
          <description>Use SSL connetion</description>
26
        </field>
27
        <field name="maxIdle" type="integer" mandatory="false"
28
          defaultValue="8" group="Advanced">
29
          <description>The maximum number of connections that can remail idle in the pool.</description>
30
        </field>
31
        <field name="networkTimeout" type="integer" mandatory="false"
32
          defaultValue="30000" group="Advanced">
33
          <description>The maximum period a connection or objects created from the connection will wait for the database to reply to any one request.</description>
34
        </field>
35
      </fields>
36
    </class>
37

  
38
    <class name="PostgreSQLStoreParameters">
39
      <extends>
40
        <class>JDBC2StoreParameters</class>
41
        <class>PostgreSQLResourceParameters</class>
42
      </extends>
43
      <fields/>
44
    </class>
45

  
46
    <class name="PostgreSQLNewStoreParameters">
47
      <extends>
48
        <class>JDBC2NewStoreParameters</class>
49
        <class>PostgreSQLResourceParameters</class>
50
      </extends>
51
      <fields/>
52
    </class>
53

  
54

  
55
    <class name="PostgreSQLServerExplorerParameters">
56
      <extends>
57
        <class>PostgreSQLResourceParameters</class>
58
        <class>JDBC2ServerExplorerParameters</class>
59
      </extends>
60
      <fields/>
61
    </class>
62

  
63

  
64
  </classes>
65
</definitions>  
tags/org.gvsig.postgresql-2.0.245/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.gvsig.fmap.dal.exception.ValidateDataParametersException;
28
import org.gvsig.fmap.dal.store.jdbc.JDBCServerExplorerParametersBase;
29

  
30
             
31
public class PostgreSQLServerExplorerParameters extends
32
        JDBCServerExplorerParametersBase 
33
    implements
34
        PostgreSQLConnectionParameters
35
    {
36
    
37
    private final PostgreSQLConnectionParametersHelper helper;
38

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

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

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

  
67
    @Override
68
    public int getMaxIdle() {
69
        return this.helper.getMaxIdle();
70
    }
71

  
72
    public void setUseSSL(boolean v) {
73
        this.helper.setUseSSL(v);
74
    }
75

  
76
    @Override
77
    public int getNetworkTimeout() {
78
        return this.helper.getNetworkTimeout();
79
    }
80
}
tags/org.gvsig.postgresql-2.0.245/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/PostgreSQLHelper.java
1

  
2
package org.gvsig.postgresql.dal;
3

  
4
import java.io.File;
5
import java.sql.Blob;
6
import java.sql.Clob;
7
import java.sql.Connection;
8
import java.sql.DriverManager;
9
import java.sql.ResultSet;
10
import java.sql.SQLException;
11
import java.util.HashMap;
12
import java.util.Map;
13
import org.apache.commons.dbcp2.BasicDataSource;
14
import org.apache.commons.io.IOUtils;
15
import org.apache.commons.lang3.ArrayUtils;
16
import org.apache.commons.lang3.BooleanUtils;
17
import org.apache.commons.lang3.StringUtils;
18
import org.gvsig.expressionevaluator.GeometryExpressionBuilderHelper.GeometrySupportType;
19
import org.gvsig.fmap.dal.DataTypes;
20
import org.gvsig.fmap.dal.exception.DataException;
21
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
22
import org.gvsig.fmap.dal.feature.spi.FeatureProvider;
23
import org.gvsig.fmap.dal.resource.exception.AccessResourceException;
24
import org.gvsig.fmap.dal.spi.DataTransactionServices;
25
import org.gvsig.fmap.dal.store.jdbc.JDBCConnectionParameters;
26
import org.gvsig.fmap.dal.store.jdbc.JDBCNewStoreParameters;
27
import org.gvsig.fmap.dal.store.jdbc.JDBCServerExplorerParameters;
28
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParameters;
29
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCCantFetchValueException;
30
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCDriverClassNotFoundException;
31
import org.gvsig.fmap.dal.store.jdbc2.JDBCConnection;
32
import org.gvsig.fmap.dal.store.jdbc2.JDBCUtils;
33
import org.gvsig.fmap.dal.store.jdbc2.OperationsFactory;
34
import org.gvsig.fmap.dal.store.jdbc2.spi.AbstractConnectionProvider;
35
import org.gvsig.fmap.dal.store.jdbc2.spi.ConnectionProvider;
36
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCConnectionBase;
37
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCHelperBase;
38
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCSQLBuilderBase;
39
import org.gvsig.fmap.dal.store.jdbc2.spi.SRSSolverBase;
40
import org.gvsig.fmap.dal.store.jdbc2.spi.SRSSolverDumb;
41
import org.gvsig.fmap.geom.Geometry;
42
import org.gvsig.postgresql.dal.operations.PostgreSQLOperationsFactory;
43
import org.gvsig.tools.dispose.Disposable;
44
import org.gvsig.tools.dispose.DisposeUtils;
45
import org.gvsig.tools.exception.BaseException;
46
import org.postgresql.util.DriverInfo;
47
import org.slf4j.Logger;
48
import org.slf4j.LoggerFactory;
49

  
50
@SuppressWarnings("UseSpecificCatch")
51
public class PostgreSQLHelper extends JDBCHelperBase {
52

  
53
    /* friend */ static final Logger LOGGER = LoggerFactory.getLogger(PostgreSQLHelper.class);
54

  
55
    public static final String POSTGRESQL_JDBC_DRIVER = "org.postgresql.Driver";
56
    
57
    public static final boolean USE_CONNECTIONS_POOL = true;
58
    
59
    public static String getConnectionURL(PostgreSQLConnectionParameters params) {
60
        return getConnectionURL(
61
            params.getHost(),
62
            params.getPort(),
63
            params.getDBName()
64
        );
65
    }
66
    
67
    public static String getConnectionURL(String host, Integer port, String db) {
68
        if( StringUtils.isEmpty(host) ) {
69
            throw new IllegalArgumentException("Parameter 'host' can't be null.");
70
        }
71
        String connectionURL = "jdbc:postgresql://" + host;
72
        if (port != null) {
73
            connectionURL = connectionURL + ":" + port;
74
        }
75
        connectionURL = connectionURL + "/" + db;
76
        LOGGER.debug("connectionURL: {}", connectionURL);
77
        return connectionURL;
78
    }
79

  
80
    private static class PostgreSQLConnectionProvider extends AbstractConnectionProvider implements Disposable, ConnectionProvider {
81

  
82
        private static boolean needRegisterDriver = true;
83

  
84
        private BasicDataSource dataSource = null;
85

  
86
        private PostgreSQLConnectionParameters connectionParameters;
87

  
88
        public PostgreSQLConnectionProvider(PostgreSQLConnectionParameters connectionParameters) {
89
            this.connectionParameters = connectionParameters;
90
            DisposeUtils.bind(this);
91
        }
92

  
93
        @Override
94
        public Connection getConnection() throws SQLException {
95
            
96
            Connection conn;
97
            if( USE_CONNECTIONS_POOL ) {
98
                if (this.dataSource == null) {
99
                    this.dataSource = this.createDataSource();               
100
                }
101
                if( LOGGER.isDebugEnabled() ) {
102
                    LOGGER.debug("getConnection:\n" + getStatusInformation());
103
                }
104
                try {
105
                    conn = this.dataSource.getConnection();
106
                } catch(Throwable ex) {
107
                    LOGGER.debug("Error getting connection from pool.",ex);
108
                    throw ex;
109
                }
110
                try {
111
                    conn.setNetworkTimeout(null, this.connectionParameters.getNetworkTimeout());
112
                } catch(Throwable ex) {
113
                    LOGGER.warn("Error setting the network timeout.",ex);
114
                }
115
                if( LOGGER.isDebugEnabled() ) {
116
                    LOGGER.debug("Created connection: {}\n  NumActive: {}\n  NumIdle: {}",
117
                        new Object[] {
118
                            conn.hashCode(), 
119
                            this.dataSource.getNumActive(),
120
                            this.dataSource.getNumIdle()
121
                        }
122
                    );
123
                }
124
            } else {
125
                try {
126
                    conn = DriverManager.getConnection(
127
                        connectionParameters.getUrl(), 
128
                        connectionParameters.getUser(), 
129
                        connectionParameters.getPassword()
130
                    );
131
                } catch(Throwable th) {
132
                    throw th;
133
                }
134
                if( LOGGER.isDebugEnabled() ) {
135
                    LOGGER.debug("Created not polled connection: {}",
136
                        new Object[] {
137
                            conn.hashCode()
138
                        }
139
                    );
140
                }
141
            }
142
            LOGGER.debug("PostgreSQL JDBC Driver: "+DriverInfo.DRIVER_VERSION);
143
            return conn;
144
        }
145
        
146
        public String getStatusInformation() {
147
            StringBuilder builder = new StringBuilder();
148
            if( this.dataSource==null ) {
149
                builder.append("Not poolled connection:\n");
150
                builder.append("  Connection URL: '").append(this.connectionParameters.getUrl()).append("'\n");
151
            } else {
152
                builder.append("BasicDataSource pool status:\n");
153
                builder.append("  Connection URL: '").append(this.dataSource.getUrl()).append("'\n");
154
                if( this.dataSource.getInitialSize()>0 ) {
155
                    builder.append("  InitialSize: ").append(this.dataSource.getInitialSize()).append(" (The initial number of connections that are created when the pool is started)\n");
156
                }
157
                if( this.dataSource.isPoolPreparedStatements() ) {
158
                    builder.append("  PoolPreparedStatements: ").append(this.dataSource.isPoolPreparedStatements()).append("\n");
159
                    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");
160
                }
161
                builder.append("  MaxTotal: ").append(this.dataSource.getMaxTotal()).append(" (The maximum number of active connections that can be allocated from this pool at the same time)\n");
162
                builder.append("  MaxIdle: ").append(this.dataSource.getMaxIdle()).append(" (The maximum number of connections that can remain idle in the pool)\n");
163
                builder.append("  NumActive:").append(this.dataSource.getNumActive()).append(" (the current number of active connections)\n");
164
                builder.append("  NumIdle:").append(this.dataSource.getNumIdle()).append(" (the current number of idle connections)\n");
165
            }
166
            return builder.toString();
167
        }
168

  
169
        private BasicDataSource createDataSource() throws SQLException {
170
            if (!this.isRegistered()) {
171
                this.registerDriver();
172
            }
173
            PostgreSQLConnectionParameters params = connectionParameters;
174

  
175
            BasicDataSource ds = new BasicDataSource();
176
            ds.setMaxIdle(params.getMaxIdle());
177
            ds.setDriverClassName(params.getJDBCDriverClassName());
178
            if( params.getUseSSL() ) {
179
                String s = BooleanUtils.toStringTrueFalse(params.getUseSSL());
180
                ds.addConnectionProperty("ssl", s );
181
            }
182
            if( !StringUtils.isEmpty(params.getUser()) ) {
183
                ds.setUsername(params.getUser());
184
            }
185
            if( !StringUtils.isEmpty(params.getPassword()) ) {
186
                ds.setPassword(params.getPassword());
187
            }
188
            ds.setUrl(params.getUrl());
189
            
190
            ds.setMinEvictableIdleTimeMillis(20*1000);
191
            ds.setTimeBetweenEvictionRunsMillis(20*1000);
192
            ds.setMinIdle(0);
193
            
194
            ds.setMaxWaitMillis(60L * 1000);
195
            return ds;
196
        }
197

  
198
        private boolean isRegistered() {
199
            return needRegisterDriver;
200
        }
201

  
202
        @Override
203
        public void registerDriver() throws SQLException {
204
            String className = this.connectionParameters.getJDBCDriverClassName();
205
            if (className == null) {
206
                return;
207
            }
208
            try {
209
                Class theClass = Class.forName(className);
210
                if (theClass == null) {
211
                    throw new JDBCDriverClassNotFoundException(PostgreSQLLibrary.NAME, className);
212
                }
213
            } catch (Exception e) {
214
                throw new SQLException("Can't register JDBC driver '" + className + "'.", e);
215
            }
216
            needRegisterDriver = false;
217
        }
218

  
219
        @Override
220
        public void dispose() {
221
            if(!DisposeUtils.release(this)){
222
                return;
223
            }
224
            if( this.dataSource!=null ) {
225
                try {
226
                    this.dataSource.close();
227
                } catch (SQLException ex) {
228
                    LOGGER.warn("Can't close BasicDataSource", ex);
229
                }
230
                this.dataSource = null;
231
            }
232
            this.connectionParameters = null;
233
        }
234
        
235
        @Override
236
        public boolean isDisposed() {
237
            return this.dataSource == null;
238
        }
239

  
240
        @Override
241
        public String getStatus() {
242
            if( dataSource==null ) {
243
                return "Not polled";
244
            }
245
            StringBuilder builder = new StringBuilder();
246
            builder.append("Pool: ");
247
            builder.append(JDBCUtils.getHexId(dataSource));
248
            builder.append(" Actives: ");
249
            builder.append(dataSource.getNumActive());
250
            builder.append("/");
251
            builder.append(dataSource.getMaxTotal()); //.getMaxActive());
252
            builder.append(" idle: ");
253
            builder.append(dataSource.getNumIdle());
254
            builder.append("/");
255
            builder.append(dataSource.getMinIdle());
256
            builder.append(":");
257
            builder.append(dataSource.getMaxIdle());
258
            return builder.toString();
259
        }
260

  
261
    }
262

  
263
    static private Map<String,ConnectionProvider> connectionProviders = new HashMap();
264
    private ConnectionProvider connectionProvider = null;
265
   
266
    /**
267
     * Constructor for use only for testing purposes.
268
     * 
269
     * @param connectionParameters
270
     * @param connectionProvider
271
     */
272
    public PostgreSQLHelper(PostgreSQLConnectionParameters connectionParameters, ConnectionProvider connectionProvider) { 
273
        super(connectionParameters);
274
        this.srssolver = new SRSSolverDumb(this);
275
        this.connectionProvider = connectionProvider;
276
    }
277
  
278

  
279

  
280
    public PostgreSQLHelper(JDBCConnectionParameters connectionParameters) {
281
        super(connectionParameters);
282
        this.srssolver = new SRSSolverBase(this);
283
    }
284

  
285
    @Override
286
    protected void doDispose() throws BaseException {
287
        if( this.connectionProvider!=null ) {
288
            this.connectionProvider.dispose();
289
            this.connectionProvider = null;
290
        }
291
        super.doDispose(); 
292
    }
293
    
294
    private ConnectionProvider getConnectionProvider(JDBCConnectionParameters connectionParameters) {
295
        if (this.connectionProvider == null) {
296
            if (this.getConnectionParameters() == null) {
297
                return null;
298
            }
299
            String key = connectionParameters.getUrl()+";user:"+connectionParameters.getUser();
300
            this.connectionProvider = connectionProviders.get(key);
301
            if (this.connectionProvider == null || ((PostgreSQLConnectionProvider) this.connectionProvider).isDisposed()) {
302
                this.connectionProvider = new PostgreSQLConnectionProvider(this.getConnectionParameters());
303
                connectionProviders.put(key, this.connectionProvider);
304
            } else {
305
                DisposeUtils.bind(this.connectionProvider);
306
            }
307
        }
308
        return this.connectionProvider;
309
    }
310

  
311
    @Override
312
    public synchronized JDBCConnection  getConnection() throws AccessResourceException {
313
        try {
314
            PostgreSQLConnectionParameters connectionParameters = this.getConnectionParameters();
315
            JDBCConnection conn = (JDBCConnection) DataTransactionServices.getConnection(transaction, connectionParameters.getUrl());
316
            if( conn != null ) {
317
                return conn;
318
            }
319
            JDBCConnection connection = new JDBCConnectionBase(
320
                    this.transaction, 
321
                    this.getConnectionProvider(connectionParameters).getConnection(), 
322
                    connectionParameters.getUrl()
323
            );
324
            return connection;
325
        } catch (SQLException ex) {
326
            throw new AccessResourceException(PostgreSQLLibrary.NAME, ex);
327
        }
328
    }
329
    
330
    @Override
331
    public PostgreSQLConnectionParameters getConnectionParameters() {
332
        return (PostgreSQLConnectionParameters) super.getConnectionParameters();
333
    }
334
    
335
    @Override
336
    public String getConnectionURL() {
337
        return getConnectionURL(this.getConnectionParameters());
338
    }
339

  
340
    @Override
341
    protected String getResourceType() {
342
        return PostgreSQLLibrary.NAME;
343
    }
344

  
345
    @Override
346
    public String getProviderName() {
347
        return PostgreSQLLibrary.NAME;
348
    }
349

  
350
    @Override
351
    public JDBCSQLBuilderBase createSQLBuilder() {
352
        return new PostgreSQLBuilder(this);
353
    }
354
    
355
    @Override
356
    public OperationsFactory getOperations() {
357
        if (this.operationsFactory == null) {
358
            this.operationsFactory = new PostgreSQLOperationsFactory(this);
359
        }
360
        return operationsFactory;
361
    }
362

  
363
    @Override
364
    public GeometrySupportType getGeometrySupportType() {
365
        return GeometrySupportType.EWKB;
366
    }
367

  
368
    @Override
369
    public boolean hasSpatialFunctions() {
370
        return true;
371
    }
372

  
373
    @Override
374
    public boolean canWriteGeometry(int geometryType, int geometrySubtype) {
375
        return true;
376
    }
377

  
378
    @Override
379
    public String getQuoteForIdentifiers() {
380
        return "\"";
381
    }
382

  
383
    @Override
384
    public boolean allowAutomaticValues() {
385
        return true;
386
    }
387

  
388
    @Override
389
    public boolean supportOffsetInSelect() {
390
        return true;
391
    }
392

  
393
    @Override
394
    public String getQuoteForStrings() {
395
        return "'";
396
    }
397
    
398
    @Override
399
    public JDBCNewStoreParameters createNewStoreParameters() {
400
        return new PostgreSQLNewStoreParameters();
401
    }
402

  
403
    @Override
404
    public JDBCStoreParameters createOpenStoreParameters() {
405
        return new PostgreSQLStoreParameters();
406
    }
407

  
408
    @Override
409
    public JDBCServerExplorerParameters createServerExplorerParameters() {
410
        return new PostgreSQLServerExplorerParameters();
411
    }
412

  
413
    @Override
414
    public void fetchFeature(FeatureProvider feature, ResultSet rs, FeatureAttributeDescriptor[] columns, String[] extraValueNames) throws DataException {
415
        Object value;
416
        try {
417
            int rsIndex = 1;
418
            for (FeatureAttributeDescriptor column : columns) {
419
                switch (column.getType()) {
420
                    case DataTypes.GEOMETRY:
421
                        value = this.getGeometryFromColumn(rs, rsIndex++);
422
                        if (value != null){
423
                            ((Geometry)value).setProjection(column.getSRS());
424
                        }
425
                        break;
426
                    case DataTypes.BYTEARRAY:
427
                        value = rs.getBytes(rsIndex++);
428
                        break;
429
                    default:
430
                        value = rs.getObject(rsIndex++);
431
                        if (value instanceof Blob) {
432
                            Blob blob = (Blob) value;
433
                            value = blob.getBytes(1, (int) blob.length());
434
                            blob.free();
435
                        } else if (value instanceof Clob) {
436
                            Clob clob = (Clob) value;
437
                            value = new String(IOUtils.toCharArray(clob.getCharacterStream()));
438
                            clob.free();
439
                        }
440
                }
441
                feature.set(column.getIndex(), value);
442
            }
443
            if (ArrayUtils.isNotEmpty(extraValueNames)) {
444
                feature.setExtraValueNames(extraValueNames);
445
                for (int index = 0; index < extraValueNames.length; index++) {
446
                    value = rs.getObject(rsIndex++);
447
                    if (value instanceof Blob) {
448
                        Blob blob = (Blob) value;
449
                        value = blob.getBytes(0, (int) blob.length());
450
                        blob.free();
451
                    }
452
                    feature.setExtraValue(index, value);
453
                }
454
            }
455
        } catch (Exception ex) {
456
            throw new JDBCCantFetchValueException(ex);
457
        }
458
    }
459

  
460
}
tags/org.gvsig.postgresql-2.0.245/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.JDBCServerExplorerParametersBase;
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((JDBCServerExplorerParametersBase) parameters, 
51
                providerServices
52
        );
53
        return server;
54
    }
55
        
56

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

  
3
import java.util.Arrays;
4
import java.util.Collections;
5
import java.util.HashSet;
6
import java.util.Set;
7
import java.util.function.Function;
8
import org.gvsig.fmap.dal.DataParameters;
9
import static org.gvsig.fmap.dal.DataStoreProviderFactory.NO;
10
import static org.gvsig.fmap.dal.DataStoreProviderFactory.UNKNOWN;
11
import static org.gvsig.fmap.dal.DataStoreProviderFactory.YES;
12
import org.gvsig.fmap.dal.exception.InitializeException;
13
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
14
import org.gvsig.fmap.dal.store.jdbc.JDBCConnectionParameters;
15
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParametersBase;
16
import org.gvsig.fmap.dal.store.jdbc2.JDBCHelper;
17
import org.gvsig.fmap.dal.store.jdbc2.JDBCStoreProvider;
18
import org.gvsig.fmap.dal.store.jdbc2.impl.JDBCStoreProviderFactoryBase;
19

  
20
public class PostgreSQLStoreProviderFactory extends JDBCStoreProviderFactoryBase {
21

  
22
    private static final Set<String> ALLOWED_FUNCTIONS = new HashSet<>(
23
            Arrays.asList(new String[]{
24
        "COUNT",
25
        "SUM",
26
        "MIN",
27
        "MAX"
28
    }
29
            )
30
    );
31
    private static final Set<String> DENIED_FUNCTIONS = Collections.EMPTY_SET;
32

  
33
    public PostgreSQLStoreProviderFactory() {
34
        super(
35
                PostgreSQLLibrary.NAME,
36
                "PostgreSQL store"
37
        );
38
    }
39

  
40
    @Override
41
    public JDBCStoreProvider createProvider(
42
            DataParameters parameters,
43
            DataStoreProviderServices providerServices
44
    ) throws InitializeException {
45
        JDBCHelper helper = new PostgreSQLHelper((JDBCConnectionParameters) parameters);
46
        JDBCStoreProvider provider = helper.createProvider((JDBCStoreParametersBase) parameters,
47
                providerServices
48
        );
49
        return provider;
50
    }
51

  
52
    @Override
53
    public JDBCStoreParametersBase createParameters() {
54
        JDBCStoreParametersBase params = new PostgreSQLStoreParameters();
55
        return params;
56
    }
57

  
58
    @Override
59
    public Function<String, Integer> allowFunction() {
60
        return (Function<String, Integer>) (String name) -> {
61
            if (ALLOWED_FUNCTIONS.contains(name)) {
62
                return YES;
63
            }
64
            if (DENIED_FUNCTIONS.contains(name)) {
65
                return NO;
66
            }
67
            return UNKNOWN;
68
        };
69
    }
70

  
71
    @Override
72
    public int allowGroupBy() {
73
        return YES;
74
    }
75

  
76
    @Override
77
    public int hasVectorialSupport() {
78
        return YES;
79
    }
80

  
81
    @Override
82
    public int hasRasterSupport() {
83
        return NO;
84
    }
85

  
86
    @Override
87
    public int hasTabularSupport() {
88
        return YES;
89
    }
90

  
91
    @Override
92
    public int hasSQLSupport() {
93
        return YES;
94
    }
95
}
tags/org.gvsig.postgresql-2.0.245/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.ResultSet;
5
import java.sql.ResultSetMetaData;
6
import java.sql.SQLException;
7
import java.sql.Statement;
8
import java.util.HashMap;
9
import java.util.List;
10
import java.util.Map;
11
import org.apache.commons.lang3.StringUtils;
12
import org.cresques.cts.IProjection;
13
import org.gvsig.expressionevaluator.ExpressionBuilder;
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.JDBCConnection;
19
import org.gvsig.fmap.dal.store.jdbc2.JDBCHelper;
20
import org.gvsig.fmap.dal.store.jdbc2.JDBCUtils;
21
import org.gvsig.fmap.dal.store.jdbc2.OperationsFactory.TableReference;
22
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCSQLBuilderBase;
23
import org.gvsig.fmap.dal.store.jdbc2.spi.SRSSolver;
24
import org.gvsig.fmap.dal.store.jdbc2.spi.operations.FetchFeatureTypeOperation;
25
import org.gvsig.fmap.geom.Geometry;
26
import org.gvsig.fmap.geom.GeometryLocator;
27
import org.gvsig.fmap.geom.GeometryManager;
28
import org.gvsig.fmap.geom.type.GeometryType;
29
import org.gvsig.postgresql.dal.PostgreSQLBuilder;
30

  
31
@SuppressWarnings("UseSpecificCatch")
32
public class PostgreSQLFetchFeatureTypeOperation extends FetchFeatureTypeOperation {
33

  
34
    private static Map<String,GeometryType>databaseGeometryTypes = null;
35
    
36
    public PostgreSQLFetchFeatureTypeOperation(
37
            JDBCHelper helper
38
        ) {
39
        super(helper);
40
    }
41

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

  
68
    @Override
69
    public void fetch(JDBCConnection conn) throws DataException {
70
        super.fetch(conn);
71
    }
72

  
73
    @Override
74
    protected int getDataTypeFromMetadata(
75
            ResultSetMetaData rsMetadata,
76
            int colIndex
77
        ) throws SQLException {
78

  
79
        return super.getDataTypeFromMetadata(rsMetadata, colIndex);
80
    }
81
    
82
    @Override
83
    public String getSQLToRetrievePrimaryKeysFromInformationSchema() throws SQLException {
84
        PostgreSQLBuilder sqlbuilder = (PostgreSQLBuilder) this.createSQLBuilder();
85
        ExpressionBuilder expbuilder = sqlbuilder.expression();
86
        
87
        String column_COLUMN_NAME = "column_name";
88
        String column_CONSTRAINT_TYPE = "constraint_type";
89
        
90
        if( sqlbuilder.getDatabaseVersion().getMajor()<10 ) {
91
            column_COLUMN_NAME = "COLUMN_NAME";
92
            column_CONSTRAINT_TYPE = "CONSTRAINT_TYPE";
93
        }
94
        sqlbuilder.select().column().name(column_COLUMN_NAME);
95
        sqlbuilder.select().column().name(column_CONSTRAINT_TYPE);
96
        sqlbuilder.select().from().custom(
97
                "INFORMATION_SCHEMA.table_constraints t_cons "
98
                + "inner join INFORMATION_SCHEMA.key_column_usage c on "
99
                + "c.constraint_catalog = t_cons.constraint_catalog and "
100
                + "c.table_schema = t_cons.table_schema and "
101
                + "c.table_name = t_cons.table_name and "
102
                + "c.constraint_name = t_cons.constraint_name "
103
        );
104
        sqlbuilder.select().where().set(
105
                expbuilder.like(
106
                        expbuilder.custom("c.TABLE_NAME"), 
107
                        expbuilder.constant(table.getTable())
108
                )
109
        );
110
        if (table.hasSchema()) {
111
            sqlbuilder.select().where().and(
112
                    expbuilder.like(
113
                            expbuilder.custom("c.TABLE_SCHEMA"),
114
                            expbuilder.constant(table.getSchema())
115
                    )
116
            );
117
        }
118
//        if (catalog != null) {
119
//            sqlbuilder.select().where().and(
120
//                    expbuilder.like(
121
//                            expbuilder.custom("c.CONSTRAINT_CATALOG"),
122
//                            expbuilder.constant(catalog)
123
//                    )
124
//            );
125
//        }
126
        sqlbuilder.select().where().and(
127
                expbuilder.eq(
128
                        expbuilder.column(column_CONSTRAINT_TYPE),
129
                        expbuilder.constant("PRIMARY KEY")
130
                )
131
        );
132
        return sqlbuilder.toString();
133
    }
134
        
135
    @Override
136
    protected void fetchGeometryTypeAndSRS(
137
            EditableFeatureAttributeDescriptor attr,
138
            ResultSetMetaData rsMetadata,
139
            int colIndex
140
        ) {
141
        if( attr.getType()!=DataTypes.GEOMETRY ) {
142
            return;
143
        }
144
        try {
145
            JDBCSQLBuilderBase sqlbuilder = this.createSQLBuilder();
146
            ExpressionBuilder expbuilder = sqlbuilder.expression();
147
            
148
            sqlbuilder.select().column().name("f_table_catalog");
149
            sqlbuilder.select().column().name("f_table_schema");
150
            sqlbuilder.select().column().name("f_table_name");
151
            sqlbuilder.select().column().name("f_geometry_column");
152
            sqlbuilder.select().column().name("coord_dimension");
153
            sqlbuilder.select().column().name("srid");
154
            sqlbuilder.select().column().name("type");
155
            sqlbuilder.select().where().set(
156
                    expbuilder.eq(
157
                            expbuilder.column("f_table_name"),
158
                            expbuilder.constant(this.getTable().getTable())
159
                    )
160
            );                
161
            sqlbuilder.select().where().and(
162
                    expbuilder.eq(
163
                            expbuilder.column("f_geometry_column"),
164
                            expbuilder.constant(attr.getName())
165
                    )
166
            );         
167
            sqlbuilder.select().from().table().name("geometry_columns");
168
            Statement st = null;
169
            ResultSet rs = null;
170
            
171
            Integer srsid = null;
172
            String geometryTypeName = null;
173
            try {
174
                st = this.getConnection().createStatement();
175
                rs = JDBCUtils.executeQuery(st, sqlbuilder.toString());
176
                if (rs.next()) {
177
                    srsid = rs.getInt("srid");
178
                    geometryTypeName = rs.getString("type");
179
                }
180
            } finally {
181
                JDBCUtils.closeQuietly(rs);
182
                JDBCUtils.closeQuietly(st);
183
            }
184
            if( !StringUtils.isEmpty(geometryTypeName) ) {
185
                GeometryType gt = getGeometryTypeFromDatabaseTypeName(geometryTypeName);
186
                attr.setGeometryType(gt);
187
            }
188
            if( srsid!=null ) {
189
                SRSSolver srssolver = this.helper.getSRSSolver();
190
                attr.setSRS(srssolver.getProjection(this.getConnection(),srsid));
191
            }
192
        } catch (Exception ex) {
193
            LOGGER.debug("Can't get geometry type and srs from column '"+attr.getName()+"'.",ex);
194
        }
195
    }
196

  
197
    private GeometryType getGeometryTypeFromDatabaseTypeName(String typeName) {
198
        if( databaseGeometryTypes==null ) {
199
            GeometryManager manager = GeometryLocator.getGeometryManager();
200
            databaseGeometryTypes = new HashMap<>();
201
            databaseGeometryTypes.put("POINT", getGT(manager, Geometry.TYPES.POINT,Geometry.SUBTYPES.GEOM2D));
202
            databaseGeometryTypes.put("POINTZ", getGT(manager, Geometry.TYPES.POINT,Geometry.SUBTYPES.GEOM3D));
203
            databaseGeometryTypes.put("POINTM", getGT(manager, Geometry.TYPES.POINT,Geometry.SUBTYPES.GEOM2DM));
204
            databaseGeometryTypes.put("POINTZM", getGT(manager, Geometry.TYPES.POINT,Geometry.SUBTYPES.GEOM3DM));
205
            
206
            databaseGeometryTypes.put("LINESTRING", getGT(manager, Geometry.TYPES.LINE,Geometry.SUBTYPES.GEOM2D));
207
            databaseGeometryTypes.put("LINESTRINGZ", getGT(manager, Geometry.TYPES.LINE,Geometry.SUBTYPES.GEOM3D));
208
            databaseGeometryTypes.put("LINESTRINGM", getGT(manager, Geometry.TYPES.LINE,Geometry.SUBTYPES.GEOM2DM));
209
            databaseGeometryTypes.put("LINESTRINGZM", getGT(manager, Geometry.TYPES.LINE,Geometry.SUBTYPES.GEOM3DM));
210
            
211
            databaseGeometryTypes.put("POLYGON", getGT(manager, Geometry.TYPES.POLYGON,Geometry.SUBTYPES.GEOM2D));
212
            databaseGeometryTypes.put("POLYGONZ", getGT(manager, Geometry.TYPES.POLYGON,Geometry.SUBTYPES.GEOM3D));
213
            databaseGeometryTypes.put("POLYGONM", getGT(manager, Geometry.TYPES.POLYGON,Geometry.SUBTYPES.GEOM2DM));
214
            databaseGeometryTypes.put("POLYGONZM", getGT(manager, Geometry.TYPES.POLYGON,Geometry.SUBTYPES.GEOM3DM));
215

  
216
            databaseGeometryTypes.put("MULTIPOINT", getGT(manager, Geometry.TYPES.MULTIPOINT,Geometry.SUBTYPES.GEOM2D));
217
            databaseGeometryTypes.put("MULTIPOINTZ", getGT(manager, Geometry.TYPES.MULTIPOINT,Geometry.SUBTYPES.GEOM3D));
218
            databaseGeometryTypes.put("MULTIPOINTM", getGT(manager, Geometry.TYPES.MULTIPOINT,Geometry.SUBTYPES.GEOM2DM));
219
            databaseGeometryTypes.put("MULTIPOINTZM", getGT(manager, Geometry.TYPES.MULTIPOINT,Geometry.SUBTYPES.GEOM3DM));
220

  
221
            databaseGeometryTypes.put("MULTILINESTRING", getGT(manager, Geometry.TYPES.MULTILINE,Geometry.SUBTYPES.GEOM2D));
222
            databaseGeometryTypes.put("MULTILINESTRINGZ", getGT(manager, Geometry.TYPES.MULTILINE,Geometry.SUBTYPES.GEOM3D));
223
            databaseGeometryTypes.put("MULTILINESTRINGM", getGT(manager, Geometry.TYPES.MULTILINE,Geometry.SUBTYPES.GEOM2DM));
224
            databaseGeometryTypes.put("MULTILINESTRINGZM", getGT(manager, Geometry.TYPES.MULTILINE,Geometry.SUBTYPES.GEOM3DM));
225

  
226
            databaseGeometryTypes.put("MULTIPOLYGON", getGT(manager, Geometry.TYPES.MULTIPOLYGON,Geometry.SUBTYPES.GEOM2D));
227
            databaseGeometryTypes.put("MULTIPOLYGONZ", getGT(manager, Geometry.TYPES.MULTIPOLYGON,Geometry.SUBTYPES.GEOM3D));
228
            databaseGeometryTypes.put("MULTIPOLYGONM", getGT(manager, Geometry.TYPES.MULTIPOLYGON,Geometry.SUBTYPES.GEOM2DM));
229
            databaseGeometryTypes.put("MULTIPOLYGONZM", getGT(manager, Geometry.TYPES.MULTIPOLYGON,Geometry.SUBTYPES.GEOM3DM));
230

  
231
            databaseGeometryTypes.put("GEOMETRY", getGT(manager, Geometry.TYPES.GEOMETRY,Geometry.SUBTYPES.GEOM2D));
232
            databaseGeometryTypes.put("GEOMETRYZ", getGT(manager, Geometry.TYPES.GEOMETRY,Geometry.SUBTYPES.GEOM3D));
233
            databaseGeometryTypes.put("GEOMETRYM", getGT(manager, Geometry.TYPES.GEOMETRY,Geometry.SUBTYPES.GEOM2DM));
234
            databaseGeometryTypes.put("GEOMETRYZM", getGT(manager, Geometry.TYPES.GEOMETRY,Geometry.SUBTYPES.GEOM3DM));
235
        }
236
        return databaseGeometryTypes.get(typeName);
237
    }
238
    
239
}
tags/org.gvsig.postgresql-2.0.245/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.List;
5
import org.cresques.cts.IProjection;
6
import org.gvsig.fmap.dal.feature.EditableFeatureType;
7
import org.gvsig.fmap.dal.store.jdbc2.JDBCHelper;
8
import org.gvsig.fmap.dal.store.jdbc2.spi.operations.FetchFeatureTypeOperation;
9
import org.gvsig.fmap.dal.store.jdbc2.spi.operations.OperationsFactoryBase;
10

  
11

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

  
18
    @Override
19
    public FetchFeatureTypeOperation createFetchFeatureType(EditableFeatureType type, TableReference table, List<String> primaryKeys, String defaultGeometryField, IProjection crs) {
20
        return new PostgreSQLFetchFeatureTypeOperation(
21
                helper, type, table, primaryKeys, 
22
                defaultGeometryField, crs, -1, -1
23
        );
24
    }  
25

  
26
    @Override
27
    public FetchFeatureTypeOperation createFetchFeatureType(EditableFeatureType type, TableReference table, List<String> primaryKeys, String defaultGeometryField, IProjection crs, int geometryType, int geometrySubtype) {
28
        return new PostgreSQLFetchFeatureTypeOperation(
29
                helper, type, table, primaryKeys, 
30
                defaultGeometryField, crs, geometryType, geometrySubtype
31
        );
32
    }  
33

  
34
}
tags/org.gvsig.postgresql-2.0.245/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/PostgreSQLStoreParameters.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.OpenDataStoreParameters;
25
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
26
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParametersBase;
27

  
28
public class PostgreSQLStoreParameters extends JDBCStoreParametersBase implements PostgreSQLConnectionParameters, OpenDataStoreParameters {
29

  
30
    private final PostgreSQLConnectionParametersHelper helper;
31
    
32
    public PostgreSQLStoreParameters() {
33
        super(
34
                PostgreSQLLibrary.NAME + "StoreParameters",
35
                PostgreSQLLibrary.NAME
36
        );
37
        this.helper = new PostgreSQLConnectionParametersHelper(this);
38
    }
39

  
40
    @Override
41
    public String getUrl() {
42
        return this.helper.getUrl();
43
    }
44
    
45
    @Override
46
    public void validate() throws ValidateDataParametersException {
47
        this.helper.validate();
48
        super.validate();
49
    }
50

  
51
    @Override
52
    public boolean getUseSSL() {
53
        return this.helper.getUseSSL();
54
    }
55

  
56
    @Override
57
    public int getMaxIdle() {
58
        return this.helper.getMaxIdle();
59
    }
60

  
61
    public void setUseSSL(boolean v) {
62
        this.helper.setUseSSL(v);
63
    }
64

  
65
    @Override
66
    public int getNetworkTimeout() {
67
        return this.helper.getNetworkTimeout();
68
    }
69
    
70
}
tags/org.gvsig.postgresql-2.0.245/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/PostgreSQLConnectionParameters.java
1
package org.gvsig.postgresql.dal;
2

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

  
6
public interface PostgreSQLConnectionParameters extends JDBCConnectionParameters, DBParameters {
7

  
8
    public static final String USESSL_PARAMTER_NAME = "UseSSL";
9
    public static final String MAXIDLE_PARAMTER_NAME = "maxIdle";
10
    public static final String NETWORK_TIMEOUT = "networkTimeout";
11

  
12
    public boolean getUseSSL();
13

  
14
    public int getMaxIdle();
15

  
16
    public int getNetworkTimeout();
17
}
tags/org.gvsig.postgresql-2.0.245/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.isBlank(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
    public int getMaxIdle() {
56
        return (int) this.getDynValue(PostgreSQLConnectionParameters.MAXIDLE_PARAMTER_NAME);
57
    }
58

  
59
    public boolean getUseSSL() {
60
        return (boolean) this.getDynValue(PostgreSQLConnectionParameters.USESSL_PARAMTER_NAME);
61
    }
62

  
63
    public void setUseSSL(boolean v) {
64
        this.setDynValue(PostgreSQLConnectionParameters.USESSL_PARAMTER_NAME, v);
65
    }
66

  
67
    public int getNetworkTimeout() {
68
        return (int) this.getDynValue(PostgreSQLConnectionParameters.NETWORK_TIMEOUT);
69
    }
70

  
71
}
tags/org.gvsig.postgresql-2.0.245/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.json.Json;
11
import org.gvsig.metadata.exceptions.MetadataException;
12
import org.gvsig.tools.library.AbstractLibrary;
13
import org.gvsig.tools.library.LibraryException;
14

  
15

  
16
public class PostgreSQLLibrary extends AbstractLibrary {
17

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

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

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

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

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

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

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

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

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

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

  
103
}
tags/org.gvsig.postgresql-2.0.245/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.DatabaseMetaData;
28
import java.text.MessageFormat;
29
import java.util.ArrayList;
30
import java.util.List;
31
import org.apache.commons.lang3.StringUtils;
32
import org.gvsig.expressionevaluator.Formatter;
33
import org.gvsig.fmap.dal.store.jdbc2.JDBCConnection;
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
@SuppressWarnings("UseSpecificCatch")
39
public class PostgreSQLBuilder extends JDBCSQLBuilderBase {
40

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

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

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

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

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

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

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

  
104
    }
105
    
106
    public class PostgreSQLUpdateTableStatisticsBuilderBase extends UpdateTableStatisticsBuilderBase {
107
        @Override
108
        public List<String> toStrings() {
109
            List<String> sqls = new ArrayList<>();
110
            
111
            if( !StringUtils.isBlank(STMT_UPDATE_TABLE_STATISTICS_table) ) {
112
                // In postGIS, UpdateLayerStatistics function, don't allow to 
113
                // use the database name in the table name.
114
                String name = as_identifier(this.table.getName());
115
                if( table.has_schema()) {
116
                    name = as_identifier(this.table.getSchema()) + "." + name;
117
                }
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff