1 package com.atlassian.johnson.spring.web.context.support;
2
3 import com.atlassian.johnson.Johnson;
4 import com.atlassian.johnson.config.JohnsonConfig;
5 import com.atlassian.johnson.event.Event;
6 import com.atlassian.johnson.spring.web.context.JohnsonContextLoaderListener;
7 import org.slf4j.Logger;
8 import org.slf4j.LoggerFactory;
9 import org.springframework.web.context.support.HttpRequestHandlerServlet;
10
11 import javax.annotation.Nonnull;
12 import javax.servlet.ServletContext;
13 import javax.servlet.ServletException;
14 import javax.servlet.http.HttpServletRequest;
15 import javax.servlet.http.HttpServletResponse;
16 import java.io.IOException;
17
18
19
20
21 public class JohnsonHttpRequestHandlerServlet extends HttpRequestHandlerServlet {
22
23 private static final Logger LOG = LoggerFactory.getLogger(JohnsonHttpRequestHandlerServlet.class);
24
25 private final Object lock = new Object();
26
27 private volatile boolean uninitialised = true;
28
29 @Override
30 public void init() throws ServletException {
31
32
33
34
35 maybeInit();
36 }
37
38 protected void sendRedirect(@Nonnull HttpServletResponse response) throws IOException {
39 ServletContext servletContext = getServletContext();
40 JohnsonConfig config = Johnson.getConfig(servletContext);
41
42 LOG.warn("HttpRequestHandlerServlet [{}] cannot be initialised to service an incoming " +
43 "request; redirecting to {}", getServletName(), config.getErrorPath());
44 response.sendRedirect(servletContext.getContextPath() + config.getErrorPath());
45 }
46
47 @Override
48 protected void service(@Nonnull HttpServletRequest request, @Nonnull HttpServletResponse response)
49 throws ServletException, IOException {
50
51
52
53
54 if (uninitialised) {
55 synchronized (lock) {
56 if (uninitialised) {
57 if (!maybeInit()) {
58
59
60 sendRedirect(response);
61
62 return;
63 }
64 }
65 }
66 }
67
68 super.service(request, response);
69 }
70
71 private boolean maybeInit() throws ServletException {
72 ServletContext servletContext = getServletContext();
73
74 Object attribute = servletContext.getAttribute(JohnsonContextLoaderListener.ATTR_BYPASSED);
75
76
77
78 if (Boolean.TRUE == attribute)
79 {
80 LOG.error("Bypassing HttpRequestHandlerServlet [{}] initialisation; Spring initialisation was bypassed",
81 getServletName());
82 return false;
83 }
84
85
86 if (attribute instanceof Event) {
87 Event event = (Event) attribute;
88
89 LOG.error("Bypassing HttpRequestHandlerServlet [{}] initialisation; Spring initialisation failed: {}",
90 getServletName(), event.getDesc());
91 return false;
92 }
93
94
95
96 try {
97 super.init();
98
99
100
101 uninitialised = false;
102 } catch (Exception e) {
103 LOG.error("HttpRequestHandlerServlet [" + getServletName() + "] could not be started", e);
104
105 return false;
106 }
107
108 return true;
109 }
110 }