[Schmitzm-commits] r931 - in trunk: src/schmitzm/geotools/feature src_junit/schmitzm/geotools/feature

scm-commit@wald.intevation.org scm-commit at wald.intevation.org
Fri Jul 2 01:11:08 CEST 2010


Author: alfonx
Date: 2010-07-02 01:11:05 +0200 (Fri, 02 Jul 2010)
New Revision: 931

Modified:
   trunk/src/schmitzm/geotools/feature/FeatureUtil.java
   trunk/src_junit/schmitzm/geotools/feature/FeatureUtilTest.java
Log:
Hack-Methode hinzugef?\195?\188gt um die in einem ECQL Ausdruck verwendeten Attribute herauszufiltern.

Modified: trunk/src/schmitzm/geotools/feature/FeatureUtil.java
===================================================================
--- trunk/src/schmitzm/geotools/feature/FeatureUtil.java	2010-07-01 18:50:38 UTC (rev 930)
+++ trunk/src/schmitzm/geotools/feature/FeatureUtil.java	2010-07-01 23:11:05 UTC (rev 931)
@@ -38,6 +38,7 @@
 import java.sql.ResultSet;
 import java.sql.ResultSetMetaData;
 import java.sql.SQLException;
+import java.text.NumberFormat;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.HashSet;
@@ -76,6 +77,7 @@
 import org.geotools.feature.simple.SimpleFeatureBuilder;
 import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
 import org.geotools.filter.FilterAbstract;
+import org.geotools.filter.text.cql2.CQL;
 import org.geotools.map.MapLayer;
 import org.geotools.resources.CRSUtilities;
 import org.geotools.resources.coverage.FeatureUtilities;
@@ -128,14 +130,56 @@
 	 * sind in properties-Dateien unter {@code
 	 * schmitzm.geotools.feature.resource.locales} hinterlegt.
 	 */
-	public static ResourceProvider RESOURCE = ResourceProvider.newInstance(LangUtil
-			.extendPackagePath(FeatureUtil.class,
+	public static ResourceProvider RESOURCE = ResourceProvider.newInstance(
+			LangUtil.extendPackagePath(FeatureUtil.class,
 					"resource.locales.FeatureResourceBundle"), Locale.ENGLISH);
 
 	private static final NameImpl GC_NAME = new NameImpl(
 			"http://www.opengis.net/gml", "GridCoverage");
 
 	/**
+	 * This is a cheap and not good hack to extract the names of attributes used
+	 * in a ECQL expression. This is not the way to do it, but a try.
+	 * Potentially returns more and/or incorrect attribute names.
+	 * 
+	 * @return an empty list if formal == <code>null</code>.
+	 */
+	public static List<String> getCQLAttributNames(String formel) {
+		ArrayList<String> result = new ArrayList<String>();
+		if (formel == null)
+			return result;
+
+		String[] split = formel.split("[ /*+-\\^]");
+
+		for (String attName : split) {
+			// Mögliche Klammern entfernen
+			attName = attName.replaceAll("[()]", "");
+			attName = attName.trim();
+
+			if (attName.isEmpty())
+				continue;
+
+			// Ignore number literals
+			try {
+				Double.parseDouble(attName);
+				continue;
+			} catch (Exception e) {
+			}
+
+			// Ignore number literals
+			try {
+				NumberFormat.getInstance().parse(attName);
+				continue;
+			} catch (Exception e) {
+			}
+
+			result.add(attName);
+		}
+
+		return result;
+	}
+
+	/**
 	 * Convenience method to access the {@link ResourceProvider}.
 	 */
 	public static String R(String key, Object... values) {
@@ -811,47 +855,47 @@
 	 */
 	protected static Vector<SimpleFeature> sortFeatures(
 			FeatureIterator<SimpleFeature> fi, String... attrName) {
-	  
-	    // Create a comparator for sorting in order to
-	    // the sort attributes
-	    FeatureComparator fComp = new FeatureComparator(attrName);
-	  
-	  
+
+		// Create a comparator for sorting in order to
+		// the sort attributes
+		FeatureComparator fComp = new FeatureComparator(attrName);
+
 		// First create a SortedMap with CollisionList
-		SortedMap<SimpleFeature, Vector<SimpleFeature>> sortedFeatureLists = new TreeMap<SimpleFeature, Vector<SimpleFeature>>(fComp);
-		
+		SortedMap<SimpleFeature, Vector<SimpleFeature>> sortedFeatureLists = new TreeMap<SimpleFeature, Vector<SimpleFeature>>(
+				fComp);
+
 		for (; fi.hasNext();) {
 			SimpleFeature f = fi.next();
-//			// Check whether attribute value is Comparable
-//			Object attrValue = f.getAttribute(attrName);
-//			if (attrValue != null && !(attrValue instanceof Comparable))
-//				throw new UnsupportedOperationException(
-//						"SimpleFeature sort only supported for Comparable attributes: "
-//								+ LangUtil.getSimpleClassName(attrValue));
-//			// Determine X value as sort attribute (NULL not permitted for
-//			// XYDateset!)
-//			Comparable<?> xValue = (Comparable<?>) attrValue;
-//			if (xValue == null)
-//				continue;
-//
-//			// Check whether collision list exists
-//			Vector<SimpleFeature> collList = sortedFeatureLists.get(xValue);
-//			if (collList == null) {
-//				collList = new Vector<SimpleFeature>();
-//				sortedFeatureLists.put(xValue, collList);
-//			}
-//			// Add feature to collision list
-//			collList.add(f);
+			// // Check whether attribute value is Comparable
+			// Object attrValue = f.getAttribute(attrName);
+			// if (attrValue != null && !(attrValue instanceof Comparable))
+			// throw new UnsupportedOperationException(
+			// "SimpleFeature sort only supported for Comparable attributes: "
+			// + LangUtil.getSimpleClassName(attrValue));
+			// // Determine X value as sort attribute (NULL not permitted for
+			// // XYDateset!)
+			// Comparable<?> xValue = (Comparable<?>) attrValue;
+			// if (xValue == null)
+			// continue;
+			//
+			// // Check whether collision list exists
+			// Vector<SimpleFeature> collList = sortedFeatureLists.get(xValue);
+			// if (collList == null) {
+			// collList = new Vector<SimpleFeature>();
+			// sortedFeatureLists.put(xValue, collList);
+			// }
+			// // Add feature to collision list
+			// collList.add(f);
 
-            // Check whether collision list exists
-            Vector<SimpleFeature> collList = sortedFeatureLists.get(f);
-            if (collList == null) {
-                collList = new Vector<SimpleFeature>();
-                sortedFeatureLists.put(f, collList);
-            }
-            // Add feature to collision list
-            collList.add(f);
-		
+			// Check whether collision list exists
+			Vector<SimpleFeature> collList = sortedFeatureLists.get(f);
+			if (collList == null) {
+				collList = new Vector<SimpleFeature>();
+				sortedFeatureLists.put(f, collList);
+			}
+			// Add feature to collision list
+			collList.add(f);
+
 		}
 
 		// Put the (now ordered) features from the collision lists
@@ -1690,8 +1734,7 @@
 	 * 
 	 * @param geomType
 	 *            LineString.class, Point.class or Polygon.class from com.jts...
-	 * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons
-	 *         Tzeggai</a>
+	 * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons Tzeggai</a>
 	 */
 
 	public static SimpleFeatureType createFeatureType(final Class<?> geomType) {
@@ -1705,8 +1748,7 @@
 	 * @param geomType
 	 *            LineString.class, Point.class or Polygon.class from com.jts...
 	 * 
-	 * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons
-	 *         Tzeggai</a>
+	 * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons Tzeggai</a>
 	 */
 	public static SimpleFeatureType createFeatureType(final Class<?> geomType,
 			CoordinateReferenceSystem crs) {
@@ -2046,93 +2088,93 @@
 	 * This method determines the average distance to next centroid.
 	 * 
 	 * @param styledFeatures
-	 * @throws IOException if features can't be accessed
+	 * @throws IOException
+	 *             if features can't be accessed
 	 */
-	public static Double calcAvgNN(StyledFeaturesInterface<?> styledFeatures) throws IOException {
-			final Integer SAMPLESIZE = 60;
+	public static Double calcAvgNN(StyledFeaturesInterface<?> styledFeatures)
+			throws IOException {
+		final Integer SAMPLESIZE = 60;
 
-			final DynamicBin1D dists = new DynamicBin1D();
+		final DynamicBin1D dists = new DynamicBin1D();
 
-			final Integer countAll = styledFeatures
-					.getFeatureCollectionFiltered().size();
-			if (countAll <= 1)
-				return Double.MAX_VALUE;
+		final Integer countAll = styledFeatures.getFeatureCollectionFiltered()
+				.size();
+		if (countAll <= 1)
+			return Double.MAX_VALUE;
 
-			final Random rand = new Random();
-			final double ratio = SAMPLESIZE.doubleValue()
-					/ countAll.doubleValue();
-			// final double ratio = countAll > SAMPLESIZE ?
-			// countAll.doubleValue() / SAMPLESIZE.doubleValue() : 1.;
-			LOGGER.debug("ratio " + ratio);
+		final Random rand = new Random();
+		final double ratio = SAMPLESIZE.doubleValue() / countAll.doubleValue();
+		// final double ratio = countAll > SAMPLESIZE ?
+		// countAll.doubleValue() / SAMPLESIZE.doubleValue() : 1.;
+		LOGGER.debug("ratio " + ratio);
 
-			Filter filter = FeatureUtil.FILTER_FACTORY2.and(styledFeatures
-					.getFilter(), new FilterAbstract(
-					FeatureUtil.FILTER_FACTORY2) {
+		Filter filter = FeatureUtil.FILTER_FACTORY2.and(styledFeatures
+				.getFilter(), new FilterAbstract(FeatureUtil.FILTER_FACTORY2) {
 
-				@Override
-				public boolean evaluate(Object object) {
-					return rand.nextDouble() <= ratio;
-				}
+			@Override
+			public boolean evaluate(Object object) {
+				return rand.nextDouble() <= ratio;
+			}
 
-			});
-			final DefaultQuery random100query = new DefaultQuery(styledFeatures
-					.getSchema().getTypeName(), filter, SAMPLESIZE, null,
-					"random query for " + ratio);
-			
-			CoordinateReferenceSystem crs = styledFeatures.getCrs();
-			
-			Unit<Length> unit = (Unit<Length>) CRSUtilities.getUnit(crs
-					.getCoordinateSystem());
-			
-			// Restrict the query to only the geometry column 
-			random100query.setPropertyNames(new String[] {styledFeatures
-					.getSchema().getGeometryDescriptor().getLocalName()});
+		});
+		final DefaultQuery random100query = new DefaultQuery(styledFeatures
+				.getSchema().getTypeName(), filter, SAMPLESIZE, null,
+				"random query for " + ratio);
 
-			// See if the unit is convertable to meters. If not, request the features in a world wgs meters CRS.
-			try {
-				unit.getConverterTo(SI.METER);
-			} catch (ConversionException ce) {
-				random100query.setCoordinateSystemReproject(GTUtil.WORLD_METER);
-			}
-			
+		CoordinateReferenceSystem crs = styledFeatures.getCrs();
 
-			final GeometryForm geometryForm = FeatureUtil
-					.getGeometryForm(styledFeatures.getSchema());
+		Unit<Length> unit = (Unit<Length>) CRSUtilities.getUnit(crs
+				.getCoordinateSystem());
 
-			Iterator<SimpleFeature> it;
-			it = styledFeatures.getFeatureSource().getFeatures(random100query)
-					.iterator();
+		// Restrict the query to only the geometry column
+		random100query.setPropertyNames(new String[] { styledFeatures
+				.getSchema().getGeometryDescriptor().getLocalName() });
 
-			while (it.hasNext()) {
+		// See if the unit is convertable to meters. If not, request the
+		// features in a world wgs meters CRS.
+		try {
+			unit.getConverterTo(SI.METER);
+		} catch (ConversionException ce) {
+			random100query.setCoordinateSystemReproject(GTUtil.WORLD_METER);
+		}
 
-				SimpleFeature f1 = it.next();
+		final GeometryForm geometryForm = FeatureUtil
+				.getGeometryForm(styledFeatures.getSchema());
 
-				switch (geometryForm) {
-				case POINT:
-					final FeatureCollection<SimpleFeatureType, SimpleFeature> allFeatures = styledFeatures
-							.getFeatureSource().getFeatures(random100query);
+		Iterator<SimpleFeature> it;
+		it = styledFeatures.getFeatureSource().getFeatures(random100query)
+				.iterator();
 
-					dists.add(extractedPoint(allFeatures, f1));
-					break;
-				case LINE:
-					dists.add(((Geometry) f1.getDefaultGeometry()).getLength());
-					break;
-				case POLYGON:
-					dists.add(((Geometry) f1.getDefaultGeometry()).getLength());
-					break;
-				}
+		while (it.hasNext()) {
+
+			SimpleFeature f1 = it.next();
+
+			switch (geometryForm) {
+			case POINT:
+				final FeatureCollection<SimpleFeatureType, SimpleFeature> allFeatures = styledFeatures
+						.getFeatureSource().getFeatures(random100query);
+
+				dists.add(extractedPoint(allFeatures, f1));
+				break;
+			case LINE:
+				dists.add(((Geometry) f1.getDefaultGeometry()).getLength());
+				break;
+			case POLYGON:
+				dists.add(((Geometry) f1.getDefaultGeometry()).getLength());
+				break;
 			}
+		}
 
-			final Double avgNN = dists.mean();
+		final Double avgNN = dists.mean();
 
-			LOGGER.info("avgNN for " + styledFeatures.getTitle() + " is "
-					+ avgNN + " in " + unit);
+		LOGGER.info("avgNN for " + styledFeatures.getTitle() + " is " + avgNN
+				+ " in " + unit);
 
-			double inMeter = unit.getConverterTo(SI.METER).convert(avgNN);
+		double inMeter = unit.getConverterTo(SI.METER).convert(avgNN);
 
-			double inPixels = inMeter * 100 * 10 / 0.28;
+		double inPixels = inMeter * 100 * 10 / 0.28;
 
-			return inPixels;
+		return inPixels;
 
 	}
 
@@ -2333,15 +2375,15 @@
 						.getLocalPart());
 			}
 		}
-		
-		// Checking for excact match with a _ infront of the seached name 
+
+		// Checking for excact match with a _ infront of the seached name
 		for (AttributeDescriptor d : attributeDescriptors) {
 			if ((d.getName().getLocalPart()).equals("_" + localName)) {
 				return new NameImpl(d.getName().getNamespaceURI(), d.getName()
 						.getLocalPart());
 			}
 		}
-		
+
 		// Checking for excact match with a _ infront of the schema name
 		for (AttributeDescriptor d : attributeDescriptors) {
 			if (("_" + d.getName().getLocalPart()).equalsIgnoreCase(localName)) {
@@ -2349,8 +2391,8 @@
 						.getLocalPart());
 			}
 		}
-		
-		// Checking for excact match with a _ infront of the seached name 
+
+		// Checking for excact match with a _ infront of the seached name
 		for (AttributeDescriptor d : attributeDescriptors) {
 			if ((d.getName().getLocalPart()).equalsIgnoreCase("_" + localName)) {
 				return new NameImpl(d.getName().getNamespaceURI(), d.getName()

Modified: trunk/src_junit/schmitzm/geotools/feature/FeatureUtilTest.java
===================================================================
--- trunk/src_junit/schmitzm/geotools/feature/FeatureUtilTest.java	2010-07-01 18:50:38 UTC (rev 930)
+++ trunk/src_junit/schmitzm/geotools/feature/FeatureUtilTest.java	2010-07-01 23:11:05 UTC (rev 931)
@@ -1,8 +1,11 @@
 package schmitzm.geotools.feature;
 
+import static org.junit.Assert.*;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
 
+import java.util.List;
+
 import org.junit.Test;
 import org.opengis.feature.type.GeometryDescriptor;
 
@@ -11,7 +14,6 @@
 import com.vividsolutions.jts.geom.Point;
 import com.vividsolutions.jts.geom.Polygon;
 
-
 public class FeatureUtilTest {
 
 	@Test
@@ -29,4 +31,24 @@
 		assertFalse(FeatureUtil.getGeometryForm(defaultGeometry) == GeometryForm.POLYGON);
 		assertFalse(FeatureUtil.getGeometryForm(defaultGeometry) == GeometryForm.LINE);
 	}
+
+	@Test
+	public void testGetCQLAttributNames() throws Exception {
+		List<String> aa = FeatureUtil.getCQLAttributNames("de_fr/ddd");
+		assertEquals("de_fr", aa.get(0));
+		assertEquals("ddd", aa.get(1));
+
+		aa = FeatureUtil.getCQLAttributNames("fff*-3(de_fr/ddd)/100+2");
+		assertEquals(3, aa.size());
+		assertEquals("fff", aa.get(0));
+		assertEquals("de_fr", aa.get(1));
+		assertEquals("ddd", aa.get(2));
+
+		aa = FeatureUtil.getCQLAttributNames("3^a * -3^b*0.3");
+		assertEquals(2, aa.size());
+		assertEquals("a", aa.get(0));
+		assertEquals("b", aa.get(1));
+
+	}
+
 }



More information about the Schmitzm-commits mailing list