Statistics
| Revision:

svn-gvsig-desktop / branches / v2_0_0_prep / extensions / org.gvsig.oracle / src / org / gvsig / fmap / dal / store / oracle / OracleHelper.java @ 29932

History | View | Annotate | Download (24.8 KB)

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 Prodevelop S.L. main development
26
 */
27

    
28
package org.gvsig.fmap.dal.store.oracle;
29

    
30
import java.awt.geom.Rectangle2D;
31
import java.sql.Connection;
32
import java.sql.PreparedStatement;
33
import java.sql.ResultSet;
34
import java.sql.ResultSetMetaData;
35
import java.sql.SQLException;
36
import java.sql.Statement;
37
import java.util.ArrayList;
38
import java.util.Comparator;
39
import java.util.Iterator;
40
import java.util.List;
41
import java.util.TreeSet;
42

    
43
import oracle.jdbc.OracleResultSetMetaData;
44
import oracle.sql.ARRAY;
45
import oracle.sql.Datum;
46
import oracle.sql.STRUCT;
47

    
48
import org.cresques.cts.IProjection;
49
import org.gvsig.fmap.crs.CRSFactory;
50
import org.gvsig.fmap.dal.DALLocator;
51
import org.gvsig.fmap.dal.DataManager;
52
import org.gvsig.fmap.dal.DataTypes;
53
import org.gvsig.fmap.dal.exception.DataException;
54
import org.gvsig.fmap.dal.exception.InitializeException;
55
import org.gvsig.fmap.dal.exception.ReadException;
56
import org.gvsig.fmap.dal.feature.EditableFeatureAttributeDescriptor;
57
import org.gvsig.fmap.dal.feature.EditableFeatureType;
58
import org.gvsig.fmap.dal.feature.Feature;
59
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
60
import org.gvsig.fmap.dal.feature.FeatureQuery;
61
import org.gvsig.fmap.dal.feature.FeatureSet;
62
import org.gvsig.fmap.dal.feature.FeatureStore;
63
import org.gvsig.fmap.dal.feature.exception.UnsupportedDataTypeException;
64
import org.gvsig.fmap.dal.feature.exception.UnsupportedGeometryException;
65
import org.gvsig.fmap.dal.resource.spi.ResourceManagerProviderServices;
66
import org.gvsig.fmap.dal.store.jdbc.JDBCHelper;
67
import org.gvsig.fmap.dal.store.jdbc.JDBCHelperUser;
68
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParameters;
69
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCException;
70
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCExecuteSQLException;
71
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCSQLException;
72
import org.gvsig.fmap.geom.Geometry;
73
import org.gvsig.fmap.geom.GeometryLocator;
74
import org.gvsig.fmap.geom.GeometryManager;
75
import org.gvsig.fmap.geom.operation.fromwkb.FromWKB;
76
import org.gvsig.fmap.geom.operation.fromwkb.FromWKBGeometryOperationContext;
77
import org.gvsig.fmap.geom.primitive.Envelope;
78
import org.gvsig.tools.exception.BaseException;
79
import org.postgresql.PGResultSetMetaData;
80
import org.slf4j.Logger;
81
import org.slf4j.LoggerFactory;
82

    
83
/**
84
 * Oracle helper
85
 * 
86
 * @author vsanjaime
87
 * 
88
 */
89
public class OracleHelper extends JDBCHelper {
90

    
91
        private static Logger logger = LoggerFactory.getLogger(OracleHelper.class);
92

    
93
        private boolean tableHasSrid = true;
94
        private String oracleSRID;
95

    
96
        /**
97
         * Constructor
98
         * 
99
         * @param consumer
100
         * @param params
101
         * @throws InitializeException
102
         */
103
        public OracleHelper(JDBCHelperUser consumer,
104
                        OracleConnectionParameters params) throws InitializeException {
105

    
106
                super(consumer, params);
107
        }
108

    
109
        /**
110
         * Initialize resource
111
         */
112
        protected void initializeResource() throws InitializeException {
113
                ResourceManagerProviderServices manager = (ResourceManagerProviderServices) DALLocator
114
                                .getResourceManager();
115
                OracleResource resource = (OracleResource) manager.createResource(
116
                                OracleResource.NAME, new Object[] { params.getUrl(),
117
                                                params.getHost(), params.getPort(), params.getDBName(),
118
                                                params.getUser(), params.getPassword(),
119
                                                params.getJDBCDriverClassName(),
120
                                                ((OracleConnectionParameters) params).getUseSSL(),
121
                                                ((OracleConnectionParameters) params).getOraDriverType() });
122
                this.setResource(resource);
123
        }
124

    
125
        /**
126
         * Get default schema name
127
         * 
128
         * @param conn
129
         * @return
130
         */
131
        protected String getDefaultSchema(Connection conn) throws JDBCException {
132
                if (defaultSchema == null) {
133
                        String sql = "SELECT sys_context('USERENV', 'CURRENT_SCHEMA') FROM dual";
134
                        ResultSet rs = null;
135
                        Statement st = null;
136
                        String schema = null;
137
                        try {
138
                                st = conn.createStatement();
139
                                try {
140
                                        rs = st.executeQuery(sql);
141
                                } catch (java.sql.SQLException e) {
142
                                        throw new JDBCExecuteSQLException(sql, e);
143
                                }
144
                                rs.next();
145
                                schema = rs.getString(1);
146
                        } catch (java.sql.SQLException e) {
147
                                throw new JDBCSQLException(e);
148
                        } finally {
149
                                try {
150
                                        rs.close();
151
                                } catch (Exception e) {
152
                                        logger.error("Exception clossing resulset", e);
153
                                }
154
                                ;
155
                                try {
156
                                        st.close();
157
                                } catch (Exception e) {
158
                                        logger.error("Exception clossing statement", e);
159
                                }
160
                                ;
161
                                rs = null;
162
                                st = null;
163
                        }
164
                        defaultSchema = schema;
165
                }
166

    
167
                return defaultSchema;
168
        }
169

    
170
        /**
171
         * 
172
         */
173
        public Envelope getFullEnvelopeOfField(JDBCStoreParameters storeParams,
174
                        String geometryAttrName, Envelope limit) throws DataException {
175

    
176
                // FIXME
177

    
178
                StringBuilder strb = new StringBuilder();
179
                strb.append("Select asbinary(extent(");
180
                strb.append(escapeFieldName(geometryAttrName));
181
                strb.append(")) from ");
182

    
183
                if (storeParams.getSQL() != null
184
                                && storeParams.getSQL().trim().length() == 0) {
185
                        strb.append('(');
186
                        strb.append(storeParams.getSQL());
187
                        strb.append(") as __extentfield__ ");
188
                } else {
189
                        strb.append(storeParams.tableID());
190
                }
191

    
192
                if (limit != null) {
193
                        strb.append(" where  intersects(GeomFromText('");
194
                        strb.append(limit.toString());
195
                        strb.append("')), boundary(");
196
                        strb.append(escapeFieldName(geometryAttrName));
197
                        strb.append(")) ");
198
                }
199

    
200
                String sql = strb.toString();
201

    
202
                ResultSet rs = null;
203
                Statement st = null;
204
                String schema = null;
205
                Connection conn = null;
206

    
207
                GeometryManager geoMan = GeometryLocator.getGeometryManager();
208

    
209
                Envelope fullEnvelope = null;
210
                this.open();
211
                this.begin();
212
                try {
213
                        conn = getConnection();
214
                        st = conn.createStatement();
215
                        try {
216
                                rs = st.executeQuery(sql);
217
                        } catch (java.sql.SQLException e) {
218
                                throw new JDBCExecuteSQLException(sql, e);
219
                        }
220
                        if (!rs.next()) {
221
                                return null;
222
                        }
223

    
224
                        byte[] data = rs.getBytes(1);
225
                        if (data == null) {
226
                                return null;
227
                        }
228
                        initializeFromWKBOperation();
229
                        fromWKBContext.setData(data);
230
                        Geometry geom = (Geometry) fromWKB.invoke(null, fromWKBContext);
231

    
232
                        fullEnvelope = geom.getEnvelope();
233

    
234
                        return fullEnvelope;
235
                } catch (java.sql.SQLException e) {
236
                        throw new JDBCSQLException(e);
237
                } catch (BaseException e) {
238
                        throw new ReadException(user.getName(), e);
239
                } finally {
240
                        try {
241
                                rs.close();
242
                        } catch (Exception e) {
243
                        }
244
                        ;
245
                        try {
246
                                st.close();
247
                        } catch (Exception e) {
248
                        }
249
                        ;
250
                        try {
251
                                conn.close();
252
                        } catch (Exception e) {
253
                        }
254
                        ;
255
                        rs = null;
256
                        st = null;
257
                        conn = null;
258
                        end();
259
                }
260

    
261
        }
262

    
263
        /**
264
         * 
265
         */
266
        protected void initializeFromWKBOperation() throws BaseException {
267
                if (fromWKB == null) {
268
                        fromWKB = (FromWKB) GeometryLocator.getGeometryManager()
269
                                        .getGeometryOperation(FromWKB.CODE,
270
                                                        Geometry.TYPES.GEOMETRY, Geometry.SUBTYPES.GEOM2D);
271
                        fromWKBContext = new FromWKBGeometryOperationContext();
272
                }
273
        }
274

    
275
        public Geometry getGeometry(byte[] buffer) throws BaseException {
276
                if (buffer == null) {
277
                        return null;
278
                }
279
                initializeFromWKBOperation();
280
                Geometry geom;
281
                try {
282
                        fromWKBContext.setData(buffer);
283

    
284
                        geom = (Geometry) fromWKB.invoke(null, fromWKBContext);
285
                } finally {
286
                        fromWKBContext.setData(null);
287
                }
288
                return geom;
289
        }
290

    
291
        /**
292
         * get geometry column name "SDO_GEOMETRY"
293
         */
294
        public String getSqlColumnTypeDescription(FeatureAttributeDescriptor attr) {
295

    
296
                switch (attr.getDataType()) {
297

    
298
                case DataTypes.GEOMETRY:
299
                        return "SDO_GEOMETRY";
300

    
301
                case DataTypes.STRING:
302
                        return "VARCHAR2(" + attr.getSize() + ")";
303

    
304
                case DataTypes.BOOLEAN:
305
                        return "NUMBER(1, 0)";
306

    
307
                case DataTypes.BYTE:
308
                        return "NUMBER";
309

    
310
                case DataTypes.DATE:
311
                        return "DATE";
312

    
313
                case DataTypes.TIMESTAMP:
314
                        return "TIMESTAMP";
315

    
316
                case DataTypes.TIME:
317
                        return "TIMESTAMP";
318

    
319
                case DataTypes.BYTEARRAY:
320

    
321
                case DataTypes.DOUBLE:
322
                        return "FLOAT";
323

    
324
                case DataTypes.FLOAT:
325
                        return "FLOAT";
326

    
327
                case DataTypes.INT:
328
                        return "NUMBER(12, 0)";
329

    
330
                case DataTypes.LONG:
331
                        return "NUMBER(38, 0)";
332

    
333
                default:
334
                        String typeName = (String) attr.getAdditionalInfo("SQLTypeName");
335
                        if (typeName != null) {
336
                                return typeName;
337
                        }
338
                        throw new UnsupportedDataTypeException(attr.getDataTypeName(), attr
339
                                        .getDataType());
340
                }
341

    
342
        }
343

    
344
        /**
345
         * Get geometry dimension
346
         * 
347
         * @param geometrySubType
348
         * @return
349
         */
350
        public int getOraGeomDimensions(int geometrySubType) {
351
                switch (geometrySubType) {
352
                case Geometry.SUBTYPES.GEOM2D:
353
                        return 2;
354
                case Geometry.SUBTYPES.GEOM2DM:
355
                case Geometry.SUBTYPES.GEOM3D:
356
                        return 3;
357

    
358
                case Geometry.SUBTYPES.GEOM3DM:
359
                        return 4;
360
                default:
361
                        throw new UnsupportedDataTypeException(
362
                                        DataTypes.TYPE_NAMES[DataTypes.GEOMETRY],
363
                                        DataTypes.GEOMETRY);
364
                }
365
        }
366

    
367
        /**
368
         * Get Oracle geometry type
369
         * 
370
         * @param geometryType
371
         * @param geometrySubType
372
         * @return
373
         */
374
        public String getOraGeomType(int geometryType, int geometrySubType) {
375
                String oraGeomType;
376
                switch (geometryType) {
377
                case Geometry.TYPES.GEOMETRY:
378
                        oraGeomType = OracleValues.OraGeometry_GTYPE_GEOMETRY;
379
                        break;
380
                case Geometry.TYPES.POINT:
381
                        oraGeomType = OracleValues.OraGeometry_GTYPE_POINT;
382
                        break;
383
                case Geometry.TYPES.CURVE:
384
                        oraGeomType = OracleValues.OraGeometry_GTYPE_CURVE;
385
                        break;
386
                case Geometry.TYPES.TEXT:
387
                        oraGeomType = OracleValues.OraGeometry_GTYPE_GEOMETRY;
388
                        break;
389
                case Geometry.TYPES.SOLID:
390
                        oraGeomType = OracleValues.OraGeometry_GTYPE_GEOMETRY;
391
                        break;
392
                case Geometry.TYPES.AGGREGATE:
393
                        oraGeomType = OracleValues.OraGeometry_GTYPE_GEOMETRY;
394
                        break;
395
                case Geometry.TYPES.SURFACE:
396
                        oraGeomType = OracleValues.OraGeometry_GTYPE_POLYGON;
397
                        break;
398
                case Geometry.TYPES.MULTIPOINT:
399
                        oraGeomType = OracleValues.OraGeometry_GTYPE_MULTIPOINT;
400
                        break;
401
                case Geometry.TYPES.MULTICURVE:
402
                        oraGeomType = OracleValues.OraGeometry_GTYPE_MULTICURVE;
403
                        break;
404
                case Geometry.TYPES.MULTISURFACE:
405
                        oraGeomType = OracleValues.OraGeometry_GTYPE_MULTIPOLYGON;
406
                        break;
407
                case Geometry.TYPES.MULTISOLID:
408
                        oraGeomType = OracleValues.OraGeometry_GTYPE_GEOMETRY;
409
                        break;
410
                case Geometry.TYPES.CIRCLE:
411
                        oraGeomType = OracleValues.OraGeometry_GTYPE_GEOMETRY;
412
                        break;
413
                case Geometry.TYPES.ARC:
414
                        oraGeomType = OracleValues.OraGeometry_GTYPE_GEOMETRY;
415
                        break;
416
                case Geometry.TYPES.ELLIPSE:
417
                        oraGeomType = OracleValues.OraGeometry_GTYPE_GEOMETRY;
418
                        break;
419
                case Geometry.TYPES.SPLINE:
420
                        oraGeomType = OracleValues.OraGeometry_GTYPE_GEOMETRY;
421
                        break;
422
                case Geometry.TYPES.ELLIPTICARC:
423
                        oraGeomType = OracleValues.OraGeometry_GTYPE_GEOMETRY;
424
                        break;
425
                default:
426
                        throw new UnsupportedGeometryException(geometryType,
427
                                        geometrySubType);
428
                }
429
                return oraGeomType;
430
        }
431

    
432
        /**
433
         * Get oracle srid from srs code(EPSG code)
434
         */
435
        public int getProviderSRID(String epsg) {
436

    
437
                DataManager manager = DALLocator.getDataManager();
438
                Integer isrs = null;
439
                if (epsg != null) {
440
                        FeatureStore oraSrsStore = (FeatureStore) OracleLibrary
441
                                        .getSRSDataStore();
442

    
443
                        FeatureSet set = null;
444
                        try {
445
                                FeatureQuery query = oraSrsStore.createFeatureQuery();
446
                                query.setFilter(manager.createExpresion("EPSG = " + epsg));
447
                                set = (FeatureSet) oraSrsStore.getDataSet(query);
448
                                if (set.getSize() > 0) {
449
                                        Iterator<Feature> it = set.iterator();
450
                                        while (it.hasNext()) {
451
                                                Feature feat = it.next();
452
                                                Double ora = feat.getDouble("ORACLE");
453
                                                int iora = ora.intValue();
454
                                                double prefe = feat.getDouble("PRF_ORACLE");
455
                                                if (prefe == 1) {
456
                                                        isrs = new Integer(iora);
457
                                                        break;
458
                                                }
459
                                        }
460
                                }
461
                        } catch (DataException e) {
462
                                e.printStackTrace();
463
                        }
464
                        if (isrs != null) {
465
                                return isrs;
466
                        }
467
                }
468
                return -1;
469
        }
470

    
471
        /**
472
         * Get oracle srid from srs code(EPSG code)
473
         */
474
        public int getProviderEPSG(String srid) {
475

    
476
                DataManager manager = DALLocator.getDataManager();
477
                Integer isrs = null;
478
                if (srid != null) {
479
                        FeatureStore oraSrsStore = (FeatureStore) OracleLibrary
480
                                        .getSRSDataStore();
481

    
482
                        FeatureSet set = null;
483
                        try {
484
                                FeatureQuery query = oraSrsStore.createFeatureQuery();
485
                                query.setFilter(manager.createExpresion("ORACLE = " + srid));
486
                                set = (FeatureSet) oraSrsStore.getDataSet(query);
487
                                if (set.getSize() > 0) {
488
                                        Iterator<Feature> it = set.iterator();
489
                                        while (it.hasNext()) {
490
                                                Feature feat = it.next();
491
                                                Double ora = feat.getDouble("EPSG");
492
                                                int iora = ora.intValue();
493
                                                isrs = new Integer(iora);
494
                                        }
495
                                }
496
                        } catch (DataException e) {
497
                                e.printStackTrace();
498
                        }
499
                        if (isrs != null) {
500
                                return isrs;
501
                        }
502
                }
503
                return -1;
504
        }
505

    
506
        /**
507
         * Get oracle srid from gvSIG projection
508
         * 
509
         * @param proj
510
         */
511
        public int getProviderSRID(IProjection proj) {
512
                if (proj != null) {
513
                        String epsg = proj.getAbrev().trim();
514
                        int ocu = epsg.indexOf(":");
515
                        if (ocu != -1) {
516
                                epsg = epsg.substring(ocu + 1);
517
                        }
518
                        Integer oraSRID = getProviderSRID(epsg);
519
                        if (oraSRID != null) {
520
                                return oraSRID.intValue();
521
                        }
522
                }
523
                return -1;
524
        }
525

    
526

    
527

    
528
        
529

    
530
        public String getSqlFieldName(FeatureAttributeDescriptor attribute) {
531
                if (attribute.getDataType() == DataTypes.GEOMETRY) {
532
                        return "asBinary(" + super.getSqlFieldName(attribute) + ")";
533
                }
534
                return super.getSqlFieldName(attribute);
535
        }
536

    
537
        protected EditableFeatureAttributeDescriptor createAttributeFromJDBC(
538
                        EditableFeatureType type, Connection conn,
539
                        ResultSetMetaData rsMetadata, int colIndex) throws SQLException {
540
                String rstypename = rsMetadata.getColumnTypeName(colIndex);
541
                if (rstypename
542
                                .equalsIgnoreCase(OracleValues.OraGeometry_GTYPE_GEOMETRY)) {
543

    
544
                        return type.add(rsMetadata.getColumnName(colIndex),
545
                                        DataTypes.GEOMETRY);
546
                }
547

    
548
                return super.createAttributeFromJDBC(type, conn, rsMetadata, colIndex);
549
        }
550

    
551
        public boolean allowAutomaticValues() {
552
                return Boolean.TRUE;
553
        }
554

    
555
        public boolean supportOffset() {
556
                return true;
557
        }
558

    
559
        public boolean supportsUnion() {
560
                return true;
561
        }
562

    
563
        /**
564
         * get sql with fields description
565
         * @param attr
566
         * @return 
567
         */
568
        public String getSqlFieldDescription(FeatureAttributeDescriptor attr)
569
                        throws DataException {
570

    
571
                StringBuilder strb = new StringBuilder();
572
                // name
573
                strb.append(attr.getName());
574
                strb.append(" ");
575

    
576
                // Type
577
                strb.append(this.getSqlColumnTypeDescription(attr));
578
                strb.append(" ");
579

    
580
                return strb.toString();
581
        }
582

    
583
        
584
        
585
         /**
586
     * UTility method to get the SQL sentence needed to update the geographic metadata table
587
     * with a new bounding box and SRS
588
     *
589
     * @param tName table name
590
     * @param ora_srid new SRS
591
     * @param bbox new bounding box
592
     * @param dim geometries dimension
593
     * @param withsrid False if the SRS is set to NULL. True otherwise.
594
     * @return the SQL sentence to perform the update
595
     */
596
    public String getSqlUpdateMetadata(OracleStoreParameters params, String ora_srid,
597
        Rectangle2D bbox, int dim, boolean withsrid) {
598
            
599
        String[] dim_name = new String[dim];
600
        double tolerance = 0.5;
601
        
602
        String _ora_srid = ora_srid;
603
        if (_ora_srid == null) _ora_srid = "NULL";
604

    
605
        if (_ora_srid.compareTo(OracleValues.GEODETIC_SRID) == 0) {
606
            dim_name[0] = "LONGITUDE";
607
            dim_name[1] = "LATITUDE";
608
        }
609
        else {
610
            dim_name[0] = "X";
611
            dim_name[1] = "Y";
612

    
613
            if (dim > 2) {
614
                dim_name[2] = "Z";
615

    
616
                if (dim > 3) {
617
                    dim_name[3] = "T";
618
                }
619
            }
620
        }
621
        
622
        double minx = bbox.getMinX();
623
        double miny = bbox.getMinY();
624
        double maxx = bbox.getMaxX();
625
        double maxy = bbox.getMaxY();
626
        
627
        String resp = "INSERT INTO " + OracleValues.USER_ORACLE_GEOMETADATA_VIEW + " " +
628
            " ( TABLE_NAME, COLUMN_NAME, DIMINFO, SRID ) " + " VALUES ("
629
            + "'" + params.getTable() + "', "
630
            + "'" + OracleValues.DEFAULT_GEO_FIELD + "', " +
631
            "MDSYS.SDO_DIM_ARRAY( " + "MDSYS.SDO_DIM_ELEMENT ('" + dim_name[0] + "', " +
632
            minx + ", " + maxx + ", " + tolerance + " ), " +
633
            "MDSYS.SDO_DIM_ELEMENT ('" + dim_name[1] + "', " + miny + ", " +
634
            maxy + ", " + tolerance + " ))";
635

    
636
        if (dim > 2) {
637
            resp = resp.substring(0, resp.length() - 1) + ",";
638
            resp = resp + "MDSYS.SDO_DIM_ELEMENT ('" + dim_name[2] +
639
                "', 0.0, 100.0, " + tolerance + " ))";
640

    
641
            if (dim > 3) {
642
                resp = resp.substring(0, resp.length() - 1) + ",";
643
                resp = resp + "MDSYS.SDO_DIM_ELEMENT ('" + dim_name[3] +
644
                    "', 0.0, 100.0, " + tolerance + " ))";
645
            }
646
        }
647

    
648
        if (withsrid) {
649
            resp = resp + ", " + _ora_srid + " )";
650
        }
651
        else {
652
            resp = resp + ", NULL )";
653
        }
654

    
655
        return resp;
656
    }        
657

    
658

    
659
        public void loadFeatureType(EditableFeatureType featureType,
660
                        JDBCStoreParameters storeParams) throws DataException {
661
                if (storeParams.getSQL() != null
662
                                && storeParams.getSQL().trim().length() == 0) {
663
                        loadFeatureType(featureType, storeParams, storeParams.getSQL(),
664
                                        null, null);
665
                } else {
666
                        String sql = "select * from " + storeParams.tableID()
667
                                        + " where rowid > (select rowid from "
668
                                        + storeParams.tableID()
669
                                        + " where rownum =1) and rownum = 1";
670

    
671
                        loadFeatureType(featureType, storeParams, sql, storeParams
672
                                        .getSchema(), storeParams.getTable());
673
                }
674
        }
675

    
676
        
677
        /**
678
         * Fill <code>featureType</code> geometry attributes with SRS and ShapeType
679
         * information stored in the table GEOMETRY_COLUMNS
680
         * 
681
         * @param conn
682
         * @param rsMetadata
683
         * @param featureType
684
         * @throws ReadException
685
         */
686
        protected void loadSRS_and_shapeType(Connection conn,
687
                        ResultSetMetaData rsMetadata, EditableFeatureType featureType,
688
                        String baseSchema, String baseTable) throws JDBCException {
689

    
690
                Statement st = null;
691
                ResultSet rs = null;
692
                try {
693
                        // Sacamos la lista de los attributos geometricos
694
                        EditableFeatureAttributeDescriptor attr;
695
                        List geoAttrs = new ArrayList();
696

    
697
                        Iterator iter = featureType.iterator();
698
                        while (iter.hasNext()) {
699
                                attr = (EditableFeatureAttributeDescriptor) iter.next();
700
                                if (attr.getDataType() == DataTypes.GEOMETRY) {
701
                                        geoAttrs.add(attr);
702
                                }
703
                        }
704
                        if (geoAttrs.size() < 1) {
705
                                return;
706
                        }
707

    
708
                        // preparamos un set con las lista de tablas de origen
709
                        // de los campos
710
                        class TableId {
711
                                public String schema = null;
712
                                public String table = null;
713
                                public String field = null;
714

    
715
                                public void appendToSQL(StringBuilder strb) {
716
                                        if (schema == null || schema.length() == 0) {
717
                                                strb
718
                                                                .append("( F_TABLE_SCHEMA = current_schema() AND F_TABLE_NAME = '");
719
                                        } else {
720
                                                strb.append("( F_TABLE_SCHEMA = '");
721
                                                strb.append(schema);
722
                                                strb.append("' AND F_TABLE_NAME = '");
723
                                        }
724
                                        strb.append(table);
725
                                        strb.append("' AND F_GEOMETRY_COLUMN = '");
726
                                        strb.append(field);
727
                                        strb.append("' )");
728
                                }
729

    
730
                        }
731
                        Comparator cmp = new Comparator() {
732
                                public int compare(Object arg0, Object arg1) {
733
                                        TableId a0 = (TableId) arg0;
734
                                        TableId a1 = (TableId) arg1;
735

    
736
                                        if (!a0.field.equals(a1.field)) {
737
                                                return -1;
738
                                        }
739
                                        if (!a0.table.equals(a1.table)) {
740
                                                return -1;
741
                                        }
742
                                        if (!a0.schema.equals(a1.schema)) {
743
                                                return -1;
744
                                        }
745
                                        return 0;
746
                                }
747
                        };
748
                        TreeSet set = new TreeSet(cmp);
749
                        TableId tableId;
750
                        iter = geoAttrs.iterator();
751
                        int rsIndex;
752
                        while (iter.hasNext()) {
753
                                attr = (EditableFeatureAttributeDescriptor) iter.next();
754
                                tableId = new TableId();
755
                                rsIndex = attr.getIndex() + 1;
756

    
757
                                if (baseSchema == null && baseTable == null) {
758
                                        if (rsMetadata instanceof OracleResultSetMetaData) {
759
                                                tableId.schema = ((ResultSetMetaData) rsMetadata)
760
                                                                .getSchemaName(rsIndex);
761
                                                tableId.table = ((ResultSetMetaData) rsMetadata)
762
                                                                .getTableName(rsIndex);
763
                                                tableId.field = ((ResultSetMetaData) rsMetadata)
764
                                                                .getColumnName(rsIndex);
765

    
766
                                        } else {
767
                                                tableId.schema = rsMetadata.getSchemaName(rsIndex);
768
                                                tableId.table = rsMetadata.getTableName(rsIndex);
769
                                                tableId.field = rsMetadata.getColumnName(rsIndex);
770
                                        }
771
                                } else {
772
                                        tableId.schema = baseSchema;
773
                                        tableId.table = baseTable;
774
                                        tableId.field = rsMetadata.getColumnName(rsIndex);
775
                                }
776
                                if (tableId.table == null || tableId.table.length() == 0) {
777
                                        // Si no tiene tabla origen (viene de algun calculo por ej.)
778
                                        // lo saltamos ya que no estara en la tabla GEOMETRY_COLUMNS
779
                                        continue;
780
                                }
781
                                set.add(tableId);
782
                        }
783

    
784
                        if (set.size() == 0) {
785
                                return;
786
                        }
787

    
788
                        // Preparamos una sql para que nos saque el resultado
789
                        StringBuilder strb = new StringBuilder();
790
                        strb
791
                                        .append("Select geometry_columns.*,auth_name || ':' || auth_srid as SRSID ");
792
                        strb.append("from geometry_columns left join spatial_ref_sys on ");
793
                        strb.append("geometry_columns.srid = spatial_ref_sys.srid WHERE ");
794
                        iter = set.iterator();
795
                        for (int i = 0; i < set.size() - 1; i++) {
796
                                tableId = (TableId) iter.next();
797
                                tableId.appendToSQL(strb);
798
                                strb.append(" OR ");
799
                        }
800
                        tableId = (TableId) iter.next();
801
                        tableId.appendToSQL(strb);
802
                        String sql = strb.toString();
803

    
804
                        st = conn.createStatement();
805
                        try {
806
                                rs = st.executeQuery(sql);
807
                        } catch (SQLException e) {
808
                                throw new JDBCExecuteSQLException(sql, e);
809
                        }
810
                        String srsID;
811
                        int pgSrid;
812
                        int geometryType;
813
                        int geometrySubtype;
814
                        String geomTypeStr;
815
                        int dimensions;
816
                        IProjection srs;
817

    
818
                        while (rs.next()) {
819
                                srsID = rs.getString("SRSID");
820
                                pgSrid = rs.getInt("SRID");
821
                                geomTypeStr = rs.getString("TYPE").toUpperCase();
822
                                geometryType = Geometry.TYPES.GEOMETRY;
823
                                if (geomTypeStr.startsWith("POINT")) {
824
                                        geometryType = Geometry.TYPES.POINT;
825
                                } else if (geomTypeStr.startsWith("LINESTRING")) {
826
                                        geometryType = Geometry.TYPES.CURVE;
827
                                } else if (geomTypeStr.startsWith("POLYGON")) {
828
                                        geometryType = Geometry.TYPES.SURFACE;
829
                                } else if (geomTypeStr.startsWith("MULTIPOINT")) {
830
                                        geometryType = Geometry.TYPES.MULTIPOINT;
831
                                } else if (geomTypeStr.startsWith("MULTILINESTRING")) {
832
                                        geometryType = Geometry.TYPES.MULTICURVE;
833
                                } else if (geomTypeStr.startsWith("MULTIPOLYGON")) {
834
                                        geometryType = Geometry.TYPES.MULTISURFACE;
835
                                }
836
                                dimensions = rs.getInt("coord_dimension");
837
                                geometrySubtype = Geometry.SUBTYPES.GEOM2D;
838
                                if (dimensions > 2) {
839
                                        if (dimensions == 3) {
840
                                                if (geomTypeStr.endsWith("M")) {
841
                                                        geometrySubtype = Geometry.SUBTYPES.GEOM2DM;
842
                                                } else {
843
                                                        geometrySubtype = Geometry.SUBTYPES.GEOM3D;
844
                                                }
845

    
846
                                        } else {
847
                                                geometrySubtype = Geometry.SUBTYPES.GEOM3DM;
848
                                        }
849
                                }
850

    
851
                                iter = geoAttrs.iterator();
852
                                while (iter.hasNext()) {
853
                                        attr = (EditableFeatureAttributeDescriptor) iter.next();
854
                                        rsIndex = attr.getIndex() + 1;
855
                                        if (!rsMetadata.getColumnName(rsIndex).equals(
856
                                                        rs.getString("f_geometry_column"))) {
857
                                                continue;
858
                                        }
859

    
860
                                        if (baseSchema == null && baseTable == null) {
861

    
862
                                                if (rsMetadata instanceof PGResultSetMetaData) {
863
                                                        if (!((PGResultSetMetaData) rsMetadata)
864
                                                                        .getBaseTableName(rsIndex).equals(
865
                                                                                        rs.getString("f_table_name"))) {
866
                                                                continue;
867
                                                        }
868
                                                        String curSchema = rs.getString("f_table_schema");
869
                                                        String metaSchema = ((PGResultSetMetaData) rsMetadata)
870
                                                                        .getBaseSchemaName(rsIndex);
871
                                                        if (!metaSchema.equals(curSchema)) {
872
                                                                if (metaSchema.length() == 0
873
                                                                                && metaSchema == getDefaultSchema(conn)) {
874
                                                                } else {
875
                                                                        continue;
876
                                                                }
877
                                                        }
878

    
879
                                                } else {
880

    
881
                                                        if (!rsMetadata.getTableName(rsIndex).equals(
882
                                                                        rs.getString("f_table_name"))) {
883
                                                                continue;
884
                                                        }
885
                                                        String curSchema = rs.getString("f_table_schema");
886
                                                        String metaSchema = rsMetadata
887
                                                                        .getSchemaName(rsIndex);
888
                                                        if (!metaSchema.equals(curSchema)) {
889
                                                                if (metaSchema.length() == 0
890
                                                                                && metaSchema == getDefaultSchema(conn)) {
891
                                                                } else {
892
                                                                        continue;
893
                                                                }
894
                                                        }
895
                                                }
896
                                        }
897
                                        attr.setGeometryType(geometryType);
898
                                        attr.setGeometrySubType(geometrySubtype);
899
                                        if (srsID != null && srsID.length() > 0) {
900
                                                attr.setSRS(CRSFactory.getCRS(srsID));
901
                                        }
902
                                        iter.remove();
903
                                }
904
                                iter = geoAttrs.iterator();
905
                                while (iter.hasNext()) {
906
                                        attr = (EditableFeatureAttributeDescriptor) iter.next();
907
                                        attr.setSRS(null);
908
                                        attr.setGeometryType(Geometry.TYPES.GEOMETRY);
909

    
910
                                }
911
                        }
912

    
913
                } catch (java.sql.SQLException e) {
914
                        throw new JDBCSQLException(e);
915
                } finally {
916
                        try {
917
                                rs.close();
918
                        } catch (Exception e) {
919
                        }
920
                        ;
921
                        try {
922
                                st.close();
923
                        } catch (Exception e) {
924
                        }
925
                        ;
926
                }
927

    
928
        }
929

    
930
        
931

    
932
}