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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26