Revision 156

View differences:

tags/org.gvsig.postgresql-2.0.36/org.gvsig.postgresql.provider/src/main/resources/org/gvsig/fmap/dal/store/postgresql/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="JDBC" 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.36/org.gvsig.postgresql.provider/src/main/resources/org/gvsig/fmap/dal/store/postgresql/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>JDBCResourceParameters</class>
8
      </extends>
9
      <fields>
10
        <field name="JDBCDriverClass" type="string" mandatory="true"
11
          defaultValue="org.postgresql.Driver" group="Advanced">
12
          <description>JDBC Driver class</description>
13
        </field>
14
		<field name="port" type="integer" mandatory="false"
15
          defaultValue="5432" group="Connection">
16
          <description></description>
17
        </field>
18
        <field name="UseSSL" type="boolean" mandatory="false"
19
          defaultValue="false" group="Basic">
20
          <description>Use SSL connetion</description>
21
        </field>
22
      </fields>
23
    </class>
24

  
25
    <class name="PostgreSQLStoreParameters">
26
      <extends>
27
        <class>JDBCStoreParameters</class>
28
        <class>PostgreSQLResourceParameters</class>
29
      </extends>
30
      <fields/>
31
    </class>
32

  
33
    <class name="PostgreSQLNewStoreParameters">
34
      <extends>
35
        <class>JDBCNewStoreParameters</class>
36
        <class>PostgreSQLResourceParameters</class>
37
      </extends>
38
      <fields/>
39
    </class>
40

  
41

  
42
    <class name="PostgreSQLServerExplorerParameters">
43
      <extends>
44
        <class>PostgreSQLResourceParameters</class>
45
        <class>JDBCServerExplorerParameters</class>
46
      </extends>
47
      <fields/>
48
    </class>
49

  
50

  
51
  </classes>
52
</definitions>  
tags/org.gvsig.postgresql-2.0.36/org.gvsig.postgresql.provider/src/main/resources/META-INF/services/org.gvsig.tools.library.Library
1
org.gvsig.fmap.dal.store.postgresql.PostgreSQLLibrary
tags/org.gvsig.postgresql-2.0.36/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.JDBCException;
43
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCSQLException;
44
import org.slf4j.Logger;
45
import org.slf4j.LoggerFactory;
46

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

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

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

  
60
	public String getName() throws AccessResourceException {
61
		PostgreSQLResourceParameters params = (PostgreSQLResourceParameters) this.getParameters();
62
		return MessageFormat.format("PostgreSQLResource({0},{1})",
63
				new Object[] { params.getUrl(),params.getUser() });
64
	}
65
        
66
        public String toString() {
67
            try {
68
                return this.getName();
69
            } catch(Exception ex) {
70
                return super.toString();
71
            }
72
        }
73

  
74
	protected void connectToDB() throws DataException {
75
		if (this.dataSource != null) {
76
			return;
77
		}
78
		JDBCResourceParameters jdbcParams = (JDBCResourceParameters) this
79
				.getParameters();
80
		BasicDataSource dataSource = new BasicDataSource();
81
		dataSource.setDriverClassName(jdbcParams.getJDBCDriverClassName());
82
		dataSource.setUsername(jdbcParams.getUser());
83
		dataSource.setPassword(jdbcParams.getPassword());
84
		dataSource.setUrl(jdbcParams.getUrl());
85

  
86
		dataSource.setMaxWait(60L * 1000); // FIXME
87

  
88
		// FIXME Set Pool parameters:
89
		/*
90
		dataSource.setMaxActive(maxActive);
91
		dataSource.setMaxIdle(maxActive);
92
		dataSource.setMaxOpenPreparedStatements(maxActive);
93
		dataSource.setMaxWait(maxActive);
94
		dataSource.setInitialSize(initialSize);
95
		dataSource.setDefaultReadOnly(defaultReadOnly);
96
		dataSource.setDefaultTransactionIsolation(defaultTransactionIsolation);
97
		dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
98
		dataSource.setMinIdle(minIdle);
99
		dataSource.setTestOnBorrow(testOnBorrow);
100
		dataSource.setTestOnReturn(testOnReturn);
101
		dataSource.setTestWhileIdle(testOnReturn);
102
		dataSource
103
				.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
104

  
105
		dataSource.setAccessToUnderlyingConnectionAllowed(allow);
106
		dataSource.setLoginTimeout(seconds);
107
		dataSource.setLogWriter(out);
108
		*/
109

  
110
		this.dataSource = dataSource;
111
	}	
112
	protected void registerJDBCDriver() throws InitializeException {
113
		String className = ((JDBCResourceParameters) getParameters())
114
				.getJDBCDriverClassName();
115
		if (className == null) {
116
			return;
117
		}
118

  
119
		Class theClass = null;
120
		try {
121
			theClass = Class.forName(className);
122
		} catch (Exception e){
123
			throw new InitializeException(e);
124
		}
125
		if (theClass == null) {
126
			try {
127
				throw new JDBCDriverClassNotFoundException(this.getName(),
128
						className);
129
			} catch (AccessResourceException e) {
130
				throw new InitializeException(e);
131

  
132
			}
133
		}
134
	}
135
	
136
	protected DataSource createDataSource() {
137
		PostgreSQLResourceParameters jdbcParams = (PostgreSQLResourceParameters) this
138
				.getParameters();
139
		BasicDataSource dataSource = new BasicDataSource();
140
		dataSource.setDriverClassName(jdbcParams.getJDBCDriverClassName());
141
		dataSource.setUsername(jdbcParams.getUser());
142
		dataSource.setPassword(jdbcParams.getPassword());
143
		dataSource.setUrl(jdbcParams.getUrl());
144

  
145
		dataSource.setMaxWait(60L * 1000); // FIXME
146

  
147
		// FIXME Set Pool parameters:
148
		/*
149
		dataSource.setMaxActive(maxActive);
150
		dataSource.setMaxIdle(maxActive);
151
		dataSource.setMaxOpenPreparedStatements(maxActive);
152
		dataSource.setMaxWait(maxActive);
153
		dataSource.setInitialSize(initialSize);
154
		dataSource.setDefaultReadOnly(defaultReadOnly);
155
		dataSource.setDefaultTransactionIsolation(defaultTransactionIsolation);
156
		dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
157
		dataSource.setMinIdle(minIdle);
158
		dataSource.setTestOnBorrow(testOnBorrow);
159
		dataSource.setTestOnReturn(testOnReturn);
160
		dataSource.setTestWhileIdle(testOnReturn);
161
		dataSource
162
			.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
163

  
164
		dataSource.setAccessToUnderlyingConnectionAllowed(allow);
165
		dataSource.setLoginTimeout(seconds);
166
		dataSource.setLogWriter(out);
167
		 */
168
		return dataSource;
169
	}
170
	
171
	
172
	public boolean isConnected() {
173
		if (dataSource == null) {
174
			return false;
175
		}
176
		if (dataSource instanceof BasicDataSource) {
177
			return ((BasicDataSource) dataSource).getNumActive() > 0
178
					|| ((BasicDataSource) dataSource).getNumIdle() > 0;
179
		}
180
		return true;
181
	}	
182
	
183
	private void logPoolStatus(String src) {
184
		if (logger.isDebugEnabled() ) {
185
			logger.debug(src + "  " + this.getStatusInformation());
186
		}
187

  
188
	}
189
        
190
        public String getStatusInformation() {
191
		if ( !(dataSource instanceof BasicDataSource) ) {
192
                    return "Connected: " + this.isConnected();
193
                }
194
        	BasicDataSource ds = (BasicDataSource) dataSource;
195
                String s = "Connected: " + this.isConnected() + ", " +
196
                        "actives: "+ ds.getNumActive() + "/"+ ds.getMaxActive() + ", " + 
197
                        "idle: " + ds.getNumIdle() + "/"+ ds.getMaxIdle() ;
198
                return s;
199
        }
200

  
201
        
202

  
203
        private static class CanGetConnectionException extends JDBCSQLException {
204
            public CanGetConnectionException(String datasource, SQLException cause) {
205
                super("Can't get a connection to the data source (%(datasource))", cause, "_CanGetConnectionException", 0);
206
                setValue("datasource", datasource);
207
            }
208
        }
209
    
210
	protected synchronized Object getTheConnection() throws DataException {
211
		try {
212
			Object conn = this.dataSource.getConnection();
213
			logPoolStatus("getTheConnection");
214
			return conn;
215
		} catch (SQLException e) {
216
			throw new CanGetConnectionException(this.toString(),e);
217
		}
218
	}	
219

  
220
}
tags/org.gvsig.postgresql-2.0.36/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
package org.gvsig.fmap.dal.store.postgresql;
31

  
32
import java.sql.Connection;
33
import java.sql.SQLException;
34
import java.sql.Statement;
35
import java.util.ArrayList;
36
import java.util.Iterator;
37
import java.util.List;
38
import java.util.logging.Level;
39

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

  
57
/**
58
 * @author jmvivo
59
 *
60
 */
61
public class PostgreSQLServerExplorer extends JDBCServerExplorer {
62

  
63
    final static private Logger logger = LoggerFactory
64
            .getLogger(PostgreSQLServerExplorer.class);
65

  
66
    public static final String NAME = "PostgreSQLExplorer";
67

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

  
75
    private PostgreSQLServerExplorerParameters getPostgreSQLParameters() {
76
        return (PostgreSQLServerExplorerParameters) getParameters();
77
    }
78

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

  
83
    public 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
    public boolean canAdd() {
103
        return true;
104
    }
105

  
106
    public DataStoreParameters getOpenParameters() throws DataException {
107
        PostgreSQLServerExplorerParameters parameters = getPostgreSQLParameters();
108
        PostgreSQLStoreParameters params = new PostgreSQLStoreParameters();
109
        params.setHost(parameters.getHost());
110
        params.setPort(parameters.getPort());
111
        params.setDBName(parameters.getDBName());
112
        params.setUser(parameters.getUser());
113
        params.setPassword(parameters.getPassword());
114
        params.setCatalog(parameters.getCatalog());
115
        params.setSchema(parameters.getSchema());
116
        params.setJDBCDriverClassName(parameters.getJDBCDriverClassName());
117
        params.setUrl(parameters.getUrl());
118
        return params;
119
    }
120

  
121
    protected void checkIsMine(DataStoreParameters dsp) {
122
        if (!(dsp instanceof PostgreSQLConnectionParameters)) {
123
            // FIXME Excpetion ???
124
            throw new IllegalArgumentException(
125
                    "not instance of PostgreSQLStoreParameters");
126
        }
127
        super.checkIsMine(dsp);
128

  
129
        PostgreSQLConnectionParameters pgp = (PostgreSQLConnectionParameters) dsp;
130
        if (pgp.getUseSSL().booleanValue() != getPostgreSQLParameters()
131
                .getUseSSL()) {
132
            throw new IllegalArgumentException("worng explorer: Host");
133
        }
134
    }
135

  
136
    public void remove(DataStoreParameters dsp) throws RemoveException {
137
        final PostgreSQLStoreParameters pgParams = (PostgreSQLStoreParameters) dsp;
138

  
139
        TransactionalAction action = new TransactionalAction() {
140
            public boolean continueTransactionAllowed() {
141
                return false;
142
            }
143

  
144
            public Object action(Connection conn) throws DataException {
145

  
146
                Statement st;
147
                try {
148
                    st = conn.createStatement();
149
                } catch (SQLException e) {
150
                    throw new JDBCSQLException(e);
151
                }
152

  
153
                String sqlDrop = "Drop table "
154
                        + pgParams.tableID();
155

  
156
                StringBuilder strb = new StringBuilder();
157
                strb.append("Delete from GEOMETRY_COLUMNS where f_table_schema = ");
158
                if (pgParams.getSchema() == null || pgParams.getSchema().length() == 0) {
159
                    strb.append("current_schema() ");
160
                } else {
161
                    strb.append('\'');
162
                    strb.append(pgParams.getSchema());
163
                    strb.append("' ");
164
                }
165
                strb.append("and f_table_name = '");
166
                strb.append(pgParams.getTable());
167
                strb.append('\'');
168

  
169
                String sqlDeleteFromGeometry_column = strb.toString();
170
                try {
171
                    try {
172
                        JDBCHelper.execute(st, sqlDrop);
173
                    } catch (SQLException e) {
174
                        throw new JDBCExecuteSQLException(sqlDrop, e);
175
                    }
176

  
177
                    try {
178
                        JDBCHelper.execute(st, sqlDeleteFromGeometry_column);
179
                    } catch (SQLException e) {
180
                        throw new JDBCExecuteSQLException(
181
                                sqlDeleteFromGeometry_column, e);
182
                    }
183

  
184
                } finally {
185
                    try {
186
                        st.close();
187
                    } catch (SQLException e) {
188
                    };
189
                }
190
                return null;
191
            }
192
        };
193
        try {
194
            this.helper.doConnectionAction(action);
195
        } catch (Exception e) {
196
            throw new RemoveException(this.getProviderName(), e);
197
        }
198
    }
199

  
200
    public NewDataStoreParameters getAddParameters() throws DataException {
201
        PostgreSQLServerExplorerParameters parameters = getPostgreSQLParameters();
202
        PostgreSQLNewStoreParameters params = new PostgreSQLNewStoreParameters();
203
        params.setHost(parameters.getHost());
204
        params.setPort(parameters.getPort());
205
        params.setDBName(parameters.getDBName());
206
        params.setUser(parameters.getUser());
207
        params.setPassword(parameters.getPassword());
208
        params.setCatalog(parameters.getCatalog());
209
        params.setSchema(parameters.getSchema());
210
        params.setJDBCDriverClassName(parameters.getJDBCDriverClassName());
211
        params.setUrl(parameters.getUrl());
212
        params.setUseSSL(parameters.getUseSSL());
213

  
214
        params.setDefaultFeatureType(this.getServerExplorerProviderServices()
215
                .createNewFeatureType());
216

  
217
        return params;
218
    }
219

  
220
    public boolean hasGeometrySupport() {
221
        return true;
222
    }
223

  
224
    protected PostgreSQLHelper getPgHelper() {
225
        return (PostgreSQLHelper) getHelper();
226
    }
227

  
228
    @Override
229
    public List getDataStoreProviderNames() {
230
        List x = new ArrayList(1);
231
        x.add(PostgreSQLStoreProvider.NAME);
232
        return x;
233
    }
234

  
235
    public void updateTableStatistics(String tableName) throws JDBCExecuteSQLException {
236
        String sql="";
237
        if( tableName.startsWith("\"") ) {
238
            sql = "VACUUM ANALYZE " + tableName ;
239
        } else {
240
            sql = "VACUUM ANALYZE \"" + tableName + "\"";
241
        }
242
        this.getHelper().execute(sql);
243
    }
244

  
245
}
tags/org.gvsig.postgresql-2.0.36/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.util.Iterator;
31
import java.util.List;
32
import java.util.Properties;
33
import java.util.regex.Matcher;
34
import java.util.regex.Pattern;
35

  
36
import org.gvsig.fmap.dal.DALLocator;
37
import org.gvsig.fmap.dal.DataManager;
38
import org.gvsig.fmap.dal.DataServerExplorer;
39
import org.gvsig.fmap.dal.DataTypes;
40
import org.gvsig.fmap.dal.exception.DataException;
41
import org.gvsig.fmap.dal.exception.InitializeException;
42
import org.gvsig.fmap.dal.exception.ReadException;
43
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
44
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
45
import org.gvsig.fmap.dal.feature.FeatureQuery;
46
import org.gvsig.fmap.dal.feature.FeatureType;
47
import org.gvsig.fmap.dal.feature.spi.FeatureProvider;
48
import org.gvsig.fmap.dal.feature.spi.FeatureSetProvider;
49
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
50
import org.gvsig.fmap.dal.store.db.DBHelper;
51
import org.gvsig.fmap.dal.store.jdbc.JDBCHelper;
52
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreProviderWriter;
53
import org.gvsig.fmap.geom.Geometry;
54
import org.slf4j.Logger;
55
import org.slf4j.LoggerFactory;
56

  
57
public class PostgreSQLStoreProvider extends JDBCStoreProviderWriter {
58

  
59
	public final static Logger logger = LoggerFactory
60
			.getLogger(PostgreSQLStoreProvider.class);
61

  
62
	public static final String NAME = "PostgreSQL";
63
	public static final String DESCRIPTION = "PostgreSQL source";
64

  
65
	public static final String METADATA_DEFINITION_NAME = NAME;
66
	
67
	public PostgreSQLStoreProvider(PostgreSQLStoreParameters params,
68
			DataStoreProviderServices storeServices)
69
			throws InitializeException {
70
		super(params, storeServices, DBHelper.newMetadataContainer(METADATA_DEFINITION_NAME));
71
	}
72

  
73
	private PostgreSQLStoreParameters getPGParameters() {
74
		return (PostgreSQLStoreParameters) this.getParameters();
75
	}
76

  
77
	protected JDBCHelper createHelper() throws InitializeException {
78
	    JDBCHelper resp = new PostgreSQLHelper(this, getPGParameters());
79
	    
80
	    return resp;
81
	}
82

  
83

  
84

  
85
	protected String fixFilter(String _filter) {
86
		if (_filter == null) {
87
			return null;
88
		}
89
		
90
		String filter = fixFunctionNames(_filter);
91

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

  
115
		}
116
		strb.append(filter.substring(pos));
117

  
118
		return strb.toString();
119
	}
120

  
121

  
122
    public String getName() {
123
		return NAME;
124
	}
125

  
126
	public FeatureSetProvider createSet(FeatureQuery query,
127
			FeatureType featureType) throws DataException {
128

  
129
		return new PostgreSQLSetProvider(this, query, featureType);
130
	}
131

  
132

  
133
	public DataServerExplorer getExplorer() throws ReadException {
134
		DataManager manager = DALLocator.getDataManager();
135
		PostgreSQLServerExplorerParameters exParams;
136
		PostgreSQLStoreParameters params = getPGParameters();
137
		try {
138
			exParams = (PostgreSQLServerExplorerParameters) manager
139
					.createServerExplorerParameters(PostgreSQLServerExplorer.NAME);
140
			exParams.setUrl(params.getUrl());
141
			exParams.setHost(params.getHost());
142
			exParams.setPort(params.getPort());
143
			exParams.setDBName(params.getDBName());
144
			exParams.setUser(params.getUser());
145
			exParams.setPassword(params.getPassword());
146
			exParams.setCatalog(params.getCatalog());
147
			exParams.setSchema(params.getSchema());
148
			exParams.setJDBCDriverClassName(params.getJDBCDriverClassName());
149
			exParams.setUseSSL(params.getUseSSL());
150

  
151
			return manager.openServerExplorer(PostgreSQLServerExplorer.NAME, exParams);
152
		} catch (DataException e) {
153
			throw new ReadException(this.getName(), e);
154
		} catch (ValidateDataParametersException e) {
155
			throw new ReadException(this.getName(), e);
156
		}
157
	}
158

  
159
	public boolean allowAutomaticValues() {
160
		return true;
161
	}
162

  
163

  
164
	public boolean hasGeometrySupport() {
165
		return true;
166
	}
167

  
168

  
169
	protected PostgreSQLHelper getPgHelper() {
170
		return (PostgreSQLHelper) getHelper();
171
	}
172

  
173

  
174

  
175
	public boolean canWriteGeometry(int geometryType, int geometrySubtype)
176
			throws DataException {
177
		FeatureType type = getFeatureStore().getDefaultFeatureType();
178
		FeatureAttributeDescriptor geomAttr = type.getAttributeDescriptor(type
179
								.getDefaultGeometryAttributeName());
180
		if (geomAttr == null) {
181
			return false;
182
		}
183
		if (geometrySubtype != geomAttr.getGeometrySubType()) {
184
			return false;
185
		}
186
		switch (geomAttr.getGeometryType()) {
187
		case Geometry.TYPES.GEOMETRY:
188
			return true;
189

  
190
		case Geometry.TYPES.MULTISURFACE:
191
			return geometryType == Geometry.TYPES.MULTISURFACE
192
					|| geometryType == Geometry.TYPES.SURFACE;
193

  
194
		case Geometry.TYPES.MULTIPOINT:
195
			return geometryType == Geometry.TYPES.MULTIPOINT
196
					|| geometryType == Geometry.TYPES.POINT;
197

  
198
		case Geometry.TYPES.MULTICURVE:
199
			return geometryType == Geometry.TYPES.MULTICURVE
200
					|| geometryType == Geometry.TYPES.CURVE;
201

  
202
		case Geometry.TYPES.MULTISOLID:
203
			return geometryType == Geometry.TYPES.MULTISOLID
204
					|| geometryType == Geometry.TYPES.SOLID;
205

  
206
		default:
207
			return geometryType == geomAttr.getGeometryType();
208
		}
209

  
210
	}
211

  
212

  
213
	protected void addToListFeatureValues(FeatureProvider featureProvider,
214
			FeatureAttributeDescriptor attrOfList,
215
			FeatureAttributeDescriptor attr,
216
			List<Object> values) throws DataException {
217

  
218
		super.addToListFeatureValues(featureProvider, attrOfList, attr, values);
219
		if (attr.getType() == DataTypes.GEOMETRY) {
220
			values.add(helper.getProviderSRID(attr.getSRS()));
221
		}
222
	}
223

  
224
	protected void prepareAttributeForInsert(
225
			FeatureAttributeDescriptor attr, List<String> fields, List<String> values) {
226

  
227
		if (attr.getType() == DataTypes.GEOMETRY) {
228
			fields.add(helper.escapeFieldName(attr.getName()));
229
			values.add(getFunctionName("ST_GeomFromWKB") + "(?,?)");
230
		} else {
231
			super.prepareAttributeForInsert(attr, fields, values);
232
		}
233

  
234
	}
235

  
236
	protected void prepareAttributeForUpdate(FeatureAttributeDescriptor attr,
237
			List<String> values) {
238
		if (attr.getType() == DataTypes.GEOMETRY) {
239
			values.add(helper.escapeFieldName(attr.getName())
240
					+ " = " + getFunctionName("ST_GeomFromWKB") + "(?,?)");
241
		} else {
242
			super.prepareAttributeForUpdate(attr, values);
243
		}
244
	}
245

  
246
	protected String getSqlStatementAddField(FeatureAttributeDescriptor attr,
247
			List<String> additionalStatement) throws DataException {
248
		if (attr.getType() == DataTypes.GEOMETRY) {
249
			PostgreSQLStoreParameters params = getPGParameters();
250
			additionalStatement.addAll(	((PostgreSQLHelper) helper)
251
					.getSqlGeometyFieldAdd(attr, params.getTable(), params
252
							.getSchema()));
253

  
254
		}
255
		return super.getSqlStatementAddField(attr, additionalStatement);
256

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

  
281
	protected String getSqlStatementDropField(FeatureAttributeDescriptor attr,
282
			List<String> additionalStatement) {
283
		String result = super.getSqlStatementDropField(attr,
284
				additionalStatement);
285
		if (attr.getType() == DataTypes.GEOMETRY) {
286
			additionalStatement.add(getSqlGeometyFieldDrop(attr));
287
		}
288
		return result;
289
	}
290

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

  
314
		return actions;
315
	}
316
	
317

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

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

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

  
394
    
395
}
tags/org.gvsig.postgresql-2.0.36/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
package org.gvsig.fmap.dal.store.postgresql;
23

  
24
import org.gvsig.fmap.dal.feature.EditableFeatureType;
25
import org.gvsig.fmap.dal.feature.FeatureType;
26
import org.gvsig.fmap.dal.feature.NewFeatureStoreParameters;
27
import org.gvsig.fmap.dal.store.jdbc.JDBCNewStoreParameters;
28

  
29
public class PostgreSQLNewStoreParameters extends JDBCNewStoreParameters
30
        implements NewFeatureStoreParameters, PostgreSQLConnectionParameters {
31

  
32
    public static final String PARAMETERS_DEFINITION_NAME = "PostgreSQLNewStoreParameters";
33

  
34
    public PostgreSQLNewStoreParameters() {
35
        super(PARAMETERS_DEFINITION_NAME, PostgreSQLStoreProvider.NAME);
36
    }
37

  
38
    public EditableFeatureType getDefaultFeatureType() {
39
        return (EditableFeatureType) this.getDynValue(FEATURETYPE_PARAMTER_NAME);
40
    }
41

  
42
    public void setDefaultFeatureType(FeatureType featureType) {
43
        this.setDynValue(FEATURETYPE_PARAMTER_NAME, featureType);
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
}
tags/org.gvsig.postgresql-2.0.36/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.36/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.36/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.sql.Connection;
34
import java.sql.PreparedStatement;
35
import java.sql.ResultSet;
36
import java.sql.ResultSetMetaData;
37
import java.sql.SQLException;
38
import java.sql.Statement;
39
import java.util.ArrayList;
40
import java.util.Comparator;
41
import java.util.Iterator;
42
import java.util.List;
43
import java.util.Map;
44
import java.util.Properties;
45
import java.util.TreeMap;
46
import java.util.TreeSet;
47

  
48
import org.cresques.cts.IProjection;
49
import org.postgresql.PGResultSetMetaData;
50
import org.slf4j.Logger;
51
import org.slf4j.LoggerFactory;
52

  
53
import org.gvsig.fmap.crs.CRSFactory;
54
import org.gvsig.fmap.dal.DALLocator;
55
import org.gvsig.fmap.dal.DataTypes;
56
import org.gvsig.fmap.dal.NewDataStoreParameters;
57
import org.gvsig.fmap.dal.exception.DataException;
58
import org.gvsig.fmap.dal.exception.InitializeException;
59
import org.gvsig.fmap.dal.exception.ReadException;
60
import org.gvsig.fmap.dal.exception.WriteException;
61
import org.gvsig.fmap.dal.feature.EditableFeatureAttributeDescriptor;
62
import org.gvsig.fmap.dal.feature.EditableFeatureType;
63
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
64
import org.gvsig.fmap.dal.feature.FeatureType;
65
import org.gvsig.fmap.dal.feature.exception.CreateGeometryException;
66
import org.gvsig.fmap.dal.feature.exception.UnsupportedDataTypeException;
67
import org.gvsig.fmap.dal.resource.ResourceAction;
68
import org.gvsig.fmap.dal.resource.spi.ResourceManagerProviderServices;
69
import org.gvsig.fmap.dal.store.jdbc.ConnectionAction;
70
import org.gvsig.fmap.dal.store.jdbc.JDBCHelper;
71
import org.gvsig.fmap.dal.store.jdbc.JDBCHelperUser;
72
import org.gvsig.fmap.dal.store.jdbc.JDBCNewStoreParameters;
73
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParameters;
74
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCException;
75
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCExecutePreparedSQLException;
76
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCExecuteSQLException;
77
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCPreparingSQLException;
78
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCSQLException;
79
import org.gvsig.fmap.geom.Geometry;
80
import org.gvsig.fmap.geom.primitive.Envelope;
81
import org.gvsig.tools.ToolsLocator;
82
import org.gvsig.tools.exception.BaseException;
83

  
84
/**
85
 * @author jmvivo
86
 *
87
 */
88
public class PostgreSQLHelper extends JDBCHelper {
89

  
90
	private static Logger logger = LoggerFactory
91
			.getLogger(PostgreSQLHelper.class);
92

  
93
	private Map pgSR2SRSID = new TreeMap();
94
	private Map srsID2pgSR = new TreeMap();
95
	
96
	private static Properties beforePostgis13 = null;
97
    private int[] postGISVersion = { 0,0,0 };
98
    private boolean versionSet = false;
99

  
100
	PostgreSQLHelper(JDBCHelperUser consumer,
101
			PostgreSQLConnectionParameters params)
102
			throws InitializeException {
103

  
104
		super(consumer, params);
105
	}
106

  
107
	protected void initializeResource() throws InitializeException {
108
		ResourceManagerProviderServices manager = (ResourceManagerProviderServices) DALLocator
109
		.getResourceManager();
110
		PostgreSQLResource resource = (PostgreSQLResource) manager
111
		.createAddResource(
112
				PostgreSQLResource.NAME, new Object[] {
113
						params.getUrl(), params.getHost(),
114
						params.getPort(), params.getDBName(), params.getUser(),
115
						params.getPassword(),
116
						params.getJDBCDriverClassName(),
117
						((PostgreSQLConnectionParameters) params).getUseSSL() });
118
		this.setResource(resource);
119
	}
120

  
121

  
122
	protected String getDefaultSchema(Connection conn)
123
			throws JDBCException {
124
		if (defaultSchema == null) {
125
			String sql = "Select current_schema()";
126
			ResultSet rs = null;
127
			Statement st = null;
128
			String schema = null;
129
			try {
130
				st = conn.createStatement();
131
				try {
132
					rs = JDBCHelper.executeQuery(st, sql); 
133
				} catch (java.sql.SQLException e) {
134
					throw new JDBCExecuteSQLException(sql, e);
135
				}
136
				rs.next();
137
				schema = rs.getString(1);
138
			} catch (java.sql.SQLException e) {
139
				throw new JDBCSQLException(e);
140
			} finally {
141
				try {rs.close();} catch (Exception e) {logger.error("Exception clossing resulset", e);};
142
				try {st.close();} catch (Exception e) {logger.error("Exception clossing statement", e);};
143
				rs = null;
144
				st = null;
145
			}
146
			defaultSchema = schema;
147
		}
148

  
149
		return defaultSchema;
150
	}
151

  
152
    public Envelope getFullEnvelopeOfField(
153
            JDBCStoreParameters storeParams,
154
            String geometryAttrName, Envelope limit)
155
            throws DataException {
156

  
157
        StringBuilder strb = new StringBuilder();
158
        strb.append("Select " + getFunctionName("ST_AsBinary") + "("
159
                + getFunctionName("ST_Extent") + "(");
160
        strb.append(escapeFieldName(geometryAttrName));
161
        strb.append(")) from ");
162

  
163
        if (storeParams.getSQL() != null
164
                && storeParams.getSQL().trim().length() > 0) {
165
            strb.append('(');
166
            strb.append(storeParams.getSQL());
167
            strb.append(") as _subquery_alias_ ");
168
        } else {
169
            strb.append(storeParams.tableID());
170
        }
171

  
172
        if (limit != null || (storeParams.getBaseFilter() != null
173
                && storeParams.getBaseFilter().trim().length() > 0)) {
174
            strb.append(" where  ");
175

  
176
            if (limit != null) {
177
                strb.append(" ( " + getFunctionName("ST_Intersects") + "("
178
                        + getFunctionName("ST_GeomFromText") + "('");
179
                String workAreaWkt = null;
180
                try {
181
                    workAreaWkt = limit.getGeometry().convertToWKT();
182
                } catch (Exception e) {
183
                    throw new CreateGeometryException(e);
184
                }
185
                strb.append(workAreaWkt);
186
                strb.append("', ");
187

  
188
                IProjection proj = storeParams.getCRS();
189
                int sridInt = this.getProviderSRID(proj);
190
                if (sridInt == -1) {
191
                    throw new CreateGeometryException(
192
                            new Exception("CRS is null or unknown."));
193
                } else {
194
                    strb.append(Integer.toString(sridInt));
195
                }
196
                strb.append("), " + getFunctionName("ST_Envelope") + "(");
197
                strb.append(escapeFieldName(geometryAttrName));
198
                strb.append(")) ) ");
199

  
200
            }
201
            if (storeParams.getBaseFilter() != null && storeParams.getBaseFilter().trim().length() > 0) {
202
                if (limit != null) {
203
                    strb.append(" and ");
204
                }
205
                strb.append(" ( ");
206
                strb.append(storeParams.getBaseFilter());
207
                strb.append(" ) ");
208
            }
209

  
210
        }
211

  
212
        final String sql = strb.toString();
213

  
214
        this.open();
215

  
216
        return (Envelope) getResource().execute(new ResourceAction() {
217
            public String toString() {
218
                return "getEnvelope";
219
            }
220

  
221
            public Object run() throws Exception {
222
                ResultSet rs = null;
223
                Statement st = null;
224
                Connection conn = null;
225
                Envelope fullEnvelope = null;
226

  
227
                Envelope emptyEnv
228
                        = geomManager.createEnvelope(Geometry.SUBTYPES.GEOM2D);
229

  
230
                try {
231

  
232
                    conn = getConnection();
233
                    st = conn.createStatement();
234
                    try {
235
                        rs = JDBCHelper.executeQuery(st, sql);
236
                    } catch (java.sql.SQLException e) {
237
                        throw new JDBCExecuteSQLException(sql, e);
238
                    }
239
                    if (!rs.next()) {
240
                        return emptyEnv;
241
                    }
242

  
243
                    byte[] data = rs.getBytes(1);
244
                    if (data == null) {
245
                        return emptyEnv;
246
                    }
247

  
248
                    Geometry geom = geomManager.createFrom(data);
249

  
250
                    fullEnvelope = geom.getEnvelope();
251

  
252
                    return fullEnvelope;
253
                } catch (java.sql.SQLException e) {
254
                    throw new JDBCSQLException(e);
255
                } catch (BaseException e) {
256
                    throw new ReadException(user.getProviderName(), e);
257
                } finally {
258
                    try {
259
                        rs.close();
260
                    } catch (Exception e) {
261
                    }
262
                    try {
263
                        st.close();
264
                    } catch (Exception e) {
265
                    }
266
                    try {
267
                        conn.close();
268
                    } catch (Exception e) {
269
                    }
270
                    rs = null;
271
                    st = null;
272
                    conn = null;
273
                }
274
            }
275
        });
276
    }
277

  
278
	@Override
279
	protected boolean supportsGeometry() {
280
		return true;
281
	}
282

  
283
	/**
284
	 * Fill <code>featureType</code> geometry attributes with SRS and ShapeType
285
	 * information stored in the table GEOMETRY_COLUMNS
286
	 *
287
	 * @param conn
288
	 * @param rsMetadata
289
	 * @param featureType
290
	 * @throws ReadException
291
	 */
292
	protected void loadSRS_and_shapeType(Connection conn,
293
			ResultSetMetaData rsMetadata, EditableFeatureType featureType,
294
			String baseSchema, String baseTable)
295
			throws JDBCException {
296

  
297
		Statement st = null;
298
		ResultSet rs = null;
299
		try {
300
			// Sacamos la lista de los attributos geometricos
301
			EditableFeatureAttributeDescriptor attr;
302
			List geoAttrs = new ArrayList();
303

  
304
			Iterator iter = featureType.iterator();
305
			while (iter.hasNext()) {
306
				attr = (EditableFeatureAttributeDescriptor) iter.next();
307
				if (attr.getType() == DataTypes.GEOMETRY) {
308
					geoAttrs.add(attr);
309
				}
310
			}
311
			if (geoAttrs.size() < 1) {
312
				return;
313
			}
314

  
315

  
316
			// preparamos un set con las lista de tablas de origen
317
			// de los campos
318
			class TableId {
319
				public String schema=null;
320
				public String table=null;
321
				public String field = null;
322

  
323
				public void appendToSQL(StringBuilder strb) {
324
					if (schema == null || schema.length() == 0) {
325
						strb
326
								.append("( F_TABLE_SCHEMA = current_schema() AND F_TABLE_NAME = '");
327
					} else {
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff