src/java/de/uapcore/lightpit/AbstractLightPITServlet.java

Sat, 30 Dec 2017 20:41:55 +0100

author
Mike Becker <universe@uap-core.de>
date
Sat, 30 Dec 2017 20:41:55 +0100
changeset 17
d1036b776eee
parent 15
bb594abac796
child 18
a94b172c3a93
permissions
-rw-r--r--

adds getter for the database facade to the abstract servlet

universe@7 1 /*
universe@7 2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
universe@7 3 *
universe@7 4 * Copyright 2017 Mike Becker. All rights reserved.
universe@7 5 *
universe@7 6 * Redistribution and use in source and binary forms, with or without
universe@7 7 * modification, are permitted provided that the following conditions are met:
universe@7 8 *
universe@7 9 * 1. Redistributions of source code must retain the above copyright
universe@7 10 * notice, this list of conditions and the following disclaimer.
universe@7 11 *
universe@7 12 * 2. Redistributions in binary form must reproduce the above copyright
universe@7 13 * notice, this list of conditions and the following disclaimer in the
universe@7 14 * documentation and/or other materials provided with the distribution.
universe@7 15 *
universe@7 16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
universe@7 17 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
universe@7 18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
universe@7 19 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
universe@7 20 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
universe@7 21 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
universe@7 22 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
universe@7 23 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
universe@7 24 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
universe@7 25 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
universe@7 26 * POSSIBILITY OF SUCH DAMAGE.
universe@7 27 *
universe@7 28 */
universe@7 29 package de.uapcore.lightpit;
universe@7 30
universe@7 31 import java.io.IOException;
universe@11 32 import java.lang.reflect.Method;
universe@11 33 import java.lang.reflect.Modifier;
universe@13 34 import java.util.Arrays;
universe@11 35 import java.util.HashMap;
universe@13 36 import java.util.List;
universe@13 37 import java.util.Locale;
universe@11 38 import java.util.Map;
universe@11 39 import java.util.Optional;
universe@7 40 import javax.servlet.ServletException;
universe@7 41 import javax.servlet.http.HttpServlet;
universe@7 42 import javax.servlet.http.HttpServletRequest;
universe@7 43 import javax.servlet.http.HttpServletResponse;
universe@13 44 import javax.servlet.http.HttpSession;
universe@10 45 import org.slf4j.Logger;
universe@10 46 import org.slf4j.LoggerFactory;
universe@7 47
universe@7 48 /**
universe@7 49 * A special implementation of a HTTPServlet which is focused on implementing
universe@7 50 * the necessary functionality for {@link LightPITModule}s.
universe@7 51 */
universe@9 52 public abstract class AbstractLightPITServlet extends HttpServlet {
universe@7 53
universe@10 54 private static final Logger LOG = LoggerFactory.getLogger(AbstractLightPITServlet.class);
universe@11 55
universe@13 56 private static final String HTML_FULL_DISPATCHER = Functions.jspPath("html_full");
universe@13 57
universe@11 58 /**
universe@11 59 * Store a reference to the annotation for quicker access.
universe@11 60 */
universe@11 61 private Optional<LightPITModule> moduleInfo = Optional.empty();
universe@10 62
universe@11 63 /**
universe@11 64 * The EL proxy is necessary, because the EL resolver cannot handle annotation properties.
universe@11 65 */
universe@11 66 private Optional<LightPITModule.ELProxy> moduleInfoELProxy = Optional.empty();
universe@10 67
universe@12 68
universe@12 69 @FunctionalInterface
universe@12 70 private static interface HandlerMethod {
universe@12 71 ResponseType apply(HttpServletRequest t, HttpServletResponse u) throws IOException, ServletException;
universe@12 72 }
universe@12 73
universe@10 74 /**
universe@11 75 * Invocation mapping gathered from the {@link RequestMapping} annotations.
universe@11 76 */
universe@12 77 private final Map<HttpMethod, Map<String, HandlerMethod>> mappings = new HashMap<>();
universe@11 78
universe@11 79 /**
universe@10 80 * Gives implementing modules access to the {@link ModuleManager}.
universe@10 81 * @return the module manager
universe@10 82 */
universe@10 83 protected final ModuleManager getModuleManager() {
universe@10 84 return (ModuleManager) getServletContext().getAttribute(ModuleManager.SC_ATTR_NAME);
universe@10 85 }
universe@10 86
universe@17 87 /**
universe@17 88 * Gives implementing modules access to the {@link DatabaseFacade}.
universe@17 89 * @return the database facade
universe@17 90 */
universe@17 91 protected final DatabaseFacade getDatabaseFacade() {
universe@17 92 return (DatabaseFacade) getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME);
universe@17 93 }
universe@17 94
universe@12 95 private ResponseType invokeMapping(Method method, HttpServletRequest req, HttpServletResponse resp)
universe@12 96 throws IOException, ServletException {
universe@11 97 try {
universe@14 98 LOG.trace("invoke {}#{}", method.getDeclaringClass().getName(), method.getName());
universe@12 99 return (ResponseType) method.invoke(this, req, resp);
universe@12 100 } catch (ReflectiveOperationException | ClassCastException ex) {
universe@11 101 LOG.error(String.format("invocation of method %s failed", method.getName()), ex);
universe@12 102 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
universe@12 103 return ResponseType.NONE;
universe@11 104 }
universe@11 105 }
universe@11 106
universe@11 107 @Override
universe@11 108 public void init() throws ServletException {
universe@11 109 moduleInfo = Optional.ofNullable(this.getClass().getAnnotation(LightPITModule.class));
universe@11 110 moduleInfoELProxy = moduleInfo.map(LightPITModule.ELProxy::convert);
universe@11 111
universe@11 112 if (moduleInfo.isPresent()) {
universe@12 113 scanForRequestMappings();
universe@12 114 }
universe@12 115
universe@12 116 LOG.trace("{} initialized", getServletName());
universe@12 117 }
universe@12 118
universe@12 119 private void scanForRequestMappings() {
universe@12 120 try {
universe@11 121 Method[] methods = getClass().getDeclaredMethods();
universe@11 122 for (Method method : methods) {
universe@11 123 Optional<RequestMapping> mapping = Optional.ofNullable(method.getAnnotation(RequestMapping.class));
universe@11 124 if (mapping.isPresent()) {
universe@11 125 if (!Modifier.isPublic(method.getModifiers())) {
universe@11 126 LOG.warn("{} is annotated with {} but is not public",
universe@11 127 method.getName(), RequestMapping.class.getSimpleName()
universe@11 128 );
universe@11 129 continue;
universe@11 130 }
universe@11 131 if (Modifier.isAbstract(method.getModifiers())) {
universe@11 132 LOG.warn("{} is annotated with {} but is abstract",
universe@11 133 method.getName(), RequestMapping.class.getSimpleName()
universe@11 134 );
universe@11 135 continue;
universe@11 136 }
universe@12 137 if (!ResponseType.class.isAssignableFrom(method.getReturnType())) {
universe@12 138 LOG.warn("{} is annotated with {} but has the wrong return type - 'ResponseType' required",
universe@12 139 method.getName(), RequestMapping.class.getSimpleName()
universe@12 140 );
universe@12 141 continue;
universe@12 142 }
universe@12 143
universe@11 144 Class<?>[] params = method.getParameterTypes();
universe@11 145 if (params.length == 2
universe@11 146 && HttpServletRequest.class.isAssignableFrom(params[0])
universe@11 147 && HttpServletResponse.class.isAssignableFrom(params[1])) {
universe@12 148
universe@11 149 if (mappings.computeIfAbsent(mapping.get().method(), k -> new HashMap<>()).
universe@11 150 putIfAbsent(mapping.get().requestPath(),
universe@11 151 (req, resp) -> invokeMapping(method, req, resp)) != null) {
universe@11 152 LOG.warn("{} {} has multiple mappings",
universe@11 153 mapping.get().method(),
universe@11 154 mapping.get().requestPath()
universe@11 155 );
universe@11 156 }
universe@12 157
universe@11 158 LOG.info("{} {} maps to {}",
universe@11 159 mapping.get().method(),
universe@11 160 mapping.get().requestPath(),
universe@11 161 method.getName()
universe@11 162 );
universe@11 163 } else {
universe@12 164 LOG.warn("{} is annotated with {} but has the wrong parameters - (HttpServletRequest,HttpServletResponse) required",
universe@11 165 method.getName(), RequestMapping.class.getSimpleName()
universe@11 166 );
universe@11 167 }
universe@11 168 }
universe@11 169 }
universe@12 170 } catch (SecurityException ex) {
universe@12 171 LOG.error("Scan for request mappings on declared methods failed.", ex);
universe@11 172 }
universe@11 173 }
universe@11 174
universe@11 175 @Override
universe@11 176 public void destroy() {
universe@11 177 mappings.clear();
universe@11 178 LOG.trace("{} destroyed", getServletName());
universe@11 179 }
universe@11 180
universe@13 181 /**
universe@13 182 * Sets the name of the dynamic fragment.
universe@13 183 *
universe@13 184 * It is sufficient to specify the name without any extension. The extension
universe@13 185 * is added automatically if not specified.
universe@13 186 *
universe@13 187 * The fragment must be located in the dynamic fragments folder.
universe@13 188 *
universe@13 189 * @param req the servlet request object
universe@13 190 * @param fragmentName the name of the fragment
universe@13 191 * @see Constants#DYN_FRAGMENT_PATH_PREFIX
universe@13 192 */
universe@13 193 public void setDynamicFragment(HttpServletRequest req, String fragmentName) {
universe@13 194 req.setAttribute(Constants.REQ_ATTR_FRAGMENT, Functions.dynFragmentPath(fragmentName));
universe@13 195 }
universe@11 196
universe@11 197 /**
universe@13 198 * Specifies the name of an additional stylesheet used by the module.
universe@13 199 *
universe@13 200 * Setting an additional stylesheet is optional, but quite common for HTML
universe@13 201 * output.
universe@13 202 *
universe@13 203 * It is sufficient to specify the name without any extension. The extension
universe@13 204 * is added automatically if not specified.
universe@11 205 *
universe@11 206 * @param req the servlet request object
universe@13 207 * @param stylesheet the name of the stylesheet
universe@11 208 */
universe@13 209 public void setStylesheet(HttpServletRequest req, String stylesheet) {
universe@13 210 req.setAttribute(Constants.REQ_ATTR_STYLESHEET, Functions.enforceExt(stylesheet, ".css"));
universe@10 211 }
universe@10 212
universe@10 213 private void forwardToFullView(HttpServletRequest req, HttpServletResponse resp)
universe@10 214 throws IOException, ServletException {
universe@10 215
universe@11 216 req.setAttribute(Constants.REQ_ATTR_MENU, getModuleManager().getMainMenu());
universe@13 217 req.getRequestDispatcher(HTML_FULL_DISPATCHER).forward(req, resp);
universe@10 218 }
universe@10 219
universe@12 220 private Optional<HandlerMethod> findMapping(HttpMethod method, HttpServletRequest req) {
universe@11 221 return Optional.ofNullable(mappings.get(method)).map(
universe@11 222 (rm) -> rm.get(Optional.ofNullable(req.getPathInfo()).orElse(""))
universe@11 223 );
universe@11 224 }
universe@11 225
universe@12 226 private void forwardAsSepcified(ResponseType type, HttpServletRequest req, HttpServletResponse resp)
universe@12 227 throws ServletException, IOException {
universe@12 228 switch (type) {
universe@12 229 case NONE: return;
universe@12 230 case HTML_FULL:
universe@12 231 forwardToFullView(req, resp);
universe@12 232 return;
universe@12 233 // TODO: implement remaining response types
universe@12 234 default:
universe@12 235 // this code should be unreachable
universe@12 236 LOG.error("ResponseType switch is not exhaustive - this is a bug!");
universe@12 237 throw new UnsupportedOperationException();
universe@12 238 }
universe@12 239 }
universe@12 240
universe@12 241 private void doProcess(HttpMethod method, HttpServletRequest req, HttpServletResponse resp)
universe@12 242 throws ServletException, IOException {
universe@13 243
universe@13 244 HttpSession session = req.getSession();
universe@13 245
universe@13 246 // choose the requested language as session language (if available) or fall back to english, otherwise
universe@13 247 if (session.getAttribute(Constants.SESSION_ATTR_LANGUAGE) == null) {
universe@13 248 Optional<List<String>> availableLanguages = Functions.availableLanguages(getServletContext()).map(Arrays::asList);
universe@13 249 Optional<Locale> reqLocale = Optional.of(req.getLocale());
universe@13 250 Locale sessionLocale = reqLocale.filter((rl) -> availableLanguages.map((al) -> al.contains(rl.getLanguage())).orElse(false)).orElse(Locale.ENGLISH);
universe@13 251 session.setAttribute(Constants.SESSION_ATTR_LANGUAGE, sessionLocale);
universe@13 252 LOG.debug("Settng language for new session {}: {}", session.getId(), sessionLocale.getDisplayLanguage());
universe@14 253 } else {
universe@15 254 Locale sessionLocale = (Locale) session.getAttribute(Constants.SESSION_ATTR_LANGUAGE);
universe@15 255 resp.setLocale(sessionLocale);
universe@15 256 LOG.trace("Continuing session {} with language {}", session.getId(), sessionLocale);
universe@13 257 }
universe@13 258
universe@13 259 req.setAttribute(Constants.REQ_ATTR_PATH, Functions.fullPath(req));
universe@13 260 req.setAttribute(Constants.REQ_ATTR_MODULE_CLASSNAME, this.getClass().getName());
universe@13 261 moduleInfoELProxy.ifPresent((proxy) -> req.setAttribute(Constants.REQ_ATTR_MODULE_INFO, proxy));
universe@13 262
universe@12 263 Optional<HandlerMethod> mapping = findMapping(method, req);
universe@12 264 if (mapping.isPresent()) {
universe@12 265 forwardAsSepcified(mapping.get().apply(req, resp), req, resp);
universe@12 266 } else {
universe@12 267 resp.sendError(HttpServletResponse.SC_NOT_FOUND);
universe@12 268 }
universe@12 269 }
universe@12 270
universe@7 271 @Override
universe@7 272 protected final void doGet(HttpServletRequest req, HttpServletResponse resp)
universe@7 273 throws ServletException, IOException {
universe@12 274 doProcess(HttpMethod.GET, req, resp);
universe@7 275 }
universe@7 276
universe@7 277 @Override
universe@7 278 protected final void doPost(HttpServletRequest req, HttpServletResponse resp)
universe@7 279 throws ServletException, IOException {
universe@12 280 doProcess(HttpMethod.POST, req, resp);
universe@7 281 }
universe@7 282 }

mercurial