View Javadoc
1   package org.itracker.web.filters;
2   
3   import org.apache.struts.Globals;
4   import org.apache.struts.action.ActionMessage;
5   import org.apache.struts.action.ActionMessages;
6   import org.itracker.model.PermissionType;
7   import org.itracker.model.util.UserUtilities;
8   import org.itracker.services.ConfigurationService;
9   import org.itracker.services.ITrackerServices;
10  import org.itracker.web.util.*;
11  import org.slf4j.Logger;
12  import org.slf4j.LoggerFactory;
13  
14  import javax.servlet.*;
15  import javax.servlet.http.HttpServletRequest;
16  import javax.servlet.http.HttpServletResponse;
17  import java.io.IOException;
18  import java.util.Locale;
19  import java.util.Map;
20  import java.util.Set;
21  
22  /**
23   * @author ranks
24   */
25  public class ExecuteAlwaysFilter implements Filter {
26  
27      /**
28       * Logger for ExecuteAlwaysFilter
29       */
30      private static final Logger log = LoggerFactory
31              .getLogger(ExecuteAlwaysFilter.class);
32  
33      private ITrackerServices iTrackerServices;
34  
35  
36      public void destroy() {
37      }
38  
39      public void doFilter(ServletRequest servletRequest,
40                           ServletResponse response, FilterChain chain) throws IOException,
41              ServletException {
42  
43          if (!(servletRequest instanceof HttpServletRequest)) {
44              RuntimeException re = new IllegalArgumentException(
45                      "Unsupported servlet-request of type: "
46                              + servletRequest.getClass().getName());
47              log.error("doFilter: failed, invalid request type", re);
48              throw re;
49          }
50  
51          HttpServletRequest request = (HttpServletRequest) servletRequest;
52  
53          String path = request.getRequestURI().substring(
54                  request.getContextPath().length());
55          if (log.isDebugEnabled()) {
56              log.debug("doFilter: called with path " + path);
57          }
58  
59          // From IrackerBaseAction.executeAlways
60          if (log.isDebugEnabled()) {
61              log.debug("doFilter: setting the common request attributes, (coming from the former header.jsp)");
62          }
63  
64          setupCommonReqAttributes(request, ServletContextUtils.getItrackerServices().getConfigurationService());
65          if (SessionManager.getSessionNeedsReset(request.getRemoteUser())) {
66              // logout and go to login
67              request.getSession().invalidate();
68              ((HttpServletResponse) response).sendRedirect(request.getContextPath());
69          }
70  
71          setupCommonReqAttributesEx(request);
72  
73          try {
74              log.debug("doFilter: executing chain..");
75  
76              chain.doFilter(request, response);
77  
78              log.debug("doFilter: completed chain execution.");
79  
80          } catch (RuntimeException e) {
81              log.error(
82                      "doFilter: failed to execute chain with runtime exception: {}",
83                              e.getMessage(), e);
84              handleError(e, request, response);
85  
86          } catch (IOException ioe) {
87              log.error("doFilter: failed to execute chain with i/o exception: {}",
88                      ioe.getMessage(), ioe);
89              handleError(ioe, request, response);
90  
91          } catch (ServletException se) {
92              log.error(
93                      "doFilter: failed to execute chain with servlet exception: "
94                              + se.getMessage(), se);
95              handleError(se, request, response);
96  
97          } catch (Error err) {
98              log.error("doFilter: caught fatal error executing filter chain",
99                      err);
100             throw err;
101         }
102     }
103 
104     private static void handleError(Throwable error, ServletRequest request, ServletResponse response) throws ServletException {
105 
106         if (null == error) {
107             log.debug("handleError: called with null throwable");
108             throw new IllegalArgumentException("null error");
109         }
110 
111         log.debug("handleError: called with " + error.getClass().getSimpleName(), error);
112 
113         if (!(response instanceof HttpServletResponse) || !(request instanceof HttpServletRequest)) {
114             log.error("handleError: unknown request/response: " + request + ", " + response, error);
115             throw new ServletException(error.getMessage(), error);
116         }
117         HttpServletRequest httpRequest = (HttpServletRequest) request;
118         HttpServletResponse httpResponse = (HttpServletResponse) response;
119 
120         ActionMessages errors = new ActionMessages();
121         errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.system.message",
122                 new Object[]{error.getLocalizedMessage() == null ? error.getMessage() : error.getLocalizedMessage(),
123                         error.getClass().getCanonicalName()}));
124 
125         saveErrors((HttpServletRequest) request, errors);
126         try {
127             httpResponse.sendRedirect(httpRequest.getContextPath() + "/error.do");
128         } catch (IOException e) {
129             log.error("handleError: failed to redirect to error-page", e);
130         }
131     }
132 
133     /**
134      * <p>Save the specified error messages keys into the appropriate request
135      * attribute for use by the &lt;html:errors&gt; tag, if any messages
136      * are required. Otherwise, ensure that the request attribute is not
137      * created.</p>
138      *
139      * @param request The servlet request we are processing
140      * @param errors  Error messages object
141      * @since Struts 1.2
142      */
143     protected static void saveErrors(HttpServletRequest request, ActionMessages errors) {
144 
145         // Remove any error messages attribute if none are required
146         if ((errors == null) || errors.isEmpty()) {
147             request.removeAttribute(Globals.ERROR_KEY);
148             request.getSession().removeAttribute(Globals.ERROR_KEY);
149             return;
150         }
151 
152         if (log.isDebugEnabled()) {
153             log.debug("saveErrors: saved errors: {}", errors);
154         }
155         // Save the error messages we need
156         request.setAttribute(Globals.ERROR_KEY, errors);
157 
158         request.getSession().setAttribute(Globals.ERROR_KEY, errors);
159     }
160 
161 
162     private static void setupCommonReqAttributes(
163             HttpServletRequest request,
164             ConfigurationService configurationService) {
165         boolean allowForgotPassword;
166         boolean allowSelfRegister;
167         boolean allowSaveLogin;
168         String siteTitle;
169         String siteLogo;
170 
171         allowForgotPassword = configurationService.getBooleanProperty(
172                 "allow_forgot_password", true);
173         allowSelfRegister = configurationService.getBooleanProperty(
174                 "allow_self_register", false);
175         allowSaveLogin = configurationService.getBooleanProperty(
176                 "allow_save_login", true);
177         siteTitle = configurationService
178                         .getProperty("site_title", "itracker.org");
179         siteLogo = configurationService
180                 .getProperty("site_logo", null);
181 
182         Locale locale = LoginUtilities.getCurrentLocale(request);
183 
184         // TODO: this should be configured per-instance. Request server-name
185         // should only be used for exception and logged (configuration not
186         // found!)
187 
188         String baseURL = configurationService.getSystemBaseURL();
189         if (null == baseURL) {
190             baseURL = request.getScheme() + "://" + request.getServerName()
191                     + ":" + request.getServerPort() + request.getContextPath();
192             log.warn("setupCommonReqAttributes: not found system_base_url configuration, setting from request: " + baseURL);
193         }
194         request.setAttribute("allowForgotPassword", allowForgotPassword);
195         request.setAttribute("allowSelfRegister", allowSelfRegister);
196         request.setAttribute("allowSaveLogin", allowSaveLogin);
197         request.setAttribute("siteLogo", siteLogo);
198         request.setAttribute("siteTitle", siteTitle);
199         request.setAttribute("baseURL", baseURL);
200         // TODO: remove deprecated currLocale attribute
201         request.setAttribute("currLocale", locale);
202 
203 
204         request.setAttribute("locales", configurationService.getAvailableLanguages());
205         request.setAttribute(Constants.LOCALE_KEY, locale);
206 
207         request.setAttribute("contextPath", request.getContextPath());
208 
209         request.setAttribute("currentDate", new java.util.Date());
210         request.setAttribute("currentVersion", configurationService.getProperty("version", "Unknown"));
211 
212 
213     }
214 
215    /**
216     * @deprecated this should not be necessary anymore (default.header.jsp).
217     * @param request
218     */
219    @Deprecated
220     private static void setupCommonReqAttributesEx(HttpServletRequest request) {
221         final Map<Integer, Set<PermissionType>> permissions = RequestHelper
222                 .getUserPermissions(request.getSession());
223         request.setAttribute("hasPermissionUserAdmin", UserUtilities.hasPermission(permissions,
224                 PermissionType.USER_ADMIN));
225         request.setAttribute("hasPermissionProductAdmin", UserUtilities.hasPermission(permissions,
226                 PermissionType.PRODUCT_ADMIN));
227         request.setAttribute("hasPermissionViewAll",
228                 UserUtilities.hasPermission(permissions,
229                         PermissionType.ISSUE_VIEW_ALL));
230     }
231 
232     /**
233      *
234      */
235     public void init(FilterConfig filterConfig) throws ServletException {
236 
237     }
238 
239     public ITrackerServices getITrackerServices() {
240         if (null == this.iTrackerServices) {
241             this.iTrackerServices = ServletContextUtils.getItrackerServices();
242         }
243         return iTrackerServices;
244     }
245 
246 }