Statistics
| Revision:

svn-gvsig-desktop / trunk / libraries / libFMap / src / com / iver / cit / gvsig / fmap / layers / LayerFactory.java @ 12062

History | View | Annotate | Download (24.3 KB)

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

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

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

    
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.driver.exceptions.InitializeDriverException;
57
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
58
import com.hardcode.gdbms.driver.exceptions.WriteDriverException;
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.driver.DriverException;
64
import com.hardcode.gdbms.engine.data.edition.DataWare;
65
import com.hardcode.gdbms.engine.values.Value;
66
import com.hardcode.gdbms.engine.values.ValueFactory;
67
import com.iver.cit.gvsig.exceptions.layers.LegendLayerException;
68
import com.iver.cit.gvsig.exceptions.layers.LoadLayerException;
69
import com.iver.cit.gvsig.fmap.DriverNotLoadedExceptionType;
70
import com.iver.cit.gvsig.fmap.LegendDriverExceptionType;
71
import com.iver.cit.gvsig.fmap.ProgressListener;
72
import com.iver.cit.gvsig.fmap.ViewPort;
73
import com.iver.cit.gvsig.fmap.drivers.ConnectionFactory;
74
import com.iver.cit.gvsig.fmap.drivers.DBException;
75
import com.iver.cit.gvsig.fmap.drivers.DBLayerDefinition;
76
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
77
import com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver;
78
import com.iver.cit.gvsig.fmap.drivers.IVectorialJDBCDriver;
79
import com.iver.cit.gvsig.fmap.drivers.RasterDriver;
80
import com.iver.cit.gvsig.fmap.drivers.VectorialDriver;
81
import com.iver.cit.gvsig.fmap.drivers.VectorialFileDriver;
82
import com.iver.cit.gvsig.fmap.drivers.WithDefaultLegend;
83
import com.iver.cit.gvsig.fmap.operations.arcview.ArcJoin;
84
import com.iver.cit.gvsig.fmap.rendering.IVectorialLegend;
85
import com.iver.cit.gvsig.fmap.rendering.LegendFactory;
86
import com.iver.cit.gvsig.fmap.rendering.styling.AttrInTableLabeling;
87
import com.iver.cit.gvsig.fmap.rendering.styling.ILabelingStrategy;
88

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

    
98
        private static String driversPath = "../FMap 03/drivers";
99
        private static String writersPath = "../FMap 03/drivers";
100
        private static DriverManager driverManager;
101
        private static WriterManager writerManager;
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 LoadLayerException  {
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 new LoadLayerException(layerName,e);
152
                }
153

    
154
                return null;
155
        }
156

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

    
178
        /*throws DriverException*/ {
179
                FLyrVect layer = new FLyrVect();
180
                try {
181
                // TODO Comprobar si hay un adaptador ya
182
                VectorialFileAdapter adapter = new VectorialFileAdapter(f);
183
                adapter.setDriver(d);
184

    
185
                //TODO azo: adapter needs a reference to projection and to spatial index (review)
186
                adapter.setProjection(proj);
187

    
188
                layer.setName(layerName);
189

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

    
197
//                try {
198
                        // Le asignamos tambi?n una legenda por defecto acorde con
199
                        // el tipo de shape que tenga. Tampoco s? si es aqu? el
200
                        // sitio adecuado, pero en fin....
201
                        if (d instanceof WithDefaultLegend) {
202
                                WithDefaultLegend aux = (WithDefaultLegend) d;
203

    
204
                                        adapter.start();
205
                                        layer.setLegend((IVectorialLegend) aux.getDefaultLegend());
206

    
207
                                        ILabelingStrategy labeler = aux.getDefaultLabelingStrategy();
208
                                        if (labeler instanceof AttrInTableLabeling) {
209
                                                ((AttrInTableLabeling) labeler).setLayer(layer);
210
                                        }
211
                                        layer.setLabelingStrategy(labeler);layer.setIsLabeled(true); // TODO: ac? no s'hauria de detectar si t? etiquetes?????
212
                                        layer.setIsLabeled(true); // TODO: ac? no s'hauria de detectar si t? etiquetes?????
213
                                        adapter.stop();
214

    
215
                        } else {
216
                                layer.setLegend(LegendFactory.createSingleSymbolLegend(layer
217
                                                .getShapeType()));
218
                        }
219

    
220
//                } catch (LegendLayerException e) {
221
//                        //this exception is caused in legend creation
222
//                        LegendDriverExceptionType excepType =
223
//                                new LegendDriverExceptionType("Error al construir la leyenda");
224
//                        //TODO Para hacer esto extensible tiene que usarse puntos
225
//                        //de extension, y comparar las clases de leyendas registradas
226
//                        VectorialLegend legend = (VectorialLegend)
227
//                                ((WithDefaultLegend)d).getDefaultLegend();
228
//
229
//                        excepType.setLegendLabelField(legend.getLabelField());
230
//                        excepType.setLegendHeightField(legend.getLabelHeightField());
231
//                        excepType.setLegendRotationField(legend.getLabelRotationField());
232
//                        DriverException exception = new DriverException(e, excepType);
233
//                        capa.setAvailable(false);
234
//                        capa.addError(exception);
235
//
236
//                }
237
//
238
//                /*
239
//                 * catch(DriverException e){
240
//                 * ESTO HAY QUE CAPTURARLO,DE FORMA QUE CREATELAYER NO LANCE NINGUNA
241
//                 * EXCEPCION (A NO SER QUE SEA IRRECUPERABLE)
242
//                 * }
243
//                 */
244
//                catch(Exception e){
245
//                        GenericDriverExceptionType type = new GenericDriverExceptionType();
246
//                        DriverException exception = new DriverException(e, type);
247
//                        capa.setAvailable(false);
248
//                        capa.addError(exception);
249
//                }
250

    
251
        } catch (ReadDriverException e) {
252
                layer.setAvailable(false);
253
                layer.addError(e);
254
        } catch (LegendLayerException e) {
255
                layer.setAvailable(false);
256
                layer.addError(e);
257
        }
258
                return layer;
259
        }
260

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

    
289
                FLyrVect layer = new FLyrVect();
290
                layer.setName(layerName);
291

    
292
                layer.setSource(adapter);
293
                layer.setProjection(proj);
294

    
295
                try {
296

    
297
                        // Le asignamos tambi?n una legenda por defecto acorde con
298
                        // el tipo de shape que tenga. Tampoco s? si es aqu? el
299
                        // sitio adecuado, pero en fin....
300
                        if (d instanceof WithDefaultLegend) {
301
                                WithDefaultLegend aux = (WithDefaultLegend) d;
302
                                adapter.start();
303
                                layer.setLegend((IVectorialLegend) aux.getDefaultLegend());
304

    
305
                                ILabelingStrategy labeler = aux.getDefaultLabelingStrategy();
306
                                if (labeler instanceof AttrInTableLabeling) {
307
                                        ((AttrInTableLabeling) labeler).setLayer(layer);
308
                                }
309
                                layer.setLabelingStrategy(labeler);
310

    
311
                                layer.setIsLabeled(true); // TODO: ac? no s'hauria de detectar si t? etiquetes?????
312

    
313
                                adapter.stop();
314
                        } else {
315
                                layer.setLegend(LegendFactory.createSingleSymbolLegend(layer
316
                                                .getShapeType()));
317
                        }
318
                } catch (LegendLayerException e) {
319
//                        this exception is caused in legend creation
320
//                        LegendDriverExceptionType excepType =
321
//                                new LegendDriverExceptionType("error al construir la leyenda, campo no encontrado");
322

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

    
332
//                        DriverException exception = new DriverException(e, excepType);
333
                        layer.setAvailable(false);
334
                        layer.addError(e);
335
//                }
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
//                } catch (UnsupportedVersionDriverException e) {
342
//                        capa.setAvailable(false);
343
//                        capa.addError(e);
344
//                } catch (InitializeDriverException e) {
345
//                        capa.setAvailable(false);
346
//                        capa.addError(e);
347
                } catch (ReadDriverException e) {
348
                        layer.setAvailable(false);
349
                        layer.addError(e);
350
                }
351

    
352
                return layer;
353
        }
354

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

    
379
                // TODO Meter esto dentro de la comprobaci?n de si hay memoria
380
                if (false) {
381
                } else {
382
                        capa.setSource(adapter);
383
                        capa.setProjection(proj);
384
                        capa.load();
385
                }
386

    
387
                return capa;
388
        }
389

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

    
417
                FLyrRaster capa = new FLyrRaster();
418
                capa.setName(layerName);
419

    
420
                // TODO Meter esto dentro de la comprobaci?n de si hay memoria
421
                if (false) {
422
                } else {
423
                        capa.setSource(adapter);
424
                        capa.setProjection(proj);
425
                        // capa.setTempExtent(vp);
426
                        capa.load();
427
                }
428

    
429
                return capa;
430
        }
431

    
432
        public static FLayer createArcSDELayer(String layerName,
433
                        IVectorialDatabaseDriver driver, IProjection proj) {
434
                // throw new UnsupportedOperationException();
435
                FLyrVect layer = new FLyrVect();
436
                VectorialAdapter adapter = new VectorialDBAdapter();
437
                adapter.setDriver(driver);
438
                adapter.setProjection(proj);
439

    
440
                layer.setName(layerName);
441
                layer.setSource(adapter);
442
                layer.setProjection(proj);
443
                try {
444
                        if (driver instanceof WithDefaultLegend) {
445
                                WithDefaultLegend aux = (WithDefaultLegend) driver;
446
                                adapter.start();
447
                                layer.setLegend((IVectorialLegend) aux.getDefaultLegend());
448

    
449
                                ILabelingStrategy labeler = aux.getDefaultLabelingStrategy();
450
                                if (labeler instanceof AttrInTableLabeling) {
451
                                        ((AttrInTableLabeling) labeler).setLayer(layer);
452
                                }
453
                                layer.setLabelingStrategy(labeler);layer.setIsLabeled(true); // TODO: ac? no s'hauria de detectar si t? etiquetes?????
454

    
455
                                adapter.stop();
456
                        } else {
457
                                layer.setLegend(LegendFactory.createSingleSymbolLegend(layer
458
                                                .getShapeType()));
459
                        }
460
                } catch (LegendLayerException e) {
461
                        throw new UnsupportedOperationException(e.getMessage());
462
                } catch (InitializeDriverException e) {
463
                        throw new UnsupportedOperationException(e.getMessage());
464
                } catch (ReadDriverException e) {
465
                        throw new UnsupportedOperationException(e.getMessage());
466
                }
467

    
468
                try {
469
                        layer.setLegend(LegendFactory.createSingleSymbolLegend(layer
470
                                        .getShapeType()));
471
                } catch (LegendLayerException e) {
472
                        e.printStackTrace();
473
                } catch (ReadDriverException e) {
474
                        e.printStackTrace();
475
                }
476
                return layer;
477
        }
478

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

    
502
        public static FLayer createDBLayer(IVectorialDatabaseDriver driver,
503
                        String layerName, IProjection proj) {
504

    
505
                FLyrVect layer = new FLyrVect();
506

    
507
                layer.setName(layerName);
508
                VectorialDBAdapter dbAdapter = new VectorialDBAdapter();
509
                dbAdapter.setDriver(driver);
510
                dbAdapter.setProjection(proj);//adapter needs also a ref to prj. review (azo)
511

    
512
                layer.setSource(dbAdapter);
513
                layer.setProjection(proj);
514
                try {
515
                        if (driver instanceof WithDefaultLegend) {
516
                                WithDefaultLegend aux = (WithDefaultLegend) driver;
517
                                dbAdapter.start();
518
                                layer.setLegend((IVectorialLegend) aux.getDefaultLegend());
519

    
520
                                ILabelingStrategy labeler = aux.getDefaultLabelingStrategy();
521
                                if (labeler instanceof AttrInTableLabeling) {
522
                                        ((AttrInTableLabeling) labeler).setLayer(layer);
523
                                }
524
                                layer.setLabelingStrategy(labeler);layer.setIsLabeled(true); // TODO: ac? no s'hauria de detectar si t? etiquetes?????
525

    
526
                                layer.setIsLabeled(true); // TODO: ac? no s'hauria de detectar si t? etiquetes?????
527

    
528
                                dbAdapter.stop();
529
                        } else {
530
                                layer.setLegend(LegendFactory.createSingleSymbolLegend(layer
531
                                                .getShapeType()));
532
                        }
533
                } catch (LegendLayerException e) {
534
                        LegendDriverExceptionType excepType =
535
                                new LegendDriverExceptionType("Error al construir la leyenda, campo no encontrado");
536
                        //TODO Para hacer esto extensible tiene que usarse puntos
537
                        //de extension, y comparar las clases de leyendas registradas
538
//                        IVectorialLegend legend = (IVectorialLegend)
539
//                                ((WithDefaultLegend)driver).getDefaultLegend();
540
//
541
//                        excepType.setLegendLabelField(legend.getLabelField());
542
//                        excepType.setLegendHeightField(legend.getLabelHeightField());
543
//                        excepType.setLegendRotationField(legend.getLabelRotationField());
544
//                        DriverException exception = new DriverException(e, excepType);
545
                        layer.setAvailable(false);
546
                        layer.addError(null);
547
                        return layer;
548
                        // throw new UnsupportedOperationException(e.getMessage());
549
                } catch (Exception e) {
550
//                        ExceptionDescription excepType = new GenericDriverExceptionType();
551
//                        DriverException exception = new DriverException(e, excepType);
552
                        layer.addError(null);
553
                        layer.setAvailable(false);
554
                        return layer;
555
                }
556

    
557
                return layer;
558

    
559
        }
560

    
561
        /**
562
         * @param driver
563
         * @param layerName
564
         * @param object
565
         * @return
566
         * @throws SQLException
567
         * @throws DriverIOException
568
         * @throws IOException
569
         * @throws DriverLoadException
570
         * @throws com.hardcode.gdbms.engine.data.driver.DriverException
571
         * @throws NoSuchTableException
572
         * @throws ClassNotFoundException
573
         * @throws ReadDriverException
574
         * @throws IOException
575
         * @throws WriteDriverException
576
         * @throws
577
         */
578
        public static FLayer createDisconnectedDBLayer(IVectorialJDBCDriver driver,
579
                        String layerName, IProjection proj, ProgressListener listener)
580
                        throws DBException,
581
                        DriverLoadException, NoSuchTableException,
582
                        ClassNotFoundException, ReadDriverException, IOException, WriteDriverException {
583
                VectorialDisconnectedDBAdapter dbAdapter = new VectorialDisconnectedDBAdapter();
584
                dbAdapter.setDriver(driver);
585
                dbAdapter.setProjection(proj);
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 (ReadDriverException e) {
603
                        // TODO Auto-generated catch block
604
                        e.printStackTrace();
605
                } catch (SQLException e) {
606
                        throw new DBException(e);
607
                }
608

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

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

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

    
639
                for (int i = 0; i < dbAdapter.getShapeCount(); i++) {
640
                        Value[] row = new Value[ds.getFieldCount() + 1];
641

    
642
                        byte[] bytes = dbAdapter.getShape(i).toWKB();
643
                        row[0] = ValueFactory.createValue(bytes);
644

    
645
                        for (int j = 0; j < ds.getFieldCount(); j++) {
646
                                row[j + 1] = ds.getFieldValue(i, j);
647
                        }
648

    
649
                        dw.insertFilledRow(row);
650
                        listener.progress(100 * i / dbAdapter.getShapeCount());
651
                }
652

    
653
                long t2 = System.currentTimeMillis();
654
                dw.commitTrans();
655
                long t3 = System.currentTimeMillis();
656
                System.out.println((t2 - t1) + " - " + (t3 - t2));
657
                dw.stop();
658
                local.stop();
659
                ds.stop();
660
                IVectorialJDBCDriver cacheDriver = (IVectorialJDBCDriver) LayerFactory
661
                                .getDM().getDriver("HSQLDB Driver");
662
                Class.forName("org.hsqldb.jdbcDriver");
663

    
664
                cacheDriver.setData(ConnectionFactory.createConnection(
665
                                "jdbc:hsqldb:file:" + database, "sa", ""), lyrDef);
666
                cacheDriver.setWorkingArea(driver.getWorkingArea());
667
                return createDBLayer(cacheDriver, layerName, proj);
668
        }
669

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

    
686
        /**
687
         * Devuelve el DriverManager.
688
         *
689
         * @return DriverManager.
690
         */
691
        public static DriverManager getDM() {
692
                initializeDriverManager();
693

    
694
                return driverManager;
695
        }
696

    
697
        /**
698
         * Devuelve el WriterManager.
699
         *
700
         * @return WriterManager.
701
         */
702
        public static WriterManager getWM() {
703
                initializeWriterManager();
704

    
705
                return writerManager;
706
        }
707

    
708
        /**
709
         * Inicializa el DriverManager.
710
         */
711
        private static void initializeDriverManager() {
712
                if (driverManager == null) {
713
                        driverManager = new DriverManager();
714
                        driverManager.loadDrivers(new File(LayerFactory.driversPath));
715

    
716
                        Throwable[] failures = driverManager.getLoadFailures();
717

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

    
722
                        getDataSourceFactory().setDriverManager(driverManager);
723
                        getDataSourceFactory().initialize();
724
                        QueryManager.registerQuery(new ArcJoin());
725
                }
726
        }
727

    
728
        /**
729
         * Inicializa el DriverManager.
730
         */
731
        private static void initializeWriterManager() {
732
                if (writerManager == null) {
733
                        writerManager = new WriterManager();
734
                        writerManager.loadWriters(new File(LayerFactory.writersPath));
735

    
736
                        Throwable[] failures = writerManager.getLoadFailures();
737

    
738
                        for (int i = 0; i < failures.length; i++) {
739
                                logger.error("", failures[i]);
740
                        }
741

    
742
                        getDataSourceFactory().setWriterManager(writerManager);
743
                        getDataSourceFactory().initialize();
744
                        // QueryManager.registerQuery(new ArcJoin());
745
                }
746
        }
747

    
748
        /**
749
         * sets drivers Directory
750
         *
751
         * @param path
752
         */
753
        public static void setDriversPath(String path) {
754
                LayerFactory.driversPath = path;
755
                initializeDriverManager();
756
        }
757

    
758
        /**
759
         * sets writers Directory
760
         *
761
         * @param path
762
         */
763
        public static void setWritersPath(String path) {
764
                LayerFactory.writersPath = path;
765
                initializeWriterManager();
766
        }
767

    
768
        /**
769
         * @return Returns the dataSourceFactory.
770
         */
771
        public static DataSourceFactory getDataSourceFactory() {
772
                if (dataSourceFactory == null) {
773
                        dataSourceFactory = new DataSourceFactory();
774
                }
775
                return dataSourceFactory;
776
        }
777

    
778
        public static void initialize() {
779
                initializeDriverManager();
780
                initializeWriterManager();
781
        }
782
}