Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.compat.cdc / org.gvsig.fmap.mapcontext / org.gvsig.fmap.mapcontext.api / src / main / java / org / gvsig / fmap / mapcontext / impl / DefaultMapContextManager.java @ 42879

History | View | Annotate | Download (30.4 KB)

1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or modify it under
7
 * the terms of the GNU General Public License as published by the Free Software
8
 * Foundation; either version 3 of the License, or (at your option) any later
9
 * version.
10
 *
11
 * This program is distributed in the hope that it will be useful, but WITHOUT
12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14
 * details.
15
 *
16
 * You should have received a copy of the GNU General Public License along with
17
 * this program; if not, write to the Free Software Foundation, Inc., 51
18
 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19
 *
20
 * For any additional information, do not hesitate to contact us at info AT
21
 * gvsig.com, or visit our website www.gvsig.com.
22
 */
23
package org.gvsig.fmap.mapcontext.impl;
24

    
25
import java.awt.Color;
26
import java.awt.Font;
27
import java.io.File;
28
import java.io.FileFilter;
29
import java.io.FileInputStream;
30
import java.io.FileNotFoundException;
31
import java.io.IOException;
32
import java.lang.reflect.InvocationTargetException;
33
import java.lang.reflect.Method;
34
import java.util.ArrayList;
35
import java.util.Collections;
36
import java.util.HashMap;
37
import java.util.Iterator;
38
import java.util.List;
39
import java.util.Map;
40

    
41
import org.cresques.cts.IProjection;
42
import org.gvsig.fmap.crs.CRSFactory;
43
import org.gvsig.fmap.dal.DataServerExplorer;
44
import org.gvsig.fmap.dal.DataStore;
45
import org.gvsig.fmap.dal.DataStoreParameters;
46
import org.gvsig.fmap.dal.exception.DataException;
47
import org.gvsig.fmap.dal.feature.FeatureStore;
48
import org.gvsig.fmap.dal.feature.FeatureType;
49
import org.gvsig.fmap.mapcontext.MapContext;
50
import org.gvsig.fmap.mapcontext.MapContextDrawer;
51
import org.gvsig.fmap.mapcontext.MapContextException;
52
import org.gvsig.fmap.mapcontext.MapContextLocator;
53
import org.gvsig.fmap.mapcontext.MapContextManager;
54
import org.gvsig.fmap.mapcontext.MapContextRuntimeException;
55
import org.gvsig.fmap.mapcontext.ViewPort;
56
import org.gvsig.fmap.mapcontext.exceptions.LoadLayerException;
57
import org.gvsig.fmap.mapcontext.layers.FLayer;
58
import org.gvsig.fmap.mapcontext.layers.LayerFactory;
59
import org.gvsig.fmap.mapcontext.layers.vectorial.GraphicLayer;
60
import org.gvsig.fmap.mapcontext.layers.vectorial.impl.DefaultGraphicLayer;
61
import org.gvsig.fmap.mapcontext.rendering.legend.ILegend;
62
import org.gvsig.fmap.mapcontext.rendering.legend.IVectorLegend;
63
import org.gvsig.fmap.mapcontext.rendering.legend.IVectorialUniqueValueLegend;
64
import org.gvsig.fmap.mapcontext.rendering.legend.driver.ILegendReader;
65
import org.gvsig.fmap.mapcontext.rendering.legend.driver.ILegendWriter;
66
import org.gvsig.fmap.mapcontext.rendering.legend.styling.ILabelingStrategy;
67
import org.gvsig.fmap.mapcontext.rendering.symbols.IMultiLayerSymbol;
68
import org.gvsig.fmap.mapcontext.rendering.symbols.ISymbol;
69
import org.gvsig.fmap.mapcontext.rendering.symbols.IWarningSymbol;
70
import org.gvsig.fmap.mapcontext.rendering.symbols.SymbolException;
71
import org.gvsig.fmap.mapcontext.rendering.symbols.SymbolManager;
72
import org.gvsig.fmap.mapcontext.rendering.symbols.SymbolPreferences;
73
import org.gvsig.tools.ToolsLocator;
74
import org.gvsig.tools.dispose.DisposeUtils;
75
import org.gvsig.tools.dynobject.exception.DynMethodException;
76
import org.gvsig.tools.dynobject.exception.DynMethodNotSupportedException;
77
import org.gvsig.tools.observer.Notification;
78
import org.gvsig.tools.observer.ObservableHelper;
79
import org.gvsig.tools.observer.Observer;
80
import org.gvsig.tools.persistence.PersistenceManager;
81
import org.slf4j.Logger;
82
import org.slf4j.LoggerFactory;
83

    
84
/**
85
 * Default implementation of the {@link MapContextManager}.
86
 *
87
 * @author <a href="mailto:cordinyana@gvsig.org">C?sar Ordi?ana</a>
88
 */
89
public class DefaultMapContextManager implements MapContextManager {
90

    
91
    private static final Logger logger = LoggerFactory
92
            .getLogger(DefaultMapContextManager.class);
93

    
94
    private Class drawerClazz = DefaultMapContextDrawer.class;
95

    
96
    private Map legends = Collections.synchronizedMap(new HashMap());
97

    
98
    private Map legendReaders = Collections.synchronizedMap(new HashMap());
99

    
100
    private Map legendWriters = Collections.synchronizedMap(new HashMap());
101

    
102
    private String defaultVectorLegend;
103

    
104
    private ObservableHelper observableHelper = new ObservableHelper();
105

    
106
    private File colorTableLibraryFolder = null;
107

    
108
    public MapContext createMapContext() {
109
        MapContext mapcontext = new MapContext(new ViewPort());
110
        return (MapContext) notifyObservers(CREATE_MAPCONTEXT, mapcontext).getValue();
111
    }
112

    
113
    public SymbolManager getSymbolManager() {
114
        return MapContextLocator.getSymbolManager();
115
    }
116

    
117
    private SymbolPreferences getSymbolPreferences() {
118
        return getSymbolManager().getSymbolPreferences();
119
    }
120

    
121
    public String getSymbolLibraryPath() {
122
        return getSymbolPreferences().getSymbolLibraryPath();
123
    }
124

    
125
    public void setSymbolLibraryPath(String symbolLibraryPath) {
126
        getSymbolPreferences().setSymbolLibraryPath(symbolLibraryPath);
127
    }
128

    
129
    public void resetSymbolLibraryPath() {
130
        getSymbolPreferences().resetSymbolLibraryPath();
131
    }
132

    
133
    public Color getDefaultSymbolColor() {
134
        return getSymbolPreferences().getDefaultSymbolColor();
135
    }
136

    
137
    public Color getDefaultSymbolFillColor() {
138
        return getSymbolPreferences().getDefaultSymbolFillColor();
139
    }
140

    
141
    public Font getDefaultSymbolFont() {
142
        return getSymbolPreferences().getDefaultSymbolFont();
143
    }
144

    
145
    public String getSymbolFileExtension() {
146
        return getSymbolPreferences().getSymbolFileExtension();
147
    }
148

    
149
    public boolean isDefaultSymbolFillColorAleatory() {
150
        return getSymbolPreferences().isDefaultSymbolFillColorAleatory();
151
    }
152

    
153
    public void resetDefaultSymbolColor() {
154
        getSymbolPreferences().resetDefaultSymbolColor();
155
    }
156

    
157
    public void resetDefaultSymbolFillColor() {
158
        getSymbolPreferences().resetDefaultSymbolFillColor();
159
    }
160

    
161
    public void resetDefaultSymbolFillColorAleatory() {
162
        getSymbolPreferences().resetDefaultSymbolFillColorAleatory();
163
    }
164

    
165
    public void resetDefaultSymbolFont() {
166
        getSymbolPreferences().resetDefaultSymbolFont();
167
    }
168

    
169
    public void setDefaultSymbolColor(Color defaultSymbolColor) {
170
        getSymbolPreferences().setDefaultSymbolColor(defaultSymbolColor);
171
    }
172

    
173
    public void setDefaultSymbolFillColor(Color defaultSymbolFillColor) {
174
        getSymbolPreferences().setDefaultSymbolFillColor(defaultSymbolFillColor);
175
    }
176

    
177
    public void setDefaultSymbolFillColorAleatory(
178
            boolean defaultSymbolFillColorAleatory) {
179
        getSymbolPreferences().setDefaultSymbolFillColorAleatory(
180
                defaultSymbolFillColorAleatory);
181
    }
182

    
183
    public void setDefaultSymbolFont(Font defaultSymbolFont) {
184
        getSymbolPreferences().setDefaultSymbolFont(defaultSymbolFont);
185
    }
186

    
187
    public void setSymbolFileExtension(String extension) {
188
        getSymbolPreferences().setSymbolFileExtension(extension);
189
    }
190

    
191
    public int getDefaultCartographicSupportMeasureUnit() {
192
        return getSymbolPreferences().getDefaultCartographicSupportMeasureUnit();
193
    }
194

    
195
    public void setDefaultCartographicSupportMeasureUnit(
196
            int defaultCartographicSupportMeasureUnit) {
197
        getSymbolPreferences().setDefaultCartographicSupportMeasureUnit(
198
                defaultCartographicSupportMeasureUnit);
199
    }
200

    
201
    public int getDefaultCartographicSupportReferenceSystem() {
202
        return getSymbolPreferences().getDefaultCartographicSupportReferenceSystem();
203
    }
204

    
205
    public void setDefaultCartographicSupportReferenceSystem(
206
            int defaultCartographicSupportReferenceSystem) {
207
        getSymbolPreferences().setDefaultCartographicSupportReferenceSystem(
208
                defaultCartographicSupportReferenceSystem);
209
    }
210

    
211
    public MapContextDrawer createMapContextDrawerInstance(Class drawerClazz)
212
            throws MapContextException {
213
        return createMapContextDrawerInstance(drawerClazz, "NONE");
214
    }
215

    
216
    public MapContextDrawer createDefaultMapContextDrawerInstance()
217
            throws MapContextException {
218

    
219
        return createMapContextDrawerInstance(drawerClazz, "default");
220
    }
221

    
222
    private MapContextDrawer createMapContextDrawerInstance(Class drawerClazz,
223
            String name) throws RegisteredClassInstantiationException {
224
        try {
225
            MapContextDrawer drawer = (MapContextDrawer) drawerClazz.newInstance();
226
            notifyObservers(CREATE_MAPCONTEXT_DRAWER, drawer);
227
            return drawer;
228
        } catch (Exception ex) {
229
            throw new RegisteredClassInstantiationException(
230
                    MapContextDrawer.class, drawerClazz, name, ex);
231
        }
232
    }
233

    
234
    public void setDefaultMapContextDrawer(Class drawerClazz)
235
            throws MapContextException {
236

    
237
        validateMapContextDrawer(drawerClazz);
238
        this.drawerClazz = drawerClazz;
239
        notifyObservers(SET_MAPCONTEXT_DRAWER, drawerClazz);
240
    }
241

    
242
    public void validateMapContextDrawer(Class drawerClazz)
243
            throws MapContextException {
244
        if (!MapContextDrawer.class.isAssignableFrom(drawerClazz)) {
245
            throw new InvalidRegisteredClassException(MapContextDrawer.class,
246
                    drawerClazz, "UNKNOWN");
247
        }
248
    }
249

    
250
    public GraphicLayer createGraphicsLayer(IProjection projection) {
251
        DefaultGraphicLayer layer = new DefaultGraphicLayer();
252
        try {
253
            layer.initialize(projection);
254
            layer.setLegend((IVectorLegend) createLegend(IVectorialUniqueValueLegend.LEGEND_NAME));
255
        } catch (Exception e) {
256
            logger.error("Error initializing the graphics layer", e);
257
        }
258
        return (GraphicLayer) notifyObservers(CREATE_GRAPHICS_LAYER, layer).getValue();
259
    }
260

    
261
    public String getDefaultVectorLegend() {
262
        return defaultVectorLegend;
263
    }
264

    
265
    public void setDefaultVectorLegend(String defaultVectorLegend) {
266
        this.defaultVectorLegend = defaultVectorLegend;
267
    }
268

    
269
    public void registerLegend(String legendName, Class legendClass)
270
            throws MapContextRuntimeException {
271

    
272
        if (legendClass == null || !ILegend.class.isAssignableFrom(legendClass)) {
273
            throw new InvalidRegisteredClassException(ILegend.class,
274
                    legendClass, legendName);
275
        }
276

    
277
        legends.put(legendName, legendClass);
278
        notifyObservers(REGISTER_LEGEND, legendName, legendClass);
279
    }
280

    
281
    public ILegend createLegend(String legendName)
282
            throws MapContextRuntimeException {
283
        Class legendClass = (Class) legends.get(legendName);
284

    
285
        if (legendClass != null) {
286
            try {
287
                ILegend legend = (ILegend) legendClass.newInstance();
288
                return (ILegend) notifyObservers(CREATE_LEGEND, legend).getValue();
289
            } catch (InstantiationException e) {
290
                throw new RegisteredClassInstantiationException(ILegend.class,
291
                        legendClass, legendName, e);
292
            } catch (IllegalAccessException e) {
293
                throw new RegisteredClassInstantiationException(ILegend.class,
294
                        legendClass, legendName, e);
295
            }
296
        }
297
        return null;
298
    }
299

    
300
    public IVectorLegend createDefaultVectorLegend(int shapeType)
301
            throws MapContextRuntimeException {
302
        try {
303
            // Create legend
304
            IVectorLegend legend
305
                    = (IVectorLegend) createLegend(getDefaultVectorLegend());
306
            if (legend == null) {
307
                return null;
308
            }
309
            // Set legend values
310
            legend.setShapeType(shapeType);
311
            ISymbol symbol = getSymbolManager().createSymbol(shapeType);
312
            if (symbol == null) {
313
                String msg = "Can't create a legend for the shape type " + shapeType + ". The type can be incorrect or there is not registered a symbol by default for that value. If this a was obtained from the store settings, review your FeatureType have correctly configured this value.";
314
                throw new RuntimeException(msg);
315
            }
316
            legend.setDefaultSymbol(symbol);
317
            return legend;
318
        } catch (Exception e) {
319
            throw new MapContextRuntimeException(e);
320
        }
321
    }
322

    
323
    // =============================================================
324
    // Legend reading/writing
325
    public void registerLegendReader(String format, Class readerClass)
326
            throws MapContextRuntimeException {
327
        if (readerClass == null
328
                || !ILegendReader.class.isAssignableFrom(readerClass)) {
329
            throw new InvalidRegisteredClassException(ILegendReader.class,
330
                    readerClass, format);
331
        }
332

    
333
        legendReaders.put(format, readerClass);
334
        notifyObservers(REGISTER_LEGEND_READER, format, readerClass);
335
    }
336

    
337
    public ILegendReader createLegendReader(String format)
338
            throws MapContextRuntimeException {
339
        Class legendReaderClazz = (Class) legendReaders.get(format);
340

    
341
        if (legendReaderClazz != null) {
342
            try {
343
                ILegendReader reader = (ILegendReader) legendReaderClazz.newInstance();
344
                return (ILegendReader) notifyObservers(CREATE_LEGEND_READER, reader).getValue();
345
            } catch (InstantiationException e) {
346
                throw new RegisteredClassInstantiationException(
347
                        ILegendReader.class, legendReaderClazz, format, e);
348
            } catch (IllegalAccessException e) {
349
                throw new RegisteredClassInstantiationException(
350
                        ILegendReader.class, legendReaderClazz, format, e);
351
            }
352
        }
353
        return null;
354
    }
355

    
356
    public void registerLegendWriter(Class legendClass, String format,
357
            Class writerClass) throws MapContextRuntimeException {
358
        if (writerClass == null
359
                || !ILegendWriter.class.isAssignableFrom(writerClass)
360
                || legendClass == null
361
                || !ILegend.class.isAssignableFrom(legendClass)) {
362

    
363
            throw new InvalidRegisteredClassException(ILegendWriter.class,
364
                    writerClass, format.concat("-").concat(
365
                            legendClass == null ? "Null" : legendClass.getName()));
366
        }
367

    
368
        Map legendFormatWriters = (Map) legendWriters.get(format);
369

    
370
        synchronized (legendWriters) {
371
            if (legendFormatWriters == null) {
372
                legendFormatWriters = Collections.synchronizedMap(new HashMap());
373
                legendWriters.put(format, legendFormatWriters);
374
            }
375
        }
376
        legendFormatWriters.put(legendClass, writerClass);
377
        notifyObservers(REGISTER_LEGEND_WRITER, format, writerClass);
378
    }
379

    
380
    public ILegendWriter createLegendWriter(Class legendClass, String format)
381
            throws MapContextRuntimeException {
382

    
383
        if (legendClass == null || format == null) {
384
            return null;
385
        }
386

    
387
        Map legendFormatWriters = getLegendWritersForFormat(format);
388

    
389
        if (legendFormatWriters != null) {
390
            Class legendWriterClazz = (Class) legendFormatWriters
391
                    .get(legendClass);
392

    
393
            if (legendWriterClazz != null) {
394
                /*
395
                 * Found exact match
396
                 */
397
                try {
398
                    ILegendWriter writer = (ILegendWriter) legendWriterClazz.newInstance();
399
                    return (ILegendWriter) notifyObservers(CREATE_LEGEND_READER, writer).getValue();
400
                } catch (InstantiationException e) {
401
                    throw new RegisteredClassInstantiationException(
402
                            ILegendWriter.class, legendWriterClazz, format
403
                            .concat("-").concat(
404
                                    legendClass == null ? "Null" : legendClass.getName()), e);
405
                } catch (IllegalAccessException e) {
406
                    throw new RegisteredClassInstantiationException(
407
                            ILegendWriter.class, legendWriterClazz, format
408
                            .concat("-").concat(
409
                                    legendClass == null ? "Null" : legendClass.getName()), e);
410
                }
411
            } else {
412
                /*
413
                 * Trying to find superclass/superinterface of parameter
414
                 */
415
                try {
416
                    return getSuperClassLegendWriter(legendFormatWriters, legendClass);
417
                } catch (Exception exc) {
418
                    throw new MapContextRuntimeException(exc);
419
                }
420
            }
421
        }
422
        return null;
423
    }
424

    
425
    private ILegendWriter getSuperClassLegendWriter(Map clsToWtr, Class legclass)
426
            throws Exception {
427

    
428
        if (!ILegend.class.isAssignableFrom(legclass)) {
429
            // Class is not a legend
430
            return null;
431
        }
432

    
433
        Iterator kiter = clsToWtr.keySet().iterator();
434
        Object oitem = null;
435
        Class citem = null;
436
        while (kiter.hasNext()) {
437
            oitem = kiter.next();
438
            if (oitem instanceof Class) {
439
                citem = (Class) oitem;
440
                if (citem.isAssignableFrom(legclass)) {
441
                    /*
442
                     * Found superclass/superinterface
443
                     */
444
                    citem = (Class) clsToWtr.get(oitem);
445
                    return (ILegendWriter) citem.newInstance();
446
                }
447
            }
448
        }
449
        /*
450
         * No superclass/superinterface found
451
         */
452
        return null;
453
    }
454

    
455
    private Map getLegendWritersForFormat(String format) {
456
        return (Map) legendWriters.get(format);
457
    }
458

    
459
    public List getLegendReadingFormats() {
460
        List resp = new ArrayList();
461
        Iterator iter = legendReaders.keySet().iterator();
462
        while (iter.hasNext()) {
463
            resp.add(iter.next());
464
        }
465
        return resp;
466
    }
467

    
468
    public List getLegendWritingFormats() {
469
        List resp = new ArrayList();
470
        Iterator iter = legendWriters.keySet().iterator();
471
        while (iter.hasNext()) {
472
            resp.add(iter.next());
473
        }
474
        return resp;
475
    }
476
    // =============================================================
477

    
478
    public IMultiLayerSymbol createMultiLayerSymbol(int shapeType)
479
            throws MapContextRuntimeException {
480
        IMultiLayerSymbol symbol = getSymbolManager().createMultiLayerSymbol(shapeType);
481
        return (IMultiLayerSymbol) notifyObservers(CREATE_SYMBOL, symbol).getValue();
482
    }
483

    
484
    public IMultiLayerSymbol createMultiLayerSymbol(String symbolName)
485
            throws MapContextRuntimeException {
486
        IMultiLayerSymbol symbol = getSymbolManager().createMultiLayerSymbol(symbolName);
487
        return (IMultiLayerSymbol) notifyObservers(CREATE_SYMBOL, symbol).getValue();
488
    }
489

    
490
    public ISymbol createSymbol(int shapeType, Color color)
491
            throws MapContextRuntimeException {
492
        ISymbol symbol = getSymbolManager().createSymbol(shapeType, color);
493
        return (ISymbol) notifyObservers(CREATE_SYMBOL, symbol).getValue();
494
    }
495

    
496
    public ISymbol createSymbol(int shapeType)
497
            throws MapContextRuntimeException {
498
        ISymbol symbol = getSymbolManager().createSymbol(shapeType);
499
        return (ISymbol) notifyObservers(CREATE_SYMBOL, symbol).getValue();
500
    }
501

    
502
    public ISymbol createSymbol(String symbolName, Color color)
503
            throws MapContextRuntimeException {
504
        ISymbol symbol = getSymbolManager().createSymbol(symbolName, color);
505
        return (ISymbol) notifyObservers(CREATE_SYMBOL, symbol).getValue();
506
    }
507

    
508
    public ISymbol createSymbol(String symbolName)
509
            throws MapContextRuntimeException {
510
        ISymbol symbol = getSymbolManager().createSymbol(symbolName);
511
        return (ISymbol) notifyObservers(CREATE_SYMBOL, symbol).getValue();
512
    }
513

    
514
    public IWarningSymbol getWarningSymbol(String message, String symbolDesc,
515
            int symbolDrawExceptionType) throws MapContextRuntimeException {
516
        return getSymbolManager().getWarningSymbol(message, symbolDesc,
517
                symbolDrawExceptionType);
518
    }
519

    
520
    public ISymbol[] loadSymbols(File folder, FileFilter filter)
521
            throws SymbolException {
522
        ISymbol[] symbols = getSymbolManager().loadSymbols(folder, filter);
523
        return (ISymbol[]) notifyObservers(LOAD_SYMBOLS, symbols).getValue();
524
    }
525

    
526
    public ISymbol[] loadSymbols(File folder) throws SymbolException {
527
        ISymbol[] symbols = getSymbolManager().loadSymbols(folder);
528
        return (ISymbol[]) notifyObservers(LOAD_SYMBOLS, symbols).getValue();
529
    }
530

    
531
    public void registerMultiLayerSymbol(String symbolName, Class symbolClass)
532
            throws MapContextRuntimeException {
533
        getSymbolManager().registerMultiLayerSymbol(symbolName, symbolClass);
534
        notifyObservers(REGISTER_MULTILAYER_SYMBOL, symbolName, symbolClass);
535
    }
536

    
537
    public void registerMultiLayerSymbol(String symbolName, int[] shapeTypes,
538
            Class symbolClass) throws MapContextRuntimeException {
539
        getSymbolManager().registerMultiLayerSymbol(symbolName, shapeTypes,
540
                symbolClass);
541
        notifyObservers(REGISTER_MULTILAYER_SYMBOL, symbolName, symbolClass, shapeTypes);
542
    }
543

    
544
    public void registerSymbol(String symbolName, Class symbolClass)
545
            throws MapContextRuntimeException {
546
        getSymbolManager().registerSymbol(symbolName, symbolClass);
547
        notifyObservers(REGISTER_SYMBOL, symbolName, symbolClass);
548
    }
549

    
550
    public void registerSymbol(String symbolName, int[] shapeTypes,
551
            Class symbolClass) throws MapContextException {
552
        getSymbolManager().registerSymbol(symbolName, shapeTypes, symbolClass);
553
        notifyObservers(REGISTER_SYMBOL, symbolName, symbolClass, shapeTypes);
554
    }
555

    
556
    public void saveSymbol(ISymbol symbol, String fileName, File folder,
557
            boolean overwrite) throws SymbolException {
558
        getSymbolManager().saveSymbol(symbol, fileName, folder, overwrite);
559
    }
560

    
561
    public void saveSymbol(ISymbol symbol, String fileName, File folder)
562
            throws SymbolException {
563
        getSymbolManager().saveSymbol(symbol, fileName, folder);
564
    }
565

    
566
    public FLayer createLayer(String layerName, DataStoreParameters parameters)
567
            throws LoadLayerException {
568
        FLayer layer = LayerFactory.getInstance().createLayer(layerName, parameters);
569
        return (FLayer) notifyObservers(CREATE_LAYER, layer).getValue();
570
    }
571

    
572
    public FLayer createLayer(String layerName, DataStore store)
573
            throws LoadLayerException {
574
        FLayer layer = LayerFactory.getInstance().createLayer(layerName, store);
575
        return (FLayer) notifyObservers(CREATE_LAYER, layer).getValue();
576
    }
577

    
578
    public ILegend getLegend(DataStore dataStore) {
579
        ILegend legend = null;
580

    
581
        File file = getResourcePath(dataStore, SymbolManager.LEGEND_FILE_EXTENSION.substring(1));
582
        try {
583
            if ((file != null) && (file.exists())) {
584
                PersistenceManager persistenceManager = ToolsLocator.getPersistenceManager();
585
                FileInputStream is = new FileInputStream(file);
586
                legend = (ILegend) persistenceManager.getObject(is);
587
                is.close();
588
            }
589
        } catch (FileNotFoundException e) {
590
            logger.error("Legend not found", e);
591
        } catch (IOException e) {
592
            logger.error("Error reading the legend", e);
593
        }
594

    
595
        //If the legend is null, next option is to check if the store has the getLegend method
596
        if (legend == null) {
597
            try {
598
                legend = (IVectorLegend) dataStore.invokeDynMethod("getLegend", null);
599
            } catch (DynMethodNotSupportedException e) {
600
                logger.debug("This store {} does not provide a legend.",
601
                        dataStore.getName());
602
            } catch (DynMethodException e) {
603
                logger.error(
604
                        "Can't load the specific legend provided for the store {}.",
605
                        dataStore.getName(), e);
606
            }
607
        }
608

    
609
        //If legend is null, last step is just try to create the legend by default
610
        if (legend == null) {
611
            FeatureType featureType;
612
            try {
613
                featureType = (((FeatureStore) dataStore).getDefaultFeatureType());
614
                int indexGeom = featureType.getDefaultGeometryAttributeIndex();
615
                if (indexGeom < 0) {
616
                    throw new IllegalArgumentException("The layer don't has a geometry column.");
617
                }
618
                int typeShape = featureType.getAttributeDescriptor(indexGeom).getGeometryType();
619
                legend = createDefaultVectorLegend(typeShape);
620
            } catch (DataException e) {
621
                logger.error("Error getting the default feature type", e);
622
            }
623
        }
624

    
625
        return legend;
626
    }
627

    
628
    public ILabelingStrategy getLabelingStrategy(DataStore dataStore) {
629
        ILabelingStrategy labelingStrategy = null;
630

    
631
        File file = getResourcePath(dataStore, SymbolManager.LABELINGSTRATEGY_FILE_EXTENSION.substring(1));
632
        try {
633
            if ((file != null) && (file.exists())) {
634
                PersistenceManager persistenceManager = ToolsLocator.getPersistenceManager();
635
                FileInputStream is = new FileInputStream(file);
636
                labelingStrategy = (ILabelingStrategy) persistenceManager.getObject(is);
637
                is.close();
638
            }
639
        } catch (FileNotFoundException e) {
640
            logger.error("Label strategy not found", e);
641
        } catch (IOException e) {
642
            logger.error("Error reading the labeling strategy", e);
643
        }
644

    
645
        //If the legend is null, next option is to check if the store has the getLegend method
646
        if (labelingStrategy == null) {
647
            try {
648
                labelingStrategy
649
                        = (ILabelingStrategy) dataStore.invokeDynMethod("getLabeling",
650
                                null);
651
            } catch (DynMethodNotSupportedException e1) {
652
                labelingStrategy = null;
653
            } catch (DynMethodException e1) {
654
                logger.error("Can't load the specific lebeling strategy provided for the datastore {}.",
655
                        dataStore.getName(),
656
                        e1);
657
            }
658
        }
659

    
660
        return labelingStrategy;
661
    }
662

    
663
    private Object call(Object instance, String methodName, Class[] signature, Object[] params) {
664
        try {
665
            Method method = instance.getClass().getMethod(methodName, signature);
666
            if (method == null) {
667
                return null;
668
            }
669
            Object value = method.invoke(instance, params);
670
            return value;
671
        } catch (NoSuchMethodException ex) {
672
            return null;
673
        } catch (SecurityException ex) {
674
            return null;
675
        } catch (IllegalAccessException ex) {
676
            return null;
677
        } catch (IllegalArgumentException ex) {
678
            return null;
679
        } catch (InvocationTargetException ex) {
680
            return null;
681
        }
682
    }
683

    
684
    private File getResourcePath(DataStore dataStore, String resource) {
685
        //Loading the file from a store based on file
686
        DataServerExplorer explorer = null;
687
        try {
688
            explorer = dataStore.getExplorer();
689
            if (explorer == null) {
690
                return null;
691
            }
692
            return explorer.getResourcePath(dataStore, resource);
693
        } catch (Exception e) {
694
            logger.warn(
695
                    "Can't locate a specific legend provided by the explorer "
696
                    + explorer, e);
697
            return null;
698
        } finally {
699
            DisposeUtils.disposeQuietly(explorer);
700
        }
701
    }
702

    
703
    private Map iconLayers = new HashMap(); //  (Map<String storeProviderName, String iconName>)
704

    
705
    public void registerIconLayer(String storeProviderName, String iconName) {
706
        if (storeProviderName == null || iconName == null) {
707
            logger.info("registerIconLayer, storeProviderName or iconName are null");
708
            return;
709
        }
710
        String storeName = storeProviderName.trim().toLowerCase();
711
        if (storeName.length() == 0 || iconName.trim().length() == 0) {
712
            logger.info("registerIconLayer, invalid storeProviderName or iconName");
713
            return;
714
        }
715
        iconLayers.put(storeName, iconName);
716
        notifyObservers(REGISTER_ICON_LAYER, storeName, iconName);
717
    }
718

    
719
    public String getIconLayer(DataStore store) {
720
        String name = (String) iconLayers.get(store.getProviderName().trim().toLowerCase());
721
        if (name == null) {
722
            return "layer-icon";
723
        }
724
        return name;
725
    }
726

    
727
    /* (non-Javadoc)
728
     * @see org.gvsig.fmap.mapcontext.MapContextManager#getDefaultCRS()
729
     */
730
    public IProjection getDefaultCRS() {
731
        IProjection crs = CRSFactory.getCRS("EPSG:4326");
732
        return (IProjection) notifyObservers(GET_DEFAULT_CRS, crs).getValue();
733
    }
734

    
735
    public Notification notifyLoadMapContext(MapContext mapContext) {
736
        return this.observableHelper.notifyObservers(this, LOAD_MAPCONTEXT, mapContext);
737
    }
738

    
739
    public Notification notifyLoadLayer(FLayer layer) {
740
        return this.observableHelper.notifyObservers(this, LOAD_LAYER, layer);
741
    }
742

    
743
    public void addObserver(Observer o) {
744
        this.observableHelper.addObserver(o);
745
    }
746

    
747
    public void deleteObserver(Observer o) {
748
        this.observableHelper.deleteObserver(o);
749
    }
750

    
751
    public void deleteObservers() {
752
        this.observableHelper.deleteObservers();
753
    }
754

    
755
    protected Notification notifyObservers(String type, Object value) {
756
        return this.observableHelper.notifyObservers(this, type, value);
757
    }
758

    
759
    protected Notification notifyObservers(String type, Object value1, Object value2) {
760
        return this.observableHelper.notifyObservers(this, type, value1, value2);
761
    }
762

    
763
    protected Notification notifyObservers(String type, Object value1, Object value2, Object value3) {
764
        return this.observableHelper.notifyObservers(this, type, value1, value2, value3);
765
    }
766

    
767
    public File getColorTableLibraryFolder() {
768
        if (this.colorTableLibraryFolder == null) {
769
            // Provide a default value to the location for the color
770
            // table library.
771
            String colorTableLibraryPath = System.getProperty("user.home")
772
                    + File.separator
773
                    + "gvSIG"
774
                    + File.separator
775
                    + "colortable";
776
            this.colorTableLibraryFolder = new File(colorTableLibraryPath);
777
        }
778
        return this.colorTableLibraryFolder;
779
    }
780

    
781
    public void setColorTableLibraryFolder(File colorTableLibraryFolder) {
782
        this.colorTableLibraryFolder = colorTableLibraryFolder;
783
    }
784

    
785
}