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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26