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

Legend:
Removed from v.224  
changed lines
  Added in v.400

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26