Statistics
| Revision:

root / branches / v2_0_0_prep / extensions / org.gvsig.oracle / src / org / gvsig / fmap / dal / store / oracle / OracleHelper.java @ 31889

History | View | Annotate | Download (26.2 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.ResultSet;
33
import java.sql.ResultSetMetaData;
34
import java.sql.SQLException;
35
import java.sql.Statement;
36
import java.util.ArrayList;
37
import java.util.Arrays;
38
import java.util.Iterator;
39
import java.util.List;
40

    
41
import oracle.sql.ARRAY;
42
import oracle.sql.Datum;
43
import oracle.sql.STRUCT;
44

    
45
import org.cresques.cts.IProjection;
46
import org.gvsig.fmap.crs.CRSFactory;
47
import org.gvsig.fmap.dal.DALLocator;
48
import org.gvsig.fmap.dal.DataManager;
49
import org.gvsig.fmap.dal.DataTypes;
50
import org.gvsig.fmap.dal.exception.DataException;
51
import org.gvsig.fmap.dal.exception.InitializeException;
52
import org.gvsig.fmap.dal.exception.ReadException;
53
import org.gvsig.fmap.dal.feature.EditableFeatureAttributeDescriptor;
54
import org.gvsig.fmap.dal.feature.EditableFeatureType;
55
import org.gvsig.fmap.dal.feature.Feature;
56
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
57
import org.gvsig.fmap.dal.feature.FeatureQuery;
58
import org.gvsig.fmap.dal.feature.FeatureSet;
59
import org.gvsig.fmap.dal.feature.FeatureStore;
60
import org.gvsig.fmap.dal.feature.FeatureType;
61
import org.gvsig.fmap.dal.feature.exception.UnsupportedDataTypeException;
62
import org.gvsig.fmap.dal.feature.exception.UnsupportedGeometryException;
63
import org.gvsig.fmap.dal.feature.impl.DefaultEditableFeatureAttributeDescriptor;
64
import org.gvsig.fmap.dal.feature.impl.DefaultEditableFeatureType;
65
import org.gvsig.fmap.dal.feature.impl.DefaultFeatureType;
66
import org.gvsig.fmap.dal.resource.spi.ResourceManagerProviderServices;
67
import org.gvsig.fmap.dal.store.jdbc.JDBCHelper;
68
import org.gvsig.fmap.dal.store.jdbc.JDBCHelperUser;
69
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParameters;
70
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCException;
71
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCExecuteSQLException;
72
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCSQLException;
73
import org.gvsig.fmap.geom.Geometry;
74
import org.gvsig.fmap.geom.Geometry.SUBTYPES;
75
import org.gvsig.fmap.geom.Geometry.TYPES;
76
import org.gvsig.fmap.geom.primitive.Envelope;
77
import org.gvsig.fmap.geom.primitive.Point;
78
import org.gvsig.fmap.geom.primitive.impl.Envelope2D;
79
import org.gvsig.fmap.geom.primitive.impl.Envelope3D;
80
import org.gvsig.fmap.geom.primitive.impl.Point2DZ;
81
import org.gvsig.tools.exception.BaseException;
82
import org.slf4j.Logger;
83
import org.slf4j.LoggerFactory;
84

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

    
93
        private static final double ORACLE_SPATIAL_DEFAULT_TOLERANCE = 0.0005;
94

    
95
        private static final String IDENTIFIER_QUOTE_STRING = "\"";
96

    
97
        private static Logger logger = LoggerFactory.getLogger(OracleHelper.class);
98

    
99
        private boolean tableHasSrid = true;
100
        private String oracleSRID;
101

    
102
        /**
103
         * Constructor
104
         * 
105
         * @param consumer
106
         * @param params
107
         * @throws InitializeException
108
         */
109
        public OracleHelper(JDBCHelperUser consumer,
110
                        OracleConnectionParameters params) throws InitializeException {
111

    
112
                super(consumer, params);
113
        }
114

    
115
        /**
116
         * Initialize resource
117
         * 
118
         * @throws InitializeException
119
         */
120
        protected void initializeResource() throws InitializeException {
121
                ResourceManagerProviderServices manager = (ResourceManagerProviderServices) DALLocator
122
                                .getResourceManager();
123
                OracleResource resource = (OracleResource) manager.createResource(
124
                                OracleResource.NAME, new Object[] {
125
                                                params.getUrl(),
126
                                                params.getHost(),
127
                                                params.getPort(),
128
                                                params.getDBName(),
129
                                                params.getUser(),
130
                                                params.getPassword(),
131
                                                params.getJDBCDriverClassName(),
132
                                                ((OracleConnectionParameters) params).getUseSSL(),
133
                                                ((OracleConnectionParameters) params)
134
                                                                .getOraDriverType() });
135
                this.setResource(resource);
136
        }
137

    
138
        /**
139
         * Get default schema name
140
         * 
141
         * @param conn
142
         * @return
143
         */
144
        protected String getDefaultSchema(Connection conn) throws JDBCException {
145
                if (defaultSchema == null) {
146
                        String sql = "SELECT sys_context('USERENV', 'CURRENT_SCHEMA') FROM dual";
147
                        ResultSet rs = null;
148
                        Statement st = null;
149
                        String schema = null;
150
                        try {
151
                                st = conn.createStatement();
152
                                try {
153
                                        rs = st.executeQuery(sql);
154
                                } catch (java.sql.SQLException e) {
155
                                        throw new JDBCExecuteSQLException(sql, e);
156
                                }
157
                                rs.next();
158
                                schema = rs.getString(1);
159
                        } catch (java.sql.SQLException e) {
160
                                throw new JDBCSQLException(e);
161
                        } finally {
162
                                try {
163
                                        rs.close();
164
                                } catch (Exception e) {
165
                                        logger.error("Exception clossing resulset", e);
166
                                }
167
                                ;
168
                                try {
169
                                        st.close();
170
                                } catch (Exception e) {
171
                                        logger.error("Exception clossing statement", e);
172
                                }
173
                                ;
174
                                rs = null;
175
                                st = null;
176
                        }
177
                        defaultSchema = schema;
178
                }
179

    
180
                return defaultSchema;
181
        }
182

    
183
        /**
184
         * get full envelope of geometry field
185
         */
186
        public Envelope getFullEnvelopeOfField(JDBCStoreParameters storeParams,
187
                        String geometryAttrName, Envelope limit) throws DataException {
188

    
189
                StringBuilder strb = new StringBuilder();
190
                strb.append("SELECT * FROM "
191
                                + OracleValues.USER_ORACLE_GEOMETADATA_VIEW);
192
                strb.append(" WHERE "
193
                                + OracleValues.USER_ORACLE_GEOMETADATA_VIEW_TABLE_NAME
194
                                + " = '" + storeParams.getTable() + "'");
195
                strb.append(" AND "
196
                                + OracleValues.USER_ORACLE_GEOMETADATA_VIEW_COLUMN_NAME
197
                                + " = '" + geometryAttrName + "'");
198
                String sql = strb.toString();
199

    
200
                ResultSet rs = null;
201
                Statement st = null;
202
                String schema = null;
203
                Connection conn = null;
204

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

    
219
                        // DIMINFO (ARRAY)
220
                        ARRAY dim_info_array = (ARRAY) rs.getObject("DIMINFO");
221

    
222
                        Datum[] da = dim_info_array.getOracleArray();
223
                        int dim = da.length;
224

    
225
                        STRUCT sx = (STRUCT) da[0];
226
                        STRUCT sy = (STRUCT) da[1];
227
                        double minx = Double.parseDouble(sx.getAttributes()[1].toString());
228
                        double maxx = Double.parseDouble(sx.getAttributes()[2].toString());
229
                        double miny = Double.parseDouble(sy.getAttributes()[1].toString());
230
                        double maxy = Double.parseDouble(sy.getAttributes()[2].toString());
231
                        if (minx > maxx) {
232
                                double aux = minx;
233
                                minx = maxx;
234
                                maxx = aux;
235
                        }
236

    
237
                        if (miny > maxy) {
238
                                double aux = miny;
239
                                miny = maxy;
240
                                maxy = aux;
241
                        }
242

    
243
                        // dim 3
244
                        STRUCT sz = null;
245
                        double minz = 0;
246
                        double maxz = 0;
247
                        if (dim == 2) {
248
                                fullEnvelope = new Envelope2D(minx, miny, maxx, maxy);
249
                        } else if (dim == 3) {
250
                                sz = (STRUCT) da[2];
251
                                minz = Double.parseDouble(sz.getAttributes()[1].toString());
252
                                maxz = Double.parseDouble(sz.getAttributes()[2].toString());
253

    
254
                                Point minPto = new Point2DZ(minx, miny, minz);
255
                                Point maxPto = new Point2DZ(maxx, maxy, maxz);
256

    
257
                                fullEnvelope = new Envelope3D(minPto, maxPto);
258
                        }
259

    
260
                        return fullEnvelope;
261

    
262
                } catch (Exception e) {
263
                        return null;
264
                }
265

    
266
                finally {
267
                        try {
268
                                rs.close();
269
                        } catch (Exception e) {
270
                        }
271

    
272
                        try {
273
                                st.close();
274
                        } catch (Exception e) {
275
                        }
276

    
277
                        try {
278
                                conn.close();
279
                        } catch (Exception e) {
280
                        }
281

    
282
                        finally {
283
                                rs = null;
284
                                st = null;
285
                                conn = null;
286
                        }
287
                }
288
        }
289

    
290
        /**
291
         * 
292
         */
293
//        protected void initializeFromWKBOperation() throws BaseException {
294
//                // TODO
295
//                if (fromWKB == null) {
296
//                        fromWKB = (FromWKB) GeometryLocator.getGeometryManager()
297
//                                        .getGeometryOperation(FromWKB.CODE,
298
//                                                        Geometry.TYPES.GEOMETRY, Geometry.SUBTYPES.GEOM2D);
299
//                        fromWKBContext = new FromWKBGeometryOperationContext();
300
//                }
301
//        }
302

    
303
        /**
304
         * 
305
         */
306
        public Geometry getGeometry(byte[] buffer) throws BaseException {
307
                // TODO BLOB format in Oracle?
308
                logger.error("Unsupported: binary Geometry format");
309
                return null;
310
        }
311

    
312
        /**
313
         * get geometry column name "SDO_GEOMETRY"
314
         * 
315
         * @param attr
316
         * @return
317
         */
318
        public String getSqlColumnTypeDescription(FeatureAttributeDescriptor attr) {
319

    
320
                switch (attr.getDataType()) {
321

    
322
                case DataTypes.GEOMETRY:
323
                        return "\"MDSYS\".\"SDO_GEOMETRY\"";
324

    
325
                case DataTypes.STRING:
326
                        return "NVARCHAR2(" + attr.getSize() + ")";
327

    
328
                case DataTypes.BOOLEAN:
329
                        return "NUMBER(1, 0)";
330

    
331
                case DataTypes.BYTE:
332
                        return "NUMBER";
333

    
334
                case DataTypes.DATE:
335
                        return "DATE";
336

    
337
                case DataTypes.TIMESTAMP:
338
                        return "TIMESTAMP";
339

    
340
                case DataTypes.TIME:
341
                        return "TIMESTAMP";
342

    
343
                case DataTypes.BYTEARRAY:
344

    
345
                case DataTypes.DOUBLE:
346
                        return "FLOAT";
347

    
348
                case DataTypes.FLOAT:
349
                        return "FLOAT";
350

    
351
                case DataTypes.INT:
352
                        return "NUMBER(12, 0)";
353

    
354
                case DataTypes.LONG:
355
                        return "NUMBER(38, 0)";
356

    
357
                default:
358
                        String typeName = (String) attr.getAdditionalInfo("SQLTypeName");
359
                        if (typeName != null) {
360
                                return typeName;
361
                        }
362
                        throw new UnsupportedDataTypeException(attr.getDataTypeName(), attr
363
                                        .getDataType());
364
                }
365

    
366
        }
367

    
368
        /**
369
         * Get oracle geometry dimension
370
         * 
371
         * @param geometrySubType
372
         * @return
373
         */
374
        public int getOraGeomDimensions(int geometrySubType) {
375

    
376
                switch (geometrySubType) {
377
                case Geometry.SUBTYPES.GEOM2D:
378
                        return 2;
379
                case Geometry.SUBTYPES.GEOM2DM:
380
                case Geometry.SUBTYPES.GEOM3D:
381
                        return 3;
382
                case Geometry.SUBTYPES.GEOM3DM:
383
                        return 4;
384
                default:
385
                        throw new UnsupportedDataTypeException(
386
                                        DataTypes.TYPE_NAMES[DataTypes.GEOMETRY],
387
                                        DataTypes.GEOMETRY);
388
                }
389
        }
390

    
391
        /**
392
         * Get Oracle geometry type
393
         * 
394
         * @param geometryType
395
         * @param geometrySubType
396
         * @return
397
         */
398
        public String getOraGeomType(int geometryType, int geometrySubType) {
399
                String oraGeomType;
400
                switch (geometryType) {
401
                case Geometry.TYPES.GEOMETRY:
402
                        oraGeomType = OracleValues.OraGeometry_GTYPE_GEOMETRY;
403
                        break;
404
                case Geometry.TYPES.POINT:
405
                        oraGeomType = OracleValues.OraGeometry_GTYPE_POINT;
406
                        break;
407
                case Geometry.TYPES.CURVE:
408
                        oraGeomType = OracleValues.OraGeometry_GTYPE_CURVE;
409
                        break;
410
                case Geometry.TYPES.TEXT:
411
                        oraGeomType = OracleValues.OraGeometry_GTYPE_GEOMETRY;
412
                        break;
413
                case Geometry.TYPES.SOLID:
414
                        oraGeomType = OracleValues.OraGeometry_GTYPE_GEOMETRY;
415
                        break;
416
                case Geometry.TYPES.AGGREGATE:
417
                        oraGeomType = OracleValues.OraGeometry_GTYPE_GEOMETRY;
418
                        break;
419
                case Geometry.TYPES.SURFACE:
420
                        oraGeomType = OracleValues.OraGeometry_GTYPE_POLYGON;
421
                        break;
422
                case Geometry.TYPES.MULTIPOINT:
423
                        oraGeomType = OracleValues.OraGeometry_GTYPE_MULTIPOINT;
424
                        break;
425
                case Geometry.TYPES.MULTICURVE:
426
                        oraGeomType = OracleValues.OraGeometry_GTYPE_MULTICURVE;
427
                        break;
428
                case Geometry.TYPES.MULTISURFACE:
429
                        oraGeomType = OracleValues.OraGeometry_GTYPE_MULTIPOLYGON;
430
                        break;
431
                case Geometry.TYPES.MULTISOLID:
432
                        oraGeomType = OracleValues.OraGeometry_GTYPE_GEOMETRY;
433
                        break;
434
                case Geometry.TYPES.CIRCLE:
435
                        oraGeomType = OracleValues.OraGeometry_GTYPE_GEOMETRY;
436
                        break;
437
                case Geometry.TYPES.ARC:
438
                        oraGeomType = OracleValues.OraGeometry_GTYPE_GEOMETRY;
439
                        break;
440
                case Geometry.TYPES.ELLIPSE:
441
                        oraGeomType = OracleValues.OraGeometry_GTYPE_GEOMETRY;
442
                        break;
443
                case Geometry.TYPES.SPLINE:
444
                        oraGeomType = OracleValues.OraGeometry_GTYPE_GEOMETRY;
445
                        break;
446
                case Geometry.TYPES.ELLIPTICARC:
447
                        oraGeomType = OracleValues.OraGeometry_GTYPE_GEOMETRY;
448
                        break;
449
                default:
450
                        throw new UnsupportedGeometryException(geometryType,
451
                                        geometrySubType);
452
                }
453
                return oraGeomType;
454
        }
455

    
456
        /**
457
         * 
458
         */
459
        public String getSqlFieldName(FeatureAttributeDescriptor attribute) {
460
                /*
461
                if (attribute.getDataType() == DataTypes.GEOMETRY) {
462
                        return "asBinary(" + super.getSqlFieldName(attribute) + ")";
463
                }
464
                */
465
                return super.getSqlFieldName(attribute);
466
        }
467
        
468
        protected String getIdentifierQuoteString() {
469
                return IDENTIFIER_QUOTE_STRING;
470
        }
471

    
472
        /**
473
         * 
474
         */
475
        protected EditableFeatureAttributeDescriptor createAttributeFromJDBC(
476
                        EditableFeatureType fType, Connection conn,
477
                        ResultSetMetaData rsMetadata, int colIndex) throws SQLException {
478
                
479
                String rstypename = rsMetadata.getColumnTypeName(colIndex);
480
                if (rstypename
481
                                .equalsIgnoreCase(OracleValues.OraGeometry_GTYPE_GEOMETRY)) {
482

    
483
                        return fType.add(rsMetadata.getColumnName(colIndex),
484
                                        DataTypes.GEOMETRY);
485
                }
486

    
487
                EditableFeatureAttributeDescriptor column;
488
                switch (rsMetadata.getColumnType(colIndex)) {
489
                case java.sql.Types.INTEGER:
490
                        column = fType.add(rsMetadata.getColumnName(colIndex),
491
                                        DataTypes.INT);
492
                        break;
493
                case java.sql.Types.BIGINT:
494
                        column = fType.add(rsMetadata.getColumnName(colIndex),
495
                                        DataTypes.LONG);
496
                        break;
497
                case java.sql.Types.REAL:
498
                        column = fType.add(rsMetadata.getColumnName(colIndex),
499
                                        DataTypes.DOUBLE);
500
                        break;
501
                case java.sql.Types.DOUBLE:
502
                        column = fType.add(rsMetadata.getColumnName(colIndex),
503
                                        DataTypes.DOUBLE);
504
                        break;
505
                case java.sql.Types.CHAR:
506
                        column = fType.add(rsMetadata.getColumnName(colIndex),
507
                                        DataTypes.STRING);
508
                        break;
509
                case java.sql.Types.VARCHAR:
510
                case java.sql.Types.LONGVARCHAR:
511
                        column = fType.add(rsMetadata.getColumnName(colIndex),
512
                                        DataTypes.STRING);
513
                        break;
514
                case java.sql.Types.FLOAT:
515
                        column = fType.add(rsMetadata.getColumnName(colIndex),
516
                                        DataTypes.FLOAT);
517
                        break;
518
                case java.sql.Types.DECIMAL:
519
                        column = fType.add(rsMetadata.getColumnName(colIndex),
520
                                        DataTypes.FLOAT);
521
                        break;
522
                case java.sql.Types.DATE:
523
                        column = fType.add(rsMetadata.getColumnName(colIndex),
524
                                        DataTypes.DATE);
525
                        break;
526
                case java.sql.Types.TIME:
527
                        column = fType.add(rsMetadata.getColumnName(colIndex),
528
                                        DataTypes.TIME);
529
                        break;
530
                case java.sql.Types.TIMESTAMP:
531
                        column = fType.add(rsMetadata.getColumnName(colIndex),
532
                                        DataTypes.TIMESTAMP);
533
                        break;
534
                case java.sql.Types.BOOLEAN:
535
                        column = fType.add(rsMetadata.getColumnName(colIndex),
536
                                        DataTypes.BOOLEAN);
537
                        break;
538
                case java.sql.Types.BLOB:
539
                case java.sql.Types.BINARY:
540
                case java.sql.Types.LONGVARBINARY:
541
                        column = fType.add(rsMetadata.getColumnName(colIndex),
542
                                        DataTypes.BYTEARRAY);
543
                        break;
544

    
545
                case java.sql.Types.NUMERIC:
546
                        
547
                        // decimal positions to the right of point
548
                        int scale = rsMetadata.getScale(colIndex);
549
                        // decimal positions to the right of point
550
                        // int leftdigits = rsMetadata.getPrecision(colIndex);
551
                        
552
                        if (scale == 0) { 
553
                                column = fType.add(rsMetadata.getColumnName(colIndex),
554
                                                DataTypes.LONG);
555
                        } else {
556
                                column = fType.add(rsMetadata.getColumnName(colIndex),
557
                                                DataTypes.DOUBLE);
558
                        }
559
                        
560
                        break;
561

    
562
                default:
563
                        column = fType.add(rsMetadata.getColumnName(colIndex),
564
                                        DataTypes.OBJECT);
565
                        column.setAdditionalInfo("SQLType", new Integer(rsMetadata
566
                                        .getColumnType(colIndex)));
567
                        column.setAdditionalInfo("SQLTypeName", rsMetadata
568
                                        .getColumnTypeName(colIndex));
569

    
570
                        break;
571
                }
572

    
573
                return column;
574

    
575

    
576
                // return super.createAttributeFromJDBC(type, conn, rsMetadata, colIndex);
577
        }
578

    
579
        /**
580
         * 
581
         */
582
        public boolean allowAutomaticValues() {
583
                return Boolean.TRUE;
584
        }
585

    
586
        /**
587
         * 
588
         */
589
        public boolean supportOffset() {
590
                return true;
591
        }
592

    
593
        /**
594
         * 
595
         */
596
        public boolean supportsUnion() {
597
                return true;
598
        }
599

    
600
        /**
601
         * get sql with fields description
602
         * 
603
         * @param attr
604
         * @return
605
         */
606
        public String getSqlFieldDescription(FeatureAttributeDescriptor attr)
607
                        throws DataException {
608

    
609
                StringBuilder strb = new StringBuilder();
610
                // name
611
                strb.append("\"" + attr.getName() + "\" ");
612

    
613
                // Type
614
                strb.append(this.getSqlColumnTypeDescription(attr));
615

    
616
                // Primary key
617
                if (attr.isPrimaryKey()) {
618
                        strb.append(" PRIMARY KEY");
619
                }
620

    
621
                return strb.toString();
622
        }
623

    
624
        /**
625
         * UTility method to get the SQL sentence needed to update the geographic
626
         * metadata table with a new bounding box and SRS
627
         * 
628
         * @param tName
629
         *            table name
630
         * @param ora_srid
631
         *            new SRS
632
         * @param bbox
633
         *            new bounding box
634
         * @param dim
635
         *            geometries dimension
636
         * @param withsrid
637
         *            False if the SRS is set to NULL. True otherwise.
638
         * @return the SQL sentence to perform the update
639
         */
640
        public String getSqlUpdateMetadata(OracleStoreParameters params,
641
                        String ora_srid, Rectangle2D bbox, int dim, boolean withsrid) {
642

    
643
                String[] dim_name = new String[dim];
644
                // double tolerance = ORACLE_SPATIAL_DEFAULT_TOLERANCE;
645

    
646
                String _ora_srid = ora_srid;
647
                if (_ora_srid == null)
648
                        _ora_srid = "NULL";
649

    
650
                if (_ora_srid.compareTo(OracleValues.GEODETIC_SRID) == 0) {
651
                        dim_name[0] = "LONGITUDE";
652
                        dim_name[1] = "LATITUDE";
653
                } else {
654
                        dim_name[0] = "X";
655
                        dim_name[1] = "Y";
656

    
657
                        if (dim > 2) {
658
                                dim_name[2] = "Z";
659

    
660
                                if (dim > 3) {
661
                                        dim_name[3] = "T";
662
                                }
663
                        }
664
                }
665

    
666
                double minx = bbox.getMinX();
667
                double miny = bbox.getMinY();
668
                double maxx = bbox.getMaxX();
669
                double maxy = bbox.getMaxY();
670

    
671
                String resp = "INSERT INTO "
672
                                + OracleValues.USER_ORACLE_GEOMETADATA_VIEW + " "
673
                                + " ( TABLE_NAME, COLUMN_NAME, DIMINFO, SRID ) " + " VALUES ("
674
                                + "'" + params.getTable() + "', " + "'"
675
                                + OracleValues.DEFAULT_GEO_FIELD + "', "
676
                                + "MDSYS.SDO_DIM_ARRAY( " + "MDSYS.SDO_DIM_ELEMENT ('"
677
                                + dim_name[0] + "', " + minx + ", " + maxx + ", " + ORACLE_SPATIAL_DEFAULT_TOLERANCE
678
                                + " ), " + "MDSYS.SDO_DIM_ELEMENT ('" + dim_name[1] + "', "
679
                                + miny + ", " + maxy + ", " + ORACLE_SPATIAL_DEFAULT_TOLERANCE + " ))";
680

    
681
                if (dim > 2) {
682
                        resp = resp.substring(0, resp.length() - 1) + ",";
683
                        resp = resp + "MDSYS.SDO_DIM_ELEMENT ('" + dim_name[2]
684
                                        + "', 0.0, 100.0, " + ORACLE_SPATIAL_DEFAULT_TOLERANCE + " ))";
685

    
686
                        if (dim > 3) {
687
                                resp = resp.substring(0, resp.length() - 1) + ",";
688
                                resp = resp + "MDSYS.SDO_DIM_ELEMENT ('" + dim_name[3]
689
                                                + "', 0.0, 100.0, " + ORACLE_SPATIAL_DEFAULT_TOLERANCE + " ))";
690
                        }
691
                }
692

    
693
                if (withsrid) {
694
                        resp = resp + ", " + _ora_srid + " )";
695
                } else {
696
                        resp = resp + ", NULL )";
697
                }
698

    
699
                return resp;
700
        }
701

    
702

    
703
        
704
        
705
        /**
706
         * 
707
         */
708
        public void loadFeatureType(EditableFeatureType featureType,
709
                        JDBCStoreParameters storeParams) throws DataException {
710
                
711
                if ((storeParams.getDefaultGeometry() == null) && (storeParams instanceof OracleNewStoreParameters)) {
712
                        OracleNewStoreParameters osp = (OracleNewStoreParameters) storeParams;
713
                        String geoname = osp.getDefaultFeatureType().getDefaultGeometryAttributeName();
714
                        storeParams.setDefaultGeometry(geoname);
715
                }
716

    
717
                String sqlstr = storeParams.getSQL();
718
                
719
                if (sqlstr != null && sqlstr.trim().length() > 0) {
720
                        // loadFeatureType(featureType, storeParams, sqlstr);
721
                } else {
722
                        sqlstr = "SELECT * FROM " + storeParams.tableID() + " WHERE ROWNUM = 1";
723
                        storeParams.setSQL(sqlstr);
724
                }
725
                
726
                loadFeatureType(featureType, storeParams, sqlstr, storeParams
727
                                .getSchema(), storeParams.getTable());
728
                
729
                storeParams.setSQL(null);
730
                // super.loadFeatureType(featureType, storeParams);
731
        }
732

    
733
        /**
734
         * Fill <code>featureType</code> geometry attributes with ShapeType
735
         * information stored in the table USER_SDO_GEOMETRY_METADATA
736
         * 
737
         * @param conn
738
         * @param rsMetadata
739
         * @param featureType
740
         * @throws ReadException
741
         */
742
        protected void loadSRS_and_shapeType(Connection conn,
743
                        ResultSetMetaData rsMetadata, EditableFeatureType featureType,
744
                        String baseSchema, String baseTable) throws JDBCException {
745

    
746
                Statement st = null;
747
                ResultSet rs = null;
748
                String reserved_geocolname = null;
749
                
750
                try {
751
                        // Sacamos la lista de los attributos geometricos
752

    
753
                        EditableFeatureAttributeDescriptor attr;
754
                        ArrayList geoAttrs = new ArrayList();
755

    
756
                        Iterator iter = featureType.iterator();
757
                        while (iter.hasNext()) {
758
                                attr = (EditableFeatureAttributeDescriptor) iter.next();
759
                                if (attr.getDataType() == DataTypes.GEOMETRY) {
760
                                        geoAttrs.add(attr);
761
                                }
762
                        }
763
                        if (geoAttrs.size() < 1) {
764
                                return;
765
                        }
766

    
767
                        // Preparamos una sql para que nos saque el resultado
768
                        StringBuilder strb = new StringBuilder();
769
                        strb.append("SELECT * FROM "
770
                                        + OracleValues.USER_ORACLE_GEOMETADATA_VIEW + " WHERE "
771
                                        + OracleValues.USER_ORACLE_GEOMETADATA_VIEW_TABLE_NAME
772
                                        + " = '" + baseTable + "'");
773
                        String sql = strb.toString();
774

    
775
                        st = conn.createStatement();
776
                        try {
777
                                rs = st.executeQuery(sql);
778
                        } catch (SQLException e) {
779
                                throw new JDBCExecuteSQLException(sql, e);
780
                        }
781
                        String srID;
782

    
783
                        EditableFeatureAttributeDescriptor auxdesc;
784
                        
785

    
786
                                while (rs.next()) {
787
                                        String rsName =
788
                                                rs.getString(OracleValues.USER_ORACLE_GEOMETADATA_VIEW_COLUMN_NAME);
789
                                        reserved_geocolname = rsName;
790
                                        auxdesc = getAttrDescForCol(geoAttrs, rsName);
791
                                        if (auxdesc != null) {
792
                                                Object sridobj = rs.getObject("SRID");
793
                                                if (sridobj == null) {
794
                                                        auxdesc.setSRS(null);
795
                                                } else {
796
                                                        srID = (String) sridobj;
797
                                                        int epsg = OracleUtils.oracleSridToEpsg(srID);
798
                                                        String sepsg = "EPSG:" + Integer.toString(epsg);
799
                                                        auxdesc.setSRS(CRSFactory.getCRS(sepsg));
800
                                                }
801
                                        }
802
                                        if (featureType.getDefaultGeometryAttribute() == null) {
803
                                                ((DefaultEditableFeatureType) featureType).setDefaultGeometryAttributeName(reserved_geocolname);
804
                                        }
805
                                        
806
                        }
807
                } catch (java.sql.SQLException e) {
808
                        throw new JDBCSQLException(e);
809
                } finally {
810
                        try { rs.close(); } catch (Exception e) { };
811
                        try { st.close(); } catch (Exception e) { };
812
                }
813
                
814
                // guess shape type
815
                String geoColName = featureType.getDefaultGeometryAttributeName();
816
                if (geoColName == null) {
817
                        geoColName = reserved_geocolname; 
818
                }
819
                
820
                try {
821
                        String str_geo = "SELECT " + geoColName + " FROM " + baseTable +
822
                        " WHERE (" + geoColName + " IS NOT NULL) AND " + OracleUtils.EXPONENTIAL_INDICES_CONDITION; 
823

    
824
                        st = conn.createStatement();
825
                        try {
826
                                rs = st.executeQuery(str_geo);
827
                        } catch (SQLException e) {
828
                                throw new JDBCExecuteSQLException(str_geo, e);
829
                        }
830
                        
831
            int aux = 0;
832
            int guess_type = TYPES.GEOMETRY;
833
            int guess_subtype = SUBTYPES.GEOM2D;
834
            
835
            STRUCT sample_geo;
836
            ArrayList shptypes = new ArrayList();
837
            int[] ty_subty;
838
            while (rs.next()) {
839
                sample_geo = (STRUCT) rs.getObject(1);
840
                ty_subty = OracleUtils.getGeoTypeSubTypeOfStruct(sample_geo); 
841
                aux = ty_subty[0];
842
                guess_subtype = ty_subty[1];
843
                shptypes.add(new Integer(aux));
844
            }
845

    
846
            if (shptypes.size() > 0) {
847
                    guess_type = OracleUtils.getShapeTypeFromArray(shptypes);
848
            } else {
849
                    logger.warn("Did not find geometries to sample. Assumed TYPE = GEOMETRY, SUBTYPE = 2D");
850
            }
851

    
852
            DefaultEditableFeatureAttributeDescriptor dfad = null;
853
            try {
854
                dfad = (DefaultEditableFeatureAttributeDescriptor) featureType.getDefaultGeometryAttribute();
855
                dfad.setGeometryType(guess_type);
856
                dfad.setGeometrySubType(guess_subtype);
857
            } catch (ClassCastException cce) {
858
                    logger.error("Unexpected non editable feature type. Did not set geo types.");
859
            }
860
                } catch (java.sql.SQLException e) {
861
                        throw new JDBCSQLException(e);
862
                } finally {
863
                        try {rs.close();} catch (Exception e) {        };
864
                        try {st.close();} catch (Exception e) { };
865
                }
866
        }
867

    
868
        private EditableFeatureAttributeDescriptor getAttrDescForCol(ArrayList list, String name) {
869
                
870
                int sz = list.size();
871
                for (int i=0; i<sz; i++) {
872
                        EditableFeatureAttributeDescriptor aux = (EditableFeatureAttributeDescriptor) list.get(i);
873
                        if (aux.getName().compareToIgnoreCase(name) == 0) {
874
                                return aux;
875
                        }
876
                }
877
                // not found
878
                return null;
879
        }
880

    
881
        /**
882
         * Add oracle geometry field and add spatial index
883
         * 
884
         * @param attr
885
         * @param table
886
         * @param schema
887
         * @return
888
         */
889
        public List<String> getSqlGeometryFieldAdd(FeatureAttributeDescriptor attr,
890
                        String table, String schema) {
891

    
892
                List<String> sqls = new ArrayList<String>();
893

    
894
                StringBuilder strb1 = new StringBuilder();
895
                strb1.append("Alter table ");
896
                if (schema != null && schema.length() > 0) {
897
                        strb1.append(schema);
898
                        strb1.append(".");
899
                }
900
                strb1.append(table);
901
                strb1.append(" add (");
902
                strb1.append(attr.getName());
903
                strb1.append(" SDO_GEOMETRY)");
904

    
905
                sqls.add(strb1.toString());
906

    
907
                String sqlindex = "CREATE INDEX "
908
                                + OracleUtils.getDerivedName(table, "SX") + " ON " + table
909
                                + " (\"" + attr.getName()
910
                                + "\") INDEXTYPE IS \"MDSYS\".\"SPATIAL_INDEX\" ";
911

    
912
                sqls.add(sqlindex);
913

    
914
                return sqls;
915
        }
916
        
917
        
918
        
919
//        protected void loadFeatureType(Connection conn,
920
//                        EditableFeatureType featureType, String sql, String[] pks,
921
//                        String defGeomName, String schema, String table)
922
//                        throws DataException {
923
//
924
//                Statement stAux = null;
925
//                ResultSet rs = null;
926
//                try {
927
//
928
//                        stAux = conn.createStatement();
929
//                        stAux.setFetchSize(1);
930
//
931
//                        try {
932
//                                rs = stAux.executeQuery(sql);
933
//                        } catch (SQLException e) {
934
//                                throw new JDBCExecuteSQLException(sql, e);
935
//                        }
936
//                        ResultSetMetaData rsMetadata = rs.getMetaData();
937
//
938
//                        List pksList = null;
939
//                        if (pks != null) {
940
//                                pksList = Arrays.asList(pks);
941
//                        }
942
//
943
//                        int i;
944
//                        int geometriesColumns = 0;
945
//                        String lastGeometry = null;
946
//
947
//                        EditableFeatureAttributeDescriptor attr;
948
//                        for (i = 1; i <= rsMetadata.getColumnCount(); i++) {
949
//                                attr = getAttributeFromJDBC(featureType, conn, rsMetadata, i);
950
//                                if (pksList != null && pksList.contains(attr.getName())) {
951
//                                        attr.setIsPrimaryKey(true);
952
//                                }
953
//                                if (attr.getDataType() == DataTypes.GEOMETRY) {
954
//                                        geometriesColumns++;
955
//                                        lastGeometry = attr.getName();
956
//                                        if (lastGeometry.equals(defGeomName)) {
957
//                                                featureType.setDefaultGeometryAttributeName(defGeomName);
958
//                                        }
959
//                                }
960
//                        }
961
//
962
//                        if (geometriesColumns > 0) {
963
//                                loadSRS_and_shapeType(conn, rsMetadata, featureType, schema,
964
//                                                table);
965
//                        }
966
//
967
//                        if (defGeomName == null && geometriesColumns == 1) {
968
//                                featureType.setDefaultGeometryAttributeName(lastGeometry);
969
//                                defGeomName = lastGeometry;
970
//                        }
971
//
972
//                } catch (java.sql.SQLException e) {
973
//                        throw new JDBCSQLException(e); // FIXME exception
974
//                } finally {
975
//                        try {
976
//                                rs.close();
977
//                        } catch (Exception e) {
978
//                        }
979
//                        try {
980
//                                stAux.close();
981
//                        } catch (Exception e) {
982
//                        }
983
//
984
//                }
985
//
986
//        }
987

    
988

    
989
}