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

Sun, 17 Dec 2017 01:45:28 +0100

author
Mike Becker <universe@uap-core.de>
date
Sun, 17 Dec 2017 01:45:28 +0100
changeset 11
737ab27e37b3
parent 10
89e3e6e28b69
child 12
005d27918b57
permissions
-rw-r--r--

implements simple request mapper

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@11 37 import java.util.function.BiConsumer;
universe@7 38 import javax.servlet.ServletException;
universe@7 39 import javax.servlet.http.HttpServlet;
universe@7 40 import javax.servlet.http.HttpServletRequest;
universe@7 41 import javax.servlet.http.HttpServletResponse;
universe@10 42 import org.slf4j.Logger;
universe@10 43 import org.slf4j.LoggerFactory;
universe@7 44
universe@7 45 /**
universe@7 46 * A special implementation of a HTTPServlet which is focused on implementing
universe@7 47 * the necessary functionality for {@link LightPITModule}s.
universe@7 48 */
universe@9 49 public abstract class AbstractLightPITServlet extends HttpServlet {
universe@7 50
universe@10 51 private static final Logger LOG = LoggerFactory.getLogger(AbstractLightPITServlet.class);
universe@11 52
universe@11 53 /**
universe@11 54 * Store a reference to the annotation for quicker access.
universe@11 55 */
universe@11 56 private Optional<LightPITModule> moduleInfo = Optional.empty();
universe@10 57
universe@11 58 /**
universe@11 59 * The EL proxy is necessary, because the EL resolver cannot handle annotation properties.
universe@11 60 */
universe@11 61 private Optional<LightPITModule.ELProxy> moduleInfoELProxy = Optional.empty();
universe@10 62
universe@10 63 /**
universe@11 64 * Invocation mapping gathered from the {@link RequestMapping} annotations.
universe@11 65 */
universe@11 66 private final Map<HttpMethod, Map<String, BiConsumer<HttpServletRequest, HttpServletResponse>>> mappings = new HashMap<>();
universe@11 67
universe@11 68 /**
universe@10 69 * Gives implementing modules access to the {@link ModuleManager}.
universe@10 70 * @return the module manager
universe@10 71 */
universe@10 72 protected final ModuleManager getModuleManager() {
universe@10 73 return (ModuleManager) getServletContext().getAttribute(ModuleManager.SC_ATTR_NAME);
universe@10 74 }
universe@10 75
universe@11 76 private void invokeMapping(Method method, HttpServletRequest req, HttpServletResponse resp) {
universe@11 77 try {
universe@11 78 LOG.debug("invoke {}", method.getName());
universe@11 79 method.invoke(this, req, resp);
universe@11 80 } catch (ReflectiveOperationException ex) {
universe@11 81 LOG.error(String.format("invocation of method %s failed", method.getName()), ex);
universe@11 82 }
universe@11 83 }
universe@11 84
universe@11 85 @Override
universe@11 86 public void init() throws ServletException {
universe@11 87 moduleInfo = Optional.ofNullable(this.getClass().getAnnotation(LightPITModule.class));
universe@11 88 moduleInfoELProxy = moduleInfo.map(LightPITModule.ELProxy::convert);
universe@11 89
universe@11 90 if (moduleInfo.isPresent()) {
universe@11 91 Method[] methods = getClass().getDeclaredMethods();
universe@11 92 for (Method method : methods) {
universe@11 93 Optional<RequestMapping> mapping = Optional.ofNullable(method.getAnnotation(RequestMapping.class));
universe@11 94 if (mapping.isPresent()) {
universe@11 95 if (!Modifier.isPublic(method.getModifiers())) {
universe@11 96 LOG.warn("{} is annotated with {} but is not public",
universe@11 97 method.getName(), RequestMapping.class.getSimpleName()
universe@11 98 );
universe@11 99 continue;
universe@11 100 }
universe@11 101 if (Modifier.isAbstract(method.getModifiers())) {
universe@11 102 LOG.warn("{} is annotated with {} but is abstract",
universe@11 103 method.getName(), RequestMapping.class.getSimpleName()
universe@11 104 );
universe@11 105 continue;
universe@11 106 }
universe@11 107
universe@11 108 Class<?>[] params = method.getParameterTypes();
universe@11 109 if (params.length == 2
universe@11 110 && HttpServletRequest.class.isAssignableFrom(params[0])
universe@11 111 && HttpServletResponse.class.isAssignableFrom(params[1])) {
universe@11 112
universe@11 113 if (mappings.computeIfAbsent(mapping.get().method(), k -> new HashMap<>()).
universe@11 114 putIfAbsent(mapping.get().requestPath(),
universe@11 115 (req, resp) -> invokeMapping(method, req, resp)) != null) {
universe@11 116 LOG.warn("{} {} has multiple mappings",
universe@11 117 mapping.get().method(),
universe@11 118 mapping.get().requestPath()
universe@11 119 );
universe@11 120 }
universe@11 121
universe@11 122 LOG.info("{} {} maps to {}",
universe@11 123 mapping.get().method(),
universe@11 124 mapping.get().requestPath(),
universe@11 125 method.getName()
universe@11 126 );
universe@11 127 } else {
universe@11 128 LOG.warn("{} is annotated with {} but has the wrong signature - (HttpServletRequest,HttpServletResponse) required",
universe@11 129 method.getName(), RequestMapping.class.getSimpleName()
universe@11 130 );
universe@11 131 }
universe@11 132 }
universe@11 133 }
universe@11 134 }
universe@11 135
universe@11 136 LOG.trace("{} initialized", getServletName());
universe@11 137 }
universe@11 138
universe@11 139 @Override
universe@11 140 public void destroy() {
universe@11 141 mappings.clear();
universe@11 142 LOG.trace("{} destroyed", getServletName());
universe@11 143 }
universe@11 144
universe@11 145
universe@11 146 /**
universe@11 147 * Sets several requests attributes, that can be used by the JSP.
universe@11 148 *
universe@11 149 * @param req the servlet request object
universe@11 150 * @see Constants#REQ_ATTR_PATH
universe@11 151 * @see Constants#REQ_ATTR_MODULE_CLASSNAME
universe@11 152 * @see Constants#REQ_ATTR_MODULE_INFO
universe@11 153 */
universe@11 154 private void setGenericRequestAttributes(HttpServletRequest req) {
universe@11 155 req.setAttribute(Constants.REQ_ATTR_PATH, Functions.fullPath(req));
universe@11 156
universe@11 157 req.setAttribute(Constants.REQ_ATTR_MODULE_CLASSNAME, this.getClass().getName());
universe@11 158
universe@11 159 moduleInfoELProxy.ifPresent((proxy) -> req.setAttribute(Constants.REQ_ATTR_MODULE_INFO, proxy));
universe@10 160 }
universe@10 161
universe@10 162 private void forwardToFullView(HttpServletRequest req, HttpServletResponse resp)
universe@10 163 throws IOException, ServletException {
universe@10 164
universe@11 165 setGenericRequestAttributes(req);
universe@11 166 req.setAttribute(Constants.REQ_ATTR_MENU, getModuleManager().getMainMenu());
universe@10 167 req.getRequestDispatcher(Functions.jspPath("full.jsp")).forward(req, resp);
universe@10 168 }
universe@10 169
universe@11 170 private Optional<BiConsumer<HttpServletRequest, HttpServletResponse>> findMapping(HttpMethod method, HttpServletRequest req) {
universe@11 171 return Optional.ofNullable(mappings.get(method)).map(
universe@11 172 (rm) -> rm.get(Optional.ofNullable(req.getPathInfo()).orElse(""))
universe@11 173 );
universe@11 174 }
universe@11 175
universe@7 176 @Override
universe@7 177 protected final void doGet(HttpServletRequest req, HttpServletResponse resp)
universe@7 178 throws ServletException, IOException {
universe@11 179
universe@11 180 findMapping(HttpMethod.GET, req).ifPresent((consumer) -> consumer.accept(req, resp));
universe@11 181
universe@11 182 // TODO: let the invoked handler decide (signature must be changed from a BiConsumer to a BiFunction)
universe@11 183 // TODO: we should call a default handler, if no specific mapping could be found
universe@10 184 forwardToFullView(req, resp);
universe@7 185 }
universe@7 186
universe@7 187 @Override
universe@7 188 protected final void doPost(HttpServletRequest req, HttpServletResponse resp)
universe@7 189 throws ServletException, IOException {
universe@10 190
universe@11 191 findMapping(HttpMethod.POST, req).ifPresent((consumer) -> consumer.accept(req, resp));
universe@11 192
universe@10 193 forwardToFullView(req, resp);
universe@7 194 }
universe@7 195 }

mercurial