Statistics
| Revision:

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

History | View | Annotate | Download (24.9 KB)

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

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

    
49
import org.apache.log4j.Logger;
50
import org.cresques.cts.IProjection;
51
import org.cresques.io.data.RasterBuf;
52
import org.cresques.px.Extent;
53

    
54
import com.hardcode.driverManager.Driver;
55
import com.hardcode.driverManager.DriverLoadException;
56
import com.hardcode.driverManager.DriverManager;
57
import com.hardcode.driverManager.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
        public static FLayer createArcSDELayer(String layerName,
468
                        IVectorialDatabaseDriver driver, IProjection proj) {
469
                // throw new UnsupportedOperationException();
470
                FLyrVect layer = new FLyrVect();
471
                VectorialAdapter adapter = new VectorialDBAdapter();
472
                adapter.setDriver(driver);
473

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

    
496
                try {
497
                        layer.setLegend(LegendFactory.createSingleSymbolLegend(layer
498
                                        .getShapeType()));
499
                } catch (FieldNotFoundException e) {
500
                        e.printStackTrace();
501
                } catch (DriverException e) {
502
                        e.printStackTrace();
503
                }
504
                return layer;
505
        }
506

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

    
530
        public static FLayer createDBLayer(IVectorialDatabaseDriver driver,
531
                        String layerName, IProjection proj) {
532

    
533
                FLyrVect capa = new FLyrVect();
534

    
535
                capa.setName(layerName);
536
                VectorialDBAdapter dbAdapter = new VectorialDBAdapter();
537
                dbAdapter.setDriver(driver);
538

    
539
                capa.setSource(dbAdapter);
540
                capa.setProjection(proj);
541
                try {
542
                        if (driver instanceof WithDefaultLegend) {
543
                                WithDefaultLegend aux = (WithDefaultLegend) driver;
544
                                dbAdapter.start();
545
                                capa.setLegend((VectorialLegend) aux.getDefaultLegend());
546
                                dbAdapter.stop();
547
                        } else {
548
                                capa.setLegend(LegendFactory.createSingleSymbolLegend(capa
549
                                                .getShapeType()));
550
                        }
551
                        if (driver instanceof IDelayedDriver)
552
                        {
553
                                // Por defecto, los drivers est?n listos para entregar
554
                                // features al terminar su initialize. Pero con los drivers
555
                                // que implementan IDelayedDriver, el driver es responsable
556
                                // de avisar cu?ndo est? listo
557
                                capa.getFLayerStatus().setDriverLoaded(false);
558
                                ((IDelayedDriver) driver).addDriverEventListener(new DefaultDelayedDriverListener(capa));
559
                        }
560
                        // PARCHE: Llamamos a getXmlEntity del driver para que se rellenen
561
                        // los valores de host, port, etc, necesarios para un posible reload
562
                        //FIXME: Se vuelve a dejar como estaba... el problema esta en el DefaultDBDriver.getXMLEntiy()
563
                        //       y comentarizemos esto o no, si no arreglamos ese metodo da problemas de persistencia
564
                        driver.setXMLEntity(driver.getXMLEntity());
565

    
566
                } catch (FieldNotFoundException e) {
567
                        LegendDriverExceptionType excepType =
568
                                new LegendDriverExceptionType("Error al construir la leyenda, campo no encontrado");
569
                        //TODO Para hacer esto extensible tiene que usarse puntos
570
                        //de extension, y comparar las clases de leyendas registradas
571
                        VectorialLegend legend = (VectorialLegend)
572
                                ((WithDefaultLegend)driver).getDefaultLegend();
573

    
574
                        excepType.setLegendLabelField(legend.getLabelField());
575
                        excepType.setLegendHeightField(legend.getLabelHeightField());
576
                        excepType.setLegendRotationField(legend.getLabelRotationField());
577
                        DriverException exception = new DriverException(e, excepType);
578
                        capa.setAvailable(false);
579
                        capa.addError(exception);
580
                        return capa;
581
                        // throw new UnsupportedOperationException(e.getMessage());
582
                } catch (DriverException e) {
583
                        DBDriverExceptionType excepType =
584
                                new DBDriverExceptionType();
585
                        excepType.setDriverName(driver.getName());
586
                        excepType.setTableName(driver.getTableName());
587
                        DriverException exception = new DriverException(e, excepType);
588
                        capa.addError(exception);
589
                        capa.setAvailable(false);
590
                        return capa;
591
                        // throw new UnsupportedOperationException(e.getMessage());
592
                } catch (Exception e) {
593
                        ExceptionDescription excepType = new GenericDriverExceptionType();
594
                        DriverException exception = new DriverException(e, excepType);
595
                        capa.addError(exception);
596
                        capa.setAvailable(false);
597
                        return capa;
598
                }
599

    
600
                return capa;
601

    
602
        }
603

    
604
        /**
605
         * @param driver
606
         * @param layerName
607
         * @param object
608
         * @return
609
         * @throws SQLException
610
         * @throws DriverIOException
611
         * @throws IOException
612
         * @throws DriverLoadException
613
         * @throws com.hardcode.gdbms.engine.data.driver.DriverException
614
         * @throws NoSuchTableException
615
         * @throws ClassNotFoundException
616
         * @throws
617
         */
618
        public static FLayer createDisconnectedDBLayer(IVectorialDatabaseDriver driver,
619
                        String layerName, IProjection proj, ProgressListener listener)
620
                        throws DBException, IOException, DriverIOException,
621
                        DriverLoadException, NoSuchTableException,
622
                        com.hardcode.gdbms.engine.data.driver.DriverException,
623
                        ClassNotFoundException {
624
                VectorialDisconnectedDBAdapter dbAdapter = new VectorialDisconnectedDBAdapter();
625
                dbAdapter.setDriver(driver);
626
                DataSource ds = dbAdapter.getRecordset();
627
                ds.start();
628
                String database = dataSourceFactory.getTempFile();
629
                String[] fieldNames = new String[ds.getFieldCount() + 1];
630
                System.arraycopy(ds.getFieldNames(), 0, fieldNames, 1, ds
631
                                .getFieldCount());
632
                fieldNames[0] = "the_geom";
633
                int[] types = new int[fieldNames.length];
634
                types[0] = Types.BINARY;
635
                for (int i = 1; i < types.length; i++) {
636
                        types[i] = ds.getFieldType(i - 1);
637
                }
638
                String dsName=null;
639
                try {
640
                        dsName = dataSourceFactory.createTable(database,
641
                                        ds.getPKNames(), fieldNames, types);
642
                } catch (SQLException e) {
643
                        throw new DBException(e);
644
                }
645

    
646
                DBLayerDefinition lyrDef = new DBLayerDefinition();
647
                lyrDef.setTableName(dsName);
648
                lyrDef.setName(layerName);
649
                lyrDef.setFieldNames(ds.getFieldNames());
650
                lyrDef.setFieldGeometry("the_geom");
651
                lyrDef.setFieldID(ds.getPKNames()[0]);
652
                lyrDef.setClassToInstantiate("org.hsqldb.jdbcDriver");
653

    
654
                dataSourceFactory.addDBDataSourceByTable(dsName, null, 0, "sa", "",
655
                                database, dsName, "GDBMS HSQLDB Transactional driver");
656
                DataSource local = dataSourceFactory.createRandomDataSource(dsName,
657
                                DataSourceFactory.MANUAL_OPENING);
658
                local.start();
659
                DataWare dw = local
660
                                .getDataWare(DataSourceFactory.DATA_WARE_COHERENT_ROW_ORDER);
661
                dw.start();
662
                long t1 = System.currentTimeMillis();
663
                dw.beginTrans();
664

    
665
                if (listener == null) {
666
                        listener = new ProgressListener() {
667
                                /**
668
                                 * @see com.iver.cit.gvsig.fmap.ProgressListener#progress(int)
669
                                 */
670
                                public void progress(int n) {
671
                                        // do nothing
672
                                }
673
                        };
674
                }
675

    
676
                for (int i = 0; i < dbAdapter.getShapeCount(); i++) {
677
                        Value[] row = new Value[ds.getFieldCount() + 1];
678

    
679
                        byte[] bytes = dbAdapter.getShape(i).toWKB();
680
                        row[0] = ValueFactory.createValue(bytes);
681

    
682
                        for (int j = 0; j < ds.getFieldCount(); j++) {
683
                                row[j + 1] = ds.getFieldValue(i, j);
684
                        }
685

    
686
                        dw.insertFilledRow(row);
687
                        listener.progress(100 * i / dbAdapter.getShapeCount());
688
                }
689

    
690
                long t2 = System.currentTimeMillis();
691
                dw.commitTrans();
692
                long t3 = System.currentTimeMillis();
693
                System.out.println((t2 - t1) + " - " + (t3 - t2));
694
                dw.stop();
695
                local.stop();
696
                ds.stop();
697
                IVectorialJDBCDriver cacheDriver = (IVectorialJDBCDriver) LayerFactory
698
                                .getDM().getDriver("HSQLDB Driver");
699
                Class.forName("org.hsqldb.jdbcDriver");
700
                IConnection conn=ConnectionFactory.createConnection("jdbc:hsqldb:file:" + database, "sa", "");
701
                cacheDriver.setData(conn, lyrDef);
702
                cacheDriver.setWorkingArea(driver.getWorkingArea());
703
                return createDBLayer(cacheDriver, layerName, proj);
704
        }
705

    
706
        /**
707
         * Crea una FLyrComplexRaster que ataca al driver que se pasa como
708
         * par?metro.
709
         *
710
         * @param driver
711
         * @param f
712
         * @param proj
713
         *
714
         * @throws IllegalArgumentException
715
         *             Si se pasa un driver que no implementa
716
         *             GeorreferencedRasterDriver o NotGeorreferencedRasterDriver
717
         */
718
        public static void createLayer(RasterDriver driver, File f, IProjection proj)
719
                        throws IllegalArgumentException {
720
        }
721

    
722
        /**
723
         * Devuelve el DriverManager.
724
         *
725
         * @return DriverManager.
726
         */
727
        public static DriverManager getDM() {
728
                initializeDriverManager();
729

    
730
                return driverManager;
731
        }
732

    
733
        /**
734
         * Devuelve el WriterManager.
735
         *
736
         * @return WriterManager.
737
         */
738
        public static WriterManager getWM() {
739
                initializeWriterManager();
740

    
741
                return writerManager;
742
        }
743

    
744
        /**
745
         * Inicializa el DriverManager.
746
         */
747
        private static void initializeDriverManager() {
748
                if (driverManager == null) {
749
                        driverManager = new DriverManager();
750
                        driverManager.loadDrivers(new File(LayerFactory.driversPath));
751

    
752
                        Throwable[] failures = driverManager.getLoadFailures();
753

    
754
                        for (int i = 0; i < failures.length; i++) {
755
                                logger.error("", failures[i]);
756
                        }
757

    
758
                        getDataSourceFactory().setDriverManager(driverManager);
759
                        getDataSourceFactory().initialize();
760
                        QueryManager.registerQuery(new ArcJoin());
761
                }
762
        }
763

    
764
        /**
765
         * Inicializa el DriverManager.
766
         */
767
        private static void initializeWriterManager() {
768
                if (writerManager == null) {
769
                        writerManager = new WriterManager();
770
                        writerManager.loadWriters(new File(LayerFactory.writersPath));
771

    
772
                        Throwable[] failures = writerManager.getLoadFailures();
773

    
774
                        for (int i = 0; i < failures.length; i++) {
775
                                logger.error("", failures[i]);
776
                        }
777

    
778
                        getDataSourceFactory().setWriterManager(writerManager);
779
                        getDataSourceFactory().initialize();
780
                        // QueryManager.registerQuery(new ArcJoin());
781
                }
782
        }
783

    
784
        /**
785
         * sets drivers Directory
786
         *
787
         * @param path
788
         */
789
        public static void setDriversPath(String path) {
790
                LayerFactory.driversPath = path;
791
                initializeDriverManager();
792
        }
793

    
794
        /**
795
         * sets writers Directory
796
         *
797
         * @param path
798
         */
799
        public static void setWritersPath(String path) {
800
                LayerFactory.writersPath = path;
801
                initializeWriterManager();
802
        }
803

    
804
        /**
805
         * @return Returns the dataSourceFactory.
806
         */
807
        public static DataSourceFactory getDataSourceFactory() {
808
                if (dataSourceFactory == null) {
809
                        dataSourceFactory = new DataSourceFactory();
810
                }
811
                return dataSourceFactory;
812
        }
813
}