/[schmitzm]/branches/1.0-gt2-2.6/src/skrueger/geotools/StyledLayerUtil.java
ViewVC logotype

Annotation of /branches/1.0-gt2-2.6/src/skrueger/geotools/StyledLayerUtil.java

Parent Directory Parent Directory | Revision Log Revision Log


Revision 400 - (hide annotations)
Mon Sep 14 12:24:50 2009 UTC (15 years, 5 months ago) by alfonx
File size: 37830 byte(s)
* Moving towards a better raster legend!
1 alfonx 244 /*******************************************************************************
2     * Copyright (c) 2009 Martin O. J. Schmitz.
3     *
4     * This file is part of the SCHMITZM library - a collection of utility
5 alfonx 256 * classes based on Java 1.6, focusing (not only) on Java Swing
6 alfonx 244 * and the Geotools library.
7     *
8     * The SCHMITZM project is hosted at:
9     * http://wald.intevation.org/projects/schmitzm/
10     *
11     * This program is free software; you can redistribute it and/or
12     * modify it under the terms of the GNU Lesser General Public License
13     * as published by the Free Software Foundation; either version 3
14     * of the License, or (at your option) any later version.
15     *
16     * This program is distributed in the hope that it will be useful,
17     * but WITHOUT ANY WARRANTY; without even the implied warranty of
18     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19     * GNU General Public License for more details.
20     *
21     * You should have received a copy of the GNU Lesser General Public License (license.txt)
22     * along with this program; if not, write to the Free Software
23     * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
24     * or try this link: http://www.gnu.org/licenses/lgpl.html
25     *
26     * Contributors:
27     * Martin O. J. Schmitz - initial API and implementation
28     * Stefan A. Krüger - additional utility classes
29     ******************************************************************************/
30     package skrueger.geotools;
31    
32 alfonx 397 import java.awt.Color;
33     import java.awt.Dimension;
34     import java.awt.Graphics;
35 alfonx 400 import java.awt.Graphics2D;
36     import java.awt.Rectangle;
37     import java.awt.geom.AffineTransform;
38 alfonx 397 import java.awt.image.BufferedImage;
39 alfonx 244 import java.io.File;
40     import java.io.FileNotFoundException;
41     import java.io.FileWriter;
42     import java.net.URL;
43     import java.text.DecimalFormat;
44     import java.util.HashMap;
45     import java.util.List;
46     import java.util.Map;
47 alfonx 400 import java.util.Set;
48 alfonx 244 import java.util.SortedMap;
49     import java.util.TreeMap;
50    
51 alfonx 397 import javax.swing.Box;
52     import javax.swing.BoxLayout;
53     import javax.swing.ImageIcon;
54     import javax.swing.JLabel;
55    
56 alfonx 244 import org.apache.log4j.Logger;
57     import org.geotools.coverage.grid.GridCoverage2D;
58     import org.geotools.coverage.grid.io.AbstractGridCoverage2DReader;
59     import org.geotools.feature.FeatureCollection;
60     import org.geotools.map.DefaultMapLayer;
61     import org.geotools.map.MapLayer;
62 alfonx 400 import org.geotools.renderer.lite.gridcoverage2d.GridCoverageRenderer;
63 alfonx 244 import org.geotools.styling.ColorMap;
64     import org.geotools.styling.ColorMapEntry;
65 alfonx 397 import org.geotools.styling.FeatureTypeStyle;
66 alfonx 244 import org.geotools.styling.RasterSymbolizer;
67 alfonx 397 import org.geotools.styling.Rule;
68 alfonx 244 import org.geotools.styling.Style;
69     import org.jdom.Document;
70     import org.jdom.Element;
71     import org.jdom.input.SAXBuilder;
72     import org.jdom.output.XMLOutputter;
73 alfonx 397 import org.opengis.feature.simple.SimpleFeatureType;
74 alfonx 244
75 alfonx 400 import schmitzm.geotools.JTSUtil;
76 alfonx 244 import schmitzm.geotools.styling.StylingUtil;
77     import schmitzm.io.IOUtil;
78     import schmitzm.lang.LangUtil;
79     import schmitzm.swing.SwingUtil;
80     import skrueger.AttributeMetaData;
81     import skrueger.RasterLegendData;
82     import skrueger.i8n.Translation;
83    
84     /**
85     * This class provides static helper methods for dealing with
86     * {@link StyledLayerInterface} stuff.
87 alfonx 400 *
88     * @author <a href="mailto:[email protected]">Martin Schmitz</a>
89     * (University of Bonn/Germany)
90 alfonx 244 * @version 1.0
91     */
92     public class StyledLayerUtil {
93 alfonx 400 private static final Logger LOGGER = Logger.getLogger(StyledLayerUtil.class
94     .getName());
95     private static final SAXBuilder SAX_BUILDER = new SAXBuilder();
96     private static final XMLOutputter XML_OUTPUTTER = new XMLOutputter();
97 alfonx 244
98 alfonx 400 /** URL for Atlas XML schema */
99     public static final String AMLURI = "http://www.wikisquare.de/AtlasML";
100     /** Name of the XML Element for the attribute meta data map */
101     public static final String ELEM_NAME_AMD = "attributeMetaData";
102     /** Name of the XML Element for the raster legend data */
103     public static final String ELEM_NAME_RLD = "rasterLegendData";
104     /** Name of the XML Element for an attribute meta data map entry */
105     public static final String ELEM_NAME_ATTRIBUTE = "dataAttribute";
106     /** Name of the XML Element for an raster legend data entry */
107     public static final String ELEM_NAME_RASTERLEGEND = "rasterLegendItem";
108     /** Name of the XML Element for a translation */
109     public static final String ELEM_NAME_TRANSLATION = "translation";
110 alfonx 244
111 alfonx 400 /**
112     * Creates a Geotools {@link MapLayer} from an object. If the object is a
113     * {@link StyledLayerInterface} then its sytle is used. In case of direct
114     * Geotools objects ({@link GridCoverage2D},
115     * {@link AbstractGridCoverage2DReader}, {@link FeatureCollection}) a
116     * default style is generated.
117     *
118     * @param object
119     * an Object
120     * @exception Exception
121     * if {@code null} is given as object or an error occurs
122     * during layer creation
123     */
124     public static MapLayer createMapLayer(Object object) throws Exception {
125     return createMapLayer(object, null);
126     }
127 alfonx 244
128 alfonx 400 /**
129     * Creates a Geotools {@link MapLayer} from an object. If the object is a
130     * {@link StyledLayerInterface} then its sytle is used. In case of direct
131     * Geotools objects ({@link GridCoverage2D},
132     * {@link AbstractGridCoverage2DReader}, {@link FeatureCollection}) a
133     * default style is generated.
134     *
135     * @param object
136     * an Object
137     * @param forcedStyle
138     * (SLD-)Style to force for the object
139     * @exception Exception
140     * if {@code null} is given as object or an error occurs
141     * during layer creation
142     */
143     public static MapLayer createMapLayer(Object object, Style forcedStyle)
144     throws Exception {
145     MapLayer layer = null;
146     Style style = null;
147     if (object instanceof StyledLayerInterface) {
148     style = ((StyledLayerInterface<?>) object).getStyle();
149     object = ((StyledLayerInterface<?>) object).getGeoObject();
150     }
151     if (forcedStyle != null)
152     style = forcedStyle;
153     if (style == null)
154     style = StylingUtil.createDefaultStyle(object);
155 alfonx 244
156 alfonx 400 if (object instanceof GridCoverage2D)
157     layer = new DefaultMapLayer((GridCoverage2D) object, style);
158     if (object instanceof AbstractGridCoverage2DReader)
159     layer = new DefaultMapLayer((AbstractGridCoverage2DReader) object,
160     style);
161     if (object instanceof FeatureCollection)
162     layer = new DefaultMapLayer((FeatureCollection) object, style);
163 alfonx 244
164 alfonx 400 if (layer == null)
165     throw new Exception("Can not create MapLayer from "
166     + (object == null ? "null" : object.getClass()));
167 alfonx 244
168 alfonx 400 return layer;
169     }
170 alfonx 244
171 alfonx 400 /**
172     * Creates an default instance of {@link StyledLayerInterface} for a
173     * Geotools object ({@link GridCoverage2D}, {@link FeatureCollection}) with
174     * a default style.
175     *
176     * @param object
177     * an Object
178     * @param title
179     * title for the object
180     * @exception UnsupportedOperationException
181     * if {@code null} is given as object or an error occurs
182     * during creation
183     */
184     public static StyledLayerInterface<?> createStyledLayer(Object object,
185     String title) {
186     return createStyledLayer(object, title, null);
187     }
188 alfonx 244
189 alfonx 400 /**
190     * Creates an default instance of {@link StyledLayerInterface} for a
191     * Geotools object ({@link GridCoverage2D}, {@link FeatureCollection}) with
192     * a given style.
193     *
194     * @param object
195     * an Object
196     * @param title
197     * title for the object
198     * @param style
199     * style and meta data for the object
200     * @exception UnsupportedOperationException
201     * if {@code null} is given as object or an error occurs
202     * during creation
203     */
204     public static StyledLayerInterface<?> createStyledLayer(Object object,
205     String title, StyledLayerStyle style) {
206     StyledLayerInterface<?> styledLayer = null;
207 alfonx 244
208 alfonx 400 String id = (title != null) ? title : "defaultID";
209 alfonx 244
210 alfonx 400 if (object instanceof GridCoverage2D)
211     styledLayer = new StyledGridCoverage((GridCoverage2D) object, id,
212     title, style);
213     else if (object instanceof AbstractGridCoverage2DReader)
214     styledLayer = new StyledGridCoverageReader(
215     (AbstractGridCoverage2DReader) object, id, title, style);
216     else if (object instanceof FeatureCollection)
217     styledLayer = new StyledFeatureCollection(
218     (FeatureCollection) object, id, title, style);
219 alfonx 244
220 alfonx 400 if (styledLayer == null)
221     throw new UnsupportedOperationException(
222     "Can not create StyledLayerInterface object from "
223     + (object == null ? "null" : object.getClass()));
224 alfonx 244
225 alfonx 400 return styledLayer;
226     }
227 alfonx 244
228 alfonx 400 /**
229     * Return only the visible or invisible entries of an AttributeMetaData-Map.
230     *
231     * @param amdMap
232     * AttributeMetaData-Map
233     * @param visible
234     * indicated whether the visible or invisible entries are
235     * returned
236     */
237     public static SortedMap<Integer, AttributeMetaData> getVisibleAttributeMetaData(
238     Map<Integer, AttributeMetaData> amdMap, boolean visible) {
239     SortedMap<Integer, AttributeMetaData> filteredMap = new TreeMap<Integer, AttributeMetaData>();
240     for (AttributeMetaData amd : amdMap.values())
241     if (amd.isVisible())
242     filteredMap.put(amd.getColIdx(), amd);
243 alfonx 244
244 alfonx 400 return filteredMap;
245     }
246 alfonx 244
247 alfonx 400 /**
248     * Parses a {@link AttributeMetaData} object from an JDOM-{@link Element}.
249     * This method works like {@link
250     * AMLImport#parseDataAttribute(org.w3c.dom.Node}, but for JDOM.
251     *
252     * @param element
253     * {@link Element} to parse
254     */
255     public static AttributeMetaData parseAttributeMetaData(final Element element) {
256     final Integer col = Integer.valueOf(element.getAttributeValue("col"));
257     final Boolean visible = Boolean.valueOf(element
258     .getAttributeValue("visible"));
259     final String unit = element.getAttributeValue("unit");
260 alfonx 244
261 alfonx 400 Translation name = new Translation();
262     Translation desc = new Translation();
263     for (final Element childElement : (List<Element>) element.getChildren()) {
264     if (childElement.getName() == null)
265     continue;
266 alfonx 244
267 alfonx 400 if (childElement.getName().equals("name"))
268     name = parseTranslation(childElement);
269     else if (childElement.getName().equals("desc"))
270     desc = parseTranslation(childElement);
271     }
272     return new AttributeMetaData(col, visible, name, desc, unit);
273     }
274 alfonx 244
275 alfonx 400 /**
276     * Parses a {@link AttributeMetaData} map from an JDOM-{@link Element} with
277     * {@code <attribute>}-childs.
278     *
279     * @param element
280     * {@link Element} to parse
281     */
282     public static Map<Integer, AttributeMetaData> parseAttributeMetaDataMap(
283     final Element element) {
284     HashMap<Integer, AttributeMetaData> metaData = new HashMap<Integer, AttributeMetaData>();
285     List<Element> attributesElements = element
286     .getChildren(ELEM_NAME_ATTRIBUTE);
287     for (Element attibuteElement : attributesElements) {
288     AttributeMetaData attrMetaData = parseAttributeMetaData(attibuteElement);
289     metaData.put(attrMetaData.getColIdx(), attrMetaData);
290     }
291     return metaData;
292     }
293 alfonx 244
294 alfonx 400 /**
295     * Loads a {@link AttributeMetaData} object from an URL.
296     *
297     * @param documentUrl
298     * {@link URL} to parse
299     * @see #parseAttributeMetaData(Element)
300     */
301     public static Map<Integer, AttributeMetaData> loadAttributeMetaDataMap(
302     final URL documentUrl) throws Exception {
303     Document document = SAX_BUILDER.build(documentUrl);
304     return parseAttributeMetaDataMap(document.getRootElement());
305     }
306 alfonx 244
307 alfonx 400 /**
308     * Creates an JDOM {@link Element} for the given {@link AttributeMetaData}
309     * object.
310     *
311     * @param amd
312     * meta data for one attribute
313     */
314     public static Element createAttributeMetaDataElement(
315     final AttributeMetaData amd) {
316     final Element element = new Element(ELEM_NAME_ATTRIBUTE, AMLURI);
317     element.setAttribute("col", String.valueOf(amd.getColIdx()));
318     element.setAttribute("visible", String.valueOf(amd.isVisible()));
319     element.setAttribute("unit", amd.getUnit());
320     // Creating a aml:name tag...
321     element.addContent(createTranslationElement("name", amd.getTitle()));
322     // Creating a aml:desc tag...
323     element.addContent(createTranslationElement("desc", amd.getDesc()));
324     return element;
325     }
326 alfonx 244
327 alfonx 400 /**
328     * Creates an JDOM {@link Element} for the given {@link AttributeMetaData}
329     * map.
330     *
331     * @param amdMap
332     * map of attribute meta data
333     */
334     public static Element createAttributeMetaDataMapElement(
335     final Map<Integer, AttributeMetaData> amdMap) {
336     final Element element = new Element(ELEM_NAME_AMD, AMLURI);
337     for (AttributeMetaData amd : amdMap.values())
338     element.addContent(createAttributeMetaDataElement(amd));
339     return element;
340     }
341 alfonx 244
342 alfonx 400 /**
343     * Saves a {@link AttributeMetaData AttributeMetaData-Map} to an URL.
344     *
345     * @param amdMap
346     * map of {@link AttributeMetaData}
347     * @param documentUrl
348     * {@link URL} to store the XML
349     */
350     public static void saveAttributeMetaDataMap(
351     final Map<Integer, AttributeMetaData> amdMap, final URL documentUrl)
352     throws Exception {
353     // Create XML-Document
354     final FileWriter out = new FileWriter(new File(documentUrl.toURI()));
355     XML_OUTPUTTER.output(createAttributeMetaDataMapElement(amdMap), out);
356     out.flush();
357     out.close();
358     }
359 alfonx 244
360 alfonx 400 /**
361     * Parses a {@link RasterLegendData} object from an JDOM-{@link Element}.
362     * This method works like {@link
363     * AMLImport#parseRasterLegendData(org.w3c.dom.Node}, but for JDOM.
364     *
365     * @param element
366     * {@link Element} to parse
367     */
368     public static RasterLegendData parseRasterLegendData(Element element) {
369 alfonx 244
370 alfonx 400 final boolean paintGaps = Boolean.valueOf(element
371     .getAttributeValue("paintGaps"));
372 alfonx 244
373 alfonx 400 RasterLegendData rld = new RasterLegendData(paintGaps);
374 alfonx 244
375 alfonx 400 for (Element childElement : (List<Element>) element.getChildren()) {
376     final String name = childElement.getName();
377     // Cancel if it's an attribute
378     if (childElement.getChildren().size() == 0)
379     continue;
380 alfonx 244
381 alfonx 400 if (name.equals(ELEM_NAME_RASTERLEGEND)) {
382     final String valueAttr = childElement
383     .getAttributeValue("value");
384     if (valueAttr == null)
385     throw new UnsupportedOperationException(
386     "Attribute 'value' missing for definition of <"
387     + ELEM_NAME_RASTERLEGEND + ">");
388     final double value = Double.valueOf(valueAttr);
389 alfonx 244
390 alfonx 400 // first and only item should be the label
391     final Element labelElement = childElement.getChild("label");
392     // id label element is missing, the translation is searched
393     // directly
394     // as childs of the rasterLegendItem element
395     Translation label = parseTranslation(labelElement != null ? labelElement
396     : childElement);
397     rld.put(value, label);
398     }
399     }
400 alfonx 244
401 alfonx 400 return rld;
402     }
403 alfonx 244
404 alfonx 400 /**
405     * Loads a {@link RasterLegendData} object from an URL.
406     *
407     * @param documentUrl
408     * {@link URL} to parse
409     * @see #parseAttributeMetaData(Element)
410     */
411     public static RasterLegendData loadRasterLegendData(final URL documentUrl)
412     throws Exception {
413     Document document = SAX_BUILDER.build(documentUrl);
414     return parseRasterLegendData(document.getRootElement());
415     }
416 alfonx 244
417 alfonx 400 /**
418     * Creates an JDOM {@link Element} for the given {@link RasterLegendData}
419     * map.
420     *
421     * @param rld
422     * raster legend data
423     */
424     public static Element createRasterLegendDataElement(
425     final RasterLegendData rld) {
426     final Element element = new Element(ELEM_NAME_RLD, AMLURI);
427     element.setAttribute("paintGaps", rld.isPaintGaps().toString());
428     for (Double key : rld.getSortedKeys()) {
429     Element item = new Element(ELEM_NAME_RASTERLEGEND, AMLURI);
430     item.setAttribute("value", key.toString());
431     item.addContent(createTranslationElement("label", rld.get(key)));
432     element.addContent(item);
433     }
434     return element;
435     }
436 alfonx 244
437 alfonx 400 /**
438     * Creates {@link RasterLegendData} from a {@link ColorMap}.
439     *
440     * @param colorMap
441     * a color map
442     * @param paintGaps
443     * indicated whether gaps are painted between the legend items
444     * @param digits
445     * number of digits the grid value classes (and legend) are
446     * rounded to (null means no round; >= 0 means digits after
447     * comma; < 0 means digits before comma)
448     */
449     public static RasterLegendData generateRasterLegendData(ColorMap colorMap,
450     boolean paintGaps, Integer digits) {
451     DecimalFormat decFormat = digits != null ? new DecimalFormat(SwingUtil
452     .getNumberFormatPattern(digits)) : null;
453     RasterLegendData rld = new RasterLegendData(paintGaps);
454     for (ColorMapEntry cme : colorMap.getColorMapEntries()) {
455     double value = StylingUtil.getQuantityFromColorMapEntry(cme);
456     String label = cme.getLabel();
457     // if no label is set (e.g. quantitative style),
458     // use the value as label
459     if (label == null || label.equals(""))
460     if (digits == null)
461     label = String.valueOf(value);
462     else
463     label = decFormat.format(LangUtil.round(value, digits));
464     rld.put(value, new Translation(" " + label));
465     }
466     return rld;
467     }
468 alfonx 244
469 alfonx 400 /**
470     * Creates {@link RasterLegendData} from the {@link ColorMap} of a style.
471     *
472     * @param style
473     * a raster style (must contain a {@link RasterSymbolizer})
474     * @param paintGaps
475     * indicated whether gaps are painted between the legend items
476     * @param digits
477     * number of digits the grid value classes (and legend) are
478     * rounded to (null means no round; >= 0 means digits after
479     * comma; < 0 means digits before comma)
480     */
481     public static RasterLegendData generateRasterLegendData(Style style,
482     boolean paintGaps, Integer digits) {
483     ColorMap colorMap = StylingUtil.getColorMapFromStyle(style);
484     if (colorMap == null)
485     throw new IllegalArgumentException(
486     "Color map can not be determined from style!");
487     return generateRasterLegendData(colorMap, paintGaps, digits);
488     }
489 alfonx 244
490 alfonx 400 /**
491     * Saves a {@link RasterLegendData} to an URL.
492     *
493     * @param rld
494     * raster legend data
495     * @param documentUrl
496     * {@link URL} to store the XML
497     */
498     public static void saveRasterLegendData(final RasterLegendData rld,
499     final URL documentUrl) throws Exception {
500     // Create XML-Document
501     final FileWriter out = new FileWriter(new File(documentUrl.toURI()));
502     XML_OUTPUTTER.output(createRasterLegendDataElement(rld), out);
503     out.flush();
504     out.close();
505     }
506 alfonx 244
507 alfonx 400 /**
508     * Parses a {@link Translation} object from an JDOM-{@link Element}. This
509     * method works like {@link AMLImport#parseTranslation(org.w3c.dom.Node},
510     * but for JDOM.
511     *
512     * @param element
513     * {@link Element} to parse
514     */
515     public final static Translation parseTranslation(final Element element) {
516     Translation trans = new Translation();
517 alfonx 244
518 alfonx 400 if (element == null)
519     return trans;
520 alfonx 244
521 alfonx 400 for (final Element translationElement : (List<Element>) element
522     .getChildren()) {
523     final String name = translationElement.getName();
524     if (name == null)
525     continue;
526 alfonx 244
527 alfonx 400 // lang attribute
528     String lang = translationElement.getAttributeValue("lang");
529     // set the default, if no language code is set
530     if (lang == null)
531     lang = Translation.DEFAULT_KEY;
532 alfonx 244
533 alfonx 400 final String translationText = translationElement.getValue();
534     if (translationText == null)
535     trans.put(lang, "");
536     else
537     trans.put(lang, translationText);
538     }
539 alfonx 244
540 alfonx 400 // if no <translation> is given, the value of the node should
541     // be used as a default translation
542     if (trans.size() == 0)
543     trans.put(Translation.DEFAULT_KEY, element.getValue());
544     // trans = new Translation(
545     // ((List<Element>)element.getChildren()).get(0).getValue() );
546 alfonx 244
547 alfonx 400 return trans;
548     }
549 alfonx 244
550 alfonx 400 /**
551     * Creates an JDOM {@link Element} for the given {@link Translation}.
552     *
553     * @param tagname
554     * Name of the Element
555     * @param translation
556     * Translation to store in the Element
557     */
558     public final static Element createTranslationElement(String tagname,
559     Translation translation) {
560     Element element = new Element(tagname, AMLURI);
561     if (translation == null)
562     throw new UnsupportedOperationException(
563     "Translation element can not be created from null!");
564 alfonx 244
565 alfonx 400 // If only a default translation is set, the <translation
566     // lang="..">..</tranlation>
567     // part is not used
568     if (translation.keySet().size() == 1
569     && translation.get(Translation.DEFAULT_KEY) != null) {
570     element.addContent(translation.get(Translation.DEFAULT_KEY));
571     return element;
572     }
573 alfonx 244
574 alfonx 400 // add a <translation lang="..">..</tranlation> part to the element for
575     // all languages
576     for (String lang : translation.keySet()) {
577     Element translationElement = new Element(ELEM_NAME_TRANSLATION,
578     AMLURI);
579     translationElement.setAttribute("lang", lang);
580     String translationString = translation.get(lang);
581     if (translationString == null)
582     translationString = "";
583     translationElement.addContent(translationString);
584     element.addContent(translationElement);
585     }
586 alfonx 244
587 alfonx 400 return element;
588     }
589 alfonx 244
590 alfonx 400 /**
591     * Sets a style to {@link StyledLayerInterface}.
592     *
593     * @param styledObject
594     * a styled object
595     * @param style
596     * a Style
597     */
598     public static void setStyledLayerStyle(StyledLayerInterface styledObject,
599     StyledLayerStyle<?> style) {
600     // set SLD style
601     styledObject.setStyle(style.getGeoObjectStyle());
602     // set meta data
603     if (styledObject instanceof StyledGridCoverageInterface
604     && (style.getMetaData() instanceof RasterLegendData || style
605     .getMetaData() == null)) {
606     RasterLegendData sourceRld = (RasterLegendData) style.getMetaData();
607     RasterLegendData destRld = ((StyledGridCoverageInterface) styledObject)
608     .getLegendMetaData();
609     if (destRld != null && sourceRld != null) {
610     destRld.setPaintGaps(sourceRld.isPaintGaps());
611     destRld.clear();
612     destRld.putAll(sourceRld);
613     }
614     return;
615     }
616     if (styledObject instanceof StyledFeatureCollectionInterface
617     && (style.getMetaData() instanceof Map || style.getMetaData() == null)) {
618     Map<Integer, AttributeMetaData> sourceAmd = (Map<Integer, AttributeMetaData>) style
619     .getMetaData();
620     Map<Integer, AttributeMetaData> destAmd = ((StyledFeatureCollectionInterface) styledObject)
621     .getAttributeMetaDataMap();
622     if (destAmd != null && sourceAmd != null) {
623     destAmd.clear();
624     destAmd.putAll(sourceAmd);
625     }
626     return;
627     }
628 alfonx 244
629 alfonx 400 throw new UnsupportedOperationException(
630     "Style is not compatible to object: "
631     + (style.getMetaData() == null ? null : style
632     .getMetaData().getClass().getSimpleName())
633     + " <-> "
634     + (styledObject == null ? null : styledObject
635     .getClass().getSimpleName()));
636     }
637 alfonx 244
638 alfonx 400 /**
639     * Returns the style a {@link StyledLayerInterface} as a
640     * {@link StyledLayerStyle}.
641     *
642     * @param styledObject
643     * a styled object
644     * @return {@code StyledLayerStyle<RasterLegendData>} for
645     * {@link StyledGridCoverageInterface} or {@code
646     * StyledLayerStyle<Map<Integer,AttributeMetaData>>} for
647     * {@link StyledFeatureCollectionInterface}
648     */
649     public static StyledLayerStyle<?> getStyledLayerStyle(
650     StyledLayerInterface styledObject) {
651     if (styledObject instanceof StyledGridCoverageInterface)
652     return getStyledLayerStyle((StyledGridCoverageInterface) styledObject);
653     if (styledObject instanceof StyledFeatureCollectionInterface)
654     return getStyledLayerStyle((StyledFeatureCollectionInterface) styledObject);
655     throw new UnsupportedOperationException(
656     "Unknown type of StyledLayerInterface: "
657     + (styledObject == null ? null : styledObject
658     .getClass().getSimpleName()));
659     }
660 alfonx 244
661 alfonx 400 /**
662     * Returns the style and raster meta data of a
663     * {@link StyledGridCoverageInterface} as a {@link StyledLayerStyle}.
664     *
665     * @param styledGC
666     * a styled grid coverage
667     */
668     public static StyledLayerStyle<RasterLegendData> getStyledLayerStyle(
669     StyledGridCoverageInterface styledGC) {
670     return new StyledLayerStyle<RasterLegendData>(styledGC.getStyle(),
671     styledGC.getLegendMetaData());
672     }
673 alfonx 244
674 alfonx 400 /**
675     * Returns the style and attribute meta data of a
676     * {@link StyledFeatureCollectionInterface} as a {@link StyledLayerStyle}.
677     *
678     * @param styledFC
679     * a styled feature collection
680     */
681     public static StyledLayerStyle<Map<Integer, AttributeMetaData>> getStyledLayerStyle(
682     StyledFeatureCollectionInterface styledFC) {
683     return new StyledLayerStyle<Map<Integer, AttributeMetaData>>(styledFC
684     .getStyle(), styledFC.getAttributeMetaDataMap());
685     }
686 alfonx 244
687 alfonx 400 /**
688     * Loads a {@linkplain Style SLD-Style} and {@linkplain RasterLegendData
689     * Raster-LegendData} for a given geo-object (raster) source. The SLD file
690     * must be present. A missing raster legend-data file is tolerated.
691     *
692     * @param geoObjectURL
693     * URL of the (already read) raster object
694     * @param sldExt
695     * file extention for the SLD file
696     * @param rldExt
697     * file extention for the raster legend-data file
698     * @return {@code null} in case of any error
699     */
700     public static StyledLayerStyle<RasterLegendData> loadStyledRasterStyle(
701     URL geoObjectURL, String sldExt, String rldExt) {
702     RasterLegendData metaData = null;
703     Style sldStyle = null;
704     try {
705     Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(
706     geoObjectURL, sldExt));
707     // SLD must be present
708     if (styles == null || styles.length == 0)
709     return null;
710     sldStyle = styles[0];
711     } catch (Exception err) {
712     // SLD must be present
713     LangUtil.logDebugError(LOGGER, err);
714     return null;
715     }
716 alfonx 244
717 alfonx 400 try {
718     metaData = StyledLayerUtil.loadRasterLegendData(IOUtil
719     .changeUrlExt(geoObjectURL, rldExt));
720     } catch (FileNotFoundException err) {
721     // ignore missing raster legend data
722     } catch (Exception err) {
723     // any other error during legend data creation leads to error
724     LangUtil.logDebugError(LOGGER, err);
725     return null;
726     }
727     return new StyledLayerStyle<RasterLegendData>(sldStyle, metaData);
728     }
729 alfonx 244
730 alfonx 400 /**
731     * Loads a {@linkplain Style SLD-Style} from a {@code .sld} file and
732     * {@linkplain RasterLegendData Raster-LegendData} from a {@code .rld} file
733     * for a given geo-object (raster) source. The SLD file must be present. A
734     * missing raster legend-data file is tolerated.
735     *
736     * @param geoObjectURL
737     * URL of the (already read) raster object
738     * @param sldExt
739     * file extention for the SLD file
740     * @param rldExt
741     * file extention for the raster legend-data file
742     * @return {@code null} in case of any error
743     */
744     public static StyledLayerStyle<RasterLegendData> loadStyledRasterStyle(
745     URL geoObjectURL) {
746     return loadStyledRasterStyle(geoObjectURL, "sld", "rld");
747     }
748 alfonx 244
749 alfonx 400 /**
750     * Loads a {@linkplain Style SLD-Style} and a {@linkplain AttributeMetaData
751     * AttributeMetaData-Map} for a given geo-object (feature) source. The SLD
752     * file must be present. A missing attribute meta-data file is tolerated.
753     *
754     * @param geoObjectURL
755     * URL of the (already read) feature object
756     * @param sldExt
757     * file extention for the SLD file
758     * @param rldExt
759     * file extention for the raster legend-data file
760     * @return {@code null} in case of any error
761     */
762     public static StyledLayerStyle<Map<Integer, AttributeMetaData>> loadStyledFeatureStyle(
763     URL geoObjectURL, String sldExt, String rldExt) {
764     Map<Integer, AttributeMetaData> metaData = null;
765     Style sldStyle = null;
766     try {
767     Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(
768     geoObjectURL, sldExt));
769     // SLD must be present
770     if (styles == null || styles.length == 0)
771     return null;
772     sldStyle = styles[0];
773     } catch (Exception err) {
774     // SLD must be present
775     LangUtil.logDebugError(LOGGER, err);
776     return null;
777     }
778 alfonx 244
779 alfonx 400 try {
780     metaData = StyledLayerUtil.loadAttributeMetaDataMap(IOUtil
781     .changeUrlExt(geoObjectURL, rldExt));
782     } catch (FileNotFoundException err) {
783     // ignore missing attribute meta data
784     } catch (Exception err) {
785     // any other error during meta data creation leads to error
786     LangUtil.logDebugError(LOGGER, err);
787     return null;
788     }
789 alfonx 244
790 alfonx 400 return new StyledLayerStyle<Map<Integer, AttributeMetaData>>(sldStyle,
791     metaData);
792     }
793 alfonx 244
794 alfonx 400 /**
795     * Loads a {@linkplain Style SLD-Style} from a {@code .sld} file and
796     * {@linkplain AttributeMetaData AttributeMetaData-Map} from a {@code .amd}
797     * file for a given geo-object (feature) source. The SLD file must be
798     * present. A missing attribute meta-data file is tolerated.
799     *
800     * @param geoObjectURL
801     * URL of the (already read) feature object
802     * @param sldExt
803     * file extention for the SLD file
804     * @param rldExt
805     * file extention for the raster legend-data file
806     * @return {@code null} in case of any error
807     */
808     public static StyledLayerStyle<Map<Integer, AttributeMetaData>> loadStyledFeatureStyle(
809     URL geoObjectURL) {
810     return loadStyledFeatureStyle(geoObjectURL, "sld", "amd");
811     }
812 alfonx 244
813 alfonx 400 /**
814     * Stores a {@linkplain Style SLD-Style} and {@linkplain RasterLegendData
815     * Raster-LegendData} for a given geo-object (raster) source.
816     *
817     * @param style
818     * style to save
819     * @param geoObjectURL
820     * URL of the raster object
821     * @param sldExt
822     * file extention for the SLD file
823     * @param mdExt
824     * file extention for the meta-data file
825     */
826     public static <T> void saveStyledLayerStyle(StyledLayerStyle<T> style,
827     URL geoObjectURL, String sldExt, String mdExt) throws Exception {
828     // Store the SLD
829     Style sldStyle = style.getGeoObjectStyle();
830     if (sldStyle != null) {
831     StylingUtil.saveStyleToSLD(sldStyle, IOUtil.changeFileExt(new File(
832     geoObjectURL.toURI()), sldExt));
833     }
834 alfonx 244
835 alfonx 400 // Store the meta data
836     T metaData = style.getMetaData();
837     if (metaData != null) {
838     if (metaData instanceof RasterLegendData) {
839     saveRasterLegendData((RasterLegendData) metaData, IOUtil
840     .changeUrlExt(geoObjectURL, mdExt));
841     // } else if ( metaData instanceof
842     // Map<Integer,AttributeMetaData> ) { // LEIDER NICHT
843     // KOMPILIERBAR!!
844     } else if (metaData instanceof Map) {
845     saveAttributeMetaDataMap(
846     (Map<Integer, AttributeMetaData>) metaData, IOUtil
847     .changeUrlExt(geoObjectURL, mdExt));
848     } else
849     throw new UnsupportedOperationException(
850     "Export for meta data not yet supported: "
851     + metaData.getClass().getSimpleName());
852     }
853     }
854 alfonx 244
855 alfonx 400 /**
856     * Stores the {@linkplain Style SLD-Style} to a {@code .sld} file and the
857     * meta data ({@link RasterLegendData} or {@link AttributeMetaData}) to a
858     * {@code .rld} or {@code .amd} file. for a given geo-object source.
859     *
860     * @param style
861     * style to save
862     * @param geoObjectURL
863     * URL of the (already read) raster object
864     */
865     public static void saveStyledLayerStyle(StyledLayerStyle<?> style,
866     URL geoObjectURL) throws Exception {
867     if (style.getMetaData() instanceof RasterLegendData)
868     saveStyledLayerStyle(style, geoObjectURL, "sld", "rld");
869     else
870     saveStyledLayerStyle(style, geoObjectURL, "sld", "amd");
871     }
872 alfonx 244
873 alfonx 397 /**
874     * Creates a {@link Box} that shows a legend for a list of
875     * {@link FeatureTypeStyle}s and a targeted featureType
876     *
877     * @param featureType
878     * If this a legend for Point, Polygon or Line?
879     * @param list
880     * The Styles to presented in this legend
881     *
882     * @author <a href="mailto:[email protected]">Stefan Alfons
883     * Kr&uuml;ger</a>
884     */
885     public static Box createLegendPanel(List<FeatureTypeStyle> list,
886     SimpleFeatureType featureType, int iconWidth, int iconHeight) {
887    
888     Box box = new Box(BoxLayout.Y_AXIS) {
889    
890     /**
891     * Nuetzlich wenn die Componente gedruckt (z.B. wenn ein Screenshot
892     * gemacht wird) wird. Dann werden wird der Hintergrund auf WEISS
893     * gesetzt.
894     *
895     * @author <a href="mailto:[email protected]">Stefan Alfons
896     * Kr&uuml;ger</a>
897     */
898     @Override
899     public void print(Graphics g) {
900     final Color orig = getBackground();
901     setBackground(Color.WHITE);
902     // wrap in try/finally so that we always restore the state
903     try {
904     super.print(g);
905     } finally {
906     setBackground(orig);
907     }
908     }
909     };
910    
911     for (FeatureTypeStyle ftStyle : list) {
912    
913     // One child-node for every rule
914     List<Rule> rules = ftStyle.rules();
915     for (Rule rule : rules) {
916    
917     /**
918     * Let's not create a hbox for Rules that only contain
919     * TextSymbolizers
920     */
921     if (StylingUtil.getTextSymbolizers(rule.getSymbolizers())
922     .size() == rule.getSymbolizers().length)
923     continue;
924    
925     Box hbox = new Box(BoxLayout.X_AXIS) {
926    
927     /**
928     * Nuetzlich wenn die Componente gedruckt (z.B. wenn ein
929     * Screenshot gemacht wird) wird. Dann werden wird der
930     * Hintergrund auf WEISS gesetzt.
931     */
932     @Override
933     public void print(Graphics g) {
934     final Color orig = getBackground();
935     setBackground(Color.WHITE);
936     // wrap in try/finally so that we always restore the
937     // state
938     try {
939     super.print(g);
940     } finally {
941     setBackground(orig);
942     }
943     }
944     };
945    
946     /**
947     * The size of the legend Symbol is dependent on the size of the
948     * font.
949     */
950     final int fontHeight = new JLabel().getFontMetrics(
951     new JLabel().getFont()).getHeight();
952 alfonx 400
953 alfonx 397 final Dimension ICON_SIZE = new Dimension(iconWidth,
954     fontHeight > 5 ? fontHeight : iconHeight);
955    
956     // ****************************************************************************
957     // Create the actual icon
958     // ****************************************************************************
959     final BufferedImage imageForRule = LegendIconFeatureRenderer
960     .getInstance().createImageForRule(rule, featureType,
961     ICON_SIZE);
962    
963     // LOGGER.debug("Creating a new Legend Image for RUle name =
964     // "+rule.getName());
965    
966     ImageIcon legendIcon = new ImageIcon(imageForRule);
967    
968     final JLabel iconLabel = new JLabel(legendIcon);
969     hbox.setAlignmentX(0f);
970     hbox.add(iconLabel);
971     hbox.add(Box.createHorizontalStrut(3));
972    
973     // ****************************************************************************
974     // The labeltext is read from the SLD. Its either the title
975     // directly, or interpreted as OneLine Code
976     // ****************************************************************************
977     // final String rawText =
978     // rule.getDescription().getTitle().toString();
979 alfonx 400 final String rawText = rule.getDescription().getTitle()
980     .toString();
981 alfonx 397
982     Translation labelT = new Translation();
983     labelT.fromOneLine(rawText);
984    
985     final JLabel classTitleLabel = new JLabel(labelT.toString());
986     hbox.add(classTitleLabel);
987 alfonx 400 classTitleLabel.setLabelFor(iconLabel);
988 alfonx 397
989     box.add(hbox);
990    
991     }
992     }
993    
994     return box;
995     }
996    
997     /**
998 alfonx 400 * Creates a
999     *
1000 alfonx 397 * @param styledGrid
1001 alfonx 400 * @param iconHeight
1002     * @param iconWidth
1003 alfonx 397 * @return
1004     */
1005 alfonx 400 public static Box createLegendPanel(StyledRasterInterface<?> styledGrid,
1006     int iconWidth, int iconHeight) {
1007     RasterLegendData rasterLegendData = styledGrid.getLegendMetaData();
1008     Set<Double> legendRasterValues = rasterLegendData.keySet();
1009     Map<Double, GridCoverage2D> sampleRasters = rasterLegendData
1010     .createSampleRasters();
1011    
1012     Box box = new Box(BoxLayout.Y_AXIS) {
1013    
1014     /**
1015     * Nuetzlich wenn die Componente gedruckt (z.B. wenn ein Screenshot
1016     * gemacht wird) wird. Dann werden wird der Hintergrund auf WEISS
1017     * gesetzt.
1018     */
1019     @Override
1020     public void print(Graphics g) {
1021     final Color orig = getBackground();
1022     setBackground(Color.WHITE);
1023     // wrap in try/finally so that we always restore the state
1024     try {
1025     super.print(g);
1026     } finally {
1027     setBackground(orig);
1028     }
1029     }
1030     };
1031    
1032     for (Double rValue : legendRasterValues) {
1033    
1034     /**
1035     * The coverage contains only one value of value rValue
1036     */
1037     GridCoverage2D sampleCov = sampleRasters.get(rValue);
1038     GridCoverageRenderer renderer;
1039     try {
1040     renderer = new GridCoverageRenderer(sampleCov
1041     .getCoordinateReferenceSystem(), JTSUtil
1042     .createEnvelope(sampleCov.getEnvelope()),
1043     new Rectangle(iconWidth, iconHeight),
1044     (AffineTransform) null);
1045     } catch (Exception e1) {
1046     throw new RuntimeException(
1047     "Creating the GridCoverageRenderer:", e1);
1048     }
1049    
1050     /**
1051     *
1052     */
1053     Box hbox = new Box(BoxLayout.X_AXIS) {
1054    
1055     /**
1056     * Nuetzlich wenn die Componente gedruckt (z.B. wenn ein
1057     * Screenshot gemacht wird) wird. Dann werden wird der
1058     * Hintergrund auf WEISS gesetzt.
1059     */
1060     @Override
1061     public void print(Graphics g) {
1062     final Color orig = getBackground();
1063     setBackground(Color.WHITE);
1064     // wrap in try/finally so that we always restore the
1065     // state
1066     try {
1067     super.print(g);
1068     } finally {
1069     setBackground(orig);
1070     }
1071     }
1072     };
1073    
1074     final Dimension ICON_SIZE = new Dimension(iconWidth,
1075     new JLabel().getFontMetrics(new JLabel().getFont())
1076     .getHeight() > 5 ? new JLabel().getFontMetrics(
1077     new JLabel().getFont()).getHeight() : iconHeight);
1078    
1079     // ****************************************************************************
1080     // Create the actual icon
1081     // ****************************************************************************
1082     BufferedImage buffImage = new BufferedImage(ICON_SIZE.width,
1083     ICON_SIZE.height, BufferedImage.TYPE_INT_ARGB);
1084     Graphics2D graphics = buffImage.createGraphics();
1085    
1086     /**
1087     * Iterate over all FeatureTypeStyles.
1088     */
1089     // for (FeatureTypeStyle ftStyle : styledGrid.getStyle()
1090     // .featureTypeStyles()) {
1091     // One child-node for every rule
1092     // List<Rule> rules = ftStyle.rules();
1093    
1094     // for (Rule rule : rules) {
1095     List<RasterSymbolizer> rSymbols = StylingUtil
1096     .getRasterSymbolizers(styledGrid.getStyle());
1097    
1098     for (RasterSymbolizer symbolizer : rSymbols) {
1099     // LOGGER.debug("Creating a new Legend Image for RUle name =
1100     // "+rule.getName());
1101     try {
1102     renderer.paint(graphics, sampleCov, symbolizer);
1103     } catch (Exception e) {
1104     LOGGER.error("Unable to paint " + symbolizer
1105     + " into the legend image", e);
1106     }
1107     // }
1108     // }
1109     }
1110    
1111     ImageIcon legendIcon = new ImageIcon(buffImage);
1112    
1113     final JLabel iconLabel = new JLabel(legendIcon);
1114     hbox.setAlignmentX(0f);
1115     hbox.add(iconLabel);
1116     hbox.add(Box.createHorizontalStrut(3));
1117    
1118     Translation labelT = rasterLegendData.get(rValue);
1119     final JLabel classTitleLabel = new JLabel(labelT.toString());
1120     hbox.add(classTitleLabel);
1121     classTitleLabel.setLabelFor(iconLabel);
1122    
1123     box.add(hbox);
1124     }
1125    
1126     return box;
1127 alfonx 397 }
1128    
1129 alfonx 244 }

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26