/[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 420 by alfonx, Thu Oct 1 20:22:48 2009 UTC trunk/src/skrueger/geotools/StyledLayerUtil.java revision 1225 by alfonx, Wed Nov 3 17:05:42 2010 UTC
# Line 25  Line 25 
25   *   *
26   * Contributors:   * Contributors:
27   *     Martin O. J. Schmitz - initial API and implementation   *     Martin O. J. Schmitz - initial API and implementation
28   *     Stefan A. Krüger - additional utility classes   *     Stefan A. Tzeggai - additional utility classes
29   ******************************************************************************/   ******************************************************************************/
30  package skrueger.geotools;  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 39  import java.awt.image.BufferedImage; Line 38  import java.awt.image.BufferedImage;
38  import java.awt.image.ColorModel;  import java.awt.image.ColorModel;
39  import java.awt.image.ComponentColorModel;  import java.awt.image.ComponentColorModel;
40  import java.awt.image.DataBuffer;  import java.awt.image.DataBuffer;
41    import java.awt.image.IndexColorModel;
42  import java.io.File;  import java.io.File;
43  import java.io.FileNotFoundException;  import java.io.FileNotFoundException;
44  import java.io.FileWriter;  import java.io.FileWriter;
45  import java.net.URL;  import java.net.URL;
46  import java.text.DecimalFormat;  import java.text.DecimalFormat;
47    import java.util.ArrayList;
48  import java.util.List;  import java.util.List;
49  import java.util.Map;  import java.util.Map;
50    import java.util.Set;
51    
52  import javax.swing.BorderFactory;  import javax.swing.BorderFactory;
 import javax.swing.Box;  
 import javax.swing.BoxLayout;  
53  import javax.swing.ImageIcon;  import javax.swing.ImageIcon;
54    import javax.swing.JComponent;
55  import javax.swing.JLabel;  import javax.swing.JLabel;
56    
57    import net.miginfocom.swing.MigLayout;
58    
59  import org.apache.log4j.Logger;  import org.apache.log4j.Logger;
60  import org.geotools.coverage.grid.GeneralGridEnvelope;  import org.geotools.coverage.grid.GeneralGridEnvelope;
61  import org.geotools.coverage.grid.GridCoverage2D;  import org.geotools.coverage.grid.GridCoverage2D;
# Line 60  import org.geotools.coverage.grid.GridGe Line 63  import org.geotools.coverage.grid.GridGe
63  import org.geotools.coverage.grid.io.AbstractGridCoverage2DReader;  import org.geotools.coverage.grid.io.AbstractGridCoverage2DReader;
64  import org.geotools.coverage.grid.io.AbstractGridFormat;  import org.geotools.coverage.grid.io.AbstractGridFormat;
65  import org.geotools.feature.FeatureCollection;  import org.geotools.feature.FeatureCollection;
66    import org.geotools.feature.NameImpl;
67  import org.geotools.geometry.jts.ReferencedEnvelope;  import org.geotools.geometry.jts.ReferencedEnvelope;
68  import org.geotools.map.DefaultMapLayer;  import org.geotools.map.DefaultMapLayer;
69  import org.geotools.map.MapLayer;  import org.geotools.map.MapLayer;
# Line 77  import org.jdom.input.SAXBuilder; Line 81  import org.jdom.input.SAXBuilder;
81  import org.jdom.output.XMLOutputter;  import org.jdom.output.XMLOutputter;
82  import org.opengis.feature.simple.SimpleFeature;  import org.opengis.feature.simple.SimpleFeature;
83  import org.opengis.feature.simple.SimpleFeatureType;  import org.opengis.feature.simple.SimpleFeatureType;
84    import org.opengis.feature.type.AttributeDescriptor;
85    import org.opengis.feature.type.GeometryDescriptor;
86    import org.opengis.feature.type.Name;
87  import org.opengis.parameter.GeneralParameterValue;  import org.opengis.parameter.GeneralParameterValue;
88    
89  import schmitzm.geotools.JTSUtil;  import schmitzm.geotools.JTSUtil;
# Line 84  import schmitzm.geotools.feature.Feature Line 91  import schmitzm.geotools.feature.Feature
91  import schmitzm.geotools.styling.StylingUtil;  import schmitzm.geotools.styling.StylingUtil;
92  import schmitzm.io.IOUtil;  import schmitzm.io.IOUtil;
93  import schmitzm.lang.LangUtil;  import schmitzm.lang.LangUtil;
94    import schmitzm.swing.ExceptionDialog;
95    import schmitzm.swing.JPanel;
96  import schmitzm.swing.SwingUtil;  import schmitzm.swing.SwingUtil;
97  import skrueger.AttributeMetaData;  import skrueger.AttributeMetadataImpl;
98    import skrueger.AttributeMetadataInterface;
99  import skrueger.RasterLegendData;  import skrueger.RasterLegendData;
100  import skrueger.i8n.Translation;  import skrueger.i8n.Translation;
101    
# Line 129  public class StyledLayerUtil { Line 139  public class StyledLayerUtil {
139           *                if {@code null} is given as object or an error occurs           *                if {@code null} is given as object or an error occurs
140           *                during layer creation           *                during layer creation
141           */           */
142          public static MapLayer createMapLayer(Object object) throws Exception {          public static MapLayer createMapLayer(final Object object) throws Exception {
143                  return createMapLayer(object, null);                  return createMapLayer(object, null);
144          }          }
145    
# Line 148  public class StyledLayerUtil { Line 158  public class StyledLayerUtil {
158           *                if {@code null} is given as object or an error occurs           *                if {@code null} is given as object or an error occurs
159           *                during layer creation           *                during layer creation
160           */           */
161          public static MapLayer createMapLayer(Object object, Style forcedStyle)          public static MapLayer createMapLayer(Object object, final Style forcedStyle)
162                          throws Exception {                          throws Exception {
163                  MapLayer layer = null;                  MapLayer layer = null;
164                  Style style = null;                  Style style = null;
# Line 189  public class StyledLayerUtil { Line 199  public class StyledLayerUtil {
199           *                if {@code null} is given as object or an error occurs           *                if {@code null} is given as object or an error occurs
200           *                during creation           *                during creation
201           */           */
202          public static StyledLayerInterface<?> createStyledLayer(Object object,          public static StyledLayerInterface<?> createStyledLayer(
203                          String title) {                          final Object object, final String title) {
204                  return createStyledLayer(object, title, null);                  return createStyledLayer(object, title, null);
205          }          }
206    
# Line 209  public class StyledLayerUtil { Line 219  public class StyledLayerUtil {
219           *                if {@code null} is given as object or an error occurs           *                if {@code null} is given as object or an error occurs
220           *                during creation           *                during creation
221           */           */
222          public static StyledLayerInterface<?> createStyledLayer(Object object,          public static StyledLayerInterface<?> createStyledLayer(
223                          String title, StyledLayerStyle style) {                          final Object object, final String title,
224                            final StyledLayerStyle style) {
225                  StyledLayerInterface<?> styledLayer = null;                  StyledLayerInterface<?> styledLayer = null;
226    
227                  String id = (title != null) ? title : "defaultID";                  final String id = (title != null) ? title : "defaultID";
228    
229                  if (object instanceof GridCoverage2D)                  if (object instanceof GridCoverage2D)
230                          styledLayer = new StyledGridCoverage((GridCoverage2D) object, id,                          styledLayer = new StyledGridCoverage((GridCoverage2D) object, id,
# Line 241  public class StyledLayerUtil { Line 252  public class StyledLayerUtil {
252           * @param visible           * @param visible
253           *            indicated whether the visible or invisible entries are           *            indicated whether the visible or invisible entries are
254           *            returned           *            returned
255             *
256             *            TODO replace with
257             *            {@link AttributeMetadataMap#sortedValuesVisibleOnly()}
258           */           */
259          public static AttributeMetadataMap getVisibleAttributeMetaData(          public static AttributeMetadataMap<? extends AttributeMetadataInterface> getVisibleAttributeMetaData(
260                          Map<Integer, AttributeMetaData> amdMap, boolean visible) {                          final AttributeMetadataMap<? extends AttributeMetadataInterface> amdMap,
261                  AttributeMetadataMap filteredMap = new AttributeMetadataMap();                          final boolean visible) {
262                  for (AttributeMetaData amd : amdMap.values())  
263                          if (amd.isVisible())                  final AttributeMetadataMap<AttributeMetadataInterface> filteredMap = (AttributeMetadataMap<AttributeMetadataInterface>) amdMap
264                                  filteredMap.put(amd.getColIdx(), amd);                                  .clone();
265                    if (filteredMap.size() > 0) {
266                            filteredMap.clear(); // Just in case the close copies the contents
267                    }
268    
269                    for (final AttributeMetadataInterface amd : amdMap.values())
270                            if (amd.isVisible() == visible)
271                                    filteredMap.put(amd.getName(), amd);
272    
273                  return filteredMap;                  return filteredMap;
274          }          }
275    
276          /**          /**
277           * Parses a {@link AttributeMetaData} object from an JDOM-{@link Element}.           * Parses a {@link AttributeMetadataImpl} object from an JDOM-
278           * This method works like {@link           * {@link Element}. This method works like {@link
279           * AMLImport#parseDataAttribute(org.w3c.dom.Node}, but for JDOM.           * AMLImport#parseDataAttribute(org.w3c.dom.Node}, but for JDOM.
280           *           *
281             * TODO 20.11.2009, SK: There are some new attribute weight, functiona,
282             * functionX and nodata in AttributeMetaData that should be parsed/exported
283             * too. but this method is only used by ISDSS, which is not supporting that
284             * stuff anyways.
285             *
286           * @param element           * @param element
287           *            {@link Element} to parse           *            {@link Element} to parse
288           */           */
289          public static AttributeMetaData parseAttributeMetaData(final Element element) {          public static AttributeMetadataImpl parseAttributeMetaData(
290                  final Integer col = Integer.valueOf(element.getAttributeValue("col"));                          final Element element) {
291                    final String namespace = element.getAttributeValue("namespace");
292                    final String localname = element.getAttributeValue("localname");
293                    final NameImpl aName = new NameImpl(namespace, localname);
294                  final Boolean visible = Boolean.valueOf(element                  final Boolean visible = Boolean.valueOf(element
295                                  .getAttributeValue("visible"));                                  .getAttributeValue("visible"));
296                  final String unit = element.getAttributeValue("unit");                  final String unit = element.getAttributeValue("unit");
# Line 277  public class StyledLayerUtil { Line 306  public class StyledLayerUtil {
306                          else if (childElement.getName().equals("desc"))                          else if (childElement.getName().equals("desc"))
307                                  desc = parseTranslation(childElement);                                  desc = parseTranslation(childElement);
308                  }                  }
309                  return new AttributeMetaData(col, visible, name, desc, unit);                  return new AttributeMetadataImpl(aName, visible, name, desc, unit);
310          }          }
311    
312          /**          /**
313           * Parses a {@link AttributeMetaData} map from an JDOM-{@link Element} with           * Parses a {@link AttributeMetadataImpl} map from an JDOM-{@link Element}
314           * {@code <attribute>}-childs.           * with {@code <attribute>}-childs.
315           *           *
316           * @param element           * @param element
317           *            {@link Element} to parse           *            {@link Element} to parse
318             *
319             *            TODO Since GP 1.3 the {@link AttributeMetadataImpl} class has
320             *            more attributes which are not used by Xulu/ISDSS. GP
321             *            exports/imports the AMD via AMLExporter and AMLImporter
322             *            classes. (SK, 3.2.2010) *
323           */           */
324          public static AttributeMetadataMap parseAttributeMetaDataMap(          public static AttributeMetadataMap parseAttributeMetaDataMap(
325                          final Element element) {                          final Element element) {
326                  AttributeMetadataMap metaData = new AttributeMetadataMap();                  final AttributeMetadataMap metaData = new AttributeMetadataImplMap();
327                  List<Element> attributesElements = element                  final List<Element> attributesElements = element
328                                  .getChildren(ELEM_NAME_ATTRIBUTE);                                  .getChildren(ELEM_NAME_ATTRIBUTE);
329                  for (Element attibuteElement : attributesElements) {                  for (final Element attibuteElement : attributesElements) {
330                          AttributeMetaData attrMetaData = parseAttributeMetaData(attibuteElement);                          final AttributeMetadataImpl attrMetaData = parseAttributeMetaData(attibuteElement);
331                          metaData.put(attrMetaData.getColIdx(), attrMetaData);                          metaData.put(attrMetaData.getName(), attrMetaData);
332                  }                  }
333                  return metaData;                  return metaData;
334          }          }
335    
336          /**          /**
337           * Loads a {@link AttributeMetaData} object from an URL.           * Loads a {@link AttributeMetadataImpl} object from an URL.
338           *           *
339           * @param documentUrl           * @param documentUrl
340           *            {@link URL} to parse           *            {@link URL} to parse
# Line 308  public class StyledLayerUtil { Line 342  public class StyledLayerUtil {
342           */           */
343          public static AttributeMetadataMap loadAttributeMetaDataMap(          public static AttributeMetadataMap loadAttributeMetaDataMap(
344                          final URL documentUrl) throws Exception {                          final URL documentUrl) throws Exception {
345                  Document document = SAX_BUILDER.build(documentUrl);                  final Document document = SAX_BUILDER.build(documentUrl);
346                  return parseAttributeMetaDataMap(document.getRootElement());                  return parseAttributeMetaDataMap(document.getRootElement());
347          }          }
348    
349          /**          /**
350           * Creates an JDOM {@link Element} for the given {@link AttributeMetaData}           * Creates an JDOM {@link Element} for the given
351           * object.           * {@link AttributeMetadataImpl} object.
352           *           *
353           * @param amd           * @param amd
354           *            meta data for one attribute           *            meta data for one attribute
355             *
356             *            TODO Since GP 1.3 the {@link AttributeMetadataImpl} class has
357             *            more attributes which are not used by Xulu/ISDSS. GP
358             *            exports/imports the AMD via AMLExporter and AMLImporter
359             *            classes. (SK, 3.2.2010)
360           */           */
361          public static Element createAttributeMetaDataElement(          public static Element createAttributeMetaDataElement(
362                          final AttributeMetaData amd) {                          final AttributeMetadataInterface amd) {
363                  final Element element = new Element(ELEM_NAME_ATTRIBUTE, AMLURI);                  final Element element = new Element(ELEM_NAME_ATTRIBUTE, AMLURI);
364                  element.setAttribute("col", String.valueOf(amd.getColIdx()));                  element.setAttribute("namespace",
365                                    String.valueOf(amd.getName().getNamespaceURI()));
366                    element.setAttribute("localname", String.valueOf(amd.getLocalName()));
367                  element.setAttribute("visible", String.valueOf(amd.isVisible()));                  element.setAttribute("visible", String.valueOf(amd.isVisible()));
368                  element.setAttribute("unit", amd.getUnit());                  element.setAttribute("unit", amd.getUnit());
369                  // Creating a aml:name tag...                  // Creating a aml:name tag...
# Line 333  public class StyledLayerUtil { Line 374  public class StyledLayerUtil {
374          }          }
375    
376          /**          /**
377           * Creates an JDOM {@link Element} for the given {@link AttributeMetaData}           * Creates an JDOM {@link Element} for the given
378           * map.           * {@link AttributeMetadataImpl} map.
379           *           *
380           * @param amdMap           * @param amdMap
381           *            map of attribute meta data           *            map of attribute meta data
382           */           */
383          public static Element createAttributeMetaDataMapElement(          public static Element createAttributeMetaDataMapElement(
384                          final AttributeMetadataMap amdMap) {                          final AttributeMetadataMap<? extends AttributeMetadataInterface> amdMap) {
385                  final Element element = new Element(ELEM_NAME_AMD, AMLURI);                  final Element element = new Element(ELEM_NAME_AMD, AMLURI);
386                  for (AttributeMetaData amd : amdMap.values())                  for (final AttributeMetadataInterface amd : amdMap.values())
387                          element.addContent(createAttributeMetaDataElement(amd));                          element.addContent(createAttributeMetaDataElement(amd));
388                  return element;                  return element;
389          }          }
390    
391          /**          /**
392           * Saves a {@link AttributeMetaData AttributeMetaData-Map} to an URL.           * Saves a {@link AttributeMetadataImpl AttributeMetaData-Map} to an URL.
393           *           *
394           * @param amdMap           * @param amdMap
395           *            map of {@link AttributeMetaData}           *            map of {@link AttributeMetadataImpl}
396           * @param documentUrl           * @param documentUrl
397           *            {@link URL} to store the XML           *            {@link URL} to store the XML
398           */           */
# Line 373  public class StyledLayerUtil { Line 414  public class StyledLayerUtil {
414           * @param element           * @param element
415           *            {@link Element} to parse           *            {@link Element} to parse
416           */           */
417          public static RasterLegendData parseRasterLegendData(Element element) {          public static RasterLegendData parseRasterLegendData(final Element element) {
418    
419                  final boolean paintGaps = Boolean.valueOf(element                  final boolean paintGaps = Boolean.valueOf(element
420                                  .getAttributeValue("paintGaps"));                                  .getAttributeValue("paintGaps"));
421    
422                  RasterLegendData rld = new RasterLegendData(paintGaps);                  final RasterLegendData rld = new RasterLegendData(paintGaps);
423    
424                  for (Element childElement : (List<Element>) element.getChildren()) {                  for (final Element childElement : (List<Element>) element.getChildren()) {
425                          final String name = childElement.getName();                          final String name = childElement.getName();
426                          // Cancel if it's an attribute                          // Cancel if it's an attribute
427                          if (childElement.getChildren().size() == 0)                          if (childElement.getChildren().size() == 0)
# Line 400  public class StyledLayerUtil { Line 441  public class StyledLayerUtil {
441                                  // id label element is missing, the translation is searched                                  // id label element is missing, the translation is searched
442                                  // directly                                  // directly
443                                  // as childs of the rasterLegendItem element                                  // as childs of the rasterLegendItem element
444                                  Translation label = parseTranslation(labelElement != null ? labelElement                                  final Translation label = parseTranslation(labelElement != null ? labelElement
445                                                  : childElement);                                                  : childElement);
446                                  rld.put(value, label);                                  rld.put(value, label);
447                          }                          }
# Line 418  public class StyledLayerUtil { Line 459  public class StyledLayerUtil {
459           */           */
460          public static RasterLegendData loadRasterLegendData(final URL documentUrl)          public static RasterLegendData loadRasterLegendData(final URL documentUrl)
461                          throws Exception {                          throws Exception {
462                  Document document = SAX_BUILDER.build(documentUrl);                  final Document document = SAX_BUILDER.build(documentUrl);
463                  return parseRasterLegendData(document.getRootElement());                  return parseRasterLegendData(document.getRootElement());
464          }          }
465    
# Line 433  public class StyledLayerUtil { Line 474  public class StyledLayerUtil {
474                          final RasterLegendData rld) {                          final RasterLegendData rld) {
475                  final Element element = new Element(ELEM_NAME_RLD, AMLURI);                  final Element element = new Element(ELEM_NAME_RLD, AMLURI);
476                  element.setAttribute("paintGaps", rld.isPaintGaps().toString());                  element.setAttribute("paintGaps", rld.isPaintGaps().toString());
477                  for (Double key : rld.getSortedKeys()) {                  for (final Double key : rld.getSortedKeys()) {
478                          Element item = new Element(ELEM_NAME_RASTERLEGEND, AMLURI);                          final Element item = new Element(ELEM_NAME_RASTERLEGEND, AMLURI);
479                          item.setAttribute("value", key.toString());                          item.setAttribute("value", key.toString());
480                          item.addContent(createTranslationElement("label", rld.get(key)));                          item.addContent(createTranslationElement("label", rld.get(key)));
481                          element.addContent(item);                          element.addContent(item);
# Line 454  public class StyledLayerUtil { Line 495  public class StyledLayerUtil {
495           *            rounded to (null means no round; >= 0 means digits after           *            rounded to (null means no round; >= 0 means digits after
496           *            comma; < 0 means digits before comma)           *            comma; < 0 means digits before comma)
497           */           */
498          public static RasterLegendData generateRasterLegendData(ColorMap colorMap,          public static RasterLegendData generateRasterLegendData(
499                          boolean paintGaps, Integer digits) {                          final ColorMap colorMap, final boolean paintGaps,
500                  DecimalFormat decFormat = digits != null ? new DecimalFormat(SwingUtil                          final Integer digits) {
501                                  .getNumberFormatPattern(digits)) : null;                  final DecimalFormat decFormat = digits != null ? new DecimalFormat(
502                  RasterLegendData rld = new RasterLegendData(paintGaps);                                  SwingUtil.getNumberFormatPattern(digits)) : null;
503                  for (ColorMapEntry cme : colorMap.getColorMapEntries()) {                  final RasterLegendData rld = new RasterLegendData(paintGaps);
504                          double value = StylingUtil.getQuantityFromColorMapEntry(cme);                  for (final ColorMapEntry cme : colorMap.getColorMapEntries()) {
505                            final double value = StylingUtil.getQuantityFromColorMapEntry(cme);
506                          String label = cme.getLabel();                          String label = cme.getLabel();
507                          // if no label is set (e.g. quantitative style),                          // if no label is set (e.g. quantitative style),
508                          // use the value as label                          // use the value as label
# Line 486  public class StyledLayerUtil { Line 528  public class StyledLayerUtil {
528           *            rounded to (null means no round; >= 0 means digits after           *            rounded to (null means no round; >= 0 means digits after
529           *            comma; < 0 means digits before comma)           *            comma; < 0 means digits before comma)
530           */           */
531          public static RasterLegendData generateRasterLegendData(Style style,          public static RasterLegendData generateRasterLegendData(final Style style,
532                          boolean paintGaps, Integer digits) {                          final boolean paintGaps, final Integer digits) {
533                  ColorMap colorMap = StylingUtil.getColorMapFromStyle(style);                  final ColorMap colorMap = StylingUtil.getColorMapFromStyle(style);
534                  if (colorMap == null)                  if (colorMap == null)
535                          throw new IllegalArgumentException(                          throw new IllegalArgumentException(
536                                          "Color map can not be determined from style!");                                          "Color map can not be determined from style!");
# Line 521  public class StyledLayerUtil { Line 563  public class StyledLayerUtil {
563           *            {@link Element} to parse           *            {@link Element} to parse
564           */           */
565          public final static Translation parseTranslation(final Element element) {          public final static Translation parseTranslation(final Element element) {
566                  Translation trans = new Translation();                  final Translation trans = new Translation();
567    
568                  if (element == null)                  if (element == null)
569                          return trans;                          return trans;
# Line 563  public class StyledLayerUtil { Line 605  public class StyledLayerUtil {
605           * @param translation           * @param translation
606           *            Translation to store in the Element           *            Translation to store in the Element
607           */           */
608          public final static Element createTranslationElement(String tagname,          public final static Element createTranslationElement(final String tagname,
609                          Translation translation) {                          final Translation translation) {
610                  Element element = new Element(tagname, AMLURI);                  final Element element = new Element(tagname, AMLURI);
611                  if (translation == null)                  if (translation == null)
612                          throw new UnsupportedOperationException(                          throw new UnsupportedOperationException(
613                                          "Translation element can not be created from null!");                                          "Translation element can not be created from null!");
# Line 581  public class StyledLayerUtil { Line 623  public class StyledLayerUtil {
623    
624                  // add a <translation lang="..">..</tranlation> part to the element for                  // add a <translation lang="..">..</tranlation> part to the element for
625                  // all languages                  // all languages
626                  for (String lang : translation.keySet()) {                  for (final String lang : translation.keySet()) {
627                          Element translationElement = new Element(ELEM_NAME_TRANSLATION,                          final Element translationElement = new Element(
628                                          AMLURI);                                          ELEM_NAME_TRANSLATION, AMLURI);
629                          translationElement.setAttribute("lang", lang);                          translationElement.setAttribute("lang", lang);
630                          String translationString = translation.get(lang);                          String translationString = translation.get(lang);
631                          if (translationString == null)                          if (translationString == null)
# Line 603  public class StyledLayerUtil { Line 645  public class StyledLayerUtil {
645           * @param style           * @param style
646           *            a Style           *            a Style
647           */           */
648          public static void setStyledLayerStyle(StyledLayerInterface styledObject,          public static void setStyledLayerStyle(
649                          StyledLayerStyle<?> style) {                          final StyledLayerInterface styledObject,
650                            final StyledLayerStyle<?> style) {
651                  // set SLD style                  // set SLD style
652                  styledObject.setStyle(style.getGeoObjectStyle());                  styledObject.setStyle(style.getGeoObjectStyle());
653                  // set meta data                  // set meta data
654                  if (styledObject instanceof StyledGridCoverageInterface                  if (styledObject instanceof StyledGridCoverageInterface
655                                  && (style.getMetaData() instanceof RasterLegendData || style                                  && (style.getMetaData() instanceof RasterLegendData || style
656                                                  .getMetaData() == null)) {                                                  .getMetaData() == null)) {
657                          RasterLegendData sourceRld = (RasterLegendData) style.getMetaData();                          final RasterLegendData sourceRld = (RasterLegendData) style
658                          RasterLegendData destRld = ((StyledGridCoverageInterface) styledObject)                                          .getMetaData();
659                            final RasterLegendData destRld = ((StyledGridCoverageInterface) styledObject)
660                                          .getLegendMetaData();                                          .getLegendMetaData();
661                          if (destRld != null && sourceRld != null) {                          if (destRld != null && sourceRld != null) {
662                                  destRld.setPaintGaps(sourceRld.isPaintGaps());                                  destRld.setPaintGaps(sourceRld.isPaintGaps());
# Line 623  public class StyledLayerUtil { Line 667  public class StyledLayerUtil {
667                  }                  }
668                  if (styledObject instanceof StyledFeatureCollectionInterface                  if (styledObject instanceof StyledFeatureCollectionInterface
669                                  && (style.getMetaData() instanceof Map || style.getMetaData() == null)) {                                  && (style.getMetaData() instanceof Map || style.getMetaData() == null)) {
670                          AttributeMetadataMap sourceAmd = (AttributeMetadataMap) style                          final AttributeMetadataMap sourceAmd = (AttributeMetadataMap) style
671                                          .getMetaData();                                          .getMetaData();
672                          AttributeMetadataMap destAmd = ((StyledFeatureCollectionInterface) styledObject)                          final AttributeMetadataMap destAmd = ((StyledFeatureCollectionInterface) styledObject)
673                                          .getAttributeMetaDataMap();                                          .getAttributeMetaDataMap();
674                          if (destAmd != null && sourceAmd != null) {                          if (destAmd != null && sourceAmd != null) {
675                                  destAmd.clear();                                  destAmd.clear();
# Line 650  public class StyledLayerUtil { Line 694  public class StyledLayerUtil {
694           * @param styledObject           * @param styledObject
695           *            a styled object           *            a styled object
696           * @return {@code StyledLayerStyle<RasterLegendData>} for           * @return {@code StyledLayerStyle<RasterLegendData>} for
697           *         {@link StyledGridCoverageInterface} or {@code           *         {@link StyledGridCoverageInterface} or
698           *         StyledLayerStyle<Map<Integer,AttributeMetaData>>} for           *         {@code StyledLayerStyle<Map<Integer,AttributeMetaData>>} for
699           *         {@link StyledFeatureCollectionInterface}           *         {@link StyledFeatureCollectionInterface}
700           */           */
701          public static StyledLayerStyle<?> getStyledLayerStyle(          public static StyledLayerStyle<?> getStyledLayerStyle(
702                          StyledLayerInterface styledObject) {                          final StyledLayerInterface styledObject) {
703                  if (styledObject instanceof StyledGridCoverageInterface)                  if (styledObject instanceof StyledGridCoverageInterface)
704                          return getStyledLayerStyle((StyledGridCoverageInterface) styledObject);                          return getStyledLayerStyle((StyledGridCoverageInterface) styledObject);
705                  if (styledObject instanceof StyledFeatureCollectionInterface)                  if (styledObject instanceof StyledFeatureCollectionInterface)
# Line 674  public class StyledLayerUtil { Line 718  public class StyledLayerUtil {
718           *            a styled grid coverage           *            a styled grid coverage
719           */           */
720          public static StyledLayerStyle<RasterLegendData> getStyledLayerStyle(          public static StyledLayerStyle<RasterLegendData> getStyledLayerStyle(
721                          StyledGridCoverageInterface styledGC) {                          final StyledGridCoverageInterface styledGC) {
722                  return new StyledLayerStyle<RasterLegendData>(styledGC.getStyle(),                  return new StyledLayerStyle<RasterLegendData>(styledGC.getStyle(),
723                                  styledGC.getLegendMetaData());                                  styledGC.getLegendMetaData());
724          }          }
# Line 686  public class StyledLayerUtil { Line 730  public class StyledLayerUtil {
730           * @param styledFC           * @param styledFC
731           *            a styled feature collection           *            a styled feature collection
732           */           */
733          public static StyledLayerStyle<Map<Integer, AttributeMetaData>> getStyledLayerStyle(          public static StyledLayerStyle<AttributeMetadataMap> getStyledLayerStyle(
734                          StyledFeatureCollectionInterface styledFC) {                          final StyledFeatureCollectionInterface styledFC) {
735                  return new StyledLayerStyle<Map<Integer, AttributeMetaData>>(styledFC                  return new StyledLayerStyle<AttributeMetadataMap>(styledFC.getStyle(),
736                                  .getStyle(), styledFC.getAttributeMetaDataMap());                                  styledFC.getAttributeMetaDataMap());
737          }          }
738    
739          /**          /**
# Line 706  public class StyledLayerUtil { Line 750  public class StyledLayerUtil {
750           * @return {@code null} in case of any error           * @return {@code null} in case of any error
751           */           */
752          public static StyledLayerStyle<RasterLegendData> loadStyledRasterStyle(          public static StyledLayerStyle<RasterLegendData> loadStyledRasterStyle(
753                          URL geoObjectURL, String sldExt, String rldExt) {                          final URL geoObjectURL, final String sldExt, final String rldExt) {
754                  RasterLegendData metaData = null;                  RasterLegendData metaData = null;
755                  Style sldStyle = null;                  Style sldStyle = null;
756                  try {                  try {
757                          Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(                          final Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(
758                                          geoObjectURL, sldExt));                                          geoObjectURL, sldExt));
759                          // SLD must be present                          // SLD must be present
760                          if (styles == null || styles.length == 0)                          if (styles == null || styles.length == 0)
761                                  return null;                                  return null;
762                          sldStyle = styles[0];                          sldStyle = styles[0];
763                  } catch (Exception err) {                  } catch (final Exception err) {
764                          // SLD must be present                          // SLD must be present
765                          LangUtil.logDebugError(LOGGER, err);                          LangUtil.logDebugError(LOGGER, err);
766                          return null;                          return null;
# Line 725  public class StyledLayerUtil { Line 769  public class StyledLayerUtil {
769                  try {                  try {
770                          metaData = StyledLayerUtil.loadRasterLegendData(IOUtil                          metaData = StyledLayerUtil.loadRasterLegendData(IOUtil
771                                          .changeUrlExt(geoObjectURL, rldExt));                                          .changeUrlExt(geoObjectURL, rldExt));
772                  } catch (FileNotFoundException err) {                  } catch (final FileNotFoundException err) {
773                          // ignore missing raster legend data                          // ignore missing raster legend data
774                  } catch (Exception err) {                  } catch (final Exception err) {
775                          // any other error during legend data creation leads to error                          // any other error during legend data creation leads to error
776                          LangUtil.logDebugError(LOGGER, err);                          LangUtil.logDebugError(LOGGER, err);
777                          return null;                          return null;
# Line 750  public class StyledLayerUtil { Line 794  public class StyledLayerUtil {
794           * @return {@code null} in case of any error           * @return {@code null} in case of any error
795           */           */
796          public static StyledLayerStyle<RasterLegendData> loadStyledRasterStyle(          public static StyledLayerStyle<RasterLegendData> loadStyledRasterStyle(
797                          URL geoObjectURL) {                          final URL geoObjectURL) {
798                  return loadStyledRasterStyle(geoObjectURL, "sld", "rld");                  return loadStyledRasterStyle(geoObjectURL, "sld", "rld");
799          }          }
800    
801          /**          /**
802           * Loads a {@linkplain Style SLD-Style} and a {@linkplain AttributeMetaData           * Loads a {@linkplain Style SLD-Style} and a
803           * AttributeMetaData-Map} for a given geo-object (feature) source. The SLD           * {@linkplain AttributeMetadataImpl AttributeMetaData-Map} for a given
804           * file must be present. A missing attribute meta-data file is tolerated.           * geo-object (feature) source. The SLD file must be present. A missing
805             * attribute meta-data file is tolerated.
806           *           *
807           * @param geoObjectURL           * @param geoObjectURL
808           *            URL of the (already read) feature object           *            URL of the (already read) feature object
# Line 767  public class StyledLayerUtil { Line 812  public class StyledLayerUtil {
812           *            file extention for the raster legend-data file           *            file extention for the raster legend-data file
813           * @return {@code null} in case of any error           * @return {@code null} in case of any error
814           */           */
815          public static StyledLayerStyle<Map<Integer, AttributeMetaData>> loadStyledFeatureStyle(          public static StyledLayerStyle<AttributeMetadataMap> loadStyledFeatureStyle(
816                          URL geoObjectURL, String sldExt, String rldExt) {                          final URL geoObjectURL, final String sldExt, final String rldExt) {
817                  Map<Integer, AttributeMetaData> metaData = null;                  AttributeMetadataMap metaData = null;
818                  Style sldStyle = null;                  Style sldStyle = null;
819                  try {                  try {
820                          Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(                          final Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(
821                                          geoObjectURL, sldExt));                                          geoObjectURL, sldExt));
822                          // SLD must be present                          // SLD must be present
823                          if (styles == null || styles.length == 0)                          if (styles == null || styles.length == 0)
824                                  return null;                                  return null;
825                          sldStyle = styles[0];                          sldStyle = styles[0];
826                  } catch (Exception err) {                  } catch (final Exception err) {
827                          // SLD must be present                          // SLD must be present
828                          LangUtil.logDebugError(LOGGER, err);                          LangUtil.logDebugError(LOGGER, err);
829                          return null;                          return null;
# Line 787  public class StyledLayerUtil { Line 832  public class StyledLayerUtil {
832                  try {                  try {
833                          metaData = StyledLayerUtil.loadAttributeMetaDataMap(IOUtil                          metaData = StyledLayerUtil.loadAttributeMetaDataMap(IOUtil
834                                          .changeUrlExt(geoObjectURL, rldExt));                                          .changeUrlExt(geoObjectURL, rldExt));
835                  } catch (FileNotFoundException err) {                  } catch (final FileNotFoundException err) {
836                          // ignore missing attribute meta data                          // ignore missing attribute meta data
837                  } catch (Exception err) {                  } catch (final Exception err) {
838                          // any other error during meta data creation leads to error                          // any other error during meta data creation leads to error
839                          LangUtil.logDebugError(LOGGER, err);                          LangUtil.logDebugError(LOGGER, err);
840                          return null;                          return null;
841                  }                  }
842    
843                  return new StyledLayerStyle<Map<Integer, AttributeMetaData>>(sldStyle,                  return new StyledLayerStyle<AttributeMetadataMap>(sldStyle, metaData);
                                 metaData);  
844          }          }
845    
846          /**          /**
847           * Loads a {@linkplain Style SLD-Style} from a {@code .sld} file and           * Loads a {@linkplain Style SLD-Style} from a {@code .sld} file and
848           * {@linkplain AttributeMetaData AttributeMetaData-Map} from a {@code .amd}           * {@linkplain AttributeMetadataImpl AttributeMetaData-Map} from a
849           * file for a given geo-object (feature) source. The SLD file must be           * {@code .amd} file for a given geo-object (feature) source. The SLD file
850           * present. A missing attribute meta-data file is tolerated.           * must be present. A missing attribute meta-data file is tolerated.
851           *           *
852           * @param geoObjectURL           * @param geoObjectURL
853           *            URL of the (already read) feature object           *            URL of the (already read) feature object
# Line 813  public class StyledLayerUtil { Line 857  public class StyledLayerUtil {
857           *            file extention for the raster legend-data file           *            file extention for the raster legend-data file
858           * @return {@code null} in case of any error           * @return {@code null} in case of any error
859           */           */
860          public static StyledLayerStyle<Map<Integer, AttributeMetaData>> loadStyledFeatureStyle(          public static StyledLayerStyle<AttributeMetadataMap> loadStyledFeatureStyle(
861                          URL geoObjectURL) {                          final URL geoObjectURL) {
862                  return loadStyledFeatureStyle(geoObjectURL, "sld", "amd");                  return loadStyledFeatureStyle(geoObjectURL, "sld", "amd");
863          }          }
864    
# Line 831  public class StyledLayerUtil { Line 875  public class StyledLayerUtil {
875           * @param mdExt           * @param mdExt
876           *            file extention for the meta-data file           *            file extention for the meta-data file
877           */           */
878          public static <T> void saveStyledLayerStyle(StyledLayerStyle<T> style,          public static <T> void saveStyledLayerStyle(
879                          URL geoObjectURL, String sldExt, String mdExt) throws Exception {                          final StyledLayerStyle<T> style, final URL geoObjectURL,
880                            final String sldExt, final String mdExt) throws Exception {
881                  // Store the SLD                  // Store the SLD
882                  Style sldStyle = style.getGeoObjectStyle();                  final Style sldStyle = style.getGeoObjectStyle();
883                  if (sldStyle != null) {                  if (sldStyle != null) {
884                          StylingUtil.saveStyleToSLD(sldStyle, IOUtil.changeFileExt(new File(                          StylingUtil.saveStyleToSld(sldStyle, IOUtil.changeFileExt(new File(
885                                          geoObjectURL.toURI()), sldExt));                                          geoObjectURL.toURI()), sldExt));
886                  }                  }
887    
888                  // Store the meta data                  // Store the meta data
889                  T metaData = style.getMetaData();                  final T metaData = style.getMetaData();
890                  if (metaData != null) {                  if (metaData != null) {
891                          if (metaData instanceof RasterLegendData) {                          if (metaData instanceof RasterLegendData) {
892                                  saveRasterLegendData((RasterLegendData) metaData, IOUtil                                  saveRasterLegendData((RasterLegendData) metaData,
893                                                  .changeUrlExt(geoObjectURL, mdExt));                                                  IOUtil.changeUrlExt(geoObjectURL, mdExt));
894                                  // } else if ( metaData instanceof                                  // } else if ( metaData instanceof
895                                  // Map<Integer,AttributeMetaData> ) { // LEIDER NICHT                                  // Map<Integer,AttributeMetaData> ) { // LEIDER NICHT
896                                  // KOMPILIERBAR!!                                  // KOMPILIERBAR!!
897                          } else if (metaData instanceof Map) {                          } else if (metaData instanceof Map) {
898                                  saveAttributeMetaDataMap(                                  saveAttributeMetaDataMap((AttributeMetadataMap) metaData,
899                                                  (AttributeMetadataMap) metaData, IOUtil                                                  IOUtil.changeUrlExt(geoObjectURL, mdExt));
                                                                 .changeUrlExt(geoObjectURL, mdExt));  
900                          } else                          } else
901                                  throw new UnsupportedOperationException(                                  throw new UnsupportedOperationException(
902                                                  "Export for meta data not yet supported: "                                                  "Export for meta data not yet supported: "
# Line 862  public class StyledLayerUtil { Line 906  public class StyledLayerUtil {
906    
907          /**          /**
908           * 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
909           * meta data ({@link RasterLegendData} or {@link AttributeMetaData}) to a           * meta data ({@link RasterLegendData} or {@link AttributeMetadataImpl}) to
910           * {@code .rld} or {@code .amd} file. for a given geo-object source.           * a {@code .rld} or {@code .amd} file. for a given geo-object source.
911           *           *
912           * @param style           * @param style
913           *            style to save           *            style to save
914           * @param geoObjectURL           * @param geoObjectURL
915           *            URL of the (already read) raster object           *            URL of the (already read) raster object
916           */           */
917          public static void saveStyledLayerStyle(StyledLayerStyle<?> style,          public static void saveStyledLayerStyle(final StyledLayerStyle<?> style,
918                          URL geoObjectURL) throws Exception {                          final URL geoObjectURL) throws Exception {
919                  if (style.getMetaData() instanceof RasterLegendData)                  if (style.getMetaData() instanceof RasterLegendData)
920                          saveStyledLayerStyle(style, geoObjectURL, "sld", "rld");                          saveStyledLayerStyle(style, geoObjectURL, "sld", "rld");
921                  else                  else
# Line 879  public class StyledLayerUtil { Line 923  public class StyledLayerUtil {
923          }          }
924    
925          /**          /**
926           * Creates a {@link Box} that shows a legend for a list of           * *If appended to the name of a rule, this rule shall not be shown in the
927             * legend
928             */
929            public final static String HIDE_IN_LAYER_LEGEND_HINT = "HIDE_IN_LEGEND";
930    
931            /**
932             * Creates a {@link JPanel} that shows a legend for a list of
933           * {@link FeatureTypeStyle}s and a targeted featureType           * {@link FeatureTypeStyle}s and a targeted featureType
934           *           *
935             * @param style
936             *            The Style to presented in this legend
937           * @param featureType           * @param featureType
938           *            If this a legend for Point, Polygon or Line?           *            If this a legend for Point, Polygon or Line?
          * @param list  
          *            The Styles to presented in this legend  
939           *           *
940           * @author <a href="mailto:[email protected]">Stefan Alfons           * @author <a href="mailto:[email protected]">Stefan Alfons Tzeggai</a>
          *         Kr&uuml;ger</a>  
941           */           */
942          public static Box createLegendPanel(List<FeatureTypeStyle> list,          public static JPanel createLegendSwingPanel(Style style,
943                          SimpleFeatureType featureType, int iconWidth, int iconHeight) {                          final SimpleFeatureType featureType, final int iconWidth,
944                            final int iconHeight) {
945    
946                  Box box = new Box(BoxLayout.Y_AXIS) {                  if (featureType == null) {
947                            ExceptionDialog.show(new IllegalStateException(
948                          /**                                          "featureType is null!"));
949                           * Nuetzlich wenn die Componente gedruckt (z.B. wenn ein Screenshot                          return new JPanel();
950                           * gemacht wird) wird. Dann werden wird der Hintergrund auf WEISS                  }
951                           * gesetzt.  
952                           *                  final List<FeatureTypeStyle> list = style.featureTypeStyles();
                          * @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);  
                                 }  
                         }  
                 };  
953    
954                  for (FeatureTypeStyle ftStyle : list) {                  final JPanel panel = new JPanel(new MigLayout("wrap 2", "[]:3:[]"));
955    
956                    if (style == null) {
957                            // No Style => no legend
958                            return panel;
959                    }
960    
961                    for (final FeatureTypeStyle ftStyle : list) {
962    
963                          // One child-node for every rule                          // One child-node for every rule
964                          List<Rule> rules = ftStyle.rules();                          final List<Rule> rules = ftStyle.rules();
965                          for (Rule rule : rules) {                          for (final Rule rule : rules) {
966    
967                                    // Check if this RULE shall actually appear in the legend
968                                    if (rule.getName() != null
969                                                    && rule.getName().endsWith(HIDE_IN_LAYER_LEGEND_HINT))
970                                            continue;
971    
972                                  /**                                  /**
973                                   * Let's not create a hbox for Rules that only contain                                   * Let's not create a hbox for Rules that only contain
# Line 930  public class StyledLayerUtil { Line 977  public class StyledLayerUtil {
977                                                  .size() == rule.getSymbolizers().length)                                                  .size() == rule.getSymbolizers().length)
978                                          continue;                                          continue;
979    
                                 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  
                                 // ****************************************************************************  
980                                  final BufferedImage imageForRule = LegendIconFeatureRenderer                                  final BufferedImage imageForRule = LegendIconFeatureRenderer
981                                                  .getInstance().createImageForRule(rule, featureType,                                                  .getInstance().createImageForRule(rule, featureType,
982                                                                  ICON_SIZE);                                                                  new Dimension(iconWidth, iconHeight));
   
                                 // LOGGER.debug("Creating a new Legend Image for RUle name =  
                                 // "+rule.getName());  
983    
984                                  ImageIcon legendIcon = new ImageIcon(imageForRule);                                  final ImageIcon legendIcon = new ImageIcon(imageForRule);
985    
986                                  final JLabel iconLabel = new JLabel(legendIcon);                                  final JLabel iconLabel = new JLabel(legendIcon);
987                                  hbox.setAlignmentX(0f);                                  panel.add(iconLabel, "sgx1");
988                                  hbox.add(iconLabel);                                  // hbox.setAlignmentX(0f);
989                                  hbox.add(Box.createHorizontalStrut(3));                                  // hbox.add(iconLabel);
990                                    // hbox.add(Box.createHorizontalStrut(3));
991    
992                                  Translation labelT = new Translation();                                  final Translation labelT = new Translation();
993                                  labelT.fromOneLine(rule.getDescription().getTitle());                                  labelT.fromOneLine(rule.getDescription().getTitle());
   
994                                  final JLabel classTitleLabel = new JLabel(labelT.toString());                                  final JLabel classTitleLabel = new JLabel(labelT.toString());
                                 hbox.add(classTitleLabel);  
                                 classTitleLabel.setLabelFor(iconLabel);  
   
                                 box.add(hbox);  
995    
996                                    panel.add(classTitleLabel, "sgx2");
997                                    classTitleLabel.setLabelFor(iconLabel);
998                          }                          }
999                  }                  }
1000    
1001                  return box;                  return panel;
1002          }          }
1003    
1004          /**          /**
1005           * Creates a           * Creates a {@link JComponent} that contains a legend for a given
1006             * {@link StyledRasterInterface} and a given {@link Style}.
1007           *           *
1008           * @param styledRaster           * @param style
1009           * @param iconHeight           *            if <code>null</code>, the default {@link Style} is extracetd
1010           * @param iconWidth           *            from the {@link StyledRasterInterface}
          * @return  
1011           */           */
1012          public static Box createLegendPanel(StyledRasterInterface<?> styledRaster,          public static JPanel createLegendSwingPanel(
1013                          int iconWidth, int iconHeight) {                          final StyledRasterInterface<?> styledRaster, Style style,
1014                            final int iconWidth, final int iconHeight) {
1015    
1016                    // If no style is given, we use the default style for this layer
1017                    if (style == null)
1018                            style = styledRaster.getStyle();
1019    
1020                  /**                  /**
1021                   * Determine whether a Style is responsible for the coloring                   * Determine whether a Style is responsible for the coloring
1022                   */                   */
1023                  ColorModel colorModel = null;                  ColorModel colorModel = null;
1024                  if (!isStyleable(styledRaster)                  if (!isStyleable(styledRaster)
1025                                  || (isStyleable(styledRaster) && styledRaster.getStyle() == null)) {                                  || (isStyleable(styledRaster) && style == null)) {
1026                          colorModel = getColorModel(styledRaster);                          colorModel = getColorModel(styledRaster);
1027                  }                  }
1028    
1029                  RasterLegendData rasterLegendData = styledRaster.getLegendMetaData();                  final RasterLegendData rasterLegendData = styledRaster
1030                  List<Double> legendRasterValues = rasterLegendData.getSortedKeys();                                  .getLegendMetaData();
1031                  Map<Double, GridCoverage2D> sampleRasters = rasterLegendData                  final List<Double> legendRasterValues = rasterLegendData
1032                                    .getSortedKeys();
1033                    final Map<Double, GridCoverage2D> sampleRasters = rasterLegendData
1034                                  .createSampleRasters();                                  .createSampleRasters();
1035    
1036                  Box box = new Box(BoxLayout.Y_AXIS) {                  final JPanel panel = new JPanel(new MigLayout("wrap 2, gapy 0"));
1037    
1038                          /**                  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) {  
1039    
1040                          /**                          // final Dimension ICON_SIZE = new Dimension(iconWidth,
1041                           *                          // new JLabel().getFontMetrics(new JLabel().getFont())
1042                           */                          // .getHeight() > 5 ? new JLabel().getFontMetrics(
1043                          Box hbox = new Box(BoxLayout.X_AXIS) {                          // new JLabel().getFont()).getHeight() : iconHeight);
   
                                 /**  
                                  * 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);  
1044    
1045                          // ****************************************************************************                          // ****************************************************************************
1046                          // Create the actual icon                          // Create the actual icon
1047                          // ****************************************************************************                          // ****************************************************************************
1048                          BufferedImage buffImage = new BufferedImage(ICON_SIZE.width,                          final BufferedImage buffImage = new BufferedImage(iconWidth,
1049                                          ICON_SIZE.height, BufferedImage.TYPE_INT_ARGB);                                          iconHeight, BufferedImage.TYPE_INT_ARGB);
1050                          Graphics2D graphics = buffImage.createGraphics();  
1051                            final Graphics2D graphics = buffImage.createGraphics();
1052    
1053                          if (colorModel != null) {                          if (colorModel != null) {
1054                                    // The colors come from the ColorModel!
1055    
1056                                  try {                                  try {
1057                                          Object inData = null;                                          Object inData = null;
# Line 1105  public class StyledLayerUtil { Line 1080  public class StyledLayerUtil {
1080                                          final Color color = new Color(colorModel.getRGB(inData));                                          final Color color = new Color(colorModel.getRGB(inData));
1081                                          graphics.setBackground(color);                                          graphics.setBackground(color);
1082                                          graphics.setColor(color);                                          graphics.setColor(color);
1083                                          graphics.fillRect(0, 0, ICON_SIZE.width, ICON_SIZE.height);                                          graphics.fillRect(0, 0, iconWidth, iconHeight);
1084                                  } catch (Exception e) {                                  } catch (final Exception e) {
1085                                          LOGGER.debug(                                          LOGGER.info(
1086                                                          "Dann nehmen wir halt den GridCoverageRenderer", e);                                                          "Dann nehmen wir halt den GridCoverageRenderer", e);
1087                                          colorModel = null;                                          colorModel = null;
1088                                  }                                  }
1089                          }                          } else {
1090                                    // The colors come from the Style
                         if (colorModel == null) {  
1091    
1092                                  /**                                  /**
1093                                   * The coverage contains only one value of value rValue                                   * The coverage contains only one value of value rValue
1094                                   */                                   */
1095                                  GridCoverage2D sampleCov = sampleRasters.get(rValue);                                  final GridCoverage2D sampleCov = sampleRasters.get(rValue);
1096                                  GridCoverageRenderer renderer;                                  GridCoverageRenderer renderer;
1097                                  try {                                  try {
1098                                          renderer = new GridCoverageRenderer(sampleCov                                          renderer = new GridCoverageRenderer(
1099                                                          .getCoordinateReferenceSystem(), JTSUtil                                                          sampleCov.getCoordinateReferenceSystem(),
1100                                                          .createEnvelope(sampleCov.getEnvelope()),                                                          JTSUtil.createEnvelope(sampleCov.getEnvelope()),
1101                                                          new Rectangle(iconWidth, iconHeight),                                                          new Rectangle(iconWidth, iconHeight),
1102                                                          (AffineTransform) null);                                                          (AffineTransform) null);
1103                                  } catch (Exception e1) {                                  } catch (final Exception e1) {
1104                                          throw new RuntimeException(                                          throw new RuntimeException(
1105                                                          "Creating the GridCoverageRenderer:", e1);                                                          "Creating a GridCoverageRenderer failed:", e1);
1106                                  }                                  }
1107    
1108                                  /**                                  /**
1109                                   * Iterate over all FeatureTypeStyles.                                   * Iterate over all FeatureTypeStyles.
1110                                   */                                   */
1111                                  // 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  
1112                                                  .getRasterSymbolizers(style);                                                  .getRasterSymbolizers(style);
1113    
1114                                  for (RasterSymbolizer symbolizer : rSymbols) {                                  for (final RasterSymbolizer symbolizer : rSymbols) {
                                         // LOGGER.debug("Creating a new Legend Image for RUle  
                                         // name =  
                                         // "+rule.getName());  
1115                                          try {                                          try {
1116                                                  renderer.paint(graphics, sampleCov, symbolizer);                                                  renderer.paint(graphics, sampleCov, symbolizer);
1117                                          } catch (Exception ee) {                                          } catch (final Exception ee) {
1118                                                  LOGGER.error("Unable to paint " + symbolizer                                                  LOGGER.error("Unable to paint " + symbolizer
1119                                                                  + " into the legend image", ee);                                                                  + " into the legend image", ee);
1120                                          }                                          }
                                         // }  
                                         // }  
1121                                  }                                  }
1122                          }                          }
1123    
1124                          ImageIcon legendIcon = new ImageIcon(buffImage);                          final JLabel iconLabel = new JLabel(new ImageIcon(buffImage));
1125                            panel.add(iconLabel, "sgx1");
                         final JLabel iconLabel = new JLabel(legendIcon);  
                         hbox.setAlignmentX(0f);  
                         hbox.add(iconLabel);  
                         hbox.add(Box.createHorizontalStrut(3));  
1126    
1127                          Translation labelT = rasterLegendData.get(rValue);                          final Translation labelT = rasterLegendData.get(rValue);
1128                          final JLabel classTitleLabel = new JLabel(labelT.toString());                          final JLabel classTitleLabel = new JLabel(labelT.toString());
1129                          hbox.add(classTitleLabel);                          panel.add(classTitleLabel, "sgx2"
1130                                            + (rasterLegendData.isPaintGaps() ? ", gapy 0:0:0 5:5:5"
1131                                                            : ""));
1132                          classTitleLabel.setLabelFor(iconLabel);                          classTitleLabel.setLabelFor(iconLabel);
1133    
1134                          box.add(hbox);                          if (rasterLegendData.isPaintGaps()) {
   
                         if (rasterLegendData.getPaintGaps()) {  
1135                                  iconLabel                                  iconLabel
1136                                                  .setBorder(BorderFactory.createLineBorder(Color.black));                                                  .setBorder(BorderFactory.createLineBorder(Color.black));
                                 box.add(Box.createVerticalStrut(3));  
1137                          }                          }
1138    
1139                  }                  }
1140    
1141                  return box;                  return panel;
1142          }          }
1143    
1144          /**          /**
# Line 1188  public class StyledLayerUtil { Line 1146  public class StyledLayerUtil {
1146           * return <code>null</code> if the geoobject can not be accessed.           * return <code>null</code> if the geoobject can not be accessed.
1147           */           */
1148          @SuppressWarnings("unchecked")          @SuppressWarnings("unchecked")
1149          public static ColorModel getColorModel(StyledRasterInterface<?> styledGrid) {          public static ColorModel getColorModel(
1150                            final StyledRasterInterface<?> styledGrid) {
1151                  ColorModel colorModel = null;                  ColorModel colorModel = null;
1152                  try {                  try {
1153                          Object geoObject = styledGrid.getGeoObject();                          final Object geoObject = styledGrid.getGeoObject();
1154                          if (geoObject instanceof GridCoverage2D) {                          if (geoObject instanceof GridCoverage2D) {
1155                                  GridCoverage2D cov = (GridCoverage2D) geoObject;                                  final GridCoverage2D cov = (GridCoverage2D) geoObject;
1156                                  colorModel = cov.getRenderedImage().getColorModel();                                  colorModel = cov.getRenderedImage().getColorModel();
1157                          } else if (styledGrid instanceof StyledRasterPyramidInterface) {                          } else if (styledGrid instanceof StyledGridCoverageReaderInterface) {
1158    
1159                                  Parameter readGG = new Parameter(                                  final Parameter readGG = new Parameter(
1160                                                  AbstractGridFormat.READ_GRIDGEOMETRY2D);                                                  AbstractGridFormat.READ_GRIDGEOMETRY2D);
1161    
1162                                  ReferencedEnvelope mapExtend = new org.geotools.geometry.jts.ReferencedEnvelope(                                  final ReferencedEnvelope mapExtend = new ReferencedEnvelope(
1163                                                  styledGrid.getEnvelope(), styledGrid.getCrs());                                                  styledGrid.getEnvelope(), styledGrid.getCrs());
1164    
1165                                  readGG.setValue(new GridGeometry2D(new GeneralGridEnvelope(                                  readGG.setValue(new GridGeometry2D(new GeneralGridEnvelope(
1166                                                  new Rectangle(0, 0, 1, 1)), mapExtend));                                                  new Rectangle(0, 0, 1, 1)), mapExtend));
1167    
1168                                  FeatureCollection<SimpleFeatureType, SimpleFeature> rFc = (FeatureCollection<SimpleFeatureType, SimpleFeature>) geoObject;                                  AbstractGridCoverage2DReader aReader;
1169                                    if (geoObject instanceof FeatureCollection) {
1170                                            final FeatureCollection<SimpleFeatureType, SimpleFeature> rFc = (FeatureCollection<SimpleFeatureType, SimpleFeature>) geoObject;
1171    
1172                                            aReader = (AbstractGridCoverage2DReader) FeatureUtil
1173                                                            .getWrappedGeoObject(rFc);
1174    
1175                                  final AbstractGridCoverage2DReader aReader = (AbstractGridCoverage2DReader) FeatureUtil                                  } else if (geoObject instanceof AbstractGridCoverage2DReader) {
1176                                                  .getWrappedGeoObject(rFc);                                          aReader = (AbstractGridCoverage2DReader) geoObject;
1177                                  GridCoverage2D cov = (GridCoverage2D) aReader  
1178                                    } else
1179                                            throw new RuntimeException("need a reader...");
1180                                    //
1181    
1182                                    final GridCoverage2D cov = (GridCoverage2D) aReader
1183                                                  .read(new GeneralParameterValue[] { readGG });                                                  .read(new GeneralParameterValue[] { readGG });
1184                                  colorModel = cov.getRenderedImage().getColorModel();                                  colorModel = cov.getRenderedImage().getColorModel();
1185                          }                          }
1186                  } catch (Exception e) {                  } catch (final Exception e) {
1187                          LOGGER.error("Error reading the colormodel from " + styledGrid, e);                          LOGGER.error("Error reading the colormodel from " + styledGrid, e);
1188                          return null;                          return null;
1189                  }                  }
# Line 1227  public class StyledLayerUtil { Line 1196  public class StyledLayerUtil {
1196           *         with their own {@link ColorModel} and will ignore any           *         with their own {@link ColorModel} and will ignore any
1197           *         {@link RasterSymbolizer} = SLD.           *         {@link RasterSymbolizer} = SLD.
1198           */           */
1199          public static boolean isStyleable(StyledRasterInterface<?> styledRaster) {          public static boolean isStyleable(
1200                  ColorModel colorModel = getColorModel(styledRaster);                          final StyledRasterInterface<?> styledRaster) {
1201                    final ColorModel colorModel = getColorModel(styledRaster);
1202                  LOGGER.info("The colormodel of " + styledRaster.getTitle() + " is "  
1203                                  + colorModel.getClass().getSimpleName());                  // LOGGER.info("The colormodel of " + styledRaster.getTitle() + " is "
1204                    // + colorModel != null ? colorModel.getClass().getSimpleName() :
1205                    // "NULL");
1206    
1207                  if (colorModel == null)                  if (colorModel == null)
1208                          return true;                          return true;
1209                  if (colorModel instanceof ComponentColorModel)                  if (colorModel instanceof ComponentColorModel)
1210                          return true;                          return true;
1211                    if (colorModel instanceof IndexColorModel)
1212                            return true;
1213    
1214                  return false;                  return false;
1215          }          }
1216    
1217            /**
1218             * Set the given Style as the Style of the {@link MapLayer}, unless the
1219             * styles are the same (not comparing selection stuff). If the
1220             * {@link MapLayer}s {@link Style} is changed, the selection FTS is kept.<br/>
1221             * Remember {@link MapLayer#setStyle(Style)} triggers an event leading to a
1222             * repaint, so only use it when needed.
1223             *
1224             * @return <code>true</code> if the {@link MapLayer}'s {@link Style} has
1225             *         been changed.
1226             */
1227            public static boolean updateMapLayerStyleIfChangedAndKeepSelection(
1228                            MapLayer mapLayer, Style style2) {
1229    
1230                    Style mapLayerStyleCleaned = StylingUtil
1231                                    .removeSelectionFeatureTypeStyle(mapLayer.getStyle());
1232    
1233                    Style newStyleCleaned = StylingUtil
1234                                    .removeSelectionFeatureTypeStyle(style2);
1235    
1236                    if (StylingUtil.isStyleDifferent(mapLayerStyleCleaned, newStyleCleaned)) {
1237    
1238                            // They are different when compared without SELECTION FTS!
1239    
1240                            // Now let's copy any SELECTION FTS to the now style
1241                            FeatureTypeStyle selectionFeatureTypeStyle = StylingUtil
1242                                            .getSelectionFeatureTypeStyle(mapLayer.getStyle());
1243                            if (selectionFeatureTypeStyle != null) {
1244                                    newStyleCleaned.featureTypeStyles().add(
1245                                                    selectionFeatureTypeStyle);
1246                                    // newStyleCleaned is not so clean anymore... We just alled a
1247                                    // selcetion FTS
1248                            }
1249    
1250                            mapLayer.setStyle(newStyleCleaned);
1251    
1252                            return true;
1253    
1254                    } else {
1255                            return false;
1256                    }
1257            }
1258    
1259            /**
1260             * After loading an atlas, the AttribteMetaData contains whatever is written
1261             * in the XML. But the DBF may have changed! This method checks an
1262             * {@link AttributeMetadataMap} against a schema and also corrects
1263             * upperCase/lowerCase problems. It will also remove any geometry column
1264             * attribute metadata.
1265             */
1266            /**
1267             * After loading an atlas, the AttribteMetaData contains whatever is written
1268             * in the XML. But the DBF may have changed!
1269             */
1270            public static void checkAttribMetaData(
1271                            AttributeMetadataMap<AttributeMetadataImpl> attributeMetaDataMap,
1272                            SimpleFeatureType schema) {
1273    
1274                    if (schema == null)
1275                            throw new IllegalArgumentException("schmema may not be null!");
1276    
1277                    ArrayList<Name> willRemove = new ArrayList<Name>();
1278    
1279                    // 1. Check.. all attributes in the atm should be in the schema as well.
1280                    // maybe correct some upperCase/loweCase stuff
1281    
1282                    for (AttributeMetadataInterface atm : attributeMetaDataMap.values()) {
1283    
1284                            AttributeDescriptor foundDescr = schema
1285                                            .getDescriptor(atm.getName());
1286                            if (foundDescr == null) {
1287                                    NameImpl bestMatch = FeatureUtil.findBestMatchingAttribute(
1288                                                    schema, atm.getLocalName());
1289                                    if (bestMatch == null)
1290                                            willRemove.add(atm.getName());
1291                                    else
1292                                            atm.setName(bestMatch);
1293                            } else if (foundDescr instanceof GeometryDescriptor) {
1294                                    // We don't want GeometryColumns in here
1295                                    willRemove.add(atm.getName());
1296                            }
1297                    }
1298    
1299                    // Remove the ones that were not findable in the schema
1300                    for (Name removeName : willRemove) {
1301                            if (attributeMetaDataMap.remove(removeName) == null) {
1302                                    LOGGER.warn("removing the AMData didn't work");
1303                            }
1304                    }
1305    
1306                    // 2. check... all attributes from the schema must have an ATM
1307                    for (AttributeDescriptor ad : schema.getAttributeDescriptors()) {
1308                            if (ad instanceof GeometryDescriptor)
1309                                    continue;
1310                            if (!attributeMetaDataMap.containsKey(ad.getName())) {
1311                                    attributeMetaDataMap.put(new NameImpl(ad.getName()
1312                                                    .getNamespaceURI(), ad.getName().getLocalPart()),
1313                                                    new AttributeMetadataImpl(ad, schema
1314                                                                    .getAttributeDescriptors().indexOf(ad),
1315                                                                    attributeMetaDataMap.getLanguages()));
1316                            }
1317                    }
1318            }
1319    
1320            /**
1321             * Checks every attribute name in the {@link AttributeMetadataMap} for its
1322             * binding type. It the type is textual, add the mrpty string as a NODATA
1323             * value.
1324             *
1325             * @param attributeMetaDataMap
1326             * @param schema
1327             */
1328            public static void addEmptyStringToAllTextualAttributes(
1329                            AttributeMetadataMap<? extends AttributeMetadataInterface> attributeMetaDataMap,
1330                            SimpleFeatureType schema) {
1331    
1332                    for (Name name : attributeMetaDataMap.keySet()) {
1333                            if (String.class.isAssignableFrom(schema.getDescriptor(name)
1334                                            .getType().getBinding())) {
1335                                    attributeMetaDataMap.get(name).getNodataValues().add("");
1336                            }
1337                    }
1338            }
1339    
1340            /**
1341             * @return a nicely formatted String containing all NODATA values of any
1342             *         {@link AttributeMetadataInterface} object. Strings are quoted so
1343             *         that any empty {@link String} can be seen.
1344             */
1345            public static String formatNoDataValues(Set<Object> nodataValuesList) {
1346                    String nicelyFormatted = "";
1347                    if (nodataValuesList != null) {
1348                            if (nodataValuesList.size() == 0)
1349                                    nicelyFormatted = "";
1350                            else {
1351                                    for (Object ndo : nodataValuesList) {
1352                                            if (ndo instanceof String)
1353                                                    nicelyFormatted += "\"" + ndo + "\"";
1354                                            else
1355                                                    nicelyFormatted += ndo.toString();
1356    
1357                                            nicelyFormatted += ",";
1358                                    }
1359                                    // Remove the extra comma
1360                                    nicelyFormatted = nicelyFormatted.substring(0,
1361                                                    nicelyFormatted.length() - 1);
1362                            }
1363                    }
1364                    return nicelyFormatted;
1365            }
1366  }  }

Legend:
Removed from v.420  
changed lines
  Added in v.1225

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26