[Schmitzm-commits] r1161 - in trunk: . src/schmitzm/geotools/io src/schmitzm/io src/schmitzm/jfree/feature/style src/schmitzm/swing src/skrueger/geotools/io src_junit/schmitzm/geotools/feature src_junit/schmitzm/swing src_junit/skrueger/geotools src_junit/skrueger/geotools/io
scm-commit@wald.intevation.org
scm-commit at wald.intevation.org
Sun Oct 24 18:44:22 CEST 2010
Author: alfonx
Date: 2010-10-24 18:44:18 +0200 (Sun, 24 Oct 2010)
New Revision: 1161
Added:
trunk/src/skrueger/geotools/io/DbServerList.java
trunk/src/skrueger/geotools/io/DbServerSettings.java
trunk/src/skrueger/geotools/io/DbSettingsJComboBox.java
trunk/src/skrueger/geotools/io/WfsServerList.java
trunk/src/skrueger/geotools/io/WfsServerSettings.java
trunk/src/skrueger/geotools/io/WfsSettingsJComboBox.java
trunk/src_junit/skrueger/geotools/io/
trunk/src_junit/skrueger/geotools/io/DbServerListTest.java
trunk/src_junit/skrueger/geotools/io/DbServerSettingsTest.java
trunk/src_junit/skrueger/geotools/io/WfsServerListTest.java
trunk/src_junit/skrueger/geotools/io/WfsServerSettingsTest.java
Removed:
trunk/src/skrueger/geotools/io/GeoImportUtilURL.java
Modified:
trunk/pom.xml
trunk/src/schmitzm/geotools/io/GeoImportUtil.java
trunk/src/schmitzm/io/IOUtil.java
trunk/src/schmitzm/jfree/feature/style/FeatureChartUtil.java
trunk/src/schmitzm/swing/MultiSplitPane.java
trunk/src_junit/schmitzm/geotools/feature/FeatureUtilTest.java
trunk/src_junit/schmitzm/swing/TestingUtil.java
Log:
* AtlasSTyler-Feature: Improved the GUI
* AtlasSTyler-Feature: Import Wizards for SHape, PostGIS and WFS
Modified: trunk/pom.xml
===================================================================
--- trunk/pom.xml 2010-10-22 21:35:30 UTC (rev 1160)
+++ trunk/pom.xml 2010-10-24 16:44:18 UTC (rev 1161)
@@ -119,6 +119,13 @@
<dependency>
<groupId>org.geotools</groupId>
+ <artifactId>gt-wfs</artifactId>
+ <version>${geotools.version}</version>
+ <type>jar</type>
+ </dependency>
+
+ <dependency>
+ <groupId>org.geotools</groupId>
<artifactId>gt-swing</artifactId>
<version>${geotools.version}</version>
<type>jar</type>
@@ -224,7 +231,6 @@
<scope>compile</scope>
</dependency>
-
<dependency>
<!-- Fuer Sonderzeichenbehandlung -->
<groupId>ant-contrib</groupId>
@@ -234,7 +240,6 @@
<scope>provided</scope>
</dependency>
-
<dependency>
<!-- Fuer Sonderzeichenbehandlung -->
<groupId>ant</groupId>
@@ -252,6 +257,14 @@
<systemPath>${java.home}/../lib/tools.jar</systemPath>
</dependency>
+ <dependency>
+ <groupId>org.geotools.jdbc</groupId>
+ <artifactId>gt-jdbc-postgis</artifactId>
+ <version>${geotools.version}</version>
+ <type>jar</type>
+ <scope>compile</scope>
+ </dependency>
+
</dependencies>
@@ -369,7 +382,7 @@
<taskdef resource="net/sf/antcontrib/antlib.xml">
<classpath refid="maven.dependency.classpath" />
</taskdef>
-
+
<typedef name="native2ascii"
classname="org.apache.tools.ant.taskdefs.optional.Native2Ascii">
<classpath refid="maven.dependency.classpath" />
Modified: trunk/src/schmitzm/geotools/io/GeoImportUtil.java
===================================================================
--- trunk/src/schmitzm/geotools/io/GeoImportUtil.java 2010-10-22 21:35:30 UTC (rev 1160)
+++ trunk/src/schmitzm/geotools/io/GeoImportUtil.java 2010-10-24 16:44:18 UTC (rev 1161)
@@ -56,6 +56,7 @@
import javax.imageio.IIOException;
import javax.imageio.ImageIO;
+import org.apache.commons.lang.NotImplementedException;
import org.apache.log4j.Logger;
import org.geotools.coverage.grid.GridCoverage2D;
import org.geotools.coverage.grid.GridCoverageFactory;
@@ -77,6 +78,7 @@
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
+import org.opengis.parameter.GeneralParameterValue;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import schmitzm.data.WritableGridRaster;
@@ -92,11 +94,34 @@
*
* @author <a href="mailto:martin.schmitz at koeln.de">Martin Schmitz</a>
* (University of Bonn/Germany)
- * @version 1.0
+ * @author Stefan Tzeggai, wikisquare.de
*/
public class GeoImportUtil {
- private static final Logger LOGGER = Logger.getLogger(GeoImportUtil.class
- .getName());
+ /**
+ * This type specifies how this class can proceed the import of ASCII
+ * rasters.
+ *
+ * @see GeoImportUtil#readGridFromArcInfoASCII(Object,
+ * CoordinateReferenceSystem)
+ * @see GeoImportUtil#readGridRasterFromGeoTiff(File,
+ * CoordinateReferenceSystem)
+ */
+ public static enum ARCASCII_IMPORT_TYPE {
+ /**
+ * Use the old {@link ArcGridRaster}. This works fine (colorization and
+ * no data transparency), but {@link ArcGridRaster} is deprecated and no
+ * longer supported since gt2-2.3.0-M0.
+ */
+ USE_ARCGRIDRASTER,
+ /**
+ * Use the {@link ArcGridReader} from "standard" GT.<br>
+ * <b>Note:</b>There may be problems with colorization and no data
+ * transparency using this import type!<br/>
+ * Stefan Tzeggai 9'2010: This is still valid for GT 2.6.5: No
+ * transparency when using Reader unless explicitly defined in the SLD!
+ */
+ USE_ARCGRIDREADER
+ }
/**
* These postfixes are associated with Arc/Info ASCII Grid files TODO .0
@@ -104,7 +129,7 @@
* packen.
* */
public static enum ARCASCII_POSTFIXES {
- arc, dat, ascii, txt, asc, a00
+ a00, arc, asc, ascii, dat, txt
};
/** These postfixes are associated with GeoTiff files */
@@ -112,31 +137,29 @@
tif, tiff
};
- /** These postfixes are associated with ESRI SHape files */
- static public enum SHP_POSTFIXES {
- shp, sbx, sbn, dbf, shx, /** Non-ESRI QuadTree Index stuff **/
- qix, /** Non-ESRI QuadTree Index stuff **/
- fix,
- /** Supported by ESRI. Contains the name of codepage used inside the DBF **/
- cpg,
- /**
- * Exported by Geoserver. Contains the name of codepage used inside the
- * DBF
- **/
- cst
- };
-
/**
* These postfixes are associated with ordinary image files, excluding
* GeoTIFF endings please
*/
static public enum IMAGE_POSTFIXES {
- png, gif, jpg, jpeg
+ gif, jpeg, jpg, png
};
+ /** These postfixes are associated with ESRI SHape files */
+ static public enum SHP_POSTFIXES {
+ /** Supported by ESRI. Contains the name of codepage used inside the DBF **/
+ cpg, /**
+ * Exported by Geoserver. Contains the name of codepage used inside
+ * the DBF
+ **/
+ cst, dbf, /** Non-ESRI QuadTree Index stuff **/
+ fix, /** Non-ESRI QuadTree Index stuff **/
+ qix, sbn, sbx, shp, shx
+ };
+
/** These postfixes are associated with world files */
static public enum WORLD_POSTFIXES {
- wld, jgw, pgw, tfw
+ jgw, pgw, tfw, wld
};
// /////////////////////////////////////////////////////////////////////////
@@ -144,32 +167,6 @@
// /////////////////////////////////////////////////////////////////////////
/**
- * This type specifies how this class can proceed the import of ASCII
- * rasters.
- *
- * @see GeoImportUtil#readGridFromArcInfoASCII(Object,
- * CoordinateReferenceSystem)
- * @see GeoImportUtil#readGridRasterFromGeoTiff(File,
- * CoordinateReferenceSystem)
- */
- public static enum ARCASCII_IMPORT_TYPE {
- /**
- * Use the old {@link ArcGridRaster}. This works fine (colorization and
- * no data transparency), but {@link ArcGridRaster} is deprecated and no
- * longer supported since gt2-2.3.0-M0.
- */
- USE_ARCGRIDRASTER,
- /**
- * Use the {@link ArcGridReader} from "standard" GT.<br>
- * <b>Note:</b>There may be problems with colorization and no data
- * transparency using this import type!<br/>
- * Stefan Tzeggai 9'2010: This is still valid for GT 2.6.5: No
- * transparency when using Reader unless explicitly defined in the SLD!
- */
- USE_ARCGRIDREADER
- }
-
- /**
* Specifies how this class proceeds the import of ASCII rasters. The
* default is {@link ARCASCII_IMPORT_TYPE#USE_ARCGRIDREADER} because this
* works fine!
@@ -182,20 +179,33 @@
private static ARCASCII_IMPORT_TYPE ARCASCII_IMPORT_MODE = ARCASCII_IMPORT_TYPE.USE_ARCGRIDRASTER;
/**
- * Sets how this class proceeds the import of ASCII rasters.
- *
- * @param mode
- * the mode how to proceed the import
+ * Standard-CRS, welches verwendet wird, wenn beim Import kein CRS ermittelt
+ * werden kann (Default: {@link DefaultGeographicCRS#WGS84}).<br>
+ * <b>Achtung:</b><br>
+ * Anwendungen koennen diese Variable gefahrlos ueberschreiben, um ein fuer
+ * die Anwendung adaequates Standard-CRS zu verwenden.
*/
- public static void setAsciiRasterImportMode(ARCASCII_IMPORT_TYPE mode) {
- ARCASCII_IMPORT_MODE = mode;
- }
+ private static CoordinateReferenceSystem DEFAULT_CRS = DefaultGeographicCRS.WGS84;
+ private static final Logger LOGGER = Logger.getLogger(GeoImportUtil.class
+ .getName());
+
/**
- * Returns the default CRS used if no CRS can be found during import.
+ * Diese Methode erzeugt einen {@link AbstractGridCoverage2DReader} aus
+ * einer Datei im GeoTIFF-Format.
+ *
+ * @param file
+ * GeoTIFF-File
+ * @throws java.lang.Exception
+ * bei irgendeinem Fehler
+ * @see #createGridReaderFromGeoTiff(File, CoordinateReferenceSystem)
+ * @deprecated {@link WorldImageReader} klappt noch nicht so 100%ig
+ * (Colorisierung schlaegt fehl!)
*/
- public static ARCASCII_IMPORT_TYPE getAsciiRasterImportMode() {
- return ARCASCII_IMPORT_MODE;
+ @Deprecated
+ public static AbstractGridCoverage2DReader createGridReaderFromGeoTiff(
+ File file) throws Exception {
+ return createGridReaderFromGeoTiff(file, null);
}
// /////////////////////////////////////////////////////////////////////////
@@ -203,32 +213,275 @@
// /////////////////////////////////////////////////////////////////////////
/**
- * Standard-CRS, welches verwendet wird, wenn beim Import kein CRS ermittelt
- * werden kann (Default: {@link DefaultGeographicCRS#WGS84}).<br>
- * <b>Achtung:</b><br>
- * Anwendungen koennen diese Variable gefahrlos ueberschreiben, um ein fuer
- * die Anwendung adaequates Standard-CRS zu verwenden.
+ * Diese Methode erzeugt einen {@link AbstractGridCoverage2DReader} aus
+ * einer Datei im GeoTIFF-Format. Zunaechst wird versucht, die
+ * Geo-Informationen (Referenz+CRS) aus den TIFF-Metadaten zu ermitteln. Ist
+ * dies nicht erfolgreich, werden ein gleichnamiges World-File (.tfw) und
+ * Projection-File (.prj) herangezogen (siehe {@link WorldImageReader}).
+ *
+ * @param file
+ * GeoTIFF-File
+ * @param crs
+ * erzwungenes CoordinateReferenceSystem fuer das Raster (kann
+ * {@code null} sein)
+ * @throws java.lang.Exception
+ * bei irgendeinem Fehler
+ * @deprecated {@link WorldImageReader} klappt noch nicht so 100%ig
+ * (Colorisierung schlaegt fehl!)
*/
- private static CoordinateReferenceSystem DEFAULT_CRS = DefaultGeographicCRS.WGS84;
+ @Deprecated
+ public static AbstractGridCoverage2DReader createGridReaderFromGeoTiff(
+ File file, CoordinateReferenceSystem crs) throws Exception {
+ // Versuchen Geo-Information aus Tiff zu lesen
+ try {
+ Hints hints = new Hints();
+ // Wenn CRS angegeben, dieses durch Hint erzwingen
+ if (crs != null)
+ hints.put(Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM, crs);
+ // Reader (mit Metadaten) erzeugen
+ GeoTiffReader reader = new GeoTiffReader(file, hints);
+ // Wenn kein Referenzsystem vorhanden, versuchen ein prj-File zu
+ // verwenden
+ if (reader.getOriginalEnvelope().getCoordinateReferenceSystem() == null) {
+ LOGGER.warn("No projection information found in '"
+ + file.getName() + "'. Using prj-file...");
+ hints.put(Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM,
+ determineProjection(file));
+ reader = new GeoTiffReader(file, hints);
+ }
+ return reader;
+ } catch (UnsupportedOperationException err) {
+ // erwartet, wenn keine Geo-Information im Tiff vorhanden ist
+ } catch (NullPointerException err) {
+ // erwartet, wenn keine Geo-Information im Tiff vorhanden ist
+ }
+ // keine Geo-Informationen in Tiff
+ // --> Raster ueber ImageIO einlesen und WorldFile/ProjectionFile
+ // verwenden
+ LOGGER.warn("No geo information found in '" + file.getName()
+ + "'. Using world- and prj-file...");
+ // @todo check the work of WorldImageReader with colorization!
+ throw new UnsupportedOperationException(
+ "WorldImageReader does not work well, yet... AbstractGridCoverage2DReader can not be created from this Tiff!");
+ // Hints hints = new Hints();
+ // // Wenn CRS angegeben, dieses durch Hint erzwingen
+ // if ( crs != null )
+ // hints.put( Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM, crs );
+ // WorldImageReader reader = new WorldImageReader(file);
+ // return reader;
+ }
+
/**
- * Sets the default CRS used if no CRS can be found during import.
+ * Liest das CRS aus einer Datei. Zunaechst wird versucht das CRS aus der
+ * uebergebene Datei zu lesen. Ist dies nicht erfolgreich wird das zur Datei
+ * korrespondierende prj-File herangezogen.
*
- * @param crs
- * the new default CRS
+ * @param file
+ * Datei
+ * @return {@code null}, wenn kein CRS gelesen werden konnte
*/
- public static void setDefaultCRS(CoordinateReferenceSystem crs) {
- DEFAULT_CRS = crs;
+ public static CoordinateReferenceSystem determineProjection(File file)
+ throws IOException {
+ return determineProjection(DataUtilities.fileToURL(file));
}
/**
+ * 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.
+ *
+ * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons Tzeggai</a>
+ */
+ public static CoordinateReferenceSystem determineProjection(URL prjUrl) {
+ CoordinateReferenceSystem crs = null;
+ try {
+ crs = GeoImportUtil.readProjectionFile(prjUrl);
+ } catch (IOException e) {
+ }
+
+ if (crs == null) {
+ try {
+ crs = GeoImportUtil.readProjectionFile(IOUtil.changeUrlExt(
+ prjUrl, "prj"));
+ } catch (IllegalArgumentException e) {
+ } catch (IOException e) {
+ }
+ }
+
+ if (crs == null) {
+ try {
+ crs = GeoImportUtil.readProjectionFile(IOUtil.changeUrlExt(
+ prjUrl, "PRJ"));
+ } catch (IllegalArgumentException e) {
+ } catch (IOException e) {
+ }
+ }
+
+ // Wenn nicht erfolgreich, Default verwenden
+ if (crs == null) {
+ LOGGER.warn("No projection found in URL. Default CRS used.");
+ crs = getDefaultCRS();
+ }
+ return crs;
+ }
+
+ /**
* Returns the default CRS used if no CRS can be found during import.
*/
+ public static ARCASCII_IMPORT_TYPE getAsciiRasterImportMode() {
+ return ARCASCII_IMPORT_MODE;
+ }
+
+ /**
+ * The URLs where a <code>.cpg</code> or <code>.cst</code> file describing
+ * the {@link Charset} could be found.
+ *
+ * @param url_
+ * must be an {@link URL} with an extension. The extensions will
+ * then the changed for possible charset containing extensions.
+ */
+ 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") };
+ }
+
+ /**
+ * Returns the default CRS used if no CRS can be found during import.
+ */
public static CoordinateReferenceSystem getDefaultCRS() {
return DEFAULT_CRS;
}
+ /**
+ * Tries to read a file containing {@link Charset} information next to a
+ * {@link URL}.
+ *
+ * @return <code>null</code> is nothing found.
+ */
+ public static Charset readCharset(URL url) {
+ URL[] cpgUrls = GeoImportUtil.getCharsetUrls(url);
+ for (URL cpgUrl : cpgUrls) {
+ try {
+ String charsetName = IOUtil.readURLasString(cpgUrl);
+
+ if (charsetName.equals(""))
+ continue;
+
+ return Charset.forName(charsetName);
+
+ } catch (Exception e) {
+ // LOGGER.warn("Reading .cpg file failed for "+cpgUrl+". Using default. ");
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Creates a {@link DataStore} from shape file
+ *
+ * @param shpURL
+ * URL to shape file
+ * @param prjURL
+ * URL to projection file
+ * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons Tzeggai</a>
+ * @throws IOException
+ * if an error occur
+ */
+ public static DataStore readDataStoreFromShape(URL shpURL, URL prjURL)
+ throws IOException {
+ Map<Object, Object> map = new HashMap<Object, Object>();
+ map.put("url", shpURL);
+ map.put("create spatial index", true);
+
+ DataStore dataStore = DataStoreFinder.getDataStore(map);
+ //
+ // // DataStore dataStore = DataStoreFinder.getDataStore( map );
+ // DataStore dataStore = new IndexedShapefileDataStore(shpURL, null,
+ // false, true, IndexType.QIX);
+ // // DataStore dataStore = new ShapefileDataStore(shpURL);
+ // LOGGER.debug("DataStore = " + dataStore.getClass().toString());
+ // IndexedShapefileDataStore dataStoreIndex =
+ // (IndexedShapefileDataStore) dataStore;
+ // try {
+ // LOGGER.debug("indexed = " + dataStoreIndex.isIndexed());
+ // LOGGER.debug("memory = " + dataStoreIndex.isMemoryMapped());
+ // } catch (Exception e) {
+ // System.err.println(e);
+ // }
+
+ return dataStore;
+ }
+
// /////////////////////////////////////////////////////////////////////////
+ // RASTER IMPORT (GridCoverage2D)
+ // /////////////////////////////////////////////////////////////////////////
+
+ /**
+ * Diese Methode extrahiert saemtliche Features aus einem ShapeFile-Projekt
+ * (<code><i>name</i>.shp <i>name</i>.prj <i>name</i>.dbf ...</code>) und
+ * speichert diese in einer
+ * <code>org.geotools.feature.FeatureCollection</code>.<br>
+ *
+ * @param file
+ * Shape-File
+ * @throws java.lang.Exception
+ * bei irgendeinem Fehler
+ *
+ * @author <a href="mailto:martin.schmitz at koeln.de">Martin Schmitz</a>
+ * (University of Bonn/Germany)
+ */
+ public static FeatureCollection<SimpleFeatureType, SimpleFeature> readFeaturesFromShapeFile(
+ File file) throws Exception {
+
+ return readFeaturesFromShapeURL(DataUtilities.fileToURL(file));
+
+ // 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;
+ }
+
+ // /////////////////////////////////////////////////////////////////////////
// FEATURE IMPORT
// /////////////////////////////////////////////////////////////////////////
/**
@@ -248,6 +501,22 @@
return readFeaturesFromShapeURL(url, null);
}
+ // 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;
+ // }
+
/**
* Diese Methode extrahiert saemtliche Features aus einem ShapeFile-Projekt
* (<code><i>name</i>.shp <i>name</i>.prj <i>name</i>.dbf ...</code>) und
@@ -319,104 +588,6 @@
}
/**
- * Diese Methode extrahiert saemtliche Features aus einem ShapeFile-Projekt
- * (<code><i>name</i>.shp <i>name</i>.prj <i>name</i>.dbf ...</code>) und
- * speichert diese in einer
- * <code>org.geotools.feature.FeatureCollection</code>.<br>
- *
- * @param file
- * Shape-File
- * @throws java.lang.Exception
- * bei irgendeinem Fehler
- *
- * @author <a href="mailto:martin.schmitz at koeln.de">Martin Schmitz</a>
- * (University of Bonn/Germany)
- */
- public static FeatureCollection<SimpleFeatureType, SimpleFeature> readFeaturesFromShapeFile(
- File file) throws Exception {
-
- return readFeaturesFromShapeURL(DataUtilities.fileToURL(file));
-
- // 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;
- }
-
- /**
- * Creates a {@link DataStore} from shape file
- *
- * @param shpURL
- * URL to shape file
- * @param prjURL
- * URL to projection file
- * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons Tzeggai</a>
- * @throws IOException
- * if an error occur
- */
- public static DataStore readDataStoreFromShape(URL shpURL, URL prjURL)
- throws IOException {
- Map<Object, Object> map = new HashMap<Object, Object>();
- map.put("url", shpURL);
- map.put("create spatial index", true);
-
- DataStore dataStore = DataStoreFinder.getDataStore(map);
- //
- // // DataStore dataStore = DataStoreFinder.getDataStore( map );
- // DataStore dataStore = new IndexedShapefileDataStore(shpURL, null,
- // false, true, IndexType.QIX);
- // // DataStore dataStore = new ShapefileDataStore(shpURL);
- // LOGGER.debug("DataStore = " + dataStore.getClass().toString());
- // IndexedShapefileDataStore dataStoreIndex =
- // (IndexedShapefileDataStore) dataStore;
- // try {
- // LOGGER.debug("indexed = " + dataStoreIndex.isIndexed());
- // LOGGER.debug("memory = " + dataStoreIndex.isMemoryMapped());
- // } catch (Exception e) {
- // System.err.println(e);
- // }
-
- return dataStore;
- }
-
- /**
* Diese Methode extrahiert saemtliche Geometrien aus einem
* ShapeFile-Projekt (
* <code><i>name</i>.shp <i>name</i>.prj <i>name</i>.dbf ...</code>) und
@@ -455,9 +626,40 @@
return geomList;
}
- // /////////////////////////////////////////////////////////////////////////
- // RASTER IMPORT (GridCoverage2D)
- // /////////////////////////////////////////////////////////////////////////
+ // NOT USED ANYMORE: File and URL are handled by the same method using
+ // Object
+ // /**
+ // * Diese Methode importiert ein Raster aus einer Datei im
+ // * ArcInfoASCII-Grid-Format. Das CRS wird aus einem prj-File (EPSG-Code
+ // * "EPSG:..." oder WKT-Definition) gelesen. Ist dies nicht erfolgreich,
+ // wird
+ // * {@link #DEFAULT_CRS} als CRS verwendet.
+ // * @param file ASCII-File
+ // * @throws java.lang.Exception bei irgendeinem Fehler
+ // * @return {@link GridCoverage2D}
+ // */
+ // public static GridCoverage2D readGridFromArcInfoASCII(File file) throws
+ // Exception {
+ // return readGridFromArcInfoASCII(file, null);
+ // }
+ //
+ // /**
+ // * Diese Methode importiert ein Raster aus einer Datei im
+ // * ArcInfoASCII-Grid-Format. Wenn kein CRS angegeben wird, wird versucht
+ // das
+ // * CRS aus einem prj-File (EPSG-Code "EPSG:..." oder WKT-Definition) zu
+ // * lesen. Ist dies nicht erfolgreich, wird {@link #DEFAULT_CRS} als CRS
+ // * verwendet.
+ // * @param file ASCII-File
+ // * @param crs CoordinateReferenceSystem fuer das Raster (kann {@code null}
+ // sein)
+ // * @throws MalformedURLException if the file can not be converted to URL
+ // * @throws Exception bei irgendeinem Fehler
+ // */
+ // public static GridCoverage2D readGridFromArcInfoASCII(File file,
+ // CoordinateReferenceSystem crs) throws MalformedURLException, Exception {
+ // return readGridFromArcInfoASCII(file.toURI().toURL(), crs);
+ // }
/**
* Imports a raster from file or URL in ArcInfoASCII format. The CRS is
@@ -497,45 +699,11 @@
+ 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;
- // }
+ // /////////////////////////////////////////////////////////////////////////
+ // RASTER IMPORT (AbstractGridCoverage2DReader)
+ // /////////////////////////////////////////////////////////////////////////
/**
- * Uses the <b>{@link ArcGridReader} class</b> (standard GT) to import a
- * raster from file or URL in ArcInfoASCII format. The CRS is taken from
- * prj-file (EPSG-Code "EPSG:..." oder WKT-Definition). If not present the
- * {@link #DEFAULT_CRS} is used.
- *
- * @param input
- * file or URL to the input file
- * @param crs
- * CRS forced to use (can be <code>null</code>)
- */
- private static GridCoverage2D readGridFromArcInfoASCII_ArcGridReader(
- Object input, CoordinateReferenceSystem crs) throws Exception {
- Hints hints = new Hints();
- if (crs != null) {
- hints.put(Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM, crs);
- }
- ArcGridReader reader = new ArcGridReader(input, hints);
- GridCoverage2D gc = (GridCoverage2D) reader.read(null);
- return gc;
- }
-
- /**
* Uses the <b>{@link ArcGridRaster} class</b> (standard GT) to import a
* raster from file or URL in ArcInfoASCII format. The CRS is taken from
* prj-file (EPSG-Code "EPSG:..." oder WKT-Definition). If not present the
@@ -592,41 +760,32 @@
return new GridCoverageFactory().create("", raster, envelope);
}
- // NOT USED ANYMORE: File and URL are handled by the same method using
- // Object
- // /**
- // * Diese Methode importiert ein Raster aus einer Datei im
- // * ArcInfoASCII-Grid-Format. Das CRS wird aus einem prj-File (EPSG-Code
- // * "EPSG:..." oder WKT-Definition) gelesen. Ist dies nicht erfolgreich,
- // wird
- // * {@link #DEFAULT_CRS} als CRS verwendet.
- // * @param file ASCII-File
- // * @throws java.lang.Exception bei irgendeinem Fehler
- // * @return {@link GridCoverage2D}
- // */
- // public static GridCoverage2D readGridFromArcInfoASCII(File file) throws
- // Exception {
- // return readGridFromArcInfoASCII(file, null);
- // }
- //
- // /**
- // * Diese Methode importiert ein Raster aus einer Datei im
- // * ArcInfoASCII-Grid-Format. Wenn kein CRS angegeben wird, wird versucht
- // das
- // * CRS aus einem prj-File (EPSG-Code "EPSG:..." oder WKT-Definition) zu
- // * lesen. Ist dies nicht erfolgreich, wird {@link #DEFAULT_CRS} als CRS
- // * verwendet.
- // * @param file ASCII-File
- // * @param crs CoordinateReferenceSystem fuer das Raster (kann {@code null}
- // sein)
- // * @throws MalformedURLException if the file can not be converted to URL
- // * @throws Exception bei irgendeinem Fehler
- // */
- // public static GridCoverage2D readGridFromArcInfoASCII(File file,
- // CoordinateReferenceSystem crs) throws MalformedURLException, Exception {
- // return readGridFromArcInfoASCII(file.toURI().toURL(), crs);
- // }
+ /**
+ * Uses the <b>{@link ArcGridReader} class</b> (standard GT) to import a
+ * raster from file or URL in ArcInfoASCII format. The CRS is taken from
+ * prj-file (EPSG-Code "EPSG:..." oder WKT-Definition). If not present the
+ * {@link #DEFAULT_CRS} is used.
+ *
+ * @param input
+ * file or URL to the input file
+ * @param crs
+ * CRS forced to use (can be <code>null</code>)
+ */
+ private static GridCoverage2D readGridFromArcInfoASCII_ArcGridReader(
+ Object input, CoordinateReferenceSystem crs) throws Exception {
+ Hints hints = new Hints();
+ if (crs != null) {
+ hints.put(Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM, crs);
+ }
+ ArcGridReader reader = new ArcGridReader(input, hints);
+ GridCoverage2D gc = reader.read(null);
+ return gc;
+ }
+ // /////////////////////////////////////////////////////////////////////////
+ // RASTER IMPORT (WritableGridRaster)
+ // /////////////////////////////////////////////////////////////////////////
+
/**
* Diese Methode importiert ein Raster aus einer Datei im GeoTIFF-Format.
*
@@ -680,7 +839,7 @@
determineProjection(file));
reader = new GeoTiffReader(file, hints);
}
- gc = (GridCoverage2D) reader.read(null);
+ gc = reader.read(null);
return gc;
} catch (UnsupportedOperationException err) {
// erwartet, wenn keine Geo-Information im Tiff vorhanden ist
@@ -723,90 +882,180 @@
return gc;
}
- // /////////////////////////////////////////////////////////////////////////
- // RASTER IMPORT (AbstractGridCoverage2DReader)
- // /////////////////////////////////////////////////////////////////////////
-
/**
- * Diese Methode erzeugt einen {@link AbstractGridCoverage2DReader} aus
- * einer Datei im GeoTIFF-Format. Zunaechst wird versucht, die
- * Geo-Informationen (Referenz+CRS) aus den TIFF-Metadaten zu ermitteln. Ist
- * dies nicht erfolgreich, werden ein gleichnamiges World-File (.tfw) und
- * Projection-File (.prj) herangezogen (siehe {@link WorldImageReader}).
- *
- * @param file
- * GeoTIFF-File
+ * @param input
+ * URL, File oder InputStream to a GeoTIFF-File
* @param crs
* erzwungenes CoordinateReferenceSystem fuer das Raster (kann
* {@code null} sein)
- * @throws java.lang.Exception
- * bei irgendeinem Fehler
- * @deprecated {@link WorldImageReader} klappt noch nicht so 100%ig
- * (Colorisierung schlaegt fehl!)
+ *
+ * @author <a href="mailto:martin.schmitz at koeln.de">Martin Schmitz</a>
+ * (University of Bonn/Germany)
+ * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons Tzeggai</a>
+ *
+ * @param readParams
+ * May be {@link NullPointerException}. Otherwise an array of
+ * {@link GeneralParameterValue}s
*/
- public static AbstractGridCoverage2DReader createGridReaderFromGeoTiff(
- File file, CoordinateReferenceSystem crs) throws Exception {
+ public static GridCoverage2D readGridFromGeoTiff(Object input,
+ CoordinateReferenceSystem crs, GeneralParameterValue[] readParams)
+ throws IOException {
+ GridCoverage2D gc = null;
+ LOGGER.debug("Loading GeoTiff from URL = " + input + " now.");
+
// Versuchen Geo-Information aus Tiff zu lesen
+
+ // Wenn CRS angegeben, dieses durch Hint erzwingen
+ Hints hints = new Hints();
+
+ if (crs != null)
+ hints.put(Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM, crs);
+ // Reader (mit Metadaten) erzeugen
+
+ LOGGER.debug("First try to create GeoTiff reader");
+
+ /**
+ * Attention, Attention: The GeoTiffReader fails for URLs like:
+ *
+ * jar:file:/home/sdsd/ad/atlas/raster_textur00949608497.jar!/ad/data/
+ * raster_textur00949608497/textur.tif
+ *
+ * It should be converted to something like:
+ * jar:http:///atlas/raster_textur00949608497
+ * .jar!/ad/data/raster_textur00949608497/textur.tif
+ * jar:http://www.wikisquare
+ * .de/atlas/raster_textur00949608497.jar!/ad/data
+ * /raster_textur00949608497/textur.tif
+ */
+
try {
- Hints hints = new Hints();
- // Wenn CRS angegeben, dieses durch Hint erzwingen
- if (crs != null)
- hints.put(Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM, crs);
- // Reader (mit Metadaten) erzeugen
- GeoTiffReader reader = new GeoTiffReader(file, hints);
- // Wenn kein Referenzsystem vorhanden, versuchen ein prj-File zu
+
+ GeoTiffReader reader = new GeoTiffReader(input, hints);
+
+ gc = reader.read(readParams);
+ LOGGER.debug("... was successfull!");
+ return gc;
+ } catch (Exception e) {
+ // keine Geo-Informationen in Tiff
+ // --> Raster ueber ImageIO einlesen und WorldFile/ProjectionFile
// verwenden
- if (reader.getOriginalEnvelope().getCoordinateReferenceSystem() == null) {
- LOGGER.warn("No projection information found in '"
- + file.getName() + "'. Using prj-file...");
- hints.put(Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM,
- determineProjection(file));
- reader = new GeoTiffReader(file, hints);
+ LOGGER.warn("No geo information found in '" + input
+ + "'. Using world- and prj-file...");
+
+ BufferedImage im = null;
+ double[] tfwInfo = null;
+ if (input instanceof File) {
+ im = ImageIO.read((File) input);
+ tfwInfo = readWorldFile(IOUtil.changeFileExt((File) input,
+ "tfw"));
+ if (crs == null)
+ crs = determineProjection((File) input);
+ } else if (input instanceof URL) {
+ tfwInfo = readWorldFile(IOUtil.changeUrlExt((URL) input, "tfw")
+ .openStream());
+ im = ImageIO.read((URL) input);
+ if (crs == null)
+ crs = determineProjection((URL) input);
}
- return reader;
- } catch (UnsupportedOperationException err) {
- // erwartet, wenn keine Geo-Information im Tiff vorhanden ist
- } catch (NullPointerException err) {
- // erwartet, wenn keine Geo-Information im Tiff vorhanden ist
+
+ if (im == null)
+ throw new IIOException(
+ "No image reader found for this image type!");
+ // World-File einlesen
+
+ float w = (float) (im.getWidth() * tfwInfo[0]); // reale Breite =
+ // RasterSpalten * hor.
+ // Aufloesung
+ float h = (float) (im.getHeight() * (-tfwInfo[3])); // reale Hoehe =
+ // RasterZeilen *
+ // vert. Aufloesung
+ float x = (float) tfwInfo[4]; // Suedwestliche Ecke!
+ float y = (float) tfwInfo[5] - h; // Suedwestliche Ecke (im tfw-File
+ // steht die Nordwestliche!)
+ // ggf. Projektion einlesen
+ Envelope2D envelope = new Envelope2D(crs, new Rectangle2D.Float(x,
+ y, w, h));
+ // WICHTIG: Name des Rasters sollte Leer-String sein, da ansonsten
+ // das
+ // Coloring des Rasters nicht klappt.
+ // --> Name der Categories muss (warum auch immer) mit dem Namen
+ // des Rasters uebereinstimmen!!!
+ gc = new GridCoverageFactory().create("", im.copyData(null),
+ envelope);
+ return gc;
}
+ }
- // keine Geo-Informationen in Tiff
- // --> Raster ueber ImageIO einlesen und WorldFile/ProjectionFile
- // verwenden
- LOGGER.warn("No geo information found in '" + file.getName()
- + "'. Using world- and prj-file...");
- // @todo check the work of WorldImageReader with colorization!
- throw new UnsupportedOperationException(
- "WorldImageReader does not work well, yet... AbstractGridCoverage2DReader can not be created from this Tiff!");
- // Hints hints = new Hints();
- // // Wenn CRS angegeben, dieses durch Hint erzwingen
- // if ( crs != null )
- // hints.put( Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM, crs );
- // WorldImageReader reader = new WorldImageReader(file);
- // return reader;
+ /**
+ * Read a {@link GridCoverage2D} from an image file. .prj and .wld files are
+ * usually expected
+ */
+ public static GridCoverage2D readGridFromImage(URL url) throws IOException {
+ return readGridFromImage(url, null);
}
/**
- * Diese Methode erzeugt einen {@link AbstractGridCoverage2DReader} aus
- * einer Datei im GeoTIFF-Format.
+ * Read a {@link GridCoverage2D} from an image file. .wld file is usually
+ * expected also. The CRS can be given as the crs parameter. null is valid.
*
- * @param file
- * GeoTIFF-File
- * @throws java.lang.Exception
- * bei irgendeinem Fehler
- * @see #createGridReaderFromGeoTiff(File, CoordinateReferenceSystem)
- * @deprecated {@link WorldImageReader} klappt noch nicht so 100%ig
- * (Colorisierung schlaegt fehl!)
+ * @author <a href="mailto:martin.schmitz at koeln.de">Martin Schmitz</a>
+ * (University of Bonn/Germany)
+ * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons Tzeggai</a>
*/
- public static AbstractGridCoverage2DReader createGridReaderFromGeoTiff(
- File file) throws Exception {
- return createGridReaderFromGeoTiff(file, null);
+ public static GridCoverage2D readGridFromImage(URL url,
+ CoordinateReferenceSystem crs) throws IOException {
+ GridCoverage2D gc = null;
+
+ BufferedImage im = ImageIO.read(url);
+ if (im == null)
+ throw new IIOException("No image reader found for this image type!");
+
+ // World-File einlesen
+ double[] tfwInfo = null;
+
+ for (WORLD_POSTFIXES pf : WORLD_POSTFIXES.values()) {
+ if (tfwInfo == null) {
+ try {
+ tfwInfo = readWorldFile(IOUtil.changeUrlExt(url,
+ pf.toString()).openStream());
+ } catch (Exception e) {
+ }
+ }
+ }
+
+ if (tfwInfo == null)
+ throw new IllegalArgumentException(
+ "No georeferencing information found.\n"
+ + "Attach a .wld file to " + url + "please.");
+
+ float w = (float) (im.getWidth() * tfwInfo[0]); // reale Breite =
+ // RasterSpalten *
+ // hor. Aufloesung
+ float h = (float) (im.getHeight() * (-tfwInfo[3])); // reale Hoehe =
+ // RasterZeilen
+ // * vert.
+ // Aufloesung
+ float x = (float) tfwInfo[4]; // Suedwestliche Ecke!
+ float y = (float) tfwInfo[5] - h; // Suedwestliche Ecke (im
+ // tfw-File steht die
+ // Nordwestliche!)
+ // ggf. Projektion einlesen
+ if (crs == null) {
+ crs = determineProjection(IOUtil.changeUrlExt(url, "prj"));
+ }
+ Envelope2D envelope = new Envelope2D(crs, new Rectangle2D.Float(x, y,
+ w, h));
+ // WICHTIG: Name des Rasters sollte Leer-String sein, da ansonsten
+ // das
+ // Coloring des Rasters nicht klappt.
+ // --> Name der Categories und ColorMapEntries-Labels muss (warum auch
+ // immer) mit dem Namen
+ // des Rasters uebereinstimmen!!!
+ gc = new GridCoverageFactory().create("", im, envelope);
+
+ return gc;
}
- // /////////////////////////////////////////////////////////////////////////
- // RASTER IMPORT (WritableGridRaster)
- // /////////////////////////////////////////////////////////////////////////
-
/**
* Import a raster from file or URL in ArcInfoASCII format. The CRS is taken
* from prj-file (EPSG-Code "EPSG:..." oder WKT-Definition). If not present
@@ -844,24 +1093,6 @@
}
/**
- * Uses the <b>{@link ArcGridReader} class</b> (standard GT) to import a
- * raster from file or URL in ArcInfoASCII format. The CRS is taken from
- * prj-file (EPSG-Code "EPSG:..." oder WKT-Definition). If not present the
- * {@link #DEFAULT_CRS} is used.
- *
- * @param input
- * file or URL to the input file
- * @param crs
- * CRS forced to use (can be <code>null</code>)
- */
- private static WritableGridRaster readGridRasterFromArcInfoASCII_ArcGridReader(
- Object input, CoordinateReferenceSystem crs) throws Exception {
- GridCoverage2D grid = readGridFromArcInfoASCII(input, crs);
- WritableRaster raster = grid.getRenderedImage().copyData(null);
- return new WritableGridRaster(raster, grid.getEnvelope2D());
- }
-
- /**
* Uses the <b>{@link ArcGridRaster} class</b> (standard GT) to import a
* raster from file or URL in ArcInfoASCII format. The CRS is taken from
* prj-file (EPSG-Code "EPSG:..." oder WKT-Definition). If not present the
@@ -913,7 +1144,29 @@
return new WritableGridRaster(raster, envelope, crs);
}
+ // /////////////////////////////////////////////////////////////////////////
+ // META DATA IMPORT (PROJECTION)
+ // /////////////////////////////////////////////////////////////////////////
+
/**
+ * Uses the <b>{@link ArcGridReader} class</b> (standard GT) to import a
+ * raster from file or URL in ArcInfoASCII format. The CRS is taken from
+ * prj-file (EPSG-Code "EPSG:..." oder WKT-Definition). If not present the
+ * {@link #DEFAULT_CRS} is used.
+ *
+ * @param input
+ * file or URL to the input file
+ * @param crs
+ * CRS forced to use (can be <code>null</code>)
+ */
+ private static WritableGridRaster readGridRasterFromArcInfoASCII_ArcGridReader(
+ Object input, CoordinateReferenceSystem crs) throws Exception {
+ GridCoverage2D grid = readGridFromArcInfoASCII(input, crs);
+ WritableRaster raster = grid.getRenderedImage().copyData(null);
+ return new WritableGridRaster(raster, grid.getEnvelope2D());
+ }
+
+ /**
* Diese Methode importiert ein Raster aus einer Datei im GeoTIFF-Format.
* Zunaechst wird versucht, die Geo-Informationen (Referenz+CRS) aus den
* TIFF-Metadaten zu ermitteln. Ist dies nicht erfolgreich, werden ein
@@ -993,161 +1246,25 @@
return raster;
}
- // /////////////////////////////////////////////////////////////////////////
- // META DATA IMPORT (WORLD FILE)
- // /////////////////////////////////////////////////////////////////////////
/**
- * Liest ein World-File (.tfw) ein und liefert die darin zeilenweise
- * gespeicherten Werte zurueck. Leer- und Kommentarzeilen werden dabei
- * ignoriert. Kann ein Zeilen-Wert nicht in einen <code>double</code>
- * umgewandelt werden, wird diese Zeile ignoriert, als 1.0 interpretiert und
- * eine Meldung in die Standard-Fehler-Ausgabe geschrieben.<br>
- * Der zurueckgegebene Array hat mindestens die Groesse 6:<br>
- * <ol>
- * <li>Zellengroesse in X-Richtung (in Meter)</li>
- * <li>Koeffizient fuer Rotation in Y-Richtung</li>
- * <li>Koeffizient fuer Rotation in X-Richtung</li>
- * <li>negative Zellengroesse in Y-Richtung (in Meter)</li>
- * <li>Horizontale Geo-Referenz (Longitude) der nord-westlichen Ecke</li>
- * <li>Vertikale Geo-Referenz (Latitude) der nord-westlichen Ecke</li>
- * </ol>
+ * Liest ein CRS aus einer Datei. Als Dateiinhalt wird entweder ein
+ * EPSG-Code oder eine WKT-Definition des CRS akzeptiert.
*
- * @todo WorldFile-Spec vervollstaendigen
- * @param file
- * World-File
- * @exception IOException
- * falls die Datei nicht existiert oder ein unerwarteter
- * Fehler beim Einlesen auftritt
- * @see IOUtil#isCommentLine(String)
- * @see System#err
- */
-
- public static double[] readWorldFile(File file) throws IOException {
- return readWorldFile(new FileInputStream(file));
- }
-
- /**
- * Liest ein World-File (.tfw) ein und liefert die darin zeilenweise
- * gespeicherten Werte zurueck. Leer- und Kommentarzeilen werden dabei
- * ignoriert. Kann ein Zeilen-Wert nicht in einen <code>double</code>
- * umgewandelt werden, wird diese Zeile ignoriert, als 1.0 interpretiert und
- * eine Meldung in die Standard-Fehler-Ausgabe geschrieben.<br>
- * Der zurueckgegebene Array hat mindestens die Groesse 6:<br>
- * <ol>
- * <li>Zellengroesse in X-Richtung (in Meter)</li>
- * <li>Koeffizient fuer Rotation in Y-Richtung</li>
- * <li>Koeffizient fuer Rotation in X-Richtung</li>
- * <li>negative Zellengroesse in Y-Richtung (in Meter)</li>
- * <li>Horizontale Geo-Referenz (Longitude) der nord-westlichen Ecke</li>
- * <li>Vertikale Geo-Referenz (Latitude) der nord-westlichen Ecke</li>
- * </ol>
+ * @param prjFile
+ * prj-Datei in der die Projektion hinterlegt ist
+ * @return {@code null}, wenn kein CRS gelesen werden konnte
+ * @see GTUtil#createCRS(String)
*
- * @todo WorldFile-Spec vervollstaendigen
- *
- * @param inputStream
- * Stream of World-File
- * @exception IOException
- * falls die Datei nicht existiert oder ein unerwarteter
- * Fehler beim Einlesen auftritt
- * @see IOUtil#isCommentLine(String)
- * @see System#err
- *
* @author <a href="mailto:martin.schmitz at koeln.de">Martin Schmitz</a>
* (University of Bonn/Germany)
- * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons Tzeggai</a>
*/
- public static double[] readWorldFile(InputStream inputStream)
+ public static CoordinateReferenceSystem readProjectionFile(File prjFile)
throws IOException {
- Vector<Double> tfwValues = new Vector<Double>();
- BufferedReader in = new BufferedReader(new InputStreamReader(
- inputStream));
- String line = null;
- for (int lineNo = 1; in.ready()
- && (line = in.readLine().trim()) != null; lineNo++) {
- if (IOUtil.isCommentLine(line) || line.equals(""))
- continue;
- try {
- StringTokenizer st = new StringTokenizer(line);
- tfwValues.add(Double.parseDouble(st.nextToken(" \n;,#|/")));
- } catch (Exception err) {
- LOGGER.error("WorldFile-Error in line " + lineNo + ": " + err);
-
- LOGGER.error(" >> expected value is set to 1.0");
- tfwValues.add(1.0);
- }
- }
-
- while (tfwValues.size() < 6) {
- LOGGER.error("WorldFile-Error: value " + tfwValues.size()
- + " missing!");
- // (SK)
- // System.err.println("WorldFile-Error in '"+file.getAbsolutePath()+"': value "+tfwValues.size()+" missing!");
- LOGGER.error(" >> expected value is set to 1.0");
- tfwValues.add(1.0);
- }
-
- // Vector in Array umwandeln
- double[] ret = new double[tfwValues.size()];
- for (int i = 0; i < ret.length; i++)
- ret[i] = tfwValues.elementAt(i);
- return ret;
- }
-
- // /////////////////////////////////////////////////////////////////////////
- // META DATA IMPORT (PROJECTION)
- // /////////////////////////////////////////////////////////////////////////
-
- /**
- * Liest das CRS aus einer Datei. Zunaechst wird versucht das CRS aus der
- * uebergebene Datei zu lesen. Ist dies nicht erfolgreich wird das zur Datei
- * korrespondierende prj-File herangezogen.
- *
- * @param file
- * Datei
- * @return {@code null}, wenn kein CRS gelesen werden konnte
- */
- public static CoordinateReferenceSystem determineProjection(File file)
- throws IOException {
- return determineProjection(DataUtilities.fileToURL(file));
- }
-
- /**
- * 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.
- *
- * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons Tzeggai</a>
- */
- public static CoordinateReferenceSystem determineProjection(URL prjUrl) {
- CoordinateReferenceSystem crs = null;
- try {
- crs = GeoImportUtil.readProjectionFile(prjUrl);
- } catch (IOException e) {
- }
-
- if (crs == null) {
- try {
- crs = GeoImportUtil.readProjectionFile(IOUtil.changeUrlExt(
- prjUrl, "prj"));
- } catch (IllegalArgumentException e) {
- } catch (IOException e) {
- }
- }
-
- if (crs == null) {
- try {
- crs = GeoImportUtil.readProjectionFile(IOUtil.changeUrlExt(
- prjUrl, "PRJ"));
- } catch (IllegalArgumentException e) {
- } catch (IOException e) {
- }
- }
-
- // Wenn nicht erfolgreich, Default verwenden
- if (crs == null) {
- LOGGER.warn("No projection found in URL. Default CRS used.");
- crs = getDefaultCRS();
- }
+ String crsDefinition = readProjectionString(prjFile);
+ CoordinateReferenceSystem crs = GTUtil.createCRS(crsDefinition);
+ // if ( crs == null )
+ // LOGGER.warn("CRS can not be read from file '"+(prjFile == null ?
+ // "null" : prjFile.getName())+"'");
return crs;
}
@@ -1174,28 +1291,6 @@
}
/**
- * Liest ein CRS aus einer Datei. Als Dateiinhalt wird entweder ein
- * EPSG-Code oder eine WKT-Definition des CRS akzeptiert.
- *
- * @param prjFile
- * prj-Datei in der die Projektion hinterlegt ist
- * @return {@code null}, wenn kein CRS gelesen werden konnte
- * @see GTUtil#createCRS(String)
- *
- * @author <a href="mailto:martin.schmitz at koeln.de">Martin Schmitz</a>
- * (University of Bonn/Germany)
- */
- public static CoordinateReferenceSystem readProjectionFile(File prjFile)
- throws IOException {
- String crsDefinition = readProjectionString(prjFile);
- CoordinateReferenceSystem crs = GTUtil.createCRS(crsDefinition);
- // if ( crs == null )
- // LOGGER.warn("CRS can not be read from file '"+(prjFile == null ?
- // "null" : prjFile.getName())+"'");
- return crs;
- }
-
- /**
* Liest die ersten Zeilen der angegebenen prj-Datei und fuegt sie zu einem
* String zusammen. Wenn die Datei zu gross ist, wird ein Leerstring
* zurueckgegeben, da es sich dann nicht um eine Projektionsdefinition
@@ -1279,6 +1374,126 @@
}
}
+ // /////////////////////////////////////////////////////////////////////////
+ // META DATA IMPORT (WORLD FILE)
+ // /////////////////////////////////////////////////////////////////////////
+ /**
+ * Liest ein World-File (.tfw) ein und liefert die darin zeilenweise
+ * gespeicherten Werte zurueck. Leer- und Kommentarzeilen werden dabei
+ * ignoriert. Kann ein Zeilen-Wert nicht in einen <code>double</code>
+ * umgewandelt werden, wird diese Zeile ignoriert, als 1.0 interpretiert und
+ * eine Meldung in die Standard-Fehler-Ausgabe geschrieben.<br>
+ * Der zurueckgegebene Array hat mindestens die Groesse 6:<br>
+ * <ol>
+ * <li>Zellengroesse in X-Richtung (in Meter)</li>
+ * <li>Koeffizient fuer Rotation in Y-Richtung</li>
+ * <li>Koeffizient fuer Rotation in X-Richtung</li>
+ * <li>negative Zellengroesse in Y-Richtung (in Meter)</li>
+ * <li>Horizontale Geo-Referenz (Longitude) der nord-westlichen Ecke</li>
+ * <li>Vertikale Geo-Referenz (Latitude) der nord-westlichen Ecke</li>
+ * </ol>
+ *
+ * @todo WorldFile-Spec vervollstaendigen
+ * @param file
+ * World-File
+ * @exception IOException
+ * falls die Datei nicht existiert oder ein unerwarteter
+ * Fehler beim Einlesen auftritt
+ * @see IOUtil#isCommentLine(String)
+ * @see System#err
+ */
+
+ public static double[] readWorldFile(File file) throws IOException {
+ return readWorldFile(new FileInputStream(file));
+ }
+
+ /**
+ * Liest ein World-File (.tfw) ein und liefert die darin zeilenweise
+ * gespeicherten Werte zurueck. Leer- und Kommentarzeilen werden dabei
+ * ignoriert. Kann ein Zeilen-Wert nicht in einen <code>double</code>
+ * umgewandelt werden, wird diese Zeile ignoriert, als 1.0 interpretiert und
+ * eine Meldung in die Standard-Fehler-Ausgabe geschrieben.<br>
+ * Der zurueckgegebene Array hat mindestens die Groesse 6:<br>
+ * <ol>
+ * <li>Zellengroesse in X-Richtung (in Meter)</li>
+ * <li>Koeffizient fuer Rotation in Y-Richtung</li>
+ * <li>Koeffizient fuer Rotation in X-Richtung</li>
+ * <li>negative Zellengroesse in Y-Richtung (in Meter)</li>
+ * <li>Horizontale Geo-Referenz (Longitude) der nord-westlichen Ecke</li>
+ * <li>Vertikale Geo-Referenz (Latitude) der nord-westlichen Ecke</li>
+ * </ol>
+ *
+ * @todo WorldFile-Spec vervollstaendigen
+ *
+ * @param inputStream
+ * Stream of World-File
+ * @exception IOException
+ * falls die Datei nicht existiert oder ein unerwarteter
+ * Fehler beim Einlesen auftritt
+ * @see IOUtil#isCommentLine(String)
+ * @see System#err
+ *
+ * @author <a href="mailto:martin.schmitz at koeln.de">Martin Schmitz</a>
+ * (University of Bonn/Germany)
+ * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons Tzeggai</a>
+ */
+ public static double[] readWorldFile(InputStream inputStream)
+ throws IOException {
+ Vector<Double> tfwValues = new Vector<Double>();
+ BufferedReader in = new BufferedReader(new InputStreamReader(
+ inputStream));
+ String line = null;
+ for (int lineNo = 1; in.ready()
+ && (line = in.readLine().trim()) != null; lineNo++) {
+ if (IOUtil.isCommentLine(line) || line.equals(""))
+ continue;
+ try {
+ StringTokenizer st = new StringTokenizer(line);
+ tfwValues.add(Double.parseDouble(st.nextToken(" \n;,#|/")));
+ } catch (Exception err) {
+ LOGGER.error("WorldFile-Error in line " + lineNo + ": " + err);
+
+ LOGGER.error(" >> expected value is set to 1.0");
+ tfwValues.add(1.0);
+ }
+ }
+
+ while (tfwValues.size() < 6) {
+ LOGGER.error("WorldFile-Error: value " + tfwValues.size()
+ + " missing!");
+ // (SK)
+ // System.err.println("WorldFile-Error in '"+file.getAbsolutePath()+"': value "+tfwValues.size()+" missing!");
+ LOGGER.error(" >> expected value is set to 1.0");
+ tfwValues.add(1.0);
+ }
+
+ // Vector in Array umwandeln
+ double[] ret = new double[tfwValues.size()];
+ for (int i = 0; i < ret.length; i++)
+ ret[i] = tfwValues.elementAt(i);
+ return ret;
+ }
+
+ /**
+ * Sets how this class proceeds the import of ASCII rasters.
+ *
+ * @param mode
+ * the mode how to proceed the import
+ */
+ public static void setAsciiRasterImportMode(ARCASCII_IMPORT_TYPE mode) {
+ ARCASCII_IMPORT_MODE = mode;
+ }
+
+ /**
+ * Sets the default CRS used if no CRS can be found during import.
+ *
+ * @param crs
+ * the new default CRS
+ */
+ public static void setDefaultCRS(CoordinateReferenceSystem crs) {
+ DEFAULT_CRS = crs;
+ }
+
public static ZipEntry testShapeInZip(InputStream zippedInputstream)
throws IOException {
ZipInputStream inStream = new ZipInputStream(zippedInputstream);
@@ -1298,12 +1513,6 @@
}
}
- // TODO Diese Methode soll alle vom GP im Templ angelegten Dateienlöschen,
- // da Windows das Temp nicht automatisch löscht.
- public static boolean uncompressShapeZipCleanup() {
- return false;
- }
-
/**
* Entpackt ein ZIP nach tmp (wo es angeblich von der Java VM nach JRE Ende
* gelöscht wird und liefert eine URL auf die erste gefundene .SHP Datei
@@ -1317,23 +1526,6 @@
}
/**
- * Entpackt ein ZIP nach tmp (wo es angeblich von der Java VM nach JRE Ende
- * gelöscht wird und liefert eine URL auf die erste gefundene .SHP Datei
- * zurück. TODO Die entpacketen Dateien bleiben in Temp liegen!.
- *
- * @throws IOException
- */
- public static URL uncompressShapeZip(URL zipUrl)
- throws FileNotFoundException, IOException {
- InputStream zipUrlStream = zipUrl.openStream();
- try {
- return uncompressShapeZip(zipUrlStream);
- } finally {
- zipUrlStream.close();
- }
- }
-
- /**
* Entpackt einen ZIP Stream nach tmp und liefert eine URL auf die erste
* gefundene .SHP Datei zurück. TODO Die entpackten Dateien bleiben in Temp
* liegen!.
@@ -1379,41 +1571,27 @@
}
/**
- * The URLs where a <code>.cpg</code> or <code>.cst</code> file describing
- * the {@link Charset} could be found.
+ * Entpackt ein ZIP nach tmp (wo es angeblich von der Java VM nach JRE Ende
+ * gelöscht wird und liefert eine URL auf die erste gefundene .SHP Datei
+ * zurück. TODO Die entpacketen Dateien bleiben in Temp liegen!.
*
- * @param url_
- * must be an {@link URL} with an extension. The extensions will
- * then the changed for possible charset containing extensions.
+ * @throws IOException
*/
- 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") };
+ public static URL uncompressShapeZip(URL zipUrl)
+ throws FileNotFoundException, IOException {
+ InputStream zipUrlStream = zipUrl.openStream();
+ try {
+ return uncompressShapeZip(zipUrlStream);
+ } finally {
+ zipUrlStream.close();
+ }
}
- /**
- * Tries to read a file containing {@link Charset} information next to a
- * {@link URL}.
- *
- * @return <code>null</code> is nothing found.
- */
- public static Charset readCharset(URL url) {
- URL[] cpgUrls = GeoImportUtil.getCharsetUrls(url);
- for (URL cpgUrl : cpgUrls) {
- try {
- String charsetName = IOUtil.readURLasString(cpgUrl);
+ // TODO Stefan Tzeggai: Diese Methode soll alle vom GP im Templ angelegten
+ // Dateienlöschen,
+ // da Windows das Temp nicht automatisch löscht.
+ public static boolean uncompressShapeZipCleanup() {
+ throw new NotImplementedException();
+ }
- if (charsetName.equals(""))
- continue;
-
- return Charset.forName(charsetName);
-
- } catch (Exception e) {
- // LOGGER.warn("Reading .cpg file failed for "+cpgUrl+". Using default. ");
- }
- }
- return null;
- }
}
Modified: trunk/src/schmitzm/io/IOUtil.java
===================================================================
--- trunk/src/schmitzm/io/IOUtil.java 2010-10-22 21:35:30 UTC (rev 1160)
+++ trunk/src/schmitzm/io/IOUtil.java 2010-10-24 16:44:18 UTC (rev 1161)
@@ -725,8 +725,9 @@
/**
* @return a {@link String} with the content of the {@link URL}. Do not use
- * this on long files! Returns <code>null</code> if an error
- * occured. A newline-character is added at every new line.
+ * this on long files! Returns <code>null</code> if an error occured
+ * or the file doesn't exists.<br/>
+ * A newline-character is added at every new line.
*/
public static String readURLasString(URL url) {
try {
@@ -761,7 +762,7 @@
openStream.close();
}
} catch (IOException e) {
- LOGGER.warn("getURLasString " + url, e);
+ // LOGGER.warn("getURLasString " + url, e);
}
return null;
}
Modified: trunk/src/schmitzm/jfree/feature/style/FeatureChartUtil.java
===================================================================
--- trunk/src/schmitzm/jfree/feature/style/FeatureChartUtil.java 2010-10-22 21:35:30 UTC (rev 1160)
+++ trunk/src/schmitzm/jfree/feature/style/FeatureChartUtil.java 2010-10-24 16:44:18 UTC (rev 1161)
@@ -699,7 +699,11 @@
// createXYDataset(..))
FeatureIterator<SimpleFeature> features = null;
Iterator<SimpleFeature> fi = null;
- Iterator<SimpleFeature> fi2 = null;
+
+
+ Iterator<SimpleFeature> fi2 = null; //TODO Martin Schmitz: Never used?!
+
+
if (chartStyle.isSortDomainAxis()) {
// Sorting attribute(s) -> Category attribute
String[] sortAttr = new String[] {xAttrName};
Modified: trunk/src/schmitzm/swing/MultiSplitPane.java
===================================================================
--- trunk/src/schmitzm/swing/MultiSplitPane.java 2010-10-22 21:35:30 UTC (rev 1160)
+++ trunk/src/schmitzm/swing/MultiSplitPane.java 2010-10-24 16:44:18 UTC (rev 1161)
@@ -604,38 +604,38 @@
return (1-getSplitPane().getResizeWeight()) * getResizeWeight();
}
- /**
- * Liefert den Container eines Blattes aus dem (Teil-)Baum. Dabei sind die
- * Container (mit 0 beginnend) von links nach recht im Baum durchnummeriert.
- * @param i Nummer des Containers
- * @exception lava.lang.ArrayIndexOutOfBoundsException falls in dem Teilbaum
- * nicht genug Container vorhanden sind
- */
- public Container getContainer(int i) {
- if ( i>= getContainerCount() )
- throw new ArrayIndexOutOfBoundsException("not enough Containers in SplitPaneTree");
+// /**
+// * Liefert den Container eines Blattes aus dem (Teil-)Baum. Dabei sind die
+// * Container (mit 0 beginnend) von links nach recht im Baum durchnummeriert.
+// * @param i Nummer des Containers
+// * @exception lava.lang.ArrayIndexOutOfBoundsException falls in dem Teilbaum
+// * nicht genug Container vorhanden sind
+// */
+// public Container getContainer(int i) {
+// if ( i>= getContainerCount() )
+// throw new ArrayIndexOutOfBoundsException("not enough Containers in SplitPaneTree");
+//
+// int leftCount = 0;
+// if ( isSplittedLeft() ) leftCount = getLeftTree().getContainerCount();
+//
+// int rightCount = 0;
+// if ( isSplittedRight() ) rightCount = getRightTree().getContainerCount();
+//
+// // erster Container gesucht und kein linker Teilbaum
+// // --> also Container im linken Teil-Pane ist der gesuchte
+// if ( i == 0 && leftCount == 0 )
+// return (Container)splitPane.getLeftComponent();
+// // letzter Container gesucht und kein rechter Teilbaum
+// // --> also Container im rechten Teil-Pane ist der gesuchte
+// if ( i == getContainerCount()-1 && rightCount == 0 )
+// return (Container)splitPane.getRightComponent();
+// // gesuchter Container liegt im linken Teil-Pane
+// if ( i < leftCount )
+// return getLeftTree().getContainer(i);
+// // gesuchter Container liegt im rechten Teil-Pane
+// return getRightTree().getContainer(i-leftCount);
+// }
- int leftCount = 0;
- if ( isSplittedLeft() ) leftCount = getLeftTree().getContainerCount();
-
- int rightCount = 0;
- if ( isSplittedRight() ) rightCount = getRightTree().getContainerCount();
-
- // erster Container gesucht und kein linker Teilbaum
- // --> also Container im linken Teil-Pane ist der gesuchte
- if ( i == 0 && leftCount == 0 )
- return (Container)splitPane.getLeftComponent();
- // letzter Container gesucht und kein rechter Teilbaum
- // --> also Container im rechten Teil-Pane ist der gesuchte
- if ( i == getContainerCount()-1 && rightCount == 0 )
- return (Container)splitPane.getRightComponent();
- // gesuchter Container liegt im linken Teil-Pane
- if ( i < leftCount )
- return getLeftTree().getContainer(i);
- // gesuchter Container liegt im rechten Teil-Pane
- return getRightTree().getContainer(i-leftCount);
- }
-
/**
* Liefert den Container eines Blattes aus dem (Teil-)Baum. Dabei sind die
* Container (mit 0 beginnend) von links nach recht im Baum durchnummeriert.
Added: trunk/src/skrueger/geotools/io/DbServerList.java
===================================================================
--- trunk/src/skrueger/geotools/io/DbServerList.java 2010-10-22 21:35:30 UTC (rev 1160)
+++ trunk/src/skrueger/geotools/io/DbServerList.java 2010-10-24 16:44:18 UTC (rev 1161)
@@ -0,0 +1,72 @@
+package skrueger.geotools.io;
+
+import java.net.MalformedURLException;
+import java.util.ArrayList;
+import java.util.regex.Pattern;
+
+import org.jfree.util.Log;
+
+/**
+ * A list of {@link DbServerSettings}.
+ */
+public class DbServerList extends ArrayList<DbServerSettings> {
+ /**
+ * Character used to separate the parameters when serializing settings to a
+ * String
+ */
+ private static final String DELIMITER = "@";
+
+ public DbServerList(DbServerSettings... wfss) {
+ for (DbServerSettings wfs : wfss) {
+ add(wfs);
+ }
+ }
+
+ /**
+ * @return transforms the settings to a String that can be stored in a
+ * .properties line. @see #parsePropertiesString
+ */
+ public String toPropertiesString() {
+
+ StringBuffer serialized = new StringBuffer(100);
+
+ for (DbServerSettings wfs : this) {
+ serialized.append(wfs.toPropertiesString());
+ serialized.append(DELIMITER);
+ }
+
+ return serialized.toString();
+ }
+
+ /**
+ * @return transforms the settings to a String that can be stored in a
+ * .properties line. @see #parsePropertiesString
+ * @throws MalformedURLException
+ */
+ public static DbServerList parsePropertiesString(String propString) {
+ DbServerList wfsServerList = new DbServerList();
+
+ if (propString == null)
+ return wfsServerList;
+
+ String[] split = propString.split(Pattern.quote(DELIMITER));
+
+ for (String s : split) {
+ try {
+ wfsServerList.add(DbServerSettings.parsePropertiesString(s));
+ } catch (MalformedURLException e) {
+ Log.error(
+ "Could not import a "
+ + DbServerSettings.class.getSimpleName()
+ + ". Ignoring it.", e);
+ } catch (IllegalArgumentException iae) {
+ Log.error(
+ "Could not import a "
+ + DbServerSettings.class.getSimpleName()
+ + ". Ignoring it.", iae);
+ }
+ }
+
+ return wfsServerList;
+ }
+}
Property changes on: trunk/src/skrueger/geotools/io/DbServerList.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Name: svn:keywords
+ Id URL
Name: svn:eol-style
+ native
Added: trunk/src/skrueger/geotools/io/DbServerSettings.java
===================================================================
--- trunk/src/skrueger/geotools/io/DbServerSettings.java 2010-10-22 21:35:30 UTC (rev 1160)
+++ trunk/src/skrueger/geotools/io/DbServerSettings.java 2010-10-24 16:44:18 UTC (rev 1161)
@@ -0,0 +1,364 @@
+package skrueger.geotools.io;
+
+import java.awt.Component;
+import java.net.MalformedURLException;
+import java.util.HashMap;
+import java.util.regex.Pattern;
+
+import org.apache.commons.lang.ArrayUtils;
+import org.geotools.data.postgis.PostgisNGDataStoreFactory;
+import org.geotools.jdbc.JDBCDataStore;
+import org.geotools.jdbc.JDBCDataStoreFactory;
+
+import schmitzm.swing.BooleanInputOption;
+import schmitzm.swing.ManualInputOption;
+import schmitzm.swing.ManualInputOption.Integer;
+import schmitzm.swing.ManualInputOption.PasswordViewable;
+import schmitzm.swing.ManualInputOption.Text;
+import schmitzm.swing.MultipleOptionPane;
+import schmitzm.swing.SelectionInputOption;
+import schmitzm.swing.SelectionInputOption.Combo;
+
+/**
+ * This class describes all settings needed to connect to a WFS server. This
+ * class extends a {@link HashMap} and contains two groups of keys:<br/>
+ * The first group of keys, are all keys provided by Geotools to create a WFS
+ * datastore, like: {@link JDBCDataStore#SCHEMA} .<br/>
+ * The second group are additional keys defined in the enum
+ * {@link DbServerSettings.Key}.<br/>
+ * This class can serialize all important parameters needed to define the
+ * connection into a {@link String} with {@link #toPropertiesString()} and
+ * re-import the String with {@link #parsePropertiesString(String)}.
+ */
+public class DbServerSettings extends HashMap<Object, Object> {
+
+ /**
+ * params.put(JDBCDataStoreFactory.DBTYPE.key, "postgis");
+ * params.put(JDBCDataStoreFactory.HOST.key, host); // the name or ip
+ * params.put(JDBCDataStoreFactory.PORT.key, port); // the port that
+ *
+ * params.put(JDBCDataStoreFactory.DATABASE.key, database); // the
+ *
+ * // name params.put(JDBCDataStoreFactory.USER.key, username); // the user
+ * to params.put(JDBCDataStoreFactory.PASSWD.key, password); // the
+ *
+ * params.put(JDBCDataStoreFactory.SCHEMA, schema);
+ *
+ * params.put(JDBCDataStoreFactory.EXPOSE_PK.key, true); *
+ */
+
+ public enum Key {
+ }
+
+ public enum DbType {
+ postgis("postgresql");
+
+ private final String protocolString;
+
+ DbType(String protocolString) {
+ this.protocolString = protocolString;
+ }
+
+ public String getProtocolString() {
+ return protocolString;
+ };
+ }
+
+ public void setPort(java.lang.Integer port) {
+ put(JDBCDataStoreFactory.PORT.key, port);
+ }
+
+ public java.lang.Integer getPort() {
+ java.lang.Integer port = (java.lang.Integer) get(JDBCDataStoreFactory.PORT.key);
+ if (port == null)
+ return (java.lang.Integer) JDBCDataStoreFactory.PORT.sample;
+ return port;
+ }
+
+ public void setSchema(String schema) {
+ put(JDBCDataStoreFactory.SCHEMA.key, schema);
+ }
+
+ public String getSchema() {
+ return (String) get(JDBCDataStoreFactory.SCHEMA.key);
+ }
+
+ public void setExposePrimaryKey(Boolean exportPk) {
+ put(JDBCDataStoreFactory.EXPOSE_PK.key, exportPk);
+ }
+
+ public Boolean getExposePrimaryKey() {
+ Boolean expk = (Boolean) get(JDBCDataStoreFactory.EXPOSE_PK.key);
+ if (expk == null)
+ return (Boolean) JDBCDataStoreFactory.EXPOSE_PK.sample;
+ return expk;
+ }
+
+ public void setHost(String host) {
+ put(JDBCDataStoreFactory.HOST.key, host);
+ }
+
+ public String getHost() {
+ return (String) get(JDBCDataStoreFactory.HOST.key);
+ }
+
+ public void setPassword(String password) {
+ put(JDBCDataStoreFactory.PASSWD.key, password);
+ }
+
+ public String getPassword() {
+ return (String) get(JDBCDataStoreFactory.PASSWD.key);
+ }
+
+ public void setUsername(String username) {
+ put(JDBCDataStoreFactory.USER.key, username);
+ }
+
+ public String getUsername() {
+ return (String) get(JDBCDataStoreFactory.USER.key);
+ }
+
+ public void setDatabase(String db) {
+ put(JDBCDataStoreFactory.DATABASE.key, db);
+ }
+
+ public String getDatabase() {
+ return (String) get(JDBCDataStoreFactory.DATABASE.key);
+ }
+
+ /**
+ * Character used to separate the parameters when serializing settings to a
+ * String
+ */
+ private static final String DELIMITER = "|";
+
+ public DbServerSettings(DbType dbType) {
+ setDbType(dbType);
+ setHost("localhost");
+ setSchema("public");
+ }
+
+ public void setDbType(DbType dbType) {
+ put(PostgisNGDataStoreFactory.DBTYPE.key, dbType.toString());
+
+ if (dbType == DbType.postgis) {
+ if (getPort() == null) {
+ // For a PostGIS DBMS automatically set the port to 5432
+ setPort(5432);
+ }
+ if (getUsername() == null) {
+ // For a PostGIS DBMS automatically set the user to postgres
+ setUsername("postgres");
+ }
+
+ }
+
+ }
+
+ public DbType getDbType() {
+ String dbt = (String) get(PostgisNGDataStoreFactory.DBTYPE.key);
+ if (dbt != null)
+ return DbType.valueOf(dbt);
+ return null;
+ }
+
+ public DbServerSettings() {
+ }
+
+ /**
+ * @return <code>true</code>, if all parameters look OK, without actually
+ * opening any connection.
+ */
+ public boolean isWellDefined() {
+ if (getDbType() == null)
+ return false;
+
+ if (getHost() == null)
+ return false;
+
+ if (getUsername() == null)
+ return false;
+
+ if (getPassword() == null)
+ return false;
+
+ if (getPort() == null)
+ return false;
+
+ if (getSchema() == null)
+ return false;
+
+ return true;
+ }
+
+ /**
+ * @return transforms the settings to a String that can be stored in a
+ * .properties line. @see #parsePropertiesString
+ */
+ public String toPropertiesString() {
+
+ StringBuffer serialized = new StringBuffer(100);
+
+ serialized.append(getDbType().toString());
+ serialized.append(DELIMITER);
+
+ serialized.append(getHost().toString());
+ serialized.append(DELIMITER);
+
+ serialized.append(getPort().toString());
+ serialized.append(DELIMITER);
+
+ serialized.append(getUsername().toString());
+ serialized.append(DELIMITER);
+
+ serialized.append(getPassword().toString());
+ serialized.append(DELIMITER);
+
+ serialized.append(getDatabase().toString());
+ serialized.append(DELIMITER);
+
+ serialized.append(getExposePrimaryKey().toString());
+ serialized.append(DELIMITER);
+
+ serialized.append(getSchema().toString());
+ serialized.append(DELIMITER);
+
+ return serialized.toString();
+ }
+
+ /**
+ * @return transforms the settings to a String that can be stored in a
+ * .properties line. @see #parsePropertiesString
+ * @throws MalformedURLException
+ */
+ public static DbServerSettings parsePropertiesString(String propString)
+ throws MalformedURLException {
+
+ if (propString == null || propString.isEmpty())
+ throw new IllegalArgumentException("parameter to parse was empty");
+
+ String[] split = propString.split(Pattern.quote(DELIMITER));
+
+ // BaseUrl
+ try {
+ DbType dbt = DbType.valueOf(split[0]);
+
+ DbServerSettings dbServer = new DbServerSettings(dbt);
+
+ dbServer.setHost(split[1]);
+ dbServer.setPort(java.lang.Integer.valueOf(split[2]));
+ dbServer.setUsername(split[3]);
+ dbServer.setPassword(split[4]);
+ dbServer.setDatabase(split[5]);
+ dbServer.setExposePrimaryKey(Boolean.valueOf(split[6]));
+ dbServer.setSchema(split[7]);
+
+ return dbServer;
+ } catch (Exception e) {
+ throw new IllegalArgumentException(e);
+ }
+
+ }
+
+ @Override
+ public String toString() {
+
+ StringBuffer s = new StringBuffer();
+
+ if (getDbType() != null) {
+ s.append(getDbType().getProtocolString() + "://");
+ }
+
+ s.append(getHost());
+
+ if (getPort() != 5432) {
+ s.append(":" + getPort());
+ }
+
+ s.append("/" + getDatabase());
+
+ return s.toString();
+ }
+
+ public void setCachedTypeNames(String[] cachedTypeNames) {
+ this.cachedTypeNames = cachedTypeNames;
+ }
+
+ public String[] getCachedTypeNames() {
+ return cachedTypeNames;
+ }
+
+ private String[] cachedTypeNames = null;
+
+ public String getTitle() {
+ // TODO
+ return "" + getDbType();
+ }
+
+ /**
+ * Opens a GUI that asks the use define a DB connection.
+ *
+ * @param dbServer
+ * <code>null</code> to create a new instance, or an instance to
+ * edit.
+ * @return <code>null</code> if the user cancelled the creation of a new
+ * {@link DbServerSettings}, otherwise the edited instance.
+ */
+ public static DbServerSettings createOrEdit(Component owner,
+ DbServerSettings dbServer) {
+ boolean newCreated = false;
+
+ if (dbServer == null) {
+ newCreated = true;
+ dbServer = new DbServerSettings(DbType.postgis);
+ }
+
+ Combo<DbType> dpTypeInput = new SelectionInputOption.Combo<DbType>(
+ "Database type", true, DbType.values(), ArrayUtils.indexOf(
+ DbType.values(), dbServer.getDbType()), DbType.values());
+
+ Text hostInput = new ManualInputOption.Text("Hostname", true,
+ dbServer.getHost());
+
+ Integer portInput = new ManualInputOption.Integer("Port", true,
+ dbServer.getPort());
+
+ Text databaseInput = new ManualInputOption.Text("Database", true,
+ dbServer.getDatabase());
+
+ Text schemaInput = new ManualInputOption.Text("Schema", true,
+ dbServer.getSchema());
+
+ Text userInput = new ManualInputOption.Text("Username", true,
+ dbServer.getUsername());
+
+ PasswordViewable passwdInput = new ManualInputOption.PasswordViewable(
+ "Passwort", true, dbServer.getPassword());
+
+ BooleanInputOption exposePkInput = new BooleanInputOption(
+ "Expose primary keys", dbServer.getExposePrimaryKey());
+
+ Object[] input = MultipleOptionPane.showMultipleInputDialog(owner,
+ "DB Connection paramters", dpTypeInput, hostInput, portInput,
+ databaseInput, schemaInput, userInput, passwdInput,
+ exposePkInput);
+
+ if (input == null) {
+ if (newCreated)
+ return null;
+ else
+ return dbServer;
+ } else {
+ dbServer.setDbType((DbType) input[0]);
+ dbServer.setHost((String) input[1]);
+ dbServer.setPort((java.lang.Integer) input[2]);
+ dbServer.setDatabase((String) input[3]);
+ dbServer.setSchema((String) input[4]);
+ dbServer.setUsername((String) input[5]);
+ dbServer.setPassword(String.valueOf((char[]) input[6]));
+ dbServer.setExposePrimaryKey((Boolean) input[7]);
+ }
+
+ return dbServer;
+ }
+}
Property changes on: trunk/src/skrueger/geotools/io/DbServerSettings.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Name: svn:keywords
+ Id URL
Name: svn:eol-style
+ native
Added: trunk/src/skrueger/geotools/io/DbSettingsJComboBox.java
===================================================================
--- trunk/src/skrueger/geotools/io/DbSettingsJComboBox.java 2010-10-22 21:35:30 UTC (rev 1160)
+++ trunk/src/skrueger/geotools/io/DbSettingsJComboBox.java 2010-10-24 16:44:18 UTC (rev 1161)
@@ -0,0 +1,23 @@
+package skrueger.geotools.io;
+
+import javax.swing.DefaultComboBoxModel;
+import javax.swing.JComboBox;
+
+public class DbSettingsJComboBox extends JComboBox {
+
+ private final DbServerList dbList;
+
+ public DbSettingsJComboBox(DbServerList wfsList) {
+ super(wfsList.toArray(new DbServerSettings[0]));
+ this.dbList = wfsList;
+ }
+
+ public DbServerList getDbList() {
+ return dbList;
+ }
+
+ public void listChanged() {
+ setModel(new DefaultComboBoxModel(dbList.toArray(new DbServerSettings[0])));
+ }
+
+}
Property changes on: trunk/src/skrueger/geotools/io/DbSettingsJComboBox.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Name: svn:keywords
+ Id URL
Name: svn:eol-style
+ native
Deleted: trunk/src/skrueger/geotools/io/GeoImportUtilURL.java
===================================================================
--- trunk/src/skrueger/geotools/io/GeoImportUtilURL.java 2010-10-22 21:35:30 UTC (rev 1160)
+++ trunk/src/skrueger/geotools/io/GeoImportUtilURL.java 2010-10-24 16:44:18 UTC (rev 1161)
@@ -1,285 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2009 Martin O. J. Schmitz.
- *
- * This file is part of the SCHMITZM library - a collection of utility
- * classes based on Java 1.6, focusing (not only) on Java Swing
- * and the Geotools library.
- *
- * The SCHMITZM project is hosted at:
- * http://wald.intevation.org/projects/schmitzm/
- *
- * This program 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 3
- * of the License, or (at your option) any later version.
- *
- * This program 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 General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License (license.txt)
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- * or try this link: http://www.gnu.org/licenses/lgpl.html
- *
- * Contributors:
- * Martin O. J. Schmitz - initial API and implementation
- * Stefan A. Tzeggai - additional utility classes
- ******************************************************************************/
-package skrueger.geotools.io;
-
-import java.awt.geom.Rectangle2D;
-import java.awt.image.BufferedImage;
-import java.io.File;
-import java.io.IOException;
-import java.net.URL;
-
-import javax.imageio.IIOException;
-import javax.imageio.ImageIO;
-
-import org.apache.log4j.Logger;
-import org.geotools.coverage.grid.GridCoverage2D;
-import org.geotools.coverage.grid.GridCoverageFactory;
-import org.geotools.factory.Hints;
-import org.geotools.gce.geotiff.GeoTiffReader;
-import org.geotools.geometry.Envelope2D;
-import org.opengis.parameter.GeneralParameterValue;
-import org.opengis.referencing.crs.CoordinateReferenceSystem;
-
-import schmitzm.geotools.io.GeoImportUtil;
-import schmitzm.io.IOUtil;
-
-/**
- * Erweiterungen von Martin's {@link GeoImportUtil} classe fuer die konsequente
- * Benutzung mit {@link URL}s. TODO Diese Klasse sollte vielleicht mit der
- * {@link GeoImportUtil} zusammengefuegt werden.
- *
- * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons Tzeggai</a>
- *
- */
-public class GeoImportUtilURL extends GeoImportUtil {
- final static private Logger LOGGER = Logger
- .getLogger(GeoImportUtilURL.class);
-
- /**
- * Read a {@link GridCoverage2D} from an image file. .prj and .wld files are
- * usually expected
- */
- public static GridCoverage2D readGridFromImage(URL url) throws IOException {
- return readGridFromImage(url, null);
- }
-
- /**
- * Read a {@link GridCoverage2D} from an image file. .wld file is usually
- * expected also. The CRS can be given as the crs parameter. null is valid.
- *
- * @author <a href="mailto:martin.schmitz at koeln.de">Martin Schmitz</a>
- * (University of Bonn/Germany)
- * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons
- * Tzeggai</a>
- */
- public static GridCoverage2D readGridFromImage(URL url,
- CoordinateReferenceSystem crs) throws IOException {
- GridCoverage2D gc = null;
-
- BufferedImage im = ImageIO.read(url);
- if (im == null)
- throw new IIOException("No image reader found for this image type!");
-
- // World-File einlesen
- double[] tfwInfo = null;
-
- for (WORLD_POSTFIXES pf : WORLD_POSTFIXES.values()) {
- if (tfwInfo == null) {
- try {
- tfwInfo = readWorldFile(IOUtil.changeUrlExt(url,
- pf.toString()).openStream());
- } catch (Exception e) {
- }
- }
- }
-
- if (tfwInfo == null)
- throw new IllegalArgumentException(
- "No georeferencing information found.\n"
- + "Attach a .wld file to " + url + "please.");
-
- float w = (float) (im.getWidth() * tfwInfo[0]); // reale Breite =
- // RasterSpalten *
- // hor. Aufloesung
- float h = (float) (im.getHeight() * (-tfwInfo[3])); // reale Hoehe =
- // RasterZeilen
- // * vert.
- // Aufloesung
- float x = (float) tfwInfo[4]; // Suedwestliche Ecke!
- float y = (float) tfwInfo[5] - h; // Suedwestliche Ecke (im
- // tfw-File steht die
- // Nordwestliche!)
- // ggf. Projektion einlesen
- if (crs == null) {
- crs = determineProjection(IOUtil.changeUrlExt(url, "prj"));
- }
- Envelope2D envelope = new Envelope2D(crs, new Rectangle2D.Float(x, y,
- w, h));
- // WICHTIG: Name des Rasters sollte Leer-String sein, da ansonsten
- // das
- // Coloring des Rasters nicht klappt.
- // --> Name der Categories und ColorMapEntries-Labels muss (warum auch
- // immer) mit dem Namen
- // des Rasters uebereinstimmen!!!
- gc = new GridCoverageFactory().create("", im, envelope);
-
- return gc;
- }
-
- /**
- * @param input
- * URL, File oder InputStream to a GeoTIFF-File
- * @param crs
- * erzwungenes CoordinateReferenceSystem fuer das Raster (kann
- * {@code null} sein)
- *
- * @author <a href="mailto:martin.schmitz at koeln.de">Martin Schmitz</a>
- * (University of Bonn/Germany)
- * @author <a href="mailto:skpublic at wikisquare.de">Stefan Alfons
- * Tzeggai</a>
- *
- * @param readParams
- * May be {@link NullPointerException}. Otherwise an array of
- * {@link GeneralParameterValue}s
- */
- public static GridCoverage2D readGridFromGeoTiff(Object input,
- CoordinateReferenceSystem crs, GeneralParameterValue[] readParams)
- throws IOException {
- GridCoverage2D gc = null;
- LOGGER.debug("Loading GeoTiff from URL = " + input + " now.");
-
- // Versuchen Geo-Information aus Tiff zu lesen
-
- // Wenn CRS angegeben, dieses durch Hint erzwingen
- Hints hints = new Hints();
-
- if (crs != null)
- hints.put(Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM, crs);
- // Reader (mit Metadaten) erzeugen
-
- LOGGER.debug("First try to create GeoTiff reader");
-
- /**
- * Attention, Attention: The GeoTiffReader fails for URLs like:
- *
- * jar:file:/home/sdsd/ad/atlas/raster_textur00949608497.jar!/ad/data/
- * raster_textur00949608497/textur.tif
- *
- * It should be converted to something like:
- * jar:http:///atlas/raster_textur00949608497
- * .jar!/ad/data/raster_textur00949608497/textur.tif
- * jar:http://www.wikisquare
- * .de/atlas/raster_textur00949608497.jar!/ad/data
- * /raster_textur00949608497/textur.tif
- */
-
- try {
-
- GeoTiffReader reader = new GeoTiffReader(input, hints);
-
- gc = (GridCoverage2D) reader.read(readParams);
- LOGGER.debug("... was successfull!");
- return gc;
- } catch (Exception e) {
- // keine Geo-Informationen in Tiff
- // --> Raster ueber ImageIO einlesen und WorldFile/ProjectionFile
- // verwenden
- LOGGER.warn("No geo information found in '" + input
- + "'. Using world- and prj-file...");
-
- BufferedImage im = null;
- double[] tfwInfo = null ;
- if (input instanceof File) {
- im = ImageIO.read((File) input);
- tfwInfo = readWorldFile(IOUtil.changeFileExt((File)input, "tfw"));
- if (crs == null)
- crs = determineProjection((File)input);
- } else if (input instanceof URL) {
- tfwInfo = readWorldFile(IOUtil.changeUrlExt((URL)input, "tfw").openStream());
- im = ImageIO.read((URL) input);
- if (crs == null)
- crs = determineProjection((URL)input);
- }
-
- if (im == null)
- throw new IIOException(
- "No image reader found for this image type!");
- // World-File einlesen
-
- float w = (float) (im.getWidth() * tfwInfo[0]); // reale Breite =
- // RasterSpalten * hor.
- // Aufloesung
- float h = (float) (im.getHeight() * (-tfwInfo[3])); // reale Hoehe =
- // RasterZeilen *
- // vert. Aufloesung
- float x = (float) tfwInfo[4]; // Suedwestliche Ecke!
- float y = (float) tfwInfo[5] - h; // Suedwestliche Ecke (im tfw-File
- // steht die Nordwestliche!)
- // ggf. Projektion einlesen
- Envelope2D envelope = new Envelope2D(crs, new Rectangle2D.Float(x,
- y, w, h));
- // WICHTIG: Name des Rasters sollte Leer-String sein, da ansonsten
- // das
- // Coloring des Rasters nicht klappt.
- // --> Name der Categories muss (warum auch immer) mit dem Namen
- // des Rasters uebereinstimmen!!!
- gc = new GridCoverageFactory().create("", im.copyData(null),
- envelope);
- return gc;
- }
- }
-
- //
- // ArcGridRaster reader = new ArcGridRaster(new BufferedReader(
- // new InputStreamReader(url.openStream())), false);
- // WritableRaster raster = reader.readRaster();
- // if (crs == null)
- // crs = determineProjection(IOUtil.changeUrlExt(url, "prj"));
- //
- // LOGGER.debug("Position " + reader.getXlCorner() + " / "
- // + reader.getYlCorner());
- // LOGGER.debug("Size " + reader.getNCols() + " / "
- // + reader.getNRows());
- // LOGGER.debug("Min/Max " + reader.getMinValue() + " / "
- // + reader.getMaxValue());
- // LOGGER.debug("NoData " + reader.getNoData());
- // LOGGER.debug("CellSize " + reader.getCellSize());
- //
- // Double x = reader.getXlCorner(); // Suedwestliche Ecke!
- // Double y = reader.getYlCorner(); // Suedwestliche Ecke!
- // if (y.isNaN() || x.isNaN()) {
- // throw new IllegalArgumentException(
- // "The parameters xlCorner and/or ylCorner could not be read. Hint: Check if the file defines 'xlcenter' instead of 'xlcorner'. If so, just replace all 'center' with 'corner' and try again.");
- // }
- //
- // Double w = (reader.getNCols() * reader.getCellSize()); // reale Breite =
- // // RasterSpalten
- // // * Aufloesung
- // Double h = (reader.getNRows() * reader.getCellSize()); // reale Hoehe =
- // // RasterZeilen
- // // * Aufloesung
- // Envelope2D envelope = new Envelope2D(crs, new Rectangle2D.Double(x, y,
- // w, h));
- //
- // // WICHTIG: Name des Rasters sollte Leer-String sein, da ansonsten das
- // // Coloring des Rasters nicht klappt.
- // // --> Name der Categories muss (warum auch immer) mit dem Namen
- // // des Rasters uebereinstimmen!!!
- // return new GridCoverageFactory().create("", raster, envelope);
- // //
- // // === OHNE ArcGridRaster ===
- // // // ArcGridReader reader = new ArcGridReader( new BufferedReader( new
- // // InputStreamReader( new FileInputStream(file) ) ));
- // // ArcGridReader reader = new ArcGridReader( file );
- // // return (GridCoverage2D)reader.read(null);
-
-
-
-}
Added: trunk/src/skrueger/geotools/io/WfsServerList.java
===================================================================
--- trunk/src/skrueger/geotools/io/WfsServerList.java 2010-10-22 21:35:30 UTC (rev 1160)
+++ trunk/src/skrueger/geotools/io/WfsServerList.java 2010-10-24 16:44:18 UTC (rev 1161)
@@ -0,0 +1,72 @@
+package skrueger.geotools.io;
+
+import java.net.MalformedURLException;
+import java.util.ArrayList;
+import java.util.regex.Pattern;
+
+import org.jfree.util.Log;
+
+/**
+ * A list of {@link WfsServerSettings}.
+ */
+public class WfsServerList extends ArrayList<WfsServerSettings> {
+ /**
+ * Character used to separate the parameters when serializing settings to a
+ * String
+ */
+ private static final String DELIMITER = "@";
+
+ public WfsServerList(WfsServerSettings... wfss) {
+ for (WfsServerSettings wfs : wfss) {
+ add(wfs);
+ }
+ }
+
+ /**
+ * @return transforms the settings to a String that can be stored in a
+ * .properties line. @see #parsePropertiesString
+ */
+ public String toPropertiesString() {
+
+ StringBuffer serialized = new StringBuffer(100);
+
+ for (WfsServerSettings wfs : this) {
+ serialized.append(wfs.toPropertiesString());
+ serialized.append(DELIMITER);
+ }
+
+ return serialized.toString();
+ }
+
+ /**
+ * @return transforms the settings to a String that can be stored in a
+ * .properties line. @see #parsePropertiesString
+ * @throws MalformedURLException
+ */
+ public static WfsServerList parsePropertiesString(String propString) {
+ WfsServerList wfsServerList = new WfsServerList();
+
+ if (propString == null)
+ return wfsServerList;
+
+ String[] split = propString.split(Pattern.quote(DELIMITER));
+
+ for (String s : split) {
+ try {
+ wfsServerList.add(WfsServerSettings.parsePropertiesString(s));
+ } catch (MalformedURLException e) {
+ Log.error(
+ "Could not import a "
+ + WfsServerSettings.class.getSimpleName()
+ + ". Ignoring it.", e);
+ } catch (IllegalArgumentException iae) {
+ Log.error(
+ "Could not import a "
+ + WfsServerSettings.class.getSimpleName()
+ + ". Ignoring it.", iae);
+ }
+ }
+
+ return wfsServerList;
+ }
+}
Property changes on: trunk/src/skrueger/geotools/io/WfsServerList.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Name: svn:keywords
+ Id URL
Name: svn:eol-style
+ native
Added: trunk/src/skrueger/geotools/io/WfsServerSettings.java
===================================================================
--- trunk/src/skrueger/geotools/io/WfsServerSettings.java 2010-10-22 21:35:30 UTC (rev 1160)
+++ trunk/src/skrueger/geotools/io/WfsServerSettings.java 2010-10-24 16:44:18 UTC (rev 1161)
@@ -0,0 +1,266 @@
+package skrueger.geotools.io;
+
+import java.awt.Component;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.HashMap;
+import java.util.regex.Pattern;
+
+import org.apache.commons.lang.ArrayUtils;
+import org.geotools.data.DataUtilities;
+import org.geotools.data.wfs.WFSDataStoreFactory;
+
+import schmitzm.swing.ManualInputOption;
+import schmitzm.swing.ManualInputOption.Text;
+import schmitzm.swing.MultipleOptionPane;
+import schmitzm.swing.SelectionInputOption;
+import schmitzm.swing.SelectionInputOption.Combo;
+
+/**
+ * This class describes all settings needed to connect to a WFS server. This
+ * class extends a {@link HashMap} and contains two groups of keys:<br/>
+ * The first group of keys, are all keys provided by Geotools to create a WFS
+ * datastore, like: {@link WFSDataStoreFactory#URL} or
+ * {@link WFSDataStoreFactory#USERNAME} .<br/>
+ * The second group are additional keys defined in the enum
+ * {@link WfsServerSettings.Key}.<br/>
+ * This class can serialize all important parameters needed to define the
+ * connection into a {@link String} with {@link #toPropertiesString()} and
+ * re-import the String with {@link #parsePropertiesString(String)}.
+ */
+public class WfsServerSettings extends HashMap<Object, Object> {
+
+ public enum Key {
+ BASE_URL, VERSION
+ }
+
+ public enum WfsProtocollVersion {
+ v1_1_1("1.1.1"), v1_1_0("1.1.0"), v1_0_0("1.0.0");
+
+ private final String versionString;
+
+ private WfsProtocollVersion(String versionString) {
+ this.versionString = versionString;
+ }
+
+ public String getVersionString() {
+ return versionString;
+ }
+ }
+
+ /**
+ * Character used to separate the parameters when serializing settings to a
+ * String
+ */
+ private static final String DELIMITER = "|";
+
+ public WfsServerSettings(URL baseUrl, WfsProtocollVersion version) {
+ setVersion(version);
+ setBaseUrl(baseUrl);
+ }
+
+ public WfsServerSettings() {
+ try {
+ setBaseUrl(new URL("http://localhost:8080/geoserver/ows"));
+ } catch (MalformedURLException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * @return <code>true</code>, if all parameters look OK, without actually
+ * opening any connection.
+ */
+ public boolean isWellDefined() {
+ return updateCapabilitesUrl();
+ }
+
+ /**
+ * @return <code>null</code> if not correctly defined, otherwise the URL of
+ * the GetCapabilites request.
+ */
+ public URL getCapabilitiesUrl() {
+ return (URL) get(WFSDataStoreFactory.URL.key);
+ }
+
+ public URL getBaseUrl() {
+ return (URL) get(Key.BASE_URL);
+ }
+
+ public void setBaseUrl(URL baseUrl) {
+
+ if (get(Key.BASE_URL) != baseUrl) {
+ setCachedTypeNames(null);
+ }
+
+ put(Key.BASE_URL, baseUrl);
+
+ updateCapabilitesUrl();
+ }
+
+ public boolean updateCapabilitesUrl() {
+ remove(WFSDataStoreFactory.URL.key);
+
+ if (getBaseUrl() == null)
+ return false;
+
+ if (getVersion() == null)
+ return false;
+
+ try {
+ URL fullUrl = DataUtilities.extendURL(getBaseUrl(),
+ "?service=wfs&version=" + getVersion().getVersionString()
+ + "&request=GetCapabilities");
+
+ put(WFSDataStoreFactory.URL.key, fullUrl);
+
+ return true;
+ } catch (MalformedURLException e) {
+ return false;
+ }
+ }
+
+ public WfsProtocollVersion getVersion() {
+ return (WfsProtocollVersion) get(Key.VERSION);
+ }
+
+ public void setVersion(WfsProtocollVersion version) {
+
+ if (get(Key.VERSION) != version) {
+ setCachedTypeNames(null);
+ }
+
+ put(Key.VERSION, version);
+ updateCapabilitesUrl();
+ }
+
+ /**
+ * @return transforms the settings to a String that can be stored in a
+ * .properties line. @see #parsePropertiesString
+ */
+ public String toPropertiesString() {
+
+ StringBuffer serialized = new StringBuffer(100);
+
+ // BaseUrl
+ serialized.append(getBaseUrl().toString());
+ serialized.append(DELIMITER);
+
+ // Version
+ serialized.append(getVersion().toString());
+ serialized.append(DELIMITER);
+
+ return serialized.toString();
+ }
+
+ /**
+ * @return transforms the settings to a String that can be stored in a
+ * .properties line. @see #parsePropertiesString
+ * @throws MalformedURLException
+ */
+ public static WfsServerSettings parsePropertiesString(String propString)
+ throws MalformedURLException {
+
+ String[] split = propString.split(Pattern.quote(DELIMITER));
+
+ // BaseUrl
+ URL baseUrl = new URL(split[0]);
+
+ // Version
+ WfsProtocollVersion v = WfsProtocollVersion.valueOf(split[1]);
+
+ return new WfsServerSettings(baseUrl, v);
+ }
+
+ @Override
+ public String toString() {
+ StringBuffer s = new StringBuffer();
+
+ URL baseUrl = getBaseUrl();
+ WfsProtocollVersion version = getVersion();
+
+ if (baseUrl != null)
+ s.append(baseUrl.toString() + " ");
+
+ if (version != null)
+ s.append(version.getVersionString());
+
+ return s.toString();
+ }
+
+ public void setCachedTypeNames(String[] cachedTypeNames) {
+ this.cachedTypeNames = cachedTypeNames;
+ }
+
+ public String[] getCachedTypeNames() {
+ return cachedTypeNames;
+ }
+
+ private String[] cachedTypeNames = null;
+
+ public String getTitle() {
+ // TODO
+ return "" + getBaseUrl() + " " + getVersion();
+ }
+
+ /**
+ * Opens a GUI that asks the use define a DB connection.
+ *
+ * @param wfsServer
+ * <code>null</code> to create a new instance, or an instance to
+ * edit.
+ * @return <code>null</code> if the user cancelled the creation of a new
+ * {@link DbServerSettings}, otherwise the edited instance.
+ */
+ public static WfsServerSettings createOrEdit(Component owner,
+ WfsServerSettings wfsServer) {
+ boolean newCreated = false;
+
+ if (wfsServer == null) {
+ newCreated = true;
+ wfsServer = new WfsServerSettings();
+ }
+
+ Text hostInput = new ManualInputOption.Text(
+ "BaseURL (without any paramters)", true, wfsServer.getBaseUrl()
+ .toString());
+
+ Combo<WfsProtocollVersion> versionInput = new SelectionInputOption.Combo<WfsProtocollVersion>(
+ "WFS Version", true, WfsProtocollVersion.values(),
+ ArrayUtils.indexOf(WfsProtocollVersion.values(),
+ wfsServer.getVersion()), WfsProtocollVersion.values());
+
+ Object[] input = MultipleOptionPane.showMultipleInputDialog(owner,
+ "WFS Connection parameters", hostInput, versionInput);
+
+ if (input == null) {
+ if (newCreated)
+ return null;
+ else
+ return wfsServer;
+ } else {
+ wfsServer.setBaseUrl((String) input[0]);
+ wfsServer.setVersion(((WfsProtocollVersion) input[1]));
+ }
+
+ return wfsServer;
+
+ }
+
+ /**
+ * Set the BaseUrl as a String. Any pending parameters are automatically cut
+ * of.
+ */
+ public void setBaseUrl(String urlString) {
+ try {
+ // Cutoff any parameters
+ if (urlString.indexOf("?") > -1) {
+ urlString = urlString.substring(0, urlString.indexOf("?"));
+ }
+
+ setBaseUrl(new URL(urlString));
+ } catch (MalformedURLException e) {
+ throw new RuntimeException(e);
+ }
+ }
+}
Property changes on: trunk/src/skrueger/geotools/io/WfsServerSettings.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Name: svn:keywords
+ Id URL
Name: svn:eol-style
+ native
Added: trunk/src/skrueger/geotools/io/WfsSettingsJComboBox.java
===================================================================
--- trunk/src/skrueger/geotools/io/WfsSettingsJComboBox.java 2010-10-22 21:35:30 UTC (rev 1160)
+++ trunk/src/skrueger/geotools/io/WfsSettingsJComboBox.java 2010-10-24 16:44:18 UTC (rev 1161)
@@ -0,0 +1,24 @@
+package skrueger.geotools.io;
+
+import javax.swing.DefaultComboBoxModel;
+import javax.swing.JComboBox;
+
+public class WfsSettingsJComboBox extends JComboBox {
+
+ private final WfsServerList wfsList;
+
+ public WfsSettingsJComboBox(WfsServerList wfsList) {
+ super(wfsList.toArray( new WfsServerSettings[0]));
+ this.wfsList = wfsList;
+ }
+
+ public WfsServerList getWfsList() {
+ return wfsList;
+ }
+
+ public void listChanged() {
+ setModel(new DefaultComboBoxModel(wfsList.toArray(new DbServerSettings[0])));
+ }
+
+
+}
Property changes on: trunk/src/skrueger/geotools/io/WfsSettingsJComboBox.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Name: svn:keywords
+ Id URL
Name: svn:eol-style
+ native
Modified: trunk/src_junit/schmitzm/geotools/feature/FeatureUtilTest.java
===================================================================
--- trunk/src_junit/schmitzm/geotools/feature/FeatureUtilTest.java 2010-10-22 21:35:30 UTC (rev 1160)
+++ trunk/src_junit/schmitzm/geotools/feature/FeatureUtilTest.java 2010-10-24 16:44:18 UTC (rev 1161)
@@ -22,10 +22,10 @@
import org.opengis.feature.type.GeometryDescriptor;
import schmitzm.geotools.feature.FeatureUtil.GeometryForm;
+import schmitzm.geotools.io.GeoImportUtil;
import schmitzm.io.IOUtil;
import schmitzm.swing.TestingUtil;
import schmitzm.swing.TestingUtil.TestDatasets;
-import skrueger.geotools.io.GeoImportUtilURL;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.geom.Polygon;
@@ -125,7 +125,7 @@
outputFs.dispose();
// Testen, ob das gewünschte Ergebnis erstellt wurde
- FeatureCollection<SimpleFeatureType, SimpleFeature> correctedFC = GeoImportUtilURL
+ FeatureCollection<SimpleFeatureType, SimpleFeature> correctedFC = GeoImportUtil
.readFeaturesFromShapeFile(outFile);
// Schema testen
Modified: trunk/src_junit/schmitzm/swing/TestingUtil.java
===================================================================
--- trunk/src_junit/schmitzm/swing/TestingUtil.java 2010-10-22 21:35:30 UTC (rev 1160)
+++ trunk/src_junit/schmitzm/swing/TestingUtil.java 2010-10-24 16:44:18 UTC (rev 1161)
@@ -41,9 +41,9 @@
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
+import schmitzm.geotools.io.GeoImportUtil;
import schmitzm.io.IOUtil;
import schmitzm.lang.LangUtil;
-import skrueger.geotools.io.GeoImportUtilURL;
/**
* Helpers to test Swing applications in general. <br/>
@@ -83,8 +83,7 @@
}
public DataStore getDataStore() throws IOException {
- DataStore ds = GeoImportUtilURL.readDataStoreFromShape(getUrl(),
- null);
+ DataStore ds = GeoImportUtil.readDataStoreFromShape(getUrl(), null);
return ds;
}
Added: trunk/src_junit/skrueger/geotools/io/DbServerListTest.java
===================================================================
--- trunk/src_junit/skrueger/geotools/io/DbServerListTest.java 2010-10-22 21:35:30 UTC (rev 1160)
+++ trunk/src_junit/skrueger/geotools/io/DbServerListTest.java 2010-10-24 16:44:18 UTC (rev 1161)
@@ -0,0 +1,33 @@
+package skrueger.geotools.io;
+
+import static org.junit.Assert.assertEquals;
+
+import java.net.MalformedURLException;
+
+import org.junit.Test;
+
+import skrueger.geotools.io.DbServerSettings.DbType;
+
+public class DbServerListTest {
+
+ @Test
+ public void testSerializeAndParseServers() throws MalformedURLException {
+ DbServerSettings dbDs1 = new DbServerSettings(DbType.postgis);
+ DbServerSettings dbDs2 = new DbServerSettings(DbType.postgis);
+
+ DbServerList list1 = new DbServerList(dbDs1, dbDs2);
+
+ DbServerList list2 = DbServerList.parsePropertiesString(list1
+ .toPropertiesString());
+
+ assertEquals(list1.size(), list2.size());
+ assertEquals(list1.get(0).getDbType(), list2.get(0).getDbType());
+ assertEquals(list1.get(1), list2.get(1));
+ }
+
+ @Test
+ public void testParseEmpty() {
+ assertEquals(0, DbServerList.parsePropertiesString(null).size());
+ assertEquals(0, DbServerList.parsePropertiesString("").size());
+ }
+}
Property changes on: trunk/src_junit/skrueger/geotools/io/DbServerListTest.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Name: svn:keywords
+ Id URL
Name: svn:eol-style
+ native
Added: trunk/src_junit/skrueger/geotools/io/DbServerSettingsTest.java
===================================================================
--- trunk/src_junit/skrueger/geotools/io/DbServerSettingsTest.java 2010-10-22 21:35:30 UTC (rev 1160)
+++ trunk/src_junit/skrueger/geotools/io/DbServerSettingsTest.java 2010-10-24 16:44:18 UTC (rev 1161)
@@ -0,0 +1,42 @@
+package skrueger.geotools.io;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.net.MalformedURLException;
+
+import org.junit.Test;
+
+import skrueger.geotools.io.DbServerSettings.DbType;
+
+public class DbServerSettingsTest {
+
+ @Test
+ public void testParseAndSerialize1() throws MalformedURLException {
+ DbServerSettings dbStore1 = new DbServerSettings(DbType.postgis);
+ dbStore1.setUsername("postgres");
+ dbStore1.setPassword("secret");
+ dbStore1.setDatabase("testDb");
+ dbStore1.setSchema("myschema");
+
+ assertFalse(dbStore1.isWellDefined());
+ dbStore1.setHost("localhost");
+ assertTrue(dbStore1.isWellDefined());
+
+ dbStore1.toPropertiesString();
+
+ DbServerSettings dbStore2 = DbServerSettings
+ .parsePropertiesString(dbStore1.toPropertiesString());
+
+ assertEquals(dbStore1.getDbType(), dbStore2.getDbType());
+
+ assertEquals(dbStore1.isWellDefined(), dbStore2.isWellDefined());
+
+ assertEquals(dbStore1.getUsername(), dbStore2.getUsername());
+ assertEquals(dbStore1.getPassword(), dbStore2.getPassword());
+ assertEquals(dbStore1.getPort(), dbStore2.getPort());
+ assertEquals(dbStore1.getSchema(), dbStore2.getSchema());
+ }
+
+}
Property changes on: trunk/src_junit/skrueger/geotools/io/DbServerSettingsTest.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Name: svn:keywords
+ Id URL
Name: svn:eol-style
+ native
Added: trunk/src_junit/skrueger/geotools/io/WfsServerListTest.java
===================================================================
--- trunk/src_junit/skrueger/geotools/io/WfsServerListTest.java 2010-10-22 21:35:30 UTC (rev 1160)
+++ trunk/src_junit/skrueger/geotools/io/WfsServerListTest.java 2010-10-24 16:44:18 UTC (rev 1161)
@@ -0,0 +1,39 @@
+package skrueger.geotools.io;
+
+import static org.junit.Assert.assertEquals;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+
+import org.junit.Test;
+
+import skrueger.geotools.io.WfsServerSettings.WfsProtocollVersion;
+
+public class WfsServerListTest {
+
+ @Test
+ public void testSerializeAndParseServers() throws MalformedURLException {
+ WfsServerSettings wfs1 = new WfsServerSettings(new URL(
+ "http://localhost:8085/geoserver/ows"),
+ WfsProtocollVersion.v1_1_1);
+ WfsServerSettings wfs2 = new WfsServerSettings(new URL(
+ "http://localhost:8080/geoserver2/ows"),
+ WfsProtocollVersion.v1_0_0);
+
+ WfsServerList list1 = new WfsServerList(wfs1, wfs2);
+
+ WfsServerList list2 = WfsServerList.parsePropertiesString(list1
+ .toPropertiesString());
+
+ assertEquals(list1.size(), list2.size());
+ assertEquals(list1.get(0).getBaseUrl(), list2.get(0).getBaseUrl());
+ assertEquals(list1.get(1), list2.get(1));
+ }
+
+ @Test
+ public void testParseEmpty() {
+ assertEquals(0, WfsServerList.parsePropertiesString(null).size());
+ assertEquals(0, WfsServerList.parsePropertiesString("").size());
+ }
+
+}
Property changes on: trunk/src_junit/skrueger/geotools/io/WfsServerListTest.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Name: svn:keywords
+ Id URL
Name: svn:eol-style
+ native
Added: trunk/src_junit/skrueger/geotools/io/WfsServerSettingsTest.java
===================================================================
--- trunk/src_junit/skrueger/geotools/io/WfsServerSettingsTest.java 2010-10-22 21:35:30 UTC (rev 1160)
+++ trunk/src_junit/skrueger/geotools/io/WfsServerSettingsTest.java 2010-10-24 16:44:18 UTC (rev 1161)
@@ -0,0 +1,41 @@
+package skrueger.geotools.io;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+
+import org.junit.Test;
+
+import skrueger.geotools.io.WfsServerSettings.WfsProtocollVersion;
+
+public class WfsServerSettingsTest {
+
+ @Test
+ public void testParseAndSerialize1() throws MalformedURLException {
+ WfsServerSettings wfs1 = new WfsServerSettings(new URL(
+ "http://localhost:8085/geoserver/ows"),
+ WfsProtocollVersion.v1_1_0);
+
+ assertTrue(wfs1.isWellDefined());
+
+ wfs1.toPropertiesString();
+
+ WfsServerSettings wfs2 = WfsServerSettings.parsePropertiesString(wfs1
+ .toPropertiesString());
+
+ assertEquals(wfs1.getBaseUrl(), wfs2.getBaseUrl());
+ assertEquals(wfs1.getVersion(), wfs2.getVersion());
+ assertEquals(wfs1.getCapabilitiesUrl(), wfs2.getCapabilitiesUrl());
+ assertEquals(wfs1.isWellDefined(), wfs2.isWellDefined());
+ }
+
+ @Test
+ public void testSetBaseUrl() {
+ WfsServerSettings wfs = new WfsServerSettings();
+ wfs.setBaseUrl("http://localhost?asd=2323");
+ assertEquals("http://localhost", wfs.getBaseUrl().toString());
+ }
+
+}
Property changes on: trunk/src_junit/skrueger/geotools/io/WfsServerSettingsTest.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Name: svn:keywords
+ Id URL
Name: svn:eol-style
+ native
More information about the Schmitzm-commits
mailing list