Statistics
| Revision:

svn-gvsig-desktop / tags / v1_1_Build_1000 / libraries / libFMap / src / com / iver / cit / gvsig / fmap / drivers / DefaultDBDriver.java @ 11885

History | View | Annotate | Download (31.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 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(Connection 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 Connection 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 = conn.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
            if (metaData.getColumnType(i) == Types.VARCHAR)
275
                return Types.VARCHAR;
276
                    if (metaData.getColumnType(i) == Types.FLOAT)
277
                        return Types.FLOAT;
278
                    if (metaData.getColumnType(i) == Types.DOUBLE)
279
                        return Types.DOUBLE;
280
                    if (metaData.getColumnType(i) == Types.INTEGER)
281
                        return Types.INTEGER;
282
                    if (metaData.getColumnType(i) == Types.SMALLINT)
283
                        return Types.SMALLINT;
284
                    if (metaData.getColumnType(i) == Types.TINYINT)
285
                        return Types.TINYINT;                    
286
                    if (metaData.getColumnType(i) == Types.BIGINT)
287
                        return Types.BIGINT;
288
                    if (metaData.getColumnType(i) == Types.BIT)
289
                        return Types.BIT;
290
                    if (metaData.getColumnType(i) == Types.DATE)
291
                        return Types.DATE;
292
            if (metaData.getColumnType(i) == Types.DECIMAL)
293
                return Types.DOUBLE;
294
            if (metaData.getColumnType(i) == Types.NUMERIC)
295
                return Types.DOUBLE;
296
            if (metaData.getColumnType(i) == Types.DATE)
297
                return Types.DATE;
298
            if (metaData.getColumnType(i) == Types.TIME)
299
                return Types.TIME;
300
            if (metaData.getColumnType(i) == Types.TIMESTAMP)
301
                return Types.TIMESTAMP;
302

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

    
352

    
353
        }
354

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

    
373
    }
374

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

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

    
414
    public void close() {
415
    }
416

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

    
428

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

    
448
    }
449

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

    
471
    /* (non-Javadoc)
472
     * @see com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver#setXMLEntity(com.iver.utiles.XMLEntity)
473
     */
474
    public void setXMLEntity(XMLEntity xml) throws XMLException
475
    {
476

    
477
        className = xml.getStringProperty("className");
478
        
479
        catalogName = xml.getStringProperty("catalog");
480
        userName =xml.getStringProperty("username");
481
        driverClass =xml.getStringProperty("driverclass");
482
        if (xml.contains("schema"))
483
        {
484
                schema = xml.getStringProperty("schema");
485
        }
486
        tableName = xml.getStringProperty("tablename");
487
        fields = xml.getStringArrayProperty("fields");
488
        FIDfield = xml.getStringProperty("FID");
489
        geometryField = xml.getStringProperty("THE_GEOM");
490
        whereClause = xml.getStringProperty("whereclause");
491
        strSRID = xml.getStringProperty("SRID");
492

    
493
        if (xml.contains("host"))
494
        {
495
                host = xml.getStringProperty("host");
496
                port = xml.getStringProperty("port");
497
                dbName = xml.getStringProperty("dbName");
498
                connName = xml.getStringProperty("connName");
499
        }
500
        else
501
        {
502
                // Por compatibilidad con versiones anteriores
503
                dbUrl = xml.getStringProperty("dbURL");
504
                extractParamsFromDbUrl(dbUrl);
505
                
506
        }
507
        if (xml.contains("minXworkArea"))
508
        {
509
            double x = xml.getDoubleProperty("minXworkArea");
510
            double y = xml.getDoubleProperty("minYworkArea");
511
            double H = xml.getDoubleProperty("HworkArea");
512
            double W = xml.getDoubleProperty("WworkArea");
513
            workingArea = new Rectangle2D.Double(x,y,W,H);
514
        }
515

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

    
528
        lyrDef.setSRID_EPSG(strSRID);
529

    
530
        setLyrDef(lyrDef);
531

    
532
    }
533

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

    
545
        public void load() throws DriverException {
546
            try {
547
            if (driverClass != null)
548
                    Class.forName(driverClass);
549
            
550
            String _drvName = getName();
551

    
552
            String keyPool = _drvName.toLowerCase() + "_" + host.toLowerCase()
553
            + "_" + port + "_" + dbName.toLowerCase()
554
            + "_" + userName.toLowerCase();
555
            
556
            Connection newConn = null;
557
            String clave = null;
558
            ConnectionWithParams cwp = null;
559
            
560
            if (poolPassw.containsKey(keyPool)) {
561
                    
562
                clave = (String) poolPassw.get(keyPool);
563
                cwp = SingleJDBCConnectionManager.instance().getConnection(
564
                                         _drvName, userName, clave, connName,
565
                                         host, port, dbName, true);
566

    
567
            } else {
568
                    
569
                cwp = SingleJDBCConnectionManager.instance().getConnection(
570
                                             _drvName, userName, null, connName,
571
                                             host, port, dbName, false);
572
                
573
                if (cwp.isConnected()) {
574
                        
575
                        poolPassw.put(keyPool, cwp.getPw());
576
                        
577
                } else {
578
                        
579
                    JPasswordDlg dlg = new JPasswordDlg();
580
                    String strMessage = Messages.getString("conectar_jdbc");
581
                    String strPassword = Messages.getString("password");
582
                    dlg.setMessage(strMessage
583
                                    + " ["
584
                                    + _drvName + ", "
585
                                    + host + ", "
586
                                    + port + ", "
587
                                    + dbName + ", "
588
                                    + userName + "]. "
589
                                    + strPassword
590
                                    + "?");
591
                    dlg.show();
592
                    clave = dlg.getPassword();
593
                    if (clave == null)
594
                        return;
595
                    poolPassw.put(keyPool, clave);
596
                    
597
                    cwp.connect(clave);
598
                }
599
            }
600

    
601
            newConn = cwp.getConnection();
602
            newConn.setAutoCommit(false);
603

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

    
617
                    lyrDef.setSRID_EPSG(strSRID);
618
            } else {
619
                    lyrDef = getLyrDef();
620
            }
621

    
622
            setData(newConn, lyrDef);
623
        } catch (ClassNotFoundException e) {
624
            logger.debug(e);
625
            DriverJdbcNotFoundExceptionType type =
626
                    new DriverJdbcNotFoundExceptionType();
627
            type.setDriverJdbcClassName(driverClass);
628
            type.setLayerName(this.getTableName());
629
            throw new DriverException("Driver JDBC no encontrado", e,  type);
630
        } catch (SQLException e) {
631
                
632
                throw new DriverException(e.getMessage());
633
                
634
                }
635
    }
636
    /* (non-Javadoc)
637
     * @see com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver#getXMLEntity()
638
     */
639
    public XMLEntity getXMLEntity()
640
    {
641
        XMLEntity xml = new XMLEntity();
642
        xml.putProperty("className",this.getClass().getName());
643
        try {
644
            DatabaseMetaData metadata = getConnection().getMetaData();
645
            xml.putProperty("catalog", getLyrDef().getCatalogName());
646
            
647
            // TODO: NO DEBEMOS GUARDAR EL NOMBRE DE USUARIO Y CONTRASE?A
648
            // AQUI. Hay que utilizar un pool de conexiones
649
            // y pedir al usuario que conecte a la base de datos
650
            // en la primera capa. En el resto, usar la conexi?n
651
            // creada con anterioridad.
652
            String userName = metadata.getUserName();
653
            int aux = userName.indexOf("@");
654
            if (aux != -1)
655
                userName = userName.substring(0,aux);
656
            xml.putProperty("username", userName);
657

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

    
669
            ConnectionWithParams cwp =
670
                    SingleJDBCConnectionManager.instance().findConnection(getConnection());
671

    
672
            //FIXME:(Chema) Estos cambios los hago porque da errores as persistencia 
673
            if (cwp != null){
674
                    xml.putProperty("host", cwp.getHost());
675
                    xml.putProperty("port", cwp.getPort());
676
                    xml.putProperty("dbName", cwp.getDb());
677
                    xml.putProperty("connName", cwp.getName());
678
            } else {
679
                    xml.putProperty("dbURL",metadata.getURL());
680
            }
681
            // Chema
682
            
683
            if (getWorkingArea() != null)
684
            {
685
                xml.putProperty("minXworkArea", getWorkingArea().getMinX());
686
                xml.putProperty("minYworkArea", getWorkingArea().getMinY());
687
                xml.putProperty("HworkArea", getWorkingArea().getHeight());
688
                xml.putProperty("WworkArea", getWorkingArea().getWidth());
689
            }
690

    
691
        } catch (SQLException e) {
692
            // TODO Auto-generated catch block
693
            e.printStackTrace();
694
        }
695

    
696

    
697
        return xml;
698

    
699
    }
700

    
701
    /**
702
     * @see com.iver.cit.gvsig.fmap.drivers.VectorialJDBCDriver#setWorkingArea(java.awt.geom.Rectangle2D)
703
     */
704
    public void setWorkingArea(Rectangle2D rect) {
705
        this.workingArea = rect;
706
    }
707

    
708
    /**
709
     * @see com.iver.cit.gvsig.fmap.drivers.VectorialJDBCDriver#getWorkingArea()
710
     */
711
    public Rectangle2D getWorkingArea() {
712
        return workingArea;
713
    }
714

    
715
    /* (non-Javadoc)
716
     * @see com.hardcode.gdbms.engine.data.driver.GDBMSDriver#setDataSourceFactory(com.hardcode.gdbms.engine.data.DataSourceFactory)
717
     */
718
    public void setDataSourceFactory(DataSourceFactory arg0) {
719
        // TODO Auto-generated method stub
720

    
721
    }
722

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

    
735
    /**
736
     * @param lyrDef The lyrDef to set.
737
     */
738
    public void setLyrDef(DBLayerDefinition lyrDef) {
739
        this.lyrDef = lyrDef;
740
    }
741

    
742
    abstract public String getSqlTotal();
743

    
744
    /**
745
     * @return Returns the completeWhere. WITHOUT order by clause!!
746
     */
747
    abstract public String getCompleteWhere();
748

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

    
760
                        conn.commit();
761

    
762
                    setData(conn, lyrDef);
763
                } catch (SQLException e) {
764
                        throw new IOException(e.getMessage());
765
                } catch (DriverException e) {
766
                        throw new IOException(e.getMessage());
767
                }
768

    
769
    }
770

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

    
787
//        public void setFlatness(double flatness) {
788
//                this.flatness = flatness;
789
//        }
790
    
791
    // -----------------------------------------------------------
792
    // ----  EXT JDBC NUEVA                           ---
793
    // -----------------------------------------------------------
794
    
795
    /**
796
     * Gets the drivers connection string given its parameters (this can be different for
797
     * different driver, so it should be overwritten in that case.)
798
     */
799
    public String getConnectionString(
800
                    String host,
801
                    String port,
802
                    String dbname,
803
                    String user,
804
                    String pw) {
805
            
806
                String resp = getConnectionStringBeginning() + "//" + host.toLowerCase();
807

    
808
                if (dbname.trim().length() > 0) {
809
                        resp += ":" + port;
810
                } else {
811
                        resp += ":" + getDefaultPort();
812
                }
813

    
814
                resp += "/" + dbname.toLowerCase();
815
                return resp;
816
    }
817
    
818
    /**
819
     * Gets available table names. Should be overwritten by subclasses if its
820
     * not compatible or if it can be refined
821
     * 
822
     * @param conn connection object
823
     * @param catalog catalog name
824
     * @return array of strings with available table names
825
     * @throws SQLException
826
     */
827
    public String[] getTableNames(Connection conn, String catalog) throws SQLException {
828
            
829
            DatabaseMetaData dbmd = conn.getMetaData();
830
        String[] types = {"TABLE", "VIEW"};
831
                ResultSet rs = dbmd.getTables(catalog, null, null, types);
832
                TreeMap ret = new TreeMap();
833
                while (rs.next()){
834
                        // ret.put(rs.getString("TABLE_NAME"), rs.getString("TABLE_NAME"));
835
                        // As suggested by Jorge Agudo, to allow charging tables from other schemas
836
                        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"));                        
837
                        
838
                }
839
                rs.close();
840
                return (String[]) ret.keySet().toArray(new String[0]);
841
    }
842
    
843

    
844
    /**
845
     *       Gets all field names of a given table
846
     * @param conn connection object
847
     * @param table_name table name
848
     * @return all field names of the given table
849
     * @throws SQLException
850
     */
851
    public String[] getAllFields(Connection conn, String table_name) throws SQLException {
852
            
853
                Statement st = conn.createStatement();
854
                ResultSet rs = st.executeQuery("select * from " + table_name + " LIMIT 1");
855
                ResultSetMetaData rsmd = rs.getMetaData();
856
                String[] ret = new String[rsmd.getColumnCount()];
857

    
858
                for (int i = 0; i < ret.length; i++) {
859
                        ret[i] = rsmd.getColumnName(i+1);
860
                }
861
                rs.close(); st.close();
862
                return ret;
863
    }
864

    
865
    /**
866
     *       Gets all field type names of a given table
867
     * @param conn connection object
868
     * @param table_name table name
869
     * @return all field type names of the given table
870
     * @throws SQLException
871
     */
872
    public String[] getAllFieldTypeNames(Connection conn, String table_name) throws SQLException {
873
            
874
                Statement st = conn.createStatement();
875
                ResultSet rs = st.executeQuery("select * from " + table_name + " LIMIT 1");
876
                ResultSetMetaData rsmd = rs.getMetaData();
877
                String[] ret = new String[rsmd.getColumnCount()];
878

    
879
                for (int i = 0; i < ret.length; i++) {
880
                        ret[i] = rsmd.getColumnTypeName(i+1);
881
                }
882
                rs.close(); st.close();
883
                return ret;
884
    }
885

    
886
    /**
887
     * Gets the table's possible id fields. By default, all fields can be id. 
888
     * It should be overwritten by subclasses.
889
     * 
890
     * @param conn conenction object
891
     * @param table_name table name
892
     * @return the table's possible id fields
893
     * @throws SQLException
894
     */
895
    public String[] getIdFieldsCandidates(Connection conn, String table_name) throws SQLException {
896
            return getAllFields(conn, table_name);
897
    }
898
    
899
    /**
900
     * Gets the table's possible geometry fields. By default, all fields can be geometry
901
     * fields. It should be overwritten by subclasses.
902
     * 
903
     * @param conn conenction object
904
     * @param table_name table name
905
     * @return the table's possible geometry fields
906
     * @throws SQLException
907
     */
908
    public String[] getGeometryFieldsCandidates(Connection conn, String table_name) throws SQLException {
909
            return getAllFields(conn, table_name);
910
    }
911
    
912
    /**
913
     * Tells if it's an empty table (with no records)
914
     * @param conn conenction object
915
     * @param tableName rtable name
916
     * @return whether it's an empty table (with no records) or not
917
     */
918
        public boolean isEmptyTable(Connection conn, String tableName) {
919
                
920
                boolean res = true;
921

    
922
                try {
923
                        Statement st = conn.createStatement();
924
                        ResultSet rs = null;
925
                        rs = st.executeQuery("select * from " + tableName + " LIMIT 1");
926
                        res = !rs.next();
927
                        rs.close(); st.close();
928
                } catch (Exception ex) {
929
                        res = true;
930
                }
931
                return res;
932
        }
933

    
934

    
935

    
936
        /**
937
         * Utility method to allow the driver to do something with the geometry field.
938
         * By default does nothing.
939
         * 
940
         * @param flds user-selected fields
941
         * @param geomField geometry field
942
         * @return new user-selected fields
943
         */
944
        public String[] manageGeometryField(String[] flds, String geomField) {
945
                return flds;
946
        }
947
        
948
        /**
949
         * Empty method called when the layer is going to be removed from the view.
950
         * Subclasses can overwrite it if needed.
951
         *
952
         */
953
        public void remove() {
954
                
955
        }
956

    
957
        public void addDriverEventListener(DriverEventListener listener) {
958
                if (!driverEventListeners.contains(listener))
959
                        driverEventListeners.add(listener);
960
                
961
        }
962

    
963
        public void removeDriverEventListener(DriverEventListener listener) {
964
                driverEventListeners.remove(listener);
965
                
966
        }
967
        
968
        public void notifyDriverEndLoaded() {
969
                DriverEvent event = new DriverEvent(DriverEvent.DRIVER_EVENT_LOADING_END);
970
                for (int i=0; i < driverEventListeners.size(); i++)
971
                {
972
                        DriverEventListener aux = (DriverEventListener) driverEventListeners.get(i);
973
                        aux.driverNotification(event);
974
                }
975
        }
976
    
977
}