Statistics
| Revision:

svn-gvsig-desktop / tags / v1_1_Build_1008 / libraries / libFMap / src / com / iver / cit / gvsig / fmap / drivers / DefaultJDBCDriver.java @ 12520

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

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

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

    
183

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

    
206
            return numReg;
207
        }
208

    
209
    /**
210
     * @throws IOException
211
     * @see com.iver.cit.gvsig.fmap.layers.ReadableVectorial#getFullExtent()
212
     */
213
    public Rectangle2D getFullExtent() throws IOException{
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().getComposedTableName() +  " " + 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
               throw new IOException(e.getMessage());
238
            }
239

    
240
        }
241
        return fullExtent;
242
    }
243

    
244

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

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

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

    
355

    
356
        }
357

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

    
376
    }
377

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

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

    
417
    public void close() {
418
    }
419

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

    
432
                        String strSQL = "SELECT " + getLyrDef().getFieldID() + " FROM "
433
                                        + getLyrDef().getComposedTableName() + " "
434
                                        + getCompleteWhere() + " ORDER BY "
435
                                        + getLyrDef().getFieldID();
436
                        Statement s = ((ConnectionJDBC) getConnection()).getConnection()
437
                                        .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
438
                                                        ResultSet.CONCUR_READ_ONLY);
439

    
440
                        ResultSet r = s.executeQuery(strSQL);
441
                        int id = 0;
442
                        int gid;
443
                        int index = 0;
444
                        while (r.next()) {
445
                                String aux = r.getString(1);
446
                                Value val = ValueFactory.createValue(aux);
447
                                hashRelate.put(val, new Integer(index));
448
                                System.out.println("ASOCIANDO CLAVE " + aux + " CON VALOR "
449
                                                + index);
450
                                index++;
451
                        }
452
                        numReg = index;
453
                        r.close();
454
                        // rs.beforeFirst();
455
            } catch (SQLException e) {
456
                        throw new DBException(e);
457
                }
458

    
459
    }
460

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

    
482
    /* (non-Javadoc)
483
     * @see com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver#setXMLEntity(com.iver.utiles.XMLEntity)
484
     */
485
    public void setXMLEntity(XMLEntity xml) throws XMLException
486
    {
487

    
488
        className = xml.getStringProperty("className");
489

    
490
        catalogName = xml.getStringProperty("catalog");
491
        userName =xml.getStringProperty("username");
492
        driverClass =xml.getStringProperty("driverclass");
493
        tableName = xml.getStringProperty("tablename");
494
        if (xml.contains("schema")){
495
                schema = xml.getStringProperty("schema");
496
        }
497
        fields = xml.getStringArrayProperty("fields");
498
        FIDfield = xml.getStringProperty("FID");
499
        geometryField = xml.getStringProperty("THE_GEOM");
500
        whereClause = xml.getStringProperty("whereclause");
501
        strSRID = xml.getStringProperty("SRID");
502

    
503
        if (xml.contains("host"))
504
        {
505
                host = xml.getStringProperty("host");
506
                port = xml.getStringProperty("port");
507
                dbName = xml.getStringProperty("dbName");
508
                connName = xml.getStringProperty("connName");
509
        }
510
        else
511
        {
512
                // Por compatibilidad con versiones anteriores
513
                dbUrl = xml.getStringProperty("dbURL");
514
                extractParamsFromDbUrl(dbUrl);
515

    
516
        }
517
        if (xml.contains("minXworkArea"))
518
        {
519
            double x = xml.getDoubleProperty("minXworkArea");
520
            double y = xml.getDoubleProperty("minYworkArea");
521
            double H = xml.getDoubleProperty("HworkArea");
522
            double W = xml.getDoubleProperty("WworkArea");
523
            workingArea = new Rectangle2D.Double(x,y,W,H);
524
        }
525

    
526
        DBLayerDefinition lyrDef = new DBLayerDefinition();
527
        lyrDef.setCatalogName(catalogName);
528
        lyrDef.setSchema(schema);
529
        lyrDef.setTableName(tableName);
530
        lyrDef.setFieldNames(fields);
531
        lyrDef.setFieldID(FIDfield);
532
        lyrDef.setFieldGeometry(geometryField);
533
        lyrDef.setWhereClause(whereClause);
534
        // lyrDef.setClassToInstantiate(driverClass);
535
        if (workingArea != null)
536
            lyrDef.setWorkingArea(workingArea);
537

    
538
        lyrDef.setSRID_EPSG(strSRID);
539

    
540
        setLyrDef(lyrDef);
541

    
542
    }
543

    
544
    private void extractParamsFromDbUrl(String dbUrl2) {
545
            //jdbc:postgres://localhost:5431/latin1
546
            int iDbName = dbUrl2.lastIndexOf('/');
547
                dbName = dbUrl2.substring(iDbName+1);
548
                int iLast2points = dbUrl2.lastIndexOf(':');
549
                port = dbUrl2.substring(iLast2points+1, iDbName);
550
                int iHost = dbUrl2.indexOf("//");
551
                host = dbUrl2.substring(iHost + 2, iLast2points);
552
                connName = dbUrl2;
553
        }
554

    
555
        public void load() throws DriverException {
556
            try {
557
            if (driverClass != null)
558
                    Class.forName(driverClass);
559

    
560
            String _drvName = getName();
561

    
562
            String keyPool = _drvName.toLowerCase() + "_" + host.toLowerCase()
563
            + "_" + port + "_" + dbName.toLowerCase()
564
            + "_" + userName.toLowerCase();
565

    
566
            IConnection newConn = null;
567
            String clave = null;
568
            ConnectionWithParams cwp = null;
569

    
570
            if (poolPassw.containsKey(keyPool)) {
571

    
572
                clave = (String) poolPassw.get(keyPool);
573
                cwp = SingleVectorialDBConnectionManager.instance().getConnection(
574
                                         _drvName, userName, clave, connName,
575
                                         host, port, dbName, true);
576

    
577
            } else {
578

    
579
                cwp = SingleVectorialDBConnectionManager.instance().getConnection(
580
                                             _drvName, userName, null, connName,
581
                                             host, port, dbName, false);
582

    
583
                if (cwp.isConnected()) {
584

    
585
                        poolPassw.put(keyPool, cwp.getPw());
586

    
587
                } else {
588

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

    
607
                    cwp.connect(clave);
608
                }
609
            }
610

    
611
            newConn = cwp.getConnection();
612
//            newConn.setAutoCommit(false);
613

    
614
            DBLayerDefinition lyrDef = new DBLayerDefinition();
615
            if (getLyrDef() == null) {
616
                    lyrDef.setCatalogName(catalogName);
617
                    lyrDef.setSchema(schema);
618
                    lyrDef.setTableName(tableName);
619
                    lyrDef.setFieldNames(fields);
620
                    lyrDef.setFieldID(FIDfield);
621
                    lyrDef.setFieldGeometry(geometryField);
622
                    lyrDef.setWhereClause(whereClause);
623
                    // lyrDef.setClassToInstantiate(driverClass);
624
                    if (workingArea != null)
625
                        lyrDef.setWorkingArea(workingArea);
626

    
627
                    lyrDef.setSRID_EPSG(strSRID);
628
            } else {
629
                    lyrDef = getLyrDef();
630
            }
631

    
632
            setData(newConn, lyrDef);
633
        } catch (ClassNotFoundException e) {
634
            logger.debug(e);
635
            DriverJdbcNotFoundExceptionType type =
636
                    new DriverJdbcNotFoundExceptionType();
637
            type.setDriverJdbcClassName(driverClass);
638
            type.setLayerName(this.getTableName());
639
            throw new DriverException("Driver JDBC no encontrado", e,  type);
640
        } catch (DBException e) {
641

    
642
                throw new DriverException(e.getMessage());
643

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

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

    
668
            Driver drv = DriverManager.getDriver(metadata.getURL());
669
            // System.out.println(drv.getClass().getName());
670
            xml.putProperty("driverclass", drv.getClass().getName());
671
            xml.putProperty("schema", lyrDef.getSchema());
672
            xml.putProperty("tablename", getTableName());
673
            xml.putProperty("fields", lyrDef.getFieldNames());
674
            xml.putProperty("FID", lyrDef.getFieldID());
675
            xml.putProperty("THE_GEOM", lyrDef.getFieldGeometry());
676
            xml.putProperty("whereclause", getWhereClause());
677
            xml.putProperty("SRID", lyrDef.getSRID_EPSG());
678

    
679
            ConnectionWithParams cwp =
680
                    SingleVectorialDBConnectionManager.instance().findConnection(getConnection());
681

    
682
            //FIXME:(Chema) Estos cambios los hago porque da errores as persistencia
683
            if (cwp != null){
684
                    xml.putProperty("host", cwp.getHost());
685
                    xml.putProperty("port", cwp.getPort());
686
                    xml.putProperty("dbName", cwp.getDb());
687
                    xml.putProperty("connName", cwp.getName());
688
            } else {
689
                    xml.putProperty("dbURL",metadata.getURL());
690
            }
691
            // Chema
692

    
693
            if (getWorkingArea() != null)
694
            {
695
                xml.putProperty("minXworkArea", getWorkingArea().getMinX());
696
                xml.putProperty("minYworkArea", getWorkingArea().getMinY());
697
                xml.putProperty("HworkArea", getWorkingArea().getHeight());
698
                xml.putProperty("WworkArea", getWorkingArea().getWidth());
699
            }
700

    
701
        } catch (SQLException e) {
702
            // TODO Auto-generated catch block
703
            e.printStackTrace();
704
        }
705

    
706

    
707
        return xml;
708

    
709
    }
710

    
711
    /**
712
     * @see com.iver.cit.gvsig.fmap.drivers.IVectorialJDBCDriver#setWorkingArea(java.awt.geom.Rectangle2D)
713
     */
714
    public void setWorkingArea(Rectangle2D rect) {
715
        this.workingArea = rect;
716
    }
717

    
718
    /**
719
     * @see com.iver.cit.gvsig.fmap.drivers.IVectorialJDBCDriver#getWorkingArea()
720
     */
721
    public Rectangle2D getWorkingArea() {
722
        return workingArea;
723
    }
724

    
725
    /* (non-Javadoc)
726
     * @see com.hardcode.gdbms.engine.data.driver.GDBMSDriver#setDataSourceFactory(com.hardcode.gdbms.engine.data.DataSourceFactory)
727
     */
728
    public void setDataSourceFactory(DataSourceFactory arg0) {
729
        // TODO Auto-generated method stub
730

    
731
    }
732

    
733
    /**
734
     * @return Returns the lyrDef.
735
     */
736
    public DBLayerDefinition getLyrDef() {
737
            if (this.conn != null){
738
                    if (lyrDef.getConnection() != this.conn){
739
                            lyrDef.setConnection(this.conn);
740
                    }
741
            }
742
        return lyrDef;
743
    }
744

    
745
    /**
746
     * @param lyrDef The lyrDef to set.
747
     */
748
    public void setLyrDef(DBLayerDefinition lyrDef) {
749
        this.lyrDef = lyrDef;
750
    }
751

    
752
    abstract public String getSqlTotal();
753

    
754
    /**
755
     * @return Returns the completeWhere. WITHOUT order by clause!!
756
     */
757
    abstract public String getCompleteWhere();
758

    
759
    /* (non-Javadoc)
760
     * @see com.iver.cit.gvsig.fmap.drivers.VectorialDriver#reLoad()
761
     */
762
    public void reload() throws IOException
763
    {
764
                try {
765
                    if ((conn == null) || (((ConnectionJDBC)conn).getConnection().isClosed()))
766
                    {
767
                            this.load();
768
                    }
769

    
770
                    ((ConnectionJDBC)conn).getConnection().commit();
771

    
772
                    setData(conn, lyrDef);
773
                } catch (SQLException e) {
774
                        throw new IOException(e.getMessage());
775
                } catch (DriverException e) {
776
                        throw new IOException(e.getMessage());
777
                } catch (DBException e) {
778
                        throw new IOException(e.getMessage());
779
                }
780

    
781
    }
782

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

    
799
//        public void setFlatness(double flatness) {
800
//                this.flatness = flatness;
801
//        }
802

    
803
    // -----------------------------------------------------------
804
    // ----  EXT JDBC NUEVA                           ---
805
    // -----------------------------------------------------------
806

    
807
    /**
808
     * Gets the drivers connection string given its parameters (this can be different for
809
     * different driver, so it should be overwritten in that case.)
810
     */
811
    public String getConnectionString(
812
                    String host,
813
                    String port,
814
                    String dbname,
815
                    String user,
816
                    String pw) {
817

    
818
                String resp = getConnectionStringBeginning() + "//" + host.toLowerCase();
819

    
820
                if (dbname.trim().length() > 0) {
821
                        resp += ":" + port;
822
                } else {
823
                        resp += ":" + getDefaultPort();
824
                }
825

    
826
                resp += "/" + dbname.toLowerCase();
827
                return resp;
828
    }
829

    
830
    /**
831
     * Gets available table names. Should be overwritten by subclasses if its
832
     * not compatible or if it can be refined
833
     *
834
     * @param conn connection object
835
     * @param catalog catalog name
836
     * @return array of strings with available table names
837
     * @throws SQLException
838
     */
839
    public String[] getTableNames(IConnection conn, String catalog) throws DBException {
840
            TreeMap ret = new TreeMap();
841
            try{
842
            DatabaseMetaData dbmd = ((ConnectionJDBC)conn).getConnection().getMetaData();
843
        String[] types = {"TABLE", "VIEW"};
844
                ResultSet rs = dbmd.getTables(catalog, null, null, types);
845
                while (rs.next()){
846
                        // ret.put(rs.getString("TABLE_NAME"), rs.getString("TABLE_NAME"));
847
                        // As suggested by Jorge Agudo, to allow charging tables from other schemas
848
                        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"));
849
                }
850
                rs.close();
851
            } catch (SQLException e) {
852
                        throw new DBException(e);
853
                }
854
                return (String[]) ret.keySet().toArray(new String[0]);
855
    }
856

    
857

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

    
873
                for (int i = 0; i < ret.length; i++) {
874
                        ret[i] = rsmd.getColumnName(i+1);
875
                }
876
                rs.close(); st.close();
877
            } catch (SQLException e) {
878
                    throw new DBException(e);
879
            }
880
                return ret;
881
    }
882

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

    
898
                for (int i = 0; i < ret.length; i++) {
899
                        ret[i] = rsmd.getColumnTypeName(i+1);
900
                }
901
                rs.close(); st.close();
902
            } catch (SQLException e) {
903
                        throw new DBException(e);
904
                }
905
                return ret;
906
    }
907

    
908
    /**
909
     * Gets the table's possible id fields. By default, all fields can be id.
910
     * It should be overwritten by subclasses.
911
     *
912
     * @param conn conenction object
913
     * @param table_name table name
914
     * @return the table's possible id fields
915
     * @throws SQLException
916
     */
917
    public String[] getIdFieldsCandidates(IConnection conn, String table_name) throws DBException {
918
            return getAllFields(conn, table_name);
919
    }
920

    
921
    /**
922
     * Gets the table's possible geometry fields. By default, all fields can be geometry
923
     * fields. It should be overwritten by subclasses.
924
     *
925
     * @param conn conenction object
926
     * @param table_name table name
927
     * @return the table's possible geometry fields
928
     * @throws SQLException
929
     */
930
    public String[] getGeometryFieldsCandidates(IConnection conn, String table_name) throws DBException {
931
            return getAllFields(conn, table_name);
932
    }
933

    
934
    /**
935
     * Tells if it's an empty table (with no records)
936
     * @param conn conenction object
937
     * @param tableName rtable name
938
     * @return whether it's an empty table (with no records) or not
939
     */
940
        public boolean isEmptyTable(IConnection conn, String tableName) {
941

    
942
                boolean res = true;
943

    
944
                try {
945
                        Statement st = ((ConnectionJDBC)conn).getConnection().createStatement();
946
                        ResultSet rs = null;
947
                        rs = st.executeQuery("select * from " + tableName + " LIMIT 1");
948
                        res = !rs.next();
949
                        rs.close(); st.close();
950
                } catch (Exception ex) {
951
                        res = true;
952
                }
953
                return res;
954
        }
955

    
956

    
957

    
958
        /**
959
         * Utility method to allow the driver to do something with the geometry field.
960
         * By default does nothing.
961
         *
962
         * @param flds user-selected fields
963
         * @param geomField geometry field
964
         * @return new user-selected fields
965
         */
966
        public String[] manageGeometryField(String[] flds, String geomField) {
967
                return flds;
968
        }
969

    
970
        /**
971
         * Empty method called when the layer is going to be removed from the view.
972
         * Subclasses can overwrite it if needed.
973
         *
974
         */
975
        public void remove() {
976

    
977
        }
978

    
979
        public void addDriverEventListener(DriverEventListener listener) {
980
                if (!driverEventListeners.contains(listener))
981
                        driverEventListeners.add(listener);
982

    
983
        }
984

    
985
        public void removeDriverEventListener(DriverEventListener listener) {
986
                driverEventListeners.remove(listener);
987

    
988
        }
989

    
990
        public void notifyDriverEndLoaded() {
991
                DriverEvent event = new DriverEvent(DriverEvent.DRIVER_EVENT_LOADING_END);
992
                for (int i=0; i < driverEventListeners.size(); i++)
993
                {
994
                        DriverEventListener aux = (DriverEventListener) driverEventListeners.get(i);
995
                        aux.driverNotification(event);
996
                }
997
        }
998

    
999
}