Example usage for javax.servlet.http HttpServletRequestWrapper HttpServletRequestWrapper

List of usage examples for javax.servlet.http HttpServletRequestWrapper HttpServletRequestWrapper

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequestWrapper HttpServletRequestWrapper.

Prototype

public HttpServletRequestWrapper(HttpServletRequest request) 

Source Link

Document

Constructs a request object wrapping the given request.

Usage

From source file:com.enonic.cms.server.service.dwr.DwrServletWrapper.java

@Override
protected void service(final HttpServletRequest req, final HttpServletResponse res)
        throws ServletException, IOException {
    if (VirtualHostHelper.hasBasePath(req)) {
        String basePath = VirtualHostHelper.getBasePath(req);
        final String servletPath = req.getServletPath().replace("/admin", basePath);

        HttpServletRequest newReq = new HttpServletRequestWrapper(req) {
            public String getServletPath() {
                return servletPath;
            }//from  www. j av  a2s. c  om
        };

        doService(res, newReq);
    } else {
        doService(res, req);
    }
}

From source file:com.tremolosecurity.embedd.EmbPostProc.java

@Override
public void postProcess(HttpFilterRequest req, HttpFilterResponse resp, UrlHolder holder,
        HttpFilterChain curSChain) throws Exception {

    ProxyRequest pr = (ProxyRequest) req.getServletRequest();

    HashMap<String, Attribute> reqHeaders = this.setHeadersCookiesEmb(req);
    EmbRequest embReq = new EmbRequest(req, pr.getSession(true), reqHeaders);

    /*Enumeration enumer = embReq.getParameterNames();
    while (enumer.hasMoreElements()) {//from   w ww.j  a  v  a 2 s.  co m
       String name = (String) enumer.nextElement();
       logger.info("Parameter : '" + name + "'='" + embReq.getParameter(name) + "'");
    }*/

    HttpServletRequestWrapper reqWrapper = new HttpServletRequestWrapper(embReq);

    /*enumer = reqWrapper.getHeaderNames();
    while (enumer.hasMoreElements()) {
       String name = (String) enumer.nextElement();
       Enumeration enumer1 = reqWrapper.getHeaders(name);
       while (enumer1.hasMoreElements()) {
    String val = (String) enumer1.nextElement();
    logger.info("wrapper header : '" + name + "'='" + val + "'");
       }
    }*/

    HttpServletResponseWrapper respWrapper = new HttpServletResponseWrapper(resp.getServletResponse());

    chain.doFilter(reqWrapper, respWrapper);

    /*logger.info(resp);
    logger.info(resp.getServletResponse());
    logger.info(resp.getServletResponse().getContentType());*/

    /*if (resp.getServletResponse().getContentType() != null && resp.getServletResponse().getContentType().startsWith("text")) {
       req.setAttribute(ProxySys.AUTOIDM_STREAM_WRITER, true);
    } else {
       req.setAttribute(ProxySys.AUTOIDM_STREAM_WRITER, false);
    }*/

    //TODO: support content manipulation

}

From source file:org.intalio.tempo.portlet.SecuredController.java

@Override
protected final ModelAndView showForm(RenderRequest request, RenderResponse response, BindException errors)
        throws Exception {
    ModelAndView mav = null;/*from w  ww  . j av a2s .  c o m*/
    Method getHttpServletRequest = request.getClass().getMethod("getHttpServletRequest");
    HttpServletRequest hsr = (HttpServletRequest) getHttpServletRequest.invoke(request);
    HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(hsr);

    String proxyTicket = (String) request.getAttribute(TokenService.CAS_PROXY_TICKET);
    // For TokenFilter && Liferay
    if (proxyTicket == null) {
        proxyTicket = (String) request.getAttribute(PROXY_TICKET);
        if (proxyTicket == null) {
            // LOG.error(requestWrapper.getSession().getAttribute(CASFilter.
            // CAS_FILTER_RECEIPT));
            String pgtIou = null;
            try {
                CASReceipt casReceipt = (CASReceipt) hsr.getSession()
                        .getAttribute(CASFilter.CAS_FILTER_RECEIPT);
                if (casReceipt != null)
                    pgtIou = casReceipt.getPgtIou();
                if (pgtIou != null)
                    proxyTicket = ProxyTicketReceptor.getProxyTicket(pgtIou, _serviceURL);
                //if(proxyTicket == null) throw new IOException("Null proxy ticket");
            } catch (IOException e) {
                throw new RuntimeException("Could not get the proxy ticket", e);
            }
        }
    }

    ApplicationState state = getApplicationState(wrapper);

    if (state.getCurrentUser() == null) {
        String token = _tokenService.getTokenFromTicket(proxyTicket, _serviceURL);
        String[] grantedRoles = new String[0];
        User currentUser = authenticate(token, grantedRoles);
        state.setCurrentUser(currentUser);
        ApplicationState.setCurrentInstance(wrapper, state);
    }
    mav = new ModelAndView("portlet");
    fillAuthorization(wrapper, mav);

    return mav;
}

From source file:com.jk.web.filters.JKDefaultFilter.java

@Override
public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain)
        throws IOException, ServletException {
    try {//  w  ww .j  a v a  2  s.  c  o m
        final HttpServletRequest request = (HttpServletRequest) req;
        final HttpServletResponse response = (HttpServletResponse) res;
        this.logger.info("@doFilter : ".concat(request.getRequestURI()));
        JKWebContextUtil.sync(request);
        final boolean multipart = ServletFileUpload.isMultipartContent(request);
        if (!multipart) {
            final boolean toPdf = request.getParameter(JKWebConstants.PARAMTER_CONVERT_TO_PDF) != null;
            if (toPdf) {
                this.logger.info("toPDF request");
                final HttpServletRequestWrapper rq = new HttpServletRequestWrapper(request);
                final CharResponseWrapper rs = new CharResponseWrapper(response);
                chain.doFilter(rq, rs);
                JKWebUtil.toPDF(request, response, rs.toString());
            } else {
                chain.doFilter(request, response);
            }
        } else {
            chain.doFilter(request, response);
        }
    } catch (final Exception e) {
        if (e instanceof ServletException) {
            throw (ServletException) e;
        }
        throw new ServletException(e);
    } finally {
        JKThreadLocal.remove();
        this.logger.info("@End of doFilter");
    }
}

From source file:org.cloudfoundry.practical.demo.core.webdav.WebDavFilter.java

private void handleWebDav(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper(request) {

        @Override/*from w w  w  . j  a  v  a 2 s  . com*/
        public String getServletPath() {
            return super.getServletPath() + MAPPING_PATH;
        }

        @Override
        public String getPathInfo() {
            return super.getPathInfo().substring(MAPPING_PATH.length());
        }
    };
    this.servlet.service(requestWrapper, response);
}

From source file:com.pearson.developer.xapi.proxy.AuthFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws java.io.IOException, ServletException {

    HttpServletRequest req = (HttpServletRequest) request;

    // AJAX will preflight xAPI request with OPTIONS request without Authorization header
    if ("OPTIONS".equals(req.getMethod())) {
        chain.doFilter(request, response);
        return;/*w  ww . java 2 s  .  c  o  m*/
    }

    boolean authorized = false;
    try { // decode and verify the basic auth credentials
        String authHeader = req.getHeader("Authorization");
        authHeader = authHeader.substring("Basic ".length());
        String decodedAuthHeader = new String(Base64.decodeBase64(authHeader), "UTF-8");
        String[] credentials = decodedAuthHeader.split(":");
        if (credentials.length == 2) {
            String username = credentials[0];
            String password = credentials[1];
            authorized = SessionDatabase.verify(username, password);
        }
    } catch (Exception e) {
        // do nothing
    }

    // proceed to xAPI if session was authorized
    if (authorized) {
        final String targetBasicAuth = config.getInitParameter("targetBasicAuth");

        // need to give the LRS it's expected Authorization value
        HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper(req) {
            @Override
            public String getHeader(String name) {
                if ("Authorization".equalsIgnoreCase(name)) {
                    return targetBasicAuth;
                }
                return super.getHeader(name);
            }

            @Override
            public Enumeration<String> getHeaders(String name) {
                if ("Authorization".equalsIgnoreCase(name)) {
                    List<String> values = new ArrayList<String>();
                    values.add(targetBasicAuth);
                    return Collections.enumeration(values);
                }
                return super.getHeaders(name);
            }
        };
        chain.doFilter(requestWrapper, response);
        return;
    }

    // respond with a 401 if missing auth
    HttpServletResponse resp = (HttpServletResponse) response;
    resp.reset();
    resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    resp.getWriter().println("401 - Unauthorized");
}

From source file:org.bessle.neo4j.proxy.HttpRequestLoggingFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {

    HttpServletRequestWrapper wrappedRequest = new HttpServletRequestWrapper(request);
    Map<String, Object> trace = getTrace(wrappedRequest);
    if (this.logger.isTraceEnabled()) {
        this.logger.trace("Processing request " + request.getMethod() + " " + request.getRequestURI());
        if (this.dumpRequests) {
            @SuppressWarnings("unchecked")
            Map<String, Object> headers = (Map<String, Object>) trace.get("headers");
            this.logger.trace("Headers: " + headers);
            Object body = trace.get("body");
            this.logger.trace("Body: " + body.toString());
        }// ww w. ja  v a2  s  .  c o  m
    }

    try {
        filterChain.doFilter(wrappedRequest, response);
    } finally {
        enhanceTrace(trace, response);
    }
}

From source file:grails.plugin.springsecurity.web.filter.DebugFilter.java

protected void invokeWithWrappedRequest(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws IOException, ServletException {

    request.setAttribute(ALREADY_FILTERED_ATTR_NAME, true);

    request = new HttpServletRequestWrapper(request) {

        @Override//  w w w.ja va 2s .  c o m
        public HttpSession getSession() {
            boolean sessionExists = super.getSession(false) != null;
            HttpSession session = super.getSession();

            if (!sessionExists) {
                log(true, "New HTTP session created: {}", session.getId());
            }

            return session;
        }

        @Override
        public HttpSession getSession(boolean create) {
            return create ? getSession() : super.getSession(false);
        }
    };

    try {
        filterChainProxy.doFilter(request, response, filterChain);
    } finally {
        request.removeAttribute(ALREADY_FILTERED_ATTR_NAME);
    }
}

From source file:com.boundlessgeo.geoserver.AppAuthFilter.java

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) servletRequest;
    HttpServletResponse res = (HttpServletResponse) servletResponse;
    String path = req.getPathInfo();

    if (req.getServletPath().startsWith("/app") && path.startsWith("/api")) {

        if ("POST".equalsIgnoreCase(req.getMethod()) && LOGIN_RE.matcher(path).matches()) {
            // hack: we have to jump through a few hoops to piggy back on the geoserver web auth:
            // 1. we fake the request path to fool the security filter
            // 2. we ignore redirects
            boolean success = runSecurityFilters(new HttpServletRequestWrapper(req) {
                @Override/* w  w w  .  j a v  a  2 s .  c  o m*/
                public String getServletPath() {
                    return "";
                }

                @Override
                public String getPathInfo() {
                    return "/j_spring_security_check";
                }
            }, new HttpServletResponseWrapper(res) {
                @Override
                public void sendRedirect(String location) throws IOException {
                }
            }, WEB_LOGIN_CHAIN_NAME);

            if (success) {
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                res.setStatus(401);
            }

        } else if (LOGOUT_RE.matcher(path).matches()) {
            // invalidate the session if it exists
            HttpSession session = req.getSession(false);
            if (session != null) {
                session.invalidate();
            }
        } else {
            // two modes of authentication, basic vs form.
            String chainName = req.getHeader("Authorization") != null ? DEFAULT_CHAIN_NAME : WEB_CHAIN_NAME;
            if (runSecurityFilters(req, res, chainName)) {
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                res.setStatus(401);
            }
        }
    } else {
        filterChain.doFilter(servletRequest, servletResponse);
    }
}

From source file:grails.plugin.springsecurity.web.SecurityRequestHolderFilter.java

/**
 * If using header check channel security, look for the specified header (typically 'X-Forwarded-Proto')
 * and if found, return a request wrapper that returns the correct values for isSecure(), getScheme(),
 * and getServerPort(). Note that the values are switched intentionally since they're configured for
 * channel security.//  w ww  . j a v  a  2 s . c o m
 *
 * @param request the original request
 * @return the original request or a wrapper for it
 */
protected HttpServletRequest wrapRequest(final HttpServletRequest request) {
    if (!useHeaderCheckChannelSecurity) {
        return request;
    }

    if (insecureHeaderValue.equals(request.getHeader(secureHeaderName)) && "http".equals(request.getScheme())) {
        return new HttpServletRequestWrapper(request) {
            @Override
            public boolean isSecure() {
                return true;
            }

            @Override
            public String getScheme() {
                return "https";
            }

            @Override
            public int getServerPort() {
                int serverPort = portResolver.getServerPort(request);
                Integer httpsPort = portMapper.lookupHttpsPort(serverPort);
                if (httpsPort == null) {
                    log.warn("No port mapping found for HTTP port {}", serverPort);
                    httpsPort = serverPort;
                }
                return httpsPort;
            }
        };
    }

    if (secureHeaderValue.equals(request.getHeader(insecureHeaderName))
            && "https".equals(request.getScheme())) {
        return new HttpServletRequestWrapper(request) {
            @Override
            public boolean isSecure() {
                return false;
            }

            @Override
            public String getScheme() {
                return "http";
            }

            @Override
            public int getServerPort() {
                int serverPort = portResolver.getServerPort(request);
                Integer httpPort = portMapper.lookupHttpPort(serverPort);
                if (httpPort == null) {
                    log.warn("No port mapping found for HTTPS port {}", serverPort);
                    httpPort = serverPort;
                }
                return httpPort;
            }
        };
    }

    return request;
}