Statistics
| Revision:

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

History | View | Annotate | Download (18.9 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
                }
198

    
199
                return capa;
200
        }
201

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

    
215
            FLyrVect capa = new FLyrVect();
216
            capa.setName(layerName);
217

    
218
            capa.setSource(adapter);
219
            capa.setProjection(proj);
220

    
221
            try {
222

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

    
241
            return capa;
242
        }
243

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

    
261
                FLyrRaster capa = new FLyrRaster();
262
                capa.setName(layerName);
263

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

    
276
                return capa;
277
        }
278

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

    
300
                FLyrRaster capa = new FLyrRaster();
301
                capa.setName(layerName);
302

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

    
316
                return capa;
317
        }
318

    
319

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

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

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

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

    
384

    
385
                FLyrVect capa = new FLyrVect();
386

    
387
                capa.setName(layerName);
388
                VectorialDBAdapter dbAdapter = new VectorialDBAdapter();
389
                dbAdapter.setDriver(driver);
390

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

    
409
                return capa;
410

    
411

    
412

    
413
                }
414

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

    
445
        DBLayerDefinition lyrDef = new DBLayerDefinition();
446
        lyrDef.setTableName(dsName);
447
        lyrDef.setName(layerName);
448
        lyrDef.setFieldNames(ds.getFieldNames());
449
        lyrDef.setFieldGeometry("the_geom");
450
        lyrDef.setFieldID(ds.getPKNames()[0]);
451
        lyrDef.setClassToInstantiate("org.hsqldb.jdbcDriver");
452

    
453
            dataSourceFactory.addDBDataSourceByTable(dsName, null, 0, "sa", "", database, dsName, "GDBMS HSQLDB Transactional driver");
454
            DataSource local = dataSourceFactory.createRandomDataSource(dsName, DataSourceFactory.MANUAL_OPENING);
455
            local.start();
456
            DataWare dw = local.getDataWare(DataSourceFactory.DATA_WARE_COHERENT_ROW_ORDER);
457
            dw.start();
458
            long t1 = System.currentTimeMillis();
459
            dw.beginTrans();
460

    
461
            if (listener == null){
462
                listener = new ProgressListener() {
463
                /**
464
                 * @see com.iver.cit.gvsig.fmap.ProgressListener#progress(int)
465
                 */
466
                public void progress(int n) {
467
                    //do nothing
468
                }
469
            };
470
            }
471

    
472
            for (int i = 0; i < dbAdapter.getShapeCount(); i++) {
473
                Value[] row = new Value[ds.getFieldCount() + 1];
474

    
475
                byte[] bytes = dbAdapter.getShape(i).toWKB();
476
                row[0] = ValueFactory.createValue(bytes);
477

    
478
                for (int j = 0; j < ds.getFieldCount(); j++) {
479
                    row[j+1] = ds.getFieldValue(i, j);
480
            }
481

    
482
                dw.insertFilledRow(row);
483
                listener.progress(100 * i / dbAdapter.getShapeCount());
484
        }
485

    
486
            long t2 = System.currentTimeMillis();
487
            dw.commitTrans();
488
            long t3 = System.currentTimeMillis();
489
            System.out.println((t2 - t1) + " - " + (t3 - t2));
490
            dw.stop();
491
            local.stop();
492
            ds.stop();
493
            VectorialJDBCDriver cacheDriver = (VectorialJDBCDriver) LayerFactory.getDM().getDriver("HSQLDB Driver");
494
        Class.forName("org.hsqldb.jdbcDriver");
495

    
496
            cacheDriver.setData(java.sql.DriverManager.getConnection("jdbc:hsqldb:file:" + database, "sa", ""), lyrDef);
497
            cacheDriver.setWorkingArea(driver.getWorkingArea());
498
        return createDBLayer(cacheDriver, layerName, proj);
499
        }
500

    
501

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

    
517
        /**
518
         * Devuelve el DriverManager.
519
         *
520
         * @return DriverManager.
521
         */
522
        public static DriverManager getDM() {
523
                initializeDriverManager();
524

    
525
                return driverManager;
526
        }
527
        /**
528
         * Devuelve el WriterManager.
529
         *
530
         * @return WriterManager.
531
         */
532
        public static WriterManager getWM() {
533
                initializeWriterManager();
534

    
535
                return writerManager;
536
        }
537
        /**
538
         * Inicializa el DriverManager.
539
         */
540
        private static void initializeDriverManager() {
541
                if (driverManager == null) {
542
                        driverManager = new DriverManager();
543
                        driverManager.loadDrivers(new File(LayerFactory.driversPath));
544

    
545
                        Throwable[] failures = driverManager.getLoadFailures();
546

    
547
                        for (int i = 0; i < failures.length; i++) {
548
                                logger.error("", failures[i]);
549
                        }
550

    
551
                        getDataSourceFactory().setDriverManager(driverManager);
552
                        getDataSourceFactory().initialize();
553
                        QueryManager.registerQuery(new ArcJoin());
554
                }
555
        }
556
        /**
557
         * Inicializa el DriverManager.
558
         */
559
        private static void initializeWriterManager() {
560
                if (writerManager == null) {
561
                        writerManager = new WriterManager();
562
                        writerManager.loadWriters(new File(LayerFactory.writersPath));
563

    
564
                        Throwable[] failures = writerManager.getLoadFailures();
565

    
566
                        for (int i = 0; i < failures.length; i++) {
567
                                logger.error("", failures[i]);
568
                        }
569

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

    
594
        /**
595
         * @return Returns the dataSourceFactory.
596
         */
597
        public static DataSourceFactory getDataSourceFactory() {
598
                if (dataSourceFactory == null){
599
                        dataSourceFactory = new DataSourceFactory();
600
                }
601
                return dataSourceFactory;
602
        }
603
}