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

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

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

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

Legend:
Removed from v.43  
changed lines
  Added in v.772

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26