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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1273 - (show annotations)
Mon Nov 15 16:22:47 2010 UTC (14 years, 3 months ago) by alfonx
File size: 48912 byte(s)
Change email address
1 /*******************************************************************************
2 * Copyright (c) 2009 Martin O. J. Schmitz.
3 *
4 * This file is part of the SCHMITZM library - a collection of utility
5 * classes based on Java 1.6, focusing (not only) on Java Swing
6 * and the Geotools library.
7 *
8 * The SCHMITZM project is hosted at:
9 * http://wald.intevation.org/projects/schmitzm/
10 *
11 * This program is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public License
13 * as published by the Free Software Foundation; either version 3
14 * of the License, or (at your option) any later version.
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU Lesser General Public License (license.txt)
22 * along with this program; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
24 * or try this link: http://www.gnu.org/licenses/lgpl.html
25 *
26 * Contributors:
27 * Martin O. J. Schmitz - initial API and implementation
28 * Stefan A. Tzeggai - additional utility classes
29 ******************************************************************************/
30 package skrueger.geotools;
31
32 import java.awt.Color;
33 import java.awt.Dimension;
34 import java.awt.Graphics2D;
35 import java.awt.Rectangle;
36 import java.awt.geom.AffineTransform;
37 import java.awt.image.BufferedImage;
38 import java.awt.image.ColorModel;
39 import java.awt.image.ComponentColorModel;
40 import java.awt.image.DataBuffer;
41 import java.awt.image.IndexColorModel;
42 import java.io.File;
43 import java.io.FileNotFoundException;
44 import java.io.FileWriter;
45 import java.net.URL;
46 import java.text.DecimalFormat;
47 import java.util.ArrayList;
48 import java.util.Collections;
49 import java.util.List;
50 import java.util.Map;
51 import java.util.Set;
52
53 import javax.swing.BorderFactory;
54 import javax.swing.ImageIcon;
55 import javax.swing.JComponent;
56 import javax.swing.JLabel;
57
58 import net.miginfocom.swing.MigLayout;
59
60 import org.apache.log4j.Logger;
61 import org.geotools.coverage.grid.GeneralGridEnvelope;
62 import org.geotools.coverage.grid.GridCoverage2D;
63 import org.geotools.coverage.grid.GridGeometry2D;
64 import org.geotools.coverage.grid.io.AbstractGridCoverage2DReader;
65 import org.geotools.coverage.grid.io.AbstractGridFormat;
66 import org.geotools.feature.FeatureCollection;
67 import org.geotools.feature.NameImpl;
68 import org.geotools.geometry.jts.ReferencedEnvelope;
69 import org.geotools.map.DefaultMapLayer;
70 import org.geotools.map.MapLayer;
71 import org.geotools.parameter.Parameter;
72 import org.geotools.renderer.lite.gridcoverage2d.GridCoverageRenderer;
73 import org.geotools.styling.ColorMap;
74 import org.geotools.styling.ColorMapEntry;
75 import org.geotools.styling.FeatureTypeStyle;
76 import org.geotools.styling.RasterSymbolizer;
77 import org.geotools.styling.Rule;
78 import org.geotools.styling.Style;
79 import org.jdom.Document;
80 import org.jdom.Element;
81 import org.jdom.input.SAXBuilder;
82 import org.jdom.output.XMLOutputter;
83 import org.opengis.feature.simple.SimpleFeature;
84 import org.opengis.feature.simple.SimpleFeatureType;
85 import org.opengis.feature.type.AttributeDescriptor;
86 import org.opengis.feature.type.GeometryDescriptor;
87 import org.opengis.feature.type.Name;
88 import org.opengis.filter.FilterFactory2;
89 import org.opengis.parameter.GeneralParameterValue;
90
91 import schmitzm.geotools.FilterUtil;
92 import schmitzm.geotools.JTSUtil;
93 import schmitzm.geotools.feature.FeatureUtil;
94 import schmitzm.geotools.styling.StylingUtil;
95 import schmitzm.io.IOUtil;
96 import schmitzm.lang.LangUtil;
97 import schmitzm.swing.ExceptionDialog;
98 import schmitzm.swing.JPanel;
99 import schmitzm.swing.SwingUtil;
100 import skrueger.AttributeMetadataImpl;
101 import skrueger.AttributeMetadataInterface;
102 import skrueger.RasterLegendData;
103 import skrueger.i8n.Translation;
104
105 import com.vividsolutions.jts.geom.Geometry;
106
107 /**
108 * This class provides static helper methods for dealing with
109 * {@link StyledLayerInterface} stuff.
110 *
111 * @author <a href="mailto:[email protected]">Martin Schmitz</a>
112 * (University of Bonn/Germany)
113 * @version 1.0
114 */
115 public class StyledLayerUtil {
116 private static final Logger LOGGER = Logger.getLogger(StyledLayerUtil.class
117 .getName());
118 private static final SAXBuilder SAX_BUILDER = new SAXBuilder();
119 private static final XMLOutputter XML_OUTPUTTER = new XMLOutputter();
120
121 /**
122 * Is appended to the name of a rule, this rule shall not be shown in the
123 * legend
124 */
125 public final static String HIDE_IN_LAYER_LEGEND_HINT = "HIDE_IN_LEGEND";
126
127 /** URL for Atlas XML schema */
128 public static final String AMLURI = "http://www.wikisquare.de/AtlasML";
129 /** Name of the XML Element for the attribute meta data map */
130 public static final String ELEM_NAME_AMD = "attributeMetaData";
131 /** Name of the XML Element for the raster legend data */
132 public static final String ELEM_NAME_RLD = "rasterLegendData";
133 /** Name of the XML Element for an attribute meta data map entry */
134 public static final String ELEM_NAME_ATTRIBUTE = "dataAttribute";
135 /** Name of the XML Element for an raster legend data entry */
136 public static final String ELEM_NAME_RASTERLEGEND = "rasterLegendItem";
137 /** Name of the XML Element for a translation */
138 public static final String ELEM_NAME_TRANSLATION = "translation";
139 private static FilterFactory2 ff = FilterUtil.FILTER_FAC2;
140
141 /**
142 * Creates a Geotools {@link MapLayer} from an object. If the object is a
143 * {@link StyledLayerInterface} then its sytle is used. In case of direct
144 * Geotools objects ({@link GridCoverage2D},
145 * {@link AbstractGridCoverage2DReader}, {@link FeatureCollection}) a
146 * default style is generated.
147 *
148 * @param object
149 * an Object
150 * @exception Exception
151 * if {@code null} is given as object or an error occurs
152 * during layer creation
153 */
154 public static MapLayer createMapLayer(final Object object) throws Exception {
155 return createMapLayer(object, null);
156 }
157
158 /**
159 * Creates a Geotools {@link MapLayer} from an object. If the object is a
160 * {@link StyledLayerInterface} then its sytle is used. In case of direct
161 * Geotools objects ({@link GridCoverage2D},
162 * {@link AbstractGridCoverage2DReader}, {@link FeatureCollection}) a
163 * default style is generated.
164 *
165 * @param object
166 * an Object
167 * @param forcedStyle
168 * (SLD-)Style to force for the object
169 * @exception Exception
170 * if {@code null} is given as object or an error occurs
171 * during layer creation
172 */
173 public static MapLayer createMapLayer(Object object, final Style forcedStyle)
174 throws Exception {
175 MapLayer layer = null;
176 Style style = null;
177 if (object instanceof StyledLayerInterface) {
178 style = ((StyledLayerInterface<?>) object).getStyle();
179 object = ((StyledLayerInterface<?>) object).getGeoObject();
180 }
181 if (forcedStyle != null)
182 style = forcedStyle;
183 if (style == null)
184 style = StylingUtil.createDefaultStyle(object);
185
186 if (object instanceof GridCoverage2D)
187 layer = new DefaultMapLayer((GridCoverage2D) object, style);
188 if (object instanceof AbstractGridCoverage2DReader)
189 layer = new DefaultMapLayer((AbstractGridCoverage2DReader) object,
190 style);
191 if (object instanceof FeatureCollection)
192 layer = new DefaultMapLayer((FeatureCollection) object, style);
193
194 if (layer == null)
195 throw new Exception("Can not create MapLayer from "
196 + (object == null ? "null" : object.getClass()));
197
198 return layer;
199 }
200
201 /**
202 * Creates an default instance of {@link StyledLayerInterface} for a
203 * Geotools object ({@link GridCoverage2D}, {@link FeatureCollection}) with
204 * a default style.
205 *
206 * @param object
207 * an Object
208 * @param title
209 * title for the object
210 * @exception UnsupportedOperationException
211 * if {@code null} is given as object or an error occurs
212 * during creation
213 */
214 public static StyledLayerInterface<?> createStyledLayer(
215 final Object object, final String title) {
216 return createStyledLayer(object, title, null);
217 }
218
219 /**
220 * Creates an default instance of {@link StyledLayerInterface} for a
221 * Geotools object ({@link GridCoverage2D}, {@link FeatureCollection}) with
222 * a given style.
223 *
224 * @param object
225 * an Object
226 * @param title
227 * title for the object
228 * @param style
229 * style and meta data for the object
230 * @exception UnsupportedOperationException
231 * if {@code null} is given as object or an error occurs
232 * during creation
233 */
234 public static StyledLayerInterface<?> createStyledLayer(
235 final Object object, final String title,
236 final StyledLayerStyle style) {
237 StyledLayerInterface<?> styledLayer = null;
238
239 final String id = (title != null) ? title : "defaultID";
240
241 if (object instanceof GridCoverage2D)
242 styledLayer = new StyledGridCoverage((GridCoverage2D) object, id,
243 title, style);
244 else if (object instanceof AbstractGridCoverage2DReader)
245 styledLayer = new StyledGridCoverageReader(
246 (AbstractGridCoverage2DReader) object, id, title, style);
247 else if (object instanceof FeatureCollection)
248 styledLayer = new StyledFeatureCollection(
249 (FeatureCollection) object, id, title, style);
250
251 if (styledLayer == null)
252 throw new UnsupportedOperationException(
253 "Can not create StyledLayerInterface object from "
254 + (object == null ? "null" : object.getClass()));
255
256 return styledLayer;
257 }
258
259 /**
260 * Return only the visible or invisible entries of an AttributeMetaData-Map.
261 *
262 * @param amdMap
263 * AttributeMetaData-Map
264 * @param visible
265 * indicated whether the visible or invisible entries are
266 * returned
267 *
268 * TODO replace with
269 * {@link AttributeMetadataMap#sortedValuesVisibleOnly()}
270 */
271 public static AttributeMetadataMap<? extends AttributeMetadataInterface> getVisibleAttributeMetaData(
272 final AttributeMetadataMap<? extends AttributeMetadataInterface> amdMap,
273 final boolean visible) {
274
275 final AttributeMetadataMap<AttributeMetadataInterface> filteredMap = (AttributeMetadataMap<AttributeMetadataInterface>) amdMap
276 .clone();
277 if (filteredMap.size() > 0) {
278 filteredMap.clear(); // Just in case the close copies the contents
279 }
280
281 for (final AttributeMetadataInterface amd : amdMap.values())
282 if (amd.isVisible() == visible)
283 filteredMap.put(amd.getName(), amd);
284
285 return filteredMap;
286 }
287
288 /**
289 * Parses a {@link AttributeMetadataImpl} object from an JDOM-
290 * {@link Element}. This method works like {@link
291 * AMLImport#parseDataAttribute(org.w3c.dom.Node}, but for JDOM.
292 *
293 * TODO 20.11.2009, SK: There are some new attribute weight, functiona,
294 * functionX and nodata in AttributeMetaData that should be parsed/exported
295 * too. but this method is only used by ISDSS, which is not supporting that
296 * stuff anyways.
297 *
298 * @param element
299 * {@link Element} to parse
300 */
301 public static AttributeMetadataImpl parseAttributeMetaData(
302 final Element element) {
303 final String namespace = element.getAttributeValue("namespace");
304 final String localname = element.getAttributeValue("localname");
305 final NameImpl aName = new NameImpl(namespace, localname);
306 final Boolean visible = Boolean.valueOf(element
307 .getAttributeValue("visible"));
308 final String unit = element.getAttributeValue("unit");
309
310 Translation name = new Translation();
311 Translation desc = new Translation();
312 for (final Element childElement : (List<Element>) element.getChildren()) {
313 if (childElement.getName() == null)
314 continue;
315
316 if (childElement.getName().equals("name"))
317 name = parseTranslation(childElement);
318 else if (childElement.getName().equals("desc"))
319 desc = parseTranslation(childElement);
320 }
321 return new AttributeMetadataImpl(aName, visible, name, desc, unit);
322 }
323
324 /**
325 * Parses a {@link AttributeMetadataImpl} map from an JDOM-{@link Element}
326 * with {@code <attribute>}-childs.
327 *
328 * @param element
329 * {@link Element} to parse
330 *
331 * TODO Since GP 1.3 the {@link AttributeMetadataImpl} class has
332 * more attributes which are not used by Xulu/ISDSS. GP
333 * exports/imports the AMD via AMLExporter and AMLImporter
334 * classes. (SK, 3.2.2010) *
335 */
336 public static AttributeMetadataMap parseAttributeMetaDataMap(
337 final Element element) {
338 final AttributeMetadataMap metaData = new AttributeMetadataImplMap();
339 final List<Element> attributesElements = element
340 .getChildren(ELEM_NAME_ATTRIBUTE);
341 for (final Element attibuteElement : attributesElements) {
342 final AttributeMetadataImpl attrMetaData = parseAttributeMetaData(attibuteElement);
343 metaData.put(attrMetaData.getName(), attrMetaData);
344 }
345 return metaData;
346 }
347
348 /**
349 * Loads a {@link AttributeMetadataImpl} object from an URL.
350 *
351 * @param documentUrl
352 * {@link URL} to parse
353 * @see #parseAttributeMetaData(Element)
354 */
355 public static AttributeMetadataMap loadAttributeMetaDataMap(
356 final URL documentUrl) throws Exception {
357 final Document document = SAX_BUILDER.build(documentUrl);
358 return parseAttributeMetaDataMap(document.getRootElement());
359 }
360
361 /**
362 * Creates an JDOM {@link Element} for the given
363 * {@link AttributeMetadataImpl} object.
364 *
365 * @param amd
366 * meta data for one attribute
367 *
368 * TODO Since GP 1.3 the {@link AttributeMetadataImpl} class has
369 * more attributes which are not used by Xulu/ISDSS. GP
370 * exports/imports the AMD via AMLExporter and AMLImporter
371 * classes. (SK, 3.2.2010)
372 */
373 public static Element createAttributeMetaDataElement(
374 final AttributeMetadataInterface amd) {
375 final Element element = new Element(ELEM_NAME_ATTRIBUTE, AMLURI);
376 element.setAttribute("namespace",
377 String.valueOf(amd.getName().getNamespaceURI()));
378 element.setAttribute("localname", String.valueOf(amd.getLocalName()));
379 element.setAttribute("visible", String.valueOf(amd.isVisible()));
380 element.setAttribute("unit", amd.getUnit());
381 // Creating a aml:name tag...
382 element.addContent(createTranslationElement("name", amd.getTitle()));
383 // Creating a aml:desc tag...
384 element.addContent(createTranslationElement("desc", amd.getDesc()));
385 return element;
386 }
387
388 /**
389 * Creates an JDOM {@link Element} for the given
390 * {@link AttributeMetadataImpl} map.
391 *
392 * @param amdMap
393 * map of attribute meta data
394 */
395 public static Element createAttributeMetaDataMapElement(
396 final AttributeMetadataMap<? extends AttributeMetadataInterface> amdMap) {
397 final Element element = new Element(ELEM_NAME_AMD, AMLURI);
398 for (final AttributeMetadataInterface amd : amdMap.values())
399 element.addContent(createAttributeMetaDataElement(amd));
400 return element;
401 }
402
403 /**
404 * Saves a {@link AttributeMetadataImpl AttributeMetaData-Map} to an URL.
405 *
406 * @param amdMap
407 * map of {@link AttributeMetadataImpl}
408 * @param documentUrl
409 * {@link URL} to store the XML
410 */
411 public static void saveAttributeMetaDataMap(
412 final AttributeMetadataMap amdMap, final URL documentUrl)
413 throws Exception {
414 // Create XML-Document
415 final FileWriter out = new FileWriter(new File(documentUrl.toURI()));
416 XML_OUTPUTTER.output(createAttributeMetaDataMapElement(amdMap), out);
417 out.flush();
418 out.close();
419 }
420
421 /**
422 * Parses a {@link RasterLegendData} object from an JDOM-{@link Element}.
423 * This method works like {@link
424 * AMLImport#parseRasterLegendData(org.w3c.dom.Node}, but for JDOM.
425 *
426 * @param element
427 * {@link Element} to parse
428 */
429 public static RasterLegendData parseRasterLegendData(final Element element) {
430
431 final boolean paintGaps = Boolean.valueOf(element
432 .getAttributeValue("paintGaps"));
433
434 final RasterLegendData rld = new RasterLegendData(paintGaps);
435
436 for (final Element childElement : (List<Element>) element.getChildren()) {
437 final String name = childElement.getName();
438 // Cancel if it's an attribute
439 if (childElement.getChildren().size() == 0)
440 continue;
441
442 if (name.equals(ELEM_NAME_RASTERLEGEND)) {
443 final String valueAttr = childElement
444 .getAttributeValue("value");
445 if (valueAttr == null)
446 throw new UnsupportedOperationException(
447 "Attribute 'value' missing for definition of <"
448 + ELEM_NAME_RASTERLEGEND + ">");
449 final double value = Double.valueOf(valueAttr);
450
451 // first and only item should be the label
452 final Element labelElement = childElement.getChild("label");
453 // id label element is missing, the translation is searched
454 // directly
455 // as childs of the rasterLegendItem element
456 final Translation label = parseTranslation(labelElement != null ? labelElement
457 : childElement);
458 rld.put(value, label);
459 }
460 }
461
462 return rld;
463 }
464
465 /**
466 * Loads a {@link RasterLegendData} object from an URL.
467 *
468 * @param documentUrl
469 * {@link URL} to parse
470 * @see #parseAttributeMetaData(Element)
471 */
472 public static RasterLegendData loadRasterLegendData(final URL documentUrl)
473 throws Exception {
474 final Document document = SAX_BUILDER.build(documentUrl);
475 return parseRasterLegendData(document.getRootElement());
476 }
477
478 /**
479 * Creates an JDOM {@link Element} for the given {@link RasterLegendData}
480 * map.
481 *
482 * @param rld
483 * raster legend data
484 */
485 public static Element createRasterLegendDataElement(
486 final RasterLegendData rld) {
487 final Element element = new Element(ELEM_NAME_RLD, AMLURI);
488 element.setAttribute("paintGaps", rld.isPaintGaps().toString());
489 for (final Double key : rld.getSortedKeys()) {
490 final Element item = new Element(ELEM_NAME_RASTERLEGEND, AMLURI);
491 item.setAttribute("value", key.toString());
492 item.addContent(createTranslationElement("label", rld.get(key)));
493 element.addContent(item);
494 }
495 return element;
496 }
497
498 /**
499 * Creates {@link RasterLegendData} from a {@link ColorMap}.
500 *
501 * @param colorMap
502 * a color map
503 * @param paintGaps
504 * indicated whether gaps are painted between the legend items
505 * @param digits
506 * number of digits the grid value classes (and legend) are
507 * rounded to (null means no round; >= 0 means digits after
508 * comma; < 0 means digits before comma)
509 */
510 public static RasterLegendData generateRasterLegendData(
511 final ColorMap colorMap, final boolean paintGaps,
512 final Integer digits) {
513 final DecimalFormat decFormat = digits != null ? new DecimalFormat(
514 SwingUtil.getNumberFormatPattern(digits)) : null;
515 final RasterLegendData rld = new RasterLegendData(paintGaps);
516 for (final ColorMapEntry cme : colorMap.getColorMapEntries()) {
517 final double value = StylingUtil.getQuantityFromColorMapEntry(cme);
518 String label = cme.getLabel();
519 // if no label is set (e.g. quantitative style),
520 // use the value as label
521 if (label == null || label.equals(""))
522 if (digits == null)
523 label = String.valueOf(value);
524 else
525 label = decFormat.format(LangUtil.round(value, digits));
526 rld.put(value, new Translation(" " + label));
527 }
528 return rld;
529 }
530
531 /**
532 * Creates {@link RasterLegendData} from the {@link ColorMap} of a style.
533 *
534 * @param style
535 * a raster style (must contain a {@link RasterSymbolizer})
536 * @param paintGaps
537 * indicated whether gaps are painted between the legend items
538 * @param digits
539 * number of digits the grid value classes (and legend) are
540 * rounded to (null means no round; >= 0 means digits after
541 * comma; < 0 means digits before comma)
542 */
543 public static RasterLegendData generateRasterLegendData(final Style style,
544 final boolean paintGaps, final Integer digits) {
545 final ColorMap colorMap = StylingUtil.getColorMapFromStyle(style);
546 if (colorMap == null)
547 throw new IllegalArgumentException(
548 "Color map can not be determined from style!");
549 return generateRasterLegendData(colorMap, paintGaps, digits);
550 }
551
552 /**
553 * Saves a {@link RasterLegendData} to an URL.
554 *
555 * @param rld
556 * raster legend data
557 * @param documentUrl
558 * {@link URL} to store the XML
559 */
560 public static void saveRasterLegendData(final RasterLegendData rld,
561 final URL documentUrl) throws Exception {
562 // Create XML-Document
563 final FileWriter out = new FileWriter(new File(documentUrl.toURI()));
564 XML_OUTPUTTER.output(createRasterLegendDataElement(rld), out);
565 out.flush();
566 out.close();
567 }
568
569 /**
570 * Parses a {@link Translation} object from an JDOM-{@link Element}. This
571 * method works like {@link AMLImport#parseTranslation(org.w3c.dom.Node},
572 * but for JDOM.
573 *
574 * @param element
575 * {@link Element} to parse
576 */
577 public final static Translation parseTranslation(final Element element) {
578 final Translation trans = new Translation();
579
580 if (element == null)
581 return trans;
582
583 for (final Element translationElement : (List<Element>) element
584 .getChildren()) {
585 final String name = translationElement.getName();
586 if (name == null)
587 continue;
588
589 // lang attribute
590 String lang = translationElement.getAttributeValue("lang");
591 // set the default, if no language code is set
592 if (lang == null)
593 lang = Translation.DEFAULT_KEY;
594
595 final String translationText = translationElement.getValue();
596 if (translationText == null)
597 trans.put(lang, "");
598 else
599 trans.put(lang, translationText);
600 }
601
602 // if no <translation> is given, the value of the node should
603 // be used as a default translation
604 if (trans.size() == 0)
605 trans.put(Translation.DEFAULT_KEY, element.getValue());
606 // trans = new Translation(
607 // ((List<Element>)element.getChildren()).get(0).getValue() );
608
609 return trans;
610 }
611
612 /**
613 * Creates an JDOM {@link Element} for the given {@link Translation}.
614 *
615 * @param tagname
616 * Name of the Element
617 * @param translation
618 * Translation to store in the Element
619 */
620 public final static Element createTranslationElement(final String tagname,
621 final Translation translation) {
622 final Element element = new Element(tagname, AMLURI);
623 if (translation == null)
624 throw new UnsupportedOperationException(
625 "Translation element can not be created from null!");
626
627 // If only a default translation is set, the <translation
628 // lang="..">..</tranlation>
629 // part is not used
630 if (translation.keySet().size() == 1
631 && translation.get(Translation.DEFAULT_KEY) != null) {
632 element.addContent(translation.get(Translation.DEFAULT_KEY));
633 return element;
634 }
635
636 // add a <translation lang="..">..</tranlation> part to the element for
637 // all languages
638 for (final String lang : translation.keySet()) {
639 final Element translationElement = new Element(
640 ELEM_NAME_TRANSLATION, AMLURI);
641 translationElement.setAttribute("lang", lang);
642 String translationString = translation.get(lang);
643 if (translationString == null)
644 translationString = "";
645 translationElement.addContent(translationString);
646 element.addContent(translationElement);
647 }
648
649 return element;
650 }
651
652 /**
653 * Sets a style to {@link StyledLayerInterface}.
654 *
655 * @param styledObject
656 * a styled object
657 * @param style
658 * a Style
659 */
660 public static void setStyledLayerStyle(
661 final StyledLayerInterface styledObject,
662 final StyledLayerStyle<?> style) {
663 // set SLD style
664 styledObject.setStyle(style.getGeoObjectStyle());
665 // set meta data
666 if (styledObject instanceof StyledGridCoverageInterface
667 && (style.getMetaData() instanceof RasterLegendData || style
668 .getMetaData() == null)) {
669 final RasterLegendData sourceRld = (RasterLegendData) style
670 .getMetaData();
671 final RasterLegendData destRld = ((StyledGridCoverageInterface) styledObject)
672 .getLegendMetaData();
673 if (destRld != null && sourceRld != null) {
674 destRld.setPaintGaps(sourceRld.isPaintGaps());
675 destRld.clear();
676 destRld.putAll(sourceRld);
677 }
678 return;
679 }
680 if (styledObject instanceof StyledFeatureCollectionInterface
681 && (style.getMetaData() instanceof Map || style.getMetaData() == null)) {
682 final AttributeMetadataMap sourceAmd = (AttributeMetadataMap) style
683 .getMetaData();
684 final AttributeMetadataMap destAmd = ((StyledFeatureCollectionInterface) styledObject)
685 .getAttributeMetaDataMap();
686 if (destAmd != null && sourceAmd != null) {
687 destAmd.clear();
688 destAmd.putAll(sourceAmd);
689 }
690 return;
691 }
692
693 throw new UnsupportedOperationException(
694 "Style is not compatible to object: "
695 + (style.getMetaData() == null ? null : style
696 .getMetaData().getClass().getSimpleName())
697 + " <-> "
698 + (styledObject == null ? null : styledObject
699 .getClass().getSimpleName()));
700 }
701
702 /**
703 * Returns the style a {@link StyledLayerInterface} as a
704 * {@link StyledLayerStyle}.
705 *
706 * @param styledObject
707 * a styled object
708 * @return {@code StyledLayerStyle<RasterLegendData>} for
709 * {@link StyledGridCoverageInterface} or
710 * {@code StyledLayerStyle<Map<Integer,AttributeMetaData>>} for
711 * {@link StyledFeatureCollectionInterface}
712 */
713 public static StyledLayerStyle<?> getStyledLayerStyle(
714 final StyledLayerInterface styledObject) {
715 if (styledObject instanceof StyledGridCoverageInterface)
716 return getStyledLayerStyle((StyledGridCoverageInterface) styledObject);
717 if (styledObject instanceof StyledFeatureCollectionInterface)
718 return getStyledLayerStyle((StyledFeatureCollectionInterface) styledObject);
719 throw new UnsupportedOperationException(
720 "Unknown type of StyledLayerInterface: "
721 + (styledObject == null ? null : styledObject
722 .getClass().getSimpleName()));
723 }
724
725 /**
726 * Returns the style and raster meta data of a
727 * {@link StyledGridCoverageInterface} as a {@link StyledLayerStyle}.
728 *
729 * @param styledGC
730 * a styled grid coverage
731 */
732 public static StyledLayerStyle<RasterLegendData> getStyledLayerStyle(
733 final StyledGridCoverageInterface styledGC) {
734 return new StyledLayerStyle<RasterLegendData>(styledGC.getStyle(),
735 styledGC.getLegendMetaData());
736 }
737
738 /**
739 * Returns the style and attribute meta data of a
740 * {@link StyledFeatureCollectionInterface} as a {@link StyledLayerStyle}.
741 *
742 * @param styledFC
743 * a styled feature collection
744 */
745 public static StyledLayerStyle<AttributeMetadataMap> getStyledLayerStyle(
746 final StyledFeatureCollectionInterface styledFC) {
747 return new StyledLayerStyle<AttributeMetadataMap>(styledFC.getStyle(),
748 styledFC.getAttributeMetaDataMap());
749 }
750
751 /**
752 * Loads a {@linkplain Style SLD-Style} and {@linkplain RasterLegendData
753 * Raster-LegendData} for a given geo-object (raster) source. The SLD file
754 * must be present. A missing raster legend-data file is tolerated.
755 *
756 * @param geoObjectURL
757 * URL of the (already read) raster object
758 * @param sldExt
759 * file extention for the SLD file
760 * @param rldExt
761 * file extention for the raster legend-data file
762 * @return {@code null} in case of any error
763 */
764 public static StyledLayerStyle<RasterLegendData> loadStyledRasterStyle(
765 final URL geoObjectURL, final String sldExt, final String rldExt) {
766 RasterLegendData metaData = null;
767 Style sldStyle = null;
768 try {
769 final Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(
770 geoObjectURL, sldExt));
771 // SLD must be present
772 if (styles == null || styles.length == 0)
773 return null;
774 sldStyle = styles[0];
775 } catch (final Exception err) {
776 // SLD must be present
777 LangUtil.logDebugError(LOGGER, err);
778 return null;
779 }
780
781 try {
782 metaData = StyledLayerUtil.loadRasterLegendData(IOUtil
783 .changeUrlExt(geoObjectURL, rldExt));
784 } catch (final FileNotFoundException err) {
785 // ignore missing raster legend data
786 } catch (final Exception err) {
787 // any other error during legend data creation leads to error
788 LangUtil.logDebugError(LOGGER, err);
789 return null;
790 }
791 return new StyledLayerStyle<RasterLegendData>(sldStyle, metaData);
792 }
793
794 /**
795 * Loads a {@linkplain Style SLD-Style} from a {@code .sld} file and
796 * {@linkplain RasterLegendData Raster-LegendData} from a {@code .rld} file
797 * for a given geo-object (raster) source. The SLD file must be present. A
798 * missing raster legend-data file is tolerated.
799 *
800 * @param geoObjectURL
801 * URL of the (already read) raster object
802 * @param sldExt
803 * file extention for the SLD file
804 * @param rldExt
805 * file extention for the raster legend-data file
806 * @return {@code null} in case of any error
807 */
808 public static StyledLayerStyle<RasterLegendData> loadStyledRasterStyle(
809 final URL geoObjectURL) {
810 return loadStyledRasterStyle(geoObjectURL, "sld", "rld");
811 }
812
813 /**
814 * Loads a {@linkplain Style SLD-Style} and a
815 * {@linkplain AttributeMetadataImpl AttributeMetaData-Map} for a given
816 * geo-object (feature) source. The SLD file must be present. A missing
817 * attribute meta-data file is tolerated.
818 *
819 * @param geoObjectURL
820 * URL of the (already read) feature object
821 * @param sldExt
822 * file extention for the SLD file
823 * @param rldExt
824 * file extention for the raster legend-data file
825 * @return {@code null} in case of any error
826 */
827 public static StyledLayerStyle<AttributeMetadataMap> loadStyledFeatureStyle(
828 final URL geoObjectURL, final String sldExt, final String rldExt) {
829 AttributeMetadataMap metaData = null;
830 Style sldStyle = null;
831 try {
832 final Style[] styles = StylingUtil.loadSLD(IOUtil.changeUrlExt(
833 geoObjectURL, sldExt));
834 // SLD must be present
835 if (styles == null || styles.length == 0)
836 return null;
837 sldStyle = styles[0];
838 } catch (final Exception err) {
839 // SLD must be present
840 LangUtil.logDebugError(LOGGER, err);
841 return null;
842 }
843
844 try {
845 metaData = StyledLayerUtil.loadAttributeMetaDataMap(IOUtil
846 .changeUrlExt(geoObjectURL, rldExt));
847 } catch (final FileNotFoundException err) {
848 // ignore missing attribute meta data
849 } catch (final Exception err) {
850 // any other error during meta data creation leads to error
851 LangUtil.logDebugError(LOGGER, err);
852 return null;
853 }
854
855 return new StyledLayerStyle<AttributeMetadataMap>(sldStyle, metaData);
856 }
857
858 /**
859 * Loads a {@linkplain Style SLD-Style} from a {@code .sld} file and
860 * {@linkplain AttributeMetadataImpl AttributeMetaData-Map} from a
861 * {@code .amd} file for a given geo-object (feature) source. The SLD file
862 * must be present. A missing attribute meta-data file is tolerated.
863 *
864 * @param geoObjectURL
865 * URL of the (already read) feature object
866 * @param sldExt
867 * file extention for the SLD file
868 * @param rldExt
869 * file extention for the raster legend-data file
870 * @return {@code null} in case of any error
871 */
872 public static StyledLayerStyle<AttributeMetadataMap> loadStyledFeatureStyle(
873 final URL geoObjectURL) {
874 return loadStyledFeatureStyle(geoObjectURL, "sld", "amd");
875 }
876
877 /**
878 * Stores a {@linkplain Style SLD-Style} and {@linkplain RasterLegendData
879 * Raster-LegendData} for a given geo-object (raster) source.
880 *
881 * @param style
882 * style to save
883 * @param geoObjectURL
884 * URL of the raster object
885 * @param sldExt
886 * file extention for the SLD file
887 * @param mdExt
888 * file extention for the meta-data file
889 */
890 public static <T> void saveStyledLayerStyle(
891 final StyledLayerStyle<T> style, final URL geoObjectURL,
892 final String sldExt, final String mdExt) throws Exception {
893 // Store the SLD
894 final Style sldStyle = style.getGeoObjectStyle();
895 if (sldStyle != null) {
896 StylingUtil.saveStyleToSld(sldStyle, IOUtil.changeFileExt(new File(
897 geoObjectURL.toURI()), sldExt));
898 }
899
900 // Store the meta data
901 final T metaData = style.getMetaData();
902 if (metaData != null) {
903 if (metaData instanceof RasterLegendData) {
904 saveRasterLegendData((RasterLegendData) metaData,
905 IOUtil.changeUrlExt(geoObjectURL, mdExt));
906 // } else if ( metaData instanceof
907 // Map<Integer,AttributeMetaData> ) { // LEIDER NICHT
908 // KOMPILIERBAR!!
909 } else if (metaData instanceof Map) {
910 saveAttributeMetaDataMap((AttributeMetadataMap) metaData,
911 IOUtil.changeUrlExt(geoObjectURL, mdExt));
912 } else
913 throw new UnsupportedOperationException(
914 "Export for meta data not yet supported: "
915 + metaData.getClass().getSimpleName());
916 }
917 }
918
919 /**
920 * Stores the {@linkplain Style SLD-Style} to a {@code .sld} file and the
921 * meta data ({@link RasterLegendData} or {@link AttributeMetadataImpl}) to
922 * a {@code .rld} or {@code .amd} file. for a given geo-object source.
923 *
924 * @param style
925 * style to save
926 * @param geoObjectURL
927 * URL of the (already read) raster object
928 */
929 public static void saveStyledLayerStyle(final StyledLayerStyle<?> style,
930 final URL geoObjectURL) throws Exception {
931 if (style.getMetaData() instanceof RasterLegendData)
932 saveStyledLayerStyle(style, geoObjectURL, "sld", "rld");
933 else
934 saveStyledLayerStyle(style, geoObjectURL, "sld", "amd");
935 }
936
937 /**
938 * Creates a {@link JPanel} that shows a legend for a list of
939 * {@link FeatureTypeStyle}s and a targeted featureType
940 *
941 * @param style
942 * The Style to presented in this legend
943 * @param featureType
944 * If this a legend for Point, Polygon or Line? Or ANY or NONE?
945 *
946 * @author <a href="mailto:[email protected]">Stefan Alfons Tzeggai</a>
947 */
948 public static JPanel createLegendSwingPanel(Style style,
949 final SimpleFeatureType featureType, final int iconWidth,
950 final int iconHeight) {
951
952 if (featureType == null) {
953 ExceptionDialog.show(new IllegalStateException(
954 "featureType is null!"));
955 return new JPanel();
956 }
957
958 final JPanel panel = new JPanel(new MigLayout("wrap 2", "[]:3:[]"));
959 if (style == null) {
960 // No Style => no legend
961 return panel;
962 }
963
964 // Reversing the list, because a point that is painted above a polygon
965 // should be higher in the list.
966 final List<FeatureTypeStyle> ftsList = style.featureTypeStyles();
967 Collections.reverse(ftsList);
968 for (final FeatureTypeStyle ftStyle : ftsList) {
969
970 // // Try to import the FeatureType into an AtlasStyler RuleList to
971 // // determine whether this RL is actually disabled.
972 // StylingUtil.sldToString(ftStyle).contains(RL_DISABLED_FILTER.toString())
973 // return;
974
975 // One child-node for every rule
976 final List<Rule> rules = ftStyle.rules();
977 for (final Rule rule : rules) {
978
979 // Check if this RULE shall actually appear in the legend
980 if (rule.getName() != null
981 && rule.getName().contains(HIDE_IN_LAYER_LEGEND_HINT))
982 continue;
983
984 /**
985 * Let's not create a hbox for Rules that only contain
986 * TextSymbolizers
987 */
988 if (StylingUtil.getTextSymbolizers(rule.getSymbolizers())
989 .size() == rule.getSymbolizers().length)
990 continue;
991
992 final BufferedImage imageForRule = LegendIconFeatureRenderer
993 .getInstance().createImageForRule(rule, featureType,
994 new Dimension(iconWidth, iconHeight));
995
996 final ImageIcon legendIcon = new ImageIcon(imageForRule);
997
998 final JLabel iconLabel = new JLabel(legendIcon);
999 panel.add(iconLabel, "sgx1");
1000 // hbox.setAlignmentX(0f);
1001 // hbox.add(iconLabel);
1002 // hbox.add(Box.createHorizontalStrut(3));
1003
1004 final Translation labelT = new Translation();
1005 labelT.fromOneLine(rule.getDescription().getTitle());
1006 final JLabel classTitleLabel = new JLabel(labelT.toString());
1007
1008 panel.add(classTitleLabel, "sgx2");
1009 classTitleLabel.setLabelFor(iconLabel);
1010 }
1011 }
1012
1013 return panel;
1014 }
1015
1016 /**
1017 * Creates a {@link JComponent} that contains a legend for a given
1018 * {@link StyledRasterInterface} and a given {@link Style}.
1019 *
1020 * @param style
1021 * if <code>null</code>, the default {@link Style} is extracetd
1022 * from the {@link StyledRasterInterface}
1023 */
1024 public static JPanel createLegendSwingPanel(
1025 final StyledRasterInterface<?> styledRaster, Style style,
1026 final int iconWidth, final int iconHeight) {
1027
1028 // If no style is given, we use the default style for this layer
1029 if (style == null)
1030 style = styledRaster.getStyle();
1031
1032 /**
1033 * Determine whether a Style is responsible for the coloring
1034 */
1035 ColorModel colorModel = null;
1036 if (!isStyleable(styledRaster)
1037 || (isStyleable(styledRaster) && style == null)) {
1038 colorModel = getColorModel(styledRaster);
1039 }
1040
1041 final RasterLegendData rasterLegendData = styledRaster
1042 .getLegendMetaData();
1043 final List<Double> legendRasterValues = rasterLegendData
1044 .getSortedKeys();
1045 final Map<Double, GridCoverage2D> sampleRasters = rasterLegendData
1046 .createSampleRasters();
1047
1048 final JPanel panel = new JPanel(new MigLayout("wrap 2, gapy 0"));
1049
1050 for (final Double rValue : legendRasterValues) {
1051
1052 // final Dimension ICON_SIZE = new Dimension(iconWidth,
1053 // new JLabel().getFontMetrics(new JLabel().getFont())
1054 // .getHeight() > 5 ? new JLabel().getFontMetrics(
1055 // new JLabel().getFont()).getHeight() : iconHeight);
1056
1057 // ****************************************************************************
1058 // Create the actual icon
1059 // ****************************************************************************
1060 final BufferedImage buffImage = new BufferedImage(iconWidth,
1061 iconHeight, BufferedImage.TYPE_INT_ARGB);
1062
1063 final Graphics2D graphics = buffImage.createGraphics();
1064
1065 if (colorModel != null) {
1066 // The colors come from the ColorModel!
1067
1068 try {
1069 Object inData = null;
1070 switch (colorModel.getTransferType()) {
1071 case DataBuffer.TYPE_BYTE:
1072 inData = new byte[] { rValue.byteValue() };
1073 break;
1074 case DataBuffer.TYPE_USHORT:
1075 inData = new short[] { rValue.shortValue() };
1076 break;
1077 case DataBuffer.TYPE_INT:
1078 inData = new int[] { rValue.intValue() };
1079 break;
1080 case DataBuffer.TYPE_SHORT:
1081 inData = new short[] { rValue.shortValue() };
1082 break;
1083 case DataBuffer.TYPE_FLOAT:
1084 inData = new float[] { rValue.floatValue() };
1085 break;
1086 case DataBuffer.TYPE_DOUBLE:
1087 inData = new double[] { rValue.doubleValue() };
1088 break;
1089 default:
1090 inData = rValue.intValue();
1091 }
1092 final Color color = new Color(colorModel.getRGB(inData));
1093 graphics.setBackground(color);
1094 graphics.setColor(color);
1095 graphics.fillRect(0, 0, iconWidth, iconHeight);
1096 } catch (final Exception e) {
1097 LOGGER.info(
1098 "Dann nehmen wir halt den GridCoverageRenderer", e);
1099 colorModel = null;
1100 }
1101 } else {
1102 // The colors come from the Style
1103
1104 /**
1105 * The coverage contains only one value of value rValue
1106 */
1107 final GridCoverage2D sampleCov = sampleRasters.get(rValue);
1108 GridCoverageRenderer renderer;
1109 try {
1110 renderer = new GridCoverageRenderer(
1111 sampleCov.getCoordinateReferenceSystem(),
1112 JTSUtil.createEnvelope(sampleCov.getEnvelope()),
1113 new Rectangle(iconWidth, iconHeight),
1114 (AffineTransform) null);
1115 } catch (final Exception e1) {
1116 throw new RuntimeException(
1117 "Creating a GridCoverageRenderer failed:", e1);
1118 }
1119
1120 /**
1121 * Iterate over all FeatureTypeStyles.
1122 */
1123 final List<RasterSymbolizer> rSymbols = StylingUtil
1124 .getRasterSymbolizers(style);
1125
1126 for (final RasterSymbolizer symbolizer : rSymbols) {
1127 try {
1128 renderer.paint(graphics, sampleCov, symbolizer);
1129 } catch (final Exception ee) {
1130 LOGGER.error("Unable to paint " + symbolizer
1131 + " into the legend image", ee);
1132 }
1133 }
1134 }
1135
1136 final JLabel iconLabel = new JLabel(new ImageIcon(buffImage));
1137 panel.add(iconLabel, "sgx1");
1138
1139 final Translation labelT = rasterLegendData.get(rValue);
1140 final JLabel classTitleLabel = new JLabel(labelT.toString());
1141 panel.add(classTitleLabel, "sgx2"
1142 + (rasterLegendData.isPaintGaps() ? ", gapy 0:0:0 5:5:5"
1143 : ""));
1144 classTitleLabel.setLabelFor(iconLabel);
1145
1146 if (rasterLegendData.isPaintGaps()) {
1147 iconLabel
1148 .setBorder(BorderFactory.createLineBorder(Color.black));
1149 }
1150
1151 }
1152
1153 return panel;
1154 }
1155
1156 /**
1157 * Extracts the {@link ColorModel} of any {@link StyledRasterInterface}. May
1158 * return <code>null</code> if the geoobject can not be accessed.
1159 */
1160 @SuppressWarnings("unchecked")
1161 public static ColorModel getColorModel(
1162 final StyledRasterInterface<?> styledGrid) {
1163 ColorModel colorModel = null;
1164 try {
1165 final Object geoObject = styledGrid.getGeoObject();
1166 if (geoObject instanceof GridCoverage2D) {
1167 final GridCoverage2D cov = (GridCoverage2D) geoObject;
1168 colorModel = cov.getRenderedImage().getColorModel();
1169 } else if (styledGrid instanceof StyledGridCoverageReaderInterface) {
1170
1171 final Parameter readGG = new Parameter(
1172 AbstractGridFormat.READ_GRIDGEOMETRY2D);
1173
1174 final ReferencedEnvelope mapExtend = new ReferencedEnvelope(
1175 styledGrid.getEnvelope(), styledGrid.getCrs());
1176
1177 readGG.setValue(new GridGeometry2D(new GeneralGridEnvelope(
1178 new Rectangle(0, 0, 1, 1)), mapExtend));
1179
1180 AbstractGridCoverage2DReader aReader;
1181 if (geoObject instanceof FeatureCollection) {
1182 final FeatureCollection<SimpleFeatureType, SimpleFeature> rFc = (FeatureCollection<SimpleFeatureType, SimpleFeature>) geoObject;
1183
1184 aReader = (AbstractGridCoverage2DReader) FeatureUtil
1185 .getWrappedGeoObject(rFc);
1186
1187 } else if (geoObject instanceof AbstractGridCoverage2DReader) {
1188 aReader = (AbstractGridCoverage2DReader) geoObject;
1189
1190 } else
1191 throw new RuntimeException("need a reader...");
1192 //
1193
1194 final GridCoverage2D cov = aReader
1195 .read(new GeneralParameterValue[] { readGG });
1196 colorModel = cov.getRenderedImage().getColorModel();
1197 }
1198 } catch (final Exception e) {
1199 LOGGER.error("Error reading the colormodel from " + styledGrid, e);
1200 return null;
1201 }
1202 return colorModel;
1203 }
1204
1205 /**
1206 * @return <code>true</code> if a {@link RasterSymbolizer} can be applied
1207 * and will have an effect. Some rasters (e.g. GeoTIFF) can come
1208 * with their own {@link ColorModel} and will ignore any
1209 * {@link RasterSymbolizer} = SLD.
1210 */
1211 public static boolean isStyleable(
1212 final StyledRasterInterface<?> styledRaster) {
1213 final ColorModel colorModel = getColorModel(styledRaster);
1214
1215 // LOGGER.info("The colormodel of " + styledRaster.getTitle() + " is "
1216 // + colorModel != null ? colorModel.getClass().getSimpleName() :
1217 // "NULL");
1218
1219 if (colorModel == null)
1220 return true;
1221 if (colorModel instanceof ComponentColorModel)
1222 return true;
1223 if (colorModel instanceof IndexColorModel)
1224 return true;
1225
1226 return false;
1227 }
1228
1229 /**
1230 * Set the given Style as the Style of the {@link MapLayer}, unless the
1231 * styles are the same (not comparing selection stuff). If the
1232 * {@link MapLayer}s {@link Style} is changed, the selection FTS is kept.<br/>
1233 * Remember {@link MapLayer#setStyle(Style)} triggers an event leading to a
1234 * repaint, so only use it when needed.
1235 *
1236 * @return <code>true</code> if the {@link MapLayer}'s {@link Style} has
1237 * been changed.
1238 */
1239 public static boolean updateMapLayerStyleIfChangedAndKeepSelection(
1240 MapLayer mapLayer, Style style2) {
1241
1242 Style mapLayerStyleCleaned = StylingUtil
1243 .removeSelectionFeatureTypeStyle(mapLayer.getStyle());
1244
1245 Style newStyleCleaned = StylingUtil
1246 .removeSelectionFeatureTypeStyle(style2);
1247
1248 if (StylingUtil.isStyleDifferent(mapLayerStyleCleaned, newStyleCleaned)) {
1249
1250 // They are different when compared without SELECTION FTS!
1251
1252 // Now let's copy any SELECTION FTS to the now style
1253 FeatureTypeStyle selectionFeatureTypeStyle = StylingUtil
1254 .getSelectionFeatureTypeStyle(mapLayer.getStyle());
1255 if (selectionFeatureTypeStyle != null) {
1256 newStyleCleaned.featureTypeStyles().add(
1257 selectionFeatureTypeStyle);
1258 // newStyleCleaned is not so clean anymore... We just alled a
1259 // selcetion FTS
1260 }
1261
1262 mapLayer.setStyle(newStyleCleaned);
1263
1264 return true;
1265
1266 } else {
1267 return false;
1268 }
1269 }
1270
1271 /**
1272 * After loading an atlas, the AttribteMetaData contains whatever is written
1273 * in the XML. But the DBF may have changed! This method checks an
1274 * {@link AttributeMetadataMap} against a schema and also corrects
1275 * upperCase/lowerCase problems. It will also remove any geometry column
1276 * attribute metadata.
1277 */
1278 /**
1279 * After loading an atlas, the AttribteMetaData contains whatever is written
1280 * in the XML. But the DBF may have changed!
1281 */
1282 public static void checkAttribMetaData(
1283 AttributeMetadataMap<AttributeMetadataImpl> attributeMetaDataMap,
1284 SimpleFeatureType schema) {
1285
1286 if (schema == null)
1287 throw new IllegalArgumentException("schmema may not be null!");
1288
1289 ArrayList<Name> willRemove = new ArrayList<Name>();
1290
1291 // 1. Check.. all attributes in the atm should be in the schema as well.
1292 // maybe correct some upperCase/loweCase stuff
1293
1294 for (AttributeMetadataInterface atm : attributeMetaDataMap.values()) {
1295
1296 AttributeDescriptor foundDescr = schema
1297 .getDescriptor(atm.getName());
1298 if (foundDescr == null) {
1299 NameImpl bestMatch = FeatureUtil.findBestMatchingAttribute(
1300 schema, atm.getLocalName());
1301 if (bestMatch == null)
1302 willRemove.add(atm.getName());
1303 else
1304 atm.setName(bestMatch);
1305 } else if (foundDescr instanceof GeometryDescriptor) {
1306 // We don't want GeometryColumns in here
1307 willRemove.add(atm.getName());
1308 }
1309 }
1310
1311 // Remove the ones that were not findable in the schema
1312 for (Name removeName : willRemove) {
1313 if (attributeMetaDataMap.remove(removeName) == null) {
1314 LOGGER.warn("removing the AMData didn't work");
1315 }
1316 }
1317
1318 // 2. check... all attributes from the schema must have an ATM
1319 for (AttributeDescriptor ad : schema.getAttributeDescriptors()) {
1320 if (ad instanceof GeometryDescriptor)
1321 continue;
1322 if (!attributeMetaDataMap.containsKey(ad.getName())) {
1323 attributeMetaDataMap.put(new NameImpl(ad.getName()
1324 .getNamespaceURI(), ad.getName().getLocalPart()),
1325 new AttributeMetadataImpl(ad, schema
1326 .getAttributeDescriptors().indexOf(ad),
1327 attributeMetaDataMap.getLanguages()));
1328 }
1329 }
1330 }
1331
1332 /**
1333 * Checks every attribute name in the {@link AttributeMetadataMap} for its
1334 * binding type. It the type is textual, add the mrpty string as a NODATA
1335 * value.
1336 *
1337 * @param attributeMetaDataMap
1338 * @param schema
1339 */
1340 public static void addEmptyStringToAllTextualAttributes(
1341 AttributeMetadataMap<? extends AttributeMetadataInterface> attributeMetaDataMap,
1342 SimpleFeatureType schema) {
1343
1344 for (Name name : attributeMetaDataMap.keySet()) {
1345 if (String.class.isAssignableFrom(schema.getDescriptor(name)
1346 .getType().getBinding())) {
1347 attributeMetaDataMap.get(name).getNodataValues().add("");
1348 }
1349 }
1350 }
1351
1352 /**
1353 * @return a nicely formatted String containing all NODATA values of any
1354 * {@link AttributeMetadataInterface} object. Strings are quoted so
1355 * that any empty {@link String} can be seen.
1356 */
1357 public static String formatNoDataValues(Set<Object> nodataValuesList) {
1358 String nicelyFormatted = "";
1359 if (nodataValuesList != null) {
1360 if (nodataValuesList.size() == 0)
1361 nicelyFormatted = "";
1362 else {
1363 for (Object ndo : nodataValuesList) {
1364 if (ndo instanceof String)
1365 nicelyFormatted += "\"" + ndo + "\"";
1366 else
1367 nicelyFormatted += ndo.toString();
1368
1369 nicelyFormatted += ",";
1370 }
1371 // Remove the extra comma
1372 nicelyFormatted = nicelyFormatted.substring(0,
1373 nicelyFormatted.length() - 1);
1374 }
1375 }
1376 return nicelyFormatted;
1377 }
1378
1379 /**
1380 * Creates a new {@link AttributeMetadataMap} with instances of
1381 * {@link AttributeMetadataInterface} for every non-geometry attribute.
1382 * Default NODATA values (like "" for String) are set.
1383 */
1384 public static AttributeMetadataMap<AttributeMetadataImpl> createDefaultAttributeMetadataMap(
1385 SimpleFeatureType schema) {
1386 AttributeMetadataImplMap attMap = new AttributeMetadataImplMap();
1387
1388 for (int i = 0; i < schema.getAttributeCount(); i++) {
1389 AttributeDescriptor attDesc = schema.getDescriptor(i);
1390
1391 if (Geometry.class.isAssignableFrom(attDesc.getType().getBinding())) {
1392 // Ignore the Geometry column
1393 continue;
1394 }
1395
1396 // TODO AttributeMetadataAS would be nicer, which would not work
1397 // with Translations ;-)
1398 AttributeMetadataImpl attMetaData = new AttributeMetadataImpl(
1399 new NameImpl(attDesc.getName().getNamespaceURI(), attDesc
1400 .getName().getLocalPart()), attMap.getLanguages());
1401
1402 if (String.class.isAssignableFrom(attDesc.getType().getBinding())) {
1403 // For Strings we add the "" as NODATA values
1404 attMetaData.addNodataValue("");
1405 }
1406
1407 attMap.put(attDesc.getName(), attMetaData);
1408 }
1409 return attMap;
1410 }
1411 }

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26