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

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

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

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

Legend:
Removed from v.127  
changed lines
  Added in v.1273

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26