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

Sat, 09 May 2020 14:26:31 +0200

author
Mike Becker <universe@uap-core.de>
date
Sat, 09 May 2020 14:26:31 +0200
changeset 29
27a0fdd7bca7
parent 27
src/java/de/uapcore/lightpit/ModuleManager.java@1f2a96efa69f
child 30
fb30f7b78f9b
permissions
-rw-r--r--

converts to maven project

universe@6 1 /*
universe@6 2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
universe@6 3 *
universe@24 4 * Copyright 2018 Mike Becker. All rights reserved.
universe@6 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@6 27 *
universe@6 28 */
universe@6 29 package de.uapcore.lightpit;
universe@6 30
universe@21 31 import de.uapcore.lightpit.entities.CoreDAOFactory;
universe@27 32 import de.uapcore.lightpit.entities.Module;
universe@21 33 import de.uapcore.lightpit.entities.ModuleDao;
universe@20 34 import java.sql.Connection;
universe@20 35 import java.sql.SQLException;
universe@10 36 import java.util.Collections;
universe@20 37 import java.util.HashMap;
universe@10 38 import java.util.List;
universe@20 39 import java.util.Map;
universe@10 40 import java.util.Optional;
universe@20 41 import java.util.concurrent.atomic.AtomicBoolean;
universe@21 42 import java.util.stream.Collectors;
universe@7 43 import javax.servlet.Registration;
universe@6 44 import javax.servlet.ServletContext;
universe@6 45 import javax.servlet.ServletContextEvent;
universe@6 46 import javax.servlet.ServletContextListener;
universe@6 47 import javax.servlet.annotation.WebListener;
universe@8 48 import org.slf4j.Logger;
universe@8 49 import org.slf4j.LoggerFactory;
universe@6 50
universe@6 51 /**
universe@6 52 * Scans registered servlets for LightPIT modules.
universe@6 53 */
universe@6 54 @WebListener
universe@10 55 public final class ModuleManager implements ServletContextListener {
universe@6 56
universe@8 57 private static final Logger LOG = LoggerFactory.getLogger(ModuleManager.class);
universe@6 58
universe@6 59 /**
universe@6 60 * The attribute name in the servlet context under which an instance of this class can be found.
universe@6 61 */
universe@6 62 public static final String SC_ATTR_NAME = ModuleManager.class.getName();
universe@10 63 private ServletContext sc;
universe@6 64
universe@20 65 /**
universe@27 66 * Maps class names to module information.
universe@27 67 */
universe@27 68 private final Map<String, LightPITModule> registeredModules = new HashMap<>();
universe@27 69
universe@27 70 /**
universe@20 71 * This flag is true, when synchronization is needed.
universe@20 72 */
universe@21 73 private final AtomicBoolean dirty = new AtomicBoolean(true);
universe@20 74
universe@6 75 @Override
universe@6 76 public void contextInitialized(ServletContextEvent sce) {
universe@6 77 sc = sce.getServletContext();
universe@6 78 reloadAll();
universe@6 79 sc.setAttribute(SC_ATTR_NAME, this);
universe@6 80 LOG.info("Module manager injected into ServletContext.");
universe@6 81 }
universe@6 82
universe@6 83 @Override
universe@6 84 public void contextDestroyed(ServletContextEvent sce) {
universe@6 85 unloadAll();
universe@6 86 }
universe@6 87
universe@10 88 private Optional<LightPITModule> getModuleInfo(Registration reg) {
universe@6 89 try {
universe@7 90 final Class scclass = Class.forName(reg.getClassName());
universe@7 91
universe@9 92 final boolean lpservlet = AbstractLightPITServlet.class.isAssignableFrom(scclass);
universe@7 93 final boolean lpmodule = scclass.isAnnotationPresent(LightPITModule.class);
universe@7 94
universe@7 95 if (lpservlet && !lpmodule) {
universe@8 96 LOG.warn(
universe@9 97 "{} is a LightPIT Servlet but is missing the module annotation.",
universe@8 98 reg.getClassName()
universe@8 99 );
universe@7 100 } else if (!lpservlet && lpmodule) {
universe@8 101 LOG.warn(
universe@9 102 "{} is annotated as a LightPIT Module but does not extend {}.",
universe@9 103 reg.getClassName(),
universe@9 104 AbstractLightPITServlet.class.getSimpleName()
universe@8 105 );
universe@7 106 }
universe@7 107
universe@10 108 if (lpservlet && lpmodule) {
universe@10 109 final Class<? extends AbstractLightPITServlet> clazz = scclass;
universe@10 110 final LightPITModule moduleInfo = clazz.getAnnotation(LightPITModule.class);
universe@10 111 return Optional.of(moduleInfo);
universe@10 112 } else {
universe@10 113 return Optional.empty();
universe@10 114 }
universe@6 115 } catch (ClassNotFoundException ex) {
universe@8 116 LOG.error(
universe@9 117 "Servlet registration refers to class {} which cannot be found by the class loader (Reason: {})",
universe@9 118 reg.getClassName(),
universe@9 119 ex.getMessage()
universe@8 120 );
universe@10 121 return Optional.empty();
universe@6 122 }
universe@6 123 }
universe@6 124
universe@7 125 private void handleServletRegistration(String name, Registration reg) {
universe@10 126 final Optional<LightPITModule> moduleInfo = getModuleInfo(reg);
universe@20 127 if (moduleInfo.isPresent()) {
universe@20 128 registeredModules.put(reg.getClassName(), moduleInfo.get());
universe@8 129 LOG.info("Module detected: {}", name);
universe@6 130 } else {
universe@8 131 LOG.debug("Servlet {} is no module, skipping.", name);
universe@6 132 }
universe@6 133 }
universe@6 134
universe@6 135 /**
universe@6 136 * Scans for modules and reloads them all.
universe@6 137 */
universe@6 138 public void reloadAll() {
universe@21 139 registeredModules.clear();
universe@6 140 sc.getServletRegistrations().forEach(this::handleServletRegistration);
universe@20 141
universe@20 142 // TODO: implement dependency resolver
universe@20 143
universe@21 144 dirty.set(true);
universe@6 145 LOG.info("Modules loaded.");
universe@6 146 }
universe@6 147
universe@6 148 /**
universe@20 149 * Synchronizes module information with the database.
universe@20 150 *
universe@27 151 * This must be called from the {@link AbstractLightPITServlet}.
universe@27 152 * Admittedly the call will perform the synchronization once after reload
universe@27 153 * and be a no-op, afterwards.
universe@27 154 * However, we since the DatabaseFacade might be loaded after the module
universe@27 155 * manager, we must defer the synchronization to the first request
universe@27 156 * handled by the Servlet.
universe@27 157 *
universe@20 158 * @param db interface to the database
universe@20 159 */
universe@20 160 public void syncWithDatabase(DatabaseFacade db) {
universe@20 161 if (dirty.compareAndSet(true, false)) {
universe@20 162 if (db.getDataSource().isPresent()) {
universe@20 163 try (Connection conn = db.getDataSource().get().getConnection()) {
universe@21 164 final ModuleDao moduleDao = CoreDAOFactory.getModuleDao(db.getSQLDialect());
universe@27 165 moduleDao.syncRegisteredModuleClasses(conn, registeredModules.entrySet());
universe@20 166 } catch (SQLException ex) {
universe@20 167 LOG.error("Unexpected SQL Exception", ex);
universe@20 168 }
universe@20 169 } else {
universe@27 170 LOG.error("No datasource present. Cannot sync module information with database.");
universe@20 171 }
universe@20 172 } else {
universe@22 173 LOG.trace("Module information clean - no synchronization required.");
universe@20 174 }
universe@20 175 }
universe@20 176
universe@20 177 /**
universe@6 178 * Unloads all found modules.
universe@6 179 */
universe@6 180 public void unloadAll() {
universe@21 181 registeredModules.clear();
universe@6 182 LOG.info("All modules unloaded.");
universe@6 183 }
universe@10 184
universe@10 185 /**
universe@10 186 * Returns the main menu.
universe@27 187 *
universe@27 188 * @param db the interface to the database
universe@10 189 * @return a list of menus belonging to the main menu
universe@10 190 */
universe@27 191 public List<Menu> getMainMenu(DatabaseFacade db) {
universe@27 192 // TODO: user specific menu
universe@27 193
universe@27 194 if (db.getDataSource().isPresent()) {
universe@27 195 try (Connection conn = db.getDataSource().get().getConnection()) {
universe@27 196 final ModuleDao dao = CoreDAOFactory.getModuleDao(db.getSQLDialect());
universe@27 197 final List<Module> modules = dao.listAll(conn);
universe@27 198
universe@27 199 final List<Menu> menu = modules
universe@27 200 .stream()
universe@27 201 .filter((mod) -> mod.isVisible())
universe@27 202 .collect(Collectors.mapping(
universe@27 203 (mod) -> new Menu(
universe@27 204 mod.getClassname(),
universe@27 205 new ResourceKey(
universe@27 206 registeredModules.get(mod.getClassname()).bundleBaseName(),
universe@27 207 registeredModules.get(mod.getClassname()).menuKey()),
universe@27 208 registeredModules.get(mod.getClassname()).modulePath()),
universe@27 209 Collectors.toList())
universe@27 210 );
universe@27 211 return menu;
universe@27 212 } catch (SQLException ex) {
universe@27 213 LOG.error("Unexpected SQLException when loading the main menu", ex);
universe@27 214 return Collections.emptyList();
universe@27 215 }
universe@27 216 } else {
universe@27 217 return Collections.emptyList();
universe@27 218 }
universe@10 219 }
universe@21 220
universe@21 221 /**
universe@21 222 * Returns an unmodifiable map of all registered modules.
universe@21 223 *
universe@21 224 * The key is the classname of the module.
universe@21 225 *
universe@21 226 * @return the map of registered modules
universe@21 227 */
universe@21 228 public Map<String, LightPITModule> getRegisteredModules() {
universe@21 229 return Collections.unmodifiableMap(registeredModules);
universe@21 230 }
universe@6 231 }

mercurial