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

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

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

trunk/src/skrueger/geotools/StyledMapUtil.java revision 43 by alfonx, Tue Apr 14 14:19:30 2009 UTC branches/1.0-gt2-2.6/src/skrueger/geotools/StyledLayerUtil.java revision 315 by mojays, Wed Aug 26 11:03:27 2009 UTC
# Line 1  Line 1 
1  package skrueger.geotools;  /*******************************************************************************
2     * Copyright (c) 2009 Martin O. J. Schmitz.
3  import java.text.DecimalFormat;   *
4  import java.util.Map;   * This file is part of the SCHMITZM library - a collection of utility
5  import java.util.HashMap;   * classes based on Java 1.6, focusing (not only) on Java Swing
6  import java.util.List;   * and the Geotools library.
7  import java.net.URL;   *
8     * The SCHMITZM project is hosted at:
9  import org.geotools.feature.FeatureCollection;   * http://wald.intevation.org/projects/schmitzm/
10  import org.geotools.map.MapLayer;   *
11  import org.geotools.map.DefaultMapLayer;   * This program is free software; you can redistribute it and/or
12  import org.geotools.coverage.grid.GridCoverage2D;   * modify it under the terms of the GNU Lesser General Public License
13  import org.geotools.coverage.grid.io.AbstractGridCoverage2DReader;   * as published by the Free Software Foundation; either version 3
14  import org.geotools.data.FeatureSource;   * of the License, or (at your option) any later version.
15  import org.geotools.styling.ColorMap;   *
16  import org.geotools.styling.ColorMapEntry;   * This program is distributed in the hope that it will be useful,
17  import org.geotools.styling.Style;   * but WITHOUT ANY WARRANTY; without even the implied warranty of
18     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  import org.apache.log4j.Logger;   * GNU General Public License for more details.
20     *
21  import org.jdom.Element;   * You should have received a copy of the GNU Lesser General Public License (license.txt)
22  import org.jdom.Document;   * along with this program; if not, write to the Free Software
23  import org.jdom.input.SAXBuilder;   * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
24  import org.jdom.output.XMLOutputter;   * or try this link: http://www.gnu.org/licenses/lgpl.html
25     *
26  import schmitzm.geotools.styling.StylingUtil;   * Contributors:
27  import skrueger.AttributeMetaData;   *     Martin O. J. Schmitz - initial API and implementation
28  import skrueger.RasterLegendData;   *     Stefan A. Krüger - additional utility classes
29  import skrueger.i8n.Translation;   ******************************************************************************/
30  import schmitzm.io.IOUtil;  package skrueger.geotools;
31  import java.io.File;  
32  import java.io.FileNotFoundException;  import java.io.File;
33  import schmitzm.lang.LangUtil;  import java.io.FileNotFoundException;
34  import schmitzm.swing.SwingUtil;  import java.io.FileWriter;
35    import java.net.URL;
36  import java.io.FileWriter;  import java.text.DecimalFormat;
37    import java.util.HashMap;
38  /**  import java.util.List;
39   * This class provides static helper methods for dealing with  import java.util.Map;
40   * {@link StyledMapInterface} stuff.  import java.util.SortedMap;
41   * @author <a href="mailto:[email protected]">Martin Schmitz</a> (University of Bonn/Germany)  import java.util.TreeMap;
42   * @version 1.0  
43   */  import org.apache.log4j.Logger;
44  public class StyledMapUtil {  import org.geotools.coverage.grid.GridCoverage2D;
45    private static final Logger LOGGER = Logger.getLogger(StyledMapUtil.class.getName());  import org.geotools.coverage.grid.io.AbstractGridCoverage2DReader;
46    private static final SAXBuilder SAX_BUILDER = new SAXBuilder();  import org.geotools.feature.FeatureCollection;
47    private static final XMLOutputter XML_OUTPUTTER = new XMLOutputter();  import org.geotools.map.DefaultMapLayer;
48    import org.geotools.map.MapLayer;
49    /** URL for Atlas XML schema */  import org.geotools.styling.ColorMap;
50    public static final String AMLURI = "http://www.wikisquare.de/AtlasML";  import org.geotools.styling.ColorMapEntry;
51    /** Name of the XML Element for the attribute meta data map */  import org.geotools.styling.RasterSymbolizer;
52    public static final String ELEM_NAME_AMD = "attributeMetaData";  import org.geotools.styling.Style;
53    /** Name of the XML Element for the raster legend data */  import org.jdom.Document;
54    public static final String ELEM_NAME_RLD = "rasterLegendData";  import org.jdom.Element;
55    /** Name of the XML Element for an attribute meta data map entry */  import org.jdom.input.SAXBuilder;
56    public static final String ELEM_NAME_ATTRIBUTE = "dataAttribute";  import org.jdom.output.XMLOutputter;
57    /** Name of the XML Element for an raster legend data entry */  
58    public static final String ELEM_NAME_RASTERLEGEND = "rasterLegendItem";  import schmitzm.geotools.styling.StylingUtil;
59    /** Name of the XML Element for a translation */  import schmitzm.io.IOUtil;
60    public static final String ELEM_NAME_TRANSLATION = "translation";  import schmitzm.lang.LangUtil;
61    import schmitzm.swing.SwingUtil;
62    /**  import skrueger.AttributeMetaData;
63     * Creates a Geotools {@link MapLayer} from an object. If the object is a  import skrueger.RasterLegendData;
64     * {@link StyledMapInterface} then its sytle is used. In case of direct  import skrueger.i8n.Translation;
65     * Geotools objects ({@link GridCoverage2D}, {@link AbstractGridCoverage2DReader},  
66     * {@link FeatureCollection}) a default style is generated.  /**
67     * @param object an Object   * This class provides static helper methods for dealing with
68     * @exception Exception if {@code null} is given as object or an error occurs during layer creation   * {@link StyledLayerInterface} stuff.
69     */   * @author <a href="mailto:[email protected]">Martin Schmitz</a> (University of Bonn/Germany)
70    public static MapLayer createMapLayer(Object object) throws Exception {   * @version 1.0
71      return createMapLayer(object,null);   */
72    }  public class StyledLayerUtil {
73      private static final Logger LOGGER = Logger.getLogger(StyledLayerUtil.class.getName());
74    /**    private static final SAXBuilder SAX_BUILDER = new SAXBuilder();
75     * Creates a Geotools {@link MapLayer} from an object. If the object is a    private static final XMLOutputter XML_OUTPUTTER = new XMLOutputter();
76     * {@link StyledMapInterface} then its sytle is used. In case of direct  
77     * Geotools objects ({@link GridCoverage2D}, {@link AbstractGridCoverage2DReader},    /** URL for Atlas XML schema */
78     * {@link FeatureCollection}) a default style is generated.    public static final String AMLURI = "http://www.wikisquare.de/AtlasML";
79     * @param object an Object    /** Name of the XML Element for the attribute meta data map */
80     * @param forcedStyle (SLD-)Style to force for the object    public static final String ELEM_NAME_AMD = "attributeMetaData";
81     * @exception Exception if {@code null} is given as object or an error occurs during layer creation    /** Name of the XML Element for the raster legend data */
82     */    public static final String ELEM_NAME_RLD = "rasterLegendData";
83    public static MapLayer createMapLayer(Object object, Style forcedStyle) throws Exception {    /** Name of the XML Element for an attribute meta data map entry */
84      MapLayer layer     = null;    public static final String ELEM_NAME_ATTRIBUTE = "dataAttribute";
85      Style    style     = null;    /** Name of the XML Element for an raster legend data entry */
86      if ( object instanceof StyledMapInterface ) {    public static final String ELEM_NAME_RASTERLEGEND = "rasterLegendItem";
87        style =  ((StyledMapInterface<?>)object).getStyle();    /** Name of the XML Element for a translation */
88        object = ((StyledMapInterface<?>)object).getGeoObject();    public static final String ELEM_NAME_TRANSLATION = "translation";
89      }  
90      if ( forcedStyle != null )    /**
91        style = forcedStyle;     * Creates a Geotools {@link MapLayer} from an object. If the object is a
92      if ( style == null )     * {@link StyledLayerInterface} then its sytle is used. In case of direct
93        style = StylingUtil.createDefaultStyle(object);     * Geotools objects ({@link GridCoverage2D}, {@link AbstractGridCoverage2DReader},
94       * {@link FeatureCollection}) a default style is generated.
95      if (object instanceof GridCoverage2D)     * @param object an Object
96        layer = new DefaultMapLayer( (GridCoverage2D) object, style);     * @exception Exception if {@code null} is given as object or an error occurs during layer creation
97      if (object instanceof AbstractGridCoverage2DReader)     */
98        layer = new DefaultMapLayer( (AbstractGridCoverage2DReader) object, style);    public static MapLayer createMapLayer(Object object) throws Exception {
99      if (object instanceof FeatureCollection)      return createMapLayer(object,null);
100        layer = new DefaultMapLayer( (FeatureCollection) object, style);    }
101    
102      if ( layer == null )    /**
103        throw new Exception("Can not create MapLayer from "+(object == null ? "null" : object.getClass()));     * Creates a Geotools {@link MapLayer} from an object. If the object is a
104       * {@link StyledLayerInterface} then its sytle is used. In case of direct
105      return layer;     * Geotools objects ({@link GridCoverage2D}, {@link AbstractGridCoverage2DReader},
106    }     * {@link FeatureCollection}) a default style is generated.
107       * @param object an Object
108    /**     * @param forcedStyle (SLD-)Style to force for the object
109     * Creates an default instance of {@link StyledMapInterface} for a Geotools     * @exception Exception if {@code null} is given as object or an error occurs during layer creation
110     * object ({@link GridCoverage2D}, {@link FeatureCollection}) with a default     */
111     * style.    public static MapLayer createMapLayer(Object object, Style forcedStyle) throws Exception {
112     * @param object an Object      MapLayer layer     = null;
113     * @param title  title for the object      Style    style     = null;
114     * @exception UnsupportedOperationException if {@code null} is given as object or an error occurs during creation      if ( object instanceof StyledLayerInterface ) {
115     */        style =  ((StyledLayerInterface<?>)object).getStyle();
116    public static StyledMapInterface<?> createStyledMap(Object object, String title) {        object = ((StyledLayerInterface<?>)object).getGeoObject();
117       return createStyledMap(object, title, null);      }
118    }      if ( forcedStyle != null )
119          style = forcedStyle;
120    /**      if ( style == null )
121     * Creates an default instance of {@link StyledMapInterface} for a Geotools        style = StylingUtil.createDefaultStyle(object);
122     * object ({@link GridCoverage2D}, {@link FeatureCollection}) with a given  
123     * style.      if (object instanceof GridCoverage2D)
124     * @param object an Object        layer = new DefaultMapLayer( (GridCoverage2D) object, style);
125     * @param title  title for the object      if (object instanceof AbstractGridCoverage2DReader)
126     * @param style  style and meta data for the object        layer = new DefaultMapLayer( (AbstractGridCoverage2DReader) object, style);
127     * @exception UnsupportedOperationException if {@code null} is given as object or an error occurs during creation      if (object instanceof FeatureCollection)
128     */        layer = new DefaultMapLayer( (FeatureCollection) object, style);
129    public static StyledMapInterface<?> createStyledMap(Object object, String title, StyledMapStyle style) {  
130      StyledMapInterface<?> styledObject = null;      if ( layer == null )
131          throw new Exception("Can not create MapLayer from "+(object == null ? "null" : object.getClass()));
132      String id = (title != null) ? title : "defaultID";  
133        return layer;
134      if ( object instanceof GridCoverage2D )    }
135        styledObject = new StyledGridCoverage(  
136            (GridCoverage2D)object,    /**
137            id,     * Creates an default instance of {@link StyledLayerInterface} for a Geotools
138            title,     * object ({@link GridCoverage2D}, {@link FeatureCollection}) with a default
139            style     * style.
140        );     * @param object an Object
141      else if ( object instanceof AbstractGridCoverage2DReader )     * @param title  title for the object
142             styledObject = new StyledGridCoverageReader(     * @exception UnsupportedOperationException if {@code null} is given as object or an error occurs during creation
143                 (AbstractGridCoverage2DReader)object,     */
144                 id,    public static StyledLayerInterface<?> createStyledLayer(Object object, String title) {
145                 title,       return createStyledLayer(object, title, null);
146                 style    }
147             );  
148      else if ( object instanceof FeatureCollection )    /**
149        styledObject = new StyledFeatureCollection(     * Creates an default instance of {@link StyledLayerInterface} for a Geotools
150            (FeatureCollection)object,     * object ({@link GridCoverage2D}, {@link FeatureCollection}) with a given
151            id,     * style.
152            title,     * @param object an Object
153            style     * @param title  title for the object
154        );     * @param style  style and meta data for the object
155           * @exception UnsupportedOperationException if {@code null} is given as object or an error occurs during creation
156      if ( styledObject == null )     */
157        throw new UnsupportedOperationException("Can not create StyledMapInterface object from "+(object == null ? "null" : object.getClass()));    public static StyledLayerInterface<?> createStyledLayer(Object object, String title, StyledLayerStyle style) {
158        StyledLayerInterface<?> styledLayer = null;
159      return styledObject;  
160    }      String id = (title != null) ? title : "defaultID";
161    
162    /**      if ( object instanceof GridCoverage2D )
163     * Parses a {@link AttributeMetaData} object from an JDOM-{@link Element}.        styledLayer = new StyledGridCoverage(
164     * This method works like {@link AMLImport#parseDataAttribute(org.w3c.dom.Node},            (GridCoverage2D)object,
165     * but for JDOM.            id,
166     * @param element {@link Element} to parse            title,
167     */            style
168    public static AttributeMetaData parseAttributeMetaData(final Element element) {        );
169      final Integer col = Integer.valueOf(element.getAttributeValue("col"));      else if ( object instanceof AbstractGridCoverage2DReader )
170      final Boolean visible = Boolean.valueOf(element.getAttributeValue("visible"));             styledLayer = new StyledGridCoverageReader(
171      final String unit = element.getAttributeValue("unit");                 (AbstractGridCoverage2DReader)object,
172                   id,
173      Translation name = new Translation();                 title,
174      Translation desc = new Translation();                 style
175      for (final Element childElement : (List<Element>)element.getChildren()) {             );
176        if (childElement.getName() == null)      else if ( object instanceof FeatureCollection )
177          continue;        styledLayer = new StyledFeatureCollection(
178              (FeatureCollection)object,
179        if (childElement.getName().equals("name"))            id,
180          name = parseTranslation(childElement);            title,
181        else if (childElement.getName().equals("desc"))            style
182          desc = parseTranslation(childElement);        );
183      }      
184      return new AttributeMetaData(col, visible, name, desc, unit);      if ( styledLayer == null )
185    }        throw new UnsupportedOperationException("Can not create StyledLayerInterface object from "+(object == null ? "null" : object.getClass()));
186    
187    /**      return styledLayer;
188     * Parses a {@link AttributeMetaData} map from an JDOM-{@link Element}    }
189     * with {@code <attribute>}-childs.  
190     * @param element {@link Element} to parse    /**
191     */     * Return only the visible or invisible entries of an AttributeMetaData-Map.
192    public static Map<Integer,AttributeMetaData> parseAttributeMetaDataMap(final Element element) {     * @param amdMap AttributeMetaData-Map
193      HashMap<Integer,AttributeMetaData> metaData = new HashMap<Integer,AttributeMetaData>();     * @param visible indicated whether the visible or invisible entries are
194      List<Element> attributesElements = element.getChildren( ELEM_NAME_ATTRIBUTE );     *                returned
195      for (Element attibuteElement : attributesElements)     */
196      {    public static SortedMap<Integer,AttributeMetaData> getVisibleAttributeMetaData(Map<Integer,AttributeMetaData> amdMap, boolean visible) {
197        AttributeMetaData attrMetaData = parseAttributeMetaData( attibuteElement );      SortedMap<Integer,AttributeMetaData> filteredMap = new TreeMap<Integer,AttributeMetaData>();
198        metaData.put( attrMetaData.getColIdx(), attrMetaData );      for (AttributeMetaData amd : amdMap.values())
199      }        if ( amd.isVisible() )
200      return metaData;          filteredMap.put(amd.getColIdx(), amd);
201    }      
202        return filteredMap;
203    /**    }
204     * Loads a {@link AttributeMetaData} object from an URL.    
205     * @param documentUrl {@link URL} to parse    
206     * @see #parseAttributeMetaData(Element)    /**
207     */     * Parses a {@link AttributeMetaData} object from an JDOM-{@link Element}.
208    public static Map<Integer,AttributeMetaData> loadAttributeMetaDataMap(final URL documentUrl) throws Exception {     * This method works like {@link AMLImport#parseDataAttribute(org.w3c.dom.Node},
209      Document document = SAX_BUILDER.build(documentUrl);     * but for JDOM.
210      return parseAttributeMetaDataMap( document.getRootElement() );     * @param element {@link Element} to parse
211    }     */
212      public static AttributeMetaData parseAttributeMetaData(final Element element) {
213    /**      final Integer col = Integer.valueOf(element.getAttributeValue("col"));
214     * Creates an JDOM {@link Element} for the given {@link AttributeMetaData}      final Boolean visible = Boolean.valueOf(element.getAttributeValue("visible"));
215     * object.      final String unit = element.getAttributeValue("unit");
216     * @param amd meta data for one attribute  
217     */      Translation name = new Translation();
218    public static Element createAttributeMetaDataElement(final AttributeMetaData amd) {      Translation desc = new Translation();
219      final Element element = new Element( ELEM_NAME_ATTRIBUTE , AMLURI);      for (final Element childElement : (List<Element>)element.getChildren()) {
220      element.setAttribute("col", String.valueOf( amd.getColIdx() ) );        if (childElement.getName() == null)
221      element.setAttribute("visible", String.valueOf( amd.isVisible() ) );          continue;
222      element.setAttribute("unit", amd.getUnit() );  
223      // Creating a aml:name tag...        if (childElement.getName().equals("name"))
224      element.addContent( createTranslationElement("name", amd.getTitle()) );          name = parseTranslation(childElement);
225      // Creating a aml:desc tag...        else if (childElement.getName().equals("desc"))
226      element.addContent( createTranslationElement("desc", amd.getDesc()) );          desc = parseTranslation(childElement);
227      return element;      }
228    }      return new AttributeMetaData(col, visible, name, desc, unit);
229      }
230    /**  
231     * Creates an JDOM {@link Element} for the given {@link AttributeMetaData}    /**
232     * map.     * Parses a {@link AttributeMetaData} map from an JDOM-{@link Element}
233     * @param amdMap map of attribute meta data     * with {@code <attribute>}-childs.
234     */     * @param element {@link Element} to parse
235    public static Element createAttributeMetaDataMapElement(final Map<Integer,AttributeMetaData> amdMap) {     */
236      final Element element = new Element( ELEM_NAME_AMD , AMLURI);    public static Map<Integer,AttributeMetaData> parseAttributeMetaDataMap(final Element element) {
237      for (AttributeMetaData amd : amdMap.values())      HashMap<Integer,AttributeMetaData> metaData = new HashMap<Integer,AttributeMetaData>();
238        element.addContent( createAttributeMetaDataElement( amd ) );      List<Element> attributesElements = element.getChildren( ELEM_NAME_ATTRIBUTE );
239      return element;      for (Element attibuteElement : attributesElements)
240    }      {
241          AttributeMetaData attrMetaData = parseAttributeMetaData( attibuteElement );
242    /**        metaData.put( attrMetaData.getColIdx(), attrMetaData );
243     * Saves a {@link AttributeMetaData AttributeMetaData-Map} to an URL.      }
244     * @param amdMap map of {@link AttributeMetaData}      return metaData;
245     * @param documentUrl {@link URL} to store the XML    }
246     */  
247    public static void saveAttributeMetaDataMap(final Map<Integer,AttributeMetaData> amdMap, final URL documentUrl) throws Exception {    /**
248      // Create XML-Document     * Loads a {@link AttributeMetaData} object from an URL.
249      final FileWriter out = new FileWriter( new File(documentUrl.toURI()) );     * @param documentUrl {@link URL} to parse
250      XML_OUTPUTTER.output(     * @see #parseAttributeMetaData(Element)
251        createAttributeMetaDataMapElement(amdMap),     */
252        out    public static Map<Integer,AttributeMetaData> loadAttributeMetaDataMap(final URL documentUrl) throws Exception {
253      );      Document document = SAX_BUILDER.build(documentUrl);
254      out.flush();      return parseAttributeMetaDataMap( document.getRootElement() );
255      out.close();    }
256    }  
257      /**
258       * Creates an JDOM {@link Element} for the given {@link AttributeMetaData}
259       * object.
260    /**     * @param amd meta data for one attribute
261     * Parses a {@link RasterLegendData} object from an JDOM-{@link Element}.     */
262     * This method works like {@link AMLImport#parseRasterLegendData(org.w3c.dom.Node},    public static Element createAttributeMetaDataElement(final AttributeMetaData amd) {
263     * but for JDOM.      final Element element = new Element( ELEM_NAME_ATTRIBUTE , AMLURI);
264     * @param element {@link Element} to parse      element.setAttribute("col", String.valueOf( amd.getColIdx() ) );
265     */      element.setAttribute("visible", String.valueOf( amd.isVisible() ) );
266    public static RasterLegendData parseRasterLegendData(Element element) {      element.setAttribute("unit", amd.getUnit() );
267        // Creating a aml:name tag...
268      final boolean paintGaps = Boolean.valueOf( element.getAttributeValue("paintGaps") );      element.addContent( createTranslationElement("name", amd.getTitle()) );
269        // Creating a aml:desc tag...
270      RasterLegendData rld = new RasterLegendData(paintGaps);      element.addContent( createTranslationElement("desc", amd.getDesc()) );
271        return element;
272      for ( Element childElement : (List<Element>)element.getChildren() ) {    }
273        final String name = childElement.getName();  
274        // Cancel if it's an attribute    /**
275        if ( childElement.getChildren().size() == 0 )     * Creates an JDOM {@link Element} for the given {@link AttributeMetaData}
276          continue;     * map.
277       * @param amdMap map of attribute meta data
278        if (name.equals( ELEM_NAME_RASTERLEGEND )) {     */
279          final String valueAttr = childElement.getAttributeValue("value");    public static Element createAttributeMetaDataMapElement(final Map<Integer,AttributeMetaData> amdMap) {
280          if ( valueAttr == null )      final Element element = new Element( ELEM_NAME_AMD , AMLURI);
281            throw new UnsupportedOperationException("Attribute 'value' missing for definition of <"+ELEM_NAME_RASTERLEGEND+">");      for (AttributeMetaData amd : amdMap.values())
282          final double value = Double.valueOf(valueAttr);        element.addContent( createAttributeMetaDataElement( amd ) );
283        return element;
284          // first and only item should be the label    }
285          final Element labelElement = childElement.getChild("label");  
286          // id label element is missing, the translation is searched directly    /**
287          // as childs of the rasterLegendItem element     * Saves a {@link AttributeMetaData AttributeMetaData-Map} to an URL.
288          Translation label = parseTranslation( labelElement != null ? labelElement : childElement );     * @param amdMap map of {@link AttributeMetaData}
289          rld.put(value, label);     * @param documentUrl {@link URL} to store the XML
290        }     */
291      }    public static void saveAttributeMetaDataMap(final Map<Integer,AttributeMetaData> amdMap, final URL documentUrl) throws Exception {
292        // Create XML-Document
293      return rld;      final FileWriter out = new FileWriter( new File(documentUrl.toURI()) );
294    }      XML_OUTPUTTER.output(
295          createAttributeMetaDataMapElement(amdMap),
296    /**        out
297     * Loads a {@link RasterLegendData} object from an URL.      );
298     * @param documentUrl {@link URL} to parse      out.flush();
299     * @see #parseAttributeMetaData(Element)      out.close();
300     */    }
301    public static RasterLegendData loadRasterLegendData(final URL documentUrl) throws Exception {  
302      Document document = SAX_BUILDER.build(documentUrl);  
303      return parseRasterLegendData( document.getRootElement() );  
304    }    /**
305       * Parses a {@link RasterLegendData} object from an JDOM-{@link Element}.
306   /**     * This method works like {@link AMLImport#parseRasterLegendData(org.w3c.dom.Node},
307     * Creates an JDOM {@link Element} for the given {@link RasterLegendData}     * but for JDOM.
308     * map.     * @param element {@link Element} to parse
309     * @param rld raster legend data     */
310     */    public static RasterLegendData parseRasterLegendData(Element element) {
311    public static Element createRasterLegendDataElement(final RasterLegendData rld) {  
312      final Element element = new Element( ELEM_NAME_RLD , AMLURI);      final boolean paintGaps = Boolean.valueOf( element.getAttributeValue("paintGaps") );
313      element.setAttribute("paintGaps", rld.isPaintGaps().toString());  
314      for (Double key : rld.getSortedKeys()) {      RasterLegendData rld = new RasterLegendData(paintGaps);
315        Element item = new Element( ELEM_NAME_RASTERLEGEND, AMLURI);  
316        item.setAttribute("value", key.toString());      for ( Element childElement : (List<Element>)element.getChildren() ) {
317        item.addContent( createTranslationElement("label", rld.get(key)) );        final String name = childElement.getName();
318        element.addContent(item);        // Cancel if it's an attribute
319      }        if ( childElement.getChildren().size() == 0 )
320      return element;          continue;
321    }  
322          if (name.equals( ELEM_NAME_RASTERLEGEND )) {
323    /**          final String valueAttr = childElement.getAttributeValue("value");
324     * Creates {@link RasterLegendData} from a {@link ColorMap}.          if ( valueAttr == null )
325     * @param colorMap  a color map            throw new UnsupportedOperationException("Attribute 'value' missing for definition of <"+ELEM_NAME_RASTERLEGEND+">");
326     * @param paintGaps indicated whether gaps are painted between the legend items          final double value = Double.valueOf(valueAttr);
327     * @param digits    number of digits the grid value classes (and legend) are  
328     *                  rounded to (null means no round; >= 0 means digits after comma;          // first and only item should be the label
329     *                  < 0 means digits before comma)    */          final Element labelElement = childElement.getChild("label");
330    public static RasterLegendData generateRasterLegendData(ColorMap colorMap, boolean paintGaps, Integer digits) {          // id label element is missing, the translation is searched directly
331      DecimalFormat    decFormat = digits != null ? new DecimalFormat( SwingUtil.getNumberFormatPattern(digits) ) : null;          // as childs of the rasterLegendItem element
332      RasterLegendData rld       = new RasterLegendData(paintGaps);          Translation label = parseTranslation( labelElement != null ? labelElement : childElement );
333      for (ColorMapEntry cme : colorMap.getColorMapEntries())          rld.put(value, label);
334      {        }
335        double value = StylingUtil.getQuantityFromColorMapEntry(cme);      }
336        String label = cme.getLabel();  
337        // if no label is set (e.g. quantitative style),      return rld;
338        // use the value as label    }
339        if ( label == null || label.equals("") )  
340          if ( digits == null )    /**
341            label = String.valueOf(value);     * Loads a {@link RasterLegendData} object from an URL.
342          else     * @param documentUrl {@link URL} to parse
343            label = decFormat.format( LangUtil.round(value, digits) );     * @see #parseAttributeMetaData(Element)
344        rld.put( value, new Translation("   "+label) );     */
345      }    public static RasterLegendData loadRasterLegendData(final URL documentUrl) throws Exception {
346      return rld;      Document document = SAX_BUILDER.build(documentUrl);
347    }      return parseRasterLegendData( document.getRootElement() );
348      }
349    /**  
350     * Creates {@link RasterLegendData} from the {@link ColorMap} of a style.   /**
351     * @param style     a raster style (must contain a  {@link RasterSymbolizer})     * Creates an JDOM {@link Element} for the given {@link RasterLegendData}
352     * @param paintGaps indicated whether gaps are painted between the legend items     * map.
353     * @param digits    number of digits the grid value classes (and legend) are     * @param rld raster legend data
354     *                  rounded to (null means no round; >= 0 means digits after comma;     */
355     *                  < 0 means digits before comma)    */    public static Element createRasterLegendDataElement(final RasterLegendData rld) {
356    public static RasterLegendData generateRasterLegendData(Style style, boolean paintGaps, Integer digits) {      final Element element = new Element( ELEM_NAME_RLD , AMLURI);
357      ColorMap colorMap = StylingUtil.getColorMapFromStyle(style);      element.setAttribute("paintGaps", rld.isPaintGaps().toString());
358      if ( colorMap == null)      for (Double key : rld.getSortedKeys()) {
359        throw new IllegalArgumentException("Color map can not be determined from style!");        Element item = new Element( ELEM_NAME_RASTERLEGEND, AMLURI);
360      return generateRasterLegendData(colorMap, paintGaps, digits);        item.setAttribute("value", key.toString());
361    }        item.addContent( createTranslationElement("label", rld.get(key)) );
362          element.addContent(item);
363    /**      }
364     * Saves a {@link RasterLegendData} to an URL.      return element;
365     * @param rld raster legend data    }
366     * @param documentUrl {@link URL} to store the XML  
367     */    /**
368    public static void saveRasterLegendData(final RasterLegendData rld, final URL documentUrl) throws Exception {     * Creates {@link RasterLegendData} from a {@link ColorMap}.
369      // Create XML-Document     * @param colorMap  a color map
370      final FileWriter out = new FileWriter( new File(documentUrl.toURI()) );     * @param paintGaps indicated whether gaps are painted between the legend items
371      XML_OUTPUTTER.output(     * @param digits    number of digits the grid value classes (and legend) are
372        createRasterLegendDataElement(rld),     *                  rounded to (null means no round; >= 0 means digits after comma;
373        out     *                  < 0 means digits before comma)    */
374      );    public static RasterLegendData generateRasterLegendData(ColorMap colorMap, boolean paintGaps, Integer digits) {
375      out.flush();      DecimalFormat    decFormat = digits != null ? new DecimalFormat( SwingUtil.getNumberFormatPattern(digits) ) : null;
376      out.close();      RasterLegendData rld       = new RasterLegendData(paintGaps);
377    }      for (ColorMapEntry cme : colorMap.getColorMapEntries())
378        {
379    /**        double value = StylingUtil.getQuantityFromColorMapEntry(cme);
380     * Parses a {@link Translation} object from an JDOM-{@link Element}.        String label = cme.getLabel();
381     * This method works like {@link AMLImport#parseTranslation(org.w3c.dom.Node},        // if no label is set (e.g. quantitative style),
382     * but for JDOM.        // use the value as label
383     * @param element {@link Element} to parse        if ( label == null || label.equals("") )
384     */          if ( digits == null )
385    public final static Translation parseTranslation(final Element element) {            label = String.valueOf(value);
386      Translation trans = new Translation();          else
387              label = decFormat.format( LangUtil.round(value, digits) );
388      if (element == null)        rld.put( value, new Translation("   "+label) );
389       return trans;      }
390        return rld;
391      for (final Element translationElement : (List<Element>)element.getChildren()) {    }
392        final String name = translationElement.getName();  
393        if (name == null)    /**
394          continue;     * Creates {@link RasterLegendData} from the {@link ColorMap} of a style.
395       * @param style     a raster style (must contain a  {@link RasterSymbolizer})
396        // lang attribute     * @param paintGaps indicated whether gaps are painted between the legend items
397        String lang = translationElement.getAttributeValue("lang");     * @param digits    number of digits the grid value classes (and legend) are
398        // set the default, if no language code is set     *                  rounded to (null means no round; >= 0 means digits after comma;
399        if ( lang == null )     *                  < 0 means digits before comma)    */
400          lang = Translation.DEFAULT_KEY;    public static RasterLegendData generateRasterLegendData(Style style, boolean paintGaps, Integer digits) {
401        ColorMap colorMap = StylingUtil.getColorMapFromStyle(style);
402        final String translationText = translationElement.getValue();      if ( colorMap == null)
403        if (translationText == null)        throw new IllegalArgumentException("Color map can not be determined from style!");
404          trans.put(lang, "");      return generateRasterLegendData(colorMap, paintGaps, digits);
405        else    }
406          trans.put(lang, translationText);  
407      }    /**
408       * Saves a {@link RasterLegendData} to an URL.
409      // if no <translation> is given, the value of the node should     * @param rld raster legend data
410      // be used as a default translation     * @param documentUrl {@link URL} to store the XML
411      if (trans.size() == 0)     */
412        trans.put( Translation.DEFAULT_KEY, element.getValue() );    public static void saveRasterLegendData(final RasterLegendData rld, final URL documentUrl) throws Exception {
413      //     trans = new Translation( ((List<Element>)element.getChildren()).get(0).getValue() );      // Create XML-Document
414        final FileWriter out = new FileWriter( new File(documentUrl.toURI()) );
415      return trans;      XML_OUTPUTTER.output(
416    }        createRasterLegendDataElement(rld),
417          out
418    /**      );
419     * Creates an JDOM {@link Element} for the given {@link Translation}.      out.flush();
420     * @param tagname Name of the Element      out.close();
421     * @param translation Translation to store in the Element    }
422     */  
423    public final static Element createTranslationElement(String tagname, Translation translation) {    /**
424      Element element = new Element(tagname, AMLURI);     * Parses a {@link Translation} object from an JDOM-{@link Element}.
425      if ( translation == null )     * This method works like {@link AMLImport#parseTranslation(org.w3c.dom.Node},
426        throw new UnsupportedOperationException("Translation element can not be created from null!");     * but for JDOM.
427       * @param element {@link Element} to parse
428      // If only a default translation is set, the <translation lang="..">..</tranlation>     */
429      // part is not used    public final static Translation parseTranslation(final Element element) {
430      if (translation.keySet().size() == 1 && translation.get(Translation.DEFAULT_KEY) != null) {      Translation trans = new Translation();
431        element.addContent( translation.get(Translation.DEFAULT_KEY) );  
432        return element;      if (element == null)
433      }       return trans;
434    
435      // add a <translation lang="..">..</tranlation> part to the element for      for (final Element translationElement : (List<Element>)element.getChildren()) {
436      // all languages        final String name = translationElement.getName();
437      for (String lang : translation.keySet()) {        if (name == null)
438        Element translationElement = new Element( ELEM_NAME_TRANSLATION , AMLURI);          continue;
439        translationElement.setAttribute("lang", lang);  
440        String translationString = translation.get(lang);        // lang attribute
441        if (translationString == null)        String lang = translationElement.getAttributeValue("lang");
442         translationString = "";        // set the default, if no language code is set
443        translationElement.addContent( translationString );        if ( lang == null )
444        element.addContent(translationElement);          lang = Translation.DEFAULT_KEY;
445      }  
446          final String translationText = translationElement.getValue();
447      return element;        if (translationText == null)
448    }          trans.put(lang, "");
449          else
450            trans.put(lang, translationText);
451    /**      }
452     * Sets a style to {@link StyledMapInterface}.  
453     * @param styledObject a styled object      // if no <translation> is given, the value of the node should
454     * @param style a Style      // be used as a default translation
455     */      if (trans.size() == 0)
456    public static void setStyledMapStyle(StyledMapInterface styledObject, StyledMapStyle<?> style) {        trans.put( Translation.DEFAULT_KEY, element.getValue() );
457      // set SLD style      //     trans = new Translation( ((List<Element>)element.getChildren()).get(0).getValue() );
458      styledObject.setStyle( style.getGeoObjectStyle() );  
459      // set meta data      return trans;
460      if ( styledObject        instanceof StyledGridCoverageInterface &&    }
461           (style.getMetaData() instanceof RasterLegendData || style.getMetaData() == null) ) {  
462        RasterLegendData sourceRld = (RasterLegendData)style.getMetaData();    /**
463        RasterLegendData destRld = ((StyledGridCoverageInterface)styledObject).getLegendMetaData();     * Creates an JDOM {@link Element} for the given {@link Translation}.
464        if ( destRld != null && sourceRld != null ) {     * @param tagname Name of the Element
465          destRld.setPaintGaps(sourceRld.isPaintGaps());     * @param translation Translation to store in the Element
466          destRld.clear();     */
467          destRld.putAll( sourceRld );    public final static Element createTranslationElement(String tagname, Translation translation) {
468        }      Element element = new Element(tagname, AMLURI);
469        return;      if ( translation == null )
470      }        throw new UnsupportedOperationException("Translation element can not be created from null!");
471      if ( styledObject        instanceof StyledFeatureCollectionInterface &&  
472           (style.getMetaData() instanceof Map || style.getMetaData() == null) ) {      // If only a default translation is set, the <translation lang="..">..</tranlation>
473        Map<Integer, AttributeMetaData> sourceAmd = (Map<Integer, AttributeMetaData>)style.getMetaData();      // part is not used
474        Map<Integer, AttributeMetaData> destAmd   = ((StyledFeatureCollectionInterface)styledObject).getAttributeMetaDataMap();      if (translation.keySet().size() == 1 && translation.get(Translation.DEFAULT_KEY) != null) {
475        if ( destAmd != null && sourceAmd != null ) {        element.addContent( translation.get(Translation.DEFAULT_KEY) );
476          destAmd.clear();        return element;
477          destAmd.putAll( sourceAmd );      }
478        }  
479        return;      // add a <translation lang="..">..</tranlation> part to the element for
480      }      // all languages
481        for (String lang : translation.keySet()) {
482      throw new UnsupportedOperationException("Style is not compatible to object: " +        Element translationElement = new Element( ELEM_NAME_TRANSLATION , AMLURI);
483                                              (style.getMetaData() == null ? null : style.getMetaData().getClass().getSimpleName()) +        translationElement.setAttribute("lang", lang);
484                                              " <-> " +        String translationString = translation.get(lang);
485                                              (styledObject == null ? null : styledObject.getClass().getSimpleName()));        if (translationString == null)
486    }         translationString = "";
487          translationElement.addContent( translationString );
488    /**        element.addContent(translationElement);
489     * Returns the style a {@link StyledMapInterface} as a {@link StyledMapStyle}.      }
490     * @param styledObject a styled object  
491     * @return {@code StyledMapStyle<RasterLegendData>} for {@link StyledGridCoverageInterface}      return element;
492     *         or {@code StyledMapStyle<Map<Integer,AttributeMetaData>>} for    }
493     *         {@link StyledFeatureCollectionInterface}  
494     */  
495    public static StyledMapStyle<?> getStyledMapStyle(StyledMapInterface styledObject) {    /**
496      if ( styledObject instanceof StyledGridCoverageInterface )     * Sets a style to {@link StyledLayerInterface}.
497        return getStyledMapStyle( (StyledGridCoverageInterface)styledObject );     * @param styledObject a styled object
498      if ( styledObject instanceof StyledFeatureCollectionInterface )     * @param style a Style
499        return getStyledMapStyle( (StyledFeatureCollectionInterface)styledObject );     */
500      throw new UnsupportedOperationException("Unknown type of StyledMapInterface: "+(styledObject == null ? null : styledObject.getClass().getSimpleName()));    public static void setStyledLayerStyle(StyledLayerInterface styledObject, StyledLayerStyle<?> style) {
501    }      // set SLD style
502        styledObject.setStyle( style.getGeoObjectStyle() );
503    /**      // set meta data
504     * Returns the style and raster meta data of a {@link StyledGridCoverageInterface}      if ( styledObject        instanceof StyledGridCoverageInterface &&
505     * as a {@link StyledMapStyle}.           (style.getMetaData() instanceof RasterLegendData || style.getMetaData() == null) ) {
506     * @param styledGC a styled grid coverage        RasterLegendData sourceRld = (RasterLegendData)style.getMetaData();
507     */        RasterLegendData destRld = ((StyledGridCoverageInterface)styledObject).getLegendMetaData();
508    public static StyledMapStyle<RasterLegendData> getStyledMapStyle(StyledGridCoverageInterface styledGC) {        if ( destRld != null && sourceRld != null ) {
509      return new StyledMapStyle<RasterLegendData>(          destRld.setPaintGaps(sourceRld.isPaintGaps());
510        styledGC.getStyle(),          destRld.clear();
511        styledGC.getLegendMetaData()          destRld.putAll( sourceRld );
512      );        }
513    }        return;
514        }
515    /**      if ( styledObject        instanceof StyledFeatureCollectionInterface &&
516     * Returns the style and attribute meta data of a {@link StyledFeatureCollectionInterface}           (style.getMetaData() instanceof Map || style.getMetaData() == null) ) {
517     * as a {@link StyledMapStyle}.        Map<Integer, AttributeMetaData> sourceAmd = (Map<Integer, AttributeMetaData>)style.getMetaData();
518     * @param styledFC a styled feature collection        Map<Integer, AttributeMetaData> destAmd   = ((StyledFeatureCollectionInterface)styledObject).getAttributeMetaDataMap();
519     */        if ( destAmd != null && sourceAmd != null ) {
520    public static StyledMapStyle<Map<Integer,AttributeMetaData>> getStyledMapStyle(StyledFeatureCollectionInterface styledFC) {          destAmd.clear();
521      return new StyledMapStyle<Map<Integer,AttributeMetaData>>(          destAmd.putAll( sourceAmd );
522        styledFC.getStyle(),        }
523        styledFC.getAttributeMetaDataMap()        return;
524      );      }
525    }  
526        throw new UnsupportedOperationException("Style is not compatible to object: " +
527    /**                                              (style.getMetaData() == null ? null : style.getMetaData().getClass().getSimpleName()) +
528     * Loads a {@linkplain Style SLD-Style} and {@linkplain RasterLegendData Raster-LegendData}                                              " <-> " +
529     * for a given geo-object (raster) source. The SLD file must be present. A missing                                              (styledObject == null ? null : styledObject.getClass().getSimpleName()));
530     * raster legend-data file is tolerated.    }
531     * @param geoObjectURL URL of the (already read) raster object  
532     * @param sldExt file extention for the SLD file    /**
533     * @param rldExt file extention for the raster legend-data file     * Returns the style a {@link StyledLayerInterface} as a {@link StyledLayerStyle}.
534     * @return {@code null} in case of any error     * @param styledObject a styled object
535     */     * @return {@code StyledLayerStyle<RasterLegendData>} for {@link StyledGridCoverageInterface}
536    public static StyledMapStyle<RasterLegendData> loadStyledRasterStyle(URL geoObjectURL, String sldExt, String rldExt) {     *         or {@code StyledLayerStyle<Map<Integer,AttributeMetaData>>} for
537      RasterLegendData metaData = null;     *         {@link StyledFeatureCollectionInterface}
538      Style sldStyle = null;     */
539      try {    public static StyledLayerStyle<?> getStyledLayerStyle(StyledLayerInterface styledObject) {
540        Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(geoObjectURL, sldExt));      if ( styledObject instanceof StyledGridCoverageInterface )
541        // SLD must be present        return getStyledLayerStyle( (StyledGridCoverageInterface)styledObject );
542        if ( styles == null || styles.length == 0 )      if ( styledObject instanceof StyledFeatureCollectionInterface )
543          return null;        return getStyledLayerStyle( (StyledFeatureCollectionInterface)styledObject );
544        sldStyle = styles[0];      throw new UnsupportedOperationException("Unknown type of StyledLayerInterface: "+(styledObject == null ? null : styledObject.getClass().getSimpleName()));
545      }    }
546      catch (Exception err) {  
547        // SLD must be present    /**
548        LangUtil.logDebugError(LOGGER,err);     * Returns the style and raster meta data of a {@link StyledGridCoverageInterface}
549        return null;     * as a {@link StyledLayerStyle}.
550      }     * @param styledGC a styled grid coverage
551       */
552      try {    public static StyledLayerStyle<RasterLegendData> getStyledLayerStyle(StyledGridCoverageInterface styledGC) {
553        metaData = StyledMapUtil.loadRasterLegendData( IOUtil.changeUrlExt(geoObjectURL,rldExt) );      return new StyledLayerStyle<RasterLegendData>(
554      } catch (FileNotFoundException err) {        styledGC.getStyle(),
555        // ignore missing raster legend data        styledGC.getLegendMetaData()
556      } catch (Exception err) {      );
557        // any other error during legend data creation leads to error    }
558        LangUtil.logDebugError(LOGGER,err);  
559        return null;    /**
560      }     * Returns the style and attribute meta data of a {@link StyledFeatureCollectionInterface}
561      return new StyledMapStyle<RasterLegendData>(sldStyle, metaData);     * as a {@link StyledLayerStyle}.
562    }     * @param styledFC a styled feature collection
563       */
564    /**    public static StyledLayerStyle<Map<Integer,AttributeMetaData>> getStyledLayerStyle(StyledFeatureCollectionInterface styledFC) {
565     * Loads a {@linkplain Style SLD-Style} from a {@code .sld} file and      return new StyledLayerStyle<Map<Integer,AttributeMetaData>>(
566     * {@linkplain RasterLegendData Raster-LegendData} from a {@code .rld} file        styledFC.getStyle(),
567     * for a given geo-object (raster) source. The SLD file must be present. A missing        styledFC.getAttributeMetaDataMap()
568     * raster legend-data file is tolerated.      );
569     * @param geoObjectURL URL of the (already read) raster object    }
570     * @param sldExt file extention for the SLD file  
571     * @param rldExt file extention for the raster legend-data file    /**
572     * @return {@code null} in case of any error     * Loads a {@linkplain Style SLD-Style} and {@linkplain RasterLegendData Raster-LegendData}
573     */     * for a given geo-object (raster) source. The SLD file must be present. A missing
574    public static StyledMapStyle<RasterLegendData> loadStyledRasterStyle(URL geoObjectURL) {     * raster legend-data file is tolerated.
575      return loadStyledRasterStyle(geoObjectURL, "sld", "rld");     * @param geoObjectURL URL of the (already read) raster object
576    }     * @param sldExt file extention for the SLD file
577       * @param rldExt file extention for the raster legend-data file
578    /**     * @return {@code null} in case of any error
579     * Loads a {@linkplain Style SLD-Style} and a {@linkplain AttributeMetaData AttributeMetaData-Map}     */
580     * for a given geo-object (feature) source. The SLD file must be present. A missing    public static StyledLayerStyle<RasterLegendData> loadStyledRasterStyle(URL geoObjectURL, String sldExt, String rldExt) {
581     * attribute meta-data file is tolerated.      RasterLegendData metaData = null;
582     * @param geoObjectURL URL of the (already read) feature object      Style sldStyle = null;
583     * @param sldExt file extention for the SLD file      try {
584     * @param rldExt file extention for the raster legend-data file        Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(geoObjectURL, sldExt));
585     * @return {@code null} in case of any error        // SLD must be present
586     */        if ( styles == null || styles.length == 0 )
587    public static StyledMapStyle<Map<Integer,AttributeMetaData>> loadStyledFeatureStyle(URL geoObjectURL, String sldExt, String rldExt) {          return null;
588      Map<Integer,AttributeMetaData> metaData = null;        sldStyle = styles[0];
589      Style                          sldStyle = null;      }
590      try {      catch (Exception err) {
591        Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(geoObjectURL, sldExt));        // SLD must be present
592        // SLD must be present        LangUtil.logDebugError(LOGGER,err);
593        if ( styles == null || styles.length == 0 )        return null;
594          return null;      }
595        sldStyle = styles[0];  
596      } catch (Exception err) {      try {
597        // SLD must be present        metaData = StyledLayerUtil.loadRasterLegendData( IOUtil.changeUrlExt(geoObjectURL,rldExt) );
598        LangUtil.logDebugError(LOGGER,err);      } catch (FileNotFoundException err) {
599        return null;        // ignore missing raster legend data
600      }      } catch (Exception err) {
601          // any other error during legend data creation leads to error
602      try {        LangUtil.logDebugError(LOGGER,err);
603        metaData = StyledMapUtil.loadAttributeMetaDataMap( IOUtil.changeUrlExt(geoObjectURL,rldExt) );        return null;
604      } catch (FileNotFoundException err) {      }
605        // ignore missing attribute meta data      return new StyledLayerStyle<RasterLegendData>(sldStyle, metaData);
606      } catch (Exception err) {    }
607        // any other error during meta data creation leads to error  
608        LangUtil.logDebugError(LOGGER,err);    /**
609        return null;     * Loads a {@linkplain Style SLD-Style} from a {@code .sld} file and
610      }     * {@linkplain RasterLegendData Raster-LegendData} from a {@code .rld} file
611       * for a given geo-object (raster) source. The SLD file must be present. A missing
612      return new StyledMapStyle<Map<Integer,AttributeMetaData>>(sldStyle, metaData);     * raster legend-data file is tolerated.
613    }     * @param geoObjectURL URL of the (already read) raster object
614       * @param sldExt file extention for the SLD file
615    /**     * @param rldExt file extention for the raster legend-data file
616     * Loads a {@linkplain Style SLD-Style} from a {@code .sld} file and     * @return {@code null} in case of any error
617     * {@linkplain AttributeMetaData AttributeMetaData-Map} from a {@code .amd} file     */
618     * for a given geo-object (feature) source. The SLD file must be present. A missing    public static StyledLayerStyle<RasterLegendData> loadStyledRasterStyle(URL geoObjectURL) {
619     * attribute meta-data file is tolerated.      return loadStyledRasterStyle(geoObjectURL, "sld", "rld");
620     * @param geoObjectURL URL of the (already read) feature object    }
621     * @param sldExt file extention for the SLD file  
622     * @param rldExt file extention for the raster legend-data file    /**
623     * @return {@code null} in case of any error     * Loads a {@linkplain Style SLD-Style} and a {@linkplain AttributeMetaData AttributeMetaData-Map}
624     */     * for a given geo-object (feature) source. The SLD file must be present. A missing
625    public static StyledMapStyle<Map<Integer,AttributeMetaData>> loadStyledFeatureStyle(URL geoObjectURL) {     * attribute meta-data file is tolerated.
626      return loadStyledFeatureStyle(geoObjectURL, "sld", "amd");     * @param geoObjectURL URL of the (already read) feature object
627    }     * @param sldExt file extention for the SLD file
628       * @param rldExt file extention for the raster legend-data file
629    /**     * @return {@code null} in case of any error
630     * Stores a {@linkplain Style SLD-Style} and {@linkplain RasterLegendData Raster-LegendData}     */
631     * for a given geo-object (raster) source.    public static StyledLayerStyle<Map<Integer,AttributeMetaData>> loadStyledFeatureStyle(URL geoObjectURL, String sldExt, String rldExt) {
632     * @param style  style to save      Map<Integer,AttributeMetaData> metaData = null;
633     * @param geoObjectURL URL of the raster object      Style                          sldStyle = null;
634     * @param sldExt file extention for the SLD file      try {
635     * @param mdExt file extention for the meta-data file        Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(geoObjectURL, sldExt));
636     */        // SLD must be present
637    public static <T> void saveStyledMapStyle(StyledMapStyle<T> style, URL geoObjectURL, String sldExt, String mdExt) throws Exception {        if ( styles == null || styles.length == 0 )
638      // Store the SLD          return null;
639      Style sldStyle = style.getGeoObjectStyle();        sldStyle = styles[0];
640      if ( sldStyle != null ) {      } catch (Exception err) {
641        StylingUtil.saveStyleToSLD(        // SLD must be present
642           sldStyle,        LangUtil.logDebugError(LOGGER,err);
643           IOUtil.changeFileExt(        return null;
644                new File(geoObjectURL.toURI()),      }
645                sldExt  
646           )      try {
647        );        metaData = StyledLayerUtil.loadAttributeMetaDataMap( IOUtil.changeUrlExt(geoObjectURL,rldExt) );
648      }      } catch (FileNotFoundException err) {
649          // ignore missing attribute meta data
650      // Store the meta data      } catch (Exception err) {
651      T metaData = style.getMetaData();        // any other error during meta data creation leads to error
652      if ( metaData != null ) {        LangUtil.logDebugError(LOGGER,err);
653        if ( metaData instanceof RasterLegendData ) {        return null;
654          saveRasterLegendData(      }
655              (RasterLegendData)metaData,  
656              IOUtil.changeUrlExt(geoObjectURL,mdExt)      return new StyledLayerStyle<Map<Integer,AttributeMetaData>>(sldStyle, metaData);
657          );    }
658  //      } else if ( metaData instanceof Map<Integer,AttributeMetaData> ) { // LEIDER NICHT KOMPILIERBAR!!  
659        } else if ( metaData instanceof Map ) {    /**
660          saveAttributeMetaDataMap(     * Loads a {@linkplain Style SLD-Style} from a {@code .sld} file and
661              (Map<Integer,AttributeMetaData>)metaData,     * {@linkplain AttributeMetaData AttributeMetaData-Map} from a {@code .amd} file
662              IOUtil.changeUrlExt(geoObjectURL,mdExt)     * for a given geo-object (feature) source. The SLD file must be present. A missing
663          );     * attribute meta-data file is tolerated.
664        } else     * @param geoObjectURL URL of the (already read) feature object
665          throw new UnsupportedOperationException("Export for meta data not yet supported: "+metaData.getClass().getSimpleName());     * @param sldExt file extention for the SLD file
666      }     * @param rldExt file extention for the raster legend-data file
667    }     * @return {@code null} in case of any error
668       */
669    /**    public static StyledLayerStyle<Map<Integer,AttributeMetaData>> loadStyledFeatureStyle(URL geoObjectURL) {
670     * Stores the {@linkplain Style SLD-Style} to a {@code .sld} file and      return loadStyledFeatureStyle(geoObjectURL, "sld", "amd");
671     * the meta data ({@link RasterLegendData} or {@link AttributeMetaData})    }
672     * to a {@code .rld} or {@code .amd} file.  
673     * for a given geo-object source.    /**
674     * @param style  style to save     * Stores a {@linkplain Style SLD-Style} and {@linkplain RasterLegendData Raster-LegendData}
675     * @param geoObjectURL URL of the (already read) raster object     * for a given geo-object (raster) source.
676     */     * @param style  style to save
677    public static void saveStyledMapStyle(StyledMapStyle<?> style, URL geoObjectURL) throws Exception {     * @param geoObjectURL URL of the raster object
678      if ( style.getMetaData() instanceof RasterLegendData )     * @param sldExt file extention for the SLD file
679        saveStyledMapStyle(style,geoObjectURL, "sld", "rld");     * @param mdExt file extention for the meta-data file
680      else     */
681        saveStyledMapStyle(style,geoObjectURL, "sld", "amd");    public static <T> void saveStyledLayerStyle(StyledLayerStyle<T> style, URL geoObjectURL, String sldExt, String mdExt) throws Exception {
682    }      // Store the SLD
683        Style sldStyle = style.getGeoObjectStyle();
684  }      if ( sldStyle != null ) {
685          StylingUtil.saveStyleToSLD(
686             sldStyle,
687             IOUtil.changeFileExt(
688                  new File(geoObjectURL.toURI()),
689                  sldExt
690             )
691          );
692        }
693    
694        // Store the meta data
695        T metaData = style.getMetaData();
696        if ( metaData != null ) {
697          if ( metaData instanceof RasterLegendData ) {
698            saveRasterLegendData(
699                (RasterLegendData)metaData,
700                IOUtil.changeUrlExt(geoObjectURL,mdExt)
701            );
702    //      } else if ( metaData instanceof Map<Integer,AttributeMetaData> ) { // LEIDER NICHT KOMPILIERBAR!!
703          } else if ( metaData instanceof Map ) {
704            saveAttributeMetaDataMap(
705                (Map<Integer,AttributeMetaData>)metaData,
706                IOUtil.changeUrlExt(geoObjectURL,mdExt)
707            );
708          } else
709            throw new UnsupportedOperationException("Export for meta data not yet supported: "+metaData.getClass().getSimpleName());
710        }
711      }
712    
713      /**
714       * Stores the {@linkplain Style SLD-Style} to a {@code .sld} file and
715       * the meta data ({@link RasterLegendData} or {@link AttributeMetaData})
716       * to a {@code .rld} or {@code .amd} file.
717       * for a given geo-object source.
718       * @param style  style to save
719       * @param geoObjectURL URL of the (already read) raster object
720       */
721      public static void saveStyledLayerStyle(StyledLayerStyle<?> style, URL geoObjectURL) throws Exception {
722        if ( style.getMetaData() instanceof RasterLegendData )
723          saveStyledLayerStyle(style,geoObjectURL, "sld", "rld");
724        else
725          saveStyledLayerStyle(style,geoObjectURL, "sld", "amd");
726      }
727    
728    }

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26