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

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

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

revision 168 by alfonx, Sun Jun 28 17:57:38 2009 UTC revision 769 by alfonx, Sun Mar 21 11:02:34 2010 UTC
# Line 1  Line 1 
1  /** SCHMITZM - This file is part of the java library of Martin O.J. Schmitz (SCHMITZM)  /*******************************************************************************
2     * Copyright (c) 2009 Martin O. J. Schmitz.
3      This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.   *
4      This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.   * This file is part of the SCHMITZM library - a collection of utility
5      You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA   * classes based on Java 1.6, focusing (not only) on Java Swing
6     * and the Geotools library.
7      Diese Bibliothek ist freie Software; Sie dürfen sie unter den Bedingungen der GNU Lesser General Public License, wie von der Free Software Foundation veröffentlicht, weiterverteilen und/oder modifizieren; entweder gemäß Version 2.1 der Lizenz oder (nach Ihrer Option) jeder späteren Version.   *
8      Diese Bibliothek wird in der Hoffnung weiterverbreitet, daß sie nützlich sein wird, jedoch OHNE IRGENDEINE GARANTIE, auch ohne die implizierte Garantie der MARKTREIFE oder der VERWENDBARKEIT FÜR EINEN BESTIMMTEN ZWECK. Mehr Details finden Sie in der GNU Lesser General Public License.   * The SCHMITZM project is hosted at:
9      Sie sollten eine Kopie der GNU Lesser General Public License zusammen mit dieser Bibliothek erhalten haben; falls nicht, schreiben Sie an die Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA.   * http://wald.intevation.org/projects/schmitzm/
10   **/   *
11  package skrueger.geotools;   * 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  import java.util.Iterator;   * as published by the Free Software Foundation; either version 3
14  import java.util.Map;   * of the License, or (at your option) any later version.
15  import java.util.Vector;   *
16     * This program is distributed in the hope that it will be useful,
17  import org.apache.log4j.Logger;   * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  import org.geotools.data.DefaultQuery;   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  import org.geotools.data.FeatureSource;   * GNU General Public License for more details.
20  import org.geotools.data.Query;   *
21  import org.geotools.data.memory.MemoryDataStore;   * You should have received a copy of the GNU Lesser General Public License (license.txt)
22  import org.geotools.feature.AttributeType;   * along with this program; if not, write to the Free Software
23  import org.geotools.feature.FeatureCollection;   * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
24  import org.opengis.filter.Filter;   * or try this link: http://www.gnu.org/licenses/lgpl.html
25     *
26  import schmitzm.geotools.gui.FeatureCollectionTableModel;   * Contributors:
27  import skrueger.AttributeMetaData;   *     Martin O. J. Schmitz - initial API and implementation
28  import skrueger.i8n.I8NUtil;   *     Stefan A. Krüger - additional utility classes
29  import skrueger.i8n.Translation;   ******************************************************************************/
30    package skrueger.geotools;
31  import com.vividsolutions.jts.geom.Envelope;  
32    import java.util.HashMap;
33  /**  import java.util.List;
34   * This class extends the the {@link FeatureCollectionTableModel} with the  import java.util.Vector;
35   * functionalities of the {@link AttributeMetaData} of  
36   * {@linkplain StyledMapInterface styled objects}.  import org.apache.log4j.Logger;
37   * <ul>  import org.geotools.data.DefaultQuery;
38   * <li>column names are translated according to  import org.geotools.data.FeatureSource;
39   * {@link AttributeMetaData#getTitle()}</li>  import org.geotools.data.Query;
40   * <li>columns are hidden according to {@link AttributeMetaData#isVisible()()}</li>  import org.geotools.feature.FeatureCollection;
41   * </ul>  import org.opengis.feature.simple.SimpleFeature;
42   *  import org.opengis.feature.simple.SimpleFeatureType;
43   * @author <a href="mailto:[email protected]">Martin Schmitz</a>  import org.opengis.feature.type.AttributeDescriptor;
44   *         (University of Bonn/Germany)  import org.opengis.filter.Filter;
45   */  
46  public class StyledFeatureCollectionTableModel extends  import schmitzm.geotools.feature.FeatureUtil;
47                  FeatureCollectionTableModel {  import schmitzm.geotools.gui.FeatureCollectionTableModel;
48          final static private Logger LOGGER = Logger  import skrueger.AttributeMetadata;
49                          .getLogger(StyledFeatureCollectionTableModel.class);  import skrueger.AttributeMetadataImpl;
50          /** Holds the data source as styled map. */  
51          protected StyledMapInterface<?> map = null;  import com.vividsolutions.jts.geom.Envelope;
52          /** Contains only the visible elements of the {@link AttributeMetaData}-Map */  
53          protected Map<Integer, AttributeMetaData> visibleAMD = null;  /**
54          /** Holds the data source for the table as {@code FeatureSource}. */   * This class extends the the {@link FeatureCollectionTableModel} with the
55          protected FeatureSource featureSource = null;   * functionalities of the {@link AttributeMetadataImpl}.
56          /** Contains the complete {@link AttributeMetaData}-Map of the styled layer. */   * <ul>
57          protected Map<Integer, AttributeMetaData> origAMD = null;   * <li>column names are translated according to
58          /** Holds the current filter on the table */   * {@link AttributeMetadataImpl#getTitle()}</li>
59          protected Filter filter = null;   * <li>columns are hidden according to {@link AttributeMetaData#isVisible()()}</li>
60          /** Holds the Bounds for all features. Only set once during the constructor **/   * <li>Any filter defined in the {@link StyledFeaturesInterface} will be
61          protected Envelope bounds;   * applied.</li>
62     * </ul>
63          /**   *
64           * Creates a new table model for a styled map.   * @author Stefan A. Krüger
65           *   */
66           * @param map  public class StyledFeatureCollectionTableModel extends
67           *            the styled map                  FeatureCollectionTableModel {
68           */          final static private Logger LOGGER = Logger
69          public StyledFeatureCollectionTableModel(                          .getLogger(StyledFeatureCollectionTableModel.class);
70                          StyledFeatureCollectionInterface map) {          /** Contains the complete {@link AttributeMetadataImpl}-Map of the styled layer. */
71                  this(map, Filter.INCLUDE);          protected AttributeMetadataMap<? extends AttributeMetadata> amdMap = null;
72          }          /** Holds the current filter on the table */
73            protected Filter filter = null;
74          /**          /** Holds the Bounds for all features. Only set once during the constructor **/
75           * Creates a new table model for a styled map.          protected Envelope bounds;
76           *          /**
77           * @param map           * Tooltips für die Spaltennamen. Wird nur beim Aufruf von
78           *            the styled map           * {@link #reorganize} befuellt.
79           * @param filter           */
80           *            filter applied to the table          protected String[] colTooltips = null;
81           */  
82          public StyledFeatureCollectionTableModel(          /** A cache for the #sortedValuesVisibleOnly() **/
83                          StyledFeatureCollectionInterface map, Filter filter) {          protected List<? extends AttributeMetadata> amdMapVisibleOnly = null;
84                  super();  
85                  setFeatureCollection(map, filter);          /**
86          }           * Creates a new table model for a styled layer.
87             *
88          /**           * @param styledFeatures
89           * Creates a new table model for a styled map.           *            the styled layer
90           *           * @param filter
91           * @param map           *            filter applied to the table
92           *            the styled map           */
93           */          public StyledFeatureCollectionTableModel(
94          public StyledFeatureCollectionTableModel(StyledFeatureSourceInterface map) {                          StyledFeaturesInterface<?> styledFeatures) {
95                  this(map, Filter.INCLUDE);                  setStyledFeatures(styledFeatures);
96          }          }
97    
98          /**          /**
99           * Creates a new table model for a styled map.           * This overwritten method filters the values for NODATA-values defined in
100           *           * the {@link AttributeMetadataImpl}
101           * @param map           */
102           *            the styled map          @Override
103           * @param filter          public Object getValueAt(int row, int col) {
104           *            filter applied to the table                  Object rawValue = super.getValueAt(row, col);
105           */                  return amdMap.sortedValuesVisibleOnly().get(col).fiterNodata(rawValue);
106          public StyledFeatureCollectionTableModel(StyledFeatureSourceInterface map,          }
107                          Filter filter) {          
108                  super();          /**
109                  setFeatureCollection(map, filter);           * Sets a new data source for the table.
110          }           *
111             * @param fs
112          /**           *            the feature source
113           * Sets a new data source for the table.           * @param amdm
114           *           *            {@link AttributeMetadataImpl}-Map to define the visible attributes
115           * @param fs           *            and translation
116           *            the feature source           */
117           * @param amd          protected void setFeatureSource(
118           *            {@link AttributeMetaData}-Map to define the visible attributes                          FeatureSource<SimpleFeatureType, SimpleFeature> fs,
119           *            and translation                          AttributeMetadataMap<? extends AttributeMetadata> amdm, Filter filter) throws Exception {
120           */  
121          protected void setFeatureSource(FeatureSource fs,                  if (filter == null)
122                          Map<Integer, AttributeMetaData> amd, Filter filter)                          filter = Filter.INCLUDE;
123                          throws Exception {  
124                  if (filter == null)                  // this.featureSource = fs;
125                          filter = Filter.INCLUDE;                  this.filter = filter;
126                    this.amdMap = amdm;
127                  this.featureSource = fs;                  this.amdMapVisibleOnly = amdMap.sortedValuesVisibleOnly();
128                  this.filter = filter;  
129                  this.origAMD = amd;                  FeatureCollection<SimpleFeatureType, SimpleFeature> fc = null;
130                  this.visibleAMD = null;                  if (fs != null) {
131    
132                  FeatureCollection fc = null;                          bounds = fs.getBounds();
133                  if (fs != null) {  
134                            final SimpleFeatureType schema = fs.getSchema();
135                          bounds = fs.getBounds();                          Query query = new DefaultQuery(schema.getTypeName(), filter);
136                            if (amdm != null) {
137                          Query query = new DefaultQuery(fs.getSchema().getTypeName(), filter);                                  Vector<String> visibleAttrNames = new Vector<String>();
138                          if (amd != null) {  
139                                  // determine the names of the visible Attributes                                  // Add the column with the geometry (usually "the_geom") always
140                                  this.visibleAMD = StyledMapUtil.getVisibleAttributeMetaData(                                  visibleAttrNames.add(schema.getGeometryDescriptor()
141                                                  amd, true);                                                  .getLocalName());
142                                  Vector<String> visibleAttrNames = new Vector<String>();  
143                                  // Add the column with the geometry (usually "the_geom")                                  // Add other visible attributes as ordered by weights
144                                  visibleAttrNames.add(fs.getSchema().getDefaultGeometry()                                  for (AttributeMetadata a : amdMapVisibleOnly) {
145                                                  .getLocalName());                                          visibleAttrNames.add(a.getLocalName());
146                                  for (int attrIdx : visibleAMD.keySet()) {                                  }
147    
148                                          /**                                  // Tested with 2.6.x trunk from 2009-11-26 and it now works. So
149                                           * If the user removed columns from the schema of the DBF                                  // we only request the properties we need!
150                                           * file, there might exist AttributeMetaData for columns                                  // /**
151                                           * that don't exists. We check here to avoid an                                  // * I got NPEs when properties contained only [the_geom]
152                                           * ArrayOutOfIndex.                                  // ?!??!!??
153                                           */                                  // */
154                                          if (attrIdx < fs.getSchema().getAttributeCount()) {                                  // if (properties.length > 1) {
155                                                  final AttributeType attributeTypeAtIdx = fs.getSchema()                                  query = new DefaultQuery(schema.getTypeName(), filter,
156                                                                  .getAttributeType(attrIdx);                                                  visibleAttrNames.toArray(new String[] {}));
157                                                  visibleAttrNames.add(attributeTypeAtIdx.getLocalName());                                  // } else {
158                                          } else {                                  // query = new DefaultQuery(schema.getTypeName(), filter);
159                                                  LOGGER.warn("AttributeMetaData has been found for columnIdx="+attrIdx+", but fs.getSchema().getAttributeCount() = "+fs.getSchema().getAttributeCount()+". Ignored.");                                  // }
160                                          }                          }
161                                  }                          fc = fs.getFeatures(query);
162                    }
163                                  // create a query for the visible attributes                  setFeatureCollection(fc);
164                                  String[] properties = visibleAttrNames.toArray(new String[0]);          }
165    
166                                  LOGGER.debug("Query contains the following attributes: "          /**
167                                                  + visibleAttrNames);           * Converts the {@code StyledFeatureCollection} to a {@code FeatureSource}
168             * and sets this as the new data source for the table.
169                                  query = new DefaultQuery(fs.getSchema().getTypeName(), filter,           *
170                                                  properties);           * @param fs
171                          }           *            the feature source
172                          fc = fs.getFeatures(query);           * @param amd
173             *            {@link AttributeMetadataImpl}-Map to define the visible attributes
174                          // FAILS:!!!, even with query = new           *            and translation
175                          // DefaultQuery(fs.getSchema().getTypeName(), filter);           */
176                          // java.lang.UnsupportedOperationException: Unknown feature          public void setStyledFeatures(StyledFeaturesInterface<?> styledFeatures) {
177                          // attribute: PQM_MOD                  try {
178                          // at                          if (styledFeatures == null)
179                          // schmitzm.geotools.feature.FeatureOperationTree.evaluate(FeatureOperationTree.java:93)                                  setFeatureSource(null, null, null);
180                          // bounds = fc.getBounds();                          else {
181                          // SK, 17.4.2009                                  setFeatureSource(styledFeatures.getFeatureSource(),
182                          //                                                        styledFeatures.getAttributeMetaDataMap(),
183                          // System.out.println("Filter = "+filter);                                                  styledFeatures.getFilter());
184                          // System.out.println("Size of FC = "+fc.size());                          }
185                          // System.out.println("anz att= "+fc.getNumberOfAttributes());                  } catch (Exception err) {
186                  }                          throw new RuntimeException(err);
187                  setFeatureCollection(fc);                  }
188          }          }
189    
190          /**          /**
191           * Converts the {@code StyledFeatureCollection} to a {@code FeatureSource}           * After calling {@code super.reorganize(.)} this method replaced the column
192           * and sets this as the new data source for the table.           * descriptions with the titles of the {@code AttributeMetaData}.
193           *           *
194           * @param fs           * @param fireTableStructureChanged
195           *            the feature source           *            indicates whether a table event is initiated after reorganize
196           * @param amd           */
197           *            {@link AttributeMetaData}-Map to define the visible attributes          @Override
198           *            and translation          protected void reorganize(boolean fireTableStructureChanged) {
199           */  
200          public void setFeatureCollection(StyledFeatureCollectionInterface map,                  featureArray = FeatureUtil.featuresToArray(featureTable);
201                          Filter filter) {                  if (featureArray == null || featureArray.length == 0) {
202                  this.map = map;                          colNames = new String[0];
203                  try {                          colTooltips = new String[0]; // Only set and used in
204                          if (map == null)                          // StyledFeatureCollectionTableModel
205                                  setFeatureSource(null, null, null);                          colClass = new Class[0];
206                          else {                  } else {
207                                  FeatureCollection fc = map.getGeoObject();                          // Struktur der Tabelle vom AttributeMetaDtaaMap übernehmen
208                                  String fcName = fc.getSchema().getTypeName();                          SimpleFeatureType schema = featureArray[0].getFeatureType();
209                                  FeatureSource fs = new MemoryDataStore(fc)                          // Pruefen, welche Attribute angezeigt werden
210                                                  .getFeatureSource(fcName);                          attrTypes.clear();
211                                  setFeatureSource(fs, map.getAttributeMetaDataMap(), filter);                          for (AttributeMetadata amd : amdMapVisibleOnly) {
212                          }                                  AttributeDescriptor type = schema.getDescriptor(amd.getName());
213                  } catch (Exception err) {                                  if (attrFilter == null || attrFilter.accept(type))
214                          throw new RuntimeException(err);                                          attrTypes.add(type);
215                  }                          }
216          }                          // Namen und Attribut-Indizes der angezeigten Spalten ermitteln
217                            colNames = new String[attrTypes.size()];
218          /**                          colTooltips = new String[attrTypes.size()]; // Only set and used in
219           * Sets the {@code StyledFeatureCollection} as new data source for the                          // StyledFeatureCollectionTableModel
220           * table.                          colClass = new Class[attrTypes.size()];
221           *                          attrIdxForCol = new int[attrTypes.size()];
222           * @param fs                          for (int i = 0; i < colNames.length; i++) {
223           *            the feature source                                  AttributeDescriptor descriptor = schema
224           * @param amd                                                  .getDescriptor(amdMapVisibleOnly.get(i).getName());
225           *            {@link AttributeMetaData}-Map to define the visible attributes  
226           *            and translation                                  // Not so nice in 26: find the index of an attribute...
227           */                                  int idx = schema.getAttributeDescriptors().indexOf(descriptor);
228          public void setFeatureCollection(StyledFeatureSourceInterface map,                                  attrIdxForCol[i] = idx;
229                          Filter filter) {  
230                  this.map = map;                                  String attName = schema.getAttributeDescriptors().get(idx)
231                  try {                                                  .getLocalName();
232                          if (map == null)                                  colNames[i] = amdMap.get(attName).getTitle().toString();
233                                  setFeatureSource(null, null, null);                                  AttributeMetadata amd = amdMap.get(attName);
234                          else                                  colTooltips[i] = "<html>" + amd.getDesc().toString() + "<br>"
235                                  setFeatureSource(map.getGeoObject(), map                                                  + amd.getName() + "</html>";
236                                                  .getAttributeMetaDataMap(), filter);                                  colClass[i] = schema.getAttributeDescriptors().get(idx)
237                  } catch (Exception err) {                                                  .getType().getBinding();
238                          throw new RuntimeException(err);                          }
239                  }                  }
240          }  
241                    // store feature indexes in HashMap to optimize findFeature(.)
242          /**                  featureIdx = new HashMap<String, Integer>();
243           * Resets the filter for the table.                  for (int i = 0; i < featureArray.length; i++)
244           *                          if (featureArray[i] != null)
245           * @param filter                                  featureIdx.put(featureArray[i].getID(), i);
246           *            a filter                  //
247           */                  // // translate the column names
248          public void setFilter(Filter filter) {                  // if (amdMap != null) {
249                  try {                  // for (int i = 0; i < colNames.length; i++) {
250                          setFeatureSource(this.featureSource, this.origAMD, filter);                  // colTooltips[i] = amdMap.get(colNames[i]).getDesc().toString()
251                  } catch (Exception err) {                  // + "<br>" + colNames[i];
252                          LOGGER.error("Setting the filter of the table model", err);                  // colNames[i] = amdMap.get(colNames[i]).getTitle().toString();
253                          throw new RuntimeException(err);                  //
254                  }                  // }
255          }                  // }
256                    if (fireTableStructureChanged)
257          /**                          fireTableStructureChanged();
258           * @return <code>Filter.INCLUDE</code> or the {@link Filter} applied to the  
259           *         Features          }
260           */  
261          public Filter getFilter() {          /**
262                  return this.filter;           * @return Cached bounds for the whole dataset (without applying the filter)
263          }           *         or <code>null</code>
264             */
265          /**          public Envelope getBounds() {
266           * After calling {@code super.reorganize(.)} this method replaced the column                  return bounds;
267           * descriptions with the titles of the {@code AttributeMetaData}.          }
268           *  }
          * @param fireTableStructureChanged  
          *            indicates whether a table event is initiated after reorganize  
          */  
         @Override  
         protected void reorganize(boolean fireTableStructureChanged) {  
                 super.reorganize(false);  
                 // translate the column names  
                 if (visibleAMD != null) {  
                         Iterator<Integer> keys = visibleAMD.keySet().iterator();  
                         for (int i = 0; i < colNames.length && keys.hasNext(); i++) {  
                                 Translation title = visibleAMD.get(keys.next()).getTitle();  
                                 if (!I8NUtil.isEmpty(title)) {  
                                         // System.out.println("set colname " + i + " to " +  
                                         // title.toString());  
                                         colNames[i] = title.toString();  
                                 }  
                         }  
                 }  
                 if (fireTableStructureChanged)  
                         fireTableStructureChanged();  
         }  
   
         /**  
          * @return Cached bounds for the whole dataset (without applying the filter)  
          *         or <code>null</code>  
          */  
         public Envelope getBounds() {  
                 return bounds;  
         }  
 }  

Legend:
Removed from v.168  
changed lines
  Added in v.769

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26