/[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

revision 400 by alfonx, Mon Sep 14 12:24:50 2009 UTC revision 420 by alfonx, Thu Oct 1 20:22:48 2009 UTC
# Line 36  import java.awt.Graphics2D; Line 36  import java.awt.Graphics2D;
36  import java.awt.Rectangle;  import java.awt.Rectangle;
37  import java.awt.geom.AffineTransform;  import java.awt.geom.AffineTransform;
38  import java.awt.image.BufferedImage;  import java.awt.image.BufferedImage;
39    import java.awt.image.ColorModel;
40    import java.awt.image.ComponentColorModel;
41    import java.awt.image.DataBuffer;
42  import java.io.File;  import java.io.File;
43  import java.io.FileNotFoundException;  import java.io.FileNotFoundException;
44  import java.io.FileWriter;  import java.io.FileWriter;
45  import java.net.URL;  import java.net.URL;
46  import java.text.DecimalFormat;  import java.text.DecimalFormat;
 import java.util.HashMap;  
47  import java.util.List;  import java.util.List;
48  import java.util.Map;  import java.util.Map;
 import java.util.Set;  
 import java.util.SortedMap;  
 import java.util.TreeMap;  
49    
50    import javax.swing.BorderFactory;
51  import javax.swing.Box;  import javax.swing.Box;
52  import javax.swing.BoxLayout;  import javax.swing.BoxLayout;
53  import javax.swing.ImageIcon;  import javax.swing.ImageIcon;
54  import javax.swing.JLabel;  import javax.swing.JLabel;
55    
56  import org.apache.log4j.Logger;  import org.apache.log4j.Logger;
57    import org.geotools.coverage.grid.GeneralGridEnvelope;
58  import org.geotools.coverage.grid.GridCoverage2D;  import org.geotools.coverage.grid.GridCoverage2D;
59    import org.geotools.coverage.grid.GridGeometry2D;
60  import org.geotools.coverage.grid.io.AbstractGridCoverage2DReader;  import org.geotools.coverage.grid.io.AbstractGridCoverage2DReader;
61    import org.geotools.coverage.grid.io.AbstractGridFormat;
62  import org.geotools.feature.FeatureCollection;  import org.geotools.feature.FeatureCollection;
63    import org.geotools.geometry.jts.ReferencedEnvelope;
64  import org.geotools.map.DefaultMapLayer;  import org.geotools.map.DefaultMapLayer;
65  import org.geotools.map.MapLayer;  import org.geotools.map.MapLayer;
66    import org.geotools.parameter.Parameter;
67  import org.geotools.renderer.lite.gridcoverage2d.GridCoverageRenderer;  import org.geotools.renderer.lite.gridcoverage2d.GridCoverageRenderer;
68  import org.geotools.styling.ColorMap;  import org.geotools.styling.ColorMap;
69  import org.geotools.styling.ColorMapEntry;  import org.geotools.styling.ColorMapEntry;
# Line 70  import org.jdom.Document; Line 75  import org.jdom.Document;
75  import org.jdom.Element;  import org.jdom.Element;
76  import org.jdom.input.SAXBuilder;  import org.jdom.input.SAXBuilder;
77  import org.jdom.output.XMLOutputter;  import org.jdom.output.XMLOutputter;
78    import org.opengis.feature.simple.SimpleFeature;
79  import org.opengis.feature.simple.SimpleFeatureType;  import org.opengis.feature.simple.SimpleFeatureType;
80    import org.opengis.parameter.GeneralParameterValue;
81    
82  import schmitzm.geotools.JTSUtil;  import schmitzm.geotools.JTSUtil;
83    import schmitzm.geotools.feature.FeatureUtil;
84  import schmitzm.geotools.styling.StylingUtil;  import schmitzm.geotools.styling.StylingUtil;
85  import schmitzm.io.IOUtil;  import schmitzm.io.IOUtil;
86  import schmitzm.lang.LangUtil;  import schmitzm.lang.LangUtil;
# Line 234  public class StyledLayerUtil { Line 242  public class StyledLayerUtil {
242           *            indicated whether the visible or invisible entries are           *            indicated whether the visible or invisible entries are
243           *            returned           *            returned
244           */           */
245          public static SortedMap<Integer, AttributeMetaData> getVisibleAttributeMetaData(          public static AttributeMetadataMap getVisibleAttributeMetaData(
246                          Map<Integer, AttributeMetaData> amdMap, boolean visible) {                          Map<Integer, AttributeMetaData> amdMap, boolean visible) {
247                  SortedMap<Integer, AttributeMetaData> filteredMap = new TreeMap<Integer, AttributeMetaData>();                  AttributeMetadataMap filteredMap = new AttributeMetadataMap();
248                  for (AttributeMetaData amd : amdMap.values())                  for (AttributeMetaData amd : amdMap.values())
249                          if (amd.isVisible())                          if (amd.isVisible())
250                                  filteredMap.put(amd.getColIdx(), amd);                                  filteredMap.put(amd.getColIdx(), amd);
# Line 279  public class StyledLayerUtil { Line 287  public class StyledLayerUtil {
287           * @param element           * @param element
288           *            {@link Element} to parse           *            {@link Element} to parse
289           */           */
290          public static Map<Integer, AttributeMetaData> parseAttributeMetaDataMap(          public static AttributeMetadataMap parseAttributeMetaDataMap(
291                          final Element element) {                          final Element element) {
292                  HashMap<Integer, AttributeMetaData> metaData = new HashMap<Integer, AttributeMetaData>();                  AttributeMetadataMap metaData = new AttributeMetadataMap();
293                  List<Element> attributesElements = element                  List<Element> attributesElements = element
294                                  .getChildren(ELEM_NAME_ATTRIBUTE);                                  .getChildren(ELEM_NAME_ATTRIBUTE);
295                  for (Element attibuteElement : attributesElements) {                  for (Element attibuteElement : attributesElements) {
# Line 298  public class StyledLayerUtil { Line 306  public class StyledLayerUtil {
306           *            {@link URL} to parse           *            {@link URL} to parse
307           * @see #parseAttributeMetaData(Element)           * @see #parseAttributeMetaData(Element)
308           */           */
309          public static Map<Integer, AttributeMetaData> loadAttributeMetaDataMap(          public static AttributeMetadataMap loadAttributeMetaDataMap(
310                          final URL documentUrl) throws Exception {                          final URL documentUrl) throws Exception {
311                  Document document = SAX_BUILDER.build(documentUrl);                  Document document = SAX_BUILDER.build(documentUrl);
312                  return parseAttributeMetaDataMap(document.getRootElement());                  return parseAttributeMetaDataMap(document.getRootElement());
# Line 332  public class StyledLayerUtil { Line 340  public class StyledLayerUtil {
340           *            map of attribute meta data           *            map of attribute meta data
341           */           */
342          public static Element createAttributeMetaDataMapElement(          public static Element createAttributeMetaDataMapElement(
343                          final Map<Integer, AttributeMetaData> amdMap) {                          final AttributeMetadataMap amdMap) {
344                  final Element element = new Element(ELEM_NAME_AMD, AMLURI);                  final Element element = new Element(ELEM_NAME_AMD, AMLURI);
345                  for (AttributeMetaData amd : amdMap.values())                  for (AttributeMetaData amd : amdMap.values())
346                          element.addContent(createAttributeMetaDataElement(amd));                          element.addContent(createAttributeMetaDataElement(amd));
# Line 348  public class StyledLayerUtil { Line 356  public class StyledLayerUtil {
356           *            {@link URL} to store the XML           *            {@link URL} to store the XML
357           */           */
358          public static void saveAttributeMetaDataMap(          public static void saveAttributeMetaDataMap(
359                          final Map<Integer, AttributeMetaData> amdMap, final URL documentUrl)                          final AttributeMetadataMap amdMap, final URL documentUrl)
360                          throws Exception {                          throws Exception {
361                  // Create XML-Document                  // Create XML-Document
362                  final FileWriter out = new FileWriter(new File(documentUrl.toURI()));                  final FileWriter out = new FileWriter(new File(documentUrl.toURI()));
# Line 615  public class StyledLayerUtil { Line 623  public class StyledLayerUtil {
623                  }                  }
624                  if (styledObject instanceof StyledFeatureCollectionInterface                  if (styledObject instanceof StyledFeatureCollectionInterface
625                                  && (style.getMetaData() instanceof Map || style.getMetaData() == null)) {                                  && (style.getMetaData() instanceof Map || style.getMetaData() == null)) {
626                          Map<Integer, AttributeMetaData> sourceAmd = (Map<Integer, AttributeMetaData>) style                          AttributeMetadataMap sourceAmd = (AttributeMetadataMap) style
627                                          .getMetaData();                                          .getMetaData();
628                          Map<Integer, AttributeMetaData> destAmd = ((StyledFeatureCollectionInterface) styledObject)                          AttributeMetadataMap destAmd = ((StyledFeatureCollectionInterface) styledObject)
629                                          .getAttributeMetaDataMap();                                          .getAttributeMetaDataMap();
630                          if (destAmd != null && sourceAmd != null) {                          if (destAmd != null && sourceAmd != null) {
631                                  destAmd.clear();                                  destAmd.clear();
# Line 843  public class StyledLayerUtil { Line 851  public class StyledLayerUtil {
851                                  // KOMPILIERBAR!!                                  // KOMPILIERBAR!!
852                          } else if (metaData instanceof Map) {                          } else if (metaData instanceof Map) {
853                                  saveAttributeMetaDataMap(                                  saveAttributeMetaDataMap(
854                                                  (Map<Integer, AttributeMetaData>) metaData, IOUtil                                                  (AttributeMetadataMap) metaData, IOUtil
855                                                                  .changeUrlExt(geoObjectURL, mdExt));                                                                  .changeUrlExt(geoObjectURL, mdExt));
856                          } else                          } else
857                                  throw new UnsupportedOperationException(                                  throw new UnsupportedOperationException(
# Line 970  public class StyledLayerUtil { Line 978  public class StyledLayerUtil {
978                                  hbox.add(iconLabel);                                  hbox.add(iconLabel);
979                                  hbox.add(Box.createHorizontalStrut(3));                                  hbox.add(Box.createHorizontalStrut(3));
980    
                                 // ****************************************************************************  
                                 // 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();  
   
981                                  Translation labelT = new Translation();                                  Translation labelT = new Translation();
982                                  labelT.fromOneLine(rawText);                                  labelT.fromOneLine(rule.getDescription().getTitle());
983    
984                                  final JLabel classTitleLabel = new JLabel(labelT.toString());                                  final JLabel classTitleLabel = new JLabel(labelT.toString());
985                                  hbox.add(classTitleLabel);                                  hbox.add(classTitleLabel);
# Line 997  public class StyledLayerUtil { Line 996  public class StyledLayerUtil {
996          /**          /**
997           * Creates a           * Creates a
998           *           *
999           * @param styledGrid           * @param styledRaster
1000           * @param iconHeight           * @param iconHeight
1001           * @param iconWidth           * @param iconWidth
1002           * @return           * @return
1003           */           */
1004          public static Box createLegendPanel(StyledRasterInterface<?> styledGrid,          public static Box createLegendPanel(StyledRasterInterface<?> styledRaster,
1005                          int iconWidth, int iconHeight) {                          int iconWidth, int iconHeight) {
1006                  RasterLegendData rasterLegendData = styledGrid.getLegendMetaData();  
1007                  Set<Double> legendRasterValues = rasterLegendData.keySet();                  /**
1008                     * Determine whether a Style is responsible for the coloring
1009                     */
1010                    ColorModel colorModel = null;
1011                    if (!isStyleable(styledRaster)
1012                                    || (isStyleable(styledRaster) && styledRaster.getStyle() == null)) {
1013                            colorModel = getColorModel(styledRaster);
1014                    }
1015    
1016                    RasterLegendData rasterLegendData = styledRaster.getLegendMetaData();
1017                    List<Double> legendRasterValues = rasterLegendData.getSortedKeys();
1018                  Map<Double, GridCoverage2D> sampleRasters = rasterLegendData                  Map<Double, GridCoverage2D> sampleRasters = rasterLegendData
1019                                  .createSampleRasters();                                  .createSampleRasters();
1020    
# Line 1032  public class StyledLayerUtil { Line 1041  public class StyledLayerUtil {
1041                  for (Double rValue : legendRasterValues) {                  for (Double rValue : legendRasterValues) {
1042    
1043                          /**                          /**
                          * The coverage contains only one value of value rValue  
                          */  
                         GridCoverage2D sampleCov = sampleRasters.get(rValue);  
                         GridCoverageRenderer renderer;  
                         try {  
                                 renderer = new GridCoverageRenderer(sampleCov  
                                                 .getCoordinateReferenceSystem(), JTSUtil  
                                                 .createEnvelope(sampleCov.getEnvelope()),  
                                                 new Rectangle(iconWidth, iconHeight),  
                                                 (AffineTransform) null);  
                         } catch (Exception e1) {  
                                 throw new RuntimeException(  
                                                 "Creating the GridCoverageRenderer:", e1);  
                         }  
   
                         /**  
1044                           *                           *
1045                           */                           */
1046                          Box hbox = new Box(BoxLayout.X_AXIS) {                          Box hbox = new Box(BoxLayout.X_AXIS) {
# Line 1083  public class StyledLayerUtil { Line 1076  public class StyledLayerUtil {
1076                                          ICON_SIZE.height, BufferedImage.TYPE_INT_ARGB);                                          ICON_SIZE.height, BufferedImage.TYPE_INT_ARGB);
1077                          Graphics2D graphics = buffImage.createGraphics();                          Graphics2D graphics = buffImage.createGraphics();
1078    
1079                          /**                          if (colorModel != null) {
                          * Iterate over all FeatureTypeStyles.  
                          */  
                         // for (FeatureTypeStyle ftStyle : styledGrid.getStyle()  
                         // .featureTypeStyles()) {  
                         // One child-node for every rule  
                         // List<Rule> rules = ftStyle.rules();  
   
                         // for (Rule rule : rules) {  
                         List<RasterSymbolizer> rSymbols = StylingUtil  
                                         .getRasterSymbolizers(styledGrid.getStyle());  
1080    
                         for (RasterSymbolizer symbolizer : rSymbols) {  
                                 // LOGGER.debug("Creating a new Legend Image for RUle name =  
                                 // "+rule.getName());  
1081                                  try {                                  try {
1082                                          renderer.paint(graphics, sampleCov, symbolizer);                                          Object inData = null;
1083                                            switch (colorModel.getTransferType()) {
1084                                            case DataBuffer.TYPE_BYTE:
1085                                                    inData = new byte[] { rValue.byteValue() };
1086                                                    break;
1087                                            case DataBuffer.TYPE_USHORT:
1088                                                    inData = new short[] { rValue.shortValue() };
1089                                                    break;
1090                                            case DataBuffer.TYPE_INT:
1091                                                    inData = new int[] { rValue.intValue() };
1092                                                    break;
1093                                            case DataBuffer.TYPE_SHORT:
1094                                                    inData = new short[] { rValue.shortValue() };
1095                                                    break;
1096                                            case DataBuffer.TYPE_FLOAT:
1097                                                    inData = new float[] { rValue.floatValue() };
1098                                                    break;
1099                                            case DataBuffer.TYPE_DOUBLE:
1100                                                    inData = new double[] { rValue.doubleValue() };
1101                                                    break;
1102                                            default:
1103                                                    inData = rValue.intValue();
1104                                            }
1105                                            final Color color = new Color(colorModel.getRGB(inData));
1106                                            graphics.setBackground(color);
1107                                            graphics.setColor(color);
1108                                            graphics.fillRect(0, 0, ICON_SIZE.width, ICON_SIZE.height);
1109                                  } catch (Exception e) {                                  } catch (Exception e) {
1110                                          LOGGER.error("Unable to paint " + symbolizer                                          LOGGER.debug(
1111                                                          + " into the legend image", e);                                                          "Dann nehmen wir halt den GridCoverageRenderer", e);
1112                                            colorModel = null;
1113                                    }
1114                            }
1115    
1116                            if (colorModel == null) {
1117    
1118                                    /**
1119                                     * The coverage contains only one value of value rValue
1120                                     */
1121                                    GridCoverage2D sampleCov = sampleRasters.get(rValue);
1122                                    GridCoverageRenderer renderer;
1123                                    try {
1124                                            renderer = new GridCoverageRenderer(sampleCov
1125                                                            .getCoordinateReferenceSystem(), JTSUtil
1126                                                            .createEnvelope(sampleCov.getEnvelope()),
1127                                                            new Rectangle(iconWidth, iconHeight),
1128                                                            (AffineTransform) null);
1129                                    } catch (Exception e1) {
1130                                            throw new RuntimeException(
1131                                                            "Creating the GridCoverageRenderer:", e1);
1132                                    }
1133    
1134                                    /**
1135                                     * Iterate over all FeatureTypeStyles.
1136                                     */
1137                                    // for (FeatureTypeStyle ftStyle : styledGrid.getStyle()
1138                                    // .featureTypeStyles()) {
1139                                    // One child-node for every rule
1140                                    // List<Rule> rules = ftStyle.rules();
1141                                    // for (Rule rule : rules) {
1142                                    final Style style = styledRaster.getStyle();
1143                                    List<RasterSymbolizer> rSymbols = StylingUtil
1144                                                    .getRasterSymbolizers(style);
1145    
1146                                    for (RasterSymbolizer symbolizer : rSymbols) {
1147                                            // LOGGER.debug("Creating a new Legend Image for RUle
1148                                            // name =
1149                                            // "+rule.getName());
1150                                            try {
1151                                                    renderer.paint(graphics, sampleCov, symbolizer);
1152                                            } catch (Exception ee) {
1153                                                    LOGGER.error("Unable to paint " + symbolizer
1154                                                                    + " into the legend image", ee);
1155                                            }
1156                                            // }
1157                                            // }
1158                                  }                                  }
                                 // }  
                                 // }  
1159                          }                          }
1160    
1161                          ImageIcon legendIcon = new ImageIcon(buffImage);                          ImageIcon legendIcon = new ImageIcon(buffImage);
# Line 1121  public class StyledLayerUtil { Line 1171  public class StyledLayerUtil {
1171                          classTitleLabel.setLabelFor(iconLabel);                          classTitleLabel.setLabelFor(iconLabel);
1172    
1173                          box.add(hbox);                          box.add(hbox);
1174    
1175                            if (rasterLegendData.getPaintGaps()) {
1176                                    iconLabel
1177                                                    .setBorder(BorderFactory.createLineBorder(Color.black));
1178                                    box.add(Box.createVerticalStrut(3));
1179                            }
1180    
1181                  }                  }
1182    
1183                  return box;                  return box;
1184          }          }
1185    
1186            /**
1187             * Extracts the {@link ColorModel} of any {@link StyledRasterInterface}. May
1188             * return <code>null</code> if the geoobject can not be accessed.
1189             */
1190            @SuppressWarnings("unchecked")
1191            public static ColorModel getColorModel(StyledRasterInterface<?> styledGrid) {
1192                    ColorModel colorModel = null;
1193                    try {
1194                            Object geoObject = styledGrid.getGeoObject();
1195                            if (geoObject instanceof GridCoverage2D) {
1196                                    GridCoverage2D cov = (GridCoverage2D) geoObject;
1197                                    colorModel = cov.getRenderedImage().getColorModel();
1198                            } else if (styledGrid instanceof StyledRasterPyramidInterface) {
1199    
1200                                    Parameter readGG = new Parameter(
1201                                                    AbstractGridFormat.READ_GRIDGEOMETRY2D);
1202    
1203                                    ReferencedEnvelope mapExtend = new org.geotools.geometry.jts.ReferencedEnvelope(
1204                                                    styledGrid.getEnvelope(), styledGrid.getCrs());
1205    
1206                                    readGG.setValue(new GridGeometry2D(new GeneralGridEnvelope(
1207                                                    new Rectangle(0, 0, 1, 1)), mapExtend));
1208    
1209                                    FeatureCollection<SimpleFeatureType, SimpleFeature> rFc = (FeatureCollection<SimpleFeatureType, SimpleFeature>) geoObject;
1210    
1211                                    final AbstractGridCoverage2DReader aReader = (AbstractGridCoverage2DReader) FeatureUtil
1212                                                    .getWrappedGeoObject(rFc);
1213                                    GridCoverage2D cov = (GridCoverage2D) aReader
1214                                                    .read(new GeneralParameterValue[] { readGG });
1215                                    colorModel = cov.getRenderedImage().getColorModel();
1216                            }
1217                    } catch (Exception e) {
1218                            LOGGER.error("Error reading the colormodel from " + styledGrid, e);
1219                            return null;
1220                    }
1221                    return colorModel;
1222            }
1223    
1224            /**
1225             * @return <code>true</code> if a {@link RasterSymbolizer} can be applied
1226             *         and will have an effect. Some rasters (e.g. GeoTIFF) can come
1227             *         with their own {@link ColorModel} and will ignore any
1228             *         {@link RasterSymbolizer} = SLD.
1229             */
1230            public static boolean isStyleable(StyledRasterInterface<?> styledRaster) {
1231                    ColorModel colorModel = getColorModel(styledRaster);
1232    
1233                    LOGGER.info("The colormodel of " + styledRaster.getTitle() + " is "
1234                                    + colorModel.getClass().getSimpleName());
1235    
1236                    if (colorModel == null)
1237                            return true;
1238                    if (colorModel instanceof ComponentColorModel)
1239                            return true;
1240                    return false;
1241            }
1242  }  }

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26