Revision 319

View differences:

tags/org.gvsig.postgresql-2.0.68/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.68</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.176</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.68</connection>
20
      <developerConnection>scm:svn:https://devel.gvsig.org/svn/gvsig-postgresql/tags/org.gvsig.postgresql-2.0.68</developerConnection>
21
      <url>https://devel.gvsig.org/redmine/projects/gvsig-postgresql/repository/show/tags/org.gvsig.postgresql-2.0.68</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.68</version>
63
          </dependency>
64
          <dependency>
65
            <groupId>org.gvsig</groupId>
66
            <artifactId>org.gvsig.postgresql.app.mainplugin</artifactId>
67
            <version>2.0.68</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.68/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.68/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="host" type="string" mandatory="false" 
19
            defaultValue="127.0.0.1" group="Connection">
20
          <description></description>
21
        </field>
22
        <field name="UseSSL" type="boolean" mandatory="false"
23
          defaultValue="false" group="Basic">
24
          <description>Use SSL connetion</description>
25
        </field>
26
      </fields>
27
    </class>
28

  
29
    <class name="PostgreSQLStoreParameters">
30
      <extends>
31
        <class>JDBCStoreParameters</class>
32
        <class>PostgreSQLResourceParameters</class>
33
      </extends>
34
      <fields/>
35
    </class>
36

  
37
    <class name="PostgreSQLNewStoreParameters">
38
      <extends>
39
        <class>JDBCNewStoreParameters</class>
40
        <class>PostgreSQLResourceParameters</class>
41
      </extends>
42
      <fields/>
43
    </class>
44

  
45

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

  
54

  
55
  </classes>
56
</definitions>  
tags/org.gvsig.postgresql-2.0.68/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.68/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
    public static final String NAME = "PostgreSQL";
44

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

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

  
63

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

  
68

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

  
73
		new JDBCLibrary().postInitialize();
74

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

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

  
136
}
tags/org.gvsig.postgresql-2.0.68/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.68/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
package org.gvsig.fmap.dal.store.postgresql;
24

  
25
import javax.sql.DataSource;
26
import org.apache.commons.dbcp.BasicDataSource;
27
import org.gvsig.fmap.dal.exception.InitializeException;
28
import org.gvsig.fmap.dal.store.jdbc.JDBCResource;
29
import org.gvsig.fmap.dal.store.jdbc.JDBCResourceParameters;
30
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCDriverClassNotFoundException;
31
import org.slf4j.Logger;
32
import org.slf4j.LoggerFactory;
33

  
34
public class PostgreSQLResource extends JDBCResource {
35
	
36
	final static private Logger logger = LoggerFactory.getLogger(PostgreSQLResource.class);
37

  
38
	public final static String NAME = "PostgreSQLResource";
39
	public static final String DESCRIPTION = "PostgreSQL Connection";
40

  
41
	public PostgreSQLResource(
42
                PostgreSQLResourceParameters parameters
43
            ) throws InitializeException {
44
            super(parameters);
45
	}
46
        
47

  
48
    /**
49
     * Registra/Carga el driver de JDBC.
50
     * 
51
     * Debe ser sobreescrita en cada proveedor de datos para asegurar que se
52
     * tegna acceso al driver.
53
     * 
54
     * @throws InitializeException 
55
     */
56
    @Override
57
    protected void registerJDBCDriver() throws InitializeException {
58
        String className = this.getParameters().getJDBCDriverClassName();
59
        if (className == null) {
60
            return;
61
        }
62
        try {
63
            Class theClass = Class.forName(className);
64
            if (theClass == null) {
65
                throw new JDBCDriverClassNotFoundException(this.getName(), className);
66
            }
67
        } catch (Exception e) {
68
            throw new InitializeException(e);
69
        }
70
    }
71

  
72
    /**
73
     * Crea el JDBC DataSource a partir de la informacion de los parametros
74
     * del recurso.
75
     * 
76
     * Debe ser sobreescrita en cada proveedor de datos para asegurar que se
77
     * tenga acceso al driver.
78
     * 
79
     * @return 
80
     */
81
    @Override
82
    protected DataSource createDataSource() {
83
        JDBCResourceParameters jdbcParams = this.getParameters();
84
        BasicDataSource dataSource = new BasicDataSource();
85
        dataSource.setDriverClassName(jdbcParams.getJDBCDriverClassName());
86
        dataSource.setUsername(jdbcParams.getUser());
87
        dataSource.setPassword(jdbcParams.getPassword());
88
        dataSource.setUrl(jdbcParams.getUrl());
89

  
90
        dataSource.setMaxWait(60L * 1000); // FIXME
91

  
92
//                FIXME Set Pool parameters:
93
//		dataSource.setMaxActive(maxActive);
94
//		dataSource.setMaxIdle(maxActive);
95
//		dataSource.setMaxOpenPreparedStatements(maxActive);
96
//		dataSource.setMaxWait(maxActive);
97
//		dataSource.setInitialSize(initialSize);
98
//		dataSource.setDefaultReadOnly(defaultReadOnly);
99
//		dataSource.setDefaultTransactionIsolation(defaultTransactionIsolation);
100
//		dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
101
//		dataSource.setMinIdle(minIdle);
102
//		dataSource.setTestOnBorrow(testOnBorrow);
103
//		dataSource.setTestOnReturn(testOnReturn);
104
//		dataSource.setTestWhileIdle(testOnReturn);
105
//		dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
106
//
107
//		dataSource.setAccessToUnderlyingConnectionAllowed(allow);
108
//		dataSource.setLoginTimeout(seconds);
109
//		dataSource.setLogWriter(out);
110
        return dataSource;
111
    }
112
        
113
//
114
//	public String getName() throws AccessResourceException {
115
//		PostgreSQLResourceParameters params = (PostgreSQLResourceParameters) this.getParameters();
116
//		return MessageFormat.format("PostgreSQLResource({0},{1})",
117
//				new Object[] { params.getUrl(),params.getUser() });
118
//	}
119
//        
120
//        public String toString() {
121
//            try {
122
//                return this.getName();
123
//            } catch(Exception ex) {
124
//                return super.toString();
125
//            }
126
//        }
127
//
128
//	protected void connectToDB() throws DataException {
129
//		if (this.dataSource != null) {
130
//			return;
131
//		}
132
//		JDBCResourceParameters jdbcParams = (JDBCResourceParameters) this
133
//				.getParameters();
134
//		BasicDataSource dataSource = new BasicDataSource();
135
//		dataSource.setDriverClassName(jdbcParams.getJDBCDriverClassName());
136
//		dataSource.setUsername(jdbcParams.getUser());
137
//		dataSource.setPassword(jdbcParams.getPassword());
138
//		dataSource.setUrl(jdbcParams.getUrl());
139
//
140
//		dataSource.setMaxWait(60L * 1000); // FIXME
141
//
142
//		// FIXME Set Pool parameters:
143
//		/*
144
//		dataSource.setMaxActive(maxActive);
145
//		dataSource.setMaxIdle(maxActive);
146
//		dataSource.setMaxOpenPreparedStatements(maxActive);
147
//		dataSource.setMaxWait(maxActive);
148
//		dataSource.setInitialSize(initialSize);
149
//		dataSource.setDefaultReadOnly(defaultReadOnly);
150
//		dataSource.setDefaultTransactionIsolation(defaultTransactionIsolation);
151
//		dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
152
//		dataSource.setMinIdle(minIdle);
153
//		dataSource.setTestOnBorrow(testOnBorrow);
154
//		dataSource.setTestOnReturn(testOnReturn);
155
//		dataSource.setTestWhileIdle(testOnReturn);
156
//		dataSource
157
//				.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
158
//
159
//		dataSource.setAccessToUnderlyingConnectionAllowed(allow);
160
//		dataSource.setLoginTimeout(seconds);
161
//		dataSource.setLogWriter(out);
162
//		*/
163
//
164
//		this.dataSource = dataSource;
165
//	}	
166
//	protected void registerJDBCDriver() throws InitializeException {
167
//		String className = ((JDBCResourceParameters) getParameters())
168
//				.getJDBCDriverClassName();
169
//		if (className == null) {
170
//			return;
171
//		}
172
//
173
//		Class theClass = null;
174
//		try {
175
//			theClass = Class.forName(className);
176
//		} catch (Exception e){
177
//			throw new InitializeException(e);
178
//		}
179
//		if (theClass == null) {
180
//			try {
181
//				throw new JDBCDriverClassNotFoundException(this.getName(),
182
//						className);
183
//			} catch (AccessResourceException e) {
184
//				throw new InitializeException(e);
185
//
186
//			}
187
//		}
188
//	}
189
//	
190
//	protected DataSource createDataSource() {
191
//		PostgreSQLResourceParameters jdbcParams = (PostgreSQLResourceParameters) this
192
//				.getParameters();
193
//		BasicDataSource dataSource = new BasicDataSource();
194
//		dataSource.setDriverClassName(jdbcParams.getJDBCDriverClassName());
195
//		dataSource.setUsername(jdbcParams.getUser());
196
//		dataSource.setPassword(jdbcParams.getPassword());
197
//		dataSource.setUrl(jdbcParams.getUrl());
198
//
199
//		dataSource.setMaxWait(60L * 1000); // FIXME
200
//
201
//		// FIXME Set Pool parameters:
202
//		/*
203
//		dataSource.setMaxActive(maxActive);
204
//		dataSource.setMaxIdle(maxActive);
205
//		dataSource.setMaxOpenPreparedStatements(maxActive);
206
//		dataSource.setMaxWait(maxActive);
207
//		dataSource.setInitialSize(initialSize);
208
//		dataSource.setDefaultReadOnly(defaultReadOnly);
209
//		dataSource.setDefaultTransactionIsolation(defaultTransactionIsolation);
210
//		dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
211
//		dataSource.setMinIdle(minIdle);
212
//		dataSource.setTestOnBorrow(testOnBorrow);
213
//		dataSource.setTestOnReturn(testOnReturn);
214
//		dataSource.setTestWhileIdle(testOnReturn);
215
//		dataSource
216
//			.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
217
//
218
//		dataSource.setAccessToUnderlyingConnectionAllowed(allow);
219
//		dataSource.setLoginTimeout(seconds);
220
//		dataSource.setLogWriter(out);
221
//		 */
222
//		return dataSource;
223
//	}
224
//	
225
//	
226
//	public boolean isConnected() {
227
//		if (dataSource == null) {
228
//			return false;
229
//		}
230
//		if (dataSource instanceof BasicDataSource) {
231
//			return ((BasicDataSource) dataSource).getNumActive() > 0
232
//					|| ((BasicDataSource) dataSource).getNumIdle() > 0;
233
//		}
234
//		return true;
235
//	}	
236
//	
237
//	private void logPoolStatus(String src) {
238
//		if (logger.isDebugEnabled() ) {
239
//			logger.debug(src + "  " + this.getStatusInformation());
240
//		}
241
//
242
//	}
243
//        
244
//        public String getStatusInformation() {
245
//		if ( !(dataSource instanceof BasicDataSource) ) {
246
//                    return "Connected: " + this.isConnected();
247
//                }
248
//        	BasicDataSource ds = (BasicDataSource) dataSource;
249
//                String s = "Connected: " + this.isConnected() + ", " +
250
//                        "actives: "+ ds.getNumActive() + "/"+ ds.getMaxActive() + ", " + 
251
//                        "idle: " + ds.getNumIdle() + "/"+ ds.getMaxIdle() ;
252
//                return s;
253
//        }
254
//
255
//        
256
//
257
//        private static class CanGetConnectionException extends JDBCSQLException {
258
//            public CanGetConnectionException(String datasource, SQLException cause) {
259
//                super("Can't get a connection to the data source (%(datasource))", cause, "_CanGetConnectionException", 0);
260
//                setValue("datasource", datasource);
261
//            }
262
//        }
263
//    
264
//	protected synchronized Object getTheConnection() throws DataException {
265
//		try {
266
//			Object conn = this.dataSource.getConnection();
267
//			logPoolStatus("getTheConnection");
268
//			return conn;
269
//		} catch (SQLException e) {
270
//			throw new CanGetConnectionException(this.toString(),e);
271
//		}
272
//	}	
273

  
274
}
tags/org.gvsig.postgresql-2.0.68/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.text.MessageFormat;
36
import java.util.ArrayList;
37
import java.util.Iterator;
38
import java.util.List;
39
import java.util.logging.Level;
40
import org.apache.commons.lang3.StringUtils;
41

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

  
59
/**
60
 * @author jmvivo
61
 *
62
 */
63
public class PostgreSQLServerExplorer extends JDBCServerExplorerBase {
64

  
65
    final static private Logger logger = LoggerFactory
66
            .getLogger(PostgreSQLServerExplorer.class);
67

  
68
    public static final String NAME = "PostgreSQLExplorer";
69

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

  
77
    private PostgreSQLServerExplorerParameters getPostgreSQLParameters() {
78
        return (PostgreSQLServerExplorerParameters) getParameters();
79
    }
80

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

  
85
    public String getStoreName() {
86
        return PostgreSQLStoreProvider.NAME;
87
    }
88

  
89
    public String getProviderName() {
90
        return NAME;
91
    }
92

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

  
98
        orgParams.setUseSSL(getPostgreSQLParameters().getUseSSL());
99

  
100
        return orgParams;
101
    }
102

  
103
	// ****************************
104
    public boolean canAdd() {
105
        return true;
106
    }
107

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

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

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

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

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

  
146
            public Object action(Connection conn) throws DataException {
147

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

  
155
                String sqlDrop = "Drop table "
156
                        + pgParams.tableID();
157

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

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

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

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

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

  
216
        params.setDefaultFeatureType(this.getServerExplorerProviderServices()
217
                .createNewFeatureType());
218

  
219
        return params;
220
    }
221

  
222
    public boolean hasGeometrySupport() {
223
        return true;
224
    }
225

  
226
    protected PostgreSQLHelper getPgHelper() {
227
        return (PostgreSQLHelper) getHelper();
228
    }
229

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

  
237
    @Override
238
    public void updateTableStatistics(String database, String schema, String table) throws JDBCExecuteSQLException {
239
        String sql = null;
240
        if( StringUtils.isEmpty(database) ) {
241
            if( StringUtils.isEmpty(schema) ) {
242
                sql = MessageFormat.format("VACUUM ANALIZE \"{0}\".\"{1}\".\"{2}\"", 
243
                        database, schema, table
244
                );
245
            }
246
        } else if( StringUtils.isEmpty(schema) ) {
247
            sql = MessageFormat.format("VACUUM ANALIZE \"{0}\".\"{1}\"", 
248
                    schema, table
249
            );
250
        } else {
251
            sql = MessageFormat.format("VACUUM ANALIZE \"{0}\"", 
252
                    table
253
            );
254
        }
255
        if( sql == null ) {
256
            throw new IllegalArgumentException("Can't update statistics, identifier of table incorrect (database '"+database+"', schema '"+schema+"', table '"+table+"')");
257
        }
258
        this.getHelper().execute(sql);
259
    }
260

  
261
}
tags/org.gvsig.postgresql-2.0.68/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.68/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.
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff