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

Legend:
Removed from v.315  
changed lines
  Added in v.1215

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26