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.kuali.rice.krad.filter.TestingLoginFilter.java

/**
 * Looks for a login user request parameter and establishs a user session for that user, then simply
 * returns a login message./*from  w  w  w .j a v  a 2  s. c  o  m*/
 *
 * {@inheritDoc}
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;

    if (StringUtils.isBlank(request.getParameter("login_user"))) {
        return;
    }

    final String user = request.getParameter("login_user");

    UserSession userSession = new UserSession(user);
    httpServletRequest.getSession().setAttribute(KRADConstants.USER_SESSION_KEY, userSession);

    // wrap the request with the signed in user
    // UserLoginFilter and WebAuthenticationService will build the session
    request = new HttpServletRequestWrapper(httpServletRequest) {
        @Override
        public String getRemoteUser() {
            return user;
        }
    };

    response.getWriter().print("Login Successful.");
}

From source file:org.kuali.rice.krad.web.filter.DummyLoginFilter.java

private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    final UserSession session = KRADUtils.getUserSessionFromRequest(request);

    if (session == null) {
        loginRequired(request, response, chain);

        return;// www  .  j a  va 2s  .c o m

    } else {
        // Perform request as signed in user
        request = new HttpServletRequestWrapper(request) {
            @Override
            public String getRemoteUser() {
                return session.getPrincipalName();
            }
        };
    }
    chain.doFilter(request, response);
}

From source file:org.kuali.rice.krad.web.filter.DummyLoginFilter.java

private void performLoginAttempt(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    IdentityService auth = KimApiServiceLocator.getIdentityService();
    final String user = request.getParameter("__login_user");
    String password = request.getParameter("__login_pw");

    // if passwords are used, they cannot be blank
    if (showPassword && StringUtils.isBlank(password)) {
        handleInvalidLogin(request, response);
        return;/*from ww  w  . j a va  2  s  . c  o m*/
    }

    // Very simple password checking. Nothing hashed or encrypted. This is strictly for demonstration purposes only.
    //    password must have non null value on krim_prncpl_t record
    Principal principal = showPassword ? auth.getPrincipalByPrincipalNameAndPassword(user, password)
            : auth.getPrincipalByPrincipalName(user);
    if (principal == null) {
        handleInvalidLogin(request, response);
        return;
    }

    UserSession userSession = new UserSession(user);

    // Test if session was successfully build for this user
    if (userSession.getPerson() == null) {
        throw new AuthenticationException("Invalid User: " + user);
    }

    request.getSession().setAttribute(KRADConstants.USER_SESSION_KEY, userSession);

    // wrap the request with the signed in user
    // UserLoginFilter and WebAuthenticationService will build the session
    request = new HttpServletRequestWrapper(request) {
        @Override
        public String getRemoteUser() {
            return user;
        }
    };

    StringBuilder redirectUrl = new StringBuilder(
            ConfigContext.getCurrentContextConfig().getProperty(KRADConstants.APPLICATION_URL_KEY));
    redirectUrl.append(findTargetUrl(request));
    response.sendRedirect(redirectUrl.toString());
}

From source file:org.madsonic.controller.RESTController.java

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

            // Support old style ID parameters.
            if ("id".equals(name)) {
                return mapId(request.getParameter("id"));
            }

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

From source file:org.niord.proxy.web.MessageDetailsServlet.java

/**
 * Main GET method/*w  w  w.j av a2 s. c om*/
 * @param request servlet request
 * @param response servlet response
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    // Determine whether to return HTML or PDF
    boolean pdf = request.getServletPath().endsWith("pdf");

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

    // Read the request parameters
    String language = settings.language(request.getParameter("language"));

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

    try {
        // Get the messages in the given language for the requested provider
        List<MessageVo> messages = getMessages(request, language);
        String searchText = getSearchText(request, language, messages);

        // Register the attributes to be used on the JSP page
        request.setAttribute("messages", messages);
        request.setAttribute("searchText", searchText);
        request.setAttribute("lang", language);
        request.setAttribute("languages", Arrays.asList(settings.getLanguages()));
        request.setAttribute("language", language);
        request.setAttribute("locale", locale);
        request.setAttribute("timeZone", settings.getTimeZone());
        request.setAttribute("now", new Date());
        request.setAttribute("pdf", pdf);

        if (pdf) {
            generatePdfFile(request, response);
        } else {
            generateHtmlPage(request, response);
        }

    } catch (Exception e) {
        log.log(Level.SEVERE, "Error generating file " + request.getServletPath(), e);
        throw new ServletException("Error generating file " + request.getServletPath(), e);
    }
}

From source file:org.nuxeo.ecm.webengine.jaxrs.login.AuthenticationFilter.java

protected HttpServletRequest wrapRequest(HttpServletRequest request, LoginContext lc) {
    Set<Principal> set = lc.getSubject().getPrincipals();
    if (!set.isEmpty()) {
        final Principal principal = set.iterator().next();
        return new HttpServletRequestWrapper(request) {
            @Override/*from   w w w  .  jav a 2 s .  co  m*/
            public Principal getUserPrincipal() {
                return principal;
            }
        };
    }
    return request;
}

From source file:org.primeframework.mvc.parameter.RequestBodyWorkflowTest.java

@Test
public void multipleFiles() throws IOException, ServletException {
    String body = FileUtils.readFileToString(
            new File("src/test/java/org/primeframework/mvc/servlet/http-test-body-multiple-files.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);/*from   ww  w  .j a  va  2 s.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("userfiles").get(0).file), "test");
            assertEquals(FileUtils.readFileToString(files.get("userfiles").get(1).file), "test2");
        } 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.primeframework.mvc.parameter.RequestBodyWorkflowTest.java

@Test
public void parse() throws IOException, ServletException {
    HttpServletRequest request = createStrictMock(HttpServletRequest.class);
    expect(request.getParameterMap()).andReturn(new HashMap<>());
    expect(request.getContentType()).andReturn("application/x-www-form-urlencoded");
    String body = "param1=value1&param2=value2&param+space+key=param+space+value&param%2Bencoded%2Bkey=param%2Bencoded%2Bvalue";
    expect(request.getInputStream()).andReturn(new MockServletInputStream(body.getBytes()));
    expect(request.getContentLength()).andReturn(body.getBytes().length);
    expect(request.getCharacterEncoding()).andReturn("UTF-8");
    replay(request);//from  w w  w . j a va 2 s  . co  m

    WorkflowChain chain = createStrictMock(WorkflowChain.class);
    chain.continueWorkflow();
    replay(chain);

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

    @SuppressWarnings("unchecked")
    Map<String, String[]> actual = wrapper.getParameterMap();
    Map<String, String[]> expected = MapBuilder.<String, String[]>map().put("param1", new String[] { "value1" })
            .put("param2", new String[] { "value2" })
            .put("param space key", new String[] { "param space value" })
            .put("param+encoded+key", new String[] { "param+encoded+value" }).done();
    assertParameterMapsEquals(actual, expected);

    verify(request, chain);
}

From source file:org.primeframework.mvc.parameter.RequestBodyWorkflowTest.java

@Test
public void parseCombine() throws IOException, ServletException {
    Map<String, String[]> oldParams = new HashMap<>();
    oldParams.put("param1", new String[] { "oldvalue1", "oldvalue2" });
    oldParams.put("param2", new String[] { "oldvalue3" });

    String body = "param1=value1&param1=value2&param2=value3";
    HttpServletRequest request = createStrictMock(HttpServletRequest.class);
    expect(request.getParameterMap()).andReturn(oldParams);
    expect(request.getContentType()).andReturn("application/x-www-form-urlencoded");
    expect(request.getInputStream()).andReturn(new MockServletInputStream(body.getBytes()));
    expect(request.getContentLength()).andReturn(body.getBytes().length);
    expect(request.getCharacterEncoding()).andReturn("UTF-8");
    replay(request);/*w  ww.j  a  v  a2s.  co  m*/

    WorkflowChain chain = createStrictMock(WorkflowChain.class);
    chain.continueWorkflow();
    replay(chain);

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

    @SuppressWarnings("unchecked")
    Map<String, String[]> actual = wrapper.getParameterMap();
    Map<String, String[]> expected = MapBuilder.<String, String[]>map()
            .put("param1", new String[] { "oldvalue1", "oldvalue2", "value1", "value2" })
            .put("param2", new String[] { "oldvalue3", "value3" }).done();
    assertParameterMapsEquals(actual, expected);

    verify(request, chain);
}

From source file:org.primeframework.mvc.parameter.RequestBodyWorkflowTest.java

@Test
public void parseMultiple() throws IOException, ServletException {
    String body = "param1=value1&param1=value2&param2=value3";
    HttpServletRequest request = createStrictMock(HttpServletRequest.class);
    expect(request.getParameterMap()).andReturn(new HashMap<>());
    expect(request.getContentType()).andReturn("application/x-www-form-urlencoded");
    expect(request.getInputStream()).andReturn(new MockServletInputStream(body.getBytes()));
    expect(request.getContentLength()).andReturn(body.getBytes().length);
    expect(request.getCharacterEncoding()).andReturn("UTF-8");
    replay(request);/*  w w  w.j  a v  a 2  s .  co  m*/

    WorkflowChain chain = createStrictMock(WorkflowChain.class);
    chain.continueWorkflow();
    replay(chain);

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

    @SuppressWarnings("unchecked")
    Map<String, String[]> actual = wrapper.getParameterMap();
    Map<String, String[]> expected = MapBuilder.<String, String[]>map()
            .put("param1", new String[] { "value1", "value2" }).put("param2", new String[] { "value3" }).done();
    assertParameterMapsEquals(actual, expected);

    verify(request, chain);
}