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

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26