Statistics
| Revision:

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

History | View | Annotate | Download (23 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.net.URL;
46
import java.sql.SQLException;
47
import java.sql.Types;
48
import java.util.TreeMap;
49

    
50
import org.apache.log4j.Logger;
51
import org.cresques.cts.IProjection;
52

    
53
import com.hardcode.driverManager.Driver;
54
import com.hardcode.driverManager.DriverLoadException;
55
import com.hardcode.driverManager.DriverManager;
56
import com.hardcode.driverManager.WriterManager;
57
import com.hardcode.gdbms.engine.customQuery.QueryManager;
58
import com.hardcode.gdbms.engine.data.DataSource;
59
import com.hardcode.gdbms.engine.data.DataSourceFactory;
60
import com.hardcode.gdbms.engine.data.NoSuchTableException;
61
import com.hardcode.gdbms.engine.data.edition.DataWare;
62
import com.hardcode.gdbms.engine.instruction.FieldNotFoundException;
63
import com.hardcode.gdbms.engine.values.Value;
64
import com.hardcode.gdbms.engine.values.ValueFactory;
65
import com.iver.cit.gvsig.fmap.DBDriverExceptionType;
66
import com.iver.cit.gvsig.fmap.DriverException;
67
import com.iver.cit.gvsig.fmap.DriverIOExceptionType;
68
import com.iver.cit.gvsig.fmap.DriverNotLoadedExceptionType;
69
import com.iver.cit.gvsig.fmap.ErrorEvent;
70
import com.iver.cit.gvsig.fmap.GenericDriverExceptionType;
71
import com.iver.cit.gvsig.fmap.LegendDriverExceptionType;
72
import com.iver.cit.gvsig.fmap.ProgressListener;
73
import com.iver.cit.gvsig.fmap.ViewPort;
74
import com.iver.cit.gvsig.fmap.drivers.DBLayerDefinition;
75
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
76
import com.iver.cit.gvsig.fmap.drivers.RasterDriver;
77
import com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver;
78
import com.iver.cit.gvsig.fmap.drivers.VectorialDriver;
79
import com.iver.cit.gvsig.fmap.drivers.VectorialFileDriver;
80
import com.iver.cit.gvsig.fmap.drivers.VectorialJDBCDriver;
81
import com.iver.cit.gvsig.fmap.drivers.WithDefaultLegend;
82
import com.iver.cit.gvsig.fmap.operations.arcview.ArcJoin;
83
import com.iver.cit.gvsig.fmap.rendering.LegendFactory;
84
import com.iver.cit.gvsig.fmap.rendering.SingleSymbolLegend;
85
import com.iver.cit.gvsig.fmap.rendering.VectorialIntervalLegend;
86
import com.iver.cit.gvsig.fmap.rendering.VectorialLegend;
87
import com.iver.cit.gvsig.fmap.rendering.VectorialUniqueValueLegend;
88
import com.iver.utiles.ExceptionDescription;
89

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

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

    
101
        private static String writersPath = "../FMap 03/drivers";
102

    
103
        private static DriverManager driverManager;
104

    
105
        private static WriterManager writerManager;
106

    
107
        private static DataSourceFactory dataSourceFactory;
108

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

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

    
136
                try {
137
                        Driver d = dm.getDriver(driverName);
138

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

    
159
                return null;
160
        }
161

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

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

    
188
                FLyrVect capa = new FLyrVect();
189
                capa.setName(layerName);
190

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

    
198
                try {
199
                        // Le asignamos tambi?n una legenda por defecto acorde con
200
                        // el tipo de shape que tenga. Tampoco s? si es aqu? el
201
                        // sitio adecuado, pero en fin....
202
                        if (d instanceof WithDefaultLegend) {
203
                                WithDefaultLegend aux = (WithDefaultLegend) d;
204
                                adapter.start();
205
                                capa.setLegend((VectorialLegend) aux.getDefaultLegend());
206
                                adapter.stop();
207
                        } else {
208
                                capa.setLegend(LegendFactory.createSingleSymbolLegend(capa
209
                                                .getShapeType()));
210
                        }
211
                        
212
                } catch (FieldNotFoundException e) {
213
                        //this exception is caused in legend creation
214
                        LegendDriverExceptionType excepType = 
215
                                new LegendDriverExceptionType("Error al construir la leyenda"); 
216
                        //TODO Para hacer esto extensible tiene que usarse puntos
217
                        //de extension, y comparar las clases de leyendas registradas
218
                        VectorialLegend legend = (VectorialLegend) 
219
                                ((WithDefaultLegend)d).getDefaultLegend();
220
                        
221
                        excepType.setLegendLabelField(legend.getLabelField());
222
                        excepType.setLegendHeightField(legend.getLabelHeightField());
223
                        excepType.setLegendRotationField(legend.getLabelRotationField());
224
                        DriverException exception = new DriverException(e, excepType);
225
                        capa.setAvailable(false);
226
                        capa.addError(exception);
227
                        
228
                } catch (DriverIOException e) {
229
                        //this error is caused for file IO problems
230
                        DriverIOExceptionType excepType = 
231
                                new DriverIOExceptionType();
232
                        excepType.setFile(f);
233
                        DriverException exception = new DriverException(e, excepType);
234
                        capa.setAvailable(false);
235
                        capa.addError(exception);
236
                }
237
                
238
                /*
239
                 * catch(DriverException e){
240
                 * ESTO HAY QUE CAPTURARLO,DE FORMA QUE CREATELAYER NO LANCE NINGUNA
241
                 * EXCEPCION (A NO SER QUE SEA IRRECUPERABLE)
242
                 * }
243
                 */
244
                catch(Exception e){
245
                        GenericDriverExceptionType type = new GenericDriverExceptionType();
246
                        DriverException exception = new DriverException(e, type);
247
                        capa.setAvailable(false);
248
                        capa.addError(exception);
249
                }
250
                return capa;
251
        }
252

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

    
279
                FLyrVect capa = new FLyrVect();
280
                capa.setName(layerName);
281

    
282
                capa.setSource(adapter);
283
                capa.setProjection(proj);
284

    
285
                try {
286

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

    
304
                        //TODO Para hacer esto extensible tiene que usarse puntos
305
                        //de extension, y comparar las clases de leyendas registradas
306
                        VectorialLegend legend = (VectorialLegend) 
307
                                ((WithDefaultLegend)d).getDefaultLegend();
308
                        excepType.setDriverName(d.getName());
309
                        excepType.setLegendLabelField(legend.getLabelField());
310
                        excepType.setLegendHeightField(legend.getLabelHeightField());
311
                        excepType.setLegendRotationField(legend.getLabelRotationField());
312
                        
313
                        DriverException exception = new DriverException(e, excepType);
314
                        capa.setAvailable(false);
315
                        capa.addError(exception);
316
                } catch (DriverIOException e) {
317
                        //by design, start and stop calls to adapter could
318
                        //cause this exception.
319
                        
320
                        //but JDBC implementations catchs all exceptions,
321
                        //and rest of layers (WFSLayer, etc.) dont use LayerFactory        
322
                        ExceptionDescription type = null;
323
                        if (d instanceof VectorialFileDriver) {
324
                                File f = ((VectorialFileDriver)adapter).getFile();
325
                                type = 
326
                                        new DriverIOExceptionType(); 
327
                                ((DriverIOExceptionType)type).setFile(f);
328
                                
329
                        }else{
330
                                type = new GenericDriverExceptionType();
331
                        }
332
                        DriverException exception = new DriverException(e, type);
333
                        capa.setAvailable(false);
334
                        capa.addError(exception);
335
                }catch(Exception e){
336
                        GenericDriverExceptionType type = new GenericDriverExceptionType();
337
                        DriverException exception = new DriverException(e, type);
338
                        capa.setAvailable(false);
339
                        capa.addError(exception);
340
                }
341

    
342
                return capa;
343
        }
344

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

    
366
                FLyrRaster capa = new FLyrRaster();
367
                capa.setName(layerName);
368

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

    
381
                return capa;
382
        }
383

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

    
410
                FLyrRaster capa = new FLyrRaster();
411
                capa.setName(layerName);
412

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

    
426
                return capa;
427
        }
428

    
429
        public static FLayer createArcSDELayer(String layerName,
430
                        VectorialDatabaseDriver driver, IProjection proj) {
431
                // throw new UnsupportedOperationException();
432
                FLyrVect layer = new FLyrVect();
433
                VectorialAdapter adapter = new VectorialDBAdapter();
434
                adapter.setDriver(driver);
435

    
436
                layer.setName(layerName);
437
                layer.setSource(adapter);
438
                layer.setProjection(proj);
439
                try {
440
                        if (driver instanceof WithDefaultLegend) {
441
                                WithDefaultLegend aux = (WithDefaultLegend) driver;
442
                                adapter.start();
443
                                layer.setLegend((VectorialLegend) aux.getDefaultLegend());
444
                                adapter.stop();
445
                        } else {
446
                                layer.setLegend(LegendFactory.createSingleSymbolLegend(layer
447
                                                .getShapeType()));
448
                        }
449
                } catch (FieldNotFoundException e) {
450
                        throw new UnsupportedOperationException(e.getMessage());
451
                } catch (DriverIOException e) {
452
                        throw new UnsupportedOperationException(e.getMessage());
453
                } catch (DriverException e) {
454
                        // TODO Auto-generated catch block
455
                        e.printStackTrace();
456
                }
457

    
458
                try {
459
                        layer.setLegend(LegendFactory.createSingleSymbolLegend(layer
460
                                        .getShapeType()));
461
                } catch (FieldNotFoundException e) {
462
                        e.printStackTrace();
463
                } catch (DriverException e) {
464
                        e.printStackTrace();
465
                }
466
                return layer;
467
        }
468

    
469
        /**
470
         * Crea un RandomVectorialWFS con el driver que se le pasa como par?metro y
471
         * guard?ndose la URL del servidor que se pasa como par?metro
472
         * 
473
         * @param driver
474
         * @param host
475
         * @param port
476
         * @param user
477
         * @param password
478
         * @param dbName
479
         * @param tableName
480
         * @param proj
481
         * 
482
         * @return Capa creada.
483
         * 
484
         * @throws UnsupportedOperationException
485
         */
486
        public static FLayer createLayer(VectorialDatabaseDriver driver,
487
                        String host, int port, String user, String password, String dbName,
488
                        String tableName, IProjection proj) {
489
                throw new UnsupportedOperationException();
490
        }
491

    
492
        public static FLayer createDBLayer(VectorialDatabaseDriver driver,
493
                        String layerName, IProjection proj) {
494

    
495
                FLyrVect capa = new FLyrVect();
496

    
497
                capa.setName(layerName);
498
                VectorialDBAdapter dbAdapter = new VectorialDBAdapter();
499
                dbAdapter.setDriver(driver);
500

    
501
                capa.setSource(dbAdapter);
502
                capa.setProjection(proj);
503
                try {
504
                        if (driver instanceof WithDefaultLegend) {
505
                                WithDefaultLegend aux = (WithDefaultLegend) driver;
506
                                dbAdapter.start();
507
                                capa.setLegend((VectorialLegend) aux.getDefaultLegend());
508
                                dbAdapter.stop();
509
                        } else {
510
                                capa.setLegend(LegendFactory.createSingleSymbolLegend(capa
511
                                                .getShapeType()));
512
                        }
513
                } catch (FieldNotFoundException e) {
514
                        LegendDriverExceptionType excepType = 
515
                                new LegendDriverExceptionType("Error al construir la leyenda, campo no encontrado");
516
                        //TODO Para hacer esto extensible tiene que usarse puntos
517
                        //de extension, y comparar las clases de leyendas registradas
518
                        VectorialLegend legend = (VectorialLegend) 
519
                                ((WithDefaultLegend)driver).getDefaultLegend();
520
                        
521
                        excepType.setLegendLabelField(legend.getLabelField());
522
                        excepType.setLegendHeightField(legend.getLabelHeightField());
523
                        excepType.setLegendRotationField(legend.getLabelRotationField());
524
                        DriverException exception = new DriverException(e, excepType);
525
                        capa.setAvailable(false);
526
                        capa.addError(exception);
527
                        return capa;
528
                        // throw new UnsupportedOperationException(e.getMessage());
529
                } catch (DriverException e) {
530
                        DBDriverExceptionType excepType = 
531
                                new DBDriverExceptionType();
532
                        excepType.setDriverName(driver.getName());
533
                        excepType.setTableName(driver.getTableName());
534
                        DriverException exception = new DriverException(e, excepType);
535
                        capa.addError(exception);
536
                        capa.setAvailable(false);
537
                        return capa;
538
                        // throw new UnsupportedOperationException(e.getMessage());
539
                } catch (Exception e) {
540
                        ExceptionDescription excepType = new GenericDriverExceptionType();
541
                        DriverException exception = new DriverException(e, excepType);
542
                        capa.addError(exception);
543
                        capa.setAvailable(false);
544
                        return capa;
545
                }
546

    
547
                return capa;
548

    
549
        }
550

    
551
        /**
552
         * @param driver
553
         * @param layerName
554
         * @param object
555
         * @return
556
         * @throws SQLException
557
         * @throws DriverIOException
558
         * @throws IOException
559
         * @throws DriverLoadException
560
         * @throws com.hardcode.gdbms.engine.data.driver.DriverException
561
         * @throws NoSuchTableException
562
         * @throws ClassNotFoundException
563
         * @throws
564
         */
565
        public static FLayer createDisconnectedDBLayer(VectorialJDBCDriver driver,
566
                        String layerName, IProjection proj, ProgressListener listener)
567
                        throws SQLException, IOException, DriverIOException,
568
                        DriverLoadException, NoSuchTableException,
569
                        com.hardcode.gdbms.engine.data.driver.DriverException,
570
                        ClassNotFoundException {
571
                VectorialDisconnectedDBAdapter dbAdapter = new VectorialDisconnectedDBAdapter();
572
                dbAdapter.setDriver(driver);
573
                DataSource ds = dbAdapter.getRecordset();
574
                ds.start();
575
                String database = dataSourceFactory.getTempFile();
576
                String[] fieldNames = new String[ds.getFieldCount() + 1];
577
                System.arraycopy(ds.getFieldNames(), 0, fieldNames, 1, ds
578
                                .getFieldCount());
579
                fieldNames[0] = "the_geom";
580
                int[] types = new int[fieldNames.length];
581
                types[0] = Types.BINARY;
582
                for (int i = 1; i < types.length; i++) {
583
                        types[i] = ds.getFieldType(i - 1);
584
                }
585
                String dsName = dataSourceFactory.createTable(database,
586
                                ds.getPKNames(), fieldNames, types);
587

    
588
                DBLayerDefinition lyrDef = new DBLayerDefinition();
589
                lyrDef.setTableName(dsName);
590
                lyrDef.setName(layerName);
591
                lyrDef.setFieldNames(ds.getFieldNames());
592
                lyrDef.setFieldGeometry("the_geom");
593
                lyrDef.setFieldID(ds.getPKNames()[0]);
594
                lyrDef.setClassToInstantiate("org.hsqldb.jdbcDriver");
595

    
596
                dataSourceFactory.addDBDataSourceByTable(dsName, null, 0, "sa", "",
597
                                database, dsName, "GDBMS HSQLDB Transactional driver");
598
                DataSource local = dataSourceFactory.createRandomDataSource(dsName,
599
                                DataSourceFactory.MANUAL_OPENING);
600
                local.start();
601
                DataWare dw = local
602
                                .getDataWare(DataSourceFactory.DATA_WARE_COHERENT_ROW_ORDER);
603
                dw.start();
604
                long t1 = System.currentTimeMillis();
605
                dw.beginTrans();
606

    
607
                if (listener == null) {
608
                        listener = new ProgressListener() {
609
                                /**
610
                                 * @see com.iver.cit.gvsig.fmap.ProgressListener#progress(int)
611
                                 */
612
                                public void progress(int n) {
613
                                        // do nothing
614
                                }
615
                        };
616
                }
617

    
618
                for (int i = 0; i < dbAdapter.getShapeCount(); i++) {
619
                        Value[] row = new Value[ds.getFieldCount() + 1];
620

    
621
                        byte[] bytes = dbAdapter.getShape(i).toWKB();
622
                        row[0] = ValueFactory.createValue(bytes);
623

    
624
                        for (int j = 0; j < ds.getFieldCount(); j++) {
625
                                row[j + 1] = ds.getFieldValue(i, j);
626
                        }
627

    
628
                        dw.insertFilledRow(row);
629
                        listener.progress(100 * i / dbAdapter.getShapeCount());
630
                }
631

    
632
                long t2 = System.currentTimeMillis();
633
                dw.commitTrans();
634
                long t3 = System.currentTimeMillis();
635
                System.out.println((t2 - t1) + " - " + (t3 - t2));
636
                dw.stop();
637
                local.stop();
638
                ds.stop();
639
                VectorialJDBCDriver cacheDriver = (VectorialJDBCDriver) LayerFactory
640
                                .getDM().getDriver("HSQLDB Driver");
641
                Class.forName("org.hsqldb.jdbcDriver");
642

    
643
                cacheDriver.setData(java.sql.DriverManager.getConnection(
644
                                "jdbc:hsqldb:file:" + database, "sa", ""), lyrDef);
645
                cacheDriver.setWorkingArea(driver.getWorkingArea());
646
                return createDBLayer(cacheDriver, layerName, proj);
647
        }
648

    
649
        /**
650
         * Crea una FLyrComplexRaster que ataca al driver que se pasa como
651
         * par?metro.
652
         * 
653
         * @param driver
654
         * @param f
655
         * @param proj
656
         * 
657
         * @throws IllegalArgumentException
658
         *             Si se pasa un driver que no implementa
659
         *             GeorreferencedRasterDriver o NotGeorreferencedRasterDriver
660
         */
661
        public static void createLayer(RasterDriver driver, File f, IProjection proj)
662
                        throws IllegalArgumentException {
663
        }
664

    
665
        /**
666
         * Devuelve el DriverManager.
667
         * 
668
         * @return DriverManager.
669
         */
670
        public static DriverManager getDM() {
671
                initializeDriverManager();
672

    
673
                return driverManager;
674
        }
675

    
676
        /**
677
         * Devuelve el WriterManager.
678
         * 
679
         * @return WriterManager.
680
         */
681
        public static WriterManager getWM() {
682
                initializeWriterManager();
683

    
684
                return writerManager;
685
        }
686

    
687
        /**
688
         * Inicializa el DriverManager.
689
         */
690
        private static void initializeDriverManager() {
691
                if (driverManager == null) {
692
                        driverManager = new DriverManager();
693
                        driverManager.loadDrivers(new File(LayerFactory.driversPath));
694

    
695
                        Throwable[] failures = driverManager.getLoadFailures();
696

    
697
                        for (int i = 0; i < failures.length; i++) {
698
                                logger.error("", failures[i]);
699
                        }
700

    
701
                        getDataSourceFactory().setDriverManager(driverManager);
702
                        getDataSourceFactory().initialize();
703
                        QueryManager.registerQuery(new ArcJoin());
704
                }
705
        }
706

    
707
        /**
708
         * Inicializa el DriverManager.
709
         */
710
        private static void initializeWriterManager() {
711
                if (writerManager == null) {
712
                        writerManager = new WriterManager();
713
                        writerManager.loadWriters(new File(LayerFactory.writersPath));
714

    
715
                        Throwable[] failures = writerManager.getLoadFailures();
716

    
717
                        for (int i = 0; i < failures.length; i++) {
718
                                logger.error("", failures[i]);
719
                        }
720

    
721
                        getDataSourceFactory().setWriterManager(writerManager);
722
                        getDataSourceFactory().initialize();
723
                        // QueryManager.registerQuery(new ArcJoin());
724
                }
725
        }
726

    
727
        /**
728
         * sets drivers Directory
729
         * 
730
         * @param path
731
         */
732
        public static void setDriversPath(String path) {
733
                LayerFactory.driversPath = path;
734
                initializeDriverManager();
735
        }
736

    
737
        /**
738
         * sets writers Directory
739
         * 
740
         * @param path
741
         */
742
        public static void setWritersPath(String path) {
743
                LayerFactory.writersPath = path;
744
                initializeWriterManager();
745
        }
746

    
747
        /**
748
         * @return Returns the dataSourceFactory.
749
         */
750
        public static DataSourceFactory getDataSourceFactory() {
751
                if (dataSourceFactory == null) {
752
                        dataSourceFactory = new DataSourceFactory();
753
                }
754
                return dataSourceFactory;
755
        }
756
}