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 1100 fjp
/* 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 214 fernando
package com.iver.cit.gvsig.fmap.layers;
42
43 2277 vcaballero
import java.io.File;
44
import java.io.IOException;
45
import java.sql.SQLException;
46
import java.sql.Types;
47 12431 jmvivo
import java.util.Hashtable;
48 2277 vcaballero
import java.util.TreeMap;
49
50
import org.apache.log4j.Logger;
51
import org.cresques.cts.IProjection;
52 10195 nacho
import org.cresques.io.data.RasterBuf;
53
import org.cresques.px.Extent;
54 2277 vcaballero
55 408 fernando
import com.hardcode.driverManager.Driver;
56
import com.hardcode.driverManager.DriverLoadException;
57
import com.hardcode.driverManager.DriverManager;
58 10401 fjp
import com.hardcode.driverManager.IDelayedDriver;
59 4143 caballero
import com.hardcode.driverManager.WriterManager;
60 1828 fernando
import com.hardcode.gdbms.engine.customQuery.QueryManager;
61 2183 fernando
import com.hardcode.gdbms.engine.data.DataSource;
62 408 fernando
import com.hardcode.gdbms.engine.data.DataSourceFactory;
63 2183 fernando
import com.hardcode.gdbms.engine.data.NoSuchTableException;
64
import com.hardcode.gdbms.engine.data.edition.DataWare;
65 470 fjp
import com.hardcode.gdbms.engine.instruction.FieldNotFoundException;
66 2183 fernando
import com.hardcode.gdbms.engine.values.Value;
67
import com.hardcode.gdbms.engine.values.ValueFactory;
68 8765 jjdelcerro
import com.iver.cit.gvsig.fmap.DBDriverExceptionType;
69 651 fernando
import com.iver.cit.gvsig.fmap.DriverException;
70 8765 jjdelcerro
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 2183 fernando
import com.iver.cit.gvsig.fmap.ProgressListener;
75 2850 nacho
import com.iver.cit.gvsig.fmap.ViewPort;
76 11928 caballero
import com.iver.cit.gvsig.fmap.drivers.ConnectionFactory;
77
import com.iver.cit.gvsig.fmap.drivers.DBException;
78 3236 fjp
import com.iver.cit.gvsig.fmap.drivers.DBLayerDefinition;
79 422 fjp
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
80 11928 caballero
import com.iver.cit.gvsig.fmap.drivers.IConnection;
81 12431 jmvivo
import com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver;
82
import com.iver.cit.gvsig.fmap.drivers.IVectorialJDBCDriver;
83 303 fernando
import com.iver.cit.gvsig.fmap.drivers.RasterDriver;
84 408 fernando
import com.iver.cit.gvsig.fmap.drivers.VectorialDriver;
85 438 fernando
import com.iver.cit.gvsig.fmap.drivers.VectorialFileDriver;
86 714 fjp
import com.iver.cit.gvsig.fmap.drivers.WithDefaultLegend;
87 1828 fernando
import com.iver.cit.gvsig.fmap.operations.arcview.ArcJoin;
88 458 fjp
import com.iver.cit.gvsig.fmap.rendering.LegendFactory;
89 714 fjp
import com.iver.cit.gvsig.fmap.rendering.VectorialLegend;
90 8765 jjdelcerro
import com.iver.utiles.ExceptionDescription;
91 303 fernando
92 214 fernando
/**
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 8765 jjdelcerro
        private static Logger logger = Logger.getLogger(LayerFactory.class
99
                        .getName());
100
101 439 luisw
        private static String driversPath = "../FMap 03/drivers";
102 8765 jjdelcerro
103 4781 fjp
        private static String writersPath = "../FMap 03/drivers";
104 8765 jjdelcerro
105 732 fernando
        private static DriverManager driverManager;
106 8765 jjdelcerro
107 4143 caballero
        private static WriterManager writerManager;
108 408 fernando
109 1828 fernando
        private static DataSourceFactory dataSourceFactory;
110 4143 caballero
111 732 fernando
        /**
112 12431 jmvivo
         * 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 732 fernando
         * Map en el que se guarda para cada fuente de datos a?adida al sistema, el
119 8765 jjdelcerro
         * 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 732 fernando
         */
125
        private static TreeMap sourceAdapter;
126 214 fernando
127 1828 fernando
        /*
128 8765 jjdelcerro
         * 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 732 fernando
         * tendr? asociada la proyecci?n que se pasa como parametro tambi?n
131 10666 caballero
         *
132 8765 jjdelcerro
         * @param layerName Nombre de la capa. @param driverName Nombre del driver.
133
         * @param f fichero. @param proj Proyecci?n.
134 10666 caballero
         *
135 8765 jjdelcerro
         * @return FLayer. @throws DriverException
136 10666 caballero
         *
137 8765 jjdelcerro
         * @throws DriverException @throws DriverIOException
138 2183 fernando
         */
139 732 fernando
        public static FLayer createLayer(String layerName, String driverName,
140 8765 jjdelcerro
                        File f, IProjection proj) throws DriverException {
141
                // Se obtiene el driver que lee
142 732 fernando
                DriverManager dm = getDM();
143 438 fernando
144 732 fernando
                try {
145
                        Driver d = dm.getDriver(driverName);
146 438 fernando
147 732 fernando
                        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 8765 jjdelcerro
                        //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 10666 caballero
                        DriverNotLoadedExceptionType exceptionType =
160 8765 jjdelcerro
                                new DriverNotLoadedExceptionType();
161
                        exceptionType.setDriverName(driverName);
162 10666 caballero
                        DriverException exception =
163
                                new DriverException(e, exceptionType);
164 8765 jjdelcerro
                        throw exception;
165 732 fernando
                }
166 438 fernando
167 732 fernando
                return null;
168
        }
169 2183 fernando
170 1034 vcaballero
        /**
171 8765 jjdelcerro
         * It creates a FLayer (FLyrVect) which reads its data from a file driver,
172
         * projected in the specified projection.
173 10666 caballero
         *
174 8765 jjdelcerro
         * @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 10666 caballero
         *
183 8765 jjdelcerro
         * @return FLayer new vectorial layer
184 10666 caballero
         *
185 1034 vcaballero
         * @throws DriverException
186
         */
187
        public static FLayer createLayer(String layerName, VectorialFileDriver d,
188 10666 caballero
                        File f, IProjection proj)
189
190 8765 jjdelcerro
        /*throws DriverException*/ {
191
192
                // TODO Comprobar si hay un adaptador ya
193 1034 vcaballero
                VectorialFileAdapter adapter = new VectorialFileAdapter(f);
194
                adapter.setDriver((VectorialDriver) d);
195 214 fernando
196 1034 vcaballero
                FLyrVect capa = new FLyrVect();
197
                capa.setName(layerName);
198 8765 jjdelcerro
199
                // TODO Meter esto dentro de la comprobaci?n de si hay memoria
200 1034 vcaballero
                if (false) {
201
                } else {
202
                        capa.setSource(adapter);
203
                        capa.setProjection(proj);
204
                }
205 4143 caballero
206 8765 jjdelcerro
                try {
207 470 fjp
                        // 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 1034 vcaballero
                        if (d instanceof WithDefaultLegend) {
211
                                WithDefaultLegend aux = (WithDefaultLegend) d;
212
                                adapter.start();
213
                                capa.setLegend((VectorialLegend) aux.getDefaultLegend());
214
                                adapter.stop();
215
                        } else {
216 8765 jjdelcerro
                                capa.setLegend(LegendFactory.createSingleSymbolLegend(capa
217
                                                .getShapeType()));
218 1034 vcaballero
                        }
219 10666 caballero
220 8765 jjdelcerro
                } catch (FieldNotFoundException e) {
221
                        //this exception is caused in legend creation
222 10666 caballero
                        LegendDriverExceptionType excepType =
223
                                new LegendDriverExceptionType("Error al construir la leyenda");
224 8765 jjdelcerro
                        //TODO Para hacer esto extensible tiene que usarse puntos
225
                        //de extension, y comparar las clases de leyendas registradas
226 10666 caballero
                        VectorialLegend legend = (VectorialLegend)
227 8765 jjdelcerro
                                ((WithDefaultLegend)d).getDefaultLegend();
228 10666 caballero
229 8765 jjdelcerro
                        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 10666 caballero
236 714 fjp
                } catch (DriverIOException e) {
237 8765 jjdelcerro
                        //this error is caused for file IO problems
238 10666 caballero
                        DriverIOExceptionType excepType =
239 8765 jjdelcerro
                                new DriverIOExceptionType();
240
                        excepType.setFile(f);
241
                        DriverException exception = new DriverException(e, excepType);
242 6537 jmvivo
                        capa.setAvailable(false);
243 8765 jjdelcerro
                        capa.addError(exception);
244 1034 vcaballero
                }
245 10666 caballero
246 8765 jjdelcerro
                /*
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 12431 jmvivo
                        e.printStackTrace();
254 8765 jjdelcerro
                        GenericDriverExceptionType type = new GenericDriverExceptionType();
255
                        DriverException exception = new DriverException(e, type);
256
                        capa.setAvailable(false);
257
                        capa.addError(exception);
258
                }
259 1034 vcaballero
                return capa;
260
        }
261 567 luisw
262 8765 jjdelcerro
        /**
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 10666 caballero
         *
266 8765 jjdelcerro
         * @param layerName
267
         * @param d
268
         * @param proj
269
         * @return
270
         * @throws DriverException
271
         */
272
        public static FLayer createLayer(String layerName, VectorialDriver d,
273 10666 caballero
                        IProjection proj)
274 8765 jjdelcerro
        /*
275 10666 caballero
        throws DriverException
276 8765 jjdelcerro
        */{
277
                VectorialAdapter adapter = null;
278
                if (d instanceof VectorialFileDriver) {
279
                        adapter = new VectorialFileAdapter(((VectorialFileDriver) d)
280
                                        .getFile());
281 11928 caballero
                } else if (d instanceof IVectorialJDBCDriver) {
282 8765 jjdelcerro
                        adapter = new VectorialDBAdapter();
283
                } else {
284
                        adapter = new VectorialDefaultAdapter();
285
                }
286
                adapter.setDriver((VectorialDriver) d);
287 3301 fjp
288 8765 jjdelcerro
                FLyrVect capa = new FLyrVect();
289
                capa.setName(layerName);
290 3301 fjp
291 8765 jjdelcerro
                capa.setSource(adapter);
292
                capa.setProjection(proj);
293 3301 fjp
294 8765 jjdelcerro
                try {
295 4143 caballero
296 8765 jjdelcerro
                        // 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 10666 caballero
                        LegendDriverExceptionType excepType =
311 8765 jjdelcerro
                                new LegendDriverExceptionType("error al construir la leyenda, campo no encontrado");
312 3301 fjp
313 8765 jjdelcerro
                        //TODO Para hacer esto extensible tiene que usarse puntos
314
                        //de extension, y comparar las clases de leyendas registradas
315 10666 caballero
                        VectorialLegend legend = (VectorialLegend)
316 8765 jjdelcerro
                                ((WithDefaultLegend)d).getDefaultLegend();
317
                        excepType.setDriverName(d.getName());
318
                        excepType.setLegendLabelField(legend.getLabelField());
319
                        excepType.setLegendHeightField(legend.getLabelHeightField());
320
                        excepType.setLegendRotationField(legend.getLabelRotationField());
321 10666 caballero
322 8765 jjdelcerro
                        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 10666 caballero
329 8765 jjdelcerro
                        //but JDBC implementations catchs all exceptions,
330 10666 caballero
                        //and rest of layers (WFSLayer, etc.) dont use LayerFactory
331 8765 jjdelcerro
                        ExceptionDescription type = null;
332
                        if (d instanceof VectorialFileDriver) {
333
                                File f = ((VectorialFileDriver)adapter).getFile();
334 10666 caballero
                                type =
335
                                        new DriverIOExceptionType();
336 8765 jjdelcerro
                                ((DriverIOExceptionType)type).setFile(f);
337 10666 caballero
338 8765 jjdelcerro
                        }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 1034 vcaballero
351 8765 jjdelcerro
                return capa;
352
        }
353
354 1034 vcaballero
        /**
355
         * Crea una capa Raster a partir del nombre driver, fichero y proyecci?n.
356 10666 caballero
         *
357 8765 jjdelcerro
         * @param layerName
358
         *            Nombre de la capa.
359
         * @param d
360
         *            RasterDriver.
361
         * @param f
362
         *            Fichero.
363
         * @param proj
364
         *            Proyecci?n.
365 10666 caballero
         *
366 1034 vcaballero
         * @return Nueva capa de tipo raster.
367 10666 caballero
         *
368 1034 vcaballero
         * @throws DriverIOException
369
         */
370 732 fernando
        public static FLyrRaster createLayer(String layerName, RasterDriver d,
371 8765 jjdelcerro
                        File f, IProjection proj) throws DriverException {
372 732 fernando
                RasterAdapter adapter = new RasterFileAdapter(f);
373
                adapter.setDriver(d);
374
375 12431 jmvivo
                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 732 fernando
                capa.setName(layerName);
395
396 8765 jjdelcerro
                // TODO Meter esto dentro de la comprobaci?n de si hay memoria
397 732 fernando
                if (false) {
398
                } else {
399
                        capa.setSource(adapter);
400
                        capa.setProjection(proj);
401 1046 fernando
                        try {
402
                                capa.load();
403
                        } catch (DriverIOException e) {
404
                                throw new DriverException(e);
405
                        }
406 732 fernando
                }
407
408 567 luisw
                return capa;
409 732 fernando
        }
410 567 luisw
411 732 fernando
        /**
412 4143 caballero
         * 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 8765 jjdelcerro
         * capas raster. Para imagenes que no tienen georeferenciaci?n hay que
415
         * asignarle una temporal, normalmente a partir de la vista activa.
416 10666 caballero
         *
417 8765 jjdelcerro
         * @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 10666 caballero
         *
428 2850 nacho
         * @return Nueva capa de tipo raster.
429 10666 caballero
         *
430 2850 nacho
         * @throws DriverIOException
431
         */
432
        public static FLyrRaster createLayer(String layerName, RasterDriver d,
433 8765 jjdelcerro
                        File f, IProjection proj, ViewPort vp) throws DriverException {
434 2850 nacho
                RasterAdapter adapter = new RasterFileAdapter(f);
435
                adapter.setDriver(d);
436 4143 caballero
437 12431 jmvivo
                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 2850 nacho
                capa.setName(layerName);
457 4143 caballero
458 8765 jjdelcerro
                // TODO Meter esto dentro de la comprobaci?n de si hay memoria
459 2850 nacho
                if (false) {
460
                } else {
461
                        capa.setSource(adapter);
462
                        capa.setProjection(proj);
463 8765 jjdelcerro
                        // capa.setTempExtent(vp);
464 2850 nacho
                        try {
465
                                capa.load();
466
                        } catch (DriverIOException e) {
467
                                throw new DriverException(e);
468
                        }
469
                }
470
471
                return capa;
472
        }
473 10666 caballero
474 12431 jmvivo
475 10195 nacho
        /**
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 10666 caballero
         * @param ext bounding box
483
         * @param proj projection
484 10195 nacho
         * @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 4143 caballero
492 12431 jmvivo
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 10195 nacho
                capa.setName(layerName);
512 10666 caballero
513 10195 nacho
                // 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 732 fernando
        /**
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 10666 caballero
         *
534 1034 vcaballero
         * @param driver
535
         * @param host
536
         * @param port
537
         * @param user
538
         * @param password
539
         * @param dbName
540
         * @param tableName
541
         * @param proj
542 10666 caballero
         *
543 1034 vcaballero
         * @return Capa creada.
544 10666 caballero
         *
545 1034 vcaballero
         * @throws UnsupportedOperationException
546 732 fernando
         */
547 11928 caballero
        public static FLayer createLayer(IVectorialDatabaseDriver driver,
548 8765 jjdelcerro
                        String host, int port, String user, String password, String dbName,
549
                        String tableName, IProjection proj) {
550 732 fernando
                throw new UnsupportedOperationException();
551
        }
552 4143 caballero
553 11928 caballero
        public static FLayer createDBLayer(IVectorialDatabaseDriver driver,
554 8765 jjdelcerro
                        String layerName, IProjection proj) {
555 4143 caballero
556 1691 fjp
                FLyrVect capa = new FLyrVect();
557 4143 caballero
558 1691 fjp
                capa.setName(layerName);
559
                VectorialDBAdapter dbAdapter = new VectorialDBAdapter();
560 4143 caballero
                dbAdapter.setDriver(driver);
561
562 1691 fjp
                capa.setSource(dbAdapter);
563
                capa.setProjection(proj);
564
                try {
565
                        if (driver instanceof WithDefaultLegend) {
566
                                WithDefaultLegend aux = (WithDefaultLegend) driver;
567
                                dbAdapter.start();
568 8765 jjdelcerro
                                capa.setLegend((VectorialLegend) aux.getDefaultLegend());
569 1691 fjp
                                dbAdapter.stop();
570 4143 caballero
                        } else {
571 8765 jjdelcerro
                                capa.setLegend(LegendFactory.createSingleSymbolLegend(capa
572
                                                .getShapeType()));
573 1691 fjp
                        }
574 10401 fjp
                        if (driver instanceof IDelayedDriver)
575
                        {
576 10442 fjp
                                // 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 10666 caballero
                                ((IDelayedDriver) driver).addDriverEventListener(new DefaultDelayedDriverListener(capa));
582 10401 fjp
                        }
583 10633 fjp
                        // PARCHE: Llamamos a getXmlEntity del driver para que se rellenen
584
                        // los valores de host, port, etc, necesarios para un posible reload
585 10698 jmvivo
                        //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 10401 fjp
589 8765 jjdelcerro
                } catch (FieldNotFoundException e) {
590 10666 caballero
                        LegendDriverExceptionType excepType =
591 8765 jjdelcerro
                                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 10666 caballero
                        VectorialLegend legend = (VectorialLegend)
595 8765 jjdelcerro
                                ((WithDefaultLegend)driver).getDefaultLegend();
596 10666 caballero
597 8765 jjdelcerro
                        excepType.setLegendLabelField(legend.getLabelField());
598
                        excepType.setLegendHeightField(legend.getLabelHeightField());
599
                        excepType.setLegendRotationField(legend.getLabelRotationField());
600
                        DriverException exception = new DriverException(e, excepType);
601 6537 jmvivo
                        capa.setAvailable(false);
602 8765 jjdelcerro
                        capa.addError(exception);
603 6400 jmvivo
                        return capa;
604 8765 jjdelcerro
                        // throw new UnsupportedOperationException(e.getMessage());
605
                } catch (DriverException e) {
606 10666 caballero
                        DBDriverExceptionType excepType =
607 8765 jjdelcerro
                                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 6400 jmvivo
                        return capa;
614 8765 jjdelcerro
                        // 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 303 fernando
623 1691 fjp
                return capa;
624
625 8765 jjdelcerro
        }
626 1691 fjp
627 2183 fernando
        /**
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 4143 caballero
         * @throws
640 2183 fernando
         */
641 11928 caballero
        public static FLayer createDisconnectedDBLayer(IVectorialDatabaseDriver driver,
642 8765 jjdelcerro
                        String layerName, IProjection proj, ProgressListener listener)
643 11928 caballero
                        throws DBException, IOException, DriverIOException,
644 8765 jjdelcerro
                        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 11928 caballero
                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 4143 caballero
669 8765 jjdelcerro
                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 4143 caballero
677 8765 jjdelcerro
                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 4143 caballero
688 8765 jjdelcerro
                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 4143 caballero
699 8765 jjdelcerro
                for (int i = 0; i < dbAdapter.getShapeCount(); i++) {
700
                        Value[] row = new Value[ds.getFieldCount() + 1];
701 4143 caballero
702 8765 jjdelcerro
                        byte[] bytes = dbAdapter.getShape(i).toWKB();
703
                        row[0] = ValueFactory.createValue(bytes);
704 4143 caballero
705 8765 jjdelcerro
                        for (int j = 0; j < ds.getFieldCount(); j++) {
706
                                row[j + 1] = ds.getFieldValue(i, j);
707
                        }
708 2183 fernando
709 8765 jjdelcerro
                        dw.insertFilledRow(row);
710
                        listener.progress(100 * i / dbAdapter.getShapeCount());
711
                }
712 4143 caballero
713 8765 jjdelcerro
                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 11928 caballero
                IVectorialJDBCDriver cacheDriver = (IVectorialJDBCDriver) LayerFactory
721 8765 jjdelcerro
                                .getDM().getDriver("HSQLDB Driver");
722
                Class.forName("org.hsqldb.jdbcDriver");
723 11928 caballero
                IConnection conn=ConnectionFactory.createConnection("jdbc:hsqldb:file:" + database, "sa", "");
724
                cacheDriver.setData(conn, lyrDef);
725 8765 jjdelcerro
                cacheDriver.setWorkingArea(driver.getWorkingArea());
726
                return createDBLayer(cacheDriver, layerName, proj);
727 2183 fernando
        }
728 4143 caballero
729 732 fernando
        /**
730
         * Crea una FLyrComplexRaster que ataca al driver que se pasa como
731
         * par?metro.
732 10666 caballero
         *
733 1034 vcaballero
         * @param driver
734
         * @param f
735
         * @param proj
736 10666 caballero
         *
737 8765 jjdelcerro
         * @throws IllegalArgumentException
738
         *             Si se pasa un driver que no implementa
739
         *             GeorreferencedRasterDriver o NotGeorreferencedRasterDriver
740 732 fernando
         */
741
        public static void createLayer(RasterDriver driver, File f, IProjection proj)
742 8765 jjdelcerro
                        throws IllegalArgumentException {
743 732 fernando
        }
744 408 fernando
745 732 fernando
        /**
746 1034 vcaballero
         * Devuelve el DriverManager.
747 10666 caballero
         *
748 1034 vcaballero
         * @return DriverManager.
749 732 fernando
         */
750
        public static DriverManager getDM() {
751 1839 fernando
                initializeDriverManager();
752 732 fernando
753
                return driverManager;
754
        }
755 8765 jjdelcerro
756 4143 caballero
        /**
757
         * Devuelve el WriterManager.
758 10666 caballero
         *
759 4143 caballero
         * @return WriterManager.
760
         */
761
        public static WriterManager getWM() {
762
                initializeWriterManager();
763 732 fernando
764 4143 caballero
                return writerManager;
765
        }
766 8765 jjdelcerro
767 732 fernando
        /**
768 1034 vcaballero
         * Inicializa el DriverManager.
769 732 fernando
         */
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 2183 fernando
                                logger.error("", failures[i]);
779 626 fernando
                        }
780
781 1828 fernando
                        getDataSourceFactory().setDriverManager(driverManager);
782 2183 fernando
                        getDataSourceFactory().initialize();
783 1836 fernando
                        QueryManager.registerQuery(new ArcJoin());
784 732 fernando
                }
785
        }
786 8765 jjdelcerro
787 4143 caballero
        /**
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 408 fernando
795 4143 caballero
                        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 8765 jjdelcerro
                        // QueryManager.registerQuery(new ArcJoin());
804 4143 caballero
                }
805
        }
806 8765 jjdelcerro
807 732 fernando
        /**
808
         * sets drivers Directory
809 10666 caballero
         *
810 732 fernando
         * @param path
811
         */
812
        public static void setDriversPath(String path) {
813
                LayerFactory.driversPath = path;
814
                initializeDriverManager();
815
        }
816 8765 jjdelcerro
817 1773 fernando
        /**
818 4143 caballero
         * sets writers Directory
819 10666 caballero
         *
820 4143 caballero
         * @param path
821
         */
822
        public static void setWritersPath(String path) {
823
                LayerFactory.writersPath = path;
824
                initializeWriterManager();
825
        }
826
827
        /**
828 1773 fernando
         * @return Returns the dataSourceFactory.
829
         */
830
        public static DataSourceFactory getDataSourceFactory() {
831 8765 jjdelcerro
                if (dataSourceFactory == null) {
832 1828 fernando
                        dataSourceFactory = new DataSourceFactory();
833
                }
834 1773 fernando
                return dataSourceFactory;
835
        }
836 12431 jmvivo
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 214 fernando
}