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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26