/[schmitzm]/branches/2.4.x/src/skrueger/geotools/StyledLayerUtil.java
ViewVC logotype

Annotation of /branches/2.4.x/src/skrueger/geotools/StyledLayerUtil.java

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1225 - (hide annotations)
Wed Nov 3 17:05:42 2010 UTC (14 years, 4 months ago) by alfonx
Original Path: trunk/src/skrueger/geotools/StyledLayerUtil.java
File size: 47171 byte(s)


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 alfonx 862 * Stefan A. Tzeggai - additional utility classes
29 alfonx 244 ******************************************************************************/
30     package skrueger.geotools;
31    
32 alfonx 397 import java.awt.Color;
33     import java.awt.Dimension;
34 alfonx 400 import java.awt.Graphics2D;
35     import java.awt.Rectangle;
36     import java.awt.geom.AffineTransform;
37 alfonx 397 import java.awt.image.BufferedImage;
38 alfonx 403 import java.awt.image.ColorModel;
39 alfonx 405 import java.awt.image.ComponentColorModel;
40     import java.awt.image.DataBuffer;
41 alfonx 1215 import java.awt.image.IndexColorModel;
42 alfonx 244 import java.io.File;
43     import java.io.FileNotFoundException;
44     import java.io.FileWriter;
45     import java.net.URL;
46     import java.text.DecimalFormat;
47 alfonx 607 import java.util.ArrayList;
48 alfonx 244 import java.util.List;
49     import java.util.Map;
50 alfonx 769 import java.util.Set;
51 alfonx 244
52 alfonx 403 import javax.swing.BorderFactory;
53 alfonx 397 import javax.swing.ImageIcon;
54 alfonx 516 import javax.swing.JComponent;
55 alfonx 397 import javax.swing.JLabel;
56    
57 alfonx 516 import net.miginfocom.swing.MigLayout;
58    
59 alfonx 244 import org.apache.log4j.Logger;
60 alfonx 403 import org.geotools.coverage.grid.GeneralGridEnvelope;
61 alfonx 244 import org.geotools.coverage.grid.GridCoverage2D;
62 alfonx 403 import org.geotools.coverage.grid.GridGeometry2D;
63 alfonx 244 import org.geotools.coverage.grid.io.AbstractGridCoverage2DReader;
64 alfonx 405 import org.geotools.coverage.grid.io.AbstractGridFormat;
65 alfonx 244 import org.geotools.feature.FeatureCollection;
66 alfonx 464 import org.geotools.feature.NameImpl;
67 alfonx 403 import org.geotools.geometry.jts.ReferencedEnvelope;
68 alfonx 244 import org.geotools.map.DefaultMapLayer;
69     import org.geotools.map.MapLayer;
70 alfonx 405 import org.geotools.parameter.Parameter;
71 alfonx 400 import org.geotools.renderer.lite.gridcoverage2d.GridCoverageRenderer;
72 alfonx 244 import org.geotools.styling.ColorMap;
73     import org.geotools.styling.ColorMapEntry;
74 alfonx 397 import org.geotools.styling.FeatureTypeStyle;
75 alfonx 244 import org.geotools.styling.RasterSymbolizer;
76 alfonx 397 import org.geotools.styling.Rule;
77 alfonx 244 import org.geotools.styling.Style;
78     import org.jdom.Document;
79     import org.jdom.Element;
80     import org.jdom.input.SAXBuilder;
81     import org.jdom.output.XMLOutputter;
82 alfonx 420 import org.opengis.feature.simple.SimpleFeature;
83 alfonx 397 import org.opengis.feature.simple.SimpleFeatureType;
84 alfonx 607 import org.opengis.feature.type.AttributeDescriptor;
85     import org.opengis.feature.type.GeometryDescriptor;
86 alfonx 464 import org.opengis.feature.type.Name;
87 alfonx 403 import org.opengis.parameter.GeneralParameterValue;
88 alfonx 244
89 alfonx 400 import schmitzm.geotools.JTSUtil;
90 alfonx 420 import schmitzm.geotools.feature.FeatureUtil;
91 alfonx 244 import schmitzm.geotools.styling.StylingUtil;
92     import schmitzm.io.IOUtil;
93     import schmitzm.lang.LangUtil;
94 alfonx 1225 import schmitzm.swing.ExceptionDialog;
95 alfonx 516 import schmitzm.swing.JPanel;
96 alfonx 244 import schmitzm.swing.SwingUtil;
97 alfonx 788 import skrueger.AttributeMetadataImpl;
98 alfonx 772 import skrueger.AttributeMetadataInterface;
99 alfonx 244 import skrueger.RasterLegendData;
100     import skrueger.i8n.Translation;
101    
102     /**
103     * This class provides static helper methods for dealing with
104     * {@link StyledLayerInterface} stuff.
105 alfonx 400 *
106     * @author <a href="mailto:[email protected]">Martin Schmitz</a>
107     * (University of Bonn/Germany)
108 alfonx 244 * @version 1.0
109     */
110     public class StyledLayerUtil {
111 alfonx 400 private static final Logger LOGGER = Logger.getLogger(StyledLayerUtil.class
112     .getName());
113     private static final SAXBuilder SAX_BUILDER = new SAXBuilder();
114     private static final XMLOutputter XML_OUTPUTTER = new XMLOutputter();
115 alfonx 244
116 alfonx 400 /** URL for Atlas XML schema */
117     public static final String AMLURI = "http://www.wikisquare.de/AtlasML";
118     /** Name of the XML Element for the attribute meta data map */
119     public static final String ELEM_NAME_AMD = "attributeMetaData";
120     /** Name of the XML Element for the raster legend data */
121     public static final String ELEM_NAME_RLD = "rasterLegendData";
122     /** Name of the XML Element for an attribute meta data map entry */
123     public static final String ELEM_NAME_ATTRIBUTE = "dataAttribute";
124     /** Name of the XML Element for an raster legend data entry */
125     public static final String ELEM_NAME_RASTERLEGEND = "rasterLegendItem";
126     /** Name of the XML Element for a translation */
127     public static final String ELEM_NAME_TRANSLATION = "translation";
128 alfonx 244
129 alfonx 400 /**
130     * Creates a Geotools {@link MapLayer} from an object. If the object is a
131     * {@link StyledLayerInterface} then its sytle is used. In case of direct
132     * Geotools objects ({@link GridCoverage2D},
133     * {@link AbstractGridCoverage2DReader}, {@link FeatureCollection}) a
134     * default style is generated.
135     *
136     * @param object
137     * an Object
138     * @exception Exception
139     * if {@code null} is given as object or an error occurs
140     * during layer creation
141     */
142 alfonx 516 public static MapLayer createMapLayer(final Object object) throws Exception {
143 alfonx 400 return createMapLayer(object, null);
144     }
145 alfonx 244
146 alfonx 400 /**
147     * Creates a Geotools {@link MapLayer} from an object. If the object is a
148     * {@link StyledLayerInterface} then its sytle is used. In case of direct
149     * Geotools objects ({@link GridCoverage2D},
150     * {@link AbstractGridCoverage2DReader}, {@link FeatureCollection}) a
151     * default style is generated.
152     *
153     * @param object
154     * an Object
155     * @param forcedStyle
156     * (SLD-)Style to force for the object
157     * @exception Exception
158     * if {@code null} is given as object or an error occurs
159     * during layer creation
160     */
161 alfonx 516 public static MapLayer createMapLayer(Object object, final Style forcedStyle)
162 alfonx 400 throws Exception {
163     MapLayer layer = null;
164     Style style = null;
165     if (object instanceof StyledLayerInterface) {
166     style = ((StyledLayerInterface<?>) object).getStyle();
167     object = ((StyledLayerInterface<?>) object).getGeoObject();
168     }
169     if (forcedStyle != null)
170     style = forcedStyle;
171     if (style == null)
172     style = StylingUtil.createDefaultStyle(object);
173 alfonx 244
174 alfonx 400 if (object instanceof GridCoverage2D)
175     layer = new DefaultMapLayer((GridCoverage2D) object, style);
176     if (object instanceof AbstractGridCoverage2DReader)
177     layer = new DefaultMapLayer((AbstractGridCoverage2DReader) object,
178     style);
179     if (object instanceof FeatureCollection)
180     layer = new DefaultMapLayer((FeatureCollection) object, style);
181 alfonx 244
182 alfonx 400 if (layer == null)
183     throw new Exception("Can not create MapLayer from "
184     + (object == null ? "null" : object.getClass()));
185 alfonx 244
186 alfonx 400 return layer;
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 default style.
193     *
194     * @param object
195     * an Object
196     * @param title
197     * title for the object
198     * @exception UnsupportedOperationException
199     * if {@code null} is given as object or an error occurs
200     * during creation
201     */
202 alfonx 516 public static StyledLayerInterface<?> createStyledLayer(
203     final Object object, final String title) {
204 alfonx 400 return createStyledLayer(object, title, null);
205     }
206 alfonx 244
207 alfonx 400 /**
208     * Creates an default instance of {@link StyledLayerInterface} for a
209     * Geotools object ({@link GridCoverage2D}, {@link FeatureCollection}) with
210     * a given style.
211     *
212     * @param object
213     * an Object
214     * @param title
215     * title for the object
216     * @param style
217     * style and meta data for the object
218     * @exception UnsupportedOperationException
219     * if {@code null} is given as object or an error occurs
220     * during creation
221     */
222 alfonx 516 public static StyledLayerInterface<?> createStyledLayer(
223     final Object object, final String title,
224     final StyledLayerStyle style) {
225 alfonx 400 StyledLayerInterface<?> styledLayer = null;
226 alfonx 244
227 alfonx 516 final String id = (title != null) ? title : "defaultID";
228 alfonx 244
229 alfonx 400 if (object instanceof GridCoverage2D)
230     styledLayer = new StyledGridCoverage((GridCoverage2D) object, id,
231     title, style);
232     else if (object instanceof AbstractGridCoverage2DReader)
233     styledLayer = new StyledGridCoverageReader(
234     (AbstractGridCoverage2DReader) object, id, title, style);
235     else if (object instanceof FeatureCollection)
236     styledLayer = new StyledFeatureCollection(
237     (FeatureCollection) object, id, title, style);
238 alfonx 244
239 alfonx 400 if (styledLayer == null)
240     throw new UnsupportedOperationException(
241     "Can not create StyledLayerInterface object from "
242     + (object == null ? "null" : object.getClass()));
243 alfonx 244
244 alfonx 400 return styledLayer;
245     }
246 alfonx 244
247 alfonx 400 /**
248     * Return only the visible or invisible entries of an AttributeMetaData-Map.
249     *
250     * @param amdMap
251     * AttributeMetaData-Map
252     * @param visible
253     * indicated whether the visible or invisible entries are
254     * returned
255 alfonx 607 *
256     * TODO replace with
257     * {@link AttributeMetadataMap#sortedValuesVisibleOnly()}
258 alfonx 400 */
259 alfonx 1215 public static AttributeMetadataMap<? extends AttributeMetadataInterface> getVisibleAttributeMetaData(
260 alfonx 772 final AttributeMetadataMap<? extends AttributeMetadataInterface> amdMap,
261 alfonx 769 final boolean visible) {
262 alfonx 516
263 alfonx 1215 final AttributeMetadataMap<AttributeMetadataInterface> filteredMap = (AttributeMetadataMap<AttributeMetadataInterface>) amdMap
264     .clone();
265     if (filteredMap.size() > 0) {
266 alfonx 769 filteredMap.clear(); // Just in case the close copies the contents
267     }
268 alfonx 1215
269 alfonx 772 for (final AttributeMetadataInterface amd : amdMap.values())
270 alfonx 464 if (amd.isVisible() == visible)
271     filteredMap.put(amd.getName(), amd);
272 alfonx 244
273 alfonx 400 return filteredMap;
274     }
275 alfonx 244
276 alfonx 400 /**
277 alfonx 769 * Parses a {@link AttributeMetadataImpl} object from an JDOM-
278     * {@link Element}. This method works like {@link
279 alfonx 400 * AMLImport#parseDataAttribute(org.w3c.dom.Node}, but for JDOM.
280     *
281 alfonx 534 * TODO 20.11.2009, SK: There are some new attribute weight, functiona,
282     * functionX and nodata in AttributeMetaData that should be parsed/exported
283     * too. but this method is only used by ISDSS, which is not supporting that
284     * stuff anyways.
285     *
286 alfonx 400 * @param element
287     * {@link Element} to parse
288     */
289 alfonx 769 public static AttributeMetadataImpl parseAttributeMetaData(
290     final Element element) {
291 mojays 1039 final String namespace = element.getAttributeValue("namespace");
292     final String localname = element.getAttributeValue("localname");
293 alfonx 770 final NameImpl aName = new NameImpl(namespace, localname);
294 alfonx 400 final Boolean visible = Boolean.valueOf(element
295     .getAttributeValue("visible"));
296     final String unit = element.getAttributeValue("unit");
297 alfonx 244
298 alfonx 400 Translation name = new Translation();
299     Translation desc = new Translation();
300     for (final Element childElement : (List<Element>) element.getChildren()) {
301     if (childElement.getName() == null)
302     continue;
303 alfonx 244
304 alfonx 400 if (childElement.getName().equals("name"))
305     name = parseTranslation(childElement);
306     else if (childElement.getName().equals("desc"))
307     desc = parseTranslation(childElement);
308     }
309 alfonx 769 return new AttributeMetadataImpl(aName, visible, name, desc, unit);
310 alfonx 400 }
311 alfonx 244
312 alfonx 400 /**
313 alfonx 769 * Parses a {@link AttributeMetadataImpl} map from an JDOM-{@link Element}
314     * with {@code <attribute>}-childs.
315 alfonx 400 *
316     * @param element
317     * {@link Element} to parse
318 alfonx 677 *
319 alfonx 769 * TODO Since GP 1.3 the {@link AttributeMetadataImpl} class has
320     * more attributes which are not used by Xulu/ISDSS. GP
321 alfonx 658 * exports/imports the AMD via AMLExporter and AMLImporter
322 alfonx 677 * classes. (SK, 3.2.2010) *
323 alfonx 400 */
324 alfonx 420 public static AttributeMetadataMap parseAttributeMetaDataMap(
325 alfonx 400 final Element element) {
326 alfonx 769 final AttributeMetadataMap metaData = new AttributeMetadataImplMap();
327 alfonx 516 final List<Element> attributesElements = element
328 alfonx 400 .getChildren(ELEM_NAME_ATTRIBUTE);
329 alfonx 516 for (final Element attibuteElement : attributesElements) {
330 alfonx 769 final AttributeMetadataImpl attrMetaData = parseAttributeMetaData(attibuteElement);
331 alfonx 464 metaData.put(attrMetaData.getName(), attrMetaData);
332 alfonx 400 }
333     return metaData;
334     }
335 alfonx 244
336 alfonx 400 /**
337 alfonx 769 * Loads a {@link AttributeMetadataImpl} object from an URL.
338 alfonx 400 *
339     * @param documentUrl
340     * {@link URL} to parse
341     * @see #parseAttributeMetaData(Element)
342     */
343 alfonx 420 public static AttributeMetadataMap loadAttributeMetaDataMap(
344 alfonx 400 final URL documentUrl) throws Exception {
345 alfonx 516 final Document document = SAX_BUILDER.build(documentUrl);
346 alfonx 400 return parseAttributeMetaDataMap(document.getRootElement());
347     }
348 alfonx 244
349 alfonx 400 /**
350 alfonx 769 * Creates an JDOM {@link Element} for the given
351     * {@link AttributeMetadataImpl} object.
352 alfonx 400 *
353     * @param amd
354     * meta data for one attribute
355 alfonx 658 *
356 alfonx 769 * TODO Since GP 1.3 the {@link AttributeMetadataImpl} class has
357     * more attributes which are not used by Xulu/ISDSS. GP
358 alfonx 658 * exports/imports the AMD via AMLExporter and AMLImporter
359     * classes. (SK, 3.2.2010)
360 alfonx 400 */
361     public static Element createAttributeMetaDataElement(
362 alfonx 772 final AttributeMetadataInterface amd) {
363 alfonx 400 final Element element = new Element(ELEM_NAME_ATTRIBUTE, AMLURI);
364 alfonx 1215 element.setAttribute("namespace",
365     String.valueOf(amd.getName().getNamespaceURI()));
366 alfonx 464 element.setAttribute("localname", String.valueOf(amd.getLocalName()));
367 alfonx 400 element.setAttribute("visible", String.valueOf(amd.isVisible()));
368     element.setAttribute("unit", amd.getUnit());
369     // Creating a aml:name tag...
370     element.addContent(createTranslationElement("name", amd.getTitle()));
371     // Creating a aml:desc tag...
372     element.addContent(createTranslationElement("desc", amd.getDesc()));
373     return element;
374     }
375 alfonx 244
376 alfonx 400 /**
377 alfonx 769 * Creates an JDOM {@link Element} for the given
378     * {@link AttributeMetadataImpl} map.
379 alfonx 400 *
380     * @param amdMap
381     * map of attribute meta data
382     */
383     public static Element createAttributeMetaDataMapElement(
384 alfonx 772 final AttributeMetadataMap<? extends AttributeMetadataInterface> amdMap) {
385 alfonx 400 final Element element = new Element(ELEM_NAME_AMD, AMLURI);
386 alfonx 772 for (final AttributeMetadataInterface amd : amdMap.values())
387 alfonx 400 element.addContent(createAttributeMetaDataElement(amd));
388     return element;
389     }
390 alfonx 244
391 alfonx 400 /**
392 alfonx 769 * Saves a {@link AttributeMetadataImpl AttributeMetaData-Map} to an URL.
393 alfonx 400 *
394     * @param amdMap
395 alfonx 769 * map of {@link AttributeMetadataImpl}
396 alfonx 400 * @param documentUrl
397     * {@link URL} to store the XML
398     */
399     public static void saveAttributeMetaDataMap(
400 alfonx 420 final AttributeMetadataMap amdMap, final URL documentUrl)
401 alfonx 400 throws Exception {
402     // Create XML-Document
403     final FileWriter out = new FileWriter(new File(documentUrl.toURI()));
404     XML_OUTPUTTER.output(createAttributeMetaDataMapElement(amdMap), out);
405     out.flush();
406     out.close();
407     }
408 alfonx 244
409 alfonx 400 /**
410     * Parses a {@link RasterLegendData} object from an JDOM-{@link Element}.
411     * This method works like {@link
412     * AMLImport#parseRasterLegendData(org.w3c.dom.Node}, but for JDOM.
413     *
414     * @param element
415     * {@link Element} to parse
416     */
417 alfonx 516 public static RasterLegendData parseRasterLegendData(final Element element) {
418 alfonx 244
419 alfonx 400 final boolean paintGaps = Boolean.valueOf(element
420     .getAttributeValue("paintGaps"));
421 alfonx 244
422 alfonx 516 final RasterLegendData rld = new RasterLegendData(paintGaps);
423 alfonx 244
424 alfonx 516 for (final Element childElement : (List<Element>) element.getChildren()) {
425 alfonx 400 final String name = childElement.getName();
426     // Cancel if it's an attribute
427     if (childElement.getChildren().size() == 0)
428     continue;
429 alfonx 244
430 alfonx 400 if (name.equals(ELEM_NAME_RASTERLEGEND)) {
431     final String valueAttr = childElement
432     .getAttributeValue("value");
433     if (valueAttr == null)
434     throw new UnsupportedOperationException(
435     "Attribute 'value' missing for definition of <"
436     + ELEM_NAME_RASTERLEGEND + ">");
437     final double value = Double.valueOf(valueAttr);
438 alfonx 244
439 alfonx 400 // first and only item should be the label
440     final Element labelElement = childElement.getChild("label");
441     // id label element is missing, the translation is searched
442     // directly
443     // as childs of the rasterLegendItem element
444 alfonx 516 final Translation label = parseTranslation(labelElement != null ? labelElement
445 alfonx 400 : childElement);
446     rld.put(value, label);
447     }
448     }
449 alfonx 244
450 alfonx 400 return rld;
451     }
452 alfonx 244
453 alfonx 400 /**
454     * Loads a {@link RasterLegendData} object from an URL.
455     *
456     * @param documentUrl
457     * {@link URL} to parse
458     * @see #parseAttributeMetaData(Element)
459     */
460     public static RasterLegendData loadRasterLegendData(final URL documentUrl)
461     throws Exception {
462 alfonx 516 final Document document = SAX_BUILDER.build(documentUrl);
463 alfonx 400 return parseRasterLegendData(document.getRootElement());
464     }
465 alfonx 244
466 alfonx 400 /**
467     * Creates an JDOM {@link Element} for the given {@link RasterLegendData}
468     * map.
469     *
470     * @param rld
471     * raster legend data
472     */
473     public static Element createRasterLegendDataElement(
474     final RasterLegendData rld) {
475     final Element element = new Element(ELEM_NAME_RLD, AMLURI);
476     element.setAttribute("paintGaps", rld.isPaintGaps().toString());
477 alfonx 516 for (final Double key : rld.getSortedKeys()) {
478     final Element item = new Element(ELEM_NAME_RASTERLEGEND, AMLURI);
479 alfonx 400 item.setAttribute("value", key.toString());
480     item.addContent(createTranslationElement("label", rld.get(key)));
481     element.addContent(item);
482     }
483     return element;
484     }
485 alfonx 244
486 alfonx 400 /**
487     * Creates {@link RasterLegendData} from a {@link ColorMap}.
488     *
489     * @param colorMap
490     * a color map
491     * @param paintGaps
492     * indicated whether gaps are painted between the legend items
493     * @param digits
494     * number of digits the grid value classes (and legend) are
495     * rounded to (null means no round; >= 0 means digits after
496     * comma; < 0 means digits before comma)
497     */
498 alfonx 516 public static RasterLegendData generateRasterLegendData(
499     final ColorMap colorMap, final boolean paintGaps,
500     final Integer digits) {
501     final DecimalFormat decFormat = digits != null ? new DecimalFormat(
502     SwingUtil.getNumberFormatPattern(digits)) : null;
503     final RasterLegendData rld = new RasterLegendData(paintGaps);
504     for (final ColorMapEntry cme : colorMap.getColorMapEntries()) {
505     final double value = StylingUtil.getQuantityFromColorMapEntry(cme);
506 alfonx 400 String label = cme.getLabel();
507     // if no label is set (e.g. quantitative style),
508     // use the value as label
509     if (label == null || label.equals(""))
510     if (digits == null)
511     label = String.valueOf(value);
512     else
513     label = decFormat.format(LangUtil.round(value, digits));
514     rld.put(value, new Translation(" " + label));
515     }
516     return rld;
517     }
518 alfonx 244
519 alfonx 400 /**
520     * Creates {@link RasterLegendData} from the {@link ColorMap} of a style.
521     *
522     * @param style
523     * a raster style (must contain a {@link RasterSymbolizer})
524     * @param paintGaps
525     * indicated whether gaps are painted between the legend items
526     * @param digits
527     * number of digits the grid value classes (and legend) are
528     * rounded to (null means no round; >= 0 means digits after
529     * comma; < 0 means digits before comma)
530     */
531 alfonx 516 public static RasterLegendData generateRasterLegendData(final Style style,
532     final boolean paintGaps, final Integer digits) {
533     final ColorMap colorMap = StylingUtil.getColorMapFromStyle(style);
534 alfonx 400 if (colorMap == null)
535     throw new IllegalArgumentException(
536     "Color map can not be determined from style!");
537     return generateRasterLegendData(colorMap, paintGaps, digits);
538     }
539 alfonx 244
540 alfonx 400 /**
541     * Saves a {@link RasterLegendData} to an URL.
542     *
543     * @param rld
544     * raster legend data
545     * @param documentUrl
546     * {@link URL} to store the XML
547     */
548     public static void saveRasterLegendData(final RasterLegendData rld,
549     final URL documentUrl) throws Exception {
550     // Create XML-Document
551     final FileWriter out = new FileWriter(new File(documentUrl.toURI()));
552     XML_OUTPUTTER.output(createRasterLegendDataElement(rld), out);
553     out.flush();
554     out.close();
555     }
556 alfonx 244
557 alfonx 400 /**
558     * Parses a {@link Translation} object from an JDOM-{@link Element}. This
559     * method works like {@link AMLImport#parseTranslation(org.w3c.dom.Node},
560     * but for JDOM.
561     *
562     * @param element
563     * {@link Element} to parse
564     */
565     public final static Translation parseTranslation(final Element element) {
566 alfonx 516 final Translation trans = new Translation();
567 alfonx 244
568 alfonx 400 if (element == null)
569     return trans;
570 alfonx 244
571 alfonx 400 for (final Element translationElement : (List<Element>) element
572     .getChildren()) {
573     final String name = translationElement.getName();
574     if (name == null)
575     continue;
576 alfonx 244
577 alfonx 400 // lang attribute
578     String lang = translationElement.getAttributeValue("lang");
579     // set the default, if no language code is set
580     if (lang == null)
581     lang = Translation.DEFAULT_KEY;
582 alfonx 244
583 alfonx 400 final String translationText = translationElement.getValue();
584     if (translationText == null)
585     trans.put(lang, "");
586     else
587     trans.put(lang, translationText);
588     }
589 alfonx 244
590 alfonx 400 // if no <translation> is given, the value of the node should
591     // be used as a default translation
592     if (trans.size() == 0)
593     trans.put(Translation.DEFAULT_KEY, element.getValue());
594     // trans = new Translation(
595     // ((List<Element>)element.getChildren()).get(0).getValue() );
596 alfonx 244
597 alfonx 400 return trans;
598     }
599 alfonx 244
600 alfonx 400 /**
601     * Creates an JDOM {@link Element} for the given {@link Translation}.
602     *
603     * @param tagname
604     * Name of the Element
605     * @param translation
606     * Translation to store in the Element
607     */
608 alfonx 516 public final static Element createTranslationElement(final String tagname,
609     final Translation translation) {
610     final Element element = new Element(tagname, AMLURI);
611 alfonx 400 if (translation == null)
612     throw new UnsupportedOperationException(
613     "Translation element can not be created from null!");
614 alfonx 244
615 alfonx 400 // If only a default translation is set, the <translation
616     // lang="..">..</tranlation>
617     // part is not used
618     if (translation.keySet().size() == 1
619     && translation.get(Translation.DEFAULT_KEY) != null) {
620     element.addContent(translation.get(Translation.DEFAULT_KEY));
621     return element;
622     }
623 alfonx 244
624 alfonx 400 // add a <translation lang="..">..</tranlation> part to the element for
625     // all languages
626 alfonx 516 for (final String lang : translation.keySet()) {
627     final Element translationElement = new Element(
628     ELEM_NAME_TRANSLATION, AMLURI);
629 alfonx 400 translationElement.setAttribute("lang", lang);
630     String translationString = translation.get(lang);
631     if (translationString == null)
632     translationString = "";
633     translationElement.addContent(translationString);
634     element.addContent(translationElement);
635     }
636 alfonx 244
637 alfonx 400 return element;
638     }
639 alfonx 244
640 alfonx 400 /**
641     * Sets a style to {@link StyledLayerInterface}.
642     *
643     * @param styledObject
644     * a styled object
645     * @param style
646     * a Style
647     */
648 alfonx 516 public static void setStyledLayerStyle(
649     final StyledLayerInterface styledObject,
650     final StyledLayerStyle<?> style) {
651 alfonx 400 // set SLD style
652     styledObject.setStyle(style.getGeoObjectStyle());
653     // set meta data
654     if (styledObject instanceof StyledGridCoverageInterface
655     && (style.getMetaData() instanceof RasterLegendData || style
656     .getMetaData() == null)) {
657 alfonx 516 final RasterLegendData sourceRld = (RasterLegendData) style
658     .getMetaData();
659     final RasterLegendData destRld = ((StyledGridCoverageInterface) styledObject)
660 alfonx 400 .getLegendMetaData();
661     if (destRld != null && sourceRld != null) {
662     destRld.setPaintGaps(sourceRld.isPaintGaps());
663     destRld.clear();
664     destRld.putAll(sourceRld);
665     }
666     return;
667     }
668     if (styledObject instanceof StyledFeatureCollectionInterface
669     && (style.getMetaData() instanceof Map || style.getMetaData() == null)) {
670 alfonx 516 final AttributeMetadataMap sourceAmd = (AttributeMetadataMap) style
671 alfonx 400 .getMetaData();
672 alfonx 516 final AttributeMetadataMap destAmd = ((StyledFeatureCollectionInterface) styledObject)
673 alfonx 400 .getAttributeMetaDataMap();
674     if (destAmd != null && sourceAmd != null) {
675     destAmd.clear();
676     destAmd.putAll(sourceAmd);
677     }
678     return;
679     }
680 alfonx 244
681 alfonx 400 throw new UnsupportedOperationException(
682     "Style is not compatible to object: "
683     + (style.getMetaData() == null ? null : style
684     .getMetaData().getClass().getSimpleName())
685     + " <-> "
686     + (styledObject == null ? null : styledObject
687     .getClass().getSimpleName()));
688     }
689 alfonx 244
690 alfonx 400 /**
691     * Returns the style a {@link StyledLayerInterface} as a
692     * {@link StyledLayerStyle}.
693     *
694     * @param styledObject
695     * a styled object
696     * @return {@code StyledLayerStyle<RasterLegendData>} for
697 alfonx 1215 * {@link StyledGridCoverageInterface} or
698     * {@code StyledLayerStyle<Map<Integer,AttributeMetaData>>} for
699 alfonx 400 * {@link StyledFeatureCollectionInterface}
700     */
701     public static StyledLayerStyle<?> getStyledLayerStyle(
702 alfonx 516 final StyledLayerInterface styledObject) {
703 alfonx 400 if (styledObject instanceof StyledGridCoverageInterface)
704     return getStyledLayerStyle((StyledGridCoverageInterface) styledObject);
705     if (styledObject instanceof StyledFeatureCollectionInterface)
706     return getStyledLayerStyle((StyledFeatureCollectionInterface) styledObject);
707     throw new UnsupportedOperationException(
708     "Unknown type of StyledLayerInterface: "
709     + (styledObject == null ? null : styledObject
710     .getClass().getSimpleName()));
711     }
712 alfonx 244
713 alfonx 400 /**
714     * Returns the style and raster meta data of a
715     * {@link StyledGridCoverageInterface} as a {@link StyledLayerStyle}.
716     *
717     * @param styledGC
718     * a styled grid coverage
719     */
720     public static StyledLayerStyle<RasterLegendData> getStyledLayerStyle(
721 alfonx 516 final StyledGridCoverageInterface styledGC) {
722 alfonx 400 return new StyledLayerStyle<RasterLegendData>(styledGC.getStyle(),
723     styledGC.getLegendMetaData());
724     }
725 alfonx 244
726 alfonx 400 /**
727     * Returns the style and attribute meta data of a
728     * {@link StyledFeatureCollectionInterface} as a {@link StyledLayerStyle}.
729     *
730     * @param styledFC
731     * a styled feature collection
732     */
733 alfonx 464 public static StyledLayerStyle<AttributeMetadataMap> getStyledLayerStyle(
734 alfonx 516 final StyledFeatureCollectionInterface styledFC) {
735     return new StyledLayerStyle<AttributeMetadataMap>(styledFC.getStyle(),
736     styledFC.getAttributeMetaDataMap());
737 alfonx 400 }
738 alfonx 244
739 alfonx 400 /**
740     * Loads a {@linkplain Style SLD-Style} and {@linkplain RasterLegendData
741     * Raster-LegendData} for a given geo-object (raster) source. The SLD file
742     * must be present. A missing raster legend-data file is tolerated.
743     *
744     * @param geoObjectURL
745     * URL of the (already read) raster object
746     * @param sldExt
747     * file extention for the SLD file
748     * @param rldExt
749     * file extention for the raster legend-data file
750     * @return {@code null} in case of any error
751     */
752     public static StyledLayerStyle<RasterLegendData> loadStyledRasterStyle(
753 alfonx 516 final URL geoObjectURL, final String sldExt, final String rldExt) {
754 alfonx 400 RasterLegendData metaData = null;
755     Style sldStyle = null;
756     try {
757 alfonx 516 final Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(
758 alfonx 400 geoObjectURL, sldExt));
759     // SLD must be present
760     if (styles == null || styles.length == 0)
761     return null;
762     sldStyle = styles[0];
763 alfonx 516 } catch (final Exception err) {
764 alfonx 400 // SLD must be present
765     LangUtil.logDebugError(LOGGER, err);
766     return null;
767     }
768 alfonx 244
769 alfonx 400 try {
770     metaData = StyledLayerUtil.loadRasterLegendData(IOUtil
771     .changeUrlExt(geoObjectURL, rldExt));
772 alfonx 516 } catch (final FileNotFoundException err) {
773 alfonx 400 // ignore missing raster legend data
774 alfonx 516 } catch (final Exception err) {
775 alfonx 400 // any other error during legend data creation leads to error
776     LangUtil.logDebugError(LOGGER, err);
777     return null;
778     }
779     return new StyledLayerStyle<RasterLegendData>(sldStyle, metaData);
780     }
781 alfonx 244
782 alfonx 400 /**
783     * Loads a {@linkplain Style SLD-Style} from a {@code .sld} file and
784     * {@linkplain RasterLegendData Raster-LegendData} from a {@code .rld} file
785     * for a given geo-object (raster) source. The SLD file must be present. A
786     * missing raster legend-data file is tolerated.
787     *
788     * @param geoObjectURL
789     * URL of the (already read) raster object
790     * @param sldExt
791     * file extention for the SLD file
792     * @param rldExt
793     * file extention for the raster legend-data file
794     * @return {@code null} in case of any error
795     */
796     public static StyledLayerStyle<RasterLegendData> loadStyledRasterStyle(
797 alfonx 516 final URL geoObjectURL) {
798 alfonx 400 return loadStyledRasterStyle(geoObjectURL, "sld", "rld");
799     }
800 alfonx 244
801 alfonx 400 /**
802 alfonx 769 * Loads a {@linkplain Style SLD-Style} and a
803     * {@linkplain AttributeMetadataImpl AttributeMetaData-Map} for a given
804     * geo-object (feature) source. The SLD file must be present. A missing
805     * attribute meta-data file is tolerated.
806 alfonx 400 *
807     * @param geoObjectURL
808     * URL of the (already read) feature object
809     * @param sldExt
810     * file extention for the SLD file
811     * @param rldExt
812     * file extention for the raster legend-data file
813     * @return {@code null} in case of any error
814     */
815 alfonx 464 public static StyledLayerStyle<AttributeMetadataMap> loadStyledFeatureStyle(
816 alfonx 516 final URL geoObjectURL, final String sldExt, final String rldExt) {
817 alfonx 464 AttributeMetadataMap metaData = null;
818 alfonx 400 Style sldStyle = null;
819     try {
820 alfonx 516 final Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(
821 alfonx 400 geoObjectURL, sldExt));
822     // SLD must be present
823     if (styles == null || styles.length == 0)
824     return null;
825     sldStyle = styles[0];
826 alfonx 516 } catch (final Exception err) {
827 alfonx 400 // SLD must be present
828     LangUtil.logDebugError(LOGGER, err);
829     return null;
830     }
831 alfonx 244
832 alfonx 400 try {
833     metaData = StyledLayerUtil.loadAttributeMetaDataMap(IOUtil
834     .changeUrlExt(geoObjectURL, rldExt));
835 alfonx 516 } catch (final FileNotFoundException err) {
836 alfonx 400 // ignore missing attribute meta data
837 alfonx 516 } catch (final Exception err) {
838 alfonx 400 // any other error during meta data creation leads to error
839     LangUtil.logDebugError(LOGGER, err);
840     return null;
841     }
842 alfonx 244
843 alfonx 516 return new StyledLayerStyle<AttributeMetadataMap>(sldStyle, metaData);
844 alfonx 400 }
845 alfonx 244
846 alfonx 400 /**
847     * Loads a {@linkplain Style SLD-Style} from a {@code .sld} file and
848 alfonx 1215 * {@linkplain AttributeMetadataImpl AttributeMetaData-Map} from a
849     * {@code .amd} file for a given geo-object (feature) source. The SLD file
850     * must be present. A missing attribute meta-data file is tolerated.
851 alfonx 400 *
852     * @param geoObjectURL
853     * URL of the (already read) feature object
854     * @param sldExt
855     * file extention for the SLD file
856     * @param rldExt
857     * file extention for the raster legend-data file
858     * @return {@code null} in case of any error
859     */
860 alfonx 464 public static StyledLayerStyle<AttributeMetadataMap> loadStyledFeatureStyle(
861 alfonx 516 final URL geoObjectURL) {
862 alfonx 400 return loadStyledFeatureStyle(geoObjectURL, "sld", "amd");
863     }
864 alfonx 244
865 alfonx 400 /**
866     * Stores a {@linkplain Style SLD-Style} and {@linkplain RasterLegendData
867     * Raster-LegendData} for a given geo-object (raster) source.
868     *
869     * @param style
870     * style to save
871     * @param geoObjectURL
872     * URL of the raster object
873     * @param sldExt
874     * file extention for the SLD file
875     * @param mdExt
876     * file extention for the meta-data file
877     */
878 alfonx 516 public static <T> void saveStyledLayerStyle(
879     final StyledLayerStyle<T> style, final URL geoObjectURL,
880     final String sldExt, final String mdExt) throws Exception {
881 alfonx 400 // Store the SLD
882 alfonx 516 final Style sldStyle = style.getGeoObjectStyle();
883 alfonx 400 if (sldStyle != null) {
884 alfonx 1212 StylingUtil.saveStyleToSld(sldStyle, IOUtil.changeFileExt(new File(
885 alfonx 400 geoObjectURL.toURI()), sldExt));
886     }
887 alfonx 244
888 alfonx 400 // Store the meta data
889 alfonx 516 final T metaData = style.getMetaData();
890 alfonx 400 if (metaData != null) {
891     if (metaData instanceof RasterLegendData) {
892 alfonx 1215 saveRasterLegendData((RasterLegendData) metaData,
893     IOUtil.changeUrlExt(geoObjectURL, mdExt));
894 alfonx 400 // } else if ( metaData instanceof
895     // Map<Integer,AttributeMetaData> ) { // LEIDER NICHT
896     // KOMPILIERBAR!!
897     } else if (metaData instanceof Map) {
898 alfonx 516 saveAttributeMetaDataMap((AttributeMetadataMap) metaData,
899     IOUtil.changeUrlExt(geoObjectURL, mdExt));
900 alfonx 400 } else
901     throw new UnsupportedOperationException(
902     "Export for meta data not yet supported: "
903     + metaData.getClass().getSimpleName());
904     }
905     }
906 alfonx 244
907 alfonx 400 /**
908     * Stores the {@linkplain Style SLD-Style} to a {@code .sld} file and the
909 alfonx 769 * meta data ({@link RasterLegendData} or {@link AttributeMetadataImpl}) to
910     * a {@code .rld} or {@code .amd} file. for a given geo-object source.
911 alfonx 400 *
912     * @param style
913     * style to save
914     * @param geoObjectURL
915     * URL of the (already read) raster object
916     */
917 alfonx 516 public static void saveStyledLayerStyle(final StyledLayerStyle<?> style,
918     final URL geoObjectURL) throws Exception {
919 alfonx 400 if (style.getMetaData() instanceof RasterLegendData)
920     saveStyledLayerStyle(style, geoObjectURL, "sld", "rld");
921     else
922     saveStyledLayerStyle(style, geoObjectURL, "sld", "amd");
923     }
924 alfonx 244
925 alfonx 397 /**
926 alfonx 694 * *If appended to the name of a rule, this rule shall not be shown in the
927     * legend
928     */
929     public final static String HIDE_IN_LAYER_LEGEND_HINT = "HIDE_IN_LEGEND";
930    
931     /**
932 alfonx 516 * Creates a {@link JPanel} that shows a legend for a list of
933 alfonx 397 * {@link FeatureTypeStyle}s and a targeted featureType
934     *
935 alfonx 824 * @param style
936     * The Style to presented in this legend
937 alfonx 397 * @param featureType
938     * If this a legend for Point, Polygon or Line?
939     *
940 alfonx 1215 * @author <a href="mailto:[email protected]">Stefan Alfons Tzeggai</a>
941 alfonx 397 */
942 alfonx 824 public static JPanel createLegendSwingPanel(Style style,
943 alfonx 516 final SimpleFeatureType featureType, final int iconWidth,
944     final int iconHeight) {
945 alfonx 397
946 alfonx 1225 if (featureType == null) {
947     ExceptionDialog.show(new IllegalStateException(
948     "featureType is null!"));
949     return new JPanel();
950     }
951    
952 alfonx 516 final List<FeatureTypeStyle> list = style.featureTypeStyles();
953 alfonx 397
954 alfonx 517 final JPanel panel = new JPanel(new MigLayout("wrap 2", "[]:3:[]"));
955 alfonx 397
956 alfonx 516 if (style == null) {
957     // No Style => no legend
958     return panel;
959     }
960 alfonx 397
961 alfonx 516 for (final FeatureTypeStyle ftStyle : list) {
962    
963 alfonx 397 // One child-node for every rule
964 alfonx 516 final List<Rule> rules = ftStyle.rules();
965     for (final Rule rule : rules) {
966 alfonx 397
967 alfonx 694 // Check if this RULE shall actually appear in the legend
968 alfonx 769 if (rule.getName() != null
969     && rule.getName().endsWith(HIDE_IN_LAYER_LEGEND_HINT))
970 alfonx 694 continue;
971    
972 alfonx 397 /**
973     * Let's not create a hbox for Rules that only contain
974     * TextSymbolizers
975     */
976     if (StylingUtil.getTextSymbolizers(rule.getSymbolizers())
977     .size() == rule.getSymbolizers().length)
978     continue;
979    
980     final BufferedImage imageForRule = LegendIconFeatureRenderer
981     .getInstance().createImageForRule(rule, featureType,
982 alfonx 516 new Dimension(iconWidth, iconHeight));
983 alfonx 397
984 alfonx 516 final ImageIcon legendIcon = new ImageIcon(imageForRule);
985 alfonx 397
986     final JLabel iconLabel = new JLabel(legendIcon);
987 alfonx 517 panel.add(iconLabel, "sgx1");
988     // hbox.setAlignmentX(0f);
989     // hbox.add(iconLabel);
990     // hbox.add(Box.createHorizontalStrut(3));
991 alfonx 397
992 alfonx 516 final Translation labelT = new Translation();
993 alfonx 409 labelT.fromOneLine(rule.getDescription().getTitle());
994 alfonx 397 final JLabel classTitleLabel = new JLabel(labelT.toString());
995 alfonx 517
996     panel.add(classTitleLabel, "sgx2");
997 alfonx 400 classTitleLabel.setLabelFor(iconLabel);
998 alfonx 397 }
999     }
1000    
1001 alfonx 516 return panel;
1002 alfonx 397 }
1003    
1004     /**
1005 alfonx 516 * Creates a {@link JComponent} that contains a legend for a given
1006 alfonx 824 * {@link StyledRasterInterface} and a given {@link Style}.
1007 alfonx 400 *
1008 alfonx 516 * @param style
1009     * if <code>null</code>, the default {@link Style} is extracetd
1010     * from the {@link StyledRasterInterface}
1011 alfonx 397 */
1012 alfonx 824 public static JPanel createLegendSwingPanel(
1013 alfonx 516 final StyledRasterInterface<?> styledRaster, Style style,
1014     final int iconWidth, final int iconHeight) {
1015 alfonx 403
1016 alfonx 516 // If no style is given, we use the default style for this layer
1017     if (style == null)
1018     style = styledRaster.getStyle();
1019    
1020 alfonx 403 /**
1021     * Determine whether a Style is responsible for the coloring
1022     */
1023     ColorModel colorModel = null;
1024 alfonx 405 if (!isStyleable(styledRaster)
1025 alfonx 516 || (isStyleable(styledRaster) && style == null)) {
1026 alfonx 405 colorModel = getColorModel(styledRaster);
1027 alfonx 403 }
1028    
1029 alfonx 516 final RasterLegendData rasterLegendData = styledRaster
1030     .getLegendMetaData();
1031     final List<Double> legendRasterValues = rasterLegendData
1032     .getSortedKeys();
1033     final Map<Double, GridCoverage2D> sampleRasters = rasterLegendData
1034 alfonx 400 .createSampleRasters();
1035    
1036 alfonx 607 final JPanel panel = new JPanel(new MigLayout("wrap 2, gapy 0"));
1037 alfonx 400
1038 alfonx 516 for (final Double rValue : legendRasterValues) {
1039 alfonx 400
1040 alfonx 516 // final Dimension ICON_SIZE = new Dimension(iconWidth,
1041     // new JLabel().getFontMetrics(new JLabel().getFont())
1042     // .getHeight() > 5 ? new JLabel().getFontMetrics(
1043     // new JLabel().getFont()).getHeight() : iconHeight);
1044 alfonx 400
1045     // ****************************************************************************
1046     // Create the actual icon
1047     // ****************************************************************************
1048 alfonx 516 final BufferedImage buffImage = new BufferedImage(iconWidth,
1049     iconHeight, BufferedImage.TYPE_INT_ARGB);
1050 alfonx 517
1051 alfonx 516 final Graphics2D graphics = buffImage.createGraphics();
1052 alfonx 400
1053 alfonx 405 if (colorModel != null) {
1054 alfonx 516 // The colors come from the ColorModel!
1055 alfonx 517
1056 alfonx 403 try {
1057 alfonx 405 Object inData = null;
1058     switch (colorModel.getTransferType()) {
1059     case DataBuffer.TYPE_BYTE:
1060     inData = new byte[] { rValue.byteValue() };
1061     break;
1062     case DataBuffer.TYPE_USHORT:
1063     inData = new short[] { rValue.shortValue() };
1064     break;
1065     case DataBuffer.TYPE_INT:
1066     inData = new int[] { rValue.intValue() };
1067     break;
1068     case DataBuffer.TYPE_SHORT:
1069     inData = new short[] { rValue.shortValue() };
1070     break;
1071     case DataBuffer.TYPE_FLOAT:
1072     inData = new float[] { rValue.floatValue() };
1073     break;
1074     case DataBuffer.TYPE_DOUBLE:
1075     inData = new double[] { rValue.doubleValue() };
1076     break;
1077     default:
1078     inData = rValue.intValue();
1079     }
1080     final Color color = new Color(colorModel.getRGB(inData));
1081 alfonx 403 graphics.setBackground(color);
1082     graphics.setColor(color);
1083 alfonx 516 graphics.fillRect(0, 0, iconWidth, iconHeight);
1084     } catch (final Exception e) {
1085     LOGGER.info(
1086 alfonx 420 "Dann nehmen wir halt den GridCoverageRenderer", e);
1087 alfonx 405 colorModel = null;
1088     }
1089 alfonx 516 } else {
1090     // The colors come from the Style
1091 alfonx 400
1092 alfonx 405 /**
1093     * The coverage contains only one value of value rValue
1094     */
1095 alfonx 516 final GridCoverage2D sampleCov = sampleRasters.get(rValue);
1096 alfonx 405 GridCoverageRenderer renderer;
1097     try {
1098 alfonx 1215 renderer = new GridCoverageRenderer(
1099     sampleCov.getCoordinateReferenceSystem(),
1100     JTSUtil.createEnvelope(sampleCov.getEnvelope()),
1101 alfonx 405 new Rectangle(iconWidth, iconHeight),
1102     (AffineTransform) null);
1103 alfonx 516 } catch (final Exception e1) {
1104 alfonx 405 throw new RuntimeException(
1105 alfonx 516 "Creating a GridCoverageRenderer failed:", e1);
1106 alfonx 405 }
1107 alfonx 403
1108 alfonx 405 /**
1109     * Iterate over all FeatureTypeStyles.
1110     */
1111 alfonx 516 final List<RasterSymbolizer> rSymbols = StylingUtil
1112 alfonx 405 .getRasterSymbolizers(style);
1113    
1114 alfonx 516 for (final RasterSymbolizer symbolizer : rSymbols) {
1115 alfonx 405 try {
1116     renderer.paint(graphics, sampleCov, symbolizer);
1117 alfonx 516 } catch (final Exception ee) {
1118 alfonx 405 LOGGER.error("Unable to paint " + symbolizer
1119     + " into the legend image", ee);
1120 alfonx 403 }
1121 alfonx 400 }
1122 alfonx 405 }
1123 alfonx 400
1124 alfonx 516 final JLabel iconLabel = new JLabel(new ImageIcon(buffImage));
1125 alfonx 517 panel.add(iconLabel, "sgx1");
1126 alfonx 400
1127 alfonx 516 final Translation labelT = rasterLegendData.get(rValue);
1128 alfonx 400 final JLabel classTitleLabel = new JLabel(labelT.toString());
1129 alfonx 517 panel.add(classTitleLabel, "sgx2"
1130 alfonx 607 + (rasterLegendData.isPaintGaps() ? ", gapy 0:0:0 5:5:5"
1131     : ""));
1132 alfonx 400 classTitleLabel.setLabelFor(iconLabel);
1133    
1134 alfonx 607 if (rasterLegendData.isPaintGaps()) {
1135 alfonx 403 iconLabel
1136     .setBorder(BorderFactory.createLineBorder(Color.black));
1137     }
1138    
1139 alfonx 400 }
1140    
1141 alfonx 516 return panel;
1142 alfonx 397 }
1143    
1144 alfonx 405 /**
1145     * Extracts the {@link ColorModel} of any {@link StyledRasterInterface}. May
1146     * return <code>null</code> if the geoobject can not be accessed.
1147     */
1148 alfonx 420 @SuppressWarnings("unchecked")
1149 alfonx 516 public static ColorModel getColorModel(
1150     final StyledRasterInterface<?> styledGrid) {
1151 alfonx 405 ColorModel colorModel = null;
1152     try {
1153 alfonx 516 final Object geoObject = styledGrid.getGeoObject();
1154 alfonx 405 if (geoObject instanceof GridCoverage2D) {
1155 alfonx 516 final GridCoverage2D cov = (GridCoverage2D) geoObject;
1156 alfonx 405 colorModel = cov.getRenderedImage().getColorModel();
1157 alfonx 1203 } else if (styledGrid instanceof StyledGridCoverageReaderInterface) {
1158 alfonx 405
1159 alfonx 516 final Parameter readGG = new Parameter(
1160 alfonx 405 AbstractGridFormat.READ_GRIDGEOMETRY2D);
1161    
1162 alfonx 1212 final ReferencedEnvelope mapExtend = new ReferencedEnvelope(
1163 alfonx 405 styledGrid.getEnvelope(), styledGrid.getCrs());
1164    
1165     readGG.setValue(new GridGeometry2D(new GeneralGridEnvelope(
1166 alfonx 420 new Rectangle(0, 0, 1, 1)), mapExtend));
1167 alfonx 405
1168 alfonx 1215 AbstractGridCoverage2DReader aReader;
1169     if (geoObject instanceof FeatureCollection) {
1170     final FeatureCollection<SimpleFeatureType, SimpleFeature> rFc = (FeatureCollection<SimpleFeatureType, SimpleFeature>) geoObject;
1171 alfonx 420
1172 alfonx 1215 aReader = (AbstractGridCoverage2DReader) FeatureUtil
1173     .getWrappedGeoObject(rFc);
1174    
1175     } else if (geoObject instanceof AbstractGridCoverage2DReader) {
1176     aReader = (AbstractGridCoverage2DReader) geoObject;
1177    
1178     } else
1179     throw new RuntimeException("need a reader...");
1180     //
1181    
1182 alfonx 516 final GridCoverage2D cov = (GridCoverage2D) aReader
1183 alfonx 405 .read(new GeneralParameterValue[] { readGG });
1184     colorModel = cov.getRenderedImage().getColorModel();
1185     }
1186 alfonx 516 } catch (final Exception e) {
1187 alfonx 420 LOGGER.error("Error reading the colormodel from " + styledGrid, e);
1188 alfonx 405 return null;
1189     }
1190     return colorModel;
1191     }
1192    
1193     /**
1194     * @return <code>true</code> if a {@link RasterSymbolizer} can be applied
1195     * and will have an effect. Some rasters (e.g. GeoTIFF) can come
1196     * with their own {@link ColorModel} and will ignore any
1197     * {@link RasterSymbolizer} = SLD.
1198     */
1199 alfonx 516 public static boolean isStyleable(
1200     final StyledRasterInterface<?> styledRaster) {
1201     final ColorModel colorModel = getColorModel(styledRaster);
1202 alfonx 405
1203 alfonx 607 // LOGGER.info("The colormodel of " + styledRaster.getTitle() + " is "
1204     // + colorModel != null ? colorModel.getClass().getSimpleName() :
1205     // "NULL");
1206    
1207 alfonx 405 if (colorModel == null)
1208     return true;
1209     if (colorModel instanceof ComponentColorModel)
1210     return true;
1211 alfonx 1215 if (colorModel instanceof IndexColorModel)
1212     return true;
1213    
1214 alfonx 405 return false;
1215     }
1216 alfonx 517
1217     /**
1218     * Set the given Style as the Style of the {@link MapLayer}, unless the
1219     * styles are the same (not comparing selection stuff). If the
1220     * {@link MapLayer}s {@link Style} is changed, the selection FTS is kept.<br/>
1221     * Remember {@link MapLayer#setStyle(Style)} triggers an event leading to a
1222     * repaint, so only use it when needed.
1223     *
1224 alfonx 607 * @return <code>true</code> if the {@link MapLayer}'s {@link Style} has
1225     * been changed.
1226 alfonx 517 */
1227 alfonx 607 public static boolean updateMapLayerStyleIfChangedAndKeepSelection(
1228     MapLayer mapLayer, Style style2) {
1229 alfonx 517
1230     Style mapLayerStyleCleaned = StylingUtil
1231 alfonx 607 .removeSelectionFeatureTypeStyle(mapLayer.getStyle());
1232    
1233     Style newStyleCleaned = StylingUtil
1234     .removeSelectionFeatureTypeStyle(style2);
1235    
1236     if (StylingUtil.isStyleDifferent(mapLayerStyleCleaned, newStyleCleaned)) {
1237    
1238 alfonx 517 // They are different when compared without SELECTION FTS!
1239 alfonx 607
1240 alfonx 517 // Now let's copy any SELECTION FTS to the now style
1241 alfonx 607 FeatureTypeStyle selectionFeatureTypeStyle = StylingUtil
1242     .getSelectionFeatureTypeStyle(mapLayer.getStyle());
1243 alfonx 517 if (selectionFeatureTypeStyle != null) {
1244 alfonx 607 newStyleCleaned.featureTypeStyles().add(
1245     selectionFeatureTypeStyle);
1246     // newStyleCleaned is not so clean anymore... We just alled a
1247     // selcetion FTS
1248     }
1249    
1250 alfonx 517 mapLayer.setStyle(newStyleCleaned);
1251 alfonx 607
1252 alfonx 517 return true;
1253 alfonx 607
1254 alfonx 526 } else {
1255     return false;
1256     }
1257 alfonx 517 }
1258    
1259 alfonx 607 /**
1260     * After loading an atlas, the AttribteMetaData contains whatever is written
1261     * in the XML. But the DBF may have changed! This method checks an
1262     * {@link AttributeMetadataMap} against a schema and also corrects
1263     * upperCase/lowerCase problems. It will also remove any geometry column
1264     * attribute metadata.
1265     */
1266     /**
1267     * After loading an atlas, the AttribteMetaData contains whatever is written
1268     * in the XML. But the DBF may have changed!
1269     */
1270 alfonx 677 public static void checkAttribMetaData(
1271 alfonx 769 AttributeMetadataMap<AttributeMetadataImpl> attributeMetaDataMap,
1272     SimpleFeatureType schema) {
1273 alfonx 607
1274 alfonx 769 if (schema == null)
1275     throw new IllegalArgumentException("schmema may not be null!");
1276    
1277 alfonx 607 ArrayList<Name> willRemove = new ArrayList<Name>();
1278    
1279     // 1. Check.. all attributes in the atm should be in the schema as well.
1280     // maybe correct some upperCase/loweCase stuff
1281    
1282 alfonx 772 for (AttributeMetadataInterface atm : attributeMetaDataMap.values()) {
1283 alfonx 607
1284     AttributeDescriptor foundDescr = schema
1285     .getDescriptor(atm.getName());
1286     if (foundDescr == null) {
1287 alfonx 1215 NameImpl bestMatch = FeatureUtil.findBestMatchingAttribute(
1288     schema, atm.getLocalName());
1289 alfonx 607 if (bestMatch == null)
1290     willRemove.add(atm.getName());
1291     else
1292     atm.setName(bestMatch);
1293     } else if (foundDescr instanceof GeometryDescriptor) {
1294     // We don't want GeometryColumns in here
1295     willRemove.add(atm.getName());
1296     }
1297     }
1298    
1299     // Remove the ones that were not findable in the schema
1300     for (Name removeName : willRemove) {
1301 alfonx 677 if (attributeMetaDataMap.remove(removeName) == null) {
1302 alfonx 607 LOGGER.warn("removing the AMData didn't work");
1303     }
1304     }
1305    
1306     // 2. check... all attributes from the schema must have an ATM
1307     for (AttributeDescriptor ad : schema.getAttributeDescriptors()) {
1308     if (ad instanceof GeometryDescriptor)
1309     continue;
1310     if (!attributeMetaDataMap.containsKey(ad.getName())) {
1311 alfonx 1215 attributeMetaDataMap.put(new NameImpl(ad.getName()
1312     .getNamespaceURI(), ad.getName().getLocalPart()),
1313 alfonx 769 new AttributeMetadataImpl(ad, schema
1314     .getAttributeDescriptors().indexOf(ad),
1315     attributeMetaDataMap.getLanguages()));
1316 alfonx 607 }
1317     }
1318     }
1319    
1320 alfonx 677 /**
1321     * Checks every attribute name in the {@link AttributeMetadataMap} for its
1322     * binding type. It the type is textual, add the mrpty string as a NODATA
1323     * value.
1324     *
1325     * @param attributeMetaDataMap
1326     * @param schema
1327     */
1328     public static void addEmptyStringToAllTextualAttributes(
1329 alfonx 772 AttributeMetadataMap<? extends AttributeMetadataInterface> attributeMetaDataMap,
1330 alfonx 769 SimpleFeatureType schema) {
1331 alfonx 677
1332     for (Name name : attributeMetaDataMap.keySet()) {
1333     if (String.class.isAssignableFrom(schema.getDescriptor(name)
1334     .getType().getBinding())) {
1335     attributeMetaDataMap.get(name).getNodataValues().add("");
1336     }
1337     }
1338     }
1339 alfonx 769
1340     /**
1341     * @return a nicely formatted String containing all NODATA values of any
1342 alfonx 1215 * {@link AttributeMetadataInterface} object. Strings are quoted so
1343     * that any empty {@link String} can be seen.
1344 alfonx 769 */
1345     public static String formatNoDataValues(Set<Object> nodataValuesList) {
1346     String nicelyFormatted = "";
1347     if (nodataValuesList != null) {
1348     if (nodataValuesList.size() == 0)
1349     nicelyFormatted = "";
1350     else {
1351     for (Object ndo : nodataValuesList) {
1352     if (ndo instanceof String)
1353     nicelyFormatted += "\"" + ndo + "\"";
1354     else
1355     nicelyFormatted += ndo.toString();
1356    
1357     nicelyFormatted += ",";
1358     }
1359     // Remove the extra comma
1360 alfonx 1215 nicelyFormatted = nicelyFormatted.substring(0,
1361     nicelyFormatted.length() - 1);
1362 alfonx 769 }
1363     }
1364     return nicelyFormatted;
1365     }
1366 alfonx 244 }

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26