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

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.io.InputStream;
33
import java.lang.reflect.InvocationTargetException;
34
import java.lang.reflect.Method;
35
import java.util.ArrayList;
36
import java.util.Collections;
37
import java.util.HashMap;
38
import java.util.Iterator;
39
import java.util.LinkedHashMap;
40
import java.util.List;
41
import java.util.Map;
42
import org.apache.commons.io.IOUtils;
43
import org.apache.commons.lang3.StringUtils;
44

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

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

    
98
    private static final Logger logger = LoggerFactory
99
            .getLogger(DefaultMapContextManager.class);
100

    
101
    private Class drawerClazz = DefaultMapContextDrawer.class;
102

    
103
    private final Map legends = new HashMap();
104

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

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

    
109
    private String defaultVectorLegend;
110

    
111
    private ObservableHelper observableHelper = new ObservableHelper();
112

    
113
    private File colorTableLibraryFolder = null;
114

    
115
    public MapContext createMapContext() {
116
        MapContext mapcontext = new MapContext(new ViewPort());
117
        return (MapContext) notifyObservers(CREATE_MAPCONTEXT, mapcontext).getValue();
118
    }
119

    
120
    public SymbolManager getSymbolManager() {
121
        return MapContextLocator.getSymbolManager();
122
    }
123

    
124
    private SymbolPreferences getSymbolPreferences() {
125
        return getSymbolManager().getSymbolPreferences();
126
    }
127

    
128
    public String getSymbolLibraryPath() {
129
        return getSymbolPreferences().getSymbolLibraryPath();
130
    }
131

    
132
    public void setSymbolLibraryPath(String symbolLibraryPath) {
133
        getSymbolPreferences().setSymbolLibraryPath(symbolLibraryPath);
134
    }
135

    
136
    public void resetSymbolLibraryPath() {
137
        getSymbolPreferences().resetSymbolLibraryPath();
138
    }
139

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

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

    
148
    public Font getDefaultSymbolFont() {
149
        return getSymbolPreferences().getDefaultSymbolFont();
150
    }
151

    
152
    public String getSymbolFileExtension() {
153
        return getSymbolPreferences().getSymbolFileExtension();
154
    }
155

    
156
    public boolean isDefaultSymbolFillColorAleatory() {
157
        return getSymbolPreferences().isDefaultSymbolFillColorAleatory();
158
    }
159

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

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

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

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

    
176
    public void setDefaultSymbolColor(Color defaultSymbolColor) {
177
        getSymbolPreferences().setDefaultSymbolColor(defaultSymbolColor);
178
    }
179

    
180
    public void setDefaultSymbolFillColor(Color defaultSymbolFillColor) {
181
        getSymbolPreferences().setDefaultSymbolFillColor(defaultSymbolFillColor);
182
    }
183

    
184
    public void setDefaultSymbolFillColorAleatory(
185
            boolean defaultSymbolFillColorAleatory) {
186
        getSymbolPreferences().setDefaultSymbolFillColorAleatory(
187
                defaultSymbolFillColorAleatory);
188
    }
189

    
190
    public void setDefaultSymbolFont(Font defaultSymbolFont) {
191
        getSymbolPreferences().setDefaultSymbolFont(defaultSymbolFont);
192
    }
193

    
194
    public void setSymbolFileExtension(String extension) {
195
        getSymbolPreferences().setSymbolFileExtension(extension);
196
    }
197

    
198
    public int getDefaultCartographicSupportMeasureUnit() {
199
        return getSymbolPreferences().getDefaultCartographicSupportMeasureUnit();
200
    }
201

    
202
    public void setDefaultCartographicSupportMeasureUnit(
203
            int defaultCartographicSupportMeasureUnit) {
204
        getSymbolPreferences().setDefaultCartographicSupportMeasureUnit(
205
                defaultCartographicSupportMeasureUnit);
206
    }
207

    
208
    public int getDefaultCartographicSupportReferenceSystem() {
209
        return getSymbolPreferences().getDefaultCartographicSupportReferenceSystem();
210
    }
211

    
212
    public void setDefaultCartographicSupportReferenceSystem(
213
            int defaultCartographicSupportReferenceSystem) {
214
        getSymbolPreferences().setDefaultCartographicSupportReferenceSystem(
215
                defaultCartographicSupportReferenceSystem);
216
    }
217

    
218
    public MapContextDrawer createMapContextDrawerInstance(Class drawerClazz)
219
            throws MapContextException {
220
        return createMapContextDrawerInstance(drawerClazz, "NONE");
221
    }
222

    
223
    public MapContextDrawer createDefaultMapContextDrawerInstance()
224
            throws MapContextException {
225

    
226
        return createMapContextDrawerInstance(drawerClazz, "default");
227
    }
228

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

    
241
    public void setDefaultMapContextDrawer(Class drawerClazz)
242
            throws MapContextException {
243

    
244
        validateMapContextDrawer(drawerClazz);
245
        this.drawerClazz = drawerClazz;
246
        notifyObservers(SET_MAPCONTEXT_DRAWER, drawerClazz);
247
    }
248

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

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

    
268
    public String getDefaultVectorLegend() {
269
        return defaultVectorLegend;
270
    }
271

    
272
    public void setDefaultVectorLegend(String defaultVectorLegend) {
273
        this.defaultVectorLegend = defaultVectorLegend;
274
    }
275

    
276
    public void registerLegend(String legendName, Class legendClass)
277
            throws MapContextRuntimeException {
278

    
279
        if (legendClass == null || !ILegend.class.isAssignableFrom(legendClass)) {
280
            throw new InvalidRegisteredClassException(ILegend.class,
281
                    legendClass, legendName);
282
        }
283

    
284
        legends.put(legendName, legendClass);
285
        notifyObservers(REGISTER_LEGEND, legendName, legendClass);
286
    }
287

    
288
    public ILegend createLegend(String legendName)
289
            throws MapContextRuntimeException {
290
        Class legendClass = (Class) legends.get(legendName);
291

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

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

    
330
    // =============================================================
331
    // Legend reading/writing
332

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

    
339
    private Class<ILegendReader> getLegendReaderForFormat(String format) {
340
        synchronized(legendReaders) {
341
            return legendReaders.get(format);
342
        }
343
    }
344

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

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

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

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

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

    
400
    @Override
401
    public ILegendReader createLegendReader(String format)
402
            throws MapContextRuntimeException {
403
        Class<ILegendReader> legendReaderClazz = getLegendReaderForFormat(format);
404

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

    
417
    @Override
418
    public ILegendWriter createLegendWriter(Class legendClass, String format)
419
            throws MapContextRuntimeException {
420

    
421
        if (legendClass == null || format == null) {
422
            return null;
423
        }
424

    
425
        Map<Class<ILegend>, Class<ILegendWriter>> legendFormatWriters = getLegendWritersForFormat(format);
426

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

    
458
    private ILegendWriter getSuperClassLegendWriter(Map<Class<ILegend>, Class<ILegendWriter>> clsToWtr, Class<ILegend> legclass)
459
            throws Exception {
460

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

    
483
    // =============================================================
484

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

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

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

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

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

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

    
521
    public IWarningSymbol getWarningSymbol(String message, String symbolDesc,
522
            int symbolDrawExceptionType) throws MapContextRuntimeException {
523
        return getSymbolManager().getWarningSymbol(message, symbolDesc,
524
                symbolDrawExceptionType);
525
    }
526

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

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

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

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

    
551
    public void registerSymbol(String symbolName, Class symbolClass)
552
            throws MapContextRuntimeException {
553
        getSymbolManager().registerSymbol(symbolName, symbolClass);
554
        notifyObservers(REGISTER_SYMBOL, symbolName, symbolClass);
555
    }
556

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

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

    
568
    public void saveSymbol(ISymbol symbol, String fileName, File folder)
569
            throws SymbolException {
570
        getSymbolManager().saveSymbol(symbol, fileName, folder);
571
    }
572

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

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

    
585
    public ILegend getLegend(DataStore dataStore) {
586
        ILegend legend = null;
587

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

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

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

    
632
        return legend;
633
    }
634

    
635
    public ILabelingStrategy getLabelingStrategy(DataStore dataStore) {
636
        ILabelingStrategy labelingStrategy = null;
637

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

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

    
667
        return labelingStrategy;
668
    }
669

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
810

    
811
}