Revision 11928

View differences:

branches/v10/libraries/libFMap/src/com/iver/cit/gvsig/fmap/edition/VectorialEditableDBAdapter.java
18 18
import com.iver.cit.gvsig.fmap.drivers.DBLayerDefinition;
19 19
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
20 20
import com.iver.cit.gvsig.fmap.drivers.IFeatureIterator;
21
import com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver;
21
import com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver;
22 22
import com.iver.cit.gvsig.fmap.layers.ISpatialDB;
23 23
import com.iver.cit.gvsig.fmap.layers.VectorialDBAdapter;
24 24
import com.vividsolutions.jts.geom.Envelope;
......
42 42

  
43 43
		private String epsg;
44 44

  
45
		private VectorialDatabaseDriver dbDriver;
45
		private IVectorialDatabaseDriver dbDriver;
46 46

  
47 47
		Hashtable alreadyDone = new Hashtable();
48 48

  
......
57 57
			epsg = strEPSG;
58 58
			orig = (VectorialDBAdapter) ova;
59 59
			featIt = orig.getFeatureIterator(extent, epsg);
60
			dbDriver = (VectorialDatabaseDriver) getOriginalDriver();
60
			dbDriver = (IVectorialDatabaseDriver) getOriginalDriver();
61 61
			getFeaturesFromExpansionFile();
62 62
		}
63 63

  
branches/v10/libraries/libFMap/src/com/iver/cit/gvsig/fmap/layers/VectorialAdapter.java
58 58
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
59 59
import com.iver.cit.gvsig.fmap.drivers.IFeatureIterator;
60 60
import com.iver.cit.gvsig.fmap.drivers.RandomAccessFeatureIterator;
61
import com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver;
61
import com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver;
62 62
import com.iver.cit.gvsig.fmap.drivers.VectorialDriver;
63 63

  
64 64
/**
branches/v10/libraries/libFMap/src/com/iver/cit/gvsig/fmap/layers/VectorialDBAdapter.java
61 61
import com.iver.cit.gvsig.fmap.drivers.DBLayerDefinition;
62 62
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
63 63
import com.iver.cit.gvsig.fmap.drivers.IFeatureIterator;
64
import com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver;
64
import com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver;
65 65

  
66 66

  
67 67

  
......
81 81
	public void start() {
82 82
            try {
83 83
            	//System.out.println("====" +this.hashCode()+" Abrir tabla: " + ((VectorialDatabaseDriver)driver).getTableName());
84
                ((VectorialDatabaseDriver)driver).open();
84
                ((IVectorialDatabaseDriver)driver).open();
85 85
            } catch (DriverException e) {
86 86
                // TODO Auto-generated catch block
87 87
                e.printStackTrace();
......
94 94
	 */
95 95
	public void stop() {
96 96
		//System.out.println("====" +this.hashCode()+" Cerrar tabla: " + ((VectorialDatabaseDriver)driver).getTableName());
97
	    ((VectorialDatabaseDriver)driver).close();
97
	    ((IVectorialDatabaseDriver)driver).close();
98 98
	}
99 99

  
100 100
	/* (non-Javadoc)
......
110 110
	}*/
111 111
	public IFeatureIterator getFeatureIterator(Rectangle2D r, String strEPSG) throws DriverException
112 112
	{
113
	    return ((VectorialDatabaseDriver)driver).getFeatureIterator(r, strEPSG);
113
	    return ((IVectorialDatabaseDriver)driver).getFeatureIterator(r, strEPSG);
114 114
	}
115 115

  
116 116
    /* (non-Javadoc)
......
118 118
	 */
119 119
    public IFeatureIterator getFeatureIterator(Rectangle2D r, String strEPSG, String[] alphaNumericFieldsNeeded) throws DriverException
120 120
    {
121
        return ((VectorialDatabaseDriver)driver).getFeatureIterator(r, strEPSG, alphaNumericFieldsNeeded);
121
        return ((IVectorialDatabaseDriver)driver).getFeatureIterator(r, strEPSG, alphaNumericFieldsNeeded);
122 122
    }
123 123

  
124 124
	/* (non-Javadoc)
......
126 126
	 */
127 127
	public String[] getFields()
128 128
	{
129
	    return ((VectorialDatabaseDriver)driver).getFields();
129
	    return ((IVectorialDatabaseDriver)driver).getFields();
130 130
	}
131 131
	/* (non-Javadoc)
132 132
	 * @see com.iver.cit.gvsig.fmap.layers.ISpatialDB#getWhereClause()
133 133
	 */
134 134
	public String getWhereClause()
135 135
	{
136
	    return ((VectorialDatabaseDriver)driver).getWhereClause();
136
	    return ((IVectorialDatabaseDriver)driver).getWhereClause();
137 137
	}
138 138
	/* (non-Javadoc)
139 139
	 * @see com.iver.cit.gvsig.fmap.layers.ISpatialDB#getTableName()
140 140
	 */
141 141
	public String getTableName()
142 142
	{
143
	    return ((VectorialDatabaseDriver)driver).getTableName();
143
	    return ((IVectorialDatabaseDriver)driver).getTableName();
144 144
	}
145 145

  
146 146

  
......
150 150
	public IGeometry getShape(int index) throws DriverIOException {
151 151
	    IGeometry geom = null;
152 152
	    try {
153
            geom = ((VectorialDatabaseDriver)driver).getShape(index);
153
            geom = ((IVectorialDatabaseDriver)driver).getShape(index);
154 154
        } catch (IOException e) {
155 155
            throw new DriverIOException(e);
156 156
        }
......
161 161
	 * @see com.iver.cit.gvsig.fmap.layers.ReadableVectorial#getShapeType()
162 162
	 */
163 163
	public int getShapeType() throws DriverIOException {
164
		return ((VectorialDatabaseDriver)driver).getShapeType();
164
		return ((IVectorialDatabaseDriver)driver).getShapeType();
165 165
	}
166 166

  
167 167
	/**
......
222 222
	 */
223 223
    public DBLayerDefinition getLyrDef()
224 224
    {
225
        return ((VectorialDatabaseDriver)driver).getLyrDef();
225
        return ((IVectorialDatabaseDriver)driver).getLyrDef();
226 226
    }
227 227

  
228 228
	public int getRowIndexByFID(IFeature feat) {
229
		return ((VectorialDatabaseDriver) driver).getRowIndexByFID(feat); 
229
		return ((IVectorialDatabaseDriver) driver).getRowIndexByFID(feat); 
230 230
	}
231 231
}
branches/v10/libraries/libFMap/src/com/iver/cit/gvsig/fmap/layers/FLayerVectorialDB.java
1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2006 Prodevelop 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
 *   Prodevelop Integraci?n de Tecnolog?as SL
34
 *   Conde Salvatierra de ?lava , 34-10
35
 *   46004 Valencia
36
 *   Spain
37
 *
38
 *   +34 963 510 612
39
 *   +34 963 510 968
40
 *   gis@prodevelop.es
41
 *   http://www.prodevelop.es
42
 */
43
package com.iver.cit.gvsig.fmap.layers;
44

  
45
import com.hardcode.gdbms.engine.instruction.FieldNotFoundException;
46

  
47
import com.iver.cit.gvsig.fmap.DriverException;
48
import com.iver.cit.gvsig.fmap.crs.CRSFactory;
49
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
50
import com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver;
51
import com.iver.cit.gvsig.fmap.drivers.WithDefaultLegend;
52
import com.iver.cit.gvsig.fmap.rendering.LegendFactory;
53
import com.iver.cit.gvsig.fmap.rendering.VectorialLegend;
54

  
55
import com.iver.utiles.XMLEntity;
56

  
57
import org.cresques.cts.IProjection;
58

  
59

  
60
public class FLayerVectorialDB extends FLyrVect {
61
    private boolean loaded = false;
62
    private IVectorialDatabaseDriver dbDriver = null;
63

  
64
    /* Esto deberia ir en el FLyrDefault */
65
    public void setProjectionByName(String projectionName)
66
        throws Exception {
67
        IProjection proj = CRSFactory.getCRS(projectionName);
68

  
69
        if (proj == null) {
70
            throw new Exception("No se ha encontrado la proyeccion: " +
71
                projectionName);
72
        }
73

  
74
        this.setProjection(proj);
75
    }
76

  
77
    public void setDriver(IVectorialDatabaseDriver driver) {
78
        this.dbDriver = driver;
79
    }
80

  
81
    public void setDriverByName(String driverName) {
82
        this.setDriver((IVectorialDatabaseDriver) LayerFactory.getDM()
83
                                                             .getDriver(driverName));
84
    }
85

  
86
    public IVectorialDatabaseDriver getDriver() {
87
        return this.dbDriver;
88
    }
89

  
90
    /* FIXME: esto tendria que tener declarado un throws de algo*/
91
    public void wakeUp() {
92
        if (!loaded) {
93
            try {
94
                this.load();
95
            }
96
            catch (DriverIOException e) {
97
                // TODO Auto-generated catch block
98
                e.printStackTrace();
99
            }
100
        }
101
    }
102

  
103
    public void load() throws DriverIOException {
104
        if ((this.getName() == null) || (this.getName().length() == 0)) {
105
            this.setAvailable(false);
106

  
107
            //TODO: traducir???
108
            throw new DriverIOException("No se ha especificado nombre de capa");
109
        }
110

  
111
        if (this.dbDriver == null) {
112
            this.setAvailable(false);
113

  
114
            //TODO: traducir???
115
            throw new DriverIOException("No se ha especificado driver");
116
        }
117

  
118
        if (this.getProjection() == null) {
119
            this.setAvailable(false);
120

  
121
            //TODO: traducir???
122
            throw new DriverIOException("No se ha especificado proyeccion");
123
        }
124

  
125
        try {
126
            ((IVectorialDatabaseDriver) this.dbDriver).load();
127
        }
128
        catch (Exception e) {
129
            this.setAvailable(false);
130
            throw new DriverIOException(e);
131
        }
132

  
133
        try {
134
            VectorialDBAdapter dbAdapter = new VectorialDBAdapter();
135
            dbAdapter.setDriver(this.dbDriver);
136
            this.setSource(dbAdapter);
137
        }
138
        catch (Exception e) {
139
            this.setAvailable(false);
140
            throw new DriverIOException(e);
141
        }
142

  
143
        try {
144
            this.putLoadSelection();
145
            this.putLoadLegend();
146
            this.initializeLegendDefault();
147
        }
148
        catch (Exception e) {
149
            this.setAvailable(false);
150

  
151
            //TODO: traducir???
152
            throw new DriverIOException(e);
153
        }
154

  
155
        this.cleanLoadOptions();
156
    }
157

  
158
    /* Esto deberia ir en FLyrVect */
159
    private void initializeLegendDefault()
160
        throws FieldNotFoundException, DriverException {
161
        if (this.getLegend() == null) {
162
            if (this.getRecordset().getDriver() instanceof WithDefaultLegend) {
163
                WithDefaultLegend aux = (WithDefaultLegend) this.getRecordset()
164
                                                                .getDriver();
165
                this.setLegend((VectorialLegend) aux.getDefaultLegend());
166
            }
167
            else {
168
                this.setLegend(LegendFactory.createSingleSymbolLegend(
169
                        this.getShapeType()));
170
            }
171
        }
172
    }
173

  
174
    public void setXMLEntity(XMLEntity xml) throws XMLException {
175
        IProjection proj = null;
176

  
177
        if (xml.contains("proj")) {
178
            proj = CRSFactory.getCRS(xml.getStringProperty("proj"));
179
        }
180
        else {
181
            proj = this.getMapContext().getViewPort().getProjection();
182
        }
183

  
184
        this.setName(xml.getName());
185
        this.setProjection(proj);
186

  
187
        String driverName = xml.getStringProperty("db");
188
        IVectorialDatabaseDriver driver;
189

  
190
        try {
191
            driver = (IVectorialDatabaseDriver) LayerFactory.getDM()
192
                                                           .getDriver(driverName);
193

  
194
            //Hay que separar la carga de los datos del XMLEntity del load.
195
            driver.setXMLEntity(xml.getChild(2));
196
            this.setDriver(driver);
197
        }
198
        catch (Exception e) {
199
            throw new XMLException(e);
200
        }
201

  
202
        super.setXMLEntityNew(xml);
203
    }
204
}
0 205

  
branches/v10/libraries/libFMap/src/com/iver/cit/gvsig/fmap/layers/LayerFactory.java
72 72
import com.iver.cit.gvsig.fmap.LegendDriverExceptionType;
73 73
import com.iver.cit.gvsig.fmap.ProgressListener;
74 74
import com.iver.cit.gvsig.fmap.ViewPort;
75
import com.iver.cit.gvsig.fmap.drivers.ConnectionFactory;
76
import com.iver.cit.gvsig.fmap.drivers.DBException;
75 77
import com.iver.cit.gvsig.fmap.drivers.DBLayerDefinition;
76 78
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
79
import com.iver.cit.gvsig.fmap.drivers.IConnection;
77 80
import com.iver.cit.gvsig.fmap.drivers.RasterDriver;
78
import com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver;
81
import com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver;
79 82
import com.iver.cit.gvsig.fmap.drivers.VectorialDriver;
80 83
import com.iver.cit.gvsig.fmap.drivers.VectorialFileDriver;
81
import com.iver.cit.gvsig.fmap.drivers.VectorialJDBCDriver;
84
import com.iver.cit.gvsig.fmap.drivers.IVectorialJDBCDriver;
82 85
import com.iver.cit.gvsig.fmap.drivers.WithDefaultLegend;
83 86
import com.iver.cit.gvsig.fmap.operations.arcview.ArcJoin;
84 87
import com.iver.cit.gvsig.fmap.rendering.LegendFactory;
......
267 270
		if (d instanceof VectorialFileDriver) {
268 271
			adapter = new VectorialFileAdapter(((VectorialFileDriver) d)
269 272
					.getFile());
270
		} else if (d instanceof VectorialJDBCDriver) {
273
		} else if (d instanceof IVectorialJDBCDriver) {
271 274
			adapter = new VectorialDBAdapter();
272 275
		} else {
273 276
			adapter = new VectorialDefaultAdapter();
......
462 465
	}
463 466

  
464 467
	public static FLayer createArcSDELayer(String layerName,
465
			VectorialDatabaseDriver driver, IProjection proj) {
468
			IVectorialDatabaseDriver driver, IProjection proj) {
466 469
		// throw new UnsupportedOperationException();
467 470
		FLyrVect layer = new FLyrVect();
468 471
		VectorialAdapter adapter = new VectorialDBAdapter();
......
518 521
	 *
519 522
	 * @throws UnsupportedOperationException
520 523
	 */
521
	public static FLayer createLayer(VectorialDatabaseDriver driver,
524
	public static FLayer createLayer(IVectorialDatabaseDriver driver,
522 525
			String host, int port, String user, String password, String dbName,
523 526
			String tableName, IProjection proj) {
524 527
		throw new UnsupportedOperationException();
525 528
	}
526 529

  
527
	public static FLayer createDBLayer(VectorialDatabaseDriver driver,
530
	public static FLayer createDBLayer(IVectorialDatabaseDriver driver,
528 531
			String layerName, IProjection proj) {
529 532

  
530 533
		FLyrVect capa = new FLyrVect();
......
612 615
	 * @throws ClassNotFoundException
613 616
	 * @throws
614 617
	 */
615
	public static FLayer createDisconnectedDBLayer(VectorialJDBCDriver driver,
618
	public static FLayer createDisconnectedDBLayer(IVectorialDatabaseDriver driver,
616 619
			String layerName, IProjection proj, ProgressListener listener)
617
			throws SQLException, IOException, DriverIOException,
620
			throws DBException, IOException, DriverIOException,
618 621
			DriverLoadException, NoSuchTableException,
619 622
			com.hardcode.gdbms.engine.data.driver.DriverException,
620 623
			ClassNotFoundException {
......
632 635
		for (int i = 1; i < types.length; i++) {
633 636
			types[i] = ds.getFieldType(i - 1);
634 637
		}
635
		String dsName = dataSourceFactory.createTable(database,
636
				ds.getPKNames(), fieldNames, types);
638
		String dsName=null;
639
		try {
640
			dsName = dataSourceFactory.createTable(database,
641
					ds.getPKNames(), fieldNames, types);
642
		} catch (SQLException e) {
643
			throw new DBException(e);
644
		}
637 645

  
638 646
		DBLayerDefinition lyrDef = new DBLayerDefinition();
639 647
		lyrDef.setTableName(dsName);
......
686 694
		dw.stop();
687 695
		local.stop();
688 696
		ds.stop();
689
		VectorialJDBCDriver cacheDriver = (VectorialJDBCDriver) LayerFactory
697
		IVectorialJDBCDriver cacheDriver = (IVectorialJDBCDriver) LayerFactory
690 698
				.getDM().getDriver("HSQLDB Driver");
691 699
		Class.forName("org.hsqldb.jdbcDriver");
692

  
693
		cacheDriver.setData(java.sql.DriverManager.getConnection(
694
				"jdbc:hsqldb:file:" + database, "sa", ""), lyrDef);
700
		IConnection conn=ConnectionFactory.createConnection("jdbc:hsqldb:file:" + database, "sa", "");
701
		cacheDriver.setData(conn, lyrDef);
695 702
		cacheDriver.setWorkingArea(driver.getWorkingArea());
696 703
		return createDBLayer(cacheDriver, layerName, proj);
697 704
	}
branches/v10/libraries/libFMap/src/com/iver/cit/gvsig/fmap/layers/FLayers.java
68 68
import com.iver.cit.gvsig.fmap.MapControl;
69 69
import com.iver.cit.gvsig.fmap.ViewPort;
70 70
import com.iver.cit.gvsig.fmap.crs.CRSFactory;
71
import com.iver.cit.gvsig.fmap.drivers.DefaultDBDriver;
71
import com.iver.cit.gvsig.fmap.drivers.DefaultJDBCDriver;
72 72
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
73
import com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver;
73
import com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver;
74 74
import com.iver.cit.gvsig.fmap.drivers.VectorialDriver;
75 75
import com.iver.cit.gvsig.fmap.drivers.VectorialFileDriver;
76 76
import com.iver.cit.gvsig.fmap.layers.layerOperations.ComposedLayer;
......
1219 1219
                if (xml.contains("db")) {
1220 1220

  
1221 1221
                    String driverName = xml.getStringProperty("db");
1222
                    VectorialDatabaseDriver driver;
1222
                    IVectorialDatabaseDriver driver;
1223 1223
                    try {
1224
                        driver = (VectorialDatabaseDriver) LayerFactory.getDM().getDriver(driverName);
1224
                        driver = (IVectorialDatabaseDriver) LayerFactory.getDM().getDriver(driverName);
1225 1225
                        //Hay que separar la carga de los datos del XMLEntity del load.
1226 1226
                        driver.setXMLEntity(xml.getChild(2));
1227 1227

  
1228 1228
                        boolean loadOk = false;
1229
                        if (driver instanceof DefaultDBDriver) {
1229
//                        if (driver instanceof DefaultJDBCDriver) {
1230 1230
							try {
1231
								((DefaultDBDriver) driver).load();
1232
								if (((DefaultDBDriver) driver)
1231
								((IVectorialDatabaseDriver) driver).load();
1232
								if (((IVectorialDatabaseDriver) driver)
1233 1233
										.getConnection() != null) {
1234 1234
									loadOk = true;
1235 1235
								}
......
1237 1237
								e.printStackTrace();
1238 1238
								loadOk = false;
1239 1239
							}
1240
						} else {
1241
							try{
1242
								((VectorialDatabaseDriver)driver).load();
1243
								loadOk=true;
1244
							}catch (Exception e) {
1245
								loadOk=false;
1246
							}
1247
						}
1240
//						} else {
1241
//							try{
1242
//								((IVectorialDatabaseDriver)driver).load();
1243
//								loadOk=true;
1244
//							}catch (Exception e) {
1245
//								loadOk=false;
1246
//							}
1247
//						}
1248 1248

  
1249 1249
                        layer = LayerFactory.createDBLayer(driver, name, proj);
1250 1250
                        if (!loadOk) {
branches/v10/libraries/libFMap/src/com/iver/cit/gvsig/fmap/layers/VectorialDisconnectedDBAdapter.java
61 61
import com.iver.cit.gvsig.fmap.core.FShape;
62 62
import com.iver.cit.gvsig.fmap.core.IGeometry;
63 63
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
64
import com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver;
64
import com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver;
65 65

  
66 66

  
67 67

  
......
107 107
	 * al driver que cierre la conexion con el servidor de base de datos
108 108
	 */
109 109
	public void stop() {
110
	    ((VectorialDatabaseDriver)driver).close();
110
	    ((IVectorialDatabaseDriver)driver).close();
111 111
	}
112 112

  
113 113
	/**
......
115 115
	 */
116 116
	public IGeometry getShape(int index) throws DriverIOException {
117 117
	    try {
118
            return ((VectorialDatabaseDriver)driver).getShape(index);
118
            return ((IVectorialDatabaseDriver)driver).getShape(index);
119 119
        } catch (IOException e) {
120 120
            throw new DriverIOException(e);
121 121
        }
122 122
	}
123 123

  
124 124
	private String getTableName(){
125
	    return ((VectorialDatabaseDriver)driver).getTableName();
125
	    return ((IVectorialDatabaseDriver)driver).getTableName();
126 126
	}
127 127

  
128 128
	/**
......
201 201
				indexChannel = indexfs.getChannel();
202 202

  
203 203
				//Creamos un adaptador conectado para bajarnos los datos
204
				VectorialDatabaseDriver d = (VectorialDatabaseDriver) VectorialDisconnectedDBAdapter.this.driver;
204
				IVectorialDatabaseDriver d = (IVectorialDatabaseDriver) VectorialDisconnectedDBAdapter.this.driver;
205 205
				connectedAdapter = new VectorialDBAdapter();
206 206
				connectedAdapter.setDriver(d);
207 207

  
branches/v10/libraries/libFMap/src/com/iver/cit/gvsig/fmap/drivers/db/utils/SingleVectorialDBConnectionManager.java
1
package com.iver.cit.gvsig.fmap.drivers.db.utils;
2

  
3
import java.util.ArrayList;
4
import java.util.HashMap;
5
import java.util.Iterator;
6

  
7
import org.apache.log4j.Logger;
8

  
9
import com.iver.cit.gvsig.fmap.drivers.ConnectionFactory;
10
import com.iver.cit.gvsig.fmap.drivers.DBException;
11
import com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver;
12
import com.iver.cit.gvsig.fmap.drivers.IConnection;
13
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
14

  
15
/**
16
 * Utility class to handle connections properly. One connection instance per
17
 * (db, user, gvsig session)
18
 *
19
 * @author jldominguez
20
 *
21
 */
22
public class SingleVectorialDBConnectionManager {
23

  
24
	private static Logger logger = Logger.getLogger(SingleVectorialDBConnectionManager.class.getName());
25
	private static SingleVectorialDBConnectionManager single_instance = null;
26
	private HashMap connections = new HashMap();
27

  
28
	/**
29
	 * Non-public to avoid unwanted instances.
30
	 *
31
	 */
32
	protected SingleVectorialDBConnectionManager() {
33

  
34
	}
35

  
36
	/**
37
	 * Singleton model to keep single instances.
38
	 *
39
	 * @return single instance
40
	 */
41
	public static SingleVectorialDBConnectionManager instance() {
42
		if (single_instance == null) {
43
			single_instance = new SingleVectorialDBConnectionManager();
44
		}
45
		return single_instance;
46
	}
47

  
48
	/**
49
	 * Utility metho to find a connection with its parameters
50
	 * given the connection object.
51
	 *
52
	 * @param co the connection object
53
	 * @return
54
	 */
55
	public ConnectionWithParams findConnection(IConnection co) {
56

  
57
		Iterator iter = connections.keySet().iterator();
58
		while (iter.hasNext()) {
59
			String keyitem = (String) iter.next();
60
			ConnectionWithParams cwp = (ConnectionWithParams) connections.get(keyitem);
61
			if (cwp.getConnection() == co) {
62
				return cwp;
63
			}
64
		}
65
		return null;
66
	}
67

  
68

  
69
	/**
70
	 * Creates a new connection with its parameters if not created yet.
71
	 *
72
	 * @param _drvName driver name
73
	 * @param _user user name
74
	 * @param _pw password
75
	 * @param _name connection name
76
	 * @param _host host url
77
	 * @param _port port number as string
78
	 * @param _db database name
79
	 * @param _connected whether or not to connect the connection
80
	 * @return the connection with parameters object
81
	 * @throws SQLException
82
	 */
83
	public ConnectionWithParams getConnection (
84
			String _drvName,
85
			String _user,
86
			String _pw,
87
			String _name,
88
			String _host,
89
			String _port,
90
			String _db,
91
			boolean _connected
92
			) throws DBException {
93

  
94
		IVectorialDatabaseDriver drv = getInstanceFromName(_drvName);
95
		if (drv==null)return null;
96
		String conn_str = drv.getConnectionString(_host, _port, _db, _user, _pw);
97

  
98
		String key = getConnectionKey(_drvName, _host, _db, _port, _user);
99

  
100
		if (!connections.containsKey(key)) {
101

  
102
			ConnectionWithParams cwp = null;
103

  
104
			if (_connected) {
105
				IConnection new_connection = null;
106
				new_connection = ConnectionFactory.createConnection(conn_str, _user, _pw);
107

  
108
//				new_connection.setAutoCommit(false);
109

  
110
				cwp = new ConnectionWithParams(
111
						conn_str,
112
						new_connection,
113
						_drvName,
114
						_user,
115
						_pw,
116
						_name,
117
						_host,
118
						_port,
119
						_db,
120
						true);
121
			} else {
122

  
123
				cwp = new ConnectionWithParams(
124
						conn_str,
125
						null,
126
						_drvName,
127
						_user,
128
						null,
129
						_name,
130
						_host,
131
						_port,
132
						_db,
133
						false);
134
			}
135
			connections.put(key, cwp);
136
		}
137

  
138
		ConnectionWithParams _cwp = (ConnectionWithParams) connections.get(key);
139

  
140
		if (_cwp.getName().compareTo(_name) != 0) {
141
			// connections.remove(key);
142
			_cwp.setName(_name);
143
			connections.put(key, _cwp);
144
		}
145

  
146
		if ((!_cwp.isConnected()) && (_connected)) {
147
			_cwp.connect(_pw);
148
		}
149

  
150
		return _cwp;
151
	}
152

  
153
	/**
154
	 * Gets available open connections.
155
	 *
156
	 * @return array of open connections with parameters
157
	 */
158
	public ConnectionWithParams[] getConnectedConnections() {
159
		Iterator iter = connections.keySet().iterator();
160
		if (!iter.hasNext()) return null;
161

  
162
		ArrayList aux = new ArrayList();
163

  
164
		while (iter.hasNext()) {
165
			ConnectionWithParams _cwp =
166
				(ConnectionWithParams) connections.get(iter.next());
167
			if (_cwp.isConnected()) {
168
				aux.add(_cwp);
169
			}
170
		}
171

  
172
		ConnectionWithParams[] resp = new ConnectionWithParams[aux.size()];
173
		for (int i=0; i<aux.size(); i++) {
174
			resp[i] = (ConnectionWithParams) aux.get(i);
175
		}
176
		return resp;
177
	}
178

  
179
	/**
180
	 * Gets all available connections.
181
	 *
182
	 * @return array of all connections with parameters
183
	 */
184
	public ConnectionWithParams[] getAllConnections() {
185
		Iterator iter = connections.keySet().iterator();
186
		if (!iter.hasNext()) return null;
187

  
188
		ArrayList aux = new ArrayList();
189

  
190
		while (iter.hasNext()) {
191
			ConnectionWithParams _cwp =
192
				(ConnectionWithParams) connections.get(iter.next());
193
			aux.add(_cwp);
194
		}
195

  
196
		ConnectionWithParams[] resp = new ConnectionWithParams[aux.size()];
197
		for (int i=0; i<aux.size(); i++) {
198
			resp[i] = (ConnectionWithParams) aux.get(i);
199
		}
200
		return resp;
201
	}
202

  
203
	/**
204
	 * Removes connection with its params.
205
	 *
206
	 * @param _cwp connection with params to be removed
207
	 */
208
	private void removeConnectionWP(ConnectionWithParams _cwp) {
209

  
210
		ArrayList keysToRemove = new ArrayList();
211

  
212
		Iterator iter = connections.keySet().iterator();
213
		while (iter.hasNext()) {
214
			Object key = iter.next();
215
			ConnectionWithParams cwp = (ConnectionWithParams) connections.get(key);
216
			if (cwp == _cwp) {
217
				keysToRemove.add(key);
218
			}
219
		}
220
		for (int i=0; i<keysToRemove.size(); i++) {
221
			connections.remove(keysToRemove.get(i));
222
		}
223
	}
224

  
225

  
226
	/**
227
	 * Closes and removes a connection with params object
228
	 *
229
	 * @param _cwp
230
	 * @return whether the connection was actually closed (false if the
231
	 * connection was not open at the start)
232
	 */
233
	public boolean closeAndRemove(ConnectionWithParams _cwp) {
234

  
235
		boolean it_was_open = true;
236

  
237
		try {
238
			it_was_open = (_cwp.getConnection() != null) && (!_cwp.getConnection().isClosed());
239
			if (_cwp.getConnection() != null) _cwp.getConnection().close();
240
			removeConnectionWP(_cwp);
241
		} catch (Exception se) {
242
			logger.error("While closing connection: " + se.getMessage(), se);
243
			return false;
244
		}
245
		logger.info("Connection successfully closed.");
246
		return it_was_open;
247
	}
248

  
249
	/**
250
	 * Called by the extension object when gvsig terminates.
251
	 *
252
	 */
253
	public void closeAllBeforeTerminate() {
254

  
255
		boolean ok = true;
256
		String key = "";
257
		ConnectionWithParams cwp = null;
258
		Iterator iter = connections.keySet().iterator();
259
		while (iter.hasNext()) {
260
			key = (String) iter.next();
261
			cwp = (ConnectionWithParams) connections.get(key);
262

  
263
			if (cwp.getConnection() == null) continue;
264

  
265
			try {
266
				cwp.getConnection().close();
267
			} catch (DBException se) {
268
				ok = false;
269
				logger.error("While closing connection: " + se.getMessage(), se);
270
			}
271
		}
272

  
273
		connections.clear();
274

  
275
		if (ok) {
276
			logger.info("Successfully closed all connections.");
277
		} else {
278
			logger.warn("Problems while closing all connections.");
279
		}
280
	}
281

  
282
	/**
283
	 * Gets the objects key to be used in the inner hashmap
284
	 * @param _drvName driver name
285
	 * @param _host host's url
286
	 * @param _db database name
287
	 * @param _port port number
288
	 * @param _user user name
289
	 * @return
290
	 */
291
	private static String getConnectionKey(
292
			String _drvName,
293
			String _host,
294
			String _db,
295
			String _port, String _user) {
296

  
297
		String resp = "_driver_" + _drvName.toLowerCase();
298
		resp = resp + "_host_" + _host.toLowerCase();
299
		resp = resp + "_db_" + _db.toLowerCase(); // ---------------- nueva
300
		resp = resp + "_port_" + _port;
301
		resp = resp + "_user_" + _user.toLowerCase();
302
		return resp;
303
	}
304

  
305
	/**
306
	 * Utility method to instantiate a driver given its name.
307
	 *
308
	 * @param drvname driver name
309
	 * @return driver instance
310
	 */
311
	public static IVectorialDatabaseDriver getInstanceFromName(String drvname) {
312

  
313
		IVectorialDatabaseDriver _driver = null;
314
        try {
315
            _driver = (IVectorialDatabaseDriver) LayerFactory.getDM().getDriver(drvname);
316
        } catch (Exception e) {
317
        	logger.error("While getting driver instance: " + e.getMessage(), e);
318
        }
319
        return _driver;
320
	}
321

  
322

  
323

  
324

  
325

  
326
}
0 327

  
branches/v10/libraries/libFMap/src/com/iver/cit/gvsig/fmap/drivers/db/utils/ConnectionWithParams.java
1
package com.iver.cit.gvsig.fmap.drivers.db.utils;
2

  
3
import org.apache.log4j.Logger;
4

  
5
import com.iver.cit.gvsig.fmap.drivers.ConnectionFactory;
6
import com.iver.cit.gvsig.fmap.drivers.DBException;
7
import com.iver.cit.gvsig.fmap.drivers.IConnection;
8

  
9
/**
10
 * Utility class to keep the connection parameters. It is used as a item in the
11
 * single connections manager tree and in the available connections combo box
12
 * (wizard db)
13
 *
14
 * @author jldominguez
15
 *
16
 */
17
public class ConnectionWithParams {
18

  
19
	private static Logger logger = Logger.getLogger(ConnectionWithParams.class.getName());
20

  
21
	private IConnection conn = null;
22
	private String connectionStr = "";
23
	private String drvName = "";
24
	private String user = "";
25
	private String pw = "";
26
	private String name = "";
27
	private boolean connected = false;
28

  
29
	private String host;
30
    private String port;
31
    private String db;
32

  
33
    private String schema;
34
    
35
    private boolean isNull = false;
36

  
37

  
38
    /**
39
     * Utility constructor to indicate an empty item.
40
     * It is used as the first item in the wizard's combo box
41
     * so that when the wizard is loaded, no query is done to any database.
42
     *
43
     */
44
	public ConnectionWithParams() {
45
		isNull = true;
46
	}
47

  
48
	/**
49
	 * Class Constructor.
50
	 *
51
	 * @param _conn_str connection string
52
	 * @param _c connection object
53
	 * @param _drvName driver name
54
	 * @param _user user name
55
	 * @param _pw password
56
	 * @param _name connection name (freely chosen by user)
57
	 * @param _host host's url
58
	 * @param _port port number as a string
59
	 * @param _db database name
60
	 * @param _isConn whether the connection is open or not
61
	 */
62
	public ConnectionWithParams(
63
			String _conn_str,
64
			IConnection _c,
65
			String _drvName,
66
			String _user,
67
			String _pw,
68
			String _name,
69
			String _host,
70
			String _port,
71
			String _db,
72
			boolean _isConn) {
73

  
74
		connectionStr = _conn_str;
75
		connected = _isConn;
76
		conn = _c;
77
		drvName = _drvName;
78
		user = _user;
79
		pw = _pw;
80
		name = _name;
81

  
82
		host = _host;
83
		port = _port;
84
		db = _db;
85

  
86
		if (!connected) {
87
			pw = null;
88
			conn = null;
89
		}
90
	}
91

  
92
	public IConnection getConnection() {
93
		return conn;
94
	}
95

  
96
	public String getDrvName() {
97
		return drvName;
98
	}
99

  
100
	public String getPw() {
101
		return pw;
102
	}
103

  
104
	public String getUser() {
105
		return user;
106
	}
107

  
108

  
109
	/**
110
	 * Used to paint the object in lists and trees
111
	 */
112
	public String toString() {
113

  
114
		if (isNull) {
115
			return "";
116
		}
117

  
118
		if (connected) {
119
			return "[C] " + name + " (" + drvName + ")";
120
		} else {
121
			return name + " (" + drvName + ")";
122
		}
123
	}
124

  
125
	public boolean isConnected() {
126
		return connected;
127
	}
128

  
129
	public void setConnected(boolean c) {
130
		connected = c;
131
	}
132

  
133
	/**
134
	 * Tries to connects the connection object with the given password.
135
	 * @param _pw password
136
	 * @throws SQLException
137
	 */
138
	public void connect(String _pw) throws DBException {
139

  
140
		try {
141
			conn = ConnectionFactory.createConnection(connectionStr, user, _pw);//DriverManager.getConnection(connectionStr, user, _pw);
142
		} catch (DBException e) {
143

  
144
			pw = null;
145
			conn = null;
146
			connected = false;
147

  
148
			throw new DBException(e);
149
		}
150

  
151
		pw = _pw;
152
		connected = true;
153
	}
154

  
155
	/**
156
	 * Disconnects the connection
157
	 *
158
	 */
159
	public void disconnect() {
160

  
161
			try {
162
				conn.close();
163
			} catch (DBException e) {
164
				logger.error("While closing connection: " + e.getMessage(), e);
165
			}
166
			pw = null;
167
			conn = null;
168
			connected = false;
169
	}
170

  
171

  
172
	public String getConnectionStr() {
173
		return connectionStr;
174
	}
175

  
176
	public void setConnectionStr(String connectionStr) {
177
		this.connectionStr = connectionStr;
178
	}
179

  
180
	public String getName() {
181
		return name;
182
	}
183

  
184
	public void setName(String name) {
185
		this.name = name;
186
	}
187

  
188
	public String getDb() {
189
		return db;
190
	}
191

  
192
	public void setDb(String db) {
193
		this.db = db;
194
	}
195

  
196
	public String getHost() {
197
		return host;
198
	}
199

  
200
	public void setHost(String host) {
201
		this.host = host;
202
	}
203

  
204
	public String getPort() {
205
		return port;
206
	}
207

  
208
	public void setPort(String port) {
209
		this.port = port;
210
	}
211

  
212
	/**
213
	 *
214
	 * @return whether or not this is the first item in the combo box.
215
	 */
216
	public boolean isNull() {
217
		return isNull;
218
	}
219

  
220
	public String getSchema() {
221
		return schema;
222
	}
223

  
224
	public void setSchema(String schema) {
225
		this.schema = schema;
226
	}
227

  
228
}
0 229

  
branches/v10/libraries/libFMap/src/com/iver/cit/gvsig/fmap/drivers/DefaultJDBCDriver.java
71 71
import com.iver.cit.gvsig.fmap.SqlDriveExceptionType;
72 72
import com.iver.cit.gvsig.fmap.core.IFeature;
73 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.SingleVectorialDBConnectionManager;
74
import com.iver.cit.gvsig.fmap.drivers.db.utils.ConnectionWithParams;
75
import com.iver.cit.gvsig.fmap.drivers.db.utils.SingleVectorialDBConnectionManager;
76 76
import com.iver.cit.gvsig.fmap.layers.SelectableDataSource;
77 77
import com.iver.cit.gvsig.fmap.layers.XMLException;
78 78
import com.iver.utiles.XMLEntity;
branches/v10/libraries/libFMap/src/com/iver/cit/gvsig/fmap/operations/strategies/DBStrategy.java
57 57
import com.iver.cit.gvsig.fmap.drivers.DriverAttributes;
58 58
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
59 59
import com.iver.cit.gvsig.fmap.drivers.IFeatureIterator;
60
import com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver;
60
import com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver;
61 61
import com.iver.cit.gvsig.fmap.layers.FBitSet;
62 62
import com.iver.cit.gvsig.fmap.layers.FLayer;
63 63
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
......
90 90
        // teniendo en cuenta el boundingbox que toca.
91 91
        FLyrVect lyr = (FLyrVect) getCapa();
92 92
        ISpatialDB dbAdapter = (ISpatialDB) ((SingleLayer) capa).getSource();
93
        VectorialDatabaseDriver dbDriver = (VectorialDatabaseDriver) dbAdapter.getDriver();
93
        IVectorialDatabaseDriver dbDriver = (IVectorialDatabaseDriver) dbAdapter.getDriver();
94 94
        try {
95 95
			dbAdapter.start();
96 96
	        Selectable selectable=lyr.getRecordset();
......
214 214
    					throws DriverException, VisitException{
215 215
    	 FLyrVect lyr = (FLyrVect) getCapa();
216 216
         ISpatialDB dbAdapter = (ISpatialDB) ((SingleLayer) capa).getSource();
217
         VectorialDatabaseDriver dbDriver = (VectorialDatabaseDriver) dbAdapter.getDriver();
217
         IVectorialDatabaseDriver dbDriver = (IVectorialDatabaseDriver) dbAdapter.getDriver();
218 218
         try {
219 219
 			dbAdapter.start();
220 220
 			ICoordTrans ct = lyr.getCoordTrans();
......
270 270
        // teniendo en cuenta el boundingbox que toca.
271 271
        FLyrVect lyr = (FLyrVect) getCapa();
272 272
        ISpatialDB dbAdapter = (ISpatialDB) ((SingleLayer) capa).getSource();
273
        VectorialDatabaseDriver dbDriver = (VectorialDatabaseDriver) dbAdapter.getDriver();
273
        IVectorialDatabaseDriver dbDriver = (IVectorialDatabaseDriver) dbAdapter.getDriver();
274 274
        try {
275 275
			dbAdapter.start();
276 276
			ICoordTrans ct = lyr.getCoordTrans();

Also available in: Unified diff