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 @ 44276

History | View | Annotate | Download (30.7 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.InputStream;
30
import java.lang.reflect.InvocationTargetException;
31
import java.lang.reflect.Method;
32
import java.util.ArrayList;
33
import java.util.HashMap;
34
import java.util.Iterator;
35
import java.util.LinkedHashMap;
36
import java.util.List;
37
import java.util.Map;
38
import org.apache.commons.io.IOUtils;
39
import org.apache.commons.lang3.StringUtils;
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.DefaultLayerInformationBuilder;
58
import org.gvsig.fmap.mapcontext.layers.FLayer;
59
import org.gvsig.fmap.mapcontext.layers.LayerFactory;
60
import org.gvsig.fmap.mapcontext.layers.LayerInformationBuilder;
61
import org.gvsig.fmap.mapcontext.layers.vectorial.GraphicLayer;
62
import org.gvsig.fmap.mapcontext.layers.vectorial.impl.DefaultGraphicLayer;
63
import org.gvsig.fmap.mapcontext.rendering.legend.ILegend;
64
import org.gvsig.fmap.mapcontext.rendering.legend.IVectorLegend;
65
import org.gvsig.fmap.mapcontext.rendering.legend.IVectorialUniqueValueLegend;
66
import org.gvsig.fmap.mapcontext.rendering.legend.driver.ILegendReader;
67
import org.gvsig.fmap.mapcontext.rendering.legend.driver.ILegendWriter;
68
import org.gvsig.fmap.mapcontext.rendering.legend.styling.ILabelingStrategy;
69
import org.gvsig.fmap.mapcontext.rendering.symbols.IMultiLayerSymbol;
70
import org.gvsig.fmap.mapcontext.rendering.symbols.ISymbol;
71
import org.gvsig.fmap.mapcontext.rendering.symbols.IWarningSymbol;
72
import org.gvsig.fmap.mapcontext.rendering.symbols.SymbolException;
73
import org.gvsig.fmap.mapcontext.rendering.symbols.SymbolManager;
74
import org.gvsig.fmap.mapcontext.rendering.symbols.SymbolPreferences;
75
import org.gvsig.tools.ToolsLocator;
76
import org.gvsig.tools.dispose.DisposeUtils;
77
import org.gvsig.tools.dynobject.exception.DynMethodException;
78
import org.gvsig.tools.dynobject.exception.DynMethodNotSupportedException;
79
import org.gvsig.tools.observer.Notification;
80
import org.gvsig.tools.observer.ObservableHelper;
81
import org.gvsig.tools.observer.Observer;
82
import org.gvsig.tools.persistence.PersistenceManager;
83
import org.gvsig.tools.util.ResourcesStorage.Resource;
84
import org.slf4j.Logger;
85
import org.slf4j.LoggerFactory;
86

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

    
94
    private static final Logger logger = LoggerFactory
95
            .getLogger(DefaultMapContextManager.class);
96

    
97
    private Class drawerClazz = DefaultMapContextDrawer.class;
98

    
99
    private final Map legends = new HashMap();
100

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

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

    
105
    private String defaultVectorLegend;
106

    
107
    private ObservableHelper observableHelper = new ObservableHelper();
108

    
109
    private File colorTableLibraryFolder = null;
110

    
111
    public MapContext createMapContext() {
112
        MapContext mapcontext = new MapContext(new ViewPort());
113
        return (MapContext) notifyObservers(CREATE_MAPCONTEXT, mapcontext).getValue();
114
    }
115

    
116
    public SymbolManager getSymbolManager() {
117
        return MapContextLocator.getSymbolManager();
118
    }
119

    
120
    private SymbolPreferences getSymbolPreferences() {
121
        return getSymbolManager().getSymbolPreferences();
122
    }
123

    
124
    public String getSymbolLibraryPath() {
125
        return getSymbolPreferences().getSymbolLibraryPath();
126
    }
127

    
128
    public void setSymbolLibraryPath(String symbolLibraryPath) {
129
        getSymbolPreferences().setSymbolLibraryPath(symbolLibraryPath);
130
    }
131

    
132
    public void resetSymbolLibraryPath() {
133
        getSymbolPreferences().resetSymbolLibraryPath();
134
    }
135

    
136
    public Color getDefaultSymbolColor() {
137
        return getSymbolPreferences().getDefaultSymbolColor();
138
    }
139

    
140
    public Color getDefaultSymbolFillColor() {
141
        return getSymbolPreferences().getDefaultSymbolFillColor();
142
    }
143

    
144
    public Font getDefaultSymbolFont() {
145
        return getSymbolPreferences().getDefaultSymbolFont();
146
    }
147

    
148
    public String getSymbolFileExtension() {
149
        return getSymbolPreferences().getSymbolFileExtension();
150
    }
151

    
152
    public boolean isDefaultSymbolFillColorAleatory() {
153
        return getSymbolPreferences().isDefaultSymbolFillColorAleatory();
154
    }
155

    
156
    public void resetDefaultSymbolColor() {
157
        getSymbolPreferences().resetDefaultSymbolColor();
158
    }
159

    
160
    public void resetDefaultSymbolFillColor() {
161
        getSymbolPreferences().resetDefaultSymbolFillColor();
162
    }
163

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

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

    
172
    public void setDefaultSymbolColor(Color defaultSymbolColor) {
173
        getSymbolPreferences().setDefaultSymbolColor(defaultSymbolColor);
174
    }
175

    
176
    public void setDefaultSymbolFillColor(Color defaultSymbolFillColor) {
177
        getSymbolPreferences().setDefaultSymbolFillColor(defaultSymbolFillColor);
178
    }
179

    
180
    public void setDefaultSymbolFillColorAleatory(
181
            boolean defaultSymbolFillColorAleatory) {
182
        getSymbolPreferences().setDefaultSymbolFillColorAleatory(
183
                defaultSymbolFillColorAleatory);
184
    }
185

    
186
    public void setDefaultSymbolFont(Font defaultSymbolFont) {
187
        getSymbolPreferences().setDefaultSymbolFont(defaultSymbolFont);
188
    }
189

    
190
    public void setSymbolFileExtension(String extension) {
191
        getSymbolPreferences().setSymbolFileExtension(extension);
192
    }
193

    
194
    public int getDefaultCartographicSupportMeasureUnit() {
195
        return getSymbolPreferences().getDefaultCartographicSupportMeasureUnit();
196
    }
197

    
198
    public void setDefaultCartographicSupportMeasureUnit(
199
            int defaultCartographicSupportMeasureUnit) {
200
        getSymbolPreferences().setDefaultCartographicSupportMeasureUnit(
201
                defaultCartographicSupportMeasureUnit);
202
    }
203

    
204
    public int getDefaultCartographicSupportReferenceSystem() {
205
        return getSymbolPreferences().getDefaultCartographicSupportReferenceSystem();
206
    }
207

    
208
    public void setDefaultCartographicSupportReferenceSystem(
209
            int defaultCartographicSupportReferenceSystem) {
210
        getSymbolPreferences().setDefaultCartographicSupportReferenceSystem(
211
                defaultCartographicSupportReferenceSystem);
212
    }
213

    
214
    public MapContextDrawer createMapContextDrawerInstance(Class drawerClazz)
215
            throws MapContextException {
216
        return createMapContextDrawerInstance(drawerClazz, "NONE");
217
    }
218

    
219
    public MapContextDrawer createDefaultMapContextDrawerInstance()
220
            throws MapContextException {
221

    
222
        return createMapContextDrawerInstance(drawerClazz, "default");
223
    }
224

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

    
237
    public void setDefaultMapContextDrawer(Class drawerClazz)
238
            throws MapContextException {
239

    
240
        validateMapContextDrawer(drawerClazz);
241
        this.drawerClazz = drawerClazz;
242
        notifyObservers(SET_MAPCONTEXT_DRAWER, drawerClazz);
243
    }
244

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

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

    
264
    public String getDefaultVectorLegend() {
265
        return defaultVectorLegend;
266
    }
267

    
268
    public void setDefaultVectorLegend(String defaultVectorLegend) {
269
        this.defaultVectorLegend = defaultVectorLegend;
270
    }
271

    
272
    public void registerLegend(String legendName, Class legendClass)
273
            throws MapContextRuntimeException {
274

    
275
        if (legendClass == null || !ILegend.class.isAssignableFrom(legendClass)) {
276
            throw new InvalidRegisteredClassException(ILegend.class,
277
                    legendClass, legendName);
278
        }
279

    
280
        legends.put(legendName, legendClass);
281
        notifyObservers(REGISTER_LEGEND, legendName, legendClass);
282
    }
283

    
284
    public ILegend createLegend(String legendName)
285
            throws MapContextRuntimeException {
286
        Class legendClass = (Class) legends.get(legendName);
287

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

    
303
    public IVectorLegend createDefaultVectorLegend(int shapeType)
304
            throws MapContextRuntimeException {
305
        try {
306
            // Create legend
307
            IVectorLegend legend
308
                    = (IVectorLegend) createLegend(getDefaultVectorLegend());
309
            if (legend == null) {
310
                return null;
311
            }
312
            // Set legend values
313
            legend.setShapeType(shapeType);
314
            ISymbol symbol = getSymbolManager().createSymbol(shapeType);
315
            if (symbol == null) {
316
                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.";
317
                throw new RuntimeException(msg);
318
            }
319
            legend.setDefaultSymbol(symbol);
320
            return legend;
321
        } catch (Exception e) {
322
            throw new MapContextRuntimeException(e);
323
        }
324
    }
325

    
326
    // =============================================================
327
    // Legend reading/writing
328

    
329
    private Map<Class<ILegend>,Class<ILegendWriter>> getLegendWritersForFormat(String format) {
330
        synchronized(legendWriters) {
331
            return legendWriters.get(format);
332
        }
333
    }
334

    
335
    private Class<ILegendReader> getLegendReaderForFormat(String format) {
336
        synchronized(legendReaders) {
337
            return legendReaders.get(format);
338
        }
339
    }
340

    
341
    @Override
342
    public List<String> getLegendReadingFormats() {
343
        synchronized(legendReaders) {
344
            List<String> resp = new ArrayList();
345
            resp.addAll(legendReaders.keySet());
346
            return resp;
347
        }
348
    }
349

    
350
    @Override
351
    public List<String> getLegendWritingFormats() {
352
        synchronized(legendWriters) {
353
            List<String> resp = new ArrayList();
354
            resp.addAll(legendWriters.keySet());
355
            return resp;
356
        }
357
    }
358
    
359
    @Override
360
    public void registerLegendReader(String format, Class readerClass)
361
            throws MapContextRuntimeException {
362
        if (readerClass == null
363
                || !ILegendReader.class.isAssignableFrom(readerClass)) {
364
            throw new InvalidRegisteredClassException(ILegendReader.class,
365
                    readerClass, format);
366
        }
367
        synchronized (legendReaders) {
368
            legendReaders.put(format, readerClass);
369
        }
370
        notifyObservers(REGISTER_LEGEND_READER, format, readerClass);
371
    }
372

    
373
    @Override
374
    public void registerLegendWriter(Class legendClass, String format,
375
            Class writerClass) throws MapContextRuntimeException {
376
        if (writerClass == null || legendClass == null
377
                || !ILegendWriter.class.isAssignableFrom(writerClass)
378
                || !ILegend.class.isAssignableFrom(legendClass)) {
379

    
380
            throw new InvalidRegisteredClassException(ILegendWriter.class,
381
                    writerClass, format.concat("-").concat(
382
                            legendClass == null ? "Null" : legendClass.getName()));
383
        }
384

    
385
        synchronized (legendWriters) {
386
            Map<Class<ILegend>, Class<ILegendWriter>> legendWriterOfFormat = legendWriters.get(format);
387
            if (legendWriterOfFormat == null) {
388
                legendWriterOfFormat = new LinkedHashMap();
389
                legendWriters.put(format, legendWriterOfFormat);
390
            }
391
            legendWriterOfFormat.put(legendClass, writerClass);
392
        }
393
        notifyObservers(REGISTER_LEGEND_WRITER, format, writerClass);
394
    }
395

    
396
    @Override
397
    public ILegendReader createLegendReader(String format)
398
            throws MapContextRuntimeException {
399
        Class<ILegendReader> legendReaderClazz = getLegendReaderForFormat(format);
400

    
401
        if (legendReaderClazz != null) {
402
            try {
403
                ILegendReader reader = (ILegendReader) legendReaderClazz.newInstance();
404
                return (ILegendReader) notifyObservers(CREATE_LEGEND_READER, reader).getValue();
405
            } catch (InstantiationException|IllegalAccessException e) {
406
                throw new RegisteredClassInstantiationException(
407
                        ILegendReader.class, legendReaderClazz, format, e);
408
            }
409
        }
410
        return null;
411
    }
412

    
413
    @Override
414
    public ILegendWriter createLegendWriter(Class legendClass, String format)
415
            throws MapContextRuntimeException {
416

    
417
        if (legendClass == null || format == null) {
418
            return null;
419
        }
420

    
421
        Map<Class<ILegend>, Class<ILegendWriter>> legendFormatWriters = getLegendWritersForFormat(format);
422

    
423
        if (legendFormatWriters != null) {
424
            Class<ILegendWriter> legendWriterClazz = legendFormatWriters.get(legendClass);
425
            if (legendWriterClazz != null) {
426
                /*
427
                 * Found exact match
428
                 */
429
                try {
430
                    ILegendWriter writer = (ILegendWriter) legendWriterClazz.newInstance();
431
                    return (ILegendWriter) notifyObservers(CREATE_LEGEND_READER, writer).getValue();
432
                } catch (InstantiationException|IllegalAccessException e) {
433
                    throw new RegisteredClassInstantiationException(
434
                            ILegendWriter.class, 
435
                            legendWriterClazz,
436
                            format.concat("-").concat(legendClass.getName()), 
437
                            e
438
                    );
439
                }
440
            } else {
441
                /*
442
                 * Trying to find superclass/superinterface of parameter
443
                 */
444
                try {
445
                    return getSuperClassLegendWriter(legendFormatWriters, legendClass);
446
                } catch (Exception exc) {
447
                    throw new MapContextRuntimeException(exc);
448
                }
449
            }
450
        }
451
        return null;
452
    }
453

    
454
    private ILegendWriter getSuperClassLegendWriter(Map<Class<ILegend>, Class<ILegendWriter>> clsToWtr, Class<ILegend> legclass)
455
            throws Exception {
456

    
457
        Iterator kiter = clsToWtr.keySet().iterator();
458
        Object oitem = null;
459
        Class citem = null;
460
        while (kiter.hasNext()) {
461
            oitem = kiter.next();
462
            if (oitem instanceof Class) {
463
                citem = (Class) oitem;
464
                if (citem.isAssignableFrom(legclass)) {
465
                    /*
466
                     * Found superclass/superinterface
467
                     */
468
                    citem = (Class) clsToWtr.get(oitem);
469
                    return (ILegendWriter) citem.newInstance();
470
                }
471
            }
472
        }
473
        /*
474
         * No superclass/superinterface found
475
         */
476
        return null;
477
    }
478

    
479
    // =============================================================
480

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

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

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

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

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

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

    
517
    public IWarningSymbol getWarningSymbol(String message, String symbolDesc,
518
            int symbolDrawExceptionType) throws MapContextRuntimeException {
519
        return getSymbolManager().getWarningSymbol(message, symbolDesc,
520
                symbolDrawExceptionType);
521
    }
522

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

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

    
534
    public void registerMultiLayerSymbol(String symbolName, Class symbolClass)
535
            throws MapContextRuntimeException {
536
        getSymbolManager().registerMultiLayerSymbol(symbolName, symbolClass);
537
        notifyObservers(REGISTER_MULTILAYER_SYMBOL, symbolName, symbolClass);
538
    }
539

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

    
547
    public void registerSymbol(String symbolName, Class symbolClass)
548
            throws MapContextRuntimeException {
549
        getSymbolManager().registerSymbol(symbolName, symbolClass);
550
        notifyObservers(REGISTER_SYMBOL, symbolName, symbolClass);
551
    }
552

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

    
559
    public void saveSymbol(ISymbol symbol, String fileName, File folder,
560
            boolean overwrite) throws SymbolException {
561
        getSymbolManager().saveSymbol(symbol, fileName, folder, overwrite);
562
    }
563

    
564
    public void saveSymbol(ISymbol symbol, String fileName, File folder)
565
            throws SymbolException {
566
        getSymbolManager().saveSymbol(symbol, fileName, folder);
567
    }
568

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

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

    
581
    public ILegend getLegend(DataStore dataStore) {
582
        ILegend legend = null;
583

    
584
        Resource resource = getResource(dataStore, SymbolManager.LEGEND_FILE_EXTENSION.substring(1));
585
        try {
586
            if ((resource != null) && (resource.exists())) {
587
                PersistenceManager persistenceManager = ToolsLocator.getPersistenceManager();
588
                InputStream is = resource.asInputStream();
589
                legend = (ILegend) persistenceManager.getObject(is);
590
                is.close();
591
            }
592
        } catch (Exception e) {
593
            logger.warn("Can't loasd legend", e);
594
        } finally {
595
            IOUtils.closeQuietly(resource);
596
        }
597

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

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

    
628
        return legend;
629
    }
630

    
631
    public ILabelingStrategy getLabelingStrategy(DataStore dataStore) {
632
        ILabelingStrategy labelingStrategy = null;
633

    
634
        Resource resource = getResource(dataStore, SymbolManager.LABELINGSTRATEGY_FILE_EXTENSION.substring(1));
635
        try {
636
            if ((resource != null) && (resource.exists())) {
637
                PersistenceManager persistenceManager = ToolsLocator.getPersistenceManager();
638
                InputStream is = resource.asInputStream();
639
                labelingStrategy = (ILabelingStrategy) persistenceManager.getObject(is);
640
                is.close();
641
            }
642
        } catch (Exception e) {
643
            logger.warn("Can't load Label strategy", e);
644
        } finally {
645
            IOUtils.closeQuietly(resource);
646
        }
647

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

    
663
        return labelingStrategy;
664
    }
665

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

    
687
    
688
    private Resource getResource(DataStore dataStore, String resource) {
689
        DataServerExplorer explorer = null;
690
        try {
691
            explorer = dataStore.getExplorer();
692
            if (explorer == null) {
693
                return null;
694
            }
695
            return explorer.getResource(dataStore, resource);
696
        } catch (Exception e) {
697
            logger.warn("Can't locate resource '"+resource+"' for '"+dataStore.getName()+"'.",e);
698
            return null;
699
        } finally {
700
            DisposeUtils.disposeQuietly(explorer);
701
        }
702
    }
703

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

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

    
720
        @Override
721
    public String getIconLayer(DataStore store) {
722
        try {
723
            return this.getIconLayer(store.getProviderName());
724
        } catch (Throwable th){
725
            return "layer-icon";
726
        }
727
    }
728

    
729
    @Override
730
    public String getIconLayer(String providerName) {
731
                String name = null;
732
                try {
733
                        name = (String) iconLayers.get(providerName.trim().toLowerCase());
734
                } catch(Throwable th) {
735
                        // Do nothing
736
                }
737
                if( StringUtils.isEmpty(name) ) {
738
                        name = "layer-icon";
739
                }
740
        return name;
741
    }
742

    
743
    /* (non-Javadoc)
744
     * @see org.gvsig.fmap.mapcontext.MapContextManager#getDefaultCRS()
745
     */
746
    public IProjection getDefaultCRS() {
747
        IProjection crs = CRSFactory.getCRS("EPSG:4326");
748
        return (IProjection) notifyObservers(GET_DEFAULT_CRS, crs).getValue();
749
    }
750

    
751
    public Notification notifyLoadMapContext(MapContext mapContext) {
752
        return this.observableHelper.notifyObservers(this, LOAD_MAPCONTEXT, mapContext);
753
    }
754

    
755
    public Notification notifyLoadLayer(FLayer layer) {
756
        return this.observableHelper.notifyObservers(this, LOAD_LAYER, layer);
757
    }
758

    
759
    public void addObserver(Observer o) {
760
        this.observableHelper.addObserver(o);
761
    }
762

    
763
    public void deleteObserver(Observer o) {
764
        this.observableHelper.deleteObserver(o);
765
    }
766

    
767
    public void deleteObservers() {
768
        this.observableHelper.deleteObservers();
769
    }
770

    
771
    protected Notification notifyObservers(String type, Object value) {
772
        return this.observableHelper.notifyObservers(this, type, value);
773
    }
774

    
775
    protected Notification notifyObservers(String type, Object value1, Object value2) {
776
        return this.observableHelper.notifyObservers(this, type, value1, value2);
777
    }
778

    
779
    protected Notification notifyObservers(String type, Object value1, Object value2, Object value3) {
780
        return this.observableHelper.notifyObservers(this, type, value1, value2, value3);
781
    }
782

    
783
    public File getColorTableLibraryFolder() {
784
        if (this.colorTableLibraryFolder == null) {
785
            // Provide a default value to the location for the color
786
            // table library.
787
            String colorTableLibraryPath = System.getProperty("user.home")
788
                    + File.separator
789
                    + "gvSIG"
790
                    + File.separator
791
                    + "colortable";
792
            this.colorTableLibraryFolder = new File(colorTableLibraryPath);
793
        }
794
        return this.colorTableLibraryFolder;
795
    }
796

    
797
    public void setColorTableLibraryFolder(File colorTableLibraryFolder) {
798
        this.colorTableLibraryFolder = colorTableLibraryFolder;
799
    }
800

    
801
    @Override
802
    public LayerInformationBuilder createLayerInformationBuilder() {
803
        return new DefaultLayerInformationBuilder();
804
    }
805

    
806

    
807
}