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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26