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:org.vaadin.webinars.springandvaadin.i18n.ui.Servlet.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    final Locale locale = localeResolver.resolveLocale(request);
    LocaleContextHolder.setLocale(locale);
    ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request);
    RequestContextHolder.setRequestAttributes(requestAttributes);
    try {// w ww  . j a  v a2s. c  om
        super.service(new HttpServletRequestWrapper(request) {
            @Override
            public Locale getLocale() {
                return locale;
            }
        }, response);
    } finally {
        if (!locale.equals(LocaleContextHolder.getLocale())) {
            localeResolver.setLocale(request, response, LocaleContextHolder.getLocale());
        }
        LocaleContextHolder.resetLocaleContext();
        RequestContextHolder.resetRequestAttributes();
    }
}

From source file:org.mvnsearch.vaadin.AdminEndPoint.java

@RequestMapping("**")
public ModelAndView handle(HttpServletRequest request, HttpServletResponse response) throws Exception {

    request = new HttpServletRequestWrapper(request) {
        @Override/*w w w .ja v  a2  s  .c o  m*/
        public String getPathInfo() {
            return stripAdminPrefix(super.getPathInfo());
        }

        @Override
        public String getRequestURI() {
            return stripAdminPrefix(super.getRequestURI());
        }

        private String stripAdminPrefix(String pathInfo) {
            if (pathInfo != null && pathInfo.startsWith(ADMIN_PATH)) {
                pathInfo = pathInfo.substring(ADMIN_PATH.length());
            }
            return pathInfo;
        }
    };
    return servletController.handleRequest(request, response);
}

From source file:com.marvelution.hudson.plugins.apiv2.servlet.filter.HudsonAPIV2ServletFilter.java

/**
 * {@inheritDoc}//  w  w  w.ja v a  2s  .c o m
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    // The Wink RestFilter can only handle HttpServletRequests so make sure we have one
    if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
        // Put the original HttpServletRequest in the HttpServletRequestWrapper
        final HttpServletRequestWrapper servletRequest = new HttpServletRequestWrapper(
                (HttpServletRequest) request);
        // Get the requestUri without the context path and the leading slash
        String requestUri = servletRequest.getPathInfo();
        if (StringUtils.isNotBlank(requestUri) && requestUri.startsWith("/")) {
            requestUri = requestUri.substring(1);
        }
        LOGGER.log(Level.FINE, "Got a request from URI: " + requestUri + " with Accept Header: "
                + servletRequest.getHeader("Accept"));
        // Make sure it is a REST call
        if (StringUtils.isNotBlank(requestUri) && requestUri.startsWith(BaseRestResource.BASE_REST_URI)) {
            validateRuntimeDelegate();
            LOGGER.log(Level.FINE, "Got a REST request, forwarding it to the Wink RestFilter");
            FilteredHttpServletResponse servletResponse = new FilteredHttpServletResponse(
                    (HttpServletResponse) response);
            restServlet.service(servletRequest, servletResponse);
            if ((!(servletResponse.isCommitted())) && (servletResponse.getStatusCode() == 404)) {
                LOGGER.log(Level.FINE, "Filter " + this.getClass().getName()
                        + " did not match a resource so letting request continue on FilterChain");
                servletResponse.setStatus(200);
                filterChain.doFilter(request, response);
            }
            // Otherwise forward the request to the next Filter in the chain
        } else {
            LOGGER.log(Level.FINE, "No REST request, forwarding request to the next ServletFilter");
            filterChain.doFilter(request, response);
        }
        // If we don't have a HttpServletRequest and HttpServletResponse then forward to the next Filter in the chain
    } else {
        LOGGER.log(Level.FINE,
                "No HttpServletRequest and HttpServletResponse, forwarding request to the next ServletFilter");
        filterChain.doFilter(request, response);
    }
}

From source file:AIR.Common.Web.Session.CaseInsensitiveFileNameFilter.java

@Override
public void doFilter(ServletRequest wrappedRequest, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) wrappedRequest;
    String servletPath = request.getServletPath();
    String requestedPath = servletPath;

    boolean remapped = false;
    boolean needsSeparateRequestDispatcher = false;

    // first do extensions mapping. this way if we need to take care of casing
    // we will do that in the later step.
    _Ref<String> extensionMappedString = new _Ref<String>();
    if (getExtensionRemap(servletPath, extensionMappedString)) {
        servletPath = extensionMappedString.get();
        remapped = needsSeparateRequestDispatcher = true;
    }//from   ww  w.j a v a2 s  .com
    String remappedServletPath = servletPath;

    // now we can do case insensitive path name mapping.
    if (_pathMap.containsKey(servletPath)) {
        remappedServletPath = _pathMap.get(servletPath);
        remapped = true;
    } else if (isMatchForRewriting(servletPath)) {
        remappedServletPath = remapUri(servletPath);
        if (!StringUtils.equals(remappedServletPath, servletPath)) {
            _pathMap.put(servletPath, remappedServletPath);
            remapped = true;
        }
    }

    if (remapped) {
        final String remappedServletPathFinal = remappedServletPath;
        HttpServletRequestWrapper modifiedHttpRequest = new HttpServletRequestWrapper(request) {
            @Override
            public String getServletPath() {
                return remappedServletPathFinal;
            }

            @Override
            public String getRequestURI() {
                return Path.combine(Server.getContextPath(), remappedServletPathFinal, "/");
            }

        };
        request = modifiedHttpRequest;
        if (needsSeparateRequestDispatcher) {
            // Sajib/Shiva: This is the only way to handle aspx to xhtml
            // transformations where
            // the xhtml is a real JSF page but this may be expensive as we may
            // already have gone
            // down other filtering chains. We are doing this as a last resort.
            _logger.warn(String.format(
                    "Redispatching as there was an extension transformation. Original URI %s. New URI %s",
                    requestedPath, remappedServletPath));
            request.getRequestDispatcher(request.getRequestURI()).forward(request, response);
        }
    }

    chain.doFilter(request, response);
}

From source file:org.apache.hadoop.security.AuthenticationWithProxyUserFilter.java

/**
 * This method provide the ability to do pre/post tasks
 * in filter chain. Override this method to authorize
 * proxy user between AuthenticationFilter and next filter.
 * @param filterChain the filter chain object.
 * @param request the request object./*from w w w  .j av a 2s  .c  o m*/
 * @param response the response object.
 *
 * @throws IOException
 * @throws ServletException
 */
@Override
protected void doFilter(FilterChain filterChain, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    // authorize proxy user before calling next filter.
    String proxyUser = getDoAs(request);
    if (proxyUser != null) {
        UserGroupInformation realUser = UserGroupInformation.createRemoteUser(request.getRemoteUser());
        UserGroupInformation proxyUserInfo = UserGroupInformation.createProxyUser(proxyUser, realUser);

        try {
            ProxyUsers.authorize(proxyUserInfo, request.getRemoteAddr());
        } catch (AuthorizationException ex) {
            HttpExceptionUtils.createServletExceptionResponse(response, HttpServletResponse.SC_FORBIDDEN, ex);
            // stop filter chain if there is an Authorization Exception.
            return;
        }

        final UserGroupInformation finalProxyUser = proxyUserInfo;
        // Change the remote user after proxy user is authorized.
        request = new HttpServletRequestWrapper(request) {
            @Override
            public String getRemoteUser() {
                return finalProxyUser.getUserName();
            }
        };

    }
    filterChain.doFilter(request, response);
}

From source file:dk.dma.msiproxy.web.MessageDetailsServlet.java

/**
 * Main GET method/*from w  w  w .ja va 2  s  . c  o m*/
 * @param request servlet request
 * @param response servlet response
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    // Never cache the response
    response = WebUtils.nocache(response);

    // Read the request parameters
    String providerId = request.getParameter("provider");
    String lang = request.getParameter("lang");
    String messageId = request.getParameter("messageId");
    String activeNow = request.getParameter("activeNow");
    String areaHeadingIds = request.getParameter("areaHeadings");

    List<AbstractProviderService> providerServices = providers.getProviders(providerId);

    if (providerServices.size() == 0) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid 'provider' parameter");
        return;
    }

    // Ensure that the language is valid
    lang = providerServices.get(0).getLanguage(lang);

    // Force the encoding and the locale based on the lang parameter
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    final Locale locale = new Locale(lang);
    request = new HttpServletRequestWrapper(request) {
        @Override
        public Locale getLocale() {
            return locale;
        }
    };

    // Get the messages in the given language for the requested provider
    MessageFilter filter = new MessageFilter().lang(lang);
    Date now = "true".equals(activeNow) ? new Date() : null;
    Integer id = StringUtils.isNumeric(messageId) ? Integer.valueOf(messageId) : null;
    Set<Integer> areaHeadings = StringUtils.isNotBlank(areaHeadingIds) ? Arrays
            .asList(areaHeadingIds.split(",")).stream().map(Integer::valueOf).collect(Collectors.toSet())
            : null;

    List<Message> messages = providerServices.stream().flatMap(p -> p.getCachedMessages(filter).stream())
            // Filter on message id
            .filter(msg -> (id == null || id.equals(msg.getId())))
            // Filter on active messages
            .filter(msg -> (now == null || msg.getValidFrom() == null || msg.getValidFrom().before(now)))
            // Filter on area headings
            .filter(msg -> (areaHeadings == null || areaHeadings.contains(getAreaHeadingId(msg))))
            .collect(Collectors.toList());

    // Register the attributes to be used on the JSP apeg
    request.setAttribute("messages", messages);
    request.setAttribute("baseUri", app.getBaseUri());
    request.setAttribute("lang", lang);
    request.setAttribute("locale", locale);
    request.setAttribute("provider", providerId);

    if (request.getServletPath().endsWith("pdf")) {
        generatePdfFile(request, response);
    } else {
        generateHtmlPage(request, response);
    }
}

From source file:org.pentaho.plugin.j2ee.EnunciateJerseyPluginServlet.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("servicing request for resource " + request.getPathInfo()); //$NON-NLS-1$
    //Strip out the content generator id from the URL here so Jersey can match the @Path of the resource
    HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request) {

        @Override/*from ww  w  . j  a  v a  2  s .  com*/
        public String getRequestURI() {
            String uri = super.getRequestURI().replace("content/", "");
            return uri;
        }

        @Override
        public StringBuffer getRequestURL() {
            String url = super.getRequestURL().toString();
            return new StringBuffer(url.replace("content/", ""));
        }

    };
    super.service(wrapper, response);
}

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

/**
 * One of six things may happen here after succesful authorization:
 *
 * If m is empty, a new session is establised.
 * If m is "refresh", monitorServer.refresh() is a called
 * If m is "restart", monitorServer.restart() is a called
 * If m is "close", monitor with id of parameter "token" is closed,
 * If m is "shutdown", current user's session is shutdown and all associated monitors closed,
 * Otherwise, a new monitor with id of parameter "token" is created for the current user.
 *
 * @param request//from  www.  j a va  2  s . c o m
 * @param response
 * @throws IOException
 */
@Override
public void doGet(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response)
        throws IOException {
    @NotNull
    final HttpServletRequestWrapper reqWrapper = new HttpServletRequestWrapper(request);

    try {
        // authorization
        verifyUserRole(request);

        if (contAftOperatingSrvIfRequested(reqWrapper, response)) {
            if (didDestroySessionOnRequest(reqWrapper))
                response.setStatus(HttpServletResponse.SC_OK);
            else {
                final String token = parseToken(reqWrapper);
                if (token.length() == 0)
                    // create new session of token is empty and none is existing
                    createNewSession(request, response);
                else
                    establishNewMonitor(response, reqWrapper, token, getSessionOrFail(request));
            }
        }
    } catch (ServletRuntimeException e) {
        e.sendToClient(response);
    }
}

From source file:com.corejsf.UploadFilter.java

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

    //System.out.println("**** doFilter #1");
    if (!(request instanceof HttpServletRequest)) {
        chain.doFilter(request, response);
        return;/*www  .  j a  va2 s .co  m*/
    }

    //System.out.println("**** doFilter #2");
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    boolean isMultipartContent = FileUpload.isMultipartContent(httpRequest);
    if (!isMultipartContent) {
        chain.doFilter(request, response);
        return;
    }

    //System.out.println("**** doFilter #3");
    DiskFileUpload upload = new DiskFileUpload();
    if (repositoryPath != null)
        upload.setRepositoryPath(repositoryPath);

    try {
        List list = upload.parseRequest(httpRequest);
        final Map map = new HashMap();
        for (int i = 0; i < list.size(); i++) {
            FileItem item = (FileItem) list.get(i);
            //System.out.println("form filed="+item.getFieldName()+" : "+str);
            if (item.isFormField()) {
                String str = item.getString("UTF-8");
                map.put(item.getFieldName(), new String[] { str });
            } else {
                httpRequest.setAttribute(item.getFieldName(), item);
            }
        }

        chain.doFilter(new HttpServletRequestWrapper(httpRequest) {
            public Map getParameterMap() {
                return map;
            }

            // busywork follows ... should have been part of the wrapper
            public String[] getParameterValues(String name) {
                Map map = getParameterMap();
                return (String[]) map.get(name);
            }

            public String getParameter(String name) {
                String[] params = getParameterValues(name);
                if (params == null)
                    return null;
                return params[0];
            }

            public Enumeration getParameterNames() {
                Map map = getParameterMap();
                return Collections.enumeration(map.keySet());
            }
        }, response);
    } catch (FileUploadException ex) {
        log.error(ex.getMessage());
        ServletException servletEx = new ServletException();
        servletEx.initCause(ex);
        throw servletEx;
    }
}