[Schmitzm-commits] r1131 - in trunk: src/schmitzm/geotools/io src/skrueger/geotools/io src_junit/schmitzm/geotools/feature

scm-commit@wald.intevation.org scm-commit at wald.intevation.org
Thu Oct 14 23:39:22 CEST 2010


Author: alfonx
Date: 2010-10-14 23:39:22 +0200 (Thu, 14 Oct 2010)
New Revision: 1131

Modified:
   trunk/src/schmitzm/geotools/io/GeoExportUtil.java
   trunk/src/schmitzm/geotools/io/GeoImportUtil.java
   trunk/src/skrueger/geotools/io/GeoImportUtilURL.java
   trunk/src_junit/schmitzm/geotools/feature/FeatureUtilTest.java
Log:


Modified: trunk/src/schmitzm/geotools/io/GeoExportUtil.java
===================================================================
--- trunk/src/schmitzm/geotools/io/GeoExportUtil.java	2010-10-14 21:31:15 UTC (rev 1130)
+++ trunk/src/schmitzm/geotools/io/GeoExportUtil.java	2010-10-14 21:39:22 UTC (rev 1131)
@@ -32,8 +32,10 @@
 import java.awt.geom.Rectangle2D;
 import java.awt.image.BufferedImage;
 import java.io.File;
+import java.io.FileWriter;
 import java.io.IOException;
 import java.io.PrintWriter;
+import java.nio.charset.Charset;
 
 import javax.imageio.ImageIO;
 
@@ -43,6 +45,7 @@
 import org.geotools.data.FeatureStore;
 import org.geotools.data.Transaction;
 import org.geotools.data.shapefile.ShapefileDataStore;
+import org.geotools.data.shapefile.indexed.IndexedShapefileDataStore;
 import org.geotools.feature.FeatureCollection;
 import org.geotools.gce.arcgrid.ArcGridWriter;
 import org.opengis.feature.simple.SimpleFeature;
@@ -72,13 +75,13 @@
 	 * Baut auf folgenden Geotools-Klassen auf: <code>
 	 * <ul>
 	 * <li>{@link ShapefileDataStore       org.geotools.data.shapefile.ShapefileDataStore}</li>
-   * <li>{@link FeatureSource            org.geotools.data.FeatureSource}</li>
-   * <li>{@link FeatureStore             org.geotools.data.FeatureStore}</li>
-   * <li>{@link Transaction              org.geotools.data.Transaction}</li>
-   * <li>{@link FeatureCollection        org.geotools.feature.FeatureCollection}</li>
-   * <li>{@link FeatureCollectionReader  schmitzm.geotools.feature.FeatureCollectionReader}</li>
-   * </ul>
-   * </code>
+	 * <li>{@link FeatureSource            org.geotools.data.FeatureSource}</li>
+	 * <li>{@link FeatureStore             org.geotools.data.FeatureStore}</li>
+	 * <li>{@link Transaction              org.geotools.data.Transaction}</li>
+	 * <li>{@link FeatureCollection        org.geotools.feature.FeatureCollection}</li>
+	 * <li>{@link FeatureCollectionReader  schmitzm.geotools.feature.FeatureCollectionReader}</li>
+	 * </ul>
+	 * </code>
 	 * 
 	 * @param fc
 	 *            zu exportierende FeatureCollection
@@ -93,14 +96,15 @@
 		// DataStore fuer Ausgabe-Datei oeffnen
 		ShapefileDataStore shpStore = null;
 		try {
-//			shpStore = new ShapefileDataStore(outFile.toURI().toURL());
+			// shpStore = new ShapefileDataStore(outFile.toURI().toURL());
 			shpStore = new ShapefileDataStore(DataUtilities.fileToURL(outFile));
 		} catch (IllegalArgumentException err) {
 			// ShapefileDataStore schmeisst eine IllegalArgumentException,
 			// wenn Dateiname nicht ".shp", ".dbf", ... ist
 			// -> Erweiterung anhaengen
 			outFile = IOUtil.appendFileExt(outFile, ".shp");
-			shpStore = new ShapefileDataStore(DataUtilities.fileToURL(outFile));
+			shpStore = new IndexedShapefileDataStore(
+					DataUtilities.fileToURL(outFile));
 		}
 
 		try {
@@ -125,6 +129,11 @@
 		} finally {
 			shpStore.dispose();
 		}
+
+		// Stefan Tzeggai 14.10.2010 Es wird angenommen, dass die gerade
+		// geschriebenen Features im aktuellen Charset des Computers geschrieben
+		// wurden. Das specihern wir in einer .cpg Datei.
+		saveCpg(IOUtil.changeFileExt(outFile, "cpg"), Charset.defaultCharset());
 	}
 
 	/**
@@ -133,9 +142,9 @@
 	 * Baut auf folgenden Geotools-Klassen auf: <code>
 	 * <ul>
 	 *   <li>{@link org.geotools.coverage.grid.GridCoverage2D}</li>
-   *   <li>{@link org.geotools.gce.arcgrid.ArcGridWriter}</li>
-   * </ul>
-   * </code>
+	 *   <li>{@link org.geotools.gce.arcgrid.ArcGridWriter}</li>
+	 * </ul>
+	 * </code>
 	 * 
 	 * @param grid
 	 *            zu exportierendes Grid
@@ -193,11 +202,11 @@
 		ImageIO.write(grid.getRenderedImage(), "tif", output);
 		// World-File schreiben
 		writeWorldFile(grid.getRenderedImage().getWidth(), grid
-				.getRenderedImage().getHeight(), grid.getEnvelope2D(), IOUtil
-				.changeFileExt(output, "tfw"));
+				.getRenderedImage().getHeight(), grid.getEnvelope2D(),
+				IOUtil.changeFileExt(output, "tfw"));
 		// Projektion schreiben
-		writeProjectionFile(grid.getCoordinateReferenceSystem(), IOUtil
-				.changeFileExt(output, "prj"));
+		writeProjectionFile(grid.getCoordinateReferenceSystem(),
+				IOUtil.changeFileExt(output, "prj"));
 	}
 
 	/**
@@ -242,8 +251,8 @@
 		writeWorldFile(grid.getWidth(), grid.getHeight(), grid.getEnvelope(),
 				IOUtil.changeFileExt(output, "tfw"));
 		// Projektion schreiben
-		writeProjectionFile(grid.getCoordinateReferenceSystem(), IOUtil
-				.changeFileExt(output, "prj"));
+		writeProjectionFile(grid.getCoordinateReferenceSystem(),
+				IOUtil.changeFileExt(output, "prj"));
 	}
 
 	/**
@@ -342,8 +351,8 @@
 			Object next = crs.getIdentifiers().iterator().next();
 			if (next instanceof Identifier) {
 				Identifier identifier = (Identifier) next;
-				if (identifier.getAuthority().getTitle().toString().equals(
-						"European Petroleum Survey Group")
+				if (identifier.getAuthority().getTitle().toString()
+						.equals("European Petroleum Survey Group")
 						|| identifier.toString().startsWith("EPSG:")) {
 					whatToWrite = "EPSG:" + identifier.getCode();
 				}
@@ -373,4 +382,37 @@
 		}
 	}
 
+	/**
+	 * Stores the given Charset as a .cpg file containing the name of charset.
+	 * If the file already contains the same content, it is not written (SVN
+	 * friendly)
+	 */
+	public static void saveCpg(final File cpgFile, Charset charset)
+			throws IOException {
+
+		String whatToWrite = charset.name();
+
+		if (cpgFile.exists()) {
+			String origContent = IOUtil.readFileAsString(cpgFile);
+			if (whatToWrite.equals(origContent)) {
+				// if the file already exists and contains the same content,
+				// do not write it.
+				return;
+			} else
+				cpgFile.delete();
+		}
+
+		final FileWriter cpgWriter = new FileWriter(cpgFile);
+		try {
+			// LOGGER.debug("Writing CPG = " + dpe.getCharset().name()
+			// + " to file");
+
+			cpgWriter.write(whatToWrite);
+		} finally {
+			cpgWriter.flush();
+			cpgWriter.close();
+		}
+
+	}
+
 }

Modified: trunk/src/schmitzm/geotools/io/GeoImportUtil.java
===================================================================
--- trunk/src/schmitzm/geotools/io/GeoImportUtil.java	2010-10-14 21:31:15 UTC (rev 1130)
+++ trunk/src/schmitzm/geotools/io/GeoImportUtil.java	2010-10-14 21:39:22 UTC (rev 1131)
@@ -45,6 +45,7 @@
 import java.io.InputStreamReader;
 import java.io.OutputStream;
 import java.net.URL;
+import java.nio.charset.Charset;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.StringTokenizer;
@@ -270,11 +271,15 @@
 	public static FeatureCollection<SimpleFeatureType, SimpleFeature> readFeaturesFromShapeURL(
 			URL url, URL prjUrl) throws IOException {
 		ShapefileDataStore store = new ShapefileDataStore(url);
+
+		/**
+		 * .crs ?
+		 */
 		try {
 			// Testen, ob Projektion ermittelt werden kann, um vorab das
 			// Standard-CRS
 			// zu setzen
-			LOGGER.debug("  parseWKT on " + prjUrl);
+			// LOGGER.debug("  parseWKT on " + prjUrl);
 			// CRS.parseWKT(readProjectionString(prjUrl));
 			GTUtil.createCRS(readProjectionString(prjUrl));
 		} catch (Exception err) {
@@ -283,6 +288,26 @@
 			LOGGER.warn(" NOT calling forceSchemaCRS now... please provide a URL to an existing .prj file!");
 			// store.forceSchemaCRS(DEFAULT_CRS);
 		}
+
+		/**
+		 * .cpg ?
+		 */
+		try {
+			for (URL cpgURL : getCharsetUrls(url)) {
+				String charsetName = IOUtil.readURLasString(cpgURL);
+				if (charsetName != null && !charsetName.equals("")) {
+					store.setStringCharset(Charset.forName(charsetName));
+					break;
+				}
+			}
+
+		} catch (Exception err) {
+			LOGGER.warn(" CRS.parseWKT mit Ex\n: ", err);
+			LOGGER.warn(" No projection found for file. Default is used.");
+			LOGGER.warn(" NOT calling forceSchemaCRS now... please provide a URL to an existing .prj file!");
+			// store.forceSchemaCRS(DEFAULT_CRS);
+		}
+
 		FeatureCollection<SimpleFeatureType, SimpleFeature> fc = store
 				.getFeatureSource().getFeatures();
 
@@ -313,52 +338,53 @@
 	 * 
 	 * @author <a href="mailto:martin.schmitz at koeln.de">Martin Schmitz</a>
 	 *         (University of Bonn/Germany)
-	 * 
-	 *         TODO Wenn readFeaturesFromShapeURL getestet ist, dann sollte die
-	 *         hiet auf readFeaturesFromShapeURL(file.getURL) umgeleitet werden
-	 *         (SK)
 	 */
 	public static FeatureCollection<SimpleFeatureType, SimpleFeature> readFeaturesFromShapeFile(
 			File file) throws Exception {
-		ShapefileDataStore store = new ShapefileDataStore(
-				DataUtilities.fileToURL(file));
-		File prjFile = IOUtil.changeFileExt(file, "prj");
-		boolean delPrjFile = false;
-		try {
-			// Testen, ob Projektion ermittelt werden kann, um vorab das
-			// Standard-CRS
-			// zu setzen
-			String prjString = readProjectionString(prjFile);
-			if (prjString == null || prjString.trim().equals(""))
-				throw new FileNotFoundException("No proper prj-File exists: "
-						+ file.getName());
-			// CRS.parseWKT(prjString);
-			GTUtil.createCRS(prjString);
-		} catch (FileNotFoundException err) {
-			store.forceSchemaCRS(getDefaultCRS());
-			LOGGER.warn("No projection found for file " + file.getName()
-					+ ". Default is used.");
-			delPrjFile = true; // von DataStore erzeugte Datei wieder loeschen
-		}
-		String[] typeNames = store.getTypeNames();
-		FeatureCollection<SimpleFeatureType, SimpleFeature> fc = store
-				.getFeatureSource(typeNames[0]).getFeatures();
-		if (delPrjFile)
-			prjFile.delete();
 
-		// Create a new DefaultFeatureCollection to allow modifying
-		// operations on the collection ("fc" is a DataFeatureCollection, whose
-		// add(.) and remove(.) methods do nothing. Furthermore a
-		// FIDFeatureReader
-		// is used which returns copies of the features, so modifying the
-		// attributes
-		// does not effect the features in the collection!)
-		FeatureCollection<SimpleFeatureType, SimpleFeature> fc1 = FeatureCollections
-				.newCollection(fc.getID());
-		fc1.addAll(fc);
-		fc = fc1;
+		return readFeaturesFromShapeURL(DataUtilities.fileToURL(file));
 
-		return fc;
+		// ShapefileDataStore store = new ShapefileDataStore(
+		// DataUtilities.fileToURL(file));
+		// File prjFile = IOUtil.changeFileExt(file, "prj");
+		// boolean delPrjFile = false;
+		// try {
+		// // Testen, ob Projektion ermittelt werden kann, um vorab das
+		// // Standard-CRS
+		// // zu setzen
+		// String prjString = readProjectionString(prjFile);
+		// if (prjString == null || prjString.trim().equals(""))
+		// throw new FileNotFoundException("No proper prj-File exists: "
+		// + file.getName());
+		// // CRS.parseWKT(prjString);
+		// GTUtil.createCRS(prjString);
+		// } catch (FileNotFoundException err) {
+		// store.forceSchemaCRS(getDefaultCRS());
+		// LOGGER.warn("No projection found for file " + file.getName()
+		// + ". Default is used.");
+		// delPrjFile = true; // von DataStore erzeugte Datei wieder loeschen
+		// }
+		// String[] typeNames = store.getTypeNames();
+		// FeatureCollection<SimpleFeatureType, SimpleFeature> fc = store
+		// .getFeatureSource(typeNames[0]).getFeatures();
+		// if (delPrjFile)
+		// prjFile.delete();
+		//
+		// // Create a new DefaultFeatureCollection to allow modifying
+		// // operations on the collection ("fc" is a DataFeatureCollection,
+		// whose
+		// // add(.) and remove(.) methods do nothing. Furthermore a
+		// // FIDFeatureReader
+		// // is used which returns copies of the features, so modifying the
+		// // attributes
+		// // does not effect the features in the collection!)
+		// FeatureCollection<SimpleFeatureType, SimpleFeature> fc1 =
+		// FeatureCollections
+		// .newCollection(fc.getID());
+		// fc1.addAll(fc);
+		// fc = fc1;
+		//
+		// return fc;
 	}
 
 	/**
@@ -371,8 +397,9 @@
 	 * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons Tzeggai</a>
 	 * @throws IOException
 	 *             if an error occur
-	 *             
-	 *             @deprecated So wird das nicht mehr gemacht. Das wird mit einem Factory Finder gemacht.
+	 * 
+	 * @deprecated So wird das nicht mehr gemacht. Das wird mit einem Factory
+	 *             Finder gemacht.
 	 */
 	public static DataStore readDataStoreFromShape(URL shpURL, URL prjURL)
 			throws IOException {
@@ -473,20 +500,21 @@
 						+ getAsciiRasterImportMode());
 	}
 
-//	private static GridCoverage2D readGridFromArcInfoASCII_ArcGridReaderSpi(
-//			Object input, CoordinateReferenceSystem crs) {
-//		final AsciiGridsImageReader reader = (AsciiGridsImageReader) new AsciiGridsImageReaderSpi()
-//				.createReaderInstance();
-//		reader.setInput(input);
-//		
-//		Hints hints = new Hints();
-//		if (crs != null) {
-//			hints.put(Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM, crs);
-//		}
-////		WritableRaster wr = reader.getRasterReader().readRaster();
-//		
-//		return gc;
-//	}
+	// private static GridCoverage2D readGridFromArcInfoASCII_ArcGridReaderSpi(
+	// Object input, CoordinateReferenceSystem crs) {
+	// final AsciiGridsImageReader reader = (AsciiGridsImageReader) new
+	// AsciiGridsImageReaderSpi()
+	// .createReaderInstance();
+	// reader.setInput(input);
+	//
+	// Hints hints = new Hints();
+	// if (crs != null) {
+	// hints.put(Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM, crs);
+	// }
+	// // WritableRaster wr = reader.getRasterReader().readRaster();
+	//
+	// return gc;
+	// }
 
 	/**
 	 * Uses the <b>{@link ArcGridReader} class</b> (standard GT) to import a
@@ -1091,16 +1119,13 @@
 
 	/**
 	 * Liest das CRS aus einer URL. Wenn keine CRS gelesen werden kann, dann
-	 * wird die Endung der URL gegen .prj und .PRJ gewechselt und nochmal versucht bevor
-	 * das {@link #DEFAULT_CRS} benutzt wird.
+	 * wird die Endung der URL gegen .prj und .PRJ gewechselt und nochmal
+	 * versucht bevor das {@link #DEFAULT_CRS} benutzt wird.
 	 * 
 	 * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons Tzeggai</a>
 	 */
 	public static CoordinateReferenceSystem determineProjection(URL prjUrl) {
 		CoordinateReferenceSystem crs = null;
-		// Versuchen CRS aus angegebener Datei zu lesen
-//		LOGGER.debug("determineProjection: Try to read a projection from URL "
-//				+ prjUrl);
 		try {
 			crs = GeoImportUtil.readProjectionFile(prjUrl);
 		} catch (IOException e) {
@@ -1358,4 +1383,14 @@
 		return shpUrl;
 	}
 
+	/**
+	 * The URLs where a <code>.cpg</code> or <code>.cst</code> file describing
+	 * the {@link Charset} could be found.
+	 */
+	public static URL[] getCharsetUrls(URL url_) {
+		return new URL[] { IOUtil.changeUrlExt(url_, "cpg"),
+				IOUtil.changeUrlExt(url_, "cst"),
+				IOUtil.changeUrlExt(url_, "CPG"),
+				IOUtil.changeUrlExt(url_, "CST") };
+	}
 }

Modified: trunk/src/skrueger/geotools/io/GeoImportUtilURL.java
===================================================================
--- trunk/src/skrueger/geotools/io/GeoImportUtilURL.java	2010-10-14 21:31:15 UTC (rev 1130)
+++ trunk/src/skrueger/geotools/io/GeoImportUtilURL.java	2010-10-14 21:39:22 UTC (rev 1131)
@@ -34,6 +34,7 @@
 import java.io.File;
 import java.io.IOException;
 import java.net.URL;
+import java.nio.charset.Charset;
 
 import javax.imageio.IIOException;
 import javax.imageio.ImageIO;
@@ -280,4 +281,6 @@
 	// // ArcGridReader reader = new ArcGridReader( file );
 	// // return (GridCoverage2D)reader.read(null);
 
+	
+
 }

Modified: trunk/src_junit/schmitzm/geotools/feature/FeatureUtilTest.java
===================================================================
--- trunk/src_junit/schmitzm/geotools/feature/FeatureUtilTest.java	2010-10-14 21:31:15 UTC (rev 1130)
+++ trunk/src_junit/schmitzm/geotools/feature/FeatureUtilTest.java	2010-10-14 21:39:22 UTC (rev 1131)
@@ -8,6 +8,7 @@
 
 import java.io.File;
 import java.util.HashSet;
+import java.util.Iterator;
 import java.util.List;
 import java.util.Set;
 
@@ -108,7 +109,8 @@
 
 		AttributeModificationRule[] destAttrs = new AttributeModificationRule[3];
 		destAttrs[0] = new AttributeModificationRule(0);
-		destAttrs[1] = new AttributeModificationRule(3, "arab", null, null, null, null);
+		destAttrs[1] = new AttributeModificationRule(3, "arab", null, null,
+				null, null);
 		destAttrs[2] = new AttributeModificationRule(2);
 		Set<Object> nullValues = new HashSet<Object>();
 		nullValues.add(39207);
@@ -127,50 +129,58 @@
 		assertEquals(3, correctedFC.getSchema().getAttributeCount());
 		assertEquals("the_geom", correctedFC.getSchema().getDescriptor(0)
 				.getLocalName());
-		
+
 		assertEquals("arab", correctedFC.getSchema().getDescriptor(1)
 				.getLocalName());
-		
+
 		assertEquals("SURFACE", correctedFC.getSchema().getDescriptor(2)
 				.getLocalName());
 		assertEquals(Integer.class, correctedFC.getSchema().getDescriptor(2)
 				.getType().getBinding());
-		
-		
+
+		Iterator<SimpleFeature> fI = correctedFC.iterator();
+		try {
+			assertTrue(fI.hasNext());
+			SimpleFeature next = fI.next();
+			assertEquals("وكالة الحوض المائي للوكوس", next.getAttribute(1));
+			assertEquals(13591, next.getAttribute(2));
+		} finally {
+			correctedFC.close(fI);
+		}
 	}
 
 	@Test
-	public void testTransformAttributeValue()
-	{
-		assertNull( FeatureUtil.transformAttributeValue(null, Integer.class) );
-		
-		assertEquals("3", FeatureUtil.transformAttributeValue(3, String.class) );
-		assertEquals("3", FeatureUtil.transformAttributeValue("3", String.class) );
-		assertEquals("3.0", FeatureUtil.transformAttributeValue(3., String.class) );
-		
-		assertEquals(3., FeatureUtil.transformAttributeValue(3, Double.class) );
-		assertEquals(3., FeatureUtil.transformAttributeValue("3", Double.class) );
-		assertEquals(3., FeatureUtil.transformAttributeValue(3l, Double.class) );
-		
-		assertEquals(3l, FeatureUtil.transformAttributeValue(3, Long.class) );
-		assertEquals(3l, FeatureUtil.transformAttributeValue("3", Long.class) );
-		assertEquals(3l, FeatureUtil.transformAttributeValue(3l, Long.class) );
-		
-		assertEquals(3l, FeatureUtil.transformAttributeValue(3, Long.class) );
-		assertEquals(3l, FeatureUtil.transformAttributeValue("3", Long.class) );
-		assertEquals(3l, FeatureUtil.transformAttributeValue(3l, Long.class) );
-		
+	public void testTransformAttributeValue() {
+		assertNull(FeatureUtil.transformAttributeValue(null, Integer.class));
+
+		assertEquals("3", FeatureUtil.transformAttributeValue(3, String.class));
+		assertEquals("3",
+				FeatureUtil.transformAttributeValue("3", String.class));
+		assertEquals("3.0",
+				FeatureUtil.transformAttributeValue(3., String.class));
+
+		assertEquals(3., FeatureUtil.transformAttributeValue(3, Double.class));
+		assertEquals(3., FeatureUtil.transformAttributeValue("3", Double.class));
+		assertEquals(3., FeatureUtil.transformAttributeValue(3l, Double.class));
+
+		assertEquals(3l, FeatureUtil.transformAttributeValue(3, Long.class));
+		assertEquals(3l, FeatureUtil.transformAttributeValue("3", Long.class));
+		assertEquals(3l, FeatureUtil.transformAttributeValue(3l, Long.class));
+
+		assertEquals(3l, FeatureUtil.transformAttributeValue(3, Long.class));
+		assertEquals(3l, FeatureUtil.transformAttributeValue("3", Long.class));
+		assertEquals(3l, FeatureUtil.transformAttributeValue(3l, Long.class));
+
 		try {
 			FeatureUtil.transformAttributeValue("A", Long.class);
 			fail();
 		} catch (Exception e) {
-			
+
 		}
 	}
 
 	@Test
-	public void testCleanAttname()
-	{
+	public void testCleanAttname() {
 		assertEquals("AEOEUSH", FeatureUtil.cleanAttname("äöush"));
 		assertEquals("_12312312", FeatureUtil.cleanAttname("12312312"));
 		assertEquals("_123123123", FeatureUtil.cleanAttname("123123123123"));



More information about the Schmitzm-commits mailing list