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

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

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

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

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26