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

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

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

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

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26