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

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26