universe@7: /* universe@7: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. universe@7: * universe@24: * Copyright 2018 Mike Becker. All rights reserved. universe@7: * universe@7: * Redistribution and use in source and binary forms, with or without universe@7: * modification, are permitted provided that the following conditions are met: universe@7: * universe@7: * 1. Redistributions of source code must retain the above copyright universe@7: * notice, this list of conditions and the following disclaimer. universe@7: * universe@7: * 2. Redistributions in binary form must reproduce the above copyright universe@7: * notice, this list of conditions and the following disclaimer in the universe@7: * documentation and/or other materials provided with the distribution. universe@7: * universe@7: * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" universe@7: * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE universe@7: * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE universe@7: * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE universe@7: * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR universe@7: * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF universe@7: * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS universe@7: * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN universe@7: * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) universe@7: * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE universe@7: * POSSIBILITY OF SUCH DAMAGE. universe@7: * universe@7: */ universe@7: package de.uapcore.lightpit; universe@7: universe@7: import java.io.IOException; universe@11: import java.lang.reflect.Method; universe@11: import java.lang.reflect.Modifier; universe@13: import java.util.Arrays; universe@11: import java.util.HashMap; universe@13: import java.util.List; universe@13: import java.util.Locale; universe@11: import java.util.Map; universe@11: import java.util.Optional; universe@7: import javax.servlet.ServletException; universe@7: import javax.servlet.http.HttpServlet; universe@7: import javax.servlet.http.HttpServletRequest; universe@7: import javax.servlet.http.HttpServletResponse; universe@13: import javax.servlet.http.HttpSession; universe@10: import org.slf4j.Logger; universe@10: import org.slf4j.LoggerFactory; universe@7: universe@7: /** universe@7: * A special implementation of a HTTPServlet which is focused on implementing universe@7: * the necessary functionality for {@link LightPITModule}s. universe@7: */ universe@9: public abstract class AbstractLightPITServlet extends HttpServlet { universe@7: universe@10: private static final Logger LOG = LoggerFactory.getLogger(AbstractLightPITServlet.class); universe@11: universe@13: private static final String HTML_FULL_DISPATCHER = Functions.jspPath("html_full"); universe@13: universe@11: /** universe@11: * Store a reference to the annotation for quicker access. universe@11: */ universe@11: private Optional moduleInfo = Optional.empty(); universe@10: universe@11: /** universe@11: * The EL proxy is necessary, because the EL resolver cannot handle annotation properties. universe@11: */ universe@11: private Optional moduleInfoELProxy = Optional.empty(); universe@10: universe@12: universe@12: @FunctionalInterface universe@12: private static interface HandlerMethod { universe@12: ResponseType apply(HttpServletRequest t, HttpServletResponse u) throws IOException, ServletException; universe@12: } universe@12: universe@10: /** universe@11: * Invocation mapping gathered from the {@link RequestMapping} annotations. universe@18: * universe@18: * Paths in this map must always start with a leading slash, although universe@18: * the specification in the annotation must not start with a leading slash. universe@18: * universe@18: * The reason for this is the different handling of empty paths in universe@18: * {@link HttpServletRequest#getPathInfo()}. universe@11: */ universe@12: private final Map> mappings = new HashMap<>(); universe@11: universe@11: /** universe@10: * Gives implementing modules access to the {@link ModuleManager}. universe@10: * @return the module manager universe@10: */ universe@10: protected final ModuleManager getModuleManager() { universe@10: return (ModuleManager) getServletContext().getAttribute(ModuleManager.SC_ATTR_NAME); universe@10: } universe@10: universe@17: /** universe@17: * Gives implementing modules access to the {@link DatabaseFacade}. universe@17: * @return the database facade universe@17: */ universe@17: protected final DatabaseFacade getDatabaseFacade() { universe@17: return (DatabaseFacade) getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME); universe@17: } universe@17: universe@12: private ResponseType invokeMapping(Method method, HttpServletRequest req, HttpServletResponse resp) universe@12: throws IOException, ServletException { universe@11: try { universe@14: LOG.trace("invoke {}#{}", method.getDeclaringClass().getName(), method.getName()); universe@12: return (ResponseType) method.invoke(this, req, resp); universe@12: } catch (ReflectiveOperationException | ClassCastException ex) { universe@11: LOG.error(String.format("invocation of method %s failed", method.getName()), ex); universe@12: resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); universe@12: return ResponseType.NONE; universe@11: } universe@11: } universe@11: universe@11: @Override universe@11: public void init() throws ServletException { universe@11: moduleInfo = Optional.ofNullable(this.getClass().getAnnotation(LightPITModule.class)); universe@11: moduleInfoELProxy = moduleInfo.map(LightPITModule.ELProxy::convert); universe@11: universe@11: if (moduleInfo.isPresent()) { universe@12: scanForRequestMappings(); universe@12: } universe@12: universe@12: LOG.trace("{} initialized", getServletName()); universe@12: } universe@12: universe@12: private void scanForRequestMappings() { universe@12: try { universe@11: Method[] methods = getClass().getDeclaredMethods(); universe@11: for (Method method : methods) { universe@11: Optional mapping = Optional.ofNullable(method.getAnnotation(RequestMapping.class)); universe@11: if (mapping.isPresent()) { universe@11: if (!Modifier.isPublic(method.getModifiers())) { universe@11: LOG.warn("{} is annotated with {} but is not public", universe@11: method.getName(), RequestMapping.class.getSimpleName() universe@11: ); universe@11: continue; universe@11: } universe@11: if (Modifier.isAbstract(method.getModifiers())) { universe@11: LOG.warn("{} is annotated with {} but is abstract", universe@11: method.getName(), RequestMapping.class.getSimpleName() universe@11: ); universe@11: continue; universe@11: } universe@12: if (!ResponseType.class.isAssignableFrom(method.getReturnType())) { universe@12: LOG.warn("{} is annotated with {} but has the wrong return type - 'ResponseType' required", universe@12: method.getName(), RequestMapping.class.getSimpleName() universe@12: ); universe@12: continue; universe@12: } universe@12: universe@11: Class[] params = method.getParameterTypes(); universe@11: if (params.length == 2 universe@11: && HttpServletRequest.class.isAssignableFrom(params[0]) universe@11: && HttpServletResponse.class.isAssignableFrom(params[1])) { universe@18: universe@18: final String requestPath = "/"+mapping.get().requestPath(); universe@12: universe@11: if (mappings.computeIfAbsent(mapping.get().method(), k -> new HashMap<>()). universe@18: putIfAbsent(requestPath, universe@11: (req, resp) -> invokeMapping(method, req, resp)) != null) { universe@11: LOG.warn("{} {} has multiple mappings", universe@11: mapping.get().method(), universe@11: mapping.get().requestPath() universe@11: ); universe@11: } universe@12: universe@22: LOG.debug("{} {} maps to {}::{}", universe@11: mapping.get().method(), universe@18: requestPath, universe@22: getClass().getSimpleName(), universe@11: method.getName() universe@11: ); universe@11: } else { universe@12: LOG.warn("{} is annotated with {} but has the wrong parameters - (HttpServletRequest,HttpServletResponse) required", universe@11: method.getName(), RequestMapping.class.getSimpleName() universe@11: ); universe@11: } universe@11: } universe@11: } universe@12: } catch (SecurityException ex) { universe@12: LOG.error("Scan for request mappings on declared methods failed.", ex); universe@11: } universe@11: } universe@11: universe@11: @Override universe@11: public void destroy() { universe@11: mappings.clear(); universe@11: LOG.trace("{} destroyed", getServletName()); universe@11: } universe@11: universe@13: /** universe@13: * Sets the name of the dynamic fragment. universe@13: * universe@13: * It is sufficient to specify the name without any extension. The extension universe@13: * is added automatically if not specified. universe@13: * universe@13: * The fragment must be located in the dynamic fragments folder. universe@13: * universe@13: * @param req the servlet request object universe@13: * @param fragmentName the name of the fragment universe@13: * @see Constants#DYN_FRAGMENT_PATH_PREFIX universe@13: */ universe@13: public void setDynamicFragment(HttpServletRequest req, String fragmentName) { universe@13: req.setAttribute(Constants.REQ_ATTR_FRAGMENT, Functions.dynFragmentPath(fragmentName)); universe@13: } universe@11: universe@11: /** universe@13: * Specifies the name of an additional stylesheet used by the module. universe@13: * universe@13: * Setting an additional stylesheet is optional, but quite common for HTML universe@13: * output. universe@13: * universe@13: * It is sufficient to specify the name without any extension. The extension universe@13: * is added automatically if not specified. universe@11: * universe@11: * @param req the servlet request object universe@13: * @param stylesheet the name of the stylesheet universe@11: */ universe@13: public void setStylesheet(HttpServletRequest req, String stylesheet) { universe@13: req.setAttribute(Constants.REQ_ATTR_STYLESHEET, Functions.enforceExt(stylesheet, ".css")); universe@10: } universe@10: universe@10: private void forwardToFullView(HttpServletRequest req, HttpServletResponse resp) universe@10: throws IOException, ServletException { universe@10: universe@27: req.setAttribute(Constants.REQ_ATTR_MENU, getModuleManager().getMainMenu(getDatabaseFacade())); universe@13: req.getRequestDispatcher(HTML_FULL_DISPATCHER).forward(req, resp); universe@10: } universe@10: universe@12: private Optional findMapping(HttpMethod method, HttpServletRequest req) { universe@11: return Optional.ofNullable(mappings.get(method)).map( universe@18: (rm) -> rm.get(Optional.ofNullable(req.getPathInfo()).orElse("/")) universe@11: ); universe@11: } universe@11: universe@12: private void forwardAsSepcified(ResponseType type, HttpServletRequest req, HttpServletResponse resp) universe@12: throws ServletException, IOException { universe@12: switch (type) { universe@12: case NONE: return; universe@12: case HTML_FULL: universe@12: forwardToFullView(req, resp); universe@12: return; universe@12: // TODO: implement remaining response types universe@12: default: universe@12: // this code should be unreachable universe@12: LOG.error("ResponseType switch is not exhaustive - this is a bug!"); universe@12: throw new UnsupportedOperationException(); universe@12: } universe@12: } universe@12: universe@12: private void doProcess(HttpMethod method, HttpServletRequest req, HttpServletResponse resp) universe@12: throws ServletException, IOException { universe@27: universe@20: // Synchronize module information with database universe@20: getModuleManager().syncWithDatabase(getDatabaseFacade()); universe@13: universe@13: // choose the requested language as session language (if available) or fall back to english, otherwise universe@20: HttpSession session = req.getSession(); universe@13: if (session.getAttribute(Constants.SESSION_ATTR_LANGUAGE) == null) { universe@13: Optional> availableLanguages = Functions.availableLanguages(getServletContext()).map(Arrays::asList); universe@13: Optional reqLocale = Optional.of(req.getLocale()); universe@13: Locale sessionLocale = reqLocale.filter((rl) -> availableLanguages.map((al) -> al.contains(rl.getLanguage())).orElse(false)).orElse(Locale.ENGLISH); universe@13: session.setAttribute(Constants.SESSION_ATTR_LANGUAGE, sessionLocale); universe@13: LOG.debug("Settng language for new session {}: {}", session.getId(), sessionLocale.getDisplayLanguage()); universe@14: } else { universe@15: Locale sessionLocale = (Locale) session.getAttribute(Constants.SESSION_ATTR_LANGUAGE); universe@15: resp.setLocale(sessionLocale); universe@15: LOG.trace("Continuing session {} with language {}", session.getId(), sessionLocale); universe@13: } universe@13: universe@21: // set some internal request attributes universe@13: req.setAttribute(Constants.REQ_ATTR_PATH, Functions.fullPath(req)); universe@13: req.setAttribute(Constants.REQ_ATTR_MODULE_CLASSNAME, this.getClass().getName()); universe@13: moduleInfoELProxy.ifPresent((proxy) -> req.setAttribute(Constants.REQ_ATTR_MODULE_INFO, proxy)); universe@13: universe@21: universe@21: // call the handler, if available, or send an HTTP 404 error universe@12: Optional mapping = findMapping(method, req); universe@12: if (mapping.isPresent()) { universe@12: forwardAsSepcified(mapping.get().apply(req, resp), req, resp); universe@12: } else { universe@12: resp.sendError(HttpServletResponse.SC_NOT_FOUND); universe@12: } universe@12: } universe@12: universe@7: @Override universe@7: protected final void doGet(HttpServletRequest req, HttpServletResponse resp) universe@7: throws ServletException, IOException { universe@12: doProcess(HttpMethod.GET, req, resp); universe@7: } universe@7: universe@7: @Override universe@7: protected final void doPost(HttpServletRequest req, HttpServletResponse resp) universe@7: throws ServletException, IOException { universe@12: doProcess(HttpMethod.POST, req, resp); universe@7: } universe@7: }