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

Legend:
Removed from v.405  
changed lines
  Added in v.1203

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26