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

Tue, 26 Dec 2017 17:36:47 +0100

author
Mike Becker <universe@uap-core.de>
date
Tue, 26 Dec 2017 17:36:47 +0100
changeset 13
f4608ad6c947
parent 12
005d27918b57
child 14
2b270c714678
permissions
-rw-r--r--

adds dynamic fragments to LightPIT request handling framework + basic language recognition code

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@12 87 private ResponseType invokeMapping(Method method, HttpServletRequest req, HttpServletResponse resp)
universe@12 88 throws IOException, ServletException {
universe@11 89 try {
universe@11 90 LOG.debug("invoke {}", method.getName());
universe@12 91 return (ResponseType) method.invoke(this, req, resp);
universe@12 92 } catch (ReflectiveOperationException | ClassCastException ex) {
universe@11 93 LOG.error(String.format("invocation of method %s failed", method.getName()), ex);
universe@12 94 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
universe@12 95 return ResponseType.NONE;
universe@11 96 }
universe@11 97 }
universe@11 98
universe@11 99 @Override
universe@11 100 public void init() throws ServletException {
universe@11 101 moduleInfo = Optional.ofNullable(this.getClass().getAnnotation(LightPITModule.class));
universe@11 102 moduleInfoELProxy = moduleInfo.map(LightPITModule.ELProxy::convert);
universe@11 103
universe@11 104 if (moduleInfo.isPresent()) {
universe@12 105 scanForRequestMappings();
universe@12 106 }
universe@12 107
universe@12 108 LOG.trace("{} initialized", getServletName());
universe@12 109 }
universe@12 110
universe@12 111 private void scanForRequestMappings() {
universe@12 112 try {
universe@11 113 Method[] methods = getClass().getDeclaredMethods();
universe@11 114 for (Method method : methods) {
universe@11 115 Optional<RequestMapping> mapping = Optional.ofNullable(method.getAnnotation(RequestMapping.class));
universe@11 116 if (mapping.isPresent()) {
universe@11 117 if (!Modifier.isPublic(method.getModifiers())) {
universe@11 118 LOG.warn("{} is annotated with {} but is not public",
universe@11 119 method.getName(), RequestMapping.class.getSimpleName()
universe@11 120 );
universe@11 121 continue;
universe@11 122 }
universe@11 123 if (Modifier.isAbstract(method.getModifiers())) {
universe@11 124 LOG.warn("{} is annotated with {} but is abstract",
universe@11 125 method.getName(), RequestMapping.class.getSimpleName()
universe@11 126 );
universe@11 127 continue;
universe@11 128 }
universe@12 129 if (!ResponseType.class.isAssignableFrom(method.getReturnType())) {
universe@12 130 LOG.warn("{} is annotated with {} but has the wrong return type - 'ResponseType' required",
universe@12 131 method.getName(), RequestMapping.class.getSimpleName()
universe@12 132 );
universe@12 133 continue;
universe@12 134 }
universe@12 135
universe@11 136 Class<?>[] params = method.getParameterTypes();
universe@11 137 if (params.length == 2
universe@11 138 && HttpServletRequest.class.isAssignableFrom(params[0])
universe@11 139 && HttpServletResponse.class.isAssignableFrom(params[1])) {
universe@12 140
universe@11 141 if (mappings.computeIfAbsent(mapping.get().method(), k -> new HashMap<>()).
universe@11 142 putIfAbsent(mapping.get().requestPath(),
universe@11 143 (req, resp) -> invokeMapping(method, req, resp)) != null) {
universe@11 144 LOG.warn("{} {} has multiple mappings",
universe@11 145 mapping.get().method(),
universe@11 146 mapping.get().requestPath()
universe@11 147 );
universe@11 148 }
universe@12 149
universe@11 150 LOG.info("{} {} maps to {}",
universe@11 151 mapping.get().method(),
universe@11 152 mapping.get().requestPath(),
universe@11 153 method.getName()
universe@11 154 );
universe@11 155 } else {
universe@12 156 LOG.warn("{} is annotated with {} but has the wrong parameters - (HttpServletRequest,HttpServletResponse) required",
universe@11 157 method.getName(), RequestMapping.class.getSimpleName()
universe@11 158 );
universe@11 159 }
universe@11 160 }
universe@11 161 }
universe@12 162 } catch (SecurityException ex) {
universe@12 163 LOG.error("Scan for request mappings on declared methods failed.", ex);
universe@11 164 }
universe@11 165 }
universe@11 166
universe@11 167 @Override
universe@11 168 public void destroy() {
universe@11 169 mappings.clear();
universe@11 170 LOG.trace("{} destroyed", getServletName());
universe@11 171 }
universe@11 172
universe@13 173 /**
universe@13 174 * Sets the name of the dynamic fragment.
universe@13 175 *
universe@13 176 * It is sufficient to specify the name without any extension. The extension
universe@13 177 * is added automatically if not specified.
universe@13 178 *
universe@13 179 * The fragment must be located in the dynamic fragments folder.
universe@13 180 *
universe@13 181 * @param req the servlet request object
universe@13 182 * @param fragmentName the name of the fragment
universe@13 183 * @see Constants#DYN_FRAGMENT_PATH_PREFIX
universe@13 184 */
universe@13 185 public void setDynamicFragment(HttpServletRequest req, String fragmentName) {
universe@13 186 req.setAttribute(Constants.REQ_ATTR_FRAGMENT, Functions.dynFragmentPath(fragmentName));
universe@13 187 }
universe@11 188
universe@11 189 /**
universe@13 190 * Specifies the name of an additional stylesheet used by the module.
universe@13 191 *
universe@13 192 * Setting an additional stylesheet is optional, but quite common for HTML
universe@13 193 * output.
universe@13 194 *
universe@13 195 * It is sufficient to specify the name without any extension. The extension
universe@13 196 * is added automatically if not specified.
universe@11 197 *
universe@11 198 * @param req the servlet request object
universe@13 199 * @param stylesheet the name of the stylesheet
universe@11 200 */
universe@13 201 public void setStylesheet(HttpServletRequest req, String stylesheet) {
universe@13 202 req.setAttribute(Constants.REQ_ATTR_STYLESHEET, Functions.enforceExt(stylesheet, ".css"));
universe@10 203 }
universe@10 204
universe@10 205 private void forwardToFullView(HttpServletRequest req, HttpServletResponse resp)
universe@10 206 throws IOException, ServletException {
universe@10 207
universe@11 208 req.setAttribute(Constants.REQ_ATTR_MENU, getModuleManager().getMainMenu());
universe@13 209 req.getRequestDispatcher(HTML_FULL_DISPATCHER).forward(req, resp);
universe@10 210 }
universe@10 211
universe@12 212 private Optional<HandlerMethod> findMapping(HttpMethod method, HttpServletRequest req) {
universe@11 213 return Optional.ofNullable(mappings.get(method)).map(
universe@11 214 (rm) -> rm.get(Optional.ofNullable(req.getPathInfo()).orElse(""))
universe@11 215 );
universe@11 216 }
universe@11 217
universe@12 218 private void forwardAsSepcified(ResponseType type, HttpServletRequest req, HttpServletResponse resp)
universe@12 219 throws ServletException, IOException {
universe@12 220 switch (type) {
universe@12 221 case NONE: return;
universe@12 222 case HTML_FULL:
universe@12 223 forwardToFullView(req, resp);
universe@12 224 return;
universe@12 225 // TODO: implement remaining response types
universe@12 226 default:
universe@12 227 // this code should be unreachable
universe@12 228 LOG.error("ResponseType switch is not exhaustive - this is a bug!");
universe@12 229 throw new UnsupportedOperationException();
universe@12 230 }
universe@12 231 }
universe@12 232
universe@12 233 private void doProcess(HttpMethod method, HttpServletRequest req, HttpServletResponse resp)
universe@12 234 throws ServletException, IOException {
universe@13 235
universe@13 236 HttpSession session = req.getSession();
universe@13 237
universe@13 238 // choose the requested language as session language (if available) or fall back to english, otherwise
universe@13 239 if (session.getAttribute(Constants.SESSION_ATTR_LANGUAGE) == null) {
universe@13 240 Optional<List<String>> availableLanguages = Functions.availableLanguages(getServletContext()).map(Arrays::asList);
universe@13 241 Optional<Locale> reqLocale = Optional.of(req.getLocale());
universe@13 242 Locale sessionLocale = reqLocale.filter((rl) -> availableLanguages.map((al) -> al.contains(rl.getLanguage())).orElse(false)).orElse(Locale.ENGLISH);
universe@13 243 session.setAttribute(Constants.SESSION_ATTR_LANGUAGE, sessionLocale);
universe@13 244 LOG.debug("Settng language for new session {}: {}", session.getId(), sessionLocale.getDisplayLanguage());
universe@13 245 }
universe@13 246
universe@13 247 req.setAttribute(Constants.REQ_ATTR_PATH, Functions.fullPath(req));
universe@13 248 req.setAttribute(Constants.REQ_ATTR_MODULE_CLASSNAME, this.getClass().getName());
universe@13 249 moduleInfoELProxy.ifPresent((proxy) -> req.setAttribute(Constants.REQ_ATTR_MODULE_INFO, proxy));
universe@13 250
universe@12 251 Optional<HandlerMethod> mapping = findMapping(method, req);
universe@12 252 if (mapping.isPresent()) {
universe@12 253 forwardAsSepcified(mapping.get().apply(req, resp), req, resp);
universe@12 254 } else {
universe@12 255 resp.sendError(HttpServletResponse.SC_NOT_FOUND);
universe@12 256 }
universe@12 257 }
universe@12 258
universe@7 259 @Override
universe@7 260 protected final void doGet(HttpServletRequest req, HttpServletResponse resp)
universe@7 261 throws ServletException, IOException {
universe@12 262 doProcess(HttpMethod.GET, req, resp);
universe@7 263 }
universe@7 264
universe@7 265 @Override
universe@7 266 protected final void doPost(HttpServletRequest req, HttpServletResponse resp)
universe@7 267 throws ServletException, IOException {
universe@12 268 doProcess(HttpMethod.POST, req, resp);
universe@7 269 }
universe@7 270 }

mercurial