universe@16: /* universe@16: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. universe@16: * universe@16: * Copyright 2017 Mike Becker. All rights reserved. universe@16: * universe@16: * Redistribution and use in source and binary forms, with or without universe@16: * modification, are permitted provided that the following conditions are met: universe@16: * universe@16: * 1. Redistributions of source code must retain the above copyright universe@16: * notice, this list of conditions and the following disclaimer. universe@16: * universe@16: * 2. Redistributions in binary form must reproduce the above copyright universe@16: * notice, this list of conditions and the following disclaimer in the universe@16: * documentation and/or other materials provided with the distribution. universe@16: * universe@16: * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" universe@16: * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE universe@16: * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE universe@16: * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE universe@16: * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR universe@16: * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF universe@16: * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS universe@16: * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN universe@16: * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) universe@16: * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE universe@16: * POSSIBILITY OF SUCH DAMAGE. universe@16: * universe@16: */ universe@16: package de.uapcore.lightpit; universe@16: universe@16: import java.sql.Connection; universe@16: import java.sql.DatabaseMetaData; universe@16: import java.sql.SQLException; universe@16: import java.util.Optional; universe@16: import javax.naming.Context; universe@16: import javax.naming.InitialContext; universe@16: import javax.naming.NamingException; universe@16: import javax.servlet.ServletContext; universe@16: import javax.servlet.ServletContextEvent; universe@16: import javax.servlet.ServletContextListener; universe@16: import javax.servlet.annotation.WebListener; universe@16: import javax.sql.DataSource; universe@16: import org.slf4j.Logger; universe@16: import org.slf4j.LoggerFactory; universe@16: universe@16: /** universe@16: * Provides access to different privilege layers within the database. universe@16: */ universe@16: @WebListener universe@16: public final class DatabaseFacade implements ServletContextListener { universe@16: universe@16: private static final Logger LOG = LoggerFactory.getLogger(DatabaseFacade.class); universe@16: universe@16: /** universe@16: * Timeout in seconds for the validation test. universe@16: */ universe@16: private static final int DB_TEST_TIMEOUT = 10; universe@16: universe@19: public static enum Dialect { universe@19: Postgres; universe@19: } universe@19: universe@19: /** universe@19: * The database dialect to use. universe@19: * universe@19: * May be override by context parameter. universe@19: * universe@19: * @see Constants#CTX_ATTR_DB_DIALECT universe@19: */ universe@19: private Dialect dialect = Dialect.Postgres; universe@19: universe@16: /** universe@16: * The default schema to test against when validating the connection. universe@16: * universe@16: * May be overridden by context parameter. universe@19: * universe@19: * @see Constants#CTX_ATTR_DB_SCHEMA universe@16: */ universe@16: private static final String DB_DEFAULT_SCHEMA = "lightpit"; universe@16: universe@16: /** universe@19: * The attribute name in the Servlet context under which an instance of this class can be found. universe@16: */ universe@16: public static final String SC_ATTR_NAME = DatabaseFacade.class.getName(); universe@16: private ServletContext sc; universe@16: universe@19: private static final String DS_JNDI_NAME = "jdbc/lightpit/app"; universe@19: private Optional dataSource; universe@16: universe@16: /** universe@19: * Returns the data source. universe@16: * universe@16: * The Optional returned should never be empty. However, if something goes universe@16: * wrong during initialization, the data source might be absent. universe@16: * Hence, users of this data source are forced to check the existence. universe@16: * universe@19: * @return a data source universe@16: */ universe@19: public Optional getDataSource() { universe@19: return dataSource; universe@16: } universe@19: universe@19: public Dialect getSQLDialect() { universe@19: return dialect; universe@16: } universe@16: universe@16: private static void checkConnection(DataSource ds, String testSchema, String errMsg) { universe@16: try (Connection conn = ds.getConnection()) { universe@16: if (!conn.isValid(DB_TEST_TIMEOUT)) { universe@16: throw new SQLException("Validation check failed."); universe@16: } universe@16: if (conn.isReadOnly()) { universe@16: throw new SQLException("Connection is read-only and thus unusable."); universe@16: } universe@16: if (!conn.getSchema().equals(testSchema)) { universe@16: throw new SQLException(String.format("Connection is not configured to use the schema %s.", testSchema)); universe@16: } universe@16: DatabaseMetaData metaData = conn.getMetaData(); universe@16: LOG.info("Connections as {} to {}/{} ready to go.", metaData.getUserName(), metaData.getURL(), conn.getSchema()); universe@16: } catch (SQLException ex) { universe@16: LOG.error(errMsg, ex); universe@16: } universe@16: } universe@16: universe@19: private static Optional retrieveDataSource(Context ctx) { universe@16: DataSource ret = null; universe@16: try { universe@19: ret = (DataSource)ctx.lookup(DS_JNDI_NAME); universe@19: LOG.info("Data source retrieved."); universe@16: } catch (NamingException ex) { universe@19: LOG.error("Data source {} not available.", DS_JNDI_NAME); universe@16: LOG.error("Reason for the missing data source: ", ex); universe@16: } universe@16: return Optional.ofNullable(ret); universe@16: } universe@16: universe@16: @Override universe@16: public void contextInitialized(ServletContextEvent sce) { universe@16: sc = sce.getServletContext(); universe@16: universe@19: dataSource = null; universe@16: universe@16: final String contextName = Optional universe@16: .ofNullable(sc.getInitParameter(Constants.CTX_ATTR_JNDI_CONTEXT)) universe@16: .orElse("java:comp/env"); universe@16: final String dbSchema = Optional universe@16: .ofNullable(sc.getInitParameter(Constants.CTX_ATTR_DB_SCHEMA)) universe@16: .orElse(DB_DEFAULT_SCHEMA); universe@19: final String dbDialect = sc.getInitParameter(Constants.CTX_ATTR_DB_DIALECT); universe@19: if (dbDialect != null) { universe@19: try { universe@19: dialect = Dialect.valueOf(dbDialect); universe@19: } catch (IllegalArgumentException ex) { universe@20: LOG.error("Unknown or unsupported database dialect {}. Defaulting to {}.", dbDialect, dialect); universe@19: } universe@19: } universe@16: universe@16: try { universe@16: LOG.debug("Trying to access JNDI context {}...", contextName); universe@16: Context initialCtx = new InitialContext(); universe@16: Context ctx = (Context) initialCtx.lookup(contextName); universe@16: universe@19: dataSource = retrieveDataSource(ctx); universe@16: universe@19: dataSource.ifPresent((ds) -> checkConnection(ds, dbSchema, "Checking database connection failed")); universe@16: } catch (NamingException | ClassCastException ex) { universe@16: LOG.error("Cannot access JNDI resources.", ex); universe@16: } universe@16: universe@16: sc.setAttribute(SC_ATTR_NAME, this); universe@16: LOG.info("Database facade injected into ServletContext."); universe@16: } universe@16: universe@16: @Override universe@16: public void contextDestroyed(ServletContextEvent sce) { universe@19: dataSource = null; universe@16: } universe@16: }