/[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 2 by mojays, Tue Feb 24 22:43:52 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.text.DecimalFormat;   *
4  import java.util.Map;   * This file is part of the SCHMITZM library - a collection of utility
5  import java.util.HashMap;   * classes based on Java 1.6, focusing (not only) on Java Swing
6  import java.util.List;   * and the Geotools library.
7  import java.net.URL;   *
8     * The SCHMITZM project is hosted at:
9  import org.geotools.feature.FeatureCollection;   * http://wald.intevation.org/projects/schmitzm/
10  import org.geotools.map.MapLayer;   *
11  import org.geotools.map.DefaultMapLayer;   * This program is free software; you can redistribute it and/or
12  import org.geotools.coverage.grid.GridCoverage2D;   * modify it under the terms of the GNU Lesser General Public License
13  import org.geotools.coverage.grid.io.AbstractGridCoverage2DReader;   * as published by the Free Software Foundation; either version 3
14  import org.geotools.styling.ColorMap;   * of the License, or (at your option) any later version.
15  import org.geotools.styling.ColorMapEntry;   *
16  import org.geotools.styling.Style;   * This program is distributed in the hope that it will be useful,
17     * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  import org.apache.log4j.Logger;   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19     * GNU General Public License for more details.
20  import org.jdom.Element;   *
21  import org.jdom.Document;   * You should have received a copy of the GNU Lesser General Public License (license.txt)
22  import org.jdom.input.SAXBuilder;   * along with this program; if not, write to the Free Software
23  import org.jdom.output.XMLOutputter;   * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
24     * or try this link: http://www.gnu.org/licenses/lgpl.html
25  import schmitzm.geotools.styling.StylingUtil;   *
26  import skrueger.AttributeMetaData;   * Contributors:
27  import skrueger.RasterLegendData;   *     Martin O. J. Schmitz - initial API and implementation
28  import skrueger.i8n.Translation;   *     Stefan A. Krüger - additional utility classes
29  import schmitzm.io.IOUtil;   ******************************************************************************/
30  import java.io.File;  package skrueger.geotools;
31  import java.io.FileNotFoundException;  
32  import schmitzm.lang.LangUtil;  import java.awt.Color;
33  import schmitzm.swing.SwingUtil;  import java.awt.Dimension;
34    import java.awt.Graphics;
35  import java.io.FileWriter;  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 StyledMapInterface} 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 StyledMapUtil {  import java.text.DecimalFormat;
44    private static final Logger LOGGER = Logger.getLogger(StyledMapUtil.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 StyledMapInterface} 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 StyledMapInterface} 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 StyledMapInterface ) {   * This class provides static helper methods for dealing with
86        style =  ((StyledMapInterface<?>)object).getStyle();   * {@link StyledLayerInterface} stuff.
87        object = ((StyledMapInterface<?>)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 StyledMapInterface} 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 StyledMapInterface<?> createStyledMap(Object object, String title) {           * {@link AbstractGridCoverage2DReader}, {@link FeatureCollection}) a
116       return createStyledMap(object, title, null);           * default style is generated.
117    }           *
118             * @param object
119    /**           *            an Object
120     * Creates an default instance of {@link StyledMapInterface} 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 StyledMapInterface<?> createStyledMap(Object object, String title, StyledMapStyle style) {          /**
129      StyledMapInterface<?> styledObject = 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        styledObject = 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             styledObject = 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        styledObject = 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 ( styledObject == null )  
156        throw new UnsupportedOperationException("Can not create StyledMapInterface object from "+(object == null ? "null" : object.getClass()));                  if (object instanceof GridCoverage2D)
157                            layer = new DefaultMapLayer((GridCoverage2D) object, style);
158      return styledObject;                  if (object instanceof AbstractGridCoverage2DReader)
159    }                          layer = new DefaultMapLayer((AbstractGridCoverage2DReader) object,
160                                            style);
161    /**                  if (object instanceof FeatureCollection)
162     * Parses a {@link AttributeMetaData} object from an JDOM-{@link Element}.                          layer = new DefaultMapLayer((FeatureCollection) object, style);
163     * This method works like {@link AMLImport#parseDataAttribute(org.w3c.dom.Node},  
164     * but for JDOM.                  if (layer == null)
165     * @param element {@link Element} to parse                          throw new Exception("Can not create MapLayer from "
166     */                                          + (object == null ? "null" : object.getClass()));
167    public static AttributeMetaData parseAttributeMetaData(final Element element) {  
168      final Integer col = Integer.valueOf(element.getAttributeValue("col"));                  return layer;
169      final Boolean visible = Boolean.valueOf(element.getAttributeValue("visible"));          }
170      final String unit = element.getAttributeValue("unit");  
171            /**
172      Translation name = new Translation();           * Creates an default instance of {@link StyledLayerInterface} for a
173      Translation desc = new Translation();           * Geotools object ({@link GridCoverage2D}, {@link FeatureCollection}) with
174      for (final Element childElement : (List<Element>)element.getChildren()) {           * a default style.
175        if (childElement.getName() == null)           *
176          continue;           * @param object
177             *            an Object
178        if (childElement.getName().equals("name"))           * @param title
179          name = parseTranslation(childElement);           *            title for the object
180        else if (childElement.getName().equals("desc"))           * @exception UnsupportedOperationException
181          desc = parseTranslation(childElement);           *                if {@code null} is given as object or an error occurs
182      }           *                during creation
183      return new AttributeMetaData(col, visible, name, desc, unit);           */
184    }          public static StyledLayerInterface<?> createStyledLayer(Object object,
185                            String title) {
186    /**                  return createStyledLayer(object, title, null);
187     * Parses a {@link AttributeMetaData} map from an JDOM-{@link Element}          }
188     * with {@code <attribute>}-childs.  
189     * @param element {@link Element} to parse          /**
190     */           * Creates an default instance of {@link StyledLayerInterface} for a
191    public static Map<Integer,AttributeMetaData> parseAttributeMetaDataMap(final Element element) {           * Geotools object ({@link GridCoverage2D}, {@link FeatureCollection}) with
192      HashMap<Integer,AttributeMetaData> metaData = new HashMap<Integer,AttributeMetaData>();           * a given style.
193      List<Element> attributesElements = element.getChildren( ELEM_NAME_ATTRIBUTE );           *
194      for (Element attibuteElement : attributesElements)           * @param object
195      {           *            an Object
196        AttributeMetaData attrMetaData = parseAttributeMetaData( attibuteElement );           * @param title
197        metaData.put( attrMetaData.getColIdx(), attrMetaData );           *            title for the object
198      }           * @param style
199      return metaData;           *            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     * Loads a {@link AttributeMetaData} object from an URL.           */
204     * @param documentUrl {@link URL} to parse          public static StyledLayerInterface<?> createStyledLayer(Object object,
205     * @see #parseAttributeMetaData(Element)                          String title, StyledLayerStyle style) {
206     */                  StyledLayerInterface<?> styledLayer = null;
207    public static Map<Integer,AttributeMetaData> loadAttributeMetaDataMap(final URL documentUrl) throws Exception {  
208      Document document = SAX_BUILDER.build(documentUrl);                  String id = (title != null) ? title : "defaultID";
209      return parseAttributeMetaDataMap( document.getRootElement() );  
210    }                  if (object instanceof GridCoverage2D)
211                            styledLayer = new StyledGridCoverage((GridCoverage2D) object, id,
212    /**                                          title, style);
213     * Creates an JDOM {@link Element} for the given {@link AttributeMetaData}                  else if (object instanceof AbstractGridCoverage2DReader)
214     * object.                          styledLayer = new StyledGridCoverageReader(
215     * @param amd meta data for one attribute                                          (AbstractGridCoverage2DReader) object, id, title, style);
216     */                  else if (object instanceof FeatureCollection)
217    public static Element createAttributeMetaDataElement(final AttributeMetaData amd) {                          styledLayer = new StyledFeatureCollection(
218      final Element element = new Element( ELEM_NAME_ATTRIBUTE , AMLURI);                                          (FeatureCollection) object, id, title, style);
219      element.setAttribute("col", String.valueOf( amd.getColIdx() ) );  
220      element.setAttribute("visible", String.valueOf( amd.isVisible() ) );                  if (styledLayer == null)
221      element.setAttribute("unit", amd.getUnit() );                          throw new UnsupportedOperationException(
222      // Creating a aml:name tag...                                          "Can not create StyledLayerInterface object from "
223      element.addContent( createTranslationElement("name", amd.getTitle()) );                                                          + (object == null ? "null" : object.getClass()));
224      // Creating a aml:desc tag...  
225      element.addContent( createTranslationElement("desc", amd.getDesc()) );                  return styledLayer;
226      return element;          }
227    }  
228            /**
229    /**           * Return only the visible or invisible entries of an AttributeMetaData-Map.
230     * Creates an JDOM {@link Element} for the given {@link AttributeMetaData}           *
231     * map.           * @param amdMap
232     * @param amdMap map of attribute meta data           *            AttributeMetaData-Map
233     */           * @param visible
234    public static Element createAttributeMetaDataMapElement(final Map<Integer,AttributeMetaData> amdMap) {           *            indicated whether the visible or invisible entries are
235      final Element element = new Element( ELEM_NAME_AMD , AMLURI);           *            returned
236      for (AttributeMetaData amd : amdMap.values())           */
237        element.addContent( createAttributeMetaDataElement( amd ) );          public static SortedMap<Integer, AttributeMetaData> getVisibleAttributeMetaData(
238      return element;                          Map<Integer, AttributeMetaData> amdMap, boolean visible) {
239    }                  SortedMap<Integer, AttributeMetaData> filteredMap = new TreeMap<Integer, AttributeMetaData>();
240                    for (AttributeMetaData amd : amdMap.values())
241    /**                          if (amd.isVisible())
242     * Saves a {@link AttributeMetaData AttributeMetaData-Map} to an URL.                                  filteredMap.put(amd.getColIdx(), amd);
243     * @param amdMap map of {@link AttributeMetaData}  
244     * @param documentUrl {@link URL} to store the XML                  return filteredMap;
245     */          }
246    public static void saveAttributeMetaDataMap(final Map<Integer,AttributeMetaData> amdMap, final URL documentUrl) throws Exception {  
247      // Create XML-Document          /**
248      final FileWriter out = new FileWriter( new File(documentUrl.toURI()) );           * Parses a {@link AttributeMetaData} object from an JDOM-{@link Element}.
249      XML_OUTPUTTER.output(           * This method works like {@link
250        createAttributeMetaDataMapElement(amdMap),           * AMLImport#parseDataAttribute(org.w3c.dom.Node}, but for JDOM.
251        out           *
252      );           * @param element
253      out.flush();           *            {@link Element} to parse
254      out.close();           */
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                                    .getAttributeValue("visible"));
259    /**                  final String unit = element.getAttributeValue("unit");
260     * Parses a {@link RasterLegendData} object from an JDOM-{@link Element}.  
261     * This method works like {@link AMLImport#parseRasterLegendData(org.w3c.dom.Node},                  Translation name = new Translation();
262     * but for JDOM.                  Translation desc = new Translation();
263     * @param element {@link Element} to parse                  for (final Element childElement : (List<Element>) element.getChildren()) {
264     */                          if (childElement.getName() == null)
265    public static RasterLegendData parseRasterLegendData(Element element) {                                  continue;
266    
267      final boolean paintGaps = Boolean.valueOf( element.getAttributeValue("paintGaps") );                          if (childElement.getName().equals("name"))
268                                    name = parseTranslation(childElement);
269      RasterLegendData rld = new RasterLegendData(paintGaps);                          else if (childElement.getName().equals("desc"))
270                                    desc = parseTranslation(childElement);
271      for ( Element childElement : (List<Element>)element.getChildren() ) {                  }
272        final String name = childElement.getName();                  return new AttributeMetaData(col, visible, name, desc, unit);
273        // Cancel if it's an attribute          }
274        if ( childElement.getChildren().size() == 0 )  
275          continue;          /**
276             * Parses a {@link AttributeMetaData} map from an JDOM-{@link Element} with
277        if (name.equals( ELEM_NAME_RASTERLEGEND )) {           * {@code <attribute>}-childs.
278          final String valueAttr = childElement.getAttributeValue("value");           *
279          if ( valueAttr == null )           * @param element
280            throw new UnsupportedOperationException("Attribute 'value' missing for definition of <"+ELEM_NAME_RASTERLEGEND+">");           *            {@link Element} to parse
281          final double value = Double.valueOf(valueAttr);           */
282            public static Map<Integer, AttributeMetaData> parseAttributeMetaDataMap(
283          // first and only item should be the label                          final Element element) {
284          final Element labelElement = childElement.getChild("label");                  HashMap<Integer, AttributeMetaData> metaData = new HashMap<Integer, AttributeMetaData>();
285          // id label element is missing, the translation is searched directly                  List<Element> attributesElements = element
286          // as childs of the rasterLegendItem element                                  .getChildren(ELEM_NAME_ATTRIBUTE);
287          Translation label = parseTranslation( labelElement != null ? labelElement : childElement );                  for (Element attibuteElement : attributesElements) {
288          rld.put(value, label);                          AttributeMetaData attrMetaData = parseAttributeMetaData(attibuteElement);
289        }                          metaData.put(attrMetaData.getColIdx(), attrMetaData);
290      }                  }
291                    return metaData;
292      return rld;          }
293    }  
294            /**
295    /**           * Loads a {@link AttributeMetaData} object from an URL.
296     * Loads a {@link RasterLegendData} object from an URL.           *
297     * @param documentUrl {@link URL} to parse           * @param documentUrl
298     * @see #parseAttributeMetaData(Element)           *            {@link URL} to parse
299     */           * @see #parseAttributeMetaData(Element)
300    public static RasterLegendData loadRasterLegendData(final URL documentUrl) throws Exception {           */
301      Document document = SAX_BUILDER.build(documentUrl);          public static Map<Integer, AttributeMetaData> loadAttributeMetaDataMap(
302      return parseRasterLegendData( document.getRootElement() );                          final URL documentUrl) throws Exception {
303    }                  Document document = SAX_BUILDER.build(documentUrl);
304                    return parseAttributeMetaDataMap(document.getRootElement());
305   /**          }
306     * Creates an JDOM {@link Element} for the given {@link RasterLegendData}  
307     * map.          /**
308     * @param rld raster legend data           * Creates an JDOM {@link Element} for the given {@link AttributeMetaData}
309     */           * object.
310    public static Element createRasterLegendDataElement(final RasterLegendData rld) {           *
311      final Element element = new Element( ELEM_NAME_RLD , AMLURI);           * @param amd
312      element.setAttribute("paintGaps", rld.isPaintGaps().toString());           *            meta data for one attribute
313      for (Double key : rld.getSortedKeys()) {           */
314        Element item = new Element( ELEM_NAME_RASTERLEGEND, AMLURI);          public static Element createAttributeMetaDataElement(
315        item.setAttribute("value", key.toString());                          final AttributeMetaData amd) {
316        item.addContent( createTranslationElement("label", rld.get(key)) );                  final Element element = new Element(ELEM_NAME_ATTRIBUTE, AMLURI);
317        element.addContent(item);                  element.setAttribute("col", String.valueOf(amd.getColIdx()));
318      }                  element.setAttribute("visible", String.valueOf(amd.isVisible()));
319      return element;                  element.setAttribute("unit", amd.getUnit());
320    }                  // Creating a aml:name tag...
321                    element.addContent(createTranslationElement("name", amd.getTitle()));
322    /**                  // Creating a aml:desc tag...
323     * Creates {@link RasterLegendData} from a {@link ColorMap}.                  element.addContent(createTranslationElement("desc", amd.getDesc()));
324     * @param colorMap  a color map                  return element;
325     * @param paintGaps indicated whether gaps are painted between the legend items          }
326     * @param digits    number of digits the grid value classes (and legend) are  
327     *                  rounded to (null means no round; >= 0 means digits after comma;          /**
328     *                  < 0 means digits before comma)    */           * Creates an JDOM {@link Element} for the given {@link AttributeMetaData}
329    public static RasterLegendData generateRasterLegendData(ColorMap colorMap, boolean paintGaps, Integer digits) {           * map.
330      DecimalFormat    decFormat = digits != null ? new DecimalFormat( SwingUtil.getNumberFormatPattern(digits) ) : null;           *
331      RasterLegendData rld       = new RasterLegendData(paintGaps);           * @param amdMap
332      for (ColorMapEntry cme : colorMap.getColorMapEntries())           *            map of attribute meta data
333      {           */
334        double value = StylingUtil.getQuantityFromColorMapEntry(cme);          public static Element createAttributeMetaDataMapElement(
335        String label = cme.getLabel();                          final Map<Integer, AttributeMetaData> amdMap) {
336        // if no label is set (e.g. quantitative style),                  final Element element = new Element(ELEM_NAME_AMD, AMLURI);
337        // use the value as label                  for (AttributeMetaData amd : amdMap.values())
338        if ( label == null || label.equals("") )                          element.addContent(createAttributeMetaDataElement(amd));
339          if ( digits == null )                  return element;
340            label = String.valueOf(value);          }
341          else  
342            label = decFormat.format( LangUtil.round(value, digits) );          /**
343        rld.put( value, new Translation("   "+label) );           * Saves a {@link AttributeMetaData AttributeMetaData-Map} to an URL.
344      }           *
345      return rld;           * @param amdMap
346    }           *            map of {@link AttributeMetaData}
347             * @param documentUrl
348    /**           *            {@link URL} to store the XML
349     * Creates {@link RasterLegendData} from the {@link ColorMap} of a style.           */
350     * @param style     a raster style (must contain a  {@link RasterSymbolizer})          public static void saveAttributeMetaDataMap(
351     * @param paintGaps indicated whether gaps are painted between the legend items                          final Map<Integer, AttributeMetaData> amdMap, final URL documentUrl)
352     * @param digits    number of digits the grid value classes (and legend) are                          throws Exception {
353     *                  rounded to (null means no round; >= 0 means digits after comma;                  // Create XML-Document
354     *                  < 0 means digits before comma)    */                  final FileWriter out = new FileWriter(new File(documentUrl.toURI()));
355    public static RasterLegendData generateRasterLegendData(Style style, boolean paintGaps, Integer digits) {                  XML_OUTPUTTER.output(createAttributeMetaDataMapElement(amdMap), out);
356      ColorMap colorMap = StylingUtil.getColorMapFromStyle(style);                  out.flush();
357      if ( colorMap == null)                  out.close();
358        throw new IllegalArgumentException("Color map can not be determined from style!");          }
359      return generateRasterLegendData(colorMap, paintGaps, digits);  
360    }          /**
361             * Parses a {@link RasterLegendData} object from an JDOM-{@link Element}.
362    /**           * This method works like {@link
363     * Saves a {@link RasterLegendData} to an URL.           * AMLImport#parseRasterLegendData(org.w3c.dom.Node}, but for JDOM.
364     * @param rld raster legend data           *
365     * @param documentUrl {@link URL} to store the XML           * @param element
366     */           *            {@link Element} to parse
367    public static void saveRasterLegendData(final RasterLegendData rld, final URL documentUrl) throws Exception {           */
368      // Create XML-Document          public static RasterLegendData parseRasterLegendData(Element element) {
369      final FileWriter out = new FileWriter( new File(documentUrl.toURI()) );  
370      XML_OUTPUTTER.output(                  final boolean paintGaps = Boolean.valueOf(element
371        createRasterLegendDataElement(rld),                                  .getAttributeValue("paintGaps"));
372        out  
373      );                  RasterLegendData rld = new RasterLegendData(paintGaps);
374      out.flush();  
375      out.close();                  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     * Parses a {@link Translation} object from an JDOM-{@link Element}.                                  continue;
380     * This method works like {@link AMLImport#parseTranslation(org.w3c.dom.Node},  
381     * but for JDOM.                          if (name.equals(ELEM_NAME_RASTERLEGEND)) {
382     * @param element {@link Element} to parse                                  final String valueAttr = childElement
383     */                                                  .getAttributeValue("value");
384    public final static Translation parseTranslation(final Element element) {                                  if (valueAttr == null)
385      Translation trans = new Translation();                                          throw new UnsupportedOperationException(
386                                                            "Attribute 'value' missing for definition of <"
387      if (element == null)                                                                          + ELEM_NAME_RASTERLEGEND + ">");
388       return trans;                                  final double value = Double.valueOf(valueAttr);
389    
390      for (final Element translationElement : (List<Element>)element.getChildren()) {                                  // first and only item should be the label
391        final String name = translationElement.getName();                                  final Element labelElement = childElement.getChild("label");
392        if (name == null)                                  // id label element is missing, the translation is searched
393          continue;                                  // directly
394                                    // as childs of the rasterLegendItem element
395        // lang attribute                                  Translation label = parseTranslation(labelElement != null ? labelElement
396        String lang = translationElement.getAttributeValue("lang");                                                  : childElement);
397        // set the default, if no language code is set                                  rld.put(value, label);
398        if ( lang == null )                          }
399          lang = Translation.DEFAULT_KEY;                  }
400    
401        final String translationText = translationElement.getValue();                  return rld;
402        if (translationText == null)          }
403          trans.put(lang, "");  
404        else          /**
405          trans.put(lang, translationText);           * Loads a {@link RasterLegendData} object from an URL.
406      }           *
407             * @param documentUrl
408      // if no <translation> is given, the value of the node should           *            {@link URL} to parse
409      // be used as a default translation           * @see #parseAttributeMetaData(Element)
410      if (trans.size() == 0)           */
411        trans.put( Translation.DEFAULT_KEY, element.getValue() );          public static RasterLegendData loadRasterLegendData(final URL documentUrl)
412      //     trans = new Translation( ((List<Element>)element.getChildren()).get(0).getValue() );                          throws Exception {
413                    Document document = SAX_BUILDER.build(documentUrl);
414      return trans;                  return parseRasterLegendData(document.getRootElement());
415    }          }
416    
417    /**          /**
418     * Creates an JDOM {@link Element} for the given {@link Translation}.           * Creates an JDOM {@link Element} for the given {@link RasterLegendData}
419     * @param tagname Name of the Element           * map.
420     * @param translation Translation to store in the Element           *
421     */           * @param rld
422    public final static Element createTranslationElement(String tagname, Translation translation) {           *            raster legend data
423      Element element = new Element(tagname, AMLURI);           */
424      if ( translation == null )          public static Element createRasterLegendDataElement(
425        throw new UnsupportedOperationException("Translation element can not be created from null!");                          final RasterLegendData rld) {
426                    final Element element = new Element(ELEM_NAME_RLD, AMLURI);
427      // If only a default translation is set, the <translation lang="..">..</tranlation>                  element.setAttribute("paintGaps", rld.isPaintGaps().toString());
428      // part is not used                  for (Double key : rld.getSortedKeys()) {
429      if (translation.keySet().size() == 1 && translation.get(Translation.DEFAULT_KEY) != null) {                          Element item = new Element(ELEM_NAME_RASTERLEGEND, AMLURI);
430        element.addContent( translation.get(Translation.DEFAULT_KEY) );                          item.setAttribute("value", key.toString());
431        return element;                          item.addContent(createTranslationElement("label", rld.get(key)));
432      }                          element.addContent(item);
433                    }
434      // add a <translation lang="..">..</tranlation> part to the element for                  return element;
435      // all languages          }
436      for (String lang : translation.keySet()) {  
437        Element translationElement = new Element( ELEM_NAME_TRANSLATION , AMLURI);          /**
438        translationElement.setAttribute("lang", lang);           * Creates {@link RasterLegendData} from a {@link ColorMap}.
439        String translationString = translation.get(lang);           *
440        if (translationString == null)           * @param colorMap
441         translationString = "";           *            a color map
442        translationElement.addContent( translationString );           * @param paintGaps
443        element.addContent(translationElement);           *            indicated whether gaps are painted between the legend items
444      }           * @param digits
445             *            number of digits the grid value classes (and legend) are
446      return element;           *            rounded to (null means no round; >= 0 means digits after
447    }           *            comma; < 0 means digits before comma)
448             */
449            public static RasterLegendData generateRasterLegendData(ColorMap colorMap,
450    /**                          boolean paintGaps, Integer digits) {
451     * Sets a style to {@link StyledMapInterface}.                  DecimalFormat decFormat = digits != null ? new DecimalFormat(SwingUtil
452     * @param styledObject a styled object                                  .getNumberFormatPattern(digits)) : null;
453     * @param style a Style                  RasterLegendData rld = new RasterLegendData(paintGaps);
454     */                  for (ColorMapEntry cme : colorMap.getColorMapEntries()) {
455    public static void setStyledMapStyle(StyledMapInterface styledObject, StyledMapStyle<?> style) {                          double value = StylingUtil.getQuantityFromColorMapEntry(cme);
456      // set SLD style                          String label = cme.getLabel();
457      styledObject.setStyle( style.getGeoObjectStyle() );                          // if no label is set (e.g. quantitative style),
458      // set meta data                          // use the value as label
459      if ( styledObject        instanceof StyledGridCoverageInterface &&                          if (label == null || label.equals(""))
460           (style.getMetaData() instanceof RasterLegendData || style.getMetaData() == null) ) {                                  if (digits == null)
461        RasterLegendData sourceRld = (RasterLegendData)style.getMetaData();                                          label = String.valueOf(value);
462        RasterLegendData destRld = ((StyledGridCoverageInterface)styledObject).getLegendMetaData();                                  else
463        if ( destRld != null && sourceRld != null ) {                                          label = decFormat.format(LangUtil.round(value, digits));
464          destRld.setPaintGaps(sourceRld.isPaintGaps());                          rld.put(value, new Translation("   " + label));
465          destRld.clear();                  }
466          destRld.putAll( sourceRld );                  return rld;
467        }          }
468        return;  
469      }          /**
470      if ( styledObject        instanceof StyledFeatureCollectionInterface &&           * Creates {@link RasterLegendData} from the {@link ColorMap} of a style.
471           (style.getMetaData() instanceof Map || style.getMetaData() == null) ) {           *
472        Map<Integer, AttributeMetaData> sourceAmd = (Map<Integer, AttributeMetaData>)style.getMetaData();           * @param style
473        Map<Integer, AttributeMetaData> destAmd   = ((StyledFeatureCollectionInterface)styledObject).getAttributeMetaDataMap();           *            a raster style (must contain a {@link RasterSymbolizer})
474        if ( destAmd != null && sourceAmd != null ) {           * @param paintGaps
475          destAmd.clear();           *            indicated whether gaps are painted between the legend items
476          destAmd.putAll( sourceAmd );           * @param digits
477        }           *            number of digits the grid value classes (and legend) are
478        return;           *            rounded to (null means no round; >= 0 means digits after
479      }           *            comma; < 0 means digits before comma)
480             */
481      throw new UnsupportedOperationException("Style is not compatible to object: " +          public static RasterLegendData generateRasterLegendData(Style style,
482                                              (style.getMetaData() == null ? null : style.getMetaData().getClass().getSimpleName()) +                          boolean paintGaps, Integer digits) {
483                                              " <-> " +                  ColorMap colorMap = StylingUtil.getColorMapFromStyle(style);
484                                              (styledObject == null ? null : styledObject.getClass().getSimpleName()));                  if (colorMap == null)
485    }                          throw new IllegalArgumentException(
486                                            "Color map can not be determined from style!");
487    /**                  return generateRasterLegendData(colorMap, paintGaps, digits);
488     * Returns the style a {@link StyledMapInterface} as a {@link StyledMapStyle}.          }
489     * @param styledObject a styled object  
490     * @return {@code StyledMapStyle<RasterLegendData>} for {@link StyledGridCoverageInterface}          /**
491     *         or {@code StyledMapStyle<Map<Integer,AttributeMetaData>>} for           * Saves a {@link RasterLegendData} to an URL.
492     *         {@link StyledFeatureCollectionInterface}           *
493     */           * @param rld
494    public static StyledMapStyle<?> getStyledMapStyle(StyledMapInterface styledObject) {           *            raster legend data
495      if ( styledObject instanceof StyledGridCoverageInterface )           * @param documentUrl
496        return getStyledMapStyle( (StyledGridCoverageInterface)styledObject );           *            {@link URL} to store the XML
497      if ( styledObject instanceof StyledFeatureCollectionInterface )           */
498        return getStyledMapStyle( (StyledFeatureCollectionInterface)styledObject );          public static void saveRasterLegendData(final RasterLegendData rld,
499      throw new UnsupportedOperationException("Unknown type of StyledMapInterface: "+(styledObject == null ? null : styledObject.getClass().getSimpleName()));                          final URL documentUrl) throws Exception {
500    }                  // Create XML-Document
501                    final FileWriter out = new FileWriter(new File(documentUrl.toURI()));
502    /**                  XML_OUTPUTTER.output(createRasterLegendDataElement(rld), out);
503     * Returns the style and raster meta data of a {@link StyledGridCoverageInterface}                  out.flush();
504     * as a {@link StyledMapStyle}.                  out.close();
505     * @param styledGC a styled grid coverage          }
506     */  
507    public static StyledMapStyle<RasterLegendData> getStyledMapStyle(StyledGridCoverageInterface styledGC) {          /**
508      return new StyledMapStyle<RasterLegendData>(           * Parses a {@link Translation} object from an JDOM-{@link Element}. This
509        styledGC.getStyle(),           * method works like {@link AMLImport#parseTranslation(org.w3c.dom.Node},
510        styledGC.getLegendMetaData()           * but for JDOM.
511      );           *
512    }           * @param element
513             *            {@link Element} to parse
514    /**           */
515     * Returns the style and attribute meta data of a {@link StyledFeatureCollectionInterface}          public final static Translation parseTranslation(final Element element) {
516     * as a {@link StyledMapStyle}.                  Translation trans = new Translation();
517     * @param styledFC a styled feature collection  
518     */                  if (element == null)
519    public static StyledMapStyle<Map<Integer,AttributeMetaData>> getStyledMapStyle(StyledFeatureCollectionInterface styledFC) {                          return trans;
520      return new StyledMapStyle<Map<Integer,AttributeMetaData>>(  
521        styledFC.getStyle(),                  for (final Element translationElement : (List<Element>) element
522        styledFC.getAttributeMetaDataMap()                                  .getChildren()) {
523      );                          final String name = translationElement.getName();
524    }                          if (name == null)
525                                    continue;
526    /**  
527     * Loads a {@linkplain Style SLD-Style} and {@linkplain RasterLegendData Raster-LegendData}                          // lang attribute
528     * for a given geo-object (raster) source. The SLD file must be present. A missing                          String lang = translationElement.getAttributeValue("lang");
529     * raster legend-data file is tolerated.                          // set the default, if no language code is set
530     * @param geoObjectURL URL of the (already read) raster object                          if (lang == null)
531     * @param sldExt file extention for the SLD file                                  lang = Translation.DEFAULT_KEY;
532     * @param rldExt file extention for the raster legend-data file  
533     * @return {@code null} in case of any error                          final String translationText = translationElement.getValue();
534     */                          if (translationText == null)
535    public static StyledMapStyle<RasterLegendData> loadStyledRasterStyle(URL geoObjectURL, String sldExt, String rldExt) {                                  trans.put(lang, "");
536      RasterLegendData metaData = null;                          else
537      Style sldStyle = null;                                  trans.put(lang, translationText);
538      try {                  }
539        Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(geoObjectURL, sldExt));  
540        // SLD must be present                  // if no <translation> is given, the value of the node should
541        if ( styles == null || styles.length == 0 )                  // be used as a default translation
542          return null;                  if (trans.size() == 0)
543        sldStyle = styles[0];                          trans.put(Translation.DEFAULT_KEY, element.getValue());
544      }                  // trans = new Translation(
545      catch (Exception err) {                  // ((List<Element>)element.getChildren()).get(0).getValue() );
546        // SLD must be present  
547        LangUtil.logDebugError(LOGGER,err);                  return trans;
548        return null;          }
549      }  
550            /**
551      try {           * Creates an JDOM {@link Element} for the given {@link Translation}.
552        metaData = StyledMapUtil.loadRasterLegendData( IOUtil.changeUrlExt(geoObjectURL,rldExt) );           *
553      } catch (FileNotFoundException err) {           * @param tagname
554        // ignore missing raster legend data           *            Name of the Element
555      } catch (Exception err) {           * @param translation
556        // any other error during legend data creation leads to error           *            Translation to store in the Element
557        LangUtil.logDebugError(LOGGER,err);           */
558        return null;          public final static Element createTranslationElement(String tagname,
559      }                          Translation translation) {
560      return new StyledMapStyle<RasterLegendData>(sldStyle, metaData);                  Element element = new Element(tagname, AMLURI);
561    }                  if (translation == null)
562                            throw new UnsupportedOperationException(
563    /**                                          "Translation element can not be created from null!");
564     * Loads a {@linkplain Style SLD-Style} from a {@code .sld} file and  
565     * {@linkplain RasterLegendData Raster-LegendData} from a {@code .rld} file                  // If only a default translation is set, the <translation
566     * for a given geo-object (raster) source. The SLD file must be present. A missing                  // lang="..">..</tranlation>
567     * raster legend-data file is tolerated.                  // part is not used
568     * @param geoObjectURL URL of the (already read) raster object                  if (translation.keySet().size() == 1
569     * @param sldExt file extention for the SLD file                                  && translation.get(Translation.DEFAULT_KEY) != null) {
570     * @param rldExt file extention for the raster legend-data file                          element.addContent(translation.get(Translation.DEFAULT_KEY));
571     * @return {@code null} in case of any error                          return element;
572     */                  }
573    public static StyledMapStyle<RasterLegendData> loadStyledRasterStyle(URL geoObjectURL) {  
574      return loadStyledRasterStyle(geoObjectURL, "sld", "rld");                  // add a <translation lang="..">..</tranlation> part to the element for
575    }                  // all languages
576                    for (String lang : translation.keySet()) {
577    /**                          Element translationElement = new Element(ELEM_NAME_TRANSLATION,
578     * Loads a {@linkplain Style SLD-Style} and a {@linkplain AttributeMetaData AttributeMetaData-Map}                                          AMLURI);
579     * for a given geo-object (feature) source. The SLD file must be present. A missing                          translationElement.setAttribute("lang", lang);
580     * attribute meta-data file is tolerated.                          String translationString = translation.get(lang);
581     * @param geoObjectURL URL of the (already read) feature object                          if (translationString == null)
582     * @param sldExt file extention for the SLD file                                  translationString = "";
583     * @param rldExt file extention for the raster legend-data file                          translationElement.addContent(translationString);
584     * @return {@code null} in case of any error                          element.addContent(translationElement);
585     */                  }
586    public static StyledMapStyle<Map<Integer,AttributeMetaData>> loadStyledFeatureStyle(URL geoObjectURL, String sldExt, String rldExt) {  
587      Map<Integer,AttributeMetaData> metaData = null;                  return element;
588      Style                          sldStyle = null;          }
589      try {  
590        Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(geoObjectURL, sldExt));          /**
591        // SLD must be present           * Sets a style to {@link StyledLayerInterface}.
592        if ( styles == null || styles.length == 0 )           *
593          return null;           * @param styledObject
594        sldStyle = styles[0];           *            a styled object
595      } catch (Exception err) {           * @param style
596        // SLD must be present           *            a Style
597        LangUtil.logDebugError(LOGGER,err);           */
598        return null;          public static void setStyledLayerStyle(StyledLayerInterface styledObject,
599      }                          StyledLayerStyle<?> style) {
600                    // set SLD style
601      try {                  styledObject.setStyle(style.getGeoObjectStyle());
602        metaData = StyledMapUtil.loadAttributeMetaDataMap( IOUtil.changeUrlExt(geoObjectURL,rldExt) );                  // set meta data
603      } catch (FileNotFoundException err) {                  if (styledObject instanceof StyledGridCoverageInterface
604        // ignore missing attribute meta data                                  && (style.getMetaData() instanceof RasterLegendData || style
605      } catch (Exception err) {                                                  .getMetaData() == null)) {
606        // any other error during meta data creation leads to error                          RasterLegendData sourceRld = (RasterLegendData) style.getMetaData();
607        LangUtil.logDebugError(LOGGER,err);                          RasterLegendData destRld = ((StyledGridCoverageInterface) styledObject)
608        return null;                                          .getLegendMetaData();
609      }                          if (destRld != null && sourceRld != null) {
610                                    destRld.setPaintGaps(sourceRld.isPaintGaps());
611      return new StyledMapStyle<Map<Integer,AttributeMetaData>>(sldStyle, metaData);                                  destRld.clear();
612    }                                  destRld.putAll(sourceRld);
613                            }
614    /**                          return;
615     * Loads a {@linkplain Style SLD-Style} from a {@code .sld} file and                  }
616     * {@linkplain AttributeMetaData AttributeMetaData-Map} from a {@code .amd} file                  if (styledObject instanceof StyledFeatureCollectionInterface
617     * for a given geo-object (feature) source. The SLD file must be present. A missing                                  && (style.getMetaData() instanceof Map || style.getMetaData() == null)) {
618     * attribute meta-data file is tolerated.                          Map<Integer, AttributeMetaData> sourceAmd = (Map<Integer, AttributeMetaData>) style
619     * @param geoObjectURL URL of the (already read) feature object                                          .getMetaData();
620     * @param sldExt file extention for the SLD file                          Map<Integer, AttributeMetaData> destAmd = ((StyledFeatureCollectionInterface) styledObject)
621     * @param rldExt file extention for the raster legend-data file                                          .getAttributeMetaDataMap();
622     * @return {@code null} in case of any error                          if (destAmd != null && sourceAmd != null) {
623     */                                  destAmd.clear();
624    public static StyledMapStyle<Map<Integer,AttributeMetaData>> loadStyledFeatureStyle(URL geoObjectURL) {                                  destAmd.putAll(sourceAmd);
625      return loadStyledFeatureStyle(geoObjectURL, "sld", "amd");                          }
626    }                          return;
627                    }
628    /**  
629     * Stores a {@linkplain Style SLD-Style} and {@linkplain RasterLegendData Raster-LegendData}                  throw new UnsupportedOperationException(
630     * for a given geo-object (raster) source.                                  "Style is not compatible to object: "
631     * @param style  style to save                                                  + (style.getMetaData() == null ? null : style
632     * @param geoObjectURL URL of the raster object                                                                  .getMetaData().getClass().getSimpleName())
633     * @param sldExt file extention for the SLD file                                                  + " <-> "
634     * @param mdExt file extention for the meta-data file                                                  + (styledObject == null ? null : styledObject
635     */                                                                  .getClass().getSimpleName()));
636    public static <T> void saveStyledMapStyle(StyledMapStyle<T> style, URL geoObjectURL, String sldExt, String mdExt) throws Exception {          }
637      // Store the SLD  
638      Style sldStyle = style.getGeoObjectStyle();          /**
639      if ( sldStyle != null ) {           * Returns the style a {@link StyledLayerInterface} as a
640        StylingUtil.saveStyleToSLD(           * {@link StyledLayerStyle}.
641           sldStyle,           *
642           IOUtil.changeFileExt(           * @param styledObject
643                new File(geoObjectURL.toURI()),           *            a styled object
644                sldExt           * @return {@code StyledLayerStyle<RasterLegendData>} for
645           )           *         {@link StyledGridCoverageInterface} or {@code
646        );           *         StyledLayerStyle<Map<Integer,AttributeMetaData>>} for
647      }           *         {@link StyledFeatureCollectionInterface}
648             */
649      // Store the meta data          public static StyledLayerStyle<?> getStyledLayerStyle(
650      T metaData = style.getMetaData();                          StyledLayerInterface styledObject) {
651      if ( metaData != null ) {                  if (styledObject instanceof StyledGridCoverageInterface)
652        if ( metaData instanceof RasterLegendData ) {                          return getStyledLayerStyle((StyledGridCoverageInterface) styledObject);
653          saveRasterLegendData(                  if (styledObject instanceof StyledFeatureCollectionInterface)
654              (RasterLegendData)metaData,                          return getStyledLayerStyle((StyledFeatureCollectionInterface) styledObject);
655              IOUtil.changeUrlExt(geoObjectURL,mdExt)                  throw new UnsupportedOperationException(
656          );                                  "Unknown type of StyledLayerInterface: "
657  //      } else if ( metaData instanceof Map<Integer,AttributeMetaData> ) { // LEIDER NICHT KOMPILIERBAR!!                                                  + (styledObject == null ? null : styledObject
658        } else if ( metaData instanceof Map ) {                                                                  .getClass().getSimpleName()));
659          saveAttributeMetaDataMap(          }
660              (Map<Integer,AttributeMetaData>)metaData,  
661              IOUtil.changeUrlExt(geoObjectURL,mdExt)          /**
662          );           * Returns the style and raster meta data of a
663        } else           * {@link StyledGridCoverageInterface} as a {@link StyledLayerStyle}.
664          throw new UnsupportedOperationException("Export for meta data not yet supported: "+metaData.getClass().getSimpleName());           *
665      }           * @param styledGC
666    }           *            a styled grid coverage
667             */
668    /**          public static StyledLayerStyle<RasterLegendData> getStyledLayerStyle(
669     * Stores the {@linkplain Style SLD-Style} to a {@code .sld} file and                          StyledGridCoverageInterface styledGC) {
670     * the meta data ({@link RasterLegendData} or {@link AttributeMetaData})                  return new StyledLayerStyle<RasterLegendData>(styledGC.getStyle(),
671     * to a {@code .rld} or {@code .amd} file.                                  styledGC.getLegendMetaData());
672     * for a given geo-object source.          }
673     * @param style  style to save  
674     * @param geoObjectURL URL of the (already read) raster object          /**
675     */           * Returns the style and attribute meta data of a
676    public static void saveStyledMapStyle(StyledMapStyle<?> style, URL geoObjectURL) throws Exception {           * {@link StyledFeatureCollectionInterface} as a {@link StyledLayerStyle}.
677      if ( style.getMetaData() instanceof RasterLegendData )           *
678        saveStyledMapStyle(style,geoObjectURL, "sld", "rld");           * @param styledFC
679      else           *            a styled feature collection
680        saveStyledMapStyle(style,geoObjectURL, "sld", "amd");           */
681    }          public static StyledLayerStyle<Map<Integer, AttributeMetaData>> getStyledLayerStyle(
682                            StyledFeatureCollectionInterface styledFC) {
683  }                  return new StyledLayerStyle<Map<Integer, AttributeMetaData>>(styledFC
684                                    .getStyle(), styledFC.getAttributeMetaDataMap());
685            }
686    
687            /**
688             * Loads a {@linkplain Style SLD-Style} and {@linkplain RasterLegendData
689             * Raster-LegendData} for a given geo-object (raster) source. The SLD file
690             * must be present. A missing raster legend-data file is tolerated.
691             *
692             * @param geoObjectURL
693             *            URL of the (already read) raster object
694             * @param sldExt
695             *            file extention for the SLD file
696             * @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.2  
changed lines
  Added in v.400

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26