Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.compat.cdc / org.gvsig.fmap.dal / org.gvsig.fmap.dal.db / org.gvsig.fmap.dal.db.jdbc / src / main / java / org / gvsig / fmap / dal / store / jdbc / JDBCServerExplorer.java @ 40596

History | View | Annotate | Download (16.1 KB)

1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
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 3
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
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.fmap.dal.store.jdbc;
25

    
26
import java.sql.Connection;
27
import java.sql.DatabaseMetaData;
28
import java.sql.ResultSet;
29
import java.sql.SQLException;
30
import java.sql.Statement;
31
import java.util.ArrayList;
32
import java.util.Iterator;
33
import java.util.List;
34

    
35
import org.slf4j.Logger;
36
import org.slf4j.LoggerFactory;
37

    
38
import org.gvsig.fmap.dal.DALLocator;
39
import org.gvsig.fmap.dal.DataManager;
40
import org.gvsig.fmap.dal.DataStore;
41
import org.gvsig.fmap.dal.DataStoreParameters;
42
import org.gvsig.fmap.dal.NewDataStoreParameters;
43
import org.gvsig.fmap.dal.exception.CloseException;
44
import org.gvsig.fmap.dal.exception.DataException;
45
import org.gvsig.fmap.dal.exception.InitializeException;
46
import org.gvsig.fmap.dal.exception.OpenException;
47
import org.gvsig.fmap.dal.exception.ProviderNotRegisteredException;
48
import org.gvsig.fmap.dal.exception.ReadException;
49
import org.gvsig.fmap.dal.exception.RemoveException;
50
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
51
import org.gvsig.fmap.dal.feature.EditableFeatureType;
52
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
53
import org.gvsig.fmap.dal.feature.FeatureType;
54
import org.gvsig.fmap.dal.feature.NewFeatureStoreParameters;
55
import org.gvsig.fmap.dal.resource.spi.ResourceProvider;
56
import org.gvsig.fmap.dal.serverexplorer.db.spi.AbstractDBServerExplorer;
57
import org.gvsig.fmap.dal.spi.DataManagerProviderServices;
58
import org.gvsig.fmap.dal.spi.DataServerExplorerProviderServices;
59
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCExecuteSQLException;
60
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCSQLException;
61
import org.gvsig.tools.exception.BaseException;
62

    
63

    
64
/**
65
 * @author jmvivo
66
 *
67
 */
68
public class JDBCServerExplorer extends AbstractDBServerExplorer
69
                implements JDBCHelperUser {
70

    
71
        private static final Logger LOG = LoggerFactory
72
                        .getLogger(JDBCServerExplorer.class);
73
        
74
        private static final String METADATA_COLUMN_TABLE_CATALOG = "TABLE_CAT";
75
        private static final String METADATA_COLUMN_TABLE_SCHEMA = "TABLE_SCHEM";
76
        private static final String METADATA_COLUMN_TABLE_NAME = "TABLE_NAME";
77

    
78
        public static final String NAME = "JDBCServerExplorer";
79
        protected JDBCHelper helper;
80

    
81
        private Boolean canAdd;
82

    
83
        public JDBCServerExplorer(JDBCServerExplorerParameters parameters,
84
                        DataServerExplorerProviderServices services)
85
                        throws InitializeException {
86
                super(parameters, services);
87
                this.helper = createHelper();
88
        }
89

    
90
        protected JDBCServerExplorerParameters getJDBCParameters() {
91
                return (JDBCServerExplorerParameters) getParameters();
92
        }
93

    
94
        protected JDBCHelper createHelper() throws InitializeException {
95
                return new JDBCHelper(this, getJDBCParameters());
96
        }
97

    
98
        protected JDBCHelper getHelper() {
99
                return helper;
100
        }
101

    
102

    
103
        public List list() throws DataException {
104
                return this.list(MODE_ALL);
105
        }
106

    
107
        public List list(boolean showInformationDBTables) throws DataException {
108
                return this.list(MODE_ALL, showInformationDBTables);
109
        }
110

    
111
        public List list(int mode) throws DataException {
112
                JDBCServerExplorerParameters parameters = getJDBCParameters();
113
                if (parameters.getShowInformationDBTables() != null) {
114
                        return this.list(mode, parameters.getShowInformationDBTables()
115
                                        .booleanValue());
116
                }
117
                Boolean show = (Boolean) parameters
118
                                .getDynClass()
119
                                .getDynField(
120
                                                JDBCServerExplorerParameters.SHOWINFORMATIONDBTABLES_PARAMTER_NAME)
121
                                .getDefaultValue();
122
                if (show == null){
123
                        show = Boolean.FALSE;
124
                }
125

    
126
                return this.list(mode, show.booleanValue());
127
        }
128

    
129

    
130
        protected DataManagerProviderServices getManager() {
131
                return (DataManagerProviderServices) DALLocator.getDataManager();
132
        }
133

    
134
        public boolean hasGeometrySupport() {
135
                return false;
136
        }
137

    
138
        public boolean closeResourceRequested(ResourceProvider resource) {
139
                try {
140
                        this.helper.close();
141
                } catch (CloseException e) {
142
                        LOG.error("Exception in close Request", e);
143
                }
144
                return !this.helper.isOpen();
145
        }
146

    
147
        public void resourceChanged(ResourceProvider resource) {
148
                // Nothing to do
149
        }
150

    
151
        public void remove(DataStoreParameters dsp) throws RemoveException {
152
                final JDBCStoreParameters dsParams =(JDBCStoreParameters) dsp;
153

    
154
                TransactionalAction action = new TransactionalAction() {
155
                        public boolean continueTransactionAllowed() {
156
                                return false;
157
                        }
158
                        public Object action(Connection conn) throws DataException {
159
                                Statement st;
160
                                try{
161
                                        st = conn.createStatement();
162
                                } catch (SQLException e) {
163
                                        throw new JDBCSQLException(e);
164
                                }
165

    
166
                                String sqlDrop = "Drop table "
167
                                        + dsParams.tableID();
168

    
169
                                try{
170
                                        try{
171
                                                st.execute(sqlDrop);
172
                                        } catch (SQLException e) {
173
                                                throw new JDBCExecuteSQLException(sqlDrop, e);
174
                                        }
175

    
176
                                } finally{
177
                                        try{ st.close(); } catch (SQLException e) {};
178
                                }
179
                                return null;
180
                        }
181
                };
182
                try {
183
                        this.helper.doConnectionAction(action);
184
                } catch (Exception e) {
185
                        throw new RemoveException(this.getProviderName(), e);
186
                }
187
        }
188

    
189
        public NewDataStoreParameters getAddParameters() throws DataException {
190
                JDBCServerExplorerParameters parameters = getJDBCParameters();
191
                JDBCNewStoreParameters params = new JDBCNewStoreParameters();
192
                params.setHost(parameters.getHost());
193
                params.setPort(parameters.getPort());
194
                params.setDBName(parameters.getDBName());
195
                params.setUser(parameters.getUser());
196
                params.setPassword(parameters.getPassword());
197
                params.setCatalog(parameters.getCatalog());
198
                params.setSchema(parameters.getSchema());
199
                params.setJDBCDriverClassName(parameters.getJDBCDriverClassName());
200
                params.setUrl(parameters.getUrl());
201

    
202
                params.setDefaultFeatureType(this.getServerExplorerProviderServices()
203
                                .createNewFeatureType());
204

    
205
                return params;
206
        }
207

    
208
        public void closeDone() throws DataException {
209
                // Nothing to do
210
        }
211

    
212
        public void opendDone() throws DataException {
213
                // Nothin to do
214

    
215
        }
216

    
217
        public DataStore open(DataStoreParameters dsp) throws DataException {
218
                checkIsMine(dsp);
219
                DataManager dataMan = DALLocator.getDataManager();
220
                DataStore store;
221
                try {
222
                        store = dataMan.openStore(dsp.getDataStoreName(), dsp);
223
                } catch (ValidateDataParametersException e) {
224
                        throw new InitializeException(e);
225
                }
226

    
227
                return store;
228
        }
229

    
230
        protected void checkIsMine(DataStoreParameters dsp) {
231
                if (!(dsp instanceof JDBCStoreParameters)) {
232
                        // FIXME Exception ???
233
                        throw new IllegalArgumentException(
234
                                        "not instance of FilesystemStoreParameters");
235
                }
236

    
237
                // try {
238
                // dsp.validate();
239
                // } catch (ValidateDataParametersException e) {
240
                // throw new IllegalArgumentException("check parameters", e);
241
                // }
242

    
243
                JDBCServerExplorerParameters parameters = getJDBCParameters();
244

    
245
                JDBCStoreParameters pgp = (JDBCStoreParameters) dsp;
246
                if (!compare(pgp.getHost(), parameters.getHost())) {
247
                        throw new IllegalArgumentException("wrong explorer: Host (mine: "
248
                                        + parameters.getHost() + " other:" + pgp.getHost() + ")");
249
                }
250
                if (!compare(pgp.getPort(), parameters.getPort())) {
251
                        throw new IllegalArgumentException("wrong explorer: Port (mine: "
252
                                        + parameters.getPort() + " other:" + pgp.getPort() + ")");
253
                }
254
                if (!compare(pgp.getDBName(), parameters.getDBName())) {
255
                        throw new IllegalArgumentException("wrong explorer: DBName (mine: "
256
                                        + parameters.getDBName() + " other:" + pgp.getDBName()
257
                                        + ")");
258
                }
259
                if (parameters.getCatalog() != null && !parameters.getCatalog().trim().equals("")) {
260
                        // implicit catalog
261
                        if (!compare(pgp.getCatalog(), parameters.getCatalog())) {
262
                                throw new IllegalArgumentException(
263
                                                "wrong explorer: Catalog (mine: "
264
                                                                + parameters.getCatalog() + " other:"
265
                                                                + pgp.getCatalog() + ")");
266
                        }
267
                }
268
                if (parameters.getSchema() != null && !parameters.getSchema().trim().equals("")) {
269
                        // implicit schema
270
                        if (!compare(pgp.getSchema(), parameters.getSchema())) {
271
                                throw new IllegalArgumentException(
272
                                                "wrong explorer: Schema (mine: "
273
                                                                + parameters.getSchema() + " other:"
274
                                                                + pgp.getSchema() + ")");
275
                        }
276
                }
277
        }
278

    
279
        protected boolean compare(Object str1, Object str2) {
280
                if (str1 == str2){
281
                        return true;
282
                }
283
                if (str1 == null){
284
                        return false;
285
                }
286
                return  str1.equals(str2);
287
        }
288

    
289
        protected JDBCStoreParameters createStoreParams()
290
                        throws InitializeException, ProviderNotRegisteredException {
291
                DataManagerProviderServices manager = this.getManager();
292
                JDBCServerExplorerParameters parameters = getJDBCParameters();
293
                JDBCStoreParameters orgParams = (JDBCStoreParameters) manager
294
                                .createStoreParameters(getStoreName());
295
                orgParams.setHost(parameters.getHost());
296
                orgParams.setPort(parameters.getPort());
297
                orgParams.setDBName(parameters.getDBName());
298
                orgParams.setUser(parameters.getUser());
299
                orgParams.setPassword(parameters.getPassword());
300
        orgParams.setCatalog(parameters.getCatalog());
301
        orgParams.setJDBCDriverClassName(parameters.getJDBCDriverClassName());
302
        orgParams.setSchema(parameters.getSchema());
303
        orgParams.setUrl(parameters.getUrl());
304
                return orgParams;
305
        }
306

    
307
        public List list(final int mode, final boolean showInformationDBTables)
308
                        throws DataException {
309

    
310
                final JDBCStoreParameters orgParams = createStoreParams();
311

    
312
                ConnectionAction action = new ConnectionAction() {
313

    
314
                        public Object action(Connection conn) throws DataException {
315

    
316
                                String[] tableTypes = null;
317
                                if (!showInformationDBTables) {
318
                                        tableTypes = new String[] { "TABLE", "VIEW" };
319
                                }
320

    
321
                                ResultSet result = null;
322
                                try {
323
                                        DatabaseMetaData metadata = conn.getMetaData();
324
                                        result = metadata.getTables(null, null, null,
325
                                                        tableTypes);
326
                                        List<JDBCStoreParameters> paramList = new ArrayList<JDBCStoreParameters>();
327
                                        while (result.next()) {
328
                                                JDBCStoreParameters params = (JDBCStoreParameters) orgParams
329
                                                                .getCopy();
330
                                                params.setCatalog(result
331
                                                                .getString(METADATA_COLUMN_TABLE_CATALOG));
332
                                                params.setSchema(result
333
                                                                .getString(METADATA_COLUMN_TABLE_SCHEMA));
334
                                                params.setTable(result
335
                                                                .getString(METADATA_COLUMN_TABLE_NAME));
336
                                                paramList.add(params);
337
                                        }
338

    
339
                                        return paramList;
340
                                } catch (SQLException e) {
341
                                        throw new JDBCSQLException(e);
342
                                } finally {
343
                                        if (result != null) {
344
                                                try {
345
                                                        result.close();
346
                                                } catch (Exception e) {
347
                                                        LOG.error("Error closing DatabaseMetadata "
348
                                                                        + "getTables() Resultset", e);
349
                                                }
350
                                        }
351
                                }
352
                        }
353

    
354
                };
355

    
356
                try {
357
                        return (List) helper.doConnectionAction(action);
358
                } catch (Exception e) {
359
                        throw new ReadException(this.getProviderName(), e);
360
                }
361
        }
362

    
363

    
364
        public void open() throws OpenException {
365
                helper.open();
366
        }
367

    
368
        public void close() throws CloseException {
369
                helper.close();
370
        }
371

    
372
        @Override
373
        protected void doDispose() throws BaseException {
374
                helper.dispose();
375
                helper = null;
376
        }
377

    
378
        public String getProviderName() {
379
                return NAME;
380
        }
381

    
382
        protected String getStoreName() {
383
                return JDBCStoreProvider.NAME;
384
        }
385

    
386
        public boolean canAdd() {
387
                if (this.canAdd == null){
388
                        ConnectionAction action = new ConnectionAction(){
389

    
390
                                public Object action(Connection conn) throws DataException {
391
                                        try {
392
                                        DatabaseMetaData metadata = conn.getMetaData();
393
                                                if (metadata.isReadOnly()) {
394
                                                        return Boolean.FALSE;
395
                                                }
396
                                                return Boolean.TRUE;
397
                                        } catch (SQLException e) {
398
                                                throw new JDBCSQLException(e);
399
                                        }
400
                                }
401

    
402
                        };
403

    
404
                        try {
405
                                this.canAdd = (Boolean) helper.doConnectionAction(action);
406
                        } catch (Exception e) {
407
                                // FIXME Exception
408
                                throw new RuntimeException(e);
409
                        }
410
                }
411
                return this.canAdd.booleanValue();
412
        }
413

    
414
        public FeatureType getFeatureType(DataStoreParameters dsp)
415
                        throws DataException {
416
                checkIsMine(dsp);
417

    
418
                // TODO: checks geometry columns and driver geometry supports
419
                EditableFeatureType edType = this.getServerExplorerProviderServices()
420
                                .createNewFeatureType();
421
                helper.loadFeatureType(edType, (JDBCStoreParameters) dsp);
422

    
423
                return edType;
424

    
425
        }
426

    
427

    
428
        public boolean add(String providerName, NewDataStoreParameters ndsp, boolean overwrite)
429
                        throws DataException {
430

    
431
                /**
432
                 * CREATE [ [ GLOBAL | LOCAL ] { TEMPORARY | TEMP } ] TABLE table_name (
433
                 * { column_name data_type [ DEFAULT default_expr ] [ column_constraint
434
                 * [ ... ] ] | table_constraint | LIKE parent_table [ { INCLUDING |
435
                 * EXCLUDING } DEFAULTS ] } [, ... ] ) [ INHERITS ( parent_table [, ...
436
                 * ] ) ] [ WITH OIDS | WITHOUT OIDS ] [ ON COMMIT { PRESERVE ROWS |
437
                 * DELETE ROWS | DROP } ]
438
                 *
439
                 * where column_constraint is:
440
                 *
441
                 * [ CONSTRAINT constraint_name ] { NOT NULL | NULL | UNIQUE | PRIMARY
442
                 * KEY | CHECK (expression) | REFERENCES reftable [ ( refcolumn ) ] [
443
                 * MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON
444
                 * UPDATE action ] } [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY
445
                 * DEFERRED | INITIALLY IMMEDIATE ]
446
                 *
447
                 * and table_constraint is:
448
                 *
449
                 * [ CONSTRAINT constraint_name ] { UNIQUE ( column_name [, ... ] ) |
450
                 * PRIMARY KEY ( column_name [, ... ] ) | CHECK ( expression ) | FOREIGN
451
                 * KEY ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ...
452
                 * ] ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE
453
                 * action ] [ ON UPDATE action ] } [ DEFERRABLE | NOT DEFERRABLE ] [
454
                 * INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
455
                 */
456

    
457
                if (!(ndsp instanceof NewFeatureStoreParameters)) {
458
                        // FIXME exception
459
                        throw new IllegalArgumentException();
460
                }
461
                checkIsMine(ndsp);
462

    
463
                NewFeatureStoreParameters nfdsp = (NewFeatureStoreParameters) ndsp;
464

    
465
                StringBuilder sql = new StringBuilder();
466

    
467
                if (!nfdsp.isValid()) {
468
                        // TODO Exception
469
                        throw new InitializeException(this.getProviderName(), new Exception(
470
                                        "Parameters not valid"));
471
                }
472
                try {
473
                        nfdsp.validate();
474
                } catch (ValidateDataParametersException e1) {
475
                        throw new InitializeException(this.getProviderName(), e1);
476
                }
477

    
478
                FeatureType fType = nfdsp.getDefaultFeatureType();
479

    
480
                sql.append("Create table " + ((JDBCStoreParameters) ndsp).tableID()
481
                                + "(");
482
                Iterator attrs = fType.iterator();
483
                String sqlAttr;
484
                List sqlAttrs = new ArrayList();
485

    
486
                while (attrs.hasNext()) {
487
                        sqlAttr = helper
488
                                        .getSqlFieldDescription((FeatureAttributeDescriptor) attrs
489
                                                        .next());
490
                        if (sqlAttr != null) {
491
                                sqlAttrs.add(sqlAttr);
492
                        }
493
                }
494

    
495
                helper.stringJoin(sqlAttrs, ", ", sql);
496

    
497
                sql.append(")");
498

    
499
                final String sqlCreate = sql.toString();
500
                final List sqlAdditional = helper
501
                                .getAdditionalSqlToCreate(ndsp, fType);
502

    
503
                TransactionalAction action = new TransactionalAction() {
504

    
505
                        public boolean continueTransactionAllowed() {
506
                                // TODO Auto-generated method stub
507
                                return false;
508
                        }
509

    
510
                        public Object action(Connection conn) throws DataException {
511
                                Statement st = null;
512

    
513
                                try {
514
                                        st = conn.createStatement();
515
                                } catch (SQLException e1) {
516
                                        throw new JDBCSQLException(e1);
517
                                }
518
                                String sql = null;
519

    
520
                                try {
521
                                        sql = sqlCreate;
522
                                        st.execute(sql);
523
                                        if (sqlAdditional != null) {
524
                                                Iterator iter = sqlAdditional.iterator();
525
                                                while (iter.hasNext()) {
526
                                                        sql = (String) iter.next();
527
                                                        st.execute(sql);
528
                                                }
529
                                        }
530

    
531
                                } catch (SQLException e) {
532
                                        throw new JDBCExecuteSQLException(sql, e);
533
                                } finally {
534
                                        try {
535
                                                st.close();
536
                                        } catch (SQLException e) {
537
                                                LOG.error("Exception clossing statement", e);
538
                                        }
539
                                        ;
540
                                }
541

    
542
                                return Boolean.TRUE;
543
                        }
544

    
545
                };
546

    
547
                Boolean result = Boolean.FALSE;
548

    
549
                try {
550
                        result = (Boolean) helper.doConnectionAction(action);
551
                } catch (Exception e) {
552
                        // FIXME Exception
553
                        throw new RuntimeException(e);
554
                }
555

    
556
                return result.booleanValue();
557
        }
558

    
559
        public List getDataStoreProviderNames() {
560
                List x = new ArrayList(1);
561
                x.add(JDBCStoreProvider.NAME);
562
                return x;
563
        }
564

    
565
}