Statistics
| Revision:

svn-gvsig-desktop / tags / v1_1_Build_1002 / libraries / libFMap / src / com / iver / cit / gvsig / fmap / layers / LayerFactory.java @ 12070

History | View | Annotate | Download (23.7 KB)

1 1100 fjp
/* 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 214 fernando
package com.iver.cit.gvsig.fmap.layers;
42
43 2277 vcaballero
import java.io.File;
44
import java.io.IOException;
45
import java.sql.SQLException;
46
import java.sql.Types;
47
import java.util.TreeMap;
48
49
import org.apache.log4j.Logger;
50
import org.cresques.cts.IProjection;
51 10195 nacho
import org.cresques.io.data.RasterBuf;
52
import org.cresques.px.Extent;
53 2277 vcaballero
54 408 fernando
import com.hardcode.driverManager.Driver;
55
import com.hardcode.driverManager.DriverLoadException;
56
import com.hardcode.driverManager.DriverManager;
57 10401 fjp
import com.hardcode.driverManager.IDelayedDriver;
58 4143 caballero
import com.hardcode.driverManager.WriterManager;
59 1828 fernando
import com.hardcode.gdbms.engine.customQuery.QueryManager;
60 2183 fernando
import com.hardcode.gdbms.engine.data.DataSource;
61 408 fernando
import com.hardcode.gdbms.engine.data.DataSourceFactory;
62 2183 fernando
import com.hardcode.gdbms.engine.data.NoSuchTableException;
63
import com.hardcode.gdbms.engine.data.edition.DataWare;
64 470 fjp
import com.hardcode.gdbms.engine.instruction.FieldNotFoundException;
65 2183 fernando
import com.hardcode.gdbms.engine.values.Value;
66
import com.hardcode.gdbms.engine.values.ValueFactory;
67 8765 jjdelcerro
import com.iver.cit.gvsig.fmap.DBDriverExceptionType;
68 651 fernando
import com.iver.cit.gvsig.fmap.DriverException;
69 8765 jjdelcerro
import com.iver.cit.gvsig.fmap.DriverIOExceptionType;
70
import com.iver.cit.gvsig.fmap.DriverNotLoadedExceptionType;
71
import com.iver.cit.gvsig.fmap.GenericDriverExceptionType;
72
import com.iver.cit.gvsig.fmap.LegendDriverExceptionType;
73 2183 fernando
import com.iver.cit.gvsig.fmap.ProgressListener;
74 2850 nacho
import com.iver.cit.gvsig.fmap.ViewPort;
75 11928 caballero
import com.iver.cit.gvsig.fmap.drivers.ConnectionFactory;
76
import com.iver.cit.gvsig.fmap.drivers.DBException;
77 3236 fjp
import com.iver.cit.gvsig.fmap.drivers.DBLayerDefinition;
78 422 fjp
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
79 11928 caballero
import com.iver.cit.gvsig.fmap.drivers.IConnection;
80 303 fernando
import com.iver.cit.gvsig.fmap.drivers.RasterDriver;
81 11928 caballero
import com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver;
82 408 fernando
import com.iver.cit.gvsig.fmap.drivers.VectorialDriver;
83 438 fernando
import com.iver.cit.gvsig.fmap.drivers.VectorialFileDriver;
84 11928 caballero
import com.iver.cit.gvsig.fmap.drivers.IVectorialJDBCDriver;
85 714 fjp
import com.iver.cit.gvsig.fmap.drivers.WithDefaultLegend;
86 1828 fernando
import com.iver.cit.gvsig.fmap.operations.arcview.ArcJoin;
87 458 fjp
import com.iver.cit.gvsig.fmap.rendering.LegendFactory;
88 714 fjp
import com.iver.cit.gvsig.fmap.rendering.VectorialLegend;
89 8765 jjdelcerro
import com.iver.utiles.ExceptionDescription;
90 303 fernando
91 214 fernando
/**
92
 * Crea un adaptador del driver que se le pasa como par?metro en los m?todos
93
 * createLayer. Si hay memoria suficiente se crea un FLyrMemory que pasa todas
94
 * las features del driver a memoria
95
 */
96
public class LayerFactory {
97 8765 jjdelcerro
        private static Logger logger = Logger.getLogger(LayerFactory.class
98
                        .getName());
99
100 439 luisw
        private static String driversPath = "../FMap 03/drivers";
101 8765 jjdelcerro
102 4781 fjp
        private static String writersPath = "../FMap 03/drivers";
103 8765 jjdelcerro
104 732 fernando
        private static DriverManager driverManager;
105 8765 jjdelcerro
106 4143 caballero
        private static WriterManager writerManager;
107 408 fernando
108 1828 fernando
        private static DataSourceFactory dataSourceFactory;
109 4143 caballero
110 732 fernando
        /**
111
         * Map en el que se guarda para cada fuente de datos a?adida al sistema, el
112 8765 jjdelcerro
         * adaptador que la maneja. Ha de ser un TreeMap ya que esta clase define la
113
         * igualdad entre las claves a traves del m?todo equals de las mismas. Los
114
         * objetos FileSource, DBSource y WFSSource tienen definido el m?todo equals
115
         * de forma que devuelven true cuando dos objetos apuntan a la misma fuente
116
         * de datos
117 732 fernando
         */
118
        private static TreeMap sourceAdapter;
119 214 fernando
120 1828 fernando
        /*
121 8765 jjdelcerro
         * Crea un RandomVectorialFile con el driver que se le pasa como par?metro y
122
         * guard?ndose el nombre del fichero para realizar los accesos, la capa
123 732 fernando
         * tendr? asociada la proyecci?n que se pasa como parametro tambi?n
124 10666 caballero
         *
125 8765 jjdelcerro
         * @param layerName Nombre de la capa. @param driverName Nombre del driver.
126
         * @param f fichero. @param proj Proyecci?n.
127 10666 caballero
         *
128 8765 jjdelcerro
         * @return FLayer. @throws DriverException
129 10666 caballero
         *
130 8765 jjdelcerro
         * @throws DriverException @throws DriverIOException
131 2183 fernando
         */
132 732 fernando
        public static FLayer createLayer(String layerName, String driverName,
133 8765 jjdelcerro
                        File f, IProjection proj) throws DriverException {
134
                // Se obtiene el driver que lee
135 732 fernando
                DriverManager dm = getDM();
136 438 fernando
137 732 fernando
                try {
138
                        Driver d = dm.getDriver(driverName);
139 438 fernando
140 732 fernando
                        if (d instanceof VectorialFileDriver) {
141
                                return createLayer(layerName, (VectorialFileDriver) d, f, proj);
142
                        } else if (d instanceof RasterDriver) {
143
                                return createLayer(layerName, (RasterDriver) d, f, proj);
144
                        }
145
                } catch (DriverLoadException e) {
146 8765 jjdelcerro
                        //hay un poco de lio sobre que excepciones se dejan subir
147
                        //arriba y que excepciones se quedan en LayerFactory
148
                        //(esto se debe a que queremos intentar recuperar ciertas capas)
149
                        //las excepciones de este metodo se dejan subir todas, puesto
150
                        //que las excepciones de los dos otros metodos createLayer si que
151
                        //se atrapan
152 10666 caballero
                        DriverNotLoadedExceptionType exceptionType =
153 8765 jjdelcerro
                                new DriverNotLoadedExceptionType();
154
                        exceptionType.setDriverName(driverName);
155 10666 caballero
                        DriverException exception =
156
                                new DriverException(e, exceptionType);
157 8765 jjdelcerro
                        throw exception;
158 732 fernando
                }
159 438 fernando
160 732 fernando
                return null;
161
        }
162 2183 fernando
163 1034 vcaballero
        /**
164 8765 jjdelcerro
         * It creates a FLayer (FLyrVect) which reads its data from a file driver,
165
         * projected in the specified projection.
166 10666 caballero
         *
167 8765 jjdelcerro
         * @param layerName
168
         *            name of the layer
169
         * @param d
170
         *            vectorial file driver to read layer's data
171
         * @param f
172
         *            file associated to the driver
173
         * @param proj
174
         *            layer projection
175 10666 caballero
         *
176 8765 jjdelcerro
         * @return FLayer new vectorial layer
177 10666 caballero
         *
178 1034 vcaballero
         * @throws DriverException
179
         */
180
        public static FLayer createLayer(String layerName, VectorialFileDriver d,
181 10666 caballero
                        File f, IProjection proj)
182
183 8765 jjdelcerro
        /*throws DriverException*/ {
184
185
                // TODO Comprobar si hay un adaptador ya
186 1034 vcaballero
                VectorialFileAdapter adapter = new VectorialFileAdapter(f);
187
                adapter.setDriver((VectorialDriver) d);
188 214 fernando
189 1034 vcaballero
                FLyrVect capa = new FLyrVect();
190
                capa.setName(layerName);
191 8765 jjdelcerro
192
                // TODO Meter esto dentro de la comprobaci?n de si hay memoria
193 1034 vcaballero
                if (false) {
194
                } else {
195
                        capa.setSource(adapter);
196
                        capa.setProjection(proj);
197
                }
198 4143 caballero
199 8765 jjdelcerro
                try {
200 470 fjp
                        // Le asignamos tambi?n una legenda por defecto acorde con
201
                        // el tipo de shape que tenga. Tampoco s? si es aqu? el
202
                        // sitio adecuado, pero en fin....
203 1034 vcaballero
                        if (d instanceof WithDefaultLegend) {
204
                                WithDefaultLegend aux = (WithDefaultLegend) d;
205
                                adapter.start();
206
                                capa.setLegend((VectorialLegend) aux.getDefaultLegend());
207
                                adapter.stop();
208
                        } else {
209 8765 jjdelcerro
                                capa.setLegend(LegendFactory.createSingleSymbolLegend(capa
210
                                                .getShapeType()));
211 1034 vcaballero
                        }
212 10666 caballero
213 8765 jjdelcerro
                } catch (FieldNotFoundException e) {
214
                        //this exception is caused in legend creation
215 10666 caballero
                        LegendDriverExceptionType excepType =
216
                                new LegendDriverExceptionType("Error al construir la leyenda");
217 8765 jjdelcerro
                        //TODO Para hacer esto extensible tiene que usarse puntos
218
                        //de extension, y comparar las clases de leyendas registradas
219 10666 caballero
                        VectorialLegend legend = (VectorialLegend)
220 8765 jjdelcerro
                                ((WithDefaultLegend)d).getDefaultLegend();
221 10666 caballero
222 8765 jjdelcerro
                        excepType.setLegendLabelField(legend.getLabelField());
223
                        excepType.setLegendHeightField(legend.getLabelHeightField());
224
                        excepType.setLegendRotationField(legend.getLabelRotationField());
225
                        DriverException exception = new DriverException(e, excepType);
226
                        capa.setAvailable(false);
227
                        capa.addError(exception);
228 10666 caballero
229 714 fjp
                } catch (DriverIOException e) {
230 8765 jjdelcerro
                        //this error is caused for file IO problems
231 10666 caballero
                        DriverIOExceptionType excepType =
232 8765 jjdelcerro
                                new DriverIOExceptionType();
233
                        excepType.setFile(f);
234
                        DriverException exception = new DriverException(e, excepType);
235 6537 jmvivo
                        capa.setAvailable(false);
236 8765 jjdelcerro
                        capa.addError(exception);
237 1034 vcaballero
                }
238 10666 caballero
239 8765 jjdelcerro
                /*
240
                 * catch(DriverException e){
241
                 * ESTO HAY QUE CAPTURARLO,DE FORMA QUE CREATELAYER NO LANCE NINGUNA
242
                 * EXCEPCION (A NO SER QUE SEA IRRECUPERABLE)
243
                 * }
244
                 */
245
                catch(Exception e){
246
                        GenericDriverExceptionType type = new GenericDriverExceptionType();
247
                        DriverException exception = new DriverException(e, type);
248
                        capa.setAvailable(false);
249
                        capa.addError(exception);
250
                }
251 1034 vcaballero
                return capa;
252
        }
253 567 luisw
254 8765 jjdelcerro
        /**
255
         * Creates a new vectorial layer from a generic layer (by generic whe mean
256
         * that we dont know a priory its origin: file, memory, jdbc database, etc.
257 10666 caballero
         *
258 8765 jjdelcerro
         * @param layerName
259
         * @param d
260
         * @param proj
261
         * @return
262
         * @throws DriverException
263
         */
264
        public static FLayer createLayer(String layerName, VectorialDriver d,
265 10666 caballero
                        IProjection proj)
266 8765 jjdelcerro
        /*
267 10666 caballero
        throws DriverException
268 8765 jjdelcerro
        */{
269
                VectorialAdapter adapter = null;
270
                if (d instanceof VectorialFileDriver) {
271
                        adapter = new VectorialFileAdapter(((VectorialFileDriver) d)
272
                                        .getFile());
273 11928 caballero
                } else if (d instanceof IVectorialJDBCDriver) {
274 8765 jjdelcerro
                        adapter = new VectorialDBAdapter();
275
                } else {
276
                        adapter = new VectorialDefaultAdapter();
277
                }
278
                adapter.setDriver((VectorialDriver) d);
279 3301 fjp
280 8765 jjdelcerro
                FLyrVect capa = new FLyrVect();
281
                capa.setName(layerName);
282 3301 fjp
283 8765 jjdelcerro
                capa.setSource(adapter);
284
                capa.setProjection(proj);
285 3301 fjp
286 8765 jjdelcerro
                try {
287 4143 caballero
288 8765 jjdelcerro
                        // Le asignamos tambi?n una legenda por defecto acorde con
289
                        // el tipo de shape que tenga. Tampoco s? si es aqu? el
290
                        // sitio adecuado, pero en fin....
291
                        if (d instanceof WithDefaultLegend) {
292
                                WithDefaultLegend aux = (WithDefaultLegend) d;
293
                                adapter.start();
294
                                capa.setLegend((VectorialLegend) aux.getDefaultLegend());
295
                                adapter.stop();
296
                        } else {
297
                                capa.setLegend(LegendFactory.createSingleSymbolLegend(capa
298
                                                .getShapeType()));
299
                        }
300
                } catch (FieldNotFoundException e) {
301
//                        this exception is caused in legend creation
302 10666 caballero
                        LegendDriverExceptionType excepType =
303 8765 jjdelcerro
                                new LegendDriverExceptionType("error al construir la leyenda, campo no encontrado");
304 3301 fjp
305 8765 jjdelcerro
                        //TODO Para hacer esto extensible tiene que usarse puntos
306
                        //de extension, y comparar las clases de leyendas registradas
307 10666 caballero
                        VectorialLegend legend = (VectorialLegend)
308 8765 jjdelcerro
                                ((WithDefaultLegend)d).getDefaultLegend();
309
                        excepType.setDriverName(d.getName());
310
                        excepType.setLegendLabelField(legend.getLabelField());
311
                        excepType.setLegendHeightField(legend.getLabelHeightField());
312
                        excepType.setLegendRotationField(legend.getLabelRotationField());
313 10666 caballero
314 8765 jjdelcerro
                        DriverException exception = new DriverException(e, excepType);
315
                        capa.setAvailable(false);
316
                        capa.addError(exception);
317
                } catch (DriverIOException e) {
318
                        //by design, start and stop calls to adapter could
319
                        //cause this exception.
320 10666 caballero
321 8765 jjdelcerro
                        //but JDBC implementations catchs all exceptions,
322 10666 caballero
                        //and rest of layers (WFSLayer, etc.) dont use LayerFactory
323 8765 jjdelcerro
                        ExceptionDescription type = null;
324
                        if (d instanceof VectorialFileDriver) {
325
                                File f = ((VectorialFileDriver)adapter).getFile();
326 10666 caballero
                                type =
327
                                        new DriverIOExceptionType();
328 8765 jjdelcerro
                                ((DriverIOExceptionType)type).setFile(f);
329 10666 caballero
330 8765 jjdelcerro
                        }else{
331
                                type = new GenericDriverExceptionType();
332
                        }
333
                        DriverException exception = new DriverException(e, type);
334
                        capa.setAvailable(false);
335
                        capa.addError(exception);
336
                }catch(Exception e){
337
                        GenericDriverExceptionType type = new GenericDriverExceptionType();
338
                        DriverException exception = new DriverException(e, type);
339
                        capa.setAvailable(false);
340
                        capa.addError(exception);
341
                }
342 1034 vcaballero
343 8765 jjdelcerro
                return capa;
344
        }
345
346 1034 vcaballero
        /**
347
         * Crea una capa Raster a partir del nombre driver, fichero y proyecci?n.
348 10666 caballero
         *
349 8765 jjdelcerro
         * @param layerName
350
         *            Nombre de la capa.
351
         * @param d
352
         *            RasterDriver.
353
         * @param f
354
         *            Fichero.
355
         * @param proj
356
         *            Proyecci?n.
357 10666 caballero
         *
358 1034 vcaballero
         * @return Nueva capa de tipo raster.
359 10666 caballero
         *
360 1034 vcaballero
         * @throws DriverIOException
361
         */
362 732 fernando
        public static FLyrRaster createLayer(String layerName, RasterDriver d,
363 8765 jjdelcerro
                        File f, IProjection proj) throws DriverException {
364 732 fernando
                RasterAdapter adapter = new RasterFileAdapter(f);
365
                adapter.setDriver(d);
366
367
                FLyrRaster capa = new FLyrRaster();
368
                capa.setName(layerName);
369
370 8765 jjdelcerro
                // TODO Meter esto dentro de la comprobaci?n de si hay memoria
371 732 fernando
                if (false) {
372
                } else {
373
                        capa.setSource(adapter);
374
                        capa.setProjection(proj);
375 1046 fernando
                        try {
376
                                capa.load();
377
                        } catch (DriverIOException e) {
378
                                throw new DriverException(e);
379
                        }
380 732 fernando
                }
381
382 567 luisw
                return capa;
383 732 fernando
        }
384 567 luisw
385 732 fernando
        /**
386 4143 caballero
         * Crea una capa Raster a partir del nombre driver, fichero y proyecci?n y
387
         * coordenadas de georeferenciaci?n. Esta funci?n es para georeferenciar
388 8765 jjdelcerro
         * capas raster. Para imagenes que no tienen georeferenciaci?n hay que
389
         * asignarle una temporal, normalmente a partir de la vista activa.
390 10666 caballero
         *
391 8765 jjdelcerro
         * @param layerName
392
         *            Nombre de la capa.
393
         * @param d
394
         *            RasterDriver.
395
         * @param f
396
         *            Fichero.
397
         * @param proj
398
         *            Proyecci?n.
399
         * @param extent
400
         *            Extent de la vista activa
401 10666 caballero
         *
402 2850 nacho
         * @return Nueva capa de tipo raster.
403 10666 caballero
         *
404 2850 nacho
         * @throws DriverIOException
405
         */
406
        public static FLyrRaster createLayer(String layerName, RasterDriver d,
407 8765 jjdelcerro
                        File f, IProjection proj, ViewPort vp) throws DriverException {
408 2850 nacho
                RasterAdapter adapter = new RasterFileAdapter(f);
409
                adapter.setDriver(d);
410 4143 caballero
411 2850 nacho
                FLyrRaster capa = new FLyrRaster();
412
                capa.setName(layerName);
413 4143 caballero
414 8765 jjdelcerro
                // TODO Meter esto dentro de la comprobaci?n de si hay memoria
415 2850 nacho
                if (false) {
416
                } else {
417
                        capa.setSource(adapter);
418
                        capa.setProjection(proj);
419 8765 jjdelcerro
                        // capa.setTempExtent(vp);
420 2850 nacho
                        try {
421
                                capa.load();
422
                        } catch (DriverIOException e) {
423
                                throw new DriverException(e);
424
                        }
425
                }
426
427
                return capa;
428
        }
429 10666 caballero
430 10195 nacho
        /**
431
         * Creates a new raster layer in memory. To create this layer type we have to set a data
432
         * buffer and a bounding box instead of a file. Don't use without CMS raster library that
433
         * include MemoryRasterDriver implementation.
434
         * @param layerName Layer name
435
         * @param d raster driver
436
         * @param buf data buffer
437 10666 caballero
         * @param ext bounding box
438
         * @param proj projection
439 10195 nacho
         * @return raster layer
440
         * @throws DriverException
441
         */
442
        public static FLyrRaster createLayer(String layerName, RasterDriver d,
443
                        RasterBuf buf, Extent ext, IProjection proj) throws DriverException {
444
                RasterAdapter adapter = new RasterFileAdapter(null);
445
                adapter.setDriver(d);
446 4143 caballero
447 10195 nacho
                FLyrRaster capa = new FLyrRaster();
448
                capa.setName(layerName);
449 10666 caballero
450 10195 nacho
                // TODO Meter esto dentro de la comprobaci?n de si hay memoria
451
                if (false) {
452
                } else {
453
                        capa.setSource(adapter);
454
                        capa.setProjection(proj);
455
                        capa.setBuffer(buf);
456
                        capa.setExtent(ext);
457
                        try {
458
                                capa.load();
459
                        } catch (DriverIOException e) {
460
                                throw new DriverException(e);
461
                        }
462
                }
463
464
                return capa;
465
        }
466
467 732 fernando
        /**
468
         * Crea un RandomVectorialWFS con el driver que se le pasa como par?metro y
469
         * guard?ndose la URL del servidor que se pasa como par?metro
470 10666 caballero
         *
471 1034 vcaballero
         * @param driver
472
         * @param host
473
         * @param port
474
         * @param user
475
         * @param password
476
         * @param dbName
477
         * @param tableName
478
         * @param proj
479 10666 caballero
         *
480 1034 vcaballero
         * @return Capa creada.
481 10666 caballero
         *
482 1034 vcaballero
         * @throws UnsupportedOperationException
483 732 fernando
         */
484 11928 caballero
        public static FLayer createLayer(IVectorialDatabaseDriver driver,
485 8765 jjdelcerro
                        String host, int port, String user, String password, String dbName,
486
                        String tableName, IProjection proj) {
487 732 fernando
                throw new UnsupportedOperationException();
488
        }
489 4143 caballero
490 11928 caballero
        public static FLayer createDBLayer(IVectorialDatabaseDriver driver,
491 8765 jjdelcerro
                        String layerName, IProjection proj) {
492 4143 caballero
493 1691 fjp
                FLyrVect capa = new FLyrVect();
494 4143 caballero
495 1691 fjp
                capa.setName(layerName);
496
                VectorialDBAdapter dbAdapter = new VectorialDBAdapter();
497 4143 caballero
                dbAdapter.setDriver(driver);
498
499 1691 fjp
                capa.setSource(dbAdapter);
500
                capa.setProjection(proj);
501
                try {
502
                        if (driver instanceof WithDefaultLegend) {
503
                                WithDefaultLegend aux = (WithDefaultLegend) driver;
504
                                dbAdapter.start();
505 8765 jjdelcerro
                                capa.setLegend((VectorialLegend) aux.getDefaultLegend());
506 1691 fjp
                                dbAdapter.stop();
507 4143 caballero
                        } else {
508 8765 jjdelcerro
                                capa.setLegend(LegendFactory.createSingleSymbolLegend(capa
509
                                                .getShapeType()));
510 1691 fjp
                        }
511 10401 fjp
                        if (driver instanceof IDelayedDriver)
512
                        {
513 10442 fjp
                                // Por defecto, los drivers est?n listos para entregar
514
                                // features al terminar su initialize. Pero con los drivers
515
                                // que implementan IDelayedDriver, el driver es responsable
516
                                // de avisar cu?ndo est? listo
517
                                capa.getFLayerStatus().setDriverLoaded(false);
518 10666 caballero
                                ((IDelayedDriver) driver).addDriverEventListener(new DefaultDelayedDriverListener(capa));
519 10401 fjp
                        }
520 10633 fjp
                        // PARCHE: Llamamos a getXmlEntity del driver para que se rellenen
521
                        // los valores de host, port, etc, necesarios para un posible reload
522 10698 jmvivo
                        //FIXME: Se vuelve a dejar como estaba... el problema esta en el DefaultDBDriver.getXMLEntiy()
523
                        //       y comentarizemos esto o no, si no arreglamos ese metodo da problemas de persistencia
524
                        driver.setXMLEntity(driver.getXMLEntity());
525 10401 fjp
526 8765 jjdelcerro
                } catch (FieldNotFoundException e) {
527 10666 caballero
                        LegendDriverExceptionType excepType =
528 8765 jjdelcerro
                                new LegendDriverExceptionType("Error al construir la leyenda, campo no encontrado");
529
                        //TODO Para hacer esto extensible tiene que usarse puntos
530
                        //de extension, y comparar las clases de leyendas registradas
531 10666 caballero
                        VectorialLegend legend = (VectorialLegend)
532 8765 jjdelcerro
                                ((WithDefaultLegend)driver).getDefaultLegend();
533 10666 caballero
534 8765 jjdelcerro
                        excepType.setLegendLabelField(legend.getLabelField());
535
                        excepType.setLegendHeightField(legend.getLabelHeightField());
536
                        excepType.setLegendRotationField(legend.getLabelRotationField());
537
                        DriverException exception = new DriverException(e, excepType);
538 6537 jmvivo
                        capa.setAvailable(false);
539 8765 jjdelcerro
                        capa.addError(exception);
540 6400 jmvivo
                        return capa;
541 8765 jjdelcerro
                        // throw new UnsupportedOperationException(e.getMessage());
542
                } catch (DriverException e) {
543 10666 caballero
                        DBDriverExceptionType excepType =
544 8765 jjdelcerro
                                new DBDriverExceptionType();
545
                        excepType.setDriverName(driver.getName());
546
                        excepType.setTableName(driver.getTableName());
547
                        DriverException exception = new DriverException(e, excepType);
548
                        capa.addError(exception);
549
                        capa.setAvailable(false);
550 6400 jmvivo
                        return capa;
551 8765 jjdelcerro
                        // throw new UnsupportedOperationException(e.getMessage());
552
                } catch (Exception e) {
553
                        ExceptionDescription excepType = new GenericDriverExceptionType();
554
                        DriverException exception = new DriverException(e, excepType);
555
                        capa.addError(exception);
556
                        capa.setAvailable(false);
557
                        return capa;
558
                }
559 303 fernando
560 1691 fjp
                return capa;
561
562 8765 jjdelcerro
        }
563 1691 fjp
564 2183 fernando
        /**
565
         * @param driver
566
         * @param layerName
567
         * @param object
568
         * @return
569
         * @throws SQLException
570
         * @throws DriverIOException
571
         * @throws IOException
572
         * @throws DriverLoadException
573
         * @throws com.hardcode.gdbms.engine.data.driver.DriverException
574
         * @throws NoSuchTableException
575
         * @throws ClassNotFoundException
576 4143 caballero
         * @throws
577 2183 fernando
         */
578 11928 caballero
        public static FLayer createDisconnectedDBLayer(IVectorialDatabaseDriver driver,
579 8765 jjdelcerro
                        String layerName, IProjection proj, ProgressListener listener)
580 11928 caballero
                        throws DBException, IOException, DriverIOException,
581 8765 jjdelcerro
                        DriverLoadException, NoSuchTableException,
582
                        com.hardcode.gdbms.engine.data.driver.DriverException,
583
                        ClassNotFoundException {
584
                VectorialDisconnectedDBAdapter dbAdapter = new VectorialDisconnectedDBAdapter();
585
                dbAdapter.setDriver(driver);
586
                DataSource ds = dbAdapter.getRecordset();
587
                ds.start();
588
                String database = dataSourceFactory.getTempFile();
589
                String[] fieldNames = new String[ds.getFieldCount() + 1];
590
                System.arraycopy(ds.getFieldNames(), 0, fieldNames, 1, ds
591
                                .getFieldCount());
592
                fieldNames[0] = "the_geom";
593
                int[] types = new int[fieldNames.length];
594
                types[0] = Types.BINARY;
595
                for (int i = 1; i < types.length; i++) {
596
                        types[i] = ds.getFieldType(i - 1);
597
                }
598 11928 caballero
                String dsName=null;
599
                try {
600
                        dsName = dataSourceFactory.createTable(database,
601
                                        ds.getPKNames(), fieldNames, types);
602
                } catch (SQLException e) {
603
                        throw new DBException(e);
604
                }
605 4143 caballero
606 8765 jjdelcerro
                DBLayerDefinition lyrDef = new DBLayerDefinition();
607
                lyrDef.setTableName(dsName);
608
                lyrDef.setName(layerName);
609
                lyrDef.setFieldNames(ds.getFieldNames());
610
                lyrDef.setFieldGeometry("the_geom");
611
                lyrDef.setFieldID(ds.getPKNames()[0]);
612
                lyrDef.setClassToInstantiate("org.hsqldb.jdbcDriver");
613 4143 caballero
614 8765 jjdelcerro
                dataSourceFactory.addDBDataSourceByTable(dsName, null, 0, "sa", "",
615
                                database, dsName, "GDBMS HSQLDB Transactional driver");
616
                DataSource local = dataSourceFactory.createRandomDataSource(dsName,
617
                                DataSourceFactory.MANUAL_OPENING);
618
                local.start();
619
                DataWare dw = local
620
                                .getDataWare(DataSourceFactory.DATA_WARE_COHERENT_ROW_ORDER);
621
                dw.start();
622
                long t1 = System.currentTimeMillis();
623
                dw.beginTrans();
624 4143 caballero
625 8765 jjdelcerro
                if (listener == null) {
626
                        listener = new ProgressListener() {
627
                                /**
628
                                 * @see com.iver.cit.gvsig.fmap.ProgressListener#progress(int)
629
                                 */
630
                                public void progress(int n) {
631
                                        // do nothing
632
                                }
633
                        };
634
                }
635 4143 caballero
636 8765 jjdelcerro
                for (int i = 0; i < dbAdapter.getShapeCount(); i++) {
637
                        Value[] row = new Value[ds.getFieldCount() + 1];
638 4143 caballero
639 8765 jjdelcerro
                        byte[] bytes = dbAdapter.getShape(i).toWKB();
640
                        row[0] = ValueFactory.createValue(bytes);
641 4143 caballero
642 8765 jjdelcerro
                        for (int j = 0; j < ds.getFieldCount(); j++) {
643
                                row[j + 1] = ds.getFieldValue(i, j);
644
                        }
645 2183 fernando
646 8765 jjdelcerro
                        dw.insertFilledRow(row);
647
                        listener.progress(100 * i / dbAdapter.getShapeCount());
648
                }
649 4143 caballero
650 8765 jjdelcerro
                long t2 = System.currentTimeMillis();
651
                dw.commitTrans();
652
                long t3 = System.currentTimeMillis();
653
                System.out.println((t2 - t1) + " - " + (t3 - t2));
654
                dw.stop();
655
                local.stop();
656
                ds.stop();
657 11928 caballero
                IVectorialJDBCDriver cacheDriver = (IVectorialJDBCDriver) LayerFactory
658 8765 jjdelcerro
                                .getDM().getDriver("HSQLDB Driver");
659
                Class.forName("org.hsqldb.jdbcDriver");
660 11928 caballero
                IConnection conn=ConnectionFactory.createConnection("jdbc:hsqldb:file:" + database, "sa", "");
661
                cacheDriver.setData(conn, lyrDef);
662 8765 jjdelcerro
                cacheDriver.setWorkingArea(driver.getWorkingArea());
663
                return createDBLayer(cacheDriver, layerName, proj);
664 2183 fernando
        }
665 4143 caballero
666 732 fernando
        /**
667
         * Crea una FLyrComplexRaster que ataca al driver que se pasa como
668
         * par?metro.
669 10666 caballero
         *
670 1034 vcaballero
         * @param driver
671
         * @param f
672
         * @param proj
673 10666 caballero
         *
674 8765 jjdelcerro
         * @throws IllegalArgumentException
675
         *             Si se pasa un driver que no implementa
676
         *             GeorreferencedRasterDriver o NotGeorreferencedRasterDriver
677 732 fernando
         */
678
        public static void createLayer(RasterDriver driver, File f, IProjection proj)
679 8765 jjdelcerro
                        throws IllegalArgumentException {
680 732 fernando
        }
681 408 fernando
682 732 fernando
        /**
683 1034 vcaballero
         * Devuelve el DriverManager.
684 10666 caballero
         *
685 1034 vcaballero
         * @return DriverManager.
686 732 fernando
         */
687
        public static DriverManager getDM() {
688 1839 fernando
                initializeDriverManager();
689 732 fernando
690
                return driverManager;
691
        }
692 8765 jjdelcerro
693 4143 caballero
        /**
694
         * Devuelve el WriterManager.
695 10666 caballero
         *
696 4143 caballero
         * @return WriterManager.
697
         */
698
        public static WriterManager getWM() {
699
                initializeWriterManager();
700 732 fernando
701 4143 caballero
                return writerManager;
702
        }
703 8765 jjdelcerro
704 732 fernando
        /**
705 1034 vcaballero
         * Inicializa el DriverManager.
706 732 fernando
         */
707
        private static void initializeDriverManager() {
708
                if (driverManager == null) {
709
                        driverManager = new DriverManager();
710
                        driverManager.loadDrivers(new File(LayerFactory.driversPath));
711
712
                        Throwable[] failures = driverManager.getLoadFailures();
713
714
                        for (int i = 0; i < failures.length; i++) {
715 2183 fernando
                                logger.error("", failures[i]);
716 626 fernando
                        }
717
718 1828 fernando
                        getDataSourceFactory().setDriverManager(driverManager);
719 2183 fernando
                        getDataSourceFactory().initialize();
720 1836 fernando
                        QueryManager.registerQuery(new ArcJoin());
721 732 fernando
                }
722
        }
723 8765 jjdelcerro
724 4143 caballero
        /**
725
         * Inicializa el DriverManager.
726
         */
727
        private static void initializeWriterManager() {
728
                if (writerManager == null) {
729
                        writerManager = new WriterManager();
730
                        writerManager.loadWriters(new File(LayerFactory.writersPath));
731 408 fernando
732 4143 caballero
                        Throwable[] failures = writerManager.getLoadFailures();
733
734
                        for (int i = 0; i < failures.length; i++) {
735
                                logger.error("", failures[i]);
736
                        }
737
738
                        getDataSourceFactory().setWriterManager(writerManager);
739
                        getDataSourceFactory().initialize();
740 8765 jjdelcerro
                        // QueryManager.registerQuery(new ArcJoin());
741 4143 caballero
                }
742
        }
743 8765 jjdelcerro
744 732 fernando
        /**
745
         * sets drivers Directory
746 10666 caballero
         *
747 732 fernando
         * @param path
748
         */
749
        public static void setDriversPath(String path) {
750
                LayerFactory.driversPath = path;
751
                initializeDriverManager();
752
        }
753 8765 jjdelcerro
754 1773 fernando
        /**
755 4143 caballero
         * sets writers Directory
756 10666 caballero
         *
757 4143 caballero
         * @param path
758
         */
759
        public static void setWritersPath(String path) {
760
                LayerFactory.writersPath = path;
761
                initializeWriterManager();
762
        }
763
764
        /**
765 1773 fernando
         * @return Returns the dataSourceFactory.
766
         */
767
        public static DataSourceFactory getDataSourceFactory() {
768 8765 jjdelcerro
                if (dataSourceFactory == null) {
769 1828 fernando
                        dataSourceFactory = new DataSourceFactory();
770
                }
771 1773 fernando
                return dataSourceFactory;
772
        }
773 214 fernando
}