Statistics
| Revision:

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

History | View | Annotate | Download (27.2 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.Hashtable;
48
import java.util.TreeMap;
49

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

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

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

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

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

    
105
        private static DriverManager driverManager;
106

    
107
        private static WriterManager writerManager;
108

    
109
        private static DataSourceFactory dataSourceFactory;
110

    
111
        /**
112
         * This Hashtable allows to register an alternative LayerClass for
113
         * an specific LayerClass than is attempting to create this factory
114
         */
115
        private static Hashtable layerClassMapping = new Hashtable();
116

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

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

    
144
                try {
145
                        Driver d = dm.getDriver(driverName);
146

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

    
167
                return null;
168
        }
169

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

    
190
        /*throws DriverException*/ {
191

    
192
                // TODO Comprobar si hay un adaptador ya
193
                VectorialFileAdapter adapter = new VectorialFileAdapter(f);
194
                adapter.setDriver((VectorialDriver) d);
195

    
196
                FLyrVect capa = new FLyrVect();
197
                capa.setName(layerName);
198

    
199
                // TODO Meter esto dentro de la comprobaci?n de si hay memoria
200
                if (false) {
201
                } else {
202
                        capa.setSource(adapter);
203
                        capa.setProjection(proj);
204
                }
205

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

    
220
                } catch (FieldNotFoundException 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
                } catch (DriverIOException e) {
237
                        //this error is caused for file IO problems
238
                        DriverIOExceptionType excepType =
239
                                new DriverIOExceptionType();
240
                        excepType.setFile(f);
241
                        DriverException exception = new DriverException(e, excepType);
242
                        capa.setAvailable(false);
243
                        capa.addError(exception);
244
                }
245

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

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

    
288
                FLyrVect capa = new FLyrVect();
289
                capa.setName(layerName);
290

    
291
                capa.setSource(adapter);
292
                capa.setProjection(proj);
293

    
294
                try {
295

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

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

    
322
                        DriverException exception = new DriverException(e, excepType);
323
                        capa.setAvailable(false);
324
                        capa.addError(exception);
325
                } catch (DriverIOException e) {
326
                        //by design, start and stop calls to adapter could
327
                        //cause this exception.
328

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

    
338
                        }else{
339
                                type = new GenericDriverExceptionType();
340
                        }
341
                        DriverException exception = new DriverException(e, type);
342
                        capa.setAvailable(false);
343
                        capa.addError(exception);
344
                }catch(Exception e){
345
                        GenericDriverExceptionType type = new GenericDriverExceptionType();
346
                        DriverException exception = new DriverException(e, type);
347
                        capa.setAvailable(false);
348
                        capa.addError(exception);
349
                }
350

    
351
                return capa;
352
        }
353

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

    
375
                Class layerClass;
376
                try {
377
                        layerClass = getLayerClassForLayerClassName(FLyrRaster.class.getName());
378
                } catch (ClassNotFoundException e1) {
379
                        e1.printStackTrace();
380
                        throw new DriverException(e1);
381
                }
382

    
383
                FLyrRaster capa;
384
                try {
385
                        capa = (FLyrRaster)layerClass.newInstance();
386
                } catch (InstantiationException e1) {
387
                        e1.printStackTrace();
388
                        throw new DriverException(e1);
389
                } catch (IllegalAccessException e1) {
390
                        e1.printStackTrace();
391
                        throw new DriverException(e1);
392
                }
393

    
394
                capa.setName(layerName);
395

    
396
                // TODO Meter esto dentro de la comprobaci?n de si hay memoria
397
                if (false) {
398
                } else {
399
                        capa.setSource(adapter);
400
                        capa.setProjection(proj);
401
                        try {
402
                                capa.load();
403
                        } catch (DriverIOException e) {
404
                                throw new DriverException(e);
405
                        }
406
                }
407

    
408
                return capa;
409
        }
410

    
411
        /**
412
         * Crea una capa Raster a partir del nombre driver, fichero y proyecci?n y
413
         * coordenadas de georeferenciaci?n. Esta funci?n es para georeferenciar
414
         * capas raster. Para imagenes que no tienen georeferenciaci?n hay que
415
         * asignarle una temporal, normalmente a partir de la vista activa.
416
         *
417
         * @param layerName
418
         *            Nombre de la capa.
419
         * @param d
420
         *            RasterDriver.
421
         * @param f
422
         *            Fichero.
423
         * @param proj
424
         *            Proyecci?n.
425
         * @param extent
426
         *            Extent de la vista activa
427
         *
428
         * @return Nueva capa de tipo raster.
429
         *
430
         * @throws DriverIOException
431
         */
432
        public static FLyrRaster createLayer(String layerName, RasterDriver d,
433
                        File f, IProjection proj, ViewPort vp) throws DriverException {
434
                RasterAdapter adapter = new RasterFileAdapter(f);
435
                adapter.setDriver(d);
436

    
437
                Class layerClass;
438
                try {
439
                        layerClass = getLayerClassForLayerClassName(FLyrRaster.class.getName());
440
                } catch (ClassNotFoundException e1) {
441
                        e1.printStackTrace();
442
                        throw new DriverException(e1);
443
                }
444

    
445
                FLyrRaster capa;
446
                try {
447
                        capa = (FLyrRaster)layerClass.newInstance();
448
                } catch (InstantiationException e1) {
449
                        e1.printStackTrace();
450
                        throw new DriverException(e1);
451
                } catch (IllegalAccessException e1) {
452
                        e1.printStackTrace();
453
                        throw new DriverException(e1);
454
                }
455

    
456
                capa.setName(layerName);
457

    
458
                // TODO Meter esto dentro de la comprobaci?n de si hay memoria
459
                if (false) {
460
                } else {
461
                        capa.setSource(adapter);
462
                        capa.setProjection(proj);
463
                        // capa.setTempExtent(vp);
464
                        try {
465
                                capa.load();
466
                        } catch (DriverIOException e) {
467
                                throw new DriverException(e);
468
                        }
469
                }
470

    
471
                return capa;
472
        }
473

    
474

    
475
        /**
476
         * Creates a new raster layer in memory. To create this layer type we have to set a data
477
         * buffer and a bounding box instead of a file. Don't use without CMS raster library that
478
         * include MemoryRasterDriver implementation.
479
         * @param layerName Layer name
480
         * @param d raster driver
481
         * @param buf data buffer
482
         * @param ext bounding box
483
         * @param proj projection
484
         * @return raster layer
485
         * @throws DriverException
486
         */
487
        public static FLyrRaster createLayer(String layerName, RasterDriver d,
488
                        RasterBuf buf, Extent ext, IProjection proj) throws DriverException {
489
                RasterAdapter adapter = new RasterFileAdapter(null);
490
                adapter.setDriver(d);
491

    
492

    
493
                Class layerClass;
494
                try {
495
                        layerClass = getLayerClassForLayerClassName(FLyrRaster.class.getName());
496
                } catch (ClassNotFoundException e1) {
497
                        e1.printStackTrace();
498
                        throw new DriverException(e1);
499
                }
500

    
501
                FLyrRaster capa;
502
                try {
503
                        capa = (FLyrRaster)layerClass.newInstance();
504
                } catch (InstantiationException e1) {
505
                        e1.printStackTrace();
506
                        throw new DriverException(e1);
507
                } catch (IllegalAccessException e1) {
508
                        e1.printStackTrace();
509
                        throw new DriverException(e1);
510
                }
511
                capa.setName(layerName);
512

    
513
                // TODO Meter esto dentro de la comprobaci?n de si hay memoria
514
                if (false) {
515
                } else {
516
                        capa.setSource(adapter);
517
                        capa.setProjection(proj);
518
                        capa.setBuffer(buf);
519
                        capa.setExtent(ext);
520
                        try {
521
                                capa.load();
522
                        } catch (DriverIOException e) {
523
                                throw new DriverException(e);
524
                        }
525
                }
526

    
527
                return capa;
528
        }
529

    
530
        /**
531
         * Crea un RandomVectorialWFS con el driver que se le pasa como par?metro y
532
         * guard?ndose la URL del servidor que se pasa como par?metro
533
         *
534
         * @param driver
535
         * @param host
536
         * @param port
537
         * @param user
538
         * @param password
539
         * @param dbName
540
         * @param tableName
541
         * @param proj
542
         *
543
         * @return Capa creada.
544
         *
545
         * @throws UnsupportedOperationException
546
         */
547
        public static FLayer createLayer(IVectorialDatabaseDriver driver,
548
                        String host, int port, String user, String password, String dbName,
549
                        String tableName, IProjection proj) {
550
                throw new UnsupportedOperationException();
551
        }
552

    
553
        public static FLayer createDBLayer(IVectorialDatabaseDriver driver,
554
                        String layerName, IProjection proj) {
555

    
556
                FLyrVect capa = new FLyrVect();
557

    
558
                capa.setName(layerName);
559
                VectorialDBAdapter dbAdapter = new VectorialDBAdapter();
560
                dbAdapter.setDriver(driver);
561

    
562
                capa.setSource(dbAdapter);
563
                capa.setProjection(proj);
564
                try {
565
                        if (driver instanceof WithDefaultLegend) {
566
                                WithDefaultLegend aux = (WithDefaultLegend) driver;
567
                                dbAdapter.start();
568
                                capa.setLegend((VectorialLegend) aux.getDefaultLegend());
569
                                dbAdapter.stop();
570
                        } else {
571
                                capa.setLegend(LegendFactory.createSingleSymbolLegend(capa
572
                                                .getShapeType()));
573
                        }
574
                        if (driver instanceof IDelayedDriver)
575
                        {
576
                                // Por defecto, los drivers est?n listos para entregar
577
                                // features al terminar su initialize. Pero con los drivers
578
                                // que implementan IDelayedDriver, el driver es responsable
579
                                // de avisar cu?ndo est? listo
580
                                capa.getFLayerStatus().setDriverLoaded(false);
581
                                ((IDelayedDriver) driver).addDriverEventListener(new DefaultDelayedDriverListener(capa));
582
                        }
583
                        // PARCHE: Llamamos a getXmlEntity del driver para que se rellenen
584
                        // los valores de host, port, etc, necesarios para un posible reload
585
                        //FIXME: Se vuelve a dejar como estaba... el problema esta en el DefaultDBDriver.getXMLEntiy()
586
                        //       y comentarizemos esto o no, si no arreglamos ese metodo da problemas de persistencia
587
                        driver.setXMLEntity(driver.getXMLEntity());
588

    
589
                } catch (FieldNotFoundException e) {
590
                        LegendDriverExceptionType excepType =
591
                                new LegendDriverExceptionType("Error al construir la leyenda, campo no encontrado");
592
                        //TODO Para hacer esto extensible tiene que usarse puntos
593
                        //de extension, y comparar las clases de leyendas registradas
594
                        VectorialLegend legend = (VectorialLegend)
595
                                ((WithDefaultLegend)driver).getDefaultLegend();
596

    
597
                        excepType.setLegendLabelField(legend.getLabelField());
598
                        excepType.setLegendHeightField(legend.getLabelHeightField());
599
                        excepType.setLegendRotationField(legend.getLabelRotationField());
600
                        DriverException exception = new DriverException(e, excepType);
601
                        capa.setAvailable(false);
602
                        capa.addError(exception);
603
                        return capa;
604
                        // throw new UnsupportedOperationException(e.getMessage());
605
                } catch (DriverException e) {
606
                        DBDriverExceptionType excepType =
607
                                new DBDriverExceptionType();
608
                        excepType.setDriverName(driver.getName());
609
                        excepType.setTableName(driver.getTableName());
610
                        DriverException exception = new DriverException(e, excepType);
611
                        capa.addError(exception);
612
                        capa.setAvailable(false);
613
                        return capa;
614
                        // throw new UnsupportedOperationException(e.getMessage());
615
                } catch (Exception e) {
616
                        ExceptionDescription excepType = new GenericDriverExceptionType();
617
                        DriverException exception = new DriverException(e, excepType);
618
                        capa.addError(exception);
619
                        capa.setAvailable(false);
620
                        return capa;
621
                }
622

    
623
                return capa;
624

    
625
        }
626

    
627
        /**
628
         * @param driver
629
         * @param layerName
630
         * @param object
631
         * @return
632
         * @throws SQLException
633
         * @throws DriverIOException
634
         * @throws IOException
635
         * @throws DriverLoadException
636
         * @throws com.hardcode.gdbms.engine.data.driver.DriverException
637
         * @throws NoSuchTableException
638
         * @throws ClassNotFoundException
639
         * @throws
640
         */
641
        public static FLayer createDisconnectedDBLayer(IVectorialDatabaseDriver driver,
642
                        String layerName, IProjection proj, ProgressListener listener)
643
                        throws DBException, IOException, DriverIOException,
644
                        DriverLoadException, NoSuchTableException,
645
                        com.hardcode.gdbms.engine.data.driver.DriverException,
646
                        ClassNotFoundException {
647
                VectorialDisconnectedDBAdapter dbAdapter = new VectorialDisconnectedDBAdapter();
648
                dbAdapter.setDriver(driver);
649
                DataSource ds = dbAdapter.getRecordset();
650
                ds.start();
651
                String database = dataSourceFactory.getTempFile();
652
                String[] fieldNames = new String[ds.getFieldCount() + 1];
653
                System.arraycopy(ds.getFieldNames(), 0, fieldNames, 1, ds
654
                                .getFieldCount());
655
                fieldNames[0] = "the_geom";
656
                int[] types = new int[fieldNames.length];
657
                types[0] = Types.BINARY;
658
                for (int i = 1; i < types.length; i++) {
659
                        types[i] = ds.getFieldType(i - 1);
660
                }
661
                String dsName=null;
662
                try {
663
                        dsName = dataSourceFactory.createTable(database,
664
                                        ds.getPKNames(), fieldNames, types);
665
                } catch (SQLException e) {
666
                        throw new DBException(e);
667
                }
668

    
669
                DBLayerDefinition lyrDef = new DBLayerDefinition();
670
                lyrDef.setTableName(dsName);
671
                lyrDef.setName(layerName);
672
                lyrDef.setFieldNames(ds.getFieldNames());
673
                lyrDef.setFieldGeometry("the_geom");
674
                lyrDef.setFieldID(ds.getPKNames()[0]);
675
                lyrDef.setClassToInstantiate("org.hsqldb.jdbcDriver");
676

    
677
                dataSourceFactory.addDBDataSourceByTable(dsName, null, 0, "sa", "",
678
                                database, dsName, "GDBMS HSQLDB Transactional driver");
679
                DataSource local = dataSourceFactory.createRandomDataSource(dsName,
680
                                DataSourceFactory.MANUAL_OPENING);
681
                local.start();
682
                DataWare dw = local
683
                                .getDataWare(DataSourceFactory.DATA_WARE_COHERENT_ROW_ORDER);
684
                dw.start();
685
                long t1 = System.currentTimeMillis();
686
                dw.beginTrans();
687

    
688
                if (listener == null) {
689
                        listener = new ProgressListener() {
690
                                /**
691
                                 * @see com.iver.cit.gvsig.fmap.ProgressListener#progress(int)
692
                                 */
693
                                public void progress(int n) {
694
                                        // do nothing
695
                                }
696
                        };
697
                }
698

    
699
                for (int i = 0; i < dbAdapter.getShapeCount(); i++) {
700
                        Value[] row = new Value[ds.getFieldCount() + 1];
701

    
702
                        byte[] bytes = dbAdapter.getShape(i).toWKB();
703
                        row[0] = ValueFactory.createValue(bytes);
704

    
705
                        for (int j = 0; j < ds.getFieldCount(); j++) {
706
                                row[j + 1] = ds.getFieldValue(i, j);
707
                        }
708

    
709
                        dw.insertFilledRow(row);
710
                        listener.progress(100 * i / dbAdapter.getShapeCount());
711
                }
712

    
713
                long t2 = System.currentTimeMillis();
714
                dw.commitTrans();
715
                long t3 = System.currentTimeMillis();
716
                System.out.println((t2 - t1) + " - " + (t3 - t2));
717
                dw.stop();
718
                local.stop();
719
                ds.stop();
720
                IVectorialJDBCDriver cacheDriver = (IVectorialJDBCDriver) LayerFactory
721
                                .getDM().getDriver("HSQLDB Driver");
722
                Class.forName("org.hsqldb.jdbcDriver");
723
                IConnection conn=ConnectionFactory.createConnection("jdbc:hsqldb:file:" + database, "sa", "");
724
                cacheDriver.setData(conn, lyrDef);
725
                cacheDriver.setWorkingArea(driver.getWorkingArea());
726
                return createDBLayer(cacheDriver, layerName, proj);
727
        }
728

    
729
        /**
730
         * Crea una FLyrComplexRaster que ataca al driver que se pasa como
731
         * par?metro.
732
         *
733
         * @param driver
734
         * @param f
735
         * @param proj
736
         *
737
         * @throws IllegalArgumentException
738
         *             Si se pasa un driver que no implementa
739
         *             GeorreferencedRasterDriver o NotGeorreferencedRasterDriver
740
         */
741
        public static void createLayer(RasterDriver driver, File f, IProjection proj)
742
                        throws IllegalArgumentException {
743
        }
744

    
745
        /**
746
         * Devuelve el DriverManager.
747
         *
748
         * @return DriverManager.
749
         */
750
        public static DriverManager getDM() {
751
                initializeDriverManager();
752

    
753
                return driverManager;
754
        }
755

    
756
        /**
757
         * Devuelve el WriterManager.
758
         *
759
         * @return WriterManager.
760
         */
761
        public static WriterManager getWM() {
762
                initializeWriterManager();
763

    
764
                return writerManager;
765
        }
766

    
767
        /**
768
         * Inicializa el DriverManager.
769
         */
770
        private static void initializeDriverManager() {
771
                if (driverManager == null) {
772
                        driverManager = new DriverManager();
773
                        driverManager.loadDrivers(new File(LayerFactory.driversPath));
774

    
775
                        Throwable[] failures = driverManager.getLoadFailures();
776

    
777
                        for (int i = 0; i < failures.length; i++) {
778
                                logger.error("", failures[i]);
779
                        }
780

    
781
                        getDataSourceFactory().setDriverManager(driverManager);
782
                        getDataSourceFactory().initialize();
783
                        QueryManager.registerQuery(new ArcJoin());
784
                }
785
        }
786

    
787
        /**
788
         * Inicializa el DriverManager.
789
         */
790
        private static void initializeWriterManager() {
791
                if (writerManager == null) {
792
                        writerManager = new WriterManager();
793
                        writerManager.loadWriters(new File(LayerFactory.writersPath));
794

    
795
                        Throwable[] failures = writerManager.getLoadFailures();
796

    
797
                        for (int i = 0; i < failures.length; i++) {
798
                                logger.error("", failures[i]);
799
                        }
800

    
801
                        getDataSourceFactory().setWriterManager(writerManager);
802
                        getDataSourceFactory().initialize();
803
                        // QueryManager.registerQuery(new ArcJoin());
804
                }
805
        }
806

    
807
        /**
808
         * sets drivers Directory
809
         *
810
         * @param path
811
         */
812
        public static void setDriversPath(String path) {
813
                LayerFactory.driversPath = path;
814
                initializeDriverManager();
815
        }
816

    
817
        /**
818
         * sets writers Directory
819
         *
820
         * @param path
821
         */
822
        public static void setWritersPath(String path) {
823
                LayerFactory.writersPath = path;
824
                initializeWriterManager();
825
        }
826

    
827
        /**
828
         * @return Returns the dataSourceFactory.
829
         */
830
        public static DataSourceFactory getDataSourceFactory() {
831
                if (dataSourceFactory == null) {
832
                        dataSourceFactory = new DataSourceFactory();
833
                }
834
                return dataSourceFactory;
835
        }
836

    
837

    
838
        /**
839
         * Set a class to use instead of the originalLayerClassName.
840
         *
841
         * @param originalLayerClassName name of class to relpace
842
         * @param layerClassToUse Class than implements FLayer interface to use
843
         *
844
         * @see  getLayerClassForLayerClassName(String,Class)
845
         * @see  unregisterLayerClassForName(String)
846
        */
847
        public static void registerLayerClassForName (String originalLayerClassName, Class layerClassToUse){
848
                boolean isFLayer = false;
849
                Class[] interfaces = layerClassToUse.getInterfaces();
850
                for (int i = 0;i < interfaces.length; i++){
851
                        if (interfaces[i] == FLayer.class){
852
                                isFLayer = true;
853
                                break;
854
                        }
855
                }
856
                if (!isFLayer){
857
                        throw new ClassCastException("The class "+ layerClassToUse.getName() + "must implements FLayer");
858
                }
859

    
860
                layerClassMapping.put(originalLayerClassName,layerClassToUse);
861
        }
862

    
863
        /**
864
         * Unregister the originalLayerClassName class replacement.
865
         *
866
         * @param originalLayerClassName name of class to relpace
867
         * @param layerClassToUse Class than implements FLayer interface to use
868
         * @return true if the class had been registered
869
         *
870
         * @see  getLayerClassForLayerClassName(String,Class)
871
         * @see  unregisterLayerClassForName(String)
872
        */
873
        public static boolean unregisterLayerClassForName (String originalLayerClassName){
874
                return layerClassMapping.remove(originalLayerClassName) != null;
875
        }
876

    
877
        /**
878
         * Gets the class to use for the layerClassName.
879
         * If isn't registered an alternative class for this layerClass
880
         * the this returns 'Class.forName(layerClassName)'
881
         *
882
         * @param layerClassName
883
         * @return Class implements FLayer to use
884
         * @throws ClassNotFoundException
885
         *
886
         * @see  registerLayerClassForName(String,Class)
887
         * @see  unregisterLayerClassForName(String)
888
         */
889
        public static Class getLayerClassForLayerClassName(String layerClassName) throws ClassNotFoundException{
890
                Class layerClass = (Class)layerClassMapping.get(layerClassName);
891
                if (layerClass == null){
892
                        layerClass = Class.forName(layerClassName);
893
                }
894
                return layerClass;
895
        }
896
}