Statistics
| Revision:

svn-gvsig-desktop / branches / org.gvsig.desktop-2018a / org.gvsig.desktop.compat.cdc / org.gvsig.fmap.mapcontext / org.gvsig.fmap.mapcontext.api / src / main / java / org / gvsig / fmap / mapcontext / impl / DefaultMapContextManager.java @ 43876

History | View | Annotate | Download (34.5 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.HashMap;
36
import java.util.Iterator;
37
import java.util.LinkedHashMap;
38
import java.util.List;
39
import java.util.Map;
40
import org.apache.commons.io.IOUtils;
41
import org.apache.commons.lang3.StringUtils;
42

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

    
94
/**
95
 * Default implementation of the {@link MapContextManager}.
96
 *
97
 * @author <a href="mailto:cordinyana@gvsig.org">C?sar Ordi?ana</a>
98
 */
99
public class DefaultMapContextManager implements MapContextManager {
100

    
101
    private static final Logger logger = LoggerFactory
102
            .getLogger(DefaultMapContextManager.class);
103

    
104
    private Class drawerClazz = DefaultMapContextDrawer.class;
105

    
106
    private final Map<String,Class<ILegend>> legends = new HashMap();
107

    
108
    private final Map<String, Class<ILegendReader>> legendReaders = new LinkedHashMap<>();
109

    
110
    private final Map<String, Map<Class<ILegend>,Class<ILegendWriter>>> legendWriters = new LinkedHashMap<>();
111

    
112
    private String defaultVectorLegend;
113

    
114
    private ObservableHelper observableHelper = new ObservableHelper();
115

    
116
    private File colorTableLibraryFolder = null;
117
    private String defaultRasterLegend;
118

    
119
    public MapContext createMapContext() {
120
        MapContext mapcontext = new MapContext(new ViewPort());
121
        return (MapContext) notifyObservers(CREATE_MAPCONTEXT, mapcontext).getValue();
122
    }
123

    
124
    public SymbolManager getSymbolManager() {
125
        return MapContextLocator.getSymbolManager();
126
    }
127

    
128
    private SymbolPreferences getSymbolPreferences() {
129
        return getSymbolManager().getSymbolPreferences();
130
    }
131

    
132
    public String getSymbolLibraryPath() {
133
        return getSymbolPreferences().getSymbolLibraryPath();
134
    }
135

    
136
    public void setSymbolLibraryPath(String symbolLibraryPath) {
137
        getSymbolPreferences().setSymbolLibraryPath(symbolLibraryPath);
138
    }
139

    
140
    public void resetSymbolLibraryPath() {
141
        getSymbolPreferences().resetSymbolLibraryPath();
142
    }
143

    
144
    public Color getDefaultSymbolColor() {
145
        return getSymbolPreferences().getDefaultSymbolColor();
146
    }
147

    
148
    public Color getDefaultSymbolFillColor() {
149
        return getSymbolPreferences().getDefaultSymbolFillColor();
150
    }
151

    
152
    public Font getDefaultSymbolFont() {
153
        return getSymbolPreferences().getDefaultSymbolFont();
154
    }
155

    
156
    public String getSymbolFileExtension() {
157
        return getSymbolPreferences().getSymbolFileExtension();
158
    }
159

    
160
    public boolean isDefaultSymbolFillColorAleatory() {
161
        return getSymbolPreferences().isDefaultSymbolFillColorAleatory();
162
    }
163

    
164
    public void resetDefaultSymbolColor() {
165
        getSymbolPreferences().resetDefaultSymbolColor();
166
    }
167

    
168
    public void resetDefaultSymbolFillColor() {
169
        getSymbolPreferences().resetDefaultSymbolFillColor();
170
    }
171

    
172
    public void resetDefaultSymbolFillColorAleatory() {
173
        getSymbolPreferences().resetDefaultSymbolFillColorAleatory();
174
    }
175

    
176
    public void resetDefaultSymbolFont() {
177
        getSymbolPreferences().resetDefaultSymbolFont();
178
    }
179

    
180
    public void setDefaultSymbolColor(Color defaultSymbolColor) {
181
        getSymbolPreferences().setDefaultSymbolColor(defaultSymbolColor);
182
    }
183

    
184
    public void setDefaultSymbolFillColor(Color defaultSymbolFillColor) {
185
        getSymbolPreferences().setDefaultSymbolFillColor(defaultSymbolFillColor);
186
    }
187

    
188
    public void setDefaultSymbolFillColorAleatory(
189
            boolean defaultSymbolFillColorAleatory) {
190
        getSymbolPreferences().setDefaultSymbolFillColorAleatory(
191
                defaultSymbolFillColorAleatory);
192
    }
193

    
194
    public void setDefaultSymbolFont(Font defaultSymbolFont) {
195
        getSymbolPreferences().setDefaultSymbolFont(defaultSymbolFont);
196
    }
197

    
198
    public void setSymbolFileExtension(String extension) {
199
        getSymbolPreferences().setSymbolFileExtension(extension);
200
    }
201

    
202
    public int getDefaultCartographicSupportMeasureUnit() {
203
        return getSymbolPreferences().getDefaultCartographicSupportMeasureUnit();
204
    }
205

    
206
    public void setDefaultCartographicSupportMeasureUnit(
207
            int defaultCartographicSupportMeasureUnit) {
208
        getSymbolPreferences().setDefaultCartographicSupportMeasureUnit(
209
                defaultCartographicSupportMeasureUnit);
210
    }
211

    
212
    public int getDefaultCartographicSupportReferenceSystem() {
213
        return getSymbolPreferences().getDefaultCartographicSupportReferenceSystem();
214
    }
215

    
216
    public void setDefaultCartographicSupportReferenceSystem(
217
            int defaultCartographicSupportReferenceSystem) {
218
        getSymbolPreferences().setDefaultCartographicSupportReferenceSystem(
219
                defaultCartographicSupportReferenceSystem);
220
    }
221

    
222
    public MapContextDrawer createMapContextDrawerInstance(Class drawerClazz)
223
            throws MapContextException {
224
        return createMapContextDrawerInstance(drawerClazz, "NONE");
225
    }
226

    
227
    public MapContextDrawer createDefaultMapContextDrawerInstance()
228
            throws MapContextException {
229

    
230
        return createMapContextDrawerInstance(drawerClazz, "default");
231
    }
232

    
233
    private MapContextDrawer createMapContextDrawerInstance(Class drawerClazz,
234
            String name) throws RegisteredClassInstantiationException {
235
        try {
236
            MapContextDrawer drawer = (MapContextDrawer) drawerClazz.newInstance();
237
            notifyObservers(CREATE_MAPCONTEXT_DRAWER, drawer);
238
            return drawer;
239
        } catch (Exception ex) {
240
            throw new RegisteredClassInstantiationException(
241
                    MapContextDrawer.class, drawerClazz, name, ex);
242
        }
243
    }
244

    
245
    public void setDefaultMapContextDrawer(Class drawerClazz)
246
            throws MapContextException {
247

    
248
        validateMapContextDrawer(drawerClazz);
249
        this.drawerClazz = drawerClazz;
250
        notifyObservers(SET_MAPCONTEXT_DRAWER, drawerClazz);
251
    }
252

    
253
    public void validateMapContextDrawer(Class drawerClazz)
254
            throws MapContextException {
255
        if (!MapContextDrawer.class.isAssignableFrom(drawerClazz)) {
256
            throw new InvalidRegisteredClassException(MapContextDrawer.class,
257
                    drawerClazz, "UNKNOWN");
258
        }
259
    }
260

    
261
    @Override
262
    public GraphicLayer createGraphicsLayer(IProjection projection) {
263
        DefaultGraphicLayer layer = new DefaultGraphicLayer();
264
        try {
265
            layer.initialize(projection);
266
            layer.setLegend((IVectorLegend) createLegend(IVectorialUniqueValueLegend.LEGEND_NAME));
267
        } catch (Exception e) {
268
            logger.error("Error initializing the graphics layer", e);
269
        }
270
        return (GraphicLayer) notifyObservers(CREATE_GRAPHICS_LAYER, layer).getValue();
271
    }
272

    
273
    @Override
274
    public String getDefaultVectorLegend() {
275
        return defaultVectorLegend;
276
    }
277

    
278
    @Override
279
    public void setDefaultVectorLegend(String defaultVectorLegend) {
280
        this.defaultVectorLegend = defaultVectorLegend;
281
    }
282

    
283
    @Override
284
    public String getDefaultRasterLegend() {
285
        return defaultRasterLegend;
286
    }
287

    
288
    @Override
289
    public void setDefaultRasterLegend(String defaultRasterLegend) {
290
        this.defaultRasterLegend = defaultRasterLegend;
291
    }
292
    
293
    @Override
294
    public void registerLegend(String legendName, Class legendClass)
295
            throws MapContextRuntimeException {
296

    
297
        if (legendClass == null || !ILegend.class.isAssignableFrom(legendClass)) {
298
            throw new InvalidRegisteredClassException(ILegend.class,
299
                    legendClass, legendName);
300
        }
301

    
302
        legends.put(legendName, legendClass);
303
        notifyObservers(REGISTER_LEGEND, legendName, legendClass);
304
    }
305

    
306
    @Override
307
    public ILegend createLegend(String legendName)
308
            throws MapContextRuntimeException {
309
        Class legendClass = (Class) legends.get(legendName);
310

    
311
        if (legendClass != null) {
312
            try {
313
                ILegend legend = (ILegend) legendClass.newInstance();
314
                return (ILegend) notifyObservers(CREATE_LEGEND, legend).getValue();
315
            } catch (InstantiationException | IllegalAccessException e) {
316
                throw new RegisteredClassInstantiationException(ILegend.class,
317
                        legendClass, legendName, e);
318
            }
319
        }
320
        return null;
321
    }
322

    
323
    @Override
324
    public IVectorLegend createDefaultVectorLegend(int shapeType)
325
            throws MapContextRuntimeException {
326
        try {
327
            // Create legend
328
            IVectorLegend legend
329
                    = (IVectorLegend) createLegend(getDefaultVectorLegend());
330
            if (legend == null) {
331
                return null;
332
            }
333
            // Set legend values
334
            legend.setShapeType(shapeType);
335
            ISymbol symbol = getSymbolManager().createSymbol(shapeType);
336
            if (symbol == null) {
337
                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.";
338
                throw new RuntimeException(msg);
339
            }
340
            legend.setDefaultSymbol(symbol);
341
            return legend;
342
        } catch (Exception e) {
343
            throw new MapContextRuntimeException(e);
344
        }
345
    }
346

    
347
    @Override
348
    public RasterLegend createDefaultRasterLegend(List<BandDescriptor> bands)
349
            throws MapContextRuntimeException {
350
        try {
351
            // Create legend
352
            RasterLegend legend = (RasterLegend) createLegend(getDefaultRasterLegend());
353
            if (legend == null) {
354
                return null;
355
            }
356
            ColorInterpretation colorInterpretation;
357
            RasterLegendManager legendManager = RasterLegendLocator.getRasterLegendManager();
358
            switch (bands.size()) {
359
                case 3:
360
                    colorInterpretation = legendManager.createColorInterpretation(ColorInterpretation.RGB);
361
                    break;
362
                case 4:
363
                    colorInterpretation = legendManager.createColorInterpretation(ColorInterpretation.ARGB);
364
                    break;
365
                default:
366
                    String[] colorBands = new String[bands.size()];
367
                    colorBands[0] = ColorInterpretation.GRAY_BAND;
368
                    for (int i = 1; i < colorBands.length; i++) {
369
                        colorBands[i] = ColorInterpretation.UNDEFINED_BAND;
370
                    }   colorInterpretation = legendManager.createColorInterpretation(colorBands);
371
                    break;
372
            }
373
            legend.setColorInterpretation(colorInterpretation);
374
            legend.addLinearStretchEnhancementOperationIfNeeded(colorInterpretation, bands, 0);
375
            return legend;
376
        } catch (Exception e) {
377
            throw new MapContextRuntimeException(e);
378
        }
379
    }
380

    
381
    // =============================================================
382
    // Legend reading/writing
383

    
384
    private Map<Class<ILegend>,Class<ILegendWriter>> getLegendWritersForFormat(String format) {
385
        synchronized(legendWriters) {
386
            return legendWriters.get(format);
387
        }
388
    }
389

    
390
    private Class<ILegendReader> getLegendReaderForFormat(String format) {
391
        synchronized(legendReaders) {
392
            return legendReaders.get(format);
393
        }
394
    }
395

    
396
    @Override
397
    public List<String> getLegendReadingFormats() {
398
        synchronized(legendReaders) {
399
            List<String> resp = new ArrayList();
400
            resp.addAll(legendReaders.keySet());
401
            return resp;
402
        }
403
    }
404

    
405
    @Override
406
    public List<String> getLegendWritingFormats() {
407
        synchronized(legendWriters) {
408
            List<String> resp = new ArrayList();
409
            resp.addAll(legendWriters.keySet());
410
            return resp;
411
        }
412
    }
413
    
414
    @Override
415
    public void registerLegendReader(String format, Class readerClass)
416
            throws MapContextRuntimeException {
417
        if (readerClass == null
418
                || !ILegendReader.class.isAssignableFrom(readerClass)) {
419
            throw new InvalidRegisteredClassException(ILegendReader.class,
420
                    readerClass, format);
421
        }
422
        synchronized (legendReaders) {
423
            legendReaders.put(format, readerClass);
424
        }
425
        notifyObservers(REGISTER_LEGEND_READER, format, readerClass);
426
    }
427

    
428
    @Override
429
    public void registerLegendWriter(Class legendClass, String format,
430
            Class writerClass) throws MapContextRuntimeException {
431
        if (writerClass == null || legendClass == null
432
                || !ILegendWriter.class.isAssignableFrom(writerClass)
433
                || !ILegend.class.isAssignableFrom(legendClass)) {
434

    
435
            throw new InvalidRegisteredClassException(ILegendWriter.class,
436
                    writerClass, format.concat("-").concat(
437
                            legendClass == null ? "Null" : legendClass.getName()));
438
        }
439

    
440
        synchronized (legendWriters) {
441
            Map<Class<ILegend>, Class<ILegendWriter>> legendWriterOfFormat = legendWriters.get(format);
442
            if (legendWriterOfFormat == null) {
443
                legendWriterOfFormat = new LinkedHashMap();
444
                legendWriters.put(format, legendWriterOfFormat);
445
            }
446
            legendWriterOfFormat.put(legendClass, writerClass);
447
        }
448
        notifyObservers(REGISTER_LEGEND_WRITER, format, writerClass);
449
    }
450

    
451
    @Override
452
    public ILegendReader createLegendReader(String format)
453
            throws MapContextRuntimeException {
454
        Class<ILegendReader> legendReaderClazz = getLegendReaderForFormat(format);
455

    
456
        if (legendReaderClazz != null) {
457
            try {
458
                ILegendReader reader = (ILegendReader) legendReaderClazz.newInstance();
459
                return (ILegendReader) notifyObservers(CREATE_LEGEND_READER, reader).getValue();
460
            } catch (InstantiationException|IllegalAccessException e) {
461
                throw new RegisteredClassInstantiationException(
462
                        ILegendReader.class, legendReaderClazz, format, e);
463
            }
464
        }
465
        return null;
466
    }
467

    
468
    @Override
469
    public ILegendWriter createLegendWriter(Class legendClass, String format)
470
            throws MapContextRuntimeException {
471

    
472
        if (legendClass == null || format == null) {
473
            return null;
474
        }
475

    
476
        Map<Class<ILegend>, Class<ILegendWriter>> legendFormatWriters = getLegendWritersForFormat(format);
477

    
478
        if (legendFormatWriters != null) {
479
            Class<ILegendWriter> legendWriterClazz = legendFormatWriters.get(legendClass);
480
            if (legendWriterClazz != null) {
481
                /*
482
                 * Found exact match
483
                 */
484
                try {
485
                    ILegendWriter writer = (ILegendWriter) legendWriterClazz.newInstance();
486
                    return (ILegendWriter) notifyObservers(CREATE_LEGEND_READER, writer).getValue();
487
                } catch (InstantiationException|IllegalAccessException e) {
488
                    throw new RegisteredClassInstantiationException(
489
                            ILegendWriter.class, 
490
                            legendWriterClazz,
491
                            format.concat("-").concat(legendClass.getName()), 
492
                            e
493
                    );
494
                }
495
            } else {
496
                /*
497
                 * Trying to find superclass/superinterface of parameter
498
                 */
499
                try {
500
                    return getSuperClassLegendWriter(legendFormatWriters, legendClass);
501
                } catch (Exception exc) {
502
                    throw new MapContextRuntimeException(exc);
503
                }
504
            }
505
        }
506
        return null;
507
    }
508

    
509
    private ILegendWriter getSuperClassLegendWriter(Map<Class<ILegend>, Class<ILegendWriter>> clsToWtr, Class<ILegend> legclass)
510
            throws Exception {
511

    
512
        Iterator kiter = clsToWtr.keySet().iterator();
513
        Object oitem = null;
514
        Class citem = null;
515
        while (kiter.hasNext()) {
516
            oitem = kiter.next();
517
            if (oitem instanceof Class) {
518
                citem = (Class) oitem;
519
                if (citem.isAssignableFrom(legclass)) {
520
                    /*
521
                     * Found superclass/superinterface
522
                     */
523
                    citem = (Class) clsToWtr.get(oitem);
524
                    return (ILegendWriter) citem.newInstance();
525
                }
526
            }
527
        }
528
        /*
529
         * No superclass/superinterface found
530
         */
531
        return null;
532
    }
533

    
534
    // =============================================================
535

    
536
    public IMultiLayerSymbol createMultiLayerSymbol(int shapeType)
537
            throws MapContextRuntimeException {
538
        IMultiLayerSymbol symbol = getSymbolManager().createMultiLayerSymbol(shapeType);
539
        return (IMultiLayerSymbol) notifyObservers(CREATE_SYMBOL, symbol).getValue();
540
    }
541

    
542
    public IMultiLayerSymbol createMultiLayerSymbol(String symbolName)
543
            throws MapContextRuntimeException {
544
        IMultiLayerSymbol symbol = getSymbolManager().createMultiLayerSymbol(symbolName);
545
        return (IMultiLayerSymbol) notifyObservers(CREATE_SYMBOL, symbol).getValue();
546
    }
547

    
548
    public ISymbol createSymbol(int shapeType, Color color)
549
            throws MapContextRuntimeException {
550
        ISymbol symbol = getSymbolManager().createSymbol(shapeType, color);
551
        return (ISymbol) notifyObservers(CREATE_SYMBOL, symbol).getValue();
552
    }
553

    
554
    public ISymbol createSymbol(int shapeType)
555
            throws MapContextRuntimeException {
556
        ISymbol symbol = getSymbolManager().createSymbol(shapeType);
557
        return (ISymbol) notifyObservers(CREATE_SYMBOL, symbol).getValue();
558
    }
559

    
560
    public ISymbol createSymbol(String symbolName, Color color)
561
            throws MapContextRuntimeException {
562
        ISymbol symbol = getSymbolManager().createSymbol(symbolName, color);
563
        return (ISymbol) notifyObservers(CREATE_SYMBOL, symbol).getValue();
564
    }
565

    
566
    public ISymbol createSymbol(String symbolName)
567
            throws MapContextRuntimeException {
568
        ISymbol symbol = getSymbolManager().createSymbol(symbolName);
569
        return (ISymbol) notifyObservers(CREATE_SYMBOL, symbol).getValue();
570
    }
571

    
572
    public IWarningSymbol getWarningSymbol(String message, String symbolDesc,
573
            int symbolDrawExceptionType) throws MapContextRuntimeException {
574
        return getSymbolManager().getWarningSymbol(message, symbolDesc,
575
                symbolDrawExceptionType);
576
    }
577

    
578
    public ISymbol[] loadSymbols(File folder, FileFilter filter)
579
            throws SymbolException {
580
        ISymbol[] symbols = getSymbolManager().loadSymbols(folder, filter);
581
        return (ISymbol[]) notifyObservers(LOAD_SYMBOLS, symbols).getValue();
582
    }
583

    
584
    public ISymbol[] loadSymbols(File folder) throws SymbolException {
585
        ISymbol[] symbols = getSymbolManager().loadSymbols(folder);
586
        return (ISymbol[]) notifyObservers(LOAD_SYMBOLS, symbols).getValue();
587
    }
588

    
589
    public void registerMultiLayerSymbol(String symbolName, Class symbolClass)
590
            throws MapContextRuntimeException {
591
        getSymbolManager().registerMultiLayerSymbol(symbolName, symbolClass);
592
        notifyObservers(REGISTER_MULTILAYER_SYMBOL, symbolName, symbolClass);
593
    }
594

    
595
    public void registerMultiLayerSymbol(String symbolName, int[] shapeTypes,
596
            Class symbolClass) throws MapContextRuntimeException {
597
        getSymbolManager().registerMultiLayerSymbol(symbolName, shapeTypes,
598
                symbolClass);
599
        notifyObservers(REGISTER_MULTILAYER_SYMBOL, symbolName, symbolClass, shapeTypes);
600
    }
601

    
602
    public void registerSymbol(String symbolName, Class symbolClass)
603
            throws MapContextRuntimeException {
604
        getSymbolManager().registerSymbol(symbolName, symbolClass);
605
        notifyObservers(REGISTER_SYMBOL, symbolName, symbolClass);
606
    }
607

    
608
    public void registerSymbol(String symbolName, int[] shapeTypes,
609
            Class symbolClass) throws MapContextException {
610
        getSymbolManager().registerSymbol(symbolName, shapeTypes, symbolClass);
611
        notifyObservers(REGISTER_SYMBOL, symbolName, symbolClass, shapeTypes);
612
    }
613

    
614
    public void saveSymbol(ISymbol symbol, String fileName, File folder,
615
            boolean overwrite) throws SymbolException {
616
        getSymbolManager().saveSymbol(symbol, fileName, folder, overwrite);
617
    }
618

    
619
    public void saveSymbol(ISymbol symbol, String fileName, File folder)
620
            throws SymbolException {
621
        getSymbolManager().saveSymbol(symbol, fileName, folder);
622
    }
623

    
624
    public FLayer createLayer(String layerName, DataStoreParameters parameters)
625
            throws LoadLayerException {
626
        FLayer layer = LayerFactory.getInstance().createLayer(layerName, parameters);
627
        return (FLayer) notifyObservers(CREATE_LAYER, layer).getValue();
628
    }
629

    
630
    @Override
631
    public FLayer createLayer(String layerName, DataStore store)
632
            throws LoadLayerException {
633
        FLayer layer = LayerFactory.getInstance().createLayer(layerName, store);
634
        return (FLayer) notifyObservers(CREATE_LAYER, layer).getValue();
635
    }
636

    
637
    @Override
638
    public ILegend getLegend(DataStore dataStore) {
639
        ILegend legend = null;
640

    
641
        File file = getResourcePath(dataStore, SymbolManager.LEGEND_FILE_EXTENSION.substring(1));
642
        if ((file != null) && (file.exists())) {
643
            FileInputStream is = null;
644
            try {
645
                PersistenceManager persistenceManager = ToolsLocator.getPersistenceManager();
646
                is = new FileInputStream(file);
647
                legend = (ILegend) persistenceManager.getObject(is);
648
            } catch (FileNotFoundException e) {
649
                logger.warn("Legend not found", e);
650
            } finally {
651
                IOUtils.closeQuietly(is);
652
            }
653
        }
654

    
655
        //If the legend is null, next option is to check if the store has the getLegend method
656
        if (legend == null) {
657
            try {
658
                legend = (ILegend) dataStore.invokeDynMethod("getLegend", null);
659
            } catch (DynMethodNotSupportedException e) {
660
                logger.debug("This store {} does not provide a legend.", dataStore.getName());
661
            } catch (DynMethodException e) {
662
                logger.warn(
663
                        "Can't load the specific legend provided for the store {}.",
664
                        dataStore.getName(), e);
665
            }
666
        }
667

    
668
        //If legend is null, last step is just try to create the legend by default
669
        if (legend == null) {
670
            if( dataStore instanceof FeatureStore ) {
671
                FeatureType featureType;
672
                try {
673
                    featureType = (((FeatureStore) dataStore).getDefaultFeatureType());
674
                    int indexGeom = featureType.getDefaultGeometryAttributeIndex();
675
                    if (indexGeom < 0) {
676
                        throw new IllegalArgumentException("The layer don't has a geometry column.");
677
                    }
678
                    int typeShape = featureType.getAttributeDescriptor(indexGeom).getGeometryType();
679
                    legend = createDefaultVectorLegend(typeShape);
680
                } catch (DataException e) {
681
                    logger.warn("Error getting the default feature type", e);
682
                }
683
                
684
            } else if( dataStore instanceof RasterStore ) {
685
                RasterStore rasterStore = (RasterStore) dataStore;
686
                List<BandDescriptor> bands = rasterStore.getBandDescriptors();
687
                legend = createDefaultRasterLegend(bands);
688
            }
689
        }
690

    
691
        if( legend instanceof RasterLegend ) {
692
            RasterLegend rasterLegend = (RasterLegend) legend;
693
            RasterStore rasterStore = (RasterStore) dataStore;
694
            ColorInterpretation colorInterpretation = rasterLegend.getColorInterpretation();
695
            if (colorInterpretation.isPalette()) {
696
                rasterLegend.addColorTableOperation(colorInterpretation, 0);
697
            } else {
698
                rasterLegend.addLinearStretchEnhancementOperationIfNeeded(
699
                        colorInterpretation, 
700
                        rasterStore.getBandDescriptors(), 
701
                        0);
702
            }
703
            if (colorInterpretation.hasAnyHSLBand()) {
704
                rasterLegend.addHSLToRGBOperation(colorInterpretation);
705
            } else if (colorInterpretation.hasAnyCMYKBand()) {
706
                rasterLegend.addCMYKToRGBOperation(colorInterpretation);
707
            } else if (colorInterpretation.hasAnyYCBCRBand()) {
708
              //TODO: Not implemented yet, meanwhile do nothing
709
    //                legend.addYCBCRToRGBOperation(colorInterpretation);
710
            }        
711
        }
712
        return legend;
713
    }
714

    
715
    @Override
716
    public ILabelingStrategy getLabelingStrategy(DataStore dataStore) {
717
        ILabelingStrategy labelingStrategy = null;
718

    
719
        File file = getResourcePath(dataStore, SymbolManager.LABELINGSTRATEGY_FILE_EXTENSION.substring(1));
720
        try {
721
            if ((file != null) && (file.exists())) {
722
                PersistenceManager persistenceManager = ToolsLocator.getPersistenceManager();
723
                FileInputStream is = new FileInputStream(file);
724
                labelingStrategy = (ILabelingStrategy) persistenceManager.getObject(is);
725
                is.close();
726
            }
727
        } catch (FileNotFoundException e) {
728
            logger.error("Label strategy not found", e);
729
        } catch (IOException e) {
730
            logger.error("Error reading the labeling strategy", e);
731
        }
732

    
733
        //If the legend is null, next option is to check if the store has the getLegend method
734
        if (labelingStrategy == null) {
735
            try {
736
                labelingStrategy
737
                        = (ILabelingStrategy) dataStore.invokeDynMethod("getLabeling",
738
                                null);
739
            } catch (DynMethodNotSupportedException e1) {
740
                labelingStrategy = null;
741
            } catch (DynMethodException e1) {
742
                logger.error("Can't load the specific lebeling strategy provided for the datastore {}.",
743
                        dataStore.getName(),
744
                        e1);
745
            }
746
        }
747

    
748
        return labelingStrategy;
749
    }
750

    
751
    private Object call(Object instance, String methodName, Class[] signature, Object[] params) {
752
        try {
753
            Method method = instance.getClass().getMethod(methodName, signature);
754
            if (method == null) {
755
                return null;
756
            }
757
            Object value = method.invoke(instance, params);
758
            return value;
759
        } catch (NoSuchMethodException ex) {
760
            return null;
761
        } catch (SecurityException ex) {
762
            return null;
763
        } catch (IllegalAccessException ex) {
764
            return null;
765
        } catch (IllegalArgumentException ex) {
766
            return null;
767
        } catch (InvocationTargetException ex) {
768
            return null;
769
        }
770
    }
771

    
772
    private File getResourcePath(DataStore dataStore, String resource) {
773
        //Loading the file from a store based on file
774
        DataServerExplorer explorer = null;
775
        try {
776
            explorer = dataStore.getExplorer();
777
            if (explorer == null) {
778
                return null;
779
            }
780
            return explorer.getResourcePath(dataStore, resource);
781
        } catch (Exception e) {
782
            logger.warn(
783
                    "Can't locate a specific legend provided by the explorer "
784
                    + explorer, e);
785
            return null;
786
        } finally {
787
            DisposeUtils.disposeQuietly(explorer);
788
        }
789
    }
790

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

    
793
    public void registerIconLayer(String storeProviderName, String iconName) {
794
        if (storeProviderName == null || iconName == null) {
795
            logger.info("registerIconLayer, storeProviderName or iconName are null");
796
            return;
797
        }
798
        String storeName = storeProviderName.trim().toLowerCase();
799
        if (storeName.length() == 0 || iconName.trim().length() == 0) {
800
            logger.info("registerIconLayer, invalid storeProviderName or iconName");
801
            return;
802
        }
803
        iconLayers.put(storeName, iconName);
804
        notifyObservers(REGISTER_ICON_LAYER, storeName, iconName);
805
    }
806

    
807
        @Override
808
    public String getIconLayer(DataStore store) {
809
        try {
810
            return this.getIconLayer(store.getProviderName());
811
        } catch (Throwable th){
812
            return "layer-icon";
813
        }
814
    }
815

    
816
    @Override
817
    public String getIconLayer(String providerName) {
818
                String name = null;
819
                try {
820
                        name = (String) iconLayers.get(providerName.trim().toLowerCase());
821
                } catch(Throwable th) {
822
                        // Do nothing
823
                }
824
                if( StringUtils.isEmpty(name) ) {
825
                        name = "layer-icon";
826
                }
827
        return name;
828
    }
829

    
830
    /* (non-Javadoc)
831
     * @see org.gvsig.fmap.mapcontext.MapContextManager#getDefaultCRS()
832
     */
833
    public IProjection getDefaultCRS() {
834
        IProjection crs = CRSFactory.getCRS("EPSG:4326");
835
        return (IProjection) notifyObservers(GET_DEFAULT_CRS, crs).getValue();
836
    }
837

    
838
    public Notification notifyLoadMapContext(MapContext mapContext) {
839
        return this.observableHelper.notifyObservers(this, LOAD_MAPCONTEXT, mapContext);
840
    }
841

    
842
    public Notification notifyLoadLayer(FLayer layer) {
843
        return this.observableHelper.notifyObservers(this, LOAD_LAYER, layer);
844
    }
845

    
846
    public void addObserver(Observer o) {
847
        this.observableHelper.addObserver(o);
848
    }
849

    
850
    public void deleteObserver(Observer o) {
851
        this.observableHelper.deleteObserver(o);
852
    }
853

    
854
    public void deleteObservers() {
855
        this.observableHelper.deleteObservers();
856
    }
857

    
858
    protected Notification notifyObservers(String type, Object value) {
859
        return this.observableHelper.notifyObservers(this, type, value);
860
    }
861

    
862
    protected Notification notifyObservers(String type, Object value1, Object value2) {
863
        return this.observableHelper.notifyObservers(this, type, value1, value2);
864
    }
865

    
866
    protected Notification notifyObservers(String type, Object value1, Object value2, Object value3) {
867
        return this.observableHelper.notifyObservers(this, type, value1, value2, value3);
868
    }
869

    
870
    public File getColorTableLibraryFolder() {
871
        if (this.colorTableLibraryFolder == null) {
872
            // Provide a default value to the location for the color
873
            // table library.
874
            String colorTableLibraryPath = System.getProperty("user.home")
875
                    + File.separator
876
                    + "gvSIG"
877
                    + File.separator
878
                    + "colortable";
879
            this.colorTableLibraryFolder = new File(colorTableLibraryPath);
880
        }
881
        return this.colorTableLibraryFolder;
882
    }
883

    
884
    public void setColorTableLibraryFolder(File colorTableLibraryFolder) {
885
        this.colorTableLibraryFolder = colorTableLibraryFolder;
886
    }
887

    
888
    @Override
889
    public LayerInformationBuilder createLayerInformationBuilder() {
890
        return new DefaultLayerInformationBuilder();
891
    }
892

    
893

    
894
}