Statistics
| Revision:

svn-gvsig-desktop / branches / v2_0_0_prep / extensions / extOracleSpatial / src / org / gvsig / fmap / dal / store / oraclespatial / OracleSpatialHelper.java @ 29563

History | View | Annotate | Download (24.6 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.oraclespatial;
29

    
30
import java.sql.Connection;
31
import java.sql.PreparedStatement;
32
import java.sql.ResultSet;
33
import java.sql.ResultSetMetaData;
34
import java.sql.SQLException;
35
import java.sql.Statement;
36
import java.sql.Types;
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 org.cresques.cts.IProjection;
44
import org.gvsig.fmap.crs.CRSFactory;
45
import org.gvsig.fmap.dal.DALLocator;
46
import org.gvsig.fmap.dal.DataManager;
47
import org.gvsig.fmap.dal.DataTypes;
48
import org.gvsig.fmap.dal.NewDataStoreParameters;
49
import org.gvsig.fmap.dal.exception.DataException;
50
import org.gvsig.fmap.dal.exception.InitializeException;
51
import org.gvsig.fmap.dal.exception.ReadException;
52
import org.gvsig.fmap.dal.exception.WriteException;
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.resource.spi.ResourceManagerProviderServices;
64
import org.gvsig.fmap.dal.store.jdbc.ConnectionAction;
65
import org.gvsig.fmap.dal.store.jdbc.JDBCHelper;
66
import org.gvsig.fmap.dal.store.jdbc.JDBCHelperUser;
67
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParameters;
68
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCException;
69
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCExecutePreparedSQLException;
70
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCExecuteSQLException;
71
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCPreparingSQLException;
72
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCSQLException;
73
import org.gvsig.fmap.geom.Geometry;
74
import org.gvsig.fmap.geom.GeometryLocator;
75
import org.gvsig.fmap.geom.GeometryManager;
76
import org.gvsig.fmap.geom.operation.fromwkb.FromWKB;
77
import org.gvsig.fmap.geom.operation.fromwkb.FromWKBGeometryOperationContext;
78
import org.gvsig.fmap.geom.primitive.Envelope;
79
import org.gvsig.tools.exception.BaseException;
80
import org.postgresql.PGResultSetMetaData;
81
import org.slf4j.Logger;
82
import org.slf4j.LoggerFactory;
83

    
84
/**
85
 * @author vsanjaime
86
 * 
87
 */
88
public class OracleSpatialHelper extends JDBCHelper {
89

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

    
93
        OracleSpatialHelper(JDBCHelperUser consumer,
94
                        OracleSpatialConnectionParameters params)
95
                        throws InitializeException {
96

    
97
                super(consumer, params);
98
        }
99

    
100
        protected void initializeResource() throws InitializeException {
101
                ResourceManagerProviderServices manager = (ResourceManagerProviderServices) DALLocator
102
                                .getResourceManager();
103
                OracleSpatialResource resource = (OracleSpatialResource) manager
104
                                .createResource(OracleSpatialResource.NAME, new Object[] {
105
                                                params.getUrl(),
106
                                                params.getHost(),
107
                                                params.getPort(),
108
                                                params.getDBName(),
109
                                                params.getUser(),
110
                                                params.getPassword(),
111
                                                params.getJDBCDriverClassName(),
112
                                                ((OracleSpatialConnectionParameters) params)
113
                                                                .getUseSSL() });
114
                this.setResource(resource);
115
        }
116

    
117
        protected String getDefaultSchema(Connection conn) throws JDBCException {
118
                if (defaultSchema == null) {
119
                        String sql = "SELECT sys_context('USERENV', 'CURRENT_SCHEMA') FROM dual;";
120
                        ResultSet rs = null;
121
                        Statement st = null;
122
                        String schema = null;
123
                        try {
124
                                st = conn.createStatement();
125
                                try {
126
                                        rs = st.executeQuery(sql);
127
                                } catch (java.sql.SQLException e) {
128
                                        throw new JDBCExecuteSQLException(sql, e);
129
                                }
130
                                rs.next();
131
                                schema = rs.getString(1);
132
                        } catch (java.sql.SQLException e) {
133
                                throw new JDBCSQLException(e);
134
                        } finally {
135
                                try {
136
                                        rs.close();
137
                                } catch (Exception e) {
138
                                        logger.error("Exception clossing resulset", e);
139
                                }
140
                                ;
141
                                try {
142
                                        st.close();
143
                                } catch (Exception e) {
144
                                        logger.error("Exception clossing statement", e);
145
                                }
146
                                ;
147
                                rs = null;
148
                                st = null;
149
                        }
150
                        defaultSchema = schema;
151
                }
152

    
153
                return defaultSchema;
154
        }
155

    
156
        public Envelope getFullEnvelopeOfField(JDBCStoreParameters storeParams,
157
                        String geometryAttrName, Envelope limit) throws DataException {
158

    
159
                StringBuilder strb = new StringBuilder();
160
                strb.append("Select asbinary(extent(");
161
                strb.append(escapeFieldName(geometryAttrName));
162
                strb.append(")) from ");
163

    
164
                if (storeParams.getSQL() != null
165
                                && storeParams.getSQL().trim().length() == 0) {
166
                        strb.append('(');
167
                        strb.append(storeParams.getSQL());
168
                        strb.append(") as __extentfield__ ");
169
                } else {
170
                        strb.append(storeParams.tableID());
171
                }
172

    
173
                if (limit != null) {
174
                        strb.append(" where  intersects(GeomFromText('");
175
                        strb.append(limit.toString());
176
                        strb.append("')), boundary(");
177
                        strb.append(escapeFieldName(geometryAttrName));
178
                        strb.append(")) ");
179
                }
180

    
181
                String sql = strb.toString();
182

    
183
                ResultSet rs = null;
184
                Statement st = null;
185
                String schema = null;
186
                Connection conn = null;
187

    
188
                GeometryManager geoMan = GeometryLocator.getGeometryManager();
189

    
190
                Envelope fullEnvelope = null;
191
                this.open();
192
                this.begin();
193
                try {
194
                        conn = getConnection();
195
                        st = conn.createStatement();
196
                        try {
197
                                rs = st.executeQuery(sql);
198
                        } catch (java.sql.SQLException e) {
199
                                throw new JDBCExecuteSQLException(sql, e);
200
                        }
201
                        if (!rs.next()) {
202
                                return null;
203
                        }
204

    
205
                        byte[] data = rs.getBytes(1);
206
                        if (data == null) {
207
                                return null;
208
                        }
209
                        initializeFromWKBOperation();
210
                        fromWKBContext.setData(data);
211
                        Geometry geom = (Geometry) fromWKB.invoke(null, fromWKBContext);
212

    
213
                        fullEnvelope = geom.getEnvelope();
214

    
215
                        return fullEnvelope;
216
                } catch (java.sql.SQLException e) {
217
                        throw new JDBCSQLException(e);
218
                } catch (BaseException e) {
219
                        throw new ReadException(user.getName(), e);
220
                } finally {
221
                        try {
222
                                rs.close();
223
                        } catch (Exception e) {
224
                        }
225
                        ;
226
                        try {
227
                                st.close();
228
                        } catch (Exception e) {
229
                        }
230
                        ;
231
                        try {
232
                                conn.close();
233
                        } catch (Exception e) {
234
                        }
235
                        ;
236
                        rs = null;
237
                        st = null;
238
                        conn = null;
239
                        end();
240
                }
241

    
242
        }
243

    
244
        protected void initializeFromWKBOperation() throws BaseException {
245
                if (fromWKB == null) {
246
                        fromWKB = (FromWKB) GeometryLocator.getGeometryManager()
247
                                        .getGeometryOperation(FromWKB.CODE,
248
                                                        Geometry.TYPES.GEOMETRY, Geometry.SUBTYPES.GEOM2D);
249
                        fromWKBContext = new FromWKBGeometryOperationContext();
250

    
251
                }
252
        }
253

    
254
        public Geometry getGeometry(byte[] buffer) throws BaseException {
255
                if (buffer == null) {
256
                        return null;
257
                }
258
                initializeFromWKBOperation();
259
                Geometry geom;
260
                try {
261
                        fromWKBContext.setData(buffer);
262

    
263
                        geom = (Geometry) fromWKB.invoke(null, fromWKBContext);
264
                } finally {
265
                        fromWKBContext.setData(null);
266
                }
267
                return geom;
268
        }
269

    
270
        /**
271
         * Fill <code>featureType</code> geometry attributes with SRS and ShapeType
272
         * information stored in the table GEOMETRY_COLUMNS
273
         * 
274
         * @param conn
275
         * @param rsMetadata
276
         * @param featureType
277
         * @throws ReadException
278
         */
279
        protected void loadSRS_and_shapeType(Connection conn,
280
                        ResultSetMetaData rsMetadata, EditableFeatureType featureType,
281
                        String baseSchema, String baseTable) throws JDBCException {
282

    
283
                Statement st = null;
284
                ResultSet rs = null;
285
                try {
286
                        // Sacamos la lista de los attributos geometricos
287
                        EditableFeatureAttributeDescriptor attr;
288
                        List geoAttrs = new ArrayList();
289

    
290
                        Iterator iter = featureType.iterator();
291
                        while (iter.hasNext()) {
292
                                attr = (EditableFeatureAttributeDescriptor) iter.next();
293
                                if (attr.getDataType() == DataTypes.GEOMETRY) {
294
                                        geoAttrs.add(attr);
295
                                }
296
                        }
297
                        if (geoAttrs.size() < 1) {
298
                                return;
299
                        }
300

    
301
                        // preparamos un set con las lista de tablas de origen
302
                        // de los campos
303
                        class TableId {
304
                                public String schema = null;
305
                                public String table = null;
306
                                public String field = null;
307

    
308
                                public void appendToSQL(StringBuilder strb) {
309
                                        if (schema == null || schema.length() == 0) {
310
                                                strb
311
                                                                .append("( F_TABLE_SCHEMA = current_schema() AND F_TABLE_NAME = '");
312
                                        } else {
313
                                                strb.append("( F_TABLE_SCHEMA = '");
314
                                                strb.append(schema);
315
                                                strb.append("' AND F_TABLE_NAME = '");
316
                                        }
317
                                        strb.append(table);
318
                                        strb.append("' AND F_GEOMETRY_COLUMN = '");
319
                                        strb.append(field);
320
                                        strb.append("' )");
321
                                }
322

    
323
                        }
324
                        Comparator cmp = new Comparator() {
325
                                public int compare(Object arg0, Object arg1) {
326
                                        TableId a0 = (TableId) arg0;
327
                                        TableId a1 = (TableId) arg1;
328

    
329
                                        if (!a0.field.equals(a1.field)) {
330
                                                return -1;
331
                                        }
332
                                        if (!a0.table.equals(a1.table)) {
333
                                                return -1;
334
                                        }
335
                                        if (!a0.schema.equals(a1.schema)) {
336
                                                return -1;
337
                                        }
338
                                        return 0;
339
                                }
340
                        };
341
                        TreeSet set = new TreeSet(cmp);
342
                        TableId tableId;
343
                        iter = geoAttrs.iterator();
344
                        int rsIndex;
345
                        while (iter.hasNext()) {
346
                                attr = (EditableFeatureAttributeDescriptor) iter.next();
347
                                tableId = new TableId();
348
                                rsIndex = attr.getIndex() + 1;
349

    
350
                                if (baseSchema == null && baseTable == null) {
351
                                        if (rsMetadata instanceof PGResultSetMetaData) {
352
                                                tableId.schema = ((PGResultSetMetaData) rsMetadata)
353
                                                                .getBaseSchemaName(rsIndex);
354
                                                tableId.table = ((PGResultSetMetaData) rsMetadata)
355
                                                                .getBaseTableName(rsIndex);
356
                                                tableId.field = ((PGResultSetMetaData) rsMetadata)
357
                                                                .getBaseColumnName(rsIndex);
358

    
359
                                        } else {
360
                                                tableId.schema = rsMetadata.getSchemaName(rsIndex);
361
                                                tableId.table = rsMetadata.getTableName(rsIndex);
362
                                                tableId.field = rsMetadata.getColumnName(rsIndex);
363
                                        }
364
                                } else {
365
                                        tableId.schema = baseSchema;
366
                                        tableId.table = baseTable;
367
                                        tableId.field = rsMetadata.getColumnName(rsIndex);
368
                                }
369
                                if (tableId.table == null || tableId.table.length() == 0) {
370
                                        // Si no tiene tabla origen (viene de algun calculo por ej.)
371
                                        // lo saltamos ya que no estara en la tabla GEOMETRY_COLUMNS
372
                                        continue;
373
                                }
374
                                set.add(tableId);
375
                        }
376

    
377
                        if (set.size() == 0) {
378
                                return;
379
                        }
380

    
381
                        // Preparamos una sql para que nos saque el resultado
382
                        StringBuilder strb = new StringBuilder();
383
                        strb
384
                                        .append("Select geometry_columns.*,auth_name || ':' || auth_srid as SRSID ");
385
                        strb.append("from geometry_columns left join spatial_ref_sys on ");
386
                        strb.append("geometry_columns.srid = spatial_ref_sys.srid WHERE ");
387
                        iter = set.iterator();
388
                        for (int i = 0; i < set.size() - 1; i++) {
389
                                tableId = (TableId) iter.next();
390
                                tableId.appendToSQL(strb);
391
                                strb.append(" OR ");
392
                        }
393
                        tableId = (TableId) iter.next();
394
                        tableId.appendToSQL(strb);
395
                        String sql = strb.toString();
396

    
397
                        st = conn.createStatement();
398
                        try {
399
                                rs = st.executeQuery(sql);
400
                        } catch (SQLException e) {
401
                                throw new JDBCExecuteSQLException(sql, e);
402
                        }
403
                        String srsID;
404
                        int pgSrid;
405
                        int geometryType;
406
                        int geometrySubtype;
407
                        String geomTypeStr;
408
                        int dimensions;
409
                        IProjection srs;
410

    
411
                        while (rs.next()) {
412
                                srsID = rs.getString("SRSID");
413
                                pgSrid = rs.getInt("SRID");
414
                                geomTypeStr = rs.getString("TYPE").toUpperCase();
415
                                geometryType = Geometry.TYPES.GEOMETRY;
416
                                if (geomTypeStr.startsWith("POINT")) {
417
                                        geometryType = Geometry.TYPES.POINT;
418
                                } else if (geomTypeStr.startsWith("LINESTRING")) {
419
                                        geometryType = Geometry.TYPES.CURVE;
420
                                } else if (geomTypeStr.startsWith("POLYGON")) {
421
                                        geometryType = Geometry.TYPES.SURFACE;
422
                                } else if (geomTypeStr.startsWith("MULTIPOINT")) {
423
                                        geometryType = Geometry.TYPES.MULTIPOINT;
424
                                } else if (geomTypeStr.startsWith("MULTILINESTRING")) {
425
                                        geometryType = Geometry.TYPES.MULTICURVE;
426
                                } else if (geomTypeStr.startsWith("MULTIPOLYGON")) {
427
                                        geometryType = Geometry.TYPES.MULTISURFACE;
428
                                }
429
                                dimensions = rs.getInt("coord_dimension");
430
                                geometrySubtype = Geometry.SUBTYPES.GEOM2D;
431
                                if (dimensions > 2) {
432
                                        if (dimensions == 3) {
433
                                                if (geomTypeStr.endsWith("M")) {
434
                                                        geometrySubtype = Geometry.SUBTYPES.GEOM2DM;
435
                                                } else {
436
                                                        geometrySubtype = Geometry.SUBTYPES.GEOM3D;
437
                                                }
438

    
439
                                        } else {
440
                                                geometrySubtype = Geometry.SUBTYPES.GEOM3DM;
441
                                        }
442
                                }
443

    
444
                                iter = geoAttrs.iterator();
445
                                while (iter.hasNext()) {
446
                                        attr = (EditableFeatureAttributeDescriptor) iter.next();
447
                                        rsIndex = attr.getIndex() + 1;
448
                                        if (!rsMetadata.getColumnName(rsIndex).equals(
449
                                                        rs.getString("f_geometry_column"))) {
450
                                                continue;
451
                                        }
452

    
453
                                        if (baseSchema == null && baseTable == null) {
454

    
455
                                                if (rsMetadata instanceof PGResultSetMetaData) {
456
                                                        if (!((PGResultSetMetaData) rsMetadata)
457
                                                                        .getBaseTableName(rsIndex).equals(
458
                                                                                        rs.getString("f_table_name"))) {
459
                                                                continue;
460
                                                        }
461
                                                        String curSchema = rs.getString("f_table_schema");
462
                                                        String metaSchema = ((PGResultSetMetaData) rsMetadata)
463
                                                                        .getBaseSchemaName(rsIndex);
464
                                                        if (!metaSchema.equals(curSchema)) {
465
                                                                if (metaSchema.length() == 0
466
                                                                                && metaSchema == getDefaultSchema(conn)) {
467
                                                                } else {
468
                                                                        continue;
469
                                                                }
470
                                                        }
471

    
472
                                                } else {
473

    
474
                                                        if (!rsMetadata.getTableName(rsIndex).equals(
475
                                                                        rs.getString("f_table_name"))) {
476
                                                                continue;
477
                                                        }
478
                                                        String curSchema = rs.getString("f_table_schema");
479
                                                        String metaSchema = rsMetadata
480
                                                                        .getSchemaName(rsIndex);
481
                                                        if (!metaSchema.equals(curSchema)) {
482
                                                                if (metaSchema.length() == 0
483
                                                                                && metaSchema == getDefaultSchema(conn)) {
484
                                                                } else {
485
                                                                        continue;
486
                                                                }
487
                                                        }
488
                                                }
489
                                        }
490
                                        attr.setGeometryType(geometryType);
491
                                        attr.setGeometrySubType(geometrySubtype);
492
                                        if (srsID != null && srsID.length() > 0) {
493
                                                attr.setSRS(CRSFactory.getCRS(srsID));
494
                                        }
495
                                        iter.remove();
496
                                }
497
                                iter = geoAttrs.iterator();
498
                                while (iter.hasNext()) {
499
                                        attr = (EditableFeatureAttributeDescriptor) iter.next();
500
                                        attr.setSRS(null);
501
                                        attr.setGeometryType(Geometry.TYPES.GEOMETRY);
502

    
503
                                }
504
                        }
505

    
506
                } catch (java.sql.SQLException e) {
507
                        throw new JDBCSQLException(e);
508
                } finally {
509
                        try {
510
                                rs.close();
511
                        } catch (Exception e) {
512
                        }
513
                        ;
514
                        try {
515
                                st.close();
516
                        } catch (Exception e) {
517
                        }
518
                        ;
519
                }
520

    
521
        }
522

    
523
        /**
524
         * get geometry column name "SDO_GEOMETRY"
525
         */
526
        public String getSqlColumnTypeDescription(FeatureAttributeDescriptor attr) {
527

    
528
                switch (attr.getDataType()) {
529

    
530
                case DataTypes.GEOMETRY:
531
                        return "SDO_GEOMETRY";
532

    
533
                case DataTypes.STRING:
534
                        return "VARCHAR2(" + attr.getSize() + ")";
535

    
536
                case DataTypes.BOOLEAN:
537
                        return "NUMBER(1, 0)";
538

    
539
                case DataTypes.BYTE:
540
                        return "NUMBER";
541

    
542
                case DataTypes.DATE:
543
                        return "DATE";
544

    
545
                case DataTypes.TIMESTAMP:
546
                        return "TIMESTAMP";
547

    
548
                case DataTypes.TIME:
549
                        return "TIMESTAMP";
550

    
551
                case DataTypes.BYTEARRAY:
552

    
553
                case DataTypes.DOUBLE:
554
                        return "FLOAT";
555

    
556
                case DataTypes.FLOAT:
557
                        return "FLOAT";
558

    
559
                case DataTypes.INT:
560
                        return "NUMBER(12, 0)";
561

    
562
                case DataTypes.LONG:
563
                        return "NUMBER(38, 0)";
564

    
565
                default:
566
                        String typeName = (String) attr.getAdditionalInfo("SQLTypeName");
567
                        if (typeName != null) {
568
                                return typeName;
569
                        }
570

    
571
                        throw new UnsupportedDataTypeException(attr.getDataTypeName(), attr
572
                                        .getDataType());
573
                }
574

    
575
        }
576

    
577
        /**
578
         * get geometry dimension
579
         * 
580
         * @param geometrySubType
581
         * @return
582
         */
583
        public int getOraGeomDimensions(int geometrySubType) {
584
                switch (geometrySubType) {
585
                case Geometry.SUBTYPES.GEOM2D:
586
                        return 2;
587
                case Geometry.SUBTYPES.GEOM2DM:
588
                case Geometry.SUBTYPES.GEOM3D:
589
                        return 3;
590

    
591
                case Geometry.SUBTYPES.GEOM3DM:
592
                        return 4;
593
                default:
594
                        throw new UnsupportedDataTypeException(
595
                                        DataTypes.TYPE_NAMES[DataTypes.GEOMETRY],
596
                                        DataTypes.GEOMETRY);
597
                }
598
        }
599

    
600
        public String getOraGeomType(int geometryType, int geometrySubType) {
601
                String oraGeomType;
602
                switch (geometryType) {
603
                case Geometry.TYPES.GEOMETRY:
604
                        oraGeomType = OracleSpatialValues.OraGeometry_GTYPE_GEOMETRY;
605
                        break;
606
                case Geometry.TYPES.POINT:
607
                        oraGeomType = OracleSpatialValues.OraGeometry_GTYPE_POINT;
608
                        break;
609
                case Geometry.TYPES.CURVE:
610
                        oraGeomType = OracleSpatialValues.OraGeometry_GTYPE_CURVE;
611
                        break;
612
                case Geometry.TYPES.SURFACE:
613
                        oraGeomType = OracleSpatialValues.OraGeometry_GTYPE_POLYGON;
614
                        break;
615
                case Geometry.TYPES.MULTIPOINT:
616
                        oraGeomType = OracleSpatialValues.OraGeometry_GTYPE_MULTIPOINT;
617
                        break;
618
                case Geometry.TYPES.MULTICURVE:
619
                        oraGeomType = OracleSpatialValues.OraGeometry_GTYPE_MULTICURVE;
620
                        break;
621
                case Geometry.TYPES.MULTISURFACE:
622
                        oraGeomType = OracleSpatialValues.OraGeometry_GTYPE_MULTIPOLYGON;
623
                        break;
624
                default:
625
                        throw new UnsupportedGeometryException(geometryType,
626
                                        geometrySubType);
627
                }        
628
                return oraGeomType;
629
        }
630

    
631
        /**
632
         * 
633
         */
634
        public int getProviderSRID(String srs) {
635

    
636
                DataManager manager = DALLocator.getDataManager();
637

    
638
                if (srs != null) {
639
                        FeatureStore oraSrsStore = (FeatureStore) OracleSpatialLibrary
640
                                        .getSRSDataStore();
641

    
642
                        FeatureSet set = null;
643
                        try {
644
                                FeatureQuery query = oraSrsStore.createFeatureQuery();
645
                                query.setFilter(manager.createExpresion("EPSG = " + srs));
646
                                set = (FeatureSet) oraSrsStore.getDataSet(query);
647
                                if (set.getSize() > 0) {
648
                                        Iterator<Feature> it = set.iterator();
649
                                        while (it.hasNext()) {
650
                                                Feature feat = it.next();
651
                                                Double ora = feat.getDouble("ORACLE");
652
                                                int iora = ora.intValue();
653
                                                double prefe = feat.getDouble("PRF_ORACLE");
654
                                                if (prefe == 1) {
655
                                                        srs = new Integer(iora).toString();
656
                                                        break;
657
                                                }
658
                                        }
659
                                }
660
                        } catch (DataException e) {
661
                                e.printStackTrace();
662
                        }
663

    
664
                        return searchOraSRID(srs);
665

    
666
                }
667
                return -1;
668
        }
669

    
670
        public int getProviderSRID(IProjection srs) {
671
                if (srs != null) {
672
                        String epsg = srs.getAbrev().trim();
673
                        int ocu = epsg.indexOf(":");
674
                        if (ocu != -1) {
675
                                epsg = epsg.substring(ocu + 1);
676
                        }
677
                        Integer oraSRID = getProviderSRID(epsg);
678
                        if (oraSRID != null) {
679
                                return oraSRID.intValue();
680
                        }
681

    
682
                        return searchOraSRID(srs);
683

    
684
                }
685
                return -1;
686
        }
687

    
688
        private int searchOraSRID(final IProjection srs) {
689
                if (srs == null) {
690
                        return -1;
691
                }
692
                return searchOraSRID(srs.getAbrev());
693
        }
694

    
695
        private int searchOraSRID(final String srsID) {
696
                if (srsID == null) {
697
                        return -1;
698
                }
699

    
700
                ConnectionAction action = new ConnectionAction() {
701

    
702
                        public Object action(Connection conn) throws DataException {
703
                                // select srid from spatial_ref_sys where auth_name = 'EPSG' and
704
                                // auth_srid = 23030
705
                                String[] abrev = srsID.split(":");
706
                                StringBuilder sqlb = new StringBuilder();
707
                                sqlb.append("select SRID from MDSYS.CS_SRS where ");
708
                                if (abrev.length > 1) {
709
                                        sqlb.append("auth_name = ? and ");
710
                                }
711
                                sqlb.append("auth_srid = ?");
712

    
713
                                String sql = sqlb.toString();
714
                                PreparedStatement st;
715
                                try {
716
                                        st = conn.prepareStatement(sql);
717
                                } catch (SQLException e) {
718
                                        throw new JDBCPreparingSQLException(sql, e);
719
                                }
720
                                ResultSet rs = null;
721
                                try {
722
                                        int i = 0;
723
                                        if (abrev.length > 1) {
724
                                                st.setString(i + 1, abrev[i]);
725
                                                i++;
726
                                        }
727
                                        st.setInt(i + 1, Integer.parseInt(abrev[i]));
728

    
729
                                        try {
730
                                                rs = st.executeQuery();
731
                                        } catch (SQLException e) {
732
                                                throw new JDBCExecutePreparedSQLException(sql, abrev, e);
733
                                        }
734

    
735
                                        if (!rs.next()) {
736
                                                return null;
737
                                        }
738

    
739
                                        return new Integer(rs.getInt(1));
740

    
741
                                } catch (SQLException e) {
742
                                        throw new JDBCSQLException(e);
743
                                } finally {
744
                                        try {
745
                                                rs.close();
746
                                        } catch (Exception e) {
747
                                        }
748
                                        ;
749
                                        try {
750
                                                st.close();
751
                                        } catch (Exception e) {
752
                                        }
753
                                        ;
754
                                }
755

    
756
                        }
757

    
758
                };
759

    
760
                Integer oraSRSID = null;
761
                try {
762
                        oraSRSID = (Integer) doConnectionAction(action);
763
                        return oraSRSID.intValue();
764
                } catch (Exception e) {
765
                        logger.error("Excetion searching pgSRS", e);
766
                        return -1;
767
                }
768
        }
769

    
770
        public List getSqlGeometyFieldAdd(FeatureAttributeDescriptor attr,
771
                        String table, String schema) {
772
                // SELECT AddGeometryColumn({schema}, {table}, {field}, {srid}(int),
773
                // {geomType}(Str), {dimensions}(int))
774

    
775
                // gemoType:
776
                /*
777
                 * POINT, LINESTRING, POLYGON, MULTIPOINT, MULTILINESTRING,
778
                 * MULTIPOLYGON, GEOMETRYCOLLECTION POINTM, LINESTRINGM, POLYGONM,
779
                 * MULTIPOINTM, MULTILINESTRINGM, MULTIPOLYGONM, GEOMETRYCOLLECTIONM
780
                 */
781

    
782
                List sqls = new ArrayList();
783

    
784
                StringBuilder strb = new StringBuilder();
785
                strb.append("SELECT AddGeometryColumn('");
786
                if (schema != null && schema.length() > 0) {
787
                        strb.append(schema);
788
                        strb.append("', '");
789
                }
790
                strb.append(table);
791
                strb.append("', '");
792
                strb.append(attr.getName());
793
                strb.append("', ");
794
                // strb.append("-1");
795
                strb.append(getProviderSRID(attr.getSRS()));
796
                strb.append(", '");
797
                strb.append(getOraGeomType(attr.getGeometryType(), attr
798
                                .getGeometrySubType()));
799
                strb.append("', ");
800
                strb.append(getOraGeomDimensions(attr.getGeometrySubType()));
801
                strb.append(")");
802

    
803
                sqls.add(strb.toString());
804

    
805
                /* ALTER TABLE muni10000_peq_test DROP CONSTRAINT enforce_srid_the_geom; */
806
                /*
807
                 * strb = new StringBuilder(); strb.append("Alter table "); if (schema
808
                 * != null && schema.length() > 0) { strb.append(schema);
809
                 * strb.append("."); } strb.append("f_table_name = '");
810
                 * strb.append(table); strb.append("' AND f_geometry_column = '");
811
                 * strb.append(attr.getName()); strb.append("' AND srid = -1");
812
                 * 
813
                 * 
814
                 * sqls.add(strb.toString());
815
                 */
816
                return sqls;
817
        }
818

    
819
        public String getSqlFieldName(FeatureAttributeDescriptor attribute) {
820
                if (attribute.getDataType() == DataTypes.GEOMETRY) {
821
                        return "asBinary(" + super.getSqlFieldName(attribute) + ")";
822
                }
823
                return super.getSqlFieldName(attribute);
824
        }
825

    
826
        protected EditableFeatureAttributeDescriptor createAttributeFromJDBC(
827
                        EditableFeatureType type, Connection conn,
828
                        ResultSetMetaData rsMetadata, int colIndex) throws SQLException {
829
                if (rsMetadata.getColumnType(colIndex) == java.sql.Types.OTHER) {
830
                        if (rsMetadata.getColumnTypeName(colIndex).equalsIgnoreCase(
831
                                        "geometry")) {
832
                                return type.add(rsMetadata.getColumnName(colIndex),
833
                                                DataTypes.GEOMETRY);
834

    
835
                        }
836
                }
837

    
838
                return super.createAttributeFromJDBC(type, conn, rsMetadata, colIndex);
839
        }
840

    
841
        public List getAdditionalSqlToCreate(NewDataStoreParameters ndsp,
842
                        FeatureType fType) {
843
                FeatureAttributeDescriptor attr;
844
                Iterator iter = fType.iterator();
845
                List result = new ArrayList();
846
                OracleSpatialNewStoreParameters oraNdsp = (OracleSpatialNewStoreParameters) ndsp;
847
                while (iter.hasNext()) {
848
                        attr = (FeatureAttributeDescriptor) iter.next();
849
                        if (attr.getDataType() == DataTypes.GEOMETRY) {
850
                                result.addAll(getSqlGeometyFieldAdd(attr, oraNdsp.getTable(),
851
                                                oraNdsp.getSchema()));
852
                        }
853
                }
854

    
855
                return result;
856
        }
857

    
858
        public boolean allowAutomaticValues() {
859
                return Boolean.TRUE;
860
        }
861

    
862
        public boolean supportOffset() {
863
                return true;
864
        }
865

    
866
        public boolean supportsUnion() {
867
                return true;
868
        }
869

    
870
        public String getSqlFieldDescription(FeatureAttributeDescriptor attr)
871
                        throws DataException {
872

    
873
                StringBuilder strb = new StringBuilder();
874
                // name
875
                strb.append(attr.getName());
876
                strb.append(" ");
877

    
878
                // Type
879
                strb.append(this.getSqlColumnTypeDescription(attr));
880
                strb.append(" ");
881

    
882
                boolean allowNull = attr.allowNull()
883
                                && !(attr.isPrimaryKey() || attr.isAutomatic());
884
                // Default
885
                String typename = attr.getDataTypeName();
886
                if (typename.compareToIgnoreCase("GEOMETRY") != 0) {
887
                        if (attr.getDefaultValue() == null) {
888
                                if (allowNull) {
889
                                        strb.append("DEFAULT NULL ");
890
                                }
891
                        } else {
892
                                String value = getDefaltFieldValueString(attr);
893
                                strb.append("DEFAULT '");
894
                                strb.append(value);
895
                                strb.append("' ");
896
                        }
897

    
898
                        // Null
899
                        if (allowNull) {
900
                                strb.append("NULL ");
901
                        } else {
902
                                strb.append("NOT NULL ");
903
                        }
904

    
905
                        // Primery key
906
                        if (attr.isPrimaryKey()) {
907
                                strb.append("PRIMARY KEY ");
908
                        }
909
                }
910
                return strb.toString();
911
        }
912

    
913
        // public String getSqlFieldDescription(FeatureAttributeDescriptor attr)
914
        // throws DataException {
915
        // if (attr.getDataType() == DataTypes.GEOMETRY) {
916
        // return null;
917
        // }
918
        // return super.getSqlFieldDescription(attr);
919
        // }
920

    
921
        public static int nvarchar2Limited(int n) {
922

    
923
                if (n <= OracleSpatialValues.VARCHAR2_STANDARD_SIZE)
924
                        return OracleSpatialValues.VARCHAR2_STANDARD_SIZE;
925
                if (n <= OracleSpatialValues.VARCHAR2_LONG_SIZE)
926
                        return n;
927

    
928
                return OracleSpatialValues.VARCHAR2_LONG_SIZE;
929
        }
930

    
931
}