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.stoxx.portlet.accountdetails.controller.AccountDetailsController.java

@ResourceMapping
public void handleResource(ResourceRequest request, ResourceResponse response) {
    try {//from www  . j av  a2s .  com
        HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(
                PortalUtil.getHttpServletRequest(request)) {

            @Override
            public String getParameter(String name) {
                log.info("The name is " + name);
                if (name.equals(AUTH_TOKEN)) {
                    log.info("The name matches");
                    return PortalUtil.getOriginalServletRequest((HttpServletRequest) super.getRequest())
                            .getParameter(name);
                }

                return super.getParameter(name);
            }
        };
        AuthTokenUtil.checkCSRFToken(wrapper, this.getClass().getName());
    } catch (Exception e) {
        log.error("INVALID CSRF TOKEN", e);
        return;
    }
    try {
        com.liferay.portal.kernel.captcha.CaptchaUtil.serveImage(request, response);
    } catch (IOException e) {
        log.error("IOException", e);
    }
}

From source file:edu.harvard.hul.ois.pds.ws.PDSWebService.java

public static void printError(HttpServletRequest req, HttpServletResponse res, String message, Throwable e) {
    HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(req);
    wrapper.setAttribute("message", message);
    wrapper.setAttribute("pdsUrl", req.getContextPath());
    wrapper.setAttribute("exception", e);
    wrapper.setAttribute("req", req);
    RequestDispatcher rd = req.getRequestDispatcher("/api-error.jsp?");
    try {//from ww  w .j  a  va2 s . c o  m
        rd.forward(req, res);
    } catch (Exception e1) {
        e1.printStackTrace();
    }
}

From source file:net.sourceforge.subsonic.controller.RESTController.java

private HttpServletRequest wrapRequest(final HttpServletRequest request, boolean jukebox) {
    final String playerId = createPlayerIfNecessary(request, jukebox);
    return new HttpServletRequestWrapper(request) {
        @Override//  w ww  .  ja v  a 2  s.co  m
        public String getParameter(String name) {
            // Returns the correct player to be used in PlayerService.getPlayer()
            if ("player".equals(name)) {
                return playerId;
            }

            return super.getParameter(name);
        }
    };
}

From source file:org.alfresco.module.vti.web.fp.MoveMethod.java

/**
 * Alters the request to include the servlet path (needed for 
 *  building the destination path), then executes as usual
 *//*  w w w  .j av a 2  s.  com*/
@Override
public void execute() throws WebDAVServerException {
    // Wrap the request to include the servlet path
    m_request = new HttpServletRequestWrapper(m_request) {
        public String getServletPath() {
            return alfrescoContext.equals("") ? "/" : alfrescoContext;
        }
    };

    // Now have the move executed as normal
    super.execute();
}

From source file:org.alfresco.web.site.servlet.SSOAuthenticationFilter.java

/**
 * Wraps an {@link HttpServletRequest} if an HTTP header has been configured for
 * use by an external SSO system to provide the name of an authenticated user.
 * The wrapper's {@link #getRemoteUser} returns the value of the header but will
 * defaults to the wrapped method's value if the header is not set.
 * @param sreq original {@code ServletRequest}
 * @return either the original {@code sreq} or a wrapped {@code HttpServletRequest}
 *///from   w  w w.ja  v a2 s  .c  o m
private ServletRequest wrapHeaderAuthenticatedRequest(ServletRequest sreq) {
    if (userHeader != null && sreq instanceof HttpServletRequest) {
        final HttpServletRequest req = (HttpServletRequest) sreq;
        sreq = new HttpServletRequestWrapper(req) {
            @Override
            public String getRemoteUser() {
                // MNT-11041 Share SSOAuthenticationFilter and non-ascii username strings
                String remoteUser = req.getHeader(userHeader);
                if (remoteUser != null) {
                    if (!org.apache.commons.codec.binary.Base64.isBase64(remoteUser)) {
                        try {
                            remoteUser = new String(remoteUser.getBytes("ISO-8859-1"), "UTF-8");
                        } catch (UnsupportedEncodingException e) {
                            // TODO
                        }
                    }
                    remoteUser = extractUserFromProxyHeader(remoteUser);
                } else {
                    remoteUser = super.getRemoteUser();
                }
                return remoteUser;
            }

            /**
             * Extracts a user ID from the proxy header. If a user ID pattern has been configured returns the contents of the
             * first matching regular expression group or <code>null</code>. Otherwise returns the trimmed header contents or
             * <code>null</code>.
             */
            private String extractUserFromProxyHeader(String userId) {
                if (userIdPattern == null) {
                    userId = userId.trim();
                } else {
                    Matcher matcher = userIdPattern.matcher(userId);
                    if (matcher.matches()) {
                        userId = matcher.group(1).trim();
                    } else {
                        return null;
                    }
                }
                return userId.length() == 0 ? null : userId;
            }
        };
    }
    return sreq;
}

From source file:org.ambraproject.util.VersionedFileDirective.java

/**
 * Resolves the filesystem path based on a web request path.  This is made complicated by
 * {@link org.ambraproject.web.VirtualJournalMappingFilter}, which remaps certain paths to journal-specific paths.
 *
 * @param path The original web request path
 * @param request The request object we're currently serving.  Note that this request will have a different path
 *     than the path param./*  www.j  a v a2  s. c om*/
 * @return The path to the resource on the filesystem
 * @throws ServletException
 */
private String getRealPath(final String path, HttpServletRequest request) throws ServletException {
    VirtualJournalContext vjc = (VirtualJournalContext) request
            .getAttribute(VirtualJournalContext.PUB_VIRTUALJOURNAL_CONTEXT);
    ServletContext servletContext = request.getSession().getServletContext();

    // This is somewhat of a hack.  VirtualJournalContext.mapRequest was originally written to be called with an
    // HttpServletRequest (supplied by VirtualJournalMappingFilter).  To reuse the code, we create a fake request
    // for the resource in question, populating only the fields that matter.
    HttpServletRequest fakeRequest = new HttpServletRequestWrapper(request) {
        public String getRequestURI() {
            return path;
        }

        public String getContextPath() {
            return "";
        }

        public String getServletPath() {
            return path;
        }

        public String getPathInfo() {
            return null;
        }
    };
    Configuration configuration = ConfigurationStore.getInstance().getConfiguration();
    HttpServletRequest mappedRequest = vjc.mapRequest(fakeRequest, configuration, servletContext);

    // If getPathInfo is null, the request was not remapped, and is intended to be served from the root context.  In
    // that case we can get the real path from the ServletContext.
    return mappedRequest.getPathInfo() != null ? mappedRequest.getPathInfo() : servletContext.getRealPath(path);
}

From source file:org.ambraproject.web.DummySSOFilter.java

protected HttpServletRequest wrapRequest(HttpServletRequest request, final String user) {
    final Principal principal = (user == null) ? null : new Principal() {
        public String getName() {
            return user;
        }//from w ww  .jav  a2s . com
    };

    return new HttpServletRequestWrapper(request) {
        public String getRemoteUser() {
            return user;
        }

        public Principal getUserPrincipal() {
            return principal;
        }
    };
}

From source file:org.ambraproject.web.VirtualJournalContext.java

/**
 * Wrap an HttpServletRequest with arbitrary URI values.
 *
 * @param request the request to wrap//  ww  w.j av  a  2 s .  co  m
 * @param paths the paths to substitute
 *
 * @return the wrapped request instance
 *
 * @throws IllegalArgumentException DOCUMENT ME!
 */
public static HttpServletRequest wrapRequest(final HttpServletRequest request, final String[] paths) {
    if ((paths == null) || (paths.length != 4))
        throw new IllegalArgumentException("Invalid path list");

    return new HttpServletRequestWrapper(request) {
        public String getRequestURI() {
            return paths[3];
        }

        public String getContextPath() {
            return paths[0];
        }

        public String getServletPath() {
            return paths[1];
        }

        public String getPathInfo() {
            return paths[2];
        }
    };
}

From source file:org.apache.atlas.web.filters.AtlasAuthenticationFilter.java

/**
 * This method is copied from hadoop auth lib, code added for error handling and fallback to other auth methods
 *
 * If the request has a valid authentication token it allows the request to continue to the target resource,
 * otherwise it triggers an authentication sequence using the configured {@link org.apache.hadoop.security.authentication.server.AuthenticationHandler}.
 *
 * @param request     the request object.
 * @param response    the response object.
 * @param filterChain the filter chain object.
 *
 * @throws IOException      thrown if an IO error occurred.
 * @throws ServletException thrown if a processing error occurred.
 *///from w w w  .j  a v a 2s.  c  o m
public void doKerberosAuth(ServletRequest request, ServletResponse response, FilterChain filterChainWrapper,
        FilterChain filterChain) throws IOException, ServletException {
    boolean unauthorizedResponse = true;
    int errCode = HttpServletResponse.SC_UNAUTHORIZED;
    AuthenticationException authenticationEx = null;
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    boolean isHttps = "https".equals(httpRequest.getScheme());
    AuthenticationHandler authHandler = getAuthenticationHandler();
    try {
        boolean newToken = false;
        AuthenticationToken token;
        try {
            token = getToken(httpRequest);
        } catch (AuthenticationException ex) {
            LOG.warn("AuthenticationToken ignored: {}", ex.getMessage());
            // will be sent back in a 401 unless filter authenticates
            authenticationEx = ex;
            token = null;
        }
        if (authHandler.managementOperation(token, httpRequest, httpResponse)) {
            if (token == null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Request [{}] triggering authentication", getRequestURL(httpRequest));
                }
                token = authHandler.authenticate(httpRequest, httpResponse);
                if (token != null && token.getExpires() != 0 && token != AuthenticationToken.ANONYMOUS) {
                    token.setExpires(System.currentTimeMillis() + getValidity() * 1000);
                }
                newToken = true;
            }
            if (token != null) {
                unauthorizedResponse = false;
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Request [{}] user [{}] authenticated", getRequestURL(httpRequest),
                            token.getUserName());
                }
                final AuthenticationToken authToken = token;
                httpRequest = new HttpServletRequestWrapper(httpRequest) {

                    @Override
                    public String getAuthType() {
                        return authToken.getType();
                    }

                    @Override
                    public String getRemoteUser() {
                        return authToken.getUserName();
                    }

                    @Override
                    public Principal getUserPrincipal() {
                        return (authToken != AuthenticationToken.ANONYMOUS) ? authToken : null;
                    }
                };
                if (newToken && !token.isExpired() && token != AuthenticationToken.ANONYMOUS) {
                    String signedToken = signer.sign(token.toString());
                    createAuthCookie(httpResponse, signedToken, getCookieDomain(), getCookiePath(),
                            token.getExpires(), isHttps);
                }

                filterChainWrapper.doFilter(httpRequest, httpResponse);
            }
        } else {
            unauthorizedResponse = false;
        }
    } catch (AuthenticationException ex) {
        // exception from the filter itself is fatal
        errCode = HttpServletResponse.SC_FORBIDDEN;
        authenticationEx = ex;
        LOG.warn("Authentication exception: {}", ex.getMessage(), ex);
    }
    if (unauthorizedResponse) {
        if (!httpResponse.isCommitted()) {
            createAuthCookie(httpResponse, "", getCookieDomain(), getCookiePath(), 0, isHttps);
            // If response code is 401. Then WWW-Authenticate Header should be
            // present.. reset to 403 if not found..
            if ((errCode == HttpServletResponse.SC_UNAUTHORIZED)
                    && (!httpResponse.containsHeader(KerberosAuthenticator.WWW_AUTHENTICATE))) {
                errCode = HttpServletResponse.SC_FORBIDDEN;
            }
            if (authenticationEx == null) { // added this code for atlas error handling and fallback
                if (!supportKeyTabBrowserLogin && isBrowser(httpRequest.getHeader("User-Agent"))) {
                    filterChain.doFilter(request, response);
                } else {
                    boolean chk = true;
                    Collection<String> headerNames = httpResponse.getHeaderNames();
                    for (String headerName : headerNames) {
                        String value = httpResponse.getHeader(headerName);
                        if (headerName.equalsIgnoreCase("Set-Cookie") && value.startsWith("ATLASSESSIONID")) {
                            chk = false;
                            break;
                        }
                    }
                    String authHeader = httpRequest.getHeader("Authorization");
                    if (authHeader == null && chk) {
                        filterChain.doFilter(request, response);
                    } else if (authHeader != null && authHeader.startsWith("Basic")) {
                        filterChain.doFilter(request, response);
                    }
                }
            } else {
                httpResponse.sendError(errCode, authenticationEx.getMessage());
            }
        }
    }
}