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

Mon, 11 May 2020 19:09:06 +0200

author
Mike Becker <universe@uap-core.de>
date
Mon, 11 May 2020 19:09:06 +0200
changeset 38
cf85ef18f231
parent 36
0f4f8f255c32
child 39
e722861558bb
permissions
-rw-r--r--

adds DAO for Project entity and save/update methods

universe@7 1 /*
universe@7 2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
universe@34 3 *
universe@24 4 * Copyright 2018 Mike Becker. All rights reserved.
universe@34 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@34 27 *
universe@7 28 */
universe@7 29 package de.uapcore.lightpit;
universe@7 30
universe@38 31 import de.uapcore.lightpit.dao.DataAccessObjects;
universe@38 32 import de.uapcore.lightpit.dao.postgres.PGDataAccessObjects;
universe@33 33 import org.slf4j.Logger;
universe@33 34 import org.slf4j.LoggerFactory;
universe@33 35
universe@7 36 import javax.servlet.ServletException;
universe@7 37 import javax.servlet.http.HttpServlet;
universe@7 38 import javax.servlet.http.HttpServletRequest;
universe@7 39 import javax.servlet.http.HttpServletResponse;
universe@13 40 import javax.servlet.http.HttpSession;
universe@33 41 import java.io.IOException;
universe@33 42 import java.lang.reflect.Method;
universe@33 43 import java.lang.reflect.Modifier;
universe@38 44 import java.sql.Connection;
universe@38 45 import java.sql.SQLException;
universe@33 46 import java.util.*;
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@34 53
universe@10 54 private static final Logger LOG = LoggerFactory.getLogger(AbstractLightPITServlet.class);
universe@34 55
universe@13 56 private static final String HTML_FULL_DISPATCHER = Functions.jspPath("html_full");
universe@33 57
universe@11 58 /**
universe@11 59 * The EL proxy is necessary, because the EL resolver cannot handle annotation properties.
universe@11 60 */
universe@36 61 private LightPITModule.ELProxy moduleInfo = null;
universe@33 62
universe@33 63
universe@12 64 @FunctionalInterface
universe@33 65 private interface HandlerMethod {
universe@38 66 ResponseType apply(HttpServletRequest request, HttpServletResponse response, DataAccessObjects dao) throws IOException, SQLException;
universe@12 67 }
universe@34 68
universe@10 69 /**
universe@11 70 * Invocation mapping gathered from the {@link RequestMapping} annotations.
universe@34 71 * <p>
universe@18 72 * Paths in this map must always start with a leading slash, although
universe@18 73 * the specification in the annotation must not start with a leading slash.
universe@34 74 * <p>
universe@34 75 * The reason for this is the different handling of empty paths in
universe@18 76 * {@link HttpServletRequest#getPathInfo()}.
universe@11 77 */
universe@12 78 private final Map<HttpMethod, Map<String, HandlerMethod>> mappings = new HashMap<>();
universe@11 79
universe@11 80 /**
universe@10 81 * Gives implementing modules access to the {@link ModuleManager}.
universe@33 82 *
universe@10 83 * @return the module manager
universe@10 84 */
universe@10 85 protected final ModuleManager getModuleManager() {
universe@10 86 return (ModuleManager) getServletContext().getAttribute(ModuleManager.SC_ATTR_NAME);
universe@10 87 }
universe@33 88
universe@38 89
universe@34 90 /**
universe@38 91 * Creates a set of data access objects for the specified connection.
universe@33 92 *
universe@38 93 * @param connection the SQL connection
universe@38 94 * @return a set of data access objects
universe@17 95 */
universe@38 96 private DataAccessObjects createDataAccessObjects(Connection connection) throws SQLException {
universe@38 97 final var df = (DatabaseFacade) getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME);
universe@38 98 switch (df.getSQLDialect()) {
universe@38 99 case Postgres:
universe@38 100 return new PGDataAccessObjects(connection);
universe@38 101 default:
universe@38 102 throw new AssertionError("Non-exhaustive switch - this is a bug.");
universe@38 103 }
universe@17 104 }
universe@33 105
universe@38 106 private ResponseType invokeMapping(Method method, HttpServletRequest req, HttpServletResponse resp, DataAccessObjects dao) throws IOException {
universe@11 107 try {
universe@14 108 LOG.trace("invoke {}#{}", method.getDeclaringClass().getName(), method.getName());
universe@38 109 return (ResponseType) method.invoke(this, req, resp, dao);
universe@12 110 } catch (ReflectiveOperationException | ClassCastException ex) {
universe@38 111 LOG.error("invocation of method {} failed: {}", method.getName(), ex.getMessage());
universe@38 112 LOG.debug("Details: ", ex);
universe@12 113 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
universe@12 114 return ResponseType.NONE;
universe@11 115 }
universe@11 116 }
universe@11 117
universe@11 118 @Override
universe@11 119 public void init() throws ServletException {
universe@36 120 moduleInfo = Optional.ofNullable(this.getClass().getAnnotation(LightPITModule.class))
universe@36 121 .map(LightPITModule.ELProxy::new).orElse(null);
universe@33 122
universe@33 123 if (moduleInfo != null) {
universe@12 124 scanForRequestMappings();
universe@12 125 }
universe@33 126
universe@12 127 LOG.trace("{} initialized", getServletName());
universe@12 128 }
universe@12 129
universe@12 130 private void scanForRequestMappings() {
universe@12 131 try {
universe@11 132 Method[] methods = getClass().getDeclaredMethods();
universe@11 133 for (Method method : methods) {
universe@11 134 Optional<RequestMapping> mapping = Optional.ofNullable(method.getAnnotation(RequestMapping.class));
universe@11 135 if (mapping.isPresent()) {
universe@11 136 if (!Modifier.isPublic(method.getModifiers())) {
universe@11 137 LOG.warn("{} is annotated with {} but is not public",
universe@11 138 method.getName(), RequestMapping.class.getSimpleName()
universe@11 139 );
universe@11 140 continue;
universe@11 141 }
universe@11 142 if (Modifier.isAbstract(method.getModifiers())) {
universe@11 143 LOG.warn("{} is annotated with {} but is abstract",
universe@11 144 method.getName(), RequestMapping.class.getSimpleName()
universe@11 145 );
universe@11 146 continue;
universe@11 147 }
universe@12 148 if (!ResponseType.class.isAssignableFrom(method.getReturnType())) {
universe@12 149 LOG.warn("{} is annotated with {} but has the wrong return type - 'ResponseType' required",
universe@12 150 method.getName(), RequestMapping.class.getSimpleName()
universe@12 151 );
universe@12 152 continue;
universe@12 153 }
universe@12 154
universe@11 155 Class<?>[] params = method.getParameterTypes();
universe@38 156 if (params.length == 3
universe@11 157 && HttpServletRequest.class.isAssignableFrom(params[0])
universe@38 158 && HttpServletResponse.class.isAssignableFrom(params[1])
universe@38 159 && DataAccessObjects.class.isAssignableFrom(params[2])) {
universe@34 160
universe@34 161 final String requestPath = "/" + mapping.get().requestPath();
universe@12 162
universe@11 163 if (mappings.computeIfAbsent(mapping.get().method(), k -> new HashMap<>()).
universe@18 164 putIfAbsent(requestPath,
universe@38 165 (req, resp, dao) -> invokeMapping(method, req, resp, dao)) != null) {
universe@11 166 LOG.warn("{} {} has multiple mappings",
universe@11 167 mapping.get().method(),
universe@11 168 mapping.get().requestPath()
universe@11 169 );
universe@11 170 }
universe@12 171
universe@22 172 LOG.debug("{} {} maps to {}::{}",
universe@11 173 mapping.get().method(),
universe@18 174 requestPath,
universe@22 175 getClass().getSimpleName(),
universe@11 176 method.getName()
universe@11 177 );
universe@11 178 } else {
universe@12 179 LOG.warn("{} is annotated with {} but has the wrong parameters - (HttpServletRequest,HttpServletResponse) required",
universe@11 180 method.getName(), RequestMapping.class.getSimpleName()
universe@11 181 );
universe@11 182 }
universe@11 183 }
universe@11 184 }
universe@12 185 } catch (SecurityException ex) {
universe@12 186 LOG.error("Scan for request mappings on declared methods failed.", ex);
universe@11 187 }
universe@11 188 }
universe@11 189
universe@11 190 @Override
universe@11 191 public void destroy() {
universe@11 192 mappings.clear();
universe@11 193 LOG.trace("{} destroyed", getServletName());
universe@11 194 }
universe@34 195
universe@13 196 /**
universe@13 197 * Sets the name of the dynamic fragment.
universe@34 198 * <p>
universe@13 199 * It is sufficient to specify the name without any extension. The extension
universe@13 200 * is added automatically if not specified.
universe@34 201 * <p>
universe@13 202 * The fragment must be located in the dynamic fragments folder.
universe@34 203 *
universe@34 204 * @param req the servlet request object
universe@13 205 * @param fragmentName the name of the fragment
universe@13 206 * @see Constants#DYN_FRAGMENT_PATH_PREFIX
universe@13 207 */
universe@13 208 public void setDynamicFragment(HttpServletRequest req, String fragmentName) {
universe@13 209 req.setAttribute(Constants.REQ_ATTR_FRAGMENT, Functions.dynFragmentPath(fragmentName));
universe@13 210 }
universe@34 211
universe@11 212 /**
universe@13 213 * Specifies the name of an additional stylesheet used by the module.
universe@34 214 * <p>
universe@13 215 * Setting an additional stylesheet is optional, but quite common for HTML
universe@13 216 * output.
universe@34 217 * <p>
universe@13 218 * It is sufficient to specify the name without any extension. The extension
universe@13 219 * is added automatically if not specified.
universe@34 220 *
universe@34 221 * @param req the servlet request object
universe@13 222 * @param stylesheet the name of the stylesheet
universe@11 223 */
universe@13 224 public void setStylesheet(HttpServletRequest req, String stylesheet) {
universe@13 225 req.setAttribute(Constants.REQ_ATTR_STYLESHEET, Functions.enforceExt(stylesheet, ".css"));
universe@10 226 }
universe@34 227
universe@10 228 private void forwardToFullView(HttpServletRequest req, HttpServletResponse resp)
universe@10 229 throws IOException, ServletException {
universe@34 230
universe@36 231 req.setAttribute(Constants.REQ_ATTR_MENU, getModuleManager().getMainMenu());
universe@13 232 req.getRequestDispatcher(HTML_FULL_DISPATCHER).forward(req, resp);
universe@10 233 }
universe@34 234
universe@12 235 private Optional<HandlerMethod> findMapping(HttpMethod method, HttpServletRequest req) {
universe@11 236 return Optional.ofNullable(mappings.get(method)).map(
universe@18 237 (rm) -> rm.get(Optional.ofNullable(req.getPathInfo()).orElse("/"))
universe@11 238 );
universe@11 239 }
universe@34 240
universe@34 241 private void forwardAsSpecified(ResponseType type, HttpServletRequest req, HttpServletResponse resp)
universe@12 242 throws ServletException, IOException {
universe@12 243 switch (type) {
universe@34 244 case NONE:
universe@34 245 return;
universe@12 246 case HTML_FULL:
universe@12 247 forwardToFullView(req, resp);
universe@12 248 return;
universe@12 249 // TODO: implement remaining response types
universe@12 250 default:
universe@34 251 throw new AssertionError("ResponseType switch is not exhaustive - this is a bug!");
universe@12 252 }
universe@12 253 }
universe@34 254
universe@38 255 private void doProcess(HttpMethod method, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
universe@27 256
universe@13 257 // choose the requested language as session language (if available) or fall back to english, otherwise
universe@20 258 HttpSession session = req.getSession();
universe@13 259 if (session.getAttribute(Constants.SESSION_ATTR_LANGUAGE) == null) {
universe@13 260 Optional<List<String>> availableLanguages = Functions.availableLanguages(getServletContext()).map(Arrays::asList);
universe@13 261 Optional<Locale> reqLocale = Optional.of(req.getLocale());
universe@13 262 Locale sessionLocale = reqLocale.filter((rl) -> availableLanguages.map((al) -> al.contains(rl.getLanguage())).orElse(false)).orElse(Locale.ENGLISH);
universe@13 263 session.setAttribute(Constants.SESSION_ATTR_LANGUAGE, sessionLocale);
universe@34 264 LOG.debug("Setting language for new session {}: {}", session.getId(), sessionLocale.getDisplayLanguage());
universe@14 265 } else {
universe@15 266 Locale sessionLocale = (Locale) session.getAttribute(Constants.SESSION_ATTR_LANGUAGE);
universe@15 267 resp.setLocale(sessionLocale);
universe@15 268 LOG.trace("Continuing session {} with language {}", session.getId(), sessionLocale);
universe@13 269 }
universe@34 270
universe@21 271 // set some internal request attributes
universe@13 272 req.setAttribute(Constants.REQ_ATTR_PATH, Functions.fullPath(req));
universe@13 273 req.setAttribute(Constants.REQ_ATTR_MODULE_CLASSNAME, this.getClass().getName());
universe@36 274 Optional.ofNullable(moduleInfo).ifPresent((proxy) -> req.setAttribute(Constants.REQ_ATTR_MODULE_INFO, proxy));
universe@34 275
universe@38 276 // obtain a connection and create the data access objects
universe@38 277 final var db = (DatabaseFacade) req.getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME);
universe@38 278 try (final var connection = db.getDataSource().getConnection()) {
universe@38 279 final var dao = createDataAccessObjects(connection);
universe@38 280 // call the handler, if available, or send an HTTP 404 error
universe@38 281 final var mapping = findMapping(method, req);
universe@38 282 if (mapping.isPresent()) {
universe@38 283 forwardAsSpecified(mapping.get().apply(req, resp, dao), req, resp);
universe@38 284 } else {
universe@38 285 resp.sendError(HttpServletResponse.SC_NOT_FOUND);
universe@38 286 }
universe@38 287 } catch (SQLException ex) {
universe@38 288 LOG.error("Database exception (Code {}): {}", ex.getErrorCode(), ex.getMessage());
universe@38 289 LOG.debug("Details: ", ex);
universe@38 290 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Database Error - Code:" + ex.getErrorCode());
universe@12 291 }
universe@12 292 }
universe@34 293
universe@7 294 @Override
universe@7 295 protected final void doGet(HttpServletRequest req, HttpServletResponse resp)
universe@7 296 throws ServletException, IOException {
universe@12 297 doProcess(HttpMethod.GET, req, resp);
universe@7 298 }
universe@7 299
universe@7 300 @Override
universe@7 301 protected final void doPost(HttpServletRequest req, HttpServletResponse resp)
universe@7 302 throws ServletException, IOException {
universe@12 303 doProcess(HttpMethod.POST, req, resp);
universe@7 304 }
universe@7 305 }

mercurial