/[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 403 by alfonx, Mon Sep 14 13:29:42 2009 UTC revision 526 by alfonx, Wed Nov 18 15:45:01 2009 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;  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;
 import java.io.IOException;  
44  import java.net.URL;  import java.net.URL;
45  import java.text.DecimalFormat;  import java.text.DecimalFormat;
 import java.util.HashMap;  
46  import java.util.List;  import java.util.List;
47  import java.util.Map;  import java.util.Map;
 import java.util.SortedMap;  
 import java.util.TreeMap;  
48    
49  import javax.swing.BorderFactory;  import javax.swing.BorderFactory;
 import javax.swing.Box;  
 import javax.swing.BoxLayout;  
50  import javax.swing.ImageIcon;  import javax.swing.ImageIcon;
51    import javax.swing.JComponent;
52  import javax.swing.JLabel;  import javax.swing.JLabel;
53    
54    import net.miginfocom.swing.MigLayout;
55    
56  import org.apache.log4j.Logger;  import org.apache.log4j.Logger;
57  import org.geotools.coverage.grid.GeneralGridEnvelope;  import org.geotools.coverage.grid.GeneralGridEnvelope;
58  import org.geotools.coverage.grid.GridCoverage2D;  import org.geotools.coverage.grid.GridCoverage2D;
59  import org.geotools.coverage.grid.GridGeometry2D;  import org.geotools.coverage.grid.GridGeometry2D;
60  import org.geotools.coverage.grid.io.AbstractGridCoverage2DReader;  import org.geotools.coverage.grid.io.AbstractGridCoverage2DReader;
61    import org.geotools.coverage.grid.io.AbstractGridFormat;
62  import org.geotools.feature.FeatureCollection;  import org.geotools.feature.FeatureCollection;
63  import org.geotools.gce.imagepyramid.ImagePyramidReader;  import org.geotools.feature.NameImpl;
64  import org.geotools.geometry.jts.ReferencedEnvelope;  import org.geotools.geometry.jts.ReferencedEnvelope;
65  import org.geotools.map.DefaultMapLayer;  import org.geotools.map.DefaultMapLayer;
66  import org.geotools.map.MapLayer;  import org.geotools.map.MapLayer;
67    import org.geotools.parameter.Parameter;
68  import org.geotools.renderer.lite.gridcoverage2d.GridCoverageRenderer;  import org.geotools.renderer.lite.gridcoverage2d.GridCoverageRenderer;
69  import org.geotools.styling.ColorMap;  import org.geotools.styling.ColorMap;
70  import org.geotools.styling.ColorMapEntry;  import org.geotools.styling.ColorMapEntry;
# Line 76  import org.jdom.Document; Line 76  import org.jdom.Document;
76  import org.jdom.Element;  import org.jdom.Element;
77  import org.jdom.input.SAXBuilder;  import org.jdom.input.SAXBuilder;
78  import org.jdom.output.XMLOutputter;  import org.jdom.output.XMLOutputter;
79    import org.opengis.feature.simple.SimpleFeature;
80  import org.opengis.feature.simple.SimpleFeatureType;  import org.opengis.feature.simple.SimpleFeatureType;
81    import org.opengis.feature.type.Name;
82  import org.opengis.parameter.GeneralParameterValue;  import org.opengis.parameter.GeneralParameterValue;
83    
84  import schmitzm.geotools.JTSUtil;  import schmitzm.geotools.JTSUtil;
85    import schmitzm.geotools.feature.FeatureUtil;
86  import schmitzm.geotools.styling.StylingUtil;  import schmitzm.geotools.styling.StylingUtil;
87  import schmitzm.io.IOUtil;  import schmitzm.io.IOUtil;
88  import schmitzm.lang.LangUtil;  import schmitzm.lang.LangUtil;
89    import schmitzm.swing.JPanel;
90  import schmitzm.swing.SwingUtil;  import schmitzm.swing.SwingUtil;
91  import skrueger.AttributeMetaData;  import skrueger.AttributeMetadata;
92  import skrueger.RasterLegendData;  import skrueger.RasterLegendData;
93  import skrueger.i8n.Translation;  import skrueger.i8n.Translation;
94    
# Line 128  public class StyledLayerUtil { Line 132  public class StyledLayerUtil {
132           *                if {@code null} is given as object or an error occurs           *                if {@code null} is given as object or an error occurs
133           *                during layer creation           *                during layer creation
134           */           */
135          public static MapLayer createMapLayer(Object object) throws Exception {          public static MapLayer createMapLayer(final Object object) throws Exception {
136                  return createMapLayer(object, null);                  return createMapLayer(object, null);
137          }          }
138    
# Line 147  public class StyledLayerUtil { Line 151  public class StyledLayerUtil {
151           *                if {@code null} is given as object or an error occurs           *                if {@code null} is given as object or an error occurs
152           *                during layer creation           *                during layer creation
153           */           */
154          public static MapLayer createMapLayer(Object object, Style forcedStyle)          public static MapLayer createMapLayer(Object object, final Style forcedStyle)
155                          throws Exception {                          throws Exception {
156                  MapLayer layer = null;                  MapLayer layer = null;
157                  Style style = null;                  Style style = null;
# Line 188  public class StyledLayerUtil { Line 192  public class StyledLayerUtil {
192           *                if {@code null} is given as object or an error occurs           *                if {@code null} is given as object or an error occurs
193           *                during creation           *                during creation
194           */           */
195          public static StyledLayerInterface<?> createStyledLayer(Object object,          public static StyledLayerInterface<?> createStyledLayer(
196                          String title) {                          final Object object, final String title) {
197                  return createStyledLayer(object, title, null);                  return createStyledLayer(object, title, null);
198          }          }
199    
# Line 208  public class StyledLayerUtil { Line 212  public class StyledLayerUtil {
212           *                if {@code null} is given as object or an error occurs           *                if {@code null} is given as object or an error occurs
213           *                during creation           *                during creation
214           */           */
215          public static StyledLayerInterface<?> createStyledLayer(Object object,          public static StyledLayerInterface<?> createStyledLayer(
216                          String title, StyledLayerStyle style) {                          final Object object, final String title,
217                            final StyledLayerStyle style) {
218                  StyledLayerInterface<?> styledLayer = null;                  StyledLayerInterface<?> styledLayer = null;
219    
220                  String id = (title != null) ? title : "defaultID";                  final String id = (title != null) ? title : "defaultID";
221    
222                  if (object instanceof GridCoverage2D)                  if (object instanceof GridCoverage2D)
223                          styledLayer = new StyledGridCoverage((GridCoverage2D) object, id,                          styledLayer = new StyledGridCoverage((GridCoverage2D) object, id,
# Line 241  public class StyledLayerUtil { Line 246  public class StyledLayerUtil {
246           *            indicated whether the visible or invisible entries are           *            indicated whether the visible or invisible entries are
247           *            returned           *            returned
248           */           */
249          public static SortedMap<Integer, AttributeMetaData> getVisibleAttributeMetaData(          public static AttributeMetadataMap getVisibleAttributeMetaData(
250                          Map<Integer, AttributeMetaData> amdMap, boolean visible) {                          final AttributeMetadataMap amdMap, final boolean visible) {
251                  SortedMap<Integer, AttributeMetaData> filteredMap = new TreeMap<Integer, AttributeMetaData>();  
252                  for (AttributeMetaData amd : amdMap.values())                  final AttributeMetadataMap filteredMap = new AttributeMetadataMap();
253                          if (amd.isVisible())                  for (final AttributeMetadata amd : amdMap.values())
254                                  filteredMap.put(amd.getColIdx(), amd);                          if (amd.isVisible() == visible)
255                                    filteredMap.put(amd.getName(), amd);
256    
257                  return filteredMap;                  return filteredMap;
258          }          }
259    
260          /**          /**
261           * Parses a {@link AttributeMetaData} object from an JDOM-{@link Element}.           * Parses a {@link AttributeMetadata} object from an JDOM-{@link Element}.
262           * This method works like {@link           * This method works like {@link
263           * AMLImport#parseDataAttribute(org.w3c.dom.Node}, but for JDOM.           * AMLImport#parseDataAttribute(org.w3c.dom.Node}, but for JDOM.
264           *           *
265           * @param element           * @param element
266           *            {@link Element} to parse           *            {@link Element} to parse
267           */           */
268          public static AttributeMetaData parseAttributeMetaData(final Element element) {          public static AttributeMetadata parseAttributeMetaData(final Element element) {
269                  final Integer col = Integer.valueOf(element.getAttributeValue("col"));                  final String namespace = String.valueOf(element
270                                    .getAttributeValue("namespace"));
271                    final String localname = String.valueOf(element
272                                    .getAttributeValue("localname"));
273                    final Name aName = new NameImpl(namespace, localname);
274                  final Boolean visible = Boolean.valueOf(element                  final Boolean visible = Boolean.valueOf(element
275                                  .getAttributeValue("visible"));                                  .getAttributeValue("visible"));
276                  final String unit = element.getAttributeValue("unit");                  final String unit = element.getAttributeValue("unit");
# Line 276  public class StyledLayerUtil { Line 286  public class StyledLayerUtil {
286                          else if (childElement.getName().equals("desc"))                          else if (childElement.getName().equals("desc"))
287                                  desc = parseTranslation(childElement);                                  desc = parseTranslation(childElement);
288                  }                  }
289                  return new AttributeMetaData(col, visible, name, desc, unit);                  return new AttributeMetadata(aName, visible, name, desc, unit);
290          }          }
291    
292          /**          /**
293           * Parses a {@link AttributeMetaData} map from an JDOM-{@link Element} with           * Parses a {@link AttributeMetadata} map from an JDOM-{@link Element} with
294           * {@code <attribute>}-childs.           * {@code <attribute>}-childs.
295           *           *
296           * @param element           * @param element
297           *            {@link Element} to parse           *            {@link Element} to parse
298           */           */
299          public static Map<Integer, AttributeMetaData> parseAttributeMetaDataMap(          public static AttributeMetadataMap parseAttributeMetaDataMap(
300                          final Element element) {                          final Element element) {
301                  HashMap<Integer, AttributeMetaData> metaData = new HashMap<Integer, AttributeMetaData>();                  final AttributeMetadataMap metaData = new AttributeMetadataMap();
302                  List<Element> attributesElements = element                  final List<Element> attributesElements = element
303                                  .getChildren(ELEM_NAME_ATTRIBUTE);                                  .getChildren(ELEM_NAME_ATTRIBUTE);
304                  for (Element attibuteElement : attributesElements) {                  for (final Element attibuteElement : attributesElements) {
305                          AttributeMetaData attrMetaData = parseAttributeMetaData(attibuteElement);                          final AttributeMetadata attrMetaData = parseAttributeMetaData(attibuteElement);
306                          metaData.put(attrMetaData.getColIdx(), attrMetaData);                          metaData.put(attrMetaData.getName(), attrMetaData);
307                  }                  }
308                  return metaData;                  return metaData;
309          }          }
310    
311          /**          /**
312           * Loads a {@link AttributeMetaData} object from an URL.           * Loads a {@link AttributeMetadata} object from an URL.
313           *           *
314           * @param documentUrl           * @param documentUrl
315           *            {@link URL} to parse           *            {@link URL} to parse
316           * @see #parseAttributeMetaData(Element)           * @see #parseAttributeMetaData(Element)
317           */           */
318          public static Map<Integer, AttributeMetaData> loadAttributeMetaDataMap(          public static AttributeMetadataMap loadAttributeMetaDataMap(
319                          final URL documentUrl) throws Exception {                          final URL documentUrl) throws Exception {
320                  Document document = SAX_BUILDER.build(documentUrl);                  final Document document = SAX_BUILDER.build(documentUrl);
321                  return parseAttributeMetaDataMap(document.getRootElement());                  return parseAttributeMetaDataMap(document.getRootElement());
322          }          }
323    
324          /**          /**
325           * Creates an JDOM {@link Element} for the given {@link AttributeMetaData}           * Creates an JDOM {@link Element} for the given {@link AttributeMetadata}
326           * object.           * object.
327           *           *
328           * @param amd           * @param amd
329           *            meta data for one attribute           *            meta data for one attribute
330           */           */
331          public static Element createAttributeMetaDataElement(          public static Element createAttributeMetaDataElement(
332                          final AttributeMetaData amd) {                          final AttributeMetadata amd) {
333                  final Element element = new Element(ELEM_NAME_ATTRIBUTE, AMLURI);                  final Element element = new Element(ELEM_NAME_ATTRIBUTE, AMLURI);
334                  element.setAttribute("col", String.valueOf(amd.getColIdx()));                  element.setAttribute("namespace", String.valueOf(amd.getName()
335                                    .getNamespaceURI()));
336                    element.setAttribute("localname", String.valueOf(amd.getLocalName()));
337                  element.setAttribute("visible", String.valueOf(amd.isVisible()));                  element.setAttribute("visible", String.valueOf(amd.isVisible()));
338                  element.setAttribute("unit", amd.getUnit());                  element.setAttribute("unit", amd.getUnit());
339                  // Creating a aml:name tag...                  // Creating a aml:name tag...
# Line 332  public class StyledLayerUtil { Line 344  public class StyledLayerUtil {
344          }          }
345    
346          /**          /**
347           * Creates an JDOM {@link Element} for the given {@link AttributeMetaData}           * Creates an JDOM {@link Element} for the given {@link AttributeMetadata}
348           * map.           * map.
349           *           *
350           * @param amdMap           * @param amdMap
351           *            map of attribute meta data           *            map of attribute meta data
352           */           */
353          public static Element createAttributeMetaDataMapElement(          public static Element createAttributeMetaDataMapElement(
354                          final Map<Integer, AttributeMetaData> amdMap) {                          final AttributeMetadataMap amdMap) {
355                  final Element element = new Element(ELEM_NAME_AMD, AMLURI);                  final Element element = new Element(ELEM_NAME_AMD, AMLURI);
356                  for (AttributeMetaData amd : amdMap.values())                  for (final AttributeMetadata amd : amdMap.values())
357                          element.addContent(createAttributeMetaDataElement(amd));                          element.addContent(createAttributeMetaDataElement(amd));
358                  return element;                  return element;
359          }          }
360    
361          /**          /**
362           * Saves a {@link AttributeMetaData AttributeMetaData-Map} to an URL.           * Saves a {@link AttributeMetadata AttributeMetaData-Map} to an URL.
363           *           *
364           * @param amdMap           * @param amdMap
365           *            map of {@link AttributeMetaData}           *            map of {@link AttributeMetadata}
366           * @param documentUrl           * @param documentUrl
367           *            {@link URL} to store the XML           *            {@link URL} to store the XML
368           */           */
369          public static void saveAttributeMetaDataMap(          public static void saveAttributeMetaDataMap(
370                          final Map<Integer, AttributeMetaData> amdMap, final URL documentUrl)                          final AttributeMetadataMap amdMap, final URL documentUrl)
371                          throws Exception {                          throws Exception {
372                  // Create XML-Document                  // Create XML-Document
373                  final FileWriter out = new FileWriter(new File(documentUrl.toURI()));                  final FileWriter out = new FileWriter(new File(documentUrl.toURI()));
# Line 372  public class StyledLayerUtil { Line 384  public class StyledLayerUtil {
384           * @param element           * @param element
385           *            {@link Element} to parse           *            {@link Element} to parse
386           */           */
387          public static RasterLegendData parseRasterLegendData(Element element) {          public static RasterLegendData parseRasterLegendData(final Element element) {
388    
389                  final boolean paintGaps = Boolean.valueOf(element                  final boolean paintGaps = Boolean.valueOf(element
390                                  .getAttributeValue("paintGaps"));                                  .getAttributeValue("paintGaps"));
391    
392                  RasterLegendData rld = new RasterLegendData(paintGaps);                  final RasterLegendData rld = new RasterLegendData(paintGaps);
393    
394                  for (Element childElement : (List<Element>) element.getChildren()) {                  for (final Element childElement : (List<Element>) element.getChildren()) {
395                          final String name = childElement.getName();                          final String name = childElement.getName();
396                          // Cancel if it's an attribute                          // Cancel if it's an attribute
397                          if (childElement.getChildren().size() == 0)                          if (childElement.getChildren().size() == 0)
# Line 399  public class StyledLayerUtil { Line 411  public class StyledLayerUtil {
411                                  // id label element is missing, the translation is searched                                  // id label element is missing, the translation is searched
412                                  // directly                                  // directly
413                                  // as childs of the rasterLegendItem element                                  // as childs of the rasterLegendItem element
414                                  Translation label = parseTranslation(labelElement != null ? labelElement                                  final Translation label = parseTranslation(labelElement != null ? labelElement
415                                                  : childElement);                                                  : childElement);
416                                  rld.put(value, label);                                  rld.put(value, label);
417                          }                          }
# Line 417  public class StyledLayerUtil { Line 429  public class StyledLayerUtil {
429           */           */
430          public static RasterLegendData loadRasterLegendData(final URL documentUrl)          public static RasterLegendData loadRasterLegendData(final URL documentUrl)
431                          throws Exception {                          throws Exception {
432                  Document document = SAX_BUILDER.build(documentUrl);                  final Document document = SAX_BUILDER.build(documentUrl);
433                  return parseRasterLegendData(document.getRootElement());                  return parseRasterLegendData(document.getRootElement());
434          }          }
435    
# Line 432  public class StyledLayerUtil { Line 444  public class StyledLayerUtil {
444                          final RasterLegendData rld) {                          final RasterLegendData rld) {
445                  final Element element = new Element(ELEM_NAME_RLD, AMLURI);                  final Element element = new Element(ELEM_NAME_RLD, AMLURI);
446                  element.setAttribute("paintGaps", rld.isPaintGaps().toString());                  element.setAttribute("paintGaps", rld.isPaintGaps().toString());
447                  for (Double key : rld.getSortedKeys()) {                  for (final Double key : rld.getSortedKeys()) {
448                          Element item = new Element(ELEM_NAME_RASTERLEGEND, AMLURI);                          final Element item = new Element(ELEM_NAME_RASTERLEGEND, AMLURI);
449                          item.setAttribute("value", key.toString());                          item.setAttribute("value", key.toString());
450                          item.addContent(createTranslationElement("label", rld.get(key)));                          item.addContent(createTranslationElement("label", rld.get(key)));
451                          element.addContent(item);                          element.addContent(item);
# Line 453  public class StyledLayerUtil { Line 465  public class StyledLayerUtil {
465           *            rounded to (null means no round; >= 0 means digits after           *            rounded to (null means no round; >= 0 means digits after
466           *            comma; < 0 means digits before comma)           *            comma; < 0 means digits before comma)
467           */           */
468          public static RasterLegendData generateRasterLegendData(ColorMap colorMap,          public static RasterLegendData generateRasterLegendData(
469                          boolean paintGaps, Integer digits) {                          final ColorMap colorMap, final boolean paintGaps,
470                  DecimalFormat decFormat = digits != null ? new DecimalFormat(SwingUtil                          final Integer digits) {
471                                  .getNumberFormatPattern(digits)) : null;                  final DecimalFormat decFormat = digits != null ? new DecimalFormat(
472                  RasterLegendData rld = new RasterLegendData(paintGaps);                                  SwingUtil.getNumberFormatPattern(digits)) : null;
473                  for (ColorMapEntry cme : colorMap.getColorMapEntries()) {                  final RasterLegendData rld = new RasterLegendData(paintGaps);
474                          double value = StylingUtil.getQuantityFromColorMapEntry(cme);                  for (final ColorMapEntry cme : colorMap.getColorMapEntries()) {
475                            final double value = StylingUtil.getQuantityFromColorMapEntry(cme);
476                          String label = cme.getLabel();                          String label = cme.getLabel();
477                          // if no label is set (e.g. quantitative style),                          // if no label is set (e.g. quantitative style),
478                          // use the value as label                          // use the value as label
# Line 485  public class StyledLayerUtil { Line 498  public class StyledLayerUtil {
498           *            rounded to (null means no round; >= 0 means digits after           *            rounded to (null means no round; >= 0 means digits after
499           *            comma; < 0 means digits before comma)           *            comma; < 0 means digits before comma)
500           */           */
501          public static RasterLegendData generateRasterLegendData(Style style,          public static RasterLegendData generateRasterLegendData(final Style style,
502                          boolean paintGaps, Integer digits) {                          final boolean paintGaps, final Integer digits) {
503                  ColorMap colorMap = StylingUtil.getColorMapFromStyle(style);                  final ColorMap colorMap = StylingUtil.getColorMapFromStyle(style);
504                  if (colorMap == null)                  if (colorMap == null)
505                          throw new IllegalArgumentException(                          throw new IllegalArgumentException(
506                                          "Color map can not be determined from style!");                                          "Color map can not be determined from style!");
# Line 520  public class StyledLayerUtil { Line 533  public class StyledLayerUtil {
533           *            {@link Element} to parse           *            {@link Element} to parse
534           */           */
535          public final static Translation parseTranslation(final Element element) {          public final static Translation parseTranslation(final Element element) {
536                  Translation trans = new Translation();                  final Translation trans = new Translation();
537    
538                  if (element == null)                  if (element == null)
539                          return trans;                          return trans;
# Line 562  public class StyledLayerUtil { Line 575  public class StyledLayerUtil {
575           * @param translation           * @param translation
576           *            Translation to store in the Element           *            Translation to store in the Element
577           */           */
578          public final static Element createTranslationElement(String tagname,          public final static Element createTranslationElement(final String tagname,
579                          Translation translation) {                          final Translation translation) {
580                  Element element = new Element(tagname, AMLURI);                  final Element element = new Element(tagname, AMLURI);
581                  if (translation == null)                  if (translation == null)
582                          throw new UnsupportedOperationException(                          throw new UnsupportedOperationException(
583                                          "Translation element can not be created from null!");                                          "Translation element can not be created from null!");
# Line 580  public class StyledLayerUtil { Line 593  public class StyledLayerUtil {
593    
594                  // add a <translation lang="..">..</tranlation> part to the element for                  // add a <translation lang="..">..</tranlation> part to the element for
595                  // all languages                  // all languages
596                  for (String lang : translation.keySet()) {                  for (final String lang : translation.keySet()) {
597                          Element translationElement = new Element(ELEM_NAME_TRANSLATION,                          final Element translationElement = new Element(
598                                          AMLURI);                                          ELEM_NAME_TRANSLATION, AMLURI);
599                          translationElement.setAttribute("lang", lang);                          translationElement.setAttribute("lang", lang);
600                          String translationString = translation.get(lang);                          String translationString = translation.get(lang);
601                          if (translationString == null)                          if (translationString == null)
# Line 602  public class StyledLayerUtil { Line 615  public class StyledLayerUtil {
615           * @param style           * @param style
616           *            a Style           *            a Style
617           */           */
618          public static void setStyledLayerStyle(StyledLayerInterface styledObject,          public static void setStyledLayerStyle(
619                          StyledLayerStyle<?> style) {                          final StyledLayerInterface styledObject,
620                            final StyledLayerStyle<?> style) {
621                  // set SLD style                  // set SLD style
622                  styledObject.setStyle(style.getGeoObjectStyle());                  styledObject.setStyle(style.getGeoObjectStyle());
623                  // set meta data                  // set meta data
624                  if (styledObject instanceof StyledGridCoverageInterface                  if (styledObject instanceof StyledGridCoverageInterface
625                                  && (style.getMetaData() instanceof RasterLegendData || style                                  && (style.getMetaData() instanceof RasterLegendData || style
626                                                  .getMetaData() == null)) {                                                  .getMetaData() == null)) {
627                          RasterLegendData sourceRld = (RasterLegendData) style.getMetaData();                          final RasterLegendData sourceRld = (RasterLegendData) style
628                          RasterLegendData destRld = ((StyledGridCoverageInterface) styledObject)                                          .getMetaData();
629                            final RasterLegendData destRld = ((StyledGridCoverageInterface) styledObject)
630                                          .getLegendMetaData();                                          .getLegendMetaData();
631                          if (destRld != null && sourceRld != null) {                          if (destRld != null && sourceRld != null) {
632                                  destRld.setPaintGaps(sourceRld.isPaintGaps());                                  destRld.setPaintGaps(sourceRld.isPaintGaps());
# Line 622  public class StyledLayerUtil { Line 637  public class StyledLayerUtil {
637                  }                  }
638                  if (styledObject instanceof StyledFeatureCollectionInterface                  if (styledObject instanceof StyledFeatureCollectionInterface
639                                  && (style.getMetaData() instanceof Map || style.getMetaData() == null)) {                                  && (style.getMetaData() instanceof Map || style.getMetaData() == null)) {
640                          Map<Integer, AttributeMetaData> sourceAmd = (Map<Integer, AttributeMetaData>) style                          final AttributeMetadataMap sourceAmd = (AttributeMetadataMap) style
641                                          .getMetaData();                                          .getMetaData();
642                          Map<Integer, AttributeMetaData> destAmd = ((StyledFeatureCollectionInterface) styledObject)                          final AttributeMetadataMap destAmd = ((StyledFeatureCollectionInterface) styledObject)
643                                          .getAttributeMetaDataMap();                                          .getAttributeMetaDataMap();
644                          if (destAmd != null && sourceAmd != null) {                          if (destAmd != null && sourceAmd != null) {
645                                  destAmd.clear();                                  destAmd.clear();
# Line 654  public class StyledLayerUtil { Line 669  public class StyledLayerUtil {
669           *         {@link StyledFeatureCollectionInterface}           *         {@link StyledFeatureCollectionInterface}
670           */           */
671          public static StyledLayerStyle<?> getStyledLayerStyle(          public static StyledLayerStyle<?> getStyledLayerStyle(
672                          StyledLayerInterface styledObject) {                          final StyledLayerInterface styledObject) {
673                  if (styledObject instanceof StyledGridCoverageInterface)                  if (styledObject instanceof StyledGridCoverageInterface)
674                          return getStyledLayerStyle((StyledGridCoverageInterface) styledObject);                          return getStyledLayerStyle((StyledGridCoverageInterface) styledObject);
675                  if (styledObject instanceof StyledFeatureCollectionInterface)                  if (styledObject instanceof StyledFeatureCollectionInterface)
# Line 673  public class StyledLayerUtil { Line 688  public class StyledLayerUtil {
688           *            a styled grid coverage           *            a styled grid coverage
689           */           */
690          public static StyledLayerStyle<RasterLegendData> getStyledLayerStyle(          public static StyledLayerStyle<RasterLegendData> getStyledLayerStyle(
691                          StyledGridCoverageInterface styledGC) {                          final StyledGridCoverageInterface styledGC) {
692                  return new StyledLayerStyle<RasterLegendData>(styledGC.getStyle(),                  return new StyledLayerStyle<RasterLegendData>(styledGC.getStyle(),
693                                  styledGC.getLegendMetaData());                                  styledGC.getLegendMetaData());
694          }          }
# Line 685  public class StyledLayerUtil { Line 700  public class StyledLayerUtil {
700           * @param styledFC           * @param styledFC
701           *            a styled feature collection           *            a styled feature collection
702           */           */
703          public static StyledLayerStyle<Map<Integer, AttributeMetaData>> getStyledLayerStyle(          public static StyledLayerStyle<AttributeMetadataMap> getStyledLayerStyle(
704                          StyledFeatureCollectionInterface styledFC) {                          final StyledFeatureCollectionInterface styledFC) {
705                  return new StyledLayerStyle<Map<Integer, AttributeMetaData>>(styledFC                  return new StyledLayerStyle<AttributeMetadataMap>(styledFC.getStyle(),
706                                  .getStyle(), styledFC.getAttributeMetaDataMap());                                  styledFC.getAttributeMetaDataMap());
707          }          }
708    
709          /**          /**
# Line 705  public class StyledLayerUtil { Line 720  public class StyledLayerUtil {
720           * @return {@code null} in case of any error           * @return {@code null} in case of any error
721           */           */
722          public static StyledLayerStyle<RasterLegendData> loadStyledRasterStyle(          public static StyledLayerStyle<RasterLegendData> loadStyledRasterStyle(
723                          URL geoObjectURL, String sldExt, String rldExt) {                          final URL geoObjectURL, final String sldExt, final String rldExt) {
724                  RasterLegendData metaData = null;                  RasterLegendData metaData = null;
725                  Style sldStyle = null;                  Style sldStyle = null;
726                  try {                  try {
727                          Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(                          final Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(
728                                          geoObjectURL, sldExt));                                          geoObjectURL, sldExt));
729                          // SLD must be present                          // SLD must be present
730                          if (styles == null || styles.length == 0)                          if (styles == null || styles.length == 0)
731                                  return null;                                  return null;
732                          sldStyle = styles[0];                          sldStyle = styles[0];
733                  } catch (Exception err) {                  } catch (final Exception err) {
734                          // SLD must be present                          // SLD must be present
735                          LangUtil.logDebugError(LOGGER, err);                          LangUtil.logDebugError(LOGGER, err);
736                          return null;                          return null;
# Line 724  public class StyledLayerUtil { Line 739  public class StyledLayerUtil {
739                  try {                  try {
740                          metaData = StyledLayerUtil.loadRasterLegendData(IOUtil                          metaData = StyledLayerUtil.loadRasterLegendData(IOUtil
741                                          .changeUrlExt(geoObjectURL, rldExt));                                          .changeUrlExt(geoObjectURL, rldExt));
742                  } catch (FileNotFoundException err) {                  } catch (final FileNotFoundException err) {
743                          // ignore missing raster legend data                          // ignore missing raster legend data
744                  } catch (Exception err) {                  } catch (final Exception err) {
745                          // any other error during legend data creation leads to error                          // any other error during legend data creation leads to error
746                          LangUtil.logDebugError(LOGGER, err);                          LangUtil.logDebugError(LOGGER, err);
747                          return null;                          return null;
# Line 749  public class StyledLayerUtil { Line 764  public class StyledLayerUtil {
764           * @return {@code null} in case of any error           * @return {@code null} in case of any error
765           */           */
766          public static StyledLayerStyle<RasterLegendData> loadStyledRasterStyle(          public static StyledLayerStyle<RasterLegendData> loadStyledRasterStyle(
767                          URL geoObjectURL) {                          final URL geoObjectURL) {
768                  return loadStyledRasterStyle(geoObjectURL, "sld", "rld");                  return loadStyledRasterStyle(geoObjectURL, "sld", "rld");
769          }          }
770    
771          /**          /**
772           * Loads a {@linkplain Style SLD-Style} and a {@linkplain AttributeMetaData           * Loads a {@linkplain Style SLD-Style} and a {@linkplain AttributeMetadata
773           * AttributeMetaData-Map} for a given geo-object (feature) source. The SLD           * AttributeMetaData-Map} for a given geo-object (feature) source. The SLD
774           * file must be present. A missing attribute meta-data file is tolerated.           * file must be present. A missing attribute meta-data file is tolerated.
775           *           *
# Line 766  public class StyledLayerUtil { Line 781  public class StyledLayerUtil {
781           *            file extention for the raster legend-data file           *            file extention for the raster legend-data file
782           * @return {@code null} in case of any error           * @return {@code null} in case of any error
783           */           */
784          public static StyledLayerStyle<Map<Integer, AttributeMetaData>> loadStyledFeatureStyle(          public static StyledLayerStyle<AttributeMetadataMap> loadStyledFeatureStyle(
785                          URL geoObjectURL, String sldExt, String rldExt) {                          final URL geoObjectURL, final String sldExt, final String rldExt) {
786                  Map<Integer, AttributeMetaData> metaData = null;                  AttributeMetadataMap metaData = null;
787                  Style sldStyle = null;                  Style sldStyle = null;
788                  try {                  try {
789                          Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(                          final Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(
790                                          geoObjectURL, sldExt));                                          geoObjectURL, sldExt));
791                          // SLD must be present                          // SLD must be present
792                          if (styles == null || styles.length == 0)                          if (styles == null || styles.length == 0)
793                                  return null;                                  return null;
794                          sldStyle = styles[0];                          sldStyle = styles[0];
795                  } catch (Exception err) {                  } catch (final Exception err) {
796                          // SLD must be present                          // SLD must be present
797                          LangUtil.logDebugError(LOGGER, err);                          LangUtil.logDebugError(LOGGER, err);
798                          return null;                          return null;
# Line 786  public class StyledLayerUtil { Line 801  public class StyledLayerUtil {
801                  try {                  try {
802                          metaData = StyledLayerUtil.loadAttributeMetaDataMap(IOUtil                          metaData = StyledLayerUtil.loadAttributeMetaDataMap(IOUtil
803                                          .changeUrlExt(geoObjectURL, rldExt));                                          .changeUrlExt(geoObjectURL, rldExt));
804                  } catch (FileNotFoundException err) {                  } catch (final FileNotFoundException err) {
805                          // ignore missing attribute meta data                          // ignore missing attribute meta data
806                  } catch (Exception err) {                  } catch (final Exception err) {
807                          // any other error during meta data creation leads to error                          // any other error during meta data creation leads to error
808                          LangUtil.logDebugError(LOGGER, err);                          LangUtil.logDebugError(LOGGER, err);
809                          return null;                          return null;
810                  }                  }
811    
812                  return new StyledLayerStyle<Map<Integer, AttributeMetaData>>(sldStyle,                  return new StyledLayerStyle<AttributeMetadataMap>(sldStyle, metaData);
                                 metaData);  
813          }          }
814    
815          /**          /**
816           * Loads a {@linkplain Style SLD-Style} from a {@code .sld} file and           * Loads a {@linkplain Style SLD-Style} from a {@code .sld} file and
817           * {@linkplain AttributeMetaData AttributeMetaData-Map} from a {@code .amd}           * {@linkplain AttributeMetadata AttributeMetaData-Map} from a {@code .amd}
818           * 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
819           * present. A missing attribute meta-data file is tolerated.           * present. A missing attribute meta-data file is tolerated.
820           *           *
# Line 812  public class StyledLayerUtil { Line 826  public class StyledLayerUtil {
826           *            file extention for the raster legend-data file           *            file extention for the raster legend-data file
827           * @return {@code null} in case of any error           * @return {@code null} in case of any error
828           */           */
829          public static StyledLayerStyle<Map<Integer, AttributeMetaData>> loadStyledFeatureStyle(          public static StyledLayerStyle<AttributeMetadataMap> loadStyledFeatureStyle(
830                          URL geoObjectURL) {                          final URL geoObjectURL) {
831                  return loadStyledFeatureStyle(geoObjectURL, "sld", "amd");                  return loadStyledFeatureStyle(geoObjectURL, "sld", "amd");
832          }          }
833    
# Line 830  public class StyledLayerUtil { Line 844  public class StyledLayerUtil {
844           * @param mdExt           * @param mdExt
845           *            file extention for the meta-data file           *            file extention for the meta-data file
846           */           */
847          public static <T> void saveStyledLayerStyle(StyledLayerStyle<T> style,          public static <T> void saveStyledLayerStyle(
848                          URL geoObjectURL, String sldExt, String mdExt) throws Exception {                          final StyledLayerStyle<T> style, final URL geoObjectURL,
849                            final String sldExt, final String mdExt) throws Exception {
850                  // Store the SLD                  // Store the SLD
851                  Style sldStyle = style.getGeoObjectStyle();                  final Style sldStyle = style.getGeoObjectStyle();
852                  if (sldStyle != null) {                  if (sldStyle != null) {
853                          StylingUtil.saveStyleToSLD(sldStyle, IOUtil.changeFileExt(new File(                          StylingUtil.saveStyleToSLD(sldStyle, IOUtil.changeFileExt(new File(
854                                          geoObjectURL.toURI()), sldExt));                                          geoObjectURL.toURI()), sldExt));
855                  }                  }
856    
857                  // Store the meta data                  // Store the meta data
858                  T metaData = style.getMetaData();                  final T metaData = style.getMetaData();
859                  if (metaData != null) {                  if (metaData != null) {
860                          if (metaData instanceof RasterLegendData) {                          if (metaData instanceof RasterLegendData) {
861                                  saveRasterLegendData((RasterLegendData) metaData, IOUtil                                  saveRasterLegendData((RasterLegendData) metaData, IOUtil
# Line 849  public class StyledLayerUtil { Line 864  public class StyledLayerUtil {
864                                  // Map<Integer,AttributeMetaData> ) { // LEIDER NICHT                                  // Map<Integer,AttributeMetaData> ) { // LEIDER NICHT
865                                  // KOMPILIERBAR!!                                  // KOMPILIERBAR!!
866                          } else if (metaData instanceof Map) {                          } else if (metaData instanceof Map) {
867                                  saveAttributeMetaDataMap(                                  saveAttributeMetaDataMap((AttributeMetadataMap) metaData,
868                                                  (Map<Integer, AttributeMetaData>) metaData, IOUtil                                                  IOUtil.changeUrlExt(geoObjectURL, mdExt));
                                                                 .changeUrlExt(geoObjectURL, mdExt));  
869                          } else                          } else
870                                  throw new UnsupportedOperationException(                                  throw new UnsupportedOperationException(
871                                                  "Export for meta data not yet supported: "                                                  "Export for meta data not yet supported: "
# Line 861  public class StyledLayerUtil { Line 875  public class StyledLayerUtil {
875    
876          /**          /**
877           * 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
878           * meta data ({@link RasterLegendData} or {@link AttributeMetaData}) to a           * meta data ({@link RasterLegendData} or {@link AttributeMetadata}) to a
879           * {@code .rld} or {@code .amd} file. for a given geo-object source.           * {@code .rld} or {@code .amd} file. for a given geo-object source.
880           *           *
881           * @param style           * @param style
# Line 869  public class StyledLayerUtil { Line 883  public class StyledLayerUtil {
883           * @param geoObjectURL           * @param geoObjectURL
884           *            URL of the (already read) raster object           *            URL of the (already read) raster object
885           */           */
886          public static void saveStyledLayerStyle(StyledLayerStyle<?> style,          public static void saveStyledLayerStyle(final StyledLayerStyle<?> style,
887                          URL geoObjectURL) throws Exception {                          final URL geoObjectURL) throws Exception {
888                  if (style.getMetaData() instanceof RasterLegendData)                  if (style.getMetaData() instanceof RasterLegendData)
889                          saveStyledLayerStyle(style, geoObjectURL, "sld", "rld");                          saveStyledLayerStyle(style, geoObjectURL, "sld", "rld");
890                  else                  else
# Line 878  public class StyledLayerUtil { Line 892  public class StyledLayerUtil {
892          }          }
893    
894          /**          /**
895           * Creates a {@link Box} that shows a legend for a list of           * Creates a {@link JPanel} that shows a legend for a list of
896           * {@link FeatureTypeStyle}s and a targeted featureType           * {@link FeatureTypeStyle}s and a targeted featureType
897           *           *
898           * @param featureType           * @param featureType
# Line 889  public class StyledLayerUtil { Line 903  public class StyledLayerUtil {
903           * @author <a href="mailto:[email protected]">Stefan Alfons           * @author <a href="mailto:[email protected]">Stefan Alfons
904           *         Kr&uuml;ger</a>           *         Kr&uuml;ger</a>
905           */           */
906          public static Box createLegendPanel(List<FeatureTypeStyle> list,          public static JPanel createLegendPanel(Style style,
907                          SimpleFeatureType featureType, int iconWidth, int iconHeight) {                          final SimpleFeatureType featureType, final int iconWidth,
908                            final int iconHeight) {
909    
910                  Box box = new Box(BoxLayout.Y_AXIS) {                  final List<FeatureTypeStyle> list = style.featureTypeStyles();
911    
912                          /**                  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);  
                                 }  
                         }  
                 };  
913    
914                  for (FeatureTypeStyle ftStyle : list) {                  if (style == null) {
915                            // No Style => no legend
916                            return panel;
917                    }
918    
919                    for (final FeatureTypeStyle ftStyle : list) {
920    
921                          // One child-node for every rule                          // One child-node for every rule
922                          List<Rule> rules = ftStyle.rules();                          final List<Rule> rules = ftStyle.rules();
923                          for (Rule rule : rules) {                          for (final Rule rule : rules) {
924    
925                                  /**                                  /**
926                                   * Let's not create a hbox for Rules that only contain                                   * Let's not create a hbox for Rules that only contain
# Line 929  public class StyledLayerUtil { Line 930  public class StyledLayerUtil {
930                                                  .size() == rule.getSymbolizers().length)                                                  .size() == rule.getSymbolizers().length)
931                                          continue;                                          continue;
932    
                                 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  
                                 // ****************************************************************************  
933                                  final BufferedImage imageForRule = LegendIconFeatureRenderer                                  final BufferedImage imageForRule = LegendIconFeatureRenderer
934                                                  .getInstance().createImageForRule(rule, featureType,                                                  .getInstance().createImageForRule(rule, featureType,
935                                                                  ICON_SIZE);                                                                  new Dimension(iconWidth, iconHeight));
   
                                 // LOGGER.debug("Creating a new Legend Image for RUle name =  
                                 // "+rule.getName());  
936    
937                                  ImageIcon legendIcon = new ImageIcon(imageForRule);                                  final ImageIcon legendIcon = new ImageIcon(imageForRule);
938    
939                                  final JLabel iconLabel = new JLabel(legendIcon);                                  final JLabel iconLabel = new JLabel(legendIcon);
940                                  hbox.setAlignmentX(0f);                                  panel.add(iconLabel, "sgx1");
941                                  hbox.add(iconLabel);                                  // hbox.setAlignmentX(0f);
942                                  hbox.add(Box.createHorizontalStrut(3));                                  // hbox.add(iconLabel);
943                                    // 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);  
944    
945                                    final Translation labelT = new Translation();
946                                    labelT.fromOneLine(rule.getDescription().getTitle());
947                                  final JLabel classTitleLabel = new JLabel(labelT.toString());                                  final JLabel classTitleLabel = new JLabel(labelT.toString());
                                 hbox.add(classTitleLabel);  
                                 classTitleLabel.setLabelFor(iconLabel);  
   
                                 box.add(hbox);  
948    
949                                    panel.add(classTitleLabel, "sgx2");
950                                    classTitleLabel.setLabelFor(iconLabel);
951                          }                          }
952                  }                  }
953    
954                  return box;                  return panel;
955          }          }
956    
957          /**          /**
958           * Creates a           * Creates a {@link JComponent} that contains a legend for a given
959             * rasterLayer and a given {@link Style}.
960           *           *
961           * @param styledGrid           * @param style
962           * @param iconHeight           *            if <code>null</code>, the default {@link Style} is extracetd
963           * @param iconWidth           *            from the {@link StyledRasterInterface}
          * @return  
964           */           */
965          public static Box createLegendPanel(StyledRasterInterface<?> styledGrid,          public static JPanel createLegendPanel(
966                          int iconWidth, int iconHeight) {                          final StyledRasterInterface<?> styledRaster, Style style,
967                            final int iconWidth, final int iconHeight) {
968    
969                    // If no style is given, we use the default style for this layer
970                    if (style == null)
971                            style = styledRaster.getStyle();
972    
973                  /**                  /**
974                   * Determine whether a Style is responsible for the coloring                   * Determine whether a Style is responsible for the coloring
975                   */                   */
                 Object geoObject = styledGrid.getGeoObject();  
976                  ColorModel colorModel = null;                  ColorModel colorModel = null;
977                  if (geoObject instanceof GridCoverage2D) {                  if (!isStyleable(styledRaster)
978                          GridCoverage2D cov = (GridCoverage2D) geoObject;                                  || (isStyleable(styledRaster) && style == null)) {
979                          colorModel = cov.getRenderedImage().getColorModel();                          colorModel = getColorModel(styledRaster);
                 } else if (geoObject instanceof ImagePyramidReader) {  
   
                         org.geotools.parameter.Parameter readGG = new org.geotools.parameter.Parameter(  
                                         org.geotools.coverage.grid.io.AbstractGridFormat.READ_GRIDGEOMETRY2D);  
   
                         ReferencedEnvelope mapExtend = new org.geotools.geometry.jts.ReferencedEnvelope(  
                                         styledGrid.getEnvelope(), styledGrid.getCrs());  
   
                         readGG.setValue(new GridGeometry2D(new GeneralGridEnvelope(  
                                         new Rectangle(0, 0, 10, 10)), mapExtend));  
   
                         final AbstractGridCoverage2DReader aReader = (AbstractGridCoverage2DReader) geoObject;  
                         try {  
                                 GridCoverage2D cov = (GridCoverage2D) aReader  
                                                 .read(new GeneralParameterValue[] { readGG });  
                                 colorModel = cov.getRenderedImage().getColorModel();  
                         } catch (IllegalArgumentException e) {  
                                 e.printStackTrace();  
                         } catch (IOException e) {  
                                 e.printStackTrace();  
                         }  
980                  }                  }
981    
982                  RasterLegendData rasterLegendData = styledGrid.getLegendMetaData();                  final RasterLegendData rasterLegendData = styledRaster
983                  List<Double> legendRasterValues = rasterLegendData.getSortedKeys();                                  .getLegendMetaData();
984                  Map<Double, GridCoverage2D> sampleRasters = rasterLegendData                  final List<Double> legendRasterValues = rasterLegendData
985                                    .getSortedKeys();
986                    final Map<Double, GridCoverage2D> sampleRasters = rasterLegendData
987                                  .createSampleRasters();                                  .createSampleRasters();
988    
989                  Box box = new Box(BoxLayout.Y_AXIS) {                  final JPanel panel = new JPanel(new MigLayout("wrap 2"));
   
                         /**  
                          * 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);  
                                 }  
                         }  
                 };  
   
                 for (Double rValue : legendRasterValues) {  
   
                         /**  
                          *  
                          */  
                         Box hbox = new Box(BoxLayout.X_AXIS) {  
990    
991                                  /**                  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);  
                                         }  
                                 }  
                         };  
992    
993                          final Dimension ICON_SIZE = new Dimension(iconWidth,                          // final Dimension ICON_SIZE = new Dimension(iconWidth,
994                                          new JLabel().getFontMetrics(new JLabel().getFont())                          // new JLabel().getFontMetrics(new JLabel().getFont())
995                                                          .getHeight() > 5 ? new JLabel().getFontMetrics(                          // .getHeight() > 5 ? new JLabel().getFontMetrics(
996                                                          new JLabel().getFont()).getHeight() : iconHeight);                          // new JLabel().getFont()).getHeight() : iconHeight);
997    
998                          // ****************************************************************************                          // ****************************************************************************
999                          // Create the actual icon                          // Create the actual icon
1000                          // ****************************************************************************                          // ****************************************************************************
1001                          BufferedImage buffImage = new BufferedImage(ICON_SIZE.width,                          final BufferedImage buffImage = new BufferedImage(iconWidth,
1002                                          ICON_SIZE.height, BufferedImage.TYPE_INT_ARGB);                                          iconHeight, BufferedImage.TYPE_INT_ARGB);
1003                          Graphics2D graphics = buffImage.createGraphics();  
1004                            final Graphics2D graphics = buffImage.createGraphics();
1005    
1006                            if (colorModel != null) {
1007                                    // The colors come from the ColorModel!
1008    
                         if (colorModel != null)  
1009                                  try {                                  try {
1010                                          final int rgb = colorModel.getRGB(rValue.intValue());                                          Object inData = null;
1011                                          final Color color = new Color(rgb);                                          switch (colorModel.getTransferType()) {
1012                                            case DataBuffer.TYPE_BYTE:
1013                                                    inData = new byte[] { rValue.byteValue() };
1014                                                    break;
1015                                            case DataBuffer.TYPE_USHORT:
1016                                                    inData = new short[] { rValue.shortValue() };
1017                                                    break;
1018                                            case DataBuffer.TYPE_INT:
1019                                                    inData = new int[] { rValue.intValue() };
1020                                                    break;
1021                                            case DataBuffer.TYPE_SHORT:
1022                                                    inData = new short[] { rValue.shortValue() };
1023                                                    break;
1024                                            case DataBuffer.TYPE_FLOAT:
1025                                                    inData = new float[] { rValue.floatValue() };
1026                                                    break;
1027                                            case DataBuffer.TYPE_DOUBLE:
1028                                                    inData = new double[] { rValue.doubleValue() };
1029                                                    break;
1030                                            default:
1031                                                    inData = rValue.intValue();
1032                                            }
1033                                            final Color color = new Color(colorModel.getRGB(inData));
1034                                          graphics.setBackground(color);                                          graphics.setBackground(color);
1035                                          graphics.setColor(color);                                          graphics.setColor(color);
1036                                          graphics.fillRect(0, 0, ICON_SIZE.width, ICON_SIZE.height);                                          graphics.fillRect(0, 0, iconWidth, iconHeight);
1037                                  } catch (Exception e) {                                  } catch (final Exception e) {
1038                                          LOGGER.debug("Dann nehmen wir den GridCoverageRenderer", e);                                          LOGGER.info(
1039                                                            "Dann nehmen wir halt den GridCoverageRenderer", e);
1040                                          /**                                          colorModel = null;
1041                                           * The coverage contains only one value of value rValue                                  }
1042                                           */                          } else {
1043                                          GridCoverage2D sampleCov = sampleRasters.get(rValue);                                  // The colors come from the Style
                                         GridCoverageRenderer renderer;  
                                         try {  
                                                 renderer = new GridCoverageRenderer(sampleCov  
                                                                 .getCoordinateReferenceSystem(), JTSUtil  
                                                                 .createEnvelope(sampleCov.getEnvelope()),  
                                                                 new Rectangle(iconWidth, iconHeight),  
                                                                 (AffineTransform) null);  
                                         } catch (Exception e1) {  
                                                 throw new RuntimeException(  
                                                                 "Creating the GridCoverageRenderer:", e1);  
                                         }  
1044    
1045                                          /**                                  /**
1046                                           * Iterate over all FeatureTypeStyles.                                   * The coverage contains only one value of value rValue
1047                                           */                                   */
1048                                          // for (FeatureTypeStyle ftStyle : styledGrid.getStyle()                                  final GridCoverage2D sampleCov = sampleRasters.get(rValue);
1049                                          // .featureTypeStyles()) {                                  GridCoverageRenderer renderer;
1050                                          // One child-node for every rule                                  try {
1051                                          // List<Rule> rules = ftStyle.rules();                                          renderer = new GridCoverageRenderer(sampleCov
1052                                          // for (Rule rule : rules) {                                                          .getCoordinateReferenceSystem(), JTSUtil
1053                                          final Style style = styledGrid.getStyle();                                                          .createEnvelope(sampleCov.getEnvelope()),
1054                                          List<RasterSymbolizer> rSymbols = StylingUtil                                                          new Rectangle(iconWidth, iconHeight),
1055                                                          .getRasterSymbolizers(style);                                                          (AffineTransform) null);
1056                                    } catch (final Exception e1) {
1057                                          for (RasterSymbolizer symbolizer : rSymbols) {                                          throw new RuntimeException(
1058                                                  // LOGGER.debug("Creating a new Legend Image for RUle                                                          "Creating a GridCoverageRenderer failed:", e1);
                                                 // name =  
                                                 // "+rule.getName());  
                                                 try {  
                                                         renderer.paint(graphics, sampleCov, symbolizer);  
                                                 } catch (Exception ee) {  
                                                         LOGGER.error("Unable to paint " + symbolizer  
                                                                         + " into the legend image", ee);  
                                                 }  
                                                 // }  
                                                 // }  
                                         }  
1059                                  }                                  }
1060    
1061                          ImageIcon legendIcon = new ImageIcon(buffImage);                                  /**
1062                                     * Iterate over all FeatureTypeStyles.
1063                                     */
1064                                    final List<RasterSymbolizer> rSymbols = StylingUtil
1065                                                    .getRasterSymbolizers(style);
1066    
1067                                    for (final RasterSymbolizer symbolizer : rSymbols) {
1068                                            try {
1069                                                    renderer.paint(graphics, sampleCov, symbolizer);
1070                                            } catch (final Exception ee) {
1071                                                    LOGGER.error("Unable to paint " + symbolizer
1072                                                                    + " into the legend image", ee);
1073                                            }
1074                                    }
1075                            }
1076    
1077                          final JLabel iconLabel = new JLabel(legendIcon);                          final JLabel iconLabel = new JLabel(new ImageIcon(buffImage));
1078                          hbox.setAlignmentX(0f);                          // hbox.setAlignmentX(0f);
1079                          hbox.add(iconLabel);                          panel.add(iconLabel, "sgx1");
1080                          hbox.add(Box.createHorizontalStrut(3));                          // hbox.add(Box.createHorizontalStrut(3));
1081    
1082                          Translation labelT = rasterLegendData.get(rValue);                          final Translation labelT = rasterLegendData.get(rValue);
1083                          final JLabel classTitleLabel = new JLabel(labelT.toString());                          final JLabel classTitleLabel = new JLabel(labelT.toString());
1084                          hbox.add(classTitleLabel);                          panel.add(classTitleLabel, "sgx2"
1085                                            + (rasterLegendData.getPaintGaps() ? ", gapy 0 3" : ""));
1086                          classTitleLabel.setLabelFor(iconLabel);                          classTitleLabel.setLabelFor(iconLabel);
1087    
1088                          box.add(hbox);                          // box.add(hbox);
1089    
1090                          if (rasterLegendData.getPaintGaps()) {                          if (rasterLegendData.getPaintGaps()) {
1091                                  iconLabel                                  iconLabel
1092                                                  .setBorder(BorderFactory.createLineBorder(Color.black));                                                  .setBorder(BorderFactory.createLineBorder(Color.black));
                                 box.add(Box.createVerticalStrut(3));  
1093                          }                          }
1094    
1095                  }                  }
1096    
1097                  return box;                  return panel;
1098            }
1099    
1100            /**
1101             * Extracts the {@link ColorModel} of any {@link StyledRasterInterface}. May
1102             * return <code>null</code> if the geoobject can not be accessed.
1103             */
1104            @SuppressWarnings("unchecked")
1105            public static ColorModel getColorModel(
1106                            final StyledRasterInterface<?> styledGrid) {
1107                    ColorModel colorModel = null;
1108                    try {
1109                            final Object geoObject = styledGrid.getGeoObject();
1110                            if (geoObject instanceof GridCoverage2D) {
1111                                    final GridCoverage2D cov = (GridCoverage2D) geoObject;
1112                                    colorModel = cov.getRenderedImage().getColorModel();
1113                            } else if (styledGrid instanceof StyledRasterPyramidInterface) {
1114    
1115                                    final Parameter readGG = new Parameter(
1116                                                    AbstractGridFormat.READ_GRIDGEOMETRY2D);
1117    
1118                                    final ReferencedEnvelope mapExtend = new org.geotools.geometry.jts.ReferencedEnvelope(
1119                                                    styledGrid.getEnvelope(), styledGrid.getCrs());
1120    
1121                                    readGG.setValue(new GridGeometry2D(new GeneralGridEnvelope(
1122                                                    new Rectangle(0, 0, 1, 1)), mapExtend));
1123    
1124                                    final FeatureCollection<SimpleFeatureType, SimpleFeature> rFc = (FeatureCollection<SimpleFeatureType, SimpleFeature>) geoObject;
1125    
1126                                    final AbstractGridCoverage2DReader aReader = (AbstractGridCoverage2DReader) FeatureUtil
1127                                                    .getWrappedGeoObject(rFc);
1128                                    final GridCoverage2D cov = (GridCoverage2D) aReader
1129                                                    .read(new GeneralParameterValue[] { readGG });
1130                                    colorModel = cov.getRenderedImage().getColorModel();
1131                            }
1132                    } catch (final Exception e) {
1133                            LOGGER.error("Error reading the colormodel from " + styledGrid, e);
1134                            return null;
1135                    }
1136                    return colorModel;
1137            }
1138    
1139            /**
1140             * @return <code>true</code> if a {@link RasterSymbolizer} can be applied
1141             *         and will have an effect. Some rasters (e.g. GeoTIFF) can come
1142             *         with their own {@link ColorModel} and will ignore any
1143             *         {@link RasterSymbolizer} = SLD.
1144             */
1145            public static boolean isStyleable(
1146                            final StyledRasterInterface<?> styledRaster) {
1147                    final ColorModel colorModel = getColorModel(styledRaster);
1148                    
1149    //              LOGGER.info("The colormodel of " + styledRaster.getTitle() + " is "
1150    //                              + colorModel != null ? colorModel.getClass().getSimpleName() : "NULL");
1151    
1152                    if (colorModel == null)
1153                            return true;
1154                    if (colorModel instanceof ComponentColorModel)
1155                            return true;
1156                    return false;
1157            }
1158    
1159            /**
1160             * Set the given Style as the Style of the {@link MapLayer}, unless the
1161             * styles are the same (not comparing selection stuff). If the
1162             * {@link MapLayer}s {@link Style} is changed, the selection FTS is kept.<br/>
1163             * Remember {@link MapLayer#setStyle(Style)} triggers an event leading to a
1164             * repaint, so only use it when needed.
1165             *
1166             * @return <code>true</code> if the {@link MapLayer}'s {@link Style} has been changed.
1167             */
1168            public static boolean updateMapLayerStyleIfChangedAndKeepSelection(MapLayer mapLayer,
1169                            Style style2) {
1170    
1171                    Style mapLayerStyleCleaned = StylingUtil
1172                                                    .removeSelectionFeatureTypeStyle(mapLayer.getStyle());
1173                    
1174                    Style newStyleCleaned = StylingUtil.removeSelectionFeatureTypeStyle(style2);
1175                    
1176                    if (StylingUtil.isStyleDifferent(mapLayerStyleCleaned,
1177                                    newStyleCleaned)) {
1178                            
1179                            // They are different when compared without SELECTION FTS!
1180                            
1181                            // Now let's copy any SELECTION FTS to the now style
1182                            FeatureTypeStyle selectionFeatureTypeStyle = StylingUtil.getSelectionFeatureTypeStyle( mapLayer.getStyle() );
1183                            if (selectionFeatureTypeStyle != null) {
1184                                    newStyleCleaned.featureTypeStyles().add(selectionFeatureTypeStyle);
1185                                    // newStyleCleaned is not so clean anymore... We just alled a selcetion FTS
1186                            }  
1187                            
1188                            mapLayer.setStyle(newStyleCleaned);
1189                            
1190                            return true;
1191                            
1192                    } else {
1193                            return false;
1194                    }
1195          }          }
1196    
1197  }  }

Legend:
Removed from v.403  
changed lines
  Added in v.526

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26