/[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 224 by alfonx, Tue Jul 14 15:57:19 2009 UTC revision 685 by alfonx, Wed Feb 10 15:04:02 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 StyledLayerInterface 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);  
50          /** Holds the data source as styled map. */  import com.vividsolutions.jts.geom.Envelope;
51          protected StyledLayerInterface<?> layer = null;  
52          /** Contains only the visible elements of the {@link AttributeMetaData}-Map */  /**
53          protected Map<Integer, AttributeMetaData> visibleAMD = null;   * This class extends the the {@link FeatureCollectionTableModel} with the
54          /** Holds the data source for the table as {@code FeatureSource}. */   * functionalities of the {@link AttributeMetadata}.
55          protected FeatureSource featureSource = null;   * <ul>
56          /** Contains the complete {@link AttributeMetaData}-Map of the styled layer. */   * <li>column names are translated according to
57          protected Map<Integer, AttributeMetaData> origAMD = null;   * {@link AttributeMetadata#getTitle()}</li>
58          /** Holds the current filter on the table */   * <li>columns are hidden according to {@link AttributeMetaData#isVisible()()}</li>
59          protected Filter filter = null;   * <li>Any filter defined in the {@link StyledFeaturesInterface} will be
60          /** Holds the Bounds for all features. Only set once during the constructor **/   * applied.</li>
61          protected Envelope bounds;   * </ul>
62     *
63             * @author Stefan A. Krüger
64     */
65          /**  public class StyledFeatureCollectionTableModel extends
66           * Creates a new table model for a styled map.                  FeatureCollectionTableModel {
67           *          final static private Logger LOGGER = Logger
68           * @param layer                          .getLogger(StyledFeatureCollectionTableModel.class);
69           *            the styled layer          /** Contains the complete {@link AttributeMetadata}-Map of the styled layer. */
70           */          protected AttributeMetadataMap amdMap = null;
71          public StyledFeatureCollectionTableModel(          /** Holds the current filter on the table */
72                          StyledFeatureCollectionInterface layer) {          protected Filter filter = null;
73                  this(layer, Filter.INCLUDE);          /** Holds the Bounds for all features. Only set once during the constructor **/
74          }          protected Envelope bounds;
75            /**
76          /**           * Tooltips für die Spaltennamen. Wird nur beim Aufruf von
77           * Creates a new table model for a styled map.           * {@link #reorganize} befuellt.
78           *           */
79           * @param layer          protected String[] colTooltips = null;
80           *            the styled layer  
81           * @param filter          /** A cache for the #sortedValuesVisibleOnly() **/
82           *            filter applied to the table          protected List<AttributeMetadata> amdMapVisibleOnly = null;
83           */  
84          public StyledFeatureCollectionTableModel(          /**
85                          StyledFeatureCollectionInterface layer, Filter filter) {           * Creates a new table model for a styled layer.
86                  super();           *
87                  setFeatureCollection(layer, filter);           * @param styledFeatures
88          }           *            the styled layer
89             * @param filter
90             *            filter applied to the table
91          /**           */
92           * Creates a new table model for a styled map.          public StyledFeatureCollectionTableModel(
93           *                          StyledFeaturesInterface<?> styledFeatures) {
94           * @param layer                  setStyledFeatures(styledFeatures);
95           *            the styled layer          }
96           */  
97          public StyledFeatureCollectionTableModel(StyledFeaturesInterface layer) {          /**
98                  this(layer, Filter.INCLUDE);           * This overwritten method filters the values for NODATA-values defined in
99          }           * the {@link AttributeMetadata}
100             */
101          /**          @Override
102           * Creates a new table model for a styled map.          public Object getValueAt(int row, int col) {
103           *                  Object rawValue = super.getValueAt(row, col);
104           * @param layer                  return amdMap.sortedValuesVisibleOnly().get(col).fiterNodata(rawValue);
105           *            the styled layer          }
106           * @param filter          
107           *            filter applied to the table          /**
108           */           * Sets a new data source for the table.
109          public StyledFeatureCollectionTableModel(StyledFeaturesInterface layer,           *
110                          Filter filter) {           * @param fs
111                  super();           *            the feature source
112                  setFeatureCollection(layer, filter);           * @param amdm
113          }           *            {@link AttributeMetadata}-Map to define the visible attributes
114             *            and translation
115          /**           */
116           * Sets a new data source for the table.          protected void setFeatureSource(
117           *                          FeatureSource<SimpleFeatureType, SimpleFeature> fs,
118           * @param fs                          AttributeMetadataMap amdm, Filter filter) throws Exception {
119           *            the feature source  
120           * @param amd                  if (filter == null)
121           *            {@link AttributeMetaData}-Map to define the visible attributes                          filter = Filter.INCLUDE;
122           *            and translation  
123           */                  // this.featureSource = fs;
124          protected void setFeatureSource(FeatureSource fs,                  this.filter = filter;
125                          Map<Integer, AttributeMetaData> amd, Filter filter)                  this.amdMap = amdm;
126                          throws Exception {                  this.amdMapVisibleOnly = amdMap.sortedValuesVisibleOnly();
127                  if (filter == null)  
128                          filter = Filter.INCLUDE;                  FeatureCollection<SimpleFeatureType, SimpleFeature> fc = null;
129                    if (fs != null) {
130                  this.featureSource = fs;  
131                  this.filter = filter;                          bounds = fs.getBounds();
132                  this.origAMD = amd;  
133                  this.visibleAMD = null;                          final SimpleFeatureType schema = fs.getSchema();
134                            Query query = new DefaultQuery(schema.getTypeName(), filter);
135                  FeatureCollection fc = null;                          if (amdm != null) {
136                  if (fs != null) {                                  Vector<String> visibleAttrNames = new Vector<String>();
137    
138                          bounds = fs.getBounds();                                  // Add the column with the geometry (usually "the_geom") always
139                                    visibleAttrNames.add(schema.getGeometryDescriptor()
140                          Query query = new DefaultQuery(fs.getSchema().getTypeName(), filter);                                                  .getLocalName());
141                          if (amd != null) {  
142                                  // determine the names of the visible Attributes                                  // Add other visible attributes as ordered by weights
143                                  this.visibleAMD = StyledLayerUtil.getVisibleAttributeMetaData(                                  for (AttributeMetadata a : amdMapVisibleOnly) {
144                                                  amd, true);                                          visibleAttrNames.add(a.getLocalName());
145                                  Vector<String> visibleAttrNames = new Vector<String>();                                  }
146                                  // Add the column with the geometry (usually "the_geom")  
147                                  visibleAttrNames.add(fs.getSchema().getDefaultGeometry()                                  // Tested with 2.6.x trunk from 2009-11-26 and it now works. So
148                                                  .getLocalName());                                  // we only request the properties we need!
149                                  for (int attrIdx : visibleAMD.keySet()) {                                  // /**
150                                    // * I got NPEs when properties contained only [the_geom]
151                                          /**                                  // ?!??!!??
152                                           * If the user removed columns from the schema of the DBF                                  // */
153                                           * file, there might exist AttributeMetaData for columns                                  // if (properties.length > 1) {
154                                           * that don't exists. We check here to avoid an                                  query = new DefaultQuery(schema.getTypeName(), filter,
155                                           * ArrayOutOfIndex.                                                  visibleAttrNames.toArray(new String[] {}));
156                                           */                                  // } else {
157                                          if (attrIdx < fs.getSchema().getAttributeCount()) {                                  // query = new DefaultQuery(schema.getTypeName(), filter);
158                                                  final AttributeType attributeTypeAtIdx = fs.getSchema()                                  // }
159                                                                  .getAttributeType(attrIdx);                          }
160                                                  visibleAttrNames.add(attributeTypeAtIdx.getLocalName());                          fc = fs.getFeatures(query);
161                                          } else {                  }
162                                                  LOGGER.warn("AttributeMetaData has been found for columnIdx="+attrIdx+", but fs.getSchema().getAttributeCount() = "+fs.getSchema().getAttributeCount()+". Ignored.");                  setFeatureCollection(fc);
163                                          }          }
164                                  }  
165            /**
166                                  // create a query for the visible attributes           * Converts the {@code StyledFeatureCollection} to a {@code FeatureSource}
167                                  String[] properties = visibleAttrNames.toArray(new String[0]);           * and sets this as the new data source for the table.
168             *
169                                  LOGGER.debug("Query contains the following attributes: "           * @param fs
170                                                  + visibleAttrNames);           *            the feature source
171             * @param amd
172                                  query = new DefaultQuery(fs.getSchema().getTypeName(), filter,           *            {@link AttributeMetadata}-Map to define the visible attributes
173                                                  properties);           *            and translation
174                          }           */
175                          fc = fs.getFeatures(query);          public void setStyledFeatures(StyledFeaturesInterface<?> styledFeatures) {
176                    try {
177                          // FAILS:!!!, even with query = new                          if (styledFeatures == null)
178                          // DefaultQuery(fs.getSchema().getTypeName(), filter);                                  setFeatureSource(null, null, null);
179                          // java.lang.UnsupportedOperationException: Unknown feature                          else {
180                          // attribute: PQM_MOD                                  setFeatureSource(styledFeatures.getFeatureSource(),
181                          // at                                                  styledFeatures.getAttributeMetaDataMap(),
182                          // schmitzm.geotools.feature.FeatureOperationTree.evaluate(FeatureOperationTree.java:93)                                                  styledFeatures.getFilter());
183                          // bounds = fc.getBounds();                          }
184                          // SK, 17.4.2009                  } catch (Exception err) {
185                          //                                throw new RuntimeException(err);
186                          // System.out.println("Filter = "+filter);                  }
187                          // System.out.println("Size of FC = "+fc.size());          }
188                          // System.out.println("anz att= "+fc.getNumberOfAttributes());  
189                  }          /**
190                  setFeatureCollection(fc);           * After calling {@code super.reorganize(.)} this method replaced the column
191          }           * descriptions with the titles of the {@code AttributeMetaData}.
192             *
193          /**           * @param fireTableStructureChanged
194           * Converts the {@code StyledFeatureCollection} to a {@code FeatureSource}           *            indicates whether a table event is initiated after reorganize
195           * and sets this as the new data source for the table.           */
196           *          @Override
197           * @param fs          protected void reorganize(boolean fireTableStructureChanged) {
198           *            the feature source  
199           * @param amd                  featureArray = FeatureUtil.featuresToArray(featureTable);
200           *            {@link AttributeMetaData}-Map to define the visible attributes                  if (featureArray == null || featureArray.length == 0) {
201           *            and translation                          colNames = new String[0];
202           */                          colTooltips = new String[0]; // Only set and used in
203          public void setFeatureCollection(StyledFeaturesInterface layer,                          // StyledFeatureCollectionTableModel
204                          Filter filter) {                          colClass = new Class[0];
205                  this.layer = layer;                  } else {
206                  try {                          // Struktur der Tabelle vom AttributeMetaDtaaMap übernehmen
207                          if (layer == null)                          SimpleFeatureType schema = featureArray[0].getFeatureType();
208                                  setFeatureSource(null, null, null);                          // Pruefen, welche Attribute angezeigt werden
209                          else {                          attrTypes.clear();
210                                  FeatureCollection fc = layer.getFeatureCollection();                          for (AttributeMetadata amd : amdMapVisibleOnly) {
211                                  String fcName = fc.getSchema().getTypeName();                                  AttributeDescriptor type = schema.getDescriptor(amd.getName());
212                                  FeatureSource fs = new MemoryDataStore(fc)                                  if (attrFilter == null || attrFilter.accept(type))
213                                                  .getFeatureSource(fcName);                                          attrTypes.add(type);
214                                  setFeatureSource(fs, layer.getAttributeMetaDataMap(), filter);                          }
215                          }                          // Namen und Attribut-Indizes der angezeigten Spalten ermitteln
216                  } catch (Exception err) {                          colNames = new String[attrTypes.size()];
217                          throw new RuntimeException(err);                          colTooltips = new String[attrTypes.size()]; // Only set and used in
218                  }                          // StyledFeatureCollectionTableModel
219          }                          colClass = new Class[attrTypes.size()];
220                            attrIdxForCol = new int[attrTypes.size()];
221          /**                          for (int i = 0; i < colNames.length; i++) {
222           * Sets the {@code StyledFeatureCollection} as new data source for the                                  AttributeDescriptor descriptor = schema
223           * table.                                                  .getDescriptor(amdMapVisibleOnly.get(i).getName());
224           *  
225           * @param fs                                  // Not so nice in 26: find the index of an attribute...
226           *            the feature source                                  int idx = schema.getAttributeDescriptors().indexOf(descriptor);
227           * @param amd                                  attrIdxForCol[i] = idx;
228           *            {@link AttributeMetaData}-Map to define the visible attributes  
229           *            and translation                                  String attName = schema.getAttributeDescriptors().get(idx)
230           */                                                  .getLocalName();
231          public void setFeatureCollection(StyledFeatureSourceInterface layer,                                  colNames[i] = amdMap.get(attName).getTitle().toString();
232                          Filter filter) {                                  AttributeMetadata amd = amdMap.get(attName);
233                  this.layer = layer;                                  colTooltips[i] = "<html>" + amd.getDesc().toString() + "<br>"
234                  try {                                                  + amd.getName() + "</html>";
235                          if (layer == null)                                  colClass[i] = schema.getAttributeDescriptors().get(idx)
236                                  setFeatureSource(null, null, null);                                                  .getType().getBinding();
237                          else                          }
238                                  setFeatureSource(layer.getGeoObject(), layer                  }
239                                                  .getAttributeMetaDataMap(), filter);  
240                  } catch (Exception err) {                  // store feature indexes in HashMap to optimize findFeature(.)
241                          throw new RuntimeException(err);                  featureIdx = new HashMap<String, Integer>();
242                  }                  for (int i = 0; i < featureArray.length; i++)
243          }                          if (featureArray[i] != null)
244                                    featureIdx.put(featureArray[i].getID(), i);
245          /**                  //
246           * Resets the filter for the table.                  // // translate the column names
247           *                  // if (amdMap != null) {
248           * @param filter                  // for (int i = 0; i < colNames.length; i++) {
249           *            a filter                  // colTooltips[i] = amdMap.get(colNames[i]).getDesc().toString()
250           */                  // + "<br>" + colNames[i];
251          public void setFilter(Filter filter) {                  // colNames[i] = amdMap.get(colNames[i]).getTitle().toString();
252                  try {                  //
253                          setFeatureSource(this.featureSource, this.origAMD, filter);                  // }
254                  } catch (Exception err) {                  // }
255                          LOGGER.error("Setting the filter of the table model", err);                  if (fireTableStructureChanged)
256                          throw new RuntimeException(err);                          fireTableStructureChanged();
257                  }  
258          }          }
259    
260          /**          /**
261           * @return <code>Filter.INCLUDE</code> or the {@link Filter} applied to the           * @return Cached bounds for the whole dataset (without applying the filter)
262           *         Features           *         or <code>null</code>
263           */           */
264          public Filter getFilter() {          public Envelope getBounds() {
265                  return this.filter;                  return bounds;
266          }          }
267    }
         /**  
          * After calling {@code super.reorganize(.)} this method replaced the column  
          * descriptions with the titles of the {@code AttributeMetaData}.  
          *  
          * @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.224  
changed lines
  Added in v.685

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26