Statistics
| Revision:

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

History | View | Annotate | Download (19 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 org.apache.log4j.Logger;
51
import org.cresques.cts.IProjection;
52

    
53
import com.hardcode.driverManager.Driver;
54
import com.hardcode.driverManager.DriverLoadException;
55
import com.hardcode.driverManager.DriverManager;
56
import com.hardcode.driverManager.WriterManager;
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.ViewPort;
68
import com.iver.cit.gvsig.fmap.drivers.DBLayerDefinition;
69
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
70
import com.iver.cit.gvsig.fmap.drivers.RasterDriver;
71
import com.iver.cit.gvsig.fmap.drivers.VectorialDatabaseDriver;
72
import com.iver.cit.gvsig.fmap.drivers.VectorialDriver;
73
import com.iver.cit.gvsig.fmap.drivers.VectorialFileDriver;
74
import com.iver.cit.gvsig.fmap.drivers.VectorialJDBCDriver;
75
import com.iver.cit.gvsig.fmap.drivers.WithDefaultLegend;
76
import com.iver.cit.gvsig.fmap.operations.arcview.ArcJoin;
77
import com.iver.cit.gvsig.fmap.rendering.LegendFactory;
78
import com.iver.cit.gvsig.fmap.rendering.VectorialLegend;
79

    
80

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

    
93
        private static DataSourceFactory dataSourceFactory;
94

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

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

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

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

    
138
                return null;
139
        }
140

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

    
161
                FLyrVect capa = new FLyrVect();
162
                capa.setName(layerName);
163
                try{
164
                //TODO Meter esto dentro de la comprobaci?n de si hay memoria
165
                if (false) {
166
                } else {
167
                        capa.setSource(adapter);
168
                        capa.setProjection(proj);
169
                }
170
                //try {
171

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

    
201
                return capa;
202
        }
203

    
204
    public static FLayer createLayer(String layerName, VectorialDriver d,
205
            IProjection proj) throws DriverException {
206
                    VectorialAdapter adapter = null;
207
            if (d instanceof VectorialFileDriver)
208
            {                    
209
                    adapter = new VectorialFileAdapter(((VectorialFileDriver)d).getFile());
210
            }
211
            else
212
            {
213
                    adapter = new VectorialDefaultAdapter();
214
            }
215
            adapter.setDriver((VectorialDriver) d);
216

    
217
            FLyrVect capa = new FLyrVect();
218
            capa.setName(layerName);
219

    
220
            capa.setSource(adapter);
221
            capa.setProjection(proj);
222

    
223
            try {
224

    
225
                // Le asignamos tambi?n una legenda por defecto acorde con
226
                // el tipo de shape que tenga. Tampoco s? si es aqu? el
227
                // sitio adecuado, pero en fin....
228
                if (d instanceof WithDefaultLegend) {
229
                    WithDefaultLegend aux = (WithDefaultLegend) d;
230
                    adapter.start();
231
                    capa.setLegend((VectorialLegend) aux.getDefaultLegend());
232
                    adapter.stop();
233
                } else {
234
                    capa.setLegend(LegendFactory.createSingleSymbolLegend(
235
                            capa.getShapeType()));
236
                }
237
            } catch (FieldNotFoundException e) {
238
                //Esta no puede saltar
239
            } catch (DriverIOException e) {
240
                throw new DriverException(e);
241
            }
242

    
243
            return capa;
244
        }
245

    
246
        /**
247
         * Crea una capa Raster a partir del nombre driver, fichero y proyecci?n.
248
         *
249
         * @param layerName Nombre de la capa.
250
         * @param d RasterDriver.
251
         * @param f Fichero.
252
         * @param proj Proyecci?n.
253
         *
254
         * @return Nueva capa de tipo raster.
255
         *
256
         * @throws DriverIOException
257
         */
258
        public static FLyrRaster createLayer(String layerName, RasterDriver d,
259
                File f, IProjection proj) throws DriverException {
260
                RasterAdapter adapter = new RasterFileAdapter(f);
261
                adapter.setDriver(d);
262

    
263
                FLyrRaster capa = new FLyrRaster();
264
                capa.setName(layerName);
265

    
266
                //TODO Meter esto dentro de la comprobaci?n de si hay memoria
267
                if (false) {
268
                } else {
269
                        capa.setSource(adapter);
270
                        capa.setProjection(proj);
271
                        try {
272
                                capa.load();
273
                        } catch (DriverIOException e) {
274
                                throw new DriverException(e);
275
                        }
276
                }
277

    
278
                return capa;
279
        }
280

    
281
        /**
282
         * Crea una capa Raster a partir del nombre driver, fichero y proyecci?n y
283
         * coordenadas de georeferenciaci?n. Esta funci?n es para georeferenciar
284
         * capas raster. Para imagenes que no tienen georeferenciaci?n hay que asignarle
285
         * una temporal, normalmente a partir de la vista activa.
286
         *
287
         * @param layerName Nombre de la capa.
288
         * @param d RasterDriver.
289
         * @param f Fichero.
290
         * @param proj Proyecci?n.
291
         * @param extent Extent de la vista activa
292
         *
293
         * @return Nueva capa de tipo raster.
294
         *
295
         * @throws DriverIOException
296
         */
297
        public static FLyrRaster createLayer(String layerName, RasterDriver d,
298
                File f, IProjection proj, ViewPort vp) throws DriverException {
299
                RasterAdapter adapter = new RasterFileAdapter(f);
300
                adapter.setDriver(d);
301

    
302
                FLyrRaster capa = new FLyrRaster();
303
                capa.setName(layerName);
304

    
305
                //TODO Meter esto dentro de la comprobaci?n de si hay memoria
306
                if (false) {
307
                } else {
308
                        capa.setSource(adapter);
309
                        capa.setProjection(proj);
310
                        //capa.setTempExtent(vp);
311
                        try {
312
                                capa.load();
313
                        } catch (DriverIOException e) {
314
                                throw new DriverException(e);
315
                        }
316
                }
317

    
318
                return capa;
319
        }
320

    
321

    
322
    public static FLayer createArcSDELayer(String layerName,VectorialDatabaseDriver driver, IProjection proj) {
323
            //throw new UnsupportedOperationException();
324
            FLyrVect layer=new FLyrVect();
325
            VectorialAdapter adapter=new VectorialDBAdapter();
326
            adapter.setDriver(driver);
327

    
328
            layer.setName(layerName);
329
            layer.setSource(adapter);
330
            layer.setProjection(proj);
331
            try {
332
                if (driver instanceof WithDefaultLegend) {
333
                    WithDefaultLegend aux = (WithDefaultLegend) driver;
334
                    adapter.start();
335
                    layer.setLegend((VectorialLegend) aux.getDefaultLegend());
336
                    adapter.stop();
337
                } else {
338
                    layer.setLegend(LegendFactory.createSingleSymbolLegend(
339
                            layer.getShapeType()));
340
                }
341
            } catch (FieldNotFoundException e) {
342
                throw new UnsupportedOperationException(e.getMessage());
343
            } catch (DriverIOException e) {
344
                throw new UnsupportedOperationException(e.getMessage());
345
            } catch (DriverException e) {
346
                // TODO Auto-generated catch block
347
                e.printStackTrace();
348
            }
349

    
350
            try {
351
                layer.setLegend(LegendFactory.createSingleSymbolLegend(
352
                        layer.getShapeType()));
353
            } catch (FieldNotFoundException e) {
354
                e.printStackTrace();
355
            } catch (DriverException e) {
356
                e.printStackTrace();
357
            }
358
            return layer;
359
        }
360

    
361
        /**
362
         * Crea un RandomVectorialWFS con el driver que se le pasa como par?metro y
363
         * guard?ndose la URL del servidor que se pasa como par?metro
364
         *
365
         * @param driver
366
         * @param host
367
         * @param port
368
         * @param user
369
         * @param password
370
         * @param dbName
371
         * @param tableName
372
         * @param proj
373
         *
374
         * @return Capa creada.
375
         *
376
         * @throws UnsupportedOperationException
377
         */
378
        public static FLayer createLayer(VectorialDatabaseDriver driver,
379
                String host, int port, String user, String password, String dbName,
380
                String tableName, IProjection proj) {
381
                throw new UnsupportedOperationException();
382
        }
383
        public static FLayer createDBLayer(VectorialDatabaseDriver driver,String layerName, IProjection proj)
384
        {
385

    
386

    
387
                FLyrVect capa = new FLyrVect();
388

    
389
                capa.setName(layerName);
390
                VectorialDBAdapter dbAdapter = new VectorialDBAdapter();
391
                dbAdapter.setDriver(driver);
392

    
393
                capa.setSource(dbAdapter);
394
                capa.setProjection(proj);
395
                try {
396
                        if (driver instanceof WithDefaultLegend) {
397
                                WithDefaultLegend aux = (WithDefaultLegend) driver;
398
                                dbAdapter.start();
399
                    capa.setLegend((VectorialLegend) aux.getDefaultLegend());
400
                                dbAdapter.stop();
401
                        } else {
402
                                capa.setLegend(LegendFactory.createSingleSymbolLegend(
403
                                                capa.getShapeType()));
404
                        }
405
        } catch (FieldNotFoundException e) {
406
                        capa.setUnavailable(true);
407
                        return capa;
408
            //throw new UnsupportedOperationException(e.getMessage());
409
        } catch (DriverException e) {
410
                        capa.setUnavailable(true);
411
                        return capa;
412
            //throw new UnsupportedOperationException(e.getMessage());
413
        }
414

    
415
                return capa;
416

    
417

    
418

    
419
                }
420

    
421
        /**
422
         * @param driver
423
         * @param layerName
424
         * @param object
425
         * @return
426
         * @throws SQLException
427
         * @throws DriverIOException
428
         * @throws IOException
429
         * @throws DriverLoadException
430
         * @throws com.hardcode.gdbms.engine.data.driver.DriverException
431
         * @throws NoSuchTableException
432
         * @throws ClassNotFoundException
433
         * @throws
434
         */
435
        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 {
436
            VectorialDisconnectedDBAdapter dbAdapter = new VectorialDisconnectedDBAdapter();
437
            dbAdapter.setDriver(driver);
438
            DataSource ds = dbAdapter.getRecordset();
439
            ds.start();
440
            String database = dataSourceFactory.getTempFile();
441
            String[] fieldNames = new String[ds.getFieldCount() + 1];
442
            System.arraycopy(ds.getFieldNames(), 0, fieldNames, 1, ds.getFieldCount());
443
            fieldNames[0] = "the_geom";
444
            int[] types = new int[fieldNames.length];
445
            types[0] = Types.BINARY;
446
            for (int i = 1; i < types.length; i++) {
447
            types[i] = ds.getFieldType(i-1);
448
        }
449
            String dsName = dataSourceFactory.createTable(database, ds.getPKNames(), fieldNames, types);
450

    
451
        DBLayerDefinition lyrDef = new DBLayerDefinition();
452
        lyrDef.setTableName(dsName);
453
        lyrDef.setName(layerName);
454
        lyrDef.setFieldNames(ds.getFieldNames());
455
        lyrDef.setFieldGeometry("the_geom");
456
        lyrDef.setFieldID(ds.getPKNames()[0]);
457
        lyrDef.setClassToInstantiate("org.hsqldb.jdbcDriver");
458

    
459
            dataSourceFactory.addDBDataSourceByTable(dsName, null, 0, "sa", "", database, dsName, "GDBMS HSQLDB Transactional driver");
460
            DataSource local = dataSourceFactory.createRandomDataSource(dsName, DataSourceFactory.MANUAL_OPENING);
461
            local.start();
462
            DataWare dw = local.getDataWare(DataSourceFactory.DATA_WARE_COHERENT_ROW_ORDER);
463
            dw.start();
464
            long t1 = System.currentTimeMillis();
465
            dw.beginTrans();
466

    
467
            if (listener == null){
468
                listener = new ProgressListener() {
469
                /**
470
                 * @see com.iver.cit.gvsig.fmap.ProgressListener#progress(int)
471
                 */
472
                public void progress(int n) {
473
                    //do nothing
474
                }
475
            };
476
            }
477

    
478
            for (int i = 0; i < dbAdapter.getShapeCount(); i++) {
479
                Value[] row = new Value[ds.getFieldCount() + 1];
480

    
481
                byte[] bytes = dbAdapter.getShape(i).toWKB();
482
                row[0] = ValueFactory.createValue(bytes);
483

    
484
                for (int j = 0; j < ds.getFieldCount(); j++) {
485
                    row[j+1] = ds.getFieldValue(i, j);
486
            }
487

    
488
                dw.insertFilledRow(row);
489
                listener.progress(100 * i / dbAdapter.getShapeCount());
490
        }
491

    
492
            long t2 = System.currentTimeMillis();
493
            dw.commitTrans();
494
            long t3 = System.currentTimeMillis();
495
            System.out.println((t2 - t1) + " - " + (t3 - t2));
496
            dw.stop();
497
            local.stop();
498
            ds.stop();
499
            VectorialJDBCDriver cacheDriver = (VectorialJDBCDriver) LayerFactory.getDM().getDriver("HSQLDB Driver");
500
        Class.forName("org.hsqldb.jdbcDriver");
501

    
502
            cacheDriver.setData(java.sql.DriverManager.getConnection("jdbc:hsqldb:file:" + database, "sa", ""), lyrDef);
503
            cacheDriver.setWorkingArea(driver.getWorkingArea());
504
        return createDBLayer(cacheDriver, layerName, proj);
505
        }
506

    
507

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

    
523
        /**
524
         * Devuelve el DriverManager.
525
         *
526
         * @return DriverManager.
527
         */
528
        public static DriverManager getDM() {
529
                initializeDriverManager();
530

    
531
                return driverManager;
532
        }
533
        /**
534
         * Devuelve el WriterManager.
535
         *
536
         * @return WriterManager.
537
         */
538
        public static WriterManager getWM() {
539
                initializeWriterManager();
540

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

    
551
                        Throwable[] failures = driverManager.getLoadFailures();
552

    
553
                        for (int i = 0; i < failures.length; i++) {
554
                                logger.error("", failures[i]);
555
                        }
556

    
557
                        getDataSourceFactory().setDriverManager(driverManager);
558
                        getDataSourceFactory().initialize();
559
                        QueryManager.registerQuery(new ArcJoin());
560
                }
561
        }
562
        /**
563
         * Inicializa el DriverManager.
564
         */
565
        private static void initializeWriterManager() {
566
                if (writerManager == null) {
567
                        writerManager = new WriterManager();
568
                        writerManager.loadWriters(new File(LayerFactory.writersPath));
569

    
570
                        Throwable[] failures = writerManager.getLoadFailures();
571

    
572
                        for (int i = 0; i < failures.length; i++) {
573
                                logger.error("", failures[i]);
574
                        }
575

    
576
                        getDataSourceFactory().setWriterManager(writerManager);
577
                        getDataSourceFactory().initialize();
578
                        //QueryManager.registerQuery(new ArcJoin());
579
                }
580
        }
581
        /**
582
         * sets drivers Directory
583
         *
584
         * @param path
585
         */
586
        public static void setDriversPath(String path) {
587
                LayerFactory.driversPath = path;
588
                initializeDriverManager();
589
        }
590
        /**
591
         * sets writers Directory
592
         *
593
         * @param path
594
         */
595
        public static void setWritersPath(String path) {
596
                LayerFactory.writersPath = path;
597
                initializeWriterManager();
598
        }
599

    
600
        /**
601
         * @return Returns the dataSourceFactory.
602
         */
603
        public static DataSourceFactory getDataSourceFactory() {
604
                if (dataSourceFactory == null){
605
                        dataSourceFactory = new DataSourceFactory();
606
                }
607
                return dataSourceFactory;
608
        }
609
}