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

History | View | Annotate | Download (30.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.Collections;
36
import java.util.HashMap;
37
import java.util.Iterator;
38
import java.util.List;
39
import java.util.Map;
40

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

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

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

    
93
    private Class drawerClazz = DefaultMapContextDrawer.class;
94

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

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

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

    
101
    private String defaultVectorLegend;
102

    
103
    private ObservableHelper observableHelper = new ObservableHelper();
104

    
105
    private File colorTableLibraryFolder = null;
106

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
215
    public MapContextDrawer createDefaultMapContextDrawerInstance()
216
            throws MapContextException {
217

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
386
        Map legendFormatWriters = getLegendWritersForFormat(format);
387

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
624
        return legend;
625
    }
626

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

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

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

    
659
        return labelingStrategy;
660
    }
661

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

    
683
    private File getResourcePath(DataStore dataStore, String resource) {
684
        //Loading the file from a store based on file
685
        DataServerExplorer explorer = null;
686
        try {
687
            explorer = dataStore.getExplorer();
688
            if (explorer == null) {
689
                return null;
690
            }
691
            return (File) call(explorer, "getResourcePath",
692
                    new Class[]{DataStore.class, String.class},
693
                    new Object[]{dataStore, resource});
694
        } catch (Exception e) {
695
            logger.warn(
696
                    "Can't locate a specific legend provided by the explorer "
697
                    + explorer, e);
698
            return null;
699
        } finally {
700
            if (explorer != null) {
701
                explorer.dispose();
702
                explorer = null;
703
            }
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
    public String getIconLayer(DataStore store) {
724
        String name = (String) iconLayers.get(store.getProviderName().trim().toLowerCase());
725
        if (name == null) {
726
            return "layer-icon";
727
        }
728
        return name;
729
    }
730

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

    
739
    public Notification notifyLoadMapContext(MapContext mapContext) {
740
        return this.observableHelper.notifyObservers(this, LOAD_MAPCONTEXT, mapContext);
741
    }
742

    
743
    public Notification notifyLoadLayer(FLayer layer) {
744
        return this.observableHelper.notifyObservers(this, LOAD_LAYER, layer);
745
    }
746

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

    
751
    public void deleteObserver(Observer o) {
752
        this.observableHelper.deleteObserver(o);
753
    }
754

    
755
    public void deleteObservers() {
756
        this.observableHelper.deleteObservers();
757
    }
758

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

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

    
767
    protected Notification notifyObservers(String type, Object value1, Object value2, Object value3) {
768
        return this.observableHelper.notifyObservers(this, type, value1, value2, value3);
769
    }
770

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

    
785
    public void setColorTableLibraryFolder(File colorTableLibraryFolder) {
786
        this.colorTableLibraryFolder = colorTableLibraryFolder;
787
    }
788

    
789
}