Statistics
| Revision:

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

History | View | Annotate | Download (24.6 KB)

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

    
43
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
import org.cresques.io.data.RasterBuf;
52
import org.cresques.px.Extent;
53

    
54
import com.hardcode.driverManager.Driver;
55
import com.hardcode.driverManager.DriverLoadException;
56
import com.hardcode.driverManager.DriverManager;
57
import com.hardcode.driverManager.IDelayedDriver;
58
import com.hardcode.driverManager.WriterManager;
59
import com.hardcode.gdbms.engine.customQuery.QueryManager;
60
import com.hardcode.gdbms.engine.data.DataSource;
61
import com.hardcode.gdbms.engine.data.DataSourceFactory;
62
import com.hardcode.gdbms.engine.data.NoSuchTableException;
63
import com.hardcode.gdbms.engine.data.edition.DataWare;
64
import com.hardcode.gdbms.engine.instruction.FieldNotFoundException;
65
import com.hardcode.gdbms.engine.values.Value;
66
import com.hardcode.gdbms.engine.values.ValueFactory;
67
import com.iver.cit.gvsig.fmap.DBDriverExceptionType;
68
import com.iver.cit.gvsig.fmap.DriverException;
69
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
import com.iver.cit.gvsig.fmap.ProgressListener;
74
import com.iver.cit.gvsig.fmap.ViewPort;
75
import com.iver.cit.gvsig.fmap.drivers.DBLayerDefinition;
76
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
77
import com.iver.cit.gvsig.fmap.drivers.RasterDriver;
78
import com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver;
79
import com.iver.cit.gvsig.fmap.drivers.VectorialDriver;
80
import com.iver.cit.gvsig.fmap.drivers.VectorialFileDriver;
81
import com.iver.cit.gvsig.fmap.drivers.VectorialJDBCDriver;
82
import com.iver.cit.gvsig.fmap.drivers.WithDefaultLegend;
83
import com.iver.cit.gvsig.fmap.operations.arcview.ArcJoin;
84
import com.iver.cit.gvsig.fmap.rendering.LegendFactory;
85
import com.iver.cit.gvsig.fmap.rendering.VectorialLegend;
86
import com.iver.utiles.ExceptionDescription;
87

    
88
/**
89
 * Crea un adaptador del driver que se le pasa como par?metro en los m?todos
90
 * createLayer. Si hay memoria suficiente se crea un FLyrMemory que pasa todas
91
 * las features del driver a memoria
92
 */
93
public class LayerFactory {
94
        private static Logger logger = Logger.getLogger(LayerFactory.class
95
                        .getName());
96

    
97
        private static String driversPath = "../FMap 03/drivers";
98

    
99
        private static String writersPath = "../FMap 03/drivers";
100

    
101
        private static DriverManager driverManager;
102

    
103
        private static WriterManager writerManager;
104

    
105
        private static DataSourceFactory dataSourceFactory;
106

    
107
        /**
108
         * Map en el que se guarda para cada fuente de datos a?adida al sistema, el
109
         * adaptador que la maneja. Ha de ser un TreeMap ya que esta clase define la
110
         * igualdad entre las claves a traves del m?todo equals de las mismas. Los
111
         * objetos FileSource, DBSource y WFSSource tienen definido el m?todo equals
112
         * de forma que devuelven true cuando dos objetos apuntan a la misma fuente
113
         * de datos
114
         */
115
        private static TreeMap sourceAdapter;
116

    
117
        /*
118
         * Crea un RandomVectorialFile con el driver que se le pasa como par?metro y
119
         * guard?ndose el nombre del fichero para realizar los accesos, la capa
120
         * tendr? asociada la proyecci?n que se pasa como parametro tambi?n
121
         *
122
         * @param layerName Nombre de la capa. @param driverName Nombre del driver.
123
         * @param f fichero. @param proj Proyecci?n.
124
         *
125
         * @return FLayer. @throws DriverException
126
         *
127
         * @throws DriverException @throws DriverIOException
128
         */
129
        public static FLayer createLayer(String layerName, String driverName,
130
                        File f, IProjection proj) throws DriverException {
131
                // Se obtiene el driver que lee
132
                DriverManager dm = getDM();
133

    
134
                try {
135
                        Driver d = dm.getDriver(driverName);
136

    
137
                        if (d instanceof VectorialFileDriver) {
138
                                return createLayer(layerName, (VectorialFileDriver) d, f, proj);
139
                        } else if (d instanceof RasterDriver) {
140
                                return createLayer(layerName, (RasterDriver) d, f, proj);
141
                        }
142
                } catch (DriverLoadException e) {
143
                        //hay un poco de lio sobre que excepciones se dejan subir
144
                        //arriba y que excepciones se quedan en LayerFactory
145
                        //(esto se debe a que queremos intentar recuperar ciertas capas)
146
                        //las excepciones de este metodo se dejan subir todas, puesto
147
                        //que las excepciones de los dos otros metodos createLayer si que
148
                        //se atrapan
149
                        DriverNotLoadedExceptionType exceptionType =
150
                                new DriverNotLoadedExceptionType();
151
                        exceptionType.setDriverName(driverName);
152
                        DriverException exception =
153
                                new DriverException(e, exceptionType);
154
                        throw exception;
155
                }
156

    
157
                return null;
158
        }
159

    
160
        /**
161
         * It creates a FLayer (FLyrVect) which reads its data from a file driver,
162
         * projected in the specified projection.
163
         *
164
         * @param layerName
165
         *            name of the layer
166
         * @param d
167
         *            vectorial file driver to read layer's data
168
         * @param f
169
         *            file associated to the driver
170
         * @param proj
171
         *            layer projection
172
         *
173
         * @return FLayer new vectorial layer
174
         *
175
         * @throws DriverException
176
         */
177
        public static FLayer createLayer(String layerName, VectorialFileDriver d,
178
                        File f, IProjection proj)
179

    
180
        /*throws DriverException*/ {
181

    
182
                // TODO Comprobar si hay un adaptador ya
183
                VectorialFileAdapter adapter = new VectorialFileAdapter(f);
184
                adapter.setDriver((VectorialDriver) d);
185

    
186
                FLyrVect capa = new FLyrVect();
187
                capa.setName(layerName);
188

    
189
                // TODO Meter esto dentro de la comprobaci?n de si hay memoria
190
                if (false) {
191
                } else {
192
                        capa.setSource(adapter);
193
                        capa.setProjection(proj);
194
                }
195

    
196
                try {
197
                        // Le asignamos tambi?n una legenda por defecto acorde con
198
                        // el tipo de shape que tenga. Tampoco s? si es aqu? el
199
                        // sitio adecuado, pero en fin....
200
                        if (d instanceof WithDefaultLegend) {
201
                                WithDefaultLegend aux = (WithDefaultLegend) d;
202
                                adapter.start();
203
                                capa.setLegend((VectorialLegend) aux.getDefaultLegend());
204
                                adapter.stop();
205
                        } else {
206
                                capa.setLegend(LegendFactory.createSingleSymbolLegend(capa
207
                                                .getShapeType()));
208
                        }
209

    
210
                } catch (FieldNotFoundException e) {
211
                        //this exception is caused in legend creation
212
                        LegendDriverExceptionType excepType =
213
                                new LegendDriverExceptionType("Error al construir la leyenda");
214
                        //TODO Para hacer esto extensible tiene que usarse puntos
215
                        //de extension, y comparar las clases de leyendas registradas
216
                        VectorialLegend legend = (VectorialLegend)
217
                                ((WithDefaultLegend)d).getDefaultLegend();
218

    
219
                        excepType.setLegendLabelField(legend.getLabelField());
220
                        excepType.setLegendHeightField(legend.getLabelHeightField());
221
                        excepType.setLegendRotationField(legend.getLabelRotationField());
222
                        DriverException exception = new DriverException(e, excepType);
223
                        capa.setAvailable(false);
224
                        capa.addError(exception);
225

    
226
                } catch (DriverIOException e) {
227
                        //this error is caused for file IO problems
228
                        DriverIOExceptionType excepType =
229
                                new DriverIOExceptionType();
230
                        excepType.setFile(f);
231
                        DriverException exception = new DriverException(e, excepType);
232
                        capa.setAvailable(false);
233
                        capa.addError(exception);
234
                }
235

    
236
                /*
237
                 * catch(DriverException e){
238
                 * ESTO HAY QUE CAPTURARLO,DE FORMA QUE CREATELAYER NO LANCE NINGUNA
239
                 * EXCEPCION (A NO SER QUE SEA IRRECUPERABLE)
240
                 * }
241
                 */
242
                catch(Exception e){
243
                        GenericDriverExceptionType type = new GenericDriverExceptionType();
244
                        DriverException exception = new DriverException(e, type);
245
                        capa.setAvailable(false);
246
                        capa.addError(exception);
247
                }
248
                return capa;
249
        }
250

    
251
        /**
252
         * Creates a new vectorial layer from a generic layer (by generic whe mean
253
         * that we dont know a priory its origin: file, memory, jdbc database, etc.
254
         *
255
         * @param layerName
256
         * @param d
257
         * @param proj
258
         * @return
259
         * @throws DriverException
260
         */
261
        public static FLayer createLayer(String layerName, VectorialDriver d,
262
                        IProjection proj)
263
        /*
264
        throws DriverException
265
        */{
266
                VectorialAdapter adapter = null;
267
                if (d instanceof VectorialFileDriver) {
268
                        adapter = new VectorialFileAdapter(((VectorialFileDriver) d)
269
                                        .getFile());
270
                } else if (d instanceof VectorialJDBCDriver) {
271
                        adapter = new VectorialDBAdapter();
272
                } else {
273
                        adapter = new VectorialDefaultAdapter();
274
                }
275
                adapter.setDriver((VectorialDriver) d);
276

    
277
                FLyrVect capa = new FLyrVect();
278
                capa.setName(layerName);
279

    
280
                capa.setSource(adapter);
281
                capa.setProjection(proj);
282

    
283
                try {
284

    
285
                        // Le asignamos tambi?n una legenda por defecto acorde con
286
                        // el tipo de shape que tenga. Tampoco s? si es aqu? el
287
                        // sitio adecuado, pero en fin....
288
                        if (d instanceof WithDefaultLegend) {
289
                                WithDefaultLegend aux = (WithDefaultLegend) d;
290
                                adapter.start();
291
                                capa.setLegend((VectorialLegend) aux.getDefaultLegend());
292
                                adapter.stop();
293
                        } else {
294
                                capa.setLegend(LegendFactory.createSingleSymbolLegend(capa
295
                                                .getShapeType()));
296
                        }
297
                } catch (FieldNotFoundException e) {
298
//                        this exception is caused in legend creation
299
                        LegendDriverExceptionType excepType =
300
                                new LegendDriverExceptionType("error al construir la leyenda, campo no encontrado");
301

    
302
                        //TODO Para hacer esto extensible tiene que usarse puntos
303
                        //de extension, y comparar las clases de leyendas registradas
304
                        VectorialLegend legend = (VectorialLegend)
305
                                ((WithDefaultLegend)d).getDefaultLegend();
306
                        excepType.setDriverName(d.getName());
307
                        excepType.setLegendLabelField(legend.getLabelField());
308
                        excepType.setLegendHeightField(legend.getLabelHeightField());
309
                        excepType.setLegendRotationField(legend.getLabelRotationField());
310

    
311
                        DriverException exception = new DriverException(e, excepType);
312
                        capa.setAvailable(false);
313
                        capa.addError(exception);
314
                } catch (DriverIOException e) {
315
                        //by design, start and stop calls to adapter could
316
                        //cause this exception.
317

    
318
                        //but JDBC implementations catchs all exceptions,
319
                        //and rest of layers (WFSLayer, etc.) dont use LayerFactory
320
                        ExceptionDescription type = null;
321
                        if (d instanceof VectorialFileDriver) {
322
                                File f = ((VectorialFileDriver)adapter).getFile();
323
                                type =
324
                                        new DriverIOExceptionType();
325
                                ((DriverIOExceptionType)type).setFile(f);
326

    
327
                        }else{
328
                                type = new GenericDriverExceptionType();
329
                        }
330
                        DriverException exception = new DriverException(e, type);
331
                        capa.setAvailable(false);
332
                        capa.addError(exception);
333
                }catch(Exception e){
334
                        GenericDriverExceptionType type = new GenericDriverExceptionType();
335
                        DriverException exception = new DriverException(e, type);
336
                        capa.setAvailable(false);
337
                        capa.addError(exception);
338
                }
339

    
340
                return capa;
341
        }
342

    
343
        /**
344
         * Crea una capa Raster a partir del nombre driver, fichero y proyecci?n.
345
         *
346
         * @param layerName
347
         *            Nombre de la capa.
348
         * @param d
349
         *            RasterDriver.
350
         * @param f
351
         *            Fichero.
352
         * @param proj
353
         *            Proyecci?n.
354
         *
355
         * @return Nueva capa de tipo raster.
356
         *
357
         * @throws DriverIOException
358
         */
359
        public static FLyrRaster createLayer(String layerName, RasterDriver d,
360
                        File f, IProjection proj) throws DriverException {
361
                RasterAdapter adapter = new RasterFileAdapter(f);
362
                adapter.setDriver(d);
363

    
364
                FLyrRaster capa = new FLyrRaster();
365
                capa.setName(layerName);
366

    
367
                // TODO Meter esto dentro de la comprobaci?n de si hay memoria
368
                if (false) {
369
                } else {
370
                        capa.setSource(adapter);
371
                        capa.setProjection(proj);
372
                        try {
373
                                capa.load();
374
                        } catch (DriverIOException e) {
375
                                throw new DriverException(e);
376
                        }
377
                }
378

    
379
                return capa;
380
        }
381

    
382
        /**
383
         * Crea una capa Raster a partir del nombre driver, fichero y proyecci?n y
384
         * coordenadas de georeferenciaci?n. Esta funci?n es para georeferenciar
385
         * capas raster. Para imagenes que no tienen georeferenciaci?n hay que
386
         * asignarle una temporal, normalmente a partir de la vista activa.
387
         *
388
         * @param layerName
389
         *            Nombre de la capa.
390
         * @param d
391
         *            RasterDriver.
392
         * @param f
393
         *            Fichero.
394
         * @param proj
395
         *            Proyecci?n.
396
         * @param extent
397
         *            Extent de la vista activa
398
         *
399
         * @return Nueva capa de tipo raster.
400
         *
401
         * @throws DriverIOException
402
         */
403
        public static FLyrRaster createLayer(String layerName, RasterDriver d,
404
                        File f, IProjection proj, ViewPort vp) throws DriverException {
405
                RasterAdapter adapter = new RasterFileAdapter(f);
406
                adapter.setDriver(d);
407

    
408
                FLyrRaster capa = new FLyrRaster();
409
                capa.setName(layerName);
410

    
411
                // TODO Meter esto dentro de la comprobaci?n de si hay memoria
412
                if (false) {
413
                } else {
414
                        capa.setSource(adapter);
415
                        capa.setProjection(proj);
416
                        // capa.setTempExtent(vp);
417
                        try {
418
                                capa.load();
419
                        } catch (DriverIOException e) {
420
                                throw new DriverException(e);
421
                        }
422
                }
423

    
424
                return capa;
425
        }
426

    
427
        /**
428
         * Creates a new raster layer in memory. To create this layer type we have to set a data
429
         * buffer and a bounding box instead of a file. Don't use without CMS raster library that
430
         * include MemoryRasterDriver implementation.
431
         * @param layerName Layer name
432
         * @param d raster driver
433
         * @param buf data buffer
434
         * @param ext bounding box
435
         * @param proj projection
436
         * @return raster layer
437
         * @throws DriverException
438
         */
439
        public static FLyrRaster createLayer(String layerName, RasterDriver d,
440
                        RasterBuf buf, Extent ext, IProjection proj) throws DriverException {
441
                RasterAdapter adapter = new RasterFileAdapter(null);
442
                adapter.setDriver(d);
443

    
444
                FLyrRaster capa = new FLyrRaster();
445
                capa.setName(layerName);
446

    
447
                // TODO Meter esto dentro de la comprobaci?n de si hay memoria
448
                if (false) {
449
                } else {
450
                        capa.setSource(adapter);
451
                        capa.setProjection(proj);
452
                        capa.setBuffer(buf);
453
                        capa.setExtent(ext);
454
                        try {
455
                                capa.load();
456
                        } catch (DriverIOException e) {
457
                                throw new DriverException(e);
458
                        }
459
                }
460

    
461
                return capa;
462
        }
463

    
464
        public static FLayer createArcSDELayer(String layerName,
465
                        VectorialDatabaseDriver driver, IProjection proj) {
466
                // throw new UnsupportedOperationException();
467
                FLyrVect layer = new FLyrVect();
468
                VectorialAdapter adapter = new VectorialDBAdapter();
469
                adapter.setDriver(driver);
470

    
471
                layer.setName(layerName);
472
                layer.setSource(adapter);
473
                layer.setProjection(proj);
474
                try {
475
                        if (driver instanceof WithDefaultLegend) {
476
                                WithDefaultLegend aux = (WithDefaultLegend) driver;
477
                                adapter.start();
478
                                layer.setLegend((VectorialLegend) aux.getDefaultLegend());
479
                                adapter.stop();
480
                        } else {
481
                                layer.setLegend(LegendFactory.createSingleSymbolLegend(layer
482
                                                .getShapeType()));
483
                        }
484
                } catch (FieldNotFoundException e) {
485
                        throw new UnsupportedOperationException(e.getMessage());
486
                } catch (DriverIOException e) {
487
                        throw new UnsupportedOperationException(e.getMessage());
488
                } catch (DriverException e) {
489
                        // TODO Auto-generated catch block
490
                        e.printStackTrace();
491
                }
492

    
493
                try {
494
                        layer.setLegend(LegendFactory.createSingleSymbolLegend(layer
495
                                        .getShapeType()));
496
                } catch (FieldNotFoundException e) {
497
                        e.printStackTrace();
498
                } catch (DriverException e) {
499
                        e.printStackTrace();
500
                }
501
                return layer;
502
        }
503

    
504
        /**
505
         * Crea un RandomVectorialWFS con el driver que se le pasa como par?metro y
506
         * guard?ndose la URL del servidor que se pasa como par?metro
507
         *
508
         * @param driver
509
         * @param host
510
         * @param port
511
         * @param user
512
         * @param password
513
         * @param dbName
514
         * @param tableName
515
         * @param proj
516
         *
517
         * @return Capa creada.
518
         *
519
         * @throws UnsupportedOperationException
520
         */
521
        public static FLayer createLayer(VectorialDatabaseDriver driver,
522
                        String host, int port, String user, String password, String dbName,
523
                        String tableName, IProjection proj) {
524
                throw new UnsupportedOperationException();
525
        }
526

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

    
530
                FLyrVect capa = new FLyrVect();
531

    
532
                capa.setName(layerName);
533
                VectorialDBAdapter dbAdapter = new VectorialDBAdapter();
534
                dbAdapter.setDriver(driver);
535

    
536
                capa.setSource(dbAdapter);
537
                capa.setProjection(proj);
538
                try {
539
                        if (driver instanceof WithDefaultLegend) {
540
                                WithDefaultLegend aux = (WithDefaultLegend) driver;
541
                                dbAdapter.start();
542
                                capa.setLegend((VectorialLegend) aux.getDefaultLegend());
543
                                dbAdapter.stop();
544
                        } else {
545
                                capa.setLegend(LegendFactory.createSingleSymbolLegend(capa
546
                                                .getShapeType()));
547
                        }
548
                        if (driver instanceof IDelayedDriver)
549
                        {
550
                                // Por defecto, los drivers est?n listos para entregar
551
                                // features al terminar su initialize. Pero con los drivers
552
                                // que implementan IDelayedDriver, el driver es responsable
553
                                // de avisar cu?ndo est? listo
554
                                capa.getFLayerStatus().setDriverLoaded(false);
555
                                ((IDelayedDriver) driver).addDriverEventListener(new DefaultDelayedDriverListener(capa));
556
                        }
557
                        // PARCHE: Llamamos a getXmlEntity del driver para que se rellenen
558
                        // los valores de host, port, etc, necesarios para un posible reload
559
                        //FIXME: Se vuelve a dejar como estaba... el problema esta en el DefaultDBDriver.getXMLEntiy()
560
                        //       y comentarizemos esto o no, si no arreglamos ese metodo da problemas de persistencia
561
                        driver.setXMLEntity(driver.getXMLEntity());
562

    
563
                } catch (FieldNotFoundException e) {
564
                        LegendDriverExceptionType excepType =
565
                                new LegendDriverExceptionType("Error al construir la leyenda, campo no encontrado");
566
                        //TODO Para hacer esto extensible tiene que usarse puntos
567
                        //de extension, y comparar las clases de leyendas registradas
568
                        VectorialLegend legend = (VectorialLegend)
569
                                ((WithDefaultLegend)driver).getDefaultLegend();
570

    
571
                        excepType.setLegendLabelField(legend.getLabelField());
572
                        excepType.setLegendHeightField(legend.getLabelHeightField());
573
                        excepType.setLegendRotationField(legend.getLabelRotationField());
574
                        DriverException exception = new DriverException(e, excepType);
575
                        capa.setAvailable(false);
576
                        capa.addError(exception);
577
                        return capa;
578
                        // throw new UnsupportedOperationException(e.getMessage());
579
                } catch (DriverException e) {
580
                        DBDriverExceptionType excepType =
581
                                new DBDriverExceptionType();
582
                        excepType.setDriverName(driver.getName());
583
                        excepType.setTableName(driver.getTableName());
584
                        DriverException exception = new DriverException(e, excepType);
585
                        capa.addError(exception);
586
                        capa.setAvailable(false);
587
                        return capa;
588
                        // throw new UnsupportedOperationException(e.getMessage());
589
                } catch (Exception e) {
590
                        ExceptionDescription excepType = new GenericDriverExceptionType();
591
                        DriverException exception = new DriverException(e, excepType);
592
                        capa.addError(exception);
593
                        capa.setAvailable(false);
594
                        return capa;
595
                }
596

    
597
                return capa;
598

    
599
        }
600

    
601
        /**
602
         * @param driver
603
         * @param layerName
604
         * @param object
605
         * @return
606
         * @throws SQLException
607
         * @throws DriverIOException
608
         * @throws IOException
609
         * @throws DriverLoadException
610
         * @throws com.hardcode.gdbms.engine.data.driver.DriverException
611
         * @throws NoSuchTableException
612
         * @throws ClassNotFoundException
613
         * @throws
614
         */
615
        public static FLayer createDisconnectedDBLayer(VectorialJDBCDriver driver,
616
                        String layerName, IProjection proj, ProgressListener listener)
617
                        throws SQLException, IOException, DriverIOException,
618
                        DriverLoadException, NoSuchTableException,
619
                        com.hardcode.gdbms.engine.data.driver.DriverException,
620
                        ClassNotFoundException {
621
                VectorialDisconnectedDBAdapter dbAdapter = new VectorialDisconnectedDBAdapter();
622
                dbAdapter.setDriver(driver);
623
                DataSource ds = dbAdapter.getRecordset();
624
                ds.start();
625
                String database = dataSourceFactory.getTempFile();
626
                String[] fieldNames = new String[ds.getFieldCount() + 1];
627
                System.arraycopy(ds.getFieldNames(), 0, fieldNames, 1, ds
628
                                .getFieldCount());
629
                fieldNames[0] = "the_geom";
630
                int[] types = new int[fieldNames.length];
631
                types[0] = Types.BINARY;
632
                for (int i = 1; i < types.length; i++) {
633
                        types[i] = ds.getFieldType(i - 1);
634
                }
635
                String dsName = dataSourceFactory.createTable(database,
636
                                ds.getPKNames(), fieldNames, types);
637

    
638
                DBLayerDefinition lyrDef = new DBLayerDefinition();
639
                lyrDef.setTableName(dsName);
640
                lyrDef.setName(layerName);
641
                lyrDef.setFieldNames(ds.getFieldNames());
642
                lyrDef.setFieldGeometry("the_geom");
643
                lyrDef.setFieldID(ds.getPKNames()[0]);
644
                lyrDef.setClassToInstantiate("org.hsqldb.jdbcDriver");
645

    
646
                dataSourceFactory.addDBDataSourceByTable(dsName, null, 0, "sa", "",
647
                                database, dsName, "GDBMS HSQLDB Transactional driver");
648
                DataSource local = dataSourceFactory.createRandomDataSource(dsName,
649
                                DataSourceFactory.MANUAL_OPENING);
650
                local.start();
651
                DataWare dw = local
652
                                .getDataWare(DataSourceFactory.DATA_WARE_COHERENT_ROW_ORDER);
653
                dw.start();
654
                long t1 = System.currentTimeMillis();
655
                dw.beginTrans();
656

    
657
                if (listener == null) {
658
                        listener = new ProgressListener() {
659
                                /**
660
                                 * @see com.iver.cit.gvsig.fmap.ProgressListener#progress(int)
661
                                 */
662
                                public void progress(int n) {
663
                                        // do nothing
664
                                }
665
                        };
666
                }
667

    
668
                for (int i = 0; i < dbAdapter.getShapeCount(); i++) {
669
                        Value[] row = new Value[ds.getFieldCount() + 1];
670

    
671
                        byte[] bytes = dbAdapter.getShape(i).toWKB();
672
                        row[0] = ValueFactory.createValue(bytes);
673

    
674
                        for (int j = 0; j < ds.getFieldCount(); j++) {
675
                                row[j + 1] = ds.getFieldValue(i, j);
676
                        }
677

    
678
                        dw.insertFilledRow(row);
679
                        listener.progress(100 * i / dbAdapter.getShapeCount());
680
                }
681

    
682
                long t2 = System.currentTimeMillis();
683
                dw.commitTrans();
684
                long t3 = System.currentTimeMillis();
685
                System.out.println((t2 - t1) + " - " + (t3 - t2));
686
                dw.stop();
687
                local.stop();
688
                ds.stop();
689
                VectorialJDBCDriver cacheDriver = (VectorialJDBCDriver) LayerFactory
690
                                .getDM().getDriver("HSQLDB Driver");
691
                Class.forName("org.hsqldb.jdbcDriver");
692

    
693
                cacheDriver.setData(java.sql.DriverManager.getConnection(
694
                                "jdbc:hsqldb:file:" + database, "sa", ""), lyrDef);
695
                cacheDriver.setWorkingArea(driver.getWorkingArea());
696
                return createDBLayer(cacheDriver, layerName, proj);
697
        }
698

    
699
        /**
700
         * Crea una FLyrComplexRaster que ataca al driver que se pasa como
701
         * par?metro.
702
         *
703
         * @param driver
704
         * @param f
705
         * @param proj
706
         *
707
         * @throws IllegalArgumentException
708
         *             Si se pasa un driver que no implementa
709
         *             GeorreferencedRasterDriver o NotGeorreferencedRasterDriver
710
         */
711
        public static void createLayer(RasterDriver driver, File f, IProjection proj)
712
                        throws IllegalArgumentException {
713
        }
714

    
715
        /**
716
         * Devuelve el DriverManager.
717
         *
718
         * @return DriverManager.
719
         */
720
        public static DriverManager getDM() {
721
                initializeDriverManager();
722

    
723
                return driverManager;
724
        }
725

    
726
        /**
727
         * Devuelve el WriterManager.
728
         *
729
         * @return WriterManager.
730
         */
731
        public static WriterManager getWM() {
732
                initializeWriterManager();
733

    
734
                return writerManager;
735
        }
736

    
737
        /**
738
         * Inicializa el DriverManager.
739
         */
740
        private static void initializeDriverManager() {
741
                if (driverManager == null) {
742
                        driverManager = new DriverManager();
743
                        driverManager.loadDrivers(new File(LayerFactory.driversPath));
744

    
745
                        Throwable[] failures = driverManager.getLoadFailures();
746

    
747
                        for (int i = 0; i < failures.length; i++) {
748
                                logger.error("", failures[i]);
749
                        }
750

    
751
                        getDataSourceFactory().setDriverManager(driverManager);
752
                        getDataSourceFactory().initialize();
753
                        QueryManager.registerQuery(new ArcJoin());
754
                }
755
        }
756

    
757
        /**
758
         * Inicializa el DriverManager.
759
         */
760
        private static void initializeWriterManager() {
761
                if (writerManager == null) {
762
                        writerManager = new WriterManager();
763
                        writerManager.loadWriters(new File(LayerFactory.writersPath));
764

    
765
                        Throwable[] failures = writerManager.getLoadFailures();
766

    
767
                        for (int i = 0; i < failures.length; i++) {
768
                                logger.error("", failures[i]);
769
                        }
770

    
771
                        getDataSourceFactory().setWriterManager(writerManager);
772
                        getDataSourceFactory().initialize();
773
                        // QueryManager.registerQuery(new ArcJoin());
774
                }
775
        }
776

    
777
        /**
778
         * sets drivers Directory
779
         *
780
         * @param path
781
         */
782
        public static void setDriversPath(String path) {
783
                LayerFactory.driversPath = path;
784
                initializeDriverManager();
785
        }
786

    
787
        /**
788
         * sets writers Directory
789
         *
790
         * @param path
791
         */
792
        public static void setWritersPath(String path) {
793
                LayerFactory.writersPath = path;
794
                initializeWriterManager();
795
        }
796

    
797
        /**
798
         * @return Returns the dataSourceFactory.
799
         */
800
        public static DataSourceFactory getDataSourceFactory() {
801
                if (dataSourceFactory == null) {
802
                        dataSourceFactory = new DataSourceFactory();
803
                }
804
                return dataSourceFactory;
805
        }
806
}