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.primeframework.mvc.parameter.RequestBodyWorkflowTest.java

@Test
public void singleFiles() throws IOException, ServletException {
    String body = FileUtils.readFileToString(
            new File("src/test/java/org/primeframework/mvc/servlet/http-test-body-single-file.txt"));

    HttpServletRequest request = EasyMock.createStrictMock(HttpServletRequest.class);
    EasyMock.expect(request.getParameterMap()).andReturn(new HashMap<>());
    EasyMock.expect(request.getContentType()).andReturn("multipart/form-data, boundary=AaB03x").times(2);
    EasyMock.expect(request.getInputStream()).andReturn(new MockServletInputStream(body.getBytes()));
    EasyMock.expect(request.getCharacterEncoding()).andReturn("UTF-8");
    EasyMock.expect(request.getContentLength()).andReturn(body.length());
    final Capture<Map<String, List<FileInfo>>> capture = new Capture<>();
    request.setAttribute(eq(RequestKeys.FILE_ATTRIBUTE), capture(capture));
    EasyMock.replay(request);/*w w  w . jav a 2s  . c  o m*/

    final AtomicBoolean run = new AtomicBoolean(false);
    MockWorkflowChain chain = new MockWorkflowChain(() -> {
        Map<String, List<FileInfo>> files = capture.getValue();
        assertEquals(files.size(), 1);
        try {
            assertEquals(FileUtils.readFileToString(files.get("userfile").get(0).file), "test");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        run.set(true);
    });

    HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request);
    RequestBodyWorkflow workflow = new RequestBodyWorkflow(wrapper);
    workflow.perform(chain);
    assertTrue(run.get());

    assertEquals(wrapper.getParameter("field1"), "value1");
    assertEquals(wrapper.getParameter("field2"), "value2");

    EasyMock.verify(request);
}

From source file:org.projectforge.business.user.filter.UserFilter.java

/**
 * @param request//from   w  w  w. j a  v a 2 s  .co  m
 * @return
 */
protected HttpServletRequest decorateWithLocale(HttpServletRequest request) {
    final Locale locale = ThreadLocalUserContext.getLocale(request.getLocale());
    request = new HttpServletRequestWrapper(request) {
        @Override
        public Locale getLocale() {
            return locale;
        }

        @Override
        public Enumeration<Locale> getLocales() {
            return Collections.enumeration(Collections.singleton(locale));
        }
    };
    return request;
}

From source file:org.projectforge.web.UserFilter.java

/**
 * @param request//from ww w  .  j  a va  2s.  c  om
 * @param user
 * @return
 */
protected HttpServletRequest decorateWithLocale(HttpServletRequest request, final PFUserDO user) {
    final Locale locale = PFUserContext.getLocale(request.getLocale());
    request = new HttpServletRequestWrapper(request) {
        @Override
        public Locale getLocale() {
            return locale;
        }

        @Override
        public Enumeration<?> getLocales() {
            return Collections.enumeration(Collections.singleton(locale));
        }
    };
    return request;
}

From source file:org.saiku.plugin.EnunciateJerseyPluginServlet.java

@Override
public void service(final 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  a2  s .c  o  m*/
        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/", ""));
        }

        @Override
        public Map getParameterMap() {
            return request.getParameterMap();
        }

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

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

From source file:org.sakaiproject.gradebook.gwt.server.WebAppToolServlet.java

protected void service(final HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // GRBK-908/*w ww.jav a  2s . c  o m*/
    if (null == sessionManager) {

        log.error("ERROR: SessionManager is null");
    } else {

        String currentSessionId = sessionManager.getCurrentSession().getId();
        String currentToken = (String) sessionManager.getCurrentSession().getAttribute(AppConstants.GB2_TOKEN);
        Cookie cookie = getCookie(request.getCookies());

        /*
         *  Creating a new GB2 TOKEN if:
         *  1: During bootstrapping time, fist access
         *  2: User deleted cookies
         */
        if (((null == currentToken || "".equals(currentToken)) && null != currentSessionId)
                || (null == cookie && null != currentSessionId)) {

            String hexCurrentSessionId = DigestUtils.md5Hex(currentSessionId.getBytes());

            String uuid = java.util.UUID.randomUUID().toString();
            String gb2Token = new StringBuilder(uuid).append("-").append(hexCurrentSessionId).toString();

            sessionManager.getCurrentSession().setAttribute(AppConstants.GB2_TOKEN, gb2Token);

            // If the cookie exists, we just change its value, otherwise we create a new one
            if (null != cookie) {

                cookie.setValue(gb2Token);
                cookie.setPath("/");
                cookie.setMaxAge(-1);
            } else {

                cookie = new Cookie(AppConstants.GB2_TOKEN, gb2Token);
                cookie.setPath("/");
                cookie.setMaxAge(-1);
            }

            response.addCookie(cookie);
        }
    }

    final String contextPath = request.getContextPath();
    request.setAttribute(Tool.NATIVE_URL, Tool.NATIVE_URL);
    HttpServletRequest wrappedRequest = new HttpServletRequestWrapper(request) {
        public String getContextPath() {
            return contextPath;
        }
    };

    if (request.getPathInfo() == null && getInitParameter(FIRST_PAGE) != null
            && !getInitParameter(FIRST_PAGE).equals("/")) {

        String uri = new StringBuilder().append(contextPath).append(getInitParameter(FIRST_PAGE)).toString();

        addVersionAsCookie(response, contextPath);
        // Set locale preferences for user
        uri = uri + "?locale=" + rb.getLocale();

        // Do redirect to first-page
        response.sendRedirect(uri);
    } else if (request.getPathInfo() == null && !request.getRequestURI().endsWith("/")) {
        String uri = new StringBuilder().append(contextPath).append("/").toString();

        // we should do the default redirect to "/"
        response.sendRedirect(uri);
    } else if (request.getPathInfo() != null
            && (request.getPathInfo().startsWith("/WEB-INF/") || request.getPathInfo().equals("/WEB-INF"))) {
        String uri = new StringBuilder().append(contextPath).append("/").toString();

        // Can't allow people to see WEB-INF
        response.sendRedirect(uri);
    } else {
        // otherwise do the dispatch
        RequestDispatcher dispatcher;
        if (request.getPathInfo() == null) {
            dispatcher = request.getRequestDispatcher("");
        } else {
            dispatcher = request.getRequestDispatcher(request.getPathInfo());
        }

        dispatcher.forward(wrappedRequest, response);
    }

}

From source file:org.sakaiproject.mbm.servlet.SakaiToolServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    if (log.isDebugEnabled()) {
        StringBuilder headers = new StringBuilder("Headers [");
        StringBuilder params = new StringBuilder("Params [");

        Enumeration<String> headerNames = req.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String s = headerNames.nextElement();
            headers.append(s).append("={")
                    .append(StringUtils.isNotEmpty(req.getHeader(s)) ? req.getHeader(s) : "null").append("},");
        }/*from w ww.  j  a va 2 s  . c  o m*/
        headers.append("]");

        Enumeration<String> paramNames = req.getParameterNames();
        while (paramNames.hasMoreElements()) {
            String s = paramNames.nextElement();
            params.append(s).append("={")
                    .append(StringUtils.isNotEmpty(req.getParameter(s)) ? req.getParameter(s) : "null")
                    .append("},");
        }
        params.append("]");

        log.debug(new StringBuilder()
                .append("SakaiToolServlet: service(HttpServletRequest, HttpServletResponse)\n")
                .append("context path = ").append(req.getContextPath()).append("\n").append("request path = ")
                .append(StringUtils.isNotEmpty(req.getPathInfo()) ? req.getPathInfo() : "null").append("\n")
                .append("headers      = ").append(headers).append("\n").append("params       = ").append(params)
                .append("\n").append("content type = ")
                .append(StringUtils.isNotEmpty(req.getContentType()) ? req.getContentType() : "null")
                .append("\n").append("method       = ").append(req.getMethod()).append("\n")
                .append("query        = ")
                .append(StringUtils.isNotEmpty(req.getQueryString()) ? req.getQueryString() : "null")
                .append("\n").append("request url  = ").append(req.getRequestURL()).append("\n")
                .append("request uri  = ").append(req.getRequestURI()).append("\n").append("locale       = ")
                .append(req.getLocale()).append("\n"));
    }

    final String startPage = StringUtils.isNotEmpty(getInitParameter("index")) ? getInitParameter("index")
            : "/";
    final String contextPath = req.getContextPath();

    req.setAttribute(Tool.NATIVE_URL, Tool.NATIVE_URL);

    HttpServletRequest wrappedReq = new HttpServletRequestWrapper(req) {
        public String getContextPath() {
            return contextPath;
        }
    };

    if (StringUtils.isEmpty(req.getPathInfo())) {
        resp.sendRedirect(contextPath + startPage);
    } else {
        RequestDispatcher dispatcher;
        if (StringUtils.isEmpty(req.getPathInfo())) {
            dispatcher = req.getRequestDispatcher("/");
        } else {
            dispatcher = req.getRequestDispatcher(req.getPathInfo());
        }
        dispatcher.forward(wrappedReq, resp);
    }
}

From source file:org.sakaiproject.tool.messageforums.FileUploadFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (!(request instanceof HttpServletRequest)) {
        chain.doFilter(request, response);
        return;/*from  w  w  w . java  2  s.co m*/
    }

    HttpServletRequest httpRequest = (HttpServletRequest) request;

    boolean isMultipartContent = FileUpload.isMultipartContent(httpRequest);
    if (!isMultipartContent) {
        chain.doFilter(request, response);
        return;
    }

    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);
            String str = item.getString();
            if (item.isFormField()) {
                map.put(item.getFieldName(), new String[] { str });
            } else {
                httpRequest.setAttribute(item.getFieldName(), item);
            }
        }

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

            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) {
        ServletException servletEx = new ServletException();
        servletEx.initCause(ex);
        throw servletEx;
    }
}

From source file:org.sakaiproject.tool.syllabus.FileUploadFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (!(request instanceof HttpServletRequest)) {
        chain.doFilter(request, response);
        return;//from   w  w w. j ava2s.co  m
    }

    HttpServletRequest httpRequest = (HttpServletRequest) request;

    boolean isMultipartContent = FileUpload.isMultipartContent(httpRequest);
    if (!isMultipartContent) {
        chain.doFilter(request, response);
        return;
    }

    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);
            String str = item.getString();
            if (item.isFormField())
                map.put(item.getFieldName(), new String[] { str });
            else
                httpRequest.setAttribute(item.getFieldName(), item);
        }

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

            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) {
        ServletException servletEx = new ServletException();
        servletEx.initCause(ex);
        throw servletEx;
    }
}

From source file:org.sonatype.nexus.extdirect.internal.ExtDirectServlet.java

@Override
public void doPost(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
    HttpServletRequest wrappedRequest = new HttpServletRequestWrapper(request) {
        private BufferedReader reader;

        @Override//from w w  w  .  j  a  v a2  s .co  m
        public BufferedReader getReader() throws IOException {
            if (reader == null) {
                try {
                    reader = super.getReader();
                } catch (IllegalStateException e) {
                    // HACK avoid "java.lang.IllegalStateException: STREAMED" which is thrown in case of request.getReader()
                    // and request.getInputStream() was already called as in case of getting request parameters
                    reader = new RequestBoundReader(new InputStreamReader(getInputStream(), EncodingUtils.UTF8),
                            request);
                }
            }
            return reader;
        }
    };
    super.doPost(wrappedRequest, response);
}

From source file:org.springframework.security.kerberos.web.authentication.SpnegoEntryPoint.java

public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex)
        throws IOException, ServletException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Add header WWW-Authenticate:Negotiate to " + request.getRequestURL() + ", forward: "
                + (forward ? forwardUrl : "no"));
    }//from   w  w  w .j a va2s .  co  m
    response.addHeader("WWW-Authenticate", "Negotiate");
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

    if (forward) {
        RequestDispatcher dispatcher = request.getRequestDispatcher(forwardUrl);

        dispatcher.forward(new HttpServletRequestWrapper(request) {
            @Override
            public String getMethod() {
                return forwardMethod.name();
            }
        }, response);
    } else {
        response.flushBuffer();
    }
}