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

Legend:
Removed from v.111  
changed lines
  Added in v.405

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26