Statistics
| Revision:

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

History | View | Annotate | Download (24.4 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
                        driver.setXMLEntity(driver.getXMLEntity());
560

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

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

    
595
                return capa;
596

    
597
        }
598

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

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

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

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

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

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

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

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

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

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

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

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

    
721
                return driverManager;
722
        }
723

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

    
732
                return writerManager;
733
        }
734

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

    
743
                        Throwable[] failures = driverManager.getLoadFailures();
744

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

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

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

    
763
                        Throwable[] failures = writerManager.getLoadFailures();
764

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

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

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

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

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