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

Legend:
Removed from v.2  
changed lines
  Added in v.1225

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26