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

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

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

branches/1.0-gt2-2.6/src/skrueger/geotools/StyledLayerUtil.java revision 400 by alfonx, Mon Sep 14 12:24:50 2009 UTC trunk/src/skrueger/geotools/StyledLayerUtil.java revision 695 by alfonx, Fri Feb 12 20:46:08 2010 UTC
# Line 31  package skrueger.geotools; Line 31  package skrueger.geotools;
31    
32  import java.awt.Color;  import java.awt.Color;
33  import java.awt.Dimension;  import java.awt.Dimension;
 import java.awt.Graphics;  
34  import java.awt.Graphics2D;  import java.awt.Graphics2D;
35  import java.awt.Rectangle;  import java.awt.Rectangle;
36  import java.awt.geom.AffineTransform;  import java.awt.geom.AffineTransform;
37  import java.awt.image.BufferedImage;  import java.awt.image.BufferedImage;
38    import java.awt.image.ColorModel;
39    import java.awt.image.ComponentColorModel;
40    import java.awt.image.DataBuffer;
41  import java.io.File;  import java.io.File;
42  import java.io.FileNotFoundException;  import java.io.FileNotFoundException;
43  import java.io.FileWriter;  import java.io.FileWriter;
44  import java.net.URL;  import java.net.URL;
45  import java.text.DecimalFormat;  import java.text.DecimalFormat;
46  import java.util.HashMap;  import java.util.ArrayList;
47  import java.util.List;  import java.util.List;
48  import java.util.Map;  import java.util.Map;
 import java.util.Set;  
 import java.util.SortedMap;  
 import java.util.TreeMap;  
49    
50  import javax.swing.Box;  import javax.swing.BorderFactory;
 import javax.swing.BoxLayout;  
51  import javax.swing.ImageIcon;  import javax.swing.ImageIcon;
52    import javax.swing.JComponent;
53  import javax.swing.JLabel;  import javax.swing.JLabel;
54    
55    import net.miginfocom.swing.MigLayout;
56    
57  import org.apache.log4j.Logger;  import org.apache.log4j.Logger;
58    import org.geotools.coverage.grid.GeneralGridEnvelope;
59  import org.geotools.coverage.grid.GridCoverage2D;  import org.geotools.coverage.grid.GridCoverage2D;
60    import org.geotools.coverage.grid.GridGeometry2D;
61  import org.geotools.coverage.grid.io.AbstractGridCoverage2DReader;  import org.geotools.coverage.grid.io.AbstractGridCoverage2DReader;
62    import org.geotools.coverage.grid.io.AbstractGridFormat;
63  import org.geotools.feature.FeatureCollection;  import org.geotools.feature.FeatureCollection;
64    import org.geotools.feature.NameImpl;
65    import org.geotools.geometry.jts.ReferencedEnvelope;
66  import org.geotools.map.DefaultMapLayer;  import org.geotools.map.DefaultMapLayer;
67  import org.geotools.map.MapLayer;  import org.geotools.map.MapLayer;
68    import org.geotools.parameter.Parameter;
69  import org.geotools.renderer.lite.gridcoverage2d.GridCoverageRenderer;  import org.geotools.renderer.lite.gridcoverage2d.GridCoverageRenderer;
70  import org.geotools.styling.ColorMap;  import org.geotools.styling.ColorMap;
71  import org.geotools.styling.ColorMapEntry;  import org.geotools.styling.ColorMapEntry;
# Line 70  import org.jdom.Document; Line 77  import org.jdom.Document;
77  import org.jdom.Element;  import org.jdom.Element;
78  import org.jdom.input.SAXBuilder;  import org.jdom.input.SAXBuilder;
79  import org.jdom.output.XMLOutputter;  import org.jdom.output.XMLOutputter;
80    import org.opengis.feature.simple.SimpleFeature;
81  import org.opengis.feature.simple.SimpleFeatureType;  import org.opengis.feature.simple.SimpleFeatureType;
82    import org.opengis.feature.type.AttributeDescriptor;
83    import org.opengis.feature.type.GeometryDescriptor;
84    import org.opengis.feature.type.Name;
85    import org.opengis.parameter.GeneralParameterValue;
86    
87  import schmitzm.geotools.JTSUtil;  import schmitzm.geotools.JTSUtil;
88    import schmitzm.geotools.feature.FeatureUtil;
89  import schmitzm.geotools.styling.StylingUtil;  import schmitzm.geotools.styling.StylingUtil;
90  import schmitzm.io.IOUtil;  import schmitzm.io.IOUtil;
91  import schmitzm.lang.LangUtil;  import schmitzm.lang.LangUtil;
92    import schmitzm.swing.JPanel;
93  import schmitzm.swing.SwingUtil;  import schmitzm.swing.SwingUtil;
94  import skrueger.AttributeMetaData;  import skrueger.AttributeMetadata;
95  import skrueger.RasterLegendData;  import skrueger.RasterLegendData;
96  import skrueger.i8n.Translation;  import skrueger.i8n.Translation;
97    
# Line 121  public class StyledLayerUtil { Line 135  public class StyledLayerUtil {
135           *                if {@code null} is given as object or an error occurs           *                if {@code null} is given as object or an error occurs
136           *                during layer creation           *                during layer creation
137           */           */
138          public static MapLayer createMapLayer(Object object) throws Exception {          public static MapLayer createMapLayer(final Object object) throws Exception {
139                  return createMapLayer(object, null);                  return createMapLayer(object, null);
140          }          }
141    
# Line 140  public class StyledLayerUtil { Line 154  public class StyledLayerUtil {
154           *                if {@code null} is given as object or an error occurs           *                if {@code null} is given as object or an error occurs
155           *                during layer creation           *                during layer creation
156           */           */
157          public static MapLayer createMapLayer(Object object, Style forcedStyle)          public static MapLayer createMapLayer(Object object, final Style forcedStyle)
158                          throws Exception {                          throws Exception {
159                  MapLayer layer = null;                  MapLayer layer = null;
160                  Style style = null;                  Style style = null;
# Line 181  public class StyledLayerUtil { Line 195  public class StyledLayerUtil {
195           *                if {@code null} is given as object or an error occurs           *                if {@code null} is given as object or an error occurs
196           *                during creation           *                during creation
197           */           */
198          public static StyledLayerInterface<?> createStyledLayer(Object object,          public static StyledLayerInterface<?> createStyledLayer(
199                          String title) {                          final Object object, final String title) {
200                  return createStyledLayer(object, title, null);                  return createStyledLayer(object, title, null);
201          }          }
202    
# Line 201  public class StyledLayerUtil { Line 215  public class StyledLayerUtil {
215           *                if {@code null} is given as object or an error occurs           *                if {@code null} is given as object or an error occurs
216           *                during creation           *                during creation
217           */           */
218          public static StyledLayerInterface<?> createStyledLayer(Object object,          public static StyledLayerInterface<?> createStyledLayer(
219                          String title, StyledLayerStyle style) {                          final Object object, final String title,
220                            final StyledLayerStyle style) {
221                  StyledLayerInterface<?> styledLayer = null;                  StyledLayerInterface<?> styledLayer = null;
222    
223                  String id = (title != null) ? title : "defaultID";                  final String id = (title != null) ? title : "defaultID";
224    
225                  if (object instanceof GridCoverage2D)                  if (object instanceof GridCoverage2D)
226                          styledLayer = new StyledGridCoverage((GridCoverage2D) object, id,                          styledLayer = new StyledGridCoverage((GridCoverage2D) object, id,
# Line 233  public class StyledLayerUtil { Line 248  public class StyledLayerUtil {
248           * @param visible           * @param visible
249           *            indicated whether the visible or invisible entries are           *            indicated whether the visible or invisible entries are
250           *            returned           *            returned
251             *
252             *            TODO replace with
253             *            {@link AttributeMetadataMap#sortedValuesVisibleOnly()}
254           */           */
255          public static SortedMap<Integer, AttributeMetaData> getVisibleAttributeMetaData(          public static AttributeMetadataMap getVisibleAttributeMetaData(
256                          Map<Integer, AttributeMetaData> amdMap, boolean visible) {                          final AttributeMetadataMap amdMap, final boolean visible) {
257                  SortedMap<Integer, AttributeMetaData> filteredMap = new TreeMap<Integer, AttributeMetaData>();  
258                  for (AttributeMetaData amd : amdMap.values())                  final AttributeMetadataMap filteredMap = new AttributeMetadataMap(
259                          if (amd.isVisible())                                  amdMap.getLanguages());
260                                  filteredMap.put(amd.getColIdx(), amd);                  for (final AttributeMetadata amd : amdMap.values())
261                            if (amd.isVisible() == visible)
262                                    filteredMap.put(amd.getName(), amd);
263    
264                  return filteredMap;                  return filteredMap;
265          }          }
266    
267          /**          /**
268           * Parses a {@link AttributeMetaData} object from an JDOM-{@link Element}.           * Parses a {@link AttributeMetadata} object from an JDOM-{@link Element}.
269           * This method works like {@link           * This method works like {@link
270           * AMLImport#parseDataAttribute(org.w3c.dom.Node}, but for JDOM.           * AMLImport#parseDataAttribute(org.w3c.dom.Node}, but for JDOM.
271           *           *
272             * TODO 20.11.2009, SK: There are some new attribute weight, functiona,
273             * functionX and nodata in AttributeMetaData that should be parsed/exported
274             * too. but this method is only used by ISDSS, which is not supporting that
275             * stuff anyways.
276             *
277           * @param element           * @param element
278           *            {@link Element} to parse           *            {@link Element} to parse
279           */           */
280          public static AttributeMetaData parseAttributeMetaData(final Element element) {          public static AttributeMetadata parseAttributeMetaData(final Element element) {
281                  final Integer col = Integer.valueOf(element.getAttributeValue("col"));                  final String namespace = String.valueOf(element
282                                    .getAttributeValue("namespace"));
283                    final String localname = String.valueOf(element
284                                    .getAttributeValue("localname"));
285                    final Name aName = new NameImpl(namespace, localname);
286                  final Boolean visible = Boolean.valueOf(element                  final Boolean visible = Boolean.valueOf(element
287                                  .getAttributeValue("visible"));                                  .getAttributeValue("visible"));
288                  final String unit = element.getAttributeValue("unit");                  final String unit = element.getAttributeValue("unit");
# Line 269  public class StyledLayerUtil { Line 298  public class StyledLayerUtil {
298                          else if (childElement.getName().equals("desc"))                          else if (childElement.getName().equals("desc"))
299                                  desc = parseTranslation(childElement);                                  desc = parseTranslation(childElement);
300                  }                  }
301                  return new AttributeMetaData(col, visible, name, desc, unit);                  return new AttributeMetadata(aName, visible, name, desc, unit);
302          }          }
303    
304          /**          /**
305           * Parses a {@link AttributeMetaData} map from an JDOM-{@link Element} with           * Parses a {@link AttributeMetadata} map from an JDOM-{@link Element} with
306           * {@code <attribute>}-childs.           * {@code <attribute>}-childs.
307           *           *
308           * @param element           * @param element
309           *            {@link Element} to parse           *            {@link Element} to parse
310             *
311             *            TODO Since GP 1.3 the {@link AttributeMetadata} class has more
312             *            attributes which are not used by Xulu/ISDSS. GP
313             *            exports/imports the AMD via AMLExporter and AMLImporter
314             *            classes. (SK, 3.2.2010) *
315           */           */
316          public static Map<Integer, AttributeMetaData> parseAttributeMetaDataMap(          public static AttributeMetadataMap parseAttributeMetaDataMap(
317                          final Element element) {                          final Element element) {
318                  HashMap<Integer, AttributeMetaData> metaData = new HashMap<Integer, AttributeMetaData>();                  final AttributeMetadataMap metaData = new AttributeMetadataMap();
319                  List<Element> attributesElements = element                  final List<Element> attributesElements = element
320                                  .getChildren(ELEM_NAME_ATTRIBUTE);                                  .getChildren(ELEM_NAME_ATTRIBUTE);
321                  for (Element attibuteElement : attributesElements) {                  for (final Element attibuteElement : attributesElements) {
322                          AttributeMetaData attrMetaData = parseAttributeMetaData(attibuteElement);                          final AttributeMetadata attrMetaData = parseAttributeMetaData(attibuteElement);
323                          metaData.put(attrMetaData.getColIdx(), attrMetaData);                          metaData.put(attrMetaData.getName(), attrMetaData);
324                  }                  }
325                  return metaData;                  return metaData;
326          }          }
327    
328          /**          /**
329           * Loads a {@link AttributeMetaData} object from an URL.           * Loads a {@link AttributeMetadata} object from an URL.
330           *           *
331           * @param documentUrl           * @param documentUrl
332           *            {@link URL} to parse           *            {@link URL} to parse
333           * @see #parseAttributeMetaData(Element)           * @see #parseAttributeMetaData(Element)
334           */           */
335          public static Map<Integer, AttributeMetaData> loadAttributeMetaDataMap(          public static AttributeMetadataMap loadAttributeMetaDataMap(
336                          final URL documentUrl) throws Exception {                          final URL documentUrl) throws Exception {
337                  Document document = SAX_BUILDER.build(documentUrl);                  final Document document = SAX_BUILDER.build(documentUrl);
338                  return parseAttributeMetaDataMap(document.getRootElement());                  return parseAttributeMetaDataMap(document.getRootElement());
339          }          }
340    
341          /**          /**
342           * Creates an JDOM {@link Element} for the given {@link AttributeMetaData}           * Creates an JDOM {@link Element} for the given {@link AttributeMetadata}
343           * object.           * object.
344           *           *
345           * @param amd           * @param amd
346           *            meta data for one attribute           *            meta data for one attribute
347             *
348             *            TODO Since GP 1.3 the {@link AttributeMetadata} class has more
349             *            attributes which are not used by Xulu/ISDSS. GP
350             *            exports/imports the AMD via AMLExporter and AMLImporter
351             *            classes. (SK, 3.2.2010)
352           */           */
353          public static Element createAttributeMetaDataElement(          public static Element createAttributeMetaDataElement(
354                          final AttributeMetaData amd) {                          final AttributeMetadata amd) {
355                  final Element element = new Element(ELEM_NAME_ATTRIBUTE, AMLURI);                  final Element element = new Element(ELEM_NAME_ATTRIBUTE, AMLURI);
356                  element.setAttribute("col", String.valueOf(amd.getColIdx()));                  element.setAttribute("namespace", String.valueOf(amd.getName()
357                                    .getNamespaceURI()));
358                    element.setAttribute("localname", String.valueOf(amd.getLocalName()));
359                  element.setAttribute("visible", String.valueOf(amd.isVisible()));                  element.setAttribute("visible", String.valueOf(amd.isVisible()));
360                  element.setAttribute("unit", amd.getUnit());                  element.setAttribute("unit", amd.getUnit());
361                  // Creating a aml:name tag...                  // Creating a aml:name tag...
# Line 325  public class StyledLayerUtil { Line 366  public class StyledLayerUtil {
366          }          }
367    
368          /**          /**
369           * Creates an JDOM {@link Element} for the given {@link AttributeMetaData}           * Creates an JDOM {@link Element} for the given {@link AttributeMetadata}
370           * map.           * map.
371           *           *
372           * @param amdMap           * @param amdMap
373           *            map of attribute meta data           *            map of attribute meta data
374           */           */
375          public static Element createAttributeMetaDataMapElement(          public static Element createAttributeMetaDataMapElement(
376                          final Map<Integer, AttributeMetaData> amdMap) {                          final AttributeMetadataMap amdMap) {
377                  final Element element = new Element(ELEM_NAME_AMD, AMLURI);                  final Element element = new Element(ELEM_NAME_AMD, AMLURI);
378                  for (AttributeMetaData amd : amdMap.values())                  for (final AttributeMetadata amd : amdMap.values())
379                          element.addContent(createAttributeMetaDataElement(amd));                          element.addContent(createAttributeMetaDataElement(amd));
380                  return element;                  return element;
381          }          }
382    
383          /**          /**
384           * Saves a {@link AttributeMetaData AttributeMetaData-Map} to an URL.           * Saves a {@link AttributeMetadata AttributeMetaData-Map} to an URL.
385           *           *
386           * @param amdMap           * @param amdMap
387           *            map of {@link AttributeMetaData}           *            map of {@link AttributeMetadata}
388           * @param documentUrl           * @param documentUrl
389           *            {@link URL} to store the XML           *            {@link URL} to store the XML
390           */           */
391          public static void saveAttributeMetaDataMap(          public static void saveAttributeMetaDataMap(
392                          final Map<Integer, AttributeMetaData> amdMap, final URL documentUrl)                          final AttributeMetadataMap amdMap, final URL documentUrl)
393                          throws Exception {                          throws Exception {
394                  // Create XML-Document                  // Create XML-Document
395                  final FileWriter out = new FileWriter(new File(documentUrl.toURI()));                  final FileWriter out = new FileWriter(new File(documentUrl.toURI()));
# Line 365  public class StyledLayerUtil { Line 406  public class StyledLayerUtil {
406           * @param element           * @param element
407           *            {@link Element} to parse           *            {@link Element} to parse
408           */           */
409          public static RasterLegendData parseRasterLegendData(Element element) {          public static RasterLegendData parseRasterLegendData(final Element element) {
410    
411                  final boolean paintGaps = Boolean.valueOf(element                  final boolean paintGaps = Boolean.valueOf(element
412                                  .getAttributeValue("paintGaps"));                                  .getAttributeValue("paintGaps"));
413    
414                  RasterLegendData rld = new RasterLegendData(paintGaps);                  final RasterLegendData rld = new RasterLegendData(paintGaps);
415    
416                  for (Element childElement : (List<Element>) element.getChildren()) {                  for (final Element childElement : (List<Element>) element.getChildren()) {
417                          final String name = childElement.getName();                          final String name = childElement.getName();
418                          // Cancel if it's an attribute                          // Cancel if it's an attribute
419                          if (childElement.getChildren().size() == 0)                          if (childElement.getChildren().size() == 0)
# Line 392  public class StyledLayerUtil { Line 433  public class StyledLayerUtil {
433                                  // id label element is missing, the translation is searched                                  // id label element is missing, the translation is searched
434                                  // directly                                  // directly
435                                  // as childs of the rasterLegendItem element                                  // as childs of the rasterLegendItem element
436                                  Translation label = parseTranslation(labelElement != null ? labelElement                                  final Translation label = parseTranslation(labelElement != null ? labelElement
437                                                  : childElement);                                                  : childElement);
438                                  rld.put(value, label);                                  rld.put(value, label);
439                          }                          }
# Line 410  public class StyledLayerUtil { Line 451  public class StyledLayerUtil {
451           */           */
452          public static RasterLegendData loadRasterLegendData(final URL documentUrl)          public static RasterLegendData loadRasterLegendData(final URL documentUrl)
453                          throws Exception {                          throws Exception {
454                  Document document = SAX_BUILDER.build(documentUrl);                  final Document document = SAX_BUILDER.build(documentUrl);
455                  return parseRasterLegendData(document.getRootElement());                  return parseRasterLegendData(document.getRootElement());
456          }          }
457    
# Line 425  public class StyledLayerUtil { Line 466  public class StyledLayerUtil {
466                          final RasterLegendData rld) {                          final RasterLegendData rld) {
467                  final Element element = new Element(ELEM_NAME_RLD, AMLURI);                  final Element element = new Element(ELEM_NAME_RLD, AMLURI);
468                  element.setAttribute("paintGaps", rld.isPaintGaps().toString());                  element.setAttribute("paintGaps", rld.isPaintGaps().toString());
469                  for (Double key : rld.getSortedKeys()) {                  for (final Double key : rld.getSortedKeys()) {
470                          Element item = new Element(ELEM_NAME_RASTERLEGEND, AMLURI);                          final Element item = new Element(ELEM_NAME_RASTERLEGEND, AMLURI);
471                          item.setAttribute("value", key.toString());                          item.setAttribute("value", key.toString());
472                          item.addContent(createTranslationElement("label", rld.get(key)));                          item.addContent(createTranslationElement("label", rld.get(key)));
473                          element.addContent(item);                          element.addContent(item);
# Line 446  public class StyledLayerUtil { Line 487  public class StyledLayerUtil {
487           *            rounded to (null means no round; >= 0 means digits after           *            rounded to (null means no round; >= 0 means digits after
488           *            comma; < 0 means digits before comma)           *            comma; < 0 means digits before comma)
489           */           */
490          public static RasterLegendData generateRasterLegendData(ColorMap colorMap,          public static RasterLegendData generateRasterLegendData(
491                          boolean paintGaps, Integer digits) {                          final ColorMap colorMap, final boolean paintGaps,
492                  DecimalFormat decFormat = digits != null ? new DecimalFormat(SwingUtil                          final Integer digits) {
493                                  .getNumberFormatPattern(digits)) : null;                  final DecimalFormat decFormat = digits != null ? new DecimalFormat(
494                  RasterLegendData rld = new RasterLegendData(paintGaps);                                  SwingUtil.getNumberFormatPattern(digits)) : null;
495                  for (ColorMapEntry cme : colorMap.getColorMapEntries()) {                  final RasterLegendData rld = new RasterLegendData(paintGaps);
496                          double value = StylingUtil.getQuantityFromColorMapEntry(cme);                  for (final ColorMapEntry cme : colorMap.getColorMapEntries()) {
497                            final double value = StylingUtil.getQuantityFromColorMapEntry(cme);
498                          String label = cme.getLabel();                          String label = cme.getLabel();
499                          // if no label is set (e.g. quantitative style),                          // if no label is set (e.g. quantitative style),
500                          // use the value as label                          // use the value as label
# Line 478  public class StyledLayerUtil { Line 520  public class StyledLayerUtil {
520           *            rounded to (null means no round; >= 0 means digits after           *            rounded to (null means no round; >= 0 means digits after
521           *            comma; < 0 means digits before comma)           *            comma; < 0 means digits before comma)
522           */           */
523          public static RasterLegendData generateRasterLegendData(Style style,          public static RasterLegendData generateRasterLegendData(final Style style,
524                          boolean paintGaps, Integer digits) {                          final boolean paintGaps, final Integer digits) {
525                  ColorMap colorMap = StylingUtil.getColorMapFromStyle(style);                  final ColorMap colorMap = StylingUtil.getColorMapFromStyle(style);
526                  if (colorMap == null)                  if (colorMap == null)
527                          throw new IllegalArgumentException(                          throw new IllegalArgumentException(
528                                          "Color map can not be determined from style!");                                          "Color map can not be determined from style!");
# Line 513  public class StyledLayerUtil { Line 555  public class StyledLayerUtil {
555           *            {@link Element} to parse           *            {@link Element} to parse
556           */           */
557          public final static Translation parseTranslation(final Element element) {          public final static Translation parseTranslation(final Element element) {
558                  Translation trans = new Translation();                  final Translation trans = new Translation();
559    
560                  if (element == null)                  if (element == null)
561                          return trans;                          return trans;
# Line 555  public class StyledLayerUtil { Line 597  public class StyledLayerUtil {
597           * @param translation           * @param translation
598           *            Translation to store in the Element           *            Translation to store in the Element
599           */           */
600          public final static Element createTranslationElement(String tagname,          public final static Element createTranslationElement(final String tagname,
601                          Translation translation) {                          final Translation translation) {
602                  Element element = new Element(tagname, AMLURI);                  final Element element = new Element(tagname, AMLURI);
603                  if (translation == null)                  if (translation == null)
604                          throw new UnsupportedOperationException(                          throw new UnsupportedOperationException(
605                                          "Translation element can not be created from null!");                                          "Translation element can not be created from null!");
# Line 573  public class StyledLayerUtil { Line 615  public class StyledLayerUtil {
615    
616                  // add a <translation lang="..">..</tranlation> part to the element for                  // add a <translation lang="..">..</tranlation> part to the element for
617                  // all languages                  // all languages
618                  for (String lang : translation.keySet()) {                  for (final String lang : translation.keySet()) {
619                          Element translationElement = new Element(ELEM_NAME_TRANSLATION,                          final Element translationElement = new Element(
620                                          AMLURI);                                          ELEM_NAME_TRANSLATION, AMLURI);
621                          translationElement.setAttribute("lang", lang);                          translationElement.setAttribute("lang", lang);
622                          String translationString = translation.get(lang);                          String translationString = translation.get(lang);
623                          if (translationString == null)                          if (translationString == null)
# Line 595  public class StyledLayerUtil { Line 637  public class StyledLayerUtil {
637           * @param style           * @param style
638           *            a Style           *            a Style
639           */           */
640          public static void setStyledLayerStyle(StyledLayerInterface styledObject,          public static void setStyledLayerStyle(
641                          StyledLayerStyle<?> style) {                          final StyledLayerInterface styledObject,
642                            final StyledLayerStyle<?> style) {
643                  // set SLD style                  // set SLD style
644                  styledObject.setStyle(style.getGeoObjectStyle());                  styledObject.setStyle(style.getGeoObjectStyle());
645                  // set meta data                  // set meta data
646                  if (styledObject instanceof StyledGridCoverageInterface                  if (styledObject instanceof StyledGridCoverageInterface
647                                  && (style.getMetaData() instanceof RasterLegendData || style                                  && (style.getMetaData() instanceof RasterLegendData || style
648                                                  .getMetaData() == null)) {                                                  .getMetaData() == null)) {
649                          RasterLegendData sourceRld = (RasterLegendData) style.getMetaData();                          final RasterLegendData sourceRld = (RasterLegendData) style
650                          RasterLegendData destRld = ((StyledGridCoverageInterface) styledObject)                                          .getMetaData();
651                            final RasterLegendData destRld = ((StyledGridCoverageInterface) styledObject)
652                                          .getLegendMetaData();                                          .getLegendMetaData();
653                          if (destRld != null && sourceRld != null) {                          if (destRld != null && sourceRld != null) {
654                                  destRld.setPaintGaps(sourceRld.isPaintGaps());                                  destRld.setPaintGaps(sourceRld.isPaintGaps());
# Line 615  public class StyledLayerUtil { Line 659  public class StyledLayerUtil {
659                  }                  }
660                  if (styledObject instanceof StyledFeatureCollectionInterface                  if (styledObject instanceof StyledFeatureCollectionInterface
661                                  && (style.getMetaData() instanceof Map || style.getMetaData() == null)) {                                  && (style.getMetaData() instanceof Map || style.getMetaData() == null)) {
662                          Map<Integer, AttributeMetaData> sourceAmd = (Map<Integer, AttributeMetaData>) style                          final AttributeMetadataMap sourceAmd = (AttributeMetadataMap) style
663                                          .getMetaData();                                          .getMetaData();
664                          Map<Integer, AttributeMetaData> destAmd = ((StyledFeatureCollectionInterface) styledObject)                          final AttributeMetadataMap destAmd = ((StyledFeatureCollectionInterface) styledObject)
665                                          .getAttributeMetaDataMap();                                          .getAttributeMetaDataMap();
666                          if (destAmd != null && sourceAmd != null) {                          if (destAmd != null && sourceAmd != null) {
667                                  destAmd.clear();                                  destAmd.clear();
# Line 647  public class StyledLayerUtil { Line 691  public class StyledLayerUtil {
691           *         {@link StyledFeatureCollectionInterface}           *         {@link StyledFeatureCollectionInterface}
692           */           */
693          public static StyledLayerStyle<?> getStyledLayerStyle(          public static StyledLayerStyle<?> getStyledLayerStyle(
694                          StyledLayerInterface styledObject) {                          final StyledLayerInterface styledObject) {
695                  if (styledObject instanceof StyledGridCoverageInterface)                  if (styledObject instanceof StyledGridCoverageInterface)
696                          return getStyledLayerStyle((StyledGridCoverageInterface) styledObject);                          return getStyledLayerStyle((StyledGridCoverageInterface) styledObject);
697                  if (styledObject instanceof StyledFeatureCollectionInterface)                  if (styledObject instanceof StyledFeatureCollectionInterface)
# Line 666  public class StyledLayerUtil { Line 710  public class StyledLayerUtil {
710           *            a styled grid coverage           *            a styled grid coverage
711           */           */
712          public static StyledLayerStyle<RasterLegendData> getStyledLayerStyle(          public static StyledLayerStyle<RasterLegendData> getStyledLayerStyle(
713                          StyledGridCoverageInterface styledGC) {                          final StyledGridCoverageInterface styledGC) {
714                  return new StyledLayerStyle<RasterLegendData>(styledGC.getStyle(),                  return new StyledLayerStyle<RasterLegendData>(styledGC.getStyle(),
715                                  styledGC.getLegendMetaData());                                  styledGC.getLegendMetaData());
716          }          }
# Line 678  public class StyledLayerUtil { Line 722  public class StyledLayerUtil {
722           * @param styledFC           * @param styledFC
723           *            a styled feature collection           *            a styled feature collection
724           */           */
725          public static StyledLayerStyle<Map<Integer, AttributeMetaData>> getStyledLayerStyle(          public static StyledLayerStyle<AttributeMetadataMap> getStyledLayerStyle(
726                          StyledFeatureCollectionInterface styledFC) {                          final StyledFeatureCollectionInterface styledFC) {
727                  return new StyledLayerStyle<Map<Integer, AttributeMetaData>>(styledFC                  return new StyledLayerStyle<AttributeMetadataMap>(styledFC.getStyle(),
728                                  .getStyle(), styledFC.getAttributeMetaDataMap());                                  styledFC.getAttributeMetaDataMap());
729          }          }
730    
731          /**          /**
# Line 698  public class StyledLayerUtil { Line 742  public class StyledLayerUtil {
742           * @return {@code null} in case of any error           * @return {@code null} in case of any error
743           */           */
744          public static StyledLayerStyle<RasterLegendData> loadStyledRasterStyle(          public static StyledLayerStyle<RasterLegendData> loadStyledRasterStyle(
745                          URL geoObjectURL, String sldExt, String rldExt) {                          final URL geoObjectURL, final String sldExt, final String rldExt) {
746                  RasterLegendData metaData = null;                  RasterLegendData metaData = null;
747                  Style sldStyle = null;                  Style sldStyle = null;
748                  try {                  try {
749                          Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(                          final Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(
750                                          geoObjectURL, sldExt));                                          geoObjectURL, sldExt));
751                          // SLD must be present                          // SLD must be present
752                          if (styles == null || styles.length == 0)                          if (styles == null || styles.length == 0)
753                                  return null;                                  return null;
754                          sldStyle = styles[0];                          sldStyle = styles[0];
755                  } catch (Exception err) {                  } catch (final Exception err) {
756                          // SLD must be present                          // SLD must be present
757                          LangUtil.logDebugError(LOGGER, err);                          LangUtil.logDebugError(LOGGER, err);
758                          return null;                          return null;
# Line 717  public class StyledLayerUtil { Line 761  public class StyledLayerUtil {
761                  try {                  try {
762                          metaData = StyledLayerUtil.loadRasterLegendData(IOUtil                          metaData = StyledLayerUtil.loadRasterLegendData(IOUtil
763                                          .changeUrlExt(geoObjectURL, rldExt));                                          .changeUrlExt(geoObjectURL, rldExt));
764                  } catch (FileNotFoundException err) {                  } catch (final FileNotFoundException err) {
765                          // ignore missing raster legend data                          // ignore missing raster legend data
766                  } catch (Exception err) {                  } catch (final Exception err) {
767                          // any other error during legend data creation leads to error                          // any other error during legend data creation leads to error
768                          LangUtil.logDebugError(LOGGER, err);                          LangUtil.logDebugError(LOGGER, err);
769                          return null;                          return null;
# Line 742  public class StyledLayerUtil { Line 786  public class StyledLayerUtil {
786           * @return {@code null} in case of any error           * @return {@code null} in case of any error
787           */           */
788          public static StyledLayerStyle<RasterLegendData> loadStyledRasterStyle(          public static StyledLayerStyle<RasterLegendData> loadStyledRasterStyle(
789                          URL geoObjectURL) {                          final URL geoObjectURL) {
790                  return loadStyledRasterStyle(geoObjectURL, "sld", "rld");                  return loadStyledRasterStyle(geoObjectURL, "sld", "rld");
791          }          }
792    
793          /**          /**
794           * Loads a {@linkplain Style SLD-Style} and a {@linkplain AttributeMetaData           * Loads a {@linkplain Style SLD-Style} and a {@linkplain AttributeMetadata
795           * AttributeMetaData-Map} for a given geo-object (feature) source. The SLD           * AttributeMetaData-Map} for a given geo-object (feature) source. The SLD
796           * file must be present. A missing attribute meta-data file is tolerated.           * file must be present. A missing attribute meta-data file is tolerated.
797           *           *
# Line 759  public class StyledLayerUtil { Line 803  public class StyledLayerUtil {
803           *            file extention for the raster legend-data file           *            file extention for the raster legend-data file
804           * @return {@code null} in case of any error           * @return {@code null} in case of any error
805           */           */
806          public static StyledLayerStyle<Map<Integer, AttributeMetaData>> loadStyledFeatureStyle(          public static StyledLayerStyle<AttributeMetadataMap> loadStyledFeatureStyle(
807                          URL geoObjectURL, String sldExt, String rldExt) {                          final URL geoObjectURL, final String sldExt, final String rldExt) {
808                  Map<Integer, AttributeMetaData> metaData = null;                  AttributeMetadataMap metaData = null;
809                  Style sldStyle = null;                  Style sldStyle = null;
810                  try {                  try {
811                          Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(                          final Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(
812                                          geoObjectURL, sldExt));                                          geoObjectURL, sldExt));
813                          // SLD must be present                          // SLD must be present
814                          if (styles == null || styles.length == 0)                          if (styles == null || styles.length == 0)
815                                  return null;                                  return null;
816                          sldStyle = styles[0];                          sldStyle = styles[0];
817                  } catch (Exception err) {                  } catch (final Exception err) {
818                          // SLD must be present                          // SLD must be present
819                          LangUtil.logDebugError(LOGGER, err);                          LangUtil.logDebugError(LOGGER, err);
820                          return null;                          return null;
# Line 779  public class StyledLayerUtil { Line 823  public class StyledLayerUtil {
823                  try {                  try {
824                          metaData = StyledLayerUtil.loadAttributeMetaDataMap(IOUtil                          metaData = StyledLayerUtil.loadAttributeMetaDataMap(IOUtil
825                                          .changeUrlExt(geoObjectURL, rldExt));                                          .changeUrlExt(geoObjectURL, rldExt));
826                  } catch (FileNotFoundException err) {                  } catch (final FileNotFoundException err) {
827                          // ignore missing attribute meta data                          // ignore missing attribute meta data
828                  } catch (Exception err) {                  } catch (final Exception err) {
829                          // any other error during meta data creation leads to error                          // any other error during meta data creation leads to error
830                          LangUtil.logDebugError(LOGGER, err);                          LangUtil.logDebugError(LOGGER, err);
831                          return null;                          return null;
832                  }                  }
833    
834                  return new StyledLayerStyle<Map<Integer, AttributeMetaData>>(sldStyle,                  return new StyledLayerStyle<AttributeMetadataMap>(sldStyle, metaData);
                                 metaData);  
835          }          }
836    
837          /**          /**
838           * Loads a {@linkplain Style SLD-Style} from a {@code .sld} file and           * Loads a {@linkplain Style SLD-Style} from a {@code .sld} file and
839           * {@linkplain AttributeMetaData AttributeMetaData-Map} from a {@code .amd}           * {@linkplain AttributeMetadata AttributeMetaData-Map} from a {@code .amd}
840           * file for a given geo-object (feature) source. The SLD file must be           * file for a given geo-object (feature) source. The SLD file must be
841           * present. A missing attribute meta-data file is tolerated.           * present. A missing attribute meta-data file is tolerated.
842           *           *
# Line 805  public class StyledLayerUtil { Line 848  public class StyledLayerUtil {
848           *            file extention for the raster legend-data file           *            file extention for the raster legend-data file
849           * @return {@code null} in case of any error           * @return {@code null} in case of any error
850           */           */
851          public static StyledLayerStyle<Map<Integer, AttributeMetaData>> loadStyledFeatureStyle(          public static StyledLayerStyle<AttributeMetadataMap> loadStyledFeatureStyle(
852                          URL geoObjectURL) {                          final URL geoObjectURL) {
853                  return loadStyledFeatureStyle(geoObjectURL, "sld", "amd");                  return loadStyledFeatureStyle(geoObjectURL, "sld", "amd");
854          }          }
855    
# Line 823  public class StyledLayerUtil { Line 866  public class StyledLayerUtil {
866           * @param mdExt           * @param mdExt
867           *            file extention for the meta-data file           *            file extention for the meta-data file
868           */           */
869          public static <T> void saveStyledLayerStyle(StyledLayerStyle<T> style,          public static <T> void saveStyledLayerStyle(
870                          URL geoObjectURL, String sldExt, String mdExt) throws Exception {                          final StyledLayerStyle<T> style, final URL geoObjectURL,
871                            final String sldExt, final String mdExt) throws Exception {
872                  // Store the SLD                  // Store the SLD
873                  Style sldStyle = style.getGeoObjectStyle();                  final Style sldStyle = style.getGeoObjectStyle();
874                  if (sldStyle != null) {                  if (sldStyle != null) {
875                          StylingUtil.saveStyleToSLD(sldStyle, IOUtil.changeFileExt(new File(                          StylingUtil.saveStyleToSLD(sldStyle, IOUtil.changeFileExt(new File(
876                                          geoObjectURL.toURI()), sldExt));                                          geoObjectURL.toURI()), sldExt));
877                  }                  }
878    
879                  // Store the meta data                  // Store the meta data
880                  T metaData = style.getMetaData();                  final T metaData = style.getMetaData();
881                  if (metaData != null) {                  if (metaData != null) {
882                          if (metaData instanceof RasterLegendData) {                          if (metaData instanceof RasterLegendData) {
883                                  saveRasterLegendData((RasterLegendData) metaData, IOUtil                                  saveRasterLegendData((RasterLegendData) metaData, IOUtil
# Line 842  public class StyledLayerUtil { Line 886  public class StyledLayerUtil {
886                                  // Map<Integer,AttributeMetaData> ) { // LEIDER NICHT                                  // Map<Integer,AttributeMetaData> ) { // LEIDER NICHT
887                                  // KOMPILIERBAR!!                                  // KOMPILIERBAR!!
888                          } else if (metaData instanceof Map) {                          } else if (metaData instanceof Map) {
889                                  saveAttributeMetaDataMap(                                  saveAttributeMetaDataMap((AttributeMetadataMap) metaData,
890                                                  (Map<Integer, AttributeMetaData>) metaData, IOUtil                                                  IOUtil.changeUrlExt(geoObjectURL, mdExt));
                                                                 .changeUrlExt(geoObjectURL, mdExt));  
891                          } else                          } else
892                                  throw new UnsupportedOperationException(                                  throw new UnsupportedOperationException(
893                                                  "Export for meta data not yet supported: "                                                  "Export for meta data not yet supported: "
# Line 854  public class StyledLayerUtil { Line 897  public class StyledLayerUtil {
897    
898          /**          /**
899           * Stores the {@linkplain Style SLD-Style} to a {@code .sld} file and the           * Stores the {@linkplain Style SLD-Style} to a {@code .sld} file and the
900           * meta data ({@link RasterLegendData} or {@link AttributeMetaData}) to a           * meta data ({@link RasterLegendData} or {@link AttributeMetadata}) to a
901           * {@code .rld} or {@code .amd} file. for a given geo-object source.           * {@code .rld} or {@code .amd} file. for a given geo-object source.
902           *           *
903           * @param style           * @param style
# Line 862  public class StyledLayerUtil { Line 905  public class StyledLayerUtil {
905           * @param geoObjectURL           * @param geoObjectURL
906           *            URL of the (already read) raster object           *            URL of the (already read) raster object
907           */           */
908          public static void saveStyledLayerStyle(StyledLayerStyle<?> style,          public static void saveStyledLayerStyle(final StyledLayerStyle<?> style,
909                          URL geoObjectURL) throws Exception {                          final URL geoObjectURL) throws Exception {
910                  if (style.getMetaData() instanceof RasterLegendData)                  if (style.getMetaData() instanceof RasterLegendData)
911                          saveStyledLayerStyle(style, geoObjectURL, "sld", "rld");                          saveStyledLayerStyle(style, geoObjectURL, "sld", "rld");
912                  else                  else
# Line 871  public class StyledLayerUtil { Line 914  public class StyledLayerUtil {
914          }          }
915    
916          /**          /**
917           * Creates a {@link Box} that shows a legend for a list of           * *If appended to the name of a rule, this rule shall not be shown in the
918             * legend
919             */
920            public final static String HIDE_IN_LAYER_LEGEND_HINT = "HIDE_IN_LEGEND";
921    
922            /**
923             * Creates a {@link JPanel} that shows a legend for a list of
924           * {@link FeatureTypeStyle}s and a targeted featureType           * {@link FeatureTypeStyle}s and a targeted featureType
925           *           *
926           * @param featureType           * @param featureType
# Line 882  public class StyledLayerUtil { Line 931  public class StyledLayerUtil {
931           * @author <a href="mailto:[email protected]">Stefan Alfons           * @author <a href="mailto:[email protected]">Stefan Alfons
932           *         Kr&uuml;ger</a>           *         Kr&uuml;ger</a>
933           */           */
934          public static Box createLegendPanel(List<FeatureTypeStyle> list,          public static JPanel createLegendPanel(Style style,
935                          SimpleFeatureType featureType, int iconWidth, int iconHeight) {                          final SimpleFeatureType featureType, final int iconWidth,
936                            final int iconHeight) {
937    
938                  Box box = new Box(BoxLayout.Y_AXIS) {                  final List<FeatureTypeStyle> list = style.featureTypeStyles();
939    
940                          /**                  final JPanel panel = new JPanel(new MigLayout("wrap 2", "[]:3:[]"));
                          * Nuetzlich wenn die Componente gedruckt (z.B. wenn ein Screenshot  
                          * gemacht wird) wird. Dann werden wird der Hintergrund auf WEISS  
                          * gesetzt.  
                          *  
                          * @author <a href="mailto:[email protected]">Stefan Alfons  
                          *         Kr&uuml;ger</a>  
                          */  
                         @Override  
                         public void print(Graphics g) {  
                                 final Color orig = getBackground();  
                                 setBackground(Color.WHITE);  
                                 // wrap in try/finally so that we always restore the state  
                                 try {  
                                         super.print(g);  
                                 } finally {  
                                         setBackground(orig);  
                                 }  
                         }  
                 };  
941    
942                  for (FeatureTypeStyle ftStyle : list) {                  if (style == null) {
943                            // No Style => no legend
944                            return panel;
945                    }
946    
947                    for (final FeatureTypeStyle ftStyle : list) {
948    
949                          // One child-node for every rule                          // One child-node for every rule
950                          List<Rule> rules = ftStyle.rules();                          final List<Rule> rules = ftStyle.rules();
951                          for (Rule rule : rules) {                          for (final Rule rule : rules) {
952    
953                                    // Check if this RULE shall actually appear in the legend
954                                    if (rule.getName() != null && rule.getName().endsWith(HIDE_IN_LAYER_LEGEND_HINT))
955                                            continue;
956    
957                                  /**                                  /**
958                                   * Let's not create a hbox for Rules that only contain                                   * Let's not create a hbox for Rules that only contain
# Line 922  public class StyledLayerUtil { Line 962  public class StyledLayerUtil {
962                                                  .size() == rule.getSymbolizers().length)                                                  .size() == rule.getSymbolizers().length)
963                                          continue;                                          continue;
964    
                                 Box hbox = new Box(BoxLayout.X_AXIS) {  
   
                                         /**  
                                          * Nuetzlich wenn die Componente gedruckt (z.B. wenn ein  
                                          * Screenshot gemacht wird) wird. Dann werden wird der  
                                          * Hintergrund auf WEISS gesetzt.  
                                          */  
                                         @Override  
                                         public void print(Graphics g) {  
                                                 final Color orig = getBackground();  
                                                 setBackground(Color.WHITE);  
                                                 // wrap in try/finally so that we always restore the  
                                                 // state  
                                                 try {  
                                                         super.print(g);  
                                                 } finally {  
                                                         setBackground(orig);  
                                                 }  
                                         }  
                                 };  
   
                                 /**  
                                  * The size of the legend Symbol is dependent on the size of the  
                                  * font.  
                                  */  
                                 final int fontHeight = new JLabel().getFontMetrics(  
                                                 new JLabel().getFont()).getHeight();  
   
                                 final Dimension ICON_SIZE = new Dimension(iconWidth,  
                                                 fontHeight > 5 ? fontHeight : iconHeight);  
   
                                 // ****************************************************************************  
                                 // Create the actual icon  
                                 // ****************************************************************************  
965                                  final BufferedImage imageForRule = LegendIconFeatureRenderer                                  final BufferedImage imageForRule = LegendIconFeatureRenderer
966                                                  .getInstance().createImageForRule(rule, featureType,                                                  .getInstance().createImageForRule(rule, featureType,
967                                                                  ICON_SIZE);                                                                  new Dimension(iconWidth, iconHeight));
   
                                 // LOGGER.debug("Creating a new Legend Image for RUle name =  
                                 // "+rule.getName());  
968    
969                                  ImageIcon legendIcon = new ImageIcon(imageForRule);                                  final ImageIcon legendIcon = new ImageIcon(imageForRule);
970    
971                                  final JLabel iconLabel = new JLabel(legendIcon);                                  final JLabel iconLabel = new JLabel(legendIcon);
972                                  hbox.setAlignmentX(0f);                                  panel.add(iconLabel, "sgx1");
973                                  hbox.add(iconLabel);                                  // hbox.setAlignmentX(0f);
974                                  hbox.add(Box.createHorizontalStrut(3));                                  // hbox.add(iconLabel);
975                                    // hbox.add(Box.createHorizontalStrut(3));
                                 // ****************************************************************************  
                                 // The labeltext is read from the SLD. Its either the title  
                                 // directly, or interpreted as OneLine Code  
                                 // ****************************************************************************  
                                 // final String rawText =  
                                 // rule.getDescription().getTitle().toString();  
                                 final String rawText = rule.getDescription().getTitle()  
                                                 .toString();  
   
                                 Translation labelT = new Translation();  
                                 labelT.fromOneLine(rawText);  
976    
977                                    final Translation labelT = new Translation();
978                                    labelT.fromOneLine(rule.getDescription().getTitle());
979                                  final JLabel classTitleLabel = new JLabel(labelT.toString());                                  final JLabel classTitleLabel = new JLabel(labelT.toString());
                                 hbox.add(classTitleLabel);  
                                 classTitleLabel.setLabelFor(iconLabel);  
   
                                 box.add(hbox);  
980    
981                                    panel.add(classTitleLabel, "sgx2");
982                                    classTitleLabel.setLabelFor(iconLabel);
983                          }                          }
984                  }                  }
985    
986                  return box;                  return panel;
987          }          }
988    
989          /**          /**
990           * Creates a           * Creates a {@link JComponent} that contains a legend for a given
991             * rasterLayer and a given {@link Style}.
992           *           *
993           * @param styledGrid           * @param style
994           * @param iconHeight           *            if <code>null</code>, the default {@link Style} is extracetd
995           * @param iconWidth           *            from the {@link StyledRasterInterface}
          * @return  
996           */           */
997          public static Box createLegendPanel(StyledRasterInterface<?> styledGrid,          public static JPanel createLegendPanel(
998                          int iconWidth, int iconHeight) {                          final StyledRasterInterface<?> styledRaster, Style style,
999                  RasterLegendData rasterLegendData = styledGrid.getLegendMetaData();                          final int iconWidth, final int iconHeight) {
1000                  Set<Double> legendRasterValues = rasterLegendData.keySet();  
1001                  Map<Double, GridCoverage2D> sampleRasters = rasterLegendData                  // If no style is given, we use the default style for this layer
1002                    if (style == null)
1003                            style = styledRaster.getStyle();
1004    
1005                    /**
1006                     * Determine whether a Style is responsible for the coloring
1007                     */
1008                    ColorModel colorModel = null;
1009                    if (!isStyleable(styledRaster)
1010                                    || (isStyleable(styledRaster) && style == null)) {
1011                            colorModel = getColorModel(styledRaster);
1012                    }
1013    
1014                    final RasterLegendData rasterLegendData = styledRaster
1015                                    .getLegendMetaData();
1016                    final List<Double> legendRasterValues = rasterLegendData
1017                                    .getSortedKeys();
1018                    final Map<Double, GridCoverage2D> sampleRasters = rasterLegendData
1019                                  .createSampleRasters();                                  .createSampleRasters();
1020    
1021                  Box box = new Box(BoxLayout.Y_AXIS) {                  final JPanel panel = new JPanel(new MigLayout("wrap 2, gapy 0"));
1022    
1023                          /**                  for (final Double rValue : legendRasterValues) {
                          * Nuetzlich wenn die Componente gedruckt (z.B. wenn ein Screenshot  
                          * gemacht wird) wird. Dann werden wird der Hintergrund auf WEISS  
                          * gesetzt.  
                          */  
                         @Override  
                         public void print(Graphics g) {  
                                 final Color orig = getBackground();  
                                 setBackground(Color.WHITE);  
                                 // wrap in try/finally so that we always restore the state  
                                 try {  
                                         super.print(g);  
                                 } finally {  
                                         setBackground(orig);  
                                 }  
                         }  
                 };  
1024    
1025                  for (Double rValue : legendRasterValues) {                          // final Dimension ICON_SIZE = new Dimension(iconWidth,
1026                            // new JLabel().getFontMetrics(new JLabel().getFont())
1027                            // .getHeight() > 5 ? new JLabel().getFontMetrics(
1028                            // new JLabel().getFont()).getHeight() : iconHeight);
1029    
1030                          /**                          // ****************************************************************************
1031                           * The coverage contains only one value of value rValue                          // Create the actual icon
1032                           */                          // ****************************************************************************
1033                          GridCoverage2D sampleCov = sampleRasters.get(rValue);                          final BufferedImage buffImage = new BufferedImage(iconWidth,
1034                          GridCoverageRenderer renderer;                                          iconHeight, BufferedImage.TYPE_INT_ARGB);
1035                          try {  
1036                                  renderer = new GridCoverageRenderer(sampleCov                          final Graphics2D graphics = buffImage.createGraphics();
                                                 .getCoordinateReferenceSystem(), JTSUtil  
                                                 .createEnvelope(sampleCov.getEnvelope()),  
                                                 new Rectangle(iconWidth, iconHeight),  
                                                 (AffineTransform) null);  
                         } catch (Exception e1) {  
                                 throw new RuntimeException(  
                                                 "Creating the GridCoverageRenderer:", e1);  
                         }  
1037    
1038                          /**                          if (colorModel != null) {
1039                           *                                  // The colors come from the ColorModel!
1040                           */  
1041                          Box hbox = new Box(BoxLayout.X_AXIS) {                                  try {
1042                                            Object inData = null;
1043                                            switch (colorModel.getTransferType()) {
1044                                            case DataBuffer.TYPE_BYTE:
1045                                                    inData = new byte[] { rValue.byteValue() };
1046                                                    break;
1047                                            case DataBuffer.TYPE_USHORT:
1048                                                    inData = new short[] { rValue.shortValue() };
1049                                                    break;
1050                                            case DataBuffer.TYPE_INT:
1051                                                    inData = new int[] { rValue.intValue() };
1052                                                    break;
1053                                            case DataBuffer.TYPE_SHORT:
1054                                                    inData = new short[] { rValue.shortValue() };
1055                                                    break;
1056                                            case DataBuffer.TYPE_FLOAT:
1057                                                    inData = new float[] { rValue.floatValue() };
1058                                                    break;
1059                                            case DataBuffer.TYPE_DOUBLE:
1060                                                    inData = new double[] { rValue.doubleValue() };
1061                                                    break;
1062                                            default:
1063                                                    inData = rValue.intValue();
1064                                            }
1065                                            final Color color = new Color(colorModel.getRGB(inData));
1066                                            graphics.setBackground(color);
1067                                            graphics.setColor(color);
1068                                            graphics.fillRect(0, 0, iconWidth, iconHeight);
1069                                    } catch (final Exception e) {
1070                                            LOGGER.info(
1071                                                            "Dann nehmen wir halt den GridCoverageRenderer", e);
1072                                            colorModel = null;
1073                                    }
1074                            } else {
1075                                    // The colors come from the Style
1076    
1077                                    /**
1078                                     * The coverage contains only one value of value rValue
1079                                     */
1080                                    final GridCoverage2D sampleCov = sampleRasters.get(rValue);
1081                                    GridCoverageRenderer renderer;
1082                                    try {
1083                                            renderer = new GridCoverageRenderer(sampleCov
1084                                                            .getCoordinateReferenceSystem(), JTSUtil
1085                                                            .createEnvelope(sampleCov.getEnvelope()),
1086                                                            new Rectangle(iconWidth, iconHeight),
1087                                                            (AffineTransform) null);
1088                                    } catch (final Exception e1) {
1089                                            throw new RuntimeException(
1090                                                            "Creating a GridCoverageRenderer failed:", e1);
1091                                    }
1092    
1093                                  /**                                  /**
1094                                   * Nuetzlich wenn die Componente gedruckt (z.B. wenn ein                                   * Iterate over all FeatureTypeStyles.
                                  * Screenshot gemacht wird) wird. Dann werden wird der  
                                  * Hintergrund auf WEISS gesetzt.  
1095                                   */                                   */
1096                                  @Override                                  final List<RasterSymbolizer> rSymbols = StylingUtil
1097                                  public void print(Graphics g) {                                                  .getRasterSymbolizers(style);
1098                                          final Color orig = getBackground();  
1099                                          setBackground(Color.WHITE);                                  for (final RasterSymbolizer symbolizer : rSymbols) {
                                         // wrap in try/finally so that we always restore the  
                                         // state  
1100                                          try {                                          try {
1101                                                  super.print(g);                                                  renderer.paint(graphics, sampleCov, symbolizer);
1102                                          } finally {                                          } catch (final Exception ee) {
1103                                                  setBackground(orig);                                                  LOGGER.error("Unable to paint " + symbolizer
1104                                                                    + " into the legend image", ee);
1105                                          }                                          }
1106                                  }                                  }
1107                          };                          }
1108    
1109                          final Dimension ICON_SIZE = new Dimension(iconWidth,                          final JLabel iconLabel = new JLabel(new ImageIcon(buffImage));
1110                                          new JLabel().getFontMetrics(new JLabel().getFont())                          panel.add(iconLabel, "sgx1");
                                                         .getHeight() > 5 ? new JLabel().getFontMetrics(  
                                                         new JLabel().getFont()).getHeight() : iconHeight);  
1111    
1112                          // ****************************************************************************                          final Translation labelT = rasterLegendData.get(rValue);
1113                          // Create the actual icon                          final JLabel classTitleLabel = new JLabel(labelT.toString());
1114                          // ****************************************************************************                          panel.add(classTitleLabel, "sgx2"
1115                          BufferedImage buffImage = new BufferedImage(ICON_SIZE.width,                                          + (rasterLegendData.isPaintGaps() ? ", gapy 0:0:0 5:5:5"
1116                                          ICON_SIZE.height, BufferedImage.TYPE_INT_ARGB);                                                          : ""));
1117                          Graphics2D graphics = buffImage.createGraphics();                          classTitleLabel.setLabelFor(iconLabel);
   
                         /**  
                          * Iterate over all FeatureTypeStyles.  
                          */  
                         // for (FeatureTypeStyle ftStyle : styledGrid.getStyle()  
                         // .featureTypeStyles()) {  
                         // One child-node for every rule  
                         // List<Rule> rules = ftStyle.rules();  
1118    
1119                          // for (Rule rule : rules) {                          if (rasterLegendData.isPaintGaps()) {
1120                          List<RasterSymbolizer> rSymbols = StylingUtil                                  iconLabel
1121                                          .getRasterSymbolizers(styledGrid.getStyle());                                                  .setBorder(BorderFactory.createLineBorder(Color.black));
   
                         for (RasterSymbolizer symbolizer : rSymbols) {  
                                 // LOGGER.debug("Creating a new Legend Image for RUle name =  
                                 // "+rule.getName());  
                                 try {  
                                         renderer.paint(graphics, sampleCov, symbolizer);  
                                 } catch (Exception e) {  
                                         LOGGER.error("Unable to paint " + symbolizer  
                                                         + " into the legend image", e);  
                                 }  
                                 // }  
                                 // }  
1122                          }                          }
1123    
1124                          ImageIcon legendIcon = new ImageIcon(buffImage);                  }
1125    
1126                          final JLabel iconLabel = new JLabel(legendIcon);                  return panel;
1127                          hbox.setAlignmentX(0f);          }
                         hbox.add(iconLabel);  
                         hbox.add(Box.createHorizontalStrut(3));  
1128    
1129                          Translation labelT = rasterLegendData.get(rValue);          /**
1130                          final JLabel classTitleLabel = new JLabel(labelT.toString());           * Extracts the {@link ColorModel} of any {@link StyledRasterInterface}. May
1131                          hbox.add(classTitleLabel);           * return <code>null</code> if the geoobject can not be accessed.
1132                          classTitleLabel.setLabelFor(iconLabel);           */
1133            @SuppressWarnings("unchecked")
1134            public static ColorModel getColorModel(
1135                            final StyledRasterInterface<?> styledGrid) {
1136                    ColorModel colorModel = null;
1137                    try {
1138                            final Object geoObject = styledGrid.getGeoObject();
1139                            if (geoObject instanceof GridCoverage2D) {
1140                                    final GridCoverage2D cov = (GridCoverage2D) geoObject;
1141                                    colorModel = cov.getRenderedImage().getColorModel();
1142                            } else if (styledGrid instanceof StyledRasterPyramidInterface) {
1143    
1144                                    final Parameter readGG = new Parameter(
1145                                                    AbstractGridFormat.READ_GRIDGEOMETRY2D);
1146    
1147                                    final ReferencedEnvelope mapExtend = new org.geotools.geometry.jts.ReferencedEnvelope(
1148                                                    styledGrid.getEnvelope(), styledGrid.getCrs());
1149    
1150                                    readGG.setValue(new GridGeometry2D(new GeneralGridEnvelope(
1151                                                    new Rectangle(0, 0, 1, 1)), mapExtend));
1152    
1153                                    final FeatureCollection<SimpleFeatureType, SimpleFeature> rFc = (FeatureCollection<SimpleFeatureType, SimpleFeature>) geoObject;
1154    
1155                                    final AbstractGridCoverage2DReader aReader = (AbstractGridCoverage2DReader) FeatureUtil
1156                                                    .getWrappedGeoObject(rFc);
1157                                    final GridCoverage2D cov = (GridCoverage2D) aReader
1158                                                    .read(new GeneralParameterValue[] { readGG });
1159                                    colorModel = cov.getRenderedImage().getColorModel();
1160                            }
1161                    } catch (final Exception e) {
1162                            LOGGER.error("Error reading the colormodel from " + styledGrid, e);
1163                            return null;
1164                    }
1165                    return colorModel;
1166            }
1167    
1168            /**
1169             * @return <code>true</code> if a {@link RasterSymbolizer} can be applied
1170             *         and will have an effect. Some rasters (e.g. GeoTIFF) can come
1171             *         with their own {@link ColorModel} and will ignore any
1172             *         {@link RasterSymbolizer} = SLD.
1173             */
1174            public static boolean isStyleable(
1175                            final StyledRasterInterface<?> styledRaster) {
1176                    final ColorModel colorModel = getColorModel(styledRaster);
1177    
1178                    // LOGGER.info("The colormodel of " + styledRaster.getTitle() + " is "
1179                    // + colorModel != null ? colorModel.getClass().getSimpleName() :
1180                    // "NULL");
1181    
1182                    if (colorModel == null)
1183                            return true;
1184                    if (colorModel instanceof ComponentColorModel)
1185                            return true;
1186                    return false;
1187            }
1188    
1189            /**
1190             * Set the given Style as the Style of the {@link MapLayer}, unless the
1191             * styles are the same (not comparing selection stuff). If the
1192             * {@link MapLayer}s {@link Style} is changed, the selection FTS is kept.<br/>
1193             * Remember {@link MapLayer#setStyle(Style)} triggers an event leading to a
1194             * repaint, so only use it when needed.
1195             *
1196             * @return <code>true</code> if the {@link MapLayer}'s {@link Style} has
1197             *         been changed.
1198             */
1199            public static boolean updateMapLayerStyleIfChangedAndKeepSelection(
1200                            MapLayer mapLayer, Style style2) {
1201    
1202                    Style mapLayerStyleCleaned = StylingUtil
1203                                    .removeSelectionFeatureTypeStyle(mapLayer.getStyle());
1204    
1205                    Style newStyleCleaned = StylingUtil
1206                                    .removeSelectionFeatureTypeStyle(style2);
1207    
1208                    if (StylingUtil.isStyleDifferent(mapLayerStyleCleaned, newStyleCleaned)) {
1209    
1210                          box.add(hbox);                          // They are different when compared without SELECTION FTS!
1211    
1212                            // Now let's copy any SELECTION FTS to the now style
1213                            FeatureTypeStyle selectionFeatureTypeStyle = StylingUtil
1214                                            .getSelectionFeatureTypeStyle(mapLayer.getStyle());
1215                            if (selectionFeatureTypeStyle != null) {
1216                                    newStyleCleaned.featureTypeStyles().add(
1217                                                    selectionFeatureTypeStyle);
1218                                    // newStyleCleaned is not so clean anymore... We just alled a
1219                                    // selcetion FTS
1220                            }
1221    
1222                            mapLayer.setStyle(newStyleCleaned);
1223    
1224                            return true;
1225    
1226                    } else {
1227                            return false;
1228                    }
1229            }
1230    
1231            /**
1232             * After loading an atlas, the AttribteMetaData contains whatever is written
1233             * in the XML. But the DBF may have changed! This method checks an
1234             * {@link AttributeMetadataMap} against a schema and also corrects
1235             * upperCase/lowerCase problems. It will also remove any geometry column
1236             * attribute metadata.
1237             */
1238            /**
1239             * After loading an atlas, the AttribteMetaData contains whatever is written
1240             * in the XML. But the DBF may have changed!
1241             */
1242            public static void checkAttribMetaData(
1243                            AttributeMetadataMap attributeMetaDataMap, SimpleFeatureType schema) {
1244    
1245                    ArrayList<Name> willRemove = new ArrayList<Name>();
1246    
1247                    // 1. Check.. all attributes in the atm should be in the schema as well.
1248                    // maybe correct some upperCase/loweCase stuff
1249    
1250                    for (AttributeMetadata atm : attributeMetaDataMap.values()) {
1251    
1252                            AttributeDescriptor foundDescr = schema
1253                                            .getDescriptor(atm.getName());
1254                            if (foundDescr == null) {
1255                                    Name bestMatch = FeatureUtil.findBestMatchingAttribute(schema,
1256                                                    atm.getLocalName());
1257                                    if (bestMatch == null)
1258                                            willRemove.add(atm.getName());
1259                                    else
1260                                            atm.setName(bestMatch);
1261                            } else if (foundDescr instanceof GeometryDescriptor) {
1262                                    // We don't want GeometryColumns in here
1263                                    willRemove.add(atm.getName());
1264                            }
1265                    }
1266    
1267                    // Remove the ones that were not findable in the schema
1268                    for (Name removeName : willRemove) {
1269                            if (attributeMetaDataMap.remove(removeName) == null) {
1270                                    LOGGER.warn("removing the AMData didn't work");
1271                            }
1272                  }                  }
1273    
1274                  return box;                  // 2. check... all attributes from the schema must have an ATM
1275                    for (AttributeDescriptor ad : schema.getAttributeDescriptors()) {
1276                            if (ad instanceof GeometryDescriptor)
1277                                    continue;
1278                            if (!attributeMetaDataMap.containsKey(ad.getName())) {
1279                                    attributeMetaDataMap.put(ad.getName(), new AttributeMetadata(
1280                                                    ad, schema.getAttributeDescriptors().indexOf(ad),
1281                                                    attributeMetaDataMap.getLanguages()));
1282                            }
1283                    }
1284          }          }
1285    
1286            /**
1287             * Checks every attribute name in the {@link AttributeMetadataMap} for its
1288             * binding type. It the type is textual, add the mrpty string as a NODATA
1289             * value.
1290             *
1291             * @param attributeMetaDataMap
1292             * @param schema
1293             */
1294            public static void addEmptyStringToAllTextualAttributes(
1295                            AttributeMetadataMap attributeMetaDataMap, SimpleFeatureType schema) {
1296    
1297                    for (Name name : attributeMetaDataMap.keySet()) {
1298                            if (String.class.isAssignableFrom(schema.getDescriptor(name)
1299                                            .getType().getBinding())) {
1300                                    attributeMetaDataMap.get(name).getNodataValues().add("");
1301                            }
1302                    }
1303            }
1304  }  }

Legend:
Removed from v.400  
changed lines
  Added in v.695

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26