universe@6: /* universe@6: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. universe@6: * universe@24: * Copyright 2018 Mike Becker. All rights reserved. universe@6: * universe@6: * Redistribution and use in source and binary forms, with or without universe@6: * modification, are permitted provided that the following conditions are met: universe@6: * universe@6: * 1. Redistributions of source code must retain the above copyright universe@6: * notice, this list of conditions and the following disclaimer. universe@6: * universe@6: * 2. Redistributions in binary form must reproduce the above copyright universe@6: * notice, this list of conditions and the following disclaimer in the universe@6: * documentation and/or other materials provided with the distribution. universe@6: * universe@6: * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" universe@6: * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE universe@6: * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE universe@6: * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE universe@6: * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR universe@6: * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF universe@6: * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS universe@6: * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN universe@6: * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) universe@6: * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE universe@6: * POSSIBILITY OF SUCH DAMAGE. universe@6: * universe@6: */ universe@6: package de.uapcore.lightpit; universe@6: universe@30: import de.uapcore.lightpit.dao.CoreDAOFactory; universe@30: import de.uapcore.lightpit.dao.ModuleDao; universe@27: import de.uapcore.lightpit.entities.Module; universe@30: import org.slf4j.Logger; universe@30: import org.slf4j.LoggerFactory; universe@30: universe@7: import javax.servlet.Registration; universe@6: import javax.servlet.ServletContext; universe@6: import javax.servlet.ServletContextEvent; universe@6: import javax.servlet.ServletContextListener; universe@6: import javax.servlet.annotation.WebListener; universe@30: import java.sql.Connection; universe@30: import java.sql.SQLException; universe@30: import java.util.*; universe@30: import java.util.concurrent.atomic.AtomicBoolean; universe@30: import java.util.stream.Collectors; universe@6: universe@6: /** universe@6: * Scans registered servlets for LightPIT modules. universe@6: */ universe@6: @WebListener universe@10: public final class ModuleManager implements ServletContextListener { universe@6: universe@8: private static final Logger LOG = LoggerFactory.getLogger(ModuleManager.class); universe@6: universe@6: /** universe@6: * The attribute name in the servlet context under which an instance of this class can be found. universe@6: */ universe@6: public static final String SC_ATTR_NAME = ModuleManager.class.getName(); universe@10: private ServletContext sc; universe@6: universe@20: /** universe@27: * Maps class names to module information. universe@27: */ universe@27: private final Map registeredModules = new HashMap<>(); universe@27: universe@27: /** universe@20: * This flag is true, when synchronization is needed. universe@20: */ universe@21: private final AtomicBoolean dirty = new AtomicBoolean(true); universe@20: universe@6: @Override universe@6: public void contextInitialized(ServletContextEvent sce) { universe@6: sc = sce.getServletContext(); universe@6: reloadAll(); universe@6: sc.setAttribute(SC_ATTR_NAME, this); universe@6: LOG.info("Module manager injected into ServletContext."); universe@6: } universe@6: universe@6: @Override universe@6: public void contextDestroyed(ServletContextEvent sce) { universe@6: unloadAll(); universe@6: } universe@6: universe@10: private Optional getModuleInfo(Registration reg) { universe@6: try { universe@7: final Class scclass = Class.forName(reg.getClassName()); universe@7: universe@9: final boolean lpservlet = AbstractLightPITServlet.class.isAssignableFrom(scclass); universe@7: final boolean lpmodule = scclass.isAnnotationPresent(LightPITModule.class); universe@7: universe@7: if (lpservlet && !lpmodule) { universe@8: LOG.warn( universe@9: "{} is a LightPIT Servlet but is missing the module annotation.", universe@8: reg.getClassName() universe@8: ); universe@7: } else if (!lpservlet && lpmodule) { universe@8: LOG.warn( universe@9: "{} is annotated as a LightPIT Module but does not extend {}.", universe@9: reg.getClassName(), universe@9: AbstractLightPITServlet.class.getSimpleName() universe@8: ); universe@7: } universe@7: universe@10: if (lpservlet && lpmodule) { universe@10: final Class clazz = scclass; universe@10: final LightPITModule moduleInfo = clazz.getAnnotation(LightPITModule.class); universe@10: return Optional.of(moduleInfo); universe@10: } else { universe@10: return Optional.empty(); universe@10: } universe@6: } catch (ClassNotFoundException ex) { universe@8: LOG.error( universe@9: "Servlet registration refers to class {} which cannot be found by the class loader (Reason: {})", universe@9: reg.getClassName(), universe@9: ex.getMessage() universe@8: ); universe@10: return Optional.empty(); universe@6: } universe@6: } universe@6: universe@7: private void handleServletRegistration(String name, Registration reg) { universe@10: final Optional moduleInfo = getModuleInfo(reg); universe@20: if (moduleInfo.isPresent()) { universe@20: registeredModules.put(reg.getClassName(), moduleInfo.get()); universe@8: LOG.info("Module detected: {}", name); universe@6: } else { universe@8: LOG.debug("Servlet {} is no module, skipping.", name); universe@6: } universe@6: } universe@6: universe@6: /** universe@6: * Scans for modules and reloads them all. universe@6: */ universe@6: public void reloadAll() { universe@21: registeredModules.clear(); universe@6: sc.getServletRegistrations().forEach(this::handleServletRegistration); universe@20: universe@20: // TODO: implement dependency resolver universe@20: universe@21: dirty.set(true); universe@6: LOG.info("Modules loaded."); universe@6: } universe@30: universe@6: /** universe@20: * Synchronizes module information with the database. universe@30: *

universe@27: * This must be called from the {@link AbstractLightPITServlet}. universe@27: * Admittedly the call will perform the synchronization once after reload universe@27: * and be a no-op, afterwards. universe@30: * However, since the DatabaseFacade might be loaded after the module universe@27: * manager, we must defer the synchronization to the first request universe@27: * handled by the Servlet. universe@30: * universe@20: * @param db interface to the database universe@20: */ universe@20: public void syncWithDatabase(DatabaseFacade db) { universe@20: if (dirty.compareAndSet(true, false)) { universe@20: if (db.getDataSource().isPresent()) { universe@20: try (Connection conn = db.getDataSource().get().getConnection()) { universe@21: final ModuleDao moduleDao = CoreDAOFactory.getModuleDao(db.getSQLDialect()); universe@27: moduleDao.syncRegisteredModuleClasses(conn, registeredModules.entrySet()); universe@20: } catch (SQLException ex) { universe@20: LOG.error("Unexpected SQL Exception", ex); universe@20: } universe@20: } else { universe@27: LOG.error("No datasource present. Cannot sync module information with database."); universe@20: } universe@20: } else { universe@22: LOG.trace("Module information clean - no synchronization required."); universe@20: } universe@20: } universe@20: universe@20: /** universe@6: * Unloads all found modules. universe@6: */ universe@6: public void unloadAll() { universe@21: registeredModules.clear(); universe@6: LOG.info("All modules unloaded."); universe@6: } universe@10: universe@10: /** universe@10: * Returns the main menu. universe@27: * universe@27: * @param db the interface to the database universe@10: * @return a list of menus belonging to the main menu universe@10: */ universe@27: public List

getMainMenu(DatabaseFacade db) { universe@27: // TODO: user specific menu universe@27: universe@27: if (db.getDataSource().isPresent()) { universe@27: try (Connection conn = db.getDataSource().get().getConnection()) { universe@27: final ModuleDao dao = CoreDAOFactory.getModuleDao(db.getSQLDialect()); universe@27: final List modules = dao.listAll(conn); universe@31: universe@31: return modules universe@31: .stream() universe@31: .filter(Module::isVisible) universe@31: .sorted(new Module.PriorityComparator()) universe@31: .map(mod -> new Menu( universe@31: mod.getClassname(), universe@31: new ResourceKey( universe@31: registeredModules.get(mod.getClassname()).bundleBaseName(), universe@31: registeredModules.get(mod.getClassname()).menuKey()), universe@31: registeredModules.get(mod.getClassname()).modulePath())) universe@31: .collect(Collectors.toList()); universe@27: } catch (SQLException ex) { universe@27: LOG.error("Unexpected SQLException when loading the main menu", ex); universe@27: return Collections.emptyList(); universe@27: } universe@27: } else { universe@27: return Collections.emptyList(); universe@27: } universe@10: } universe@21: universe@21: /** universe@21: * Returns an unmodifiable map of all registered modules. universe@21: * universe@21: * The key is the classname of the module. universe@21: * universe@21: * @return the map of registered modules universe@21: */ universe@21: public Map getRegisteredModules() { universe@21: return Collections.unmodifiableMap(registeredModules); universe@21: } universe@6: }