migrate DataSourceProvider

Sat, 24 Oct 2020 12:09:08 +0200

author
Mike Becker <universe@uap-core.de>
date
Sat, 24 Oct 2020 12:09:08 +0200
changeset 151
b3f14cd4f3ab
parent 150
822b7e3d064d
child 152
7761c37c5e61

migrate DataSourceProvider

build.gradle.kts file | annotate | diff | comparison | revisions
src/main/java/de/uapcore/lightpit/AbstractLightPITServlet.java file | annotate | diff | comparison | revisions
src/main/java/de/uapcore/lightpit/DatabaseFacade.java file | annotate | diff | comparison | revisions
src/main/kotlin/de/uapcore/lightpit/DataSourceProvider.kt file | annotate | diff | comparison | revisions
src/main/kotlin/de/uapcore/lightpit/Logging.kt file | annotate | diff | comparison | revisions
--- a/build.gradle.kts	Fri Oct 23 20:34:57 2020 +0200
+++ b/build.gradle.kts	Sat Oct 24 12:09:08 2020 +0200
@@ -1,3 +1,4 @@
+import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
 
 plugins {
     kotlin("jvm") version "1.4.10"
@@ -13,6 +14,10 @@
     mavenCentral()
 }
 
+tasks.withType<KotlinCompile>().configureEach {
+    kotlinOptions.jvmTarget = "11"
+}
+
 tasks.war {
     archiveFileName.set("lightpit.war")
     from("src/main/resources")
--- a/src/main/java/de/uapcore/lightpit/AbstractLightPITServlet.java	Fri Oct 23 20:34:57 2020 +0200
+++ b/src/main/java/de/uapcore/lightpit/AbstractLightPITServlet.java	Sat Oct 24 12:09:08 2020 +0200
@@ -101,11 +101,11 @@
      * @return a set of data access objects
      */
     private DataAccessObjects createDataAccessObjects(Connection connection) throws SQLException {
-        final var df = (DatabaseFacade) getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME);
-        if (df.getSQLDialect() == DatabaseFacade.Dialect.Postgres) {
+        final var df = (DataSourceProvider) getServletContext().getAttribute(DataSourceProvider.Companion.getSC_ATTR_NAME());
+        if (df.getDialect() == DatabaseDialect.Postgres) {
             return new PGDataAccessObjects(connection);
         }
-        throw new AssertionError("Non-exhaustive if-else - this is a bug.");
+        throw new UnsupportedOperationException("Non-exhaustive if-else - this is a bug.");
     }
 
     private ResponseType invokeMapping(Map.Entry<PathPattern, Method> mapping, HttpServletRequest req, HttpServletResponse resp, DataAccessObjects dao) throws IOException {
@@ -434,7 +434,7 @@
         }
 
         // obtain a connection and create the data access objects
-        final var db = (DatabaseFacade) req.getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME);
+        final var db = (DataSourceProvider) req.getServletContext().getAttribute(DataSourceProvider.Companion.getSC_ATTR_NAME());
         final var ds = db.getDataSource();
         if (ds == null) {
             resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "JNDI DataSource lookup failed. See log for details.");
--- a/src/main/java/de/uapcore/lightpit/DatabaseFacade.java	Fri Oct 23 20:34:57 2020 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,176 +0,0 @@
-/*
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
- *
- * Copyright 2018 Mike Becker. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- *   1. Redistributions of source code must retain the above copyright
- *      notice, this list of conditions and the following disclaimer.
- *
- *   2. Redistributions in binary form must reproduce the above copyright
- *      notice, this list of conditions and the following disclaimer in the
- *      documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- *
- */
-package de.uapcore.lightpit;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.naming.Context;
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-import javax.servlet.ServletContext;
-import javax.servlet.ServletContextEvent;
-import javax.servlet.ServletContextListener;
-import javax.servlet.annotation.WebListener;
-import javax.sql.DataSource;
-import java.sql.Connection;
-import java.sql.DatabaseMetaData;
-import java.sql.SQLException;
-import java.util.Optional;
-
-/**
- * Provides access to different privilege layers within the database.
- */
-@WebListener
-public final class DatabaseFacade implements ServletContextListener {
-
-    private static final Logger LOG = LoggerFactory.getLogger(DatabaseFacade.class);
-
-    /**
-     * Timeout in seconds for the validation test.
-     */
-    private static final int DB_TEST_TIMEOUT = 10;
-
-    /**
-     * Specifies the database dialect.
-     */
-    public enum Dialect {
-        Postgres
-    }
-
-    /**
-     * The database dialect to use.
-     * <p>
-     * May be overridden by context parameter.
-     *
-     * @see Constants#CTX_ATTR_DB_DIALECT
-     */
-    private Dialect dialect = Dialect.Postgres;
-
-    /**
-     * The default schema to test against when validating the connection.
-     * <p>
-     * May be overridden by context parameter.
-     *
-     * @see Constants#CTX_ATTR_DB_SCHEMA
-     */
-    private static final String DB_DEFAULT_SCHEMA = "lightpit";
-
-    /**
-     * The attribute name in the Servlet context under which an instance of this class can be found.
-     */
-    public static final String SC_ATTR_NAME = DatabaseFacade.class.getName();
-
-    private static final String DS_JNDI_NAME = "jdbc/lightpit/app";
-    private DataSource dataSource;
-
-    /**
-     * Returns the data source.
-     *
-     * @return a data source
-     */
-    public DataSource getDataSource() {
-        return dataSource;
-    }
-
-    public Dialect getSQLDialect() {
-        return dialect;
-    }
-
-    private static void checkConnection(DataSource ds, String testSchema) {
-        try (Connection conn = ds.getConnection()) {
-            if (!conn.isValid(DB_TEST_TIMEOUT)) {
-                throw new SQLException("Validation check failed.");
-            }
-            if (conn.isReadOnly()) {
-                throw new SQLException("Connection is read-only and thus unusable.");
-            }
-            if (!conn.getSchema().equals(testSchema)) {
-                throw new SQLException(String.format("Connection is not configured to use the schema %s.", testSchema));
-            }
-            DatabaseMetaData metaData = conn.getMetaData();
-            LOG.info("Connections as {} to {}/{} ready to go.", metaData.getUserName(), metaData.getURL(), conn.getSchema());
-        } catch (SQLException ex) {
-            LOG.error("Checking database connection failed", ex);
-        }
-    }
-
-    private static DataSource retrieveDataSource(Context ctx) {
-        DataSource ret = null;
-        try {
-            ret = (DataSource) ctx.lookup(DS_JNDI_NAME);
-            LOG.info("Data source retrieved.");
-        } catch (NamingException ex) {
-            LOG.error("Data source {} not available.", DS_JNDI_NAME);
-            LOG.error("Reason for the missing data source: ", ex);
-        }
-        return ret;
-    }
-
-    @Override
-    public void contextInitialized(ServletContextEvent sce) {
-        ServletContext sc = sce.getServletContext();
-
-        dataSource = null;
-
-        final String dbSchema = Optional
-                .ofNullable(sc.getInitParameter(Constants.CTX_ATTR_DB_SCHEMA))
-                .orElse(DB_DEFAULT_SCHEMA);
-        final String dbDialect = sc.getInitParameter(Constants.CTX_ATTR_DB_DIALECT);
-        if (dbDialect != null) {
-            try {
-                dialect = Dialect.valueOf(dbDialect);
-            } catch (IllegalArgumentException ex) {
-                LOG.error("Unknown or unsupported database dialect {}. Defaulting to {}.", dbDialect, dialect);
-            }
-        }
-
-        try {
-            LOG.debug("Trying to access JNDI context ...");
-            Context initialCtx = new InitialContext();
-            Context ctx = (Context) initialCtx.lookup("java:comp/env");
-
-            dataSource = retrieveDataSource(ctx);
-
-            if (dataSource != null) {
-                checkConnection(dataSource, dbSchema);
-            }
-        } catch (NamingException | ClassCastException ex) {
-            LOG.error("Cannot access JNDI resources.", ex);
-        }
-
-        sc.setAttribute(SC_ATTR_NAME, this);
-        LOG.info("Database facade injected into ServletContext.");
-    }
-
-    @Override
-    public void contextDestroyed(ServletContextEvent sce) {
-        dataSource = null;
-    }
-}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/main/kotlin/de/uapcore/lightpit/DataSourceProvider.kt	Sat Oct 24 12:09:08 2020 +0200
@@ -0,0 +1,165 @@
+/*
+ * Copyright 2020 Mike Becker. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package de.uapcore.lightpit
+
+import java.sql.SQLException
+import javax.naming.Context
+import javax.naming.InitialContext
+import javax.naming.NamingException
+import javax.servlet.ServletContextEvent
+import javax.servlet.ServletContextListener
+import javax.servlet.annotation.WebListener
+import javax.sql.DataSource
+
+enum class DatabaseDialect {
+    Postgres
+}
+
+/**
+ * Provides access to the database.
+ */
+@WebListener
+class DataSourceProvider : ServletContextListener, LoggingTrait {
+
+    /**
+     * The database dialect to use.
+     * May be overridden by context parameter.
+     *
+     * @see Constants.CTX_ATTR_DB_DIALECT
+     */
+    var dialect = DatabaseDialect.Postgres; private set
+
+    /**
+     * The data source, if available.
+     */
+    var dataSource: DataSource? = null
+
+    companion object {
+        /**
+         * The attribute name in the Servlet context under which an instance of this class can be found.
+         */
+        val SC_ATTR_NAME = "lightpit.service.DataSourceProvider"
+
+        /**
+         * Timeout in seconds for the validation test.
+         */
+        private val DB_TEST_TIMEOUT = 10
+
+        /**
+         * The default schema to test against when validating the connection.
+         * May be overridden by context parameter.
+         *
+         * @see Constants.CTX_ATTR_DB_SCHEMA
+         */
+        private val DB_DEFAULT_SCHEMA = "lightpit"
+
+        /**
+         * The JNDI resource name for the data source.
+         */
+        private val DS_JNDI_NAME = "jdbc/lightpit/app"
+    }
+
+    private fun checkConnection(ds: DataSource, testSchema: String) {
+        try {
+            ds.connection.use { conn ->
+                if (!conn.isValid(DB_TEST_TIMEOUT)) {
+                    throw SQLException("Validation check failed.")
+                }
+                if (conn.isReadOnly) {
+                    throw SQLException("Connection is read-only and thus unusable.")
+                }
+                if (conn.schema != testSchema) {
+                    throw SQLException(
+                        String.format(
+                            "Connection is not configured to use the schema %s.",
+                            testSchema
+                        )
+                    )
+                }
+                val metaData = conn.metaData
+                logger().info(
+                    "Connections as {} to {}/{} ready to go.",
+                    metaData.userName,
+                    metaData.url,
+                    conn.schema
+                )
+            }
+        } catch (ex: SQLException) {
+            logger().error("Checking database connection failed", ex)
+        }
+    }
+
+    private fun retrieveDataSource(ctx: Context): DataSource? {
+        return try {
+            val ret = ctx.lookup(DS_JNDI_NAME) as DataSource
+            logger().info("Data source retrieved.")
+            ret
+        } catch (ex: NamingException) {
+            logger().error("Data source {} not available.", DS_JNDI_NAME)
+            logger().error("Reason for the missing data source: ", ex)
+            null
+        }
+    }
+
+    override fun contextInitialized(sce: ServletContextEvent?) {
+        val sc = sce!!.servletContext
+
+        val dbSchema = sc.getInitParameter(Constants.CTX_ATTR_DB_SCHEMA) ?: DB_DEFAULT_SCHEMA
+        sc.getInitParameter(Constants.CTX_ATTR_DB_DIALECT)?.let {dbDialect ->
+            try {
+                dialect = DatabaseDialect.valueOf(dbDialect)
+            } catch (ex: IllegalArgumentException) {
+                logger().error(
+                    "Unknown or unsupported database dialect {}. Defaulting to {}.",
+                    dbDialect,
+                    dialect
+                )
+            }
+        }
+
+        dataSource = try {
+            logger().debug("Trying to access JNDI context ...")
+            val initialCtx: Context = InitialContext()
+            val ctx = initialCtx.lookup("java:comp/env") as Context
+            retrieveDataSource(ctx)
+        } catch (ex: NamingException) {
+            logger().error("Cannot access JNDI resources.", ex)
+            null
+        } catch (ex: ClassCastException) {
+            logger().error("Cannot access JNDI resources.", ex)
+            null
+        }
+
+        dataSource?.let { checkConnection(it, dbSchema) }
+
+        sc.setAttribute(SC_ATTR_NAME, this)
+        logger().info("Database facade injected into ServletContext.")
+    }
+
+    override fun contextDestroyed(sce: ServletContextEvent?) {
+        dataSource = null
+    }
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/main/kotlin/de/uapcore/lightpit/Logging.kt	Sat Oct 24 12:09:08 2020 +0200
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2020 Mike Becker. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package de.uapcore.lightpit
+
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+
+interface LoggingTrait
+inline fun <reified T : LoggingTrait> T.logger(): Logger = LoggerFactory.getLogger(T::class.java);

mercurial