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

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26