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.codename1.corsproxy.CORSProxy.java

@Override
protected void copyRequestHeaders(HttpServletRequest servletRequest, HttpRequest proxyRequest) {

    HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper(servletRequest) {

        @Override/*from  w  w  w .  j  a  v a2  s . c o m*/
        public Enumeration<String> getHeaderNames() {
            Enumeration<String> names = super.getHeaderNames();
            Vector<String> filteredNames = new Vector<String>();
            boolean foundCookie = false;
            boolean foundRealCookie = false;
            while (names.hasMoreElements()) {
                String name = names.nextElement();
                Enumeration<String> vals = this.getHeaders(name);

                if (!name.equalsIgnoreCase("Referer") && !name.equalsIgnoreCase("Host")
                        && !name.equalsIgnoreCase("origin")) {
                    filteredNames.add(name);
                }
                if (name.equalsIgnoreCase("X-CN1-Cookie")) {
                    foundCookie = true;
                }
                if (name.equalsIgnoreCase("Cookie")) {
                    foundRealCookie = true;
                }
            }

            if (foundCookie && !foundRealCookie) {
                filteredNames.add("Cookie");
            }

            return filteredNames.elements();
        }

        @Override
        public Enumeration<String> getHeaders(String name) {

            Enumeration<String> headers = super.getHeaders(name);
            Vector<String> out = new Vector<String>();
            while (headers.hasMoreElements()) {
                out.add(headers.nextElement());
            }
            if ("Cookie".equalsIgnoreCase(name)) {
                Enumeration<String> xHeaders = getHeaders("X-CN1-Cookie");
                while (xHeaders.hasMoreElements()) {
                    out.add(xHeaders.nextElement());
                }
            }
            return out.elements();
        }

    };
    super.copyRequestHeaders(requestWrapper, proxyRequest);
}

From source file:io.fabric8.apiman.BearerTokenFilter.java

/**
 * Wrap the request to provide the principal.
 * /* w w  w . j  av a  2s. c  o m*/
 * @param request
 *            the request
 * @param principal
 *            the principal
 */
private HttpServletRequest wrapTheRequest(final ServletRequest request, final AuthPrincipal principal) {
    HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper((HttpServletRequest) request) {
        @Override
        public Principal getUserPrincipal() {
            return principal;
        }

        @Override
        public boolean isUserInRole(String role) {
            return principal.getRoles().contains(role);
        }

        @Override
        public String getRemoteUser() {
            return principal.getName();
        }
    };
    return wrapper;
}

From source file:de.zib.gndms.kit.monitor.GroovyMoniServlet.java

/**
 * Stream incoming HTTP multiparts to a monitor previously opened by the current user.
 *
 * @param servletRequest/*w w w.  j  a  v a 2  s  . c om*/
 * @param servletResponse
 * @throws ServletException
 * @throws IOException
 */
@Override
protected void doPost(@NotNull HttpServletRequest servletRequest, @NotNull HttpServletResponse servletResponse)
        throws ServletException, IOException {
    @NotNull
    HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper(servletRequest);

    try {
        verifyUserRole(servletRequest);

        String token = parseToken(requestWrapper);
        if (token.length() == 0)
            throw notAcceptable("Zero-length token");

        @NotNull
        HttpSession session = getSessionOrFail(servletRequest);
        final @NotNull GroovyMonitor monitor = lookupMonitorOrFail(servletRequest.getUserPrincipal(), session,
                token);

        monitor.evalParts(servletRequest, parseArgs(requestWrapper), shouldDecodeBase64(requestWrapper));
        servletResponse.setStatus(HttpServletResponse.SC_OK);
    } catch (ServletRuntimeException e) {
        e.sendToClient(servletResponse);
    }
}

From source file:com.github.peholmst.springsecuritydemo.servlet.SpringApplicationServlet.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    /*//from   w ww . j  a v a  2 s  .co m
     * Resolve the locale from the request
     */
    final Locale locale = localeResolver.resolveLocale(request);
    if (logger.isDebugEnabled()) {
        logger.debug("Resolved locale [" + locale + "]");
    }

    /*
     * Store the locale in the LocaleContextHolder, making it available to
     * Spring.
     */
    LocaleContextHolder.setLocale(locale);
    ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request);
    RequestContextHolder.setRequestAttributes(requestAttributes);
    try {
        /*
         * We need to override the request to return the locale resolved by
         * Spring.
         */
        super.service(new HttpServletRequestWrapper(request) {
            @Override
            public Locale getLocale() {
                return locale;
            }
        }, response);
    } finally {
        if (!locale.equals(LocaleContextHolder.getLocale())) {
            /*
             * The locale in LocaleContextHolder was changed during the
             * request, so we have to update the resolver.
             */
            if (logger.isDebugEnabled()) {
                logger.debug("Locale changed, updating locale resolver");
            }
            localeResolver.setLocale(request, response, LocaleContextHolder.getLocale());
        }
        LocaleContextHolder.resetLocaleContext();
        RequestContextHolder.resetRequestAttributes();
    }
}

From source file:com.nominanuda.web.http.ServletHelper.java

@SuppressWarnings("unchecked")
private HttpEntity buildEntity(HttpServletRequest servletRequest, final InputStream is, long contentLength,
        String ct, String cenc) throws IOException {
    if (ServletFileUpload.isMultipartContent(servletRequest)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items;
        try {/* w  w w . ja  v  a 2 s. c om*/
            items = upload.parseRequest(new HttpServletRequestWrapper(servletRequest) {
                public ServletInputStream getInputStream() throws IOException {
                    return new ServletInputStream() {
                        public int read() throws IOException {
                            return is.read();
                        }

                        public int read(byte[] arg0) throws IOException {
                            return is.read(arg0);
                        }

                        public int read(byte[] b, int off, int len) throws IOException {
                            return is.read(b, off, len);
                        }

                        //@Override
                        @SuppressWarnings("unused")
                        public boolean isFinished() {
                            Check.illegalstate.fail(NOT_IMPLEMENTED);
                            return false;
                        }

                        //@Override
                        @SuppressWarnings("unused")
                        public boolean isReady() {
                            Check.illegalstate.fail(NOT_IMPLEMENTED);
                            return false;
                        }

                        //@Override
                        @SuppressWarnings("unused")
                        public void setReadListener(ReadListener arg0) {
                            Check.illegalstate.fail(NOT_IMPLEMENTED);
                        }
                    };
                }
            });
        } catch (FileUploadException e) {
            throw new IOException(e);
        }
        MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        for (FileItem i : items) {
            multipartEntity.addPart(i.getFieldName(), new InputStreamBody(i.getInputStream(), i.getName()));
        }
        return multipartEntity;
    } else {
        InputStreamEntity entity = new InputStreamEntity(is, contentLength);
        entity.setContentType(ct);
        if (cenc != null) {
            entity.setContentEncoding(cenc);
        }
        return entity;
    }
}

From source file:com.example.AzureADResponseFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {
    try {//  ww w.  j a  v  a2  s.c  o  m

        String currentUri = AuthHelper.getCurrentUri(request);

        csrfToken = null;

        // check if user has a session
        if (!AuthHelper.isAuthenticated(request) && AuthHelper.containsAuthenticationData(request)) {

            // The current session does not have the authentication info and the request contains the authentication data.
            // This request comes from AzureAD login page after login process is completed.

            if (log.isTraceEnabled()) {
                log.trace("AuthHelper.isAuthenticated = false && AuthHelper.containsAuthenticationData = true");
            }

            Map<String, String> params = new HashMap<String, String>();
            for (String key : request.getParameterMap().keySet()) {
                params.put(key, request.getParameterMap().get(key)[0]);
            }

            String fullUrl = currentUri
                    + (request.getQueryString() != null ? "?" + request.getQueryString() : "");
            if (log.isTraceEnabled()) {
                log.trace("URL: " + fullUrl);
            }

            AuthenticationResponse authResponse = AuthenticationResponseParser.parse(new URI(fullUrl), params);
            if (log.isTraceEnabled()) {
                log.trace("authResponse = " + authResponse);
            }

            if (AuthHelper.isAuthenticationSuccessful(authResponse)) {
                if (log.isTraceEnabled()) {
                    log.trace("AuthHelper.isAuthenticationSuccessful = true");
                }

                // Retrieve authentication response.
                AuthenticationSuccessResponse oidcResponse = (AuthenticationSuccessResponse) authResponse;
                AuthenticationResult result = getAccessToken(oidcResponse.getAuthorizationCode(), currentUri);

                // Retrieve CSRF token (the state is our csrf token.)
                if (log.isDebugEnabled()) {
                    log.debug("oidcResponse.getState() = " + oidcResponse.getState());
                }
                csrfToken = oidcResponse.getState().getValue();

                // Store authenticated principal to spring security context holder.
                Authentication anAuthentication = new PreAuthenticatedAuthenticationToken(result.getUserInfo(),
                        null);
                anAuthentication.setAuthenticated(true);
                SecurityContextHolder.getContext().setAuthentication(anAuthentication);

                if (log.isDebugEnabled()) {
                    log.debug("SecurityContextHolder.getContext().getAuthentication() = "
                            + SecurityContextHolder.getContext().getAuthentication());
                }

                // Store authentication data to current session.
                AuthHelper.setAuthSessionObject(request, result);
            } else {
                if (log.isTraceEnabled()) {
                    log.trace("AuthHelper.isAuthenticationSuccessful = false");
                }

                AuthenticationErrorResponse oidcResponse = (AuthenticationErrorResponse) authResponse;
                throw new Exception(String.format("Request for auth code failed: %s - %s",
                        oidcResponse.getErrorObject().getCode(),
                        oidcResponse.getErrorObject().getDescription()));
            }
        }
    } catch (Throwable exc) {
        response.setStatus(500);
        request.setAttribute("error", exc.getMessage());
        response.sendRedirect(((HttpServletRequest) request).getContextPath() + error);
    }

    if (csrfToken != null) {
        // When csrf token is retrieved, create a dummy request and put this csrf token to the header.
        if (log.isDebugEnabled()) {
            log.debug("Create a dummy request and put csrf token in its header {}", csrfToken);
        }
        filterChain.doFilter(new HttpServletRequestWrapper(request) {
            @Override
            public String getHeader(String name) {
                if ("X-CSRF-TOKEN".equals(name)) {
                    if (log.isDebugEnabled()) {
                        log.debug("Read csrf token from request header: {}", csrfToken);
                    }
                    return csrfToken;
                }
                return super.getHeader(name);
            }
        }, response);
    } else {
        filterChain.doFilter(request, response);
    }
}

From source file:jp.aegif.alfresco.online_webdav.WebDAVMethod.java

/**
 * Set the request/response details//from   w w w. j  av a  2 s. c om
 * 
 * @param req
 *            HttpServletRequest
 * @param resp
 *            HttpServletResponse
 * @param registry
 *            ServiceRegistry
 * @param rootNode
 *            NodeRef
 */
public void setDetails(final HttpServletRequest req, HttpServletResponse resp, WebDAVHelper davHelper,
        NodeRef rootNode) {
    // Wrap the request so that it is 'retryable'. Calls to getInputStream() and getReader() will result in the
    // request body being read into an intermediate file.
    this.m_request = new HttpServletRequestWrapper(req) {

        @Override
        public ServletInputStream getInputStream() throws IOException {
            if (WebDAVMethod.this.m_reader != null) {
                throw new IllegalStateException("Reader in use");
            }
            if (WebDAVMethod.this.m_inputStream == null) {
                final FileInputStream in = new FileInputStream(getRequestBodyAsFile(req));
                WebDAVMethod.this.m_inputStream = new ServletInputStream() {

                    @Override
                    public int read() throws IOException {
                        return in.read();
                    }

                    @Override
                    public int read(byte b[]) throws IOException {
                        return in.read(b);
                    }

                    @Override
                    public int read(byte b[], int off, int len) throws IOException {
                        return in.read(b, off, len);
                    }

                    @Override
                    public long skip(long n) throws IOException {
                        return in.skip(n);
                    }

                    @Override
                    public int available() throws IOException {
                        return in.available();
                    }

                    @Override
                    public void close() throws IOException {
                        in.close();
                    }

                    @Override
                    public void mark(int readlimit) {
                        in.mark(readlimit);
                    }

                    @Override
                    public void reset() throws IOException {
                        in.reset();
                    }

                    @Override
                    public boolean markSupported() {
                        return in.markSupported();
                    }
                };
            }

            return WebDAVMethod.this.m_inputStream;
        }

        @Override
        public BufferedReader getReader() throws IOException {
            if (WebDAVMethod.this.m_inputStream != null) {
                throw new IllegalStateException("Input Stream in use");
            }
            if (WebDAVMethod.this.m_reader == null) {
                String encoding = req.getCharacterEncoding();
                WebDAVMethod.this.m_reader = new BufferedReader(
                        new InputStreamReader(new FileInputStream(getRequestBodyAsFile(req)),
                                encoding == null ? "ISO-8859-1" : encoding));
            }

            return WebDAVMethod.this.m_reader;
        }

    };
    this.m_response = resp;
    this.m_davHelper = davHelper;
    this.m_rootNodeRef = rootNode;

    this.m_strPath = m_davHelper.getRepositoryPath(m_request);
}

From source file:de.hybris.platform.secureportaladdon.interceptors.SecurePortalBeforeControllerHandler.java

/**
 * Method to handle the case that the referer of the request is empty. The execution of this method could be switched
 * off from project.properties./*from  www . jav a 2  s.  com*/
 */
protected HttpServletRequest hackRefererHeader(final HttpServletRequest request) {
    // Since the WebHttpSessionRequestCache of hybris uses the referer header, we need to make sure there is one.
    // If we access the site directly using something like powertools.local:9001/yb2bacceleratorstorefront/ we don't get a referer
    // header sent by the browser! Using the referer header is NOT recommended as it can be removed by firewalls, spoofed etc.
    return new HttpServletRequestWrapper(request) {
        @Override
        public String getHeader(final String name) {
            if (StringUtils.equalsIgnoreCase(name, HttpHeaders.REFERER)) {
                final String headerValue = super.getHeader(name);

                if (StringUtils.isNotBlank(headerValue)) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(String.format("Referer header is present! The saved request will use '%s'.",
                                headerValue));
                    }
                    return headerValue;
                } else {
                    final String url = request.getRequestURL().toString();

                    if (LOG.isDebugEnabled()) {
                        LOG.debug(String.format(
                                "Referer header is empty! Creating a the URL '%s' for the SavedRequest.", url));
                    }

                    return url;
                }
            }
            return super.getHeader(name);
        }
    };
}

From source file:com.iorga.iraj.security.AbstractSecurityFilter.java

protected void doFilterWhenSecurityOK(final HttpServletRequest httpRequest,
        final HttpServletResponse httpResponse, final FilterChain chain, final String accessKeyId,
        final S securityContext) throws IOException, ServletException {
    // By default, security OK, forward to next filter
    chain.doFilter(new HttpServletRequestWrapper(httpRequest) {
        @Override//w  w w.  ja  v  a2 s .  c o  m
        public Principal getUserPrincipal() {
            return securityContext;
        }
    }, httpResponse);
}