Statistics
| Revision:

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

History | View | Annotate | Download (15.5 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 IVER T.I   {{Task}}
26
 */
27

    
28
/**
29
 *
30
 */
31
package org.gvsig.fmap.dal.store.oracle;
32

    
33
import java.awt.geom.Rectangle2D;
34
import java.sql.Connection;
35
import java.sql.ResultSet;
36
import java.sql.SQLException;
37
import java.sql.Statement;
38
import java.util.ArrayList;
39
import java.util.Iterator;
40
import java.util.List;
41

    
42
import org.gvsig.fmap.dal.DataStoreParameters;
43
import org.gvsig.fmap.dal.NewDataStoreParameters;
44
import org.gvsig.fmap.dal.exception.DataException;
45
import org.gvsig.fmap.dal.exception.InitializeException;
46
import org.gvsig.fmap.dal.exception.ProviderNotRegisteredException;
47
import org.gvsig.fmap.dal.exception.ReadException;
48
import org.gvsig.fmap.dal.exception.RemoveException;
49
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
50
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
51
import org.gvsig.fmap.dal.feature.FeatureType;
52
import org.gvsig.fmap.dal.feature.NewFeatureStoreParameters;
53
import org.gvsig.fmap.dal.spi.DataServerExplorerProviderServices;
54
import org.gvsig.fmap.dal.store.jdbc.ConnectionAction;
55
import org.gvsig.fmap.dal.store.jdbc.JDBCHelper;
56
import org.gvsig.fmap.dal.store.jdbc.JDBCServerExplorer;
57
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParameters;
58
import org.gvsig.fmap.dal.store.jdbc.TransactionalAction;
59
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCExecuteSQLException;
60
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCSQLException;
61
import org.slf4j.Logger;
62
import org.slf4j.LoggerFactory;
63

    
64
/**
65
 * ORACLE SERVER EXPLORER
66
 * 
67
 * @author vsanjaime
68
 * 
69
 */
70
public class OracleServerExplorer extends JDBCServerExplorer {
71

    
72
        final static private Logger logger = LoggerFactory
73
                        .getLogger(OracleServerExplorer.class);
74

    
75
        public static final String NAME = "OracleServerExplorer";
76

    
77
        /**
78
         * Constructor
79
         * 
80
         * @param parameters
81
         * @param services
82
         * @throws InitializeException
83
         */
84
        public OracleServerExplorer(OracleServerExplorerParameters parameters,
85
                        DataServerExplorerProviderServices services)
86
                        throws InitializeException {
87
                super(parameters, services);
88
        }
89

    
90
        /**
91
         * get explorer name
92
         */
93
        public String getName() {
94
                return NAME;
95
        }
96

    
97
        /**
98
         * can add
99
         */
100
        public boolean canAdd() {
101
                return true;
102
        }
103

    
104
        /**
105
         * remove
106
         */
107
        public void removeMetadata(DataStoreParameters dsp) {
108

    
109
                final OracleStoreParameters oraParams = (OracleStoreParameters) dsp;
110

    
111
                TransactionalAction action = new TransactionalAction() {
112
                        public boolean continueTransactionAllowed() {
113
                                return false;
114
                        }
115

    
116
                        public Object action(Connection conn) throws DataException {
117

    
118
                                Statement st;
119
                                try {
120
                                        st = conn.createStatement();
121
                                } catch (SQLException e) {
122
                                        throw new JDBCSQLException(e);
123
                                }
124

    
125

    
126
                                // SQL DELETE METADATA
127
                                String tname = oraParams.tableID();
128
                                String sqlDeleteMetadata = "";
129
                                int ind = tname.lastIndexOf(".");
130
                                if (ind != -1) {
131
                                        String schema = tname.substring(0, ind);
132
                                        tname = tname.substring(ind + 1, tname.length());
133
                                        sqlDeleteMetadata = "DELETE FROM "
134
                                                        + OracleValues.USER_ORACLE_GEOMETADATA_VIEW
135
                                                        + " WHERE TABLE_NAME = '" + tname + "'";
136

    
137
                                } else {
138
                                        sqlDeleteMetadata = "DELETE FROM "
139
                                                        + OracleValues.USER_ORACLE_GEOMETADATA_VIEW
140
                                                        + " WHERE TABLE_NAME = '" + tname + "'";
141
                                }
142

    
143
                                try {
144
                                        st.execute(sqlDeleteMetadata);
145
                                } catch (SQLException e) {
146
                                        logger.error("While deleting metadata: " + e.getMessage());
147
                                }
148
                                
149
                                if (st != null) {
150
                                        try {
151
                                                st.close();
152
                                        } catch (SQLException e) {
153
                                                logger.error("While closing statement: " + e.getMessage());
154
                                        }
155
                                }
156
                                return null;
157
                        }
158
                };
159
                try {
160
                        this.helper.doConnectionAction(action);
161
                } catch (Exception e) {
162
                        logger.error("While removing metadatat: " + e.getMessage());
163
                }
164
        }
165
        
166
        
167
        /**
168
         * remove
169
         */
170
        public void remove(DataStoreParameters dsp) throws RemoveException {
171

    
172
                final OracleStoreParameters oraParams = (OracleStoreParameters) dsp;
173

    
174
                TransactionalAction action = new TransactionalAction() {
175
                        public boolean continueTransactionAllowed() {
176
                                return false;
177
                        }
178

    
179
                        public Object action(Connection conn) throws DataException {
180

    
181
                                Statement st;
182
                                try {
183
                                        st = conn.createStatement();
184
                                } catch (SQLException e) {
185
                                        throw new JDBCSQLException(e);
186
                                }
187
                                // SQL REMOVE TABLE
188
                                String sqlDropTable = "DROP TABLE " + oraParams.tableID()
189
                                                + " CASCADE CONSTRAINTS";
190

    
191
                                // SQL DELETE METADATA
192
                                String tname = oraParams.tableID();
193
                                String sqlDeleteMetadata = "";
194
                                int ind = tname.lastIndexOf(".");
195
                                if (ind != -1) {
196
                                        String schema = tname.substring(0, ind);
197
                                        tname = tname.substring(ind + 1, tname.length());
198
                                        sqlDeleteMetadata = "DELETE FROM "
199
                                                        + OracleValues.USER_ORACLE_GEOMETADATA_VIEW
200
                                                        + " WHERE TABLE_NAME = '" + tname + "'";
201

    
202
                                } else {
203
                                        sqlDeleteMetadata = "DELETE FROM "
204
                                                        + OracleValues.USER_ORACLE_GEOMETADATA_VIEW
205
                                                        + " WHERE TABLE_NAME = '" + tname + "'";
206
                                }
207

    
208
                                try {
209
                                        // DROP TABLE
210
                                        try {
211
                                                st.execute(sqlDropTable);
212
                                        } catch (SQLException e) {
213
                                                throw new JDBCExecuteSQLException(sqlDropTable, e);
214
                                        }
215
                                        // DELETE METADATA
216
                                        try {
217
                                                st.execute(sqlDeleteMetadata);
218
                                        } catch (SQLException e) {
219
                                                throw new JDBCExecuteSQLException(sqlDeleteMetadata, e);
220
                                        }
221

    
222
                                } finally {
223
                                        try {
224
                                                st.close();
225
                                        } catch (SQLException e) {
226
                                        }
227
                                        ;
228
                                }
229
                                return null;
230
                        }
231
                };
232
                try {
233
                        this.helper.doConnectionAction(action);
234
                } catch (Exception e) {
235
                        throw new RemoveException(this.getName(), e);
236
                }
237
        }
238

    
239
        /**
240
         * get parameters
241
         */
242
        public NewDataStoreParameters getAddParameters() throws DataException {
243
                OracleServerExplorerParameters parameters = getOracleServerExplorerParameters();
244
                OracleNewStoreParameters params = new OracleNewStoreParameters();
245
                params.setHost(parameters.getHost());
246
                params.setPort(parameters.getPort());
247
                params.setDBName(parameters.getDBName());
248
                params.setUser(parameters.getUser());
249
                params.setPassword(parameters.getPassword());
250
                params.setCatalog(parameters.getCatalog());
251
                params.setSchema(parameters.getSchema());
252
                params.setJDBCDriverClassName(parameters.getJDBCDriverClassName());
253
                params.setUrl(parameters.getUrl());
254
                params.setUseSSL(parameters.getUseSSL());
255
                params.setOraDriverType(parameters.getOraDriverType());
256

    
257
                params.setDefaultFeatureType(this.getServerExplorerProviderServices()
258
                                .createNewFeatureType());
259

    
260
                return params;
261
        }
262

    
263
        /**
264
         * Geometry support
265
         */
266
        public boolean hasGeometrySupport() {
267
                return true;
268
        }
269

    
270
        /**
271
         * Get list of table availables in Oracle schema registered in geometry
272
         * metadata view
273
         */
274
        public List<JDBCStoreParameters> list(final int mode,
275
                        final boolean showInformationDBTables) throws DataException {
276

    
277
                final JDBCStoreParameters orgParams = createStoreParams();
278

    
279
                ConnectionAction action = new ConnectionAction() {
280

    
281
                        public Object action(Connection conn) throws DataException {
282
                                ResultSet rs = null;
283
                                Statement st = null;
284

    
285
                                List<String> sqls = getSQLForList(mode, showInformationDBTables);
286

    
287
                                try {
288
                                        JDBCStoreParameters params = null;
289

    
290
                                        List<JDBCStoreParameters> paramList = new ArrayList<JDBCStoreParameters>();
291

    
292
                                        conn = helper.getConnection();
293
                                        st = conn.createStatement();
294
                                        String sql;
295
                                        Iterator<String> sqlIter = sqls.iterator();
296
                                        while (sqlIter.hasNext()) {
297
                                                sql = sqlIter.next();
298
                                                rs = st.executeQuery(sql);
299
                                                while (rs.next()) {
300
                                                        params = (JDBCStoreParameters) orgParams.getCopy();
301
                                                        params.setTable(rs.getString(1));
302
                                                        paramList.add(params);
303
                                                }
304
                                        }
305

    
306
                                        return paramList;
307
                                } catch (SQLException e) {
308
                                        throw new JDBCSQLException(e);
309
                                } finally {
310
                                        try {
311
                                                rs.close();
312
                                        } catch (Exception e) {
313
                                        }
314
                                        ;
315
                                        try {
316
                                                st.close();
317
                                        } catch (Exception e) {
318
                                        }
319
                                        ;
320
                                }
321
                        }
322

    
323
                };
324

    
325
                try {
326
                        return (List) helper.doConnectionAction(action);
327
                } catch (Exception e) {
328
                        throw new ReadException(this.getName(), e);
329
                }
330
        }
331

    
332
        public boolean dataStoreExists(DataStoreParameters dsp) {
333
                
334
                final String select_str = "SELECT * FROM " + ((JDBCStoreParameters) dsp).tableID();
335
                TransactionalAction action = new TransactionalAction() {
336

    
337
                        public boolean continueTransactionAllowed() {
338
                                return false;
339
                        }
340

    
341
                        public Object action(Connection conn) throws DataException {
342
                                Statement st = null;
343

    
344
                                try {
345
                                        st = conn.createStatement();
346
                                } catch (SQLException e1) {
347
                                        throw new JDBCSQLException(e1);
348
                                }
349

    
350
                                boolean resp = true;
351
                                
352
                                // try select
353
                                try {
354
                                        st.execute(select_str);
355
                                        logger.warn("Table exists: " + select_str);
356
                                } catch (SQLException e) {
357
                                        logger.warn("Table does not exist: " + select_str);
358
                                        resp = false;
359
                                }
360
                                
361
                                try {
362
                                        st.close();
363
                                } catch (Exception ex) {
364
                                        logger.error("Exception closing statement", ex);
365
                                }
366

    
367
                                return resp;
368
                        }
369

    
370
                };
371

    
372
                Boolean result = Boolean.FALSE;
373

    
374
                try {
375
                        result = (Boolean) helper.doConnectionAction(action);
376
                } catch (Exception e) {
377
                        throw new RuntimeException(e);
378
                }
379

    
380
                return result.booleanValue();        }
381
        /**
382
         * create new table
383
         * 
384
         * @params ndsp
385
         * @params overwrite
386
         * @return
387
         */
388
        public boolean add(NewDataStoreParameters ndsp, boolean overwrite)
389
                        throws DataException {
390

    
391
                if (!(ndsp instanceof NewFeatureStoreParameters)) {
392
                        throw new IllegalArgumentException();
393
                }
394
                this.checkIsMine(ndsp);
395

    
396
                NewFeatureStoreParameters nfdsp = (NewFeatureStoreParameters) ndsp;
397

    
398
                // SQL CREATE NEW TABLE
399
                StringBuilder sqlnewtable = new StringBuilder();
400

    
401
                if (!nfdsp.isValid()) {
402
                        throw new InitializeException(this.getName(), new Exception(
403
                                        "Parameters not valid"));
404
                }
405
                try {
406
                        nfdsp.validate();
407
                } catch (ValidateDataParametersException e1) {
408
                        throw new InitializeException(this.getName(), e1);
409
                }
410

    
411
                FeatureType fType = nfdsp.getDefaultFeatureType();
412

    
413
                sqlnewtable.append("CREATE TABLE "
414
                                + ((JDBCStoreParameters) ndsp).tableID() + "(");
415
                Iterator<FeatureAttributeDescriptor> attrs = fType.iterator();
416
                String sqlAttr;
417
                List<String> sqlAttrs = new ArrayList<String>();
418

    
419
                while (attrs.hasNext()) {
420
                        sqlAttr = helper
421
                                        .getSqlFieldDescription((FeatureAttributeDescriptor) attrs
422
                                                        .next());
423
                        if (sqlAttr != null) {
424
                                sqlAttrs.add(sqlAttr);
425
                        }
426
                }
427

    
428
                helper.stringJoin(sqlAttrs, ", ", sqlnewtable);
429

    
430
                String pk = "CONSTRAINT "
431
                                + OracleUtils.getDerivedName(((JDBCStoreParameters) ndsp)
432
                                                .tableID(), "PK") + " PRIMARY KEY (\""
433
                                + OracleValues.DEFAULT_ID_FIELD_CASE_SENSITIVE + "\") ENABLE";
434

    
435
                sqlnewtable.append(", ");
436
                sqlnewtable.append(pk);
437

    
438
                sqlnewtable.append(")");
439
                final String sqlCreateNew = sqlnewtable.toString();
440

    
441
                // SQL CREATE SPATIAL INDEX
442
                final String sqlindex = "CREATE INDEX "
443
                                + OracleUtils.getDerivedName(((JDBCStoreParameters) ndsp)
444
                                                .tableID(), "SX") + " ON "
445
                                + ((JDBCStoreParameters) ndsp).tableID() + " (\""
446
                                + OracleValues.DEFAULT_GEO_FIELD
447
                                + "\") INDEXTYPE IS \"MDSYS\".\"SPATIAL_INDEX\" ";
448

    
449
                // SQL CREATE TABLE METADATA
450
                Rectangle2D bbox = new Rectangle2D.Double(0, 0, 1, 1);
451
                final String sqlmeta = ((OracleHelper) helper).getSqlUpdateMetadata(
452
                                (OracleStoreParameters) ndsp, null, bbox, 2, true);
453

    
454
                TransactionalAction action = new TransactionalAction() {
455

    
456
                        public boolean continueTransactionAllowed() {
457
                                return false;
458
                        }
459

    
460
                        public Object action(Connection conn) throws DataException {
461
                                Statement st = null;
462

    
463
                                try {
464
                                        st = conn.createStatement();
465
                                } catch (SQLException e1) {
466
                                        throw new JDBCSQLException(e1);
467
                                }
468
                                String sqlnew = null;
469
                                String sqlspatialindex = null;
470
                                String sqlmetadata = null;
471

    
472
                                // new table
473
                                try {
474
                                        sqlnew = sqlCreateNew;
475
                                        st.execute(sqlnew);
476

    
477
                                } catch (SQLException e) {
478
                                        try { st.close(); } catch (SQLException se) { logger.error("Exception closing statement", se); }
479
                                        throw new JDBCExecuteSQLException(sqlnew, e);
480
                                }
481
                                // new metadata
482
                                try {
483
                                        sqlmetadata = sqlmeta;
484
                                        st.execute(sqlmetadata);
485
                                } catch (SQLException e) {
486
                                        try { st.close(); } catch (SQLException se) { logger.error("Exception closing statement", se); }
487
                                        throw new JDBCExecuteSQLException(sqlspatialindex, e);
488
                                }
489
                                // new spatial index
490
                                try {
491
                                        sqlspatialindex = sqlindex;
492
                                        st.execute(sqlspatialindex);
493

    
494
                                } catch (SQLException e) {
495
                                        try { st.close(); } catch (SQLException se) { logger.error("Exception closing statement", se); }
496
                                        throw new JDBCExecuteSQLException(sqlspatialindex, e);
497
                                }
498

    
499
                                return Boolean.TRUE;
500
                        }
501

    
502
                };
503

    
504
                Boolean result = Boolean.FALSE;
505

    
506
                try {
507
                        result = (Boolean) helper.doConnectionAction(action);
508
                } catch (Exception e) {
509
                        throw new RuntimeException(e);
510
                }
511

    
512
                return result.booleanValue();
513
        }
514

    
515
        /**
516
         * create helper
517
         */
518
        protected JDBCHelper createHelper() throws InitializeException {
519
                return new OracleHelper(this, this.getOracleServerExplorerParameters());
520
        }
521

    
522
        /**
523
         * Get store name
524
         * 
525
         * @return
526
         */
527
        protected String getStoreName() {
528
                return OracleStoreProvider.NAME;
529
        }
530

    
531
        /**
532
         * get Oracle helper
533
         * 
534
         * @return
535
         */
536
        protected OracleHelper getOracleHelper() {
537
                return (OracleHelper) getHelper();
538
        }
539

    
540
        /**
541
         * Get list sql sentences for list available tables
542
         * 
543
         * @param mode
544
         * @param showInformationDBtables
545
         * @return
546
         */
547
        protected List<String> getSQLForList(int mode,
548
                        boolean showInformationDBTables) {
549
                List<String> list = new ArrayList<String>(1);
550
                list.add("SELECT TABLE_NAME FROM USER_SDO_GEOM_METADATA");
551

    
552
                return list;
553

    
554
        }
555

    
556
        /**
557
         * check oracle data store parameters, validate SSL and type driver (THIN or
558
         * OCI)
559
         * 
560
         * @param dsp
561
         */
562
        protected void checkIsMine(DataStoreParameters dsp) {
563
                if (!(dsp instanceof OracleStoreParameters)) {
564
                        throw new IllegalArgumentException(
565
                                        "not instance of OracleStoreParameters");
566
                }
567
                super.checkIsMine(dsp);
568

    
569
                OracleStoreParameters orap = (OracleStoreParameters) dsp;
570
                if (orap.getUseSSL().booleanValue() != this.getOracleServerExplorerParameters()
571
                                .getUseSSL()) {
572
                        throw new IllegalArgumentException("worng explorer: SSL");
573
                }
574
                if (orap.getOraDriverType().compareToIgnoreCase(
575
                                this.getOracleServerExplorerParameters().getOraDriverType()) != 0) {
576
                        throw new IllegalArgumentException(
577
                                        "worng explorer: Oracle type driver: THIN or OCI");
578
                }
579
        }
580

    
581
        /**
582
         * Create store parameters
583
         */
584
        protected JDBCStoreParameters createStoreParams()
585
                        throws InitializeException, ProviderNotRegisteredException {
586
                OracleStoreParameters params = (OracleStoreParameters) super.createStoreParams();
587
                // add SSL and type driver (THIN or OCI)
588
                params.setSchema(params.getUser());
589
                params.setUseSSL(this.getOracleServerExplorerParameters().getUseSSL());
590
                params.setOraDriverType(this.getOracleServerExplorerParameters()
591
                                .getOraDriverType());
592

    
593
                return params;
594
        }
595

    
596
        /**
597
         * Get Oracle server explorer parameters
598
         * 
599
         * @return
600
         */
601
        private OracleServerExplorerParameters getOracleServerExplorerParameters() {
602
                return (OracleServerExplorerParameters) getParameters();
603
        }
604

    
605
}