/[schmitzm]/branches/2.3.KECK/src/skrueger/geotools/StyledFeatureCollectionTableModel.java
ViewVC logotype

Diff of /branches/2.3.KECK/src/skrueger/geotools/StyledFeatureCollectionTableModel.java

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

trunk/src/skrueger/geotools/StyledFeatureCollectionTableModel.java revision 62 by alfonx, Fri Apr 17 18:56:17 2009 UTC branches/2.0-RC2/src/skrueger/geotools/StyledFeatureCollectionTableModel.java revision 681 by alfonx, Tue Feb 9 22:08:26 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.TreeMap;   *
16  import java.util.Vector;   * This program is distributed in the hope that it will be useful,
17     * 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.FeatureCollection;   * along with this program; if not, write to the Free Software
23  import org.opengis.filter.Filter;   * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
24     * or try this link: http://www.gnu.org/licenses/lgpl.html
25  import com.vividsolutions.jts.geom.Envelope;   *
26     * Contributors:
27  import schmitzm.geotools.gui.FeatureCollectionTableModel;   *     Martin O. J. Schmitz - initial API and implementation
28  import skrueger.AttributeMetaData;   *     Stefan A. Krüger - additional utility classes
29  import skrueger.i8n.I8NUtil;   ******************************************************************************/
30  import skrueger.i8n.Translation;  package skrueger.geotools;
31    
32  /**  import java.util.HashMap;
33   * This class extends the the {@link FeatureCollectionTableModel} with the  import java.util.List;
34   * functionalities of the {@link AttributeMetaData} of  import java.util.Vector;
35   * {@linkplain StyledMapInterface styled objects}.  
36   * <ul>  import org.apache.log4j.Logger;
37   *   <li>column names are translated according to {@link AttributeMetaData#getTitle()}</li>  import org.geotools.data.DefaultQuery;
38   *   <li>columns are hidden according to {@link AttributeMetaData#isVisible()()}</li>  import org.geotools.data.FeatureSource;
39   * </ul>  import org.geotools.data.Query;
40   * @author <a href="mailto:[email protected]">Martin Schmitz</a> (University of Bonn/Germany)  import org.geotools.feature.FeatureCollection;
41   */  import org.opengis.feature.simple.SimpleFeature;
42  public class StyledFeatureCollectionTableModel extends FeatureCollectionTableModel {  import org.opengis.feature.simple.SimpleFeatureType;
43    /** Holds the data source as styled map. */  import org.opengis.feature.type.AttributeDescriptor;
44    protected StyledMapInterface map = null;  import org.opengis.filter.Filter;
45    /** Contains only the visible elements of the {@link AttributeMetaData}-Map */  
46    protected Map<Integer, AttributeMetaData> visibleAMD = null;  import schmitzm.geotools.feature.FeatureUtil;
47    /** Holds the data source for the table as {@code FeatureSource}. */  import schmitzm.geotools.gui.FeatureCollectionTableModel;
48    protected FeatureSource featureSource = null;  import skrueger.AttributeMetadata;
49    /** Contains the complete {@link AttributeMetaData}-Map of the styled layer. */  
50    protected Map<Integer, AttributeMetaData> origAMD = null;  import com.vividsolutions.jts.geom.Envelope;
51    /** Holds the current filter on the table */  
52    protected Filter filter = null;  /**
53    /** Holds the Bounds for all features. Only set once during the constructor **/   * This class extends the the {@link FeatureCollectionTableModel} with the
54    protected Envelope bounds;   * functionalities of the {@link AttributeMetadata}.
55     * <ul>
56    /**   * <li>column names are translated according to
57     * Creates a new table model for a styled map.   * {@link AttributeMetadata#getTitle()}</li>
58     * @param map the styled map   * <li>columns are hidden according to {@link AttributeMetaData#isVisible()()}</li>
59     */   * <li>Any filter defined in the {@link StyledFeaturesInterface} will be
60    public StyledFeatureCollectionTableModel(StyledFeatureCollectionInterface map) {   * applied.</li>
61      this(map,Filter.INCLUDE);   * </ul>
62    }   *
63     * @author Stefan A. Krüger
64    /**   */
65     * Creates a new table model for a styled map.  public class StyledFeatureCollectionTableModel extends
66     * @param map the styled map                  FeatureCollectionTableModel {
67     * @param filter filter applied to the table          final static private Logger LOGGER = Logger
68     */                          .getLogger(StyledFeatureCollectionTableModel.class);
69    public StyledFeatureCollectionTableModel(StyledFeatureCollectionInterface map, Filter filter) {          /** Contains the complete {@link AttributeMetadata}-Map of the styled layer. */
70      super();          protected AttributeMetadataMap amdMap = null;
71      setFeatureCollection(map, filter);          /** Holds the current filter on the table */
72    }          protected Filter filter = null;
73            /** Holds the Bounds for all features. Only set once during the constructor **/
74    /**          protected Envelope bounds;
75     * Creates a new table model for a styled map.          /**
76     * @param map the styled map           * Tooltips für die Spaltennamen. Wird nur beim Aufruf von
77     */           * {@link #reorganize} befuellt.
78    public StyledFeatureCollectionTableModel(StyledFeatureSourceInterface map) {           */
79      this(map,Filter.INCLUDE);          protected String[] colTooltips = null;
80    }  
81            /** A cache for the #sortedValuesVisibleOnly() **/
82    /**          protected List<AttributeMetadata> amdMapVisibleOnly = null;
83     * Creates a new table model for a styled map.  
84     * @param map the styled map          /**
85     * @param filter filter applied to the table           * Creates a new table model for a styled layer.
86     */           *
87    public StyledFeatureCollectionTableModel(StyledFeatureSourceInterface map, Filter filter) {           * @param styledFeatures
88      super();           *            the styled layer
89      setFeatureCollection(map, filter);           * @param filter
90    }           *            filter applied to the table
91             */
92    /**          public StyledFeatureCollectionTableModel(
93     * Sets a new data source for the table.                          StyledFeaturesInterface<?> styledFeatures) {
94     * @param fs     the feature source                  setStyledFeatures(styledFeatures);
95     * @param amd    {@link AttributeMetaData}-Map to define the visible attributes          }
96     *               and translation  
97     */          /**
98    protected void setFeatureSource(FeatureSource fs, Map<Integer, AttributeMetaData> amd, Filter filter) throws Exception {           * This overwritten method filters the values for NODATA-values defined in
99      if ( filter == null )           * the {@link AttributeMetadata}
100        filter = Filter.INCLUDE;           */
101                @Override
102      this.featureSource = fs;          public Object getValueAt(int row, int col) {
103      this.filter        = filter;                  Object rawValue = super.getValueAt(row, col);
104      this.origAMD       = amd;                  return amdMap.sortedValuesVisibleOnly().get(col).fiterNodata(rawValue);
105      this.visibleAMD    = null;          }
106                
107      FeatureCollection fc = null;          /**
108      if (fs != null) {           * Sets a new data source for the table.
109                     *
110         bounds = fs.getBounds();           * @param fs
111                     *            the feature source
112        Query query = new DefaultQuery(fs.getSchema().getTypeName(), filter);           * @param amdm
113        if (amd != null) {           *            {@link AttributeMetadata}-Map to define the visible attributes
114          // determine the names of the visible Attributes           *            and translation
115          this.visibleAMD = StyledMapUtil.getVisibleAttributeMetaData(amd, true);           */
116          Vector<String> visibleAttrNames = new Vector<String>();          protected void setFeatureSource(
117          // Add the column with the geometry (usually "the_geom")                          FeatureSource<SimpleFeatureType, SimpleFeature> fs,
118          visibleAttrNames.add(fs.getSchema().getDefaultGeometry().getLocalName());                          AttributeMetadataMap amdm, Filter filter) throws Exception {
119          for (int attrIdx : visibleAMD.keySet())  
120            visibleAttrNames.add(fs.getSchema().getAttributeType(attrIdx).getLocalName());                  if (filter == null)
121                            filter = Filter.INCLUDE;
122          // create a query for the visible attributes  
123          String[] properties = visibleAttrNames.toArray(new String[0]);                  // this.featureSource = fs;
124                            this.filter = filter;
125          query = new DefaultQuery(fs.getSchema().getTypeName(), filter, properties);                  this.amdMap = amdm;
126        }                  this.amdMapVisibleOnly = amdMap.sortedValuesVisibleOnly();
127        fc = fs.getFeatures(query);  
128                    FeatureCollection<SimpleFeatureType, SimpleFeature> fc = null;
129  // FAILS:!!!, even with  query = new DefaultQuery(fs.getSchema().getTypeName(), filter);                  if (fs != null) {
130                          // java.lang.UnsupportedOperationException: Unknown feature  
131                          // attribute: PQM_MOD                          bounds = fs.getBounds();
132                          // at  
133                          // schmitzm.geotools.feature.FeatureOperationTree.evaluate(FeatureOperationTree.java:93)                          final SimpleFeatureType schema = fs.getSchema();
134                          // bounds = fc.getBounds();                          Query query = new DefaultQuery(schema.getTypeName(), filter);
135                          // SK, 17.4.2009                          if (amdm != null) {
136                          //                                        Vector<String> visibleAttrNames = new Vector<String>();
137                          // System.out.println("Filter = "+filter);  
138                          // System.out.println("Size of FC = "+fc.size());                                  // Add the column with the geometry (usually "the_geom") always
139                          // System.out.println("anz att= "+fc.getNumberOfAttributes());                                  visibleAttrNames.add(schema.getGeometryDescriptor()
140      }                                                  .getLocalName());
141      setFeatureCollection(fc);  
142    }                                  // Add other visible attributes as ordered by weights
143                                    for (AttributeMetadata a : amdMapVisibleOnly) {
144    /**                                          visibleAttrNames.add(a.getLocalName());
145     * Converts the {@code StyledFeatureCollection} to a {@code FeatureSource}                                  }
146     * and sets this as the new data source for the table.  
147     * @param fs     the feature source                                  // Tested with 2.6.x trunk from 2009-11-26 and it now works. So
148     * @param amd    {@link AttributeMetaData}-Map to define the visible attributes                                  // we only request the properties we need!
149     *               and translation                                  // /**
150     */                                  // * I got NPEs when properties contained only [the_geom]
151    public void setFeatureCollection(StyledFeatureCollectionInterface map, Filter filter) {                                  // ?!??!!??
152      this.map = map;                                  // */
153      try {                                  // if (properties.length > 1) {
154        if (map == null)                                  query = new DefaultQuery(schema.getTypeName(), filter,
155          setFeatureSource(null, null, null);                                                  visibleAttrNames.toArray(new String[] {}));
156        else {                                  // } else {
157          FeatureCollection fc = map.getGeoObject();                                  // query = new DefaultQuery(schema.getTypeName(), filter);
158          String fcName = fc.getFeatureType().getTypeName();                                  // }
159          FeatureSource fs = new MemoryDataStore(fc).getFeatureSource(fcName);                          }
160          setFeatureSource(fs, map.getAttributeMetaDataMap(), filter);                          fc = fs.getFeatures(query);
161        }                  }
162      } catch (Exception err) {                  setFeatureCollection(fc);
163        throw new RuntimeException(err);          }
164      }  
165    }          /**
166             * Converts the {@code StyledFeatureCollection} to a {@code FeatureSource}
167    /**           * and sets this as the new data source for the table.
168     * Sets the {@code StyledFeatureCollection} as new data source for the table.           *
169     * @param fs     the feature source           * @param fs
170     * @param amd    {@link AttributeMetaData}-Map to define the visible attributes           *            the feature source
171     *               and translation           * @param amd
172     */           *            {@link AttributeMetadata}-Map to define the visible attributes
173    public void setFeatureCollection(StyledFeatureSourceInterface map, Filter filter) {           *            and translation
174      this.map = map;           */
175      try {          public void setStyledFeatures(StyledFeaturesInterface<?> styledFeatures) {
176        if (map == null)                  try {
177          setFeatureSource(null, null, null);                          if (styledFeatures == null)
178        else                                  setFeatureSource(null, null, null);
179          setFeatureSource(map.getGeoObject(), map.getAttributeMetaDataMap(), filter);                          else {
180      } catch (Exception err) {                                  setFeatureSource(styledFeatures.getFeatureSource(),
181        throw new RuntimeException(err);                                                  styledFeatures.getAttributeMetaDataMap(),
182      }                                                  styledFeatures.getFilter());
183    }                          }
184                      } catch (Exception err) {
185    /**                          throw new RuntimeException(err);
186     * Resets the filter for the table.                  }
187     * @param filter a filter          }
188     */  
189    public void setFilter(Filter filter) {          /**
190      try{           * After calling {@code super.reorganize(.)} this method replaced the column
191        setFeatureSource(this.featureSource, this.origAMD, filter);           * descriptions with the titles of the {@code AttributeMetaData}.
192      } catch (Exception err) {           *
193        throw new RuntimeException(err);           * @param fireTableStructureChanged
194      }           *            indicates whether a table event is initiated after reorganize
195    }           */
196              @Override
197    /**          protected void reorganize(boolean fireTableStructureChanged) {
198     * @return <code>Filter.INCLUDE</code> or the {@link Filter} applied to the Features  
199     */                  featureArray = FeatureUtil.featuresToArray(featureTable);
200    public Filter getFilter() {                  if (featureArray == null || featureArray.length == 0) {
201            return this.filter;                          colNames = new String[0];
202    }                          colTooltips = new String[0]; // Only set and used in
203                            // StyledFeatureCollectionTableModel
204    /**                          colClass = new Class[0];
205     * After calling {@code super.reorganize(.)} this method replaced the                  } else {
206     * column descriptions with the titles of the {@code AttributeMetaData}.                          // Struktur der Tabelle vom AttributeMetaDtaaMap übernehmen
207     * @param fireTableStructureChanged indicates whether a table event is                          SimpleFeatureType schema = featureArray[0].getFeatureType();
208     *        initiated after reorganize                          // Pruefen, welche Attribute angezeigt werden
209     */                          attrTypes.clear();
210    @Override                          for (AttributeMetadata amd : amdMapVisibleOnly) {
211    protected void reorganize(boolean fireTableStructureChanged) {                                  AttributeDescriptor type = schema.getDescriptor(amd.getName());
212      super.reorganize(false);                                  if (attrFilter == null || attrFilter.accept(type))
213      // translate the column names                                          attrTypes.add(type);
214      if (visibleAMD != null) {                          }
215        Iterator<Integer> keys = visibleAMD.keySet().iterator();                          // Namen und Attribut-Indizes der angezeigten Spalten ermitteln
216        for (int i = 0; i < colNames.length && keys.hasNext(); i++) {                          colNames = new String[attrTypes.size()];
217          Translation title = visibleAMD.get(keys.next()).getTitle();                          colTooltips = new String[attrTypes.size()]; // Only set and used in
218          if (!I8NUtil.isEmpty(title)) {                          // StyledFeatureCollectionTableModel
219  //          System.out.println("set colname " + i + " to " + title.toString());                          colClass = new Class[attrTypes.size()];
220            colNames[i] = title.toString();                          attrIdxForCol = new int[attrTypes.size()];
221          }                          for (int i = 0; i < colNames.length; i++) {
222        }                                  AttributeDescriptor descriptor = schema
223      }                                                  .getDescriptor(amdMapVisibleOnly.get(i).getName());
224      if ( fireTableStructureChanged )  
225        fireTableStructureChanged();                                  // Not so nice in 26: find the index of an attribute...
226    }                                  int idx = schema.getAttributeDescriptors().indexOf(descriptor);
227                                    attrIdxForCol[i] = idx;
228    /**  
229           * @returns Cached bounds for the whole dataset (without applying the                                  String attName = schema.getAttributeDescriptors().get(idx)
230           *          filter) or <code>null</code>                                                  .getLocalName();
231           */                                  colNames[i] = amdMap.get(attName).getTitle().toString();
232          public Envelope getBounds() {                                  AttributeMetadata amd = amdMap.get(attName);
233                  return bounds;                                  colTooltips[i] = "<html>" + amd.getDesc().toString() + "<br>"
234          }                                                  + amd.getName() + "</html>";
235  }                                  colClass[i] = schema.getAttributeDescriptors().get(idx)
236                                                    .getType().getBinding();
237                            }
238                    }
239    
240                    // store feature indexes in HashMap to optimize findFeature(.)
241                    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                    // // translate the column names
247                    // if (amdMap != null) {
248                    // for (int i = 0; i < colNames.length; i++) {
249                    // colTooltips[i] = amdMap.get(colNames[i]).getDesc().toString()
250                    // + "<br>" + colNames[i];
251                    // colNames[i] = amdMap.get(colNames[i]).getTitle().toString();
252                    //
253                    // }
254                    // }
255                    if (fireTableStructureChanged)
256                            fireTableStructureChanged();
257    
258            }
259    
260            /**
261             * @return Cached bounds for the whole dataset (without applying the filter)
262             *         or <code>null</code>
263             */
264            public Envelope getBounds() {
265                    return bounds;
266            }
267    }

Legend:
Removed from v.62  
changed lines
  Added in v.681

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26