/[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 400 by alfonx, Mon Sep 14 12:24:50 2009 UTC revision 516 by alfonx, Wed Nov 11 21:17:33 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;
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;
 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.Set;  
 import java.util.SortedMap;  
 import java.util.TreeMap;  
48    
49  import javax.swing.Box;  import javax.swing.BorderFactory;
 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;
58  import org.geotools.coverage.grid.GridCoverage2D;  import org.geotools.coverage.grid.GridCoverage2D;
59    import org.geotools.coverage.grid.GridGeometry2D;
60  import org.geotools.coverage.grid.io.AbstractGridCoverage2DReader;  import org.geotools.coverage.grid.io.AbstractGridCoverage2DReader;
61    import org.geotools.coverage.grid.io.AbstractGridFormat;
62  import org.geotools.feature.FeatureCollection;  import org.geotools.feature.FeatureCollection;
63    import org.geotools.feature.NameImpl;
64    import org.geotools.geometry.jts.ReferencedEnvelope;
65  import org.geotools.map.DefaultMapLayer;  import org.geotools.map.DefaultMapLayer;
66  import org.geotools.map.MapLayer;  import org.geotools.map.MapLayer;
67    import org.geotools.parameter.Parameter;
68  import org.geotools.renderer.lite.gridcoverage2d.GridCoverageRenderer;  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 70  import org.jdom.Document; Line 76  import org.jdom.Document;
76  import org.jdom.Element;  import org.jdom.Element;
77  import org.jdom.input.SAXBuilder;  import org.jdom.input.SAXBuilder;
78  import org.jdom.output.XMLOutputter;  import org.jdom.output.XMLOutputter;
79    import org.opengis.feature.simple.SimpleFeature;
80  import org.opengis.feature.simple.SimpleFeatureType;  import org.opengis.feature.simple.SimpleFeatureType;
81    import org.opengis.feature.type.Name;
82    import org.opengis.parameter.GeneralParameterValue;
83    
84  import schmitzm.geotools.JTSUtil;  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 121  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 140  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 181  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 201  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 234  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 269  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 325  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 365  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 392  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 410  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 425  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 446  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 478  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 513  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 555  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 573  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 595  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 615  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 647  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 666  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 678  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 698  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 717  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 742  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 759  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 779  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 805  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 823  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 842  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 854  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 862  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 871  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 882  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:[]"));
913                           * Nuetzlich wenn die Componente gedruckt (z.B. wenn ein Screenshot  
914                           * gemacht wird) wird. Dann werden wird der Hintergrund auf WEISS                  if (style == null) {
915                           * gesetzt.                          // No Style => no legend
916                           *                          return panel;
917                           * @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);  
                                 }  
                         }  
                 };  
918    
919                  for (FeatureTypeStyle ftStyle : list) {                  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 922  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());
948                                  hbox.add(classTitleLabel);                                  
949                                    panel.add(classTitleLabel,"sgx2");
950                                  classTitleLabel.setLabelFor(iconLabel);                                  classTitleLabel.setLabelFor(iconLabel);
   
                                 box.add(hbox);  
   
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                  RasterLegendData rasterLegendData = styledGrid.getLegendMetaData();                          final int iconWidth, final int iconHeight) {
                 Set<Double> legendRasterValues = rasterLegendData.keySet();  
                 Map<Double, GridCoverage2D> sampleRasters = rasterLegendData  
                                 .createSampleRasters();  
968    
969                  Box box = new Box(BoxLayout.Y_AXIS) {                  // If no style is given, we use the default style for this layer
970                    if (style == null)
971                            style = styledRaster.getStyle();
972    
973                          /**                  /**
974                           * Nuetzlich wenn die Componente gedruckt (z.B. wenn ein Screenshot                   * Determine whether a Style is responsible for the coloring
975                           * gemacht wird) wird. Dann werden wird der Hintergrund auf WEISS                   */
976                           * gesetzt.                  ColorModel colorModel = null;
977                           */                  if (!isStyleable(styledRaster)
978                          @Override                                  || (isStyleable(styledRaster) && style == null)) {
979                          public void print(Graphics g) {                          colorModel = getColorModel(styledRaster);
980                                  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);  
                                 }  
                         }  
                 };  
981    
982                  for (Double rValue : legendRasterValues) {                  final RasterLegendData rasterLegendData = styledRaster
983                                    .getLegendMetaData();
984                    final List<Double> legendRasterValues = rasterLegendData
985                                    .getSortedKeys();
986                    final Map<Double, GridCoverage2D> sampleRasters = rasterLegendData
987                                    .createSampleRasters();
988    
989                          /**                  final JPanel panel = new JPanel(new MigLayout("wrap 2"));
                          * The coverage contains only one value of value rValue  
                          */  
                         GridCoverage2D sampleCov = sampleRasters.get(rValue);  
                         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);  
                         }  
990    
991                          /**                  for (final Double rValue : legendRasterValues) {
                          *  
                          */  
                         Box hbox = new Box(BoxLayout.X_AXIS) {  
992    
993                                  /**                          // final Dimension ICON_SIZE = new Dimension(iconWidth,
994                                   * Nuetzlich wenn die Componente gedruckt (z.B. wenn ein                          // new JLabel().getFontMetrics(new JLabel().getFont())
995                                   * Screenshot gemacht wird) wird. Dann werden wird der                          // .getHeight() > 5 ? new JLabel().getFontMetrics(
996                                   * Hintergrund auf WEISS gesetzt.                          // new JLabel().getFont()).getHeight() : iconHeight);
                                  */  
                                 @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);  
                                         }  
                                 }  
                         };  
   
                         final Dimension ICON_SIZE = new Dimension(iconWidth,  
                                         new JLabel().getFontMetrics(new JLabel().getFont())  
                                                         .getHeight() > 5 ? new JLabel().getFontMetrics(  
                                                         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                           * Iterate over all FeatureTypeStyles.                          if (colorModel != null) {
1007                           */                                  // The colors come from the ColorModel!
1008                          // for (FeatureTypeStyle ftStyle : styledGrid.getStyle()                                  
1009                          // .featureTypeStyles()) {                                  try {
1010                          // One child-node for every rule                                          Object inData = null;
1011                          // List<Rule> rules = ftStyle.rules();                                          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);
1035                                            graphics.setColor(color);
1036                                            graphics.fillRect(0, 0, iconWidth, iconHeight);
1037                                    } catch (final Exception e) {
1038                                            LOGGER.info(
1039                                                            "Dann nehmen wir halt den GridCoverageRenderer", e);
1040                                            colorModel = null;
1041                                    }
1042                            } else {
1043                                    // The colors come from the Style
1044    
1045                          // for (Rule rule : rules) {                                  /**
1046                          List<RasterSymbolizer> rSymbols = StylingUtil                                   * The coverage contains only one value of value rValue
1047                                          .getRasterSymbolizers(styledGrid.getStyle());                                   */
1048                                    final GridCoverage2D sampleCov = sampleRasters.get(rValue);
1049                          for (RasterSymbolizer symbolizer : rSymbols) {                                  GridCoverageRenderer renderer;
                                 // LOGGER.debug("Creating a new Legend Image for RUle name =  
                                 // "+rule.getName());  
1050                                  try {                                  try {
1051                                          renderer.paint(graphics, sampleCov, symbolizer);                                          renderer = new GridCoverageRenderer(sampleCov
1052                                  } catch (Exception e) {                                                          .getCoordinateReferenceSystem(), JTSUtil
1053                                          LOGGER.error("Unable to paint " + symbolizer                                                          .createEnvelope(sampleCov.getEnvelope()),
1054                                                          + " into the legend image", e);                                                          new Rectangle(iconWidth, iconHeight),
1055                                                            (AffineTransform) null);
1056                                    } catch (final Exception e1) {
1057                                            throw new RuntimeException(
1058                                                            "Creating a GridCoverageRenderer failed:", e1);
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" + (rasterLegendData.getPaintGaps()? ", gapy 0 3":""));
1085                          classTitleLabel.setLabelFor(iconLabel);                          classTitleLabel.setLabelFor(iconLabel);
1086    
1087                          box.add(hbox);  //                      box.add(hbox);
1088    
1089                            if (rasterLegendData.getPaintGaps()) {
1090                                    iconLabel
1091                                                    .setBorder(BorderFactory.createLineBorder(Color.black));
1092                            }
1093    
1094                  }                  }
1095    
1096                  return box;                  return panel;
1097            }
1098    
1099            /**
1100             * Extracts the {@link ColorModel} of any {@link StyledRasterInterface}. May
1101             * return <code>null</code> if the geoobject can not be accessed.
1102             */
1103            @SuppressWarnings("unchecked")
1104            public static ColorModel getColorModel(
1105                            final StyledRasterInterface<?> styledGrid) {
1106                    ColorModel colorModel = null;
1107                    try {
1108                            final Object geoObject = styledGrid.getGeoObject();
1109                            if (geoObject instanceof GridCoverage2D) {
1110                                    final GridCoverage2D cov = (GridCoverage2D) geoObject;
1111                                    colorModel = cov.getRenderedImage().getColorModel();
1112                            } else if (styledGrid instanceof StyledRasterPyramidInterface) {
1113    
1114                                    final Parameter readGG = new Parameter(
1115                                                    AbstractGridFormat.READ_GRIDGEOMETRY2D);
1116    
1117                                    final ReferencedEnvelope mapExtend = new org.geotools.geometry.jts.ReferencedEnvelope(
1118                                                    styledGrid.getEnvelope(), styledGrid.getCrs());
1119    
1120                                    readGG.setValue(new GridGeometry2D(new GeneralGridEnvelope(
1121                                                    new Rectangle(0, 0, 1, 1)), mapExtend));
1122    
1123                                    final FeatureCollection<SimpleFeatureType, SimpleFeature> rFc = (FeatureCollection<SimpleFeatureType, SimpleFeature>) geoObject;
1124    
1125                                    final AbstractGridCoverage2DReader aReader = (AbstractGridCoverage2DReader) FeatureUtil
1126                                                    .getWrappedGeoObject(rFc);
1127                                    final GridCoverage2D cov = (GridCoverage2D) aReader
1128                                                    .read(new GeneralParameterValue[] { readGG });
1129                                    colorModel = cov.getRenderedImage().getColorModel();
1130                            }
1131                    } catch (final Exception e) {
1132                            LOGGER.error("Error reading the colormodel from " + styledGrid, e);
1133                            return null;
1134                    }
1135                    return colorModel;
1136          }          }
1137    
1138            /**
1139             * @return <code>true</code> if a {@link RasterSymbolizer} can be applied
1140             *         and will have an effect. Some rasters (e.g. GeoTIFF) can come
1141             *         with their own {@link ColorModel} and will ignore any
1142             *         {@link RasterSymbolizer} = SLD.
1143             */
1144            public static boolean isStyleable(
1145                            final StyledRasterInterface<?> styledRaster) {
1146                    final ColorModel colorModel = getColorModel(styledRaster);
1147    
1148                    LOGGER.info("The colormodel of " + styledRaster.getTitle() + " is "
1149                                    + colorModel.getClass().getSimpleName());
1150    
1151                    if (colorModel == null)
1152                            return true;
1153                    if (colorModel instanceof ComponentColorModel)
1154                            return true;
1155                    return false;
1156            }
1157  }  }

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26