Revision 10627 trunk/libraries/libFMap/src/com/iver/cit/gvsig/fmap/drivers/DefaultDBDriver.java

View differences:

DefaultDBDriver.java
41 41
package com.iver.cit.gvsig.fmap.drivers;
42 42

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

  
58 56
import org.apache.log4j.Logger;
59 57

  
58
import com.hardcode.gdbms.driver.exceptions.BadFieldDriverException;
59
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
60
import com.hardcode.gdbms.driver.exceptions.ReloadDriverException;
60 61
import com.hardcode.gdbms.engine.data.DataSourceFactory;
62
import com.hardcode.gdbms.engine.data.driver.DriverException;
61 63
import com.hardcode.gdbms.engine.data.driver.ObjectDriver;
62 64
import com.hardcode.gdbms.engine.values.Value;
63 65
import com.hardcode.gdbms.engine.values.ValueFactory;
64
import com.iver.cit.gvsig.fmap.DriverException;
66
import com.iver.cit.gvsig.exceptions.expansionfile.ExpansionFileReadException;
65 67
import com.iver.cit.gvsig.fmap.DriverJdbcNotFoundExceptionType;
66 68
import com.iver.cit.gvsig.fmap.MapContext;
67 69
import com.iver.cit.gvsig.fmap.Messages;
68
import com.iver.cit.gvsig.fmap.SqlDriveExceptionType;
69 70
import com.iver.cit.gvsig.fmap.core.IFeature;
70 71
import com.iver.cit.gvsig.fmap.core.IGeometry;
71 72
import com.iver.cit.gvsig.fmap.drivers.jdbc.utils.ConnectionWithParams;
......
117 118
    protected String whereClause;
118 119
    protected String strSRID;
119 120
	//private double flatness;
120
	
121

  
121 122
    protected String host, port, dbName, connName;
122
    
123

  
123 124
    private MapContext mapContext = null;
124 125

  
125 126
    abstract public void setData(Connection conn, DBLayerDefinition lyrDef);
......
183 184
	 * @throws DriverException
184 185
	 * @see com.iver.cit.gvsig.fmap.layers.ReadableVectorial#getShapeCount()
185 186
	 */
186
	public int getShapeCount() throws IOException {
187
	public int getShapeCount() throws ReadDriverException {
187 188
	    	if (numReg == -1)
188 189
	    	{
189 190
	    	    try
......
196 197
	            }
197 198
	    	    catch (SQLException e)
198 199
	    	    {
199
	    	        throw new IOException(e.getMessage());
200
	    	        throw new ReadDriverException(getName(),e);
200 201
	    	    }
201 202
	    	}
202 203

  
......
204 205
	}
205 206

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

  
237 232
        }
238 233
        return fullExtent;
239 234
    }
......
259 254
		return lyrDef.getShapeType();
260 255
	}
261 256

  
262
	public int getFieldType(int idField) throws com.hardcode.gdbms.engine.data.driver.DriverException
263
	{
257
	public int getFieldType(int idField) throws ReadDriverException{
264 258
	    String str = "";
265 259
	    try {
266 260
	        int i = idField + 2; // idField viene basado en 1, y
......
277 271
		    if (metaData.getColumnType(i) == Types.SMALLINT)
278 272
		        return Types.SMALLINT;
279 273
		    if (metaData.getColumnType(i) == Types.TINYINT)
280
		        return Types.TINYINT;		    
274
		        return Types.TINYINT;
281 275
		    if (metaData.getColumnType(i) == Types.BIGINT)
282 276
		        return Types.BIGINT;
283 277
		    if (metaData.getColumnType(i) == Types.BIT)
......
296 290
                return Types.TIMESTAMP;
297 291

  
298 292
	    } catch (SQLException e) {
299
	    	throw new com.hardcode.gdbms.engine.data.driver.DriverException(e);
293
	    	throw new BadFieldDriverException(getName(),e,String.valueOf(idField));
300 294
    	}
301 295
	    return Types.OTHER;
302 296
        // throw new com.hardcode.gdbms.engine.data.driver.DriverException("Tipo no soportado: " + str);
......
315 309
     * @throws DriverException Si se produce un error accediendo al DataSource
316 310
     */
317 311
    public Value getFieldValue(long rowIndex, int idField)
318
        throws com.hardcode.gdbms.engine.data.driver.DriverException
312
        throws ReadDriverException
319 313
        {
320 314
        	int i = (int) (rowIndex + 1);
321 315
        	int fieldId = idField+2;
......
340 334
    		    if (metaData.getColumnType(fieldId) == Types.DATE)
341 335
    		        return ValueFactory.createValue(rs.getDate(fieldId));
342 336
    	    } catch (SQLException e) {
343
                throw new com.hardcode.gdbms.engine.data.driver.DriverException("Tipo no soportado: columna " + fieldId );
337
                throw new BadFieldDriverException(getName(),e,String.valueOf(fieldId));
344 338
        	}
345 339
        	return null;
346 340

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

  
368 362
    }
......
378 372
     * @throws DriverException Si se produce alg?n error accediendo al
379 373
     *         DataSource
380 374
     */
381
    public String getFieldName(int fieldId) throws com.hardcode.gdbms.engine.data.driver.DriverException
375
    public String getFieldName(int fieldId) throws ReadDriverException
382 376
    {
383 377
        try {
384 378
            return rs.getMetaData().getColumnName(fieldId+2);
385 379
        } catch (SQLException e) {
386
            throw new com.hardcode.gdbms.engine.data.driver.DriverException(e);
380
            throw new ReadDriverException(getName(),e);
387 381
        }
388 382
    }
389 383

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

  
409 397
    public void close() {
......
512 500

  
513 501
    }
514 502

  
515
    public void load() throws DriverException {
503
    public void load() throws ReadDriverException {
516 504
    	try {
517 505
            Class.forName(driverClass);
518
            
506

  
519 507
            String _drvName = getName();
520 508

  
521 509
            String keyPool = _drvName.toLowerCase() + "_" + host.toLowerCase()
522 510
            + "_" + port + "_" + dbName.toLowerCase()
523 511
            + "_" + userName.toLowerCase();
524
            
512

  
525 513
            Connection newConn = null;
526 514
            String clave = null;
527 515
            ConnectionWithParams cwp = null;
528
            
516

  
529 517
            if (poolPassw.containsKey(keyPool)) {
530
            	
518

  
531 519
                clave = (String) poolPassw.get(keyPool);
532 520
                cwp = SingleJDBCConnectionManager.instance().getConnection(
533 521
 					_drvName, userName, clave, connName,
534 522
 					host, port, dbName, true);
535 523

  
536 524
            } else {
537
            	
525

  
538 526
                cwp = SingleJDBCConnectionManager.instance().getConnection(
539 527
     					_drvName, userName, null, connName,
540 528
     					host, port, dbName, false);
541
                
529

  
542 530
                if (cwp.isConnected()) {
543
                	
531

  
544 532
                	poolPassw.put(keyPool, cwp.getPw());
545
                	
533

  
546 534
                } else {
547
                	
535

  
548 536
                    JPasswordDlg dlg = new JPasswordDlg();
549 537
                    String strMessage = Messages.getString("conectar_jdbc");
550 538
                    String strPassword = Messages.getString("password");
......
562 550
                    if (clave == null)
563 551
                        return;
564 552
                    poolPassw.put(keyPool, clave);
565
                    
553

  
566 554
                    cwp.connect(clave);
567 555
                }
568 556
            }
......
589 577

  
590 578
            setData(newConn, lyrDef);
591 579
        } catch (ClassNotFoundException e) {
592
            logger.debug(e);
593
            DriverJdbcNotFoundExceptionType type =
594
            	new DriverJdbcNotFoundExceptionType();
595
            type.setDriverJdbcClassName(driverClass);
596
            type.setLayerName(this.getTableName());
597
            throw new DriverException("Driver JDBC no encontrado", e,  type);
580
//            logger.debug(e);
581
//            DriverJdbcNotFoundExceptionType type =
582
//            	new DriverJdbcNotFoundExceptionType();
583
//            type.setDriverJdbcClassName(driverClass);
584
//            type.setLayerName(this.getTableName());
585
            throw new ReadDriverException(getName(),e);
598 586
        } catch (SQLException e) {
599
        	
600
        	throw new DriverException(e.getMessage());
601
        	
587
        	throw new ReadDriverException(getName(),e);
588

  
602 589
		}
603 590
    }
604 591
    /* (non-Javadoc)
......
611 598
        try {
612 599
            DatabaseMetaData metadata = getConnection().getMetaData();
613 600
            xml.putProperty("catalog", getLyrDef().getCatalogName());
614
            
601

  
615 602
            // TODO: NO DEBEMOS GUARDAR EL NOMBRE DE USUARIO Y CONTRASE?A
616 603
            // AQUI. Hay que utilizar un pool de conexiones
617 604
            // y pedir al usuario que conecte a la base de datos
......
706 693
    /* (non-Javadoc)
707 694
     * @see com.iver.cit.gvsig.fmap.drivers.VectorialDriver#reLoad()
708 695
     */
709
    public void reload() throws IOException
696
    public void reload() throws ReloadDriverException
710 697
    {
711 698
		try {
712 699
	    	if (conn == null) this.load();
......
715 702

  
716 703
	    	setData(conn, lyrDef);
717 704
		} catch (SQLException e) {
718
			throw new IOException(e.getMessage());
719
		} catch (DriverException e) {
720
			throw new IOException(e.getMessage());
705
			throw new ReloadDriverException(getName(),e);
706
		} catch (ReadDriverException e) {
707
			throw new ReloadDriverException(getName(),e);
721 708
		}
722 709

  
723 710
    }
......
741 728
//	public void setFlatness(double flatness) {
742 729
//		this.flatness = flatness;
743 730
//	}
744
    
731

  
745 732
    // -----------------------------------------------------------
746 733
    // ----  EXT JDBC NUEVA                           ---
747 734
    // -----------------------------------------------------------
748
    
735

  
749 736
    /**
750 737
     * Gets the drivers connection string given its parameters (this can be different for
751 738
     * different driver, so it should be overwritten in that case.)
......
756 743
    		String dbname,
757 744
    		String user,
758 745
    		String pw) {
759
    	
746

  
760 747
		String resp = getConnectionStringBeginning() + "//" + host.toLowerCase();
761 748

  
762 749
		if (dbname.trim().length() > 0) {
......
768 755
		resp += "/" + dbname.toLowerCase();
769 756
		return resp;
770 757
    }
771
    
758

  
772 759
    /**
773 760
     * Gets available table names. Should be overwritten by subclasses if its
774 761
     * not compatible or if it can be refined
775
     * 
762
     *
776 763
     * @param conn connection object
777 764
     * @param catalog catalog name
778 765
     * @return array of strings with available table names
779 766
     * @throws SQLException
780 767
     */
781 768
    public String[] getTableNames(Connection conn, String catalog) throws SQLException {
782
    	
769

  
783 770
    	DatabaseMetaData dbmd = conn.getMetaData();
784 771
        String[] types = {"TABLE", "VIEW"};
785 772
		ResultSet rs = dbmd.getTables(catalog, null, null, types);
......
790 777
		rs.close();
791 778
		return (String[]) ret.keySet().toArray(new String[0]);
792 779
    }
793
    
794 780

  
781

  
795 782
    /**
796 783
     *       Gets all field names of a given table
797 784
     * @param conn connection object
......
800 787
     * @throws SQLException
801 788
     */
802 789
    public String[] getAllFields(Connection conn, String table_name) throws SQLException {
803
    	
790

  
804 791
		Statement st = conn.createStatement();
805 792
		ResultSet rs = st.executeQuery("select * from " + table_name + " LIMIT 1");
806 793
		ResultSetMetaData rsmd = rs.getMetaData();
......
821 808
     * @throws SQLException
822 809
     */
823 810
    public String[] getAllFieldTypeNames(Connection conn, String table_name) throws SQLException {
824
    	
811

  
825 812
		Statement st = conn.createStatement();
826 813
		ResultSet rs = st.executeQuery("select * from " + table_name + " LIMIT 1");
827 814
		ResultSetMetaData rsmd = rs.getMetaData();
......
835 822
    }
836 823

  
837 824
    /**
838
     * Gets the table's possible id fields. By default, all fields can be id. 
825
     * Gets the table's possible id fields. By default, all fields can be id.
839 826
     * It should be overwritten by subclasses.
840
     * 
827
     *
841 828
     * @param conn conenction object
842 829
     * @param table_name table name
843 830
     * @return the table's possible id fields
......
846 833
    public String[] getIdFieldsCandidates(Connection conn, String table_name) throws SQLException {
847 834
    	return getAllFields(conn, table_name);
848 835
    }
849
    
836

  
850 837
    /**
851 838
     * Gets the table's possible geometry fields. By default, all fields can be geometry
852 839
     * fields. It should be overwritten by subclasses.
853
     * 
840
     *
854 841
     * @param conn conenction object
855 842
     * @param table_name table name
856 843
     * @return the table's possible geometry fields
......
859 846
    public String[] getGeometryFieldsCandidates(Connection conn, String table_name) throws SQLException {
860 847
    	return getAllFields(conn, table_name);
861 848
    }
862
    
849

  
863 850
    /**
864 851
     * Tells if it's an empty table (with no records)
865 852
     * @param conn conenction object
......
867 854
     * @return whether it's an empty table (with no records) or not
868 855
     */
869 856
	public boolean isEmptyTable(Connection conn, String tableName) {
870
		
857

  
871 858
		boolean res = true;
872 859

  
873 860
		try {
......
887 874
	/**
888 875
	 * Utility method to allow the driver to do something with the geometry field.
889 876
	 * By default does nothing.
890
	 * 
877
	 *
891 878
	 * @param flds user-selected fields
892 879
	 * @param geomField geometry field
893 880
	 * @return new user-selected fields
......
895 882
	public String[] manageGeometryField(String[] flds, String geomField) {
896 883
		return flds;
897 884
	}
898
	
885

  
899 886
	/**
900 887
	 * Empty method called when the layer is going to be removed from the view.
901 888
	 * Subclasses can overwrite it if needed.
902 889
	 *
903 890
	 */
904 891
	public void remove() {
905
		
892

  
906 893
	}
907 894

  
908
    
909
    
895

  
896

  
910 897
}

Also available in: Unified diff