src/main/java/de/uapcore/lightpit/DatabaseFacade.java

Sat, 09 May 2020 17:01:29 +0200

author
Mike Becker <universe@uap-core.de>
date
Sat, 09 May 2020 17:01:29 +0200
changeset 34
824d4042c857
parent 33
fd8c40ff78c3
child 38
cf85ef18f231
permissions
-rw-r--r--

cleanup and simplification of database access layer

universe@16 1 /*
universe@16 2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
universe@34 3 *
universe@24 4 * Copyright 2018 Mike Becker. All rights reserved.
universe@34 5 *
universe@16 6 * Redistribution and use in source and binary forms, with or without
universe@16 7 * modification, are permitted provided that the following conditions are met:
universe@16 8 *
universe@16 9 * 1. Redistributions of source code must retain the above copyright
universe@16 10 * notice, this list of conditions and the following disclaimer.
universe@16 11 *
universe@16 12 * 2. Redistributions in binary form must reproduce the above copyright
universe@16 13 * notice, this list of conditions and the following disclaimer in the
universe@16 14 * documentation and/or other materials provided with the distribution.
universe@16 15 *
universe@16 16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
universe@16 17 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
universe@16 18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
universe@16 19 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
universe@16 20 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
universe@16 21 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
universe@16 22 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
universe@16 23 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
universe@16 24 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
universe@16 25 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
universe@16 26 * POSSIBILITY OF SUCH DAMAGE.
universe@34 27 *
universe@16 28 */
universe@16 29 package de.uapcore.lightpit;
universe@16 30
universe@34 31 import de.uapcore.lightpit.dao.DataAccessObjects;
universe@34 32 import de.uapcore.lightpit.dao.postgres.PGDataAccessObjects;
universe@33 33 import org.slf4j.Logger;
universe@33 34 import org.slf4j.LoggerFactory;
universe@33 35
universe@16 36 import javax.naming.Context;
universe@16 37 import javax.naming.InitialContext;
universe@16 38 import javax.naming.NamingException;
universe@16 39 import javax.servlet.ServletContext;
universe@16 40 import javax.servlet.ServletContextEvent;
universe@16 41 import javax.servlet.ServletContextListener;
universe@16 42 import javax.servlet.annotation.WebListener;
universe@16 43 import javax.sql.DataSource;
universe@33 44 import java.sql.Connection;
universe@33 45 import java.sql.DatabaseMetaData;
universe@33 46 import java.sql.SQLException;
universe@33 47 import java.util.Optional;
universe@16 48
universe@16 49 /**
universe@16 50 * Provides access to different privilege layers within the database.
universe@16 51 */
universe@16 52 @WebListener
universe@16 53 public final class DatabaseFacade implements ServletContextListener {
universe@33 54
universe@16 55 private static final Logger LOG = LoggerFactory.getLogger(DatabaseFacade.class);
universe@33 56
universe@16 57 /**
universe@16 58 * Timeout in seconds for the validation test.
universe@16 59 */
universe@16 60 private static final int DB_TEST_TIMEOUT = 10;
universe@33 61
universe@34 62 /**
universe@34 63 * Specifies the database dialect.
universe@34 64 */
universe@33 65 public enum Dialect {
universe@33 66 Postgres
universe@19 67 }
universe@33 68
universe@19 69 /**
universe@19 70 * The database dialect to use.
universe@33 71 * <p>
universe@34 72 * May be overridden by context parameter.
universe@33 73 *
universe@19 74 * @see Constants#CTX_ATTR_DB_DIALECT
universe@19 75 */
universe@19 76 private Dialect dialect = Dialect.Postgres;
universe@34 77
universe@16 78 /**
universe@16 79 * The default schema to test against when validating the connection.
universe@34 80 * <p>
universe@16 81 * May be overridden by context parameter.
universe@34 82 *
universe@19 83 * @see Constants#CTX_ATTR_DB_SCHEMA
universe@16 84 */
universe@16 85 private static final String DB_DEFAULT_SCHEMA = "lightpit";
universe@34 86
universe@16 87 /**
universe@19 88 * The attribute name in the Servlet context under which an instance of this class can be found.
universe@16 89 */
universe@16 90 public static final String SC_ATTR_NAME = DatabaseFacade.class.getName();
universe@33 91
universe@19 92 private static final String DS_JNDI_NAME = "jdbc/lightpit/app";
universe@33 93 private DataSource dataSource;
universe@34 94 private DataAccessObjects dataAccessObjects;
universe@34 95
universe@16 96 /**
universe@19 97 * Returns the data source.
universe@34 98 * <p>
universe@16 99 * The Optional returned should never be empty. However, if something goes
universe@16 100 * wrong during initialization, the data source might be absent.
universe@16 101 * Hence, users of this data source are forced to check the existence.
universe@34 102 *
universe@19 103 * @return a data source
universe@16 104 */
universe@19 105 public Optional<DataSource> getDataSource() {
universe@33 106 // TODO: this should not be an optional, if an empty optional is actually an exception
universe@33 107 return Optional.ofNullable(dataSource);
universe@16 108 }
universe@34 109
universe@34 110 /**
universe@34 111 * Returns the data access objects.
universe@34 112 *
universe@34 113 * @return an interface to obtain the data access objects
universe@34 114 */
universe@34 115 public DataAccessObjects getDataAccessObjects() {
universe@34 116 return dataAccessObjects;
universe@34 117 }
universe@34 118
universe@19 119 public Dialect getSQLDialect() {
universe@19 120 return dialect;
universe@16 121 }
universe@33 122
universe@33 123 private static void checkConnection(DataSource ds, String testSchema) {
universe@16 124 try (Connection conn = ds.getConnection()) {
universe@16 125 if (!conn.isValid(DB_TEST_TIMEOUT)) {
universe@16 126 throw new SQLException("Validation check failed.");
universe@16 127 }
universe@16 128 if (conn.isReadOnly()) {
universe@16 129 throw new SQLException("Connection is read-only and thus unusable.");
universe@16 130 }
universe@16 131 if (!conn.getSchema().equals(testSchema)) {
universe@16 132 throw new SQLException(String.format("Connection is not configured to use the schema %s.", testSchema));
universe@16 133 }
universe@16 134 DatabaseMetaData metaData = conn.getMetaData();
universe@16 135 LOG.info("Connections as {} to {}/{} ready to go.", metaData.getUserName(), metaData.getURL(), conn.getSchema());
universe@16 136 } catch (SQLException ex) {
universe@33 137 LOG.error("Checking database connection failed", ex);
universe@16 138 }
universe@16 139 }
universe@33 140
universe@33 141 private static DataSource retrieveDataSource(Context ctx) {
universe@16 142 DataSource ret = null;
universe@16 143 try {
universe@33 144 ret = (DataSource) ctx.lookup(DS_JNDI_NAME);
universe@19 145 LOG.info("Data source retrieved.");
universe@16 146 } catch (NamingException ex) {
universe@19 147 LOG.error("Data source {} not available.", DS_JNDI_NAME);
universe@16 148 LOG.error("Reason for the missing data source: ", ex);
universe@16 149 }
universe@33 150 return ret;
universe@16 151 }
universe@16 152
universe@16 153 @Override
universe@16 154 public void contextInitialized(ServletContextEvent sce) {
universe@33 155 ServletContext sc = sce.getServletContext();
universe@34 156
universe@19 157 dataSource = null;
universe@34 158
universe@16 159 final String contextName = Optional
universe@16 160 .ofNullable(sc.getInitParameter(Constants.CTX_ATTR_JNDI_CONTEXT))
universe@16 161 .orElse("java:comp/env");
universe@16 162 final String dbSchema = Optional
universe@16 163 .ofNullable(sc.getInitParameter(Constants.CTX_ATTR_DB_SCHEMA))
universe@16 164 .orElse(DB_DEFAULT_SCHEMA);
universe@19 165 final String dbDialect = sc.getInitParameter(Constants.CTX_ATTR_DB_DIALECT);
universe@19 166 if (dbDialect != null) {
universe@19 167 try {
universe@19 168 dialect = Dialect.valueOf(dbDialect);
universe@19 169 } catch (IllegalArgumentException ex) {
universe@20 170 LOG.error("Unknown or unsupported database dialect {}. Defaulting to {}.", dbDialect, dialect);
universe@19 171 }
universe@19 172 }
universe@16 173
universe@34 174 dataAccessObjects = createDataAccessObjects(dialect);
universe@34 175
universe@16 176 try {
universe@16 177 LOG.debug("Trying to access JNDI context {}...", contextName);
universe@16 178 Context initialCtx = new InitialContext();
universe@16 179 Context ctx = (Context) initialCtx.lookup(contextName);
universe@33 180
universe@19 181 dataSource = retrieveDataSource(ctx);
universe@33 182
universe@33 183 if (dataSource != null) {
universe@33 184 checkConnection(dataSource, dbSchema);
universe@33 185 }
universe@16 186 } catch (NamingException | ClassCastException ex) {
universe@16 187 LOG.error("Cannot access JNDI resources.", ex);
universe@16 188 }
universe@34 189
universe@16 190 sc.setAttribute(SC_ATTR_NAME, this);
universe@16 191 LOG.info("Database facade injected into ServletContext.");
universe@16 192 }
universe@16 193
universe@34 194 private static DataAccessObjects createDataAccessObjects(Dialect dialect) {
universe@34 195 switch (dialect) {
universe@34 196 case Postgres:
universe@34 197 return new PGDataAccessObjects();
universe@34 198 default:
universe@34 199 throw new AssertionError("Non-exhaustive switch - this is a bug.");
universe@34 200 }
universe@34 201 }
universe@34 202
universe@16 203 @Override
universe@16 204 public void contextDestroyed(ServletContextEvent sce) {
universe@19 205 dataSource = null;
universe@34 206 }
universe@16 207 }

mercurial