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

revision 397 by alfonx, Mon Sep 14 11:40:17 2009 UTC revision 464 by alfonx, Tue Oct 13 13:22:31 2009 UTC
# Line 32  package skrueger.geotools; Line 32  package skrueger.geotools;
32  import java.awt.Color;  import java.awt.Color;
33  import java.awt.Dimension;  import java.awt.Dimension;
34  import java.awt.Graphics;  import java.awt.Graphics;
35    import java.awt.Graphics2D;
36    import java.awt.Rectangle;
37    import java.awt.geom.AffineTransform;
38  import java.awt.image.BufferedImage;  import java.awt.image.BufferedImage;
39    import java.awt.image.ColorModel;
40    import java.awt.image.ComponentColorModel;
41    import java.awt.image.DataBuffer;
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;
 import java.util.HashMap;  
47  import java.util.List;  import java.util.List;
48  import java.util.Map;  import java.util.Map;
 import java.util.SortedMap;  
 import java.util.TreeMap;  
49    
50    import javax.swing.BorderFactory;
51  import javax.swing.Box;  import javax.swing.Box;
52  import javax.swing.BoxLayout;  import javax.swing.BoxLayout;
53  import javax.swing.ImageIcon;  import javax.swing.ImageIcon;
54  import javax.swing.JLabel;  import javax.swing.JLabel;
55    
56  import org.apache.log4j.Logger;  import org.apache.log4j.Logger;
57    import org.geotools.coverage.grid.GeneralGridEnvelope;
58  import org.geotools.coverage.grid.GridCoverage2D;  import org.geotools.coverage.grid.GridCoverage2D;
59    import org.geotools.coverage.grid.GridGeometry2D;
60  import org.geotools.coverage.grid.io.AbstractGridCoverage2DReader;  import org.geotools.coverage.grid.io.AbstractGridCoverage2DReader;
61    import org.geotools.coverage.grid.io.AbstractGridFormat;
62  import org.geotools.feature.FeatureCollection;  import org.geotools.feature.FeatureCollection;
63    import org.geotools.feature.NameImpl;
64    import org.geotools.geometry.jts.ReferencedEnvelope;
65  import org.geotools.map.DefaultMapLayer;  import org.geotools.map.DefaultMapLayer;
66  import org.geotools.map.MapLayer;  import org.geotools.map.MapLayer;
67    import org.geotools.parameter.Parameter;
68    import org.geotools.renderer.lite.gridcoverage2d.GridCoverageRenderer;
69  import org.geotools.styling.ColorMap;  import org.geotools.styling.ColorMap;
70  import org.geotools.styling.ColorMapEntry;  import org.geotools.styling.ColorMapEntry;
71  import org.geotools.styling.FeatureTypeStyle;  import org.geotools.styling.FeatureTypeStyle;
# Line 65  import org.jdom.Document; Line 76  import org.jdom.Document;
76  import org.jdom.Element;  import org.jdom.Element;
77  import org.jdom.input.SAXBuilder;  import org.jdom.input.SAXBuilder;
78  import org.jdom.output.XMLOutputter;  import org.jdom.output.XMLOutputter;
79    import org.opengis.feature.simple.SimpleFeature;
80  import org.opengis.feature.simple.SimpleFeatureType;  import org.opengis.feature.simple.SimpleFeatureType;
81    import org.opengis.feature.type.Name;
82    import org.opengis.parameter.GeneralParameterValue;
83    
84    import schmitzm.geotools.JTSUtil;
85    import schmitzm.geotools.feature.FeatureUtil;
86  import schmitzm.geotools.styling.StylingUtil;  import schmitzm.geotools.styling.StylingUtil;
87  import schmitzm.io.IOUtil;  import schmitzm.io.IOUtil;
88  import schmitzm.lang.LangUtil;  import schmitzm.lang.LangUtil;
89  import schmitzm.swing.SwingUtil;  import schmitzm.swing.SwingUtil;
90  import skrueger.AttributeMetaData;  import skrueger.AttributeMetadata;
91  import skrueger.RasterLegendData;  import skrueger.RasterLegendData;
92  import skrueger.i8n.Translation;  import skrueger.i8n.Translation;
93    
94  /**  /**
95   * This class provides static helper methods for dealing with   * This class provides static helper methods for dealing with
96   * {@link StyledLayerInterface} stuff.   * {@link StyledLayerInterface} stuff.
97   * @author <a href="mailto:[email protected]">Martin Schmitz</a> (University of Bonn/Germany)   *
98     * @author <a href="mailto:[email protected]">Martin Schmitz</a>
99     *         (University of Bonn/Germany)
100   * @version 1.0   * @version 1.0
101   */   */
102  public class StyledLayerUtil {  public class StyledLayerUtil {
103    private static final Logger LOGGER = Logger.getLogger(StyledLayerUtil.class.getName());          private static final Logger LOGGER = Logger.getLogger(StyledLayerUtil.class
104    private static final SAXBuilder SAX_BUILDER = new SAXBuilder();                          .getName());
105    private static final XMLOutputter XML_OUTPUTTER = new XMLOutputter();          private static final SAXBuilder SAX_BUILDER = new SAXBuilder();
106            private static final XMLOutputter XML_OUTPUTTER = new XMLOutputter();
107    /** URL for Atlas XML schema */  
108    public static final String AMLURI = "http://www.wikisquare.de/AtlasML";          /** URL for Atlas XML schema */
109    /** Name of the XML Element for the attribute meta data map */          public static final String AMLURI = "http://www.wikisquare.de/AtlasML";
110    public static final String ELEM_NAME_AMD = "attributeMetaData";          /** Name of the XML Element for the attribute meta data map */
111    /** Name of the XML Element for the raster legend data */          public static final String ELEM_NAME_AMD = "attributeMetaData";
112    public static final String ELEM_NAME_RLD = "rasterLegendData";          /** Name of the XML Element for the raster legend data */
113    /** Name of the XML Element for an attribute meta data map entry */          public static final String ELEM_NAME_RLD = "rasterLegendData";
114    public static final String ELEM_NAME_ATTRIBUTE = "dataAttribute";          /** Name of the XML Element for an attribute meta data map entry */
115    /** Name of the XML Element for an raster legend data entry */          public static final String ELEM_NAME_ATTRIBUTE = "dataAttribute";
116    public static final String ELEM_NAME_RASTERLEGEND = "rasterLegendItem";          /** Name of the XML Element for an raster legend data entry */
117    /** Name of the XML Element for a translation */          public static final String ELEM_NAME_RASTERLEGEND = "rasterLegendItem";
118    public static final String ELEM_NAME_TRANSLATION = "translation";          /** Name of the XML Element for a translation */
119            public static final String ELEM_NAME_TRANSLATION = "translation";
120    /**  
121     * Creates a Geotools {@link MapLayer} from an object. If the object is a          /**
122     * {@link StyledLayerInterface} then its sytle is used. In case of direct           * Creates a Geotools {@link MapLayer} from an object. If the object is a
123     * Geotools objects ({@link GridCoverage2D}, {@link AbstractGridCoverage2DReader},           * {@link StyledLayerInterface} then its sytle is used. In case of direct
124     * {@link FeatureCollection}) a default style is generated.           * Geotools objects ({@link GridCoverage2D},
125     * @param object an Object           * {@link AbstractGridCoverage2DReader}, {@link FeatureCollection}) a
126     * @exception Exception if {@code null} is given as object or an error occurs during layer creation           * default style is generated.
127     */           *
128    public static MapLayer createMapLayer(Object object) throws Exception {           * @param object
129      return createMapLayer(object,null);           *            an Object
130    }           * @exception Exception
131             *                if {@code null} is given as object or an error occurs
132    /**           *                during layer creation
133     * Creates a Geotools {@link MapLayer} from an object. If the object is a           */
134     * {@link StyledLayerInterface} then its sytle is used. In case of direct          public static MapLayer createMapLayer(Object object) throws Exception {
135     * Geotools objects ({@link GridCoverage2D}, {@link AbstractGridCoverage2DReader},                  return createMapLayer(object, null);
136     * {@link FeatureCollection}) a default style is generated.          }
137     * @param object an Object  
138     * @param forcedStyle (SLD-)Style to force for the object          /**
139     * @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
140     */           * {@link StyledLayerInterface} then its sytle is used. In case of direct
141    public static MapLayer createMapLayer(Object object, Style forcedStyle) throws Exception {           * Geotools objects ({@link GridCoverage2D},
142      MapLayer layer     = null;           * {@link AbstractGridCoverage2DReader}, {@link FeatureCollection}) a
143      Style    style     = null;           * default style is generated.
144      if ( object instanceof StyledLayerInterface ) {           *
145        style =  ((StyledLayerInterface<?>)object).getStyle();           * @param object
146        object = ((StyledLayerInterface<?>)object).getGeoObject();           *            an Object
147      }           * @param forcedStyle
148      if ( forcedStyle != null )           *            (SLD-)Style to force for the object
149        style = forcedStyle;           * @exception Exception
150      if ( style == null )           *                if {@code null} is given as object or an error occurs
151        style = StylingUtil.createDefaultStyle(object);           *                during layer creation
152             */
153      if (object instanceof GridCoverage2D)          public static MapLayer createMapLayer(Object object, Style forcedStyle)
154        layer = new DefaultMapLayer( (GridCoverage2D) object, style);                          throws Exception {
155      if (object instanceof AbstractGridCoverage2DReader)                  MapLayer layer = null;
156        layer = new DefaultMapLayer( (AbstractGridCoverage2DReader) object, style);                  Style style = null;
157      if (object instanceof FeatureCollection)                  if (object instanceof StyledLayerInterface) {
158        layer = new DefaultMapLayer( (FeatureCollection) object, style);                          style = ((StyledLayerInterface<?>) object).getStyle();
159                            object = ((StyledLayerInterface<?>) object).getGeoObject();
160      if ( layer == null )                  }
161        throw new Exception("Can not create MapLayer from "+(object == null ? "null" : object.getClass()));                  if (forcedStyle != null)
162                            style = forcedStyle;
163      return layer;                  if (style == null)
164    }                          style = StylingUtil.createDefaultStyle(object);
165    
166    /**                  if (object instanceof GridCoverage2D)
167     * Creates an default instance of {@link StyledLayerInterface} for a Geotools                          layer = new DefaultMapLayer((GridCoverage2D) object, style);
168     * object ({@link GridCoverage2D}, {@link FeatureCollection}) with a default                  if (object instanceof AbstractGridCoverage2DReader)
169     * style.                          layer = new DefaultMapLayer((AbstractGridCoverage2DReader) object,
170     * @param object an Object                                          style);
171     * @param title  title for the object                  if (object instanceof FeatureCollection)
172     * @exception UnsupportedOperationException if {@code null} is given as object or an error occurs during creation                          layer = new DefaultMapLayer((FeatureCollection) object, style);
173     */  
174    public static StyledLayerInterface<?> createStyledLayer(Object object, String title) {                  if (layer == null)
175       return createStyledLayer(object, title, null);                          throw new Exception("Can not create MapLayer from "
176    }                                          + (object == null ? "null" : object.getClass()));
177    
178    /**                  return layer;
179     * Creates an default instance of {@link StyledLayerInterface} for a Geotools          }
180     * object ({@link GridCoverage2D}, {@link FeatureCollection}) with a given  
181     * style.          /**
182     * @param object an Object           * Creates an default instance of {@link StyledLayerInterface} for a
183     * @param title  title for the object           * Geotools object ({@link GridCoverage2D}, {@link FeatureCollection}) with
184     * @param style  style and meta data for the object           * a default style.
185     * @exception UnsupportedOperationException if {@code null} is given as object or an error occurs during creation           *
186     */           * @param object
187    public static StyledLayerInterface<?> createStyledLayer(Object object, String title, StyledLayerStyle style) {           *            an Object
188      StyledLayerInterface<?> styledLayer = null;           * @param title
189             *            title for the object
190      String id = (title != null) ? title : "defaultID";           * @exception UnsupportedOperationException
191             *                if {@code null} is given as object or an error occurs
192      if ( object instanceof GridCoverage2D )           *                during creation
193        styledLayer = new StyledGridCoverage(           */
194            (GridCoverage2D)object,          public static StyledLayerInterface<?> createStyledLayer(Object object,
195            id,                          String title) {
196            title,                  return createStyledLayer(object, title, null);
197            style          }
198        );  
199      else if ( object instanceof AbstractGridCoverage2DReader )          /**
200             styledLayer = new StyledGridCoverageReader(           * Creates an default instance of {@link StyledLayerInterface} for a
201                 (AbstractGridCoverage2DReader)object,           * Geotools object ({@link GridCoverage2D}, {@link FeatureCollection}) with
202                 id,           * a given style.
203                 title,           *
204                 style           * @param object
205             );           *            an Object
206      else if ( object instanceof FeatureCollection )           * @param title
207        styledLayer = new StyledFeatureCollection(           *            title for the object
208            (FeatureCollection)object,           * @param style
209            id,           *            style and meta data for the object
210            title,           * @exception UnsupportedOperationException
211            style           *                if {@code null} is given as object or an error occurs
212        );           *                during creation
213                 */
214      if ( styledLayer == null )          public static StyledLayerInterface<?> createStyledLayer(Object object,
215        throw new UnsupportedOperationException("Can not create StyledLayerInterface object from "+(object == null ? "null" : object.getClass()));                          String title, StyledLayerStyle style) {
216                    StyledLayerInterface<?> styledLayer = null;
217      return styledLayer;  
218    }                  String id = (title != null) ? title : "defaultID";
219    
220    /**                  if (object instanceof GridCoverage2D)
221     * Return only the visible or invisible entries of an AttributeMetaData-Map.                          styledLayer = new StyledGridCoverage((GridCoverage2D) object, id,
222     * @param amdMap AttributeMetaData-Map                                          title, style);
223     * @param visible indicated whether the visible or invisible entries are                  else if (object instanceof AbstractGridCoverage2DReader)
224     *                returned                          styledLayer = new StyledGridCoverageReader(
225     */                                          (AbstractGridCoverage2DReader) object, id, title, style);
226    public static SortedMap<Integer,AttributeMetaData> getVisibleAttributeMetaData(Map<Integer,AttributeMetaData> amdMap, boolean visible) {                  else if (object instanceof FeatureCollection)
227      SortedMap<Integer,AttributeMetaData> filteredMap = new TreeMap<Integer,AttributeMetaData>();                          styledLayer = new StyledFeatureCollection(
228      for (AttributeMetaData amd : amdMap.values())                                          (FeatureCollection) object, id, title, style);
229        if ( amd.isVisible() )  
230          filteredMap.put(amd.getColIdx(), amd);                  if (styledLayer == null)
231                                throw new UnsupportedOperationException(
232      return filteredMap;                                          "Can not create StyledLayerInterface object from "
233    }                                                          + (object == null ? "null" : object.getClass()));
234      
235                      return styledLayer;
236    /**          }
237     * Parses a {@link AttributeMetaData} object from an JDOM-{@link Element}.  
238     * This method works like {@link AMLImport#parseDataAttribute(org.w3c.dom.Node},          /**
239     * but for JDOM.           * Return only the visible or invisible entries of an AttributeMetaData-Map.
240     * @param element {@link Element} to parse           *
241     */           * @param amdMap
242    public static AttributeMetaData parseAttributeMetaData(final Element element) {           *            AttributeMetaData-Map
243      final Integer col = Integer.valueOf(element.getAttributeValue("col"));           * @param visible
244      final Boolean visible = Boolean.valueOf(element.getAttributeValue("visible"));           *            indicated whether the visible or invisible entries are
245      final String unit = element.getAttributeValue("unit");           *            returned
246             */
247      Translation name = new Translation();          public static AttributeMetadataMap getVisibleAttributeMetaData(
248      Translation desc = new Translation();                          AttributeMetadataMap amdMap, boolean visible) {
249      for (final Element childElement : (List<Element>)element.getChildren()) {                  
250        if (childElement.getName() == null)                  AttributeMetadataMap filteredMap = new AttributeMetadataMap();
251          continue;                  for (AttributeMetadata amd : amdMap.values())
252                            if (amd.isVisible() == visible)
253        if (childElement.getName().equals("name"))                                  filteredMap.put(amd.getName(), amd);
254          name = parseTranslation(childElement);  
255        else if (childElement.getName().equals("desc"))                  return filteredMap;
256          desc = parseTranslation(childElement);          }
257      }  
258      return new AttributeMetaData(col, visible, name, desc, unit);          /**
259    }           * Parses a {@link AttributeMetadata} object from an JDOM-{@link Element}.
260             * This method works like {@link
261    /**           * AMLImport#parseDataAttribute(org.w3c.dom.Node}, but for JDOM.
262     * Parses a {@link AttributeMetaData} map from an JDOM-{@link Element}           *
263     * with {@code <attribute>}-childs.           * @param element
264     * @param element {@link Element} to parse           *            {@link Element} to parse
265     */           */
266    public static Map<Integer,AttributeMetaData> parseAttributeMetaDataMap(final Element element) {          public static AttributeMetadata parseAttributeMetaData(final Element element) {
267      HashMap<Integer,AttributeMetaData> metaData = new HashMap<Integer,AttributeMetaData>();                  final String namespace = String.valueOf(element.getAttributeValue("namespace"));
268      List<Element> attributesElements = element.getChildren( ELEM_NAME_ATTRIBUTE );                  final String localname = String.valueOf(element.getAttributeValue("localname"));
269      for (Element attibuteElement : attributesElements)                  final Name aName= new NameImpl(namespace,localname);
270      {                  final Boolean visible = Boolean.valueOf(element
271        AttributeMetaData attrMetaData = parseAttributeMetaData( attibuteElement );                                  .getAttributeValue("visible"));
272        metaData.put( attrMetaData.getColIdx(), attrMetaData );                  final String unit = element.getAttributeValue("unit");
273      }  
274      return metaData;                  Translation name = new Translation();
275    }                  Translation desc = new Translation();
276                    for (final Element childElement : (List<Element>) element.getChildren()) {
277    /**                          if (childElement.getName() == null)
278     * Loads a {@link AttributeMetaData} object from an URL.                                  continue;
279     * @param documentUrl {@link URL} to parse  
280     * @see #parseAttributeMetaData(Element)                          if (childElement.getName().equals("name"))
281     */                                  name = parseTranslation(childElement);
282    public static Map<Integer,AttributeMetaData> loadAttributeMetaDataMap(final URL documentUrl) throws Exception {                          else if (childElement.getName().equals("desc"))
283      Document document = SAX_BUILDER.build(documentUrl);                                  desc = parseTranslation(childElement);
284      return parseAttributeMetaDataMap( document.getRootElement() );                  }
285    }                  return new AttributeMetadata(aName, visible, name, desc, unit);
286            }
287    /**  
288     * Creates an JDOM {@link Element} for the given {@link AttributeMetaData}          /**
289     * object.           * Parses a {@link AttributeMetadata} map from an JDOM-{@link Element} with
290     * @param amd meta data for one attribute           * {@code <attribute>}-childs.
291     */           *
292    public static Element createAttributeMetaDataElement(final AttributeMetaData amd) {           * @param element
293      final Element element = new Element( ELEM_NAME_ATTRIBUTE , AMLURI);           *            {@link Element} to parse
294      element.setAttribute("col", String.valueOf( amd.getColIdx() ) );           */
295      element.setAttribute("visible", String.valueOf( amd.isVisible() ) );          public static AttributeMetadataMap parseAttributeMetaDataMap(
296      element.setAttribute("unit", amd.getUnit() );                          final Element element) {
297      // Creating a aml:name tag...                  AttributeMetadataMap metaData = new AttributeMetadataMap();
298      element.addContent( createTranslationElement("name", amd.getTitle()) );                  List<Element> attributesElements = element
299      // Creating a aml:desc tag...                                  .getChildren(ELEM_NAME_ATTRIBUTE);
300      element.addContent( createTranslationElement("desc", amd.getDesc()) );                  for (Element attibuteElement : attributesElements) {
301      return element;                          AttributeMetadata attrMetaData = parseAttributeMetaData(attibuteElement);
302    }                          metaData.put(attrMetaData.getName(), attrMetaData);
303                    }
304    /**                  return metaData;
305     * Creates an JDOM {@link Element} for the given {@link AttributeMetaData}          }
306     * map.  
307     * @param amdMap map of attribute meta data          /**
308     */           * Loads a {@link AttributeMetadata} object from an URL.
309    public static Element createAttributeMetaDataMapElement(final Map<Integer,AttributeMetaData> amdMap) {           *
310      final Element element = new Element( ELEM_NAME_AMD , AMLURI);           * @param documentUrl
311      for (AttributeMetaData amd : amdMap.values())           *            {@link URL} to parse
312        element.addContent( createAttributeMetaDataElement( amd ) );           * @see #parseAttributeMetaData(Element)
313      return element;           */
314    }          public static AttributeMetadataMap loadAttributeMetaDataMap(
315                            final URL documentUrl) throws Exception {
316    /**                  Document document = SAX_BUILDER.build(documentUrl);
317     * Saves a {@link AttributeMetaData AttributeMetaData-Map} to an URL.                  return parseAttributeMetaDataMap(document.getRootElement());
318     * @param amdMap map of {@link AttributeMetaData}          }
319     * @param documentUrl {@link URL} to store the XML  
320     */          /**
321    public static void saveAttributeMetaDataMap(final Map<Integer,AttributeMetaData> amdMap, final URL documentUrl) throws Exception {           * Creates an JDOM {@link Element} for the given {@link AttributeMetadata}
322      // Create XML-Document           * object.
323      final FileWriter out = new FileWriter( new File(documentUrl.toURI()) );           *
324      XML_OUTPUTTER.output(           * @param amd
325        createAttributeMetaDataMapElement(amdMap),           *            meta data for one attribute
326        out           */
327      );          public static Element createAttributeMetaDataElement(
328      out.flush();                          final AttributeMetadata amd) {
329      out.close();                  final Element element = new Element(ELEM_NAME_ATTRIBUTE, AMLURI);
330    }                  element.setAttribute("namespace", String.valueOf(amd.getName().getNamespaceURI()));
331                    element.setAttribute("localname", String.valueOf(amd.getLocalName()));
332                    element.setAttribute("visible", String.valueOf(amd.isVisible()));
333                    element.setAttribute("unit", amd.getUnit());
334    /**                  // Creating a aml:name tag...
335     * Parses a {@link RasterLegendData} object from an JDOM-{@link Element}.                  element.addContent(createTranslationElement("name", amd.getTitle()));
336     * This method works like {@link AMLImport#parseRasterLegendData(org.w3c.dom.Node},                  // Creating a aml:desc tag...
337     * but for JDOM.                  element.addContent(createTranslationElement("desc", amd.getDesc()));
338     * @param element {@link Element} to parse                  return element;
339     */          }
340    public static RasterLegendData parseRasterLegendData(Element element) {  
341            /**
342      final boolean paintGaps = Boolean.valueOf( element.getAttributeValue("paintGaps") );           * Creates an JDOM {@link Element} for the given {@link AttributeMetadata}
343             * map.
344      RasterLegendData rld = new RasterLegendData(paintGaps);           *
345             * @param amdMap
346      for ( Element childElement : (List<Element>)element.getChildren() ) {           *            map of attribute meta data
347        final String name = childElement.getName();           */
348        // Cancel if it's an attribute          public static Element createAttributeMetaDataMapElement(
349        if ( childElement.getChildren().size() == 0 )                          final AttributeMetadataMap amdMap) {
350          continue;                  final Element element = new Element(ELEM_NAME_AMD, AMLURI);
351                    for (AttributeMetadata amd : amdMap.values())
352        if (name.equals( ELEM_NAME_RASTERLEGEND )) {                          element.addContent(createAttributeMetaDataElement(amd));
353          final String valueAttr = childElement.getAttributeValue("value");                  return element;
354          if ( valueAttr == null )          }
355            throw new UnsupportedOperationException("Attribute 'value' missing for definition of <"+ELEM_NAME_RASTERLEGEND+">");  
356          final double value = Double.valueOf(valueAttr);          /**
357             * Saves a {@link AttributeMetadata AttributeMetaData-Map} to an URL.
358          // first and only item should be the label           *
359          final Element labelElement = childElement.getChild("label");           * @param amdMap
360          // id label element is missing, the translation is searched directly           *            map of {@link AttributeMetadata}
361          // as childs of the rasterLegendItem element           * @param documentUrl
362          Translation label = parseTranslation( labelElement != null ? labelElement : childElement );           *            {@link URL} to store the XML
363          rld.put(value, label);           */
364        }          public static void saveAttributeMetaDataMap(
365      }                          final AttributeMetadataMap amdMap, final URL documentUrl)
366                            throws Exception {
367      return rld;                  // Create XML-Document
368    }                  final FileWriter out = new FileWriter(new File(documentUrl.toURI()));
369                    XML_OUTPUTTER.output(createAttributeMetaDataMapElement(amdMap), out);
370    /**                  out.flush();
371     * Loads a {@link RasterLegendData} object from an URL.                  out.close();
372     * @param documentUrl {@link URL} to parse          }
373     * @see #parseAttributeMetaData(Element)  
374     */          /**
375    public static RasterLegendData loadRasterLegendData(final URL documentUrl) throws Exception {           * Parses a {@link RasterLegendData} object from an JDOM-{@link Element}.
376      Document document = SAX_BUILDER.build(documentUrl);           * This method works like {@link
377      return parseRasterLegendData( document.getRootElement() );           * AMLImport#parseRasterLegendData(org.w3c.dom.Node}, but for JDOM.
378    }           *
379             * @param element
380   /**           *            {@link Element} to parse
381     * Creates an JDOM {@link Element} for the given {@link RasterLegendData}           */
382     * map.          public static RasterLegendData parseRasterLegendData(Element element) {
383     * @param rld raster legend data  
384     */                  final boolean paintGaps = Boolean.valueOf(element
385    public static Element createRasterLegendDataElement(final RasterLegendData rld) {                                  .getAttributeValue("paintGaps"));
386      final Element element = new Element( ELEM_NAME_RLD , AMLURI);  
387      element.setAttribute("paintGaps", rld.isPaintGaps().toString());                  RasterLegendData rld = new RasterLegendData(paintGaps);
388      for (Double key : rld.getSortedKeys()) {  
389        Element item = new Element( ELEM_NAME_RASTERLEGEND, AMLURI);                  for (Element childElement : (List<Element>) element.getChildren()) {
390        item.setAttribute("value", key.toString());                          final String name = childElement.getName();
391        item.addContent( createTranslationElement("label", rld.get(key)) );                          // Cancel if it's an attribute
392        element.addContent(item);                          if (childElement.getChildren().size() == 0)
393      }                                  continue;
394      return element;  
395    }                          if (name.equals(ELEM_NAME_RASTERLEGEND)) {
396                                    final String valueAttr = childElement
397    /**                                                  .getAttributeValue("value");
398     * Creates {@link RasterLegendData} from a {@link ColorMap}.                                  if (valueAttr == null)
399     * @param colorMap  a color map                                          throw new UnsupportedOperationException(
400     * @param paintGaps indicated whether gaps are painted between the legend items                                                          "Attribute 'value' missing for definition of <"
401     * @param digits    number of digits the grid value classes (and legend) are                                                                          + ELEM_NAME_RASTERLEGEND + ">");
402     *                  rounded to (null means no round; >= 0 means digits after comma;                                  final double value = Double.valueOf(valueAttr);
403     *                  < 0 means digits before comma)    */  
404    public static RasterLegendData generateRasterLegendData(ColorMap colorMap, boolean paintGaps, Integer digits) {                                  // first and only item should be the label
405      DecimalFormat    decFormat = digits != null ? new DecimalFormat( SwingUtil.getNumberFormatPattern(digits) ) : null;                                  final Element labelElement = childElement.getChild("label");
406      RasterLegendData rld       = new RasterLegendData(paintGaps);                                  // id label element is missing, the translation is searched
407      for (ColorMapEntry cme : colorMap.getColorMapEntries())                                  // directly
408      {                                  // as childs of the rasterLegendItem element
409        double value = StylingUtil.getQuantityFromColorMapEntry(cme);                                  Translation label = parseTranslation(labelElement != null ? labelElement
410        String label = cme.getLabel();                                                  : childElement);
411        // if no label is set (e.g. quantitative style),                                  rld.put(value, label);
412        // use the value as label                          }
413        if ( label == null || label.equals("") )                  }
414          if ( digits == null )  
415            label = String.valueOf(value);                  return rld;
416          else          }
417            label = decFormat.format( LangUtil.round(value, digits) );  
418        rld.put( value, new Translation("   "+label) );          /**
419      }           * Loads a {@link RasterLegendData} object from an URL.
420      return rld;           *
421    }           * @param documentUrl
422             *            {@link URL} to parse
423    /**           * @see #parseAttributeMetaData(Element)
424     * Creates {@link RasterLegendData} from the {@link ColorMap} of a style.           */
425     * @param style     a raster style (must contain a  {@link RasterSymbolizer})          public static RasterLegendData loadRasterLegendData(final URL documentUrl)
426     * @param paintGaps indicated whether gaps are painted between the legend items                          throws Exception {
427     * @param digits    number of digits the grid value classes (and legend) are                  Document document = SAX_BUILDER.build(documentUrl);
428     *                  rounded to (null means no round; >= 0 means digits after comma;                  return parseRasterLegendData(document.getRootElement());
429     *                  < 0 means digits before comma)    */          }
430    public static RasterLegendData generateRasterLegendData(Style style, boolean paintGaps, Integer digits) {  
431      ColorMap colorMap = StylingUtil.getColorMapFromStyle(style);          /**
432      if ( colorMap == null)           * Creates an JDOM {@link Element} for the given {@link RasterLegendData}
433        throw new IllegalArgumentException("Color map can not be determined from style!");           * map.
434      return generateRasterLegendData(colorMap, paintGaps, digits);           *
435    }           * @param rld
436             *            raster legend data
437    /**           */
438     * Saves a {@link RasterLegendData} to an URL.          public static Element createRasterLegendDataElement(
439     * @param rld raster legend data                          final RasterLegendData rld) {
440     * @param documentUrl {@link URL} to store the XML                  final Element element = new Element(ELEM_NAME_RLD, AMLURI);
441     */                  element.setAttribute("paintGaps", rld.isPaintGaps().toString());
442    public static void saveRasterLegendData(final RasterLegendData rld, final URL documentUrl) throws Exception {                  for (Double key : rld.getSortedKeys()) {
443      // Create XML-Document                          Element item = new Element(ELEM_NAME_RASTERLEGEND, AMLURI);
444      final FileWriter out = new FileWriter( new File(documentUrl.toURI()) );                          item.setAttribute("value", key.toString());
445      XML_OUTPUTTER.output(                          item.addContent(createTranslationElement("label", rld.get(key)));
446        createRasterLegendDataElement(rld),                          element.addContent(item);
447        out                  }
448      );                  return element;
449      out.flush();          }
450      out.close();  
451    }          /**
452             * Creates {@link RasterLegendData} from a {@link ColorMap}.
453    /**           *
454     * Parses a {@link Translation} object from an JDOM-{@link Element}.           * @param colorMap
455     * This method works like {@link AMLImport#parseTranslation(org.w3c.dom.Node},           *            a color map
456     * but for JDOM.           * @param paintGaps
457     * @param element {@link Element} to parse           *            indicated whether gaps are painted between the legend items
458     */           * @param digits
459    public final static Translation parseTranslation(final Element element) {           *            number of digits the grid value classes (and legend) are
460      Translation trans = new Translation();           *            rounded to (null means no round; >= 0 means digits after
461             *            comma; < 0 means digits before comma)
462      if (element == null)           */
463       return trans;          public static RasterLegendData generateRasterLegendData(ColorMap colorMap,
464                            boolean paintGaps, Integer digits) {
465      for (final Element translationElement : (List<Element>)element.getChildren()) {                  DecimalFormat decFormat = digits != null ? new DecimalFormat(SwingUtil
466        final String name = translationElement.getName();                                  .getNumberFormatPattern(digits)) : null;
467        if (name == null)                  RasterLegendData rld = new RasterLegendData(paintGaps);
468          continue;                  for (ColorMapEntry cme : colorMap.getColorMapEntries()) {
469                            double value = StylingUtil.getQuantityFromColorMapEntry(cme);
470        // lang attribute                          String label = cme.getLabel();
471        String lang = translationElement.getAttributeValue("lang");                          // if no label is set (e.g. quantitative style),
472        // set the default, if no language code is set                          // use the value as label
473        if ( lang == null )                          if (label == null || label.equals(""))
474          lang = Translation.DEFAULT_KEY;                                  if (digits == null)
475                                            label = String.valueOf(value);
476        final String translationText = translationElement.getValue();                                  else
477        if (translationText == null)                                          label = decFormat.format(LangUtil.round(value, digits));
478          trans.put(lang, "");                          rld.put(value, new Translation("   " + label));
479        else                  }
480          trans.put(lang, translationText);                  return rld;
481      }          }
482    
483      // if no <translation> is given, the value of the node should          /**
484      // be used as a default translation           * Creates {@link RasterLegendData} from the {@link ColorMap} of a style.
485      if (trans.size() == 0)           *
486        trans.put( Translation.DEFAULT_KEY, element.getValue() );           * @param style
487      //     trans = new Translation( ((List<Element>)element.getChildren()).get(0).getValue() );           *            a raster style (must contain a {@link RasterSymbolizer})
488             * @param paintGaps
489      return trans;           *            indicated whether gaps are painted between the legend items
490    }           * @param digits
491             *            number of digits the grid value classes (and legend) are
492    /**           *            rounded to (null means no round; >= 0 means digits after
493     * Creates an JDOM {@link Element} for the given {@link Translation}.           *            comma; < 0 means digits before comma)
494     * @param tagname Name of the Element           */
495     * @param translation Translation to store in the Element          public static RasterLegendData generateRasterLegendData(Style style,
496     */                          boolean paintGaps, Integer digits) {
497    public final static Element createTranslationElement(String tagname, Translation translation) {                  ColorMap colorMap = StylingUtil.getColorMapFromStyle(style);
498      Element element = new Element(tagname, AMLURI);                  if (colorMap == null)
499      if ( translation == null )                          throw new IllegalArgumentException(
500        throw new UnsupportedOperationException("Translation element can not be created from null!");                                          "Color map can not be determined from style!");
501                    return generateRasterLegendData(colorMap, paintGaps, digits);
502      // If only a default translation is set, the <translation lang="..">..</tranlation>          }
503      // part is not used  
504      if (translation.keySet().size() == 1 && translation.get(Translation.DEFAULT_KEY) != null) {          /**
505        element.addContent( translation.get(Translation.DEFAULT_KEY) );           * Saves a {@link RasterLegendData} to an URL.
506        return element;           *
507      }           * @param rld
508             *            raster legend data
509      // add a <translation lang="..">..</tranlation> part to the element for           * @param documentUrl
510      // all languages           *            {@link URL} to store the XML
511      for (String lang : translation.keySet()) {           */
512        Element translationElement = new Element( ELEM_NAME_TRANSLATION , AMLURI);          public static void saveRasterLegendData(final RasterLegendData rld,
513        translationElement.setAttribute("lang", lang);                          final URL documentUrl) throws Exception {
514        String translationString = translation.get(lang);                  // Create XML-Document
515        if (translationString == null)                  final FileWriter out = new FileWriter(new File(documentUrl.toURI()));
516         translationString = "";                  XML_OUTPUTTER.output(createRasterLegendDataElement(rld), out);
517        translationElement.addContent( translationString );                  out.flush();
518        element.addContent(translationElement);                  out.close();
519      }          }
520    
521      return element;          /**
522    }           * Parses a {@link Translation} object from an JDOM-{@link Element}. This
523             * method works like {@link AMLImport#parseTranslation(org.w3c.dom.Node},
524             * but for JDOM.
525    /**           *
526     * Sets a style to {@link StyledLayerInterface}.           * @param element
527     * @param styledObject a styled object           *            {@link Element} to parse
528     * @param style a Style           */
529     */          public final static Translation parseTranslation(final Element element) {
530    public static void setStyledLayerStyle(StyledLayerInterface styledObject, StyledLayerStyle<?> style) {                  Translation trans = new Translation();
531      // set SLD style  
532      styledObject.setStyle( style.getGeoObjectStyle() );                  if (element == null)
533      // set meta data                          return trans;
534      if ( styledObject        instanceof StyledGridCoverageInterface &&  
535           (style.getMetaData() instanceof RasterLegendData || style.getMetaData() == null) ) {                  for (final Element translationElement : (List<Element>) element
536        RasterLegendData sourceRld = (RasterLegendData)style.getMetaData();                                  .getChildren()) {
537        RasterLegendData destRld = ((StyledGridCoverageInterface)styledObject).getLegendMetaData();                          final String name = translationElement.getName();
538        if ( destRld != null && sourceRld != null ) {                          if (name == null)
539          destRld.setPaintGaps(sourceRld.isPaintGaps());                                  continue;
540          destRld.clear();  
541          destRld.putAll( sourceRld );                          // lang attribute
542        }                          String lang = translationElement.getAttributeValue("lang");
543        return;                          // set the default, if no language code is set
544      }                          if (lang == null)
545      if ( styledObject        instanceof StyledFeatureCollectionInterface &&                                  lang = Translation.DEFAULT_KEY;
546           (style.getMetaData() instanceof Map || style.getMetaData() == null) ) {  
547        Map<Integer, AttributeMetaData> sourceAmd = (Map<Integer, AttributeMetaData>)style.getMetaData();                          final String translationText = translationElement.getValue();
548        Map<Integer, AttributeMetaData> destAmd   = ((StyledFeatureCollectionInterface)styledObject).getAttributeMetaDataMap();                          if (translationText == null)
549        if ( destAmd != null && sourceAmd != null ) {                                  trans.put(lang, "");
550          destAmd.clear();                          else
551          destAmd.putAll( sourceAmd );                                  trans.put(lang, translationText);
552        }                  }
553        return;  
554      }                  // if no <translation> is given, the value of the node should
555                    // be used as a default translation
556      throw new UnsupportedOperationException("Style is not compatible to object: " +                  if (trans.size() == 0)
557                                              (style.getMetaData() == null ? null : style.getMetaData().getClass().getSimpleName()) +                          trans.put(Translation.DEFAULT_KEY, element.getValue());
558                                              " <-> " +                  // trans = new Translation(
559                                              (styledObject == null ? null : styledObject.getClass().getSimpleName()));                  // ((List<Element>)element.getChildren()).get(0).getValue() );
560    }  
561                    return trans;
562    /**          }
563     * Returns the style a {@link StyledLayerInterface} as a {@link StyledLayerStyle}.  
564     * @param styledObject a styled object          /**
565     * @return {@code StyledLayerStyle<RasterLegendData>} for {@link StyledGridCoverageInterface}           * Creates an JDOM {@link Element} for the given {@link Translation}.
566     *         or {@code StyledLayerStyle<Map<Integer,AttributeMetaData>>} for           *
567     *         {@link StyledFeatureCollectionInterface}           * @param tagname
568     */           *            Name of the Element
569    public static StyledLayerStyle<?> getStyledLayerStyle(StyledLayerInterface styledObject) {           * @param translation
570      if ( styledObject instanceof StyledGridCoverageInterface )           *            Translation to store in the Element
571        return getStyledLayerStyle( (StyledGridCoverageInterface)styledObject );           */
572      if ( styledObject instanceof StyledFeatureCollectionInterface )          public final static Element createTranslationElement(String tagname,
573        return getStyledLayerStyle( (StyledFeatureCollectionInterface)styledObject );                          Translation translation) {
574      throw new UnsupportedOperationException("Unknown type of StyledLayerInterface: "+(styledObject == null ? null : styledObject.getClass().getSimpleName()));                  Element element = new Element(tagname, AMLURI);
575    }                  if (translation == null)
576                            throw new UnsupportedOperationException(
577    /**                                          "Translation element can not be created from null!");
578     * Returns the style and raster meta data of a {@link StyledGridCoverageInterface}  
579     * as a {@link StyledLayerStyle}.                  // If only a default translation is set, the <translation
580     * @param styledGC a styled grid coverage                  // lang="..">..</tranlation>
581     */                  // part is not used
582    public static StyledLayerStyle<RasterLegendData> getStyledLayerStyle(StyledGridCoverageInterface styledGC) {                  if (translation.keySet().size() == 1
583      return new StyledLayerStyle<RasterLegendData>(                                  && translation.get(Translation.DEFAULT_KEY) != null) {
584        styledGC.getStyle(),                          element.addContent(translation.get(Translation.DEFAULT_KEY));
585        styledGC.getLegendMetaData()                          return element;
586      );                  }
587    }  
588                    // add a <translation lang="..">..</tranlation> part to the element for
589    /**                  // all languages
590     * Returns the style and attribute meta data of a {@link StyledFeatureCollectionInterface}                  for (String lang : translation.keySet()) {
591     * as a {@link StyledLayerStyle}.                          Element translationElement = new Element(ELEM_NAME_TRANSLATION,
592     * @param styledFC a styled feature collection                                          AMLURI);
593     */                          translationElement.setAttribute("lang", lang);
594    public static StyledLayerStyle<Map<Integer,AttributeMetaData>> getStyledLayerStyle(StyledFeatureCollectionInterface styledFC) {                          String translationString = translation.get(lang);
595      return new StyledLayerStyle<Map<Integer,AttributeMetaData>>(                          if (translationString == null)
596        styledFC.getStyle(),                                  translationString = "";
597        styledFC.getAttributeMetaDataMap()                          translationElement.addContent(translationString);
598      );                          element.addContent(translationElement);
599    }                  }
600    
601    /**                  return element;
602     * Loads a {@linkplain Style SLD-Style} and {@linkplain RasterLegendData Raster-LegendData}          }
603     * for a given geo-object (raster) source. The SLD file must be present. A missing  
604     * raster legend-data file is tolerated.          /**
605     * @param geoObjectURL URL of the (already read) raster object           * Sets a style to {@link StyledLayerInterface}.
606     * @param sldExt file extention for the SLD file           *
607     * @param rldExt file extention for the raster legend-data file           * @param styledObject
608     * @return {@code null} in case of any error           *            a styled object
609     */           * @param style
610    public static StyledLayerStyle<RasterLegendData> loadStyledRasterStyle(URL geoObjectURL, String sldExt, String rldExt) {           *            a Style
611      RasterLegendData metaData = null;           */
612      Style sldStyle = null;          public static void setStyledLayerStyle(StyledLayerInterface styledObject,
613      try {                          StyledLayerStyle<?> style) {
614        Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(geoObjectURL, sldExt));                  // set SLD style
615        // SLD must be present                  styledObject.setStyle(style.getGeoObjectStyle());
616        if ( styles == null || styles.length == 0 )                  // set meta data
617          return null;                  if (styledObject instanceof StyledGridCoverageInterface
618        sldStyle = styles[0];                                  && (style.getMetaData() instanceof RasterLegendData || style
619      }                                                  .getMetaData() == null)) {
620      catch (Exception err) {                          RasterLegendData sourceRld = (RasterLegendData) style.getMetaData();
621        // SLD must be present                          RasterLegendData destRld = ((StyledGridCoverageInterface) styledObject)
622        LangUtil.logDebugError(LOGGER,err);                                          .getLegendMetaData();
623        return null;                          if (destRld != null && sourceRld != null) {
624      }                                  destRld.setPaintGaps(sourceRld.isPaintGaps());
625                                    destRld.clear();
626      try {                                  destRld.putAll(sourceRld);
627        metaData = StyledLayerUtil.loadRasterLegendData( IOUtil.changeUrlExt(geoObjectURL,rldExt) );                          }
628      } catch (FileNotFoundException err) {                          return;
629        // ignore missing raster legend data                  }
630      } catch (Exception err) {                  if (styledObject instanceof StyledFeatureCollectionInterface
631        // any other error during legend data creation leads to error                                  && (style.getMetaData() instanceof Map || style.getMetaData() == null)) {
632        LangUtil.logDebugError(LOGGER,err);                          AttributeMetadataMap sourceAmd = (AttributeMetadataMap) style
633        return null;                                          .getMetaData();
634      }                          AttributeMetadataMap destAmd = ((StyledFeatureCollectionInterface) styledObject)
635      return new StyledLayerStyle<RasterLegendData>(sldStyle, metaData);                                          .getAttributeMetaDataMap();
636    }                          if (destAmd != null && sourceAmd != null) {
637                                    destAmd.clear();
638    /**                                  destAmd.putAll(sourceAmd);
639     * Loads a {@linkplain Style SLD-Style} from a {@code .sld} file and                          }
640     * {@linkplain RasterLegendData Raster-LegendData} from a {@code .rld} file                          return;
641     * for a given geo-object (raster) source. The SLD file must be present. A missing                  }
642     * raster legend-data file is tolerated.  
643     * @param geoObjectURL URL of the (already read) raster object                  throw new UnsupportedOperationException(
644     * @param sldExt file extention for the SLD file                                  "Style is not compatible to object: "
645     * @param rldExt file extention for the raster legend-data file                                                  + (style.getMetaData() == null ? null : style
646     * @return {@code null} in case of any error                                                                  .getMetaData().getClass().getSimpleName())
647     */                                                  + " <-> "
648    public static StyledLayerStyle<RasterLegendData> loadStyledRasterStyle(URL geoObjectURL) {                                                  + (styledObject == null ? null : styledObject
649      return loadStyledRasterStyle(geoObjectURL, "sld", "rld");                                                                  .getClass().getSimpleName()));
650    }          }
651    
652    /**          /**
653     * Loads a {@linkplain Style SLD-Style} and a {@linkplain AttributeMetaData AttributeMetaData-Map}           * Returns the style a {@link StyledLayerInterface} as a
654     * for a given geo-object (feature) source. The SLD file must be present. A missing           * {@link StyledLayerStyle}.
655     * attribute meta-data file is tolerated.           *
656     * @param geoObjectURL URL of the (already read) feature object           * @param styledObject
657     * @param sldExt file extention for the SLD file           *            a styled object
658     * @param rldExt file extention for the raster legend-data file           * @return {@code StyledLayerStyle<RasterLegendData>} for
659     * @return {@code null} in case of any error           *         {@link StyledGridCoverageInterface} or {@code
660     */           *         StyledLayerStyle<Map<Integer,AttributeMetaData>>} for
661    public static StyledLayerStyle<Map<Integer,AttributeMetaData>> loadStyledFeatureStyle(URL geoObjectURL, String sldExt, String rldExt) {           *         {@link StyledFeatureCollectionInterface}
662      Map<Integer,AttributeMetaData> metaData = null;           */
663      Style                          sldStyle = null;          public static StyledLayerStyle<?> getStyledLayerStyle(
664      try {                          StyledLayerInterface styledObject) {
665        Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(geoObjectURL, sldExt));                  if (styledObject instanceof StyledGridCoverageInterface)
666        // SLD must be present                          return getStyledLayerStyle((StyledGridCoverageInterface) styledObject);
667        if ( styles == null || styles.length == 0 )                  if (styledObject instanceof StyledFeatureCollectionInterface)
668          return null;                          return getStyledLayerStyle((StyledFeatureCollectionInterface) styledObject);
669        sldStyle = styles[0];                  throw new UnsupportedOperationException(
670      } catch (Exception err) {                                  "Unknown type of StyledLayerInterface: "
671        // SLD must be present                                                  + (styledObject == null ? null : styledObject
672        LangUtil.logDebugError(LOGGER,err);                                                                  .getClass().getSimpleName()));
673        return null;          }
674      }  
675            /**
676      try {           * Returns the style and raster meta data of a
677        metaData = StyledLayerUtil.loadAttributeMetaDataMap( IOUtil.changeUrlExt(geoObjectURL,rldExt) );           * {@link StyledGridCoverageInterface} as a {@link StyledLayerStyle}.
678      } catch (FileNotFoundException err) {           *
679        // ignore missing attribute meta data           * @param styledGC
680      } catch (Exception err) {           *            a styled grid coverage
681        // any other error during meta data creation leads to error           */
682        LangUtil.logDebugError(LOGGER,err);          public static StyledLayerStyle<RasterLegendData> getStyledLayerStyle(
683        return null;                          StyledGridCoverageInterface styledGC) {
684      }                  return new StyledLayerStyle<RasterLegendData>(styledGC.getStyle(),
685                                    styledGC.getLegendMetaData());
686      return new StyledLayerStyle<Map<Integer,AttributeMetaData>>(sldStyle, metaData);          }
687    }  
688            /**
689    /**           * Returns the style and attribute meta data of a
690     * Loads a {@linkplain Style SLD-Style} from a {@code .sld} file and           * {@link StyledFeatureCollectionInterface} as a {@link StyledLayerStyle}.
691     * {@linkplain AttributeMetaData AttributeMetaData-Map} from a {@code .amd} file           *
692     * for a given geo-object (feature) source. The SLD file must be present. A missing           * @param styledFC
693     * attribute meta-data file is tolerated.           *            a styled feature collection
694     * @param geoObjectURL URL of the (already read) feature object           */
695     * @param sldExt file extention for the SLD file          public static StyledLayerStyle<AttributeMetadataMap> getStyledLayerStyle(
696     * @param rldExt file extention for the raster legend-data file                          StyledFeatureCollectionInterface styledFC) {
697     * @return {@code null} in case of any error                  return new StyledLayerStyle<AttributeMetadataMap>(styledFC
698     */                                  .getStyle(), styledFC.getAttributeMetaDataMap());
699    public static StyledLayerStyle<Map<Integer,AttributeMetaData>> loadStyledFeatureStyle(URL geoObjectURL) {          }
700      return loadStyledFeatureStyle(geoObjectURL, "sld", "amd");  
701    }          /**
702             * Loads a {@linkplain Style SLD-Style} and {@linkplain RasterLegendData
703    /**           * Raster-LegendData} for a given geo-object (raster) source. The SLD file
704     * Stores a {@linkplain Style SLD-Style} and {@linkplain RasterLegendData Raster-LegendData}           * must be present. A missing raster legend-data file is tolerated.
705     * for a given geo-object (raster) source.           *
706     * @param style  style to save           * @param geoObjectURL
707     * @param geoObjectURL URL of the raster object           *            URL of the (already read) raster object
708     * @param sldExt file extention for the SLD file           * @param sldExt
709     * @param mdExt file extention for the meta-data file           *            file extention for the SLD file
710     */           * @param rldExt
711    public static <T> void saveStyledLayerStyle(StyledLayerStyle<T> style, URL geoObjectURL, String sldExt, String mdExt) throws Exception {           *            file extention for the raster legend-data file
712      // Store the SLD           * @return {@code null} in case of any error
713      Style sldStyle = style.getGeoObjectStyle();           */
714      if ( sldStyle != null ) {          public static StyledLayerStyle<RasterLegendData> loadStyledRasterStyle(
715        StylingUtil.saveStyleToSLD(                          URL geoObjectURL, String sldExt, String rldExt) {
716           sldStyle,                  RasterLegendData metaData = null;
717           IOUtil.changeFileExt(                  Style sldStyle = null;
718                new File(geoObjectURL.toURI()),                  try {
719                sldExt                          Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(
720           )                                          geoObjectURL, sldExt));
721        );                          // SLD must be present
722      }                          if (styles == null || styles.length == 0)
723                                    return null;
724      // Store the meta data                          sldStyle = styles[0];
725      T metaData = style.getMetaData();                  } catch (Exception err) {
726      if ( metaData != null ) {                          // SLD must be present
727        if ( metaData instanceof RasterLegendData ) {                          LangUtil.logDebugError(LOGGER, err);
728          saveRasterLegendData(                          return null;
729              (RasterLegendData)metaData,                  }
730              IOUtil.changeUrlExt(geoObjectURL,mdExt)  
731          );                  try {
732  //      } else if ( metaData instanceof Map<Integer,AttributeMetaData> ) { // LEIDER NICHT KOMPILIERBAR!!                          metaData = StyledLayerUtil.loadRasterLegendData(IOUtil
733        } else if ( metaData instanceof Map ) {                                          .changeUrlExt(geoObjectURL, rldExt));
734          saveAttributeMetaDataMap(                  } catch (FileNotFoundException err) {
735              (Map<Integer,AttributeMetaData>)metaData,                          // ignore missing raster legend data
736              IOUtil.changeUrlExt(geoObjectURL,mdExt)                  } catch (Exception err) {
737          );                          // any other error during legend data creation leads to error
738        } else                          LangUtil.logDebugError(LOGGER, err);
739          throw new UnsupportedOperationException("Export for meta data not yet supported: "+metaData.getClass().getSimpleName());                          return null;
740      }                  }
741    }                  return new StyledLayerStyle<RasterLegendData>(sldStyle, metaData);
742            }
743    /**  
744     * Stores the {@linkplain Style SLD-Style} to a {@code .sld} file and          /**
745     * the meta data ({@link RasterLegendData} or {@link AttributeMetaData})           * Loads a {@linkplain Style SLD-Style} from a {@code .sld} file and
746     * to a {@code .rld} or {@code .amd} file.           * {@linkplain RasterLegendData Raster-LegendData} from a {@code .rld} file
747     * for a given geo-object source.           * for a given geo-object (raster) source. The SLD file must be present. A
748     * @param style  style to save           * missing raster legend-data file is tolerated.
749     * @param geoObjectURL URL of the (already read) raster object           *
750     */           * @param geoObjectURL
751    public static void saveStyledLayerStyle(StyledLayerStyle<?> style, URL geoObjectURL) throws Exception {           *            URL of the (already read) raster object
752      if ( style.getMetaData() instanceof RasterLegendData )           * @param sldExt
753        saveStyledLayerStyle(style,geoObjectURL, "sld", "rld");           *            file extention for the SLD file
754      else           * @param rldExt
755        saveStyledLayerStyle(style,geoObjectURL, "sld", "amd");           *            file extention for the raster legend-data file
756    }           * @return {@code null} in case of any error
757               */
758              public static StyledLayerStyle<RasterLegendData> loadStyledRasterStyle(
759                            URL geoObjectURL) {
760                    return loadStyledRasterStyle(geoObjectURL, "sld", "rld");
761            }
762    
763            /**
764             * Loads a {@linkplain Style SLD-Style} and a {@linkplain AttributeMetadata
765             * AttributeMetaData-Map} for a given geo-object (feature) source. The SLD
766             * file must be present. A missing attribute meta-data file is tolerated.
767             *
768             * @param geoObjectURL
769             *            URL of the (already read) feature object
770             * @param sldExt
771             *            file extention for the SLD file
772             * @param rldExt
773             *            file extention for the raster legend-data file
774             * @return {@code null} in case of any error
775             */
776            public static StyledLayerStyle<AttributeMetadataMap> loadStyledFeatureStyle(
777                            URL geoObjectURL, String sldExt, String rldExt) {
778                    AttributeMetadataMap metaData = null;
779                    Style sldStyle = null;
780                    try {
781                            Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(
782                                            geoObjectURL, sldExt));
783                            // SLD must be present
784                            if (styles == null || styles.length == 0)
785                                    return null;
786                            sldStyle = styles[0];
787                    } catch (Exception err) {
788                            // SLD must be present
789                            LangUtil.logDebugError(LOGGER, err);
790                            return null;
791                    }
792    
793                    try {
794                            metaData = StyledLayerUtil.loadAttributeMetaDataMap(IOUtil
795                                            .changeUrlExt(geoObjectURL, rldExt));
796                    } catch (FileNotFoundException err) {
797                            // ignore missing attribute meta data
798                    } catch (Exception err) {
799                            // any other error during meta data creation leads to error
800                            LangUtil.logDebugError(LOGGER, err);
801                            return null;
802                    }
803    
804                    return new StyledLayerStyle<AttributeMetadataMap>(sldStyle,
805                                    metaData);
806            }
807    
808            /**
809             * Loads a {@linkplain Style SLD-Style} from a {@code .sld} file and
810             * {@linkplain AttributeMetadata AttributeMetaData-Map} from a {@code .amd}
811             * file for a given geo-object (feature) source. The SLD file must be
812             * present. A missing attribute meta-data file is tolerated.
813             *
814             * @param geoObjectURL
815             *            URL of the (already read) feature object
816             * @param sldExt
817             *            file extention for the SLD file
818             * @param rldExt
819             *            file extention for the raster legend-data file
820             * @return {@code null} in case of any error
821             */
822            public static StyledLayerStyle<AttributeMetadataMap> loadStyledFeatureStyle(
823                            URL geoObjectURL) {
824                    return loadStyledFeatureStyle(geoObjectURL, "sld", "amd");
825            }
826    
827            /**
828             * Stores a {@linkplain Style SLD-Style} and {@linkplain RasterLegendData
829             * Raster-LegendData} for a given geo-object (raster) source.
830             *
831             * @param style
832             *            style to save
833             * @param geoObjectURL
834             *            URL of the raster object
835             * @param sldExt
836             *            file extention for the SLD file
837             * @param mdExt
838             *            file extention for the meta-data file
839             */
840            public static <T> void saveStyledLayerStyle(StyledLayerStyle<T> style,
841                            URL geoObjectURL, String sldExt, String mdExt) throws Exception {
842                    // Store the SLD
843                    Style sldStyle = style.getGeoObjectStyle();
844                    if (sldStyle != null) {
845                            StylingUtil.saveStyleToSLD(sldStyle, IOUtil.changeFileExt(new File(
846                                            geoObjectURL.toURI()), sldExt));
847                    }
848    
849                    // Store the meta data
850                    T metaData = style.getMetaData();
851                    if (metaData != null) {
852                            if (metaData instanceof RasterLegendData) {
853                                    saveRasterLegendData((RasterLegendData) metaData, IOUtil
854                                                    .changeUrlExt(geoObjectURL, mdExt));
855                                    // } else if ( metaData instanceof
856                                    // Map<Integer,AttributeMetaData> ) { // LEIDER NICHT
857                                    // KOMPILIERBAR!!
858                            } else if (metaData instanceof Map) {
859                                    saveAttributeMetaDataMap(
860                                                    (AttributeMetadataMap) metaData, IOUtil
861                                                                    .changeUrlExt(geoObjectURL, mdExt));
862                            } else
863                                    throw new UnsupportedOperationException(
864                                                    "Export for meta data not yet supported: "
865                                                                    + metaData.getClass().getSimpleName());
866                    }
867            }
868    
869            /**
870             * Stores the {@linkplain Style SLD-Style} to a {@code .sld} file and the
871             * meta data ({@link RasterLegendData} or {@link AttributeMetadata}) to a
872             * {@code .rld} or {@code .amd} file. for a given geo-object source.
873             *
874             * @param style
875             *            style to save
876             * @param geoObjectURL
877             *            URL of the (already read) raster object
878             */
879            public static void saveStyledLayerStyle(StyledLayerStyle<?> style,
880                            URL geoObjectURL) throws Exception {
881                    if (style.getMetaData() instanceof RasterLegendData)
882                            saveStyledLayerStyle(style, geoObjectURL, "sld", "rld");
883                    else
884                            saveStyledLayerStyle(style, geoObjectURL, "sld", "amd");
885            }
886    
887          /**          /**
888           * Creates a {@link Box} that shows a legend for a list of           * Creates a {@link Box} that shows a legend for a list of
# Line 797  public class StyledLayerUtil { Line 942  public class StyledLayerUtil {
942                                           * Nuetzlich wenn die Componente gedruckt (z.B. wenn ein                                           * Nuetzlich wenn die Componente gedruckt (z.B. wenn ein
943                                           * Screenshot gemacht wird) wird. Dann werden wird der                                           * Screenshot gemacht wird) wird. Dann werden wird der
944                                           * Hintergrund auf WEISS gesetzt.                                           * Hintergrund auf WEISS gesetzt.
                                          *  
                                          * @author <a href="mailto:[email protected]">Stefan  
                                          *         Alfons Kr&uuml;ger</a>  
945                                           */                                           */
946                                          @Override                                          @Override
947                                          public void print(Graphics g) {                                          public void print(Graphics g) {
# Line 821  public class StyledLayerUtil { Line 963  public class StyledLayerUtil {
963                                   */                                   */
964                                  final int fontHeight = new JLabel().getFontMetrics(                                  final int fontHeight = new JLabel().getFontMetrics(
965                                                  new JLabel().getFont()).getHeight();                                                  new JLabel().getFont()).getHeight();
966                                    
967                                  final Dimension ICON_SIZE = new Dimension(iconWidth,                                  final Dimension ICON_SIZE = new Dimension(iconWidth,
968                                                  fontHeight > 5 ? fontHeight : iconHeight);                                                  fontHeight > 5 ? fontHeight : iconHeight);
969    
# Line 842  public class StyledLayerUtil { Line 984  public class StyledLayerUtil {
984                                  hbox.add(iconLabel);                                  hbox.add(iconLabel);
985                                  hbox.add(Box.createHorizontalStrut(3));                                  hbox.add(Box.createHorizontalStrut(3));
986    
                                 // ****************************************************************************  
                                 // The labeltext is read from the SLD. Its either the title  
                                 // directly, or interpreted as OneLine Code  
                                 // ****************************************************************************  
                                 // final String rawText =  
                                 // rule.getDescription().getTitle().toString();  
                                 final String rawText = rule.getDescription().getTitle().toString();  
   
987                                  Translation labelT = new Translation();                                  Translation labelT = new Translation();
988                                  labelT.fromOneLine(rawText);                                  labelT.fromOneLine(rule.getDescription().getTitle());
989    
990                                  final JLabel classTitleLabel = new JLabel(labelT.toString());                                  final JLabel classTitleLabel = new JLabel(labelT.toString());
991                                  hbox.add(classTitleLabel);                                  hbox.add(classTitleLabel);
992                                  classTitleLabel.setLabelFor(iconLabel);                                  classTitleLabel.setLabelFor(iconLabel);
993    
994                                  box.add(hbox);                                  box.add(hbox);
995    
# Line 865  public class StyledLayerUtil { Line 999  public class StyledLayerUtil {
999                  return box;                  return box;
1000          }          }
1001    
   
1002          /**          /**
1003           * Creates a           * Creates a
1004           * @param styledGrid           *
1005           * @param iconHeight           * @param styledRaster
1006           * @param iconWidth           * @param iconHeight
1007             * @param iconWidth
1008           * @return           * @return
1009           */           */
1010          public static Box createLegendPanel(StyledRasterInterface<?> styledGrid, int iconWidth, int iconHeight) {          public static Box createLegendPanel(StyledRasterInterface<?> styledRaster,
1011                  throw new RuntimeException("Not yet...");                          int iconWidth, int iconHeight) {
1012    
1013                    /**
1014                     * Determine whether a Style is responsible for the coloring
1015                     */
1016                    ColorModel colorModel = null;
1017                    if (!isStyleable(styledRaster)
1018                                    || (isStyleable(styledRaster) && styledRaster.getStyle() == null)) {
1019                            colorModel = getColorModel(styledRaster);
1020                    }
1021    
1022                    RasterLegendData rasterLegendData = styledRaster.getLegendMetaData();
1023                    List<Double> legendRasterValues = rasterLegendData.getSortedKeys();
1024                    Map<Double, GridCoverage2D> sampleRasters = rasterLegendData
1025                                    .createSampleRasters();
1026    
1027                    Box box = new Box(BoxLayout.Y_AXIS) {
1028    
1029                            /**
1030                             * Nuetzlich wenn die Componente gedruckt (z.B. wenn ein Screenshot
1031                             * gemacht wird) wird. Dann werden wird der Hintergrund auf WEISS
1032                             * gesetzt.
1033                             */
1034                            @Override
1035                            public void print(Graphics g) {
1036                                    final Color orig = getBackground();
1037                                    setBackground(Color.WHITE);
1038                                    // wrap in try/finally so that we always restore the state
1039                                    try {
1040                                            super.print(g);
1041                                    } finally {
1042                                            setBackground(orig);
1043                                    }
1044                            }
1045                    };
1046    
1047                    for (Double rValue : legendRasterValues) {
1048    
1049                            /**
1050                             *
1051                             */
1052                            Box hbox = new Box(BoxLayout.X_AXIS) {
1053    
1054                                    /**
1055                                     * Nuetzlich wenn die Componente gedruckt (z.B. wenn ein
1056                                     * Screenshot gemacht wird) wird. Dann werden wird der
1057                                     * Hintergrund auf WEISS gesetzt.
1058                                     */
1059                                    @Override
1060                                    public void print(Graphics g) {
1061                                            final Color orig = getBackground();
1062                                            setBackground(Color.WHITE);
1063                                            // wrap in try/finally so that we always restore the
1064                                            // state
1065                                            try {
1066                                                    super.print(g);
1067                                            } finally {
1068                                                    setBackground(orig);
1069                                            }
1070                                    }
1071                            };
1072    
1073                            final Dimension ICON_SIZE = new Dimension(iconWidth,
1074                                            new JLabel().getFontMetrics(new JLabel().getFont())
1075                                                            .getHeight() > 5 ? new JLabel().getFontMetrics(
1076                                                            new JLabel().getFont()).getHeight() : iconHeight);
1077    
1078                            // ****************************************************************************
1079                            // Create the actual icon
1080                            // ****************************************************************************
1081                            BufferedImage buffImage = new BufferedImage(ICON_SIZE.width,
1082                                            ICON_SIZE.height, BufferedImage.TYPE_INT_ARGB);
1083                            Graphics2D graphics = buffImage.createGraphics();
1084    
1085                            if (colorModel != null) {
1086    
1087                                    try {
1088                                            Object inData = null;
1089                                            switch (colorModel.getTransferType()) {
1090                                            case DataBuffer.TYPE_BYTE:
1091                                                    inData = new byte[] { rValue.byteValue() };
1092                                                    break;
1093                                            case DataBuffer.TYPE_USHORT:
1094                                                    inData = new short[] { rValue.shortValue() };
1095                                                    break;
1096                                            case DataBuffer.TYPE_INT:
1097                                                    inData = new int[] { rValue.intValue() };
1098                                                    break;
1099                                            case DataBuffer.TYPE_SHORT:
1100                                                    inData = new short[] { rValue.shortValue() };
1101                                                    break;
1102                                            case DataBuffer.TYPE_FLOAT:
1103                                                    inData = new float[] { rValue.floatValue() };
1104                                                    break;
1105                                            case DataBuffer.TYPE_DOUBLE:
1106                                                    inData = new double[] { rValue.doubleValue() };
1107                                                    break;
1108                                            default:
1109                                                    inData = rValue.intValue();
1110                                            }
1111                                            final Color color = new Color(colorModel.getRGB(inData));
1112                                            graphics.setBackground(color);
1113                                            graphics.setColor(color);
1114                                            graphics.fillRect(0, 0, ICON_SIZE.width, ICON_SIZE.height);
1115                                    } catch (Exception e) {
1116                                            LOGGER.debug(
1117                                                            "Dann nehmen wir halt den GridCoverageRenderer", e);
1118                                            colorModel = null;
1119                                    }
1120                            }
1121    
1122                            if (colorModel == null) {
1123    
1124                                    /**
1125                                     * The coverage contains only one value of value rValue
1126                                     */
1127                                    GridCoverage2D sampleCov = sampleRasters.get(rValue);
1128                                    GridCoverageRenderer renderer;
1129                                    try {
1130                                            renderer = new GridCoverageRenderer(sampleCov
1131                                                            .getCoordinateReferenceSystem(), JTSUtil
1132                                                            .createEnvelope(sampleCov.getEnvelope()),
1133                                                            new Rectangle(iconWidth, iconHeight),
1134                                                            (AffineTransform) null);
1135                                    } catch (Exception e1) {
1136                                            throw new RuntimeException(
1137                                                            "Creating the GridCoverageRenderer:", e1);
1138                                    }
1139    
1140                                    /**
1141                                     * Iterate over all FeatureTypeStyles.
1142                                     */
1143                                    // for (FeatureTypeStyle ftStyle : styledGrid.getStyle()
1144                                    // .featureTypeStyles()) {
1145                                    // One child-node for every rule
1146                                    // List<Rule> rules = ftStyle.rules();
1147                                    // for (Rule rule : rules) {
1148                                    final Style style = styledRaster.getStyle();
1149                                    List<RasterSymbolizer> rSymbols = StylingUtil
1150                                                    .getRasterSymbolizers(style);
1151    
1152                                    for (RasterSymbolizer symbolizer : rSymbols) {
1153                                            // LOGGER.debug("Creating a new Legend Image for RUle
1154                                            // name =
1155                                            // "+rule.getName());
1156                                            try {
1157                                                    renderer.paint(graphics, sampleCov, symbolizer);
1158                                            } catch (Exception ee) {
1159                                                    LOGGER.error("Unable to paint " + symbolizer
1160                                                                    + " into the legend image", ee);
1161                                            }
1162                                            // }
1163                                            // }
1164                                    }
1165                            }
1166    
1167                            ImageIcon legendIcon = new ImageIcon(buffImage);
1168    
1169                            final JLabel iconLabel = new JLabel(legendIcon);
1170                            hbox.setAlignmentX(0f);
1171                            hbox.add(iconLabel);
1172                            hbox.add(Box.createHorizontalStrut(3));
1173    
1174                            Translation labelT = rasterLegendData.get(rValue);
1175                            final JLabel classTitleLabel = new JLabel(labelT.toString());
1176                            hbox.add(classTitleLabel);
1177                            classTitleLabel.setLabelFor(iconLabel);
1178    
1179                            box.add(hbox);
1180    
1181                            if (rasterLegendData.getPaintGaps()) {
1182                                    iconLabel
1183                                                    .setBorder(BorderFactory.createLineBorder(Color.black));
1184                                    box.add(Box.createVerticalStrut(3));
1185                            }
1186    
1187                    }
1188    
1189                    return box;
1190            }
1191    
1192            /**
1193             * Extracts the {@link ColorModel} of any {@link StyledRasterInterface}. May
1194             * return <code>null</code> if the geoobject can not be accessed.
1195             */
1196            @SuppressWarnings("unchecked")
1197            public static ColorModel getColorModel(StyledRasterInterface<?> styledGrid) {
1198                    ColorModel colorModel = null;
1199                    try {
1200                            Object geoObject = styledGrid.getGeoObject();
1201                            if (geoObject instanceof GridCoverage2D) {
1202                                    GridCoverage2D cov = (GridCoverage2D) geoObject;
1203                                    colorModel = cov.getRenderedImage().getColorModel();
1204                            } else if (styledGrid instanceof StyledRasterPyramidInterface) {
1205    
1206                                    Parameter readGG = new Parameter(
1207                                                    AbstractGridFormat.READ_GRIDGEOMETRY2D);
1208    
1209                                    ReferencedEnvelope mapExtend = new org.geotools.geometry.jts.ReferencedEnvelope(
1210                                                    styledGrid.getEnvelope(), styledGrid.getCrs());
1211    
1212                                    readGG.setValue(new GridGeometry2D(new GeneralGridEnvelope(
1213                                                    new Rectangle(0, 0, 1, 1)), mapExtend));
1214    
1215                                    FeatureCollection<SimpleFeatureType, SimpleFeature> rFc = (FeatureCollection<SimpleFeatureType, SimpleFeature>) geoObject;
1216    
1217                                    final AbstractGridCoverage2DReader aReader = (AbstractGridCoverage2DReader) FeatureUtil
1218                                                    .getWrappedGeoObject(rFc);
1219                                    GridCoverage2D cov = (GridCoverage2D) aReader
1220                                                    .read(new GeneralParameterValue[] { readGG });
1221                                    colorModel = cov.getRenderedImage().getColorModel();
1222                            }
1223                    } catch (Exception e) {
1224                            LOGGER.error("Error reading the colormodel from " + styledGrid, e);
1225                            return null;
1226                    }
1227                    return colorModel;
1228          }          }
1229    
1230            /**
1231             * @return <code>true</code> if a {@link RasterSymbolizer} can be applied
1232             *         and will have an effect. Some rasters (e.g. GeoTIFF) can come
1233             *         with their own {@link ColorModel} and will ignore any
1234             *         {@link RasterSymbolizer} = SLD.
1235             */
1236            public static boolean isStyleable(StyledRasterInterface<?> styledRaster) {
1237                    ColorModel colorModel = getColorModel(styledRaster);
1238    
1239                    LOGGER.info("The colormodel of " + styledRaster.getTitle() + " is "
1240                                    + colorModel.getClass().getSimpleName());
1241    
1242                    if (colorModel == null)
1243                            return true;
1244                    if (colorModel instanceof ComponentColorModel)
1245                            return true;
1246                    return false;
1247            }
1248  }  }

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26