class SessionHelpers {

  public ServletRequest prepareRequest(ServletRequest request, ServletResponse response,
      ServletContext originalServletContext) {
    // Only execute this code once per request
    if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
      HttpRequestWrapper wrappedRequest = (HttpRequestWrapper)request.getAttribute(REQUEST_WRAPPED_ATTRIBUTE);
      ServletContext servletContext = originalServletContext;
      if (servletContext == null) {
        logger.info("ServletContext was null when prepareRequest() was called from Filter. "
            + "This means that filter's init() method was not called at initialization time. "
            + "This may result in unexpected behavior if this filter was invoked after"
            + "servlet dispatch forward() and include() calls.");
        servletContext = ((HttpServletRequest)request).getServletContext();
      }

      // for following we actually test that servlet context points to same
      // references, and so we don't use equals() method
      if (wrappedRequest == null || servletContext != wrappedRequest.getServletContext()) { // NOSONAR
        if (interceptListeners) {
          findListenersByIntercepting(servletContext, (HttpServletRequest)request);
        }
        wrappedRequest = wrapRequest(request, servletContext);
        wrappedRequest.setResponse(wrapResponse(response, wrappedRequest));
        request.setAttribute(REQUEST_WRAPPED_ATTRIBUTE, wrappedRequest);
        return wrappedRequest;
      }
    }
    return request;
  }

}