Revision 206

View differences:

tags/org.gvsig.postgresql-2.0.46/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.46</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.122</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.46</connection>
20
      <developerConnection>scm:svn:https://devel.gvsig.org/svn/gvsig-postgresql/tags/org.gvsig.postgresql-2.0.46</developerConnection>
21
      <url>https://devel.gvsig.org/redmine/projects/gvsig-postgresql/repository/show/tags/org.gvsig.postgresql-2.0.46</url>
22
  </scm>
23

  
24
    <repositories>
25
        <repository>
26
            <id>gvsig-public-http-repository</id>
27
            <name>gvSIG maven public HTTP repository</name>
28
            <url>http://devel.gvsig.org/m2repo/j2se</url>
29
            <releases>
30
                <enabled>true</enabled>
31
                <updatePolicy>daily</updatePolicy>
32
                <checksumPolicy>warn</checksumPolicy>
33
            </releases>
34
            <snapshots>
35
                <enabled>true</enabled>
36
                <updatePolicy>daily</updatePolicy>
37
                <checksumPolicy>warn</checksumPolicy>
38
            </snapshots>
39
        </repository>
40
    </repositories>
41
  
42
  
43
	<build>
44
		<plugins>
45
			<plugin>
46
				<groupId>org.apache.maven.plugins</groupId>
47
				<artifactId>maven-release-plugin</artifactId>
48
				<configuration>
49
					<tagBase>https://devel.gvsig.org/svn/gvsig-postgresql/tags/</tagBase>
50
					<goals>deploy</goals>
51
				</configuration>
52
			</plugin>
53
		</plugins>
54
	</build>
55

  
56

  
57
  <dependencyManagement>
58
      <dependencies>
59
          <dependency>
60
            <groupId>org.gvsig</groupId>
61
            <artifactId>org.gvsig.postgresql.provider</artifactId>
62
            <version>2.0.46</version>
63
          </dependency>
64
          <dependency>
65
            <groupId>org.gvsig</groupId>
66
            <artifactId>org.gvsig.postgresql.app.mainplugin</artifactId>
67
            <version>2.0.46</version>
68
          </dependency>
69
      </dependencies>
70
  </dependencyManagement>
71

  
72
  <dependencies>
73
        <dependency>
74
            <groupId>org.slf4j</groupId>
75
            <artifactId>slf4j-api</artifactId>
76
            <scope>compile</scope>
77
        </dependency>
78
  </dependencies>
79

  
80
  
81
  <modules>
82
    <module>org.gvsig.postgresql.app</module>
83
    <module>org.gvsig.postgresql.provider</module>
84
  </modules>
85

  
86

  
87
</project>
tags/org.gvsig.postgresql-2.0.46/org.gvsig.postgresql.provider/src/main/java/org/gvsig/fmap/dal/store/postgresql/PostgreSQLConnectionParameters.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.store.jdbc.JDBCConnectionParameters;
34

  
35
/**
36
 * @author jmvivo
37
 *
38
 */
39
public interface PostgreSQLConnectionParameters extends
40
		JDBCConnectionParameters {
41

  
42
	public static final String DYNFIELDNAME_USESSL = "UseSSL";
43

  
44
	public Boolean getUseSSL();
45
}
tags/org.gvsig.postgresql-2.0.46/org.gvsig.postgresql.provider/src/main/java/org/gvsig/fmap/dal/store/postgresql/PostgreSQLLibrary.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.DALLibrary;
31
import org.gvsig.fmap.dal.DALLocator;
32
import org.gvsig.fmap.dal.resource.spi.ResourceManagerProviderServices;
33
import org.gvsig.fmap.dal.spi.DataManagerProviderServices;
34
import org.gvsig.fmap.dal.store.db.DBHelper;
35
import org.gvsig.fmap.dal.store.jdbc.JDBCLibrary;
36
import org.gvsig.metadata.exceptions.MetadataException;
37
import org.gvsig.tools.library.AbstractLibrary;
38
import org.gvsig.tools.library.LibraryException;
39

  
40
public class PostgreSQLLibrary extends AbstractLibrary {
41

  
42
	static String DEFAULT_JDCB_DRIVER_NAME = "org.postgresql.Driver";
43

  
44
    @Override
45
    public void doRegistration() {
46
        registerAsServiceOf(DALLibrary.class);
47
        require(JDBCLibrary.class);
48
    }
49

  
50
	public static String getJdbcUrl(String host, Integer port, String db) {
51
		String url = null;
52
		if(host != null){
53
		    String sport = "";
54
		    if (port != null) {
55
		        sport = ":" + port;
56
		    }
57
		    url = "jdbc:postgresql://" + host + sport + "/" + db;
58
		}
59
		return url;
60
	}
61

  
62

  
63
	@Override
64
	protected void doInitialize() throws LibraryException {
65
	}
66

  
67

  
68
	@Override
69
	protected void doPostInitialize() throws LibraryException {
70
		LibraryException ex=null;
71

  
72
		new JDBCLibrary().postInitialize();
73

  
74
		 DBHelper.registerParametersDefinition(
75
				 PostgreSQLStoreParameters.PARAMETERS_DEFINITION_NAME,
76
				 PostgreSQLStoreParameters.class,
77
				 "PostgreSQLParameters.xml"
78
		);
79
		DBHelper.registerParametersDefinition(
80
				PostgreSQLNewStoreParameters.PARAMETERS_DEFINITION_NAME,
81
				PostgreSQLNewStoreParameters.class,
82
				"PostgreSQLParameters.xml"
83
		);
84
		DBHelper.registerParametersDefinition(
85
				PostgreSQLServerExplorerParameters.PARAMETERS_DEFINITION_NAME, 
86
				PostgreSQLServerExplorerParameters.class, 
87
				"PostgreSQLParameters.xml"
88
		);
89
		DBHelper.registerParametersDefinition(
90
				PostgreSQLResourceParameters.PARAMETERS_DEFINITION_NAME, 
91
				PostgreSQLResourceParameters.class, 
92
				"PostgreSQLParameters.xml"
93
		);
94
		try {
95
			DBHelper.registerMetadataDefinition(
96
					PostgreSQLStoreProvider.METADATA_DEFINITION_NAME, 
97
					PostgreSQLStoreProvider.class, 
98
					"PostgreSQLMetadata.xml"
99
			);
100
		} catch (MetadataException e) {
101
			ex = new LibraryException(this.getClass(),e);
102
		}
103
		
104
		ResourceManagerProviderServices resman = (ResourceManagerProviderServices) DALLocator
105
		.getResourceManager();
106

  
107
		
108
		if (!resman.getResourceProviders().contains(PostgreSQLResource.NAME)) {
109
			resman.register(PostgreSQLResource.NAME,
110
					PostgreSQLResource.DESCRIPTION, PostgreSQLResource.class,
111
					PostgreSQLResourceParameters.class);
112
		}
113
		
114
		
115
		DataManagerProviderServices dataman = (DataManagerProviderServices) DALLocator
116
				.getDataManager();
117
		
118
		if (!dataman.getStoreProviders().contains(PostgreSQLStoreProvider.NAME)) {
119
			dataman.registerStoreProvider(PostgreSQLStoreProvider.NAME,
120
					PostgreSQLStoreProvider.class,
121
					PostgreSQLStoreParameters.class);
122
		}
123
		
124
		if (!dataman.getExplorerProviders().contains(
125
				PostgreSQLStoreProvider.NAME)) {
126
			dataman.registerExplorerProvider(PostgreSQLServerExplorer.NAME,
127
					PostgreSQLServerExplorer.class,
128
					PostgreSQLServerExplorerParameters.class);
129
		}
130
		if( ex!=null ) {
131
			throw ex;
132
		}
133
	}
134

  
135
}
tags/org.gvsig.postgresql-2.0.46/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.46/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.46/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.46/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.46/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.46/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) {
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff