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

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

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

revision 238 by alfonx, Tue Jul 28 08:07:12 2009 UTC revision 1159 by alfonx, Fri Oct 22 17:56:28 2010 UTC
# Line 1  Line 1 
1  package skrueger.geotools;  /*******************************************************************************
2     * Copyright (c) 2009 Martin O. J. Schmitz.
3  import java.io.File;   *
4  import java.io.FileNotFoundException;   * This file is part of the SCHMITZM library - a collection of utility
5  import java.io.IOException;   * classes based on Java 1.6, focusing (not only) on Java Swing
6  import java.net.URL;   * and the Geotools library.
7  import java.util.Date;   *
8  import java.util.HashMap;   * The SCHMITZM project is hosted at:
9  import java.util.Map;   * http://wald.intevation.org/projects/schmitzm/
10  import java.util.Random;   *
11     * This program is free software; you can redistribute it and/or
12  import javax.swing.ImageIcon;   * modify it under the terms of the GNU Lesser General Public License
13  import javax.swing.JPanel;   * as published by the Free Software Foundation; either version 3
14     * of the License, or (at your option) any later version.
15  import org.apache.log4j.Logger;   *
16  import org.geotools.data.FeatureSource;   * This program is distributed in the hope that it will be useful,
17  import org.geotools.feature.AttributeType;   * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  import org.geotools.feature.FeatureCollection;   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  import org.geotools.styling.Style;   * GNU General Public License for more details.
20  import org.opengis.referencing.crs.CoordinateReferenceSystem;   *
21     * You should have received a copy of the GNU Lesser General Public License (license.txt)
22  import schmitzm.geotools.styling.StylingUtil;   * along with this program; if not, write to the Free Software
23  import skrueger.AttributeMetaData;   * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
24  import skrueger.i8n.Translation;   * or try this link: http://www.gnu.org/licenses/lgpl.html
25     *
26  import com.vividsolutions.jts.geom.Envelope;   * Contributors:
27     *     Martin O. J. Schmitz - initial API and implementation
28  /**   *     Stefan A. Tzeggai - additional utility classes
29   * This class enables a non Atlas context to use the Atlas LayerPanel   ******************************************************************************/
30   * {@link JPanel} as a {@link MapContextManagerInterface}  package skrueger.geotools;
31   *  
32   * @author <a href="mailto:[email protected]">Stefan Alfons Kr&uuml;ger</a>  import java.io.File;
33   */  import java.io.IOException;
34  public class StyledFS implements StyledFeatureSourceInterface {  import java.net.URL;
35          private static final Logger LOGGER = Logger.getLogger(StyledFS.class);  import java.util.Date;
36    import java.util.Random;
37          private final FeatureSource fs;  
38    import javax.swing.ImageIcon;
39          /**  import javax.swing.JPanel;
40           * A unique ID which identifies the Layer in the Atlas. It's more important  
41           * than it should be ;-)  import org.apache.log4j.Logger;
42           */  import org.geotools.data.FeatureSource;
43          private String id;  import org.geotools.feature.FeatureCollection;
44    import org.geotools.feature.NameImpl;
45          private Style style;  import org.geotools.styling.Style;
46    import org.opengis.feature.simple.SimpleFeature;
47          private Translation title;  import org.opengis.feature.simple.SimpleFeatureType;
48    import org.opengis.feature.type.AttributeDescriptor;
49          private Translation desc;  import org.opengis.filter.Filter;
50    import org.opengis.referencing.crs.CoordinateReferenceSystem;
51          private File sldFile;  
52    import schmitzm.geotools.io.GeoImportUtil;
53          private HashMap<Integer, AttributeMetaData> map;  import schmitzm.geotools.styling.StylingUtil;
54    import skrueger.AttributeMetadataImpl;
55          /**  import skrueger.i8n.Translation;
56           * This class enables a non Atlas context to use the Atlas LayerPanel  
57           * {@link JPanel} as a {@link MapContextManagerInterface}  import com.vividsolutions.jts.geom.Envelope;
58           *  
59           * @param fs  /**
60           *            {@link FeatureSource} that is beeing styled.   * This class enables a non Atlas context to use the Atlas LayerPanel
61           *   * {@link JPanel} as a {@link MapContextManagerInterface}
62           * @param sldFile   *
63           *            may be <code>null</code>. Otherwise the SLD {@link File} to   * @author <a href="mailto:[email protected]">Stefan Alfons Tzeggai</a>
64           *            import and associate with this {@link StyledFS}   *
65           */   *         TODO Rename to StyledShapefile
66          public StyledFS(FeatureSource fs, File sldFile) {   */
67    public class StyledFS implements StyledFeatureSourceInterface {
68                  this.fs = fs;          private static final Logger LOGGER = Logger.getLogger(StyledFS.class);
69                  id = StyledFS.class.getSimpleName()  
70                                  + new Random(new Date().getTime()).nextInt(10000000);          private final FeatureSource<SimpleFeatureType, SimpleFeature> fs;
71    
72                  this.sldFile = sldFile;          /** Caching the CRS of the layer **/
73            CoordinateReferenceSystem crs = null;
74                  if ((sldFile != null) && (sldFile.exists())) {  
75                          try {          /**
76                                  style = StylingUtil.loadSLD(sldFile)[0];           * A unique ID which identifies the Layer in the Atlas. It's more important
77                          } catch (FileNotFoundException e) {           * than it should be ;-)
78                                  LOGGER           */
79                                                  .debug("The SLD file passed was empty. Leaving the Style untouched. (We are in the constructor.. so its null");          final private String id;
80                          } catch (Exception e) {  
81                                  LOGGER.warn("Reading SLD failed: " + sldFile, e);          private Style style;
82                          }  
83                  }          private Translation title;
84                  title = new Translation();  
85                  title.fromOneLine(sldFile.getName());          private Translation desc;
86    
87                  desc = new Translation();          private File sldFile;
88                  desc.fromOneLine(sldFile.getAbsolutePath());  
89          }          /** A map of simple attribute names to their meta-data **/
90            private AttributeMetadataMap<AttributeMetadataImpl> map;
91          public void dispose() {  
92          }          private Filter filter = Filter.INCLUDE;
93    
94          /**          /**
95           * Returnes human readable {@link String} of the CRS natively used by this           * This class enables a non Atlas context to use the Atlas LayerPanel
96           * {@link DpLayer}           * {@link JPanel} as a {@link MapContextManagerInterface}
97           *           *
98           * If crs == null, it will call {@link #getGeoObject()}           * @param fs
99           *           *            {@link FeatureSource} that is beeing styled.
100           */           *
101          public String getCRSString() {           * @param sldFile
102                  if (getCrs() == null)           *            may be <code>null</code>. Otherwise the SLD {@link File} to
103                          return "CRS?";           *            import and associate with this {@link StyledFS}
104             *
105                  return getCrs().getName().getCode();           * @param id
106          }           *            <code>null</code> is allowed and will autogenerate an id
107             */
108          public CoordinateReferenceSystem getCrs() {          public StyledFS(FeatureSource<SimpleFeatureType, SimpleFeature> fs,
109                  return fs.getSchema().getDefaultGeometry().getCoordinateSystem();                          File sldFile, String id) {
110          }  
111                    this.fs = fs;
112          public Translation getDesc() {  
113                  return desc;                  if (id == null) {
114          }                          this.id = StyledFS.class.getSimpleName()
115                                            + new Random(new Date().getTime()).nextInt(10000000);
116          public Envelope getEnvelope() {                  } else {
117                  try {                          this.id = id;
118                          return fs.getBounds();                  }
119                  } catch (IOException e) {  
120                          e.printStackTrace();                  this.sldFile = sldFile;
121                          return null;  
122                  }                  // datei existiert, dann lesen
123          }                  if (sldFile != null && sldFile.exists()) {
124                            try {
125          public FeatureSource getGeoObject() {                                  style = StylingUtil.loadSLD(sldFile)[0];
126                  return fs;                          } catch (Exception e) {
127          }                                  LOGGER.warn("Reading SLD failed: " + sldFile, e);
128                                    style = null;
129          public String getId() {                          }
130                  return id;                  }
131          }  
132                    title = new Translation();
133          public ImageIcon getImageIcon() {                  desc = new Translation();
134                  return null;  
135          }                  if (sldFile != null) {
136                            title.fromOneLine(sldFile.getName());
137          public URL getInfoURL() {                          desc.fromOneLine(sldFile.getAbsolutePath());
138                  return null;                  }
139          }  
140            }
141          public Translation getKeywords() {  
142                  return null;          public StyledFS(FeatureSource<SimpleFeatureType, SimpleFeature> fs) {
143          }                  this(fs, (File) null, null);
144            }
145          public Style getStyle() {  
146                  return style;          public StyledFS(FeatureSource<SimpleFeatureType, SimpleFeature> fs,
147          }                          String id) {
148                    this(fs, null, id);
149          public Translation getTitle() {          }
150                  return title;  
151          }          public void dispose() {
152            }
153          public boolean isDisposed() {  
154                  return false;          /**
155          }           * Returns human readable {@link String} of the CRS natively used by this
156             * {@link DpLayer}
157          /**           *
158           * If true, this layer will not be shown in the legend. Default = false           * If CRS == null, it will call {@link #getGeoObject()}
159           */           *
160          /**           */
161           *          public String getCRSString() {
162           * Killed by SK: 6. April 09: Ein Layer soll nicht generell auf                  if (getCrs() == null)
163           * verstecken/nicht verstecken gestellt werden können. Das sind                          return "CRS?";
164           * Eigenschaften der Karte/MapContext, ebenso wie die Reihenfolge der Layer.  
165           * Im Atlas verwaltet deshalb nun die Klasse skrueger.atlas.Map welche Layer                  return getCrs().getName().getCode();
166           * nicht in der Legende auftauchen sollen. Meines Wissens hat keiner bisher          }
167           * die Funktion genutzt.  
168           *          public CoordinateReferenceSystem getCrs() {
169           * // public boolean isHideInLegend() { // return false; // }                  if (crs == null) {
170           */                          crs = fs.getSchema().getCoordinateReferenceSystem();
171                            if (crs == null) {
172          public void setDesc(Translation dec) {  
173                  this.desc = dec;                                  crs = fs.getSchema().getGeometryDescriptor()
174          }                                                  .getCoordinateReferenceSystem();
175    
176          public void setImageIcon(ImageIcon icon) {                                  if (crs == null) {
177          }                                          LOGGER.warn("Could not determine the CRS of " + getTitle()
178                                                            + ". Using default "
179          public void setKeywords(Translation keywords) {                                                          + GeoImportUtil.getDefaultCRS());
180          }                                          crs = GeoImportUtil.getDefaultCRS();
181                                    }
182          public void setStyle(Style style) {                          }
183                  this.style = style;                  }
184                    return crs;
185          }          }
186    
187          public void setTitle(Translation title) {          public Translation getDesc() {
188                  this.title = title;                  return desc;
189            }
190          }  
191            public Envelope getEnvelope() {
192          public void uncache() {                  try {
193          }                          return fs.getBounds();
194                    } catch (IOException e) {
195          /**                          e.printStackTrace();
196           *                          return null;
197           */                  }
198          public Map<Integer, AttributeMetaData> getAttributeMetaDataMap() {          }
199                  if (map == null) {  
200            public FeatureSource<SimpleFeatureType, SimpleFeature> getGeoObject() {
201                          map = new HashMap<Integer, AttributeMetaData>();                  return fs;
202            }
203                          // Leaving out the first one, it will be the_geom  
204                          for (int i = 1; i < fs.getSchema().getAttributeCount(); i++) {          public String getId() {
205                                  AttributeType att = fs.getSchema().getAttributeType(i);                  return id;
206            }
207                                  AttributeMetaData attMetaData = new AttributeMetaData(i, att  
208                                                  .getLocalName());          public ImageIcon getImageIcon() {
209                                  map.put(i, attMetaData);                  return null;
210                          }          }
211                  }  
212                  return map;          public URL getInfoURL() {
213          }                  return null;
214            }
215          /**  
216           * @return The {@link File} where the SLD was loaded from or          public Translation getKeywords() {
217           *         <code>null</code> if there didn't exist a {@link File}.                  return null;
218           *          }
219           * @author <a href="mailto:[email protected]">Stefan Alfons  
220           *         Kr&uuml;ger</a>          public Style getStyle() {
221           */                  return style;
222          public File getSldFile() {          }
223                  return sldFile;  
224          }          public Translation getTitle() {
225                    return title;
226          public void setSldFile(File sldFile) {          }
227                  this.sldFile = sldFile;  
228          }          public boolean isDisposed() {
229                    return false;
230          /**          }
231           * Returns the features of the {@link FeatureSource}.  
232           *          /**
233           * @see {@link StyledFeaturesInterface}           * If true, this layer will not be shown in the legend. Default = false
234           */           */
235          @Override          /**
236          public FeatureCollection getFeatureCollection() {           *
237                  FeatureCollection features;           * Killed by SK: 6. April 09: Ein Layer soll nicht generell auf
238                  try {           * verstecken/nicht verstecken gestellt werden können. Das sind
239                          features = getGeoObject().getFeatures();           * Eigenschaften der Karte/MapContext, ebenso wie die Reihenfolge der Layer.
240                  } catch (IOException e) {           * Im Atlas verwaltet deshalb nun die Klasse skrueger.atlas.Map welche Layer
241                          throw new RuntimeException(           * nicht in der Legende auftauchen sollen. Meines Wissens hat keiner bisher
242                                          "Error getting the features of the  FeatureSource");           * die Funktion genutzt.
243                  }           *
244                  return features;           * // public boolean isHideInLegend() { // return false; // }
245          }           */
246    
247          /**          public void setDesc(Translation dec) {
248           * Same as {@link #getGeoObject()} method, but complies to the                  this.desc = dec;
249           * {@link StyledFeaturesInterface}          }
250           *  
251           * @see {@link StyledFeaturesInterface}          public void setImageIcon(ImageIcon icon) {
252           */          }
253          @Override  
254          public FeatureSource getFeatureSource() {          public void setKeywords(Translation keywords) {
255                  return getGeoObject();          }
256          }  
257            public void setStyle(Style style) {
258  }                  this.style = style;
259    
260            }
261    
262            public void setTitle(Translation title) {
263                    this.title = title;
264    
265            }
266    
267            public void uncache() {
268            }
269    
270            /**
271             *
272             */
273            public AttributeMetadataMap<AttributeMetadataImpl> getAttributeMetaDataMap() {
274                    if (map == null) {
275    
276                            map = new AttributeMetadataImplMap();
277    
278                            // // Leaving out the first one, it will be the_geom
279                            // for (int i = 1; i < fs.getSchema().getAttributeCount(); i++) {
280                            // AttributeDescriptor attDesc = fs.getSchema().getDescriptor(i);
281                            //
282                            // AttributeMetadataImpl attMetaData = new AttributeMetadataImpl(
283                            // new NameImpl(attDesc
284                            // .getName().getNamespaceURI(), attDesc
285                            // .getName().getLocalPart()), map.getLanguages());
286                            // map.put(attDesc.getName(), attMetaData);
287                            // }
288    
289                            // Leaving out the first one, it will be the_geom
290                            for (int i = 1; i < fs.getSchema().getAttributeCount(); i++) {
291                                    AttributeDescriptor attDesc = fs.getSchema().getDescriptor(i);
292    
293                                    // TODO AttributeMetadataAS would be nicer, which would not work
294                                    // with Translations ;-)
295                                    AttributeMetadataImpl attMetaData = new AttributeMetadataImpl(
296                                                    new NameImpl(attDesc.getName().getNamespaceURI(),
297                                                                    attDesc.getName().getLocalPart()),
298                                                    map.getLanguages());
299                                    if (String.class.isAssignableFrom(attDesc.getType()
300                                                    .getBinding())) {
301                                            // For Strings we add the "" as NODATA values
302                                            attMetaData.addNodataValue("");
303                                    }
304                                    map.put(attDesc.getName(), attMetaData);
305                            }
306                    }
307                    return map;
308            }
309    
310            /**
311             * @return The {@link File} where the SLD was loaded from or
312             *         <code>null</code> if there didn't exist a {@link File}.
313             *
314             * @author <a href="mailto:[email protected]">Stefan Alfons Tzeggai</a>
315             */
316            public File getSldFile() {
317                    return sldFile;
318            }
319    
320            public void setSldFile(File sldFile) {
321                    this.sldFile = sldFile;
322            }
323    
324            /**
325             * Returns the features of the {@link FeatureSource}.
326             *
327             * @see {@link StyledFeaturesInterface}
328             */
329            @Override
330            public FeatureCollection<SimpleFeatureType, SimpleFeature> getFeatureCollection() {
331                    FeatureCollection<SimpleFeatureType, SimpleFeature> features;
332                    try {
333                            features = getGeoObject().getFeatures();
334                    } catch (IOException e) {
335                            throw new RuntimeException(
336                                            "Error getting the features of the  FeatureSource");
337                    }
338                    return features;
339            }
340    
341            /**
342             * Same as {@link #getGeoObject()} method, but complies to the
343             * {@link StyledFeaturesInterface}
344             *
345             * @see {@link StyledFeaturesInterface}
346             */
347            @Override
348            public FeatureSource<SimpleFeatureType, SimpleFeature> getFeatureSource() {
349                    return getGeoObject();
350            }
351    
352            @Override
353            public FeatureCollection<SimpleFeatureType, SimpleFeature> getFeatureCollectionFiltered() {
354                    // final FeatureCollection<SimpleFeatureType, SimpleFeature> fc =
355                    // getFeatureCollection();
356                    // if (filter == Filter.EXCLUDE)
357                    // return new EmptyFeatureCollection(fc.getSchema());
358                    // if (filter == Filter.INCLUDE)
359                    // return fc;
360                    // return fc.subCollection(filter);
361    
362                    try {
363                            if (filter != Filter.INCLUDE)
364                                    return getFeatureSource().getFeatures(filter);
365                            else
366                                    return getFeatureSource().getFeatures();
367                    } catch (IOException e) {
368                            throw new RuntimeException(e);
369                    }
370            }
371    
372            @Override
373            public Filter getFilter() {
374                    return filter;
375            }
376    
377            @Override
378            public void setFilter(Filter filter) {
379                    this.filter = filter;
380            }
381    
382            @Override
383            public SimpleFeatureType getSchema() {
384                    return getGeoObject().getSchema();
385            }
386    
387            /**
388             * Tries to load a style from the file denoted in {@link #getSldFile()}. If
389             * the file doesn't exits, return <code>null</code>;
390             *
391             * @return <code>true</code> is style was loaded
392             */
393            public boolean loadStyle() {
394                    if (getSldFile() == null)
395                            return false;
396    
397                    try {
398                            Style[] loadSLD = StylingUtil.loadSLD(getSldFile());
399                            setStyle(loadSLD[0]);
400                            return true;
401                    } catch (Exception e) {
402                            return false;
403                    }
404    
405            }
406    
407            public void setTitle(String title) {
408                    setTitle(new Translation(title));
409            }
410    
411            public void setDesc(String desc) {
412                    setDesc(new Translation(desc));
413            }
414    
415    }

Legend:
Removed from v.238  
changed lines
  Added in v.1159

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26