/[schmitzm]/trunk/src/skrueger/geotools/StyledLayerUtil.java
ViewVC logotype

Annotation of /trunk/src/skrueger/geotools/StyledLayerUtil.java

Parent Directory Parent Directory | Revision Log Revision Log


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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26