/[schmitzm]/branches/2.2.x/src/skrueger/geotools/StyledFeatureCollectionTableModel.java
ViewVC logotype

Diff of /branches/2.2.x/src/skrueger/geotools/StyledFeatureCollectionTableModel.java

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

trunk/src/skrueger/geotools/StyledFeatureCollectionTableModel.java revision 225 by alfonx, Wed Jul 15 08:05:22 2009 UTC branches/2.2.x/src/skrueger/geotools/StyledFeatureCollectionTableModel.java revision 1055 by alfonx, Thu Sep 23 17:38:23 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) {                                  String geomColumnLocalName = schema.getGeometryDescriptor()
142                                  // determine the names of the visible Attributes                                                  .getLocalName();
143                                  this.visibleAMD = StyledLayerUtil.getVisibleAttributeMetaData(                                  visibleAttrNames.add(geomColumnLocalName);
144                                                  amd, true);  
145                                  Vector<String> visibleAttrNames = new Vector<String>();                                  // Add other visible attributes as ordered by weights
146                                  // Add the column with the geometry (usually "the_geom")                                  for (AttributeMetadataInterface a : amdMapVisibleOnly) {
147                                  visibleAttrNames.add(fs.getSchema().getDefaultGeometry()                                          visibleAttrNames.add(a.getLocalName());
148                                                  .getLocalName());                                  }
149                                  for (int attrIdx : visibleAMD.keySet()) {  
150                                    // Tested with 2.6.x trunk from 2009-11-26 and it now works. So
151                                          /**                                  // we only request the properties we need!
152                                           * If the user removed columns from the schema of the DBF                                  // /**
153                                           * file, there might exist AttributeMetaData for columns                                  // * I got NPEs when properties contained only [the_geom]
154                                           * that don't exists. We check here to avoid an                                  // ?!??!!??
155                                           * ArrayOutOfIndex.                                  // */
156                                           */                                  // if (properties.length > 1) {
157                                          if (attrIdx < fs.getSchema().getAttributeCount()) {                                  query = new DefaultQuery(schema.getTypeName(), filter,
158                                                  final AttributeType attributeTypeAtIdx = fs.getSchema()                                                  visibleAttrNames.toArray(new String[] {}));
159                                                                  .getAttributeType(attrIdx);                                  // } else {
160                                                  visibleAttrNames.add(attributeTypeAtIdx.getLocalName());                                  // query = new DefaultQuery(schema.getTypeName(), filter);
161                                          } else {                                  // }
162                                                  LOGGER.warn("AttributeMetaData has been found for columnIdx="+attrIdx+", but fs.getSchema().getAttributeCount() = "+fs.getSchema().getAttributeCount()+". Ignored.");                                  
163                                          }                                  System.out.println(query.getPropertyNames());
164                                  }                          }
165                            fc = fs.getFeatures(query);
166                                  // create a query for the visible attributes                  }
167                                  String[] properties = visibleAttrNames.toArray(new String[0]);                  setFeatureCollection(fc);
168            }
169                                  LOGGER.debug("Query contains the following attributes: "  
170                                                  + visibleAttrNames);          /**
171             * Converts the {@code StyledFeatureCollection} to a {@code FeatureSource}
172                                  query = new DefaultQuery(fs.getSchema().getTypeName(), filter,           * and sets this as the new data source for the table.
173                                                  properties);           *
174                          }           * @param fs
175                          fc = fs.getFeatures(query);           *            the feature source
176             * @param amd
177                          // FAILS:!!!, even with query = new           *            {@link AttributeMetadataImpl}-Map to define the visible attributes
178                          // DefaultQuery(fs.getSchema().getTypeName(), filter);           *            and translation
179                          // java.lang.UnsupportedOperationException: Unknown feature           */
180                          // attribute: PQM_MOD          public void setStyledFeatures(StyledFeaturesInterface<?> styledFeatures) {
181                          // at                  try {
182                          // schmitzm.geotools.feature.FeatureOperationTree.evaluate(FeatureOperationTree.java:93)                          if (styledFeatures == null)
183                          // bounds = fc.getBounds();                                  setFeatureSource(null, null, null);
184                          // SK, 17.4.2009                          else {
185                          //                                        setFeatureSource(styledFeatures.getFeatureSource(),
186                          // System.out.println("Filter = "+filter);                                                  styledFeatures.getAttributeMetaDataMap(),
187                          // System.out.println("Size of FC = "+fc.size());                                                  styledFeatures.getFilter());
188                          // System.out.println("anz att= "+fc.getNumberOfAttributes());                          }
189                  }                  } catch (Exception err) {
190                  setFeatureCollection(fc);                          throw new RuntimeException(err);
191          }                  }
192            }
193          /**  
194           * Converts the {@code StyledFeatureCollection} to a {@code FeatureSource}          /**
195           * and sets this as the new data source for the table.           * After calling {@code super.reorganize(.)} this method replaced the column
196           *           * descriptions with the titles of the {@code AttributeMetaData}.
197           * @param fs           *
198           *            the feature source           * @param fireTableStructureChanged
199           * @param amd           *            indicates whether a table event is initiated after reorganize
200           *            {@link AttributeMetaData}-Map to define the visible attributes           */
201           *            and translation          @Override
202           */          protected void reorganize(boolean fireTableStructureChanged) {
203          public void setFeatureCollection(StyledFeaturesInterface layer,  
204                          Filter filter) {                  featureArray = FeatureUtil.featuresToArray(featureTable);
205                  this.layer = layer;                  if (featureArray == null || featureArray.length == 0) {
206                  try {                          colNames = new String[0];
207                          if (layer == null)                          colTooltips = new String[0]; // Only set and used in
208                                  setFeatureSource(null, null, null);                          // StyledFeatureCollectionTableModel
209                          else {                          colClass = new Class[0];
210                                  FeatureCollection fc = layer.getFeatureCollection();                  } else {
211                                  String fcName = fc.getSchema().getTypeName();                          // Struktur der Tabelle vom AttributeMetaDtaaMap übernehmen
212                                  FeatureSource fs = new MemoryDataStore(fc)                          SimpleFeatureType schema = featureArray[0].getFeatureType();
213                                                  .getFeatureSource(fcName);                          // Pruefen, welche Attribute angezeigt werden
214                                  setFeatureSource(fs, layer.getAttributeMetaDataMap(), filter);                          attrTypes.clear();
215                          }                          for (AttributeMetadataInterface amd : amdMapVisibleOnly) {
216                  } catch (Exception err) {                                  Name name = amd.getName();
217                          throw new RuntimeException(err);                  AttributeDescriptor type = schema.getDescriptor(name);
218                  }                  // if type can not be determined by complete name,
219          }                  // try only the local name
220                    if ( type == null )
221          /**                    type = schema.getDescriptor(name.getLocalPart());
222           * Sets the {@code StyledFeatureCollection} as new data source for the                                  if (attrFilter == null || attrFilter.accept(type))
223           * table.                                          attrTypes.add(type);
224           *                          }
225           * @param fs                          // Namen und Attribut-Indizes der angezeigten Spalten ermitteln
226           *            the feature source                          colNames = new String[attrTypes.size()];
227           * @param amd                          colTooltips = new String[attrTypes.size()]; // Only set and used in
228           *            {@link AttributeMetaData}-Map to define the visible attributes                          // StyledFeatureCollectionTableModel
229           *            and translation                          colClass = new Class[attrTypes.size()];
230           */                          attrIdxForCol = new int[attrTypes.size()];
231          public void setFeatureCollection(StyledFeatureSourceInterface layer,                          for (int i = 0; i < colNames.length; i++) {
232                          Filter filter) {                                  Name name = amdMapVisibleOnly.get(i).getName();
233                  this.layer = layer;                  AttributeDescriptor descriptor = schema.getDescriptor(name);
234                  try {                  // if type can not be determined by complete name,
235                          if (layer == null)                  // try only the local name
236                                  setFeatureSource(null, null, null);                  if ( descriptor == null )
237                          else                    descriptor = schema.getDescriptor(name.getLocalPart());
238                                  setFeatureSource(layer.getGeoObject(), layer  
239                                                  .getAttributeMetaDataMap(), filter);                                  // Not so nice in 26: find the index of an attribute...
240                  } catch (Exception err) {                                  int idx = schema.getAttributeDescriptors().indexOf(descriptor);
241                          throw new RuntimeException(err);                                  attrIdxForCol[i] = idx;
242                  }  
243          }                                  String attName = schema.getAttributeDescriptors().get(idx)
244                                                    .getLocalName();
245          /**                                  colNames[i] = amdMap.get(attName).getTitle().toString();
246           * Resets the filter for the table.                                  AttributeMetadataInterface amd = amdMap.get(attName);
247           *                                  colTooltips[i] = "<html>" + amd.getDesc().toString() + "<br>"
248           * @param filter                                                  + amd.getName() + "</html>";
249           *            a filter                                  colClass[i] = schema.getAttributeDescriptors().get(idx)
250           */                                                  .getType().getBinding();
251          public void setFilter(Filter filter) {                          }
252                  try {                  }
253                          setFeatureSource(this.featureSource, this.origAMD, filter);  
254                  } catch (Exception err) {                  // store feature indexes in HashMap to optimize findFeature(.)
255                          LOGGER.error("Setting the filter of the table model", err);                  featureIdx = new HashMap<String, Integer>();
256                          throw new RuntimeException(err);                  for (int i = 0; i < featureArray.length; i++)
257                  }                          if (featureArray[i] != null)
258          }                                  featureIdx.put(featureArray[i].getID(), i);
259                    //
260          /**                  // // translate the column names
261           * @return <code>Filter.INCLUDE</code> or the {@link Filter} applied to the                  // if (amdMap != null) {
262           *         Features                  // for (int i = 0; i < colNames.length; i++) {
263           */                  // colTooltips[i] = amdMap.get(colNames[i]).getDesc().toString()
264          public Filter getFilter() {                  // + "<br>" + colNames[i];
265                  return this.filter;                  // colNames[i] = amdMap.get(colNames[i]).getTitle().toString();
266          }                  //
267                    // }
268          /**                  // }
269           * After calling {@code super.reorganize(.)} this method replaced the column                  if (fireTableStructureChanged)
270           * descriptions with the titles of the {@code AttributeMetaData}.                          fireTableStructureChanged();
271           *  
272           * @param fireTableStructureChanged          }
273           *            indicates whether a table event is initiated after reorganize  
274           */          /**
275          @Override           * @return Cached bounds for the whole dataset (without applying the filter)
276          protected void reorganize(boolean fireTableStructureChanged) {           *         or <code>null</code>
277                  super.reorganize(false);           */
278                  // translate the column names          public Envelope getBounds() {
279                  if (visibleAMD != null) {                  return bounds;
280                          Iterator<Integer> keys = visibleAMD.keySet().iterator();          }
281                          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.1055

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26