/[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

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

Legend:
Removed from v.397  
changed lines
  Added in v.607

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26