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

Sun, 08 Apr 2018 14:40:57 +0200

author
Mike Becker <universe@uap-core.de>
date
Sun, 08 Apr 2018 14:40:57 +0200
changeset 24
8137ec335416
parent 22
5a91fb7067af
child 27
1f2a96efa69f
permissions
-rw-r--r--

updates copyright header

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

mercurial