Revision 962

View differences:

tags/org.gvsig.postgresql-2.0.187/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.187/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.187/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.187/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/FakePostgreSQLConnectionParameters.java
1
/*
2
 * To change this license header, choose License Headers in Project Properties.
3
 * To change this template file, choose Tools | Templates
4
 * and open the template in the editor.
5
 */
6
package org.gvsig.postgresql.dal;
7

  
8
import org.gvsig.fmap.dal.store.jdbc2.spi.FakeConnectionParameters;
9

  
10
/**
11
 *
12
 * @author fdiaz
13
 */
14
public class FakePostgreSQLConnectionParameters extends FakeConnectionParameters implements PostgreSQLConnectionParameters {
15

  
16
    @Override
17
    public boolean getUseSSL() {
18
        return false;
19
    }
20

  
21
    @Override
22
    public int getMaxIdle() {
23
        return 8;
24
    }
25

  
26
    @Override
27
    public int getNetworkTimeout() {
28
        return 30000;
29
    }
30
    
31
}
tags/org.gvsig.postgresql-2.0.187/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
    @Override
69
    public int getNetworkTimeout() {
70
        return this.helper.getNetworkTimeout();
71
    }
72

  
73
}
tags/org.gvsig.postgresql-2.0.187/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.JDBCServerExplorerParameters;
29

  
30
             
31
public class PostgreSQLServerExplorerParameters extends
32
        JDBCServerExplorerParameters 
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.187/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.DriverManager;
6
import java.sql.SQLException;
7
import org.apache.commons.dbcp2.BasicDataSource;
8
import org.apache.commons.lang3.BooleanUtils;
9
import org.apache.commons.lang3.StringUtils;
10
import org.gvsig.expressionevaluator.GeometryExpressionBuilderHelper.GeometrySupportType;
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.JDBCUtils;
18
import org.gvsig.fmap.dal.store.jdbc2.OperationsFactory;
19
import org.gvsig.fmap.dal.store.jdbc2.spi.ConnectionProvider;
20
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCHelperBase;
21
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCSQLBuilderBase;
22
import org.gvsig.fmap.dal.store.jdbc2.spi.SRSSolverBase;
23
import org.gvsig.fmap.dal.store.jdbc2.spi.SRSSolverDumb;
24
import org.gvsig.postgresql.dal.operations.PostgreSQLOperationsFactory;
25
import org.gvsig.tools.dispose.Disposable;
26
import org.gvsig.tools.exception.BaseException;
27
import org.postgresql.util.DriverInfo;
28
import org.slf4j.Logger;
29
import org.slf4j.LoggerFactory;
30

  
31
@SuppressWarnings("UseSpecificCatch")
32
public class PostgreSQLHelper extends JDBCHelperBase {
33

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

  
36
    public static final String POSTGRESQL_JDBC_DRIVER = "org.postgresql.Driver";
37
    
38
    public static final boolean USE_CONNECTIONS_POOL = true;
39
    
40
    public static String getConnectionURL(PostgreSQLConnectionParameters params) {
41
        return getConnectionURL(
42
            params.getHost(),
43
            params.getPort(),
44
            params.getDBName()
45
        );
46
    }
47
    
48
    public static String getConnectionURL(String host, Integer port, String db) {
49
        if( StringUtils.isEmpty(host) ) {
50
            throw new IllegalArgumentException("Parameter 'host' can't be null.");
51
        }
52
        String connectionURL = "jdbc:postgresql://" + host;
53
        if (port != null) {
54
            connectionURL = connectionURL + ":" + port;
55
        }
56
        connectionURL = connectionURL + "/" + db;
57
        LOGGER.debug("connectionURL: {}", connectionURL);
58
        return connectionURL;
59
    }
60

  
61
    private static class PostgreSQLConnectionProvider implements Disposable, ConnectionProvider {
62

  
63
        private static boolean needRegisterDriver = true;
64

  
65
        private BasicDataSource dataSource = null;
66

  
67
        private PostgreSQLConnectionParameters connectionParameters;
68

  
69
        public PostgreSQLConnectionProvider(PostgreSQLConnectionParameters connectionParameters) {
70
            this.connectionParameters = connectionParameters;
71
        }
72

  
73
        @Override
74
        public Connection getConnection() throws SQLException {
75
            
76
            Connection conn;
77
            if( USE_CONNECTIONS_POOL ) {
78
                if (this.dataSource == null) {
79
                    this.dataSource = this.createDataSource();               
80
                }
81
                if( LOGGER.isDebugEnabled() ) {
82
                    LOGGER.debug("getConnection:\n" + getStatusInformation());
83
                }
84
                try {
85
                    conn = this.dataSource.getConnection();
86
                } catch(Throwable ex) {
87
                    LOGGER.debug("Error getting connection from pool.",ex);
88
                    throw ex;
89
                }
90
                try {
91
                    conn.setNetworkTimeout(null, this.connectionParameters.getNetworkTimeout());
92
                } catch(Throwable ex) {
93
                    LOGGER.warn("Error setting the network timeout.",ex);
94
                }
95
                if( LOGGER.isDebugEnabled() ) {
96
                    LOGGER.debug("Created connection: {}\n  NumActive: {}\n  NumIdle: {}",
97
                        new Object[] {
98
                            conn.hashCode(), 
99
                            this.dataSource.getNumActive(),
100
                            this.dataSource.getNumIdle()
101
                        }
102
                    );
103
                }
104
            } else {
105
                try {
106
                    conn = DriverManager.getConnection(
107
                        connectionParameters.getUrl(), 
108
                        connectionParameters.getUser(), 
109
                        connectionParameters.getPassword()
110
                    );
111
                } catch(Throwable th) {
112
                    throw th;
113
                }
114
                if( LOGGER.isDebugEnabled() ) {
115
                    LOGGER.debug("Created not polled connection: {}",
116
                        new Object[] {
117
                            conn.hashCode()
118
                        }
119
                    );
120
                }
121
            }
122
            LOGGER.debug("PostgreSQL JDBC Driver: "+DriverInfo.DRIVER_VERSION);
123
            return conn;
124
        }
125
        
126
        public String getStatusInformation() {
127
            StringBuilder builder = new StringBuilder();
128
            if( this.dataSource==null ) {
129
                builder.append("Not poolled connection:\n");
130
                builder.append("  Connection URL: '").append(this.connectionParameters.getUrl()).append("'\n");
131
            } else {
132
                builder.append("BasicDataSource pool status:\n");
133
                builder.append("  Connection URL: '").append(this.dataSource.getUrl()).append("'\n");
134
                if( this.dataSource.getInitialSize()>0 ) {
135
                    builder.append("  InitialSize: ").append(this.dataSource.getInitialSize()).append(" (The initial number of connections that are created when the pool is started)\n");
136
                }
137
                if( this.dataSource.isPoolPreparedStatements() ) {
138
                    builder.append("  PoolPreparedStatements: ").append(this.dataSource.isPoolPreparedStatements()).append("\n");
139
                    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");
140
                }
141
                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");
142
                builder.append("  MaxIdle: ").append(this.dataSource.getMaxIdle()).append(" (The maximum number of connections that can remain idle in the pool)\n");
143
                builder.append("  NumActive:").append(this.dataSource.getNumActive()).append(" (the current number of active connections)\n");
144
                builder.append("  NumIdle:").append(this.dataSource.getNumIdle()).append(" (the current number of idle connections)\n");
145
            }
146
            return builder.toString();
147
        }
148

  
149
        private BasicDataSource createDataSource() throws SQLException {
150
            if (!this.isRegistered()) {
151
                this.registerDriver();
152
            }
153
            PostgreSQLConnectionParameters params = connectionParameters;
154

  
155
            BasicDataSource ds = new BasicDataSource();
156
            ds.setMaxIdle(params.getMaxIdle());
157
            ds.setDriverClassName(params.getJDBCDriverClassName());
158
            if( params.getUseSSL() ) {
159
                String s = BooleanUtils.toStringTrueFalse(params.getUseSSL());
160
                ds.addConnectionProperty("ssl", s );
161
            }
162
            if( !StringUtils.isEmpty(params.getUser()) ) {
163
                ds.setUsername(params.getUser());
164
            }
165
            if( !StringUtils.isEmpty(params.getPassword()) ) {
166
                ds.setPassword(params.getPassword());
167
            }
168
            ds.setUrl(params.getUrl());
169
            
170
            ds.setMinEvictableIdleTimeMillis(20*1000);
171
            ds.setTimeBetweenEvictionRunsMillis(20*1000);
172
            ds.setMinIdle(0);
173
            
174
            ds.setMaxWaitMillis(60L * 1000);
175
            return ds;
176
        }
177

  
178
        private boolean isRegistered() {
179
            return needRegisterDriver;
180
        }
181

  
182
        @Override
183
        public void registerDriver() throws SQLException {
184
            String className = this.connectionParameters.getJDBCDriverClassName();
185
            if (className == null) {
186
                return;
187
            }
188
            try {
189
                Class theClass = Class.forName(className);
190
                if (theClass == null) {
191
                    throw new JDBCDriverClassNotFoundException(PostgreSQLLibrary.NAME, className);
192
                }
193
            } catch (Exception e) {
194
                throw new SQLException("Can't register JDBC driver '" + className + "'.", e);
195
            }
196
            needRegisterDriver = false;
197
        }
198

  
199
        @Override
200
        public void dispose() {
201
            if( this.dataSource!=null ) {
202
                try {
203
                    this.dataSource.close();
204
                } catch (SQLException ex) {
205
                    LOGGER.warn("Can't close BasicDataSource", ex);
206
                }
207
                this.dataSource = null;
208
            }
209
            this.connectionParameters = null;
210
        }
211

  
212
        @Override
213
        public String getStatus() {
214
            if( dataSource==null ) {
215
                return "Not polled";
216
            }
217
            StringBuilder builder = new StringBuilder();
218
            builder.append("Pool: ");
219
            builder.append(JDBCUtils.getHexId(dataSource));
220
            builder.append(" Actives: ");
221
            builder.append(dataSource.getNumActive());
222
            builder.append("/");
223
            builder.append(dataSource.getMaxTotal()); //.getMaxActive());
224
            builder.append(" idle: ");
225
            builder.append(dataSource.getNumIdle());
226
            builder.append("/");
227
            builder.append(dataSource.getMinIdle());
228
            builder.append(":");
229
            builder.append(dataSource.getMaxIdle());
230
            return builder.toString();
231
        }
232

  
233
    }
234

  
235
    private ConnectionProvider connectionProvider = null;
236
   
237
    /**
238
     * Constructor for use only for testing purposes.
239
     * 
240
     * @param connectionParameters
241
     * @param connectionProvider
242
     */
243
    public PostgreSQLHelper(PostgreSQLConnectionParameters connectionParameters, ConnectionProvider connectionProvider) { 
244
        super(connectionParameters);
245
        this.srssolver = new SRSSolverDumb(this);
246
        this.connectionProvider = connectionProvider;
247
    }
248
  
249

  
250

  
251
    public PostgreSQLHelper(JDBCConnectionParameters connectionParameters) {
252
        super(connectionParameters);
253
        this.srssolver = new SRSSolverBase(this);
254
    }
255

  
256
    @Override
257
    protected void doDispose() throws BaseException {
258
        if( this.connectionProvider!=null ) {
259
            this.connectionProvider.dispose();
260
            this.connectionProvider = null;
261
        }
262
        super.doDispose(); 
263
    }
264

  
265
    @Override
266
    public Connection getConnection() throws AccessResourceException {
267
        try {
268
            if (this.connectionProvider == null) {
269
              if( this.getConnectionParameters()==null ) {
270
                return null;
271
              }
272
              this.connectionProvider = new PostgreSQLConnectionProvider(this.getConnectionParameters());
273
            }
274
            return this.connectionProvider.getConnection();
275
        } catch (SQLException ex) {
276
            throw new AccessResourceException(PostgreSQLLibrary.NAME, ex);
277
        }
278
    }
279

  
280
    @Override
281
    public void closeConnection(Connection connection) {
282
        if (connection != null) { // In test ???
283
            LOGGER.debug("[" + JDBCUtils.getConnId(connection) + "] closeConnection " + this.connectionProvider.getStatus());
284
        }
285
        super.closeConnection(connection);
286
    }
287
    
288
    @Override
289
    public PostgreSQLConnectionParameters getConnectionParameters() {
290
        return (PostgreSQLConnectionParameters) super.getConnectionParameters();
291
    }
292
    
293
    @Override
294
    public String getConnectionURL() {
295
        return getConnectionURL(this.getConnectionParameters());
296
    }
297

  
298
    @Override
299
    protected String getResourceType() {
300
        return PostgreSQLLibrary.NAME;
301
    }
302

  
303
    @Override
304
    public String getProviderName() {
305
        return PostgreSQLLibrary.NAME;
306
    }
307

  
308
    @Override
309
    public JDBCSQLBuilderBase createSQLBuilder() {
310
        return new PostgreSQLBuilder(this);
311
    }
312
    
313
    @Override
314
    public OperationsFactory getOperations() {
315
        if (this.operationsFactory == null) {
316
            this.operationsFactory = new PostgreSQLOperationsFactory(this);
317
        }
318
        return operationsFactory;
319
    }
320

  
321
    @Override
322
    public GeometrySupportType getGeometrySupportType() {
323
        return GeometrySupportType.EWKB;
324
    }
325

  
326
    @Override
327
    public boolean hasSpatialFunctions() {
328
        return true;
329
    }
330

  
331
    @Override
332
    public boolean canWriteGeometry(int geometryType, int geometrySubtype) {
333
        return true;
334
    }
335

  
336
    @Override
337
    public String getQuoteForIdentifiers() {
338
        return "\"";
339
    }
340

  
341
    @Override
342
    public boolean allowAutomaticValues() {
343
        return true;
344
    }
345

  
346
    @Override
347
    public boolean supportOffsetInSelect() {
348
        return true;
349
    }
350

  
351
    @Override
352
    public String getQuoteForStrings() {
353
        return "'";
354
    }
355
    
356
    @Override
357
    public String getSourceId(JDBCStoreParameters parameters) {
358
        return parameters.getDBName() + "." + 
359
               parameters.getSchema()+ "." + 
360
               parameters.getTable();
361
    }
362

  
363
    @Override
364
    public JDBCNewStoreParameters createNewStoreParameters() {
365
        return new PostgreSQLNewStoreParameters();
366
    }
367

  
368
    @Override
369
    public JDBCStoreParameters createOpenStoreParameters() {
370
        return new PostgreSQLStoreParameters();
371
    }
372

  
373
    @Override
374
    public JDBCServerExplorerParameters createServerExplorerParameters() {
375
        return new PostgreSQLServerExplorerParameters();
376
    }
377
}
tags/org.gvsig.postgresql-2.0.187/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/PostgreSQLServerExplorerFactory.java
1

  
2
package org.gvsig.postgresql.dal;
3

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

  
15

  
16
public class PostgreSQLServerExplorerFactory extends JDBCServerExplorerFactory {
17

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

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

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

  
58
    @Override
59
    public JDBCServerExplorerParameters createParameters() {
60
        JDBCServerExplorerParameters params = new PostgreSQLServerExplorerParameters();
61
        return params;    
62
    }
63
    
64
}
tags/org.gvsig.postgresql-2.0.187/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.JDBCStoreParameters;
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.JDBCStoreProviderFactory;
19

  
20
public class PostgreSQLStoreProviderFactory extends JDBCStoreProviderFactory {
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(
47
                (JDBCStoreParameters) parameters,
48
                providerServices
49
        );
50
        return provider;
51
    }
52

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

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

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

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

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

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

  
92
    @Override
93
    public int hasSQLSupport() {
94
        return YES;
95
    }
96
}
tags/org.gvsig.postgresql-2.0.187/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/operations/PostgreSQLFetchFeatureTypeOperation.java
1

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

  
4
import java.sql.Connection;
5
import java.sql.ResultSet;
6
import java.sql.ResultSetMetaData;
7
import java.sql.SQLException;
8
import java.sql.Statement;
9
import java.util.HashMap;
10
import java.util.List;
11
import java.util.Map;
12
import org.apache.commons.lang3.StringUtils;
13
import org.cresques.cts.IProjection;
14
import org.gvsig.expressionevaluator.ExpressionBuilder;
15
import org.gvsig.fmap.dal.DataTypes;
16
import org.gvsig.fmap.dal.exception.DataException;
17
import org.gvsig.fmap.dal.feature.EditableFeatureAttributeDescriptor;
18
import org.gvsig.fmap.dal.feature.EditableFeatureType;
19
import org.gvsig.fmap.dal.store.jdbc2.JDBCHelper;
20
import org.gvsig.fmap.dal.store.jdbc2.JDBCUtils;
21
import org.gvsig.fmap.dal.store.jdbc2.OperationsFactory.TableReference;
22
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCSQLBuilderBase;
23
import org.gvsig.fmap.dal.store.jdbc2.spi.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(Connection 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.187/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.187/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.exception.ValidateDataParametersException;
25
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParameters;
26

  
27
public class PostgreSQLStoreParameters extends JDBCStoreParameters implements PostgreSQLConnectionParameters {
28

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

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

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

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

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

  
64
    @Override
65
    public int getNetworkTimeout() {
66
        return this.helper.getNetworkTimeout();
67
    }
68
    
69
}
tags/org.gvsig.postgresql-2.0.187/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.187/org.gvsig.postgresql.provider/src/main/java/org/gvsig/postgresql/dal/PostgreSQLConnectionParametersHelper.java
1

  
2
package org.gvsig.postgresql.dal;
3

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

  
9

  
10
public class PostgreSQLConnectionParametersHelper {
11

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

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

  
47
    private Object getDynValue(String name) {
48
        return ((DataParameters)this.parameters).getDynValue(name);
49
    }
50
    
51
    private void setDynValue(String name, Object value) {
52
        ((DataParameters)this.parameters).setDynValue(name,value);
53
    }
54
    
55
    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.187/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.187/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
@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
            Connection 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
                this.getHelper().closeConnectionQuietly(conn);
78
            }
79
        }
80
        return databaseVersion;
81
    }
82
    
83
    public PostgreSQLBuilder(JDBCHelper helper) {
84
        super(helper);
85
        this.defaultSchema = "public";
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff