Statistics
| Revision:

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

History | View | Annotate | Download (27.4 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 12431 jmvivo
import org.geotools.geometry.coordinatesequence.InPlaceCoordinateSequenceTransformer;
55 2277 vcaballero
56 408 fernando
import com.hardcode.driverManager.Driver;
57
import com.hardcode.driverManager.DriverLoadException;
58
import com.hardcode.driverManager.DriverManager;
59 10401 fjp
import com.hardcode.driverManager.IDelayedDriver;
60 4143 caballero
import com.hardcode.driverManager.WriterManager;
61 1828 fernando
import com.hardcode.gdbms.engine.customQuery.QueryManager;
62 2183 fernando
import com.hardcode.gdbms.engine.data.DataSource;
63 408 fernando
import com.hardcode.gdbms.engine.data.DataSourceFactory;
64 2183 fernando
import com.hardcode.gdbms.engine.data.NoSuchTableException;
65
import com.hardcode.gdbms.engine.data.edition.DataWare;
66 470 fjp
import com.hardcode.gdbms.engine.instruction.FieldNotFoundException;
67 2183 fernando
import com.hardcode.gdbms.engine.values.Value;
68
import com.hardcode.gdbms.engine.values.ValueFactory;
69 8765 jjdelcerro
import com.iver.cit.gvsig.fmap.DBDriverExceptionType;
70 651 fernando
import com.iver.cit.gvsig.fmap.DriverException;
71 8765 jjdelcerro
import com.iver.cit.gvsig.fmap.DriverIOExceptionType;
72
import com.iver.cit.gvsig.fmap.DriverNotLoadedExceptionType;
73
import com.iver.cit.gvsig.fmap.GenericDriverExceptionType;
74
import com.iver.cit.gvsig.fmap.LegendDriverExceptionType;
75 2183 fernando
import com.iver.cit.gvsig.fmap.ProgressListener;
76 2850 nacho
import com.iver.cit.gvsig.fmap.ViewPort;
77 11928 caballero
import com.iver.cit.gvsig.fmap.drivers.ConnectionFactory;
78
import com.iver.cit.gvsig.fmap.drivers.DBException;
79 3236 fjp
import com.iver.cit.gvsig.fmap.drivers.DBLayerDefinition;
80 422 fjp
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
81 11928 caballero
import com.iver.cit.gvsig.fmap.drivers.IConnection;
82 12431 jmvivo
import com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver;
83
import com.iver.cit.gvsig.fmap.drivers.IVectorialJDBCDriver;
84 303 fernando
import com.iver.cit.gvsig.fmap.drivers.RasterDriver;
85 408 fernando
import com.iver.cit.gvsig.fmap.drivers.VectorialDriver;
86 438 fernando
import com.iver.cit.gvsig.fmap.drivers.VectorialFileDriver;
87 714 fjp
import com.iver.cit.gvsig.fmap.drivers.WithDefaultLegend;
88 1828 fernando
import com.iver.cit.gvsig.fmap.operations.arcview.ArcJoin;
89 458 fjp
import com.iver.cit.gvsig.fmap.rendering.LegendFactory;
90 714 fjp
import com.iver.cit.gvsig.fmap.rendering.VectorialLegend;
91 8765 jjdelcerro
import com.iver.utiles.ExceptionDescription;
92 12431 jmvivo
import com.sun.media.jai.codec.SeekableOutputStream;
93 303 fernando
94 214 fernando
/**
95
 * Crea un adaptador del driver que se le pasa como par?metro en los m?todos
96
 * createLayer. Si hay memoria suficiente se crea un FLyrMemory que pasa todas
97
 * las features del driver a memoria
98
 */
99
public class LayerFactory {
100 8765 jjdelcerro
        private static Logger logger = Logger.getLogger(LayerFactory.class
101
                        .getName());
102
103 439 luisw
        private static String driversPath = "../FMap 03/drivers";
104 8765 jjdelcerro
105 4781 fjp
        private static String writersPath = "../FMap 03/drivers";
106 8765 jjdelcerro
107 732 fernando
        private static DriverManager driverManager;
108 8765 jjdelcerro
109 4143 caballero
        private static WriterManager writerManager;
110 408 fernando
111 1828 fernando
        private static DataSourceFactory dataSourceFactory;
112 4143 caballero
113 732 fernando
        /**
114 12431 jmvivo
         * This Hashtable allows to register an alternative LayerClass for
115
         * an specific LayerClass than is attempting to create this factory
116
         */
117
        private static Hashtable layerClassMapping = new Hashtable();
118
119
        /**
120 732 fernando
         * Map en el que se guarda para cada fuente de datos a?adida al sistema, el
121 8765 jjdelcerro
         * adaptador que la maneja. Ha de ser un TreeMap ya que esta clase define la
122
         * igualdad entre las claves a traves del m?todo equals de las mismas. Los
123
         * objetos FileSource, DBSource y WFSSource tienen definido el m?todo equals
124
         * de forma que devuelven true cuando dos objetos apuntan a la misma fuente
125
         * de datos
126 732 fernando
         */
127
        private static TreeMap sourceAdapter;
128 214 fernando
129 1828 fernando
        /*
130 8765 jjdelcerro
         * Crea un RandomVectorialFile con el driver que se le pasa como par?metro y
131
         * guard?ndose el nombre del fichero para realizar los accesos, la capa
132 732 fernando
         * tendr? asociada la proyecci?n que se pasa como parametro tambi?n
133 10666 caballero
         *
134 8765 jjdelcerro
         * @param layerName Nombre de la capa. @param driverName Nombre del driver.
135
         * @param f fichero. @param proj Proyecci?n.
136 10666 caballero
         *
137 8765 jjdelcerro
         * @return FLayer. @throws DriverException
138 10666 caballero
         *
139 8765 jjdelcerro
         * @throws DriverException @throws DriverIOException
140 2183 fernando
         */
141 732 fernando
        public static FLayer createLayer(String layerName, String driverName,
142 8765 jjdelcerro
                        File f, IProjection proj) throws DriverException {
143
                // Se obtiene el driver que lee
144 732 fernando
                DriverManager dm = getDM();
145 438 fernando
146 732 fernando
                try {
147
                        Driver d = dm.getDriver(driverName);
148 438 fernando
149 732 fernando
                        if (d instanceof VectorialFileDriver) {
150
                                return createLayer(layerName, (VectorialFileDriver) d, f, proj);
151
                        } else if (d instanceof RasterDriver) {
152
                                return createLayer(layerName, (RasterDriver) d, f, proj);
153
                        }
154
                } catch (DriverLoadException e) {
155 8765 jjdelcerro
                        //hay un poco de lio sobre que excepciones se dejan subir
156
                        //arriba y que excepciones se quedan en LayerFactory
157
                        //(esto se debe a que queremos intentar recuperar ciertas capas)
158
                        //las excepciones de este metodo se dejan subir todas, puesto
159
                        //que las excepciones de los dos otros metodos createLayer si que
160
                        //se atrapan
161 10666 caballero
                        DriverNotLoadedExceptionType exceptionType =
162 8765 jjdelcerro
                                new DriverNotLoadedExceptionType();
163
                        exceptionType.setDriverName(driverName);
164 10666 caballero
                        DriverException exception =
165
                                new DriverException(e, exceptionType);
166 8765 jjdelcerro
                        throw exception;
167 732 fernando
                }
168 438 fernando
169 732 fernando
                return null;
170
        }
171 2183 fernando
172 1034 vcaballero
        /**
173 8765 jjdelcerro
         * It creates a FLayer (FLyrVect) which reads its data from a file driver,
174
         * projected in the specified projection.
175 10666 caballero
         *
176 8765 jjdelcerro
         * @param layerName
177
         *            name of the layer
178
         * @param d
179
         *            vectorial file driver to read layer's data
180
         * @param f
181
         *            file associated to the driver
182
         * @param proj
183
         *            layer projection
184 10666 caballero
         *
185 8765 jjdelcerro
         * @return FLayer new vectorial layer
186 10666 caballero
         *
187 1034 vcaballero
         * @throws DriverException
188
         */
189
        public static FLayer createLayer(String layerName, VectorialFileDriver d,
190 10666 caballero
                        File f, IProjection proj)
191
192 8765 jjdelcerro
        /*throws DriverException*/ {
193
194
                // TODO Comprobar si hay un adaptador ya
195 1034 vcaballero
                VectorialFileAdapter adapter = new VectorialFileAdapter(f);
196
                adapter.setDriver((VectorialDriver) d);
197 214 fernando
198 1034 vcaballero
                FLyrVect capa = new FLyrVect();
199
                capa.setName(layerName);
200 8765 jjdelcerro
201
                // TODO Meter esto dentro de la comprobaci?n de si hay memoria
202 1034 vcaballero
                if (false) {
203
                } else {
204
                        capa.setSource(adapter);
205
                        capa.setProjection(proj);
206
                }
207 4143 caballero
208 8765 jjdelcerro
                try {
209 470 fjp
                        // Le asignamos tambi?n una legenda por defecto acorde con
210
                        // el tipo de shape que tenga. Tampoco s? si es aqu? el
211
                        // sitio adecuado, pero en fin....
212 1034 vcaballero
                        if (d instanceof WithDefaultLegend) {
213
                                WithDefaultLegend aux = (WithDefaultLegend) d;
214
                                adapter.start();
215
                                capa.setLegend((VectorialLegend) aux.getDefaultLegend());
216
                                adapter.stop();
217
                        } else {
218 8765 jjdelcerro
                                capa.setLegend(LegendFactory.createSingleSymbolLegend(capa
219
                                                .getShapeType()));
220 1034 vcaballero
                        }
221 10666 caballero
222 8765 jjdelcerro
                } catch (FieldNotFoundException e) {
223
                        //this exception is caused in legend creation
224 10666 caballero
                        LegendDriverExceptionType excepType =
225
                                new LegendDriverExceptionType("Error al construir la leyenda");
226 8765 jjdelcerro
                        //TODO Para hacer esto extensible tiene que usarse puntos
227
                        //de extension, y comparar las clases de leyendas registradas
228 10666 caballero
                        VectorialLegend legend = (VectorialLegend)
229 8765 jjdelcerro
                                ((WithDefaultLegend)d).getDefaultLegend();
230 10666 caballero
231 8765 jjdelcerro
                        excepType.setLegendLabelField(legend.getLabelField());
232
                        excepType.setLegendHeightField(legend.getLabelHeightField());
233
                        excepType.setLegendRotationField(legend.getLabelRotationField());
234
                        DriverException exception = new DriverException(e, excepType);
235
                        capa.setAvailable(false);
236
                        capa.addError(exception);
237 10666 caballero
238 714 fjp
                } catch (DriverIOException e) {
239 8765 jjdelcerro
                        //this error is caused for file IO problems
240 10666 caballero
                        DriverIOExceptionType excepType =
241 8765 jjdelcerro
                                new DriverIOExceptionType();
242
                        excepType.setFile(f);
243
                        DriverException exception = new DriverException(e, excepType);
244 6537 jmvivo
                        capa.setAvailable(false);
245 8765 jjdelcerro
                        capa.addError(exception);
246 1034 vcaballero
                }
247 10666 caballero
248 8765 jjdelcerro
                /*
249
                 * catch(DriverException e){
250
                 * ESTO HAY QUE CAPTURARLO,DE FORMA QUE CREATELAYER NO LANCE NINGUNA
251
                 * EXCEPCION (A NO SER QUE SEA IRRECUPERABLE)
252
                 * }
253
                 */
254
                catch(Exception e){
255 12431 jmvivo
                        e.printStackTrace();
256 8765 jjdelcerro
                        GenericDriverExceptionType type = new GenericDriverExceptionType();
257
                        DriverException exception = new DriverException(e, type);
258
                        capa.setAvailable(false);
259
                        capa.addError(exception);
260
                }
261 1034 vcaballero
                return capa;
262
        }
263 567 luisw
264 8765 jjdelcerro
        /**
265
         * Creates a new vectorial layer from a generic layer (by generic whe mean
266
         * that we dont know a priory its origin: file, memory, jdbc database, etc.
267 10666 caballero
         *
268 8765 jjdelcerro
         * @param layerName
269
         * @param d
270
         * @param proj
271
         * @return
272
         * @throws DriverException
273
         */
274
        public static FLayer createLayer(String layerName, VectorialDriver d,
275 10666 caballero
                        IProjection proj)
276 8765 jjdelcerro
        /*
277 10666 caballero
        throws DriverException
278 8765 jjdelcerro
        */{
279
                VectorialAdapter adapter = null;
280
                if (d instanceof VectorialFileDriver) {
281
                        adapter = new VectorialFileAdapter(((VectorialFileDriver) d)
282
                                        .getFile());
283 11928 caballero
                } else if (d instanceof IVectorialJDBCDriver) {
284 8765 jjdelcerro
                        adapter = new VectorialDBAdapter();
285
                } else {
286
                        adapter = new VectorialDefaultAdapter();
287
                }
288
                adapter.setDriver((VectorialDriver) d);
289 3301 fjp
290 8765 jjdelcerro
                FLyrVect capa = new FLyrVect();
291
                capa.setName(layerName);
292 3301 fjp
293 8765 jjdelcerro
                capa.setSource(adapter);
294
                capa.setProjection(proj);
295 3301 fjp
296 8765 jjdelcerro
                try {
297 4143 caballero
298 8765 jjdelcerro
                        // Le asignamos tambi?n una legenda por defecto acorde con
299
                        // el tipo de shape que tenga. Tampoco s? si es aqu? el
300
                        // sitio adecuado, pero en fin....
301
                        if (d instanceof WithDefaultLegend) {
302
                                WithDefaultLegend aux = (WithDefaultLegend) d;
303
                                adapter.start();
304
                                capa.setLegend((VectorialLegend) aux.getDefaultLegend());
305
                                adapter.stop();
306
                        } else {
307
                                capa.setLegend(LegendFactory.createSingleSymbolLegend(capa
308
                                                .getShapeType()));
309
                        }
310
                } catch (FieldNotFoundException e) {
311
//                        this exception is caused in legend creation
312 10666 caballero
                        LegendDriverExceptionType excepType =
313 8765 jjdelcerro
                                new LegendDriverExceptionType("error al construir la leyenda, campo no encontrado");
314 3301 fjp
315 8765 jjdelcerro
                        //TODO Para hacer esto extensible tiene que usarse puntos
316
                        //de extension, y comparar las clases de leyendas registradas
317 10666 caballero
                        VectorialLegend legend = (VectorialLegend)
318 8765 jjdelcerro
                                ((WithDefaultLegend)d).getDefaultLegend();
319
                        excepType.setDriverName(d.getName());
320
                        excepType.setLegendLabelField(legend.getLabelField());
321
                        excepType.setLegendHeightField(legend.getLabelHeightField());
322
                        excepType.setLegendRotationField(legend.getLabelRotationField());
323 10666 caballero
324 8765 jjdelcerro
                        DriverException exception = new DriverException(e, excepType);
325
                        capa.setAvailable(false);
326
                        capa.addError(exception);
327
                } catch (DriverIOException e) {
328
                        //by design, start and stop calls to adapter could
329
                        //cause this exception.
330 10666 caballero
331 8765 jjdelcerro
                        //but JDBC implementations catchs all exceptions,
332 10666 caballero
                        //and rest of layers (WFSLayer, etc.) dont use LayerFactory
333 8765 jjdelcerro
                        ExceptionDescription type = null;
334
                        if (d instanceof VectorialFileDriver) {
335
                                File f = ((VectorialFileDriver)adapter).getFile();
336 10666 caballero
                                type =
337
                                        new DriverIOExceptionType();
338 8765 jjdelcerro
                                ((DriverIOExceptionType)type).setFile(f);
339 10666 caballero
340 8765 jjdelcerro
                        }else{
341
                                type = new GenericDriverExceptionType();
342
                        }
343
                        DriverException exception = new DriverException(e, type);
344
                        capa.setAvailable(false);
345
                        capa.addError(exception);
346
                }catch(Exception e){
347
                        GenericDriverExceptionType type = new GenericDriverExceptionType();
348
                        DriverException exception = new DriverException(e, type);
349
                        capa.setAvailable(false);
350
                        capa.addError(exception);
351
                }
352 1034 vcaballero
353 8765 jjdelcerro
                return capa;
354
        }
355
356 1034 vcaballero
        /**
357
         * Crea una capa Raster a partir del nombre driver, fichero y proyecci?n.
358 10666 caballero
         *
359 8765 jjdelcerro
         * @param layerName
360
         *            Nombre de la capa.
361
         * @param d
362
         *            RasterDriver.
363
         * @param f
364
         *            Fichero.
365
         * @param proj
366
         *            Proyecci?n.
367 10666 caballero
         *
368 1034 vcaballero
         * @return Nueva capa de tipo raster.
369 10666 caballero
         *
370 1034 vcaballero
         * @throws DriverIOException
371
         */
372 732 fernando
        public static FLyrRaster createLayer(String layerName, RasterDriver d,
373 8765 jjdelcerro
                        File f, IProjection proj) throws DriverException {
374 732 fernando
                RasterAdapter adapter = new RasterFileAdapter(f);
375
                adapter.setDriver(d);
376
377 12431 jmvivo
                Class layerClass;
378
                try {
379
                        layerClass = getLayerClassForLayerClassName(FLyrRaster.class.getName());
380
                } catch (ClassNotFoundException e1) {
381
                        e1.printStackTrace();
382
                        throw new DriverException(e1);
383
                }
384
385
                FLyrRaster capa;
386
                try {
387
                        capa = (FLyrRaster)layerClass.newInstance();
388
                } catch (InstantiationException e1) {
389
                        e1.printStackTrace();
390
                        throw new DriverException(e1);
391
                } catch (IllegalAccessException e1) {
392
                        e1.printStackTrace();
393
                        throw new DriverException(e1);
394
                }
395
396 732 fernando
                capa.setName(layerName);
397
398 8765 jjdelcerro
                // TODO Meter esto dentro de la comprobaci?n de si hay memoria
399 732 fernando
                if (false) {
400
                } else {
401
                        capa.setSource(adapter);
402
                        capa.setProjection(proj);
403 1046 fernando
                        try {
404
                                capa.load();
405
                        } catch (DriverIOException e) {
406
                                throw new DriverException(e);
407
                        }
408 732 fernando
                }
409
410 567 luisw
                return capa;
411 732 fernando
        }
412 567 luisw
413 732 fernando
        /**
414 4143 caballero
         * Crea una capa Raster a partir del nombre driver, fichero y proyecci?n y
415
         * coordenadas de georeferenciaci?n. Esta funci?n es para georeferenciar
416 8765 jjdelcerro
         * capas raster. Para imagenes que no tienen georeferenciaci?n hay que
417
         * asignarle una temporal, normalmente a partir de la vista activa.
418 10666 caballero
         *
419 8765 jjdelcerro
         * @param layerName
420
         *            Nombre de la capa.
421
         * @param d
422
         *            RasterDriver.
423
         * @param f
424
         *            Fichero.
425
         * @param proj
426
         *            Proyecci?n.
427
         * @param extent
428
         *            Extent de la vista activa
429 10666 caballero
         *
430 2850 nacho
         * @return Nueva capa de tipo raster.
431 10666 caballero
         *
432 2850 nacho
         * @throws DriverIOException
433
         */
434
        public static FLyrRaster createLayer(String layerName, RasterDriver d,
435 8765 jjdelcerro
                        File f, IProjection proj, ViewPort vp) throws DriverException {
436 2850 nacho
                RasterAdapter adapter = new RasterFileAdapter(f);
437
                adapter.setDriver(d);
438 4143 caballero
439 12431 jmvivo
                Class layerClass;
440
                try {
441
                        layerClass = getLayerClassForLayerClassName(FLyrRaster.class.getName());
442
                } catch (ClassNotFoundException e1) {
443
                        e1.printStackTrace();
444
                        throw new DriverException(e1);
445
                }
446
447
                FLyrRaster capa;
448
                try {
449
                        capa = (FLyrRaster)layerClass.newInstance();
450
                } catch (InstantiationException e1) {
451
                        e1.printStackTrace();
452
                        throw new DriverException(e1);
453
                } catch (IllegalAccessException e1) {
454
                        e1.printStackTrace();
455
                        throw new DriverException(e1);
456
                }
457
458 2850 nacho
                capa.setName(layerName);
459 4143 caballero
460 8765 jjdelcerro
                // TODO Meter esto dentro de la comprobaci?n de si hay memoria
461 2850 nacho
                if (false) {
462
                } else {
463
                        capa.setSource(adapter);
464
                        capa.setProjection(proj);
465 8765 jjdelcerro
                        // capa.setTempExtent(vp);
466 2850 nacho
                        try {
467
                                capa.load();
468
                        } catch (DriverIOException e) {
469
                                throw new DriverException(e);
470
                        }
471
                }
472
473
                return capa;
474
        }
475 10666 caballero
476 12431 jmvivo
477 10195 nacho
        /**
478
         * Creates a new raster layer in memory. To create this layer type we have to set a data
479
         * buffer and a bounding box instead of a file. Don't use without CMS raster library that
480
         * include MemoryRasterDriver implementation.
481
         * @param layerName Layer name
482
         * @param d raster driver
483
         * @param buf data buffer
484 10666 caballero
         * @param ext bounding box
485
         * @param proj projection
486 10195 nacho
         * @return raster layer
487
         * @throws DriverException
488
         */
489
        public static FLyrRaster createLayer(String layerName, RasterDriver d,
490
                        RasterBuf buf, Extent ext, IProjection proj) throws DriverException {
491
                RasterAdapter adapter = new RasterFileAdapter(null);
492
                adapter.setDriver(d);
493 4143 caballero
494 12431 jmvivo
495
                Class layerClass;
496
                try {
497
                        layerClass = getLayerClassForLayerClassName(FLyrRaster.class.getName());
498
                } catch (ClassNotFoundException e1) {
499
                        e1.printStackTrace();
500
                        throw new DriverException(e1);
501
                }
502
503
                FLyrRaster capa;
504
                try {
505
                        capa = (FLyrRaster)layerClass.newInstance();
506
                } catch (InstantiationException e1) {
507
                        e1.printStackTrace();
508
                        throw new DriverException(e1);
509
                } catch (IllegalAccessException e1) {
510
                        e1.printStackTrace();
511
                        throw new DriverException(e1);
512
                }
513 10195 nacho
                capa.setName(layerName);
514 10666 caballero
515 10195 nacho
                // TODO Meter esto dentro de la comprobaci?n de si hay memoria
516
                if (false) {
517
                } else {
518
                        capa.setSource(adapter);
519
                        capa.setProjection(proj);
520
                        capa.setBuffer(buf);
521
                        capa.setExtent(ext);
522
                        try {
523
                                capa.load();
524
                        } catch (DriverIOException e) {
525
                                throw new DriverException(e);
526
                        }
527
                }
528
529
                return capa;
530
        }
531
532 732 fernando
        /**
533
         * Crea un RandomVectorialWFS con el driver que se le pasa como par?metro y
534
         * guard?ndose la URL del servidor que se pasa como par?metro
535 10666 caballero
         *
536 1034 vcaballero
         * @param driver
537
         * @param host
538
         * @param port
539
         * @param user
540
         * @param password
541
         * @param dbName
542
         * @param tableName
543
         * @param proj
544 10666 caballero
         *
545 1034 vcaballero
         * @return Capa creada.
546 10666 caballero
         *
547 1034 vcaballero
         * @throws UnsupportedOperationException
548 732 fernando
         */
549 11928 caballero
        public static FLayer createLayer(IVectorialDatabaseDriver driver,
550 8765 jjdelcerro
                        String host, int port, String user, String password, String dbName,
551
                        String tableName, IProjection proj) {
552 732 fernando
                throw new UnsupportedOperationException();
553
        }
554 4143 caballero
555 11928 caballero
        public static FLayer createDBLayer(IVectorialDatabaseDriver driver,
556 8765 jjdelcerro
                        String layerName, IProjection proj) {
557 4143 caballero
558 1691 fjp
                FLyrVect capa = new FLyrVect();
559 4143 caballero
560 1691 fjp
                capa.setName(layerName);
561
                VectorialDBAdapter dbAdapter = new VectorialDBAdapter();
562 4143 caballero
                dbAdapter.setDriver(driver);
563
564 1691 fjp
                capa.setSource(dbAdapter);
565
                capa.setProjection(proj);
566
                try {
567
                        if (driver instanceof WithDefaultLegend) {
568
                                WithDefaultLegend aux = (WithDefaultLegend) driver;
569
                                dbAdapter.start();
570 8765 jjdelcerro
                                capa.setLegend((VectorialLegend) aux.getDefaultLegend());
571 1691 fjp
                                dbAdapter.stop();
572 4143 caballero
                        } else {
573 8765 jjdelcerro
                                capa.setLegend(LegendFactory.createSingleSymbolLegend(capa
574
                                                .getShapeType()));
575 1691 fjp
                        }
576 10401 fjp
                        if (driver instanceof IDelayedDriver)
577
                        {
578 10442 fjp
                                // Por defecto, los drivers est?n listos para entregar
579
                                // features al terminar su initialize. Pero con los drivers
580
                                // que implementan IDelayedDriver, el driver es responsable
581
                                // de avisar cu?ndo est? listo
582
                                capa.getFLayerStatus().setDriverLoaded(false);
583 10666 caballero
                                ((IDelayedDriver) driver).addDriverEventListener(new DefaultDelayedDriverListener(capa));
584 10401 fjp
                        }
585 10633 fjp
                        // PARCHE: Llamamos a getXmlEntity del driver para que se rellenen
586
                        // los valores de host, port, etc, necesarios para un posible reload
587 10698 jmvivo
                        //FIXME: Se vuelve a dejar como estaba... el problema esta en el DefaultDBDriver.getXMLEntiy()
588
                        //       y comentarizemos esto o no, si no arreglamos ese metodo da problemas de persistencia
589
                        driver.setXMLEntity(driver.getXMLEntity());
590 10401 fjp
591 8765 jjdelcerro
                } catch (FieldNotFoundException e) {
592 10666 caballero
                        LegendDriverExceptionType excepType =
593 8765 jjdelcerro
                                new LegendDriverExceptionType("Error al construir la leyenda, campo no encontrado");
594
                        //TODO Para hacer esto extensible tiene que usarse puntos
595
                        //de extension, y comparar las clases de leyendas registradas
596 10666 caballero
                        VectorialLegend legend = (VectorialLegend)
597 8765 jjdelcerro
                                ((WithDefaultLegend)driver).getDefaultLegend();
598 10666 caballero
599 8765 jjdelcerro
                        excepType.setLegendLabelField(legend.getLabelField());
600
                        excepType.setLegendHeightField(legend.getLabelHeightField());
601
                        excepType.setLegendRotationField(legend.getLabelRotationField());
602
                        DriverException exception = new DriverException(e, excepType);
603 6537 jmvivo
                        capa.setAvailable(false);
604 8765 jjdelcerro
                        capa.addError(exception);
605 6400 jmvivo
                        return capa;
606 8765 jjdelcerro
                        // throw new UnsupportedOperationException(e.getMessage());
607
                } catch (DriverException e) {
608 10666 caballero
                        DBDriverExceptionType excepType =
609 8765 jjdelcerro
                                new DBDriverExceptionType();
610
                        excepType.setDriverName(driver.getName());
611
                        excepType.setTableName(driver.getTableName());
612
                        DriverException exception = new DriverException(e, excepType);
613
                        capa.addError(exception);
614
                        capa.setAvailable(false);
615 6400 jmvivo
                        return capa;
616 8765 jjdelcerro
                        // throw new UnsupportedOperationException(e.getMessage());
617
                } catch (Exception e) {
618
                        ExceptionDescription excepType = new GenericDriverExceptionType();
619
                        DriverException exception = new DriverException(e, excepType);
620
                        capa.addError(exception);
621
                        capa.setAvailable(false);
622
                        return capa;
623
                }
624 303 fernando
625 1691 fjp
                return capa;
626
627 8765 jjdelcerro
        }
628 1691 fjp
629 2183 fernando
        /**
630
         * @param driver
631
         * @param layerName
632
         * @param object
633
         * @return
634
         * @throws SQLException
635
         * @throws DriverIOException
636
         * @throws IOException
637
         * @throws DriverLoadException
638
         * @throws com.hardcode.gdbms.engine.data.driver.DriverException
639
         * @throws NoSuchTableException
640
         * @throws ClassNotFoundException
641 4143 caballero
         * @throws
642 2183 fernando
         */
643 11928 caballero
        public static FLayer createDisconnectedDBLayer(IVectorialDatabaseDriver driver,
644 8765 jjdelcerro
                        String layerName, IProjection proj, ProgressListener listener)
645 11928 caballero
                        throws DBException, IOException, DriverIOException,
646 8765 jjdelcerro
                        DriverLoadException, NoSuchTableException,
647
                        com.hardcode.gdbms.engine.data.driver.DriverException,
648
                        ClassNotFoundException {
649
                VectorialDisconnectedDBAdapter dbAdapter = new VectorialDisconnectedDBAdapter();
650
                dbAdapter.setDriver(driver);
651
                DataSource ds = dbAdapter.getRecordset();
652
                ds.start();
653
                String database = dataSourceFactory.getTempFile();
654
                String[] fieldNames = new String[ds.getFieldCount() + 1];
655
                System.arraycopy(ds.getFieldNames(), 0, fieldNames, 1, ds
656
                                .getFieldCount());
657
                fieldNames[0] = "the_geom";
658
                int[] types = new int[fieldNames.length];
659
                types[0] = Types.BINARY;
660
                for (int i = 1; i < types.length; i++) {
661
                        types[i] = ds.getFieldType(i - 1);
662
                }
663 11928 caballero
                String dsName=null;
664
                try {
665
                        dsName = dataSourceFactory.createTable(database,
666
                                        ds.getPKNames(), fieldNames, types);
667
                } catch (SQLException e) {
668
                        throw new DBException(e);
669
                }
670 4143 caballero
671 8765 jjdelcerro
                DBLayerDefinition lyrDef = new DBLayerDefinition();
672
                lyrDef.setTableName(dsName);
673
                lyrDef.setName(layerName);
674
                lyrDef.setFieldNames(ds.getFieldNames());
675
                lyrDef.setFieldGeometry("the_geom");
676
                lyrDef.setFieldID(ds.getPKNames()[0]);
677
                lyrDef.setClassToInstantiate("org.hsqldb.jdbcDriver");
678 4143 caballero
679 8765 jjdelcerro
                dataSourceFactory.addDBDataSourceByTable(dsName, null, 0, "sa", "",
680
                                database, dsName, "GDBMS HSQLDB Transactional driver");
681
                DataSource local = dataSourceFactory.createRandomDataSource(dsName,
682
                                DataSourceFactory.MANUAL_OPENING);
683
                local.start();
684
                DataWare dw = local
685
                                .getDataWare(DataSourceFactory.DATA_WARE_COHERENT_ROW_ORDER);
686
                dw.start();
687
                long t1 = System.currentTimeMillis();
688
                dw.beginTrans();
689 4143 caballero
690 8765 jjdelcerro
                if (listener == null) {
691
                        listener = new ProgressListener() {
692
                                /**
693
                                 * @see com.iver.cit.gvsig.fmap.ProgressListener#progress(int)
694
                                 */
695
                                public void progress(int n) {
696
                                        // do nothing
697
                                }
698
                        };
699
                }
700 4143 caballero
701 8765 jjdelcerro
                for (int i = 0; i < dbAdapter.getShapeCount(); i++) {
702
                        Value[] row = new Value[ds.getFieldCount() + 1];
703 4143 caballero
704 8765 jjdelcerro
                        byte[] bytes = dbAdapter.getShape(i).toWKB();
705
                        row[0] = ValueFactory.createValue(bytes);
706 4143 caballero
707 8765 jjdelcerro
                        for (int j = 0; j < ds.getFieldCount(); j++) {
708
                                row[j + 1] = ds.getFieldValue(i, j);
709
                        }
710 2183 fernando
711 8765 jjdelcerro
                        dw.insertFilledRow(row);
712
                        listener.progress(100 * i / dbAdapter.getShapeCount());
713
                }
714 4143 caballero
715 8765 jjdelcerro
                long t2 = System.currentTimeMillis();
716
                dw.commitTrans();
717
                long t3 = System.currentTimeMillis();
718
                System.out.println((t2 - t1) + " - " + (t3 - t2));
719
                dw.stop();
720
                local.stop();
721
                ds.stop();
722 11928 caballero
                IVectorialJDBCDriver cacheDriver = (IVectorialJDBCDriver) LayerFactory
723 8765 jjdelcerro
                                .getDM().getDriver("HSQLDB Driver");
724
                Class.forName("org.hsqldb.jdbcDriver");
725 11928 caballero
                IConnection conn=ConnectionFactory.createConnection("jdbc:hsqldb:file:" + database, "sa", "");
726
                cacheDriver.setData(conn, lyrDef);
727 8765 jjdelcerro
                cacheDriver.setWorkingArea(driver.getWorkingArea());
728
                return createDBLayer(cacheDriver, layerName, proj);
729 2183 fernando
        }
730 4143 caballero
731 732 fernando
        /**
732
         * Crea una FLyrComplexRaster que ataca al driver que se pasa como
733
         * par?metro.
734 10666 caballero
         *
735 1034 vcaballero
         * @param driver
736
         * @param f
737
         * @param proj
738 10666 caballero
         *
739 8765 jjdelcerro
         * @throws IllegalArgumentException
740
         *             Si se pasa un driver que no implementa
741
         *             GeorreferencedRasterDriver o NotGeorreferencedRasterDriver
742 732 fernando
         */
743
        public static void createLayer(RasterDriver driver, File f, IProjection proj)
744 8765 jjdelcerro
                        throws IllegalArgumentException {
745 732 fernando
        }
746 408 fernando
747 732 fernando
        /**
748 1034 vcaballero
         * Devuelve el DriverManager.
749 10666 caballero
         *
750 1034 vcaballero
         * @return DriverManager.
751 732 fernando
         */
752
        public static DriverManager getDM() {
753 1839 fernando
                initializeDriverManager();
754 732 fernando
755
                return driverManager;
756
        }
757 8765 jjdelcerro
758 4143 caballero
        /**
759
         * Devuelve el WriterManager.
760 10666 caballero
         *
761 4143 caballero
         * @return WriterManager.
762
         */
763
        public static WriterManager getWM() {
764
                initializeWriterManager();
765 732 fernando
766 4143 caballero
                return writerManager;
767
        }
768 8765 jjdelcerro
769 732 fernando
        /**
770 1034 vcaballero
         * Inicializa el DriverManager.
771 732 fernando
         */
772
        private static void initializeDriverManager() {
773
                if (driverManager == null) {
774
                        driverManager = new DriverManager();
775
                        driverManager.loadDrivers(new File(LayerFactory.driversPath));
776
777
                        Throwable[] failures = driverManager.getLoadFailures();
778
779
                        for (int i = 0; i < failures.length; i++) {
780 2183 fernando
                                logger.error("", failures[i]);
781 626 fernando
                        }
782
783 1828 fernando
                        getDataSourceFactory().setDriverManager(driverManager);
784 2183 fernando
                        getDataSourceFactory().initialize();
785 1836 fernando
                        QueryManager.registerQuery(new ArcJoin());
786 732 fernando
                }
787
        }
788 8765 jjdelcerro
789 4143 caballero
        /**
790
         * Inicializa el DriverManager.
791
         */
792
        private static void initializeWriterManager() {
793
                if (writerManager == null) {
794
                        writerManager = new WriterManager();
795
                        writerManager.loadWriters(new File(LayerFactory.writersPath));
796 408 fernando
797 4143 caballero
                        Throwable[] failures = writerManager.getLoadFailures();
798
799
                        for (int i = 0; i < failures.length; i++) {
800
                                logger.error("", failures[i]);
801
                        }
802
803
                        getDataSourceFactory().setWriterManager(writerManager);
804
                        getDataSourceFactory().initialize();
805 8765 jjdelcerro
                        // QueryManager.registerQuery(new ArcJoin());
806 4143 caballero
                }
807
        }
808 8765 jjdelcerro
809 732 fernando
        /**
810
         * sets drivers Directory
811 10666 caballero
         *
812 732 fernando
         * @param path
813
         */
814
        public static void setDriversPath(String path) {
815
                LayerFactory.driversPath = path;
816
                initializeDriverManager();
817
        }
818 8765 jjdelcerro
819 1773 fernando
        /**
820 4143 caballero
         * sets writers Directory
821 10666 caballero
         *
822 4143 caballero
         * @param path
823
         */
824
        public static void setWritersPath(String path) {
825
                LayerFactory.writersPath = path;
826
                initializeWriterManager();
827
        }
828
829
        /**
830 1773 fernando
         * @return Returns the dataSourceFactory.
831
         */
832
        public static DataSourceFactory getDataSourceFactory() {
833 8765 jjdelcerro
                if (dataSourceFactory == null) {
834 1828 fernando
                        dataSourceFactory = new DataSourceFactory();
835
                }
836 1773 fernando
                return dataSourceFactory;
837
        }
838 12431 jmvivo
839
840
        /**
841
         * Set a class to use instead of the originalLayerClassName.
842
         *
843
         * @param originalLayerClassName name of class to relpace
844
         * @param layerClassToUse Class than implements FLayer interface to use
845
         *
846
         * @see  getLayerClassForLayerClassName(String,Class)
847
         * @see  unregisterLayerClassForName(String)
848
        */
849
        public static void registerLayerClassForName (String originalLayerClassName, Class layerClassToUse){
850
                boolean isFLayer = false;
851
                Class[] interfaces = layerClassToUse.getInterfaces();
852
                for (int i = 0;i < interfaces.length; i++){
853
                        if (interfaces[i] == FLayer.class){
854
                                isFLayer = true;
855
                                break;
856
                        }
857
                }
858
                if (!isFLayer){
859
                        throw new ClassCastException("The class "+ layerClassToUse.getName() + "must implements FLayer");
860
                }
861
862
                layerClassMapping.put(originalLayerClassName,layerClassToUse);
863
        }
864
865
        /**
866
         * Unregister the originalLayerClassName class replacement.
867
         *
868
         * @param originalLayerClassName name of class to relpace
869
         * @param layerClassToUse Class than implements FLayer interface to use
870
         * @return true if the class had been registered
871
         *
872
         * @see  getLayerClassForLayerClassName(String,Class)
873
         * @see  unregisterLayerClassForName(String)
874
        */
875
        public static boolean unregisterLayerClassForName (String originalLayerClassName){
876
                return layerClassMapping.remove(originalLayerClassName) != null;
877
        }
878
879
        /**
880
         * Gets the class to use for the layerClassName.
881
         * If isn't registered an alternative class for this layerClass
882
         * the this returns 'Class.forName(layerClassName)'
883
         *
884
         * @param layerClassName
885
         * @return Class implements FLayer to use
886
         * @throws ClassNotFoundException
887
         *
888
         * @see  registerLayerClassForName(String,Class)
889
         * @see  unregisterLayerClassForName(String)
890
         */
891
        public static Class getLayerClassForLayerClassName(String layerClassName) throws ClassNotFoundException{
892
                Class layerClass = (Class)layerClassMapping.get(layerClassName);
893
                if (layerClass == null){
894
                        layerClass = Class.forName(layerClassName);
895
                }
896
                return layerClass;
897
        }
898 214 fernando
}