/[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 409 by alfonx, Fri Sep 18 15:00:29 2009 UTC branches/2.0-RC2/src/skrueger/geotools/StyledLayerUtil.java revision 658 by alfonx, Wed Feb 3 15:32:21 2010 UTC
# Line 31  package skrueger.geotools; Line 31  package skrueger.geotools;
31    
32  import java.awt.Color;  import java.awt.Color;
33  import java.awt.Dimension;  import java.awt.Dimension;
 import java.awt.Graphics;  
34  import java.awt.Graphics2D;  import java.awt.Graphics2D;
35  import java.awt.Rectangle;  import java.awt.Rectangle;
36  import java.awt.geom.AffineTransform;  import java.awt.geom.AffineTransform;
# 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             *            TODO Since GP 1.3 the {@link AttributeMetadata} class has more
312             *            attributes which are not used by Xulu/ISDSS. GP
313             *            exports/imports the AMD via AMLExporter and AMLImporter
314             *            classes. (SK, 3.2.2010)    *            
315           */           */
316          public static Map<Integer, AttributeMetaData> parseAttributeMetaDataMap(          public static AttributeMetadataMap parseAttributeMetaDataMap(
317                          final Element element) {                          final Element element) {
318                  HashMap<Integer, AttributeMetaData> metaData = new HashMap<Integer, AttributeMetaData>();                  final AttributeMetadataMap metaData = new AttributeMetadataMap();
319                  List<Element> attributesElements = element                  final List<Element> attributesElements = element
320                                  .getChildren(ELEM_NAME_ATTRIBUTE);                                  .getChildren(ELEM_NAME_ATTRIBUTE);
321                  for (Element attibuteElement : attributesElements) {                  for (final Element attibuteElement : attributesElements) {
322                          AttributeMetaData attrMetaData = parseAttributeMetaData(attibuteElement);                          final AttributeMetadata attrMetaData = parseAttributeMetaData(attibuteElement);
323                          metaData.put(attrMetaData.getColIdx(), attrMetaData);                          metaData.put(attrMetaData.getName(), attrMetaData);
324                  }                  }
325                  return metaData;                  return metaData;
326          }          }
327    
328          /**          /**
329           * Loads a {@link AttributeMetaData} object from an URL.           * Loads a {@link AttributeMetadata} object from an URL.
330           *           *
331           * @param documentUrl           * @param documentUrl
332           *            {@link URL} to parse           *            {@link URL} to parse
333           * @see #parseAttributeMetaData(Element)           * @see #parseAttributeMetaData(Element)
334           */           */
335          public static Map<Integer, AttributeMetaData> loadAttributeMetaDataMap(          public static AttributeMetadataMap loadAttributeMetaDataMap(
336                          final URL documentUrl) throws Exception {                          final URL documentUrl) throws Exception {
337                  Document document = SAX_BUILDER.build(documentUrl);                  final Document document = SAX_BUILDER.build(documentUrl);
338                  return parseAttributeMetaDataMap(document.getRootElement());                  return parseAttributeMetaDataMap(document.getRootElement());
339          }          }
340    
341          /**          /**
342           * Creates an JDOM {@link Element} for the given {@link AttributeMetaData}           * Creates an JDOM {@link Element} for the given {@link AttributeMetadata}
343           * object.           * object.
344           *           *
345           * @param amd           * @param amd
346           *            meta data for one attribute           *            meta data for one attribute
347             *
348             *            TODO Since GP 1.3 the {@link AttributeMetadata} class has more
349             *            attributes which are not used by Xulu/ISDSS. GP
350             *            exports/imports the AMD via AMLExporter and AMLImporter
351             *            classes. (SK, 3.2.2010)
352           */           */
353          public static Element createAttributeMetaDataElement(          public static Element createAttributeMetaDataElement(
354                          final AttributeMetaData amd) {                          final AttributeMetadata amd) {
355                  final Element element = new Element(ELEM_NAME_ATTRIBUTE, AMLURI);                  final Element element = new Element(ELEM_NAME_ATTRIBUTE, AMLURI);
356                  element.setAttribute("col", String.valueOf(amd.getColIdx()));                  element.setAttribute("namespace", String.valueOf(amd.getName()
357                                    .getNamespaceURI()));
358                    element.setAttribute("localname", String.valueOf(amd.getLocalName()));
359                  element.setAttribute("visible", String.valueOf(amd.isVisible()));                  element.setAttribute("visible", String.valueOf(amd.isVisible()));
360                  element.setAttribute("unit", amd.getUnit());                  element.setAttribute("unit", amd.getUnit());
361                  // Creating a aml:name tag...                  // Creating a aml:name tag...
# Line 335  public class StyledLayerUtil { Line 366  public class StyledLayerUtil {
366          }          }
367    
368          /**          /**
369           * Creates an JDOM {@link Element} for the given {@link AttributeMetaData}           * Creates an JDOM {@link Element} for the given {@link AttributeMetadata}
370           * map.           * map.
371           *           *
372           * @param amdMap           * @param amdMap
373           *            map of attribute meta data           *            map of attribute meta data
374           */           */
375          public static Element createAttributeMetaDataMapElement(          public static Element createAttributeMetaDataMapElement(
376                          final Map<Integer, AttributeMetaData> amdMap) {                          final AttributeMetadataMap amdMap) {
377                  final Element element = new Element(ELEM_NAME_AMD, AMLURI);                  final Element element = new Element(ELEM_NAME_AMD, AMLURI);
378                  for (AttributeMetaData amd : amdMap.values())                  for (final AttributeMetadata amd : amdMap.values())
379                          element.addContent(createAttributeMetaDataElement(amd));                          element.addContent(createAttributeMetaDataElement(amd));
380                  return element;                  return element;
381          }          }
382    
383          /**          /**
384           * Saves a {@link AttributeMetaData AttributeMetaData-Map} to an URL.           * Saves a {@link AttributeMetadata AttributeMetaData-Map} to an URL.
385           *           *
386           * @param amdMap           * @param amdMap
387           *            map of {@link AttributeMetaData}           *            map of {@link AttributeMetadata}
388           * @param documentUrl           * @param documentUrl
389           *            {@link URL} to store the XML           *            {@link URL} to store the XML
390           */           */
391          public static void saveAttributeMetaDataMap(          public static void saveAttributeMetaDataMap(
392                          final Map<Integer, AttributeMetaData> amdMap, final URL documentUrl)                          final AttributeMetadataMap amdMap, final URL documentUrl)
393                          throws Exception {                          throws Exception {
394                  // Create XML-Document                  // Create XML-Document
395                  final FileWriter out = new FileWriter(new File(documentUrl.toURI()));                  final FileWriter out = new FileWriter(new File(documentUrl.toURI()));
# Line 375  public class StyledLayerUtil { Line 406  public class StyledLayerUtil {
406           * @param element           * @param element
407           *            {@link Element} to parse           *            {@link Element} to parse
408           */           */
409          public static RasterLegendData parseRasterLegendData(Element element) {          public static RasterLegendData parseRasterLegendData(final Element element) {
410    
411                  final boolean paintGaps = Boolean.valueOf(element                  final boolean paintGaps = Boolean.valueOf(element
412                                  .getAttributeValue("paintGaps"));                                  .getAttributeValue("paintGaps"));
413    
414                  RasterLegendData rld = new RasterLegendData(paintGaps);                  final RasterLegendData rld = new RasterLegendData(paintGaps);
415    
416                  for (Element childElement : (List<Element>) element.getChildren()) {                  for (final Element childElement : (List<Element>) element.getChildren()) {
417                          final String name = childElement.getName();                          final String name = childElement.getName();
418                          // Cancel if it's an attribute                          // Cancel if it's an attribute
419                          if (childElement.getChildren().size() == 0)                          if (childElement.getChildren().size() == 0)
# Line 402  public class StyledLayerUtil { Line 433  public class StyledLayerUtil {
433                                  // id label element is missing, the translation is searched                                  // id label element is missing, the translation is searched
434                                  // directly                                  // directly
435                                  // as childs of the rasterLegendItem element                                  // as childs of the rasterLegendItem element
436                                  Translation label = parseTranslation(labelElement != null ? labelElement                                  final Translation label = parseTranslation(labelElement != null ? labelElement
437                                                  : childElement);                                                  : childElement);
438                                  rld.put(value, label);                                  rld.put(value, label);
439                          }                          }
# Line 420  public class StyledLayerUtil { Line 451  public class StyledLayerUtil {
451           */           */
452          public static RasterLegendData loadRasterLegendData(final URL documentUrl)          public static RasterLegendData loadRasterLegendData(final URL documentUrl)
453                          throws Exception {                          throws Exception {
454                  Document document = SAX_BUILDER.build(documentUrl);                  final Document document = SAX_BUILDER.build(documentUrl);
455                  return parseRasterLegendData(document.getRootElement());                  return parseRasterLegendData(document.getRootElement());
456          }          }
457    
# Line 435  public class StyledLayerUtil { Line 466  public class StyledLayerUtil {
466                          final RasterLegendData rld) {                          final RasterLegendData rld) {
467                  final Element element = new Element(ELEM_NAME_RLD, AMLURI);                  final Element element = new Element(ELEM_NAME_RLD, AMLURI);
468                  element.setAttribute("paintGaps", rld.isPaintGaps().toString());                  element.setAttribute("paintGaps", rld.isPaintGaps().toString());
469                  for (Double key : rld.getSortedKeys()) {                  for (final Double key : rld.getSortedKeys()) {
470                          Element item = new Element(ELEM_NAME_RASTERLEGEND, AMLURI);                          final Element item = new Element(ELEM_NAME_RASTERLEGEND, AMLURI);
471                          item.setAttribute("value", key.toString());                          item.setAttribute("value", key.toString());
472                          item.addContent(createTranslationElement("label", rld.get(key)));                          item.addContent(createTranslationElement("label", rld.get(key)));
473                          element.addContent(item);                          element.addContent(item);
# Line 456  public class StyledLayerUtil { Line 487  public class StyledLayerUtil {
487           *            rounded to (null means no round; >= 0 means digits after           *            rounded to (null means no round; >= 0 means digits after
488           *            comma; < 0 means digits before comma)           *            comma; < 0 means digits before comma)
489           */           */
490          public static RasterLegendData generateRasterLegendData(ColorMap colorMap,          public static RasterLegendData generateRasterLegendData(
491                          boolean paintGaps, Integer digits) {                          final ColorMap colorMap, final boolean paintGaps,
492                  DecimalFormat decFormat = digits != null ? new DecimalFormat(SwingUtil                          final Integer digits) {
493                                  .getNumberFormatPattern(digits)) : null;                  final DecimalFormat decFormat = digits != null ? new DecimalFormat(
494                  RasterLegendData rld = new RasterLegendData(paintGaps);                                  SwingUtil.getNumberFormatPattern(digits)) : null;
495                  for (ColorMapEntry cme : colorMap.getColorMapEntries()) {                  final RasterLegendData rld = new RasterLegendData(paintGaps);
496                          double value = StylingUtil.getQuantityFromColorMapEntry(cme);                  for (final ColorMapEntry cme : colorMap.getColorMapEntries()) {
497                            final double value = StylingUtil.getQuantityFromColorMapEntry(cme);
498                          String label = cme.getLabel();                          String label = cme.getLabel();
499                          // if no label is set (e.g. quantitative style),                          // if no label is set (e.g. quantitative style),
500                          // use the value as label                          // use the value as label
# Line 488  public class StyledLayerUtil { Line 520  public class StyledLayerUtil {
520           *            rounded to (null means no round; >= 0 means digits after           *            rounded to (null means no round; >= 0 means digits after
521           *            comma; < 0 means digits before comma)           *            comma; < 0 means digits before comma)
522           */           */
523          public static RasterLegendData generateRasterLegendData(Style style,          public static RasterLegendData generateRasterLegendData(final Style style,
524                          boolean paintGaps, Integer digits) {                          final boolean paintGaps, final Integer digits) {
525                  ColorMap colorMap = StylingUtil.getColorMapFromStyle(style);                  final ColorMap colorMap = StylingUtil.getColorMapFromStyle(style);
526                  if (colorMap == null)                  if (colorMap == null)
527                          throw new IllegalArgumentException(                          throw new IllegalArgumentException(
528                                          "Color map can not be determined from style!");                                          "Color map can not be determined from style!");
# Line 523  public class StyledLayerUtil { Line 555  public class StyledLayerUtil {
555           *            {@link Element} to parse           *            {@link Element} to parse
556           */           */
557          public final static Translation parseTranslation(final Element element) {          public final static Translation parseTranslation(final Element element) {
558                  Translation trans = new Translation();                  final Translation trans = new Translation();
559    
560                  if (element == null)                  if (element == null)
561                          return trans;                          return trans;
# Line 565  public class StyledLayerUtil { Line 597  public class StyledLayerUtil {
597           * @param translation           * @param translation
598           *            Translation to store in the Element           *            Translation to store in the Element
599           */           */
600          public final static Element createTranslationElement(String tagname,          public final static Element createTranslationElement(final String tagname,
601                          Translation translation) {                          final Translation translation) {
602                  Element element = new Element(tagname, AMLURI);                  final Element element = new Element(tagname, AMLURI);
603                  if (translation == null)                  if (translation == null)
604                          throw new UnsupportedOperationException(                          throw new UnsupportedOperationException(
605                                          "Translation element can not be created from null!");                                          "Translation element can not be created from null!");
# Line 583  public class StyledLayerUtil { Line 615  public class StyledLayerUtil {
615    
616                  // add a <translation lang="..">..</tranlation> part to the element for                  // add a <translation lang="..">..</tranlation> part to the element for
617                  // all languages                  // all languages
618                  for (String lang : translation.keySet()) {                  for (final String lang : translation.keySet()) {
619                          Element translationElement = new Element(ELEM_NAME_TRANSLATION,                          final Element translationElement = new Element(
620                                          AMLURI);                                          ELEM_NAME_TRANSLATION, AMLURI);
621                          translationElement.setAttribute("lang", lang);                          translationElement.setAttribute("lang", lang);
622                          String translationString = translation.get(lang);                          String translationString = translation.get(lang);
623                          if (translationString == null)                          if (translationString == null)
# Line 605  public class StyledLayerUtil { Line 637  public class StyledLayerUtil {
637           * @param style           * @param style
638           *            a Style           *            a Style
639           */           */
640          public static void setStyledLayerStyle(StyledLayerInterface styledObject,          public static void setStyledLayerStyle(
641                          StyledLayerStyle<?> style) {                          final StyledLayerInterface styledObject,
642                            final StyledLayerStyle<?> style) {
643                  // set SLD style                  // set SLD style
644                  styledObject.setStyle(style.getGeoObjectStyle());                  styledObject.setStyle(style.getGeoObjectStyle());
645                  // set meta data                  // set meta data
646                  if (styledObject instanceof StyledGridCoverageInterface                  if (styledObject instanceof StyledGridCoverageInterface
647                                  && (style.getMetaData() instanceof RasterLegendData || style                                  && (style.getMetaData() instanceof RasterLegendData || style
648                                                  .getMetaData() == null)) {                                                  .getMetaData() == null)) {
649                          RasterLegendData sourceRld = (RasterLegendData) style.getMetaData();                          final RasterLegendData sourceRld = (RasterLegendData) style
650                          RasterLegendData destRld = ((StyledGridCoverageInterface) styledObject)                                          .getMetaData();
651                            final RasterLegendData destRld = ((StyledGridCoverageInterface) styledObject)
652                                          .getLegendMetaData();                                          .getLegendMetaData();
653                          if (destRld != null && sourceRld != null) {                          if (destRld != null && sourceRld != null) {
654                                  destRld.setPaintGaps(sourceRld.isPaintGaps());                                  destRld.setPaintGaps(sourceRld.isPaintGaps());
# Line 625  public class StyledLayerUtil { Line 659  public class StyledLayerUtil {
659                  }                  }
660                  if (styledObject instanceof StyledFeatureCollectionInterface                  if (styledObject instanceof StyledFeatureCollectionInterface
661                                  && (style.getMetaData() instanceof Map || style.getMetaData() == null)) {                                  && (style.getMetaData() instanceof Map || style.getMetaData() == null)) {
662                          Map<Integer, AttributeMetaData> sourceAmd = (Map<Integer, AttributeMetaData>) style                          final AttributeMetadataMap sourceAmd = (AttributeMetadataMap) style
663                                          .getMetaData();                                          .getMetaData();
664                          Map<Integer, AttributeMetaData> destAmd = ((StyledFeatureCollectionInterface) styledObject)                          final AttributeMetadataMap destAmd = ((StyledFeatureCollectionInterface) styledObject)
665                                          .getAttributeMetaDataMap();                                          .getAttributeMetaDataMap();
666                          if (destAmd != null && sourceAmd != null) {                          if (destAmd != null && sourceAmd != null) {
667                                  destAmd.clear();                                  destAmd.clear();
# Line 657  public class StyledLayerUtil { Line 691  public class StyledLayerUtil {
691           *         {@link StyledFeatureCollectionInterface}           *         {@link StyledFeatureCollectionInterface}
692           */           */
693          public static StyledLayerStyle<?> getStyledLayerStyle(          public static StyledLayerStyle<?> getStyledLayerStyle(
694                          StyledLayerInterface styledObject) {                          final StyledLayerInterface styledObject) {
695                  if (styledObject instanceof StyledGridCoverageInterface)                  if (styledObject instanceof StyledGridCoverageInterface)
696                          return getStyledLayerStyle((StyledGridCoverageInterface) styledObject);                          return getStyledLayerStyle((StyledGridCoverageInterface) styledObject);
697                  if (styledObject instanceof StyledFeatureCollectionInterface)                  if (styledObject instanceof StyledFeatureCollectionInterface)
# Line 676  public class StyledLayerUtil { Line 710  public class StyledLayerUtil {
710           *            a styled grid coverage           *            a styled grid coverage
711           */           */
712          public static StyledLayerStyle<RasterLegendData> getStyledLayerStyle(          public static StyledLayerStyle<RasterLegendData> getStyledLayerStyle(
713                          StyledGridCoverageInterface styledGC) {                          final StyledGridCoverageInterface styledGC) {
714                  return new StyledLayerStyle<RasterLegendData>(styledGC.getStyle(),                  return new StyledLayerStyle<RasterLegendData>(styledGC.getStyle(),
715                                  styledGC.getLegendMetaData());                                  styledGC.getLegendMetaData());
716          }          }
# Line 688  public class StyledLayerUtil { Line 722  public class StyledLayerUtil {
722           * @param styledFC           * @param styledFC
723           *            a styled feature collection           *            a styled feature collection
724           */           */
725          public static StyledLayerStyle<Map<Integer, AttributeMetaData>> getStyledLayerStyle(          public static StyledLayerStyle<AttributeMetadataMap> getStyledLayerStyle(
726                          StyledFeatureCollectionInterface styledFC) {                          final StyledFeatureCollectionInterface styledFC) {
727                  return new StyledLayerStyle<Map<Integer, AttributeMetaData>>(styledFC                  return new StyledLayerStyle<AttributeMetadataMap>(styledFC.getStyle(),
728                                  .getStyle(), styledFC.getAttributeMetaDataMap());                                  styledFC.getAttributeMetaDataMap());
729          }          }
730    
731          /**          /**
# Line 708  public class StyledLayerUtil { Line 742  public class StyledLayerUtil {
742           * @return {@code null} in case of any error           * @return {@code null} in case of any error
743           */           */
744          public static StyledLayerStyle<RasterLegendData> loadStyledRasterStyle(          public static StyledLayerStyle<RasterLegendData> loadStyledRasterStyle(
745                          URL geoObjectURL, String sldExt, String rldExt) {                          final URL geoObjectURL, final String sldExt, final String rldExt) {
746                  RasterLegendData metaData = null;                  RasterLegendData metaData = null;
747                  Style sldStyle = null;                  Style sldStyle = null;
748                  try {                  try {
749                          Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(                          final Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(
750                                          geoObjectURL, sldExt));                                          geoObjectURL, sldExt));
751                          // SLD must be present                          // SLD must be present
752                          if (styles == null || styles.length == 0)                          if (styles == null || styles.length == 0)
753                                  return null;                                  return null;
754                          sldStyle = styles[0];                          sldStyle = styles[0];
755                  } catch (Exception err) {                  } catch (final Exception err) {
756                          // SLD must be present                          // SLD must be present
757                          LangUtil.logDebugError(LOGGER, err);                          LangUtil.logDebugError(LOGGER, err);
758                          return null;                          return null;
# Line 727  public class StyledLayerUtil { Line 761  public class StyledLayerUtil {
761                  try {                  try {
762                          metaData = StyledLayerUtil.loadRasterLegendData(IOUtil                          metaData = StyledLayerUtil.loadRasterLegendData(IOUtil
763                                          .changeUrlExt(geoObjectURL, rldExt));                                          .changeUrlExt(geoObjectURL, rldExt));
764                  } catch (FileNotFoundException err) {                  } catch (final FileNotFoundException err) {
765                          // ignore missing raster legend data                          // ignore missing raster legend data
766                  } catch (Exception err) {                  } catch (final Exception err) {
767                          // any other error during legend data creation leads to error                          // any other error during legend data creation leads to error
768                          LangUtil.logDebugError(LOGGER, err);                          LangUtil.logDebugError(LOGGER, err);
769                          return null;                          return null;
# Line 752  public class StyledLayerUtil { Line 786  public class StyledLayerUtil {
786           * @return {@code null} in case of any error           * @return {@code null} in case of any error
787           */           */
788          public static StyledLayerStyle<RasterLegendData> loadStyledRasterStyle(          public static StyledLayerStyle<RasterLegendData> loadStyledRasterStyle(
789                          URL geoObjectURL) {                          final URL geoObjectURL) {
790                  return loadStyledRasterStyle(geoObjectURL, "sld", "rld");                  return loadStyledRasterStyle(geoObjectURL, "sld", "rld");
791          }          }
792    
793          /**          /**
794           * Loads a {@linkplain Style SLD-Style} and a {@linkplain AttributeMetaData           * Loads a {@linkplain Style SLD-Style} and a {@linkplain AttributeMetadata
795           * AttributeMetaData-Map} for a given geo-object (feature) source. The SLD           * AttributeMetaData-Map} for a given geo-object (feature) source. The SLD
796           * file must be present. A missing attribute meta-data file is tolerated.           * file must be present. A missing attribute meta-data file is tolerated.
797           *           *
# Line 769  public class StyledLayerUtil { Line 803  public class StyledLayerUtil {
803           *            file extention for the raster legend-data file           *            file extention for the raster legend-data file
804           * @return {@code null} in case of any error           * @return {@code null} in case of any error
805           */           */
806          public static StyledLayerStyle<Map<Integer, AttributeMetaData>> loadStyledFeatureStyle(          public static StyledLayerStyle<AttributeMetadataMap> loadStyledFeatureStyle(
807                          URL geoObjectURL, String sldExt, String rldExt) {                          final URL geoObjectURL, final String sldExt, final String rldExt) {
808                  Map<Integer, AttributeMetaData> metaData = null;                  AttributeMetadataMap metaData = null;
809                  Style sldStyle = null;                  Style sldStyle = null;
810                  try {                  try {
811                          Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(                          final Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(
812                                          geoObjectURL, sldExt));                                          geoObjectURL, sldExt));
813                          // SLD must be present                          // SLD must be present
814                          if (styles == null || styles.length == 0)                          if (styles == null || styles.length == 0)
815                                  return null;                                  return null;
816                          sldStyle = styles[0];                          sldStyle = styles[0];
817                  } catch (Exception err) {                  } catch (final Exception err) {
818                          // SLD must be present                          // SLD must be present
819                          LangUtil.logDebugError(LOGGER, err);                          LangUtil.logDebugError(LOGGER, err);
820                          return null;                          return null;
# Line 789  public class StyledLayerUtil { Line 823  public class StyledLayerUtil {
823                  try {                  try {
824                          metaData = StyledLayerUtil.loadAttributeMetaDataMap(IOUtil                          metaData = StyledLayerUtil.loadAttributeMetaDataMap(IOUtil
825                                          .changeUrlExt(geoObjectURL, rldExt));                                          .changeUrlExt(geoObjectURL, rldExt));
826                  } catch (FileNotFoundException err) {                  } catch (final FileNotFoundException err) {
827                          // ignore missing attribute meta data                          // ignore missing attribute meta data
828                  } catch (Exception err) {                  } catch (final Exception err) {
829                          // any other error during meta data creation leads to error                          // any other error during meta data creation leads to error
830                          LangUtil.logDebugError(LOGGER, err);                          LangUtil.logDebugError(LOGGER, err);
831                          return null;                          return null;
832                  }                  }
833    
834                  return new StyledLayerStyle<Map<Integer, AttributeMetaData>>(sldStyle,                  return new StyledLayerStyle<AttributeMetadataMap>(sldStyle, metaData);
                                 metaData);  
835          }          }
836    
837          /**          /**
838           * Loads a {@linkplain Style SLD-Style} from a {@code .sld} file and           * Loads a {@linkplain Style SLD-Style} from a {@code .sld} file and
839           * {@linkplain AttributeMetaData AttributeMetaData-Map} from a {@code .amd}           * {@linkplain AttributeMetadata AttributeMetaData-Map} from a {@code .amd}
840           * file for a given geo-object (feature) source. The SLD file must be           * file for a given geo-object (feature) source. The SLD file must be
841           * present. A missing attribute meta-data file is tolerated.           * present. A missing attribute meta-data file is tolerated.
842           *           *
# Line 815  public class StyledLayerUtil { Line 848  public class StyledLayerUtil {
848           *            file extention for the raster legend-data file           *            file extention for the raster legend-data file
849           * @return {@code null} in case of any error           * @return {@code null} in case of any error
850           */           */
851          public static StyledLayerStyle<Map<Integer, AttributeMetaData>> loadStyledFeatureStyle(          public static StyledLayerStyle<AttributeMetadataMap> loadStyledFeatureStyle(
852                          URL geoObjectURL) {                          final URL geoObjectURL) {
853                  return loadStyledFeatureStyle(geoObjectURL, "sld", "amd");                  return loadStyledFeatureStyle(geoObjectURL, "sld", "amd");
854          }          }
855    
# Line 833  public class StyledLayerUtil { Line 866  public class StyledLayerUtil {
866           * @param mdExt           * @param mdExt
867           *            file extention for the meta-data file           *            file extention for the meta-data file
868           */           */
869          public static <T> void saveStyledLayerStyle(StyledLayerStyle<T> style,          public static <T> void saveStyledLayerStyle(
870                          URL geoObjectURL, String sldExt, String mdExt) throws Exception {                          final StyledLayerStyle<T> style, final URL geoObjectURL,
871                            final String sldExt, final String mdExt) throws Exception {
872                  // Store the SLD                  // Store the SLD
873                  Style sldStyle = style.getGeoObjectStyle();                  final Style sldStyle = style.getGeoObjectStyle();
874                  if (sldStyle != null) {                  if (sldStyle != null) {
875                          StylingUtil.saveStyleToSLD(sldStyle, IOUtil.changeFileExt(new File(                          StylingUtil.saveStyleToSLD(sldStyle, IOUtil.changeFileExt(new File(
876                                          geoObjectURL.toURI()), sldExt));                                          geoObjectURL.toURI()), sldExt));
877                  }                  }
878    
879                  // Store the meta data                  // Store the meta data
880                  T metaData = style.getMetaData();                  final T metaData = style.getMetaData();
881                  if (metaData != null) {                  if (metaData != null) {
882                          if (metaData instanceof RasterLegendData) {                          if (metaData instanceof RasterLegendData) {
883                                  saveRasterLegendData((RasterLegendData) metaData, IOUtil                                  saveRasterLegendData((RasterLegendData) metaData, IOUtil
# Line 852  public class StyledLayerUtil { Line 886  public class StyledLayerUtil {
886                                  // Map<Integer,AttributeMetaData> ) { // LEIDER NICHT                                  // Map<Integer,AttributeMetaData> ) { // LEIDER NICHT
887                                  // KOMPILIERBAR!!                                  // KOMPILIERBAR!!
888                          } else if (metaData instanceof Map) {                          } else if (metaData instanceof Map) {
889                                  saveAttributeMetaDataMap(                                  saveAttributeMetaDataMap((AttributeMetadataMap) metaData,
890                                                  (Map<Integer, AttributeMetaData>) metaData, IOUtil                                                  IOUtil.changeUrlExt(geoObjectURL, mdExt));
                                                                 .changeUrlExt(geoObjectURL, mdExt));  
891                          } else                          } else
892                                  throw new UnsupportedOperationException(                                  throw new UnsupportedOperationException(
893                                                  "Export for meta data not yet supported: "                                                  "Export for meta data not yet supported: "
# Line 864  public class StyledLayerUtil { Line 897  public class StyledLayerUtil {
897    
898          /**          /**
899           * Stores the {@linkplain Style SLD-Style} to a {@code .sld} file and the           * Stores the {@linkplain Style SLD-Style} to a {@code .sld} file and the
900           * meta data ({@link RasterLegendData} or {@link AttributeMetaData}) to a           * meta data ({@link RasterLegendData} or {@link AttributeMetadata}) to a
901           * {@code .rld} or {@code .amd} file. for a given geo-object source.           * {@code .rld} or {@code .amd} file. for a given geo-object source.
902           *           *
903           * @param style           * @param style
# Line 872  public class StyledLayerUtil { Line 905  public class StyledLayerUtil {
905           * @param geoObjectURL           * @param geoObjectURL
906           *            URL of the (already read) raster object           *            URL of the (already read) raster object
907           */           */
908          public static void saveStyledLayerStyle(StyledLayerStyle<?> style,          public static void saveStyledLayerStyle(final StyledLayerStyle<?> style,
909                          URL geoObjectURL) throws Exception {                          final URL geoObjectURL) throws Exception {
910                  if (style.getMetaData() instanceof RasterLegendData)                  if (style.getMetaData() instanceof RasterLegendData)
911                          saveStyledLayerStyle(style, geoObjectURL, "sld", "rld");                          saveStyledLayerStyle(style, geoObjectURL, "sld", "rld");
912                  else                  else
# Line 881  public class StyledLayerUtil { Line 914  public class StyledLayerUtil {
914          }          }
915    
916          /**          /**
917           * Creates a {@link Box} that shows a legend for a list of           * Creates a {@link JPanel} that shows a legend for a list of
918           * {@link FeatureTypeStyle}s and a targeted featureType           * {@link FeatureTypeStyle}s and a targeted featureType
919           *           *
920           * @param featureType           * @param featureType
# Line 892  public class StyledLayerUtil { Line 925  public class StyledLayerUtil {
925           * @author <a href="mailto:[email protected]">Stefan Alfons           * @author <a href="mailto:[email protected]">Stefan Alfons
926           *         Kr&uuml;ger</a>           *         Kr&uuml;ger</a>
927           */           */
928          public static Box createLegendPanel(List<FeatureTypeStyle> list,          public static JPanel createLegendPanel(Style style,
929                          SimpleFeatureType featureType, int iconWidth, int iconHeight) {                          final SimpleFeatureType featureType, final int iconWidth,
930                            final int iconHeight) {
931    
932                  Box box = new Box(BoxLayout.Y_AXIS) {                  final List<FeatureTypeStyle> list = style.featureTypeStyles();
933    
934                          /**                  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);  
                                 }  
                         }  
                 };  
935    
936                  for (FeatureTypeStyle ftStyle : list) {                  if (style == null) {
937                            // No Style => no legend
938                            return panel;
939                    }
940    
941                    for (final FeatureTypeStyle ftStyle : list) {
942    
943                          // One child-node for every rule                          // One child-node for every rule
944                          List<Rule> rules = ftStyle.rules();                          final List<Rule> rules = ftStyle.rules();
945                          for (Rule rule : rules) {                          for (final Rule rule : rules) {
946    
947                                  /**                                  /**
948                                   * 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 952  public class StyledLayerUtil {
952                                                  .size() == rule.getSymbolizers().length)                                                  .size() == rule.getSymbolizers().length)
953                                          continue;                                          continue;
954    
                                 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  
                                 // ****************************************************************************  
955                                  final BufferedImage imageForRule = LegendIconFeatureRenderer                                  final BufferedImage imageForRule = LegendIconFeatureRenderer
956                                                  .getInstance().createImageForRule(rule, featureType,                                                  .getInstance().createImageForRule(rule, featureType,
957                                                                  ICON_SIZE);                                                                  new Dimension(iconWidth, iconHeight));
958    
959                                  // LOGGER.debug("Creating a new Legend Image for RUle name =                                  final ImageIcon legendIcon = new ImageIcon(imageForRule);
                                 // "+rule.getName());  
   
                                 ImageIcon legendIcon = new ImageIcon(imageForRule);  
960    
961                                  final JLabel iconLabel = new JLabel(legendIcon);                                  final JLabel iconLabel = new JLabel(legendIcon);
962                                  hbox.setAlignmentX(0f);                                  panel.add(iconLabel, "sgx1");
963                                  hbox.add(iconLabel);                                  // hbox.setAlignmentX(0f);
964                                  hbox.add(Box.createHorizontalStrut(3));                                  // hbox.add(iconLabel);
965                                    // hbox.add(Box.createHorizontalStrut(3));
966    
967                                  Translation labelT = new Translation();                                  final Translation labelT = new Translation();
968                                  labelT.fromOneLine(rule.getDescription().getTitle());                                  labelT.fromOneLine(rule.getDescription().getTitle());
   
969                                  final JLabel classTitleLabel = new JLabel(labelT.toString());                                  final JLabel classTitleLabel = new JLabel(labelT.toString());
                                 hbox.add(classTitleLabel);  
                                 classTitleLabel.setLabelFor(iconLabel);  
   
                                 box.add(hbox);  
970    
971                                    panel.add(classTitleLabel, "sgx2");
972                                    classTitleLabel.setLabelFor(iconLabel);
973                          }                          }
974                  }                  }
975    
976                  return box;                  return panel;
977          }          }
978    
979          /**          /**
980           * Creates a           * Creates a {@link JComponent} that contains a legend for a given
981             * rasterLayer and a given {@link Style}.
982           *           *
983           * @param styledRaster           * @param style
984           * @param iconHeight           *            if <code>null</code>, the default {@link Style} is extracetd
985           * @param iconWidth           *            from the {@link StyledRasterInterface}
          * @return  
986           */           */
987          public static Box createLegendPanel(StyledRasterInterface<?> styledRaster,          public static JPanel createLegendPanel(
988                          int iconWidth, int iconHeight) {                          final StyledRasterInterface<?> styledRaster, Style style,
989                            final int iconWidth, final int iconHeight) {
990    
991                    // If no style is given, we use the default style for this layer
992                    if (style == null)
993                            style = styledRaster.getStyle();
994    
995                  /**                  /**
996                   * Determine whether a Style is responsible for the coloring                   * Determine whether a Style is responsible for the coloring
997                   */                   */
998                  ColorModel colorModel = null;                  ColorModel colorModel = null;
999                  if (!isStyleable(styledRaster)                  if (!isStyleable(styledRaster)
1000                                  || (isStyleable(styledRaster) && styledRaster.getStyle() == null)) {                                  || (isStyleable(styledRaster) && style == null)) {
1001                          colorModel = getColorModel(styledRaster);                          colorModel = getColorModel(styledRaster);
1002                  }                  }
1003    
1004                  RasterLegendData rasterLegendData = styledRaster.getLegendMetaData();                  final RasterLegendData rasterLegendData = styledRaster
1005                  List<Double> legendRasterValues = rasterLegendData.getSortedKeys();                                  .getLegendMetaData();
1006                  Map<Double, GridCoverage2D> sampleRasters = rasterLegendData                  final List<Double> legendRasterValues = rasterLegendData
1007                                    .getSortedKeys();
1008                    final Map<Double, GridCoverage2D> sampleRasters = rasterLegendData
1009                                  .createSampleRasters();                                  .createSampleRasters();
1010    
1011                  Box box = new Box(BoxLayout.Y_AXIS) {                  final JPanel panel = new JPanel(new MigLayout("wrap 2, gapy 0"));
1012    
1013                          /**                  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);  
                                 }  
                         }  
                 };  
   
                 for (Double rValue : legendRasterValues) {  
   
                         /**  
                          *  
                          */  
                         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);  
                                         }  
                                 }  
                         };  
1014    
1015                          final Dimension ICON_SIZE = new Dimension(iconWidth,                          // final Dimension ICON_SIZE = new Dimension(iconWidth,
1016                                          new JLabel().getFontMetrics(new JLabel().getFont())                          // new JLabel().getFontMetrics(new JLabel().getFont())
1017                                                          .getHeight() > 5 ? new JLabel().getFontMetrics(                          // .getHeight() > 5 ? new JLabel().getFontMetrics(
1018                                                          new JLabel().getFont()).getHeight() : iconHeight);                          // new JLabel().getFont()).getHeight() : iconHeight);
1019    
1020                          // ****************************************************************************                          // ****************************************************************************
1021                          // Create the actual icon                          // Create the actual icon
1022                          // ****************************************************************************                          // ****************************************************************************
1023                          BufferedImage buffImage = new BufferedImage(ICON_SIZE.width,                          final BufferedImage buffImage = new BufferedImage(iconWidth,
1024                                          ICON_SIZE.height, BufferedImage.TYPE_INT_ARGB);                                          iconHeight, BufferedImage.TYPE_INT_ARGB);
1025                          Graphics2D graphics = buffImage.createGraphics();  
1026                            final Graphics2D graphics = buffImage.createGraphics();
1027    
1028                          if (colorModel != null) {                          if (colorModel != null) {
1029                                    // The colors come from the ColorModel!
1030    
1031                                  try {                                  try {
1032                                          Object inData = null;                                          Object inData = null;
# Line 1107  public class StyledLayerUtil { Line 1055  public class StyledLayerUtil {
1055                                          final Color color = new Color(colorModel.getRGB(inData));                                          final Color color = new Color(colorModel.getRGB(inData));
1056                                          graphics.setBackground(color);                                          graphics.setBackground(color);
1057                                          graphics.setColor(color);                                          graphics.setColor(color);
1058                                          graphics.fillRect(0, 0, ICON_SIZE.width, ICON_SIZE.height);                                          graphics.fillRect(0, 0, iconWidth, iconHeight);
1059                                  } catch (Exception e) {                                  } catch (final Exception e) {
1060                                          LOGGER.debug("Dann nehmen wir halt den GridCoverageRenderer", e);                                          LOGGER.info(
1061                                                            "Dann nehmen wir halt den GridCoverageRenderer", e);
1062                                          colorModel = null;                                          colorModel = null;
1063                                  }                                  }
1064                          }                          } else {
1065                                    // The colors come from the Style
                         if (colorModel == null) {  
1066    
1067                                  /**                                  /**
1068                                   * The coverage contains only one value of value rValue                                   * The coverage contains only one value of value rValue
1069                                   */                                   */
1070                                  GridCoverage2D sampleCov = sampleRasters.get(rValue);                                  final GridCoverage2D sampleCov = sampleRasters.get(rValue);
1071                                  GridCoverageRenderer renderer;                                  GridCoverageRenderer renderer;
1072                                  try {                                  try {
1073                                          renderer = new GridCoverageRenderer(sampleCov                                          renderer = new GridCoverageRenderer(sampleCov
# Line 1127  public class StyledLayerUtil { Line 1075  public class StyledLayerUtil {
1075                                                          .createEnvelope(sampleCov.getEnvelope()),                                                          .createEnvelope(sampleCov.getEnvelope()),
1076                                                          new Rectangle(iconWidth, iconHeight),                                                          new Rectangle(iconWidth, iconHeight),
1077                                                          (AffineTransform) null);                                                          (AffineTransform) null);
1078                                  } catch (Exception e1) {                                  } catch (final Exception e1) {
1079                                          throw new RuntimeException(                                          throw new RuntimeException(
1080                                                          "Creating the GridCoverageRenderer:", e1);                                                          "Creating a GridCoverageRenderer failed:", e1);
1081                                  }                                  }
1082    
1083                                  /**                                  /**
1084                                   * Iterate over all FeatureTypeStyles.                                   * Iterate over all FeatureTypeStyles.
1085                                   */                                   */
1086                                  // 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  
1087                                                  .getRasterSymbolizers(style);                                                  .getRasterSymbolizers(style);
1088    
1089                                  for (RasterSymbolizer symbolizer : rSymbols) {                                  for (final RasterSymbolizer symbolizer : rSymbols) {
                                         // LOGGER.debug("Creating a new Legend Image for RUle  
                                         // name =  
                                         // "+rule.getName());  
1090                                          try {                                          try {
1091                                                  renderer.paint(graphics, sampleCov, symbolizer);                                                  renderer.paint(graphics, sampleCov, symbolizer);
1092                                          } catch (Exception ee) {                                          } catch (final Exception ee) {
1093                                                  LOGGER.error("Unable to paint " + symbolizer                                                  LOGGER.error("Unable to paint " + symbolizer
1094                                                                  + " into the legend image", ee);                                                                  + " into the legend image", ee);
1095                                          }                                          }
                                         // }  
                                         // }  
1096                                  }                                  }
1097                          }                          }
1098    
1099                          ImageIcon legendIcon = new ImageIcon(buffImage);                          final JLabel iconLabel = new JLabel(new ImageIcon(buffImage));
1100                            panel.add(iconLabel, "sgx1");
1101    
1102                          final JLabel iconLabel = new JLabel(legendIcon);                          final Translation labelT = rasterLegendData.get(rValue);
                         hbox.setAlignmentX(0f);  
                         hbox.add(iconLabel);  
                         hbox.add(Box.createHorizontalStrut(3));  
   
                         Translation labelT = rasterLegendData.get(rValue);  
1103                          final JLabel classTitleLabel = new JLabel(labelT.toString());                          final JLabel classTitleLabel = new JLabel(labelT.toString());
1104                          hbox.add(classTitleLabel);                          panel.add(classTitleLabel, "sgx2"
1105                                            + (rasterLegendData.isPaintGaps() ? ", gapy 0:0:0 5:5:5"
1106                                                            : ""));
1107                          classTitleLabel.setLabelFor(iconLabel);                          classTitleLabel.setLabelFor(iconLabel);
1108    
1109                          box.add(hbox);                          if (rasterLegendData.isPaintGaps()) {
   
                         if (rasterLegendData.getPaintGaps()) {  
1110                                  iconLabel                                  iconLabel
1111                                                  .setBorder(BorderFactory.createLineBorder(Color.black));                                                  .setBorder(BorderFactory.createLineBorder(Color.black));
                                 box.add(Box.createVerticalStrut(3));  
1112                          }                          }
1113    
1114                  }                  }
1115    
1116                  return box;                  return panel;
1117          }          }
1118    
1119          /**          /**
1120           * Extracts the {@link ColorModel} of any {@link StyledRasterInterface}. May           * Extracts the {@link ColorModel} of any {@link StyledRasterInterface}. May
1121           * return <code>null</code> if the geoobject can not be accessed.           * return <code>null</code> if the geoobject can not be accessed.
1122           */           */
1123          public static ColorModel getColorModel(StyledRasterInterface<?> styledGrid) {          @SuppressWarnings("unchecked")
1124            public static ColorModel getColorModel(
1125                            final StyledRasterInterface<?> styledGrid) {
1126                  ColorModel colorModel = null;                  ColorModel colorModel = null;
1127                  try {                  try {
1128                          Object geoObject = styledGrid.getGeoObject();                          final Object geoObject = styledGrid.getGeoObject();
1129                          if (geoObject instanceof GridCoverage2D) {                          if (geoObject instanceof GridCoverage2D) {
1130                                  GridCoverage2D cov = (GridCoverage2D) geoObject;                                  final GridCoverage2D cov = (GridCoverage2D) geoObject;
1131                                  colorModel = cov.getRenderedImage().getColorModel();                                  colorModel = cov.getRenderedImage().getColorModel();
1132                          } else if (geoObject instanceof ImagePyramidReader) {                          } else if (styledGrid instanceof StyledRasterPyramidInterface) {
1133    
1134                                  Parameter readGG = new Parameter(                                  final Parameter readGG = new Parameter(
1135                                                  AbstractGridFormat.READ_GRIDGEOMETRY2D);                                                  AbstractGridFormat.READ_GRIDGEOMETRY2D);
1136    
1137                                  ReferencedEnvelope mapExtend = new org.geotools.geometry.jts.ReferencedEnvelope(                                  final ReferencedEnvelope mapExtend = new org.geotools.geometry.jts.ReferencedEnvelope(
1138                                                  styledGrid.getEnvelope(), styledGrid.getCrs());                                                  styledGrid.getEnvelope(), styledGrid.getCrs());
1139    
1140                                  readGG.setValue(new GridGeometry2D(new GeneralGridEnvelope(                                  readGG.setValue(new GridGeometry2D(new GeneralGridEnvelope(
1141                                                  new Rectangle(0, 0, 10, 10)), mapExtend));                                                  new Rectangle(0, 0, 1, 1)), mapExtend));
1142    
1143                                  final AbstractGridCoverage2DReader aReader = (AbstractGridCoverage2DReader) geoObject;                                  final FeatureCollection<SimpleFeatureType, SimpleFeature> rFc = (FeatureCollection<SimpleFeatureType, SimpleFeature>) geoObject;
1144                                  GridCoverage2D cov = (GridCoverage2D) aReader  
1145                                    final AbstractGridCoverage2DReader aReader = (AbstractGridCoverage2DReader) FeatureUtil
1146                                                    .getWrappedGeoObject(rFc);
1147                                    final GridCoverage2D cov = (GridCoverage2D) aReader
1148                                                  .read(new GeneralParameterValue[] { readGG });                                                  .read(new GeneralParameterValue[] { readGG });
1149                                  colorModel = cov.getRenderedImage().getColorModel();                                  colorModel = cov.getRenderedImage().getColorModel();
1150                          }                          }
1151                  } catch (Exception e) {                  } catch (final Exception e) {
1152                          LOGGER.error("Error reading the colormodel from " + styledGrid);                          LOGGER.error("Error reading the colormodel from " + styledGrid, e);
1153                          return null;                          return null;
1154                  }                  }
1155                  return colorModel;                  return colorModel;
# Line 1224  public class StyledLayerUtil { Line 1161  public class StyledLayerUtil {
1161           *         with their own {@link ColorModel} and will ignore any           *         with their own {@link ColorModel} and will ignore any
1162           *         {@link RasterSymbolizer} = SLD.           *         {@link RasterSymbolizer} = SLD.
1163           */           */
1164          public static boolean isStyleable(StyledRasterInterface<?> styledRaster) {          public static boolean isStyleable(
1165                  ColorModel colorModel = getColorModel(styledRaster);                          final StyledRasterInterface<?> styledRaster) {
1166                    final ColorModel colorModel = getColorModel(styledRaster);
1167                  LOGGER.info("The colormodel of " + styledRaster.getTitle() + " is "  
1168                                  + colorModel.getClass().getSimpleName());                  // LOGGER.info("The colormodel of " + styledRaster.getTitle() + " is "
1169                    // + colorModel != null ? colorModel.getClass().getSimpleName() :
1170                    // "NULL");
1171    
1172                  if (colorModel == null)                  if (colorModel == null)
1173                          return true;                          return true;
# Line 1236  public class StyledLayerUtil { Line 1175  public class StyledLayerUtil {
1175                          return true;                          return true;
1176                  return false;                  return false;
1177          }          }
1178    
1179            /**
1180             * Set the given Style as the Style of the {@link MapLayer}, unless the
1181             * styles are the same (not comparing selection stuff). If the
1182             * {@link MapLayer}s {@link Style} is changed, the selection FTS is kept.<br/>
1183             * Remember {@link MapLayer#setStyle(Style)} triggers an event leading to a
1184             * repaint, so only use it when needed.
1185             *
1186             * @return <code>true</code> if the {@link MapLayer}'s {@link Style} has
1187             *         been changed.
1188             */
1189            public static boolean updateMapLayerStyleIfChangedAndKeepSelection(
1190                            MapLayer mapLayer, Style style2) {
1191    
1192                    Style mapLayerStyleCleaned = StylingUtil
1193                                    .removeSelectionFeatureTypeStyle(mapLayer.getStyle());
1194    
1195                    Style newStyleCleaned = StylingUtil
1196                                    .removeSelectionFeatureTypeStyle(style2);
1197    
1198                    if (StylingUtil.isStyleDifferent(mapLayerStyleCleaned, newStyleCleaned)) {
1199    
1200                            // They are different when compared without SELECTION FTS!
1201    
1202                            // Now let's copy any SELECTION FTS to the now style
1203                            FeatureTypeStyle selectionFeatureTypeStyle = StylingUtil
1204                                            .getSelectionFeatureTypeStyle(mapLayer.getStyle());
1205                            if (selectionFeatureTypeStyle != null) {
1206                                    newStyleCleaned.featureTypeStyles().add(
1207                                                    selectionFeatureTypeStyle);
1208                                    // newStyleCleaned is not so clean anymore... We just alled a
1209                                    // selcetion FTS
1210                            }
1211    
1212                            mapLayer.setStyle(newStyleCleaned);
1213    
1214                            return true;
1215    
1216                    } else {
1217                            return false;
1218                    }
1219            }
1220    
1221            /**
1222             * After loading an atlas, the AttribteMetaData contains whatever is written
1223             * in the XML. But the DBF may have changed! This method checks an
1224             * {@link AttributeMetadataMap} against a schema and also corrects
1225             * upperCase/lowerCase problems. It will also remove any geometry column
1226             * attribute metadata.
1227             */
1228            /**
1229             * After loading an atlas, the AttribteMetaData contains whatever is written
1230             * in the XML. But the DBF may have changed!
1231             */
1232            public static void checkAttribMetaData(AttributeMetadataMap attributeMetaDataMap,
1233                            SimpleFeatureType schema) {
1234    
1235                    ArrayList<Name> willRemove = new ArrayList<Name>();
1236    
1237                    // 1. Check.. all attributes in the atm should be in the schema as well.
1238                    // maybe correct some upperCase/loweCase stuff
1239    
1240                    for (AttributeMetadata atm : attributeMetaDataMap.values()) {
1241    
1242                            AttributeDescriptor foundDescr = schema
1243                                            .getDescriptor(atm.getName());
1244                            if (foundDescr == null) {
1245                                    Name bestMatch = FeatureUtil.findBestMatchingAttribute(schema,
1246                                                    atm.getLocalName());
1247                                    if (bestMatch == null)
1248                                            willRemove.add(atm.getName());
1249                                    else
1250                                            atm.setName(bestMatch);
1251                            } else if (foundDescr instanceof GeometryDescriptor) {
1252                                    // We don't want GeometryColumns in here
1253                                    willRemove.add(atm.getName());
1254                            }
1255                    }
1256    
1257                    // Remove the ones that were not findable in the schema
1258                    for (Name removeName : willRemove) {
1259                            if (attributeMetaDataMap.remove(removeName) == null){
1260                                    LOGGER.warn("removing the AMData didn't work");
1261                            }
1262                    }
1263    
1264                    // 2. check... all attributes from the schema must have an ATM
1265                    for (AttributeDescriptor ad : schema.getAttributeDescriptors()) {
1266                            if (ad instanceof GeometryDescriptor)
1267                                    continue;
1268                            if (!attributeMetaDataMap.containsKey(ad.getName())) {
1269                                    attributeMetaDataMap.put(ad.getName(), new AttributeMetadata(
1270                                                    ad, schema.getAttributeDescriptors().indexOf(ad), attributeMetaDataMap
1271                                                                    .getLanguages()));
1272                            }
1273                    }
1274    
1275            }
1276    
1277  }  }

Legend:
Removed from v.409  
changed lines
  Added in v.658

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26