Statistics
| Revision:

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

History | View | Annotate | Download (24.3 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

    
558
                } catch (FieldNotFoundException e) {
559
                        LegendDriverExceptionType excepType = 
560
                                new LegendDriverExceptionType("Error al construir la leyenda, campo no encontrado");
561
                        //TODO Para hacer esto extensible tiene que usarse puntos
562
                        //de extension, y comparar las clases de leyendas registradas
563
                        VectorialLegend legend = (VectorialLegend) 
564
                                ((WithDefaultLegend)driver).getDefaultLegend();
565
                        
566
                        excepType.setLegendLabelField(legend.getLabelField());
567
                        excepType.setLegendHeightField(legend.getLabelHeightField());
568
                        excepType.setLegendRotationField(legend.getLabelRotationField());
569
                        DriverException exception = new DriverException(e, excepType);
570
                        capa.setAvailable(false);
571
                        capa.addError(exception);
572
                        return capa;
573
                        // throw new UnsupportedOperationException(e.getMessage());
574
                } catch (DriverException e) {
575
                        DBDriverExceptionType excepType = 
576
                                new DBDriverExceptionType();
577
                        excepType.setDriverName(driver.getName());
578
                        excepType.setTableName(driver.getTableName());
579
                        DriverException exception = new DriverException(e, excepType);
580
                        capa.addError(exception);
581
                        capa.setAvailable(false);
582
                        return capa;
583
                        // throw new UnsupportedOperationException(e.getMessage());
584
                } catch (Exception e) {
585
                        ExceptionDescription excepType = new GenericDriverExceptionType();
586
                        DriverException exception = new DriverException(e, excepType);
587
                        capa.addError(exception);
588
                        capa.setAvailable(false);
589
                        return capa;
590
                }
591

    
592
                return capa;
593

    
594
        }
595

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

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

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

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

    
663
                for (int i = 0; i < dbAdapter.getShapeCount(); i++) {
664
                        Value[] row = new Value[ds.getFieldCount() + 1];
665

    
666
                        byte[] bytes = dbAdapter.getShape(i).toWKB();
667
                        row[0] = ValueFactory.createValue(bytes);
668

    
669
                        for (int j = 0; j < ds.getFieldCount(); j++) {
670
                                row[j + 1] = ds.getFieldValue(i, j);
671
                        }
672

    
673
                        dw.insertFilledRow(row);
674
                        listener.progress(100 * i / dbAdapter.getShapeCount());
675
                }
676

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

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

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

    
710
        /**
711
         * Devuelve el DriverManager.
712
         * 
713
         * @return DriverManager.
714
         */
715
        public static DriverManager getDM() {
716
                initializeDriverManager();
717

    
718
                return driverManager;
719
        }
720

    
721
        /**
722
         * Devuelve el WriterManager.
723
         * 
724
         * @return WriterManager.
725
         */
726
        public static WriterManager getWM() {
727
                initializeWriterManager();
728

    
729
                return writerManager;
730
        }
731

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

    
740
                        Throwable[] failures = driverManager.getLoadFailures();
741

    
742
                        for (int i = 0; i < failures.length; i++) {
743
                                logger.error("", failures[i]);
744
                        }
745

    
746
                        getDataSourceFactory().setDriverManager(driverManager);
747
                        getDataSourceFactory().initialize();
748
                        QueryManager.registerQuery(new ArcJoin());
749
                }
750
        }
751

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

    
760
                        Throwable[] failures = writerManager.getLoadFailures();
761

    
762
                        for (int i = 0; i < failures.length; i++) {
763
                                logger.error("", failures[i]);
764
                        }
765

    
766
                        getDataSourceFactory().setWriterManager(writerManager);
767
                        getDataSourceFactory().initialize();
768
                        // QueryManager.registerQuery(new ArcJoin());
769
                }
770
        }
771

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

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

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