Abstract base class for page servlets.
| 38 | * Abstract base class for page servlets. |
| 39 | */ |
| 40 | public abstract class PageServlet extends HttpServlet { |
| 41 | private static final ThreadLocal<HttpServletRequest> request = new ThreadLocal<>(); |
| 42 | private static final ThreadLocal<HttpServletResponse> response = new ThreadLocal<>(); |
| 43 | |
| 44 | @Override |
| 45 | public void init() throws ServletException { |
| 46 | var fields = getClass().getDeclaredFields(); |
| 47 | |
| 48 | for (var i = 0; i < fields.length; i++) { |
| 49 | var field = fields[i]; |
| 50 | |
| 51 | var fieldType = field.getType(); |
| 52 | |
| 53 | if (WebService.class.isAssignableFrom(fieldType) && field.getAnnotation(WebService.Instance.class) != null) { |
| 54 | field.setAccessible(true); |
| 55 | |
| 56 | try { |
| 57 | field.set(this, WebService.instances.get(fieldType)); |
| 58 | } catch (IllegalAccessException exception) { |
| 59 | throw new UnsupportedOperationException(exception); |
| 60 | } |
| 61 | } |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | @Override |
| 66 | protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { |
| 67 | if (!request.getMethod().equalsIgnoreCase("GET")) { |
| 68 | response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); |
| 69 | return; |
| 70 | } |
| 71 | |
| 72 | try (var connection = openConnection()) { |
| 73 | if (connection != null) { |
| 74 | connection.setReadOnly(true); |
| 75 | } |
| 76 | |
| 77 | WebService.setConnection(connection); |
| 78 | |
| 79 | try { |
| 80 | process(request, response); |
| 81 | } catch (Exception exception) { |
| 82 | log(exception.getMessage(), exception); |
| 83 | |
| 84 | throw exception; |
| 85 | } finally { |
| 86 | if (connection != null) { |
| 87 | connection.setReadOnly(false); |
| 88 | } |
| 89 | } |
| 90 | } catch (SQLException exception) { |
| 91 | throw new ServletException(exception); |
| 92 | } finally { |
| 93 | WebService.setConnection(null); |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | /** |
nothing calls this directly
no outgoing calls
no test coverage detected