Statistics
| Revision:

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

History | View | Annotate | Download (23.9 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.WriterManager;
58
import com.hardcode.gdbms.engine.customQuery.QueryManager;
59
import com.hardcode.gdbms.engine.data.DataSource;
60
import com.hardcode.gdbms.engine.data.DataSourceFactory;
61
import com.hardcode.gdbms.engine.data.NoSuchTableException;
62
import com.hardcode.gdbms.engine.data.edition.DataWare;
63
import com.hardcode.gdbms.engine.instruction.FieldNotFoundException;
64
import com.hardcode.gdbms.engine.values.Value;
65
import com.hardcode.gdbms.engine.values.ValueFactory;
66
import com.iver.cit.gvsig.fmap.DBDriverExceptionType;
67
import com.iver.cit.gvsig.fmap.DriverException;
68
import com.iver.cit.gvsig.fmap.DriverIOExceptionType;
69
import com.iver.cit.gvsig.fmap.DriverNotLoadedExceptionType;
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.VectorialLegend;
85
import com.iver.utiles.ExceptionDescription;
86

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

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

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

    
100
        private static DriverManager driverManager;
101

    
102
        private static WriterManager writerManager;
103

    
104
        private static DataSourceFactory dataSourceFactory;
105

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

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

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

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

    
156
                return null;
157
        }
158

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

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

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

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

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

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

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

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

    
282
                try {
283

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

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

    
339
                return capa;
340
        }
341

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

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

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

    
378
                return capa;
379
        }
380

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

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

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

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

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

    
460
                return capa;
461
        }
462

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

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

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

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

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

    
529
                FLyrVect capa = new FLyrVect();
530

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

    
535
                capa.setSource(dbAdapter);
536
                capa.setProjection(proj);
537
                try {
538
                        if (driver instanceof WithDefaultLegend) {
539
                                WithDefaultLegend aux = (WithDefaultLegend) driver;
540
                                dbAdapter.start();
541
                                capa.setLegend((VectorialLegend) aux.getDefaultLegend());
542
                                dbAdapter.stop();
543
                        } else {
544
                                capa.setLegend(LegendFactory.createSingleSymbolLegend(capa
545
                                                .getShapeType()));
546
                        }
547
                } catch (FieldNotFoundException e) {
548
                        LegendDriverExceptionType excepType = 
549
                                new LegendDriverExceptionType("Error al construir la leyenda, campo no encontrado");
550
                        //TODO Para hacer esto extensible tiene que usarse puntos
551
                        //de extension, y comparar las clases de leyendas registradas
552
                        VectorialLegend legend = (VectorialLegend) 
553
                                ((WithDefaultLegend)driver).getDefaultLegend();
554
                        
555
                        excepType.setLegendLabelField(legend.getLabelField());
556
                        excepType.setLegendHeightField(legend.getLabelHeightField());
557
                        excepType.setLegendRotationField(legend.getLabelRotationField());
558
                        DriverException exception = new DriverException(e, excepType);
559
                        capa.setAvailable(false);
560
                        capa.addError(exception);
561
                        return capa;
562
                        // throw new UnsupportedOperationException(e.getMessage());
563
                } catch (DriverException e) {
564
                        DBDriverExceptionType excepType = 
565
                                new DBDriverExceptionType();
566
                        excepType.setDriverName(driver.getName());
567
                        excepType.setTableName(driver.getTableName());
568
                        DriverException exception = new DriverException(e, excepType);
569
                        capa.addError(exception);
570
                        capa.setAvailable(false);
571
                        return capa;
572
                        // throw new UnsupportedOperationException(e.getMessage());
573
                } catch (Exception e) {
574
                        ExceptionDescription excepType = new GenericDriverExceptionType();
575
                        DriverException exception = new DriverException(e, excepType);
576
                        capa.addError(exception);
577
                        capa.setAvailable(false);
578
                        return capa;
579
                }
580

    
581
                return capa;
582

    
583
        }
584

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

    
622
                DBLayerDefinition lyrDef = new DBLayerDefinition();
623
                lyrDef.setTableName(dsName);
624
                lyrDef.setName(layerName);
625
                lyrDef.setFieldNames(ds.getFieldNames());
626
                lyrDef.setFieldGeometry("the_geom");
627
                lyrDef.setFieldID(ds.getPKNames()[0]);
628
                lyrDef.setClassToInstantiate("org.hsqldb.jdbcDriver");
629

    
630
                dataSourceFactory.addDBDataSourceByTable(dsName, null, 0, "sa", "",
631
                                database, dsName, "GDBMS HSQLDB Transactional driver");
632
                DataSource local = dataSourceFactory.createRandomDataSource(dsName,
633
                                DataSourceFactory.MANUAL_OPENING);
634
                local.start();
635
                DataWare dw = local
636
                                .getDataWare(DataSourceFactory.DATA_WARE_COHERENT_ROW_ORDER);
637
                dw.start();
638
                long t1 = System.currentTimeMillis();
639
                dw.beginTrans();
640

    
641
                if (listener == null) {
642
                        listener = new ProgressListener() {
643
                                /**
644
                                 * @see com.iver.cit.gvsig.fmap.ProgressListener#progress(int)
645
                                 */
646
                                public void progress(int n) {
647
                                        // do nothing
648
                                }
649
                        };
650
                }
651

    
652
                for (int i = 0; i < dbAdapter.getShapeCount(); i++) {
653
                        Value[] row = new Value[ds.getFieldCount() + 1];
654

    
655
                        byte[] bytes = dbAdapter.getShape(i).toWKB();
656
                        row[0] = ValueFactory.createValue(bytes);
657

    
658
                        for (int j = 0; j < ds.getFieldCount(); j++) {
659
                                row[j + 1] = ds.getFieldValue(i, j);
660
                        }
661

    
662
                        dw.insertFilledRow(row);
663
                        listener.progress(100 * i / dbAdapter.getShapeCount());
664
                }
665

    
666
                long t2 = System.currentTimeMillis();
667
                dw.commitTrans();
668
                long t3 = System.currentTimeMillis();
669
                System.out.println((t2 - t1) + " - " + (t3 - t2));
670
                dw.stop();
671
                local.stop();
672
                ds.stop();
673
                VectorialJDBCDriver cacheDriver = (VectorialJDBCDriver) LayerFactory
674
                                .getDM().getDriver("HSQLDB Driver");
675
                Class.forName("org.hsqldb.jdbcDriver");
676

    
677
                cacheDriver.setData(java.sql.DriverManager.getConnection(
678
                                "jdbc:hsqldb:file:" + database, "sa", ""), lyrDef);
679
                cacheDriver.setWorkingArea(driver.getWorkingArea());
680
                return createDBLayer(cacheDriver, layerName, proj);
681
        }
682

    
683
        /**
684
         * Crea una FLyrComplexRaster que ataca al driver que se pasa como
685
         * par?metro.
686
         * 
687
         * @param driver
688
         * @param f
689
         * @param proj
690
         * 
691
         * @throws IllegalArgumentException
692
         *             Si se pasa un driver que no implementa
693
         *             GeorreferencedRasterDriver o NotGeorreferencedRasterDriver
694
         */
695
        public static void createLayer(RasterDriver driver, File f, IProjection proj)
696
                        throws IllegalArgumentException {
697
        }
698

    
699
        /**
700
         * Devuelve el DriverManager.
701
         * 
702
         * @return DriverManager.
703
         */
704
        public static DriverManager getDM() {
705
                initializeDriverManager();
706

    
707
                return driverManager;
708
        }
709

    
710
        /**
711
         * Devuelve el WriterManager.
712
         * 
713
         * @return WriterManager.
714
         */
715
        public static WriterManager getWM() {
716
                initializeWriterManager();
717

    
718
                return writerManager;
719
        }
720

    
721
        /**
722
         * Inicializa el DriverManager.
723
         */
724
        private static void initializeDriverManager() {
725
                if (driverManager == null) {
726
                        driverManager = new DriverManager();
727
                        driverManager.loadDrivers(new File(LayerFactory.driversPath));
728

    
729
                        Throwable[] failures = driverManager.getLoadFailures();
730

    
731
                        for (int i = 0; i < failures.length; i++) {
732
                                logger.error("", failures[i]);
733
                        }
734

    
735
                        getDataSourceFactory().setDriverManager(driverManager);
736
                        getDataSourceFactory().initialize();
737
                        QueryManager.registerQuery(new ArcJoin());
738
                }
739
        }
740

    
741
        /**
742
         * Inicializa el DriverManager.
743
         */
744
        private static void initializeWriterManager() {
745
                if (writerManager == null) {
746
                        writerManager = new WriterManager();
747
                        writerManager.loadWriters(new File(LayerFactory.writersPath));
748

    
749
                        Throwable[] failures = writerManager.getLoadFailures();
750

    
751
                        for (int i = 0; i < failures.length; i++) {
752
                                logger.error("", failures[i]);
753
                        }
754

    
755
                        getDataSourceFactory().setWriterManager(writerManager);
756
                        getDataSourceFactory().initialize();
757
                        // QueryManager.registerQuery(new ArcJoin());
758
                }
759
        }
760

    
761
        /**
762
         * sets drivers Directory
763
         * 
764
         * @param path
765
         */
766
        public static void setDriversPath(String path) {
767
                LayerFactory.driversPath = path;
768
                initializeDriverManager();
769
        }
770

    
771
        /**
772
         * sets writers Directory
773
         * 
774
         * @param path
775
         */
776
        public static void setWritersPath(String path) {
777
                LayerFactory.writersPath = path;
778
                initializeWriterManager();
779
        }
780

    
781
        /**
782
         * @return Returns the dataSourceFactory.
783
         */
784
        public static DataSourceFactory getDataSourceFactory() {
785
                if (dataSourceFactory == null) {
786
                        dataSourceFactory = new DataSourceFactory();
787
                }
788
                return dataSourceFactory;
789
        }
790
}