Statistics
| Revision:

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

History | View | Annotate | Download (23.7 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.ConnectionFactory;
76
import com.iver.cit.gvsig.fmap.drivers.DBException;
77
import com.iver.cit.gvsig.fmap.drivers.DBLayerDefinition;
78
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
79
import com.iver.cit.gvsig.fmap.drivers.IConnection;
80
import com.iver.cit.gvsig.fmap.drivers.RasterDriver;
81
import com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver;
82
import com.iver.cit.gvsig.fmap.drivers.VectorialDriver;
83
import com.iver.cit.gvsig.fmap.drivers.VectorialFileDriver;
84
import com.iver.cit.gvsig.fmap.drivers.IVectorialJDBCDriver;
85
import com.iver.cit.gvsig.fmap.drivers.WithDefaultLegend;
86
import com.iver.cit.gvsig.fmap.operations.arcview.ArcJoin;
87
import com.iver.cit.gvsig.fmap.rendering.LegendFactory;
88
import com.iver.cit.gvsig.fmap.rendering.VectorialLegend;
89
import com.iver.utiles.ExceptionDescription;
90

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

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

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

    
104
        private static DriverManager driverManager;
105

    
106
        private static WriterManager writerManager;
107

    
108
        private static DataSourceFactory dataSourceFactory;
109

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

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

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

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

    
160
                return null;
161
        }
162

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

    
183
        /*throws DriverException*/ {
184

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

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

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

    
199
                try {
200
                        // Le asignamos tambi?n una legenda por defecto acorde con
201
                        // el tipo de shape que tenga. Tampoco s? si es aqu? el
202
                        // sitio adecuado, pero en fin....
203
                        if (d instanceof WithDefaultLegend) {
204
                                WithDefaultLegend aux = (WithDefaultLegend) d;
205
                                adapter.start();
206
                                capa.setLegend((VectorialLegend) aux.getDefaultLegend());
207
                                adapter.stop();
208
                        } else {
209
                                capa.setLegend(LegendFactory.createSingleSymbolLegend(capa
210
                                                .getShapeType()));
211
                        }
212

    
213
                } catch (FieldNotFoundException e) {
214
                        //this exception is caused in legend creation
215
                        LegendDriverExceptionType excepType =
216
                                new LegendDriverExceptionType("Error al construir la leyenda");
217
                        //TODO Para hacer esto extensible tiene que usarse puntos
218
                        //de extension, y comparar las clases de leyendas registradas
219
                        VectorialLegend legend = (VectorialLegend)
220
                                ((WithDefaultLegend)d).getDefaultLegend();
221

    
222
                        excepType.setLegendLabelField(legend.getLabelField());
223
                        excepType.setLegendHeightField(legend.getLabelHeightField());
224
                        excepType.setLegendRotationField(legend.getLabelRotationField());
225
                        DriverException exception = new DriverException(e, excepType);
226
                        capa.setAvailable(false);
227
                        capa.addError(exception);
228

    
229
                } catch (DriverIOException e) {
230
                        //this error is caused for file IO problems
231
                        DriverIOExceptionType excepType =
232
                                new DriverIOExceptionType();
233
                        excepType.setFile(f);
234
                        DriverException exception = new DriverException(e, excepType);
235
                        capa.setAvailable(false);
236
                        capa.addError(exception);
237
                }
238

    
239
                /*
240
                 * catch(DriverException e){
241
                 * ESTO HAY QUE CAPTURARLO,DE FORMA QUE CREATELAYER NO LANCE NINGUNA
242
                 * EXCEPCION (A NO SER QUE SEA IRRECUPERABLE)
243
                 * }
244
                 */
245
                catch(Exception e){
246
                        GenericDriverExceptionType type = new GenericDriverExceptionType();
247
                        DriverException exception = new DriverException(e, type);
248
                        capa.setAvailable(false);
249
                        capa.addError(exception);
250
                }
251
                return capa;
252
        }
253

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

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

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

    
286
                try {
287

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

    
305
                        //TODO Para hacer esto extensible tiene que usarse puntos
306
                        //de extension, y comparar las clases de leyendas registradas
307
                        VectorialLegend legend = (VectorialLegend)
308
                                ((WithDefaultLegend)d).getDefaultLegend();
309
                        excepType.setDriverName(d.getName());
310
                        excepType.setLegendLabelField(legend.getLabelField());
311
                        excepType.setLegendHeightField(legend.getLabelHeightField());
312
                        excepType.setLegendRotationField(legend.getLabelRotationField());
313

    
314
                        DriverException exception = new DriverException(e, excepType);
315
                        capa.setAvailable(false);
316
                        capa.addError(exception);
317
                } catch (DriverIOException e) {
318
                        //by design, start and stop calls to adapter could
319
                        //cause this exception.
320

    
321
                        //but JDBC implementations catchs all exceptions,
322
                        //and rest of layers (WFSLayer, etc.) dont use LayerFactory
323
                        ExceptionDescription type = null;
324
                        if (d instanceof VectorialFileDriver) {
325
                                File f = ((VectorialFileDriver)adapter).getFile();
326
                                type =
327
                                        new DriverIOExceptionType();
328
                                ((DriverIOExceptionType)type).setFile(f);
329

    
330
                        }else{
331
                                type = new GenericDriverExceptionType();
332
                        }
333
                        DriverException exception = new DriverException(e, type);
334
                        capa.setAvailable(false);
335
                        capa.addError(exception);
336
                }catch(Exception e){
337
                        GenericDriverExceptionType type = new GenericDriverExceptionType();
338
                        DriverException exception = new DriverException(e, type);
339
                        capa.setAvailable(false);
340
                        capa.addError(exception);
341
                }
342

    
343
                return capa;
344
        }
345

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

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

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

    
382
                return capa;
383
        }
384

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

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

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

    
427
                return capa;
428
        }
429

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

    
447
                FLyrRaster capa = new FLyrRaster();
448
                capa.setName(layerName);
449

    
450
                // TODO Meter esto dentro de la comprobaci?n de si hay memoria
451
                if (false) {
452
                } else {
453
                        capa.setSource(adapter);
454
                        capa.setProjection(proj);
455
                        capa.setBuffer(buf);
456
                        capa.setExtent(ext);
457
                        try {
458
                                capa.load();
459
                        } catch (DriverIOException e) {
460
                                throw new DriverException(e);
461
                        }
462
                }
463

    
464
                return capa;
465
        }
466

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

    
490
        public static FLayer createDBLayer(IVectorialDatabaseDriver driver,
491
                        String layerName, IProjection proj) {
492

    
493
                FLyrVect capa = new FLyrVect();
494

    
495
                capa.setName(layerName);
496
                VectorialDBAdapter dbAdapter = new VectorialDBAdapter();
497
                dbAdapter.setDriver(driver);
498

    
499
                capa.setSource(dbAdapter);
500
                capa.setProjection(proj);
501
                try {
502
                        if (driver instanceof WithDefaultLegend) {
503
                                WithDefaultLegend aux = (WithDefaultLegend) driver;
504
                                dbAdapter.start();
505
                                capa.setLegend((VectorialLegend) aux.getDefaultLegend());
506
                                dbAdapter.stop();
507
                        } else {
508
                                capa.setLegend(LegendFactory.createSingleSymbolLegend(capa
509
                                                .getShapeType()));
510
                        }
511
                        if (driver instanceof IDelayedDriver)
512
                        {
513
                                // Por defecto, los drivers est?n listos para entregar
514
                                // features al terminar su initialize. Pero con los drivers
515
                                // que implementan IDelayedDriver, el driver es responsable
516
                                // de avisar cu?ndo est? listo
517
                                capa.getFLayerStatus().setDriverLoaded(false);
518
                                ((IDelayedDriver) driver).addDriverEventListener(new DefaultDelayedDriverListener(capa));
519
                        }
520
                        // PARCHE: Llamamos a getXmlEntity del driver para que se rellenen
521
                        // los valores de host, port, etc, necesarios para un posible reload
522
                        //FIXME: Se vuelve a dejar como estaba... el problema esta en el DefaultDBDriver.getXMLEntiy()
523
                        //       y comentarizemos esto o no, si no arreglamos ese metodo da problemas de persistencia
524
                        driver.setXMLEntity(driver.getXMLEntity());
525

    
526
                } catch (FieldNotFoundException e) {
527
                        LegendDriverExceptionType excepType =
528
                                new LegendDriverExceptionType("Error al construir la leyenda, campo no encontrado");
529
                        //TODO Para hacer esto extensible tiene que usarse puntos
530
                        //de extension, y comparar las clases de leyendas registradas
531
                        VectorialLegend legend = (VectorialLegend)
532
                                ((WithDefaultLegend)driver).getDefaultLegend();
533

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

    
560
                return capa;
561

    
562
        }
563

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

    
606
                DBLayerDefinition lyrDef = new DBLayerDefinition();
607
                lyrDef.setTableName(dsName);
608
                lyrDef.setName(layerName);
609
                lyrDef.setFieldNames(ds.getFieldNames());
610
                lyrDef.setFieldGeometry("the_geom");
611
                lyrDef.setFieldID(ds.getPKNames()[0]);
612
                lyrDef.setClassToInstantiate("org.hsqldb.jdbcDriver");
613

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

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

    
636
                for (int i = 0; i < dbAdapter.getShapeCount(); i++) {
637
                        Value[] row = new Value[ds.getFieldCount() + 1];
638

    
639
                        byte[] bytes = dbAdapter.getShape(i).toWKB();
640
                        row[0] = ValueFactory.createValue(bytes);
641

    
642
                        for (int j = 0; j < ds.getFieldCount(); j++) {
643
                                row[j + 1] = ds.getFieldValue(i, j);
644
                        }
645

    
646
                        dw.insertFilledRow(row);
647
                        listener.progress(100 * i / dbAdapter.getShapeCount());
648
                }
649

    
650
                long t2 = System.currentTimeMillis();
651
                dw.commitTrans();
652
                long t3 = System.currentTimeMillis();
653
                System.out.println((t2 - t1) + " - " + (t3 - t2));
654
                dw.stop();
655
                local.stop();
656
                ds.stop();
657
                IVectorialJDBCDriver cacheDriver = (IVectorialJDBCDriver) LayerFactory
658
                                .getDM().getDriver("HSQLDB Driver");
659
                Class.forName("org.hsqldb.jdbcDriver");
660
                IConnection conn=ConnectionFactory.createConnection("jdbc:hsqldb:file:" + database, "sa", "");
661
                cacheDriver.setData(conn, lyrDef);
662
                cacheDriver.setWorkingArea(driver.getWorkingArea());
663
                return createDBLayer(cacheDriver, layerName, proj);
664
        }
665

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

    
682
        /**
683
         * Devuelve el DriverManager.
684
         *
685
         * @return DriverManager.
686
         */
687
        public static DriverManager getDM() {
688
                initializeDriverManager();
689

    
690
                return driverManager;
691
        }
692

    
693
        /**
694
         * Devuelve el WriterManager.
695
         *
696
         * @return WriterManager.
697
         */
698
        public static WriterManager getWM() {
699
                initializeWriterManager();
700

    
701
                return writerManager;
702
        }
703

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

    
712
                        Throwable[] failures = driverManager.getLoadFailures();
713

    
714
                        for (int i = 0; i < failures.length; i++) {
715
                                logger.error("", failures[i]);
716
                        }
717

    
718
                        getDataSourceFactory().setDriverManager(driverManager);
719
                        getDataSourceFactory().initialize();
720
                        QueryManager.registerQuery(new ArcJoin());
721
                }
722
        }
723

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

    
732
                        Throwable[] failures = writerManager.getLoadFailures();
733

    
734
                        for (int i = 0; i < failures.length; i++) {
735
                                logger.error("", failures[i]);
736
                        }
737

    
738
                        getDataSourceFactory().setWriterManager(writerManager);
739
                        getDataSourceFactory().initialize();
740
                        // QueryManager.registerQuery(new ArcJoin());
741
                }
742
        }
743

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

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

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