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

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

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

branches/1.0-gt2-2.6/src/skrueger/geotools/StyledLayerUtil.java revision 406 by alfonx, Mon Sep 14 18:06:27 2009 UTC branches/2.0-RC1/src/skrueger/geotools/StyledLayerUtil.java revision 607 by alfonx, Wed Dec 9 15:13:42 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;
# Line 44  import java.io.FileNotFoundException; Line 43  import java.io.FileNotFoundException;
43  import java.io.FileWriter;  import java.io.FileWriter;
44  import java.net.URL;  import java.net.URL;
45  import java.text.DecimalFormat;  import java.text.DecimalFormat;
46  import java.util.HashMap;  import java.util.ArrayList;
47  import java.util.List;  import java.util.List;
48  import java.util.Map;  import java.util.Map;
 import java.util.SortedMap;  
 import java.util.TreeMap;  
49    
50  import javax.swing.BorderFactory;  import javax.swing.BorderFactory;
 import javax.swing.Box;  
 import javax.swing.BoxLayout;  
51  import javax.swing.ImageIcon;  import javax.swing.ImageIcon;
52    import javax.swing.JComponent;
53  import javax.swing.JLabel;  import javax.swing.JLabel;
54    
55    import net.miginfocom.swing.MigLayout;
56    
57  import org.apache.log4j.Logger;  import org.apache.log4j.Logger;
58  import org.geotools.coverage.grid.GeneralGridEnvelope;  import org.geotools.coverage.grid.GeneralGridEnvelope;
59  import org.geotools.coverage.grid.GridCoverage2D;  import org.geotools.coverage.grid.GridCoverage2D;
# Line 63  import org.geotools.coverage.grid.GridGe Line 61  import org.geotools.coverage.grid.GridGe
61  import org.geotools.coverage.grid.io.AbstractGridCoverage2DReader;  import org.geotools.coverage.grid.io.AbstractGridCoverage2DReader;
62  import org.geotools.coverage.grid.io.AbstractGridFormat;  import org.geotools.coverage.grid.io.AbstractGridFormat;
63  import org.geotools.feature.FeatureCollection;  import org.geotools.feature.FeatureCollection;
64  import org.geotools.gce.imagepyramid.ImagePyramidReader;  import org.geotools.feature.NameImpl;
65  import org.geotools.geometry.jts.ReferencedEnvelope;  import org.geotools.geometry.jts.ReferencedEnvelope;
66  import org.geotools.map.DefaultMapLayer;  import org.geotools.map.DefaultMapLayer;
67  import org.geotools.map.MapLayer;  import org.geotools.map.MapLayer;
# Line 79  import org.jdom.Document; Line 77  import org.jdom.Document;
77  import org.jdom.Element;  import org.jdom.Element;
78  import org.jdom.input.SAXBuilder;  import org.jdom.input.SAXBuilder;
79  import org.jdom.output.XMLOutputter;  import org.jdom.output.XMLOutputter;
80    import org.opengis.feature.simple.SimpleFeature;
81  import org.opengis.feature.simple.SimpleFeatureType;  import org.opengis.feature.simple.SimpleFeatureType;
82    import org.opengis.feature.type.AttributeDescriptor;
83    import org.opengis.feature.type.GeometryDescriptor;
84    import org.opengis.feature.type.Name;
85  import org.opengis.parameter.GeneralParameterValue;  import org.opengis.parameter.GeneralParameterValue;
86    
87  import schmitzm.geotools.JTSUtil;  import schmitzm.geotools.JTSUtil;
88    import schmitzm.geotools.feature.FeatureUtil;
89  import schmitzm.geotools.styling.StylingUtil;  import schmitzm.geotools.styling.StylingUtil;
90  import schmitzm.io.IOUtil;  import schmitzm.io.IOUtil;
91  import schmitzm.lang.LangUtil;  import schmitzm.lang.LangUtil;
92    import schmitzm.swing.JPanel;
93  import schmitzm.swing.SwingUtil;  import schmitzm.swing.SwingUtil;
94  import skrueger.AttributeMetaData;  import skrueger.AttributeMetadata;
95  import skrueger.RasterLegendData;  import skrueger.RasterLegendData;
96  import skrueger.i8n.Translation;  import skrueger.i8n.Translation;
97    
# Line 131  public class StyledLayerUtil { Line 135  public class StyledLayerUtil {
135           *                if {@code null} is given as object or an error occurs           *                if {@code null} is given as object or an error occurs
136           *                during layer creation           *                during layer creation
137           */           */
138          public static MapLayer createMapLayer(Object object) throws Exception {          public static MapLayer createMapLayer(final Object object) throws Exception {
139                  return createMapLayer(object, null);                  return createMapLayer(object, null);
140          }          }
141    
# Line 150  public class StyledLayerUtil { Line 154  public class StyledLayerUtil {
154           *                if {@code null} is given as object or an error occurs           *                if {@code null} is given as object or an error occurs
155           *                during layer creation           *                during layer creation
156           */           */
157          public static MapLayer createMapLayer(Object object, Style forcedStyle)          public static MapLayer createMapLayer(Object object, final Style forcedStyle)
158                          throws Exception {                          throws Exception {
159                  MapLayer layer = null;                  MapLayer layer = null;
160                  Style style = null;                  Style style = null;
# Line 191  public class StyledLayerUtil { Line 195  public class StyledLayerUtil {
195           *                if {@code null} is given as object or an error occurs           *                if {@code null} is given as object or an error occurs
196           *                during creation           *                during creation
197           */           */
198          public static StyledLayerInterface<?> createStyledLayer(Object object,          public static StyledLayerInterface<?> createStyledLayer(
199                          String title) {                          final Object object, final String title) {
200                  return createStyledLayer(object, title, null);                  return createStyledLayer(object, title, null);
201          }          }
202    
# Line 211  public class StyledLayerUtil { Line 215  public class StyledLayerUtil {
215           *                if {@code null} is given as object or an error occurs           *                if {@code null} is given as object or an error occurs
216           *                during creation           *                during creation
217           */           */
218          public static StyledLayerInterface<?> createStyledLayer(Object object,          public static StyledLayerInterface<?> createStyledLayer(
219                          String title, StyledLayerStyle style) {                          final Object object, final String title,
220                            final StyledLayerStyle style) {
221                  StyledLayerInterface<?> styledLayer = null;                  StyledLayerInterface<?> styledLayer = null;
222    
223                  String id = (title != null) ? title : "defaultID";                  final String id = (title != null) ? title : "defaultID";
224    
225                  if (object instanceof GridCoverage2D)                  if (object instanceof GridCoverage2D)
226                          styledLayer = new StyledGridCoverage((GridCoverage2D) object, id,                          styledLayer = new StyledGridCoverage((GridCoverage2D) object, id,
# Line 243  public class StyledLayerUtil { Line 248  public class StyledLayerUtil {
248           * @param visible           * @param visible
249           *            indicated whether the visible or invisible entries are           *            indicated whether the visible or invisible entries are
250           *            returned           *            returned
251             *
252             *            TODO replace with
253             *            {@link AttributeMetadataMap#sortedValuesVisibleOnly()}
254           */           */
255          public static SortedMap<Integer, AttributeMetaData> getVisibleAttributeMetaData(          public static AttributeMetadataMap getVisibleAttributeMetaData(
256                          Map<Integer, AttributeMetaData> amdMap, boolean visible) {                          final AttributeMetadataMap amdMap, final boolean visible) {
257                  SortedMap<Integer, AttributeMetaData> filteredMap = new TreeMap<Integer, AttributeMetaData>();  
258                  for (AttributeMetaData amd : amdMap.values())                  final AttributeMetadataMap filteredMap = new AttributeMetadataMap(
259                          if (amd.isVisible())                                  amdMap.getLanguages());
260                                  filteredMap.put(amd.getColIdx(), amd);                  for (final AttributeMetadata amd : amdMap.values())
261                            if (amd.isVisible() == visible)
262                                    filteredMap.put(amd.getName(), amd);
263    
264                  return filteredMap;                  return filteredMap;
265          }          }
266    
267          /**          /**
268           * Parses a {@link AttributeMetaData} object from an JDOM-{@link Element}.           * Parses a {@link AttributeMetadata} object from an JDOM-{@link Element}.
269           * This method works like {@link           * This method works like {@link
270           * AMLImport#parseDataAttribute(org.w3c.dom.Node}, but for JDOM.           * AMLImport#parseDataAttribute(org.w3c.dom.Node}, but for JDOM.
271           *           *
272             * TODO 20.11.2009, SK: There are some new attribute weight, functiona,
273             * functionX and nodata in AttributeMetaData that should be parsed/exported
274             * too. but this method is only used by ISDSS, which is not supporting that
275             * stuff anyways.
276             *
277           * @param element           * @param element
278           *            {@link Element} to parse           *            {@link Element} to parse
279           */           */
280          public static AttributeMetaData parseAttributeMetaData(final Element element) {          public static AttributeMetadata parseAttributeMetaData(final Element element) {
281                  final Integer col = Integer.valueOf(element.getAttributeValue("col"));                  final String namespace = String.valueOf(element
282                                    .getAttributeValue("namespace"));
283                    final String localname = String.valueOf(element
284                                    .getAttributeValue("localname"));
285                    final Name aName = new NameImpl(namespace, localname);
286                  final Boolean visible = Boolean.valueOf(element                  final Boolean visible = Boolean.valueOf(element
287                                  .getAttributeValue("visible"));                                  .getAttributeValue("visible"));
288                  final String unit = element.getAttributeValue("unit");                  final String unit = element.getAttributeValue("unit");
# Line 279  public class StyledLayerUtil { Line 298  public class StyledLayerUtil {
298                          else if (childElement.getName().equals("desc"))                          else if (childElement.getName().equals("desc"))
299                                  desc = parseTranslation(childElement);                                  desc = parseTranslation(childElement);
300                  }                  }
301                  return new AttributeMetaData(col, visible, name, desc, unit);                  return new AttributeMetadata(aName, visible, name, desc, unit);
302          }          }
303    
304          /**          /**
305           * Parses a {@link AttributeMetaData} map from an JDOM-{@link Element} with           * Parses a {@link AttributeMetadata} map from an JDOM-{@link Element} with
306           * {@code <attribute>}-childs.           * {@code <attribute>}-childs.
307           *           *
308           * @param element           * @param element
309           *            {@link Element} to parse           *            {@link Element} to parse
310           */           */
311          public static Map<Integer, AttributeMetaData> parseAttributeMetaDataMap(          public static AttributeMetadataMap parseAttributeMetaDataMap(
312                          final Element element) {                          final Element element) {
313                  HashMap<Integer, AttributeMetaData> metaData = new HashMap<Integer, AttributeMetaData>();                  final AttributeMetadataMap metaData = new AttributeMetadataMap();
314                  List<Element> attributesElements = element                  final List<Element> attributesElements = element
315                                  .getChildren(ELEM_NAME_ATTRIBUTE);                                  .getChildren(ELEM_NAME_ATTRIBUTE);
316                  for (Element attibuteElement : attributesElements) {                  for (final Element attibuteElement : attributesElements) {
317                          AttributeMetaData attrMetaData = parseAttributeMetaData(attibuteElement);                          final AttributeMetadata attrMetaData = parseAttributeMetaData(attibuteElement);
318                          metaData.put(attrMetaData.getColIdx(), attrMetaData);                          metaData.put(attrMetaData.getName(), attrMetaData);
319                  }                  }
320                  return metaData;                  return metaData;
321          }          }
322    
323          /**          /**
324           * Loads a {@link AttributeMetaData} object from an URL.           * Loads a {@link AttributeMetadata} object from an URL.
325           *           *
326           * @param documentUrl           * @param documentUrl
327           *            {@link URL} to parse           *            {@link URL} to parse
328           * @see #parseAttributeMetaData(Element)           * @see #parseAttributeMetaData(Element)
329           */           */
330          public static Map<Integer, AttributeMetaData> loadAttributeMetaDataMap(          public static AttributeMetadataMap loadAttributeMetaDataMap(
331                          final URL documentUrl) throws Exception {                          final URL documentUrl) throws Exception {
332                  Document document = SAX_BUILDER.build(documentUrl);                  final Document document = SAX_BUILDER.build(documentUrl);
333                  return parseAttributeMetaDataMap(document.getRootElement());                  return parseAttributeMetaDataMap(document.getRootElement());
334          }          }
335    
336          /**          /**
337           * Creates an JDOM {@link Element} for the given {@link AttributeMetaData}           * Creates an JDOM {@link Element} for the given {@link AttributeMetadata}
338           * object.           * object.
339           *           *
340           * @param amd           * @param amd
341           *            meta data for one attribute           *            meta data for one attribute
342           */           */
343          public static Element createAttributeMetaDataElement(          public static Element createAttributeMetaDataElement(
344                          final AttributeMetaData amd) {                          final AttributeMetadata amd) {
345                  final Element element = new Element(ELEM_NAME_ATTRIBUTE, AMLURI);                  final Element element = new Element(ELEM_NAME_ATTRIBUTE, AMLURI);
346                  element.setAttribute("col", String.valueOf(amd.getColIdx()));                  element.setAttribute("namespace", String.valueOf(amd.getName()
347                                    .getNamespaceURI()));
348                    element.setAttribute("localname", String.valueOf(amd.getLocalName()));
349                  element.setAttribute("visible", String.valueOf(amd.isVisible()));                  element.setAttribute("visible", String.valueOf(amd.isVisible()));
350                  element.setAttribute("unit", amd.getUnit());                  element.setAttribute("unit", amd.getUnit());
351                  // Creating a aml:name tag...                  // Creating a aml:name tag...
# Line 335  public class StyledLayerUtil { Line 356  public class StyledLayerUtil {
356          }          }
357    
358          /**          /**
359           * Creates an JDOM {@link Element} for the given {@link AttributeMetaData}           * Creates an JDOM {@link Element} for the given {@link AttributeMetadata}
360           * map.           * map.
361           *           *
362           * @param amdMap           * @param amdMap
363           *            map of attribute meta data           *            map of attribute meta data
364           */           */
365          public static Element createAttributeMetaDataMapElement(          public static Element createAttributeMetaDataMapElement(
366                          final Map<Integer, AttributeMetaData> amdMap) {                          final AttributeMetadataMap amdMap) {
367                  final Element element = new Element(ELEM_NAME_AMD, AMLURI);                  final Element element = new Element(ELEM_NAME_AMD, AMLURI);
368                  for (AttributeMetaData amd : amdMap.values())                  for (final AttributeMetadata amd : amdMap.values())
369                          element.addContent(createAttributeMetaDataElement(amd));                          element.addContent(createAttributeMetaDataElement(amd));
370                  return element;                  return element;
371          }          }
372    
373          /**          /**
374           * Saves a {@link AttributeMetaData AttributeMetaData-Map} to an URL.           * Saves a {@link AttributeMetadata AttributeMetaData-Map} to an URL.
375           *           *
376           * @param amdMap           * @param amdMap
377           *            map of {@link AttributeMetaData}           *            map of {@link AttributeMetadata}
378           * @param documentUrl           * @param documentUrl
379           *            {@link URL} to store the XML           *            {@link URL} to store the XML
380           */           */
381          public static void saveAttributeMetaDataMap(          public static void saveAttributeMetaDataMap(
382                          final Map<Integer, AttributeMetaData> amdMap, final URL documentUrl)                          final AttributeMetadataMap amdMap, final URL documentUrl)
383                          throws Exception {                          throws Exception {
384                  // Create XML-Document                  // Create XML-Document
385                  final FileWriter out = new FileWriter(new File(documentUrl.toURI()));                  final FileWriter out = new FileWriter(new File(documentUrl.toURI()));
# Line 375  public class StyledLayerUtil { Line 396  public class StyledLayerUtil {
396           * @param element           * @param element
397           *            {@link Element} to parse           *            {@link Element} to parse
398           */           */
399          public static RasterLegendData parseRasterLegendData(Element element) {          public static RasterLegendData parseRasterLegendData(final Element element) {
400    
401                  final boolean paintGaps = Boolean.valueOf(element                  final boolean paintGaps = Boolean.valueOf(element
402                                  .getAttributeValue("paintGaps"));                                  .getAttributeValue("paintGaps"));
403    
404                  RasterLegendData rld = new RasterLegendData(paintGaps);                  final RasterLegendData rld = new RasterLegendData(paintGaps);
405    
406                  for (Element childElement : (List<Element>) element.getChildren()) {                  for (final Element childElement : (List<Element>) element.getChildren()) {
407                          final String name = childElement.getName();                          final String name = childElement.getName();
408                          // Cancel if it's an attribute                          // Cancel if it's an attribute
409                          if (childElement.getChildren().size() == 0)                          if (childElement.getChildren().size() == 0)
# Line 402  public class StyledLayerUtil { Line 423  public class StyledLayerUtil {
423                                  // id label element is missing, the translation is searched                                  // id label element is missing, the translation is searched
424                                  // directly                                  // directly
425                                  // as childs of the rasterLegendItem element                                  // as childs of the rasterLegendItem element
426                                  Translation label = parseTranslation(labelElement != null ? labelElement                                  final Translation label = parseTranslation(labelElement != null ? labelElement
427                                                  : childElement);                                                  : childElement);
428                                  rld.put(value, label);                                  rld.put(value, label);
429                          }                          }
# Line 420  public class StyledLayerUtil { Line 441  public class StyledLayerUtil {
441           */           */
442          public static RasterLegendData loadRasterLegendData(final URL documentUrl)          public static RasterLegendData loadRasterLegendData(final URL documentUrl)
443                          throws Exception {                          throws Exception {
444                  Document document = SAX_BUILDER.build(documentUrl);                  final Document document = SAX_BUILDER.build(documentUrl);
445                  return parseRasterLegendData(document.getRootElement());                  return parseRasterLegendData(document.getRootElement());
446          }          }
447    
# Line 435  public class StyledLayerUtil { Line 456  public class StyledLayerUtil {
456                          final RasterLegendData rld) {                          final RasterLegendData rld) {
457                  final Element element = new Element(ELEM_NAME_RLD, AMLURI);                  final Element element = new Element(ELEM_NAME_RLD, AMLURI);
458                  element.setAttribute("paintGaps", rld.isPaintGaps().toString());                  element.setAttribute("paintGaps", rld.isPaintGaps().toString());
459                  for (Double key : rld.getSortedKeys()) {                  for (final Double key : rld.getSortedKeys()) {
460                          Element item = new Element(ELEM_NAME_RASTERLEGEND, AMLURI);                          final Element item = new Element(ELEM_NAME_RASTERLEGEND, AMLURI);
461                          item.setAttribute("value", key.toString());                          item.setAttribute("value", key.toString());
462                          item.addContent(createTranslationElement("label", rld.get(key)));                          item.addContent(createTranslationElement("label", rld.get(key)));
463                          element.addContent(item);                          element.addContent(item);
# Line 456  public class StyledLayerUtil { Line 477  public class StyledLayerUtil {
477           *            rounded to (null means no round; >= 0 means digits after           *            rounded to (null means no round; >= 0 means digits after
478           *            comma; < 0 means digits before comma)           *            comma; < 0 means digits before comma)
479           */           */
480          public static RasterLegendData generateRasterLegendData(ColorMap colorMap,          public static RasterLegendData generateRasterLegendData(
481                          boolean paintGaps, Integer digits) {                          final ColorMap colorMap, final boolean paintGaps,
482                  DecimalFormat decFormat = digits != null ? new DecimalFormat(SwingUtil                          final Integer digits) {
483                                  .getNumberFormatPattern(digits)) : null;                  final DecimalFormat decFormat = digits != null ? new DecimalFormat(
484                  RasterLegendData rld = new RasterLegendData(paintGaps);                                  SwingUtil.getNumberFormatPattern(digits)) : null;
485                  for (ColorMapEntry cme : colorMap.getColorMapEntries()) {                  final RasterLegendData rld = new RasterLegendData(paintGaps);
486                          double value = StylingUtil.getQuantityFromColorMapEntry(cme);                  for (final ColorMapEntry cme : colorMap.getColorMapEntries()) {
487                            final double value = StylingUtil.getQuantityFromColorMapEntry(cme);
488                          String label = cme.getLabel();                          String label = cme.getLabel();
489                          // if no label is set (e.g. quantitative style),                          // if no label is set (e.g. quantitative style),
490                          // use the value as label                          // use the value as label
# Line 488  public class StyledLayerUtil { Line 510  public class StyledLayerUtil {
510           *            rounded to (null means no round; >= 0 means digits after           *            rounded to (null means no round; >= 0 means digits after
511           *            comma; < 0 means digits before comma)           *            comma; < 0 means digits before comma)
512           */           */
513          public static RasterLegendData generateRasterLegendData(Style style,          public static RasterLegendData generateRasterLegendData(final Style style,
514                          boolean paintGaps, Integer digits) {                          final boolean paintGaps, final Integer digits) {
515                  ColorMap colorMap = StylingUtil.getColorMapFromStyle(style);                  final ColorMap colorMap = StylingUtil.getColorMapFromStyle(style);
516                  if (colorMap == null)                  if (colorMap == null)
517                          throw new IllegalArgumentException(                          throw new IllegalArgumentException(
518                                          "Color map can not be determined from style!");                                          "Color map can not be determined from style!");
# Line 523  public class StyledLayerUtil { Line 545  public class StyledLayerUtil {
545           *            {@link Element} to parse           *            {@link Element} to parse
546           */           */
547          public final static Translation parseTranslation(final Element element) {          public final static Translation parseTranslation(final Element element) {
548                  Translation trans = new Translation();                  final Translation trans = new Translation();
549    
550                  if (element == null)                  if (element == null)
551                          return trans;                          return trans;
# Line 565  public class StyledLayerUtil { Line 587  public class StyledLayerUtil {
587           * @param translation           * @param translation
588           *            Translation to store in the Element           *            Translation to store in the Element
589           */           */
590          public final static Element createTranslationElement(String tagname,          public final static Element createTranslationElement(final String tagname,
591                          Translation translation) {                          final Translation translation) {
592                  Element element = new Element(tagname, AMLURI);                  final Element element = new Element(tagname, AMLURI);
593                  if (translation == null)                  if (translation == null)
594                          throw new UnsupportedOperationException(                          throw new UnsupportedOperationException(
595                                          "Translation element can not be created from null!");                                          "Translation element can not be created from null!");
# Line 583  public class StyledLayerUtil { Line 605  public class StyledLayerUtil {
605    
606                  // add a <translation lang="..">..</tranlation> part to the element for                  // add a <translation lang="..">..</tranlation> part to the element for
607                  // all languages                  // all languages
608                  for (String lang : translation.keySet()) {                  for (final String lang : translation.keySet()) {
609                          Element translationElement = new Element(ELEM_NAME_TRANSLATION,                          final Element translationElement = new Element(
610                                          AMLURI);                                          ELEM_NAME_TRANSLATION, AMLURI);
611                          translationElement.setAttribute("lang", lang);                          translationElement.setAttribute("lang", lang);
612                          String translationString = translation.get(lang);                          String translationString = translation.get(lang);
613                          if (translationString == null)                          if (translationString == null)
# Line 605  public class StyledLayerUtil { Line 627  public class StyledLayerUtil {
627           * @param style           * @param style
628           *            a Style           *            a Style
629           */           */
630          public static void setStyledLayerStyle(StyledLayerInterface styledObject,          public static void setStyledLayerStyle(
631                          StyledLayerStyle<?> style) {                          final StyledLayerInterface styledObject,
632                            final StyledLayerStyle<?> style) {
633                  // set SLD style                  // set SLD style
634                  styledObject.setStyle(style.getGeoObjectStyle());                  styledObject.setStyle(style.getGeoObjectStyle());
635                  // set meta data                  // set meta data
636                  if (styledObject instanceof StyledGridCoverageInterface                  if (styledObject instanceof StyledGridCoverageInterface
637                                  && (style.getMetaData() instanceof RasterLegendData || style                                  && (style.getMetaData() instanceof RasterLegendData || style
638                                                  .getMetaData() == null)) {                                                  .getMetaData() == null)) {
639                          RasterLegendData sourceRld = (RasterLegendData) style.getMetaData();                          final RasterLegendData sourceRld = (RasterLegendData) style
640                          RasterLegendData destRld = ((StyledGridCoverageInterface) styledObject)                                          .getMetaData();
641                            final RasterLegendData destRld = ((StyledGridCoverageInterface) styledObject)
642                                          .getLegendMetaData();                                          .getLegendMetaData();
643                          if (destRld != null && sourceRld != null) {                          if (destRld != null && sourceRld != null) {
644                                  destRld.setPaintGaps(sourceRld.isPaintGaps());                                  destRld.setPaintGaps(sourceRld.isPaintGaps());
# Line 625  public class StyledLayerUtil { Line 649  public class StyledLayerUtil {
649                  }                  }
650                  if (styledObject instanceof StyledFeatureCollectionInterface                  if (styledObject instanceof StyledFeatureCollectionInterface
651                                  && (style.getMetaData() instanceof Map || style.getMetaData() == null)) {                                  && (style.getMetaData() instanceof Map || style.getMetaData() == null)) {
652                          Map<Integer, AttributeMetaData> sourceAmd = (Map<Integer, AttributeMetaData>) style                          final AttributeMetadataMap sourceAmd = (AttributeMetadataMap) style
653                                          .getMetaData();                                          .getMetaData();
654                          Map<Integer, AttributeMetaData> destAmd = ((StyledFeatureCollectionInterface) styledObject)                          final AttributeMetadataMap destAmd = ((StyledFeatureCollectionInterface) styledObject)
655                                          .getAttributeMetaDataMap();                                          .getAttributeMetaDataMap();
656                          if (destAmd != null && sourceAmd != null) {                          if (destAmd != null && sourceAmd != null) {
657                                  destAmd.clear();                                  destAmd.clear();
# Line 657  public class StyledLayerUtil { Line 681  public class StyledLayerUtil {
681           *         {@link StyledFeatureCollectionInterface}           *         {@link StyledFeatureCollectionInterface}
682           */           */
683          public static StyledLayerStyle<?> getStyledLayerStyle(          public static StyledLayerStyle<?> getStyledLayerStyle(
684                          StyledLayerInterface styledObject) {                          final StyledLayerInterface styledObject) {
685                  if (styledObject instanceof StyledGridCoverageInterface)                  if (styledObject instanceof StyledGridCoverageInterface)
686                          return getStyledLayerStyle((StyledGridCoverageInterface) styledObject);                          return getStyledLayerStyle((StyledGridCoverageInterface) styledObject);
687                  if (styledObject instanceof StyledFeatureCollectionInterface)                  if (styledObject instanceof StyledFeatureCollectionInterface)
# Line 676  public class StyledLayerUtil { Line 700  public class StyledLayerUtil {
700           *            a styled grid coverage           *            a styled grid coverage
701           */           */
702          public static StyledLayerStyle<RasterLegendData> getStyledLayerStyle(          public static StyledLayerStyle<RasterLegendData> getStyledLayerStyle(
703                          StyledGridCoverageInterface styledGC) {                          final StyledGridCoverageInterface styledGC) {
704                  return new StyledLayerStyle<RasterLegendData>(styledGC.getStyle(),                  return new StyledLayerStyle<RasterLegendData>(styledGC.getStyle(),
705                                  styledGC.getLegendMetaData());                                  styledGC.getLegendMetaData());
706          }          }
# Line 688  public class StyledLayerUtil { Line 712  public class StyledLayerUtil {
712           * @param styledFC           * @param styledFC
713           *            a styled feature collection           *            a styled feature collection
714           */           */
715          public static StyledLayerStyle<Map<Integer, AttributeMetaData>> getStyledLayerStyle(          public static StyledLayerStyle<AttributeMetadataMap> getStyledLayerStyle(
716                          StyledFeatureCollectionInterface styledFC) {                          final StyledFeatureCollectionInterface styledFC) {
717                  return new StyledLayerStyle<Map<Integer, AttributeMetaData>>(styledFC                  return new StyledLayerStyle<AttributeMetadataMap>(styledFC.getStyle(),
718                                  .getStyle(), styledFC.getAttributeMetaDataMap());                                  styledFC.getAttributeMetaDataMap());
719          }          }
720    
721          /**          /**
# Line 708  public class StyledLayerUtil { Line 732  public class StyledLayerUtil {
732           * @return {@code null} in case of any error           * @return {@code null} in case of any error
733           */           */
734          public static StyledLayerStyle<RasterLegendData> loadStyledRasterStyle(          public static StyledLayerStyle<RasterLegendData> loadStyledRasterStyle(
735                          URL geoObjectURL, String sldExt, String rldExt) {                          final URL geoObjectURL, final String sldExt, final String rldExt) {
736                  RasterLegendData metaData = null;                  RasterLegendData metaData = null;
737                  Style sldStyle = null;                  Style sldStyle = null;
738                  try {                  try {
739                          Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(                          final Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(
740                                          geoObjectURL, sldExt));                                          geoObjectURL, sldExt));
741                          // SLD must be present                          // SLD must be present
742                          if (styles == null || styles.length == 0)                          if (styles == null || styles.length == 0)
743                                  return null;                                  return null;
744                          sldStyle = styles[0];                          sldStyle = styles[0];
745                  } catch (Exception err) {                  } catch (final Exception err) {
746                          // SLD must be present                          // SLD must be present
747                          LangUtil.logDebugError(LOGGER, err);                          LangUtil.logDebugError(LOGGER, err);
748                          return null;                          return null;
# Line 727  public class StyledLayerUtil { Line 751  public class StyledLayerUtil {
751                  try {                  try {
752                          metaData = StyledLayerUtil.loadRasterLegendData(IOUtil                          metaData = StyledLayerUtil.loadRasterLegendData(IOUtil
753                                          .changeUrlExt(geoObjectURL, rldExt));                                          .changeUrlExt(geoObjectURL, rldExt));
754                  } catch (FileNotFoundException err) {                  } catch (final FileNotFoundException err) {
755                          // ignore missing raster legend data                          // ignore missing raster legend data
756                  } catch (Exception err) {                  } catch (final Exception err) {
757                          // any other error during legend data creation leads to error                          // any other error during legend data creation leads to error
758                          LangUtil.logDebugError(LOGGER, err);                          LangUtil.logDebugError(LOGGER, err);
759                          return null;                          return null;
# Line 752  public class StyledLayerUtil { Line 776  public class StyledLayerUtil {
776           * @return {@code null} in case of any error           * @return {@code null} in case of any error
777           */           */
778          public static StyledLayerStyle<RasterLegendData> loadStyledRasterStyle(          public static StyledLayerStyle<RasterLegendData> loadStyledRasterStyle(
779                          URL geoObjectURL) {                          final URL geoObjectURL) {
780                  return loadStyledRasterStyle(geoObjectURL, "sld", "rld");                  return loadStyledRasterStyle(geoObjectURL, "sld", "rld");
781          }          }
782    
783          /**          /**
784           * Loads a {@linkplain Style SLD-Style} and a {@linkplain AttributeMetaData           * Loads a {@linkplain Style SLD-Style} and a {@linkplain AttributeMetadata
785           * AttributeMetaData-Map} for a given geo-object (feature) source. The SLD           * AttributeMetaData-Map} for a given geo-object (feature) source. The SLD
786           * file must be present. A missing attribute meta-data file is tolerated.           * file must be present. A missing attribute meta-data file is tolerated.
787           *           *
# Line 769  public class StyledLayerUtil { Line 793  public class StyledLayerUtil {
793           *            file extention for the raster legend-data file           *            file extention for the raster legend-data file
794           * @return {@code null} in case of any error           * @return {@code null} in case of any error
795           */           */
796          public static StyledLayerStyle<Map<Integer, AttributeMetaData>> loadStyledFeatureStyle(          public static StyledLayerStyle<AttributeMetadataMap> loadStyledFeatureStyle(
797                          URL geoObjectURL, String sldExt, String rldExt) {                          final URL geoObjectURL, final String sldExt, final String rldExt) {
798                  Map<Integer, AttributeMetaData> metaData = null;                  AttributeMetadataMap metaData = null;
799                  Style sldStyle = null;                  Style sldStyle = null;
800                  try {                  try {
801                          Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(                          final Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(
802                                          geoObjectURL, sldExt));                                          geoObjectURL, sldExt));
803                          // SLD must be present                          // SLD must be present
804                          if (styles == null || styles.length == 0)                          if (styles == null || styles.length == 0)
805                                  return null;                                  return null;
806                          sldStyle = styles[0];                          sldStyle = styles[0];
807                  } catch (Exception err) {                  } catch (final Exception err) {
808                          // SLD must be present                          // SLD must be present
809                          LangUtil.logDebugError(LOGGER, err);                          LangUtil.logDebugError(LOGGER, err);
810                          return null;                          return null;
# Line 789  public class StyledLayerUtil { Line 813  public class StyledLayerUtil {
813                  try {                  try {
814                          metaData = StyledLayerUtil.loadAttributeMetaDataMap(IOUtil                          metaData = StyledLayerUtil.loadAttributeMetaDataMap(IOUtil
815                                          .changeUrlExt(geoObjectURL, rldExt));                                          .changeUrlExt(geoObjectURL, rldExt));
816                  } catch (FileNotFoundException err) {                  } catch (final FileNotFoundException err) {
817                          // ignore missing attribute meta data                          // ignore missing attribute meta data
818                  } catch (Exception err) {                  } catch (final Exception err) {
819                          // any other error during meta data creation leads to error                          // any other error during meta data creation leads to error
820                          LangUtil.logDebugError(LOGGER, err);                          LangUtil.logDebugError(LOGGER, err);
821                          return null;                          return null;
822                  }                  }
823    
824                  return new StyledLayerStyle<Map<Integer, AttributeMetaData>>(sldStyle,                  return new StyledLayerStyle<AttributeMetadataMap>(sldStyle, metaData);
                                 metaData);  
825          }          }
826    
827          /**          /**
828           * Loads a {@linkplain Style SLD-Style} from a {@code .sld} file and           * Loads a {@linkplain Style SLD-Style} from a {@code .sld} file and
829           * {@linkplain AttributeMetaData AttributeMetaData-Map} from a {@code .amd}           * {@linkplain AttributeMetadata AttributeMetaData-Map} from a {@code .amd}
830           * 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
831           * present. A missing attribute meta-data file is tolerated.           * present. A missing attribute meta-data file is tolerated.
832           *           *
# Line 815  public class StyledLayerUtil { Line 838  public class StyledLayerUtil {
838           *            file extention for the raster legend-data file           *            file extention for the raster legend-data file
839           * @return {@code null} in case of any error           * @return {@code null} in case of any error
840           */           */
841          public static StyledLayerStyle<Map<Integer, AttributeMetaData>> loadStyledFeatureStyle(          public static StyledLayerStyle<AttributeMetadataMap> loadStyledFeatureStyle(
842                          URL geoObjectURL) {                          final URL geoObjectURL) {
843                  return loadStyledFeatureStyle(geoObjectURL, "sld", "amd");                  return loadStyledFeatureStyle(geoObjectURL, "sld", "amd");
844          }          }
845    
# Line 833  public class StyledLayerUtil { Line 856  public class StyledLayerUtil {
856           * @param mdExt           * @param mdExt
857           *            file extention for the meta-data file           *            file extention for the meta-data file
858           */           */
859          public static <T> void saveStyledLayerStyle(StyledLayerStyle<T> style,          public static <T> void saveStyledLayerStyle(
860                          URL geoObjectURL, String sldExt, String mdExt) throws Exception {                          final StyledLayerStyle<T> style, final URL geoObjectURL,
861                            final String sldExt, final String mdExt) throws Exception {
862                  // Store the SLD                  // Store the SLD
863                  Style sldStyle = style.getGeoObjectStyle();                  final Style sldStyle = style.getGeoObjectStyle();
864                  if (sldStyle != null) {                  if (sldStyle != null) {
865                          StylingUtil.saveStyleToSLD(sldStyle, IOUtil.changeFileExt(new File(                          StylingUtil.saveStyleToSLD(sldStyle, IOUtil.changeFileExt(new File(
866                                          geoObjectURL.toURI()), sldExt));                                          geoObjectURL.toURI()), sldExt));
867                  }                  }
868    
869                  // Store the meta data                  // Store the meta data
870                  T metaData = style.getMetaData();                  final T metaData = style.getMetaData();
871                  if (metaData != null) {                  if (metaData != null) {
872                          if (metaData instanceof RasterLegendData) {                          if (metaData instanceof RasterLegendData) {
873                                  saveRasterLegendData((RasterLegendData) metaData, IOUtil                                  saveRasterLegendData((RasterLegendData) metaData, IOUtil
# Line 852  public class StyledLayerUtil { Line 876  public class StyledLayerUtil {
876                                  // Map<Integer,AttributeMetaData> ) { // LEIDER NICHT                                  // Map<Integer,AttributeMetaData> ) { // LEIDER NICHT
877                                  // KOMPILIERBAR!!                                  // KOMPILIERBAR!!
878                          } else if (metaData instanceof Map) {                          } else if (metaData instanceof Map) {
879                                  saveAttributeMetaDataMap(                                  saveAttributeMetaDataMap((AttributeMetadataMap) metaData,
880                                                  (Map<Integer, AttributeMetaData>) metaData, IOUtil                                                  IOUtil.changeUrlExt(geoObjectURL, mdExt));
                                                                 .changeUrlExt(geoObjectURL, mdExt));  
881                          } else                          } else
882                                  throw new UnsupportedOperationException(                                  throw new UnsupportedOperationException(
883                                                  "Export for meta data not yet supported: "                                                  "Export for meta data not yet supported: "
# Line 864  public class StyledLayerUtil { Line 887  public class StyledLayerUtil {
887    
888          /**          /**
889           * 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
890           * meta data ({@link RasterLegendData} or {@link AttributeMetaData}) to a           * meta data ({@link RasterLegendData} or {@link AttributeMetadata}) to a
891           * {@code .rld} or {@code .amd} file. for a given geo-object source.           * {@code .rld} or {@code .amd} file. for a given geo-object source.
892           *           *
893           * @param style           * @param style
# Line 872  public class StyledLayerUtil { Line 895  public class StyledLayerUtil {
895           * @param geoObjectURL           * @param geoObjectURL
896           *            URL of the (already read) raster object           *            URL of the (already read) raster object
897           */           */
898          public static void saveStyledLayerStyle(StyledLayerStyle<?> style,          public static void saveStyledLayerStyle(final StyledLayerStyle<?> style,
899                          URL geoObjectURL) throws Exception {                          final URL geoObjectURL) throws Exception {
900                  if (style.getMetaData() instanceof RasterLegendData)                  if (style.getMetaData() instanceof RasterLegendData)
901                          saveStyledLayerStyle(style, geoObjectURL, "sld", "rld");                          saveStyledLayerStyle(style, geoObjectURL, "sld", "rld");
902                  else                  else
# Line 881  public class StyledLayerUtil { Line 904  public class StyledLayerUtil {
904          }          }
905    
906          /**          /**
907           * Creates a {@link Box} that shows a legend for a list of           * Creates a {@link JPanel} that shows a legend for a list of
908           * {@link FeatureTypeStyle}s and a targeted featureType           * {@link FeatureTypeStyle}s and a targeted featureType
909           *           *
910           * @param featureType           * @param featureType
# Line 892  public class StyledLayerUtil { Line 915  public class StyledLayerUtil {
915           * @author <a href="mailto:[email protected]">Stefan Alfons           * @author <a href="mailto:[email protected]">Stefan Alfons
916           *         Kr&uuml;ger</a>           *         Kr&uuml;ger</a>
917           */           */
918          public static Box createLegendPanel(List<FeatureTypeStyle> list,          public static JPanel createLegendPanel(Style style,
919                          SimpleFeatureType featureType, int iconWidth, int iconHeight) {                          final SimpleFeatureType featureType, final int iconWidth,
920                            final int iconHeight) {
921    
922                  Box box = new Box(BoxLayout.Y_AXIS) {                  final List<FeatureTypeStyle> list = style.featureTypeStyles();
923    
924                          /**                  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);  
                                 }  
                         }  
                 };  
925    
926                  for (FeatureTypeStyle ftStyle : list) {                  if (style == null) {
927                            // No Style => no legend
928                            return panel;
929                    }
930    
931                    for (final FeatureTypeStyle ftStyle : list) {
932    
933                          // One child-node for every rule                          // One child-node for every rule
934                          List<Rule> rules = ftStyle.rules();                          final List<Rule> rules = ftStyle.rules();
935                          for (Rule rule : rules) {                          for (final Rule rule : rules) {
936    
937                                  /**                                  /**
938                                   * Let's not create a hbox for Rules that only contain                                   * Let's not create a hbox for Rules that only contain
# Line 932  public class StyledLayerUtil { Line 942  public class StyledLayerUtil {
942                                                  .size() == rule.getSymbolizers().length)                                                  .size() == rule.getSymbolizers().length)
943                                          continue;                                          continue;
944    
                                 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  
                                 // ****************************************************************************  
945                                  final BufferedImage imageForRule = LegendIconFeatureRenderer                                  final BufferedImage imageForRule = LegendIconFeatureRenderer
946                                                  .getInstance().createImageForRule(rule, featureType,                                                  .getInstance().createImageForRule(rule, featureType,
947                                                                  ICON_SIZE);                                                                  new Dimension(iconWidth, iconHeight));
   
                                 // LOGGER.debug("Creating a new Legend Image for RUle name =  
                                 // "+rule.getName());  
948    
949                                  ImageIcon legendIcon = new ImageIcon(imageForRule);                                  final ImageIcon legendIcon = new ImageIcon(imageForRule);
950    
951                                  final JLabel iconLabel = new JLabel(legendIcon);                                  final JLabel iconLabel = new JLabel(legendIcon);
952                                  hbox.setAlignmentX(0f);                                  panel.add(iconLabel, "sgx1");
953                                  hbox.add(iconLabel);                                  // hbox.setAlignmentX(0f);
954                                  hbox.add(Box.createHorizontalStrut(3));                                  // hbox.add(iconLabel);
955                                    // 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);  
956    
957                                    final Translation labelT = new Translation();
958                                    labelT.fromOneLine(rule.getDescription().getTitle());
959                                  final JLabel classTitleLabel = new JLabel(labelT.toString());                                  final JLabel classTitleLabel = new JLabel(labelT.toString());
                                 hbox.add(classTitleLabel);  
                                 classTitleLabel.setLabelFor(iconLabel);  
   
                                 box.add(hbox);  
960    
961                                    panel.add(classTitleLabel, "sgx2");
962                                    classTitleLabel.setLabelFor(iconLabel);
963                          }                          }
964                  }                  }
965    
966                  return box;                  return panel;
967          }          }
968    
969          /**          /**
970           * Creates a           * Creates a {@link JComponent} that contains a legend for a given
971             * rasterLayer and a given {@link Style}.
972           *           *
973           * @param styledRaster           * @param style
974           * @param iconHeight           *            if <code>null</code>, the default {@link Style} is extracetd
975           * @param iconWidth           *            from the {@link StyledRasterInterface}
          * @return  
976           */           */
977          public static Box createLegendPanel(StyledRasterInterface<?> styledRaster,          public static JPanel createLegendPanel(
978                          int iconWidth, int iconHeight) {                          final StyledRasterInterface<?> styledRaster, Style style,
979                            final int iconWidth, final int iconHeight) {
980    
981                    // If no style is given, we use the default style for this layer
982                    if (style == null)
983                            style = styledRaster.getStyle();
984    
985                  /**                  /**
986                   * Determine whether a Style is responsible for the coloring                   * Determine whether a Style is responsible for the coloring
987                   */                   */
988                  ColorModel colorModel = null;                  ColorModel colorModel = null;
989                  if (!isStyleable(styledRaster)                  if (!isStyleable(styledRaster)
990                                  || (isStyleable(styledRaster) && styledRaster.getStyle() == null)) {                                  || (isStyleable(styledRaster) && style == null)) {
991                          colorModel = getColorModel(styledRaster);                          colorModel = getColorModel(styledRaster);
992                  }                  }
993    
994                  RasterLegendData rasterLegendData = styledRaster.getLegendMetaData();                  final RasterLegendData rasterLegendData = styledRaster
995                  List<Double> legendRasterValues = rasterLegendData.getSortedKeys();                                  .getLegendMetaData();
996                  Map<Double, GridCoverage2D> sampleRasters = rasterLegendData                  final List<Double> legendRasterValues = rasterLegendData
997                                    .getSortedKeys();
998                    final Map<Double, GridCoverage2D> sampleRasters = rasterLegendData
999                                  .createSampleRasters();                                  .createSampleRasters();
1000    
1001                  Box box = new Box(BoxLayout.Y_AXIS) {                  final JPanel panel = new JPanel(new MigLayout("wrap 2, gapy 0"));
1002    
1003                          /**                  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);  
                                 }  
                         }  
                 };  
1004    
1005                  for (Double rValue : legendRasterValues) {                          // final Dimension ICON_SIZE = new Dimension(iconWidth,
1006                            // new JLabel().getFontMetrics(new JLabel().getFont())
1007                          /**                          // .getHeight() > 5 ? new JLabel().getFontMetrics(
1008                           *                          // new JLabel().getFont()).getHeight() : iconHeight);
                          */  
                         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);  
                                         }  
                                 }  
                         };  
   
                         final Dimension ICON_SIZE = new Dimension(iconWidth,  
                                         new JLabel().getFontMetrics(new JLabel().getFont())  
                                                         .getHeight() > 5 ? new JLabel().getFontMetrics(  
                                                         new JLabel().getFont()).getHeight() : iconHeight);  
1009    
1010                          // ****************************************************************************                          // ****************************************************************************
1011                          // Create the actual icon                          // Create the actual icon
1012                          // ****************************************************************************                          // ****************************************************************************
1013                          BufferedImage buffImage = new BufferedImage(ICON_SIZE.width,                          final BufferedImage buffImage = new BufferedImage(iconWidth,
1014                                          ICON_SIZE.height, BufferedImage.TYPE_INT_ARGB);                                          iconHeight, BufferedImage.TYPE_INT_ARGB);
1015                          Graphics2D graphics = buffImage.createGraphics();  
1016                            final Graphics2D graphics = buffImage.createGraphics();
1017    
1018                          if (colorModel != null) {                          if (colorModel != null) {
1019                                    // The colors come from the ColorModel!
1020    
1021                                  try {                                  try {
1022                                          Object inData = null;                                          Object inData = null;
# Line 1116  public class StyledLayerUtil { Line 1045  public class StyledLayerUtil {
1045                                          final Color color = new Color(colorModel.getRGB(inData));                                          final Color color = new Color(colorModel.getRGB(inData));
1046                                          graphics.setBackground(color);                                          graphics.setBackground(color);
1047                                          graphics.setColor(color);                                          graphics.setColor(color);
1048                                          graphics.fillRect(0, 0, ICON_SIZE.width, ICON_SIZE.height);                                          graphics.fillRect(0, 0, iconWidth, iconHeight);
1049                                  } catch (Exception e) {                                  } catch (final Exception e) {
1050                                          LOGGER.debug("Dann nehmen wir halt den GridCoverageRenderer", e);                                          LOGGER.info(
1051                                                            "Dann nehmen wir halt den GridCoverageRenderer", e);
1052                                          colorModel = null;                                          colorModel = null;
1053                                  }                                  }
1054                          }                          } else {
1055                                    // The colors come from the Style
                         if (colorModel == null) {  
1056    
1057                                  /**                                  /**
1058                                   * The coverage contains only one value of value rValue                                   * The coverage contains only one value of value rValue
1059                                   */                                   */
1060                                  GridCoverage2D sampleCov = sampleRasters.get(rValue);                                  final GridCoverage2D sampleCov = sampleRasters.get(rValue);
1061                                  GridCoverageRenderer renderer;                                  GridCoverageRenderer renderer;
1062                                  try {                                  try {
1063                                          renderer = new GridCoverageRenderer(sampleCov                                          renderer = new GridCoverageRenderer(sampleCov
# Line 1136  public class StyledLayerUtil { Line 1065  public class StyledLayerUtil {
1065                                                          .createEnvelope(sampleCov.getEnvelope()),                                                          .createEnvelope(sampleCov.getEnvelope()),
1066                                                          new Rectangle(iconWidth, iconHeight),                                                          new Rectangle(iconWidth, iconHeight),
1067                                                          (AffineTransform) null);                                                          (AffineTransform) null);
1068                                  } catch (Exception e1) {                                  } catch (final Exception e1) {
1069                                          throw new RuntimeException(                                          throw new RuntimeException(
1070                                                          "Creating the GridCoverageRenderer:", e1);                                                          "Creating a GridCoverageRenderer failed:", e1);
1071                                  }                                  }
1072    
1073                                  /**                                  /**
1074                                   * Iterate over all FeatureTypeStyles.                                   * Iterate over all FeatureTypeStyles.
1075                                   */                                   */
1076                                  // for (FeatureTypeStyle ftStyle : styledGrid.getStyle()                                  final List<RasterSymbolizer> rSymbols = StylingUtil
                                 // .featureTypeStyles()) {  
                                 // One child-node for every rule  
                                 // List<Rule> rules = ftStyle.rules();  
                                 // for (Rule rule : rules) {  
                                 final Style style = styledRaster.getStyle();  
                                 List<RasterSymbolizer> rSymbols = StylingUtil  
1077                                                  .getRasterSymbolizers(style);                                                  .getRasterSymbolizers(style);
1078    
1079                                  for (RasterSymbolizer symbolizer : rSymbols) {                                  for (final RasterSymbolizer symbolizer : rSymbols) {
                                         // LOGGER.debug("Creating a new Legend Image for RUle  
                                         // name =  
                                         // "+rule.getName());  
1080                                          try {                                          try {
1081                                                  renderer.paint(graphics, sampleCov, symbolizer);                                                  renderer.paint(graphics, sampleCov, symbolizer);
1082                                          } catch (Exception ee) {                                          } catch (final Exception ee) {
1083                                                  LOGGER.error("Unable to paint " + symbolizer                                                  LOGGER.error("Unable to paint " + symbolizer
1084                                                                  + " into the legend image", ee);                                                                  + " into the legend image", ee);
1085                                          }                                          }
                                         // }  
                                         // }  
1086                                  }                                  }
1087                          }                          }
1088    
1089                          ImageIcon legendIcon = new ImageIcon(buffImage);                          final JLabel iconLabel = new JLabel(new ImageIcon(buffImage));
1090                            panel.add(iconLabel, "sgx1");
                         final JLabel iconLabel = new JLabel(legendIcon);  
                         hbox.setAlignmentX(0f);  
                         hbox.add(iconLabel);  
                         hbox.add(Box.createHorizontalStrut(3));  
1091    
1092                          Translation labelT = rasterLegendData.get(rValue);                          final Translation labelT = rasterLegendData.get(rValue);
1093                          final JLabel classTitleLabel = new JLabel(labelT.toString());                          final JLabel classTitleLabel = new JLabel(labelT.toString());
1094                          hbox.add(classTitleLabel);                          panel.add(classTitleLabel, "sgx2"
1095                                            + (rasterLegendData.isPaintGaps() ? ", gapy 0:0:0 5:5:5"
1096                                                            : ""));
1097                          classTitleLabel.setLabelFor(iconLabel);                          classTitleLabel.setLabelFor(iconLabel);
1098    
1099                          box.add(hbox);                          if (rasterLegendData.isPaintGaps()) {
   
                         if (rasterLegendData.getPaintGaps()) {  
1100                                  iconLabel                                  iconLabel
1101                                                  .setBorder(BorderFactory.createLineBorder(Color.black));                                                  .setBorder(BorderFactory.createLineBorder(Color.black));
                                 box.add(Box.createVerticalStrut(3));  
1102                          }                          }
1103    
1104                  }                  }
1105    
1106                  return box;                  return panel;
1107          }          }
1108    
1109          /**          /**
1110           * Extracts the {@link ColorModel} of any {@link StyledRasterInterface}. May           * Extracts the {@link ColorModel} of any {@link StyledRasterInterface}. May
1111           * return <code>null</code> if the geoobject can not be accessed.           * return <code>null</code> if the geoobject can not be accessed.
1112           */           */
1113          public static ColorModel getColorModel(StyledRasterInterface<?> styledGrid) {          @SuppressWarnings("unchecked")
1114            public static ColorModel getColorModel(
1115                            final StyledRasterInterface<?> styledGrid) {
1116                  ColorModel colorModel = null;                  ColorModel colorModel = null;
1117                  try {                  try {
1118                          Object geoObject = styledGrid.getGeoObject();                          final Object geoObject = styledGrid.getGeoObject();
1119                          if (geoObject instanceof GridCoverage2D) {                          if (geoObject instanceof GridCoverage2D) {
1120                                  GridCoverage2D cov = (GridCoverage2D) geoObject;                                  final GridCoverage2D cov = (GridCoverage2D) geoObject;
1121                                  colorModel = cov.getRenderedImage().getColorModel();                                  colorModel = cov.getRenderedImage().getColorModel();
1122                          } else if (geoObject instanceof ImagePyramidReader) {                          } else if (styledGrid instanceof StyledRasterPyramidInterface) {
1123    
1124                                  Parameter readGG = new Parameter(                                  final Parameter readGG = new Parameter(
1125                                                  AbstractGridFormat.READ_GRIDGEOMETRY2D);                                                  AbstractGridFormat.READ_GRIDGEOMETRY2D);
1126    
1127                                  ReferencedEnvelope mapExtend = new org.geotools.geometry.jts.ReferencedEnvelope(                                  final ReferencedEnvelope mapExtend = new org.geotools.geometry.jts.ReferencedEnvelope(
1128                                                  styledGrid.getEnvelope(), styledGrid.getCrs());                                                  styledGrid.getEnvelope(), styledGrid.getCrs());
1129    
1130                                  readGG.setValue(new GridGeometry2D(new GeneralGridEnvelope(                                  readGG.setValue(new GridGeometry2D(new GeneralGridEnvelope(
1131                                                  new Rectangle(0, 0, 10, 10)), mapExtend));                                                  new Rectangle(0, 0, 1, 1)), mapExtend));
1132    
1133                                    final FeatureCollection<SimpleFeatureType, SimpleFeature> rFc = (FeatureCollection<SimpleFeatureType, SimpleFeature>) geoObject;
1134    
1135                                  final AbstractGridCoverage2DReader aReader = (AbstractGridCoverage2DReader) geoObject;                                  final AbstractGridCoverage2DReader aReader = (AbstractGridCoverage2DReader) FeatureUtil
1136                                  GridCoverage2D cov = (GridCoverage2D) aReader                                                  .getWrappedGeoObject(rFc);
1137                                    final GridCoverage2D cov = (GridCoverage2D) aReader
1138                                                  .read(new GeneralParameterValue[] { readGG });                                                  .read(new GeneralParameterValue[] { readGG });
1139                                  colorModel = cov.getRenderedImage().getColorModel();                                  colorModel = cov.getRenderedImage().getColorModel();
1140                          }                          }
1141                  } catch (Exception e) {                  } catch (final Exception e) {
1142                          LOGGER.error("Error reading the colormodel from " + styledGrid);                          LOGGER.error("Error reading the colormodel from " + styledGrid, e);
1143                          return null;                          return null;
1144                  }                  }
1145                  return colorModel;                  return colorModel;
# Line 1233  public class StyledLayerUtil { Line 1151  public class StyledLayerUtil {
1151           *         with their own {@link ColorModel} and will ignore any           *         with their own {@link ColorModel} and will ignore any
1152           *         {@link RasterSymbolizer} = SLD.           *         {@link RasterSymbolizer} = SLD.
1153           */           */
1154          public static boolean isStyleable(StyledRasterInterface<?> styledRaster) {          public static boolean isStyleable(
1155                  ColorModel colorModel = getColorModel(styledRaster);                          final StyledRasterInterface<?> styledRaster) {
1156                    final ColorModel colorModel = getColorModel(styledRaster);
1157                  LOGGER.info("The colormodel of " + styledRaster.getTitle() + " is "  
1158                                  + colorModel.getClass().getSimpleName());                  // LOGGER.info("The colormodel of " + styledRaster.getTitle() + " is "
1159                    // + colorModel != null ? colorModel.getClass().getSimpleName() :
1160                    // "NULL");
1161    
1162                  if (colorModel == null)                  if (colorModel == null)
1163                          return true;                          return true;
# Line 1245  public class StyledLayerUtil { Line 1165  public class StyledLayerUtil {
1165                          return true;                          return true;
1166                  return false;                  return false;
1167          }          }
1168    
1169            /**
1170             * Set the given Style as the Style of the {@link MapLayer}, unless the
1171             * styles are the same (not comparing selection stuff). If the
1172             * {@link MapLayer}s {@link Style} is changed, the selection FTS is kept.<br/>
1173             * Remember {@link MapLayer#setStyle(Style)} triggers an event leading to a
1174             * repaint, so only use it when needed.
1175             *
1176             * @return <code>true</code> if the {@link MapLayer}'s {@link Style} has
1177             *         been changed.
1178             */
1179            public static boolean updateMapLayerStyleIfChangedAndKeepSelection(
1180                            MapLayer mapLayer, Style style2) {
1181    
1182                    Style mapLayerStyleCleaned = StylingUtil
1183                                    .removeSelectionFeatureTypeStyle(mapLayer.getStyle());
1184    
1185                    Style newStyleCleaned = StylingUtil
1186                                    .removeSelectionFeatureTypeStyle(style2);
1187    
1188                    if (StylingUtil.isStyleDifferent(mapLayerStyleCleaned, newStyleCleaned)) {
1189    
1190                            // They are different when compared without SELECTION FTS!
1191    
1192                            // Now let's copy any SELECTION FTS to the now style
1193                            FeatureTypeStyle selectionFeatureTypeStyle = StylingUtil
1194                                            .getSelectionFeatureTypeStyle(mapLayer.getStyle());
1195                            if (selectionFeatureTypeStyle != null) {
1196                                    newStyleCleaned.featureTypeStyles().add(
1197                                                    selectionFeatureTypeStyle);
1198                                    // newStyleCleaned is not so clean anymore... We just alled a
1199                                    // selcetion FTS
1200                            }
1201    
1202                            mapLayer.setStyle(newStyleCleaned);
1203    
1204                            return true;
1205    
1206                    } else {
1207                            return false;
1208                    }
1209            }
1210    
1211            /**
1212             * After loading an atlas, the AttribteMetaData contains whatever is written
1213             * in the XML. But the DBF may have changed! This method checks an
1214             * {@link AttributeMetadataMap} against a schema and also corrects
1215             * upperCase/lowerCase problems. It will also remove any geometry column
1216             * attribute metadata.
1217             */
1218            /**
1219             * After loading an atlas, the AttribteMetaData contains whatever is written
1220             * in the XML. But the DBF may have changed!
1221             */
1222            public static void checkAttribMetaData(AttributeMetadataMap attributeMetaDataMap,
1223                            SimpleFeatureType schema) {
1224    
1225                    ArrayList<Name> willRemove = new ArrayList<Name>();
1226    
1227                    // 1. Check.. all attributes in the atm should be in the schema as well.
1228                    // maybe correct some upperCase/loweCase stuff
1229    
1230                    for (AttributeMetadata atm : attributeMetaDataMap.values()) {
1231    
1232                            AttributeDescriptor foundDescr = schema
1233                                            .getDescriptor(atm.getName());
1234                            if (foundDescr == null) {
1235                                    Name bestMatch = FeatureUtil.findBestMatchingAttribute(schema,
1236                                                    atm.getLocalName());
1237                                    if (bestMatch == null)
1238                                            willRemove.add(atm.getName());
1239                                    else
1240                                            atm.setName(bestMatch);
1241                            } else if (foundDescr instanceof GeometryDescriptor) {
1242                                    // We don't want GeometryColumns in here
1243                                    willRemove.add(atm.getName());
1244                            }
1245                    }
1246    
1247                    // Remove the ones that were not findable in the schema
1248                    for (Name removeName : willRemove) {
1249                            if (attributeMetaDataMap.remove(removeName) == null){
1250                                    LOGGER.warn("removing the AMData didn't work");
1251                            }
1252                    }
1253    
1254                    // 2. check... all attributes from the schema must have an ATM
1255                    for (AttributeDescriptor ad : schema.getAttributeDescriptors()) {
1256                            if (ad instanceof GeometryDescriptor)
1257                                    continue;
1258                            if (!attributeMetaDataMap.containsKey(ad.getName())) {
1259                                    attributeMetaDataMap.put(ad.getName(), new AttributeMetadata(
1260                                                    ad, schema.getAttributeDescriptors().indexOf(ad), attributeMetaDataMap
1261                                                                    .getLanguages()));
1262                            }
1263                    }
1264    
1265            }
1266    
1267  }  }

Legend:
Removed from v.406  
changed lines
  Added in v.607

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26