/[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 trunk/src/skrueger/geotools/StyledLayerUtil.java revision 685 by alfonx, Wed Feb 10 15:04:02 2010 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           *            TODO Since GP 1.3 the {@link AttributeMetadata} class has more
312     */           *            attributes which are not used by Xulu/ISDSS. GP
313    public static Element createAttributeMetaDataMapElement(final Map<Integer,AttributeMetaData> amdMap) {           *            exports/imports the AMD via AMLExporter and AMLImporter
314      final Element element = new Element( ELEM_NAME_AMD , AMLURI);           *            classes. (SK, 3.2.2010) *
315      for (AttributeMetaData amd : amdMap.values())           */
316        element.addContent( createAttributeMetaDataElement( amd ) );          public static AttributeMetadataMap parseAttributeMetaDataMap(
317      return element;                          final Element element) {
318    }                  final AttributeMetadataMap metaData = new AttributeMetadataMap();
319                    final List<Element> attributesElements = element
320    /**                                  .getChildren(ELEM_NAME_ATTRIBUTE);
321     * Saves a {@link AttributeMetaData AttributeMetaData-Map} to an URL.                  for (final Element attibuteElement : attributesElements) {
322     * @param amdMap map of {@link AttributeMetaData}                          final AttributeMetadata attrMetaData = parseAttributeMetaData(attibuteElement);
323     * @param documentUrl {@link URL} to store the XML                          metaData.put(attrMetaData.getName(), attrMetaData);
324     */                  }
325    public static void saveAttributeMetaDataMap(final Map<Integer,AttributeMetaData> amdMap, final URL documentUrl) throws Exception {                  return metaData;
326      // Create XML-Document          }
327      final FileWriter out = new FileWriter( new File(documentUrl.toURI()) );  
328      XML_OUTPUTTER.output(          /**
329        createAttributeMetaDataMapElement(amdMap),           * Loads a {@link AttributeMetadata} object from an URL.
330        out           *
331      );           * @param documentUrl
332      out.flush();           *            {@link URL} to parse
333      out.close();           * @see #parseAttributeMetaData(Element)
334    }           */
335            public static AttributeMetadataMap loadAttributeMetaDataMap(
336                            final URL documentUrl) throws Exception {
337                    final Document document = SAX_BUILDER.build(documentUrl);
338    /**                  return parseAttributeMetaDataMap(document.getRootElement());
339     * Parses a {@link RasterLegendData} object from an JDOM-{@link Element}.          }
340     * This method works like {@link AMLImport#parseRasterLegendData(org.w3c.dom.Node},  
341     * but for JDOM.          /**
342     * @param element {@link Element} to parse           * Creates an JDOM {@link Element} for the given {@link AttributeMetadata}
343     */           * object.
344    public static RasterLegendData parseRasterLegendData(Element element) {           *
345             * @param amd
346      final boolean paintGaps = Boolean.valueOf( element.getAttributeValue("paintGaps") );           *            meta data for one attribute
347             *
348      RasterLegendData rld = new RasterLegendData(paintGaps);           *            TODO Since GP 1.3 the {@link AttributeMetadata} class has more
349             *            attributes which are not used by Xulu/ISDSS. GP
350      for ( Element childElement : (List<Element>)element.getChildren() ) {           *            exports/imports the AMD via AMLExporter and AMLImporter
351        final String name = childElement.getName();           *            classes. (SK, 3.2.2010)
352        // Cancel if it's an attribute           */
353        if ( childElement.getChildren().size() == 0 )          public static Element createAttributeMetaDataElement(
354          continue;                          final AttributeMetadata amd) {
355                    final Element element = new Element(ELEM_NAME_ATTRIBUTE, AMLURI);
356        if (name.equals( ELEM_NAME_RASTERLEGEND )) {                  element.setAttribute("namespace", String.valueOf(amd.getName()
357          final String valueAttr = childElement.getAttributeValue("value");                                  .getNamespaceURI()));
358          if ( valueAttr == null )                  element.setAttribute("localname", String.valueOf(amd.getLocalName()));
359            throw new UnsupportedOperationException("Attribute 'value' missing for definition of <"+ELEM_NAME_RASTERLEGEND+">");                  element.setAttribute("visible", String.valueOf(amd.isVisible()));
360          final double value = Double.valueOf(valueAttr);                  element.setAttribute("unit", amd.getUnit());
361                    // Creating a aml:name tag...
362          // first and only item should be the label                  element.addContent(createTranslationElement("name", amd.getTitle()));
363          final Element labelElement = childElement.getChild("label");                  // Creating a aml:desc tag...
364          // id label element is missing, the translation is searched directly                  element.addContent(createTranslationElement("desc", amd.getDesc()));
365          // as childs of the rasterLegendItem element                  return element;
366          Translation label = parseTranslation( labelElement != null ? labelElement : childElement );          }
367          rld.put(value, label);  
368        }          /**
369      }           * Creates an JDOM {@link Element} for the given {@link AttributeMetadata}
370             * map.
371      return rld;           *
372    }           * @param amdMap
373             *            map of attribute meta data
374    /**           */
375     * Loads a {@link RasterLegendData} object from an URL.          public static Element createAttributeMetaDataMapElement(
376     * @param documentUrl {@link URL} to parse                          final AttributeMetadataMap amdMap) {
377     * @see #parseAttributeMetaData(Element)                  final Element element = new Element(ELEM_NAME_AMD, AMLURI);
378     */                  for (final AttributeMetadata amd : amdMap.values())
379    public static RasterLegendData loadRasterLegendData(final URL documentUrl) throws Exception {                          element.addContent(createAttributeMetaDataElement(amd));
380      Document document = SAX_BUILDER.build(documentUrl);                  return element;
381      return parseRasterLegendData( document.getRootElement() );          }
382    }  
383            /**
384   /**           * Saves a {@link AttributeMetadata AttributeMetaData-Map} to an URL.
385     * Creates an JDOM {@link Element} for the given {@link RasterLegendData}           *
386     * map.           * @param amdMap
387     * @param rld raster legend data           *            map of {@link AttributeMetadata}
388     */           * @param documentUrl
389    public static Element createRasterLegendDataElement(final RasterLegendData rld) {           *            {@link URL} to store the XML
390      final Element element = new Element( ELEM_NAME_RLD , AMLURI);           */
391      element.setAttribute("paintGaps", rld.isPaintGaps().toString());          public static void saveAttributeMetaDataMap(
392      for (Double key : rld.getSortedKeys()) {                          final AttributeMetadataMap amdMap, final URL documentUrl)
393        Element item = new Element( ELEM_NAME_RASTERLEGEND, AMLURI);                          throws Exception {
394        item.setAttribute("value", key.toString());                  // Create XML-Document
395        item.addContent( createTranslationElement("label", rld.get(key)) );                  final FileWriter out = new FileWriter(new File(documentUrl.toURI()));
396        element.addContent(item);                  XML_OUTPUTTER.output(createAttributeMetaDataMapElement(amdMap), out);
397      }                  out.flush();
398      return element;                  out.close();
399    }          }
400    
401    /**          /**
402     * Creates {@link RasterLegendData} from a {@link ColorMap}.           * Parses a {@link RasterLegendData} object from an JDOM-{@link Element}.
403     * @param colorMap  a color map           * This method works like {@link
404     * @param paintGaps indicated whether gaps are painted between the legend items           * AMLImport#parseRasterLegendData(org.w3c.dom.Node}, but for JDOM.
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;           * @param element
407     *                  < 0 means digits before comma)    */           *            {@link Element} to parse
408    public static RasterLegendData generateRasterLegendData(ColorMap colorMap, boolean paintGaps, Integer digits) {           */
409      DecimalFormat    decFormat = digits != null ? new DecimalFormat( SwingUtil.getNumberFormatPattern(digits) ) : null;          public static RasterLegendData parseRasterLegendData(final Element element) {
410      RasterLegendData rld       = new RasterLegendData(paintGaps);  
411      for (ColorMapEntry cme : colorMap.getColorMapEntries())                  final boolean paintGaps = Boolean.valueOf(element
412      {                                  .getAttributeValue("paintGaps"));
413        double value = StylingUtil.getQuantityFromColorMapEntry(cme);  
414        String label = cme.getLabel();                  final RasterLegendData rld = new RasterLegendData(paintGaps);
415        // if no label is set (e.g. quantitative style),  
416        // use the value as label                  for (final Element childElement : (List<Element>) element.getChildren()) {
417        if ( label == null || label.equals("") )                          final String name = childElement.getName();
418          if ( digits == null )                          // Cancel if it's an attribute
419            label = String.valueOf(value);                          if (childElement.getChildren().size() == 0)
420          else                                  continue;
421            label = decFormat.format( LangUtil.round(value, digits) );  
422        rld.put( value, new Translation("   "+label) );                          if (name.equals(ELEM_NAME_RASTERLEGEND)) {
423      }                                  final String valueAttr = childElement
424      return rld;                                                  .getAttributeValue("value");
425    }                                  if (valueAttr == null)
426                                            throw new UnsupportedOperationException(
427    /**                                                          "Attribute 'value' missing for definition of <"
428     * Creates {@link RasterLegendData} from the {@link ColorMap} of a style.                                                                          + ELEM_NAME_RASTERLEGEND + ">");
429     * @param style     a raster style (must contain a  {@link RasterSymbolizer})                                  final double value = Double.valueOf(valueAttr);
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                                  // first and only item should be the label
432     *                  rounded to (null means no round; >= 0 means digits after comma;                                  final Element labelElement = childElement.getChild("label");
433     *                  < 0 means digits before comma)    */                                  // id label element is missing, the translation is searched
434    public static RasterLegendData generateRasterLegendData(Style style, boolean paintGaps, Integer digits) {                                  // directly
435      ColorMap colorMap = StylingUtil.getColorMapFromStyle(style);                                  // as childs of the rasterLegendItem element
436      if ( colorMap == null)                                  final Translation label = parseTranslation(labelElement != null ? labelElement
437        throw new IllegalArgumentException("Color map can not be determined from style!");                                                  : childElement);
438      return generateRasterLegendData(colorMap, paintGaps, digits);                                  rld.put(value, label);
439    }                          }
440                    }
441    /**  
442     * Saves a {@link RasterLegendData} to an URL.                  return rld;
443     * @param rld raster legend data          }
444     * @param documentUrl {@link URL} to store the XML  
445     */          /**
446    public static void saveRasterLegendData(final RasterLegendData rld, final URL documentUrl) throws Exception {           * Loads a {@link RasterLegendData} object from an URL.
447      // Create XML-Document           *
448      final FileWriter out = new FileWriter( new File(documentUrl.toURI()) );           * @param documentUrl
449      XML_OUTPUTTER.output(           *            {@link URL} to parse
450        createRasterLegendDataElement(rld),           * @see #parseAttributeMetaData(Element)
451        out           */
452      );          public static RasterLegendData loadRasterLegendData(final URL documentUrl)
453      out.flush();                          throws Exception {
454      out.close();                  final Document document = SAX_BUILDER.build(documentUrl);
455    }                  return parseRasterLegendData(document.getRootElement());
456            }
457    /**  
458     * Parses a {@link Translation} object from an JDOM-{@link Element}.          /**
459     * This method works like {@link AMLImport#parseTranslation(org.w3c.dom.Node},           * Creates an JDOM {@link Element} for the given {@link RasterLegendData}
460     * but for JDOM.           * map.
461     * @param element {@link Element} to parse           *
462     */           * @param rld
463    public final static Translation parseTranslation(final Element element) {           *            raster legend data
464      Translation trans = new Translation();           */
465            public static Element createRasterLegendDataElement(
466      if (element == null)                          final RasterLegendData rld) {
467       return trans;                  final Element element = new Element(ELEM_NAME_RLD, AMLURI);
468                    element.setAttribute("paintGaps", rld.isPaintGaps().toString());
469      for (final Element translationElement : (List<Element>)element.getChildren()) {                  for (final Double key : rld.getSortedKeys()) {
470        final String name = translationElement.getName();                          final Element item = new Element(ELEM_NAME_RASTERLEGEND, AMLURI);
471        if (name == null)                          item.setAttribute("value", key.toString());
472          continue;                          item.addContent(createTranslationElement("label", rld.get(key)));
473                            element.addContent(item);
474        // lang attribute                  }
475        String lang = translationElement.getAttributeValue("lang");                  return element;
476        // set the default, if no language code is set          }
477        if ( lang == null )  
478          lang = Translation.DEFAULT_KEY;          /**
479             * Creates {@link RasterLegendData} from a {@link ColorMap}.
480        final String translationText = translationElement.getValue();           *
481        if (translationText == null)           * @param colorMap
482          trans.put(lang, "");           *            a color map
483        else           * @param paintGaps
484          trans.put(lang, translationText);           *            indicated whether gaps are painted between the legend items
485      }           * @param digits
486             *            number of digits the grid value classes (and legend) are
487      // if no <translation> is given, the value of the node should           *            rounded to (null means no round; >= 0 means digits after
488      // be used as a default translation           *            comma; < 0 means digits before comma)
489      if (trans.size() == 0)           */
490        trans.put( Translation.DEFAULT_KEY, element.getValue() );          public static RasterLegendData generateRasterLegendData(
491      //     trans = new Translation( ((List<Element>)element.getChildren()).get(0).getValue() );                          final ColorMap colorMap, final boolean paintGaps,
492                            final Integer digits) {
493      return trans;                  final DecimalFormat decFormat = digits != null ? new DecimalFormat(
494    }                                  SwingUtil.getNumberFormatPattern(digits)) : null;
495                    final RasterLegendData rld = new RasterLegendData(paintGaps);
496    /**                  for (final ColorMapEntry cme : colorMap.getColorMapEntries()) {
497     * Creates an JDOM {@link Element} for the given {@link Translation}.                          final double value = StylingUtil.getQuantityFromColorMapEntry(cme);
498     * @param tagname Name of the Element                          String label = cme.getLabel();
499     * @param translation Translation to store in the Element                          // if no label is set (e.g. quantitative style),
500     */                          // use the value as label
501    public final static Element createTranslationElement(String tagname, Translation translation) {                          if (label == null || label.equals(""))
502      Element element = new Element(tagname, AMLURI);                                  if (digits == null)
503      if ( translation == null )                                          label = String.valueOf(value);
504        throw new UnsupportedOperationException("Translation element can not be created from null!");                                  else
505                                            label = decFormat.format(LangUtil.round(value, digits));
506      // If only a default translation is set, the <translation lang="..">..</tranlation>                          rld.put(value, new Translation("   " + label));
507      // part is not used                  }
508      if (translation.keySet().size() == 1 && translation.get(Translation.DEFAULT_KEY) != null) {                  return rld;
509        element.addContent( translation.get(Translation.DEFAULT_KEY) );          }
510        return element;  
511      }          /**
512             * Creates {@link RasterLegendData} from the {@link ColorMap} of a style.
513      // add a <translation lang="..">..</tranlation> part to the element for           *
514      // all languages           * @param style
515      for (String lang : translation.keySet()) {           *            a raster style (must contain a {@link RasterSymbolizer})
516        Element translationElement = new Element( ELEM_NAME_TRANSLATION , AMLURI);           * @param paintGaps
517        translationElement.setAttribute("lang", lang);           *            indicated whether gaps are painted between the legend items
518        String translationString = translation.get(lang);           * @param digits
519        if (translationString == null)           *            number of digits the grid value classes (and legend) are
520         translationString = "";           *            rounded to (null means no round; >= 0 means digits after
521        translationElement.addContent( translationString );           *            comma; < 0 means digits before comma)
522        element.addContent(translationElement);           */
523      }          public static RasterLegendData generateRasterLegendData(final Style style,
524                            final boolean paintGaps, final Integer digits) {
525      return element;                  final ColorMap colorMap = StylingUtil.getColorMapFromStyle(style);
526    }                  if (colorMap == null)
527                            throw new IllegalArgumentException(
528                                            "Color map can not be determined from style!");
529    /**                  return generateRasterLegendData(colorMap, paintGaps, digits);
530     * Sets a style to {@link StyledLayerInterface}.          }
531     * @param styledObject a styled object  
532     * @param style a Style          /**
533     */           * Saves a {@link RasterLegendData} to an URL.
534    public static void setStyledLayerStyle(StyledLayerInterface styledObject, StyledLayerStyle<?> style) {           *
535      // set SLD style           * @param rld
536      styledObject.setStyle( style.getGeoObjectStyle() );           *            raster legend data
537      // set meta data           * @param documentUrl
538      if ( styledObject        instanceof StyledGridCoverageInterface &&           *            {@link URL} to store the XML
539           (style.getMetaData() instanceof RasterLegendData || style.getMetaData() == null) ) {           */
540        RasterLegendData sourceRld = (RasterLegendData)style.getMetaData();          public static void saveRasterLegendData(final RasterLegendData rld,
541        RasterLegendData destRld = ((StyledGridCoverageInterface)styledObject).getLegendMetaData();                          final URL documentUrl) throws Exception {
542        if ( destRld != null && sourceRld != null ) {                  // Create XML-Document
543          destRld.setPaintGaps(sourceRld.isPaintGaps());                  final FileWriter out = new FileWriter(new File(documentUrl.toURI()));
544          destRld.clear();                  XML_OUTPUTTER.output(createRasterLegendDataElement(rld), out);
545          destRld.putAll( sourceRld );                  out.flush();
546        }                  out.close();
547        return;          }
548      }  
549      if ( styledObject        instanceof StyledFeatureCollectionInterface &&          /**
550           (style.getMetaData() instanceof Map || style.getMetaData() == null) ) {           * Parses a {@link Translation} object from an JDOM-{@link Element}. This
551        Map<Integer, AttributeMetaData> sourceAmd = (Map<Integer, AttributeMetaData>)style.getMetaData();           * method works like {@link AMLImport#parseTranslation(org.w3c.dom.Node},
552        Map<Integer, AttributeMetaData> destAmd   = ((StyledFeatureCollectionInterface)styledObject).getAttributeMetaDataMap();           * but for JDOM.
553        if ( destAmd != null && sourceAmd != null ) {           *
554          destAmd.clear();           * @param element
555          destAmd.putAll( sourceAmd );           *            {@link Element} to parse
556        }           */
557        return;          public final static Translation parseTranslation(final Element element) {
558      }                  final Translation trans = new Translation();
559    
560      throw new UnsupportedOperationException("Style is not compatible to object: " +                  if (element == null)
561                                              (style.getMetaData() == null ? null : style.getMetaData().getClass().getSimpleName()) +                          return trans;
562                                              " <-> " +  
563                                              (styledObject == null ? null : styledObject.getClass().getSimpleName()));                  for (final Element translationElement : (List<Element>) element
564    }                                  .getChildren()) {
565                            final String name = translationElement.getName();
566    /**                          if (name == null)
567     * Returns the style a {@link StyledLayerInterface} as a {@link StyledLayerStyle}.                                  continue;
568     * @param styledObject a styled object  
569     * @return {@code StyledLayerStyle<RasterLegendData>} for {@link StyledGridCoverageInterface}                          // lang attribute
570     *         or {@code StyledLayerStyle<Map<Integer,AttributeMetaData>>} for                          String lang = translationElement.getAttributeValue("lang");
571     *         {@link StyledFeatureCollectionInterface}                          // set the default, if no language code is set
572     */                          if (lang == null)
573    public static StyledLayerStyle<?> getStyledLayerStyle(StyledLayerInterface styledObject) {                                  lang = Translation.DEFAULT_KEY;
574      if ( styledObject instanceof StyledGridCoverageInterface )  
575        return getStyledLayerStyle( (StyledGridCoverageInterface)styledObject );                          final String translationText = translationElement.getValue();
576      if ( styledObject instanceof StyledFeatureCollectionInterface )                          if (translationText == null)
577        return getStyledLayerStyle( (StyledFeatureCollectionInterface)styledObject );                                  trans.put(lang, "");
578      throw new UnsupportedOperationException("Unknown type of StyledLayerInterface: "+(styledObject == null ? null : styledObject.getClass().getSimpleName()));                          else
579    }                                  trans.put(lang, translationText);
580                    }
581    /**  
582     * Returns the style and raster meta data of a {@link StyledGridCoverageInterface}                  // if no <translation> is given, the value of the node should
583     * as a {@link StyledLayerStyle}.                  // be used as a default translation
584     * @param styledGC a styled grid coverage                  if (trans.size() == 0)
585     */                          trans.put(Translation.DEFAULT_KEY, element.getValue());
586    public static StyledLayerStyle<RasterLegendData> getStyledLayerStyle(StyledGridCoverageInterface styledGC) {                  // trans = new Translation(
587      return new StyledLayerStyle<RasterLegendData>(                  // ((List<Element>)element.getChildren()).get(0).getValue() );
588        styledGC.getStyle(),  
589        styledGC.getLegendMetaData()                  return trans;
590      );          }
591    }  
592            /**
593    /**           * Creates an JDOM {@link Element} for the given {@link Translation}.
594     * Returns the style and attribute meta data of a {@link StyledFeatureCollectionInterface}           *
595     * as a {@link StyledLayerStyle}.           * @param tagname
596     * @param styledFC a styled feature collection           *            Name of the Element
597     */           * @param translation
598    public static StyledLayerStyle<Map<Integer,AttributeMetaData>> getStyledLayerStyle(StyledFeatureCollectionInterface styledFC) {           *            Translation to store in the Element
599      return new StyledLayerStyle<Map<Integer,AttributeMetaData>>(           */
600        styledFC.getStyle(),          public final static Element createTranslationElement(final String tagname,
601        styledFC.getAttributeMetaDataMap()                          final Translation translation) {
602      );                  final Element element = new Element(tagname, AMLURI);
603    }                  if (translation == null)
604                            throw new UnsupportedOperationException(
605    /**                                          "Translation element can not be created from null!");
606     * Loads a {@linkplain Style SLD-Style} and {@linkplain RasterLegendData Raster-LegendData}  
607     * for a given geo-object (raster) source. The SLD file must be present. A missing                  // If only a default translation is set, the <translation
608     * raster legend-data file is tolerated.                  // lang="..">..</tranlation>
609     * @param geoObjectURL URL of the (already read) raster object                  // part is not used
610     * @param sldExt file extention for the SLD file                  if (translation.keySet().size() == 1
611     * @param rldExt file extention for the raster legend-data file                                  && translation.get(Translation.DEFAULT_KEY) != null) {
612     * @return {@code null} in case of any error                          element.addContent(translation.get(Translation.DEFAULT_KEY));
613     */                          return element;
614    public static StyledLayerStyle<RasterLegendData> loadStyledRasterStyle(URL geoObjectURL, String sldExt, String rldExt) {                  }
615      RasterLegendData metaData = null;  
616      Style sldStyle = null;                  // add a <translation lang="..">..</tranlation> part to the element for
617      try {                  // all languages
618        Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(geoObjectURL, sldExt));                  for (final String lang : translation.keySet()) {
619        // SLD must be present                          final Element translationElement = new Element(
620        if ( styles == null || styles.length == 0 )                                          ELEM_NAME_TRANSLATION, AMLURI);
621          return null;                          translationElement.setAttribute("lang", lang);
622        sldStyle = styles[0];                          String translationString = translation.get(lang);
623      }                          if (translationString == null)
624      catch (Exception err) {                                  translationString = "";
625        // SLD must be present                          translationElement.addContent(translationString);
626        LangUtil.logDebugError(LOGGER,err);                          element.addContent(translationElement);
627        return null;                  }
628      }  
629                    return element;
630      try {          }
631        metaData = StyledLayerUtil.loadRasterLegendData( IOUtil.changeUrlExt(geoObjectURL,rldExt) );  
632      } catch (FileNotFoundException err) {          /**
633        // ignore missing raster legend data           * Sets a style to {@link StyledLayerInterface}.
634      } catch (Exception err) {           *
635        // any other error during legend data creation leads to error           * @param styledObject
636        LangUtil.logDebugError(LOGGER,err);           *            a styled object
637        return null;           * @param style
638      }           *            a Style
639      return new StyledLayerStyle<RasterLegendData>(sldStyle, metaData);           */
640    }          public static void setStyledLayerStyle(
641                            final StyledLayerInterface styledObject,
642    /**                          final StyledLayerStyle<?> style) {
643     * Loads a {@linkplain Style SLD-Style} from a {@code .sld} file and                  // set SLD style
644     * {@linkplain RasterLegendData Raster-LegendData} from a {@code .rld} file                  styledObject.setStyle(style.getGeoObjectStyle());
645     * for a given geo-object (raster) source. The SLD file must be present. A missing                  // set meta data
646     * raster legend-data file is tolerated.                  if (styledObject instanceof StyledGridCoverageInterface
647     * @param geoObjectURL URL of the (already read) raster object                                  && (style.getMetaData() instanceof RasterLegendData || style
648     * @param sldExt file extention for the SLD file                                                  .getMetaData() == null)) {
649     * @param rldExt file extention for the raster legend-data file                          final RasterLegendData sourceRld = (RasterLegendData) style
650     * @return {@code null} in case of any error                                          .getMetaData();
651     */                          final RasterLegendData destRld = ((StyledGridCoverageInterface) styledObject)
652    public static StyledLayerStyle<RasterLegendData> loadStyledRasterStyle(URL geoObjectURL) {                                          .getLegendMetaData();
653      return loadStyledRasterStyle(geoObjectURL, "sld", "rld");                          if (destRld != null && sourceRld != null) {
654    }                                  destRld.setPaintGaps(sourceRld.isPaintGaps());
655                                    destRld.clear();
656    /**                                  destRld.putAll(sourceRld);
657     * Loads a {@linkplain Style SLD-Style} and a {@linkplain AttributeMetaData AttributeMetaData-Map}                          }
658     * for a given geo-object (feature) source. The SLD file must be present. A missing                          return;
659     * attribute meta-data file is tolerated.                  }
660     * @param geoObjectURL URL of the (already read) feature object                  if (styledObject instanceof StyledFeatureCollectionInterface
661     * @param sldExt file extention for the SLD file                                  && (style.getMetaData() instanceof Map || style.getMetaData() == null)) {
662     * @param rldExt file extention for the raster legend-data file                          final AttributeMetadataMap sourceAmd = (AttributeMetadataMap) style
663     * @return {@code null} in case of any error                                          .getMetaData();
664     */                          final AttributeMetadataMap destAmd = ((StyledFeatureCollectionInterface) styledObject)
665    public static StyledLayerStyle<Map<Integer,AttributeMetaData>> loadStyledFeatureStyle(URL geoObjectURL, String sldExt, String rldExt) {                                          .getAttributeMetaDataMap();
666      Map<Integer,AttributeMetaData> metaData = null;                          if (destAmd != null && sourceAmd != null) {
667      Style                          sldStyle = null;                                  destAmd.clear();
668      try {                                  destAmd.putAll(sourceAmd);
669        Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(geoObjectURL, sldExt));                          }
670        // SLD must be present                          return;
671        if ( styles == null || styles.length == 0 )                  }
672          return null;  
673        sldStyle = styles[0];                  throw new UnsupportedOperationException(
674      } catch (Exception err) {                                  "Style is not compatible to object: "
675        // SLD must be present                                                  + (style.getMetaData() == null ? null : style
676        LangUtil.logDebugError(LOGGER,err);                                                                  .getMetaData().getClass().getSimpleName())
677        return null;                                                  + " <-> "
678      }                                                  + (styledObject == null ? null : styledObject
679                                                                    .getClass().getSimpleName()));
680      try {          }
681        metaData = StyledLayerUtil.loadAttributeMetaDataMap( IOUtil.changeUrlExt(geoObjectURL,rldExt) );  
682      } catch (FileNotFoundException err) {          /**
683        // ignore missing attribute meta data           * Returns the style a {@link StyledLayerInterface} as a
684      } catch (Exception err) {           * {@link StyledLayerStyle}.
685        // any other error during meta data creation leads to error           *
686        LangUtil.logDebugError(LOGGER,err);           * @param styledObject
687        return null;           *            a styled object
688      }           * @return {@code StyledLayerStyle<RasterLegendData>} for
689             *         {@link StyledGridCoverageInterface} or {@code
690      return new StyledLayerStyle<Map<Integer,AttributeMetaData>>(sldStyle, metaData);           *         StyledLayerStyle<Map<Integer,AttributeMetaData>>} for
691    }           *         {@link StyledFeatureCollectionInterface}
692             */
693    /**          public static StyledLayerStyle<?> getStyledLayerStyle(
694     * Loads a {@linkplain Style SLD-Style} from a {@code .sld} file and                          final StyledLayerInterface styledObject) {
695     * {@linkplain AttributeMetaData AttributeMetaData-Map} from a {@code .amd} file                  if (styledObject instanceof StyledGridCoverageInterface)
696     * for a given geo-object (feature) source. The SLD file must be present. A missing                          return getStyledLayerStyle((StyledGridCoverageInterface) styledObject);
697     * attribute meta-data file is tolerated.                  if (styledObject instanceof StyledFeatureCollectionInterface)
698     * @param geoObjectURL URL of the (already read) feature object                          return getStyledLayerStyle((StyledFeatureCollectionInterface) styledObject);
699     * @param sldExt file extention for the SLD file                  throw new UnsupportedOperationException(
700     * @param rldExt file extention for the raster legend-data file                                  "Unknown type of StyledLayerInterface: "
701     * @return {@code null} in case of any error                                                  + (styledObject == null ? null : styledObject
702     */                                                                  .getClass().getSimpleName()));
703    public static StyledLayerStyle<Map<Integer,AttributeMetaData>> loadStyledFeatureStyle(URL geoObjectURL) {          }
704      return loadStyledFeatureStyle(geoObjectURL, "sld", "amd");  
705    }          /**
706             * Returns the style and raster meta data of a
707    /**           * {@link StyledGridCoverageInterface} as a {@link StyledLayerStyle}.
708     * Stores a {@linkplain Style SLD-Style} and {@linkplain RasterLegendData Raster-LegendData}           *
709     * for a given geo-object (raster) source.           * @param styledGC
710     * @param style  style to save           *            a styled grid coverage
711     * @param geoObjectURL URL of the raster object           */
712     * @param sldExt file extention for the SLD file          public static StyledLayerStyle<RasterLegendData> getStyledLayerStyle(
713     * @param mdExt file extention for the meta-data file                          final StyledGridCoverageInterface styledGC) {
714     */                  return new StyledLayerStyle<RasterLegendData>(styledGC.getStyle(),
715    public static <T> void saveStyledLayerStyle(StyledLayerStyle<T> style, URL geoObjectURL, String sldExt, String mdExt) throws Exception {                                  styledGC.getLegendMetaData());
716      // Store the SLD          }
717      Style sldStyle = style.getGeoObjectStyle();  
718      if ( sldStyle != null ) {          /**
719        StylingUtil.saveStyleToSLD(           * Returns the style and attribute meta data of a
720           sldStyle,           * {@link StyledFeatureCollectionInterface} as a {@link StyledLayerStyle}.
721           IOUtil.changeFileExt(           *
722                new File(geoObjectURL.toURI()),           * @param styledFC
723                sldExt           *            a styled feature collection
724           )           */
725        );          public static StyledLayerStyle<AttributeMetadataMap> getStyledLayerStyle(
726      }                          final StyledFeatureCollectionInterface styledFC) {
727                    return new StyledLayerStyle<AttributeMetadataMap>(styledFC.getStyle(),
728      // Store the meta data                                  styledFC.getAttributeMetaDataMap());
729      T metaData = style.getMetaData();          }
730      if ( metaData != null ) {  
731        if ( metaData instanceof RasterLegendData ) {          /**
732          saveRasterLegendData(           * Loads a {@linkplain Style SLD-Style} and {@linkplain RasterLegendData
733              (RasterLegendData)metaData,           * Raster-LegendData} for a given geo-object (raster) source. The SLD file
734              IOUtil.changeUrlExt(geoObjectURL,mdExt)           * must be present. A missing raster legend-data file is tolerated.
735          );           *
736  //      } else if ( metaData instanceof Map<Integer,AttributeMetaData> ) { // LEIDER NICHT KOMPILIERBAR!!           * @param geoObjectURL
737        } else if ( metaData instanceof Map ) {           *            URL of the (already read) raster object
738          saveAttributeMetaDataMap(           * @param sldExt
739              (Map<Integer,AttributeMetaData>)metaData,           *            file extention for the SLD file
740              IOUtil.changeUrlExt(geoObjectURL,mdExt)           * @param rldExt
741          );           *            file extention for the raster legend-data file
742        } else           * @return {@code null} in case of any error
743          throw new UnsupportedOperationException("Export for meta data not yet supported: "+metaData.getClass().getSimpleName());           */
744      }          public static StyledLayerStyle<RasterLegendData> loadStyledRasterStyle(
745    }                          final URL geoObjectURL, final String sldExt, final String rldExt) {
746                    RasterLegendData metaData = null;
747    /**                  Style sldStyle = null;
748     * Stores the {@linkplain Style SLD-Style} to a {@code .sld} file and                  try {
749     * the meta data ({@link RasterLegendData} or {@link AttributeMetaData})                          final Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(
750     * to a {@code .rld} or {@code .amd} file.                                          geoObjectURL, sldExt));
751     * for a given geo-object source.                          // SLD must be present
752     * @param style  style to save                          if (styles == null || styles.length == 0)
753     * @param geoObjectURL URL of the (already read) raster object                                  return null;
754     */                          sldStyle = styles[0];
755    public static void saveStyledLayerStyle(StyledLayerStyle<?> style, URL geoObjectURL) throws Exception {                  } catch (final Exception err) {
756      if ( style.getMetaData() instanceof RasterLegendData )                          // SLD must be present
757        saveStyledLayerStyle(style,geoObjectURL, "sld", "rld");                          LangUtil.logDebugError(LOGGER, err);
758      else                          return null;
759        saveStyledLayerStyle(style,geoObjectURL, "sld", "amd");                  }
760    }  
761                      try {
762                              metaData = StyledLayerUtil.loadRasterLegendData(IOUtil
763                                            .changeUrlExt(geoObjectURL, rldExt));
764                    } catch (final FileNotFoundException err) {
765                            // ignore missing raster legend data
766                    } catch (final Exception err) {
767                            // any other error during legend data creation leads to error
768                            LangUtil.logDebugError(LOGGER, err);
769                            return null;
770                    }
771                    return new StyledLayerStyle<RasterLegendData>(sldStyle, metaData);
772            }
773    
774          /**          /**
775           * Creates a {@link Box} that shows a legend for a list of           * Loads a {@linkplain Style SLD-Style} from a {@code .sld} file and
776             * {@linkplain RasterLegendData Raster-LegendData} from a {@code .rld} file
777             * for a given geo-object (raster) source. The SLD file must be present. A
778             * missing raster legend-data file is tolerated.
779             *
780             * @param geoObjectURL
781             *            URL of the (already read) raster object
782             * @param sldExt
783             *            file extention for the SLD file
784             * @param rldExt
785             *            file extention for the raster legend-data file
786             * @return {@code null} in case of any error
787             */
788            public static StyledLayerStyle<RasterLegendData> loadStyledRasterStyle(
789                            final URL geoObjectURL) {
790                    return loadStyledRasterStyle(geoObjectURL, "sld", "rld");
791            }
792    
793            /**
794             * Loads a {@linkplain Style SLD-Style} and a {@linkplain AttributeMetadata
795             * AttributeMetaData-Map} for a given geo-object (feature) source. The SLD
796             * file must be present. A missing attribute meta-data file is tolerated.
797             *
798             * @param geoObjectURL
799             *            URL of the (already read) feature object
800             * @param sldExt
801             *            file extention for the SLD file
802             * @param rldExt
803             *            file extention for the raster legend-data file
804             * @return {@code null} in case of any error
805             */
806            public static StyledLayerStyle<AttributeMetadataMap> loadStyledFeatureStyle(
807                            final URL geoObjectURL, final String sldExt, final String rldExt) {
808                    AttributeMetadataMap metaData = null;
809                    Style sldStyle = null;
810                    try {
811                            final Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(
812                                            geoObjectURL, sldExt));
813                            // SLD must be present
814                            if (styles == null || styles.length == 0)
815                                    return null;
816                            sldStyle = styles[0];
817                    } catch (final Exception err) {
818                            // SLD must be present
819                            LangUtil.logDebugError(LOGGER, err);
820                            return null;
821                    }
822    
823                    try {
824                            metaData = StyledLayerUtil.loadAttributeMetaDataMap(IOUtil
825                                            .changeUrlExt(geoObjectURL, rldExt));
826                    } catch (final FileNotFoundException err) {
827                            // ignore missing attribute meta data
828                    } catch (final Exception err) {
829                            // any other error during meta data creation leads to error
830                            LangUtil.logDebugError(LOGGER, err);
831                            return null;
832                    }
833    
834                    return new StyledLayerStyle<AttributeMetadataMap>(sldStyle, metaData);
835            }
836    
837            /**
838             * Loads a {@linkplain Style SLD-Style} from a {@code .sld} file and
839             * {@linkplain AttributeMetadata AttributeMetaData-Map} from a {@code .amd}
840             * file for a given geo-object (feature) source. The SLD file must be
841             * present. A missing attribute meta-data file is tolerated.
842             *
843             * @param geoObjectURL
844             *            URL of the (already read) feature object
845             * @param sldExt
846             *            file extention for the SLD file
847             * @param rldExt
848             *            file extention for the raster legend-data file
849             * @return {@code null} in case of any error
850             */
851            public static StyledLayerStyle<AttributeMetadataMap> loadStyledFeatureStyle(
852                            final URL geoObjectURL) {
853                    return loadStyledFeatureStyle(geoObjectURL, "sld", "amd");
854            }
855    
856            /**
857             * Stores a {@linkplain Style SLD-Style} and {@linkplain RasterLegendData
858             * Raster-LegendData} for a given geo-object (raster) source.
859             *
860             * @param style
861             *            style to save
862             * @param geoObjectURL
863             *            URL of the raster object
864             * @param sldExt
865             *            file extention for the SLD file
866             * @param mdExt
867             *            file extention for the meta-data file
868             */
869            public static <T> void saveStyledLayerStyle(
870                            final StyledLayerStyle<T> style, final URL geoObjectURL,
871                            final String sldExt, final String mdExt) throws Exception {
872                    // Store the SLD
873                    final Style sldStyle = style.getGeoObjectStyle();
874                    if (sldStyle != null) {
875                            StylingUtil.saveStyleToSLD(sldStyle, IOUtil.changeFileExt(new File(
876                                            geoObjectURL.toURI()), sldExt));
877                    }
878    
879                    // Store the meta data
880                    final T metaData = style.getMetaData();
881                    if (metaData != null) {
882                            if (metaData instanceof RasterLegendData) {
883                                    saveRasterLegendData((RasterLegendData) metaData, IOUtil
884                                                    .changeUrlExt(geoObjectURL, mdExt));
885                                    // } else if ( metaData instanceof
886                                    // Map<Integer,AttributeMetaData> ) { // LEIDER NICHT
887                                    // KOMPILIERBAR!!
888                            } else if (metaData instanceof Map) {
889                                    saveAttributeMetaDataMap((AttributeMetadataMap) metaData,
890                                                    IOUtil.changeUrlExt(geoObjectURL, mdExt));
891                            } else
892                                    throw new UnsupportedOperationException(
893                                                    "Export for meta data not yet supported: "
894                                                                    + metaData.getClass().getSimpleName());
895                    }
896            }
897    
898            /**
899             * Stores the {@linkplain Style SLD-Style} to a {@code .sld} file and the
900             * meta data ({@link RasterLegendData} or {@link AttributeMetadata}) to a
901             * {@code .rld} or {@code .amd} file. for a given geo-object source.
902             *
903             * @param style
904             *            style to save
905             * @param geoObjectURL
906             *            URL of the (already read) raster object
907             */
908            public static void saveStyledLayerStyle(final StyledLayerStyle<?> style,
909                            final URL geoObjectURL) throws Exception {
910                    if (style.getMetaData() instanceof RasterLegendData)
911                            saveStyledLayerStyle(style, geoObjectURL, "sld", "rld");
912                    else
913                            saveStyledLayerStyle(style, geoObjectURL, "sld", "amd");
914            }
915    
916            /**
917             * Creates a {@link JPanel} that shows a legend for a list of
918           * {@link FeatureTypeStyle}s and a targeted featureType           * {@link FeatureTypeStyle}s and a targeted featureType
919           *           *
920           * @param featureType           * @param featureType
# Line 751  public class StyledLayerUtil { Line 925  public class StyledLayerUtil {
925           * @author <a href="mailto:[email protected]">Stefan Alfons           * @author <a href="mailto:[email protected]">Stefan Alfons
926           *         Kr&uuml;ger</a>           *         Kr&uuml;ger</a>
927           */           */
928          public static Box createLegendPanel(List<FeatureTypeStyle> list,          public static JPanel createLegendPanel(Style style,
929                          SimpleFeatureType featureType, int iconWidth, int iconHeight) {                          final SimpleFeatureType featureType, final int iconWidth,
930                            final int iconHeight) {
931    
932                  Box box = new Box(BoxLayout.Y_AXIS) {                  final List<FeatureTypeStyle> list = style.featureTypeStyles();
933    
934                          /**                  final JPanel panel = new JPanel(new MigLayout("wrap 2", "[]:3:[]"));
                          * Nuetzlich wenn die Componente gedruckt (z.B. wenn ein Screenshot  
                          * gemacht wird) wird. Dann werden wird der Hintergrund auf WEISS  
                          * gesetzt.  
                          *  
                          * @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);  
                                 }  
                         }  
                 };  
935    
936                  for (FeatureTypeStyle ftStyle : list) {                  if (style == null) {
937                            // No Style => no legend
938                            return panel;
939                    }
940    
941                    for (final FeatureTypeStyle ftStyle : list) {
942    
943                          // One child-node for every rule                          // One child-node for every rule
944                          List<Rule> rules = ftStyle.rules();                          final List<Rule> rules = ftStyle.rules();
945                          for (Rule rule : rules) {                          for (final Rule rule : rules) {
946    
947                                  /**                                  /**
948                                   * 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 952  public class StyledLayerUtil {
952                                                  .size() == rule.getSymbolizers().length)                                                  .size() == rule.getSymbolizers().length)
953                                          continue;                                          continue;
954    
955                                  Box hbox = new Box(BoxLayout.X_AXIS) {                                  final BufferedImage imageForRule = LegendIconFeatureRenderer
956                                                    .getInstance().createImageForRule(rule, featureType,
957                                                                    new Dimension(iconWidth, iconHeight));
958    
959                                    final ImageIcon legendIcon = new ImageIcon(imageForRule);
960    
961                                    final JLabel iconLabel = new JLabel(legendIcon);
962                                    panel.add(iconLabel, "sgx1");
963                                    // hbox.setAlignmentX(0f);
964                                    // hbox.add(iconLabel);
965                                    // hbox.add(Box.createHorizontalStrut(3));
966    
967                                          /**                                  final Translation labelT = new Translation();
968                                           * Nuetzlich wenn die Componente gedruckt (z.B. wenn ein                                  labelT.fromOneLine(rule.getDescription().getTitle());
969                                           * Screenshot gemacht wird) wird. Dann werden wird der                                  final JLabel classTitleLabel = new JLabel(labelT.toString());
970                                           * Hintergrund auf WEISS gesetzt.  
971                                           *                                  panel.add(classTitleLabel, "sgx2");
972                                           * @author <a href="mailto:[email protected]">Stefan                                  classTitleLabel.setLabelFor(iconLabel);
973                                           *         Alfons Kr&uuml;ger</a>                          }
974                                           */                  }
975                                          @Override  
976                                          public void print(Graphics g) {                  return panel;
977                                                  final Color orig = getBackground();          }
978                                                  setBackground(Color.WHITE);  
979                                                  // wrap in try/finally so that we always restore the          /**
980                                                  // state           * Creates a {@link JComponent} that contains a legend for a given
981                                                  try {           * rasterLayer and a given {@link Style}.
982                                                          super.print(g);           *
983                                                  } finally {           * @param style
984                                                          setBackground(orig);           *            if <code>null</code>, the default {@link Style} is extracetd
985                                                  }           *            from the {@link StyledRasterInterface}
986             */
987            public static JPanel createLegendPanel(
988                            final StyledRasterInterface<?> styledRaster, Style style,
989                            final int iconWidth, final int iconHeight) {
990    
991                    // If no style is given, we use the default style for this layer
992                    if (style == null)
993                            style = styledRaster.getStyle();
994    
995                    /**
996                     * Determine whether a Style is responsible for the coloring
997                     */
998                    ColorModel colorModel = null;
999                    if (!isStyleable(styledRaster)
1000                                    || (isStyleable(styledRaster) && style == null)) {
1001                            colorModel = getColorModel(styledRaster);
1002                    }
1003    
1004                    final RasterLegendData rasterLegendData = styledRaster
1005                                    .getLegendMetaData();
1006                    final List<Double> legendRasterValues = rasterLegendData
1007                                    .getSortedKeys();
1008                    final Map<Double, GridCoverage2D> sampleRasters = rasterLegendData
1009                                    .createSampleRasters();
1010    
1011                    final JPanel panel = new JPanel(new MigLayout("wrap 2, gapy 0"));
1012    
1013                    for (final Double rValue : legendRasterValues) {
1014    
1015                            // final Dimension ICON_SIZE = new Dimension(iconWidth,
1016                            // new JLabel().getFontMetrics(new JLabel().getFont())
1017                            // .getHeight() > 5 ? new JLabel().getFontMetrics(
1018                            // new JLabel().getFont()).getHeight() : iconHeight);
1019    
1020                            // ****************************************************************************
1021                            // Create the actual icon
1022                            // ****************************************************************************
1023                            final BufferedImage buffImage = new BufferedImage(iconWidth,
1024                                            iconHeight, BufferedImage.TYPE_INT_ARGB);
1025    
1026                            final Graphics2D graphics = buffImage.createGraphics();
1027    
1028                            if (colorModel != null) {
1029                                    // The colors come from the ColorModel!
1030    
1031                                    try {
1032                                            Object inData = null;
1033                                            switch (colorModel.getTransferType()) {
1034                                            case DataBuffer.TYPE_BYTE:
1035                                                    inData = new byte[] { rValue.byteValue() };
1036                                                    break;
1037                                            case DataBuffer.TYPE_USHORT:
1038                                                    inData = new short[] { rValue.shortValue() };
1039                                                    break;
1040                                            case DataBuffer.TYPE_INT:
1041                                                    inData = new int[] { rValue.intValue() };
1042                                                    break;
1043                                            case DataBuffer.TYPE_SHORT:
1044                                                    inData = new short[] { rValue.shortValue() };
1045                                                    break;
1046                                            case DataBuffer.TYPE_FLOAT:
1047                                                    inData = new float[] { rValue.floatValue() };
1048                                                    break;
1049                                            case DataBuffer.TYPE_DOUBLE:
1050                                                    inData = new double[] { rValue.doubleValue() };
1051                                                    break;
1052                                            default:
1053                                                    inData = rValue.intValue();
1054                                          }                                          }
1055                                  };                                          final Color color = new Color(colorModel.getRGB(inData));
1056                                            graphics.setBackground(color);
1057                                            graphics.setColor(color);
1058                                            graphics.fillRect(0, 0, iconWidth, iconHeight);
1059                                    } catch (final Exception e) {
1060                                            LOGGER.info(
1061                                                            "Dann nehmen wir halt den GridCoverageRenderer", e);
1062                                            colorModel = null;
1063                                    }
1064                            } else {
1065                                    // The colors come from the Style
1066    
1067                                  /**                                  /**
1068                                   * The size of the legend Symbol is dependent on the size of the                                   * The coverage contains only one value of value rValue
                                  * font.  
1069                                   */                                   */
1070                                  final int fontHeight = new JLabel().getFontMetrics(                                  final GridCoverage2D sampleCov = sampleRasters.get(rValue);
1071                                                  new JLabel().getFont()).getHeight();                                  GridCoverageRenderer renderer;
1072                                                                    try {
1073                                  final Dimension ICON_SIZE = new Dimension(iconWidth,                                          renderer = new GridCoverageRenderer(sampleCov
1074                                                  fontHeight > 5 ? fontHeight : iconHeight);                                                          .getCoordinateReferenceSystem(), JTSUtil
1075                                                            .createEnvelope(sampleCov.getEnvelope()),
1076                                  // ****************************************************************************                                                          new Rectangle(iconWidth, iconHeight),
1077                                  // Create the actual icon                                                          (AffineTransform) null);
1078                                  // ****************************************************************************                                  } catch (final Exception e1) {
1079                                  final BufferedImage imageForRule = LegendIconFeatureRenderer                                          throw new RuntimeException(
1080                                                  .getInstance().createImageForRule(rule, featureType,                                                          "Creating a GridCoverageRenderer failed:", e1);
1081                                                                  ICON_SIZE);                                  }
1082    
1083                                  // LOGGER.debug("Creating a new Legend Image for RUle name =                                  /**
1084                                  // "+rule.getName());                                   * Iterate over all FeatureTypeStyles.
1085                                     */
1086                                    final List<RasterSymbolizer> rSymbols = StylingUtil
1087                                                    .getRasterSymbolizers(style);
1088    
1089                                  ImageIcon legendIcon = new ImageIcon(imageForRule);                                  for (final RasterSymbolizer symbolizer : rSymbols) {
1090                                            try {
1091                                                    renderer.paint(graphics, sampleCov, symbolizer);
1092                                            } catch (final Exception ee) {
1093                                                    LOGGER.error("Unable to paint " + symbolizer
1094                                                                    + " into the legend image", ee);
1095                                            }
1096                                    }
1097                            }
1098    
1099                                  final JLabel iconLabel = new JLabel(legendIcon);                          final JLabel iconLabel = new JLabel(new ImageIcon(buffImage));
1100                                  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();  
1101    
1102                                  Translation labelT = new Translation();                          final Translation labelT = rasterLegendData.get(rValue);
1103                                  labelT.fromOneLine(rawText);                          final JLabel classTitleLabel = new JLabel(labelT.toString());
1104                            panel.add(classTitleLabel, "sgx2"
1105                                            + (rasterLegendData.isPaintGaps() ? ", gapy 0:0:0 5:5:5"
1106                                                            : ""));
1107                            classTitleLabel.setLabelFor(iconLabel);
1108    
1109                            if (rasterLegendData.isPaintGaps()) {
1110                                    iconLabel
1111                                                    .setBorder(BorderFactory.createLineBorder(Color.black));
1112                            }
1113    
1114                                  final JLabel classTitleLabel = new JLabel(labelT.toString());                  }
                                 hbox.add(classTitleLabel);  
                                 classTitleLabel.setLabelFor(iconLabel);  
1115    
1116                                  box.add(hbox);                  return panel;
1117            }
1118    
1119            /**
1120             * Extracts the {@link ColorModel} of any {@link StyledRasterInterface}. May
1121             * return <code>null</code> if the geoobject can not be accessed.
1122             */
1123            @SuppressWarnings("unchecked")
1124            public static ColorModel getColorModel(
1125                            final StyledRasterInterface<?> styledGrid) {
1126                    ColorModel colorModel = null;
1127                    try {
1128                            final Object geoObject = styledGrid.getGeoObject();
1129                            if (geoObject instanceof GridCoverage2D) {
1130                                    final GridCoverage2D cov = (GridCoverage2D) geoObject;
1131                                    colorModel = cov.getRenderedImage().getColorModel();
1132                            } else if (styledGrid instanceof StyledRasterPyramidInterface) {
1133    
1134                                    final Parameter readGG = new Parameter(
1135                                                    AbstractGridFormat.READ_GRIDGEOMETRY2D);
1136    
1137                                    final ReferencedEnvelope mapExtend = new org.geotools.geometry.jts.ReferencedEnvelope(
1138                                                    styledGrid.getEnvelope(), styledGrid.getCrs());
1139    
1140                                    readGG.setValue(new GridGeometry2D(new GeneralGridEnvelope(
1141                                                    new Rectangle(0, 0, 1, 1)), mapExtend));
1142    
1143                                    final FeatureCollection<SimpleFeatureType, SimpleFeature> rFc = (FeatureCollection<SimpleFeatureType, SimpleFeature>) geoObject;
1144    
1145                                    final AbstractGridCoverage2DReader aReader = (AbstractGridCoverage2DReader) FeatureUtil
1146                                                    .getWrappedGeoObject(rFc);
1147                                    final GridCoverage2D cov = (GridCoverage2D) aReader
1148                                                    .read(new GeneralParameterValue[] { readGG });
1149                                    colorModel = cov.getRenderedImage().getColorModel();
1150                          }                          }
1151                    } catch (final Exception e) {
1152                            LOGGER.error("Error reading the colormodel from " + styledGrid, e);
1153                            return null;
1154                  }                  }
1155                    return colorModel;
1156            }
1157    
1158                  return box;          /**
1159             * @return <code>true</code> if a {@link RasterSymbolizer} can be applied
1160             *         and will have an effect. Some rasters (e.g. GeoTIFF) can come
1161             *         with their own {@link ColorModel} and will ignore any
1162             *         {@link RasterSymbolizer} = SLD.
1163             */
1164            public static boolean isStyleable(
1165                            final StyledRasterInterface<?> styledRaster) {
1166                    final ColorModel colorModel = getColorModel(styledRaster);
1167    
1168                    // LOGGER.info("The colormodel of " + styledRaster.getTitle() + " is "
1169                    // + colorModel != null ? colorModel.getClass().getSimpleName() :
1170                    // "NULL");
1171    
1172                    if (colorModel == null)
1173                            return true;
1174                    if (colorModel instanceof ComponentColorModel)
1175                            return true;
1176                    return false;
1177          }          }
1178    
1179            /**
1180             * Set the given Style as the Style of the {@link MapLayer}, unless the
1181             * styles are the same (not comparing selection stuff). If the
1182             * {@link MapLayer}s {@link Style} is changed, the selection FTS is kept.<br/>
1183             * Remember {@link MapLayer#setStyle(Style)} triggers an event leading to a
1184             * repaint, so only use it when needed.
1185             *
1186             * @return <code>true</code> if the {@link MapLayer}'s {@link Style} has
1187             *         been changed.
1188             */
1189            public static boolean updateMapLayerStyleIfChangedAndKeepSelection(
1190                            MapLayer mapLayer, Style style2) {
1191    
1192                    Style mapLayerStyleCleaned = StylingUtil
1193                                    .removeSelectionFeatureTypeStyle(mapLayer.getStyle());
1194    
1195                    Style newStyleCleaned = StylingUtil
1196                                    .removeSelectionFeatureTypeStyle(style2);
1197    
1198                    if (StylingUtil.isStyleDifferent(mapLayerStyleCleaned, newStyleCleaned)) {
1199    
1200                            // They are different when compared without SELECTION FTS!
1201    
1202                            // Now let's copy any SELECTION FTS to the now style
1203                            FeatureTypeStyle selectionFeatureTypeStyle = StylingUtil
1204                                            .getSelectionFeatureTypeStyle(mapLayer.getStyle());
1205                            if (selectionFeatureTypeStyle != null) {
1206                                    newStyleCleaned.featureTypeStyles().add(
1207                                                    selectionFeatureTypeStyle);
1208                                    // newStyleCleaned is not so clean anymore... We just alled a
1209                                    // selcetion FTS
1210                            }
1211    
1212                            mapLayer.setStyle(newStyleCleaned);
1213    
1214                            return true;
1215    
1216                    } else {
1217                            return false;
1218                    }
1219            }
1220    
1221            /**
1222             * After loading an atlas, the AttribteMetaData contains whatever is written
1223             * in the XML. But the DBF may have changed! This method checks an
1224             * {@link AttributeMetadataMap} against a schema and also corrects
1225             * upperCase/lowerCase problems. It will also remove any geometry column
1226             * attribute metadata.
1227             */
1228          /**          /**
1229           * Creates a           * After loading an atlas, the AttribteMetaData contains whatever is written
1230           * @param styledGrid           * in the XML. But the DBF may have changed!
          * @param iconHeight  
          * @param iconWidth  
          * @return  
1231           */           */
1232          public static Box createLegendPanel(StyledRasterInterface<?> styledGrid, int iconWidth, int iconHeight) {          public static void checkAttribMetaData(
1233                  throw new RuntimeException("Not yet...");                          AttributeMetadataMap attributeMetaDataMap, SimpleFeatureType schema) {
1234    
1235                    ArrayList<Name> willRemove = new ArrayList<Name>();
1236    
1237                    // 1. Check.. all attributes in the atm should be in the schema as well.
1238                    // maybe correct some upperCase/loweCase stuff
1239    
1240                    for (AttributeMetadata atm : attributeMetaDataMap.values()) {
1241    
1242                            AttributeDescriptor foundDescr = schema
1243                                            .getDescriptor(atm.getName());
1244                            if (foundDescr == null) {
1245                                    Name bestMatch = FeatureUtil.findBestMatchingAttribute(schema,
1246                                                    atm.getLocalName());
1247                                    if (bestMatch == null)
1248                                            willRemove.add(atm.getName());
1249                                    else
1250                                            atm.setName(bestMatch);
1251                            } else if (foundDescr instanceof GeometryDescriptor) {
1252                                    // We don't want GeometryColumns in here
1253                                    willRemove.add(atm.getName());
1254                            }
1255                    }
1256    
1257                    // Remove the ones that were not findable in the schema
1258                    for (Name removeName : willRemove) {
1259                            if (attributeMetaDataMap.remove(removeName) == null) {
1260                                    LOGGER.warn("removing the AMData didn't work");
1261                            }
1262                    }
1263    
1264                    // 2. check... all attributes from the schema must have an ATM
1265                    for (AttributeDescriptor ad : schema.getAttributeDescriptors()) {
1266                            if (ad instanceof GeometryDescriptor)
1267                                    continue;
1268                            if (!attributeMetaDataMap.containsKey(ad.getName())) {
1269                                    attributeMetaDataMap.put(ad.getName(), new AttributeMetadata(
1270                                                    ad, schema.getAttributeDescriptors().indexOf(ad),
1271                                                    attributeMetaDataMap.getLanguages()));
1272                            }
1273                    }
1274          }          }
1275    
1276            /**
1277             * Checks every attribute name in the {@link AttributeMetadataMap} for its
1278             * binding type. It the type is textual, add the mrpty string as a NODATA
1279             * value.
1280             *
1281             * @param attributeMetaDataMap
1282             * @param schema
1283             */
1284            public static void addEmptyStringToAllTextualAttributes(
1285                            AttributeMetadataMap attributeMetaDataMap, SimpleFeatureType schema) {
1286    
1287                    for (Name name : attributeMetaDataMap.keySet()) {
1288                            if (String.class.isAssignableFrom(schema.getDescriptor(name)
1289                                            .getType().getBinding())) {
1290                                    attributeMetaDataMap.get(name).getNodataValues().add("");
1291                            }
1292                    }
1293            }
1294  }  }

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26