Statistics
| Revision:

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

History | View | Annotate | Download (29.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.gdbms.engine.data.DataSourceFactory;
61
import com.hardcode.gdbms.engine.data.driver.ObjectDriver;
62
import com.hardcode.gdbms.engine.values.Value;
63
import com.hardcode.gdbms.engine.values.ValueFactory;
64
import com.iver.cit.gvsig.fmap.DriverException;
65
import com.iver.cit.gvsig.fmap.DriverJdbcNotFoundExceptionType;
66
import com.iver.cit.gvsig.fmap.MapContext;
67
import com.iver.cit.gvsig.fmap.Messages;
68
import com.iver.cit.gvsig.fmap.SqlDriveExceptionType;
69
import com.iver.cit.gvsig.fmap.core.IFeature;
70
import com.iver.cit.gvsig.fmap.core.IGeometry;
71
import com.iver.cit.gvsig.fmap.drivers.jdbc.utils.ConnectionWithParams;
72
import com.iver.cit.gvsig.fmap.drivers.jdbc.utils.SingleJDBCConnectionManager;
73
import com.iver.cit.gvsig.fmap.layers.SelectableDataSource;
74
import com.iver.cit.gvsig.fmap.layers.XMLException;
75
import com.iver.utiles.XMLEntity;
76
import com.iver.utiles.swing.JPasswordDlg;
77

    
78

    
79

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

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

    
98
    protected Rectangle2D fullExtent = null;
99

    
100
    // protected String strFID_FieldName;
101
    // protected String idFID_FieldName;
102

    
103
    protected Hashtable hashRelate;
104

    
105

    
106
    protected ResultSetMetaData metaData = null;
107
    protected Rectangle2D workingArea;
108
    protected String driverClass;
109
    protected String userName;
110
    protected String dbUrl;
111
    protected String className;
112
    protected String catalogName;
113
    protected String tableName;
114
    protected String[] fields;
115
    protected String FIDfield;
116
    protected String geometryField;
117
    protected String whereClause;
118
    protected String strSRID;
119
        //private double flatness;
120
        
121
    protected String host, port, dbName, connName;
122
    
123

    
124
    abstract public void setData(Connection conn, DBLayerDefinition lyrDef);
125

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

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

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

    
179

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

    
202
            return numReg;
203
        }
204

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

    
236
        }
237
        return fullExtent;
238
    }
239

    
240

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

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

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

    
346

    
347
        }
348

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

    
367
    }
368

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

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

    
408
    public void close() {
409
    }
410

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

    
422

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

    
442
    }
443

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

    
465
    /* (non-Javadoc)
466
     * @see com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver#setXMLEntity(com.iver.utiles.XMLEntity)
467
     */
468
    public void setXMLEntity(XMLEntity xml) throws XMLException
469
    {
470

    
471
        className = xml.getStringProperty("className");
472
        
473
        catalogName = xml.getStringProperty("catalog");
474
        userName =xml.getStringProperty("username");
475
        driverClass =xml.getStringProperty("driverclass");
476
        tableName = xml.getStringProperty("tablename");
477
        fields = xml.getStringArrayProperty("fields");
478
        FIDfield = xml.getStringProperty("FID");
479
        geometryField = xml.getStringProperty("THE_GEOM");
480
        whereClause = xml.getStringProperty("whereclause");
481
        strSRID = xml.getStringProperty("SRID");
482

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

    
506
        DBLayerDefinition lyrDef = new DBLayerDefinition();
507
        lyrDef.setCatalogName(catalogName);
508
        lyrDef.setTableName(tableName);
509
        lyrDef.setFieldNames(fields);
510
        lyrDef.setFieldID(FIDfield);
511
        lyrDef.setFieldGeometry(geometryField);
512
        lyrDef.setWhereClause(whereClause);
513
        // lyrDef.setClassToInstantiate(driverClass);
514
        if (workingArea != null)
515
            lyrDef.setWorkingArea(workingArea);
516

    
517
        lyrDef.setSRID_EPSG(strSRID);
518

    
519
        setLyrDef(lyrDef);
520

    
521
    }
522

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

    
534
        public void load() throws DriverException {
535
            try {
536
            Class.forName(driverClass);
537
            
538
            String _drvName = getName();
539

    
540
            String keyPool = _drvName.toLowerCase() + "_" + host.toLowerCase()
541
            + "_" + port + "_" + dbName.toLowerCase()
542
            + "_" + userName.toLowerCase();
543
            
544
            Connection newConn = null;
545
            String clave = null;
546
            ConnectionWithParams cwp = null;
547
            
548
            if (poolPassw.containsKey(keyPool)) {
549
                    
550
                clave = (String) poolPassw.get(keyPool);
551
                cwp = SingleJDBCConnectionManager.instance().getConnection(
552
                                         _drvName, userName, clave, connName,
553
                                         host, port, dbName, true);
554

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

    
589
            newConn = cwp.getConnection();
590
            newConn.setAutoCommit(false);
591

    
592
            DBLayerDefinition lyrDef = new DBLayerDefinition();
593
            if (getLyrDef() == null) {
594
                    lyrDef.setCatalogName(catalogName);
595
                    lyrDef.setTableName(tableName);
596
                    lyrDef.setFieldNames(fields);
597
                    lyrDef.setFieldID(FIDfield);
598
                    lyrDef.setFieldGeometry(geometryField);
599
                    lyrDef.setWhereClause(whereClause);
600
                    // lyrDef.setClassToInstantiate(driverClass);
601
                    if (workingArea != null)
602
                        lyrDef.setWorkingArea(workingArea);
603

    
604
                    lyrDef.setSRID_EPSG(strSRID);
605
            } else {
606
                    lyrDef = getLyrDef();
607
            }
608

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

    
645
            Driver drv = DriverManager.getDriver(metadata.getURL());
646
            // System.out.println(drv.getClass().getName());
647
            xml.putProperty("driverclass", drv.getClass().getName());
648

    
649
            xml.putProperty("tablename", getTableName());
650
            xml.putProperty("fields", lyrDef.getFieldNames());
651
            xml.putProperty("FID", lyrDef.getFieldID());
652
            xml.putProperty("THE_GEOM", lyrDef.getFieldGeometry());
653
            xml.putProperty("whereclause", getWhereClause());
654
            xml.putProperty("SRID", lyrDef.getSRID_EPSG());
655

    
656
            ConnectionWithParams cwp =
657
                    SingleJDBCConnectionManager.instance().findConnection(getConnection());
658

    
659
            xml.putProperty("host", cwp.getHost());
660
            xml.putProperty("port", cwp.getPort());
661
            xml.putProperty("dbName", cwp.getDb());
662
            xml.putProperty("connName", cwp.getName());
663

    
664
            if (getWorkingArea() != null)
665
            {
666
                xml.putProperty("minXworkArea", getWorkingArea().getMinX());
667
                xml.putProperty("minYworkArea", getWorkingArea().getMinY());
668
                xml.putProperty("HworkArea", getWorkingArea().getHeight());
669
                xml.putProperty("WworkArea", getWorkingArea().getWidth());
670
            }
671

    
672
        } catch (SQLException e) {
673
            // TODO Auto-generated catch block
674
            e.printStackTrace();
675
        }
676

    
677

    
678
        return xml;
679

    
680
    }
681

    
682
    /**
683
     * @see com.iver.cit.gvsig.fmap.drivers.VectorialJDBCDriver#setWorkingArea(java.awt.geom.Rectangle2D)
684
     */
685
    public void setWorkingArea(Rectangle2D rect) {
686
        this.workingArea = rect;
687
    }
688

    
689
    /**
690
     * @see com.iver.cit.gvsig.fmap.drivers.VectorialJDBCDriver#getWorkingArea()
691
     */
692
    public Rectangle2D getWorkingArea() {
693
        return workingArea;
694
    }
695

    
696
    /* (non-Javadoc)
697
     * @see com.hardcode.gdbms.engine.data.driver.GDBMSDriver#setDataSourceFactory(com.hardcode.gdbms.engine.data.DataSourceFactory)
698
     */
699
    public void setDataSourceFactory(DataSourceFactory arg0) {
700
        // TODO Auto-generated method stub
701

    
702
    }
703

    
704
    /**
705
     * @return Returns the lyrDef.
706
     */
707
    public DBLayerDefinition getLyrDef() {
708
        return lyrDef;
709
    }
710

    
711
    /**
712
     * @param lyrDef The lyrDef to set.
713
     */
714
    public void setLyrDef(DBLayerDefinition lyrDef) {
715
        this.lyrDef = lyrDef;
716
    }
717

    
718
    abstract public String getSqlTotal();
719

    
720
    /**
721
     * @return Returns the completeWhere. WITHOUT order by clause!!
722
     */
723
    abstract public String getCompleteWhere();
724

    
725
    /* (non-Javadoc)
726
     * @see com.iver.cit.gvsig.fmap.drivers.VectorialDriver#reLoad()
727
     */
728
    public void reload() throws IOException
729
    {
730
                try {
731
                    if (conn == null) this.load();
732

    
733
                        conn.commit();
734

    
735
                    setData(conn, lyrDef);
736
                } catch (SQLException e) {
737
                        throw new IOException(e.getMessage());
738
                } catch (DriverException e) {
739
                        throw new IOException(e.getMessage());
740
                }
741

    
742
    }
743

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

    
760
//        public void setFlatness(double flatness) {
761
//                this.flatness = flatness;
762
//        }
763
    
764
    // -----------------------------------------------------------
765
    // ----  EXT JDBC NUEVA                           ---
766
    // -----------------------------------------------------------
767
    
768
    /**
769
     * Gets the drivers connection string given its parameters (this can be different for
770
     * different driver, so it should be overwritten in that case.)
771
     */
772
    public String getConnectionString(
773
                    String host,
774
                    String port,
775
                    String dbname,
776
                    String user,
777
                    String pw) {
778
            
779
                String resp = getConnectionStringBeginning() + "//" + host.toLowerCase();
780

    
781
                if (dbname.trim().length() > 0) {
782
                        resp += ":" + port;
783
                } else {
784
                        resp += ":" + getDefaultPort();
785
                }
786

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

    
814
    /**
815
     *       Gets all field names of a given table
816
     * @param conn connection object
817
     * @param table_name table name
818
     * @return all field names of the given table
819
     * @throws SQLException
820
     */
821
    public String[] getAllFields(Connection conn, String table_name) throws SQLException {
822
            
823
                Statement st = conn.createStatement();
824
                ResultSet rs = st.executeQuery("select * from " + table_name + " LIMIT 1");
825
                ResultSetMetaData rsmd = rs.getMetaData();
826
                String[] ret = new String[rsmd.getColumnCount()];
827

    
828
                for (int i = 0; i < ret.length; i++) {
829
                        ret[i] = rsmd.getColumnName(i+1);
830
                }
831
                rs.close(); st.close();
832
                return ret;
833
    }
834

    
835
    /**
836
     *       Gets all field type names of a given table
837
     * @param conn connection object
838
     * @param table_name table name
839
     * @return all field type names of the given table
840
     * @throws SQLException
841
     */
842
    public String[] getAllFieldTypeNames(Connection conn, String table_name) throws SQLException {
843
            
844
                Statement st = conn.createStatement();
845
                ResultSet rs = st.executeQuery("select * from " + table_name + " LIMIT 1");
846
                ResultSetMetaData rsmd = rs.getMetaData();
847
                String[] ret = new String[rsmd.getColumnCount()];
848

    
849
                for (int i = 0; i < ret.length; i++) {
850
                        ret[i] = rsmd.getColumnTypeName(i+1);
851
                }
852
                rs.close(); st.close();
853
                return ret;
854
    }
855

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

    
892
                try {
893
                        Statement st = conn.createStatement();
894
                        ResultSet rs = null;
895
                        rs = st.executeQuery("select * from " + tableName + " LIMIT 1");
896
                        res = !rs.next();
897
                        rs.close(); st.close();
898
                } catch (Exception ex) {
899
                        res = true;
900
                }
901
                return res;
902
        }
903

    
904

    
905

    
906
        /**
907
         * Utility method to allow the driver to do something with the geometry field.
908
         * By default does nothing.
909
         * 
910
         * @param flds user-selected fields
911
         * @param geomField geometry field
912
         * @return new user-selected fields
913
         */
914
        public String[] manageGeometryField(String[] flds, String geomField) {
915
                return flds;
916
        }
917
        
918
        /**
919
         * Empty method called when the layer is going to be removed from the view.
920
         * Subclasses can overwrite it if needed.
921
         *
922
         */
923
        public void remove() {
924
                
925
        }
926

    
927
    
928
    
929
}