src/main/java/de/uapcore/lightpit/ModuleManager.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 36
0f4f8f255c32
permissions
-rw-r--r--

cleanup and simplification of database access layer

universe@6 1 /*
universe@6 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@6 6 * Redistribution and use in source and binary forms, with or without
universe@6 7 * modification, are permitted provided that the following conditions are met:
universe@6 8 *
universe@6 9 * 1. Redistributions of source code must retain the above copyright
universe@6 10 * notice, this list of conditions and the following disclaimer.
universe@6 11 *
universe@6 12 * 2. Redistributions in binary form must reproduce the above copyright
universe@6 13 * notice, this list of conditions and the following disclaimer in the
universe@6 14 * documentation and/or other materials provided with the distribution.
universe@6 15 *
universe@6 16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
universe@6 17 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
universe@6 18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
universe@6 19 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
universe@6 20 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
universe@6 21 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
universe@6 22 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
universe@6 23 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
universe@6 24 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
universe@6 25 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
universe@6 26 * POSSIBILITY OF SUCH DAMAGE.
universe@34 27 *
universe@6 28 */
universe@6 29 package de.uapcore.lightpit;
universe@6 30
universe@27 31 import de.uapcore.lightpit.entities.Module;
universe@30 32 import org.slf4j.Logger;
universe@30 33 import org.slf4j.LoggerFactory;
universe@30 34
universe@7 35 import javax.servlet.Registration;
universe@6 36 import javax.servlet.ServletContext;
universe@6 37 import javax.servlet.ServletContextEvent;
universe@6 38 import javax.servlet.ServletContextListener;
universe@6 39 import javax.servlet.annotation.WebListener;
universe@30 40 import java.sql.Connection;
universe@30 41 import java.sql.SQLException;
universe@30 42 import java.util.*;
universe@30 43 import java.util.concurrent.atomic.AtomicBoolean;
universe@30 44 import java.util.stream.Collectors;
universe@6 45
universe@6 46 /**
universe@6 47 * Scans registered servlets for LightPIT modules.
universe@6 48 */
universe@6 49 @WebListener
universe@10 50 public final class ModuleManager implements ServletContextListener {
universe@34 51
universe@8 52 private static final Logger LOG = LoggerFactory.getLogger(ModuleManager.class);
universe@34 53
universe@6 54 /**
universe@6 55 * The attribute name in the servlet context under which an instance of this class can be found.
universe@6 56 */
universe@6 57 public static final String SC_ATTR_NAME = ModuleManager.class.getName();
universe@10 58 private ServletContext sc;
universe@34 59
universe@20 60 /**
universe@27 61 * Maps class names to module information.
universe@27 62 */
universe@27 63 private final Map<String, LightPITModule> registeredModules = new HashMap<>();
universe@34 64
universe@27 65 /**
universe@20 66 * This flag is true, when synchronization is needed.
universe@20 67 */
universe@21 68 private final AtomicBoolean dirty = new AtomicBoolean(true);
universe@34 69
universe@6 70 @Override
universe@6 71 public void contextInitialized(ServletContextEvent sce) {
universe@6 72 sc = sce.getServletContext();
universe@6 73 reloadAll();
universe@6 74 sc.setAttribute(SC_ATTR_NAME, this);
universe@6 75 LOG.info("Module manager injected into ServletContext.");
universe@6 76 }
universe@6 77
universe@6 78 @Override
universe@6 79 public void contextDestroyed(ServletContextEvent sce) {
universe@6 80 unloadAll();
universe@6 81 }
universe@34 82
universe@10 83 private Optional<LightPITModule> getModuleInfo(Registration reg) {
universe@6 84 try {
universe@33 85 final Class<?> scclass = Class.forName(reg.getClassName());
universe@34 86
universe@9 87 final boolean lpservlet = AbstractLightPITServlet.class.isAssignableFrom(scclass);
universe@7 88 final boolean lpmodule = scclass.isAnnotationPresent(LightPITModule.class);
universe@34 89
universe@7 90 if (lpservlet && !lpmodule) {
universe@8 91 LOG.warn(
universe@34 92 "{} is a LightPIT Servlet but is missing the module annotation.",
universe@34 93 reg.getClassName()
universe@8 94 );
universe@7 95 } else if (!lpservlet && lpmodule) {
universe@8 96 LOG.warn(
universe@34 97 "{} is annotated as a LightPIT Module but does not extend {}.",
universe@34 98 reg.getClassName(),
universe@34 99 AbstractLightPITServlet.class.getSimpleName()
universe@8 100 );
universe@7 101 }
universe@34 102
universe@10 103 if (lpservlet && lpmodule) {
universe@33 104 final LightPITModule moduleInfo = scclass.getAnnotation(LightPITModule.class);
universe@10 105 return Optional.of(moduleInfo);
universe@10 106 } else {
universe@10 107 return Optional.empty();
universe@10 108 }
universe@6 109 } catch (ClassNotFoundException ex) {
universe@8 110 LOG.error(
universe@9 111 "Servlet registration refers to class {} which cannot be found by the class loader (Reason: {})",
universe@9 112 reg.getClassName(),
universe@9 113 ex.getMessage()
universe@8 114 );
universe@10 115 return Optional.empty();
universe@34 116 }
universe@6 117 }
universe@34 118
universe@7 119 private void handleServletRegistration(String name, Registration reg) {
universe@10 120 final Optional<LightPITModule> moduleInfo = getModuleInfo(reg);
universe@20 121 if (moduleInfo.isPresent()) {
universe@34 122 registeredModules.put(reg.getClassName(), moduleInfo.get());
universe@8 123 LOG.info("Module detected: {}", name);
universe@6 124 } else {
universe@8 125 LOG.debug("Servlet {} is no module, skipping.", name);
universe@6 126 }
universe@6 127 }
universe@34 128
universe@6 129 /**
universe@6 130 * Scans for modules and reloads them all.
universe@6 131 */
universe@6 132 public void reloadAll() {
universe@21 133 registeredModules.clear();
universe@6 134 sc.getServletRegistrations().forEach(this::handleServletRegistration);
universe@34 135
universe@20 136 // TODO: implement dependency resolver
universe@34 137
universe@21 138 dirty.set(true);
universe@6 139 LOG.info("Modules loaded.");
universe@6 140 }
universe@30 141
universe@6 142 /**
universe@20 143 * Synchronizes module information with the database.
universe@30 144 * <p>
universe@27 145 * This must be called from the {@link AbstractLightPITServlet}.
universe@27 146 * Admittedly the call will perform the synchronization once after reload
universe@27 147 * and be a no-op, afterwards.
universe@30 148 * However, since the DatabaseFacade might be loaded after the module
universe@27 149 * manager, we must defer the synchronization to the first request
universe@27 150 * handled by the Servlet.
universe@30 151 *
universe@20 152 * @param db interface to the database
universe@20 153 */
universe@20 154 public void syncWithDatabase(DatabaseFacade db) {
universe@20 155 if (dirty.compareAndSet(true, false)) {
universe@20 156 if (db.getDataSource().isPresent()) {
universe@20 157 try (Connection conn = db.getDataSource().get().getConnection()) {
universe@34 158 db.getDataAccessObjects()
universe@34 159 .getModuleDao()
universe@34 160 .syncRegisteredModuleClasses(conn, registeredModules.entrySet());
universe@20 161 } catch (SQLException ex) {
universe@20 162 LOG.error("Unexpected SQL Exception", ex);
universe@20 163 }
universe@20 164 } else {
universe@27 165 LOG.error("No datasource present. Cannot sync module information with database.");
universe@20 166 }
universe@20 167 } else {
universe@22 168 LOG.trace("Module information clean - no synchronization required.");
universe@20 169 }
universe@20 170 }
universe@34 171
universe@20 172 /**
universe@6 173 * Unloads all found modules.
universe@6 174 */
universe@6 175 public void unloadAll() {
universe@21 176 registeredModules.clear();
universe@6 177 LOG.info("All modules unloaded.");
universe@6 178 }
universe@10 179
universe@10 180 /**
universe@10 181 * Returns the main menu.
universe@34 182 *
universe@27 183 * @param db the interface to the database
universe@10 184 * @return a list of menus belonging to the main menu
universe@10 185 */
universe@27 186 public List<Menu> getMainMenu(DatabaseFacade db) {
universe@27 187 // TODO: user specific menu
universe@34 188
universe@27 189 if (db.getDataSource().isPresent()) {
universe@27 190 try (Connection conn = db.getDataSource().get().getConnection()) {
universe@34 191 final List<Module> modules = db.getDataAccessObjects().getModuleDao().list(conn);
universe@31 192
universe@31 193 return modules
universe@31 194 .stream()
universe@31 195 .filter(Module::isVisible)
universe@31 196 .sorted(new Module.PriorityComparator())
universe@31 197 .map(mod -> new Menu(
universe@31 198 mod.getClassname(),
universe@31 199 new ResourceKey(
universe@31 200 registeredModules.get(mod.getClassname()).bundleBaseName(),
universe@31 201 registeredModules.get(mod.getClassname()).menuKey()),
universe@31 202 registeredModules.get(mod.getClassname()).modulePath()))
universe@31 203 .collect(Collectors.toList());
universe@27 204 } catch (SQLException ex) {
universe@27 205 LOG.error("Unexpected SQLException when loading the main menu", ex);
universe@27 206 return Collections.emptyList();
universe@27 207 }
universe@27 208 } else {
universe@27 209 return Collections.emptyList();
universe@27 210 }
universe@10 211 }
universe@34 212
universe@21 213 /**
universe@21 214 * Returns an unmodifiable map of all registered modules.
universe@34 215 * <p>
universe@21 216 * The key is the classname of the module.
universe@34 217 *
universe@21 218 * @return the map of registered modules
universe@21 219 */
universe@21 220 public Map<String, LightPITModule> getRegisteredModules() {
universe@21 221 return Collections.unmodifiableMap(registeredModules);
universe@21 222 }
universe@6 223 }

mercurial