Statistics
| Revision:

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

History | View | Annotate | Download (12.7 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 remove(DataStoreParameters dsp) throws RemoveException {
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
                                // SQL REMOVE TABLE
125
                                String sqlDropTable = "DROP TABLE " + oraParams.tableID()
126
                                                + " CASCADE CONSTRAINTS";
127

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

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

    
145
                                try {
146
                                        // DROP TABLE
147
                                        try {
148
                                                st.execute(sqlDropTable);
149
                                        } catch (SQLException e) {
150
                                                throw new JDBCExecuteSQLException(sqlDropTable, e);
151
                                        }
152
                                        // DELETE METADATA
153
                                        try {
154
                                                st.execute(sqlDeleteMetadata);
155
                                        } catch (SQLException e) {
156
                                                throw new JDBCExecuteSQLException(sqlDeleteMetadata, e);
157
                                        }
158

    
159
                                } finally {
160
                                        try {
161
                                                st.close();
162
                                        } catch (SQLException e) {
163
                                        }
164
                                        ;
165
                                }
166
                                return null;
167
                        }
168
                };
169
                try {
170
                        this.helper.doConnectionAction(action);
171
                } catch (Exception e) {
172
                        throw new RemoveException(this.getName(), e);
173
                }
174
        }
175

    
176
        /**
177
         * get parameters
178
         */
179
        public NewDataStoreParameters getAddParameters() throws DataException {
180
                OracleServerExplorerParameters parameters = getOracleSpatialParameters();
181
                OracleNewStoreParameters params = new OracleNewStoreParameters();
182
                params.setHost(parameters.getHost());
183
                params.setPort(parameters.getPort());
184
                params.setDBName(parameters.getDBName());
185
                params.setUser(parameters.getUser());
186
                params.setPassword(parameters.getPassword());
187
                params.setCatalog(parameters.getCatalog());
188
                params.setSchema(parameters.getSchema());
189
                params.setJDBCDriverClassName(parameters.getJDBCDriverClassName());
190
                params.setUrl(parameters.getUrl());
191
                params.setUseSSL(parameters.getUseSSL());
192
                params.setOraDriverType(parameters.getOraDriverType());
193

    
194
                params.setDefaultFeatureType(this.getServerExplorerProviderServices()
195
                                .createNewFeatureType());
196

    
197
                return params;
198
        }
199

    
200
        /**
201
         * Geometry support
202
         */
203
        public boolean hasGeometrySupport() {
204
                return true;
205
        }
206

    
207
        /**
208
         * Get list of table availables in Oracle schema registered in geometry
209
         * metadata view
210
         */
211
        public List<JDBCStoreParameters> list(final int mode,
212
                        final boolean showInformationDBTables) throws DataException {
213

    
214
                final JDBCStoreParameters orgParams = createStoreParams();
215

    
216
                ConnectionAction action = new ConnectionAction() {
217

    
218
                        public Object action(Connection conn) throws DataException {
219
                                ResultSet rs = null;
220
                                Statement st = null;
221

    
222
                                List<String> sqls = getSQLForList(mode, showInformationDBTables);
223

    
224
                                try {
225
                                        JDBCStoreParameters params = null;
226

    
227
                                        List<JDBCStoreParameters> paramList = new ArrayList<JDBCStoreParameters>();
228

    
229
                                        conn = helper.getConnection();
230
                                        st = conn.createStatement();
231
                                        String sql;
232
                                        Iterator<String> sqlIter = sqls.iterator();
233
                                        while (sqlIter.hasNext()) {
234
                                                sql = sqlIter.next();
235
                                                rs = st.executeQuery(sql);
236
                                                while (rs.next()) {
237
                                                        params = (JDBCStoreParameters) orgParams.getCopy();
238
                                                        params.setTable(rs.getString(1));
239
                                                        paramList.add(params);
240
                                                }
241
                                        }
242

    
243
                                        return paramList;
244
                                } catch (SQLException e) {
245
                                        throw new JDBCSQLException(e);
246
                                } finally {
247
                                        try {
248
                                                rs.close();
249
                                        } catch (Exception e) {
250
                                        }
251
                                        ;
252
                                        try {
253
                                                st.close();
254
                                        } catch (Exception e) {
255
                                        }
256
                                        ;
257
                                }
258
                        }
259

    
260
                };
261

    
262
                try {
263
                        return (List) helper.doConnectionAction(action);
264
                } catch (Exception e) {
265
                        throw new ReadException(this.getName(), e);
266
                }
267
        }
268

    
269
        /**
270
         * create new table
271
         * 
272
         * @params ndsp
273
         * @params overwrite
274
         * @return
275
         */
276
        public boolean add(NewDataStoreParameters ndsp, boolean overwrite)
277
                        throws DataException {
278

    
279
                if (!(ndsp instanceof NewFeatureStoreParameters)) {
280
                        throw new IllegalArgumentException();
281
                }
282
                this.checkIsMine(ndsp);
283

    
284
                NewFeatureStoreParameters nfdsp = (NewFeatureStoreParameters) ndsp;
285

    
286
                // SQL CREATE NEW TABLE
287
                StringBuilder sqlnewtable = new StringBuilder();
288

    
289
                if (!nfdsp.isValid()) {
290
                        throw new InitializeException(this.getName(), new Exception(
291
                                        "Parameters not valid"));
292
                }
293
                try {
294
                        nfdsp.validate();
295
                } catch (ValidateDataParametersException e1) {
296
                        throw new InitializeException(this.getName(), e1);
297
                }
298

    
299
                FeatureType fType = nfdsp.getDefaultFeatureType();
300

    
301
                sqlnewtable.append("CREATE TABLE " + ((JDBCStoreParameters) ndsp).tableID()
302
                                + "(");
303
                Iterator<FeatureAttributeDescriptor> attrs = fType.iterator();
304
                String sqlAttr;
305
                List<String> sqlAttrs = new ArrayList<String>();
306

    
307
                while (attrs.hasNext()) {
308
                        sqlAttr = helper
309
                                        .getSqlFieldDescription((FeatureAttributeDescriptor) attrs
310
                                                        .next());
311
                        if (sqlAttr != null) {
312
                                sqlAttrs.add(sqlAttr);
313
                        }
314
                }
315

    
316
                helper.stringJoin(sqlAttrs, ", ", sqlnewtable);
317

    
318
                String pk = "CONSTRAINT "
319
                                + OracleUtils.getDerivedName(
320
                                                ((JDBCStoreParameters) ndsp).tableID(), "PK")
321
                                + " PRIMARY KEY (\""
322
                                + OracleValues.DEFAULT_ID_FIELD_CASE_SENSITIVE + "\") ENABLE";
323

    
324
                sqlnewtable.append(", ");
325
                sqlnewtable.append(pk);
326

    
327
                sqlnewtable.append("); ");
328
                final String sqlCreateNew = sqlnewtable.toString();
329
                
330
                // SQL CREATE SPATIAL INDEX
331
                final String sqlindex = "CREATE INDEX "
332
                        + OracleUtils.getDerivedName(((JDBCStoreParameters) ndsp).tableID(), "SX") + " ON "
333
                        + ((JDBCStoreParameters) ndsp).tableID() + " (\"" + OracleValues.DEFAULT_GEO_FIELD
334
                        + "\") INDEXTYPE IS \"MDSYS\".\"SPATIAL_INDEX\" ";
335

    
336
                // SQL CREATE TABLE METADATA
337
                Rectangle2D bbox = new Rectangle2D.Double(0,0,1,1);
338
                final String sqlmeta = ((OracleHelper) helper)
339
                                .getSqlUpdateMetadata((OracleStoreParameters)ndsp, null, bbox, 2, true);                
340

    
341
                TransactionalAction action = new TransactionalAction() {
342

    
343
                        public boolean continueTransactionAllowed() {
344
                                return false;
345
                        }
346

    
347
                        public Object action(Connection conn) throws DataException {
348
                                Statement st = null;
349

    
350
                                try {
351
                                        st = conn.createStatement();
352
                                } catch (SQLException e1) {
353
                                        throw new JDBCSQLException(e1);
354
                                }
355
                                String sqlnew = null;
356
                                String sqlspatialindex = null;
357
                                String sqlmetadata = null;
358

    
359
                                // new table
360
                                try {
361
                                        sqlnew = sqlCreateNew;
362
                                        st.execute(sqlnew);
363

    
364
                                } catch (SQLException e) {
365
                                        throw new JDBCExecuteSQLException(sqlnew, e);
366
                                }
367
                                //new spatial index
368
                                try {
369
                                        sqlspatialindex = sqlindex;
370
                                        st.execute(sqlspatialindex);
371

    
372
                                } catch (SQLException e) {
373
                                        throw new JDBCExecuteSQLException(sqlspatialindex, e);
374
                                }
375
                                //new metadata
376
                                try {
377
                                        sqlmetadata = sqlmeta;
378
                                        st.execute(sqlmetadata);
379

    
380
                                } catch (SQLException e) {
381
                                        throw new JDBCExecuteSQLException(sqlspatialindex, e);
382
                                } finally {
383
                                        try {
384
                                                st.close();
385
                                        } catch (SQLException e) {
386
                                                logger.error("Exception clossing statement", e);
387
                                        }
388
                                        ;
389
                                }
390

    
391
                                return Boolean.TRUE;
392
                        }
393

    
394
                };
395

    
396
                Boolean result = Boolean.FALSE;
397

    
398
                try {
399
                        result = (Boolean) helper.doConnectionAction(action);
400
                } catch (Exception e) {
401
                        throw new RuntimeException(e);
402
                }
403

    
404
                return result.booleanValue();
405
        }
406

    
407
        /**
408
         * create helper
409
         */
410
        protected JDBCHelper createHelper() throws InitializeException {
411
                return new OracleHelper(this, getOracleSpatialParameters());
412
        }
413

    
414
        /**
415
         * Get store name
416
         * 
417
         * @return
418
         */
419
        protected String getStoreName() {
420
                return OracleStoreProvider.NAME;
421
        }
422

    
423
        /**
424
         * get Oracle helper
425
         * 
426
         * @return
427
         */
428
        protected OracleHelper getOracleHelper() {
429
                return (OracleHelper) getHelper();
430
        }
431

    
432
        /**
433
         * Get list sql sentences for list available tables
434
         * 
435
         * @param mode
436
         * @param showInformationDBtables
437
         * @return
438
         */
439
        protected List<String> getSQLForList(int mode,
440
                        boolean showInformationDBTables) {
441
                List<String> list = new ArrayList<String>(1);
442
                list.add("SELECT TABLE_NAME FROM USER_SDO_GEOM_METADATA");
443

    
444
                return list;
445

    
446
        }
447

    
448
        /**
449
         * check oracle data store parameters, validate SSL and type driver (THIN or
450
         * OCI)
451
         * 
452
         * @param dsp
453
         */
454
        protected void checkIsMine(DataStoreParameters dsp) {
455
                if (!(dsp instanceof OracleStoreParameters)) {
456
                        throw new IllegalArgumentException(
457
                                        "not instance of OracleSpatialStoreParameters");
458
                }
459
                super.checkIsMine(dsp);
460

    
461
                OracleStoreParameters orap = (OracleStoreParameters) dsp;
462
                if (orap.getUseSSL().booleanValue() != getOracleSpatialParameters()
463
                                .getUseSSL()) {
464
                        throw new IllegalArgumentException("worng explorer: SSL");
465
                }
466
                if (orap.getOraDriverType().compareToIgnoreCase(
467
                                getOracleSpatialParameters().getOraDriverType()) != 0) {
468
                        throw new IllegalArgumentException(
469
                                        "worng explorer: Oracle type driver: THIN or OCI");
470
                }
471
        }
472

    
473
        /**
474
         * Create store parameters
475
         */
476
        protected JDBCStoreParameters createStoreParams()
477
                        throws InitializeException, ProviderNotRegisteredException {
478
                OracleStoreParameters params = (OracleStoreParameters) super
479
                                .createStoreParams();
480
                // add SSL and type driver (THIN or OCI)
481
                params.setUseSSL(getOracleSpatialParameters().getUseSSL());
482
                params
483
                                .setOraDriverType(getOracleSpatialParameters()
484
                                                .getOraDriverType());
485

    
486
                return params;
487
        }
488

    
489
        /**
490
         * Get Oracle server explorer parameters
491
         * 
492
         * @return
493
         */
494
        private OracleServerExplorerParameters getOracleSpatialParameters() {
495
                return (OracleServerExplorerParameters) getParameters();
496
        }
497

    
498
}