Statistics
| Revision:

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

History | View | Annotate | Download (18.4 KB)

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

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

    
50
import javax.swing.JOptionPane;
51

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

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

    
81

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

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

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

    
125
                try {
126
                        Driver d = dm.getDriver(driverName);
127

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

    
137
                return null;
138
        }
139

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

    
160
                FLyrVect capa = new FLyrVect();
161
                capa.setName(layerName);
162
                try{
163
                //TODO Meter esto dentro de la comprobaci?n de si hay memoria
164
                if (false) {
165
                } else {
166
                        capa.setSource(adapter);
167
                        capa.setProjection(proj);
168
                }
169
                //try {
170
                        
171
                        // Le asignamos tambi?n una legenda por defecto acorde con
172
                        // el tipo de shape que tenga. Tampoco s? si es aqu? el
173
                        // sitio adecuado, pero en fin....
174
                        if (d instanceof WithDefaultLegend) {
175
                                WithDefaultLegend aux = (WithDefaultLegend) d;
176
                                adapter.start();
177
                                capa.setLegend((VectorialLegend) aux.getDefaultLegend());
178
                                adapter.stop();
179
                        } else {
180
                                capa.setLegend(LegendFactory.createSingleSymbolLegend(
181
                                                capa.getShapeType()));
182
                        }
183
                /*} catch (FieldNotFoundException e) {
184
                        //Esta no puede saltar
185
                } catch (DriverIOException e) {
186
                        throw new DriverException(e);
187
                }*/
188
                }catch (Exception e) {
189
                /*        JOptionPane.showMessageDialog(null,"Se ha producido un error cargando la capa '" 
190
                                        +layerName+"'\n El recurso asociado a la capa es : "
191
                                        +f.getAbsolutePath()+"\n Esta capa ser? eliminada del proyecto.");
192
                        */
193
                        //capa.setBroken(true);        
194
                        //return capa;
195
                        throw new DriverException(e);
196
                }
197

    
198
                return capa;
199
        }
200

    
201
    public static FLayer createLayer(String layerName, VectorialDriver d,
202
            IProjection proj) throws DriverException {
203
            //TODO Comprobar si hay un adaptador ya
204
            VectorialDefaultAdapter adapter = new VectorialDefaultAdapter();
205
            adapter.setDriver((VectorialDriver) d);
206

    
207
            FLyrVect capa = new FLyrVect();
208
            capa.setName(layerName);
209

    
210
            capa.setSource(adapter);
211
            capa.setProjection(proj);
212

    
213
            try {
214
                
215
                // Le asignamos tambi?n una legenda por defecto acorde con
216
                // el tipo de shape que tenga. Tampoco s? si es aqu? el
217
                // sitio adecuado, pero en fin....
218
                if (d instanceof WithDefaultLegend) {
219
                    WithDefaultLegend aux = (WithDefaultLegend) d;
220
                    adapter.start();
221
                    capa.setLegend((VectorialLegend) aux.getDefaultLegend());
222
                    adapter.stop();
223
                } else {
224
                    capa.setLegend(LegendFactory.createSingleSymbolLegend(
225
                            capa.getShapeType()));
226
                }
227
            } catch (FieldNotFoundException e) {
228
                //Esta no puede saltar
229
            } catch (DriverIOException e) {
230
                throw new DriverException(e);
231
            }
232

    
233
            return capa;
234
        }
235

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

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

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

    
268
                return capa;
269
        }
270

    
271
        /**
272
         * Crea una capa Raster a partir del nombre driver, fichero y proyecci?n y 
273
         * coordenadas de georeferenciaci?n. Esta funci?n es para georeferenciar 
274
         * capas raster. Para imagenes que no tienen georeferenciaci?n hay que asignarle
275
         * una temporal, normalmente a partir de la vista activa.
276
         *
277
         * @param layerName Nombre de la capa.
278
         * @param d RasterDriver.
279
         * @param f Fichero.
280
         * @param proj Proyecci?n.
281
         * @param extent Extent de la vista activa
282
         *
283
         * @return Nueva capa de tipo raster.
284
         *
285
         * @throws DriverIOException
286
         */
287
        public static FLyrRaster createLayer(String layerName, RasterDriver d,
288
                File f, IProjection proj, ViewPort vp) throws DriverException {
289
                RasterAdapter adapter = new RasterFileAdapter(f);
290
                adapter.setDriver(d);
291
                
292
                FLyrRaster capa = new FLyrRaster();
293
                capa.setName(layerName);
294
                
295
                //TODO Meter esto dentro de la comprobaci?n de si hay memoria
296
                if (false) {
297
                } else {
298
                        capa.setSource(adapter);
299
                        capa.setProjection(proj);
300
                        //capa.setTempExtent(vp);
301
                        try {
302
                                capa.load();
303
                        } catch (DriverIOException e) {
304
                                throw new DriverException(e);
305
                        }
306
                }
307

    
308
                return capa;
309
        }
310
        
311
        
312
    public static FLayer createArcSDELayer(String layerName,VectorialDatabaseDriver driver, IProjection proj) {
313
            //throw new UnsupportedOperationException();
314
            FLyrVect layer=new FLyrVect();
315
            VectorialAdapter adapter=new VectorialDBAdapter();
316
            adapter.setDriver(driver);
317
            
318
            layer.setName(layerName);
319
            layer.setSource(adapter);
320
            layer.setProjection(proj);
321
            try {
322
                if (driver instanceof WithDefaultLegend) {
323
                    WithDefaultLegend aux = (WithDefaultLegend) driver;
324
                    adapter.start();
325
                    layer.setLegend((VectorialLegend) aux.getDefaultLegend());
326
                    adapter.stop();
327
                } else { 
328
                    layer.setLegend(LegendFactory.createSingleSymbolLegend(
329
                            layer.getShapeType()));
330
                }
331
            } catch (FieldNotFoundException e) {
332
                throw new UnsupportedOperationException(e.getMessage());
333
            } catch (DriverIOException e) {
334
                throw new UnsupportedOperationException(e.getMessage());
335
            } catch (DriverException e) {
336
                // TODO Auto-generated catch block
337
                e.printStackTrace();
338
            }
339
            
340
            try {
341
                layer.setLegend(LegendFactory.createSingleSymbolLegend(
342
                        layer.getShapeType()));
343
            } catch (FieldNotFoundException e) {
344
                e.printStackTrace();
345
            } catch (DriverException e) {
346
                e.printStackTrace();
347
            }
348
            return layer;
349
        }
350

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

    
401
                return capa;
402

    
403

    
404
                    
405
                }
406

    
407
        /**
408
         * @param driver
409
         * @param layerName
410
         * @param object
411
         * @return
412
         * @throws SQLException
413
         * @throws DriverIOException
414
         * @throws IOException
415
         * @throws DriverLoadException
416
         * @throws com.hardcode.gdbms.engine.data.driver.DriverException
417
         * @throws NoSuchTableException
418
         * @throws ClassNotFoundException
419
         * @throws 
420
         */
421
        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 {
422
            VectorialDisconnectedDBAdapter dbAdapter = new VectorialDisconnectedDBAdapter();
423
            dbAdapter.setDriver(driver);
424
            DataSource ds = dbAdapter.getRecordset();
425
            ds.start();
426
            String database = dataSourceFactory.getTempFile();
427
            String[] fieldNames = new String[ds.getFieldCount() + 1];
428
            System.arraycopy(ds.getFieldNames(), 0, fieldNames, 1, ds.getFieldCount());
429
            fieldNames[0] = "the_geom";
430
            int[] types = new int[fieldNames.length];
431
            types[0] = Types.BINARY;
432
            for (int i = 1; i < types.length; i++) {
433
            types[i] = ds.getFieldType(i-1);
434
        }
435
            String dsName = dataSourceFactory.createTable(database, ds.getPKNames(), fieldNames, types);
436
            
437
        DBLayerDefinition lyrDef = new DBLayerDefinition();
438
        lyrDef.setTableName(dsName);
439
        lyrDef.setLayerName(layerName);
440
        lyrDef.setFieldNames(ds.getFieldNames());
441
        lyrDef.setFieldGeometry("the_geom");
442
        lyrDef.setFieldID(ds.getPKNames()[0]);
443
        lyrDef.setClassToInstantiate("org.hsqldb.jdbcDriver");
444
        
445
            dataSourceFactory.addDBDataSourceByTable(dsName, null, 0, "sa", "", database, dsName, "GDBMS HSQLDB Transactional driver");
446
            DataSource local = dataSourceFactory.createRandomDataSource(dsName, DataSourceFactory.MANUAL_OPENING);
447
            local.start();
448
            DataWare dw = local.getDataWare(DataSourceFactory.DATA_WARE_COHERENT_ROW_ORDER);
449
            dw.start();
450
            long t1 = System.currentTimeMillis();
451
            dw.beginTrans();
452
            
453
            if (listener == null){
454
                listener = new ProgressListener() {
455
                /**
456
                 * @see com.iver.cit.gvsig.fmap.ProgressListener#progress(int)
457
                 */
458
                public void progress(int n) {
459
                    //do nothing
460
                }
461
            };
462
            }
463
            
464
            for (int i = 0; i < dbAdapter.getShapeCount(); i++) {
465
                Value[] row = new Value[ds.getFieldCount() + 1];
466
                
467
                byte[] bytes = dbAdapter.getShape(i).toWKB();
468
                row[0] = ValueFactory.createValue(bytes);
469
                                
470
                for (int j = 0; j < ds.getFieldCount(); j++) {
471
                    row[j+1] = ds.getFieldValue(i, j);                
472
            }
473

    
474
                dw.insertFilledRow(row);
475
                listener.progress(100 * i / dbAdapter.getShapeCount());
476
        }
477
            
478
            long t2 = System.currentTimeMillis();
479
            dw.commitTrans();
480
            long t3 = System.currentTimeMillis();
481
            System.out.println((t2 - t1) + " - " + (t3 - t2));
482
            dw.stop();
483
            local.stop();
484
            ds.stop();
485
            VectorialJDBCDriver cacheDriver = (VectorialJDBCDriver) LayerFactory.getDM().getDriver("HSQLDB Driver");
486
        Class.forName("org.hsqldb.jdbcDriver");
487

    
488
            cacheDriver.setData(java.sql.DriverManager.getConnection("jdbc:hsqldb:file:" + database, "sa", ""), lyrDef);
489
            cacheDriver.setWorkingArea(driver.getWorkingArea());
490
        return createDBLayer(cacheDriver, layerName, proj);
491
        }
492
        
493
        
494
        /**
495
         * Obtiene el adaptador de un driver si ya se ha a?adido el origen de datos
496
         * o null si es un origen de datos nuevo
497
         *
498
         * @param source Adaptador.
499
         */
500
        private static void getAdapter(Source source) {
501
        }
502

    
503
        /**
504
         * Registra la asociaci?n entre la fuente de datos que se pasa como
505
         * par?metro y el VectorialAdapter que se pasa como par?metro, para
506
         * satisfacer futuras llamadas a getAdapter
507
         *
508
         * @param s Adaptador
509
         * @param a VectorialAdapter.
510
         */
511
        private static void saveSourceAdapter(Source s, VectorialAdapter a) {
512
        }
513

    
514
        /**
515
         * Crea una FLyrComplexRaster que ataca al driver que se pasa como
516
         * par?metro.
517
         *
518
         * @param driver
519
         * @param f
520
         * @param proj
521
         *
522
         * @throws IllegalArgumentException Si se pasa un driver que no implementa
523
         *                    GeorreferencedRasterDriver o NotGeorreferencedRasterDriver
524
         */
525
        public static void createLayer(RasterDriver driver, File f, IProjection proj)
526
                throws IllegalArgumentException {
527
        }
528

    
529
        /**
530
         * Devuelve el DriverManager.
531
         *
532
         * @return DriverManager.
533
         */
534
        public static DriverManager getDM() {
535
                initializeDriverManager();
536

    
537
                return driverManager;
538
        }
539

    
540
        /**
541
         * Inicializa el DriverManager.
542
         */
543
        private static void initializeDriverManager() {
544
                if (driverManager == null) {
545
                        driverManager = new DriverManager();
546
                        driverManager.loadDrivers(new File(LayerFactory.driversPath));
547

    
548
                        Throwable[] failures = driverManager.getLoadFailures();
549

    
550
                        for (int i = 0; i < failures.length; i++) {
551
                                logger.error("", failures[i]);
552
                        }
553

    
554
                        getDataSourceFactory().setDriverManager(driverManager);
555
                        getDataSourceFactory().initialize();
556
                        QueryManager.registerQuery(new ArcJoin());
557
                }
558
        }
559

    
560
        /**
561
         * sets drivers Directory
562
         *
563
         * @param path
564
         */
565
        public static void setDriversPath(String path) {
566
                LayerFactory.driversPath = path;
567
                initializeDriverManager();
568
        }
569
        
570
        
571
        /**
572
         * @return Returns the dataSourceFactory.
573
         */
574
        public static DataSourceFactory getDataSourceFactory() {
575
                if (dataSourceFactory == null){
576
                        dataSourceFactory = new DataSourceFactory();
577
                }
578
                return dataSourceFactory;
579
        }
580
}