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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26