From 64ed3d94ddfb211c6784621e0cc8ded37f255755 Mon Sep 17 00:00:00 2001
From: Nikolaus Krismer <niko@krismer.de>
Date: Tue, 1 Apr 2014 15:15:49 +0200
Subject: [PATCH] splitting configurations of webfrontend and backend into
 separate files fixed some problems in web application according to database
 connections

---
 .../inf/isochrone/config/ConfigIsochrone.java |  2 +-
 .../it/unibz/inf/isochrone/db/Database.java   | 59 +++++++++++--------
 .../inf/isoga/config/ConfigGeoserver.java     | 18 +++---
 .../it/unibz/inf/isoga/db/DatabaseWeb.java    | 13 +++-
 .../inf/isoga/service/ServiceIsochrone.java   | 10 ++--
 src/main/resources/config.xml                 | 12 +---
 src/main/resources/configWeb.xml              | 13 ++++
 src/test/resources/config-test.xml            |  4 +-
 8 files changed, 78 insertions(+), 53 deletions(-)
 create mode 100644 src/main/resources/configWeb.xml

diff --git a/src/main/java/it/unibz/inf/isochrone/config/ConfigIsochrone.java b/src/main/java/it/unibz/inf/isochrone/config/ConfigIsochrone.java
index 4ce45731..78eaa752 100644
--- a/src/main/java/it/unibz/inf/isochrone/config/ConfigIsochrone.java
+++ b/src/main/java/it/unibz/inf/isochrone/config/ConfigIsochrone.java
@@ -73,7 +73,7 @@ public final class ConfigIsochrone {
 
 	@NotNull
 	@DefaultValue("")
-	@PropertyValue("cfg.clientPrefix")
+	@PropertyValue("prefix")
 	private String prefix;
 
 	@NotNull
diff --git a/src/main/java/it/unibz/inf/isochrone/db/Database.java b/src/main/java/it/unibz/inf/isochrone/db/Database.java
index de4cd7c4..95155784 100644
--- a/src/main/java/it/unibz/inf/isochrone/db/Database.java
+++ b/src/main/java/it/unibz/inf/isochrone/db/Database.java
@@ -61,8 +61,8 @@ public class Database {
 	protected final ConfigDataset config;
 	protected Mode mode;
 	protected boolean isIncoming;
-	protected Connection connection; /** The connection the the database. It is lazy-loaded by {@link #getPstmt(String)} method. */
 	private Map<String, PreparedStatement> pstmtsCacheMap;
+	private Connection connection; /** The connection the the database. It is lazy-loaded by {@link #getPstmt(String)} method. */
 	// Constructor
 
 	public Database(final ConfigDataset config, final Mode mode, final Direction direction) {
@@ -633,10 +633,7 @@ public class Database {
 	// FIXME: Find a fix for prepared statements with parameters
 	// (we should NOT set strings in preparedStatemens just because we want to cache something)
 	protected PreparedStatement getPstmt(final String query) {
-		if (connection == null) {
-			// lazy-loading of the database connection (so it is not created on object construction)
-			connection = ConfigIsochrone.getInstance().getConnection();
-		}
+		initConnection();
 		if (pstmtsCacheMap == null) {
 			pstmtsCacheMap = new HashMap<String, PreparedStatement>();
 		}
@@ -656,6 +653,18 @@ public class Database {
 		return null;
 	}
 
+	protected void initConnection() {
+		if (connection == null) {
+			// lazy-loading of the database connection (so it is not created on object construction)
+			connection = ConfigIsochrone.getInstance().getConnection();
+		}
+	}
+
+	protected Connection getConnection() {
+		initConnection();
+		return connection;
+	}
+
 	// Private methods
 
 	private Link createLinkFromResultSet(final int nodeId, final int adjNodeId, final ResultSet rs) throws SQLException {
@@ -678,25 +687,7 @@ public class Database {
 		return new Link(linkId, start, end, routeId);
 	}
 
-	// Private static methods
-
-	/**
-	 * Prepares a number of place holders for a prepared statement.
-	 *
-	 * @param length The number of placeholders that is needed
-	 * @return a string with the placeholders plugged in to a statement.
-	 */
-	private static String preparePlaceHolders(final int length) {
-		final StringBuilder builder = new StringBuilder();
-		for (int i = 0; i < length; ++i) {
-			builder.append("?");
-			if ((i + 1) < length) {
-				builder.append(",");
-			}
-		}
-
-		return builder.toString();
-	}
+	// Protected static methods
 
 	/**
 	 * Sets the values in the placeholders in a prepared statement, generated by
@@ -717,6 +708,26 @@ public class Database {
 		return startIdx + values.length;
 	}
 
+	// Private static methods
+
+	/**
+	 * Prepares a number of place holders for a prepared statement.
+	 *
+	 * @param length The number of placeholders that is needed
+	 * @return a string with the placeholders plugged in to a statement.
+	 */
+	private static String preparePlaceHolders(final int length) {
+		final StringBuilder builder = new StringBuilder();
+		for (int i = 0; i < length; ++i) {
+			builder.append("?");
+			if ((i + 1) < length) {
+				builder.append(",");
+			}
+		}
+
+		return builder.toString();
+	}
+
 	/**
 	 * Adds a node to the network.
 	 *
diff --git a/src/main/java/it/unibz/inf/isoga/config/ConfigGeoserver.java b/src/main/java/it/unibz/inf/isoga/config/ConfigGeoserver.java
index 78c6cd21..5af24a90 100644
--- a/src/main/java/it/unibz/inf/isoga/config/ConfigGeoserver.java
+++ b/src/main/java/it/unibz/inf/isoga/config/ConfigGeoserver.java
@@ -1,5 +1,13 @@
 package it.unibz.inf.isoga.config;
 
+import com.tngtech.configbuilder.ConfigBuilder;
+import com.tngtech.configbuilder.annotation.propertyloaderconfiguration.PropertiesFiles;
+import com.tngtech.configbuilder.annotation.propertyloaderconfiguration.PropertyExtension;
+import com.tngtech.configbuilder.annotation.propertyloaderconfiguration.PropertyLocations;
+import com.tngtech.configbuilder.annotation.propertyloaderconfiguration.PropertySuffixes;
+import com.tngtech.configbuilder.annotation.valueextractor.DefaultValue;
+import com.tngtech.configbuilder.annotation.valueextractor.PropertyValue;
+
 import it.geosolutions.geoserver.rest.GeoServerRESTManager;
 import it.geosolutions.geoserver.rest.GeoServerRESTPublisher;
 import it.geosolutions.geoserver.rest.GeoServerRESTReader;
@@ -13,19 +21,11 @@ import javax.validation.constraints.NotNull;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.tngtech.configbuilder.ConfigBuilder;
-import com.tngtech.configbuilder.annotation.propertyloaderconfiguration.PropertiesFiles;
-import com.tngtech.configbuilder.annotation.propertyloaderconfiguration.PropertyExtension;
-import com.tngtech.configbuilder.annotation.propertyloaderconfiguration.PropertyLocations;
-import com.tngtech.configbuilder.annotation.propertyloaderconfiguration.PropertySuffixes;
-import com.tngtech.configbuilder.annotation.valueextractor.DefaultValue;
-import com.tngtech.configbuilder.annotation.valueextractor.PropertyValue;
-
 /**
  * @author Nikolaus Krismer
  * @version 3
  */
-@PropertiesFiles({ "config", "config-test" })
+@PropertiesFiles({ "configWeb", "configWeb-test" })
 @PropertyLocations(fromClassLoader = true)
 @PropertyExtension("xml")
 @PropertySuffixes(extraSuffixes = { }, hostNames = false)
diff --git a/src/main/java/it/unibz/inf/isoga/db/DatabaseWeb.java b/src/main/java/it/unibz/inf/isoga/db/DatabaseWeb.java
index 994ea7f6..4625a6c0 100644
--- a/src/main/java/it/unibz/inf/isoga/db/DatabaseWeb.java
+++ b/src/main/java/it/unibz/inf/isoga/db/DatabaseWeb.java
@@ -90,6 +90,7 @@ public class DatabaseWeb extends Database {
 	// Public methods
 
 	public void createBuffer(final String bufferTable, final String edgeTable, final double bufferSize) {
+		final Connection connection = getConnection();
 		final StringBuilder b = new StringBuilder("INSERT INTO ").append(bufferTable);
 		b.append(" SELECT 1,ST_Multi(ST_UNION(ST_BUFFER(\"GEOMETRY\", ").append(bufferSize).append("))) \"GEOMETRY\" FROM ").append(edgeTable);
 
@@ -136,8 +137,9 @@ public class DatabaseWeb extends Database {
 		return edges;
 	}
 
+	@Override
 	public Connection getConnection() {
-		return connection;
+		return super.getConnection();
 	}
 
 	@SuppressFBWarnings(
@@ -313,12 +315,13 @@ public class DatabaseWeb extends Database {
 	*/
 
 	public void storeArea(final int areaId, final List<Point> points, final double bufferSize) {
+		final Connection connection = getConnection();
 		final Geometry geometry = PgHelper.asPgGeometry(points);
 		final String geometryString = geometry.getTypeString() + geometry.getValue();
-
 		final StringBuilder b = new StringBuilder();
 		b.append("INSERT INTO ").append(config.getAreaBufferTableEntry().getTableName());
 		b.append("(\"ID\",\"GEOMETRY\") VALUES(?,ST_MULTI(ST_Buffer(ST_MakeValid(ST_GeomFromText(?," + config.getServerSRID() + ")),?,'endcap=round join=round')))");
+
 		PreparedStatement statement = null;
 		try {
 			statement = getPstmt(b.toString());
@@ -337,7 +340,9 @@ public class DatabaseWeb extends Database {
 	}
 
 	public final void storeLinks(final Collection<Link> links, final Direction direction) {
+		final Connection connection = getConnection();
 		final boolean isIncoming = direction == Direction.INCOMING;
+
 		PreparedStatement statementPartial = null;
 		PreparedStatement statementFull = null;
 		try {
@@ -388,6 +393,7 @@ public class DatabaseWeb extends Database {
 	}
 
 	public void storeVertices(final Set<Node> nodes) {
+		final Connection connection = getConnection();
 		PreparedStatement insertVerticesStatement = null;
 		PreparedStatement insertVertexAnnotationStatement = null;
 
@@ -427,11 +433,14 @@ public class DatabaseWeb extends Database {
 	}
 
 	public Point transform(final Point p) {
+		final Connection connection = getConnection();
 		final String query = "SELECT ST_X(P.GEO) X, ST_Y(P.GEO) Y FROM (SELECT ST_Transform(ST_PointFromText(?,?),?) GEO ) P";
 		return DatabaseWeb.transform(connection, config, p, getPstmt(query));
 	}
 
 	public void updateVertexTable() {
+		final Connection connection = getConnection();
+
 		PreparedStatement statement = null;
 		try {
 			statement = getPstmt(queryUpdateVertices);
diff --git a/src/main/java/it/unibz/inf/isoga/service/ServiceIsochrone.java b/src/main/java/it/unibz/inf/isoga/service/ServiceIsochrone.java
index 5f36e40b..59aa9f94 100644
--- a/src/main/java/it/unibz/inf/isoga/service/ServiceIsochrone.java
+++ b/src/main/java/it/unibz/inf/isoga/service/ServiceIsochrone.java
@@ -61,10 +61,9 @@ public class ServiceIsochrone extends AbstractService<RequestIsochrone, Response
 		if (!config.isRegistered()) {
 			registerTableAndLayers(db.getConnection(), config);
 		}
-
-		// Timing start
-
 		truncateTables(db.getConnection(), config);
+
+		// create query and calculate isochrone
 		final Query query = new Query(direction, request.getSpeed(), request.getDmax(), request.getDate(), true, request.getMode());
 		query.setStartLocations(locationsFromQueryNodes(request.getQueryNodes(), db));
 		final Isochrone isochrone = getAlgorithm(request.getAlgorithm(), config, db, query);
@@ -83,11 +82,12 @@ public class ServiceIsochrone extends AbstractService<RequestIsochrone, Response
 			}
 		}
 
-		db.close();
-
 		final ResponseIsochrone response = new ResponseIsochrone();
 		response.setBoundingBox(output.getBoundingBox());
 
+		// now that bbox is calculated, we can close the database connection
+		db.close();
+
 		final long currentTime = System.currentTimeMillis();
 		final long totalRequestTime = currentTime - startRequestTiming;
 		final long timeCoveraging = (startComputationTiming <= 0) ? 0 : currentTime - startCoverageTiming;
diff --git a/src/main/resources/config.xml b/src/main/resources/config.xml
index 9acb4d33..ae96077d 100644
--- a/src/main/resources/config.xml
+++ b/src/main/resources/config.xml
@@ -12,14 +12,6 @@
 	<entry key="org.postgresql.password">secretPhdPassword#2014!</entry>
 	<entry key="org.postgresql.port">5432</entry>
 
-	<!-- Rendering engine properties -->
-	<entry key="rendering.server.rest.url">http://localhost:8080/geoserver</entry>
-	<entry key="rendering.server.rest.username">admin</entry>
-	<entry key="rendering.server.rest.password">geoserver</entry>
-	<entry key="rendering.server.rest.workspace">isochrone</entry>
-	<entry key="rendering.server.rest.datastore">sessions</entry>
-
-	<!-- Configuration parameters -->
-	<entry key="cfg.clientSRID">3857</entry>
-	<entry key="cfg.clientPrefix"></entry>
+	<!-- Postgres/Geoserver prefix -->
+	<entry key="tablePrefix"></entry>
 </properties>
diff --git a/src/main/resources/configWeb.xml b/src/main/resources/configWeb.xml
new file mode 100644
index 00000000..20b3973e
--- /dev/null
+++ b/src/main/resources/configWeb.xml
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
+<properties>
+	<!-- Rendering engine properties -->
+	<entry key="rendering.server.rest.url">http://localhost:8080/geoserver</entry>
+	<entry key="rendering.server.rest.username">admin</entry>
+	<entry key="rendering.server.rest.password">geoserver</entry>
+	<entry key="rendering.server.rest.workspace">isochrone</entry>
+	<entry key="rendering.server.rest.datastore">sessions</entry>
+
+	<!-- Configuration parameters -->
+	<entry key="cfg.clientSRID">3857</entry>
+</properties>
diff --git a/src/test/resources/config-test.xml b/src/test/resources/config-test.xml
index d13a8851..b8fdfea6 100644
--- a/src/test/resources/config-test.xml
+++ b/src/test/resources/config-test.xml
@@ -4,6 +4,6 @@
 	<!-- Postgres database -->
 	<entry key="org.postgresql.servername">dbis-isochrone.uibk.ac.at</entry>
 
-	<!-- Geoserver/PostgisLayer prefix -->
-	<entry key="cfg.clientPrefix">test</entry>
+	<!-- Postgres/Geoserver prefix -->
+	<entry key="prefix">test</entry>
 </properties>
-- 
GitLab