Sat, 23 Dec 2017 17:28:19 +0100
implements ResponseTypes
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@11 | 34 | import java.util.HashMap; |
universe@11 | 35 | import java.util.Map; |
universe@11 | 36 | import java.util.Optional; |
universe@7 | 37 | import javax.servlet.ServletException; |
universe@7 | 38 | import javax.servlet.http.HttpServlet; |
universe@7 | 39 | import javax.servlet.http.HttpServletRequest; |
universe@7 | 40 | import javax.servlet.http.HttpServletResponse; |
universe@10 | 41 | import org.slf4j.Logger; |
universe@10 | 42 | import org.slf4j.LoggerFactory; |
universe@7 | 43 | |
universe@7 | 44 | /** |
universe@7 | 45 | * A special implementation of a HTTPServlet which is focused on implementing |
universe@7 | 46 | * the necessary functionality for {@link LightPITModule}s. |
universe@7 | 47 | */ |
universe@9 | 48 | public abstract class AbstractLightPITServlet extends HttpServlet { |
universe@7 | 49 | |
universe@10 | 50 | private static final Logger LOG = LoggerFactory.getLogger(AbstractLightPITServlet.class); |
universe@11 | 51 | |
universe@11 | 52 | /** |
universe@11 | 53 | * Store a reference to the annotation for quicker access. |
universe@11 | 54 | */ |
universe@11 | 55 | private Optional<LightPITModule> moduleInfo = Optional.empty(); |
universe@10 | 56 | |
universe@11 | 57 | /** |
universe@11 | 58 | * The EL proxy is necessary, because the EL resolver cannot handle annotation properties. |
universe@11 | 59 | */ |
universe@11 | 60 | private Optional<LightPITModule.ELProxy> moduleInfoELProxy = Optional.empty(); |
universe@10 | 61 | |
universe@12 | 62 | |
universe@12 | 63 | @FunctionalInterface |
universe@12 | 64 | private static interface HandlerMethod { |
universe@12 | 65 | ResponseType apply(HttpServletRequest t, HttpServletResponse u) throws IOException, ServletException; |
universe@12 | 66 | } |
universe@12 | 67 | |
universe@10 | 68 | /** |
universe@11 | 69 | * Invocation mapping gathered from the {@link RequestMapping} annotations. |
universe@11 | 70 | */ |
universe@12 | 71 | private final Map<HttpMethod, Map<String, HandlerMethod>> mappings = new HashMap<>(); |
universe@11 | 72 | |
universe@11 | 73 | /** |
universe@10 | 74 | * Gives implementing modules access to the {@link ModuleManager}. |
universe@10 | 75 | * @return the module manager |
universe@10 | 76 | */ |
universe@10 | 77 | protected final ModuleManager getModuleManager() { |
universe@10 | 78 | return (ModuleManager) getServletContext().getAttribute(ModuleManager.SC_ATTR_NAME); |
universe@10 | 79 | } |
universe@10 | 80 | |
universe@12 | 81 | private ResponseType invokeMapping(Method method, HttpServletRequest req, HttpServletResponse resp) |
universe@12 | 82 | throws IOException, ServletException { |
universe@11 | 83 | try { |
universe@11 | 84 | LOG.debug("invoke {}", method.getName()); |
universe@12 | 85 | return (ResponseType) method.invoke(this, req, resp); |
universe@12 | 86 | } catch (ReflectiveOperationException | ClassCastException ex) { |
universe@11 | 87 | LOG.error(String.format("invocation of method %s failed", method.getName()), ex); |
universe@12 | 88 | resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); |
universe@12 | 89 | return ResponseType.NONE; |
universe@11 | 90 | } |
universe@11 | 91 | } |
universe@11 | 92 | |
universe@11 | 93 | @Override |
universe@11 | 94 | public void init() throws ServletException { |
universe@11 | 95 | moduleInfo = Optional.ofNullable(this.getClass().getAnnotation(LightPITModule.class)); |
universe@11 | 96 | moduleInfoELProxy = moduleInfo.map(LightPITModule.ELProxy::convert); |
universe@11 | 97 | |
universe@11 | 98 | if (moduleInfo.isPresent()) { |
universe@12 | 99 | scanForRequestMappings(); |
universe@12 | 100 | } |
universe@12 | 101 | |
universe@12 | 102 | LOG.trace("{} initialized", getServletName()); |
universe@12 | 103 | } |
universe@12 | 104 | |
universe@12 | 105 | private void scanForRequestMappings() { |
universe@12 | 106 | try { |
universe@11 | 107 | Method[] methods = getClass().getDeclaredMethods(); |
universe@11 | 108 | for (Method method : methods) { |
universe@11 | 109 | Optional<RequestMapping> mapping = Optional.ofNullable(method.getAnnotation(RequestMapping.class)); |
universe@11 | 110 | if (mapping.isPresent()) { |
universe@11 | 111 | if (!Modifier.isPublic(method.getModifiers())) { |
universe@11 | 112 | LOG.warn("{} is annotated with {} but is not public", |
universe@11 | 113 | method.getName(), RequestMapping.class.getSimpleName() |
universe@11 | 114 | ); |
universe@11 | 115 | continue; |
universe@11 | 116 | } |
universe@11 | 117 | if (Modifier.isAbstract(method.getModifiers())) { |
universe@11 | 118 | LOG.warn("{} is annotated with {} but is abstract", |
universe@11 | 119 | method.getName(), RequestMapping.class.getSimpleName() |
universe@11 | 120 | ); |
universe@11 | 121 | continue; |
universe@11 | 122 | } |
universe@12 | 123 | if (!ResponseType.class.isAssignableFrom(method.getReturnType())) { |
universe@12 | 124 | LOG.warn("{} is annotated with {} but has the wrong return type - 'ResponseType' required", |
universe@12 | 125 | method.getName(), RequestMapping.class.getSimpleName() |
universe@12 | 126 | ); |
universe@12 | 127 | continue; |
universe@12 | 128 | } |
universe@12 | 129 | |
universe@11 | 130 | Class<?>[] params = method.getParameterTypes(); |
universe@11 | 131 | if (params.length == 2 |
universe@11 | 132 | && HttpServletRequest.class.isAssignableFrom(params[0]) |
universe@11 | 133 | && HttpServletResponse.class.isAssignableFrom(params[1])) { |
universe@12 | 134 | |
universe@11 | 135 | if (mappings.computeIfAbsent(mapping.get().method(), k -> new HashMap<>()). |
universe@11 | 136 | putIfAbsent(mapping.get().requestPath(), |
universe@11 | 137 | (req, resp) -> invokeMapping(method, req, resp)) != null) { |
universe@11 | 138 | LOG.warn("{} {} has multiple mappings", |
universe@11 | 139 | mapping.get().method(), |
universe@11 | 140 | mapping.get().requestPath() |
universe@11 | 141 | ); |
universe@11 | 142 | } |
universe@12 | 143 | |
universe@11 | 144 | LOG.info("{} {} maps to {}", |
universe@11 | 145 | mapping.get().method(), |
universe@11 | 146 | mapping.get().requestPath(), |
universe@11 | 147 | method.getName() |
universe@11 | 148 | ); |
universe@11 | 149 | } else { |
universe@12 | 150 | LOG.warn("{} is annotated with {} but has the wrong parameters - (HttpServletRequest,HttpServletResponse) required", |
universe@11 | 151 | method.getName(), RequestMapping.class.getSimpleName() |
universe@11 | 152 | ); |
universe@11 | 153 | } |
universe@11 | 154 | } |
universe@11 | 155 | } |
universe@12 | 156 | } catch (SecurityException ex) { |
universe@12 | 157 | LOG.error("Scan for request mappings on declared methods failed.", ex); |
universe@11 | 158 | } |
universe@11 | 159 | } |
universe@11 | 160 | |
universe@11 | 161 | @Override |
universe@11 | 162 | public void destroy() { |
universe@11 | 163 | mappings.clear(); |
universe@11 | 164 | LOG.trace("{} destroyed", getServletName()); |
universe@11 | 165 | } |
universe@11 | 166 | |
universe@11 | 167 | |
universe@11 | 168 | /** |
universe@11 | 169 | * Sets several requests attributes, that can be used by the JSP. |
universe@11 | 170 | * |
universe@11 | 171 | * @param req the servlet request object |
universe@11 | 172 | * @see Constants#REQ_ATTR_PATH |
universe@11 | 173 | * @see Constants#REQ_ATTR_MODULE_CLASSNAME |
universe@11 | 174 | * @see Constants#REQ_ATTR_MODULE_INFO |
universe@11 | 175 | */ |
universe@11 | 176 | private void setGenericRequestAttributes(HttpServletRequest req) { |
universe@11 | 177 | req.setAttribute(Constants.REQ_ATTR_PATH, Functions.fullPath(req)); |
universe@11 | 178 | |
universe@11 | 179 | req.setAttribute(Constants.REQ_ATTR_MODULE_CLASSNAME, this.getClass().getName()); |
universe@11 | 180 | |
universe@11 | 181 | moduleInfoELProxy.ifPresent((proxy) -> req.setAttribute(Constants.REQ_ATTR_MODULE_INFO, proxy)); |
universe@10 | 182 | } |
universe@10 | 183 | |
universe@10 | 184 | private void forwardToFullView(HttpServletRequest req, HttpServletResponse resp) |
universe@10 | 185 | throws IOException, ServletException { |
universe@10 | 186 | |
universe@11 | 187 | setGenericRequestAttributes(req); |
universe@11 | 188 | req.setAttribute(Constants.REQ_ATTR_MENU, getModuleManager().getMainMenu()); |
universe@10 | 189 | req.getRequestDispatcher(Functions.jspPath("full.jsp")).forward(req, resp); |
universe@10 | 190 | } |
universe@10 | 191 | |
universe@12 | 192 | private Optional<HandlerMethod> findMapping(HttpMethod method, HttpServletRequest req) { |
universe@11 | 193 | return Optional.ofNullable(mappings.get(method)).map( |
universe@11 | 194 | (rm) -> rm.get(Optional.ofNullable(req.getPathInfo()).orElse("")) |
universe@11 | 195 | ); |
universe@11 | 196 | } |
universe@11 | 197 | |
universe@12 | 198 | private void forwardAsSepcified(ResponseType type, HttpServletRequest req, HttpServletResponse resp) |
universe@12 | 199 | throws ServletException, IOException { |
universe@12 | 200 | switch (type) { |
universe@12 | 201 | case NONE: return; |
universe@12 | 202 | case HTML_FULL: |
universe@12 | 203 | forwardToFullView(req, resp); |
universe@12 | 204 | return; |
universe@12 | 205 | // TODO: implement remaining response types |
universe@12 | 206 | default: |
universe@12 | 207 | // this code should be unreachable |
universe@12 | 208 | LOG.error("ResponseType switch is not exhaustive - this is a bug!"); |
universe@12 | 209 | throw new UnsupportedOperationException(); |
universe@12 | 210 | } |
universe@12 | 211 | } |
universe@12 | 212 | |
universe@12 | 213 | private void doProcess(HttpMethod method, HttpServletRequest req, HttpServletResponse resp) |
universe@12 | 214 | throws ServletException, IOException { |
universe@12 | 215 | Optional<HandlerMethod> mapping = findMapping(method, req); |
universe@12 | 216 | if (mapping.isPresent()) { |
universe@12 | 217 | forwardAsSepcified(mapping.get().apply(req, resp), req, resp); |
universe@12 | 218 | } else { |
universe@12 | 219 | resp.sendError(HttpServletResponse.SC_NOT_FOUND); |
universe@12 | 220 | } |
universe@12 | 221 | } |
universe@12 | 222 | |
universe@7 | 223 | @Override |
universe@7 | 224 | protected final void doGet(HttpServletRequest req, HttpServletResponse resp) |
universe@7 | 225 | throws ServletException, IOException { |
universe@12 | 226 | doProcess(HttpMethod.GET, req, resp); |
universe@7 | 227 | } |
universe@7 | 228 | |
universe@7 | 229 | @Override |
universe@7 | 230 | protected final void doPost(HttpServletRequest req, HttpServletResponse resp) |
universe@7 | 231 | throws ServletException, IOException { |
universe@12 | 232 | doProcess(HttpMethod.POST, req, resp); |
universe@7 | 233 | } |
universe@7 | 234 | } |