/[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

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

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26