/[schmitzm]/trunk/src/skrueger/geotools/StyledLayerUtil.java
ViewVC logotype

Diff of /trunk/src/skrueger/geotools/StyledLayerUtil.java

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

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

Legend:
Removed from v.244  
changed lines
  Added in v.534

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26