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

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

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

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

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26