Revision 37896 branches/v2_0_0_prep/extensions/org.gvsig.oracle/src/org/gvsig/fmap/dal/store/oracle/OracleServerExplorer.java

View differences:

OracleServerExplorer.java
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
	
383
	public void addWithEnvelopeAndDims(NewFeatureStoreParameters params, boolean b,
384
			Rectangle2D envelope, int thedims) throws DataException {
385
		
386
		String sql_create = add_SqlCreate(params, b);
387
		String sql_index = add_SqlIndex(params, b);
388
		String sql_meta = add_SqlMeta(params, b, envelope, new Integer(thedims));
389
		doAdd(sql_create, sql_index, sql_meta);
390
	}
391

  
392
	private boolean doAdd(final String sql_create, final String sql_index, final String sql_meta) {
393
		
394
		TransactionalAction action = new TransactionalAction() {
395

  
396
			public boolean continueTransactionAllowed() {
397
				return false;
398
			}
399

  
400
			public Object action(Connection conn) throws DataException {
401
				Statement st = null;
402

  
403
				try {
404
					st = conn.createStatement();
405
				} catch (SQLException e1) {
406
					throw new JDBCSQLException(e1);
407
				}
408
				String sqlnew = null;
409
				String sqlspatialindex = null;
410
				String sqlmetadata = null;
411

  
412
				// new table
413
				try {
414
					sqlnew = sql_create;
415
					st.execute(sqlnew);
416

  
417
				} catch (SQLException e) {
418
					try { st.close(); } catch (SQLException se) { logger.error("Exception closing statement", se); }
419
					throw new JDBCExecuteSQLException(sqlnew, e);
420
				}
421
				// new metadata
422
				try {
423
					sqlmetadata = sql_meta;
424
					st.execute(sqlmetadata);
425
				} catch (SQLException e) {
426
					try { st.close(); } catch (SQLException se) { logger.error("Exception closing statement", se); }
427
					throw new JDBCExecuteSQLException(sqlspatialindex, e);
428
				}
429
				// new spatial index
430
				try {
431
					sqlspatialindex = sql_index;
432
					st.execute(sqlspatialindex);
433

  
434
				} catch (SQLException e) {
435
					try { st.close(); } catch (SQLException se) { logger.error("Exception closing statement", se); }
436
					throw new JDBCExecuteSQLException(sqlspatialindex, e);
437
				}
438

  
439
				return Boolean.TRUE;
440
			}
441

  
442
		};
443

  
444
		Boolean result = Boolean.FALSE;
445

  
446
		try {
447
			result = (Boolean) helper.doConnectionAction(action);
448
		} catch (Exception e) {
449
			throw new RuntimeException(e);
450
		}
451

  
452
		return result.booleanValue();
453
	}
454

  
455
	private String add_SqlMeta(NewFeatureStoreParameters params, boolean b,
456
			Rectangle2D bbox, Integer thedims) {
457

  
458
		// SQL CREATE TABLE METADATA
459
		Rectangle2D _bbox = bbox;
460
		if (_bbox == null) {
461
			logger.warn("Envelope not found in parameters: set (0,0) - (1,1)");
462
			_bbox = OracleUtils.DEFAULT_BBOX;
463
		}
464
		
465
		int _dims = 2;
466
		if (thedims == null) {
467
			logger.warn("Dimensions not found in parameters: assumed 2");
468
		} else {
469
			_dims = thedims.intValue();
470
		}
471

  
472
		String sqlmeta = ((OracleHelper) helper).getSqlUpdateMetadata(
473
				(OracleStoreParameters) params, null, _bbox, _dims, true);
474
		// TODO Auto-generated method stub
475
		return sqlmeta;
476
	}
477

  
478
	private String add_SqlIndex(NewFeatureStoreParameters params, boolean b) {
479
		
480
		// SQL CREATE SPATIAL INDEX
481
		String sqlindex = "CREATE INDEX "
482
				+ OracleUtils.getDerivedName(((JDBCStoreParameters) params)
483
						.tableID(), "SX") + " ON "
484
				+ ((JDBCStoreParameters) params).tableID() + " (\""
485
				+ OracleValues.DEFAULT_GEO_FIELD
486
				+ "\") INDEXTYPE IS \"MDSYS\".\"SPATIAL_INDEX\" ";
487
		return sqlindex;
488
	}
489

  
490
	private String add_SqlCreate(NewFeatureStoreParameters nfdsp, boolean b) throws DataException {
491

  
492
		// SQL CREATE NEW TABLE
493
		StringBuilder sqlnewtable = new StringBuilder();
494

  
495
		FeatureType fType = nfdsp.getDefaultFeatureType();
496

  
497
		sqlnewtable.append("CREATE TABLE "
498
				+ ((JDBCStoreParameters) nfdsp).tableID() + "(");
499
		Iterator<FeatureAttributeDescriptor> attrs = fType.iterator();
500
		String sqlAttr;
501
		List<String> sqlAttrs = new ArrayList<String>();
502

  
503
		while (attrs.hasNext()) {
504
			sqlAttr = helper
505
					.getSqlFieldDescription((FeatureAttributeDescriptor) attrs
506
							.next());
507
			if (sqlAttr != null) {
508
				sqlAttrs.add(sqlAttr);
509
			}
510
		}
511

  
512
		helper.stringJoin(sqlAttrs, ", ", sqlnewtable);
513

  
514
		String pk = "CONSTRAINT "
515
				+ OracleUtils.getDerivedName(((JDBCStoreParameters) nfdsp)
516
						.tableID(), "PK") + " PRIMARY KEY (\""
517
				+ OracleValues.DEFAULT_ID_FIELD_CASE_SENSITIVE + "\") ENABLE";
518

  
519
		sqlnewtable.append(", ");
520
		sqlnewtable.append(pk);
521

  
522
		sqlnewtable.append(")");
523
		return sqlnewtable.toString();		
524

  
525
	}
526

  
527
	/**
528
	 * create new table
529
	 * 
530
	 * @params ndsp
531
	 * @params overwrite
532
	 * @return
533
	 */
534
	public boolean add(NewDataStoreParameters ndsp, boolean overwrite)
535
			throws DataException {
536

  
537
		if (!(ndsp instanceof NewFeatureStoreParameters)) {
538
			throw new IllegalArgumentException("Expected: NewFeatureStoreParameters");
539
		}
540
		
541
		checkIsMine(ndsp);
542
		NewFeatureStoreParameters nfdsp = (NewFeatureStoreParameters) ndsp;
543

  
544
		if (!nfdsp.isValid()) {
545
			throw new InitializeException(this.getName(), new Exception(
546
					"Parameters not valid"));
547
		}
548
		try {
549
			nfdsp.validate();
550
		} catch (ValidateDataParametersException e1) {
551
			throw new InitializeException(this.getName(), e1);
552
		}
553

  
554
		String sql_create = add_SqlCreate(nfdsp, overwrite);
555
		String sql_index = add_SqlIndex(nfdsp, overwrite);
556
		String sql_meta = add_SqlMeta(nfdsp, overwrite, null, null);
557
		return doAdd(sql_create, sql_index, sql_meta);
558
	}
559

  
560
	/**
561
	 * create helper
562
	 */
563
	protected JDBCHelper createHelper() throws InitializeException {
564
		return new OracleHelper(this, this.getOracleServerExplorerParameters());
565
	}
566

  
567
	/**
568
	 * Get store name
569
	 * 
570
	 * @return
571
	 */
572
	protected String getStoreName() {
573
		return OracleStoreProvider.NAME;
574
	}
575

  
576
	/**
577
	 * get Oracle helper
578
	 * 
579
	 * @return
580
	 */
581
	protected OracleHelper getOracleHelper() {
582
		return (OracleHelper) getHelper();
583
	}
584

  
585
	/**
586
	 * Get list sql sentences for list available tables
587
	 * 
588
	 * @param mode
589
	 * @param showInformationDBtables
590
	 * @return
591
	 */
592
	protected List<String> getSQLForList(int mode,
593
			boolean showInformationDBTables) {
594
		List<String> list = new ArrayList<String>(1);
595
		list.add("SELECT TABLE_NAME FROM USER_SDO_GEOM_METADATA");
596

  
597
		return list;
598

  
599
	}
600

  
601
	/**
602
	 * check oracle data store parameters, validate SSL and type driver (THIN or
603
	 * OCI)
604
	 * 
605
	 * @param dsp
606
	 */
607
	protected void checkIsMine(DataStoreParameters dsp) {
608
		if (!(dsp instanceof OracleStoreParameters)) {
609
			throw new IllegalArgumentException(
610
					"not instance of OracleStoreParameters");
611
		}
612
		super.checkIsMine(dsp);
613

  
614
		OracleStoreParameters orap = (OracleStoreParameters) dsp;
615
		if (orap.getUseSSL().booleanValue() != this.getOracleServerExplorerParameters()
616
				.getUseSSL()) {
617
			throw new IllegalArgumentException("worng explorer: SSL");
618
		}
619
		if (orap.getOraDriverType().compareToIgnoreCase(
620
				this.getOracleServerExplorerParameters().getOraDriverType()) != 0) {
621
			throw new IllegalArgumentException(
622
					"worng explorer: Oracle type driver: THIN or OCI");
623
		}
624
	}
625

  
626
	/**
627
	 * Create store parameters
628
	 */
629
	protected JDBCStoreParameters createStoreParams()
630
			throws InitializeException, ProviderNotRegisteredException {
631
		OracleStoreParameters params = (OracleStoreParameters) super.createStoreParams();
632
		// add SSL and type driver (THIN or OCI)
633
		params.setSchema(params.getUser().toUpperCase());
634
		params.setUseSSL(this.getOracleServerExplorerParameters().getUseSSL());
635
		params.setOraDriverType(this.getOracleServerExplorerParameters()
636
				.getOraDriverType());
637

  
638
		return params;
639
	}
640

  
641
	/**
642
	 * Get Oracle server explorer parameters
643
	 * 
644
	 * @return
645
	 */
646
	private OracleServerExplorerParameters getOracleServerExplorerParameters() {
647
		return (OracleServerExplorerParameters) getParameters();
648
	}
649
	
650
}
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
	
383
	public void addWithEnvelopeAndDims(NewFeatureStoreParameters params, boolean b,
384
			Rectangle2D envelope, int thedims) throws DataException {
385
		
386
		String sql_create = add_SqlCreate(params, b);
387
		String sql_index = add_SqlIndex(params, b);
388
		String sql_meta = add_SqlMeta(params, b, envelope, new Integer(thedims));
389
		doAdd(sql_create, sql_index, sql_meta);
390
	}
391

  
392
	private boolean doAdd(final String sql_create, final String sql_index, final String sql_meta) {
393
		
394
		TransactionalAction action = new TransactionalAction() {
395

  
396
			public boolean continueTransactionAllowed() {
397
				return false;
398
			}
399

  
400
			public Object action(Connection conn) throws DataException {
401
				Statement st = null;
402

  
403
				try {
404
					st = conn.createStatement();
405
				} catch (SQLException e1) {
406
					throw new JDBCSQLException(e1);
407
				}
408
				String sqlnew = null;
409
				String sqlspatialindex = null;
410
				String sqlmetadata = null;
411

  
412
				// new table
413
				try {
414
					sqlnew = sql_create;
415
					st.execute(sqlnew);
416

  
417
				} catch (SQLException e) {
418
					try { st.close(); } catch (SQLException se) { logger.error("Exception closing statement", se); }
419
					throw new JDBCExecuteSQLException(sqlnew, e);
420
				}
421
				// new metadata
422
				try {
423
					sqlmetadata = sql_meta;
424
					st.execute(sqlmetadata);
425
				} catch (SQLException e) {
426
					try { st.close(); } catch (SQLException se) { logger.error("Exception closing statement", se); }
427
					throw new JDBCExecuteSQLException(sqlspatialindex, e);
428
				}
429
				// new spatial index
430
				try {
431
					sqlspatialindex = sql_index;
432
					st.execute(sqlspatialindex);
433

  
434
				} catch (SQLException e) {
435
					try { st.close(); } catch (SQLException se) { logger.error("Exception closing statement", se); }
436
					throw new JDBCExecuteSQLException(sqlspatialindex, e);
437
				}
438

  
439
				return Boolean.TRUE;
440
			}
441

  
442
		};
443

  
444
		Boolean result = Boolean.FALSE;
445

  
446
		try {
447
			result = (Boolean) helper.doConnectionAction(action);
448
		} catch (Exception e) {
449
			throw new RuntimeException(e);
450
		}
451

  
452
		return result.booleanValue();
453
	}
454

  
455
	private String add_SqlMeta(NewFeatureStoreParameters params, boolean b,
456
			Rectangle2D bbox, Integer thedims) {
457

  
458
		// SQL CREATE TABLE METADATA
459
		Rectangle2D _bbox = bbox;
460
		if (_bbox == null) {
461
			logger.warn("Envelope not found in parameters: set (0,0) - (1,1)");
462
			_bbox = OracleUtils.DEFAULT_BBOX;
463
		}
464
		
465
		int _dims = 2;
466
		if (thedims == null) {
467
			logger.warn("Dimensions not found in parameters: assumed 2");
468
		} else {
469
			_dims = thedims.intValue();
470
		}
471

  
472
		String sqlmeta = ((OracleHelper) helper).getSqlUpdateMetadata(
473
				(OracleStoreParameters) params, null, _bbox, _dims, true);
474
		// TODO Auto-generated method stub
475
		return sqlmeta;
476
	}
477

  
478
	private String add_SqlIndex(NewFeatureStoreParameters params, boolean b) {
479
		
480
		// SQL CREATE SPATIAL INDEX
481
		String sqlindex = "CREATE INDEX "
482
				+ OracleUtils.getDerivedName(((JDBCStoreParameters) params)
483
						.tableID(), "SX") + " ON "
484
				+ ((JDBCStoreParameters) params).tableID() + " (\""
485
				+ OracleValues.DEFAULT_GEO_FIELD
486
				+ "\") INDEXTYPE IS \"MDSYS\".\"SPATIAL_INDEX\" ";
487
		return sqlindex;
488
	}
489

  
490
	private String add_SqlCreate(NewFeatureStoreParameters nfdsp, boolean b) throws DataException {
491

  
492
		// SQL CREATE NEW TABLE
493
		StringBuilder sqlnewtable = new StringBuilder();
494

  
495
		FeatureType fType = nfdsp.getDefaultFeatureType();
496

  
497
		sqlnewtable.append("CREATE TABLE "
498
				+ ((JDBCStoreParameters) nfdsp).tableID() + "(");
499
		Iterator<FeatureAttributeDescriptor> attrs = fType.iterator();
500
		String sqlAttr;
501
		List<String> sqlAttrs = new ArrayList<String>();
502

  
503
		while (attrs.hasNext()) {
504
			sqlAttr = helper
505
					.getSqlFieldDescription((FeatureAttributeDescriptor) attrs
506
							.next());
507
			if (sqlAttr != null) {
508
				sqlAttrs.add(sqlAttr);
509
			}
510
		}
511

  
512
		helper.stringJoin(sqlAttrs, ", ", sqlnewtable);
513

  
514
		String pk = "CONSTRAINT "
515
				+ OracleUtils.getDerivedName(((JDBCStoreParameters) nfdsp)
516
						.tableID(), "PK") + " PRIMARY KEY (\""
517
				+ OracleValues.DEFAULT_ID_FIELD_CASE_SENSITIVE + "\") ENABLE";
518

  
519
		sqlnewtable.append(", ");
520
		sqlnewtable.append(pk);
521

  
522
		sqlnewtable.append(")");
523
		return sqlnewtable.toString();		
524

  
525
	}
526

  
527
	/**
528
	 * create new table
529
	 * 
530
	 * @params ndsp
531
	 * @params overwrite
532
	 * @return
533
	 */
534
	public boolean add(NewDataStoreParameters ndsp, boolean overwrite)
535
			throws DataException {
536

  
537
		if (!(ndsp instanceof NewFeatureStoreParameters)) {
538
			throw new IllegalArgumentException("Expected: NewFeatureStoreParameters");
539
		}
540
		
541
		checkIsMine(ndsp);
542
		NewFeatureStoreParameters nfdsp = (NewFeatureStoreParameters) ndsp;
543

  
544
		if (!nfdsp.isValid()) {
545
			throw new InitializeException(this.getName(), new Exception(
546
					"Parameters not valid"));
547
		}
548
		try {
549
			nfdsp.validate();
550
		} catch (ValidateDataParametersException e1) {
551
			throw new InitializeException(this.getName(), e1);
552
		}
553

  
554
		String sql_create = add_SqlCreate(nfdsp, overwrite);
555
		String sql_index = add_SqlIndex(nfdsp, overwrite);
556
		String sql_meta = add_SqlMeta(nfdsp, overwrite, null, null);
557
		return doAdd(sql_create, sql_index, sql_meta);
558
	}
559

  
560
	/**
561
	 * create helper
562
	 */
563
	protected JDBCHelper createHelper() throws InitializeException {
564
		return new OracleHelper(this, this.getOracleServerExplorerParameters());
565
	}
566

  
567
	/**
568
	 * Get store name
569
	 * 
570
	 * @return
571
	 */
572
	protected String getStoreName() {
573
		return OracleStoreProvider.NAME;
574
	}
575

  
576
	/**
577
	 * get Oracle helper
578
	 * 
579
	 * @return
580
	 */
581
	protected OracleHelper getOracleHelper() {
582
		return (OracleHelper) getHelper();
583
	}
584

  
585
	/**
586
	 * Get list sql sentences for list available tables
587
	 * 
588
	 * @param mode
589
	 * @param showInformationDBtables
590
	 * @return
591
	 */
592
	protected List<String> getSQLForList(int mode,
593
			boolean showInformationDBTables) {
594
		List<String> list = new ArrayList<String>(1);
595
		list.add("SELECT TABLE_NAME FROM TABS");
596
		//USER_SDO_GEOM_METADATA means tables witg geometry
597
		//list.add("SELECT TABLE_NAME FROM USER_SDO_GEOM_METADATA");
598

  
599
		return list;
600

  
601
	}
602

  
603
	/**
604
	 * check oracle data store parameters, validate SSL and type driver (THIN or
605
	 * OCI)
606
	 * 
607
	 * @param dsp
608
	 */
609
	protected void checkIsMine(DataStoreParameters dsp) {
610
		if (!(dsp instanceof OracleStoreParameters)) {
611
			throw new IllegalArgumentException(
612
					"not instance of OracleStoreParameters");
613
		}
614
		super.checkIsMine(dsp);
615

  
616
		OracleStoreParameters orap = (OracleStoreParameters) dsp;
617
		if (orap.getUseSSL().booleanValue() != this.getOracleServerExplorerParameters()
618
				.getUseSSL()) {
619
			throw new IllegalArgumentException("worng explorer: SSL");
620
		}
621
		if (orap.getOraDriverType().compareToIgnoreCase(
622
				this.getOracleServerExplorerParameters().getOraDriverType()) != 0) {
623
			throw new IllegalArgumentException(
624
					"worng explorer: Oracle type driver: THIN or OCI");
625
		}
626
	}
627

  
628
	/**
629
	 * Create store parameters
630
	 */
631
	protected JDBCStoreParameters createStoreParams()
632
			throws InitializeException, ProviderNotRegisteredException {
633
		OracleStoreParameters params = (OracleStoreParameters) super.createStoreParams();
634
		// add SSL and type driver (THIN or OCI)
635
		params.setSchema(params.getUser().toUpperCase());
636
		params.setUseSSL(this.getOracleServerExplorerParameters().getUseSSL());
637
		params.setOraDriverType(this.getOracleServerExplorerParameters()
638
				.getOraDriverType());
639

  
640
		return params;
641
	}
642

  
643
	/**
644
	 * Get Oracle server explorer parameters
645
	 * 
646
	 * @return
647
	 */
648
	private OracleServerExplorerParameters getOracleServerExplorerParameters() {
649
		return (OracleServerExplorerParameters) getParameters();
650
	}
651
	
652
}

Also available in: Unified diff