Statistics
| Revision:

root / trunk / libraries / libFMap / src / com / iver / cit / gvsig / fmap / layers / LayerFactory.java @ 18621

History | View | Annotate | Download (22.7 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.sql.SQLException;
46
import java.sql.Types;
47
import java.util.Hashtable;
48
import java.util.TreeMap;
49

    
50
import org.apache.log4j.Logger;
51
import org.cresques.cts.IProjection;
52
import org.gvsig.exceptions.BaseException;
53

    
54
import com.hardcode.driverManager.Driver;
55
import com.hardcode.driverManager.DriverLoadException;
56
import com.hardcode.driverManager.DriverManager;
57
import com.hardcode.driverManager.IDelayedDriver;
58
import com.hardcode.driverManager.WriterManager;
59
import com.hardcode.gdbms.driver.exceptions.InitializeDriverException;
60
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
61
import com.hardcode.gdbms.driver.exceptions.WriteDriverException;
62
import com.hardcode.gdbms.engine.customQuery.QueryManager;
63
import com.hardcode.gdbms.engine.data.DataSource;
64
import com.hardcode.gdbms.engine.data.DataSourceFactory;
65
import com.hardcode.gdbms.engine.data.NoSuchTableException;
66
import com.hardcode.gdbms.engine.data.driver.DriverException;
67
import com.hardcode.gdbms.engine.data.edition.DataWare;
68
import com.hardcode.gdbms.engine.values.Value;
69
import com.hardcode.gdbms.engine.values.ValueFactory;
70
import com.iver.cit.gvsig.exceptions.layers.LegendLayerException;
71
import com.iver.cit.gvsig.exceptions.layers.LoadLayerException;
72
import com.iver.cit.gvsig.fmap.DriverNotLoadedExceptionType;
73
import com.iver.cit.gvsig.fmap.LegendDriverExceptionType;
74
import com.iver.cit.gvsig.fmap.ProgressListener;
75
import com.iver.cit.gvsig.fmap.drivers.ConnectionFactory;
76
import com.iver.cit.gvsig.fmap.drivers.DBException;
77
import com.iver.cit.gvsig.fmap.drivers.DBLayerDefinition;
78
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
79
import com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver;
80
import com.iver.cit.gvsig.fmap.drivers.IVectorialJDBCDriver;
81
import com.iver.cit.gvsig.fmap.drivers.VectorialDriver;
82
import com.iver.cit.gvsig.fmap.drivers.VectorialFileDriver;
83
import com.iver.cit.gvsig.fmap.drivers.WithDefaultLegend;
84
import com.iver.cit.gvsig.fmap.operations.arcview.ArcJoin;
85
import com.iver.cit.gvsig.fmap.rendering.IVectorLegend;
86
import com.iver.cit.gvsig.fmap.rendering.LegendFactory;
87
import com.iver.cit.gvsig.fmap.rendering.styling.labeling.AttrInTableLabelingStrategy;
88
import com.iver.cit.gvsig.fmap.rendering.styling.labeling.ILabelingStrategy;
89

    
90
/**
91
 * Crea un adaptador del driver que se le pasa como par?metro en los m?todos
92
 * createLayer. Si hay memoria suficiente se crea un FLyrMemory que pasa todas
93
 * las features del driver a memoria
94
 */
95
public class LayerFactory {
96
//        private static ArrayList<ISolveErrorListener> solveListeners=new ArrayList<ISolveErrorListener>();
97
        private static Hashtable<Class, ISolveErrorListener> solveListeners = new Hashtable<Class,ISolveErrorListener>();
98

    
99

    
100
        private static Logger logger = Logger.getLogger(LayerFactory.class
101
                        .getName());
102

    
103
        private static String driversPath = "../FMap 03/drivers";
104
        private static String writersPath = "../FMap 03/drivers";
105
        private static DriverManager driverManager;
106
        private static WriterManager writerManager;
107
        private static DataSourceFactory dataSourceFactory;
108

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

    
119
        /**
120
         * This Hashtable allows to register an alternative LayerClass for
121
         * an specific LayerClass than is attempting to create this factory
122
         */
123
        private static Hashtable layerClassMapping = new Hashtable();
124

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

    
142
                try {
143
                        Driver d = dm.getDriver(driverName);
144

    
145
                        if (d instanceof VectorialFileDriver) {
146
                                return createLayer(layerName, (VectorialFileDriver) d, f, proj);
147
                        }
148
                } catch (DriverLoadException e) {
149
                        //hay un poco de lio sobre que excepciones se dejan subir
150
                        //arriba y que excepciones se quedan en LayerFactory
151
                        //(esto se debe a que queremos intentar recuperar ciertas capas)
152
                        //las excepciones de este metodo se dejan subir todas, puesto
153
                        //que las excepciones de los dos otros metodos createLayer si que
154
                        //se atrapan
155
                        DriverNotLoadedExceptionType exceptionType =
156
                                new DriverNotLoadedExceptionType();
157
                        exceptionType.setDriverName(driverName);
158
//                        DriverException exception =
159
//                                new DriverException(e, exceptionType);
160
                        throw new LoadLayerException(layerName,e);
161
                }
162

    
163
                return null;
164
        }
165

    
166
        /**
167
         * It creates a FLayer (FLyrVect) which reads its data from a file driver,
168
         * projected in the specified projection.
169
         *
170
         * @param layerName
171
         *            name of the layer
172
         * @param d
173
         *            vectorial file driver to read layer's data
174
         * @param f
175
         *            file associated to the driver
176
         * @param proj
177
         *            layer projection
178
         *
179
         * @return FLayer new vectorial layer
180
         * @throws LoadLayerException
181
         *
182
         * @throws DriverException
183
         */
184
        public static FLayer createLayer(String layerName, VectorialFileDriver d,
185
                        File f, IProjection proj)
186

    
187
        /*throws DriverException*/ {
188
                FLyrVect layer = new FLyrVect();
189
                try {
190
                // TODO Comprobar si hay un adaptador ya
191
                VectorialFileAdapter adapter = new VectorialFileAdapter(f);
192
                adapter.setDriver(d);
193

    
194
                //TODO azo: adapter needs a reference to projection and to spatial index (review)
195
                adapter.setProjection(proj);
196

    
197
                layer.setName(layerName);
198

    
199
                // TODO Meter esto dentro de la comprobaci?n de si hay memoria
200
                if (false) {
201
                } else {
202
                        layer.setSource(adapter);
203
                        layer.setProjection(proj);
204
                }
205

    
206

    
207
                        // Le asignamos tambi?n una legenda por defecto acorde con
208
                        // el tipo de shape que tenga. Tampoco s? si es aqu? el
209
                        // sitio adecuado, pero en fin....
210
                        if (d instanceof WithDefaultLegend) {
211
                                WithDefaultLegend aux = (WithDefaultLegend) d;
212

    
213
                                        adapter.start();
214
                                        layer.setLegend((IVectorLegend) aux.getDefaultLegend());
215

    
216
                                        ILabelingStrategy labeler = aux.getDefaultLabelingStrategy();
217
                                        if (labeler instanceof AttrInTableLabelingStrategy) {
218
                                                ((AttrInTableLabelingStrategy) labeler).setLayer(layer);
219
                                        }
220
                                        layer.setLabelingStrategy(labeler);
221
                                        layer.setIsLabeled(true); // TODO: ac? no s'hauria de detectar si t? etiquetes?????
222
                                        adapter.stop();
223

    
224
                        } else {
225
                                IVectorLegend leg = LegendFactory.createSingleSymbolLegend(layer
226
                                                .getShapeType());
227
                                layer.setLegend(leg);
228

    
229
                        }
230
        } catch (ReadDriverException e) {
231
                layer=tryToSolveError(e,layer,d);
232
        } catch (LoadLayerException e) {
233
                layer=tryToSolveError(e,layer,d);
234
        }
235
                return layer;
236
        }
237

    
238
        private static FLyrVect tryToSolveError(BaseException e,FLayer layer,Driver d) {
239
                ISolveErrorListener sel = solveListeners.get(e.getClass());
240
                if (sel!=null){
241
                        FLyrVect solvedLayer=null;
242
                        solvedLayer=(FLyrVect)sel.solve(layer,d);
243
                        if (solvedLayer!=null && sel!=null){
244
                                return solvedLayer;
245
                        }
246
                }
247
                layer.setAvailable(false);
248
                layer.addError(e);
249
                return (FLyrVect)layer;
250
        }
251

    
252
        public static void addSolveErrorForLayer(Class exception, ISolveErrorListener sel) {
253
                solveListeners.put(exception,sel);
254
        }
255
        public static void removeSolveErrorListener(Class exception){
256
                solveListeners.remove(exception);
257
        }
258
        /**
259
         * Creates a new vectorial layer from a generic layer (by generic whe mean
260
         * that we dont know a priory its origin: file, memory, jdbc database, etc.
261
         *
262
         * @param layerName
263
         * @param d
264
         * @param proj
265
         * @return
266
         * @throws DriverException
267
         */
268
        public static FLayer createLayer(String layerName, VectorialDriver d,
269
                        IProjection proj)
270
        /*
271
        throws DriverException
272
        */{
273
                VectorialAdapter adapter = null;
274
                if (d instanceof VectorialFileDriver) {
275
                        adapter = new VectorialFileAdapter(((VectorialFileDriver) d)
276
                                        .getFile());
277
                } else if (d instanceof IVectorialDatabaseDriver) {
278
                        adapter = new VectorialDBAdapter();
279
                } else {
280
                        adapter = new VectorialDefaultAdapter();
281
                }
282
                adapter.setDriver((VectorialDriver) d);
283
                //TODO azo:adapter needs a reference to the projection
284
                adapter.setProjection(proj);
285

    
286
                FLyrVect layer = new FLyrVect();
287
                layer.setName(layerName);
288

    
289
                layer.setSource(adapter);
290
                layer.setProjection(proj);
291

    
292
                try {
293

    
294
                        // Le asignamos tambi?n una legenda por defecto acorde con
295
                        // el tipo de shape que tenga. Tampoco s? si es aqu? el
296
                        // sitio adecuado, pero en fin....
297
                        if (d instanceof WithDefaultLegend) {
298
                                WithDefaultLegend aux = (WithDefaultLegend) d;
299
                                adapter.start();
300
                                layer.setLegend((IVectorLegend) aux.getDefaultLegend());
301

    
302
                                ILabelingStrategy labeler = aux.getDefaultLabelingStrategy();
303
                                if (labeler instanceof AttrInTableLabelingStrategy) {
304
                                        ((AttrInTableLabelingStrategy) labeler).setLayer(layer);
305
                                }
306
                                layer.setLabelingStrategy(labeler);
307

    
308
                                layer.setIsLabeled(true); // TODO: ac? no s'hauria de detectar si t? etiquetes?????
309

    
310
                                adapter.stop();
311
                        } else {
312
                                layer.setLegend(LegendFactory.createSingleSymbolLegend(layer
313
                                                .getShapeType()));
314
                        }
315
                } catch (LegendLayerException e) {
316

    
317
                        layer.setAvailable(false);
318
                        layer.addError(e);
319

    
320
                } catch (ReadDriverException e) {
321
                        layer.setAvailable(false);
322
                        layer.addError(e);
323
                }
324

    
325
                return layer;
326
        }
327

    
328
        public static FLayer createArcSDELayer(String layerName,
329
                        IVectorialDatabaseDriver driver, IProjection proj) {
330
                // throw new UnsupportedOperationException();
331
                FLyrVect layer = new FLyrVect();
332
                VectorialAdapter adapter = new VectorialDBAdapter();
333
                adapter.setDriver(driver);
334
                adapter.setProjection(proj);
335

    
336
                layer.setName(layerName);
337
                layer.setSource(adapter);
338
                layer.setProjection(proj);
339
                try {
340
                        if (driver instanceof WithDefaultLegend) {
341
                                WithDefaultLegend aux = (WithDefaultLegend) driver;
342
                                adapter.start();
343
                                layer.setLegend((IVectorLegend) aux.getDefaultLegend());
344

    
345
                                ILabelingStrategy labeler = aux.getDefaultLabelingStrategy();
346
                                if (labeler instanceof AttrInTableLabelingStrategy) {
347
                                        ((AttrInTableLabelingStrategy) labeler).setLayer(layer);
348
                                }
349
                                layer.setLabelingStrategy(labeler);layer.setIsLabeled(true); // TODO: ac? no s'hauria de detectar si t? etiquetes?????
350

    
351
                                adapter.stop();
352
                        } else {
353
                                layer.setLegend(LegendFactory.createSingleSymbolLegend(layer
354
                                                .getShapeType()));
355
                        }
356
                } catch (LegendLayerException e) {
357
                        throw new UnsupportedOperationException(e.getMessage());
358
                } catch (InitializeDriverException e) {
359
                        throw new UnsupportedOperationException(e.getMessage());
360
                } catch (ReadDriverException e) {
361
                        throw new UnsupportedOperationException(e.getMessage());
362
                }
363

    
364
                try {
365
                        layer.setLegend(LegendFactory.createSingleSymbolLegend(layer
366
                                        .getShapeType()));
367
                } catch (LegendLayerException e) {
368
                        e.printStackTrace();
369
                } catch (ReadDriverException e) {
370
                        e.printStackTrace();
371
                }
372
                return layer;
373
        }
374

    
375
        /**
376
         * Crea un RandomVectorialWFS con el driver que se le pasa como par?metro y
377
         * guard?ndose la URL del servidor que se pasa como par?metro
378
         *
379
         * @param driver
380
         * @param host
381
         * @param port
382
         * @param user
383
         * @param password
384
         * @param dbName
385
         * @param tableName
386
         * @param proj
387
         *
388
         * @return Capa creada.
389
         *
390
         * @throws UnsupportedOperationException
391
         */
392
        public static FLayer createLayer(IVectorialDatabaseDriver driver,
393
                        String host, int port, String user, String password, String dbName,
394
                        String tableName, IProjection proj) {
395
                throw new UnsupportedOperationException();
396
        }
397

    
398
        public static FLayer createDBLayer(IVectorialDatabaseDriver driver,
399
                        String layerName, IProjection proj) {
400

    
401
                FLyrVect layer = new FLyrVect();
402

    
403
                layer.setName(layerName);
404
                VectorialDBAdapter dbAdapter = new VectorialDBAdapter();
405
                dbAdapter.setDriver(driver);
406
                dbAdapter.setProjection(proj);//adapter needs also a ref to prj. review (azo)
407

    
408
                layer.setSource(dbAdapter);
409
                layer.setProjection(proj);
410
                try {
411
                        if (driver instanceof WithDefaultLegend) {
412
                                WithDefaultLegend aux = (WithDefaultLegend) driver;
413
                                dbAdapter.start();
414
                                layer.setLegend((IVectorLegend) aux.getDefaultLegend());
415

    
416
                                ILabelingStrategy labeler = aux.getDefaultLabelingStrategy();
417
                                if (labeler instanceof AttrInTableLabelingStrategy) {
418
                                        ((AttrInTableLabelingStrategy) labeler).setLayer(layer);
419
                                }
420
                                layer.setLabelingStrategy(labeler);
421

    
422
                                layer.setIsLabeled(true); // TODO: ac? no s'hauria de detectar si t? etiquetes?????
423

    
424
                                dbAdapter.stop();
425
                        } else {
426
                                layer.setLegend(LegendFactory.createSingleSymbolLegend(layer
427
                                                .getShapeType()));
428
                        }
429
                        if (driver instanceof IDelayedDriver){
430
                                // Por defecto, los drivers est?n listos para entregar
431
                                // features al terminar su initialize. Pero con los drivers
432
                                // que implementan IDelayedDriver, el driver es responsable
433
                                // de avisar cu?ndo est? listo
434
                                layer.getFLayerStatus().setDriverLoaded(false);
435
                                ((IDelayedDriver) driver).addDriverEventListener(new DefaultDelayedDriverListener(layer));
436
                        }
437
                } catch (LegendLayerException e) {
438
                        LegendDriverExceptionType excepType =
439
                                new LegendDriverExceptionType("Error al construir la leyenda, campo no encontrado");
440
                        //TODO Para hacer esto extensible tiene que usarse puntos
441
                        //de extension, y comparar las clases de leyendas registradas
442
//                        IVectorialLegend legend = (IVectorialLegend)
443
//                                ((WithDefaultLegend)driver).getDefaultLegend();
444
//
445
//                        excepType.setLegendLabelField(legend.getLabelField());
446
//                        excepType.setLegendHeightField(legend.getLabelHeightField());
447
//                        excepType.setLegendRotationField(legend.getLabelRotationField());
448
//                        DriverException exception = new DriverException(e, excepType);
449
                        layer.setAvailable(false);
450
                        layer.addError(null);
451
                        return layer;
452
                        // throw new UnsupportedOperationException(e.getMessage());
453
                } catch (Exception e) {
454
//                        ExceptionDescription excepType = new GenericDriverExceptionType();
455
//                        DriverException exception = new DriverException(e, excepType);
456
                        layer.addError(null);
457
                        layer.setAvailable(false);
458
                        return layer;
459
                }
460

    
461
                return layer;
462

    
463
        }
464

    
465
        /**
466
         * @param driver
467
         * @param layerName
468
         * @param object
469
         * @return
470
         * @throws SQLException
471
         * @throws DriverIOException
472
         * @throws IOException
473
         * @throws DriverLoadException
474
         * @throws com.hardcode.gdbms.engine.data.driver.DriverException
475
         * @throws NoSuchTableException
476
         * @throws ClassNotFoundException
477
         * @throws ReadDriverException
478
         * @throws IOException
479
         * @throws WriteDriverException
480
         * @throws
481
         */
482
        public static FLayer createDisconnectedDBLayer(IVectorialJDBCDriver driver,
483
                        String layerName, IProjection proj, ProgressListener listener)
484
                        throws DBException,
485
                        DriverLoadException, NoSuchTableException,
486
                        ClassNotFoundException, ReadDriverException, IOException, WriteDriverException {
487
                VectorialDisconnectedDBAdapter dbAdapter = new VectorialDisconnectedDBAdapter();
488
                dbAdapter.setDriver(driver);
489
                dbAdapter.setProjection(proj);
490
                DataSource ds = dbAdapter.getRecordset();
491
                ds.start();
492
                String database = dataSourceFactory.getTempFile();
493
                String[] fieldNames = new String[ds.getFieldCount() + 1];
494
                System.arraycopy(ds.getFieldNames(), 0, fieldNames, 1, ds
495
                                .getFieldCount());
496
                fieldNames[0] = "the_geom";
497
                int[] types = new int[fieldNames.length];
498
                types[0] = Types.BINARY;
499
                for (int i = 1; i < types.length; i++) {
500
                        types[i] = ds.getFieldType(i - 1);
501
                }
502
                String dsName=null;
503
                try {
504
                        dsName = dataSourceFactory.createTable(database,
505
                                        ds.getPKNames(), fieldNames, types);
506
                } catch (ReadDriverException e) {
507
                        // TODO Auto-generated catch block
508
                        e.printStackTrace();
509
                } catch (SQLException e) {
510
                        throw new DBException(e);
511
                }
512

    
513
                DBLayerDefinition lyrDef = new DBLayerDefinition();
514
                lyrDef.setTableName(dsName);
515
                lyrDef.setName(layerName);
516
                lyrDef.setFieldNames(ds.getFieldNames());
517
                lyrDef.setFieldGeometry("the_geom");
518
                lyrDef.setFieldID(ds.getPKNames()[0]);
519
                lyrDef.setClassToInstantiate("org.hsqldb.jdbcDriver");
520

    
521
                dataSourceFactory.addDBDataSourceByTable(dsName, null, 0, "sa", "",
522
                                database, dsName, "GDBMS HSQLDB Transactional driver");
523
                DataSource local = dataSourceFactory.createRandomDataSource(dsName,
524
                                DataSourceFactory.AUTOMATIC_OPENING);
525
                local.start();
526
                DataWare dw = local
527
                                .getDataWare(DataSourceFactory.DATA_WARE_COHERENT_ROW_ORDER);
528
                dw.start();
529
                long t1 = System.currentTimeMillis();
530
                dw.beginTrans();
531

    
532
                if (listener == null) {
533
                        listener = new ProgressListener() {
534
                                /**
535
                                 * @see com.iver.cit.gvsig.fmap.ProgressListener#progress(int)
536
                                 */
537
                                public void progress(int n) {
538
                                        // do nothing
539
                                }
540
                        };
541
                }
542

    
543
                for (int i = 0; i < dbAdapter.getShapeCount(); i++) {
544
                        Value[] row = new Value[ds.getFieldCount() + 1];
545

    
546
                        byte[] bytes = dbAdapter.getShape(i).toWKB();
547
                        row[0] = ValueFactory.createValue(bytes);
548

    
549
                        for (int j = 0; j < ds.getFieldCount(); j++) {
550
                                row[j + 1] = ds.getFieldValue(i, j);
551
                        }
552

    
553
                        dw.insertFilledRow(row);
554
                        listener.progress(100 * i / dbAdapter.getShapeCount());
555
                }
556

    
557
                long t2 = System.currentTimeMillis();
558
                dw.commitTrans();
559
                long t3 = System.currentTimeMillis();
560
                System.out.println((t2 - t1) + " - " + (t3 - t2));
561
                dw.stop();
562
                local.stop();
563
                ds.stop();
564
                IVectorialJDBCDriver cacheDriver = (IVectorialJDBCDriver) LayerFactory
565
                                .getDM().getDriver("HSQLDB Driver");
566
                Class.forName("org.hsqldb.jdbcDriver");
567

    
568
                cacheDriver.setData(ConnectionFactory.createConnection(
569
                                "jdbc:hsqldb:file:" + database, "sa", ""), lyrDef);
570
                cacheDriver.setWorkingArea(driver.getWorkingArea());
571
                return createDBLayer(cacheDriver, layerName, proj);
572
        }
573

    
574
        /**
575
         * Devuelve el DriverManager.
576
         *
577
         * @return DriverManager.
578
         */
579
        public static DriverManager getDM() {
580
                initializeDriverManager();
581

    
582
                return driverManager;
583
        }
584

    
585
        /**
586
         * Devuelve el WriterManager.
587
         *
588
         * @return WriterManager.
589
         */
590
        public static WriterManager getWM() {
591
                initializeWriterManager();
592

    
593
                return writerManager;
594
        }
595

    
596
        /**
597
         * Inicializa el DriverManager.
598
         */
599
        private static void initializeDriverManager() {
600
                if (driverManager == null) {
601
                        driverManager = new DriverManager();
602
                        driverManager.loadDrivers(new File(LayerFactory.driversPath));
603

    
604
                        Throwable[] failures = driverManager.getLoadFailures();
605

    
606
                        for (int i = 0; i < failures.length; i++) {
607
                                logger.error("", failures[i]);
608
                        }
609

    
610
                        getDataSourceFactory().setDriverManager(driverManager);
611
                        getDataSourceFactory().initialize();
612
                        QueryManager.registerQuery(new ArcJoin());
613
                }
614
        }
615

    
616
        /**
617
         * Inicializa el DriverManager.
618
         */
619
        private static void initializeWriterManager() {
620
                if (writerManager == null) {
621
                        writerManager = new WriterManager();
622
                        writerManager.loadWriters(new File(LayerFactory.writersPath));
623

    
624
                        Throwable[] failures = writerManager.getLoadFailures();
625

    
626
                        for (int i = 0; i < failures.length; i++) {
627
                                logger.error("", failures[i]);
628
                        }
629

    
630
                        getDataSourceFactory().setWriterManager(writerManager);
631
                        getDataSourceFactory().initialize();
632
                        // QueryManager.registerQuery(new ArcJoin());
633
                }
634
        }
635

    
636
        /**
637
         * sets drivers Directory
638
         *
639
         * @param path
640
         */
641
        public static void setDriversPath(String path) {
642
                LayerFactory.driversPath = path;
643
                initializeDriverManager();
644
        }
645

    
646
        /**
647
         * sets writers Directory
648
         *
649
         * @param path
650
         */
651
        public static void setWritersPath(String path) {
652
                LayerFactory.writersPath = path;
653
                initializeWriterManager();
654
        }
655

    
656
        /**
657
         * @return Returns the dataSourceFactory.
658
         */
659
        public static DataSourceFactory getDataSourceFactory() {
660
                if (dataSourceFactory == null) {
661
                        dataSourceFactory = new DataSourceFactory();
662
                }
663
                return dataSourceFactory;
664
        }
665

    
666
        public static void initialize() {
667
                initializeDriverManager();
668
                initializeWriterManager();
669
        }
670

    
671
        /**
672
         * Set a class to use instead of the originalLayerClassName.
673
         *
674
         * @param originalLayerClassName name of class to relpace
675
         * @param layerClassToUse Class than implements FLayer interface to use
676
         *
677
         * @see  getLayerClassForLayerClassName(String,Class)
678
         * @see  unregisterLayerClassForName(String)
679
        */
680
        public static void registerLayerClassForName (String originalLayerClassName, Class layerClassToUse){
681
                Class[] interfaces = layerClassToUse.getInterfaces();
682
                for (int i = 0;i < interfaces.length; i++){
683
                        if (interfaces[i] == FLayer.class)
684
                                break;
685
                }
686

    
687
                layerClassMapping.put(originalLayerClassName,layerClassToUse);
688
        }
689

    
690
        /**
691
         * Unregister the originalLayerClassName class replacement.
692
         *
693
         * @param originalLayerClassName name of class to relpace
694
         * @param layerClassToUse Class than implements FLayer interface to use
695
         * @return true if the class had been registered
696
         *
697
         * @see  getLayerClassForLayerClassName(String,Class)
698
         * @see  unregisterLayerClassForName(String)
699
        */
700
        public static boolean unregisterLayerClassForName (String originalLayerClassName){
701
                return layerClassMapping.remove(originalLayerClassName) != null;
702
        }
703

    
704
        /**
705
         * Gets the class to use for the layerClassName.
706
         * If isn't registered an alternative class for this layerClass
707
         * the this returns 'Class.forName(layerClassName)'
708
         *
709
         * @param layerClassName
710
         * @return Class implements FLayer to use
711
         * @throws ClassNotFoundException
712
         *
713
         * @see  registerLayerClassForName(String,Class)
714
         * @see  unregisterLayerClassForName(String)
715
         */
716
        public static Class getLayerClassForLayerClassName(String layerClassName) throws ClassNotFoundException{
717
                Class layerClass = (Class)layerClassMapping.get(layerClassName);
718
                if (layerClass == null)
719
                        layerClass = Class.forName(layerClassName);
720
                return layerClass;
721
        }
722
}