Revision 43377

View differences:

trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.spi/src/main/java/org/gvsig/fmap/dal/feature/spi/AbstractFeatureSetProvider.java
79 79
	protected FeatureQuery getQuery() {
80 80
		return query;
81 81
	}
82

  
82
    
83 83
	/**
84 84
	 * Returns the type of features to load.
85 85
	 * 
......
88 88
	protected FeatureType getFeatureType() {
89 89
		return featureType;
90 90
	}
91

  
91
    
92 92
    @Override
93 93
	public final DisposableIterator fastIterator() throws DataException {
94 94
		return fastIterator(0);
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.spi/src/main/java/org/gvsig/fmap/dal/feature/spi/FeatureSetProvider.java
25 25
package org.gvsig.fmap.dal.feature.spi;
26 26

  
27 27
import org.gvsig.fmap.dal.exception.DataException;
28
import org.gvsig.fmap.dal.feature.FeatureType;
28 29
import org.gvsig.tools.dispose.Disposable;
29 30
import org.gvsig.tools.dispose.DisposableIterator;
30 31

  
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.spi/src/main/java/org/gvsig/fmap/dal/spi/DataManagerProviderServices.java
33 33
import org.gvsig.fmap.dal.Register;
34 34
import org.gvsig.fmap.dal.exception.InitializeException;
35 35
import org.gvsig.fmap.dal.exception.ProviderNotRegisteredException;
36
import org.gvsig.fmap.dal.feature.EditableFeatureType;
36 37
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
37 38
import org.gvsig.fmap.dal.feature.FeatureStore;
38 39
import org.gvsig.fmap.dal.feature.FeatureType;
......
148 149
     * @return
149 150
     */
150 151
    public InputStream getResourceAsStream(Object resourcesLoader, String name);
151
    
152

  
152 153
}
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.impl/src/main/java/org/gvsig/fmap/dal/feature/impl/DefaultFeatureStore.java
387 387
        }
388 388
        this.notifyChange(DataStoreNotification.BEFORE_DISPOSE);
389 389
        this.disposeIndexes();
390
        this.provider.dispose();
390
        if( this.provider!=null ) {
391
            this.provider.dispose();
392
        }
391 393
        if (this.selection != null) {
392 394
            this.selection.dispose();
393 395
            this.selection = null;
......
1147 1149
    private void disposeIndexes() {
1148 1150
        FeatureIndexes theIndexes = getIndexes();
1149 1151
        LOG.debug("Disposing indexes: {}", theIndexes);
1152
        if( theIndexes==null ) {
1153
            return;
1154
        }
1150 1155
        for (Iterator iterator = theIndexes.iterator(); iterator.hasNext();) {
1151 1156
            FeatureIndex index = (FeatureIndex) iterator.next();
1152 1157
            if (index instanceof FeatureIndexProviderServices) {
......
1410 1415
                throw new NeedEditingModeException(this.getName());
1411 1416

  
1412 1417
            case MODE_APPEND:
1413
                ((FeatureSelection) this.getSelection()).deselectAll();
1418
                if( selection!=null ) {
1419
                    selection = null;
1420
                }
1414 1421
                notifyChange(FeatureStoreNotification.BEFORE_FINISHEDITING);
1415 1422
                provider.endAppend();
1416 1423
                exitEditingMode();
......
1422 1429
                if (hasStrongChanges && !this.allowWrite()) {
1423 1430
                    throw new WriteNotAllowedException(getName());
1424 1431
                }
1425

  
1426
                if(featureManager.isSelectionCompromised()) {
1427
                    ((FeatureSelection) this.getSelection()).deselectAll();
1428
                };
1429

  
1432
                if(featureManager.isSelectionCompromised() && selection!=null ) {
1433
                    selection = null;
1434
                }
1430 1435
                notifyChange(FeatureStoreNotification.BEFORE_FINISHEDITING);
1431 1436
                if (hasStrongChanges) {
1432 1437
                    validateFeatures(Feature.FINISH_EDITING);
......
2101 2106

  
2102 2107
    @Override
2103 2108
    public EditableFeatureType createFeatureType() {
2104
        DefaultEditableFeatureType ftype = new DefaultEditableFeatureType();
2109
        EditableFeatureType ftype = this.dataManager.createFeatureType();
2105 2110
        return ftype;
2106 2111
    }
2107 2112

  
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.impl/src/main/java/org/gvsig/fmap/dal/feature/impl/DefaultFeatureType.java
27 27
import java.util.ArrayList;
28 28
import java.util.Arrays;
29 29
import java.util.Collections;
30
import java.util.HashSet;
31 30
import java.util.Iterator;
32 31
import java.util.List;
33
import java.util.Set;
34 32
import org.apache.commons.lang3.ArrayUtils;
33
import org.apache.commons.lang3.StringUtils;
35 34

  
36 35
import org.cresques.cts.IProjection;
37 36

  
......
75 74
	private List srsList = null; 
76 75

  
77 76
	protected DefaultFeatureType(String id) {
77
        if( StringUtils.isEmpty(id) ) {
78
            id = "default";
79
        }
78 80
		this.internalID = Integer.toHexString((int) (Math.random()*100000)).toUpperCase();
79 81
		this.id = id;
80 82
		this.rules = new DefaultFeatureRules();
......
87 89
	}
88 90

  
89 91
	protected DefaultFeatureType() {
90
		this("default");
92
		this((String)null);
91 93
	}
92 94

  
93 95
	protected DefaultFeatureType(DefaultFeatureType other) {
94
		this("default");
96
		this((String)null);
95 97
		initialize(other, true);
96 98
	}
97 99

  
98 100
	protected DefaultFeatureType(DefaultFeatureType other,
99 101
			boolean copyAttributes) {
100
		this("default");
102
		this((String)null);
101 103
		initialize(other, copyAttributes);
102 104
	}
103 105
        
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.impl/src/main/java/org/gvsig/fmap/dal/impl/DataStoreImplementation.java
1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 3
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.impl/src/main/java/org/gvsig/fmap/dal/impl/DefaultDataManager.java
826 826
            throw new CreateFileStoreException(e, providerName);
827 827
        }
828 828
    }
829

  
830

  
831 829
}
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.db/org.gvsig.fmap.dal.db.h2/src/main/java/org/gvsig/fmap/dal/store/h2/H2ConnectionParameters.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.h2;
32

  
33
import java.io.File;
34
import org.gvsig.fmap.dal.store.jdbc.JDBCConnectionParameters;
35

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

  
43
	public static final String PARAMETER_NAME_USESSL = "UseSSL";
44
        
45
        public static final String PARAMETER_NAME_BASEFOLDER = "BaseFolder";
46

  
47
        public File getBaseFolder();
48
        
49
	public Boolean getUseSSL();
50
}
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.db/org.gvsig.fmap.dal.db.h2/src/main/java/org/gvsig/fmap/dal/store/h2/H2ParametersHelper.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.h2;
23

  
24
import java.io.File;
25
import java.io.IOException;
26
import org.apache.commons.io.FileUtils;
27
import org.apache.commons.lang3.StringUtils;
28
import org.slf4j.Logger;
29
import org.slf4j.LoggerFactory;
30

  
31
public class H2ParametersHelper {
32

  
33
    private static Logger logger = LoggerFactory.getLogger(H2ParametersHelper.class);
34

  
35
    public static String getConnectionString(H2ConnectionParameters params) {
36
        String connectionString = null;
37

  
38
        File baseFolder = params.getBaseFolder();
39
        String baseFolderPath = null;
40
        if ( baseFolder == null ) {
41
            baseFolder = getDefaultBaseFolder();
42
        }
43
        if ( baseFolder == null ) {
44
            baseFolderPath = baseFolder.getAbsolutePath();
45
            baseFolderPath = baseFolderPath.replace("\\", "/");
46
        }
47
        
48
        String dbname = params.getDBName();
49
        if ( dbname == null ) {
50
            logger.warn("dbname is null.");
51
            throw new IllegalArgumentException("dbname is null");
52
        }
53

  
54
        String host = params.getHost();
55

  
56
        Integer port = params.getPort();
57
        if ( port == null ) {
58
            port = new Integer(9123);
59
        }
60

  
61
        if ( StringUtils.isBlank(host) ) {
62
            if( baseFolderPath == null ) {
63
                throw new IllegalArgumentException("baseFolder required");
64
            }
65
            connectionString = "jdbc:h2:" + baseFolderPath + "/" + dbname + ";MODE=PostgreSQL;AUTO_SERVER=TRUE";
66
        } else {
67
            if ( host.trim().equalsIgnoreCase("localhost") ) {
68
                if( baseFolderPath == null ) {
69
                    connectionString = "jdbc:h2:tcp://localhost:" + port.intValue() + "/" + dbname + ";MODE=PostgreSQL";
70
                } else {
71
                    connectionString = "jdbc:h2:" + baseFolderPath + "/" + dbname + ";MODE=PostgreSQL;AUTO_SERVER=TRUE;AUTO_SERVER_PORT=" + port;
72
                }
73
            } else {
74
                if( baseFolderPath == null ) {
75
                    connectionString = "jdbc:h2:tcp://" + host + ":" + port.intValue() + "/" + dbname + ";MODE=PostgreSQL";
76
                } else {
77
                    connectionString = "jdbc:h2:tcp://" + host + ":" + port.intValue() + "/" + dbname + ":" + baseFolder + ";MODE=PostgreSQL";
78
                }
79
            }
80
        }
81

  
82
        return connectionString;
83
    }
84

  
85
    public static File getDefaultBaseFolder() {
86
        File baseFolder = null;
87
        String s = System.getProperty("user.home");
88
        File baseFolderInHome = new File(s + File.separator + "gvSIG" + File.separator + "dbs.h2");
89
        if ( !baseFolderInHome.exists() ) {
90
            try {
91
                FileUtils.forceMkdir(baseFolderInHome);
92
                baseFolder = baseFolderInHome;
93
            } catch (IOException ex) {
94

  
95
            }
96
        }
97
        if ( baseFolder == null ) {
98
            s = System.getProperty("java.io.tmpdir");
99
            File baseFolderInTemp = new File(s + File.separator + "gvSIG" + File.separator + "dbs.h2");
100
            if ( !baseFolderInTemp.exists() ) {
101
                try {
102
                    FileUtils.forceMkdir(baseFolderInTemp);
103
                    baseFolder = baseFolderInTemp;
104
                } catch (IOException ex) {
105

  
106
                }
107
            }
108
        }
109
        return baseFolder;
110
    }
111

  
112
}
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.db/org.gvsig.fmap.dal.db.h2/src/main/java/org/gvsig/fmap/dal/store/h2/H2Library.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 3
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 */
22
package org.gvsig.fmap.dal.store.h2;
23

  
24
import org.gvsig.fmap.dal.DALLibrary;
25
import org.gvsig.fmap.dal.DALLocator;
26
import org.gvsig.fmap.dal.resource.spi.ResourceManagerProviderServices;
27
import org.gvsig.fmap.dal.spi.DataManagerProviderServices;
28
import org.gvsig.fmap.dal.store.db.DBHelper;
29
import org.gvsig.fmap.dal.store.jdbc.JDBCLibrary;
30
import org.gvsig.metadata.exceptions.MetadataException;
31
import org.gvsig.tools.library.AbstractLibrary;
32
import org.gvsig.tools.library.LibraryException;
33

  
34
public class H2Library extends AbstractLibrary {
35

  
36
    static String DEFAULT_H2_DRIVER_NAME = "org.h2.Driver";
37

  
38
    @Override
39
    public void doRegistration() {
40
        registerAsServiceOf(DALLibrary.class);
41
        require(JDBCLibrary.class);
42
    }
43

  
44
    @Override
45
    protected void doInitialize() throws LibraryException {
46
    }
47

  
48
    @Override
49
    protected void doPostInitialize() throws LibraryException {
50
        LibraryException ex = null;
51

  
52
        //new JDBCLibrary().postInitialize();
53

  
54
        DBHelper.registerParametersDefinition(
55
                H2StoreParameters.PARAMETERS_DEFINITION_NAME,
56
                H2StoreParameters.class,
57
                "H2SQLParameters.xml"
58
        );
59
        DBHelper.registerParametersDefinition(
60
                H2NewStoreParameters.PARAMETERS_DEFINITION_NAME,
61
                H2NewStoreParameters.class,
62
                "H2SQLParameters.xml"
63
        );
64
        DBHelper.registerParametersDefinition(
65
                H2ServerExplorerParameters.PARAMETERS_DEFINITION_NAME,
66
                H2ServerExplorerParameters.class,
67
                "H2SQLParameters.xml"
68
        );
69
        DBHelper.registerParametersDefinition(
70
                H2ResourceParameters.PARAMETERS_DEFINITION_NAME,
71
                H2ResourceParameters.class,
72
                "H2SQLParameters.xml"
73
        );
74
        try {
75
            DBHelper.registerMetadataDefinition(
76
                    H2StoreProvider.METADATA_DEFINITION_NAME,
77
                    H2StoreProvider.class,
78
                    "H2SQLMetadata.xml"
79
            );
80
        } catch (MetadataException e) {
81
            ex = new LibraryException(this.getClass(), e);
82
        }
83

  
84
        ResourceManagerProviderServices resman = (ResourceManagerProviderServices) DALLocator
85
                .getResourceManager();
86

  
87
        if ( !resman.getResourceProviders().contains(H2Resource.NAME) ) {
88
            resman.register(H2Resource.NAME,
89
                    H2Resource.DESCRIPTION, H2Resource.class,
90
                    H2ResourceParameters.class);
91
        }
92

  
93
        DataManagerProviderServices dataman = (DataManagerProviderServices) DALLocator
94
                .getDataManager();
95

  
96
        if ( !dataman.getStoreProviders().contains(H2StoreProvider.NAME) ) {
97
            dataman.registerStoreProvider(H2StoreProvider.NAME,
98
                    H2StoreProvider.class,
99
                    H2StoreParameters.class);
100
        }
101

  
102
        if ( !dataman.getExplorerProviders().contains(
103
                H2StoreProvider.NAME) ) {
104
            dataman.registerExplorerProvider(H2ServerExplorer.NAME,
105
                    H2ServerExplorer.class,
106
                    H2ServerExplorerParameters.class);
107
        }
108
        if ( ex != null ) {
109
            throw ex;
110
        }
111
    }
112

  
113
}
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.db/org.gvsig.fmap.dal.db.h2/src/main/java/org/gvsig/fmap/dal/store/h2/H2SetProvider.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.h2;
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 H2SetProvider extends JDBCSetProvider {
59

  
60
    private static Logger logger = LoggerFactory.getLogger(H2SetProvider.class);
61
    
62
	public H2SetProvider(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
        H2StoreProvider pg_sto_prov = (H2StoreProvider) this.getStore();
146
        H2Helper 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
            H2StoreProvider sprov = (H2StoreProvider) getStore();
191
            H2Helper 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
}
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.db/org.gvsig.fmap.dal.db.h2/src/main/java/org/gvsig/fmap/dal/store/h2/H2Resource.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.h2;
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 H2Resource extends JDBCResource {
48
	
49
	final static private Logger logger = LoggerFactory
50
			.getLogger(H2Resource.class);
51

  
52
	public final static String NAME = "H2SQLResource";
53
	public static final String DESCRIPTION = "H2SQL Connection";
54

  
55
	public H2Resource(H2ResourceParameters parameters)
56
			throws InitializeException {
57
		super(parameters);
58
	}
59

  
60
	public String getName() throws AccessResourceException {
61
		H2ResourceParameters params = (H2ResourceParameters) this.getParameters();
62
		return MessageFormat.format("H2SQLResource({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
		H2ResourceParameters jdbcParams = (H2ResourceParameters) 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() && dataSource instanceof BasicDataSource) {
185
			BasicDataSource ds = (BasicDataSource) dataSource;
186
			logger.debug(src + "  actives:" + ds.getNumActive() + "("
187
					+ ds.getMaxActive() + ") idle:" + ds.getNumIdle() + "("
188
					+ ds.getMaxIdle() + ")");
189
		}
190

  
191
	}
192

  
193
        private static class CanGetConnectionException extends JDBCSQLException {
194
            public CanGetConnectionException(String datasource, SQLException cause) {
195
                super("Can't get a connection to the data source (%(datasource))", cause, "_CanGetConnectionException", 0);
196
                setValue("datasource", datasource);
197
            }
198
        }
199
    
200
	protected synchronized Object getTheConnection() throws DataException {
201
		try {
202
			Object conn = this.dataSource.getConnection();
203
			logPoolStatus("getTheConnection");
204
			return conn;
205
		} catch (SQLException e) {
206
			throw new CanGetConnectionException(this.toString(),e);
207
		}
208
	}	
209

  
210
}
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.db/org.gvsig.fmap.dal.db.h2/src/main/java/org/gvsig/fmap/dal/store/h2/H2ServerExplorer.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.h2;
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 H2ServerExplorer extends JDBCServerExplorer {
62

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

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

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

  
75
    private H2ServerExplorerParameters getH2SQLParameters() {
76
        return (H2ServerExplorerParameters) getParameters();
77
    }
78

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

  
83
    public String getStoreName() {
84
        return H2StoreProvider.NAME;
85
    }
86

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

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

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

  
98
        return orgParams;
99
    }
100

  
101
	// ****************************
102
    public boolean canAdd() {
103
        return true;
104
    }
105

  
106
    public DataStoreParameters getOpenParameters() throws DataException {
107
        H2ServerExplorerParameters parameters = getH2SQLParameters();
108
        H2StoreParameters params = new H2StoreParameters();
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 H2ConnectionParameters)) {
123
            // FIXME Excpetion ???
124
            throw new IllegalArgumentException(
125
                    "not instance of H2SQLConnectionParameters");
126
        }
127
        super.checkIsMine(dsp);
128

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

  
136
    public void remove(DataStoreParameters dsp) throws RemoveException {
137
        final H2StoreParameters pgParams = (H2StoreParameters) 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
        H2ServerExplorerParameters parameters = getH2SQLParameters();
202
        H2NewStoreParameters params = new H2NewStoreParameters();
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 H2Helper getPgHelper() {
225
        return (H2Helper) getHelper();
226
    }
227

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

  
235
    public void updateTableStatistics(String tableName) throws JDBCExecuteSQLException {
236
        String sql="";
237
        try {
238
            
239
            if( tableName.startsWith("\"") ) {
240
                sql = "VACUUM ANALYZE " + tableName ;
241
            } else {
242
                sql = "VACUUM ANALYZE \"" + tableName + "\"";
243
            }
244
            Connection conn = this.getHelper().getConnection();
245
            Statement st = conn.createStatement();
246
            JDBCHelper.execute(st, sql);
247
        } catch (Exception ex) {
248
            throw new JDBCExecuteSQLException(sql, ex);
249
        }
250

  
251
    }
252

  
253
}
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.db/org.gvsig.fmap.dal.db.h2/src/main/java/org/gvsig/fmap/dal/store/h2/H2StoreProvider.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.h2;
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 H2StoreProvider extends JDBCStoreProviderWriter {
58

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

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

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

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

  
77
	protected JDBCHelper createHelper() throws InitializeException {
78
	    JDBCHelper resp = new H2Helper(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 H2SetProvider(this, query, featureType);
130
	}
131

  
132

  
133
	public DataServerExplorer getExplorer() throws ReadException {
134
		DataManager manager = DALLocator.getDataManager();
135
		H2ServerExplorerParameters exParams;
136
		H2StoreParameters params = getPGParameters();
137
		try {
138
			exParams = (H2ServerExplorerParameters) manager
139
					.createServerExplorerParameters(H2ServerExplorer.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(H2ServerExplorer.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 H2Helper getPgHelper() {
170
		return (H2Helper) 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
			H2StoreParameters params = getPGParameters();
250
			additionalStatement.addAll(	((H2Helper) 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
		H2StoreParameters 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
		H2StoreParameters 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(((H2Helper) 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) {
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff