Statistics
| Revision:

root / tags / v1_1_Build_1004 / libraries / libFMap / src / com / iver / cit / gvsig / fmap / drivers / DefaultJDBCDriver.java @ 12319

History | View | Annotate | Download (31.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.db.utils.ConnectionWithParams;
75
import com.iver.cit.gvsig.fmap.drivers.db.utils.SingleVectorialDBConnectionManager;
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 DefaultJDBCDriver implements IVectorialJDBCDriver, ObjectDriver {
87
    private static Logger logger = Logger.getLogger(SelectableDataSource.class.getName());
88
    protected static Hashtable poolPassw = new Hashtable();
89

    
90
    protected IConnection 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 schema;
117
    protected String tableName;
118
    protected String[] fields;
119
    protected String FIDfield;
120
    protected String geometryField;
121
    protected String whereClause;
122
    protected String strSRID;
123
        //private double flatness;
124

    
125
    protected String host, port, dbName, connName;
126

    
127
    protected ArrayList driverEventListeners = new ArrayList();
128

    
129

    
130
    abstract public void setData(IConnection conn, DBLayerDefinition lyrDef);
131

    
132
        /**
133
         * @return devuelve la Conexi?n a la base de datos, para que
134
         * el usuario pueda hacer la consulta que quiera, si lo desea.
135
         * Por ejemplo, esto puede ser ?til para abrir un cuadro de dialogo
136
         * avanazado y lanzar peticiones del tipo "Devuelveme un buffer
137
         * a las autopistas", y con el resultset que te venga, escribir
138
         * un shape, o cosas as?.
139
         */
140
        public IConnection getConnection()
141
        {
142
            return conn;
143
        }
144
        public String[] getFields()
145
        {
146
        /* StringTokenizer tokenizer = new StringTokenizer(fields, ",");
147
        String[] arrayFields = new String[tokenizer.countTokens()];
148
        int i=0;
149
        while (tokenizer.hasMoreTokens())
150
        {
151
            arrayFields[i] = tokenizer.nextToken();
152
            i++;
153
        }
154
            return arrayFields; */
155
        return lyrDef.getFieldNames();
156

    
157
        }
158
    /**
159
     * First, the geometry field. After, the rest of fields
160
     * @return
161
     */
162
    public String getTotalFields()
163
    {
164
        String strAux = getGeometryField(getLyrDef().getFieldGeometry());
165
        String[] fieldNames = getLyrDef().getFieldNames();
166
        for (int i=0; i< fieldNames.length; i++)
167
        {
168
            strAux = strAux + ", " + fieldNames[i];
169
        }
170
        return strAux;
171
    }
172

    
173
        /* (non-Javadoc)
174
         * @see com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver#getWhereClause()
175
         */
176
        public String getWhereClause()
177
        {
178
            return lyrDef.getWhereClause().toUpperCase();
179
        }
180
        public String getTableName()
181
        {
182
            return lyrDef.getTableName();
183
        }
184

    
185

    
186
        /**
187
         * @throws DriverIOException
188
         * @throws DriverException
189
         * @see com.iver.cit.gvsig.fmap.layers.ReadableVectorial#getShapeCount()
190
         */
191
        public int getShapeCount() throws IOException {
192
                    if (numReg == -1)
193
                    {
194
                        try
195
                    {
196
                            Statement s = ((ConnectionJDBC)conn).getConnection().createStatement();
197
                            ResultSet r = s.executeQuery("SELECT COUNT(*) AS NUMREG FROM " + lyrDef.getTableName() + " " + getCompleteWhere());
198
                            r.next();
199
                            numReg = r.getInt(1);
200
                            System.err.println("numReg = " + numReg);
201
                    }
202
                        catch (SQLException e)
203
                        {
204
                            throw new IOException(e.getMessage());
205
                        }
206
                    }
207

    
208
            return numReg;
209
        }
210

    
211
    /**
212
     * @see com.iver.cit.gvsig.fmap.layers.ReadableVectorial#getFullExtent()
213
     */
214
    public Rectangle2D getFullExtent(){
215
        // Por defecto recorremos todas las geometrias.
216
        // Las bases de datos como PostGIS pueden y deben
217
        // sobreescribir este m?todo.
218
        if (fullExtent == null)
219
        {
220
            try
221
            {
222
                IFeatureIterator itGeom = getFeatureIterator("SELECT " +
223
                        getGeometryField(getLyrDef().getFieldGeometry()) + ", " + getLyrDef().getFieldID() + " FROM " +
224
                        getLyrDef().getComposedTableName() +  " " + getCompleteWhere());
225
                IGeometry geom;
226
                int cont = 0;
227
                while (itGeom.hasNext())
228
                {
229
                    geom = itGeom.next().getGeometry();
230
                    if (cont==0)
231
                        fullExtent = geom.getBounds2D();
232
                    else
233
                        fullExtent.add(geom.getBounds2D());
234
                    cont++;
235
                }
236
            }
237
            catch (DriverException e) {
238
                // TODO Auto-generated catch block
239
                e.printStackTrace();
240
            }
241

    
242
        }
243
        return fullExtent;
244
    }
245

    
246

    
247
        /**
248
         * @see com.iver.cit.gvsig.fmap.layers.ReadableVectorial#getShapeType()
249
         */
250
        public int getShapeType() {
251
        /* IGeometry geom;
252
        if (shapeType == -1)
253
        {
254
                shapeType = FShape.MULTI;
255
                try {
256
                        geom = getShape(0);
257
                        if (geom != null)
258
                                shapeType = geom.getGeometryType();
259
                } catch (IOException e) {
260
                        // e.printStackTrace();
261
                }
262
        }
263
        return shapeType; */
264
                return lyrDef.getShapeType();
265
        }
266

    
267
        public int getFieldType(int idField) throws com.hardcode.gdbms.engine.data.driver.DriverException
268
        {
269
//            String str = "";
270
            try {
271
                int i = idField + 2; // idField viene basado en 1, y
272
                                        // adem?s nos saltamos el campo de geometry
273
//                str = metaData.getColumnClassName(i);
274
            int type=metaData.getColumnType(i);
275
                if (type == Types.VARCHAR)
276
                return Types.VARCHAR;
277
                    if (type == Types.FLOAT)
278
                        return Types.FLOAT;
279
                    if (type == Types.REAL)
280
                        return Types.FLOAT;
281
                    if (type == Types.DOUBLE)
282
                        return Types.DOUBLE;
283
                    if (type == Types.INTEGER)
284
                        return Types.INTEGER;
285
                    if (type == Types.SMALLINT)
286
                        return Types.SMALLINT;
287
                    if (type == Types.TINYINT)
288
                        return Types.TINYINT;
289
                    if (type == Types.BIGINT)
290
                        return Types.BIGINT;
291
                    if (type == Types.BIT)
292
                        return Types.BIT;
293
                    if (type == Types.DATE)
294
                        return Types.DATE;
295
            if (type == Types.DECIMAL)
296
                return Types.DOUBLE;
297
            if (type == Types.NUMERIC)
298
                return Types.DOUBLE;
299
            if (type == Types.DATE)
300
                return Types.DATE;
301
            if (type == Types.TIME)
302
                return Types.TIME;
303
            if (type == Types.TIMESTAMP)
304
                return Types.TIMESTAMP;
305
            if (type == Types.NUMERIC)
306
                        return Types.DOUBLE;
307

    
308
            } catch (SQLException e) {
309
                    throw new com.hardcode.gdbms.engine.data.driver.DriverException(e);
310
            }
311
            return Types.OTHER;
312
        // throw new com.hardcode.gdbms.engine.data.driver.DriverException("Tipo no soportado: " + str);
313
        }
314
    /**
315
     * Obtiene el valor que se encuentra en la fila y columna indicada
316
     * Esta es la implementaci?n por defecto. Si lo del absolute
317
     * no va bien, como es el caso del PostGis, el driver lo
318
     * tiene que reimplementar
319
     *
320
     * @param rowIndex fila
321
     * @param fieldId columna
322
     *
323
     * @return subclase de Value con el valor del origen de datos
324
     *
325
     * @throws DriverException Si se produce un error accediendo al DataSource
326
     */
327
    public Value getFieldValue(long rowIndex, int idField)
328
        throws com.hardcode.gdbms.engine.data.driver.DriverException
329
        {
330
                int i = (int) (rowIndex + 1);
331
                int fieldId = idField+2;
332
                try {
333
                    rs.absolute(i);
334
                if (metaData.getColumnType(fieldId) == Types.VARCHAR)
335
                {
336
                    String strAux = rs.getString(fieldId);
337
                    if (strAux == null) strAux = "";
338
                    return ValueFactory.createValue(strAux);
339
                }
340
                        if (metaData.getColumnType(fieldId) == Types.FLOAT)
341
                            return ValueFactory.createValue(rs.getFloat(fieldId));
342
                        if (metaData.getColumnType(fieldId) == Types.DOUBLE)
343
                            return ValueFactory.createValue(rs.getDouble(fieldId));
344
                        if (metaData.getColumnType(fieldId) == Types.INTEGER)
345
                            return ValueFactory.createValue(rs.getInt(fieldId));
346
                        if (metaData.getColumnType(fieldId) == Types.BIGINT)
347
                            return ValueFactory.createValue(rs.getLong(fieldId));
348
                        if (metaData.getColumnType(fieldId) == Types.BIT)
349
                            return ValueFactory.createValue(rs.getBoolean(fieldId));
350
                        if (metaData.getColumnType(fieldId) == Types.DATE)
351
                            return ValueFactory.createValue(rs.getDate(fieldId));
352
                } catch (SQLException e) {
353
                throw new com.hardcode.gdbms.engine.data.driver.DriverException("Tipo no soportado: columna " + fieldId );
354
                }
355
                return null;
356

    
357

    
358
        }
359

    
360
    /**
361
     * Obtiene el n?mero de campos del DataSource
362
     *
363
     * @return
364
     *
365
     * @throws DriverException Si se produce alg?n error accediendo al
366
     *         DataSource
367
     */
368
    public int getFieldCount() throws com.hardcode.gdbms.engine.data.driver.DriverException
369
    {
370
        try {
371
            // Suponemos que el primer campo es el de las geometries, y no lo
372
            // contamos
373
            return rs.getMetaData().getColumnCount()-1;
374
        } catch (SQLException e) {
375
            throw new com.hardcode.gdbms.engine.data.driver.DriverException(e);
376
        }
377

    
378
    }
379

    
380
    /**
381
     * Devuelve el nombre del campo fieldId-?simo
382
     *
383
     * @param fieldId ?ndice del campo cuyo nombre se quiere obtener
384
     *
385
     * @return
386
     * @throws com.hardcode.gdbms.engine.data.driver.DriverException
387
     *
388
     * @throws DriverException Si se produce alg?n error accediendo al
389
     *         DataSource
390
     */
391
    public String getFieldName(int fieldId) throws com.hardcode.gdbms.engine.data.driver.DriverException
392
    {
393
        try {
394
            return rs.getMetaData().getColumnName(fieldId+2);
395
        } catch (SQLException e) {
396
            throw new com.hardcode.gdbms.engine.data.driver.DriverException(e);
397
        }
398
    }
399

    
400
    /**
401
     * Obtiene el n?mero de registros del DataSource
402
     *
403
     * @return
404
     *
405
     * @throws DriverException Si se produce alg?n error accediendo al
406
     *         DataSource
407
     */
408
    public long getRowCount()
409
    {
410
        try {
411
            return getShapeCount();
412
        } catch (IOException e) {
413
            // TODO Auto-generated catch block
414
            e.printStackTrace();
415
        }
416
        return -1;
417
    }
418

    
419
    public void close() {
420
    }
421

    
422
    /**
423
     * Recorre el recordset creando una tabla Hash que usaremos para
424
     * relacionar el n?mero de un registro con su identificador ?nico.
425
     * Debe ser llamado en el setData justo despu?s de crear el recorset
426
     * principal
427
     * @throws SQLException
428
     */
429
    protected void doRelateID_FID() throws SQLException
430
    {
431
        hashRelate = new Hashtable();
432

    
433

    
434
        String strSQL = "SELECT " + getLyrDef().getFieldID() + " FROM " + getLyrDef().getComposedTableName()
435
        + " " + getCompleteWhere() + " ORDER BY " + getLyrDef().getFieldID();
436
        Statement s = ((ConnectionJDBC)getConnection()).getConnection().createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
437
        ResultSet r = s.executeQuery(strSQL);
438
        int id=0;
439
        int gid;
440
        int index = 0;
441
        while (r.next())
442
        {
443
            String aux = r.getString(1);
444
            Value val = ValueFactory.createValue(aux);
445
            hashRelate.put(val, new Integer(index));
446
            System.out.println("ASOCIANDO CLAVE " + aux + " CON VALOR " + index);
447
            index++;
448
        }
449
        numReg = index;
450
        r.close();
451
        // rs.beforeFirst();
452

    
453
    }
454

    
455
    /* (non-Javadoc)
456
     * @see com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver#getRowIndexByFID(java.lang.Object)
457
     */
458
    public int getRowIndexByFID(IFeature FID)
459
    {
460
        int resul;
461
        // Object obj = FID.getAttribute(lyrDef.getIdFieldID());
462
        String theId = FID.getID();
463
        Value aux = ValueFactory.createValue(theId);
464
        // System.err.println("Mirando si existe " + aux.toString());
465
        if (hashRelate.containsKey(aux))
466
        {
467
                Integer rowIndex = (Integer) hashRelate.get(aux);
468
                resul = rowIndex.intValue();
469
                // System.err.println("Row asociada a " + aux.toString() + ":" + resul);
470
                return resul;
471
        }
472
        else
473
                return -1;
474
    }
475

    
476
    /* (non-Javadoc)
477
     * @see com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver#setXMLEntity(com.iver.utiles.XMLEntity)
478
     */
479
    public void setXMLEntity(XMLEntity xml) throws XMLException
480
    {
481

    
482
        className = xml.getStringProperty("className");
483

    
484
        catalogName = xml.getStringProperty("catalog");
485
        userName =xml.getStringProperty("username");
486
        driverClass =xml.getStringProperty("driverclass");
487
        tableName = xml.getStringProperty("tablename");
488
        if (xml.contains("schema")){
489
                schema = xml.getStringProperty("schema");
490
        }
491
        fields = xml.getStringArrayProperty("fields");
492
        FIDfield = xml.getStringProperty("FID");
493
        geometryField = xml.getStringProperty("THE_GEOM");
494
        whereClause = xml.getStringProperty("whereclause");
495
        strSRID = xml.getStringProperty("SRID");
496

    
497
        if (xml.contains("host"))
498
        {
499
                host = xml.getStringProperty("host");
500
                port = xml.getStringProperty("port");
501
                dbName = xml.getStringProperty("dbName");
502
                connName = xml.getStringProperty("connName");
503
        }
504
        else
505
        {
506
                // Por compatibilidad con versiones anteriores
507
                dbUrl = xml.getStringProperty("dbURL");
508
                extractParamsFromDbUrl(dbUrl);
509

    
510
        }
511
        if (xml.contains("minXworkArea"))
512
        {
513
            double x = xml.getDoubleProperty("minXworkArea");
514
            double y = xml.getDoubleProperty("minYworkArea");
515
            double H = xml.getDoubleProperty("HworkArea");
516
            double W = xml.getDoubleProperty("WworkArea");
517
            workingArea = new Rectangle2D.Double(x,y,W,H);
518
        }
519

    
520
        DBLayerDefinition lyrDef = new DBLayerDefinition();
521
        lyrDef.setCatalogName(catalogName);
522
        lyrDef.setSchema(schema);
523
        lyrDef.setTableName(tableName);
524
        lyrDef.setFieldNames(fields);
525
        lyrDef.setFieldID(FIDfield);
526
        lyrDef.setFieldGeometry(geometryField);
527
        lyrDef.setWhereClause(whereClause);
528
        // lyrDef.setClassToInstantiate(driverClass);
529
        if (workingArea != null)
530
            lyrDef.setWorkingArea(workingArea);
531

    
532
        lyrDef.setSRID_EPSG(strSRID);
533

    
534
        setLyrDef(lyrDef);
535

    
536
    }
537

    
538
    private void extractParamsFromDbUrl(String dbUrl2) {
539
            //jdbc:postgres://localhost:5431/latin1
540
            int iDbName = dbUrl2.lastIndexOf('/');
541
                dbName = dbUrl2.substring(iDbName+1);
542
                int iLast2points = dbUrl2.lastIndexOf(':');
543
                port = dbUrl2.substring(iLast2points+1, iDbName);
544
                int iHost = dbUrl2.indexOf("//");
545
                host = dbUrl2.substring(iHost + 2, iLast2points);
546
                connName = dbUrl2;
547
        }
548

    
549
        public void load() throws DriverException {
550
            try {
551
            if (driverClass != null)
552
                    Class.forName(driverClass);
553

    
554
            String _drvName = getName();
555

    
556
            String keyPool = _drvName.toLowerCase() + "_" + host.toLowerCase()
557
            + "_" + port + "_" + dbName.toLowerCase()
558
            + "_" + userName.toLowerCase();
559

    
560
            IConnection newConn = null;
561
            String clave = null;
562
            ConnectionWithParams cwp = null;
563

    
564
            if (poolPassw.containsKey(keyPool)) {
565

    
566
                clave = (String) poolPassw.get(keyPool);
567
                cwp = SingleVectorialDBConnectionManager.instance().getConnection(
568
                                         _drvName, userName, clave, connName,
569
                                         host, port, dbName, true);
570

    
571
            } else {
572

    
573
                cwp = SingleVectorialDBConnectionManager.instance().getConnection(
574
                                             _drvName, userName, null, connName,
575
                                             host, port, dbName, false);
576

    
577
                if (cwp.isConnected()) {
578

    
579
                        poolPassw.put(keyPool, cwp.getPw());
580

    
581
                } else {
582

    
583
                    JPasswordDlg dlg = new JPasswordDlg();
584
                    String strMessage = Messages.getString("conectar_jdbc");
585
                    String strPassword = Messages.getString("password");
586
                    dlg.setMessage(strMessage
587
                                    + " ["
588
                                    + _drvName + ", "
589
                                    + host + ", "
590
                                    + port + ", "
591
                                    + dbName + ", "
592
                                    + userName + "]. "
593
                                    + strPassword
594
                                    + "?");
595
                    dlg.show();
596
                    clave = dlg.getPassword();
597
                    if (clave == null)
598
                        return;
599
                    poolPassw.put(keyPool, clave);
600

    
601
                    cwp.connect(clave);
602
                }
603
            }
604

    
605
            newConn = cwp.getConnection();
606
//            newConn.setAutoCommit(false);
607

    
608
            DBLayerDefinition lyrDef = new DBLayerDefinition();
609
            if (getLyrDef() == null) {
610
                    lyrDef.setCatalogName(catalogName);
611
                    lyrDef.setSchema(schema);
612
                    lyrDef.setTableName(tableName);
613
                    lyrDef.setFieldNames(fields);
614
                    lyrDef.setFieldID(FIDfield);
615
                    lyrDef.setFieldGeometry(geometryField);
616
                    lyrDef.setWhereClause(whereClause);
617
                    // lyrDef.setClassToInstantiate(driverClass);
618
                    if (workingArea != null)
619
                        lyrDef.setWorkingArea(workingArea);
620

    
621
                    lyrDef.setSRID_EPSG(strSRID);
622
            } else {
623
                    lyrDef = getLyrDef();
624
            }
625

    
626
            setData(newConn, lyrDef);
627
        } catch (ClassNotFoundException e) {
628
            logger.debug(e);
629
            DriverJdbcNotFoundExceptionType type =
630
                    new DriverJdbcNotFoundExceptionType();
631
            type.setDriverJdbcClassName(driverClass);
632
            type.setLayerName(this.getTableName());
633
            throw new DriverException("Driver JDBC no encontrado", e,  type);
634
        } catch (DBException e) {
635

    
636
                throw new DriverException(e.getMessage());
637

    
638
                }
639
    }
640
    /* (non-Javadoc)
641
     * @see com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver#getXMLEntity()
642
     */
643
    public XMLEntity getXMLEntity()
644
    {
645
        XMLEntity xml = new XMLEntity();
646
        xml.putProperty("className",this.getClass().getName());
647
        try {
648
            DatabaseMetaData metadata = ((ConnectionJDBC)getConnection()).getConnection().getMetaData();
649
            xml.putProperty("catalog", getLyrDef().getCatalogName());
650

    
651
            // TODO: NO DEBEMOS GUARDAR EL NOMBRE DE USUARIO Y CONTRASE?A
652
            // AQUI. Hay que utilizar un pool de conexiones
653
            // y pedir al usuario que conecte a la base de datos
654
            // en la primera capa. En el resto, usar la conexi?n
655
            // creada con anterioridad.
656
            String userName = metadata.getUserName();
657
            int aux = userName.indexOf("@");
658
            if (aux != -1)
659
                userName = userName.substring(0,aux);
660
            xml.putProperty("username", userName);
661

    
662
            Driver drv = DriverManager.getDriver(metadata.getURL());
663
            // System.out.println(drv.getClass().getName());
664
            xml.putProperty("driverclass", drv.getClass().getName());
665
            xml.putProperty("schema", lyrDef.getSchema());
666
            xml.putProperty("tablename", getTableName());
667
            xml.putProperty("fields", lyrDef.getFieldNames());
668
            xml.putProperty("FID", lyrDef.getFieldID());
669
            xml.putProperty("THE_GEOM", lyrDef.getFieldGeometry());
670
            xml.putProperty("whereclause", getWhereClause());
671
            xml.putProperty("SRID", lyrDef.getSRID_EPSG());
672

    
673
            ConnectionWithParams cwp =
674
                    SingleVectorialDBConnectionManager.instance().findConnection(getConnection());
675

    
676
            //FIXME:(Chema) Estos cambios los hago porque da errores as persistencia
677
            if (cwp != null){
678
                    xml.putProperty("host", cwp.getHost());
679
                    xml.putProperty("port", cwp.getPort());
680
                    xml.putProperty("dbName", cwp.getDb());
681
                    xml.putProperty("connName", cwp.getName());
682
            } else {
683
                    xml.putProperty("dbURL",metadata.getURL());
684
            }
685
            // Chema
686

    
687
            if (getWorkingArea() != null)
688
            {
689
                xml.putProperty("minXworkArea", getWorkingArea().getMinX());
690
                xml.putProperty("minYworkArea", getWorkingArea().getMinY());
691
                xml.putProperty("HworkArea", getWorkingArea().getHeight());
692
                xml.putProperty("WworkArea", getWorkingArea().getWidth());
693
            }
694

    
695
        } catch (SQLException e) {
696
            // TODO Auto-generated catch block
697
            e.printStackTrace();
698
        }
699

    
700

    
701
        return xml;
702

    
703
    }
704

    
705
    /**
706
     * @see com.iver.cit.gvsig.fmap.drivers.IVectorialJDBCDriver#setWorkingArea(java.awt.geom.Rectangle2D)
707
     */
708
    public void setWorkingArea(Rectangle2D rect) {
709
        this.workingArea = rect;
710
    }
711

    
712
    /**
713
     * @see com.iver.cit.gvsig.fmap.drivers.IVectorialJDBCDriver#getWorkingArea()
714
     */
715
    public Rectangle2D getWorkingArea() {
716
        return workingArea;
717
    }
718

    
719
    /* (non-Javadoc)
720
     * @see com.hardcode.gdbms.engine.data.driver.GDBMSDriver#setDataSourceFactory(com.hardcode.gdbms.engine.data.DataSourceFactory)
721
     */
722
    public void setDataSourceFactory(DataSourceFactory arg0) {
723
        // TODO Auto-generated method stub
724

    
725
    }
726

    
727
    /**
728
     * @return Returns the lyrDef.
729
     */
730
    public DBLayerDefinition getLyrDef() {
731
            if (this.conn != null){
732
                    if (lyrDef.getConnection() != this.conn){
733
                            lyrDef.setConnection(this.conn);
734
                    }
735
            }
736
        return lyrDef;
737
    }
738

    
739
    /**
740
     * @param lyrDef The lyrDef to set.
741
     */
742
    public void setLyrDef(DBLayerDefinition lyrDef) {
743
        this.lyrDef = lyrDef;
744
    }
745

    
746
    abstract public String getSqlTotal();
747

    
748
    /**
749
     * @return Returns the completeWhere. WITHOUT order by clause!!
750
     */
751
    abstract public String getCompleteWhere();
752

    
753
    /* (non-Javadoc)
754
     * @see com.iver.cit.gvsig.fmap.drivers.VectorialDriver#reLoad()
755
     */
756
    public void reload() throws IOException
757
    {
758
                try {
759
                    if ((conn == null) || (((ConnectionJDBC)conn).getConnection().isClosed()))
760
                    {
761
                            this.load();
762
                    }
763

    
764
                    ((ConnectionJDBC)conn).getConnection().commit();
765

    
766
                    setData(conn, lyrDef);
767
                } catch (SQLException e) {
768
                        throw new IOException(e.getMessage());
769
                } catch (DriverException e) {
770
                        throw new IOException(e.getMessage());
771
                }
772

    
773
    }
774

    
775
    public int getFieldWidth(int fieldId)
776
    {
777
            int i = -1;
778
            try {
779
                    int aux = fieldId + 2; // idField viene basado en 1, y
780
                        i = rs.getMetaData().getColumnDisplaySize(aux);
781
                } catch (SQLException e) {
782
                        e.printStackTrace();
783
                }
784
                // SUN define que getColumnDisplaySize devuelve numeros negativos cuando el campo es de tipo Text o Vartext
785
                // sin ancho. Nosotros vamos a devolver 255 para que fucione, por lo menos al exportar a DBF.
786
                // Nota: Si se truncan cadenas, este es el sitio que lo provoca.
787
                if (i <0) i=255;
788
                return i;
789
    }
790

    
791
//        public void setFlatness(double flatness) {
792
//                this.flatness = flatness;
793
//        }
794

    
795
    // -----------------------------------------------------------
796
    // ----  EXT JDBC NUEVA                           ---
797
    // -----------------------------------------------------------
798

    
799
    /**
800
     * Gets the drivers connection string given its parameters (this can be different for
801
     * different driver, so it should be overwritten in that case.)
802
     */
803
    public String getConnectionString(
804
                    String host,
805
                    String port,
806
                    String dbname,
807
                    String user,
808
                    String pw) {
809

    
810
                String resp = getConnectionStringBeginning() + "//" + host.toLowerCase();
811

    
812
                if (dbname.trim().length() > 0) {
813
                        resp += ":" + port;
814
                } else {
815
                        resp += ":" + getDefaultPort();
816
                }
817

    
818
                resp += "/" + dbname.toLowerCase();
819
                return resp;
820
    }
821

    
822
    /**
823
     * Gets available table names. Should be overwritten by subclasses if its
824
     * not compatible or if it can be refined
825
     *
826
     * @param conn connection object
827
     * @param catalog catalog name
828
     * @return array of strings with available table names
829
     * @throws SQLException
830
     */
831
    public String[] getTableNames(IConnection conn, String catalog) throws DBException {
832
            TreeMap ret = new TreeMap();
833
            try{
834
            DatabaseMetaData dbmd = ((ConnectionJDBC)conn).getConnection().getMetaData();
835
        String[] types = {"TABLE", "VIEW"};
836
                ResultSet rs = dbmd.getTables(catalog, null, null, types);
837
                while (rs.next()){
838
                        // ret.put(rs.getString("TABLE_NAME"), rs.getString("TABLE_NAME"));
839
                        // As suggested by Jorge Agudo, to allow charging tables from other schemas
840
                        ret.put((rs.getString("TABLE_SCHEM")!=null?(rs.getString("TABLE_SCHEM") + "."): "") + rs.getString("TABLE_NAME"), (rs.getString("TABLE_SCHEM")!=null?(rs.getString("TABLE_SCHEM") + "."): "") + rs.getString("TABLE_NAME"));
841
                }
842
                rs.close();
843
            } catch (SQLException e) {
844
                        throw new DBException(e);
845
                }
846
                return (String[]) ret.keySet().toArray(new String[0]);
847
    }
848

    
849

    
850
    /**
851
     *       Gets all field names of a given table
852
     * @param conn connection object
853
     * @param table_name table name
854
     * @return all field names of the given table
855
     * @throws SQLException
856
     */
857
    public String[] getAllFields(IConnection conn, String table_name) throws DBException {
858
            String[] ret = null;
859
            try{
860
                Statement st = ((ConnectionJDBC)conn).getConnection().createStatement();
861
                ResultSet rs = st.executeQuery("select * from " + table_name + " LIMIT 1");
862
                ResultSetMetaData rsmd = rs.getMetaData();
863
                ret = new String[rsmd.getColumnCount()];
864

    
865
                for (int i = 0; i < ret.length; i++) {
866
                        ret[i] = rsmd.getColumnName(i+1);
867
                }
868
                rs.close(); st.close();
869
            } catch (SQLException e) {
870
                    // TODO Auto-generated catch block
871
                    e.printStackTrace();
872
            }
873
                return ret;
874
    }
875

    
876
    /**
877
     *       Gets all field type names of a given table
878
     * @param conn connection object
879
     * @param table_name table name
880
     * @return all field type names of the given table
881
     * @throws SQLException
882
     */
883
    public String[] getAllFieldTypeNames(IConnection conn, String table_name) throws DBException {
884
            String[] ret = null;
885
            try{
886
                Statement st = ((ConnectionJDBC)conn).getConnection().createStatement();
887
                ResultSet rs = st.executeQuery("select * from " + table_name + " LIMIT 1");
888
                ResultSetMetaData rsmd = rs.getMetaData();
889
                ret = new String[rsmd.getColumnCount()];
890

    
891
                for (int i = 0; i < ret.length; i++) {
892
                        ret[i] = rsmd.getColumnTypeName(i+1);
893
                }
894
                rs.close(); st.close();
895
            } catch (SQLException e) {
896
                        throw new DBException(e);
897
                }
898
                return ret;
899
    }
900

    
901
    /**
902
     * Gets the table's possible id fields. By default, all fields can be id.
903
     * It should be overwritten by subclasses.
904
     *
905
     * @param conn conenction object
906
     * @param table_name table name
907
     * @return the table's possible id fields
908
     * @throws SQLException
909
     */
910
    public String[] getIdFieldsCandidates(IConnection conn, String table_name) throws DBException {
911
            return getAllFields(conn, table_name);
912
    }
913

    
914
    /**
915
     * Gets the table's possible geometry fields. By default, all fields can be geometry
916
     * fields. It should be overwritten by subclasses.
917
     *
918
     * @param conn conenction object
919
     * @param table_name table name
920
     * @return the table's possible geometry fields
921
     * @throws SQLException
922
     */
923
    public String[] getGeometryFieldsCandidates(IConnection conn, String table_name) throws DBException {
924
            return getAllFields(conn, table_name);
925
    }
926

    
927
    /**
928
     * Tells if it's an empty table (with no records)
929
     * @param conn conenction object
930
     * @param tableName rtable name
931
     * @return whether it's an empty table (with no records) or not
932
     */
933
        public boolean isEmptyTable(IConnection conn, String tableName) {
934

    
935
                boolean res = true;
936

    
937
                try {
938
                        Statement st = ((ConnectionJDBC)conn).getConnection().createStatement();
939
                        ResultSet rs = null;
940
                        rs = st.executeQuery("select * from " + tableName + " LIMIT 1");
941
                        res = !rs.next();
942
                        rs.close(); st.close();
943
                } catch (Exception ex) {
944
                        res = true;
945
                }
946
                return res;
947
        }
948

    
949

    
950

    
951
        /**
952
         * Utility method to allow the driver to do something with the geometry field.
953
         * By default does nothing.
954
         *
955
         * @param flds user-selected fields
956
         * @param geomField geometry field
957
         * @return new user-selected fields
958
         */
959
        public String[] manageGeometryField(String[] flds, String geomField) {
960
                return flds;
961
        }
962

    
963
        /**
964
         * Empty method called when the layer is going to be removed from the view.
965
         * Subclasses can overwrite it if needed.
966
         *
967
         */
968
        public void remove() {
969

    
970
        }
971

    
972
        public void addDriverEventListener(DriverEventListener listener) {
973
                if (!driverEventListeners.contains(listener))
974
                        driverEventListeners.add(listener);
975

    
976
        }
977

    
978
        public void removeDriverEventListener(DriverEventListener listener) {
979
                driverEventListeners.remove(listener);
980

    
981
        }
982

    
983
        public void notifyDriverEndLoaded() {
984
                DriverEvent event = new DriverEvent(DriverEvent.DRIVER_EVENT_LOADING_END);
985
                for (int i=0; i < driverEventListeners.size(); i++)
986
                {
987
                        DriverEventListener aux = (DriverEventListener) driverEventListeners.get(i);
988
                        aux.driverNotification(event);
989
                }
990
        }
991

    
992
}