root / tags / v1_0_2_Build_899 / libraries / libFMap / src / com / iver / cit / gvsig / fmap / drivers / DefaultDBDriver.java @ 10517
History | View | Annotate | Download (30.5 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 |
Class.forName(driverClass);
|
542 |
|
543 |
String _drvName = getName();
|
544 |
|
545 |
String keyPool = _drvName.toLowerCase() + "_" + host.toLowerCase() |
546 |
+ "_" + port + "_" + dbName.toLowerCase() |
547 |
+ "_" + userName.toLowerCase();
|
548 |
|
549 |
Connection newConn = null; |
550 |
String clave = null; |
551 |
ConnectionWithParams cwp = null;
|
552 |
|
553 |
if (poolPassw.containsKey(keyPool)) {
|
554 |
|
555 |
clave = (String) poolPassw.get(keyPool);
|
556 |
cwp = SingleJDBCConnectionManager.instance().getConnection( |
557 |
_drvName, userName, clave, connName, |
558 |
host, port, dbName, true);
|
559 |
|
560 |
} else {
|
561 |
|
562 |
cwp = SingleJDBCConnectionManager.instance().getConnection( |
563 |
_drvName, userName, null, connName,
|
564 |
host, port, dbName, false);
|
565 |
|
566 |
if (cwp.isConnected()) {
|
567 |
|
568 |
poolPassw.put(keyPool, cwp.getPw()); |
569 |
|
570 |
} else {
|
571 |
|
572 |
JPasswordDlg dlg = new JPasswordDlg();
|
573 |
String strMessage = Messages.getString("conectar_jdbc"); |
574 |
String strPassword = Messages.getString("password"); |
575 |
dlg.setMessage(strMessage |
576 |
+ " ["
|
577 |
+ _drvName + ", "
|
578 |
+ host + ", "
|
579 |
+ port + ", "
|
580 |
+ dbName + ", "
|
581 |
+ userName + "]. "
|
582 |
+ strPassword |
583 |
+ "?");
|
584 |
dlg.show(); |
585 |
clave = dlg.getPassword(); |
586 |
if (clave == null) |
587 |
return;
|
588 |
poolPassw.put(keyPool, clave); |
589 |
|
590 |
cwp.connect(clave); |
591 |
} |
592 |
} |
593 |
|
594 |
newConn = cwp.getConnection(); |
595 |
newConn.setAutoCommit(false);
|
596 |
|
597 |
DBLayerDefinition lyrDef = new DBLayerDefinition();
|
598 |
if (getLyrDef() == null) { |
599 |
lyrDef.setCatalogName(catalogName); |
600 |
lyrDef.setTableName(tableName); |
601 |
lyrDef.setFieldNames(fields); |
602 |
lyrDef.setFieldID(FIDfield); |
603 |
lyrDef.setFieldGeometry(geometryField); |
604 |
lyrDef.setWhereClause(whereClause); |
605 |
// lyrDef.setClassToInstantiate(driverClass);
|
606 |
if (workingArea != null) |
607 |
lyrDef.setWorkingArea(workingArea); |
608 |
|
609 |
lyrDef.setSRID_EPSG(strSRID); |
610 |
} else {
|
611 |
lyrDef = getLyrDef(); |
612 |
} |
613 |
|
614 |
setData(newConn, lyrDef); |
615 |
} catch (ClassNotFoundException e) { |
616 |
logger.debug(e); |
617 |
DriverJdbcNotFoundExceptionType type = |
618 |
new DriverJdbcNotFoundExceptionType();
|
619 |
type.setDriverJdbcClassName(driverClass); |
620 |
type.setLayerName(this.getTableName());
|
621 |
throw new DriverException("Driver JDBC no encontrado", e, type); |
622 |
} catch (SQLException e) { |
623 |
|
624 |
throw new DriverException(e.getMessage()); |
625 |
|
626 |
} |
627 |
} |
628 |
/* (non-Javadoc)
|
629 |
* @see com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver#getXMLEntity()
|
630 |
*/
|
631 |
public XMLEntity getXMLEntity()
|
632 |
{ |
633 |
XMLEntity xml = new XMLEntity();
|
634 |
xml.putProperty("className",this.getClass().getName()); |
635 |
try {
|
636 |
DatabaseMetaData metadata = getConnection().getMetaData();
|
637 |
xml.putProperty("catalog", getLyrDef().getCatalogName());
|
638 |
|
639 |
// TODO: NO DEBEMOS GUARDAR EL NOMBRE DE USUARIO Y CONTRASE?A
|
640 |
// AQUI. Hay que utilizar un pool de conexiones
|
641 |
// y pedir al usuario que conecte a la base de datos
|
642 |
// en la primera capa. En el resto, usar la conexi?n
|
643 |
// creada con anterioridad.
|
644 |
String userName = metadata.getUserName();
|
645 |
int aux = userName.indexOf("@"); |
646 |
if (aux != -1) |
647 |
userName = userName.substring(0,aux);
|
648 |
xml.putProperty("username", userName);
|
649 |
|
650 |
Driver drv = DriverManager.getDriver(metadata.getURL()); |
651 |
// System.out.println(drv.getClass().getName());
|
652 |
xml.putProperty("driverclass", drv.getClass().getName());
|
653 |
|
654 |
xml.putProperty("tablename", getTableName());
|
655 |
xml.putProperty("fields", lyrDef.getFieldNames());
|
656 |
xml.putProperty("FID", lyrDef.getFieldID());
|
657 |
xml.putProperty("THE_GEOM", lyrDef.getFieldGeometry());
|
658 |
xml.putProperty("whereclause", getWhereClause());
|
659 |
xml.putProperty("SRID", lyrDef.getSRID_EPSG());
|
660 |
|
661 |
ConnectionWithParams cwp = |
662 |
SingleJDBCConnectionManager.instance().findConnection(getConnection()); |
663 |
|
664 |
xml.putProperty("host", cwp.getHost());
|
665 |
xml.putProperty("port", cwp.getPort());
|
666 |
xml.putProperty("dbName", cwp.getDb());
|
667 |
xml.putProperty("connName", cwp.getName());
|
668 |
|
669 |
if (getWorkingArea() != null) |
670 |
{ |
671 |
xml.putProperty("minXworkArea", getWorkingArea().getMinX());
|
672 |
xml.putProperty("minYworkArea", getWorkingArea().getMinY());
|
673 |
xml.putProperty("HworkArea", getWorkingArea().getHeight());
|
674 |
xml.putProperty("WworkArea", getWorkingArea().getWidth());
|
675 |
} |
676 |
|
677 |
} catch (SQLException e) { |
678 |
// TODO Auto-generated catch block
|
679 |
e.printStackTrace(); |
680 |
} |
681 |
|
682 |
|
683 |
return xml;
|
684 |
|
685 |
} |
686 |
|
687 |
/**
|
688 |
* @see com.iver.cit.gvsig.fmap.drivers.VectorialJDBCDriver#setWorkingArea(java.awt.geom.Rectangle2D)
|
689 |
*/
|
690 |
public void setWorkingArea(Rectangle2D rect) { |
691 |
this.workingArea = rect;
|
692 |
} |
693 |
|
694 |
/**
|
695 |
* @see com.iver.cit.gvsig.fmap.drivers.VectorialJDBCDriver#getWorkingArea()
|
696 |
*/
|
697 |
public Rectangle2D getWorkingArea() { |
698 |
return workingArea;
|
699 |
} |
700 |
|
701 |
/* (non-Javadoc)
|
702 |
* @see com.hardcode.gdbms.engine.data.driver.GDBMSDriver#setDataSourceFactory(com.hardcode.gdbms.engine.data.DataSourceFactory)
|
703 |
*/
|
704 |
public void setDataSourceFactory(DataSourceFactory arg0) { |
705 |
// TODO Auto-generated method stub
|
706 |
|
707 |
} |
708 |
|
709 |
/**
|
710 |
* @return Returns the lyrDef.
|
711 |
*/
|
712 |
public DBLayerDefinition getLyrDef() {
|
713 |
return lyrDef;
|
714 |
} |
715 |
|
716 |
/**
|
717 |
* @param lyrDef The lyrDef to set.
|
718 |
*/
|
719 |
public void setLyrDef(DBLayerDefinition lyrDef) { |
720 |
this.lyrDef = lyrDef;
|
721 |
} |
722 |
|
723 |
abstract public String getSqlTotal(); |
724 |
|
725 |
/**
|
726 |
* @return Returns the completeWhere. WITHOUT order by clause!!
|
727 |
*/
|
728 |
abstract public String getCompleteWhere(); |
729 |
|
730 |
/* (non-Javadoc)
|
731 |
* @see com.iver.cit.gvsig.fmap.drivers.VectorialDriver#reLoad()
|
732 |
*/
|
733 |
public void reload() throws IOException |
734 |
{ |
735 |
try {
|
736 |
if (conn == null) this.load(); |
737 |
|
738 |
conn.commit(); |
739 |
|
740 |
setData(conn, lyrDef); |
741 |
} catch (SQLException e) { |
742 |
throw new IOException(e.getMessage()); |
743 |
} catch (DriverException e) {
|
744 |
throw new IOException(e.getMessage()); |
745 |
} |
746 |
|
747 |
} |
748 |
|
749 |
public int getFieldWidth(int fieldId) |
750 |
{ |
751 |
int i = -1; |
752 |
try {
|
753 |
int aux = fieldId + 2; // idField viene basado en 1, y |
754 |
i = rs.getMetaData().getColumnDisplaySize(aux); |
755 |
} catch (SQLException e) { |
756 |
e.printStackTrace(); |
757 |
} |
758 |
// SUN define que getColumnDisplaySize devuelve numeros negativos cuando el campo es de tipo Text o Vartext
|
759 |
// sin ancho. Nosotros vamos a devolver 255 para que fucione, por lo menos al exportar a DBF.
|
760 |
// Nota: Si se truncan cadenas, este es el sitio que lo provoca.
|
761 |
if (i <0) i=255; |
762 |
return i;
|
763 |
} |
764 |
|
765 |
// public void setFlatness(double flatness) {
|
766 |
// this.flatness = flatness;
|
767 |
// }
|
768 |
|
769 |
// -----------------------------------------------------------
|
770 |
// ---- EXT JDBC NUEVA ---
|
771 |
// -----------------------------------------------------------
|
772 |
|
773 |
/**
|
774 |
* Gets the drivers connection string given its parameters (this can be different for
|
775 |
* different driver, so it should be overwritten in that case.)
|
776 |
*/
|
777 |
public String getConnectionString( |
778 |
String host,
|
779 |
String port,
|
780 |
String dbname,
|
781 |
String user,
|
782 |
String pw) {
|
783 |
|
784 |
String resp = getConnectionStringBeginning() + "//" + host.toLowerCase(); |
785 |
|
786 |
if (dbname.trim().length() > 0) { |
787 |
resp += ":" + port;
|
788 |
} else {
|
789 |
resp += ":" + getDefaultPort();
|
790 |
} |
791 |
|
792 |
resp += "/" + dbname.toLowerCase();
|
793 |
return resp;
|
794 |
} |
795 |
|
796 |
/**
|
797 |
* Gets available table names. Should be overwritten by subclasses if its
|
798 |
* not compatible or if it can be refined
|
799 |
*
|
800 |
* @param conn connection object
|
801 |
* @param catalog catalog name
|
802 |
* @return array of strings with available table names
|
803 |
* @throws SQLException
|
804 |
*/
|
805 |
public String[] getTableNames(Connection conn, String catalog) throws SQLException { |
806 |
|
807 |
DatabaseMetaData dbmd = conn.getMetaData();
|
808 |
String[] types = {"TABLE", "VIEW"}; |
809 |
ResultSet rs = dbmd.getTables(catalog, null, null, types); |
810 |
TreeMap ret = new TreeMap(); |
811 |
while (rs.next()){
|
812 |
ret.put(rs.getString("TABLE_NAME"), rs.getString("TABLE_NAME")); |
813 |
} |
814 |
rs.close(); |
815 |
return (String[]) ret.keySet().toArray(new String[0]); |
816 |
} |
817 |
|
818 |
|
819 |
/**
|
820 |
* Gets all field names of a given table
|
821 |
* @param conn connection object
|
822 |
* @param table_name table name
|
823 |
* @return all field names of the given table
|
824 |
* @throws SQLException
|
825 |
*/
|
826 |
public String[] getAllFields(Connection conn, String table_name) throws SQLException { |
827 |
|
828 |
Statement st = conn.createStatement();
|
829 |
ResultSet rs = st.executeQuery("select * from " + table_name + " LIMIT 1"); |
830 |
ResultSetMetaData rsmd = rs.getMetaData();
|
831 |
String[] ret = new String[rsmd.getColumnCount()]; |
832 |
|
833 |
for (int i = 0; i < ret.length; i++) { |
834 |
ret[i] = rsmd.getColumnName(i+1);
|
835 |
} |
836 |
rs.close(); st.close(); |
837 |
return ret;
|
838 |
} |
839 |
|
840 |
/**
|
841 |
* Gets all field type names of a given table
|
842 |
* @param conn connection object
|
843 |
* @param table_name table name
|
844 |
* @return all field type names of the given table
|
845 |
* @throws SQLException
|
846 |
*/
|
847 |
public String[] getAllFieldTypeNames(Connection conn, String table_name) throws SQLException { |
848 |
|
849 |
Statement st = conn.createStatement();
|
850 |
ResultSet rs = st.executeQuery("select * from " + table_name + " LIMIT 1"); |
851 |
ResultSetMetaData rsmd = rs.getMetaData();
|
852 |
String[] ret = new String[rsmd.getColumnCount()]; |
853 |
|
854 |
for (int i = 0; i < ret.length; i++) { |
855 |
ret[i] = rsmd.getColumnTypeName(i+1);
|
856 |
} |
857 |
rs.close(); st.close(); |
858 |
return ret;
|
859 |
} |
860 |
|
861 |
/**
|
862 |
* Gets the table's possible id fields. By default, all fields can be id.
|
863 |
* It should be overwritten by subclasses.
|
864 |
*
|
865 |
* @param conn conenction object
|
866 |
* @param table_name table name
|
867 |
* @return the table's possible id fields
|
868 |
* @throws SQLException
|
869 |
*/
|
870 |
public String[] getIdFieldsCandidates(Connection conn, String table_name) throws SQLException { |
871 |
return getAllFields(conn, table_name);
|
872 |
} |
873 |
|
874 |
/**
|
875 |
* Gets the table's possible geometry fields. By default, all fields can be geometry
|
876 |
* fields. It should be overwritten by subclasses.
|
877 |
*
|
878 |
* @param conn conenction object
|
879 |
* @param table_name table name
|
880 |
* @return the table's possible geometry fields
|
881 |
* @throws SQLException
|
882 |
*/
|
883 |
public String[] getGeometryFieldsCandidates(Connection conn, String table_name) throws SQLException { |
884 |
return getAllFields(conn, table_name);
|
885 |
} |
886 |
|
887 |
/**
|
888 |
* Tells if it's an empty table (with no records)
|
889 |
* @param conn conenction object
|
890 |
* @param tableName rtable name
|
891 |
* @return whether it's an empty table (with no records) or not
|
892 |
*/
|
893 |
public boolean isEmptyTable(Connection conn, String tableName) { |
894 |
|
895 |
boolean res = true; |
896 |
|
897 |
try {
|
898 |
Statement st = conn.createStatement();
|
899 |
ResultSet rs = null; |
900 |
rs = st.executeQuery("select * from " + tableName + " LIMIT 1"); |
901 |
res = !rs.next(); |
902 |
rs.close(); st.close(); |
903 |
} catch (Exception ex) { |
904 |
res = true;
|
905 |
} |
906 |
return res;
|
907 |
} |
908 |
|
909 |
|
910 |
|
911 |
/**
|
912 |
* Utility method to allow the driver to do something with the geometry field.
|
913 |
* By default does nothing.
|
914 |
*
|
915 |
* @param flds user-selected fields
|
916 |
* @param geomField geometry field
|
917 |
* @return new user-selected fields
|
918 |
*/
|
919 |
public String[] manageGeometryField(String[] flds, String geomField) { |
920 |
return flds;
|
921 |
} |
922 |
|
923 |
/**
|
924 |
* Empty method called when the layer is going to be removed from the view.
|
925 |
* Subclasses can overwrite it if needed.
|
926 |
*
|
927 |
*/
|
928 |
public void remove() { |
929 |
|
930 |
} |
931 |
|
932 |
public void addDriverEventListener(DriverEventListener listener) { |
933 |
if (!driverEventListeners.contains(listener))
|
934 |
driverEventListeners.add(listener); |
935 |
|
936 |
} |
937 |
|
938 |
public void removeDriverEventListener(DriverEventListener listener) { |
939 |
driverEventListeners.remove(listener); |
940 |
|
941 |
} |
942 |
|
943 |
public void notifyDriverEndLoaded() { |
944 |
DriverEvent event = new DriverEvent(DriverEvent.DRIVER_EVENT_LOADING_END);
|
945 |
for (int i=0; i < driverEventListeners.size(); i++) |
946 |
{ |
947 |
DriverEventListener aux = (DriverEventListener) driverEventListeners.get(i); |
948 |
aux.driverNotification(event); |
949 |
} |
950 |
} |
951 |
|
952 |
} |