Statistics
| Revision:

svn-gvsig-desktop / branches / v2_0_0_prep / libraries / libFMap_dataDB / src / org / gvsig / fmap / data / feature / db / jdbc / postgresql / PostgresqlStore.java @ 23842

History | View | Annotate | Download (9.85 KB)

1
package org.gvsig.fmap.data.feature.db.jdbc.postgresql;
2

    
3
import java.lang.ref.WeakReference;
4
import java.sql.Connection;
5
import java.sql.ResultSet;
6
import java.sql.SQLException;
7
import java.sql.Statement;
8
import java.util.ArrayList;
9
import java.util.Iterator;
10

    
11
import org.gvsig.fmap.data.DataSet;
12
import org.gvsig.fmap.data.DataExplorer;
13
import org.gvsig.fmap.data.DataManager;
14
import org.gvsig.fmap.data.exceptions.CloseException;
15
import org.gvsig.fmap.data.exceptions.DataException;
16
import org.gvsig.fmap.data.exceptions.InitializeException;
17
import org.gvsig.fmap.data.exceptions.OpenException;
18
import org.gvsig.fmap.data.exceptions.ReadException;
19
import org.gvsig.fmap.data.feature.Feature;
20
import org.gvsig.fmap.data.feature.FeatureSet;
21
import org.gvsig.fmap.data.feature.FeatureType;
22
import org.gvsig.fmap.data.feature.db.DBFeatureType;
23
import org.gvsig.fmap.data.feature.db.DBResource;
24
import org.gvsig.fmap.data.feature.db.DBStoreParameters;
25
import org.gvsig.fmap.data.feature.db.jdbc.JDBCFeaturesWriter;
26
import org.gvsig.fmap.data.feature.db.jdbc.JDBCStore;
27
import org.gvsig.fmap.data.feature.db.jdbc.JDBCStoreParameters;
28
import org.gvsig.fmap.data.feature.exceptions.InitializeWriterException;
29
import org.gvsig.fmap.data.impl.DefaultDataManager;
30
import org.gvsig.fmap.geom.primitive.DefaultEnvelope;
31
import org.gvsig.fmap.geom.primitive.Envelope;
32
import org.gvsig.metadata.Metadata;
33
import org.gvsig.metadata.MetadataManager;
34
import org.gvsig.metadata.DefaultMetadataManager;
35
import org.gvsig.tools.exception.BaseException;
36
import org.postgis.PGbox2d;
37
import org.postgis.PGbox3d;
38
import org.postgresql.util.PGobject;
39

    
40
public class PostgresqlStore extends JDBCStore{
41
        public static final String CONNECTION_STRING = "postgresql";
42
        public static String DATASTORE_NAME = "PostgresqlStore";
43
    PostgresqlStoreParameters getParametersPostgresql(){
44
                return (PostgresqlStoreParameters)this.parameters;
45
        }
46

    
47
        /* (non-Javadoc)
48
         * @see org.gvsig.fmap.data.feature.db.jdbc.JDBCStore#createResource(org.gvsig.fmap.data.feature.file.dbf.DBFStoreParameters)
49
         */
50
        protected DBResource createResource(JDBCStoreParameters params) {
51
                return new PostgresqlResource(params);
52
        }
53

    
54

    
55
        protected void initFeatureType() throws InitializeException{
56
                PostgresqlStoreParameters dParams = this.getParametersPostgresql();
57
                try {
58
                        this.defaultFeatureType = PostgresqlStoreUtils.getFeatureType(this.getConnection(), dParams);
59
                } catch (ReadException e) {
60
                        throw new InitializeException(DATASTORE_NAME,e);
61
                }
62
                String[] fieldsID = dParams.getFieldsId();
63
                if (fieldsID == null || fieldsID.length < 1){
64
                        throw new InitializeException(
65
                                        DATASTORE_NAME,
66
                                        new Exception("Field Id not set"));
67
                } else if (fieldsID.length > 1){
68
                        //TODO: Falta por implementar soporte para multiples ID
69
                        throw new InitializeException(
70
                                        DATASTORE_NAME,
71
                                        new Exception("Multy fields id not supported yet"));
72

    
73
                } else{
74
                        for (int i=0;i<fieldsID.length;i++){
75
                                if (this.getDefaultFeatureType().getIndex(fieldsID[i]) < 0) {
76

    
77
                                throw new InitializeException(
78
                                                DATASTORE_NAME,
79
                                                new Exception("Field id '"+ fieldsID[i] +"' (id pos "+ (i+1) +") not Found"));
80

    
81
                                }
82
                        }
83
                }
84

    
85
                this.featureTypes = new ArrayList();
86
                this.featureTypes.add(defaultFeatureType);
87

    
88

    
89
        }
90

    
91
        public DataSet getDataCollection(FeatureType type, String filter, String order) throws ReadException {
92
                try {
93
                        type = this.checkFeatureTypeForCollection(type);
94
                } catch (DataException e) {
95
                        throw new ReadException(this.getName(), e);
96
                }
97

    
98
                if (useSqlSource ){
99
                        if (filter != null || order != null) {
100
                                throw new ReadException("Unsuported filter/order in sqlSource mode",this.getName());
101
                        }
102
                }
103

    
104
                FeatureSet coll;
105
                if (featureManager == null){
106
                        coll=new PostgresqlFeatureCollection(this,type,filter,order);
107
                }else{
108
                        if ((order != null && order != "")){
109
                                coll=new PostgresqlFeatureCollectionWithFeatureID(featureManager,this,type,filter,order);
110
                        } else{
111
                                if (filter == null || filter == ""){
112
                                        coll=new PostgresqlFeatureCollectionEditing(featureManager,this,type);
113
                                } else {
114
                                        coll=new PostgresqlFeatureCollectionEditingFiltered(featureManager,this,type,filter);
115
                                }
116
                        }
117

    
118

    
119
                }
120
                this.addObserver(new WeakReference(coll));
121

    
122
                return coll;
123
        }
124

    
125
        protected Connection getConnection() throws ReadException{
126
                return super.getConnection();
127

    
128
        }
129

    
130

    
131
        protected void initSqlProperties() throws InitializeException{
132
                PostgresqlStoreParameters dParams = (PostgresqlStoreParameters)this.getParameters();
133
                if (dParams.getSqlSoure() != null){
134
                        this.sqlSource = dParams.getSqlSoure();
135
                        this.useSqlSource = true;
136
                        this.sqlSelectPart = null;
137
                        this.baseWhereClause = null;
138
                        this.baseOrder = null;
139
                } else {
140
                        this.sqlSelectPart = "SELECT " + dParams.getFieldsString() +" FROM "+ dParams.tableID();
141

    
142
                        this.baseWhereClause = dParams.getBaseFilter();
143

    
144
                        if (dParams.getWorkingArea() != null){
145
                                String waWhere = getWorkingAreaFilter(dParams.getWorkingArea(), dParams.getSRISD());
146
                                if (waWhere != null){
147
                                        this.baseWhereClause = "(("+this.baseWhereClause+") and "+waWhere +")";
148
                                }
149

    
150
                        }
151

    
152
                        this.baseOrder = dParams.getBaseOrder();
153
                }
154
        }
155
        private String getWorkingAreaFilter(Envelope env, String strEPSG) {
156
                if (env == null) {
157
                        return null;
158
                }
159
                String wktBox = "GeometryFromText('LINESTRING(" + env.getMinimum(0)
160
                                + " " + env.getMinimum(1) + ", " + env.getMaximum(0) + " "
161
                                + env.getMinimum(1) + ", " + env.getMaximum(0) + " "
162
                                + env.getMaximum(1) + ", " + env.getMinimum(0) + " "
163
                                + env.getMaximum(1) + ")', " + strEPSG + ")";
164

    
165
                return wktBox;
166
        }
167

    
168

    
169
        public boolean canAlterFeatureType() {
170
                return true;
171
        }
172

    
173

    
174
        protected void doDispose() throws CloseException{
175
                super.doDispose();
176
        }
177

    
178

    
179
        public String getName() {
180
                return DATASTORE_NAME;
181
        }
182

    
183

    
184
        protected JDBCFeaturesWriter getFeaturesWriter() throws InitializeWriterException {
185
                JDBCFeaturesWriter writer = new PostgresqlFeaturesWriter();
186
                writer.init(this);
187
                return writer;
188
        }
189

    
190
        public DataExplorer getExplorer() throws ReadException {
191
                DataManager dm = DefaultDataManager.getManager();
192
                PostgresqlExplorerParameters explorerParams = (PostgresqlExplorerParameters) dm
193
                                .createDataExplorerParameters(PostgresqlExplorer.DATAEXPLORER_NAME);
194
                explorerParams.putAllDefaultValues(this.getParameters());
195
                return dm.createDataExplorer(explorerParams);
196
        }
197

    
198
        public Metadata getMetadata() throws BaseException {
199
                if (metadata==null){
200
                        MetadataManager manager=DefaultMetadataManager.getManager();
201
                        metadata=manager.create(DATASTORE_NAME);
202
                        Envelope extent=this.getFullExtent();
203
                        metadata.set("extent",extent);
204
                        String srs = this.getDefaultFeatureType().getDefaultSRS();
205
                        metadata.set("srs", srs);
206
                }
207
                if (this.alterMode){
208
                        Envelope extent=(Envelope)metadata.get("extent");
209
                        FeatureSet featureCollection=(FeatureSet)getDataSet();
210
                        if (spatialManager.isFullExtentDirty()){
211
                                if (!featureCollection.isEmpty()){
212
                                        Iterator featureIterator=featureCollection.iterator();
213
                                        extent = ((Feature)featureIterator.next()).getDefaultEnvelope();
214
                                        while(featureIterator.hasNext()){
215
                                                Feature feature=(Feature)featureIterator.next();
216
                                                Envelope boundExtent=feature.getDefaultEnvelope();
217
                                                if (boundExtent!=null) {
218
                                                        extent.add(boundExtent);
219
                                                }
220
                                        }
221
                                }
222
                        }
223
                        metadata.set("extent",extent);
224
                }
225
                return metadata;
226

    
227

    
228
//                if (metadata==null){
229
//                        IMetadata tmp=super.getMetadata();
230
//
231
//                        return tmp;
232
//                }else{
233
//                        return super.getMetadata();
234
//                }
235

    
236
        }
237

    
238
        private Envelope getFullExtent() throws ReadException {
239
                Envelope fullExtent=null;
240
                Statement s = null;
241
                ResultSet r = null;
242

    
243

    
244
                try {
245
                        DBStoreParameters params = this.getParametersPostgresql();
246
                        if (params.getDefaultGeometryField() == null
247
                                        || params.getDefaultGeometryField().length() == 0) {
248
                                return null;
249
                        }
250
                        s = getConnection().createStatement();
251

    
252
                        StringBuffer sql = new StringBuffer();
253
                        sql.append("SELECT extent(");
254
                        sql.append(params.getDefaultGeometryField());
255
                        sql.append(") AS FullExtent FROM ");
256
                        sql.append(params.tableID());
257
                        if (this.getBaseWhereClause() != null
258
                                        && this.getBaseWhereClause() != "") {
259
                                sql.append(" WHERE ");
260
                                sql.append(this.getBaseWhereClause());
261
                        }
262

    
263
                        r = s.executeQuery(sql.toString());
264
                        if (!r.next()) {
265
                                return null;
266
                        }
267
                        PGobject data = (PGobject) r.getObject(1);
268
                        if (data instanceof PGbox3d) {
269
                                PGbox3d box3d = (PGbox3d) data;
270
                                fullExtent = new DefaultEnvelope(
271
                                                box3d.getLLB().x, box3d.getLLB().y,box3d.getLLB().z,
272
                                                box3d.getURT().x, box3d.getURT().y,box3d.getURT().z);
273

    
274
                        } else {
275
                                PGbox2d box2d = (PGbox2d) data;
276
                                fullExtent = new DefaultEnvelope(
277
                                                box2d.getLLB().x, box2d.getLLB().y,
278
                                                box2d.getURT().x, box2d.getURT().y);
279
                        }
280
                        String strAux = r.getString(1);
281
                        System.out.println("fullExtent = " + strAux);
282
                } catch (SQLException e) {
283
                        throw new ReadException(this.getName(),e);
284
                } finally {
285
                        if (r != null) {
286
                                try {
287
                                        r.close();
288
                                } catch (SQLException e) {
289
                                        // TODO Auto-generated catch block
290
                                        e.printStackTrace();
291
                                }
292
                        }
293
                        if (s != null) {
294
                                try {
295
                                        s.close();
296
                                } catch (SQLException e) {
297
                                        // TODO Auto-generated catch block
298
                                        e.printStackTrace();
299
                                }
300

    
301
                        }
302

    
303
                }
304

    
305
                return fullExtent;
306
        }
307

    
308
        protected Feature createFeatureFromResulset(ResultSet rs, DBFeatureType featureType2) throws ReadException {
309
                if (featureType2== null){
310
                        return new PostgresqlFeature(this.getDefaultFeatureType(),this,rs);
311
                }else{
312
                        return new PostgresqlFeature(featureType2,this,rs);
313
                }
314
        }
315

    
316

    
317
        /* (non-Javadoc)
318
         * @see org.gvsig.fmap.data.feature.FeatureStore#doRefresh()
319
         */
320
        protected void doRefresh() throws OpenException, InitializeException {
321
                this.initFeatureType();
322
                this.initSqlProperties();
323
        }
324
        public boolean canWriteGeometry(int gvSIGgeometryType) {
325
                try {
326
                        return getFeaturesWriter().canWriteGeometry(gvSIGgeometryType);
327
                } catch (InitializeWriterException e) {
328
                        e.printStackTrace();
329
                }
330
                return false;
331
        }
332

    
333
        public Feature getByIndex(long index) throws ReadException {
334
                // TODO Auto-generated method stub
335
                return null;
336
        }
337

    
338
}