Statistics
| Revision:

svn-gvsig-desktop / trunk / libraries / libFMap / src / com / iver / cit / gvsig / fmap / layers / LayerFactory.java @ 2277

History | View | Annotate | Download (17.1 KB)

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

    
43
import java.awt.geom.Rectangle2D;
44
import java.io.File;
45
import java.io.IOException;
46
import java.net.URL;
47
import java.sql.SQLException;
48
import java.sql.Types;
49
import java.util.TreeMap;
50

    
51
import org.apache.log4j.Logger;
52
import org.cresques.cts.IProjection;
53

    
54
import com.hardcode.driverManager.Driver;
55
import com.hardcode.driverManager.DriverLoadException;
56
import com.hardcode.driverManager.DriverManager;
57
import com.hardcode.gdbms.engine.customQuery.QueryManager;
58
import com.hardcode.gdbms.engine.data.DataSource;
59
import com.hardcode.gdbms.engine.data.DataSourceFactory;
60
import com.hardcode.gdbms.engine.data.NoSuchTableException;
61
import com.hardcode.gdbms.engine.data.edition.DataWare;
62
import com.hardcode.gdbms.engine.instruction.FieldNotFoundException;
63
import com.hardcode.gdbms.engine.values.Value;
64
import com.hardcode.gdbms.engine.values.ValueFactory;
65
import com.iver.cit.gvsig.fmap.DriverException;
66
import com.iver.cit.gvsig.fmap.ProgressListener;
67
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
68
import com.iver.cit.gvsig.fmap.drivers.RasterDriver;
69
import com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver;
70
import com.iver.cit.gvsig.fmap.drivers.VectorialDriver;
71
import com.iver.cit.gvsig.fmap.drivers.VectorialFileDriver;
72
import com.iver.cit.gvsig.fmap.drivers.VectorialJDBCDriver;
73
import com.iver.cit.gvsig.fmap.drivers.WithDefaultLegend;
74
import com.iver.cit.gvsig.fmap.operations.arcview.ArcJoin;
75
import com.iver.cit.gvsig.fmap.rendering.LegendFactory;
76
import com.iver.cit.gvsig.fmap.rendering.VectorialLegend;
77
import com.iver.utiles.StringUtilities;
78

    
79

    
80
/**
81
 * Crea un adaptador del driver que se le pasa como par?metro en los m?todos
82
 * createLayer. Si hay memoria suficiente se crea un FLyrMemory que pasa todas
83
 * las features del driver a memoria
84
 */
85
public class LayerFactory {
86
        private static Logger logger = Logger.getLogger(LayerFactory.class.getName());
87
        private static String driversPath = "../FMap 03/drivers";
88
        private static DriverManager driverManager;
89

    
90
        private static DataSourceFactory dataSourceFactory;
91
        
92
        /**
93
         * Map en el que se guarda para cada fuente de datos a?adida al sistema, el
94
         * adaptador que la maneja. Ha de ser un TreeMap ya que esta clase define
95
         * la igualdad entre las claves a traves del m?todo equals de las mismas.
96
         * Los objetos FileSource, DBSource y WFSSource tienen definido el m?todo
97
         * equals de forma que devuelven true cuando dos objetos apuntan a la
98
         * misma fuente de datos
99
         */
100
        private static TreeMap sourceAdapter;
101

    
102
        /*
103
         * Crea un RandomVectorialFile con el driver que se le pasa como par?metro
104
         * y guard?ndose el nombre del fichero para realizar los accesos, la capa
105
         * tendr? asociada la proyecci?n que se pasa como parametro tambi?n
106
         *
107
         * @param layerName Nombre de la capa.
108
         * @param driverName Nombre del driver.
109
         * @param f fichero.
110
         * @param proj Proyecci?n.
111
         *
112
         * @return FLayer.
113
         * @throws DriverException
114
         *
115
         * @throws DriverException
116
         * @throws DriverIOException
117
         */
118
        public static FLayer createLayer(String layerName, String driverName,
119
                File f, IProjection proj) throws DriverException  {
120
                //Se obtiene el driver que lee
121
                DriverManager dm = getDM();
122

    
123
                try {
124
                        Driver d = dm.getDriver(driverName);
125

    
126
                        if (d instanceof VectorialFileDriver) {
127
                                return createLayer(layerName, (VectorialFileDriver) d, f, proj);
128
                        } else if (d instanceof RasterDriver) {
129
                                return createLayer(layerName, (RasterDriver) d, f, proj);
130
                        }
131
                } catch (DriverLoadException e) {
132
                        throw new DriverException(e);
133
                }
134

    
135
                return null;
136
        }
137

    
138
        /**
139
         * Crea un RandomVectorialFile con el driver que se le pasa como par?metro
140
         * y guard?ndose el nombre del fichero para realizar los accesos, la capa
141
         * tendr? asociada la proyecci?n que se pasa como parametro tambi?n
142
         *
143
         * @param layerName Nombre del Layer.
144
         * @param d VectorialAdapter.
145
         * @param f Fichero.
146
         * @param proj Proyecci?n.
147
         *
148
         * @return FLayer creado.
149
         *
150
         * @throws DriverException
151
         */
152
        public static FLayer createLayer(String layerName, VectorialFileDriver d,
153
                File f, IProjection proj) throws DriverException {
154
                //TODO Comprobar si hay un adaptador ya
155
                VectorialFileAdapter adapter = new VectorialFileAdapter(f);
156
                adapter.setDriver((VectorialDriver) d);
157

    
158
                FLyrVect capa = new FLyrVect();
159
                capa.setName(layerName);
160

    
161
                //TODO Meter esto dentro de la comprobaci?n de si hay memoria
162
                if (false) {
163
                } else {
164
                        capa.setSource(adapter);
165
                        capa.setProjection(proj);
166
                }
167

    
168
                try {
169
                        
170
                        // Le asignamos tambi?n una legenda por defecto acorde con
171
                        // el tipo de shape que tenga. Tampoco s? si es aqu? el
172
                        // sitio adecuado, pero en fin....
173
                        if (d instanceof WithDefaultLegend) {
174
                                WithDefaultLegend aux = (WithDefaultLegend) d;
175
                                adapter.start();
176
                                capa.setLegend((VectorialLegend) aux.getDefaultLegend());
177
                                adapter.stop();
178
                        } else {
179
                                capa.setLegend(LegendFactory.createSingleSymbolLegend(
180
                                                capa.getShapeType()));
181
                        }
182
                } catch (FieldNotFoundException e) {
183
                        //Esta no puede saltar
184
                } catch (DriverIOException e) {
185
                        throw new DriverException(e);
186
                }
187

    
188
                return capa;
189
        }
190

    
191
        /**
192
         * Crea una capa WMS con el driver que se le pasa como par?metro y
193
         * guard?ndose el nombre del fichero para realizar los accesos, la capa
194
         * tendr? asociada la proyecci?n que se pasa como parametro tambi?n
195
         *
196
         * @param layerName Nombre de la capa.
197
         * @param rect extent
198
         * @param host URL.
199
         * @param format Formato
200
         * @param query Consulta.
201
         * @param infoQuery inforamci?n de la consulta.
202
         * @param srs SRS.
203
         *
204
         * @return Capa creada.
205
         */
206
        public static FLayer createLayer(String layerName, Rectangle2D rect,
207
                URL host, String format, String query, String infoQuery, String srs) {
208
                FLyrWMS layer = new FLyrWMS();
209
                layer.setHost(host);
210
                layer.setFullExtent(rect);
211
                layer.setFormat(format);
212
                layer.setLayerQuery(query);
213
                layer.setInfoLayerQuery(infoQuery);
214
                layer.setSRS(srs);
215
                layer.setName(layerName);
216

    
217
                return layer;
218
        }
219

    
220
        /**
221
         * Crea una capa Raster a partir del nombre driver, fichero y proyecci?n.
222
         *
223
         * @param layerName Nombre de la capa.
224
         * @param d RasterDriver.
225
         * @param f Fichero.
226
         * @param proj Proyecci?n.
227
         *
228
         * @return Nueva capa de tipo raster.
229
         *
230
         * @throws DriverIOException
231
         */
232
        public static FLyrRaster createLayer(String layerName, RasterDriver d,
233
                File f, IProjection proj) throws DriverException {
234
                RasterAdapter adapter = new RasterFileAdapter(f);
235
                adapter.setDriver(d);
236

    
237
                FLyrRaster capa = new FLyrRaster();
238
                capa.setName(layerName);
239

    
240
                //TODO Meter esto dentro de la comprobaci?n de si hay memoria
241
                if (false) {
242
                } else {
243
                        capa.setSource(adapter);
244
                        capa.setProjection(proj);
245
                        try {
246
                                capa.load();
247
                        } catch (DriverIOException e) {
248
                                throw new DriverException(e);
249
                        }
250
                }
251

    
252
                return capa;
253
        }
254

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

    
329
        /**
330
         * Crea un RandomVectorialWFS con el driver que se le pasa como par?metro y
331
         * guard?ndose la URL del servidor que se pasa como par?metro
332
         *
333
         * @param driver
334
         * @param host
335
         * @param port
336
         * @param user
337
         * @param password
338
         * @param dbName
339
         * @param tableName
340
         * @param proj
341
         *
342
         * @return Capa creada.
343
         *
344
         * @throws UnsupportedOperationException
345
         */
346
        public static FLayer createLayer(VectorialDatabaseDriver driver,
347
                String host, int port, String user, String password, String dbName,
348
                String tableName, IProjection proj) {
349
                throw new UnsupportedOperationException();
350
        }
351
        public static FLayer createDBLayer(VectorialDatabaseDriver driver,String layerName, IProjection proj)
352
        {
353
            
354
                
355
                FLyrVect capa = new FLyrVect();
356
                
357
                capa.setName(layerName);
358
                VectorialDBAdapter dbAdapter = new VectorialDBAdapter();
359
                dbAdapter.setDriver(driver);                        
360
        
361
                capa.setSource(dbAdapter);
362
                capa.setProjection(proj);
363
                try {
364
                        if (driver instanceof WithDefaultLegend) {
365
                                WithDefaultLegend aux = (WithDefaultLegend) driver;
366
                                dbAdapter.start();
367
                    capa.setLegend((VectorialLegend) aux.getDefaultLegend());
368
                                dbAdapter.stop();
369
                        } else { 
370
                                capa.setLegend(LegendFactory.createSingleSymbolLegend(
371
                                                capa.getShapeType()));
372
                        }
373
        } catch (FieldNotFoundException e) {
374
            throw new UnsupportedOperationException(e.getMessage());
375
        } catch (DriverException e) {
376
            throw new UnsupportedOperationException(e.getMessage());
377
        }
378

    
379
                return capa;
380

    
381

    
382
                    
383
                }
384

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

    
444
                dw.insertFilledRow(row);
445
                listener.progress(100 * i / dbAdapter.getShapeCount());
446
        }
447
            
448
            long t2 = System.currentTimeMillis();
449
            dw.commitTrans();
450
            long t3 = System.currentTimeMillis();
451
            System.out.println((t2 - t1) + " - " + (t3 - t2));
452
            dw.stop();
453
            local.stop();
454
            ds.stop();
455
            VectorialJDBCDriver cacheDriver = (VectorialJDBCDriver) LayerFactory.getDM().getDriver("HSQLDB Driver");
456
        Class.forName("org.hsqldb.jdbcDriver");
457

    
458
            cacheDriver.setData(java.sql.DriverManager.getConnection("jdbc:hsqldb:file:" + database, "sa", ""), dsName, StringUtilities.getComaSeparated(local.getFieldNames()), "", local.getPrimaryKeys()[0]+1);
459
            cacheDriver.setWorkingArea(driver.getWorkingArea());
460
        return createDBLayer(cacheDriver, layerName, proj);
461
        }
462
        
463
        
464
        /**
465
         * Obtiene el adaptador de un driver si ya se ha a?adido el origen de datos
466
         * o null si es un origen de datos nuevo
467
         *
468
         * @param source Adaptador.
469
         */
470
        private static void getAdapter(Source source) {
471
        }
472

    
473
        /**
474
         * Registra la asociaci?n entre la fuente de datos que se pasa como
475
         * par?metro y el VectorialAdapter que se pasa como par?metro, para
476
         * satisfacer futuras llamadas a getAdapter
477
         *
478
         * @param s Adaptador
479
         * @param a VectorialAdapter.
480
         */
481
        private static void saveSourceAdapter(Source s, VectorialAdapter a) {
482
        }
483

    
484
        /**
485
         * Crea una FLyrComplexRaster que ataca al driver que se pasa como
486
         * par?metro.
487
         *
488
         * @param driver
489
         * @param f
490
         * @param proj
491
         *
492
         * @throws IllegalArgumentException Si se pasa un driver que no implementa
493
         *                    GeorreferencedRasterDriver o NotGeorreferencedRasterDriver
494
         */
495
        public static void createLayer(RasterDriver driver, File f, IProjection proj)
496
                throws IllegalArgumentException {
497
        }
498

    
499
        /**
500
         * Devuelve el DriverManager.
501
         *
502
         * @return DriverManager.
503
         */
504
        public static DriverManager getDM() {
505
                initializeDriverManager();
506

    
507
                return driverManager;
508
        }
509

    
510
        /**
511
         * Inicializa el DriverManager.
512
         */
513
        private static void initializeDriverManager() {
514
                if (driverManager == null) {
515
                        driverManager = new DriverManager();
516
                        driverManager.loadDrivers(new File(LayerFactory.driversPath));
517

    
518
                        Throwable[] failures = driverManager.getLoadFailures();
519

    
520
                        for (int i = 0; i < failures.length; i++) {
521
                                logger.error("", failures[i]);
522
                        }
523

    
524
                        getDataSourceFactory().setDriverManager(driverManager);
525
                        getDataSourceFactory().initialize();
526
                        QueryManager.registerQuery(new ArcJoin());
527
                }
528
        }
529

    
530
        /**
531
         * sets drivers Directory
532
         *
533
         * @param path
534
         */
535
        public static void setDriversPath(String path) {
536
                LayerFactory.driversPath = path;
537
                initializeDriverManager();
538
        }
539
        
540
        
541
        /**
542
         * @return Returns the dataSourceFactory.
543
         */
544
        public static DataSourceFactory getDataSourceFactory() {
545
                if (dataSourceFactory == null){
546
                        dataSourceFactory = new DataSourceFactory();
547
                }
548
                return dataSourceFactory;
549
        }
550
}