Statistics
| Revision:

svn-gvsig-desktop / branches / simbologia / libraries / libFMap / src / com / iver / cit / gvsig / fmap / layers / LayerFactory.java @ 10104

History | View | Annotate | Download (23.4 KB)

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

    
43
import java.io.File;
44
import java.io.IOException;
45
import java.sql.SQLException;
46
import java.sql.Types;
47
import java.util.TreeMap;
48

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

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

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

    
94
        private static String driversPath = "../FMap 03/drivers";
95

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

    
98
        private static DriverManager driverManager;
99

    
100
        private static WriterManager writerManager;
101

    
102
        private static DataSourceFactory dataSourceFactory;
103

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

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

    
131
                try {
132
                        Driver d = dm.getDriver(driverName);
133

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

    
154
                return null;
155
        }
156

    
157
        public static FLayer createLayer(String layerName, VectorialFileDriver d,
158
                        File f, IProjection proj) {
159
                return createLayer(layerName, d, f, proj, FLyrVect.class.getName());
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, String className)
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

    
189
                FLayer l = null;
190
                try {
191
                        l = (FLayer) Class.forName(className).newInstance();
192
                } catch (InstantiationException e1) {
193
                        // TODO Auto-generated catch block
194
                        e1.printStackTrace();
195
                } catch (IllegalAccessException e1) {
196
                        // TODO Auto-generated catch block
197
                        e1.printStackTrace();
198
                } catch (ClassNotFoundException e1) {
199
                        // TODO Auto-generated catch block
200
                        e1.printStackTrace();
201
                }
202
                FLyrVect capa = (FLyrVect) l; //new FLyrVect();
203
                capa.setName(layerName);
204

    
205
                // TODO Meter esto dentro de la comprobaci?n de si hay memoria
206
                if (false) {
207
                } else {
208
                        capa.setSource(adapter);
209
                        capa.setProjection(proj);
210
                }
211

    
212
                try {
213
                        // Le asignamos tambi?n una legenda por defecto acorde con
214
                        // el tipo de shape que tenga. Tampoco s? si es aqu? el
215
                        // sitio adecuado, pero en fin....
216
                        if (d instanceof WithDefaultLegend) {
217
                                WithDefaultLegend aux = (WithDefaultLegend) d;
218
                                adapter.start();
219
                                capa.setLegend((VectorialLegend) aux.getDefaultLegend());
220
                                adapter.stop();
221
                        } else {
222
                                capa.setLegend(LegendFactory.createSingleSymbolLegend(capa
223
                                                .getShapeType()));
224
                        }
225

    
226
                } catch (FieldNotFoundException e) {
227
                        //this exception is caused in legend creation
228
                        LegendDriverExceptionType excepType =
229
                                new LegendDriverExceptionType("Error al construir la leyenda");
230
                        //TODO Para hacer esto extensible tiene que usarse puntos
231
                        //de extension, y comparar las clases de leyendas registradas
232
                        VectorialLegend legend = (VectorialLegend)
233
                                ((WithDefaultLegend)d).getDefaultLegend();
234

    
235
                        excepType.setLegendLabelField(legend.getLabelField());
236
                        excepType.setLegendHeightField(legend.getLabelHeightField());
237
                        excepType.setLegendRotationField(legend.getLabelRotationField());
238
                        DriverException exception = new DriverException(e, excepType);
239
                        capa.setAvailable(false);
240
                        capa.addError(exception);
241

    
242
                } catch (DriverIOException e) {
243
                        //this error is caused for file IO problems
244
                        DriverIOExceptionType excepType =
245
                                new DriverIOExceptionType();
246
                        excepType.setFile(f);
247
                        DriverException exception = new DriverException(e, excepType);
248
                        capa.setAvailable(false);
249
                        capa.addError(exception);
250
                }
251

    
252
                /*
253
                 * catch(DriverException e){
254
                 * ESTO HAY QUE CAPTURARLO,DE FORMA QUE CREATELAYER NO LANCE NINGUNA
255
                 * EXCEPCION (A NO SER QUE SEA IRRECUPERABLE)
256
                 * }
257
                 */
258
                catch(Exception e){
259
                        GenericDriverExceptionType type = new GenericDriverExceptionType();
260
                        DriverException exception = new DriverException(e, type);
261
                        capa.setAvailable(false);
262
                        capa.addError(exception);
263
                }
264
                return capa;
265
        }
266

    
267
        /**
268
         * Creates a new vectorial layer from a generic layer (by generic whe mean
269
         * that we dont know a priory its origin: file, memory, jdbc database, etc.
270
         *
271
         * @param layerName
272
         * @param d
273
         * @param proj
274
         * @return
275
         * @throws DriverException
276
         */
277
        public static FLayer createLayer(String layerName, VectorialDriver d,
278
                        IProjection proj)
279
        /*
280
        throws DriverException
281
        */{
282
                VectorialAdapter adapter = null;
283
                if (d instanceof VectorialFileDriver) {
284
                        adapter = new VectorialFileAdapter(((VectorialFileDriver) d)
285
                                        .getFile());
286
                } else if (d instanceof VectorialJDBCDriver) {
287
                        adapter = new VectorialDBAdapter();
288
                } else {
289
                        adapter = new VectorialDefaultAdapter();
290
                }
291
                adapter.setDriver((VectorialDriver) d);
292

    
293
                FLyrVect capa = new FLyrVect();
294
                capa.setName(layerName);
295

    
296
                capa.setSource(adapter);
297
                capa.setProjection(proj);
298

    
299
                try {
300

    
301
                        // Le asignamos tambi?n una legenda por defecto acorde con
302
                        // el tipo de shape que tenga. Tampoco s? si es aqu? el
303
                        // sitio adecuado, pero en fin....
304
                        if (d instanceof WithDefaultLegend) {
305
                                WithDefaultLegend aux = (WithDefaultLegend) d;
306
                                adapter.start();
307
                                capa.setLegend((VectorialLegend) aux.getDefaultLegend());
308
                                adapter.stop();
309
                        } else {
310
                                capa.setLegend(LegendFactory.createSingleSymbolLegend(capa
311
                                                .getShapeType()));
312
                        }
313
                } catch (FieldNotFoundException e) {
314
//                        this exception is caused in legend creation
315
                        LegendDriverExceptionType excepType =
316
                                new LegendDriverExceptionType("error al construir la leyenda, campo no encontrado");
317

    
318
                        //TODO Para hacer esto extensible tiene que usarse puntos
319
                        //de extension, y comparar las clases de leyendas registradas
320
                        VectorialLegend legend = (VectorialLegend)
321
                                ((WithDefaultLegend)d).getDefaultLegend();
322
                        excepType.setDriverName(d.getName());
323
                        excepType.setLegendLabelField(legend.getLabelField());
324
                        excepType.setLegendHeightField(legend.getLabelHeightField());
325
                        excepType.setLegendRotationField(legend.getLabelRotationField());
326

    
327
                        DriverException exception = new DriverException(e, excepType);
328
                        capa.setAvailable(false);
329
                        capa.addError(exception);
330
                } catch (DriverIOException e) {
331
                        //by design, start and stop calls to adapter could
332
                        //cause this exception.
333

    
334
                        //but JDBC implementations catchs all exceptions,
335
                        //and rest of layers (WFSLayer, etc.) dont use LayerFactory
336
                        ExceptionDescription type = null;
337
                        if (d instanceof VectorialFileDriver) {
338
                                File f = ((VectorialFileDriver)adapter).getFile();
339
                                type =
340
                                        new DriverIOExceptionType();
341
                                ((DriverIOExceptionType)type).setFile(f);
342

    
343
                        }else{
344
                                type = new GenericDriverExceptionType();
345
                        }
346
                        DriverException exception = new DriverException(e, type);
347
                        capa.setAvailable(false);
348
                        capa.addError(exception);
349
                }catch(Exception e){
350
                        GenericDriverExceptionType type = new GenericDriverExceptionType();
351
                        DriverException exception = new DriverException(e, type);
352
                        capa.setAvailable(false);
353
                        capa.addError(exception);
354
                }
355

    
356
                return capa;
357
        }
358

    
359
        /**
360
         * Crea una capa Raster a partir del nombre driver, fichero y proyecci?n.
361
         *
362
         * @param layerName
363
         *            Nombre de la capa.
364
         * @param d
365
         *            RasterDriver.
366
         * @param f
367
         *            Fichero.
368
         * @param proj
369
         *            Proyecci?n.
370
         *
371
         * @return Nueva capa de tipo raster.
372
         *
373
         * @throws DriverIOException
374
         */
375
        public static FLyrRaster createLayer(String layerName, RasterDriver d,
376
                        File f, IProjection proj) throws DriverException {
377
                RasterAdapter adapter = new RasterFileAdapter(f);
378
                adapter.setDriver(d);
379

    
380
                FLyrRaster capa = new FLyrRaster();
381
                capa.setName(layerName);
382

    
383
                // TODO Meter esto dentro de la comprobaci?n de si hay memoria
384
                if (false) {
385
                } else {
386
                        capa.setSource(adapter);
387
                        capa.setProjection(proj);
388
                        try {
389
                                capa.load();
390
                        } catch (DriverIOException e) {
391
                                throw new DriverException(e);
392
                        }
393
                }
394

    
395
                return capa;
396
        }
397

    
398
        /**
399
         * Crea una capa Raster a partir del nombre driver, fichero y proyecci?n y
400
         * coordenadas de georeferenciaci?n. Esta funci?n es para georeferenciar
401
         * capas raster. Para imagenes que no tienen georeferenciaci?n hay que
402
         * asignarle una temporal, normalmente a partir de la vista activa.
403
         *
404
         * @param layerName
405
         *            Nombre de la capa.
406
         * @param d
407
         *            RasterDriver.
408
         * @param f
409
         *            Fichero.
410
         * @param proj
411
         *            Proyecci?n.
412
         * @param extent
413
         *            Extent de la vista activa
414
         *
415
         * @return Nueva capa de tipo raster.
416
         *
417
         * @throws DriverIOException
418
         */
419
        public static FLyrRaster createLayer(String layerName, RasterDriver d,
420
                        File f, IProjection proj, ViewPort vp) throws DriverException {
421
                RasterAdapter adapter = new RasterFileAdapter(f);
422
                adapter.setDriver(d);
423

    
424
                FLyrRaster capa = new FLyrRaster();
425
                capa.setName(layerName);
426

    
427
                // TODO Meter esto dentro de la comprobaci?n de si hay memoria
428
                if (false) {
429
                } else {
430
                        capa.setSource(adapter);
431
                        capa.setProjection(proj);
432
                        // capa.setTempExtent(vp);
433
                        try {
434
                                capa.load();
435
                        } catch (DriverIOException e) {
436
                                throw new DriverException(e);
437
                        }
438
                }
439

    
440
                return capa;
441
        }
442

    
443
        public static FLayer createArcSDELayer(String layerName,
444
                        VectorialDatabaseDriver driver, IProjection proj) {
445
                // throw new UnsupportedOperationException();
446
                FLyrVect layer = new FLyrVect();
447
                VectorialAdapter adapter = new VectorialDBAdapter();
448
                adapter.setDriver(driver);
449

    
450
                layer.setName(layerName);
451
                layer.setSource(adapter);
452
                layer.setProjection(proj);
453
                try {
454
                        if (driver instanceof WithDefaultLegend) {
455
                                WithDefaultLegend aux = (WithDefaultLegend) driver;
456
                                adapter.start();
457
                                layer.setLegend((VectorialLegend) aux.getDefaultLegend());
458
                                adapter.stop();
459
                        } else {
460
                                layer.setLegend(LegendFactory.createSingleSymbolLegend(layer
461
                                                .getShapeType()));
462
                        }
463
                } catch (FieldNotFoundException e) {
464
                        throw new UnsupportedOperationException(e.getMessage());
465
                } catch (DriverIOException e) {
466
                        throw new UnsupportedOperationException(e.getMessage());
467
                } catch (DriverException e) {
468
                        // TODO Auto-generated catch block
469
                        e.printStackTrace();
470
                }
471

    
472
                try {
473
                        layer.setLegend(LegendFactory.createSingleSymbolLegend(layer
474
                                        .getShapeType()));
475
                } catch (FieldNotFoundException e) {
476
                        e.printStackTrace();
477
                } catch (DriverException e) {
478
                        e.printStackTrace();
479
                }
480
                return layer;
481
        }
482

    
483
        /**
484
         * Crea un RandomVectorialWFS con el driver que se le pasa como par?metro y
485
         * guard?ndose la URL del servidor que se pasa como par?metro
486
         *
487
         * @param driver
488
         * @param host
489
         * @param port
490
         * @param user
491
         * @param password
492
         * @param dbName
493
         * @param tableName
494
         * @param proj
495
         *
496
         * @return Capa creada.
497
         *
498
         * @throws UnsupportedOperationException
499
         */
500
        public static FLayer createLayer(VectorialDatabaseDriver driver,
501
                        String host, int port, String user, String password, String dbName,
502
                        String tableName, IProjection proj) {
503
                throw new UnsupportedOperationException();
504
        }
505

    
506
        public static FLayer createDBLayer(VectorialDatabaseDriver driver,
507
                        String layerName, IProjection proj) {
508

    
509
                FLyrVect capa = new FLyrVect();
510

    
511
                capa.setName(layerName);
512
                VectorialDBAdapter dbAdapter = new VectorialDBAdapter();
513
                dbAdapter.setDriver(driver);
514

    
515
                capa.setSource(dbAdapter);
516
                capa.setProjection(proj);
517
                try {
518
                        if (driver instanceof WithDefaultLegend) {
519
                                WithDefaultLegend aux = (WithDefaultLegend) driver;
520
                                dbAdapter.start();
521
                                capa.setLegend((VectorialLegend) aux.getDefaultLegend());
522
                                dbAdapter.stop();
523
                        } else {
524
                                capa.setLegend(LegendFactory.createSingleSymbolLegend(capa
525
                                                .getShapeType()));
526
                        }
527
                } catch (FieldNotFoundException e) {
528
                        LegendDriverExceptionType excepType =
529
                                new LegendDriverExceptionType("Error al construir la leyenda, campo no encontrado");
530
                        //TODO Para hacer esto extensible tiene que usarse puntos
531
                        //de extension, y comparar las clases de leyendas registradas
532
                        VectorialLegend legend = (VectorialLegend)
533
                                ((WithDefaultLegend)driver).getDefaultLegend();
534

    
535
                        excepType.setLegendLabelField(legend.getLabelField());
536
                        excepType.setLegendHeightField(legend.getLabelHeightField());
537
                        excepType.setLegendRotationField(legend.getLabelRotationField());
538
                        DriverException exception = new DriverException(e, excepType);
539
                        capa.setAvailable(false);
540
                        capa.addError(exception);
541
                        return capa;
542
                        // throw new UnsupportedOperationException(e.getMessage());
543
                } catch (DriverException e) {
544
                        DBDriverExceptionType excepType =
545
                                new DBDriverExceptionType();
546
                        excepType.setDriverName(driver.getName());
547
                        excepType.setTableName(driver.getTableName());
548
                        DriverException exception = new DriverException(e, excepType);
549
                        capa.addError(exception);
550
                        capa.setAvailable(false);
551
                        return capa;
552
                        // throw new UnsupportedOperationException(e.getMessage());
553
                } catch (Exception e) {
554
                        ExceptionDescription excepType = new GenericDriverExceptionType();
555
                        DriverException exception = new DriverException(e, excepType);
556
                        capa.addError(exception);
557
                        capa.setAvailable(false);
558
                        return capa;
559
                }
560

    
561
                return capa;
562

    
563
        }
564

    
565
        /**
566
         * @param driver
567
         * @param layerName
568
         * @param object
569
         * @return
570
         * @throws SQLException
571
         * @throws DriverIOException
572
         * @throws IOException
573
         * @throws DriverLoadException
574
         * @throws com.hardcode.gdbms.engine.data.driver.DriverException
575
         * @throws NoSuchTableException
576
         * @throws ClassNotFoundException
577
         * @throws
578
         */
579
        public static FLayer createDisconnectedDBLayer(VectorialJDBCDriver driver,
580
                        String layerName, IProjection proj, ProgressListener listener)
581
                        throws SQLException, IOException, DriverIOException,
582
                        DriverLoadException, NoSuchTableException,
583
                        com.hardcode.gdbms.engine.data.driver.DriverException,
584
                        ClassNotFoundException {
585
                VectorialDisconnectedDBAdapter dbAdapter = new VectorialDisconnectedDBAdapter();
586
                dbAdapter.setDriver(driver);
587
                DataSource ds = dbAdapter.getRecordset();
588
                ds.start();
589
                String database = dataSourceFactory.getTempFile();
590
                String[] fieldNames = new String[ds.getFieldCount() + 1];
591
                System.arraycopy(ds.getFieldNames(), 0, fieldNames, 1, ds
592
                                .getFieldCount());
593
                fieldNames[0] = "the_geom";
594
                int[] types = new int[fieldNames.length];
595
                types[0] = Types.BINARY;
596
                for (int i = 1; i < types.length; i++) {
597
                        types[i] = ds.getFieldType(i - 1);
598
                }
599
                String dsName = dataSourceFactory.createTable(database,
600
                                ds.getPKNames(), fieldNames, types);
601

    
602
                DBLayerDefinition lyrDef = new DBLayerDefinition();
603
                lyrDef.setTableName(dsName);
604
                lyrDef.setName(layerName);
605
                lyrDef.setFieldNames(ds.getFieldNames());
606
                lyrDef.setFieldGeometry("the_geom");
607
                lyrDef.setFieldID(ds.getPKNames()[0]);
608
                lyrDef.setClassToInstantiate("org.hsqldb.jdbcDriver");
609

    
610
                dataSourceFactory.addDBDataSourceByTable(dsName, null, 0, "sa", "",
611
                                database, dsName, "GDBMS HSQLDB Transactional driver");
612
                DataSource local = dataSourceFactory.createRandomDataSource(dsName,
613
                                DataSourceFactory.MANUAL_OPENING);
614
                local.start();
615
                DataWare dw = local
616
                                .getDataWare(DataSourceFactory.DATA_WARE_COHERENT_ROW_ORDER);
617
                dw.start();
618
                long t1 = System.currentTimeMillis();
619
                dw.beginTrans();
620

    
621
                if (listener == null) {
622
                        listener = new ProgressListener() {
623
                                /**
624
                                 * @see com.iver.cit.gvsig.fmap.ProgressListener#progress(int)
625
                                 */
626
                                public void progress(int n) {
627
                                        // do nothing
628
                                }
629
                        };
630
                }
631

    
632
                for (int i = 0; i < dbAdapter.getShapeCount(); i++) {
633
                        Value[] row = new Value[ds.getFieldCount() + 1];
634

    
635
                        byte[] bytes = dbAdapter.getShape(i).toWKB();
636
                        row[0] = ValueFactory.createValue(bytes);
637

    
638
                        for (int j = 0; j < ds.getFieldCount(); j++) {
639
                                row[j + 1] = ds.getFieldValue(i, j);
640
                        }
641

    
642
                        dw.insertFilledRow(row);
643
                        listener.progress(100 * i / dbAdapter.getShapeCount());
644
                }
645

    
646
                long t2 = System.currentTimeMillis();
647
                dw.commitTrans();
648
                long t3 = System.currentTimeMillis();
649
                System.out.println((t2 - t1) + " - " + (t3 - t2));
650
                dw.stop();
651
                local.stop();
652
                ds.stop();
653
                VectorialJDBCDriver cacheDriver = (VectorialJDBCDriver) LayerFactory
654
                                .getDM().getDriver("HSQLDB Driver");
655
                Class.forName("org.hsqldb.jdbcDriver");
656

    
657
                cacheDriver.setData(java.sql.DriverManager.getConnection(
658
                                "jdbc:hsqldb:file:" + database, "sa", ""), lyrDef);
659
                cacheDriver.setWorkingArea(driver.getWorkingArea());
660
                return createDBLayer(cacheDriver, layerName, proj);
661
        }
662

    
663
        /**
664
         * Crea una FLyrComplexRaster que ataca al driver que se pasa como
665
         * par?metro.
666
         *
667
         * @param driver
668
         * @param f
669
         * @param proj
670
         *
671
         * @throws IllegalArgumentException
672
         *             Si se pasa un driver que no implementa
673
         *             GeorreferencedRasterDriver o NotGeorreferencedRasterDriver
674
         */
675
        public static void createLayer(RasterDriver driver, File f, IProjection proj)
676
                        throws IllegalArgumentException {
677
        }
678

    
679
        /**
680
         * Devuelve el DriverManager.
681
         *
682
         * @return DriverManager.
683
         */
684
        public static DriverManager getDM() {
685
                initializeDriverManager();
686

    
687
                return driverManager;
688
        }
689

    
690
        /**
691
         * Devuelve el WriterManager.
692
         *
693
         * @return WriterManager.
694
         */
695
        public static WriterManager getWM() {
696
                initializeWriterManager();
697

    
698
                return writerManager;
699
        }
700

    
701
        /**
702
         * Inicializa el DriverManager.
703
         */
704
        private static void initializeDriverManager() {
705
                if (driverManager == null) {
706
                        driverManager = new DriverManager();
707
                        driverManager.loadDrivers(new File(LayerFactory.driversPath));
708

    
709
                        Throwable[] failures = driverManager.getLoadFailures();
710

    
711
                        for (int i = 0; i < failures.length; i++) {
712
                                logger.error("", failures[i]);
713
                        }
714

    
715
                        getDataSourceFactory().setDriverManager(driverManager);
716
                        getDataSourceFactory().initialize();
717
                        QueryManager.registerQuery(new ArcJoin());
718
                }
719
        }
720

    
721
        /**
722
         * Inicializa el DriverManager.
723
         */
724
        private static void initializeWriterManager() {
725
                if (writerManager == null) {
726
                        writerManager = new WriterManager();
727
                        writerManager.loadWriters(new File(LayerFactory.writersPath));
728

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

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

    
735
                        getDataSourceFactory().setWriterManager(writerManager);
736
                        getDataSourceFactory().initialize();
737
                        // QueryManager.registerQuery(new ArcJoin());
738
                }
739
        }
740

    
741
        /**
742
         * sets drivers Directory
743
         *
744
         * @param path
745
         */
746
        public static void setDriversPath(String path) {
747
                LayerFactory.driversPath = path;
748
                initializeDriverManager();
749
        }
750

    
751
        /**
752
         * sets writers Directory
753
         *
754
         * @param path
755
         */
756
        public static void setWritersPath(String path) {
757
                LayerFactory.writersPath = path;
758
                initializeWriterManager();
759
        }
760

    
761
        /**
762
         * @return Returns the dataSourceFactory.
763
         */
764
        public static DataSourceFactory getDataSourceFactory() {
765
                if (dataSourceFactory == null) {
766
                        dataSourceFactory = new DataSourceFactory();
767
                }
768
                return dataSourceFactory;
769
        }
770

    
771
        public static void initialize() {
772
                initializeDriverManager();
773
                initializeWriterManager();
774
        }
775
}