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

Legend:
Removed from v.52  
changed lines
  Added in v.694

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26