Statistics
| Revision:

root / branches / v2_0_0_prep / libraries / libFMap_dataDB / src / org / gvsig / fmap / data / feature / db / jdbc / postgresql / PostgresqlStore.java @ 23303

History | View | Annotate | Download (9.33 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.Iterator;
9

    
10
import org.gvsig.fmap.data.CloseException;
11
import org.gvsig.fmap.data.DataCollection;
12
import org.gvsig.fmap.data.DataException;
13
import org.gvsig.fmap.data.DataExplorer;
14
import org.gvsig.fmap.data.InitializeException;
15
import org.gvsig.fmap.data.OpenException;
16
import org.gvsig.fmap.data.ReadException;
17
import org.gvsig.fmap.data.feature.Feature;
18
import org.gvsig.fmap.data.feature.FeatureCollection;
19
import org.gvsig.fmap.data.feature.FeatureType;
20
import org.gvsig.fmap.data.feature.InitializeWriterException;
21
import org.gvsig.fmap.data.feature.db.DBFeatureType;
22
import org.gvsig.fmap.data.feature.db.DBParameters;
23
import org.gvsig.fmap.data.feature.db.jdbc.JDBCFeaturesWriter;
24
import org.gvsig.fmap.data.feature.db.jdbc.JDBCResource;
25
import org.gvsig.fmap.data.feature.db.jdbc.JDBCStore;
26
import org.gvsig.fmap.data.feature.db.jdbc.JDBCStoreParameters;
27
import org.gvsig.fmap.geom.primitive.DefaultEnvelope;
28
import org.gvsig.fmap.geom.primitive.Envelope;
29
import org.gvsig.metadata.IMetadata;
30
import org.gvsig.metadata.IMetadataManager;
31
import org.gvsig.metadata.MetadataManager;
32
import org.gvsig.tools.exception.BaseException;
33
import org.postgis.PGbox2d;
34
import org.postgis.PGbox3d;
35
import org.postgresql.util.PGobject;
36

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

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

    
51

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

    
70
                } else{
71
                        for (int i=0;i<fieldsID.length;i++){
72
                                if (this.getDefaultFeatureType().getFieldIndex(fieldsID[i]) < 0) {
73

    
74
                                throw new InitializeException(
75
                                                DATASTORE_NAME,
76
                                                new Exception("Field id '"+ fieldsID[i] +"' (id pos "+ (i+1) +") not Found"));
77

    
78
                                }
79
                        }
80
                }
81

    
82

    
83
        }
84

    
85
        public DataCollection getDataCollection(FeatureType type, String filter, String order) throws ReadException {
86
                try {
87
                        type = this.checkFeatureTypeForCollection(type);
88
                } catch (DataException e) {
89
                        throw new ReadException(this.getName(), e);
90
                }
91

    
92
                if (useSqlSource ){
93
                        if (filter != null || order != null) {
94
                                throw new ReadException("Unsuported filter/order in sqlSource mode",this.getName());
95
                        }
96
                }
97

    
98
                FeatureCollection coll;
99
                if (featureManager == null){
100
                        coll=new PostgresqlFeatureCollection(this,type,filter,order);
101
                }else{
102
                        if ((order != null && order != "")){
103
                                coll=new PostgresqlFeatureCollectionWithFeatureID(featureManager,this,type,filter,order);
104
                        } else{
105
                                if (filter == null || filter == ""){
106
                                        coll=new PostgresqlFeatureCollectionEditing(featureManager,this,type);
107
                                } else {
108
                                        coll=new PostgresqlFeatureCollectionEditingFiltered(featureManager,this,type,filter);
109
                                }
110
                        }
111

    
112

    
113
                }
114
                this.addObserver(new WeakReference(coll));
115

    
116
                return coll;
117
        }
118

    
119
        protected Connection getConnection() throws ReadException{
120
                return super.getConnection();
121

    
122
        }
123

    
124

    
125
        protected void initSqlProperties() throws InitializeException{
126
                PostgresqlStoreParameters dParams = (PostgresqlStoreParameters)this.getParameters();
127
                if (dParams.getSqlSoure() != null){
128
                        this.sqlSource = dParams.getSqlSoure();
129
                        this.useSqlSource = true;
130
                        this.sqlSelectPart = null;
131
                        this.baseWhereClause = null;
132
                        this.baseOrder = null;
133
                } else {
134
                        this.sqlSelectPart = "SELECT " + dParams.getFieldsString() +" FROM "+ dParams.tableID();
135

    
136
                        this.baseWhereClause = dParams.getBaseFilter();
137

    
138
                        if (dParams.getWorkingArea() != null){
139
                                String waWhere = getWorkingAreaFilter(dParams.getWorkingArea(), dParams.getSRISD());
140
                                if (waWhere != null){
141
                                        this.baseWhereClause = "(("+this.baseWhereClause+") and "+waWhere +")";
142
                                }
143

    
144
                        }
145

    
146
                        this.baseOrder = dParams.getBaseOrder();
147
                }
148
        }
149
        private String getWorkingAreaFilter(Envelope env, String strEPSG) {
150
                if (env == null) {
151
                        return null;
152
                }
153
                String wktBox = "GeometryFromText('LINESTRING(" + env.getMinimum(0)
154
                                + " " + env.getMinimum(1) + ", " + env.getMaximum(0) + " "
155
                                + env.getMinimum(1) + ", " + env.getMaximum(0) + " "
156
                                + env.getMaximum(1) + ", " + env.getMinimum(0) + " "
157
                                + env.getMaximum(1) + ")', " + strEPSG + ")";
158

    
159
                return wktBox;
160
        }
161

    
162

    
163
        public boolean canAlterFeatureType() {
164
                return true;
165
        }
166

    
167

    
168
        protected void doDispose() throws CloseException{
169
                super.doDispose();
170
        }
171

    
172

    
173
        public String getName() {
174
                return DATASTORE_NAME;
175
        }
176

    
177

    
178
        protected JDBCFeaturesWriter getFeaturesWriter() throws InitializeWriterException {
179
                JDBCFeaturesWriter writer = new PostgresqlFeaturesWriter();
180
                writer.init(this);
181
                return writer;
182
        }
183

    
184
        public DataExplorer getExplorer() {
185
                // TODO Auto-generated method stub
186
                return null;
187
        }
188

    
189
        public IMetadata getMetadata() throws BaseException {
190
                if (metadata==null){
191
                        IMetadataManager manager=MetadataManager.getManager();
192
                        metadata=manager.create(DATASTORE_NAME);
193
                        Envelope extent=this.getFullExtent();
194
                        metadata.set("extent",extent);
195
                        String srs = this.getDefaultFeatureType().getDefaultSRS();
196
                        metadata.set("srs", srs);
197
                }
198
                if (this.alterMode){
199
                        Envelope extent=(Envelope)metadata.get("extent");
200
                        FeatureCollection featureCollection=(FeatureCollection)getDataCollection();
201
                        if (spatialManager.isFullExtentDirty()){
202
                                if (!featureCollection.isEmpty()){
203
                                        Iterator featureIterator=featureCollection.iterator();
204
                                        extent = ((Feature)featureIterator.next()).getExtent();
205
                                        while(featureIterator.hasNext()){
206
                                                Feature feature=(Feature)featureIterator.next();
207
                                                Envelope boundExtent=feature.getExtent();
208
                                                if (boundExtent!=null) {
209
                                                        extent.add(boundExtent);
210
                                                }
211
                                        }
212
                                }
213
                        }
214
                        metadata.set("extent",extent);
215
                }
216
                return metadata;
217

    
218

    
219
//                if (metadata==null){
220
//                        IMetadata tmp=super.getMetadata();
221
//
222
//                        return tmp;
223
//                }else{
224
//                        return super.getMetadata();
225
//                }
226

    
227
        }
228

    
229
        private Envelope getFullExtent() throws ReadException {
230
                Envelope fullExtent=null;
231
                Statement s = null;
232
                ResultSet r = null;
233

    
234

    
235
                try {
236
                        DBParameters params = this.getParametersPostgresql();
237
                        if (params.getDefaultGeometryField() == null
238
                                        || params.getDefaultGeometryField().length() == 0) {
239
                                return null;
240
                        }
241
                        s = getConnection().createStatement();
242

    
243
                        StringBuffer sql = new StringBuffer();
244
                        sql.append("SELECT extent(");
245
                        sql.append(params.getDefaultGeometryField());
246
                        sql.append(") AS FullExtent FROM ");
247
                        sql.append(params.tableID());
248
                        if (this.getBaseWhereClause() != null
249
                                        && this.getBaseWhereClause() != "") {
250
                                sql.append(" WHERE ");
251
                                sql.append(this.getBaseWhereClause());
252
                        }
253

    
254
                        r = s.executeQuery(sql.toString());
255
                        if (!r.next()) {
256
                                return null;
257
                        }
258
                        PGobject data = (PGobject) r.getObject(1);
259
                        if (data instanceof PGbox3d) {
260
                                PGbox3d box3d = (PGbox3d) data;
261
                                fullExtent = new DefaultEnvelope(
262
                                                box3d.getLLB().x, box3d.getLLB().y,box3d.getLLB().z,
263
                                                box3d.getURT().x, box3d.getURT().y,box3d.getURT().z);
264

    
265
                        } else {
266
                                PGbox2d box2d = (PGbox2d) data;
267
                                fullExtent = new DefaultEnvelope(
268
                                                box2d.getLLB().x, box2d.getLLB().y,
269
                                                box2d.getURT().x, box2d.getURT().y);
270
                        }
271
                        String strAux = r.getString(1);
272
                        System.out.println("fullExtent = " + strAux);
273
                } catch (SQLException e) {
274
                        throw new ReadException(this.getName(),e);
275
                } finally {
276
                        if (r != null) {
277
                                try {
278
                                        r.close();
279
                                } catch (SQLException e) {
280
                                        // TODO Auto-generated catch block
281
                                        e.printStackTrace();
282
                                }
283
                        }
284
                        if (s != null) {
285
                                try {
286
                                        s.close();
287
                                } catch (SQLException e) {
288
                                        // TODO Auto-generated catch block
289
                                        e.printStackTrace();
290
                                }
291

    
292
                        }
293

    
294
                }
295

    
296
                return fullExtent;
297
        }
298

    
299
        protected Feature createFeatureFromResulset(ResultSet rs, DBFeatureType featureType2) throws ReadException {
300
                if (featureType2== null){
301
                        return new PostgresqlFeature(this.getDefaultFeatureType(),this,rs);
302
                }else{
303
                        return new PostgresqlFeature(featureType2,this,rs);
304
                }
305
        }
306

    
307

    
308
        /* (non-Javadoc)
309
         * @see org.gvsig.fmap.data.feature.FeatureStore#doRefresh()
310
         */
311
        protected void doRefresh() throws OpenException, InitializeException {
312
                this.initFeatureType();
313
                this.initSqlProperties();
314
        }
315
        public boolean canWriteGeometry(int gvSIGgeometryType) {
316
                try {
317
                        return getFeaturesWriter().canWriteGeometry(gvSIGgeometryType);
318
                } catch (InitializeWriterException e) {
319
                        e.printStackTrace();
320
                }
321
                return false;
322
        }
323

    
324
        public Feature getByIndex(long index) throws ReadException {
325
                // TODO Auto-generated method stub
326
                return null;
327
        }
328

    
329
}