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