Statistics
| Revision:

root / branches / Fmap_GisPlanet / libraries / libFMap / src / com / iver / cit / gvsig / fmap / layers / LayerFactory.java @ 1993

History | View | Annotate | Download (17.2 KB)

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

    
43
import com.hardcode.driverManager.Driver;
44
import com.hardcode.driverManager.DriverLoadException;
45
import com.hardcode.driverManager.DriverManager;
46

    
47
import com.hardcode.gdbms.engine.customQuery.QueryManager;
48
import com.hardcode.gdbms.engine.data.DataSource;
49
import com.hardcode.gdbms.engine.data.DataSourceFactory;
50
import com.hardcode.gdbms.engine.data.NoSuchTableException;
51
import com.hardcode.gdbms.engine.data.edition.DataWare;
52
import com.hardcode.gdbms.engine.instruction.FieldNotFoundException;
53
import com.hardcode.gdbms.engine.instruction.TableNotFoundException;
54
import com.hardcode.gdbms.engine.values.Value;
55
import com.hardcode.gdbms.engine.values.ValueFactory;
56

    
57
import com.iver.cit.gvsig.fmap.DriverException;
58
import com.iver.cit.gvsig.fmap.ProgressListener;
59
import com.iver.cit.gvsig.fmap.core.IGeometry;
60
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
61
import com.iver.cit.gvsig.fmap.drivers.RasterDriver;
62
import com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver;
63
import com.iver.cit.gvsig.fmap.drivers.VectorialDriver;
64
import com.iver.cit.gvsig.fmap.drivers.VectorialFileDriver;
65
import com.iver.cit.gvsig.fmap.drivers.VectorialJDBCDriver;
66
import com.iver.cit.gvsig.fmap.drivers.WithDefaultLegend;
67
import com.iver.cit.gvsig.fmap.drivers.arcsde.ArcSdeDriver;
68
import com.iver.cit.gvsig.fmap.drivers.wfs.WFSDriver;
69
import com.iver.cit.gvsig.fmap.layers.layerOperations.AlphanumericData;
70
import com.iver.cit.gvsig.fmap.operations.arcview.ArcJoin;
71
import com.iver.cit.gvsig.fmap.rendering.LegendFactory;
72
import com.iver.cit.gvsig.fmap.rendering.VectorialLegend;
73
import com.iver.utiles.StringUtilities;
74

    
75
import org.apache.log4j.Logger;
76

    
77
import org.cresques.cts.IProjection;
78
//import org.hsqldb.lib.StringUtil;
79

    
80
import java.awt.geom.Rectangle2D;
81

    
82
import java.io.File;
83
import java.io.IOException;
84

    
85
import java.net.URL;
86

    
87
import java.sql.ResultSet;
88
import java.sql.SQLException;
89
import java.sql.Statement;
90
import java.sql.Types;
91
import java.util.Enumeration;
92
import java.util.TreeMap;
93

    
94

    
95
/**
96
 * Crea un adaptador del driver que se le pasa como par?metro en los m?todos
97
 * createLayer. Si hay memoria suficiente se crea un FLyrMemory que pasa todas
98
 * las features del driver a memoria
99
 */
100
public class LayerFactory {
101
        private static Logger logger = Logger.getLogger(LayerFactory.class.getName());
102
        private static String driversPath = "../FMap 03/drivers";
103
        private static DriverManager driverManager;
104

    
105
        private static DataSourceFactory dataSourceFactory;
106
        
107
        /**
108
         * Map en el que se guarda para cada fuente de datos a?adida al sistema, el
109
         * adaptador que la maneja. Ha de ser un TreeMap ya que esta clase define
110
         * la igualdad entre las claves a traves del m?todo equals de las mismas.
111
         * Los objetos FileSource, DBSource y WFSSource tienen definido el m?todo
112
         * equals de forma que devuelven true cuando dos objetos apuntan a la
113
         * misma fuente de datos
114
         */
115
        private static TreeMap sourceAdapter;
116

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

    
138
                try {
139
                        Driver d = dm.getDriver(driverName);
140

    
141
                        if (d instanceof VectorialFileDriver) {
142
                                return createLayer(layerName, (VectorialFileDriver) d, f, proj);
143
                        } else if (d instanceof RasterDriver) {
144
                                return createLayer(layerName, (RasterDriver) d, f, proj);
145
                        }
146
                } catch (DriverLoadException e) {
147
                        throw new DriverException(e);
148
                }
149

    
150
                return null;
151
        }
152

    
153
        /**
154
         * Crea un RandomVectorialFile con el driver que se le pasa como par?metro
155
         * y guard?ndose el nombre del fichero para realizar los accesos, la capa
156
         * tendr? asociada la proyecci?n que se pasa como parametro tambi?n
157
         *
158
         * @param layerName Nombre del Layer.
159
         * @param d VectorialAdapter.
160
         * @param f Fichero.
161
         * @param proj Proyecci?n.
162
         *
163
         * @return FLayer creado.
164
         *
165
         * @throws DriverException
166
         */
167
        public static FLayer createLayer(String layerName, VectorialFileDriver d,
168
                File f, IProjection proj) throws DriverException {
169
                //TODO Comprobar si hay un adaptador ya
170
                VectorialFileAdapter adapter = new VectorialFileAdapter(f);
171
                adapter.setDriver((VectorialDriver) d);
172

    
173
                FLyrVect capa = new FLyrVect();
174
                capa.setName(layerName);
175

    
176
                //TODO Meter esto dentro de la comprobaci?n de si hay memoria
177
                if (false) {
178
                } else {
179
                        capa.setSource(adapter);
180
                        capa.setProjection(proj);
181
                }
182

    
183
                try {
184
                        
185
                        // Le asignamos tambi?n una legenda por defecto acorde con
186
                        // el tipo de shape que tenga. Tampoco s? si es aqu? el
187
                        // sitio adecuado, pero en fin....
188
                        if (d instanceof WithDefaultLegend) {
189
                                WithDefaultLegend aux = (WithDefaultLegend) d;
190
                                adapter.start();
191
                                capa.setLegend((VectorialLegend) aux.getDefaultLegend());
192
                                adapter.stop();
193
                        } else {
194
                                capa.setLegend(LegendFactory.createSingleSymbolLegend(
195
                                                capa.getShapeType()));
196
                        }
197
                } catch (FieldNotFoundException e) {
198
                        //Esta no puede saltar
199
                } catch (DriverIOException e) {
200
                        throw new DriverException(e);
201
                }
202

    
203
                return capa;
204
        }
205

    
206
        /**
207
         * Crea una capa WMS con el driver que se le pasa como par?metro y
208
         * guard?ndose el nombre del fichero para realizar los accesos, la capa
209
         * tendr? asociada la proyecci?n que se pasa como parametro tambi?n
210
         *
211
         * @param layerName Nombre de la capa.
212
         * @param rect extent
213
         * @param host URL.
214
         * @param format Formato
215
         * @param query Consulta.
216
         * @param infoQuery inforamci?n de la consulta.
217
         * @param srs SRS.
218
         *
219
         * @return Capa creada.
220
         */
221
        public static FLayer createLayer(String layerName, Rectangle2D rect,
222
                URL host, String format, String query, String infoQuery, String srs) {
223
                FLyrWMS layer = new FLyrWMS();
224
                layer.setHost(host);
225
                layer.setFullExtent(rect);
226
                layer.setFormat(format);
227
                layer.setLayerQuery(query);
228
                layer.setInfoLayerQuery(infoQuery);
229
                layer.setSRS(srs);
230
                layer.setName(layerName);
231

    
232
                return layer;
233
        }
234

    
235
        /**
236
         * Crea una capa Raster a partir del nombre driver, fichero y proyecci?n.
237
         *
238
         * @param layerName Nombre de la capa.
239
         * @param d RasterDriver.
240
         * @param f Fichero.
241
         * @param proj Proyecci?n.
242
         *
243
         * @return Nueva capa de tipo raster.
244
         *
245
         * @throws DriverIOException
246
         */
247
        public static FLyrRaster createLayer(String layerName, RasterDriver d,
248
                File f, IProjection proj) throws DriverException {
249
                RasterAdapter adapter = new RasterFileAdapter(f);
250
                adapter.setDriver(d);
251

    
252
                FLyrRaster capa = new FLyrRaster();
253
                capa.setName(layerName);
254

    
255
                //TODO Meter esto dentro de la comprobaci?n de si hay memoria
256
                if (false) {
257
                } else {
258
                        capa.setSource(adapter);
259
                        capa.setProjection(proj);
260
                        try {
261
                                capa.load();
262
                        } catch (DriverIOException e) {
263
                                throw new DriverException(e);
264
                        }
265
                }
266

    
267
                return capa;
268
        }
269

    
270
        /**
271
         * Crea un RandomVectorialWFS con el driver que se le pasa como par?metro y
272
         * guard?ndose la URL del servidor que se pasa como par?metro
273
         *
274
         * @param driver Driver WFS.
275
         * @param host URL.
276
         * @param proj Proyecci?n.
277
         *
278
         * @return Capa creada.
279
         *
280
         * @throws UnsupportedOperationException
281
         */
282
        public static FLayer createWFSLayer(String layerName,WFSDriver driver, URL host,
283
                IProjection proj) {
284
                //throw new UnsupportedOperationException();
285
                FLyrVect layer=new FLyrVect();
286
                //layer.setName(name);
287
                VectorialAdapter adapter=new WFSAdapter();
288
                adapter.setDriver(driver);
289
                //WithDefaultLegend aux=(WithDefaultLegend)driver;
290
                
291
                layer.setName(layerName);
292
                layer.setSource(adapter);
293
                layer.setProjection(proj);
294
                try {
295
                        layer.setLegend(LegendFactory.createSingleSymbolLegend(
296
                                        layer.getShapeType()));
297
                } catch (FieldNotFoundException e) {
298
                        e.printStackTrace();
299
                } catch (DriverException e) {
300
                        e.printStackTrace();
301
                }
302
                //layer.setHost(host);
303
                return layer;
304
        }
305
    public static FLayer createArcSDELayer(String layerName,ArcSdeDriver driver, IProjection proj) {
306
            //throw new UnsupportedOperationException();
307
            FLyrVect layer=new FLyrVect();
308
            VectorialAdapter adapter=new VectorialDBAdapter();
309
            adapter.setDriver(driver);
310
            
311
            layer.setName(layerName);
312
            layer.setSource(adapter);
313
            layer.setProjection(proj);
314
            try {
315
                if (driver instanceof WithDefaultLegend) {
316
                    WithDefaultLegend aux = (WithDefaultLegend) driver;
317
                    adapter.start();
318
                    layer.setLegend((VectorialLegend) aux.getDefaultLegend());
319
                    adapter.stop();
320
                } else { 
321
                    layer.setLegend(LegendFactory.createSingleSymbolLegend(
322
                            layer.getShapeType()));
323
                }
324
            } catch (FieldNotFoundException e) {
325
                throw new UnsupportedOperationException(e.getMessage());
326
            } catch (DriverIOException e) {
327
                throw new UnsupportedOperationException(e.getMessage());
328
            } catch (DriverException e) {
329
                // TODO Auto-generated catch block
330
                e.printStackTrace();
331
            }
332
            
333
            try {
334
                layer.setLegend(LegendFactory.createSingleSymbolLegend(
335
                        layer.getShapeType()));
336
            } catch (FieldNotFoundException e) {
337
                e.printStackTrace();
338
            } catch (DriverException e) {
339
                e.printStackTrace();
340
            }
341
            return layer;
342
        }
343

    
344
        /**
345
         * Crea un RandomVectorialWFS con el driver que se le pasa como par?metro y
346
         * guard?ndose la URL del servidor que se pasa como par?metro
347
         *
348
         * @param driver
349
         * @param host
350
         * @param port
351
         * @param user
352
         * @param password
353
         * @param dbName
354
         * @param tableName
355
         * @param proj
356
         *
357
         * @return Capa creada.
358
         *
359
         * @throws UnsupportedOperationException
360
         */
361
        public static FLayer createLayer(VectorialDatabaseDriver driver,
362
                String host, int port, String user, String password, String dbName,
363
                String tableName, IProjection proj) {
364
                throw new UnsupportedOperationException();
365
        }
366
        public static FLayer createDBLayer(VectorialDatabaseDriver driver,String layerName, IProjection proj)
367
        {
368
            
369
                
370
                FLyrVect capa = new FLyrVect();
371
                
372
                capa.setName(layerName);
373
                VectorialDBAdapter dbAdapter = new VectorialDBAdapter();
374
                dbAdapter.setDriver(driver);                        
375
        
376
                capa.setSource(dbAdapter);
377
                capa.setProjection(proj);
378
                try {
379
                        if (driver instanceof WithDefaultLegend) {
380
                                WithDefaultLegend aux = (WithDefaultLegend) driver;
381
                                dbAdapter.start();
382
                    capa.setLegend((VectorialLegend) aux.getDefaultLegend());
383
                                dbAdapter.stop();
384
                        } else { 
385
                                capa.setLegend(LegendFactory.createSingleSymbolLegend(
386
                                                capa.getShapeType()));
387
                        }
388
        } catch (FieldNotFoundException e) {
389
            throw new UnsupportedOperationException(e.getMessage());
390
        } catch (DriverException e) {
391
            throw new UnsupportedOperationException(e.getMessage());
392
        }
393

    
394
                return capa;
395

    
396

    
397
                    
398
                }
399

    
400
        /**
401
         * @param driver
402
         * @param layerName
403
         * @param object
404
         * @return
405
         * @throws SQLException
406
         * @throws DriverIOException
407
         * @throws IOException
408
         * @throws DriverLoadException
409
         * @throws com.hardcode.gdbms.engine.data.driver.DriverException
410
         * @throws NoSuchTableException
411
         * @throws ClassNotFoundException
412
         * @throws 
413
         */
414
        public static FLayer createDisconnectedDBLayer(VectorialDatabaseDriver driver, String layerName, IProjection proj, ProgressListener listener) throws SQLException, IOException, DriverIOException, DriverLoadException, NoSuchTableException, com.hardcode.gdbms.engine.data.driver.DriverException, ClassNotFoundException {
415
            VectorialDisconnectedDBAdapter dbAdapter = new VectorialDisconnectedDBAdapter();
416
            dbAdapter.setDriver(driver);
417
            DataSource ds = dbAdapter.getRecordset();
418
            ds.start();
419
            String database = dataSourceFactory.getTempFile();
420
            String[] fieldNames = new String[ds.getFieldCount() + 1];
421
            System.arraycopy(ds.getFieldNames(), 0, fieldNames, 1, ds.getFieldCount());
422
            fieldNames[0] = "the_geom";
423
            int[] types = new int[fieldNames.length];
424
            types[0] = Types.BINARY;
425
            for (int i = 1; i < types.length; i++) {
426
            types[i] = ds.getFieldType(i-1);
427
        }
428
            String dsName = dataSourceFactory.createTable(database, ds.getPKNames(), fieldNames, types);
429
            
430
            dataSourceFactory.addDBDataSourceByTable(dsName, null, 0, "sa", "", database, dsName, "GDBMS HSQLDB driver", null);
431
            DataSource local = dataSourceFactory.createRandomDataSource(dsName, DataSourceFactory.MANUAL_MODE);
432
            local.start();
433
            DataWare dw = local.getDataWare();
434
            dw.beginTrans();
435
            
436
            if (listener == null){
437
                listener = new ProgressListener() {
438
                /**
439
                 * @see com.iver.cit.gvsig.fmap.ProgressListener#progress(int)
440
                 */
441
                public void progress(int n) {
442
                    //do nothing
443
                }
444
            };
445
            }
446
            
447
            for (int i = 0; i < dbAdapter.getShapeCount(); i++) {
448
                Value[] row = new Value[ds.getFieldCount() + 1];
449
                
450
                byte[] bytes = dbAdapter.getShape(i).toWKB();
451
                row[0] = ValueFactory.createValue(bytes);
452
                                
453
                for (int j = 0; j < ds.getFieldCount(); j++) {
454
                    row[j+1] = ds.getFieldValue(i, j);                
455
            }
456

    
457
                dw.insertFilledRow(row);
458
                listener.progress(100 * i / dbAdapter.getShapeCount());
459
        }
460
            
461
            dw.commitTrans();
462
            local.stop();
463
            ds.stop();
464
            VectorialJDBCDriver cacheDriver = (VectorialJDBCDriver) LayerFactory.getDM().getDriver("HSQLDB Driver");
465
        Class.forName("org.hsqldb.jdbcDriver");
466

    
467
            cacheDriver.setData(java.sql.DriverManager.getConnection("jdbc:hsqldb:file:" + database, "sa", ""), dsName, StringUtilities.getComaSeparated(local.getFieldNames()), "", local.getPrimaryKeys()[0]+1);
468
        return createDBLayer(cacheDriver, layerName, proj);
469
        }
470
        
471
        
472
        /**
473
         * Obtiene el adaptador de un driver si ya se ha a?adido el origen de datos
474
         * o null si es un origen de datos nuevo
475
         *
476
         * @param source Adaptador.
477
         */
478
        private static void getAdapter(Source source) {
479
        }
480

    
481
        /**
482
         * Registra la asociaci?n entre la fuente de datos que se pasa como
483
         * par?metro y el VectorialAdapter que se pasa como par?metro, para
484
         * satisfacer futuras llamadas a getAdapter
485
         *
486
         * @param s Adaptador
487
         * @param a VectorialAdapter.
488
         */
489
        private static void saveSourceAdapter(Source s, VectorialAdapter a) {
490
        }
491

    
492
        /**
493
         * Crea una FLyrComplexRaster que ataca al driver que se pasa como
494
         * par?metro.
495
         *
496
         * @param driver
497
         * @param f
498
         * @param proj
499
         *
500
         * @throws IllegalArgumentException Si se pasa un driver que no implementa
501
         *                    GeorreferencedRasterDriver o NotGeorreferencedRasterDriver
502
         */
503
        public static void createLayer(RasterDriver driver, File f, IProjection proj)
504
                throws IllegalArgumentException {
505
        }
506

    
507
        /**
508
         * Devuelve el DriverManager.
509
         *
510
         * @return DriverManager.
511
         */
512
        public static DriverManager getDM() {
513
                initializeDriverManager();
514

    
515
                return driverManager;
516
        }
517

    
518
        /**
519
         * Inicializa el DriverManager.
520
         */
521
        private static void initializeDriverManager() {
522
                if (driverManager == null) {
523
                        driverManager = new DriverManager();
524
                        driverManager.loadDrivers(new File(LayerFactory.driversPath));
525

    
526
                        Throwable[] failures = driverManager.getLoadFailures();
527

    
528
                        for (int i = 0; i < failures.length; i++) {
529
                                logger.error("", failures[i]);
530
                        }
531

    
532
                        getDataSourceFactory().setDriverManager(driverManager);
533
                        getDataSourceFactory().initialize();
534
                        QueryManager.registerQuery(new ArcJoin());
535
                }
536
        }
537

    
538
        /**
539
         * sets drivers Directory
540
         *
541
         * @param path
542
         */
543
        public static void setDriversPath(String path) {
544
                LayerFactory.driversPath = path;
545
                initializeDriverManager();
546
        }
547
        
548
        
549
        /**
550
         * @return Returns the dataSourceFactory.
551
         */
552
        public static DataSourceFactory getDataSourceFactory() {
553
                if (dataSourceFactory == null){
554
                        dataSourceFactory = new DataSourceFactory();
555
                }
556
                return dataSourceFactory;
557
        }
558
}