Statistics
| Revision:

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

History | View | Annotate | Download (30.6 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 *
19
 * For more information, contact:
20
 *
21
 *  Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib??ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *      +34 963862235
28
 *   gvsig@gva.es
29
 *      www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   IVER T.I. S.A
34
 *   Salamanca 50
35
 *   46005 Valencia
36
 *   Spain
37
 *
38
 *   +34 963163400
39
 *   dac@iver.es
40
 */
41
package com.iver.cit.gvsig.fmap.drivers;
42

    
43
import java.awt.geom.Rectangle2D;
44
import java.io.IOException;
45
import java.sql.Connection;
46
import java.sql.DatabaseMetaData;
47
import java.sql.Driver;
48
import java.sql.DriverManager;
49
import java.sql.ResultSet;
50
import java.sql.ResultSetMetaData;
51
import java.sql.SQLException;
52
import java.sql.Statement;
53
import java.sql.Types;
54
import java.util.ArrayList;
55
import java.util.Hashtable;
56
import java.util.TreeMap;
57

    
58
import org.apache.log4j.Logger;
59

    
60
import com.hardcode.driverManager.DriverEvent;
61
import com.hardcode.driverManager.DriverEventListener;
62
import com.hardcode.driverManager.IDelayedDriver;
63
import com.hardcode.gdbms.engine.data.DataSourceFactory;
64
import com.hardcode.gdbms.engine.data.driver.ObjectDriver;
65
import com.hardcode.gdbms.engine.values.Value;
66
import com.hardcode.gdbms.engine.values.ValueFactory;
67
import com.iver.cit.gvsig.fmap.DriverException;
68
import com.iver.cit.gvsig.fmap.DriverJdbcNotFoundExceptionType;
69
import com.iver.cit.gvsig.fmap.MapContext;
70
import com.iver.cit.gvsig.fmap.Messages;
71
import com.iver.cit.gvsig.fmap.SqlDriveExceptionType;
72
import com.iver.cit.gvsig.fmap.core.IFeature;
73
import com.iver.cit.gvsig.fmap.core.IGeometry;
74
import com.iver.cit.gvsig.fmap.drivers.jdbc.utils.ConnectionWithParams;
75
import com.iver.cit.gvsig.fmap.drivers.jdbc.utils.SingleJDBCConnectionManager;
76
import com.iver.cit.gvsig.fmap.layers.SelectableDataSource;
77
import com.iver.cit.gvsig.fmap.layers.XMLException;
78
import com.iver.utiles.XMLEntity;
79
import com.iver.utiles.swing.JPasswordDlg;
80

    
81

    
82

    
83
/**
84
 * Clase abstracta qu
85
 */
86
public abstract class DefaultDBDriver implements VectorialJDBCDriver, ObjectDriver {
87
    private static Logger logger = Logger.getLogger(SelectableDataSource.class.getName());
88
    protected static Hashtable poolPassw = new Hashtable();
89

    
90
    protected Connection conn;
91
    // protected String tableName;
92
    // protected String whereClause;
93
    // protected String fields;
94
    // protected String sqlOrig;
95
    protected DBLayerDefinition lyrDef = null;
96
    protected ResultSet rs;
97
    protected boolean bCursorActivo = false;
98
    protected Statement st;
99
    protected int numReg=-1;
100

    
101
    protected Rectangle2D fullExtent = null;
102

    
103
    // protected String strFID_FieldName;
104
    // protected String idFID_FieldName;
105

    
106
    protected Hashtable hashRelate;
107

    
108

    
109
    protected ResultSetMetaData metaData = null;
110
    protected Rectangle2D workingArea;
111
    protected String driverClass;
112
    protected String userName;
113
    protected String dbUrl;
114
    protected String className;
115
    protected String catalogName;
116
    protected String tableName;
117
    protected String[] fields;
118
    protected String FIDfield;
119
    protected String geometryField;
120
    protected String whereClause;
121
    protected String strSRID;
122
        //private double flatness;
123
        
124
    protected String host, port, dbName, connName;
125
    
126
    protected ArrayList driverEventListeners = new ArrayList();
127
    
128

    
129
    abstract public void setData(Connection conn, DBLayerDefinition lyrDef);
130

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

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

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

    
184

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

    
207
            return numReg;
208
        }
209

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

    
241
        }
242
        return fullExtent;
243
    }
244

    
245

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

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

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

    
351

    
352
        }
353

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

    
372
    }
373

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

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

    
413
    public void close() {
414
    }
415

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

    
427

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

    
447
    }
448

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

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

    
476
        className = xml.getStringProperty("className");
477
        
478
        catalogName = xml.getStringProperty("catalog");
479
        userName =xml.getStringProperty("username");
480
        driverClass =xml.getStringProperty("driverclass");
481
        tableName = xml.getStringProperty("tablename");
482
        fields = xml.getStringArrayProperty("fields");
483
        FIDfield = xml.getStringProperty("FID");
484
        geometryField = xml.getStringProperty("THE_GEOM");
485
        whereClause = xml.getStringProperty("whereclause");
486
        strSRID = xml.getStringProperty("SRID");
487

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

    
511
        DBLayerDefinition lyrDef = new DBLayerDefinition();
512
        lyrDef.setCatalogName(catalogName);
513
        lyrDef.setTableName(tableName);
514
        lyrDef.setFieldNames(fields);
515
        lyrDef.setFieldID(FIDfield);
516
        lyrDef.setFieldGeometry(geometryField);
517
        lyrDef.setWhereClause(whereClause);
518
        // lyrDef.setClassToInstantiate(driverClass);
519
        if (workingArea != null)
520
            lyrDef.setWorkingArea(workingArea);
521

    
522
        lyrDef.setSRID_EPSG(strSRID);
523

    
524
        setLyrDef(lyrDef);
525

    
526
    }
527

    
528
    private void extractParamsFromDbUrl(String dbUrl2) {
529
            //jdbc:postgres://localhost:5431/latin1
530
            int iDbName = dbUrl2.lastIndexOf('/');
531
                dbName = dbUrl2.substring(iDbName+1);
532
                int iLast2points = dbUrl2.lastIndexOf(':');
533
                port = dbUrl2.substring(iLast2points+1, iDbName);
534
                int iHost = dbUrl2.indexOf("//");
535
                host = dbUrl2.substring(iHost + 2, iLast2points);
536
                connName = dbUrl2;
537
        }
538

    
539
        public void load() throws DriverException {
540
            try {
541
            if (driverClass != null)
542
                    Class.forName(driverClass);
543
            
544
            String _drvName = getName();
545

    
546
            String keyPool = _drvName.toLowerCase() + "_" + host.toLowerCase()
547
            + "_" + port + "_" + dbName.toLowerCase()
548
            + "_" + userName.toLowerCase();
549
            
550
            Connection newConn = null;
551
            String clave = null;
552
            ConnectionWithParams cwp = null;
553
            
554
            if (poolPassw.containsKey(keyPool)) {
555
                    
556
                clave = (String) poolPassw.get(keyPool);
557
                cwp = SingleJDBCConnectionManager.instance().getConnection(
558
                                         _drvName, userName, clave, connName,
559
                                         host, port, dbName, true);
560

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

    
595
            newConn = cwp.getConnection();
596
            newConn.setAutoCommit(false);
597

    
598
            DBLayerDefinition lyrDef = new DBLayerDefinition();
599
            if (getLyrDef() == null) {
600
                    lyrDef.setCatalogName(catalogName);
601
                    lyrDef.setTableName(tableName);
602
                    lyrDef.setFieldNames(fields);
603
                    lyrDef.setFieldID(FIDfield);
604
                    lyrDef.setFieldGeometry(geometryField);
605
                    lyrDef.setWhereClause(whereClause);
606
                    // lyrDef.setClassToInstantiate(driverClass);
607
                    if (workingArea != null)
608
                        lyrDef.setWorkingArea(workingArea);
609

    
610
                    lyrDef.setSRID_EPSG(strSRID);
611
            } else {
612
                    lyrDef = getLyrDef();
613
            }
614

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

    
651
            Driver drv = DriverManager.getDriver(metadata.getURL());
652
            // System.out.println(drv.getClass().getName());
653
            xml.putProperty("driverclass", drv.getClass().getName());
654

    
655
            xml.putProperty("tablename", getTableName());
656
            xml.putProperty("fields", lyrDef.getFieldNames());
657
            xml.putProperty("FID", lyrDef.getFieldID());
658
            xml.putProperty("THE_GEOM", lyrDef.getFieldGeometry());
659
            xml.putProperty("whereclause", getWhereClause());
660
            xml.putProperty("SRID", lyrDef.getSRID_EPSG());
661

    
662
            ConnectionWithParams cwp =
663
                    SingleJDBCConnectionManager.instance().findConnection(getConnection());
664

    
665
            xml.putProperty("host", cwp.getHost());
666
            xml.putProperty("port", cwp.getPort());
667
            xml.putProperty("dbName", cwp.getDb());
668
            xml.putProperty("connName", cwp.getName());
669

    
670
            if (getWorkingArea() != null)
671
            {
672
                xml.putProperty("minXworkArea", getWorkingArea().getMinX());
673
                xml.putProperty("minYworkArea", getWorkingArea().getMinY());
674
                xml.putProperty("HworkArea", getWorkingArea().getHeight());
675
                xml.putProperty("WworkArea", getWorkingArea().getWidth());
676
            }
677

    
678
        } catch (SQLException e) {
679
            // TODO Auto-generated catch block
680
            e.printStackTrace();
681
        }
682

    
683

    
684
        return xml;
685

    
686
    }
687

    
688
    /**
689
     * @see com.iver.cit.gvsig.fmap.drivers.VectorialJDBCDriver#setWorkingArea(java.awt.geom.Rectangle2D)
690
     */
691
    public void setWorkingArea(Rectangle2D rect) {
692
        this.workingArea = rect;
693
    }
694

    
695
    /**
696
     * @see com.iver.cit.gvsig.fmap.drivers.VectorialJDBCDriver#getWorkingArea()
697
     */
698
    public Rectangle2D getWorkingArea() {
699
        return workingArea;
700
    }
701

    
702
    /* (non-Javadoc)
703
     * @see com.hardcode.gdbms.engine.data.driver.GDBMSDriver#setDataSourceFactory(com.hardcode.gdbms.engine.data.DataSourceFactory)
704
     */
705
    public void setDataSourceFactory(DataSourceFactory arg0) {
706
        // TODO Auto-generated method stub
707

    
708
    }
709

    
710
    /**
711
     * @return Returns the lyrDef.
712
     */
713
    public DBLayerDefinition getLyrDef() {
714
        return lyrDef;
715
    }
716

    
717
    /**
718
     * @param lyrDef The lyrDef to set.
719
     */
720
    public void setLyrDef(DBLayerDefinition lyrDef) {
721
        this.lyrDef = lyrDef;
722
    }
723

    
724
    abstract public String getSqlTotal();
725

    
726
    /**
727
     * @return Returns the completeWhere. WITHOUT order by clause!!
728
     */
729
    abstract public String getCompleteWhere();
730

    
731
    /* (non-Javadoc)
732
     * @see com.iver.cit.gvsig.fmap.drivers.VectorialDriver#reLoad()
733
     */
734
    public void reload() throws IOException
735
    {
736
                try {
737
                    if ((conn == null) || (conn.isClosed()))
738
                    {
739
                            this.load();
740
                    }
741

    
742
                        conn.commit();
743

    
744
                    setData(conn, lyrDef);
745
                } catch (SQLException e) {
746
                        throw new IOException(e.getMessage());
747
                } catch (DriverException e) {
748
                        throw new IOException(e.getMessage());
749
                }
750

    
751
    }
752

    
753
    public int getFieldWidth(int fieldId)
754
    {
755
            int i = -1;
756
            try {
757
                    int aux = fieldId + 2; // idField viene basado en 1, y
758
                        i = rs.getMetaData().getColumnDisplaySize(aux);
759
                } catch (SQLException e) {
760
                        e.printStackTrace();
761
                }
762
                // SUN define que getColumnDisplaySize devuelve numeros negativos cuando el campo es de tipo Text o Vartext
763
                // sin ancho. Nosotros vamos a devolver 255 para que fucione, por lo menos al exportar a DBF.
764
                // Nota: Si se truncan cadenas, este es el sitio que lo provoca.
765
                if (i <0) i=255;
766
                return i;
767
    }
768

    
769
//        public void setFlatness(double flatness) {
770
//                this.flatness = flatness;
771
//        }
772
    
773
    // -----------------------------------------------------------
774
    // ----  EXT JDBC NUEVA                           ---
775
    // -----------------------------------------------------------
776
    
777
    /**
778
     * Gets the drivers connection string given its parameters (this can be different for
779
     * different driver, so it should be overwritten in that case.)
780
     */
781
    public String getConnectionString(
782
                    String host,
783
                    String port,
784
                    String dbname,
785
                    String user,
786
                    String pw) {
787
            
788
                String resp = getConnectionStringBeginning() + "//" + host.toLowerCase();
789

    
790
                if (dbname.trim().length() > 0) {
791
                        resp += ":" + port;
792
                } else {
793
                        resp += ":" + getDefaultPort();
794
                }
795

    
796
                resp += "/" + dbname.toLowerCase();
797
                return resp;
798
    }
799
    
800
    /**
801
     * Gets available table names. Should be overwritten by subclasses if its
802
     * not compatible or if it can be refined
803
     * 
804
     * @param conn connection object
805
     * @param catalog catalog name
806
     * @return array of strings with available table names
807
     * @throws SQLException
808
     */
809
    public String[] getTableNames(Connection conn, String catalog) throws SQLException {
810
            
811
            DatabaseMetaData dbmd = conn.getMetaData();
812
        String[] types = {"TABLE", "VIEW"};
813
                ResultSet rs = dbmd.getTables(catalog, null, null, types);
814
                TreeMap ret = new TreeMap();
815
                while (rs.next()){
816
                        ret.put(rs.getString("TABLE_NAME"), rs.getString("TABLE_NAME"));
817
                }
818
                rs.close();
819
                return (String[]) ret.keySet().toArray(new String[0]);
820
    }
821
    
822

    
823
    /**
824
     *       Gets all field names of a given table
825
     * @param conn connection object
826
     * @param table_name table name
827
     * @return all field names of the given table
828
     * @throws SQLException
829
     */
830
    public String[] getAllFields(Connection conn, String table_name) throws SQLException {
831
            
832
                Statement st = conn.createStatement();
833
                ResultSet rs = st.executeQuery("select * from " + table_name + " LIMIT 1");
834
                ResultSetMetaData rsmd = rs.getMetaData();
835
                String[] ret = new String[rsmd.getColumnCount()];
836

    
837
                for (int i = 0; i < ret.length; i++) {
838
                        ret[i] = rsmd.getColumnName(i+1);
839
                }
840
                rs.close(); st.close();
841
                return ret;
842
    }
843

    
844
    /**
845
     *       Gets all field type names of a given table
846
     * @param conn connection object
847
     * @param table_name table name
848
     * @return all field type names of the given table
849
     * @throws SQLException
850
     */
851
    public String[] getAllFieldTypeNames(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.getColumnTypeName(i+1);
860
                }
861
                rs.close(); st.close();
862
                return ret;
863
    }
864

    
865
    /**
866
     * Gets the table's possible id fields. By default, all fields can be id. 
867
     * It should be overwritten by subclasses.
868
     * 
869
     * @param conn conenction object
870
     * @param table_name table name
871
     * @return the table's possible id fields
872
     * @throws SQLException
873
     */
874
    public String[] getIdFieldsCandidates(Connection conn, String table_name) throws SQLException {
875
            return getAllFields(conn, table_name);
876
    }
877
    
878
    /**
879
     * Gets the table's possible geometry fields. By default, all fields can be geometry
880
     * fields. It should be overwritten by subclasses.
881
     * 
882
     * @param conn conenction object
883
     * @param table_name table name
884
     * @return the table's possible geometry fields
885
     * @throws SQLException
886
     */
887
    public String[] getGeometryFieldsCandidates(Connection conn, String table_name) throws SQLException {
888
            return getAllFields(conn, table_name);
889
    }
890
    
891
    /**
892
     * Tells if it's an empty table (with no records)
893
     * @param conn conenction object
894
     * @param tableName rtable name
895
     * @return whether it's an empty table (with no records) or not
896
     */
897
        public boolean isEmptyTable(Connection conn, String tableName) {
898
                
899
                boolean res = true;
900

    
901
                try {
902
                        Statement st = conn.createStatement();
903
                        ResultSet rs = null;
904
                        rs = st.executeQuery("select * from " + tableName + " LIMIT 1");
905
                        res = !rs.next();
906
                        rs.close(); st.close();
907
                } catch (Exception ex) {
908
                        res = true;
909
                }
910
                return res;
911
        }
912

    
913

    
914

    
915
        /**
916
         * Utility method to allow the driver to do something with the geometry field.
917
         * By default does nothing.
918
         * 
919
         * @param flds user-selected fields
920
         * @param geomField geometry field
921
         * @return new user-selected fields
922
         */
923
        public String[] manageGeometryField(String[] flds, String geomField) {
924
                return flds;
925
        }
926
        
927
        /**
928
         * Empty method called when the layer is going to be removed from the view.
929
         * Subclasses can overwrite it if needed.
930
         *
931
         */
932
        public void remove() {
933
                
934
        }
935

    
936
        public void addDriverEventListener(DriverEventListener listener) {
937
                if (!driverEventListeners.contains(listener))
938
                        driverEventListeners.add(listener);
939
                
940
        }
941

    
942
        public void removeDriverEventListener(DriverEventListener listener) {
943
                driverEventListeners.remove(listener);
944
                
945
        }
946
        
947
        public void notifyDriverEndLoaded() {
948
                DriverEvent event = new DriverEvent(DriverEvent.DRIVER_EVENT_LOADING_END);
949
                for (int i=0; i < driverEventListeners.size(); i++)
950
                {
951
                        DriverEventListener aux = (DriverEventListener) driverEventListeners.get(i);
952
                        aux.driverNotification(event);
953
                }
954
        }
955
    
956
}