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

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26