root / tags / v1_0_2_Build_903+3D / libraries / libFMap / src / com / iver / cit / gvsig / fmap / drivers / DefaultDBDriver.java @ 10722
History | View | Annotate | Download (30.8 KB)
1 |
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
|
---|---|
2 |
*
|
3 |
* Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
|
4 |
*
|
5 |
* This program is free software; you can redistribute it and/or
|
6 |
* modify it under the terms of the GNU General Public License
|
7 |
* as published by the Free Software Foundation; either version 2
|
8 |
* of the License, or (at your option) any later version.
|
9 |
*
|
10 |
* This program is distributed in the hope that it will be useful,
|
11 |
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
12 |
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
13 |
* GNU General Public License for more details.
|
14 |
*
|
15 |
* You should have received a copy of the GNU General Public License
|
16 |
* along with this program; if not, write to the Free Software
|
17 |
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,USA.
|
18 |
*
|
19 |
* For more information, contact:
|
20 |
*
|
21 |
* Generalitat Valenciana
|
22 |
* Conselleria d'Infraestructures i Transport
|
23 |
* Av. Blasco Ib??ez, 50
|
24 |
* 46010 VALENCIA
|
25 |
* SPAIN
|
26 |
*
|
27 |
* +34 963862235
|
28 |
* gvsig@gva.es
|
29 |
* www.gvsig.gva.es
|
30 |
*
|
31 |
* or
|
32 |
*
|
33 |
* IVER T.I. S.A
|
34 |
* Salamanca 50
|
35 |
* 46005 Valencia
|
36 |
* Spain
|
37 |
*
|
38 |
* +34 963163400
|
39 |
* dac@iver.es
|
40 |
*/
|
41 |
package com.iver.cit.gvsig.fmap.drivers; |
42 |
|
43 |
import java.awt.geom.Rectangle2D; |
44 |
import java.io.IOException; |
45 |
import java.sql.Connection; |
46 |
import java.sql.DatabaseMetaData; |
47 |
import java.sql.Driver; |
48 |
import java.sql.DriverManager; |
49 |
import java.sql.ResultSet; |
50 |
import java.sql.ResultSetMetaData; |
51 |
import java.sql.SQLException; |
52 |
import java.sql.Statement; |
53 |
import java.sql.Types; |
54 |
import java.util.ArrayList; |
55 |
import java.util.Hashtable; |
56 |
import java.util.TreeMap; |
57 |
|
58 |
import org.apache.log4j.Logger; |
59 |
|
60 |
import com.hardcode.driverManager.DriverEvent; |
61 |
import com.hardcode.driverManager.DriverEventListener; |
62 |
import com.hardcode.driverManager.IDelayedDriver; |
63 |
import com.hardcode.gdbms.engine.data.DataSourceFactory; |
64 |
import com.hardcode.gdbms.engine.data.driver.ObjectDriver; |
65 |
import com.hardcode.gdbms.engine.values.Value; |
66 |
import com.hardcode.gdbms.engine.values.ValueFactory; |
67 |
import com.iver.cit.gvsig.fmap.DriverException; |
68 |
import com.iver.cit.gvsig.fmap.DriverJdbcNotFoundExceptionType; |
69 |
import com.iver.cit.gvsig.fmap.MapContext; |
70 |
import com.iver.cit.gvsig.fmap.Messages; |
71 |
import com.iver.cit.gvsig.fmap.SqlDriveExceptionType; |
72 |
import com.iver.cit.gvsig.fmap.core.IFeature; |
73 |
import com.iver.cit.gvsig.fmap.core.IGeometry; |
74 |
import com.iver.cit.gvsig.fmap.drivers.jdbc.utils.ConnectionWithParams; |
75 |
import com.iver.cit.gvsig.fmap.drivers.jdbc.utils.SingleJDBCConnectionManager; |
76 |
import com.iver.cit.gvsig.fmap.layers.SelectableDataSource; |
77 |
import com.iver.cit.gvsig.fmap.layers.XMLException; |
78 |
import com.iver.utiles.XMLEntity; |
79 |
import com.iver.utiles.swing.JPasswordDlg; |
80 |
|
81 |
|
82 |
|
83 |
/**
|
84 |
* Clase abstracta qu
|
85 |
*/
|
86 |
public abstract class DefaultDBDriver implements VectorialJDBCDriver, ObjectDriver { |
87 |
private static Logger logger = Logger.getLogger(SelectableDataSource.class.getName()); |
88 |
protected static Hashtable poolPassw = new Hashtable(); |
89 |
|
90 |
protected Connection conn; |
91 |
// protected String tableName;
|
92 |
// protected String whereClause;
|
93 |
// protected String fields;
|
94 |
// protected String sqlOrig;
|
95 |
protected DBLayerDefinition lyrDef = null; |
96 |
protected ResultSet rs; |
97 |
protected boolean bCursorActivo = false; |
98 |
protected Statement st; |
99 |
protected int numReg=-1; |
100 |
|
101 |
protected Rectangle2D fullExtent = null; |
102 |
|
103 |
// protected String strFID_FieldName;
|
104 |
// protected String idFID_FieldName;
|
105 |
|
106 |
protected Hashtable hashRelate; |
107 |
|
108 |
|
109 |
protected ResultSetMetaData metaData = null; |
110 |
protected Rectangle2D workingArea; |
111 |
protected String driverClass; |
112 |
protected String userName; |
113 |
protected String dbUrl; |
114 |
protected String className; |
115 |
protected String catalogName; |
116 |
protected String tableName; |
117 |
protected String[] fields; |
118 |
protected String FIDfield; |
119 |
protected String geometryField; |
120 |
protected String whereClause; |
121 |
protected String strSRID; |
122 |
//private double flatness;
|
123 |
|
124 |
protected String host, port, dbName, connName; |
125 |
|
126 |
protected ArrayList driverEventListeners = new ArrayList(); |
127 |
|
128 |
|
129 |
abstract public void setData(Connection conn, DBLayerDefinition lyrDef); |
130 |
|
131 |
/**
|
132 |
* @return devuelve la Conexi?n a la base de datos, para que
|
133 |
* el usuario pueda hacer la consulta que quiera, si lo desea.
|
134 |
* Por ejemplo, esto puede ser ?til para abrir un cuadro de dialogo
|
135 |
* avanazado y lanzar peticiones del tipo "Devuelveme un buffer
|
136 |
* a las autopistas", y con el resultset que te venga, escribir
|
137 |
* un shape, o cosas as?.
|
138 |
*/
|
139 |
public Connection getConnection() |
140 |
{ |
141 |
return conn;
|
142 |
} |
143 |
public String[] getFields() |
144 |
{ |
145 |
/* StringTokenizer tokenizer = new StringTokenizer(fields, ",");
|
146 |
String[] arrayFields = new String[tokenizer.countTokens()];
|
147 |
int i=0;
|
148 |
while (tokenizer.hasMoreTokens())
|
149 |
{
|
150 |
arrayFields[i] = tokenizer.nextToken();
|
151 |
i++;
|
152 |
}
|
153 |
return arrayFields; */
|
154 |
return lyrDef.getFieldNames();
|
155 |
|
156 |
} |
157 |
/**
|
158 |
* First, the geometry field. After, the rest of fields
|
159 |
* @return
|
160 |
*/
|
161 |
public String getTotalFields() |
162 |
{ |
163 |
String strAux = getGeometryField(getLyrDef().getFieldGeometry());
|
164 |
String[] fieldNames = getLyrDef().getFieldNames(); |
165 |
for (int i=0; i< fieldNames.length; i++) |
166 |
{ |
167 |
strAux = strAux + ", " + fieldNames[i];
|
168 |
} |
169 |
return strAux;
|
170 |
} |
171 |
|
172 |
/* (non-Javadoc)
|
173 |
* @see com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver#getWhereClause()
|
174 |
*/
|
175 |
public String getWhereClause() |
176 |
{ |
177 |
return lyrDef.getWhereClause().toUpperCase();
|
178 |
} |
179 |
public String getTableName() |
180 |
{ |
181 |
return lyrDef.getTableName();
|
182 |
} |
183 |
|
184 |
|
185 |
/**
|
186 |
* @throws DriverIOException
|
187 |
* @throws DriverException
|
188 |
* @see com.iver.cit.gvsig.fmap.layers.ReadableVectorial#getShapeCount()
|
189 |
*/
|
190 |
public int getShapeCount() throws IOException { |
191 |
if (numReg == -1) |
192 |
{ |
193 |
try
|
194 |
{ |
195 |
Statement s = conn.createStatement();
|
196 |
ResultSet r = s.executeQuery("SELECT COUNT(*) AS NUMREG FROM " + lyrDef.getTableName() + " " + getCompleteWhere()); |
197 |
r.next(); |
198 |
numReg = r.getInt(1);
|
199 |
System.err.println("numReg = " + numReg); |
200 |
} |
201 |
catch (SQLException e) |
202 |
{ |
203 |
throw new IOException(e.getMessage()); |
204 |
} |
205 |
} |
206 |
|
207 |
return numReg;
|
208 |
} |
209 |
|
210 |
/**
|
211 |
* @see com.iver.cit.gvsig.fmap.layers.ReadableVectorial#getFullExtent()
|
212 |
*/
|
213 |
public Rectangle2D getFullExtent(){ |
214 |
// Por defecto recorremos todas las geometrias.
|
215 |
// Las bases de datos como PostGIS pueden y deben
|
216 |
// sobreescribir este m?todo.
|
217 |
if (fullExtent == null) |
218 |
{ |
219 |
try
|
220 |
{ |
221 |
IFeatureIterator itGeom = getFeatureIterator("SELECT " +
|
222 |
getGeometryField(getLyrDef().getFieldGeometry()) + ", " + getLyrDef().getFieldID() + " FROM " + |
223 |
getLyrDef().getTableName() + " " + getCompleteWhere());
|
224 |
IGeometry geom; |
225 |
int cont = 0; |
226 |
while (itGeom.hasNext())
|
227 |
{ |
228 |
geom = itGeom.next().getGeometry(); |
229 |
if (cont==0) |
230 |
fullExtent = geom.getBounds2D(); |
231 |
else
|
232 |
fullExtent.add(geom.getBounds2D()); |
233 |
cont++; |
234 |
} |
235 |
} |
236 |
catch (DriverException e) {
|
237 |
// TODO Auto-generated catch block
|
238 |
e.printStackTrace(); |
239 |
} |
240 |
|
241 |
} |
242 |
return fullExtent;
|
243 |
} |
244 |
|
245 |
|
246 |
/**
|
247 |
* @see com.iver.cit.gvsig.fmap.layers.ReadableVectorial#getShapeType()
|
248 |
*/
|
249 |
public int getShapeType() { |
250 |
/* IGeometry geom;
|
251 |
if (shapeType == -1)
|
252 |
{
|
253 |
shapeType = FShape.MULTI;
|
254 |
try {
|
255 |
geom = getShape(0);
|
256 |
if (geom != null)
|
257 |
shapeType = geom.getGeometryType();
|
258 |
} catch (IOException e) {
|
259 |
// e.printStackTrace();
|
260 |
}
|
261 |
}
|
262 |
return shapeType; */
|
263 |
return lyrDef.getShapeType();
|
264 |
} |
265 |
|
266 |
public int getFieldType(int idField) throws com.hardcode.gdbms.engine.data.driver.DriverException |
267 |
{ |
268 |
String str = ""; |
269 |
try {
|
270 |
int i = idField + 2; // idField viene basado en 1, y |
271 |
// adem?s nos saltamos el campo de geometry
|
272 |
str = metaData.getColumnClassName(i); |
273 |
if (metaData.getColumnType(i) == Types.VARCHAR) |
274 |
return Types.VARCHAR; |
275 |
if (metaData.getColumnType(i) == Types.FLOAT) |
276 |
return Types.FLOAT; |
277 |
if (metaData.getColumnType(i) == Types.DOUBLE) |
278 |
return Types.DOUBLE; |
279 |
if (metaData.getColumnType(i) == Types.INTEGER) |
280 |
return Types.INTEGER; |
281 |
if (metaData.getColumnType(i) == Types.SMALLINT) |
282 |
return Types.SMALLINT; |
283 |
if (metaData.getColumnType(i) == Types.TINYINT) |
284 |
return Types.TINYINT; |
285 |
if (metaData.getColumnType(i) == Types.BIGINT) |
286 |
return Types.BIGINT; |
287 |
if (metaData.getColumnType(i) == Types.BIT) |
288 |
return Types.BIT; |
289 |
if (metaData.getColumnType(i) == Types.DATE) |
290 |
return Types.DATE; |
291 |
if (metaData.getColumnType(i) == Types.DECIMAL) |
292 |
return Types.DOUBLE; |
293 |
if (metaData.getColumnType(i) == Types.NUMERIC) |
294 |
return Types.DOUBLE; |
295 |
if (metaData.getColumnType(i) == Types.DATE) |
296 |
return Types.DATE; |
297 |
if (metaData.getColumnType(i) == Types.TIME) |
298 |
return Types.TIME; |
299 |
if (metaData.getColumnType(i) == Types.TIMESTAMP) |
300 |
return Types.TIMESTAMP; |
301 |
|
302 |
} catch (SQLException e) { |
303 |
throw new com.hardcode.gdbms.engine.data.driver.DriverException(e); |
304 |
} |
305 |
return Types.OTHER; |
306 |
// throw new com.hardcode.gdbms.engine.data.driver.DriverException("Tipo no soportado: " + str);
|
307 |
} |
308 |
/**
|
309 |
* Obtiene el valor que se encuentra en la fila y columna indicada
|
310 |
* Esta es la implementaci?n por defecto. Si lo del absolute
|
311 |
* no va bien, como es el caso del PostGis, el driver lo
|
312 |
* tiene que reimplementar
|
313 |
*
|
314 |
* @param rowIndex fila
|
315 |
* @param fieldId columna
|
316 |
*
|
317 |
* @return subclase de Value con el valor del origen de datos
|
318 |
*
|
319 |
* @throws DriverException Si se produce un error accediendo al DataSource
|
320 |
*/
|
321 |
public Value getFieldValue(long rowIndex, int idField) |
322 |
throws com.hardcode.gdbms.engine.data.driver.DriverException
|
323 |
{ |
324 |
int i = (int) (rowIndex + 1); |
325 |
int fieldId = idField+2; |
326 |
try {
|
327 |
rs.absolute(i); |
328 |
if (metaData.getColumnType(fieldId) == Types.VARCHAR) |
329 |
{ |
330 |
String strAux = rs.getString(fieldId);
|
331 |
if (strAux == null) strAux = ""; |
332 |
return ValueFactory.createValue(strAux);
|
333 |
} |
334 |
if (metaData.getColumnType(fieldId) == Types.FLOAT) |
335 |
return ValueFactory.createValue(rs.getFloat(fieldId));
|
336 |
if (metaData.getColumnType(fieldId) == Types.DOUBLE) |
337 |
return ValueFactory.createValue(rs.getDouble(fieldId));
|
338 |
if (metaData.getColumnType(fieldId) == Types.INTEGER) |
339 |
return ValueFactory.createValue(rs.getInt(fieldId));
|
340 |
if (metaData.getColumnType(fieldId) == Types.BIGINT) |
341 |
return ValueFactory.createValue(rs.getLong(fieldId));
|
342 |
if (metaData.getColumnType(fieldId) == Types.BIT) |
343 |
return ValueFactory.createValue(rs.getBoolean(fieldId));
|
344 |
if (metaData.getColumnType(fieldId) == Types.DATE) |
345 |
return ValueFactory.createValue(rs.getDate(fieldId));
|
346 |
} catch (SQLException e) { |
347 |
throw new com.hardcode.gdbms.engine.data.driver.DriverException("Tipo no soportado: columna " + fieldId ); |
348 |
} |
349 |
return null; |
350 |
|
351 |
|
352 |
} |
353 |
|
354 |
/**
|
355 |
* Obtiene el n?mero de campos del DataSource
|
356 |
*
|
357 |
* @return
|
358 |
*
|
359 |
* @throws DriverException Si se produce alg?n error accediendo al
|
360 |
* DataSource
|
361 |
*/
|
362 |
public int getFieldCount() throws com.hardcode.gdbms.engine.data.driver.DriverException |
363 |
{ |
364 |
try {
|
365 |
// Suponemos que el primer campo es el de las geometries, y no lo
|
366 |
// contamos
|
367 |
return rs.getMetaData().getColumnCount()-1; |
368 |
} catch (SQLException e) { |
369 |
throw new com.hardcode.gdbms.engine.data.driver.DriverException(e); |
370 |
} |
371 |
|
372 |
} |
373 |
|
374 |
/**
|
375 |
* Devuelve el nombre del campo fieldId-?simo
|
376 |
*
|
377 |
* @param fieldId ?ndice del campo cuyo nombre se quiere obtener
|
378 |
*
|
379 |
* @return
|
380 |
* @throws com.hardcode.gdbms.engine.data.driver.DriverException
|
381 |
*
|
382 |
* @throws DriverException Si se produce alg?n error accediendo al
|
383 |
* DataSource
|
384 |
*/
|
385 |
public String getFieldName(int fieldId) throws com.hardcode.gdbms.engine.data.driver.DriverException |
386 |
{ |
387 |
try {
|
388 |
return rs.getMetaData().getColumnName(fieldId+2); |
389 |
} catch (SQLException e) { |
390 |
throw new com.hardcode.gdbms.engine.data.driver.DriverException(e); |
391 |
} |
392 |
} |
393 |
|
394 |
/**
|
395 |
* Obtiene el n?mero de registros del DataSource
|
396 |
*
|
397 |
* @return
|
398 |
*
|
399 |
* @throws DriverException Si se produce alg?n error accediendo al
|
400 |
* DataSource
|
401 |
*/
|
402 |
public long getRowCount() |
403 |
{ |
404 |
try {
|
405 |
return getShapeCount();
|
406 |
} catch (IOException e) { |
407 |
// TODO Auto-generated catch block
|
408 |
e.printStackTrace(); |
409 |
} |
410 |
return -1; |
411 |
} |
412 |
|
413 |
public void close() { |
414 |
} |
415 |
|
416 |
/**
|
417 |
* Recorre el recordset creando una tabla Hash que usaremos para
|
418 |
* relacionar el n?mero de un registro con su identificador ?nico.
|
419 |
* Debe ser llamado en el setData justo despu?s de crear el recorset
|
420 |
* principal
|
421 |
* @throws SQLException
|
422 |
*/
|
423 |
protected void doRelateID_FID() throws SQLException |
424 |
{ |
425 |
hashRelate = new Hashtable(); |
426 |
|
427 |
|
428 |
String strSQL = "SELECT " + getLyrDef().getFieldID() + " FROM " + getLyrDef().getTableName() |
429 |
+ " " + getCompleteWhere() + " ORDER BY " + getLyrDef().getFieldID(); |
430 |
Statement s = getConnection().createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); |
431 |
ResultSet r = s.executeQuery(strSQL);
|
432 |
int id=0; |
433 |
int gid;
|
434 |
int index = 0; |
435 |
while (r.next())
|
436 |
{ |
437 |
String aux = r.getString(1); |
438 |
Value val = ValueFactory.createValue(aux); |
439 |
hashRelate.put(val, new Integer(index)); |
440 |
System.out.println("ASOCIANDO CLAVE " + aux + " CON VALOR " + index); |
441 |
index++; |
442 |
} |
443 |
numReg = index; |
444 |
r.close(); |
445 |
// rs.beforeFirst();
|
446 |
|
447 |
} |
448 |
|
449 |
/* (non-Javadoc)
|
450 |
* @see com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver#getRowIndexByFID(java.lang.Object)
|
451 |
*/
|
452 |
public int getRowIndexByFID(IFeature FID) |
453 |
{ |
454 |
int resul;
|
455 |
// Object obj = FID.getAttribute(lyrDef.getIdFieldID());
|
456 |
String theId = FID.getID();
|
457 |
Value aux = ValueFactory.createValue(theId); |
458 |
// System.err.println("Mirando si existe " + aux.toString());
|
459 |
if (hashRelate.containsKey(aux))
|
460 |
{ |
461 |
Integer rowIndex = (Integer) hashRelate.get(aux); |
462 |
resul = rowIndex.intValue(); |
463 |
// System.err.println("Row asociada a " + aux.toString() + ":" + resul);
|
464 |
return resul;
|
465 |
} |
466 |
else
|
467 |
return -1; |
468 |
} |
469 |
|
470 |
/* (non-Javadoc)
|
471 |
* @see com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver#setXMLEntity(com.iver.utiles.XMLEntity)
|
472 |
*/
|
473 |
public void setXMLEntity(XMLEntity xml) throws XMLException |
474 |
{ |
475 |
|
476 |
className = xml.getStringProperty("className");
|
477 |
|
478 |
catalogName = xml.getStringProperty("catalog");
|
479 |
userName =xml.getStringProperty("username");
|
480 |
driverClass =xml.getStringProperty("driverclass");
|
481 |
tableName = xml.getStringProperty("tablename");
|
482 |
fields = xml.getStringArrayProperty("fields");
|
483 |
FIDfield = xml.getStringProperty("FID");
|
484 |
geometryField = xml.getStringProperty("THE_GEOM");
|
485 |
whereClause = xml.getStringProperty("whereclause");
|
486 |
strSRID = xml.getStringProperty("SRID");
|
487 |
|
488 |
if (xml.contains("host")) |
489 |
{ |
490 |
host = xml.getStringProperty("host");
|
491 |
port = xml.getStringProperty("port");
|
492 |
dbName = xml.getStringProperty("dbName");
|
493 |
connName = xml.getStringProperty("connName");
|
494 |
} |
495 |
else
|
496 |
{ |
497 |
// Por compatibilidad con versiones anteriores
|
498 |
dbUrl = xml.getStringProperty("dbURL");
|
499 |
extractParamsFromDbUrl(dbUrl); |
500 |
|
501 |
} |
502 |
if (xml.contains("minXworkArea")) |
503 |
{ |
504 |
double x = xml.getDoubleProperty("minXworkArea"); |
505 |
double y = xml.getDoubleProperty("minYworkArea"); |
506 |
double H = xml.getDoubleProperty("HworkArea"); |
507 |
double W = xml.getDoubleProperty("WworkArea"); |
508 |
workingArea = new Rectangle2D.Double(x,y,W,H); |
509 |
} |
510 |
|
511 |
DBLayerDefinition lyrDef = new DBLayerDefinition();
|
512 |
lyrDef.setCatalogName(catalogName); |
513 |
lyrDef.setTableName(tableName); |
514 |
lyrDef.setFieldNames(fields); |
515 |
lyrDef.setFieldID(FIDfield); |
516 |
lyrDef.setFieldGeometry(geometryField); |
517 |
lyrDef.setWhereClause(whereClause); |
518 |
// lyrDef.setClassToInstantiate(driverClass);
|
519 |
if (workingArea != null) |
520 |
lyrDef.setWorkingArea(workingArea); |
521 |
|
522 |
lyrDef.setSRID_EPSG(strSRID); |
523 |
|
524 |
setLyrDef(lyrDef); |
525 |
|
526 |
} |
527 |
|
528 |
private void extractParamsFromDbUrl(String dbUrl2) { |
529 |
//jdbc:postgres://localhost:5431/latin1
|
530 |
int iDbName = dbUrl2.lastIndexOf('/'); |
531 |
dbName = dbUrl2.substring(iDbName+1);
|
532 |
int iLast2points = dbUrl2.lastIndexOf(':'); |
533 |
port = dbUrl2.substring(iLast2points+1, iDbName);
|
534 |
int iHost = dbUrl2.indexOf("//"); |
535 |
host = dbUrl2.substring(iHost + 2, iLast2points);
|
536 |
connName = dbUrl2; |
537 |
} |
538 |
|
539 |
public void load() throws DriverException { |
540 |
try {
|
541 |
if (driverClass != null) |
542 |
Class.forName(driverClass);
|
543 |
|
544 |
String _drvName = getName();
|
545 |
|
546 |
String keyPool = _drvName.toLowerCase() + "_" + host.toLowerCase() |
547 |
+ "_" + port + "_" + dbName.toLowerCase() |
548 |
+ "_" + userName.toLowerCase();
|
549 |
|
550 |
Connection newConn = null; |
551 |
String clave = null; |
552 |
ConnectionWithParams cwp = null;
|
553 |
|
554 |
if (poolPassw.containsKey(keyPool)) {
|
555 |
|
556 |
clave = (String) poolPassw.get(keyPool);
|
557 |
cwp = SingleJDBCConnectionManager.instance().getConnection( |
558 |
_drvName, userName, clave, connName, |
559 |
host, port, dbName, true);
|
560 |
|
561 |
} else {
|
562 |
|
563 |
cwp = SingleJDBCConnectionManager.instance().getConnection( |
564 |
_drvName, userName, null, connName,
|
565 |
host, port, dbName, false);
|
566 |
|
567 |
if (cwp.isConnected()) {
|
568 |
|
569 |
poolPassw.put(keyPool, cwp.getPw()); |
570 |
|
571 |
} else {
|
572 |
|
573 |
JPasswordDlg dlg = new JPasswordDlg();
|
574 |
String strMessage = Messages.getString("conectar_jdbc"); |
575 |
String strPassword = Messages.getString("password"); |
576 |
dlg.setMessage(strMessage |
577 |
+ " ["
|
578 |
+ _drvName + ", "
|
579 |
+ host + ", "
|
580 |
+ port + ", "
|
581 |
+ dbName + ", "
|
582 |
+ userName + "]. "
|
583 |
+ strPassword |
584 |
+ "?");
|
585 |
dlg.show(); |
586 |
clave = dlg.getPassword(); |
587 |
if (clave == null) |
588 |
return;
|
589 |
poolPassw.put(keyPool, clave); |
590 |
|
591 |
cwp.connect(clave); |
592 |
} |
593 |
} |
594 |
|
595 |
newConn = cwp.getConnection(); |
596 |
newConn.setAutoCommit(false);
|
597 |
|
598 |
DBLayerDefinition lyrDef = new DBLayerDefinition();
|
599 |
if (getLyrDef() == null) { |
600 |
lyrDef.setCatalogName(catalogName); |
601 |
lyrDef.setTableName(tableName); |
602 |
lyrDef.setFieldNames(fields); |
603 |
lyrDef.setFieldID(FIDfield); |
604 |
lyrDef.setFieldGeometry(geometryField); |
605 |
lyrDef.setWhereClause(whereClause); |
606 |
// lyrDef.setClassToInstantiate(driverClass);
|
607 |
if (workingArea != null) |
608 |
lyrDef.setWorkingArea(workingArea); |
609 |
|
610 |
lyrDef.setSRID_EPSG(strSRID); |
611 |
} else {
|
612 |
lyrDef = getLyrDef(); |
613 |
} |
614 |
|
615 |
setData(newConn, lyrDef); |
616 |
} catch (ClassNotFoundException e) { |
617 |
logger.debug(e); |
618 |
DriverJdbcNotFoundExceptionType type = |
619 |
new DriverJdbcNotFoundExceptionType();
|
620 |
type.setDriverJdbcClassName(driverClass); |
621 |
type.setLayerName(this.getTableName());
|
622 |
throw new DriverException("Driver JDBC no encontrado", e, type); |
623 |
} catch (SQLException e) { |
624 |
|
625 |
throw new DriverException(e.getMessage()); |
626 |
|
627 |
} |
628 |
} |
629 |
/* (non-Javadoc)
|
630 |
* @see com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver#getXMLEntity()
|
631 |
*/
|
632 |
public XMLEntity getXMLEntity()
|
633 |
{ |
634 |
XMLEntity xml = new XMLEntity();
|
635 |
xml.putProperty("className",this.getClass().getName()); |
636 |
try {
|
637 |
DatabaseMetaData metadata = getConnection().getMetaData();
|
638 |
xml.putProperty("catalog", getLyrDef().getCatalogName());
|
639 |
|
640 |
// TODO: NO DEBEMOS GUARDAR EL NOMBRE DE USUARIO Y CONTRASE?A
|
641 |
// AQUI. Hay que utilizar un pool de conexiones
|
642 |
// y pedir al usuario que conecte a la base de datos
|
643 |
// en la primera capa. En el resto, usar la conexi?n
|
644 |
// creada con anterioridad.
|
645 |
String userName = metadata.getUserName();
|
646 |
int aux = userName.indexOf("@"); |
647 |
if (aux != -1) |
648 |
userName = userName.substring(0,aux);
|
649 |
xml.putProperty("username", userName);
|
650 |
|
651 |
Driver drv = DriverManager.getDriver(metadata.getURL()); |
652 |
// System.out.println(drv.getClass().getName());
|
653 |
xml.putProperty("driverclass", drv.getClass().getName());
|
654 |
|
655 |
xml.putProperty("tablename", getTableName());
|
656 |
xml.putProperty("fields", lyrDef.getFieldNames());
|
657 |
xml.putProperty("FID", lyrDef.getFieldID());
|
658 |
xml.putProperty("THE_GEOM", lyrDef.getFieldGeometry());
|
659 |
xml.putProperty("whereclause", getWhereClause());
|
660 |
xml.putProperty("SRID", lyrDef.getSRID_EPSG());
|
661 |
|
662 |
ConnectionWithParams cwp = |
663 |
SingleJDBCConnectionManager.instance().findConnection(getConnection()); |
664 |
|
665 |
//FIXME:(Chema) Estos cambios los hago porque da errores as persistencia
|
666 |
if (cwp != null){ |
667 |
xml.putProperty("host", cwp.getHost());
|
668 |
xml.putProperty("port", cwp.getPort());
|
669 |
xml.putProperty("dbName", cwp.getDb());
|
670 |
xml.putProperty("connName", cwp.getName());
|
671 |
} else {
|
672 |
xml.putProperty("dbURL",metadata.getURL());
|
673 |
} |
674 |
// Chema
|
675 |
|
676 |
if (getWorkingArea() != null) |
677 |
{ |
678 |
xml.putProperty("minXworkArea", getWorkingArea().getMinX());
|
679 |
xml.putProperty("minYworkArea", getWorkingArea().getMinY());
|
680 |
xml.putProperty("HworkArea", getWorkingArea().getHeight());
|
681 |
xml.putProperty("WworkArea", getWorkingArea().getWidth());
|
682 |
} |
683 |
|
684 |
} catch (SQLException e) { |
685 |
// TODO Auto-generated catch block
|
686 |
e.printStackTrace(); |
687 |
} |
688 |
|
689 |
|
690 |
return xml;
|
691 |
|
692 |
} |
693 |
|
694 |
/**
|
695 |
* @see com.iver.cit.gvsig.fmap.drivers.VectorialJDBCDriver#setWorkingArea(java.awt.geom.Rectangle2D)
|
696 |
*/
|
697 |
public void setWorkingArea(Rectangle2D rect) { |
698 |
this.workingArea = rect;
|
699 |
} |
700 |
|
701 |
/**
|
702 |
* @see com.iver.cit.gvsig.fmap.drivers.VectorialJDBCDriver#getWorkingArea()
|
703 |
*/
|
704 |
public Rectangle2D getWorkingArea() { |
705 |
return workingArea;
|
706 |
} |
707 |
|
708 |
/* (non-Javadoc)
|
709 |
* @see com.hardcode.gdbms.engine.data.driver.GDBMSDriver#setDataSourceFactory(com.hardcode.gdbms.engine.data.DataSourceFactory)
|
710 |
*/
|
711 |
public void setDataSourceFactory(DataSourceFactory arg0) { |
712 |
// TODO Auto-generated method stub
|
713 |
|
714 |
} |
715 |
|
716 |
/**
|
717 |
* @return Returns the lyrDef.
|
718 |
*/
|
719 |
public DBLayerDefinition getLyrDef() {
|
720 |
return lyrDef;
|
721 |
} |
722 |
|
723 |
/**
|
724 |
* @param lyrDef The lyrDef to set.
|
725 |
*/
|
726 |
public void setLyrDef(DBLayerDefinition lyrDef) { |
727 |
this.lyrDef = lyrDef;
|
728 |
} |
729 |
|
730 |
abstract public String getSqlTotal(); |
731 |
|
732 |
/**
|
733 |
* @return Returns the completeWhere. WITHOUT order by clause!!
|
734 |
*/
|
735 |
abstract public String getCompleteWhere(); |
736 |
|
737 |
/* (non-Javadoc)
|
738 |
* @see com.iver.cit.gvsig.fmap.drivers.VectorialDriver#reLoad()
|
739 |
*/
|
740 |
public void reload() throws IOException |
741 |
{ |
742 |
try {
|
743 |
if ((conn == null) || (conn.isClosed())) |
744 |
{ |
745 |
this.load();
|
746 |
} |
747 |
|
748 |
conn.commit(); |
749 |
|
750 |
setData(conn, lyrDef); |
751 |
} catch (SQLException e) { |
752 |
throw new IOException(e.getMessage()); |
753 |
} catch (DriverException e) {
|
754 |
throw new IOException(e.getMessage()); |
755 |
} |
756 |
|
757 |
} |
758 |
|
759 |
public int getFieldWidth(int fieldId) |
760 |
{ |
761 |
int i = -1; |
762 |
try {
|
763 |
int aux = fieldId + 2; // idField viene basado en 1, y |
764 |
i = rs.getMetaData().getColumnDisplaySize(aux); |
765 |
} catch (SQLException e) { |
766 |
e.printStackTrace(); |
767 |
} |
768 |
// SUN define que getColumnDisplaySize devuelve numeros negativos cuando el campo es de tipo Text o Vartext
|
769 |
// sin ancho. Nosotros vamos a devolver 255 para que fucione, por lo menos al exportar a DBF.
|
770 |
// Nota: Si se truncan cadenas, este es el sitio que lo provoca.
|
771 |
if (i <0) i=255; |
772 |
return i;
|
773 |
} |
774 |
|
775 |
// public void setFlatness(double flatness) {
|
776 |
// this.flatness = flatness;
|
777 |
// }
|
778 |
|
779 |
// -----------------------------------------------------------
|
780 |
// ---- EXT JDBC NUEVA ---
|
781 |
// -----------------------------------------------------------
|
782 |
|
783 |
/**
|
784 |
* Gets the drivers connection string given its parameters (this can be different for
|
785 |
* different driver, so it should be overwritten in that case.)
|
786 |
*/
|
787 |
public String getConnectionString( |
788 |
String host,
|
789 |
String port,
|
790 |
String dbname,
|
791 |
String user,
|
792 |
String pw) {
|
793 |
|
794 |
String resp = getConnectionStringBeginning() + "//" + host.toLowerCase(); |
795 |
|
796 |
if (dbname.trim().length() > 0) { |
797 |
resp += ":" + port;
|
798 |
} else {
|
799 |
resp += ":" + getDefaultPort();
|
800 |
} |
801 |
|
802 |
resp += "/" + dbname.toLowerCase();
|
803 |
return resp;
|
804 |
} |
805 |
|
806 |
/**
|
807 |
* Gets available table names. Should be overwritten by subclasses if its
|
808 |
* not compatible or if it can be refined
|
809 |
*
|
810 |
* @param conn connection object
|
811 |
* @param catalog catalog name
|
812 |
* @return array of strings with available table names
|
813 |
* @throws SQLException
|
814 |
*/
|
815 |
public String[] getTableNames(Connection conn, String catalog) throws SQLException { |
816 |
|
817 |
DatabaseMetaData dbmd = conn.getMetaData();
|
818 |
String[] types = {"TABLE", "VIEW"}; |
819 |
ResultSet rs = dbmd.getTables(catalog, null, null, types); |
820 |
TreeMap ret = new TreeMap(); |
821 |
while (rs.next()){
|
822 |
ret.put(rs.getString("TABLE_NAME"), rs.getString("TABLE_NAME")); |
823 |
} |
824 |
rs.close(); |
825 |
return (String[]) ret.keySet().toArray(new String[0]); |
826 |
} |
827 |
|
828 |
|
829 |
/**
|
830 |
* Gets all field names of a given table
|
831 |
* @param conn connection object
|
832 |
* @param table_name table name
|
833 |
* @return all field names of the given table
|
834 |
* @throws SQLException
|
835 |
*/
|
836 |
public String[] getAllFields(Connection conn, String table_name) throws SQLException { |
837 |
|
838 |
Statement st = conn.createStatement();
|
839 |
ResultSet rs = st.executeQuery("select * from " + table_name + " LIMIT 1"); |
840 |
ResultSetMetaData rsmd = rs.getMetaData();
|
841 |
String[] ret = new String[rsmd.getColumnCount()]; |
842 |
|
843 |
for (int i = 0; i < ret.length; i++) { |
844 |
ret[i] = rsmd.getColumnName(i+1);
|
845 |
} |
846 |
rs.close(); st.close(); |
847 |
return ret;
|
848 |
} |
849 |
|
850 |
/**
|
851 |
* Gets all field type names of a given table
|
852 |
* @param conn connection object
|
853 |
* @param table_name table name
|
854 |
* @return all field type names of the given table
|
855 |
* @throws SQLException
|
856 |
*/
|
857 |
public String[] getAllFieldTypeNames(Connection conn, String table_name) throws SQLException { |
858 |
|
859 |
Statement st = conn.createStatement();
|
860 |
ResultSet rs = st.executeQuery("select * from " + table_name + " LIMIT 1"); |
861 |
ResultSetMetaData rsmd = rs.getMetaData();
|
862 |
String[] ret = new String[rsmd.getColumnCount()]; |
863 |
|
864 |
for (int i = 0; i < ret.length; i++) { |
865 |
ret[i] = rsmd.getColumnTypeName(i+1);
|
866 |
} |
867 |
rs.close(); st.close(); |
868 |
return ret;
|
869 |
} |
870 |
|
871 |
/**
|
872 |
* Gets the table's possible id fields. By default, all fields can be id.
|
873 |
* It should be overwritten by subclasses.
|
874 |
*
|
875 |
* @param conn conenction object
|
876 |
* @param table_name table name
|
877 |
* @return the table's possible id fields
|
878 |
* @throws SQLException
|
879 |
*/
|
880 |
public String[] getIdFieldsCandidates(Connection conn, String table_name) throws SQLException { |
881 |
return getAllFields(conn, table_name);
|
882 |
} |
883 |
|
884 |
/**
|
885 |
* Gets the table's possible geometry fields. By default, all fields can be geometry
|
886 |
* fields. It should be overwritten by subclasses.
|
887 |
*
|
888 |
* @param conn conenction object
|
889 |
* @param table_name table name
|
890 |
* @return the table's possible geometry fields
|
891 |
* @throws SQLException
|
892 |
*/
|
893 |
public String[] getGeometryFieldsCandidates(Connection conn, String table_name) throws SQLException { |
894 |
return getAllFields(conn, table_name);
|
895 |
} |
896 |
|
897 |
/**
|
898 |
* Tells if it's an empty table (with no records)
|
899 |
* @param conn conenction object
|
900 |
* @param tableName rtable name
|
901 |
* @return whether it's an empty table (with no records) or not
|
902 |
*/
|
903 |
public boolean isEmptyTable(Connection conn, String tableName) { |
904 |
|
905 |
boolean res = true; |
906 |
|
907 |
try {
|
908 |
Statement st = conn.createStatement();
|
909 |
ResultSet rs = null; |
910 |
rs = st.executeQuery("select * from " + tableName + " LIMIT 1"); |
911 |
res = !rs.next(); |
912 |
rs.close(); st.close(); |
913 |
} catch (Exception ex) { |
914 |
res = true;
|
915 |
} |
916 |
return res;
|
917 |
} |
918 |
|
919 |
|
920 |
|
921 |
/**
|
922 |
* Utility method to allow the driver to do something with the geometry field.
|
923 |
* By default does nothing.
|
924 |
*
|
925 |
* @param flds user-selected fields
|
926 |
* @param geomField geometry field
|
927 |
* @return new user-selected fields
|
928 |
*/
|
929 |
public String[] manageGeometryField(String[] flds, String geomField) { |
930 |
return flds;
|
931 |
} |
932 |
|
933 |
/**
|
934 |
* Empty method called when the layer is going to be removed from the view.
|
935 |
* Subclasses can overwrite it if needed.
|
936 |
*
|
937 |
*/
|
938 |
public void remove() { |
939 |
|
940 |
} |
941 |
|
942 |
public void addDriverEventListener(DriverEventListener listener) { |
943 |
if (!driverEventListeners.contains(listener))
|
944 |
driverEventListeners.add(listener); |
945 |
|
946 |
} |
947 |
|
948 |
public void removeDriverEventListener(DriverEventListener listener) { |
949 |
driverEventListeners.remove(listener); |
950 |
|
951 |
} |
952 |
|
953 |
public void notifyDriverEndLoaded() { |
954 |
DriverEvent event = new DriverEvent(DriverEvent.DRIVER_EVENT_LOADING_END);
|
955 |
for (int i=0; i < driverEventListeners.size(); i++) |
956 |
{ |
957 |
DriverEventListener aux = (DriverEventListener) driverEventListeners.get(i); |
958 |
aux.driverNotification(event); |
959 |
} |
960 |
} |
961 |
|
962 |
} |