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

History | View | Annotate | Download (30.9 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.LinkedHashMap;
39
import java.util.List;
40
import java.util.Map;
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.mapcontext.MapContext;
52
import org.gvsig.fmap.mapcontext.MapContextDrawer;
53
import org.gvsig.fmap.mapcontext.MapContextException;
54
import org.gvsig.fmap.mapcontext.MapContextLocator;
55
import org.gvsig.fmap.mapcontext.MapContextManager;
56
import org.gvsig.fmap.mapcontext.MapContextRuntimeException;
57
import org.gvsig.fmap.mapcontext.ViewPort;
58
import org.gvsig.fmap.mapcontext.exceptions.LoadLayerException;
59
import org.gvsig.fmap.mapcontext.layers.DefaultLayerInformationBuilder;
60
import org.gvsig.fmap.mapcontext.layers.FLayer;
61
import org.gvsig.fmap.mapcontext.layers.LayerFactory;
62
import org.gvsig.fmap.mapcontext.layers.LayerInformationBuilder;
63
import org.gvsig.fmap.mapcontext.layers.vectorial.GraphicLayer;
64
import org.gvsig.fmap.mapcontext.layers.vectorial.impl.DefaultGraphicLayer;
65
import org.gvsig.fmap.mapcontext.rendering.legend.ILegend;
66
import org.gvsig.fmap.mapcontext.rendering.legend.IVectorLegend;
67
import org.gvsig.fmap.mapcontext.rendering.legend.IVectorialUniqueValueLegend;
68
import org.gvsig.fmap.mapcontext.rendering.legend.driver.ILegendReader;
69
import org.gvsig.fmap.mapcontext.rendering.legend.driver.ILegendWriter;
70
import org.gvsig.fmap.mapcontext.rendering.legend.styling.ILabelingStrategy;
71
import org.gvsig.fmap.mapcontext.rendering.symbols.IMultiLayerSymbol;
72
import org.gvsig.fmap.mapcontext.rendering.symbols.ISymbol;
73
import org.gvsig.fmap.mapcontext.rendering.symbols.IWarningSymbol;
74
import org.gvsig.fmap.mapcontext.rendering.symbols.SymbolException;
75
import org.gvsig.fmap.mapcontext.rendering.symbols.SymbolManager;
76
import org.gvsig.fmap.mapcontext.rendering.symbols.SymbolPreferences;
77
import org.gvsig.tools.ToolsLocator;
78
import org.gvsig.tools.dispose.DisposeUtils;
79
import org.gvsig.tools.dynobject.exception.DynMethodException;
80
import org.gvsig.tools.dynobject.exception.DynMethodNotSupportedException;
81
import org.gvsig.tools.observer.Notification;
82
import org.gvsig.tools.observer.ObservableHelper;
83
import org.gvsig.tools.observer.Observer;
84
import org.gvsig.tools.persistence.PersistenceManager;
85
import org.slf4j.Logger;
86
import org.slf4j.LoggerFactory;
87

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

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

    
98
    private Class drawerClazz = DefaultMapContextDrawer.class;
99

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

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

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

    
106
    private String defaultVectorLegend;
107

    
108
    private ObservableHelper observableHelper = new ObservableHelper();
109

    
110
    private File colorTableLibraryFolder = null;
111

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
220
    public MapContextDrawer createDefaultMapContextDrawerInstance()
221
            throws MapContextException {
222

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
327
    // =============================================================
328
    // Legend reading/writing
329

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
480
    // =============================================================
481

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
629
        return legend;
630
    }
631

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

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

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

    
664
        return labelingStrategy;
665
    }
666

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

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

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

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

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

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

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

    
754
    public Notification notifyLoadMapContext(MapContext mapContext) {
755
        return this.observableHelper.notifyObservers(this, LOAD_MAPCONTEXT, mapContext);
756
    }
757

    
758
    public Notification notifyLoadLayer(FLayer layer) {
759
        return this.observableHelper.notifyObservers(this, LOAD_LAYER, layer);
760
    }
761

    
762
    public void addObserver(Observer o) {
763
        this.observableHelper.addObserver(o);
764
    }
765

    
766
    public void deleteObserver(Observer o) {
767
        this.observableHelper.deleteObserver(o);
768
    }
769

    
770
    public void deleteObservers() {
771
        this.observableHelper.deleteObservers();
772
    }
773

    
774
    protected Notification notifyObservers(String type, Object value) {
775
        return this.observableHelper.notifyObservers(this, type, value);
776
    }
777

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

    
782
    protected Notification notifyObservers(String type, Object value1, Object value2, Object value3) {
783
        return this.observableHelper.notifyObservers(this, type, value1, value2, value3);
784
    }
785

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

    
800
    public void setColorTableLibraryFolder(File colorTableLibraryFolder) {
801
        this.colorTableLibraryFolder = colorTableLibraryFolder;
802
    }
803

    
804
    @Override
805
    public LayerInformationBuilder createLayerInformationBuilder() {
806
        return new DefaultLayerInformationBuilder();
807
    }
808

    
809

    
810
}