Revision 51

View differences:

tags/org.gvsig.postgresql-2.0.19/pom.xml
1
<?xml version="1.0" encoding="UTF-8"?>
2

  
3
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4

  
5
  <modelVersion>4.0.0</modelVersion>
6
  <artifactId>org.gvsig.postgresql</artifactId>
7
  <version>2.0.19</version>
8
  <packaging>pom</packaging>
9
  <name>${project.artifactId}</name>
10
  <description>PostgreSQL support fort DAL and gvSIG</description>
11
  <parent>
12
      <groupId>org.gvsig</groupId>
13
      <artifactId>org.gvsig.desktop</artifactId>
14
      <version>2.0.24</version>
15
  </parent>
16

  
17
  <url>https://devel.gvsig.org/redmine/projects/gvsig-postgresql</url>
18
  <scm>
19
      <connection>scm:svn:https://devel.gvsig.org/svn/gvsig-postgresql/tags/org.gvsig.postgresql-2.0.19</connection>
20
      <developerConnection>scm:svn:https://devel.gvsig.org/svn/gvsig-postgresql/tags/org.gvsig.postgresql-2.0.19</developerConnection>
21
      <url>https://devel.gvsig.org/redmine/projects/gvsig-postgresql/repository/show/tags/org.gvsig.postgresql-2.0.19</url>
22
  </scm>
23
  
24
  
25
	<build>
26
		<plugins>
27
			<plugin>
28
				<groupId>org.apache.maven.plugins</groupId>
29
				<artifactId>maven-release-plugin</artifactId>
30
				<configuration>
31
					<tagBase>https://devel.gvsig.org/svn/gvsig-postgresql/tags/</tagBase>
32
					<goals>deploy</goals>
33
				</configuration>
34
			</plugin>
35
		</plugins>
36
	</build>
37

  
38

  
39
  <dependencyManagement>
40
      <dependencies>
41
          <dependency>
42
            <groupId>org.gvsig</groupId>
43
            <artifactId>org.gvsig.postgresql.provider</artifactId>
44
            <version>2.0.19</version>
45
          </dependency>
46
          <dependency>
47
            <groupId>org.gvsig</groupId>
48
            <artifactId>org.gvsig.postgresql.app.mainplugin</artifactId>
49
            <version>2.0.19</version>
50
          </dependency>
51
      </dependencies>
52
  </dependencyManagement>
53

  
54
  <dependencies>
55
        <dependency>
56
            <groupId>org.slf4j</groupId>
57
            <artifactId>slf4j-api</artifactId>
58
            <scope>compile</scope>
59
        </dependency>
60
  </dependencies>
61

  
62
  
63
  <modules>
64
    <module>org.gvsig.postgresql.app</module>
65
    <module>org.gvsig.postgresql.provider</module>
66
  </modules>
67

  
68

  
69
</project>
tags/org.gvsig.postgresql-2.0.19/org.gvsig.postgresql.provider/src/main/java/org/gvsig/fmap/dal/store/postgresql/PostgreSQLSetProvider.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
* AUTHORS (In addition to CIT):
25
* 2009 IVER T.I   {{Task}}
26
*/
27

  
28
/**
29
 *
30
 */
31
package org.gvsig.fmap.dal.store.postgresql;
32

  
33
import java.util.ArrayList;
34
import java.util.List;
35

  
36
import org.cresques.cts.IProjection;
37
import org.slf4j.Logger;
38
import org.slf4j.LoggerFactory;
39

  
40
import org.gvsig.fmap.dal.exception.DataException;
41
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
42
import org.gvsig.fmap.dal.feature.FeatureQuery;
43
import org.gvsig.fmap.dal.feature.FeatureStore;
44
import org.gvsig.fmap.dal.feature.FeatureType;
45
import org.gvsig.fmap.dal.feature.exception.CreateGeometryException;
46
import org.gvsig.fmap.dal.store.db.DBStoreParameters;
47
import org.gvsig.fmap.dal.store.jdbc.JDBCSetProvider;
48
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreProvider;
49
import org.gvsig.fmap.geom.primitive.Envelope;
50
import org.gvsig.tools.evaluator.Evaluator;
51
import org.gvsig.tools.evaluator.EvaluatorFieldValue;
52
import org.gvsig.tools.evaluator.EvaluatorFieldsInfo;
53

  
54
/**
55
 * @author jmvivo
56
 *
57
 */
58
public class PostgreSQLSetProvider extends JDBCSetProvider {
59

  
60
    private static Logger logger = LoggerFactory.getLogger(PostgreSQLSetProvider.class);
61
    
62
	public PostgreSQLSetProvider(JDBCStoreProvider store, FeatureQuery query,
63
			FeatureType featureType) throws DataException {
64
		super(store, query, featureType);
65
	}
66

  
67

  
68
	/*
69
	 * (non-Javadoc)
70
	 *
71
	 * @see org.gvsig.fmap.dal.feature.spi.FeatureSetProvider#canFilter()
72
	 */
73
	public boolean canFilter() {
74
		// TODO more checks
75
		if (!super.canFilter()) {
76
			return false;
77
		}
78
		return true;
79

  
80
	}
81
	
82
    protected String getSqlForEvaluator(Evaluator filter) {
83
        
84
        String resp = null;
85
        if (filter != null && filter.getSQL() != null) {
86
            // =================================================
87
            EvaluatorFieldsInfo info = filter.getFieldsInfo();
88
            String filterString = filter.getSQL();
89
            
90
            String[] filterNames = null;
91
            String[] finalNames = null;
92
            
93
            if (info == null) {
94
                filterNames = getFieldNames(getFeatureType());
95
            } else {
96
                filterNames = info.getFieldNames();
97
            }
98
            
99
            finalNames = new String[filterNames.length];
100
            FeatureAttributeDescriptor attr;
101
            for (int i = 0; i < filterNames.length; i++) {
102
                attr = getFeatureType().getAttributeDescriptor(filterNames[i]);
103
                if (attr == null) {
104
                    finalNames[i] = filterNames[i];
105
                    continue;
106
                }
107
                finalNames[i] = getEscapedFieldName(attr.getName());
108
            }
109

  
110
            for (int i = 0; i < filterNames.length; i++) {
111
                if (!filterNames[i].equals(finalNames[i])) {
112
                    filterString = filterString.replaceAll(
113
                            "\\b" + filterNames[i] + "\\b",
114
                            finalNames[i]);
115
                }
116
            }
117
            resp = filterString;        
118
        }
119
        // ================================
120
        // In any case, append working area filter
121
        
122
        try {
123
            resp = appendWorkingAreaCondition(resp);
124
        } catch (Exception e) {
125
            logger.error("While appending working area condition.", e);
126
        }
127
        return resp;
128
    }	
129
    
130
    private String[] getFieldNames(FeatureType ft) {
131
        
132
        if (ft == null) {
133
            return new String[0];
134
        }
135
        FeatureAttributeDescriptor[] atts = ft.getAttributeDescriptors();
136
        String[] resp = new String[atts.length];
137
        for (int i=0; i<atts.length; i++) {
138
            resp[i] = atts[i].getName();
139
        }
140
        return resp;
141
    }
142
    
143
    private String getFunctionName(String newFunctionName) {
144
        
145
        PostgreSQLStoreProvider pg_sto_prov = (PostgreSQLStoreProvider) this.getStore();
146
        PostgreSQLHelper hpr = pg_sto_prov.getPgHelper();
147
        if (hpr == null) {
148
            logger.info("Unable to get PG helper.", new Exception("Helper is null"));
149
            return newFunctionName;
150
        } else {
151
            return hpr.getFunctionName(newFunctionName);
152
        }
153
    }
154

  
155

  
156
    private String appendWorkingAreaCondition(String sql) throws Exception {
157
        
158
        
159
        DBStoreParameters dbParams = 
160
        (DBStoreParameters) getStore().getParameters();
161
        
162
        Envelope wa = dbParams.getWorkingArea(); 
163
        if (wa == null) {
164
            return sql;
165
        } else {
166
            
167
            FeatureStore fstore = this.getStore().getFeatureStore();
168
            String geoname =
169
                fstore.getDefaultFeatureType().getDefaultGeometryAttributeName();
170
            
171
            StringBuffer strbuf = new StringBuffer();
172
            
173
            if (sql == null)  {
174
                strbuf.append(
175
                    getFunctionName("ST_Intersects") + "("
176
                    + getFunctionName("ST_GeomFromText") + "('");
177
            } else {
178
                strbuf.append("(");
179
                strbuf.append(sql);
180
                strbuf.append(") AND "
181
                    + getFunctionName("ST_Intersects") + "("
182
                    + getFunctionName("ST_GeomFromText") + "('");
183
            }
184
            
185
            String workAreaWkt = null;
186
            workAreaWkt = wa.getGeometry().convertToWKT();
187
            strbuf.append(workAreaWkt);
188
            strbuf.append("', ");
189
            
190
            PostgreSQLStoreProvider sprov = (PostgreSQLStoreProvider) getStore();
191
            PostgreSQLHelper helper = sprov.getPgHelper();
192
            
193
            IProjection proj = dbParams.getCRS();
194
            int sridInt = helper.getProviderSRID(proj); 
195
            if (sridInt == -1) {
196
                throw new CreateGeometryException(
197
                        new Exception("CRS is null or unknown."));
198
            } else {
199
                strbuf.append(Integer.toString(sridInt));
200
            }
201
            strbuf.append("), " + getFunctionName("ST_Envelope") + "(");
202
            strbuf.append(helper.escapeFieldName(geoname));
203
            strbuf.append("))");
204
            
205
            return strbuf.toString();
206
        }
207
    }
208
	
209

  
210
}
tags/org.gvsig.postgresql-2.0.19/org.gvsig.postgresql.provider/src/main/java/org/gvsig/fmap/dal/store/postgresql/PostgreSQLResource.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
* AUTHORS (In addition to CIT):
25
* 2009 IVER T.I   {{Task}}
26
*/
27

  
28
package org.gvsig.fmap.dal.store.postgresql;
29

  
30
import java.sql.SQLException;
31
import java.text.MessageFormat;
32

  
33
import javax.sql.DataSource;
34

  
35
import org.apache.commons.dbcp.BasicDataSource;
36
import org.gvsig.fmap.dal.exception.DataException;
37
import org.gvsig.fmap.dal.exception.InitializeException;
38
import org.gvsig.fmap.dal.resource.exception.AccessResourceException;
39
import org.gvsig.fmap.dal.store.jdbc.JDBCResource;
40
import org.gvsig.fmap.dal.store.jdbc.JDBCResourceParameters;
41
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCDriverClassNotFoundException;
42
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCSQLException;
43
import org.slf4j.Logger;
44
import org.slf4j.LoggerFactory;
45

  
46
public class PostgreSQLResource extends JDBCResource {
47
	
48
	final static private Logger logger = LoggerFactory
49
			.getLogger(PostgreSQLResource.class);
50

  
51
	public final static String NAME = "PostgreSQLResource";
52
	public static final String DESCRIPTION = "PostgreSQL Connection";
53

  
54
	public PostgreSQLResource(PostgreSQLResourceParameters parameters)
55
			throws InitializeException {
56
		super(parameters);
57
	}
58

  
59
	public String getName() throws AccessResourceException {
60
		PostgreSQLResourceParameters params = (PostgreSQLResourceParameters) this.getParameters();
61
		return MessageFormat.format("PostgreSQLResource({0},{1})",
62
				new Object[] { params.getUrl(),params.getUser() });
63
	}
64

  
65
	protected void connectToDB() throws DataException {
66
		if (this.dataSource != null) {
67
			return;
68
		}
69
		JDBCResourceParameters jdbcParams = (JDBCResourceParameters) this
70
				.getParameters();
71
		BasicDataSource dataSource = new BasicDataSource();
72
		dataSource.setDriverClassName(jdbcParams.getJDBCDriverClassName());
73
		dataSource.setUsername(jdbcParams.getUser());
74
		dataSource.setPassword(jdbcParams.getPassword());
75
		dataSource.setUrl(jdbcParams.getUrl());
76

  
77
		dataSource.setMaxWait(60L * 1000); // FIXME
78

  
79
		// FIXME Set Pool parameters:
80
		/*
81
		dataSource.setMaxActive(maxActive);
82
		dataSource.setMaxIdle(maxActive);
83
		dataSource.setMaxOpenPreparedStatements(maxActive);
84
		dataSource.setMaxWait(maxActive);
85
		dataSource.setInitialSize(initialSize);
86
		dataSource.setDefaultReadOnly(defaultReadOnly);
87
		dataSource.setDefaultTransactionIsolation(defaultTransactionIsolation);
88
		dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
89
		dataSource.setMinIdle(minIdle);
90
		dataSource.setTestOnBorrow(testOnBorrow);
91
		dataSource.setTestOnReturn(testOnReturn);
92
		dataSource.setTestWhileIdle(testOnReturn);
93
		dataSource
94
				.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
95

  
96
		dataSource.setAccessToUnderlyingConnectionAllowed(allow);
97
		dataSource.setLoginTimeout(seconds);
98
		dataSource.setLogWriter(out);
99
		*/
100

  
101
		this.dataSource = dataSource;
102
	}	
103
	protected void registerJDBCDriver() throws InitializeException {
104
		String className = ((JDBCResourceParameters) getParameters())
105
				.getJDBCDriverClassName();
106
		if (className == null) {
107
			return;
108
		}
109

  
110
		Class theClass = null;
111
		try {
112
			theClass = Class.forName(className);
113
		} catch (Exception e){
114
			throw new InitializeException(e);
115
		}
116
		if (theClass == null) {
117
			try {
118
				throw new JDBCDriverClassNotFoundException(this.getName(),
119
						className);
120
			} catch (AccessResourceException e) {
121
				throw new InitializeException(e);
122

  
123
			}
124
		}
125
	}
126
	
127
	protected DataSource createDataSource() {
128
		PostgreSQLResourceParameters jdbcParams = (PostgreSQLResourceParameters) this
129
				.getParameters();
130
		BasicDataSource dataSource = new BasicDataSource();
131
		dataSource.setDriverClassName(jdbcParams.getJDBCDriverClassName());
132
		dataSource.setUsername(jdbcParams.getUser());
133
		dataSource.setPassword(jdbcParams.getPassword());
134
		dataSource.setUrl(jdbcParams.getUrl());
135

  
136
		dataSource.setMaxWait(60L * 1000); // FIXME
137

  
138
		// FIXME Set Pool parameters:
139
		/*
140
		dataSource.setMaxActive(maxActive);
141
		dataSource.setMaxIdle(maxActive);
142
		dataSource.setMaxOpenPreparedStatements(maxActive);
143
		dataSource.setMaxWait(maxActive);
144
		dataSource.setInitialSize(initialSize);
145
		dataSource.setDefaultReadOnly(defaultReadOnly);
146
		dataSource.setDefaultTransactionIsolation(defaultTransactionIsolation);
147
		dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
148
		dataSource.setMinIdle(minIdle);
149
		dataSource.setTestOnBorrow(testOnBorrow);
150
		dataSource.setTestOnReturn(testOnReturn);
151
		dataSource.setTestWhileIdle(testOnReturn);
152
		dataSource
153
			.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
154

  
155
		dataSource.setAccessToUnderlyingConnectionAllowed(allow);
156
		dataSource.setLoginTimeout(seconds);
157
		dataSource.setLogWriter(out);
158
		 */
159
		return dataSource;
160
	}
161
	
162
	
163
	public boolean isConnected() {
164
		if (dataSource == null) {
165
			return false;
166
		}
167
		if (dataSource instanceof BasicDataSource) {
168
			return ((BasicDataSource) dataSource).getNumActive() > 0
169
					|| ((BasicDataSource) dataSource).getNumIdle() > 0;
170
		}
171
		return true;
172
	}	
173
	
174
	private void logPoolStatus(String src) {
175
		if (logger.isDebugEnabled() && dataSource instanceof BasicDataSource) {
176
			BasicDataSource ds = (BasicDataSource) dataSource;
177
			logger.debug(src + "  actives:" + ds.getNumActive() + "("
178
					+ ds.getMaxActive() + ") idle:" + ds.getNumIdle() + "("
179
					+ ds.getMaxIdle() + ")");
180
		}
181

  
182
	}
183

  
184
	protected synchronized Object getTheConnection() throws DataException {
185
		try {
186
			Object conn = this.dataSource.getConnection();
187
			logPoolStatus("getTheConnection");
188
			return conn;
189
		} catch (SQLException e) {
190
			throw new JDBCSQLException(e);
191
		}
192
	}	
193

  
194
}
tags/org.gvsig.postgresql-2.0.19/org.gvsig.postgresql.provider/src/main/java/org/gvsig/fmap/dal/store/postgresql/PostgreSQLServerExplorer.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
* AUTHORS (In addition to CIT):
25
* 2009 IVER T.I   {{Task}}
26
*/
27

  
28
/**
29
 *
30
 */
31
package org.gvsig.fmap.dal.store.postgresql;
32

  
33
import java.sql.Connection;
34
import java.sql.SQLException;
35
import java.sql.Statement;
36
import java.util.ArrayList;
37
import java.util.List;
38

  
39
import org.gvsig.fmap.dal.DataStoreParameters;
40
import org.gvsig.fmap.dal.NewDataStoreParameters;
41
import org.gvsig.fmap.dal.exception.DataException;
42
import org.gvsig.fmap.dal.exception.InitializeException;
43
import org.gvsig.fmap.dal.exception.ProviderNotRegisteredException;
44
import org.gvsig.fmap.dal.exception.RemoveException;
45
import org.gvsig.fmap.dal.spi.DataServerExplorerProviderServices;
46
import org.gvsig.fmap.dal.store.jdbc.JDBCHelper;
47
import org.gvsig.fmap.dal.store.jdbc.JDBCServerExplorer;
48
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParameters;
49
import org.gvsig.fmap.dal.store.jdbc.TransactionalAction;
50
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCExecuteSQLException;
51
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCSQLException;
52
import org.slf4j.Logger;
53
import org.slf4j.LoggerFactory;
54

  
55
/**
56
 * @author jmvivo
57
 *
58
 */
59
public class PostgreSQLServerExplorer extends JDBCServerExplorer {
60
	final static private Logger logger = LoggerFactory
61
			.getLogger(PostgreSQLServerExplorer.class);
62

  
63
	public static final String NAME = "PostgreSQLExplorer";
64

  
65

  
66
	public PostgreSQLServerExplorer(
67
			PostgreSQLServerExplorerParameters parameters,
68
			DataServerExplorerProviderServices services)
69
			throws InitializeException {
70
		super(parameters, services);
71
	}
72

  
73
	private PostgreSQLServerExplorerParameters getPostgreSQLParameters() {
74
		return (PostgreSQLServerExplorerParameters) getParameters();
75
	}
76

  
77

  
78
	protected JDBCHelper createHelper() throws InitializeException {
79
		return new PostgreSQLHelper(this, getPostgreSQLParameters());
80
	}
81

  
82

  
83
	protected String getStoreName() {
84
		return PostgreSQLStoreProvider.NAME;
85
	}
86

  
87
	public String getProviderName() {
88
		return NAME;
89
	}
90

  
91
	protected JDBCStoreParameters createStoreParams()
92
			throws InitializeException, ProviderNotRegisteredException {
93
		PostgreSQLStoreParameters orgParams = (PostgreSQLStoreParameters) super
94
				.createStoreParams();
95

  
96
		orgParams.setUseSSL(getPostgreSQLParameters().getUseSSL());
97

  
98
		return orgParams;
99
	}
100

  
101

  
102
	// ****************************
103

  
104

  
105
	public boolean canAdd() {
106
		return true;
107
	}
108

  
109
	protected void checkIsMine(DataStoreParameters dsp) {
110
		if (!(dsp instanceof PostgreSQLStoreParameters)) {
111
			// FIXME Excpetion ???
112
			throw new IllegalArgumentException(
113
					"not instance of PostgreSQLStoreParameters");
114
		}
115
		super.checkIsMine(dsp);
116

  
117
		PostgreSQLStoreParameters pgp = (PostgreSQLStoreParameters) dsp;
118
		if (pgp.getUseSSL().booleanValue() != getPostgreSQLParameters()
119
				.getUseSSL()) {
120
			throw new IllegalArgumentException("worng explorer: Host");
121
		}
122
	}
123

  
124
	public void remove(DataStoreParameters dsp) throws RemoveException {
125
		final PostgreSQLStoreParameters pgParams =(PostgreSQLStoreParameters) dsp;
126

  
127
		TransactionalAction action = new TransactionalAction() {
128
			public boolean continueTransactionAllowed() {
129
				return false;
130
			}
131
			public Object action(Connection conn) throws DataException {
132

  
133

  
134
				Statement st;
135
				try{
136
					st = conn.createStatement();
137
				} catch (SQLException e) {
138
					throw new JDBCSQLException(e);
139
				}
140

  
141
				String sqlDrop = "Drop table "
142
					+ pgParams.tableID();
143

  
144
				StringBuilder strb = new StringBuilder();
145
				strb.append("Delete from GEOMETRY_COLUMNS where f_table_schema = ");
146
				if (pgParams.getSchema() == null || pgParams.getSchema().length() ==  0) {
147
					strb.append("current_schema() ");
148
				} else {
149
					strb.append('\'');
150
					strb.append(pgParams.getSchema());
151
					strb.append("' ");
152
				}
153
				strb.append("and f_table_name = '");
154
				strb.append(pgParams.getTable());
155
				strb.append('\'');
156

  
157
				String sqlDeleteFromGeometry_column = strb.toString();
158
				try{
159
					try{
160
						st.execute(sqlDrop);
161
					} catch (SQLException e) {
162
						throw new JDBCExecuteSQLException(sqlDrop, e);
163
					}
164

  
165
					try {
166
						st.execute(sqlDeleteFromGeometry_column);
167
					} catch (SQLException e) {
168
						throw new JDBCExecuteSQLException(
169
								sqlDeleteFromGeometry_column, e);
170
					}
171

  
172
				} finally{
173
					try{ st.close(); } catch (SQLException e) {};
174
				}
175
				return null;
176
			}
177
		};
178
		try {
179
			this.helper.doConnectionAction(action);
180
		} catch (Exception e) {
181
			throw new RemoveException(this.getProviderName(), e);
182
		}
183
	}
184

  
185
	public NewDataStoreParameters getAddParameters() throws DataException {
186
		PostgreSQLServerExplorerParameters parameters = getPostgreSQLParameters();
187
		PostgreSQLNewStoreParameters params = new PostgreSQLNewStoreParameters();
188
		params.setHost(parameters.getHost());
189
		params.setPort(parameters.getPort());
190
		params.setDBName(parameters.getDBName());
191
		params.setUser(parameters.getUser());
192
		params.setPassword(parameters.getPassword());
193
		params.setCatalog(parameters.getCatalog());
194
		params.setSchema(parameters.getSchema());
195
		params.setJDBCDriverClassName(parameters.getJDBCDriverClassName());
196
		params.setUrl(parameters.getUrl());
197
		params.setUseSSL(parameters.getUseSSL());
198

  
199

  
200
		params.setDefaultFeatureType(this.getServerExplorerProviderServices()
201
				.createNewFeatureType());
202

  
203

  
204
		return params;
205
	}
206

  
207

  
208

  
209
	// ***********************
210
	// ***********************
211

  
212

  
213
	public boolean hasGeometrySupport() {
214
		return true;
215
	}
216

  
217
	protected PostgreSQLHelper getPgHelper() {
218
		return (PostgreSQLHelper) getHelper();
219
	}
220

  
221
	@Override
222
	public List getDataStoreProviderNames() {
223
			List x = new ArrayList(1);
224
			x.add(PostgreSQLStoreProvider.NAME);
225
			return x;
226
	}
227
}
tags/org.gvsig.postgresql-2.0.19/org.gvsig.postgresql.provider/src/main/java/org/gvsig/fmap/dal/store/postgresql/PostgreSQLStoreProvider.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
* AUTHORS (In addition to CIT):
25
* 2009 IVER T.I   {{Task}}
26
*/
27

  
28
package org.gvsig.fmap.dal.store.postgresql;
29

  
30
import java.sql.DatabaseMetaData;
31
import java.sql.ResultSet;
32
import java.sql.SQLException;
33
import java.sql.Statement;
34
import java.util.Iterator;
35
import java.util.List;
36
import java.util.Properties;
37
import java.util.regex.Matcher;
38
import java.util.regex.Pattern;
39

  
40
import org.gvsig.fmap.dal.DALLocator;
41
import org.gvsig.fmap.dal.DataManager;
42
import org.gvsig.fmap.dal.DataServerExplorer;
43
import org.gvsig.fmap.dal.DataTypes;
44
import org.gvsig.fmap.dal.exception.DataException;
45
import org.gvsig.fmap.dal.exception.InitializeException;
46
import org.gvsig.fmap.dal.exception.ReadException;
47
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
48
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
49
import org.gvsig.fmap.dal.feature.FeatureQuery;
50
import org.gvsig.fmap.dal.feature.FeatureType;
51
import org.gvsig.fmap.dal.feature.spi.FeatureProvider;
52
import org.gvsig.fmap.dal.feature.spi.FeatureSetProvider;
53
import org.gvsig.fmap.dal.resource.exception.AccessResourceException;
54
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
55
import org.gvsig.fmap.dal.store.db.DBHelper;
56
import org.gvsig.fmap.dal.store.jdbc.JDBCHelper;
57
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreProviderWriter;
58
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCExecuteSQLException;
59
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCSQLException;
60
import org.gvsig.fmap.geom.Geometry;
61
import org.slf4j.Logger;
62
import org.slf4j.LoggerFactory;
63

  
64
public class PostgreSQLStoreProvider extends JDBCStoreProviderWriter {
65

  
66
	public final static Logger logger = LoggerFactory
67
			.getLogger(PostgreSQLStoreProvider.class);
68

  
69
	public static final String NAME = "PostgreSQL";
70
	public static final String DESCRIPTION = "PostgreSQL source";
71

  
72
	public static final String METADATA_DEFINITION_NAME = NAME;
73
	
74
	public PostgreSQLStoreProvider(PostgreSQLStoreParameters params,
75
			DataStoreProviderServices storeServices)
76
			throws InitializeException {
77
		super(params, storeServices, DBHelper.newMetadataContainer(METADATA_DEFINITION_NAME));
78
	}
79

  
80
	private PostgreSQLStoreParameters getPGParameters() {
81
		return (PostgreSQLStoreParameters) this.getParameters();
82
	}
83

  
84
	protected JDBCHelper createHelper() throws InitializeException {
85
	    JDBCHelper resp = new PostgreSQLHelper(this, getPGParameters());
86
	    
87
	    return resp;
88
	}
89

  
90

  
91

  
92
	protected String fixFilter(String _filter) {
93
		if (_filter == null) {
94
			return null;
95
		}
96
		
97
		String filter = fixFunctionNames(_filter);
98

  
99
		// Transform SRS to code
100
		// GeomFromText\s*\(\s*'[^']*'\s*,\s*('[^']*')\s*\)
101
		
102
		String geom_from_text = this.getFunctionName("ST_GeomFromText");
103
		Pattern pattern = Pattern
104
				.compile(geom_from_text + "\\s*\\(\\s*'[^']*'\\s*,\\s*'([^']*)'\\s*\\)");
105
		Matcher matcher = pattern.matcher(filter);
106
		StringBuilder strb = new StringBuilder();
107
		int pos = 0;
108
		String srsCode;
109
		while (matcher.find(pos)) {
110
			strb.append(filter.substring(pos, matcher.start(1)));
111
			srsCode = matcher.group(1).trim();
112
			if (srsCode.startsWith("'")) {
113
				srsCode = srsCode.substring(1);
114
			}
115
			if (srsCode.endsWith("'")) {
116
				srsCode = srsCode.substring(0, srsCode.length() - 1);
117
			}
118
			strb.append(helper.getProviderSRID(srsCode));
119
			strb.append(filter.substring(matcher.end(1), matcher.end()));
120
			pos = matcher.end();
121

  
122
		}
123
		strb.append(filter.substring(pos));
124

  
125
		return strb.toString();
126
	}
127

  
128

  
129
    public String getName() {
130
		return NAME;
131
	}
132

  
133
	public FeatureSetProvider createSet(FeatureQuery query,
134
			FeatureType featureType) throws DataException {
135

  
136
		return new PostgreSQLSetProvider(this, query, featureType);
137
	}
138

  
139

  
140
	public DataServerExplorer getExplorer() throws ReadException {
141
		DataManager manager = DALLocator.getDataManager();
142
		PostgreSQLServerExplorerParameters exParams;
143
		PostgreSQLStoreParameters params = getPGParameters();
144
		try {
145
			exParams = (PostgreSQLServerExplorerParameters) manager
146
					.createServerExplorerParameters(PostgreSQLServerExplorer.NAME);
147
			exParams.setUrl(params.getUrl());
148
			exParams.setHost(params.getHost());
149
			exParams.setPort(params.getPort());
150
			exParams.setDBName(params.getDBName());
151
			exParams.setUser(params.getUser());
152
			exParams.setPassword(params.getPassword());
153
			exParams.setCatalog(params.getCatalog());
154
			exParams.setSchema(params.getSchema());
155
			exParams.setJDBCDriverClassName(params.getJDBCDriverClassName());
156
			exParams.setUseSSL(params.getUseSSL());
157

  
158
			return manager.openServerExplorer(PostgreSQLServerExplorer.NAME, exParams);
159
		} catch (DataException e) {
160
			throw new ReadException(this.getName(), e);
161
		} catch (ValidateDataParametersException e) {
162
			throw new ReadException(this.getName(), e);
163
		}
164
	}
165

  
166
	public boolean allowAutomaticValues() {
167
		return true;
168
	}
169

  
170

  
171
	public boolean hasGeometrySupport() {
172
		return true;
173
	}
174

  
175

  
176
	protected PostgreSQLHelper getPgHelper() {
177
		return (PostgreSQLHelper) getHelper();
178
	}
179

  
180

  
181

  
182
	public boolean canWriteGeometry(int geometryType, int geometrySubtype)
183
			throws DataException {
184
		FeatureType type = getFeatureStore().getDefaultFeatureType();
185
		FeatureAttributeDescriptor geomAttr = type.getAttributeDescriptor(type
186
								.getDefaultGeometryAttributeName());
187
		if (geomAttr == null) {
188
			return false;
189
		}
190
		if (geometrySubtype != geomAttr.getGeometrySubType()) {
191
			return false;
192
		}
193
		switch (geomAttr.getGeometryType()) {
194
		case Geometry.TYPES.GEOMETRY:
195
			return true;
196

  
197
		case Geometry.TYPES.MULTISURFACE:
198
			return geometryType == Geometry.TYPES.MULTISURFACE
199
					|| geometryType == Geometry.TYPES.SURFACE;
200

  
201
		case Geometry.TYPES.MULTIPOINT:
202
			return geometryType == Geometry.TYPES.MULTIPOINT
203
					|| geometryType == Geometry.TYPES.POINT;
204

  
205
		case Geometry.TYPES.MULTICURVE:
206
			return geometryType == Geometry.TYPES.MULTICURVE
207
					|| geometryType == Geometry.TYPES.CURVE;
208

  
209
		case Geometry.TYPES.MULTISOLID:
210
			return geometryType == Geometry.TYPES.MULTISOLID
211
					|| geometryType == Geometry.TYPES.SOLID;
212

  
213
		default:
214
			return geometryType == geomAttr.getGeometryType();
215
		}
216

  
217
	}
218

  
219

  
220
	protected void addToListFeatureValues(FeatureProvider featureProvider,
221
			FeatureAttributeDescriptor attrOfList,
222
			FeatureAttributeDescriptor attr,
223
			List<Object> values) throws DataException {
224

  
225
		super.addToListFeatureValues(featureProvider, attrOfList, attr, values);
226
		if (attr.getType() == DataTypes.GEOMETRY) {
227
			values.add(helper.getProviderSRID(attr.getSRS()));
228
		}
229
	}
230

  
231
	protected void prepareAttributeForInsert(
232
			FeatureAttributeDescriptor attr, List<String> fields, List<String> values) {
233

  
234
		if (attr.getType() == DataTypes.GEOMETRY) {
235
			fields.add(helper.escapeFieldName(attr.getName()));
236
			values.add(getFunctionName("ST_GeomFromWKB") + "(?,?)");
237
		} else {
238
			super.prepareAttributeForInsert(attr, fields, values);
239
		}
240

  
241
	}
242

  
243
	protected void prepareAttributeForUpdate(FeatureAttributeDescriptor attr,
244
			List<String> values) {
245
		if (attr.getType() == DataTypes.GEOMETRY) {
246
			values.add(helper.escapeFieldName(attr.getName())
247
					+ " = " + getFunctionName("ST_GeomFromWKB") + "(?,?)");
248
		} else {
249
			super.prepareAttributeForUpdate(attr, values);
250
		}
251
	}
252

  
253
	protected String getSqlStatementAddField(FeatureAttributeDescriptor attr,
254
			List<String> additionalStatement) throws DataException {
255
		if (attr.getType() == DataTypes.GEOMETRY) {
256
			PostgreSQLStoreParameters params = getPGParameters();
257
			additionalStatement.addAll(	((PostgreSQLHelper) helper)
258
					.getSqlGeometyFieldAdd(attr, params.getTable(), params
259
							.getSchema()));
260

  
261
		}
262
		return super.getSqlStatementAddField(attr, additionalStatement);
263

  
264
	}
265
	private String getSqlGeometyFieldDrop(FeatureAttributeDescriptor attr) {
266
		StringBuilder strb = new StringBuilder();
267
		PostgreSQLStoreParameters params = getPGParameters();
268
		strb.append("Delete from geometry_columns where f_geometry_column = '");
269
		strb.append(attr.getName());
270
		strb.append("' and f_table_nam = '");
271
		strb.append(params.getTable());
272
		strb.append("' and f_table_schema = ");
273
		if (params.getSchema() == null || params.getSchema().length() == 0) {
274
			strb.append("current_schema()");
275
		} else {
276
			strb.append("'");
277
			strb.append(params.getSchema());
278
			strb.append("'");
279
		}
280
		if (params.getCatalog() != null && params.getCatalog().length() > 0) {
281
			strb.append(" and f_table_catalog = '");
282
			strb.append(params.getCatalog());
283
			strb.append("'");
284
		}
285
		return strb.toString();
286
	}
287

  
288
	protected String getSqlStatementDropField(FeatureAttributeDescriptor attr,
289
			List<String> additionalStatement) {
290
		String result = super.getSqlStatementDropField(attr,
291
				additionalStatement);
292
		if (attr.getType() == DataTypes.GEOMETRY) {
293
			additionalStatement.add(getSqlGeometyFieldDrop(attr));
294
		}
295
		return result;
296
	}
297

  
298
	protected List<String> getSqlStatementAlterField(
299
			FeatureAttributeDescriptor attrOrg,
300
			FeatureAttributeDescriptor attrTrg, List<String> additionalStatement)
301
			throws DataException {
302
		//
303
		List<String> actions = super.getSqlStatementAlterField(attrOrg, attrTrg,
304
				additionalStatement);
305
		PostgreSQLStoreParameters params = getPGParameters();
306
		if (attrOrg.getDataType() != attrTrg.getDataType()) {
307
			if (attrOrg.getType() == DataTypes.GEOMETRY) {
308
				additionalStatement.add(getSqlGeometyFieldDrop(attrOrg));
309
			}
310
			if (attrTrg.getType() == DataTypes.GEOMETRY) {
311
				additionalStatement.addAll(((PostgreSQLHelper) helper)
312
						.getSqlGeometyFieldAdd(attrTrg, params.getTable(),
313
								params.getSchema()));
314
			}
315
		}
316
		if (attrOrg.getDataType() == attrTrg.getDataType()
317
				&& attrTrg.getType() == DataTypes.GEOMETRY) {
318
			// TODO Checks SRS and GeomType/Subtype
319
		}
320

  
321
		return actions;
322
	}
323
	
324

  
325
	private String getFunctionName(String newFunctionName) {
326
        
327
        PostgreSQLHelper hpr = getPgHelper();
328
        if (hpr == null) {
329
            logger.info("Unable to get PG helper.", new Exception("Helper is null"));
330
            return newFunctionName;
331
        } else {
332
            return hpr.getFunctionName(newFunctionName);
333
        }
334
    }
335
	
336
    private String fixFunctionNames(String _filter) {
337
        
338
        Properties props = this.getPgHelper().getBeforePostgis13Properties();
339
        Iterator iter = props.keySet().iterator();
340
        String kstr = null;
341
        String vstr = null;
342
        
343
        String resp = _filter;
344
        
345
        while (iter.hasNext()) {
346
            kstr = (String) iter.next();
347
            vstr = getPgHelper().getFunctionName(kstr);
348
            resp = replace(resp, kstr, vstr);
349
        }
350
        return resp;
351
    }
352

  
353
    private String replace(String str, String oldstr, String newstr) {
354
        
355
        if (oldstr == null || newstr == null ||
356
            oldstr.length() == 0 || oldstr.equals(newstr)) {
357
            return str;
358
        }
359
        
360
        String lowerstr = str.toLowerCase();
361
        String lowerold = oldstr.toLowerCase();
362
        
363
        if (lowerstr.indexOf(lowerold) == -1) {
364
            // nothing to do
365
            return str;
366
        }
367
        
368
        Pattern p = Pattern.compile(lowerold, Pattern.LITERAL);
369
        String[] parts = p.split(lowerstr); 
370
        
371
        StringBuffer resp = new StringBuffer();
372
        int auxind = 0;
373
        resp.append(str.subSequence(0, parts[0].length()));
374
        for (int i=1; i<parts.length; i++) {
375
            resp.append(newstr);
376
            auxind = getIndex(parts, i-1, oldstr.length());
377
            resp.append(str.subSequence(auxind, auxind + parts[i].length()));
378
        }
379
        return resp.toString();
380
    }
381

  
382
    /**
383
     * This method gets the index where the n-th part (0-based)
384
     * starts in the original string
385
     * 
386
     * @param parts
387
     * @param n
388
     * @param length
389
     * @return
390
     */
391
    private int getIndex(String[] parts, int till_n, int length) {
392
        
393
        int resp = 0;
394
        for (int i=0; i<(till_n+1); i++) {
395
            resp = resp + parts[i].length();
396
            resp = resp + length;
397
        }
398
        return resp;
399
    }
400

  
401
    
402
}
tags/org.gvsig.postgresql-2.0.19/org.gvsig.postgresql.provider/src/main/java/org/gvsig/fmap/dal/store/postgresql/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

  
23
/*
24
* AUTHORS (In addition to CIT):
25
* 2008 IVER T.I. S.A.   {{Task}}
26
*/
27

  
28
package org.gvsig.fmap.dal.store.postgresql;
29

  
30
import org.gvsig.fmap.dal.feature.EditableFeatureType;
31
import org.gvsig.fmap.dal.feature.FeatureType;
32
import org.gvsig.fmap.dal.feature.NewFeatureStoreParameters;
33

  
34
public class PostgreSQLNewStoreParameters extends PostgreSQLStoreParameters
35
		implements NewFeatureStoreParameters {
36

  
37
    public static final String PARAMETERS_DEFINITION_NAME = "PostgreSQLNewStoreParameters";
38

  
39
    public PostgreSQLNewStoreParameters() {
40
    	super(PARAMETERS_DEFINITION_NAME);
41
    }
42
    
43
	public EditableFeatureType getDefaultFeatureType() {
44
		return (EditableFeatureType) this.getDynValue(FEATURETYPE_PARAMTER_NAME);
45
	}
46

  
47
	public void setDefaultFeatureType(FeatureType featureType) {
48
		this.setDynValue(FEATURETYPE_PARAMTER_NAME, featureType);
49
	}
50

  
51
}
tags/org.gvsig.postgresql-2.0.19/org.gvsig.postgresql.provider/src/main/java/org/gvsig/fmap/dal/store/postgresql/PostgreSQLResourceParameters.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
* AUTHORS (In addition to CIT):
25
* 2009 IVER T.I   {{Task}}
26
*/
27

  
28
package org.gvsig.fmap.dal.store.postgresql;
29

  
30
import org.gvsig.fmap.dal.store.jdbc.JDBCResourceParameters;
31

  
32
public class PostgreSQLResourceParameters extends JDBCResourceParameters
33
		implements PostgreSQLConnectionParameters {
34

  
35
	public static final String PARAMETERS_DEFINITION_NAME = "PostgreSQLResourceParameters";
36

  
37
	public PostgreSQLResourceParameters() {
38
		super(PARAMETERS_DEFINITION_NAME,PostgreSQLResource.NAME);
39
	}
40

  
41
    public PostgreSQLResourceParameters(String url, String host, Integer port,
42
			String dbName, String user, String password,
43
			String jdbcDriverClassName, Boolean ssl) {
44
		super(PARAMETERS_DEFINITION_NAME,PostgreSQLResource.NAME,url, host, port, dbName, user, password, jdbcDriverClassName);
45
		if (ssl != null) {
46
			this.setUseSSL(ssl.booleanValue());
47
		}
48
	}
49

  
50
	public String getUrl() {
51
		return PostgreSQLLibrary.getJdbcUrl(getHost(),
52
				getPort(),
53
				getDBName());
54
	}
55

  
56
	public Boolean getUseSSL() {
57
		return (Boolean) this.getDynValue(DYNFIELDNAME_USESSL);
58
	}
59

  
60
	public void setUseSSL(Boolean useSSL) {
61
		this.setDynValue(DYNFIELDNAME_USESSL, useSSL);
62
	}
63

  
64
	public void setUseSSL(boolean useSSL) {
65
		this.setDynValue(DYNFIELDNAME_USESSL, new Boolean(useSSL));
66
	}
67

  
68
}
tags/org.gvsig.postgresql-2.0.19/org.gvsig.postgresql.provider/src/main/java/org/gvsig/fmap/dal/store/postgresql/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
* AUTHORS (In addition to CIT):
25
* 2009 IVER T.I   {{Task}}
26
*/
27

  
28
/**
29
 *
30
 */
31
package org.gvsig.fmap.dal.store.postgresql;
32

  
33
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
34
import org.gvsig.fmap.dal.store.jdbc.JDBCServerExplorerParameters;
35

  
36
public class PostgreSQLServerExplorerParameters extends
37
		JDBCServerExplorerParameters implements PostgreSQLConnectionParameters {
38

  
39

  
40
	public static final String PARAMETERS_DEFINITION_NAME = "PostgreSQLServerExplorerParameters";
41

  
42
	public PostgreSQLServerExplorerParameters() {
43
		super(PARAMETERS_DEFINITION_NAME, PostgreSQLServerExplorer.NAME);
44
	}
45

  
46
	public Boolean getUseSSL() {
47
		return (Boolean) this.getDynValue(DYNFIELDNAME_USESSL);
48
	}
49

  
50
	public void setUseSSL(Boolean useSSL) {
51
		this.setDynValue(DYNFIELDNAME_USESSL, useSSL);
52
	}
53

  
54
	public void setUseSSL(boolean useSSL) {
55
		this.setDynValue(DYNFIELDNAME_USESSL, new Boolean(useSSL));
56
	}
57

  
58
	public void validate() throws ValidateDataParametersException {
59
		if (getJDBCDriverClassName() == null) {
60
			setJDBCDriverClassName(PostgreSQLLibrary.DEFAULT_JDCB_DRIVER_NAME);
61
		}
62
		if (getUrl() == null) {
63
			setUrl(PostgreSQLLibrary.getJdbcUrl(getHost(), getPort(),
64
					getDBName()));
65
		}
66

  
67
		if (getPort() == null) {
68
			setPort(new Integer(5432));
69
		}
70
		super.validate();
71
	}
72

  
73
}
tags/org.gvsig.postgresql-2.0.19/org.gvsig.postgresql.provider/src/main/java/org/gvsig/fmap/dal/store/postgresql/PostgreSQLHelper.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
* AUTHORS (In addition to CIT):
25
* 2009 IVER T.I   {{Task}}
26
*/
27

  
28
/**
29
 *
30
 */
31
package org.gvsig.fmap.dal.store.postgresql;
32

  
33
import java.io.File;
34
import java.io.InputStream;
35
import java.net.URL;
36
import java.sql.Connection;
37
import java.sql.PreparedStatement;
38
import java.sql.ResultSet;
39
import java.sql.ResultSetMetaData;
40
import java.sql.SQLException;
41
import java.sql.Statement;
42
import java.util.ArrayList;
43
import java.util.Comparator;
44
import java.util.Iterator;
45
import java.util.List;
46
import java.util.Map;
47
import java.util.Properties;
48
import java.util.TreeMap;
49
import java.util.TreeSet;
50

  
51
import org.cresques.cts.IProjection;
52
import org.postgresql.PGResultSetMetaData;
53
import org.slf4j.Logger;
54
import org.slf4j.LoggerFactory;
55

  
56
import org.gvsig.fmap.crs.CRSFactory;
57
import org.gvsig.fmap.dal.DALLocator;
58
import org.gvsig.fmap.dal.DataTypes;
59
import org.gvsig.fmap.dal.NewDataStoreParameters;
60
import org.gvsig.fmap.dal.exception.DataException;
61
import org.gvsig.fmap.dal.exception.InitializeException;
62
import org.gvsig.fmap.dal.exception.ReadException;
63
import org.gvsig.fmap.dal.exception.WriteException;
64
import org.gvsig.fmap.dal.feature.EditableFeatureAttributeDescriptor;
65
import org.gvsig.fmap.dal.feature.EditableFeatureType;
66
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
67
import org.gvsig.fmap.dal.feature.FeatureType;
68
import org.gvsig.fmap.dal.feature.exception.CreateGeometryException;
69
import org.gvsig.fmap.dal.feature.exception.UnsupportedDataTypeException;
70
import org.gvsig.fmap.dal.feature.exception.UnsupportedGeometryException;
71
import org.gvsig.fmap.dal.resource.ResourceAction;
72
import org.gvsig.fmap.dal.resource.spi.ResourceManagerProviderServices;
73
import org.gvsig.fmap.dal.store.jdbc.ConnectionAction;
74
import org.gvsig.fmap.dal.store.jdbc.JDBCHelper;
75
import org.gvsig.fmap.dal.store.jdbc.JDBCHelperUser;
76
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParameters;
77
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCException;
78
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCExecutePreparedSQLException;
79
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCExecuteSQLException;
80
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCPreparingSQLException;
81
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCSQLException;
82
import org.gvsig.fmap.geom.Geometry;
83
import org.gvsig.fmap.geom.GeometryLocator;
84
import org.gvsig.fmap.geom.GeometryManager;
85
import org.gvsig.fmap.geom.operation.GeometryOperationException;
86
import org.gvsig.fmap.geom.operation.GeometryOperationNotSupportedException;
87
import org.gvsig.fmap.geom.operation.fromwkb.FromWKB;
88
import org.gvsig.fmap.geom.operation.fromwkb.FromWKBGeometryOperationContext;
89
import org.gvsig.fmap.geom.primitive.Envelope;
90
import org.gvsig.tools.ToolsLocator;
91
import org.gvsig.tools.exception.BaseException;
92

  
93
/**
94
 * @author jmvivo
95
 *
96
 */
97
public class PostgreSQLHelper extends JDBCHelper {
98

  
99
	private static Logger logger = LoggerFactory
100
			.getLogger(PostgreSQLHelper.class);
101

  
102
	private Map pgSR2SRSID = new TreeMap();
103
	private Map srsID2pgSR = new TreeMap();
104
	
105
	private static Properties beforePostgis13 = null;
106
    private int[] postGISVersion = { 0,0,0 };
107
    private boolean versionSet = false;
108

  
109
	PostgreSQLHelper(JDBCHelperUser consumer,
110
			PostgreSQLConnectionParameters params)
111
			throws InitializeException {
112

  
113
		super(consumer, params);
114
	}
115

  
116
	protected void initializeResource() throws InitializeException {
117
		ResourceManagerProviderServices manager = (ResourceManagerProviderServices) DALLocator
118
		.getResourceManager();
119
		PostgreSQLResource resource = (PostgreSQLResource) manager
120
		.createAddResource(
121
				PostgreSQLResource.NAME, new Object[] {
122
						params.getUrl(), params.getHost(),
123
						params.getPort(), params.getDBName(), params.getUser(),
124
						params.getPassword(),
125
						params.getJDBCDriverClassName(),
126
						((PostgreSQLConnectionParameters) params).getUseSSL() });
127
		this.setResource(resource);
128
	}
129

  
130

  
131
	protected String getDefaultSchema(Connection conn)
132
			throws JDBCException {
133
		if (defaultSchema == null) {
134
			String sql = "Select current_schema()";
135
			ResultSet rs = null;
136
			Statement st = null;
137
			String schema = null;
138
			try {
139
				st = conn.createStatement();
140
				try {
141
					rs = st.executeQuery(sql);
142
				} catch (java.sql.SQLException e) {
143
					throw new JDBCExecuteSQLException(sql, e);
144
				}
145
				rs.next();
146
				schema = rs.getString(1);
147
			} catch (java.sql.SQLException e) {
148
				throw new JDBCSQLException(e);
149
			} finally {
150
				try {rs.close();} catch (Exception e) {logger.error("Exception clossing resulset", e);};
151
				try {st.close();} catch (Exception e) {logger.error("Exception clossing statement", e);};
152
				rs = null;
153
				st = null;
154
			}
155
			defaultSchema = schema;
156
		}
157

  
158
		return defaultSchema;
159
	}
160

  
161
	public Envelope getFullEnvelopeOfField(
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff