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 / JDBCServerExplorerBase.java @ 43377

History | View | Annotate | Download (21.4 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 modify it under
7
 * the terms of the GNU General Public License as published by the Free Software
8
 * Foundation; either version 3 of the License, or (at your option) any later
9
 * version.
10
 *
11
 * This program is distributed in the hope that it will be useful, but WITHOUT
12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14
 * details.
15
 *
16
 * You should have received a copy of the GNU General Public License along with
17
 * this program; if not, write to the Free Software Foundation, Inc., 51
18
 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19
 *
20
 * For any additional information, do not hesitate to contact us at info AT
21
 * gvsig.com, or visit our website www.gvsig.com.
22
 */
23
package org.gvsig.fmap.dal.store.jdbc;
24

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

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

    
37
import org.gvsig.fmap.dal.DALLocator;
38
import org.gvsig.fmap.dal.DataManager;
39
import org.gvsig.fmap.dal.DataStore;
40
import org.gvsig.fmap.dal.DataStoreParameters;
41
import org.gvsig.fmap.dal.NewDataStoreParameters;
42
import org.gvsig.fmap.dal.exception.CloseException;
43
import org.gvsig.fmap.dal.exception.DataException;
44
import org.gvsig.fmap.dal.exception.InitializeException;
45
import org.gvsig.fmap.dal.exception.OpenException;
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.EditableFeatureType;
51
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
52
import org.gvsig.fmap.dal.feature.FeatureType;
53
import org.gvsig.fmap.dal.resource.spi.ResourceProvider;
54
import org.gvsig.fmap.dal.serverexplorer.db.spi.AbstractDBServerExplorer;
55
import org.gvsig.fmap.dal.spi.DataManagerProviderServices;
56
import org.gvsig.fmap.dal.spi.DataServerExplorerProviderServices;
57
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCExecuteSQLException;
58
import org.gvsig.fmap.dal.store.jdbc.exception.JDBCSQLException;
59
import org.gvsig.tools.exception.BaseException;
60

    
61
/**
62
 * @author jmvivo
63
 *
64
 */
65
public class JDBCServerExplorerBase extends AbstractDBServerExplorer
66
        implements JDBCHelperUser, JDBCServerExplorer {
67

    
68
    private static final Logger LOG = LoggerFactory
69
            .getLogger(JDBCServerExplorerBase.class);
70

    
71
    private static final String METADATA_COLUMN_TABLE_CATALOG = "TABLE_CAT";
72
    private static final String METADATA_COLUMN_TABLE_SCHEMA = "TABLE_SCHEM";
73
    private static final String METADATA_COLUMN_TABLE_NAME = "TABLE_NAME";
74

    
75
    public static final String NAME = "JDBCServerExplorer";
76
    protected JDBCHelper helper;
77

    
78
    private Boolean canAdd;
79

    
80
    public JDBCServerExplorerBase(JDBCServerExplorerParameters parameters,
81
            DataServerExplorerProviderServices services)
82
            throws InitializeException {
83
        super(parameters, services);
84
        this.helper = createHelper();
85
    }
86

    
87
    protected JDBCServerExplorerParameters getJDBCParameters() {
88
        return (JDBCServerExplorerParameters) getParameters();
89
    }
90

    
91
    protected JDBCHelper createHelper() throws InitializeException {
92
        return new JDBCHelper(this, getJDBCParameters());
93
    }
94

    
95
    protected JDBCHelper getHelper() {
96
        return helper;
97
    }
98

    
99
    public List list() throws DataException {
100
        return this.list(MODE_ALL);
101
    }
102

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

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

    
123
        return this.list(mode, show.booleanValue());
124
    }
125

    
126
    protected DataManagerProviderServices getManager() {
127
        return (DataManagerProviderServices) DALLocator.getDataManager();
128
    }
129

    
130
    public boolean hasGeometrySupport() {
131
        return false;
132
    }
133

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

    
143
    public void resourceChanged(ResourceProvider resource) {
144
        // Nothing to do
145
    }
146

    
147
    @Override
148
    public void remove(DataStoreParameters dsp) throws RemoveException {
149
        final JDBCStoreParameters dsParams = (JDBCStoreParameters) dsp;
150

    
151
        TransactionalAction action = new TransactionalAction() {
152
            public boolean continueTransactionAllowed() {
153
                return false;
154
            }
155

    
156
            public Object action(Connection conn) throws DataException {
157
                Statement st;
158
                try {
159
                    st = conn.createStatement();
160
                } catch (SQLException e) {
161
                    throw new JDBCSQLException(e);
162
                }
163

    
164
                String sqlDrop = "Drop table "
165
                        + dsParams.tableID();
166

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

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

    
190
    @Override
191
    public DataStoreParameters getOpenParameters() throws DataException {
192
        JDBCServerExplorerParameters parameters = getJDBCParameters();
193
        JDBCStoreParameters params = new JDBCStoreParameters();
194
        params.setHost(parameters.getHost());
195
        params.setPort(parameters.getPort());
196
        params.setDBName(parameters.getDBName());
197
        params.setUser(parameters.getUser());
198
        params.setPassword(parameters.getPassword());
199
        params.setCatalog(parameters.getCatalog());
200
        params.setSchema(parameters.getSchema());
201
        params.setJDBCDriverClassName(parameters.getJDBCDriverClassName());
202
        params.setUrl(parameters.getUrl());
203
        return params;
204
    }
205

    
206
    @Override
207
    public NewDataStoreParameters getAddParameters() throws DataException {
208
        JDBCServerExplorerParameters parameters = getJDBCParameters();
209
        JDBCNewStoreParameters params = new JDBCNewStoreParameters();
210
        params.setHost(parameters.getHost());
211
        params.setPort(parameters.getPort());
212
        params.setDBName(parameters.getDBName());
213
        params.setUser(parameters.getUser());
214
        params.setPassword(parameters.getPassword());
215
        params.setCatalog(parameters.getCatalog());
216
        params.setSchema(parameters.getSchema());
217
        params.setJDBCDriverClassName(parameters.getJDBCDriverClassName());
218
        params.setUrl(parameters.getUrl());
219

    
220
        params.setDefaultFeatureType(this.getServerExplorerProviderServices()
221
                .createNewFeatureType());
222

    
223
        return params;
224
    }
225

    
226
    public void closeDone() throws DataException {
227
        // Nothing to do
228
    }
229

    
230
    public void opendDone() throws DataException {
231
        // Nothin to do
232

    
233
    }
234

    
235
    @Override
236
    public DataStore open(DataStoreParameters dsp) throws DataException {
237
        checkIsMine(dsp);
238
        DataManager dataMan = DALLocator.getDataManager();
239
        DataStore store;
240
        try {
241
            store = dataMan.openStore(dsp.getDataStoreName(), dsp);
242
        } catch (ValidateDataParametersException e) {
243
            throw new InitializeException(e);
244
        }
245

    
246
        return store;
247
    }
248

    
249
    protected void checkIsMine(DataStoreParameters dsp) {
250
        if (!(dsp instanceof JDBCConnectionParameters)) {
251
            // FIXME Exception ???
252
            throw new IllegalArgumentException(
253
                    "not instance of FilesystemStoreParameters");
254
        }
255

    
256
                // try {
257
        // dsp.validate();
258
        // } catch (ValidateDataParametersException e) {
259
        // throw new IllegalArgumentException("check parameters", e);
260
        // }
261
        JDBCServerExplorerParameters parameters = getJDBCParameters();
262

    
263
        JDBCConnectionParameters pgp = (JDBCConnectionParameters) dsp;
264
        if (!compare(pgp.getHost(), parameters.getHost())) {
265
            throw new IllegalArgumentException("wrong explorer: Host (mine: "
266
                    + parameters.getHost() + " other:" + pgp.getHost() + ")");
267
        }
268
        if (!compare(pgp.getPort(), parameters.getPort())) {
269
            throw new IllegalArgumentException("wrong explorer: Port (mine: "
270
                    + parameters.getPort() + " other:" + pgp.getPort() + ")");
271
        }
272
        if (!compare(pgp.getDBName(), parameters.getDBName())) {
273
            throw new IllegalArgumentException("wrong explorer: DBName (mine: "
274
                    + parameters.getDBName() + " other:" + pgp.getDBName()
275
                    + ")");
276
        }
277
        if (parameters.getCatalog() != null && !parameters.getCatalog().trim().equals("")) {
278
            // implicit catalog
279
            if (!compare(pgp.getCatalog(), parameters.getCatalog())) {
280
                throw new IllegalArgumentException(
281
                        "wrong explorer: Catalog (mine: "
282
                        + parameters.getCatalog() + " other:"
283
                        + pgp.getCatalog() + ")");
284
            }
285
        }
286
        if (parameters.getSchema() != null && !parameters.getSchema().trim().equals("")) {
287
            // implicit schema
288
            if (!compare(pgp.getSchema(), parameters.getSchema())) {
289
                throw new IllegalArgumentException(
290
                        "wrong explorer: Schema (mine: "
291
                        + parameters.getSchema() + " other:"
292
                        + pgp.getSchema() + ")");
293
            }
294
        }
295
    }
296

    
297
    protected boolean compare(Object str1, Object str2) {
298
        if (str1 == str2) {
299
            return true;
300
        }
301
        if (str1 == null) {
302
            return false;
303
        }
304
        return str1.equals(str2);
305
    }
306

    
307
    protected JDBCStoreParameters createStoreParams()
308
            throws InitializeException, ProviderNotRegisteredException {
309
        DataManagerProviderServices manager = this.getManager();
310
        JDBCServerExplorerParameters parameters = getJDBCParameters();
311
        JDBCStoreParameters orgParams = (JDBCStoreParameters) manager
312
                .createStoreParameters(getStoreName());
313
        orgParams.setHost(parameters.getHost());
314
        orgParams.setPort(parameters.getPort());
315
        orgParams.setDBName(parameters.getDBName());
316
        orgParams.setUser(parameters.getUser());
317
        orgParams.setPassword(parameters.getPassword());
318
        orgParams.setCatalog(parameters.getCatalog());
319
        orgParams.setJDBCDriverClassName(parameters.getJDBCDriverClassName());
320
        orgParams.setSchema(parameters.getSchema());
321
        orgParams.setUrl(parameters.getUrl());
322
        return orgParams;
323
    }
324

    
325
    public List list(final int mode, final boolean showInformationDBTables)
326
            throws DataException {
327

    
328
        final JDBCStoreParameters orgParams = createStoreParams();
329

    
330
        ConnectionAction action = new ConnectionAction() {
331

    
332
            public Object action(Connection conn) throws DataException {
333

    
334
                String[] tableTypes = null;
335
                if (!showInformationDBTables) {
336
                    tableTypes = new String[]{"TABLE", "VIEW"};
337
                }
338

    
339
                ResultSet result = null;
340
                try {
341
                    DatabaseMetaData metadata = conn.getMetaData();
342
                    result = metadata.getTables(null, null, null,
343
                            tableTypes);
344
                    List<JDBCStoreParameters> paramList = new ArrayList<JDBCStoreParameters>();
345
                    while (result.next()) {
346
                        JDBCStoreParameters params = (JDBCStoreParameters) orgParams
347
                                .getCopy();
348
                        params.setCatalog(result
349
                                .getString(METADATA_COLUMN_TABLE_CATALOG));
350
                        params.setSchema(result
351
                                .getString(METADATA_COLUMN_TABLE_SCHEMA));
352
                        params.setTable(result
353
                                .getString(METADATA_COLUMN_TABLE_NAME));
354
                        paramList.add(params);
355
                    }
356

    
357
                    return paramList;
358
                } catch (SQLException e) {
359
                    throw new JDBCSQLException(e);
360
                } finally {
361
                    if (result != null) {
362
                        try {
363
                            result.close();
364
                        } catch (Exception e) {
365
                            LOG.error("Error closing DatabaseMetadata "
366
                                    + "getTables() Resultset", e);
367
                        }
368
                    }
369
                }
370
            }
371

    
372
        };
373

    
374
        try {
375
            return (List) helper.doConnectionAction(action);
376
        } catch(JDBCSQLException e) {
377
            throw e;
378
        } catch (Exception e) {
379
            throw new ReadException(this.getProviderName(),e);
380
        }
381
    }
382

    
383
    public void open() throws OpenException {
384
        helper.open();
385
    }
386

    
387
    public void close() throws CloseException {
388
        helper.close();
389
    }
390

    
391
    @Override
392
    protected void doDispose() throws BaseException {
393
        helper.dispose();
394
        helper = null;
395
    }
396

    
397
    @Override
398
    public String getProviderName() {
399
        return NAME;
400
    }
401

    
402
    @Override
403
    public String getStoreName() {
404
        return JDBCStoreProvider.NAME;
405
    }
406

    
407
    @Override
408
    public boolean canAdd() {
409
        if (this.canAdd == null) {
410
            ConnectionAction action = new ConnectionAction() {
411

    
412
                public Object action(Connection conn) throws DataException {
413
                    try {
414
                        DatabaseMetaData metadata = conn.getMetaData();
415
                        if (metadata.isReadOnly()) {
416
                            return Boolean.FALSE;
417
                        }
418
                        return Boolean.TRUE;
419
                    } catch (SQLException e) {
420
                        throw new JDBCSQLException(e);
421
                    }
422
                }
423

    
424
            };
425

    
426
            try {
427
                this.canAdd = (Boolean) helper.doConnectionAction(action);
428
            } catch (Exception e) {
429
                // FIXME Exception
430
                throw new RuntimeException(e);
431
            }
432
        }
433
        return this.canAdd.booleanValue();
434
    }
435

    
436
    @Override
437
    public FeatureType getFeatureType(DataStoreParameters dsp)
438
            throws DataException {
439
        checkIsMine(dsp);
440

    
441
        // TODO: checks geometry columns and driver geometry supports
442
        EditableFeatureType edType = this.getServerExplorerProviderServices()
443
                .createNewFeatureType();
444
        helper.loadFeatureType(edType, (JDBCStoreParameters) dsp);
445

    
446
        return edType;
447

    
448
    }
449

    
450
    @Override
451
    public boolean add(String providerName, NewDataStoreParameters ndsp, boolean overwrite)
452
            throws DataException {
453

    
454
        /**
455
         * CREATE [ [ GLOBAL | LOCAL ] { TEMPORARY | TEMP } ] TABLE table_name (
456
         * { column_name data_type [ DEFAULT default_expr ] [ column_constraint
457
         * [ ... ] ] | table_constraint | LIKE parent_table [ { INCLUDING |
458
         * EXCLUDING } DEFAULTS ] } [, ... ] ) [ INHERITS ( parent_table [, ...
459
         * ] ) ] [ WITH OIDS | WITHOUT OIDS ] [ ON COMMIT { PRESERVE ROWS |
460
         * DELETE ROWS | DROP } ]
461
         *
462
         * where column_constraint is:
463
         *
464
         * [ CONSTRAINT constraint_name ] { NOT NULL | NULL | UNIQUE | PRIMARY
465
         * KEY | CHECK (expression) | REFERENCES reftable [ ( refcolumn ) ] [
466
         * MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON
467
         * UPDATE action ] } [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY
468
         * DEFERRED | INITIALLY IMMEDIATE ]
469
         *
470
         * and table_constraint is:
471
         *
472
         * [ CONSTRAINT constraint_name ] { UNIQUE ( column_name [, ... ] ) |
473
         * PRIMARY KEY ( column_name [, ... ] ) | CHECK ( expression ) | FOREIGN
474
         * KEY ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ...
475
         * ] ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE
476
         * action ] [ ON UPDATE action ] } [ DEFERRABLE | NOT DEFERRABLE ] [
477
         * INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
478
         */
479
        if (!(ndsp instanceof JDBCNewStoreParameters)) {
480
            // FIXME exception
481
            throw new IllegalArgumentException();
482
        }
483
        checkIsMine(ndsp);
484

    
485
        JDBCNewStoreParameters jdbcnsp = (JDBCNewStoreParameters) ndsp;
486

    
487
        StringBuilder sql = new StringBuilder();
488

    
489
        if (!jdbcnsp.isValid()) {
490
            // TODO Exception
491
            throw new InitializeException(this.getProviderName(), new Exception(
492
                    "Parameters not valid"));
493
        }
494
        try {
495
            jdbcnsp.validate();
496
        } catch (ValidateDataParametersException e1) {
497
            throw new InitializeException(this.getProviderName(), e1);
498
        }
499

    
500
        FeatureType fType = jdbcnsp.getDefaultFeatureType();
501

    
502
        sql.append("Create table " + jdbcnsp.tableID()
503
                + "(");
504
        Iterator attrs = fType.iterator();
505
        String sqlAttr;
506
        List sqlAttrs = new ArrayList();
507

    
508
        while (attrs.hasNext()) {
509
            sqlAttr = helper
510
                    .getSqlFieldDescription((FeatureAttributeDescriptor) attrs
511
                            .next());
512
            if (sqlAttr != null) {
513
                sqlAttrs.add(sqlAttr);
514
            }
515
        }
516

    
517
        helper.stringJoin(sqlAttrs, ", ", sql);
518

    
519
        sql.append(")");
520

    
521
        final String sqlCreate = sql.toString();
522
        final List sqlAdditional = helper.getAdditionalSqlToCreate(ndsp, fType);
523

    
524
        List permissions = this.getHelper().createGrantStatements((JDBCNewStoreParameters) ndsp);
525
        if (permissions != null) {
526
            sqlAdditional.addAll(permissions);
527
        }
528

    
529
        if (((JDBCNewStoreParameters) ndsp).getPostCreatingStatement() != null) {
530
            sqlAdditional.add(((JDBCNewStoreParameters) ndsp).getPostCreatingStatement());
531
        }
532

    
533
        TransactionalAction action = new TransactionalAction() {
534

    
535
            public boolean continueTransactionAllowed() {
536
                // TODO Auto-generated method stub
537
                return false;
538
            }
539

    
540
            public Object action(Connection conn) throws DataException {
541
                Statement st = null;
542

    
543
                try {
544
                    st = conn.createStatement();
545
                } catch (SQLException e1) {
546
                    throw new JDBCSQLException(e1);
547
                }
548
                String sql = null;
549

    
550
                try {
551
                    sql = sqlCreate;
552
                    JDBCHelper.execute(st, sql);
553
                    if (sqlAdditional != null) {
554
                        Iterator iter = sqlAdditional.iterator();
555
                        while (iter.hasNext()) {
556
                            sql = (String) iter.next();
557
                            JDBCHelper.execute(st, sql);
558
                        }
559
                    }
560

    
561
                } catch (SQLException e) {
562
                    throw new JDBCExecuteSQLException(sql, e);
563
                } finally {
564
                    try {
565
                        st.close();
566
                    } catch (SQLException e) {
567
                        LOG.error("Exception clossing statement", e);
568
                    }
569
                    ;
570
                }
571

    
572
                return Boolean.TRUE;
573
            }
574

    
575
        };
576

    
577
        Boolean result = Boolean.FALSE;
578

    
579
        try {
580
            result = (Boolean) helper.doConnectionAction(action);
581
        } catch (DataException e) {
582
            throw e;
583
        } catch (Exception e) {
584
            // FIXME Exception
585
            throw new RuntimeException(e);
586
        }
587

    
588
        return result.booleanValue();
589
    }
590

    
591
    @Override
592
    public List getDataStoreProviderNames() {
593
        List x = new ArrayList(1);
594
        x.add(JDBCStoreProvider.NAME);
595
        return x;
596
    }
597

    
598
    @Override
599
    public void updateTableStatistics(String database, String schema, String table) throws JDBCExecuteSQLException {
600
    }
601

    
602
    @Override
603
    public DataStoreParameters get(String name) throws DataException {
604
        JDBCStoreParameters params = this.createStoreParams();
605
        params.setTable(name);
606
        return params;
607
    }
608

    
609
    @Override
610
    public void execute(String sql) {
611
        throw new UnsupportedOperationException("Not supported yet.");
612
    }
613
}