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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26