javax.servlet.http.HttpServletRequest

Here are the examples of the java api class javax.servlet.http.HttpServletRequest taken from open source projects.

1. DefaultCxfMessageMapperTest#testSecurityContext()

View license
@Test
public void testSecurityContext() {
    DefaultCxfMessageMapper mapper = new DefaultCxfMessageMapper();
    HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
    request.getUserPrincipal();
    EasyMock.expectLastCall().andReturn(new SimplePrincipal("barry"));
    request.isUserInRole("role1");
    EasyMock.expectLastCall().andReturn(true);
    request.isUserInRole("role2");
    EasyMock.expectLastCall().andReturn(false);
    EasyMock.replay(request);
    Exchange camelExchange = setupCamelExchange("/", "/", request);
    Message cxfMessage = mapper.createCxfMessageFromCamelExchange(camelExchange, EasyMock.createMock(HeaderFilterStrategy.class));
    SecurityContext sc = cxfMessage.get(SecurityContext.class);
    assertNotNull(sc);
    assertEquals("barry", sc.getUserPrincipal().getName());
    assertTrue(sc.isUserInRole("role1"));
    assertFalse(sc.isUserInRole("role2"));
}

2. SecurityFilter#doFilter()

Project: lorsource
Source File: SecurityFilter.java
View license
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    HttpServletRequest request = (HttpServletRequest) req;
    request.setAttribute("configuration", ctx.getBean(SiteConfig.class));
    request.setAttribute("template", new Template(ctx));
    // ???????? tomcat
    request.setCharacterEncoding("utf-8");
    res.setLocale(russian);
    CSRFManipulation(request, (HttpServletResponse) res);
    chain.doFilter(req, res);
}

3. RestRequestListener#execute()

Project: railo
Source File: RestRequestListener.java
View license
@Override
public PageSource execute(PageContext pc, PageSource requestedPage) throws PageException {
    result = mapping.getResult(pc, path, matrix, format, hasFormatExtension, accept, contentType, defaultValue);
    HttpServletRequest req = pc.getHttpServletRequest();
    req.setAttribute("client", "railo-rest-1-0");
    req.setAttribute("rest-path", path);
    req.setAttribute("rest-result", result);
    if (result == null) {
        RestUtil.setStatus(pc, 404, "no rest service for [" + path + "] found in mapping [" + mapping.getVirtual() + "]");
        return null;
    }
    return result.getSource().getPageSource();
}

4. TestPKIAuthenticationPlugin#createMockRequest()

View license
private HttpServletRequest createMockRequest(final AtomicReference<Header> header) {
    HttpServletRequest mockReq = EasyMock.createMock(HttpServletRequest.class);
    EasyMock.reset(mockReq);
    mockReq.getHeader(EasyMock.anyObject(String.class));
    EasyMock.expectLastCall().andAnswer(() -> {
        if (PKIAuthenticationPlugin.HEADER.equals(getCurrentArguments()[0])) {
            if (header.get() == null)
                return null;
            return header.get().getValue();
        } else
            return null;
    }).anyTimes();
    mockReq.getUserPrincipal();
    EasyMock.expectLastCall().andAnswer(() -> null).anyTimes();
    mockReq.getRequestURI();
    EasyMock.expectLastCall().andAnswer(() -> "/collection1/select").anyTimes();
    EasyMock.replay(mockReq);
    return mockReq;
}

5. UserListWidget#handleQueryList()

View license
/**
     * @return The list of users.
     */
@Override
protected PageableList<DetailedUserData> handleQueryList() {
    HttpServletRequest request = getRequest();
    UserQueryParameters queryParameters = USER_QUERY.createInstance();
    configurator.configure(getParameters(), queryParameters, SessionHandler.instance().getCurrentLocale(request));
    queryParameters.setHideSelectedTags(false);
    queryParameters.setIncludeStatusFilter(new UserStatus[] { UserStatus.ACTIVE, UserStatus.TEMPORARILY_DISABLED, UserStatus.INVITED });
    queryParameters.addRoleToExclude(UserRole.ROLE_CRAWL_USER);
    PageableList<DetailedUserData> result = ServiceLocator.findService(QueryManagement.class).query(USER_QUERY, queryParameters, new ListUsersUserListItemQueryResultConverter());
    request.setAttribute("pageInformation", queryParameters.getPageInformation(result, 5));
    request.setAttribute("imageSmall", ImageSizeType.SMALL);
    setResponseMetadata("nextOffset", result.getOffset() + result.size());
    return result;
}

6. ServletSessionTokenStore#logout()

View license
@Override
public void logout() {
    final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    HttpServletRequest req = (HttpServletRequest) servletRequestContext.getServletRequest();
    req.removeAttribute(KeycloakUndertowAccount.class.getName());
    req.removeAttribute(KeycloakSecurityContext.class.getName());
    HttpSession session = req.getSession(false);
    if (session == null)
        return;
    try {
        KeycloakUndertowAccount account = (KeycloakUndertowAccount) session.getAttribute(KeycloakUndertowAccount.class.getName());
        if (account == null)
            return;
        session.removeAttribute(KeycloakSecurityContext.class.getName());
        session.removeAttribute(KeycloakUndertowAccount.class.getName());
    } catch (IllegalStateException ise) {
        log.debugf("Session %s logged-out already", session.getId());
    }
}

7. ChatTool#getEnterTool()

Project: sakai
Source File: ChatTool.java
View license
/**
    * This is called from the first page to redirect the user to the proper view.
    * This is the first call after JSF creates a new instance, so initialization is 
    *   done here.
    * If the tool is set to go to the select a chat room view and there are multiple chat
    * rooms, then it will go to the select a room page.  If the user is to select a room and
    * there is only one room, then it will go to that room.
    * 
    * @return String
    */
public String getEnterTool() {
    setupTool();
    // if there is no room selected to enter then go to select a room
    String url = PAGE_ENTER_ROOM;
    if (currentChannel == null)
        url = PAGE_LIST_ROOMS;
    ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
    HttpServletRequest req = (HttpServletRequest) context.getRequest();
    //signal to WrappedRequest that we want the Sakai managed
    req.setAttribute(Tool.NATIVE_URL, null);
    setToolContext(req.getContextPath());
    req.setAttribute(Tool.NATIVE_URL, Tool.NATIVE_URL);
    try {
        context.redirect(url);
    } catch (IOException e) {
        throw new RuntimeException("Failed to redirect to " + url, e);
    }
    return "";
}

8. DefaultWebSessionManager#onStart()

Project: shiro
Source File: DefaultWebSessionManager.java
View license
/**
     * Stores the Session's ID, usually as a Cookie, to associate with future requests.
     *
     * @param session the session that was just {@link #createSession created}.
     */
@Override
protected void onStart(Session session, SessionContext context) {
    super.onStart(session, context);
    if (!WebUtils.isHttp(context)) {
        log.debug("SessionContext argument is not HTTP compatible or does not have an HTTP request/response " + "pair. No session ID cookie will be set.");
        return;
    }
    HttpServletRequest request = WebUtils.getHttpRequest(context);
    HttpServletResponse response = WebUtils.getHttpResponse(context);
    if (isSessionIdCookieEnabled()) {
        Serializable sessionId = session.getId();
        storeSessionId(sessionId, request, response);
    } else {
        log.debug("Session ID cookie is disabled.  No cookie has been set for new session with id {}", session.getId());
    }
    request.removeAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE);
    request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_IS_NEW, Boolean.TRUE);
}

9. ConfigActionHelper#setupRequestAttributes()

Project: spacewalk
Source File: ConfigActionHelper.java
View license
/**
     * Adds the config revision, config file, and config channel as request attributes
     * when we already know the file and rev
     * @param rctxIn The request context which has the request.
     * @param file known config-file
     * @param cr known revision (null if there isn't one)
     */
public static void setupRequestAttributes(RequestContext rctxIn, ConfigFile file, ConfigRevision cr) {
    HttpServletRequest req = rctxIn.getRequest();
    setupRequestAttributes(rctxIn, file.getConfigChannel());
    req.setAttribute(FILE_ID, file.getId());
    req.setAttribute(FILE, file);
    // not want to set the revision-info
    if (cr != null) {
        req.setAttribute(REVISION_ID, cr.getId());
        req.setAttribute(REVISION, cr);
    }
}

10. ActionChainEntryRenderer#renderAsync()

View license
/**
     * Renders Action Chain entries from an Action Chain having a certain sort
     * order number.
     * @param actionChainId Action Chain identifier
     * @param sortOrder sort order number
     * @return a response string
     * @throws ServletException if something goes wrong
     * @throws IOException if something goes wrong
     */
public String renderAsync(Long actionChainId, Integer sortOrder) throws ServletException, IOException {
    WebContext webContext = WebContextFactory.get();
    HttpServletRequest request = webContext.getHttpServletRequest();
    User u = new RequestContext(request).getCurrentUser();
    ActionChain actionChain = ActionChainFactory.getActionChain(u, actionChainId);
    request.setAttribute("sortOrder", sortOrder);
    request.setAttribute("entries", ActionChainFactory.getActionChainEntries(actionChain, sortOrder));
    HttpServletResponse response = webContext.getHttpServletResponse();
    return RendererHelper.renderRequest("/WEB-INF/pages/common/fragments/schedule/actionchainentries.jsp", request, response);
}

11. BasePackageListAction#processRequestAttributes()

View license
/**
     * {@inheritDoc}
     */
protected void processRequestAttributes(RequestContext rctxIn) {
    HttpServletRequest request = rctxIn.getRequest();
    User user = rctxIn.getCurrentUser();
    long pid = rctxIn.getRequiredParam("pid");
    Package pkg = PackageFactory.lookupByIdAndUser(pid, user);
    // show permission error if pid is invalid like we did before
    if (pkg == null) {
        throw new PermissionException("Invalid pid");
    }
    request.setAttribute("pid", pid);
    request.setAttribute("package_name", pkg.getFilename());
}

12. ListHelper#setupDataSet()

Project: spacewalk
Source File: ListHelper.java
View license
/**
     *
     */
private void setupDataSet() {
    List dataSet = listable.getResult(context);
    HttpServletRequest request = context.getRequest();
    request.setAttribute(ListTagHelper.PARENT_URL, getParentUrl());
    request.setAttribute(getDataSetName(), dataSet);
    if (!StringUtils.isBlank(getListName()) && dataSet instanceof DataResult) {
        DataResult data = (DataResult) dataSet;
        Elaborator elab = data.getElaborator();
        if (elab != null) {
            TagHelper.bindElaboratorTo(getListName(), elab, request);
        }
    }
}

13. ContextMapperTest#testUnauthorized()

Project: gerrit
Source File: ContextMapperTest.java
View license
@Test
public void testUnauthorized() throws Exception {
    ContextMapper classUnderTest = new ContextMapper(CONTEXT);
    HttpServletRequest originalRequest = createFakeRequest("/plugins/", PLUGIN_NAME + "/" + RESOURCE);
    HttpServletRequest result = classUnderTest.create(originalRequest, PLUGIN_NAME);
    assertThat(result.getContextPath()).isEqualTo(CONTEXT + "/plugins/" + PLUGIN_NAME);
    assertThat(result.getServletPath()).isEqualTo("");
    assertThat(result.getPathInfo()).isEqualTo("/" + RESOURCE);
    assertThat(result.getRequestURI()).isEqualTo(CONTEXT + "/plugins/" + PLUGIN_NAME + "/" + RESOURCE);
}

14. ContextMapperTest#testAuthorized()

Project: gerrit
Source File: ContextMapperTest.java
View license
@Test
public void testAuthorized() throws Exception {
    ContextMapper classUnderTest = new ContextMapper(CONTEXT);
    HttpServletRequest originalRequest = createFakeRequest("/a/plugins/", PLUGIN_NAME + "/" + RESOURCE);
    HttpServletRequest result = classUnderTest.create(originalRequest, PLUGIN_NAME);
    assertThat(result.getContextPath()).isEqualTo(CONTEXT + "/a/plugins/" + PLUGIN_NAME);
    assertThat(result.getServletPath()).isEqualTo("");
    assertThat(result.getPathInfo()).isEqualTo("/" + RESOURCE);
    assertThat(result.getRequestURI()).isEqualTo(CONTEXT + "/a/plugins/" + PLUGIN_NAME + "/" + RESOURCE);
}

15. AuthenticatedUser#getRemoteHost()

View license
/**
     * Derives the remote host of the authenticating user from the given
     * credentials object. The remote host is derived from X-Forwarded-For
     * in addition to the actual source IP of the request, and thus is not
     * trusted. The derived remote host is really only useful for logging,
     * unless the server is configured such that X-Forwarded-For is guaranteed
     * to be trustworthy.
     *
     * @param credentials
     *     The credentials to derive the remote host from.
     *
     * @return
     *     The remote host from which the user with the given credentials is
     *     authenticating.
     */
private static String getRemoteHost(Credentials credentials) {
    HttpServletRequest request = credentials.getRequest();
    // Use X-Forwarded-For, if present and valid
    String header = request.getHeader("X-Forwarded-For");
    if (header != null) {
        Matcher matcher = X_FORWARDED_FOR.matcher(header);
        if (matcher.matches())
            return matcher.group(1);
    }
    // If header absent or invalid, just use source IP
    return request.getRemoteAddr();
}

16. AuthenticatedUser#getRemoteHost()

Project: home
Source File: AuthenticatedUser.java
View license
/**
     * Derives the remote host of the authenticating user from the given
     * credentials object. The remote host is derived from X-Forwarded-For
     * in addition to the actual source IP of the request, and thus is not
     * trusted. The derived remote host is really only useful for logging,
     * unless the server is configured such that X-Forwarded-For is guaranteed
     * to be trustworthy.
     *
     * @param credentials
     *     The credentials to derive the remote host from.
     *
     * @return
     *     The remote host from which the user with the given credentials is
     *     authenticating.
     */
private static String getRemoteHost(Credentials credentials) {
    HttpServletRequest request = credentials.getRequest();
    // Use X-Forwarded-For, if present and valid
    String header = request.getHeader("X-Forwarded-For");
    if (header != null) {
        Matcher matcher = X_FORWARDED_FOR.matcher(header);
        if (matcher.matches())
            return matcher.group(1);
    }
    // If header absent or invalid, just use source IP
    return request.getRemoteAddr();
}

17. AccessDeniedHandlerImpl#handle()

Project: hudson
Source File: AccessDeniedHandlerImpl.java
View license
public void handle(ServletRequest request, ServletResponse response, AccessDeniedException cause) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse rsp = (HttpServletResponse) response;
    rsp.setStatus(HttpServletResponse.SC_FORBIDDEN);
    req.setAttribute("exception", cause);
    if (cause instanceof AccessDeniedException2) {
        ((AccessDeniedException2) cause).reportAsHeaders(rsp);
    }
    WebApp.get(Jenkins.getInstance().servletContext).getSomeStapler().invoke(req, rsp, Jenkins.getInstance(), "/accessDenied");
}

18. AuthenticatedUser#getRemoteHost()

View license
/**
     * Derives the remote host of the authenticating user from the given
     * credentials object. The remote host is derived from X-Forwarded-For
     * in addition to the actual source IP of the request, and thus is not
     * trusted. The derived remote host is really only useful for logging,
     * unless the server is configured such that X-Forwarded-For is guaranteed
     * to be trustworthy.
     *
     * @param credentials
     *     The credentials to derive the remote host from.
     *
     * @return
     *     The remote host from which the user with the given credentials is
     *     authenticating.
     */
private static String getRemoteHost(Credentials credentials) {
    HttpServletRequest request = credentials.getRequest();
    // Use X-Forwarded-For, if present and valid
    String header = request.getHeader("X-Forwarded-For");
    if (header != null) {
        Matcher matcher = X_FORWARDED_FOR.matcher(header);
        if (matcher.matches())
            return matcher.group(1);
    }
    // If header absent or invalid, just use source IP
    return request.getRemoteAddr();
}

19. ResourceCachingFilter#doFilter()

Project: isis
Source File: ResourceCachingFilter.java
View license
/**
     * Do filter.
     * 
     * @param servletRequest
     *            the request
     * @param servletResponse
     *            the response
     * @param chain
     *            the chain
     * 
     * @throws IOException
     *             Signals that an I/O exception has occurred.
     * @throws ServletException
     *             the servlet exception
     * 
     * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
     *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
     */
@Override
public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain chain) throws IOException, ServletException {
    // Apply the headers
    final HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
    final HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
    for (final String[] replyHeader : this.mReplyHeaders) {
        final String name = replyHeader[0];
        final String value = replyHeader[1];
        httpResponse.addHeader(name, value);
    }
    if (this.cacheTime > 0L) {
        final long now = System.currentTimeMillis();
        final DateFormat httpDateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        httpDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        httpResponse.addHeader(LAST_MODIFIED_HEADER, httpDateFormat.format(new Date(now)));
        httpResponse.addHeader(EXPIRES_HEADER, httpDateFormat.format(new Date(now + (this.cacheTime.longValue() * MILLISECONDS_IN_SECOND))));
    }
    httpRequest.setAttribute(REQUEST_ATTRIBUTE, true);
    chain.doFilter(servletRequest, servletResponse);
}

20. AccessDeniedHandlerImpl#handle()

View license
public void handle(ServletRequest request, ServletResponse response, AccessDeniedException cause) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse rsp = (HttpServletResponse) response;
    rsp.setStatus(HttpServletResponse.SC_FORBIDDEN);
    req.setAttribute("exception", cause);
    if (cause instanceof AccessDeniedException2) {
        ((AccessDeniedException2) cause).reportAsHeaders(rsp);
    }
    WebApp.get(Jenkins.getInstance().servletContext).getSomeStapler().invoke(req, rsp, Jenkins.getInstance(), "/accessDenied");
}

21. BookActionResult#render()

Project: jodd
Source File: BookActionResult.java
View license
public void render(ActionRequest actionRequest, Book book) throws Exception {
    HttpServletRequest request = actionRequest.getHttpServletRequest();
    request.setAttribute("book", book);
    String method = actionRequest.getActionConfig().getActionMethod();
    if (method.equalsIgnoreCase("POST")) {
        DispatcherUtil.forward(request, actionRequest.getHttpServletResponse(), "/book/post.jsp");
    } else {
        DispatcherUtil.forward(request, actionRequest.getHttpServletResponse(), "/book/get.jsp");
    }
}

22. JSecurityHttpServletResponse#isEncodeable()

View license
/**
     * Return <code>true</code> if the specified URL should be encoded with
     * a session identifier.  This will be true if all of the following
     * conditions are met:
     * <ul>
     * <li>The request we are responding to asked for a valid session
     * <li>The requested session ID was not received via a cookie
     * <li>The specified URL points back to somewhere within the web
     * application that is responding to this request
     * </ul>
     *
     * @param location Absolute URL to be validated
     */
protected boolean isEncodeable(final String location) {
    if (location == null)
        return (false);
    // Is this an intra-document reference?
    if (location.startsWith("#"))
        return (false);
    // Are we in a valid session that is not using cookies?
    final HttpServletRequest hreq = request;
    final HttpSession session = hreq.getSession(false);
    if (session == null)
        return (false);
    if (hreq.isRequestedSessionIdFromCookie())
        return (false);
    return doIsEncodeable(hreq, session, location);
}

23. GZipFilter#doFilter()

Project: linkbinder
Source File: GZipFilter.java
View license
/* (non-Javadoc)
     * @see javax.servlet.Filter#doFilter(
     *      javax.servlet.ServletRequest,
     *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
     */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    if (isFiltered(req)) {
        chain.doFilter(req, res);
        return;
    }
    req.setAttribute(FILTERED, "true");
    if (!isCompressionSupported(req)) {
        chain.doFilter(req, res);
        return;
    }
    GZipResponseWrapper wrapper = new GZipResponseWrapper(res);
    try {
        chain.doFilter(req, wrapper);
    } finally {
        wrapper.finish();
    }
}

24. ShiroHttpServletResponse#isEncodeable()

Project: shiro
Source File: ShiroHttpServletResponse.java
View license
/**
     * Return <code>true</code> if the specified URL should be encoded with
     * a session identifier.  This will be true if all of the following
     * conditions are met:
     * <ul>
     * <li>The request we are responding to asked for a valid session
     * <li>The requested session ID was not received via a cookie
     * <li>The specified URL points back to somewhere within the web
     * application that is responding to this request
     * </ul>
     *
     * @param location Absolute URL to be validated
     * @return {@code true} if the specified URL should be encoded with a session identifier, {@code false} otherwise.
     */
protected boolean isEncodeable(final String location) {
    if (location == null)
        return (false);
    // Is this an intra-document reference?
    if (location.startsWith("#"))
        return (false);
    // Are we in a valid session that is not using cookies?
    final HttpServletRequest hreq = request;
    final HttpSession session = hreq.getSession(false);
    if (session == null)
        return (false);
    if (hreq.isRequestedSessionIdFromCookie())
        return (false);
    return doIsEncodeable(hreq, session, location);
}

25. AddPackagesConfirmAction#getResult()

View license
/** {@inheritDoc} */
public List getResult(RequestContext context) {
    User user = context.getCurrentUser();
    HttpServletRequest request = context.getRequest();
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("eid", context.getRequiredParam("eid"));
    String setName = RhnSetDecl.PACKAGES_TO_ADD.createCustom(context.getRequiredParam("eid")).getLabel();
    DataResult dr = PackageManager.packageIdsInSet(user, setName);
    // Put the advisory into the request for the page header
    Errata errata = new RequestContext(request).lookupErratum();
    request.setAttribute("advisory", errata.getAdvisory());
    return dr;
}

26. FreeMarkerAutoConfigurationTests#render()

View license
private MockHttpServletResponse render(String viewName) throws Exception {
    FreeMarkerViewResolver resolver = this.context.getBean(FreeMarkerViewResolver.class);
    View view = resolver.resolveViewName(viewName, Locale.UK);
    assertThat(view).isNotNull();
    HttpServletRequest request = new MockHttpServletRequest();
    request.setAttribute(RequestContext.WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
    MockHttpServletResponse response = new MockHttpServletResponse();
    view.render(null, request, response);
    return response;
}

27. GroovyTemplateAutoConfigurationTests#render()

View license
private MockHttpServletResponse render(String viewName, Locale locale) throws Exception {
    LocaleContextHolder.setLocale(locale);
    GroovyMarkupViewResolver resolver = this.context.getBean(GroovyMarkupViewResolver.class);
    View view = resolver.resolveViewName(viewName, locale);
    assertThat(view).isNotNull();
    HttpServletRequest request = new MockHttpServletRequest();
    request.setAttribute(RequestContext.WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
    MockHttpServletResponse response = new MockHttpServletResponse();
    view.render(null, request, response);
    return response;
}

28. SecurityContextHolderAwareRequestFilterTests#logout()

View license
@Test
public void logout() throws Exception {
    TestingAuthenticationToken expectedAuth = new TestingAuthenticationToken("user", "password", "ROLE_USER");
    SecurityContextHolder.getContext().setAuthentication(expectedAuth);
    HttpServletRequest wrappedRequest = wrappedRequest();
    wrappedRequest.logout();
    verify(this.logoutHandler).logout(wrappedRequest, this.response, expectedAuth);
    verifyZeroInteractions(this.authenticationManager, this.logoutHandler);
    verify(this.request, times(0)).logout();
}

29. ShowArticleUpdateValidation#doAdvice()

View license
@Override
public void doAdvice(final HTTPRequestContext context, final Map<String, Object> args) throws RequestProcessAdviceException {
    final HttpServletRequest request = context.getRequest();
    JSONObject article = null;
    try {
        final String articleId = request.getParameter("id");
        if (Strings.isEmptyOrNull(articleId)) {
            throw new RequestProcessAdviceException(new JSONObject().put(Keys.MSG, langPropsService.get("updateArticleNotFoundLabel")));
        }
        article = articleQueryService.getArticleById(articleId);
        if (null == article) {
            throw new RequestProcessAdviceException(new JSONObject().put(Keys.MSG, langPropsService.get("updateArticleNotFoundLabel")));
        }
    } catch (final Exception e) {
        throw new RequestProcessAdviceException(new JSONObject().put(Keys.MSG, e.getMessage()));
    }
    request.setAttribute(Article.ARTICLE, article);
}

30. RequestImplTest#used_encoding_from_request()

Project: tapestry-5
Source File: RequestImplTest.java
View license
@Test
public void used_encoding_from_request() throws Exception {
    HttpServletRequest sr = mockHttpServletRequest();
    expect(sr.getCharacterEncoding()).andReturn("request-encoding");
    sr.setCharacterEncoding("request-encoding");
    expect(sr.getParameterNames()).andReturn(Collections.enumeration(Collections.EMPTY_LIST));
    replay();
    new RequestImpl(sr, "app-encoding-is-ignored", null).getParameterNames();
    verify();
}

31. RequestImplTest#set_encoding_success()

Project: tapestry-5
Source File: RequestImplTest.java
View license
@Test
public void set_encoding_success() throws Exception {
    HttpServletRequest sr = mockHttpServletRequest();
    String encoding = "the-encoding";
    sr.setCharacterEncoding(encoding);
    expect(sr.getCharacterEncoding()).andReturn(null);
    expect(sr.getParameterNames()).andReturn(Collections.enumeration(Collections.EMPTY_LIST));
    replay();
    new RequestImpl(sr, encoding, null).getParameterNames();
    verify();
}

32. MultipartDecoderImplTest#process_file_items_does_nothing_when_null_file_items()

View license
@Test
public void process_file_items_does_nothing_when_null_file_items() throws Exception {
    HttpServletRequest request = mockHttpServletRequest();
    MultipartDecoderImpl decoder = new MultipartDecoderImpl(fileItemFactory, -1, -1, CHARSET);
    List<FileItem> items = Collections.emptyList();
    replay();
    HttpServletRequest decodedRequest = decoder.processFileItems(request, items);
    verify();
    assertSame(request, decodedRequest);
}

33. MultipartDecoderImplTest#process_file_items_does_nothing_when_empty_file_items()

View license
@Test
public void process_file_items_does_nothing_when_empty_file_items() throws Exception {
    HttpServletRequest request = mockHttpServletRequest();
    MultipartDecoderImpl decoder = new MultipartDecoderImpl(fileItemFactory, -1, -1, CHARSET);
    List<FileItem> fileItems = Collections.emptyList();
    replay();
    HttpServletRequest decodedRequest = decoder.processFileItems(request, fileItems);
    verify();
    assertSame(request, decodedRequest);
}

34. MultipartDecoderImplTest#process_file_items_creates_wrapped_request_and_sets_non_file_parameters()

View license
@Test
public void process_file_items_creates_wrapped_request_and_sets_non_file_parameters() throws Exception {
    HttpServletRequest request = mockHttpServletRequest();
    expect(request.getParameterMap()).andReturn(Collections.EMPTY_MAP);
    MultipartDecoderImpl decoder = new MultipartDecoderImpl(fileItemFactory, -1, -1, CHARSET);
    List<FileItem> fileItems = Arrays.asList(createValueItem("one", "first"), createValueItem("two", "second"));
    replay();
    HttpServletRequest decodedRequest = decoder.processFileItems(request, fileItems);
    assertNotSame(decodedRequest, request);
    assertEquals(decodedRequest.getParameter("one"), "first");
    assertEquals(decodedRequest.getParameter("two"), "second");
    verify();
}

35. MultipartDecoderImplTest#non_file_items_with_null_request_encoding()

View license
@Test
public void non_file_items_with_null_request_encoding() throws Exception {
    HttpServletRequest request = mockHttpServletRequest();
    expect(request.getParameterMap()).andReturn(Collections.EMPTY_MAP);
    MultipartDecoderImpl decoder = new MultipartDecoderImpl(fileItemFactory, -1, -1, CHARSET);
    List<FileItem> fileItems = Arrays.asList(createValueItem("one", "first"), createValueItem("two", "second"));
    replay();
    HttpServletRequest decodedRequest = decoder.processFileItems(request, fileItems);
    assertNotSame(decodedRequest, request);
    assertEquals(decodedRequest.getParameter("one"), "first");
    assertEquals(decodedRequest.getParameter("two"), "second");
    verify();
}

36. MultipartDecoderImplTest#process_file_items_set_file_parameters_with_file_name()

View license
@Test
public void process_file_items_set_file_parameters_with_file_name() throws Exception {
    HttpServletRequest request = mockHttpServletRequest();
    expect(request.getParameterMap()).andReturn(Collections.EMPTY_MAP);
    MultipartDecoderImpl decoder = new MultipartDecoderImpl(fileItemFactory, -1, -1, CHARSET);
    List<FileItem> fileItems = Arrays.asList(createFileItem("one", "first.txt"), createFileItem("two", "second.txt"));
    replay();
    HttpServletRequest decodedRequest = decoder.processFileItems(request, fileItems);
    assertNotSame(decodedRequest, request);
    assertEquals(decodedRequest.getParameter("one"), "first.txt");
    assertEquals(decodedRequest.getParameter("two"), "second.txt");
    verify();
}

37. MultipartServletRequestFilterTest#multipartRequestIsDecoded()

View license
@Test
public void multipartRequestIsDecoded() throws Exception {
    MultipartDecoder decoder = newMock(MultipartDecoder.class);
    HttpServletRequest request = mockHttpServletRequest();
    HttpServletRequest decodedRequest = mockHttpServletRequest();
    HttpServletResponse response = mockHttpServletResponse();
    HttpServletRequestHandler handler = newMock(HttpServletRequestHandler.class);
    MultipartServletRequestFilter filter = new MultipartServletRequestFilter(decoder);
    expect(request.getMethod()).andReturn("post");
    expect(request.getContentType()).andReturn("multipart/form");
    expect(decoder.decode(request)).andReturn(decodedRequest);
    expect(handler.service(decodedRequest, response)).andReturn(true);
    replay();
    boolean isHandled = filter.service(request, response, handler);
    assertTrue(isHandled);
    verify();
}

38. TestUploadFormParametersWrapper#testGetSingleParameterWhenNull()

View license
public void testGetSingleParameterWhenNull() {
    HttpServletRequest request = newRequest();
    replayControls();
    HttpServletRequest r = new UploadFormParametersWrapper(request, new HashMap());
    assertNull(r.getParameter("unknown-key"));
    verifyControls();
}

39. TestUploadFormParametersWrapper#testGetSingleParameterWhenEmptyArray()

View license
public void testGetSingleParameterWhenEmptyArray() {
    HttpServletRequest request = newRequest();
    replayControls();
    HashMap params = new HashMap();
    params.put("empty-key", new String[0]);
    HttpServletRequest r = new UploadFormParametersWrapper(request, params);
    assertNull(r.getParameter("empty-key"));
    verifyControls();
}

40. TestUploadFormParametersWrapper#testGetParameterValues()

View license
public void testGetParameterValues() {
    String[] values = { "fred", "barney" };
    HttpServletRequest request = newRequest();
    replayControls();
    HashMap params = new HashMap();
    params.put("key", values);
    HttpServletRequest r = new UploadFormParametersWrapper(request, params);
    assertSame(values, r.getParameterValues("key"));
    verifyControls();
}

41. TestUploadFormParametersWrapper#testGetParameterNames()

View license
public void testGetParameterNames() {
    HttpServletRequest request = newRequest();
    replayControls();
    HashMap params = new HashMap();
    params.put("key", new String[0]);
    HttpServletRequest r = new UploadFormParametersWrapper(request, params);
    Enumeration e = r.getParameterNames();
    assertEquals(true, e.hasMoreElements());
    assertEquals("key", e.nextElement());
    assertEquals(false, e.hasMoreElements());
    verifyControls();
}

42. TestRequestContext#testGetParameter()

Project: tapestry4
Source File: TestRequestContext.java
View license
public void testGetParameter() {
    MockControl control = newControl(HttpServletRequest.class);
    HttpServletRequest request = (HttpServletRequest) control.getMock();
    HttpServletResponse response = newResponse();
    String value = "VALUE";
    request.getParameter("myparam");
    control.setReturnValue(value);
    replayControls();
    RequestContext rc = new RequestContext(request, response);
    assertSame(value, rc.getParameter("myparam"));
    verifyControls();
}

43. TestRequestContext#testGetParameters()

Project: tapestry4
Source File: TestRequestContext.java
View license
public void testGetParameters() {
    MockControl control = newControl(HttpServletRequest.class);
    HttpServletRequest request = (HttpServletRequest) control.getMock();
    HttpServletResponse response = newResponse();
    String[] values = { "this", "that" };
    request.getParameterValues("myparam");
    control.setReturnValue(values);
    replayControls();
    RequestContext rc = new RequestContext(request, response);
    assertSame(values, rc.getParameters("myparam"));
    verifyControls();
}

44. TestRequestContext#testGetAttribute()

Project: tapestry4
Source File: TestRequestContext.java
View license
public void testGetAttribute() {
    MockControl control = newControl(HttpServletRequest.class);
    HttpServletRequest request = (HttpServletRequest) control.getMock();
    HttpServletResponse response = newResponse();
    Object attribute = new Object();
    request.getAttribute("myattr");
    control.setReturnValue(attribute);
    replayControls();
    RequestContext rc = new RequestContext(request, response);
    assertSame(attribute, rc.getAttribute("myattr"));
    verifyControls();
}

45. TestSetupRequestEncoding#testEncodingNull()

View license
public void testEncodingNull() throws Exception {
    HttpServletRequest request = newRequest(null);
    HttpServletResponse response = newResponse();
    ServletRequestServicer servicer = newServicer();
    request.setCharacterEncoding("output-encoding");
    servicer.service(request, response);
    replayControls();
    SetupRequestEncoding sre = new SetupRequestEncoding();
    sre.setOutputEncoding("output-encoding");
    sre.service(request, response, servicer);
    verifyControls();
}

46. TestServletWebRequest#testGetParameterNames()

View license
public void testGetParameterNames() {
    HttpServletRequest request = newRequest();
    HttpServletResponse response = newResponse();
    request.getParameterNames();
    setReturnValue(request, newEnumeration());
    replayControls();
    WebRequest wr = new ServletWebRequest(request, response);
    List l = wr.getParameterNames();
    checkList(l);
    verifyControls();
}

47. TestServletWebRequest#testGetParameterValue()

View license
public void testGetParameterValue() {
    HttpServletRequest request = newRequest();
    HttpServletResponse response = newResponse();
    String value = "William Orbit";
    request.getParameter("artist");
    setReturnValue(request, value);
    replayControls();
    WebRequest wr = new ServletWebRequest(request, response);
    assertSame(value, wr.getParameterValue("artist"));
    verifyControls();
}

48. TestServletWebRequest#testGetParameterValues()

View license
public void testGetParameterValues() {
    HttpServletRequest request = newRequest();
    HttpServletResponse response = newResponse();
    String[] values = { "William Orbit", "Steely Dan" };
    request.getParameterValues("artist");
    setReturnValue(request, values);
    replayControls();
    WebRequest wr = new ServletWebRequest(request, response);
    assertSame(values, wr.getParameterValues("artist"));
    verifyControls();
}

49. TestServletWebRequest#testGetContextPath()

View license
public void testGetContextPath() {
    HttpServletRequest request = newRequest();
    HttpServletResponse response = newResponse();
    request.getContextPath();
    setReturnValue(request, "/foo");
    replayControls();
    WebRequest wr = new ServletWebRequest(request, response);
    assertEquals("/foo", wr.getContextPath());
    verifyControls();
}

50. TestServletWebRequest#testGetAttributeNames()

View license
public void testGetAttributeNames() {
    HttpServletRequest request = newRequest();
    HttpServletResponse response = newResponse();
    request.getAttributeNames();
    setReturnValue(request, newEnumeration());
    replayControls();
    WebRequest wr = new ServletWebRequest(request, response);
    List l = wr.getAttributeNames();
    checkList(l);
    verifyControls();
}

51. TestServletWebRequest#testGetAttribute()

View license
public void testGetAttribute() {
    HttpServletRequest request = newRequest();
    HttpServletResponse response = newResponse();
    Object attribute = new Object();
    request.getAttribute("attr");
    setReturnValue(request, attribute);
    replayControls();
    WebRequest wr = new ServletWebRequest(request, response);
    assertSame(attribute, wr.getAttribute("attr"));
    verifyControls();
}

52. TestServletWebRequest#testSetAttribute()

View license
public void testSetAttribute() {
    HttpServletRequest request = newRequest();
    HttpServletResponse response = newResponse();
    Object attribute = new Object();
    request.setAttribute("name", attribute);
    replayControls();
    WebRequest wr = new ServletWebRequest(request, response);
    wr.setAttribute("name", attribute);
    verifyControls();
}

53. TestServletWebRequest#testSetAttributeToNull()

View license
public void testSetAttributeToNull() {
    HttpServletRequest request = newRequest();
    HttpServletResponse response = newResponse();
    request.removeAttribute("tonull");
    replayControls();
    WebRequest wr = new ServletWebRequest(request, response);
    wr.setAttribute("tonull", null);
    verifyControls();
}

54. TestServletWebRequest#testGetScheme()

View license
public void testGetScheme() {
    HttpServletRequest request = newRequest();
    HttpServletResponse response = newResponse();
    request.getScheme();
    setReturnValue(request, "http");
    replayControls();
    WebRequest wr = new ServletWebRequest(request, response);
    assertEquals("http", wr.getScheme());
    verifyControls();
}

55. TestServletWebRequest#testGetServerName()

View license
public void testGetServerName() {
    HttpServletRequest request = newRequest();
    HttpServletResponse response = newResponse();
    request.getServerName();
    setReturnValue(request, "www.myhost.com");
    replayControls();
    WebRequest wr = new ServletWebRequest(request, response);
    assertEquals("www.myhost.com", wr.getServerName());
    verifyControls();
}

56. TestServletWebRequest#testGetServerPort()

View license
public void testGetServerPort() {
    HttpServletRequest request = newRequest();
    HttpServletResponse response = newResponse();
    request.getServerPort();
    setReturnValue(request, 80);
    replayControls();
    WebRequest wr = new ServletWebRequest(request, response);
    assertEquals(80, wr.getServerPort());
    verifyControls();
}

57. TestServletWebRequest#testGetRequestURI()

View license
public void testGetRequestURI() {
    HttpServletRequest request = newRequest();
    HttpServletResponse response = newResponse();
    request.getRequestURI();
    setReturnValue(request, "/foo/bar");
    replayControls();
    WebRequest wr = new ServletWebRequest(request, response);
    assertEquals("/foo/bar", wr.getRequestURI());
    verifyControls();
}

58. TestServletWebRequest#testGetActivationPath()

View license
public void testGetActivationPath() {
    HttpServletRequest request = newRequest();
    HttpServletResponse response = newResponse();
    request.getServletPath();
    setReturnValue(request, "/foo");
    replayControls();
    WebRequest wr = new ServletWebRequest(request, response);
    assertEquals("/foo", wr.getActivationPath());
    verifyControls();
}

59. TestServletWebRequest#testGetPathInfo()

View license
public void testGetPathInfo() {
    HttpServletRequest request = newRequest();
    HttpServletResponse response = newResponse();
    request.getPathInfo();
    setReturnValue(request, "bar/baz");
    replayControls();
    WebRequest wr = new ServletWebRequest(request, response);
    assertEquals("bar/baz", wr.getPathInfo());
    verifyControls();
}

60. RequestImplTest#set_encoding_success()

Project: tapestry5
Source File: RequestImplTest.java
View license
@Test
public void set_encoding_success() throws Exception {
    HttpServletRequest sr = mockHttpServletRequest();
    String encoding = "the-encoding";
    sr.setCharacterEncoding(encoding);
    expect(sr.getParameterNames()).andReturn(Collections.enumeration(Collections.EMPTY_LIST));
    replay();
    new RequestImpl(sr, encoding).getParameterNames();
    verify();
}

61. RequestImplTest#set_encoding_failure()

Project: tapestry5
Source File: RequestImplTest.java
View license
@Test
public void set_encoding_failure() throws Exception {
    HttpServletRequest sr = mockHttpServletRequest();
    String encoding = "the-encoding";
    UnsupportedEncodingException exception = new UnsupportedEncodingException("Oops.");
    sr.setCharacterEncoding(encoding);
    setThrowable(exception);
    replay();
    try {
        new RequestImpl(sr, encoding).getParameterNames();
        unreachable();
    } catch (RuntimeException ex) {
        assertSame(ex.getCause(), exception);
    }
    verify();
}

62. MultipartDecoderImplTest#process_file_items_does_nothing_when_null_file_items()

View license
@Test
public void process_file_items_does_nothing_when_null_file_items() throws Exception {
    HttpServletRequest request = mockHttpServletRequest();
    MultipartDecoderImpl decoder = new MultipartDecoderImpl(fileItemFactory, -1, -1, CHARSET);
    List<FileItem> items = Collections.emptyList();
    replay();
    HttpServletRequest decodedRequest = decoder.processFileItems(request, items);
    verify();
    assertSame(request, decodedRequest);
}

63. MultipartDecoderImplTest#process_file_items_does_nothing_when_empty_file_items()

View license
@Test
public void process_file_items_does_nothing_when_empty_file_items() throws Exception {
    HttpServletRequest request = mockHttpServletRequest();
    MultipartDecoderImpl decoder = new MultipartDecoderImpl(fileItemFactory, -1, -1, CHARSET);
    List<FileItem> fileItems = Collections.emptyList();
    replay();
    HttpServletRequest decodedRequest = decoder.processFileItems(request, fileItems);
    verify();
    assertSame(request, decodedRequest);
}

64. MultipartDecoderImplTest#process_file_items_creates_wrapped_request_and_sets_non_file_parameters()

View license
@Test
public void process_file_items_creates_wrapped_request_and_sets_non_file_parameters() throws Exception {
    HttpServletRequest request = mockHttpServletRequest();
    MultipartDecoderImpl decoder = new MultipartDecoderImpl(fileItemFactory, -1, -1, CHARSET);
    List<FileItem> fileItems = Arrays.asList(createValueItem("one", "first"), createValueItem("two", "second"));
    replay();
    HttpServletRequest decodedRequest = decoder.processFileItems(request, fileItems);
    assertNotSame(decodedRequest, request);
    assertEquals(decodedRequest.getParameter("one"), "first");
    assertEquals(decodedRequest.getParameter("two"), "second");
    verify();
}

65. MultipartDecoderImplTest#non_file_items_with_null_request_encoding()

View license
@Test
public void non_file_items_with_null_request_encoding() throws Exception {
    HttpServletRequest request = mockHttpServletRequest();
    MultipartDecoderImpl decoder = new MultipartDecoderImpl(fileItemFactory, -1, -1, CHARSET);
    List<FileItem> fileItems = Arrays.asList(createValueItem("one", "first"), createValueItem("two", "second"));
    replay();
    HttpServletRequest decodedRequest = decoder.processFileItems(request, fileItems);
    assertNotSame(decodedRequest, request);
    assertEquals(decodedRequest.getParameter("one"), "first");
    assertEquals(decodedRequest.getParameter("two"), "second");
    verify();
}

66. MultipartDecoderImplTest#process_file_items_set_file_parameters_with_file_name()

View license
@Test
public void process_file_items_set_file_parameters_with_file_name() throws Exception {
    HttpServletRequest request = mockHttpServletRequest();
    MultipartDecoderImpl decoder = new MultipartDecoderImpl(fileItemFactory, -1, -1, CHARSET);
    List<FileItem> fileItems = Arrays.asList(createFileItem("one", "first.txt"), createFileItem("two", "second.txt"));
    replay();
    HttpServletRequest decodedRequest = decoder.processFileItems(request, fileItems);
    assertNotSame(decodedRequest, request);
    assertEquals(decodedRequest.getParameter("one"), "first.txt");
    assertEquals(decodedRequest.getParameter("two"), "second.txt");
    verify();
}

67. MultipartServletRequestFilterTest#multipartRequestIsDecoded()

View license
@Test
public void multipartRequestIsDecoded() throws Exception {
    MultipartDecoder decoder = newMock(MultipartDecoder.class);
    HttpServletRequest request = mockHttpServletRequest();
    HttpServletRequest decodedRequest = mockHttpServletRequest();
    HttpServletResponse response = mockHttpServletResponse();
    HttpServletRequestHandler handler = newMock(HttpServletRequestHandler.class);
    MultipartServletRequestFilter filter = new MultipartServletRequestFilter(decoder);
    expect(request.getMethod()).andReturn("post");
    expect(request.getContentType()).andReturn("multipart/form");
    expect(decoder.decode(request)).andReturn(decodedRequest);
    expect(handler.service(decodedRequest, response)).andReturn(true);
    replay();
    boolean isHandled = filter.service(request, response, handler);
    assertTrue(isHandled);
    verify();
}

68. StandardLinkBuilder#computeContextPath()

Project: thymeleaf
Source File: StandardLinkBuilder.java
View license
/**
     * <p>
     *   Compute the context path to be applied to URLs that have been determined to be context-relative (and therefore
     *   need a context path to be inserted at their beginning).
     * </p>
     * <p>
     *   By default, this method will obtain the context path from <tt>HttpServletRequest.getContextPath()</tt>,
     *   throwing an exception if <tt>context</tt> is not an instance of <tt>IWebContext</tt> given context-relative
     *   URLs are (by default) only allowed in web contexts.
     * </p>
     * <p>
     *   This method can be overridden by any subclasses that want to change this behaviour (e.g. in order to
     *   avoid using the Servlet API for resolving context path or to allow context-relative URLs in non-web
     *   contexts).
     * </p>
     *
     * @param context the execution context.
     * @param base the URL base specified.
     * @param parameters the URL parameters specified.
     * @return the context path.
     */
protected String computeContextPath(final IExpressionContext context, final String base, final Map<String, Object> parameters) {
    if (!(context instanceof IWebContext)) {
        throw new TemplateProcessingException("Link base \"" + base + "\" cannot be context relative (/...) unless the context " + "used for executing the engine implements the " + IWebContext.class.getName() + " interface");
    }
    // If it is context-relative, it has to be a web context
    final HttpServletRequest request = ((IWebContext) context).getRequest();
    return request.getContextPath();
}

69. PropertyToAttributePropertiesManager#addResponseProperty()

View license
@Override
public boolean addResponseProperty(HttpServletRequest portletRequest, IPortletWindow portletWindow, String property, String value) {
    if (this.propertyToAttributeMappings.isEmpty() && this.nonNamespacedProperties.isEmpty()) {
        return false;
    }
    final HttpServletRequest portalRequest = this.portalRequestUtils.getOriginalPortalRequest(portletRequest);
    final String attributeName = getAttributeName(portletWindow, property);
    final Object existingValue = portalRequest.getAttribute(attributeName);
    if (!(existingValue instanceof List)) {
        this.logger.warn("Attribute {} for property {} exists but is NOT a List, it will be replaced", attributeName, property);
        this.setResponseProperty(portletRequest, portletWindow, property, value);
        return true;
    }
    logger.debug("Adding property {} as attribute {}", property, attributeName);
    @SuppressWarnings("unchecked") final List<String> values = (List<String>) existingValue;
    values.add(value);
    portalRequest.setAttribute(attributeName, values);
    return true;
}

70. PropertyToAttributePropertiesManager#setResponseProperty()

View license
@Override
public boolean setResponseProperty(HttpServletRequest portletRequest, IPortletWindow portletWindow, String property, String value) {
    if (this.propertyToAttributeMappings.isEmpty() && this.nonNamespacedProperties.isEmpty()) {
        return false;
    }
    final HttpServletRequest portalRequest = this.portalRequestUtils.getOriginalPortalRequest(portletRequest);
    final String attributeName = getAttributeName(portletWindow, property);
    logger.debug("Setting property {} as attribute {}", property, attributeName);
    final List<String> values = new LinkedList<String>();
    values.add(value);
    portalRequest.setAttribute(attributeName, values);
    return true;
}

71. DispatcherStreamLocator#getWrappedServletRequest()

Project: wro4j
Source File: DispatcherStreamLocator.java
View license
/**
   * Build a wrapped servlet request which will be used for dispatching.
   */
private ServletRequest getWrappedServletRequest(final HttpServletRequest request, final String location) {
    final HttpServletRequest wrappedRequest = new HttpServletRequestWrapper(request) {

        @Override
        public String getRequestURI() {
            return getContextPath() + location;
        }

        @Override
        public String getPathInfo() {
            return WroUtil.getPathInfoFromLocation(this, location);
        }

        @Override
        public String getServletPath() {
            return WroUtil.getServletPathFromLocation(this, location);
        }
    };
    // add an attribute to mark this request as included from wro
    wrappedRequest.setAttribute(ATTRIBUTE_INCLUDED_BY_DISPATCHER, Boolean.TRUE);
    return wrappedRequest;
}

72. AbstractDispatcherCacheHeaderFilter#doFilter()

View license
@Override
public final void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException {
    if (!(servletRequest instanceof HttpServletRequest) || !(servletResponse instanceof HttpServletResponse)) {
        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }
    final HttpServletRequest request = (HttpServletRequest) servletRequest;
    final HttpServletResponse response = (HttpServletResponse) servletResponse;
    if (this.accepts(request)) {
        String header = getHeaderName();
        String val = getHeaderValue();
        log.debug("Adding header {}: {}", header, val);
        response.addHeader(header, val);
    }
    filterChain.doFilter(request, response);
}

73. VersionFilter#doFilter()

View license
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    final String accept = httpRequest.getHeader("accept");
    if (accept != null) {
        final int index = accept.indexOf(AEROGEAR_VERSION_PREFIX);
        if (index != -1) {
            final int beginIndex = index + AEROGEAR_VERSION_PREFIX.length();
            final String version = accept.substring(beginIndex, beginIndex + VERSION_LENGTH);
            chain.doFilter(new TransformHttpServletRequestWrapper(version, httpRequest), response);
            return;
        }
    }
    chain.doFilter(request, response);
}

74. HttpBasicHelperTest#extractUsernameAndPasswordFromBasicHeader()

View license
@Test
public void extractUsernameAndPasswordFromBasicHeader() {
    final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    final String encodedUserPassword = Base64.getEncoder().encodeToString("user:password".getBytes(StandardCharsets.UTF_8));
    Mockito.when(request.getHeader("Authorization")).thenReturn("Basic " + encodedUserPassword);
    final String[] credentials = HttpBasicHelper.extractUsernameAndPasswordFromBasicHeader(request);
    assertThat(credentials).isNotNull();
    assertThat(credentials[0]).isEqualTo("user");
    assertThat(credentials[1]).isEqualTo("password");
    assertThat(credentials[0]).isNotEqualTo(" user");
    assertThat(credentials[1]).isNotEqualTo(" password");
}

75. HttpRequestHelperTest#extractRemoteAddress()

View license
@Test
public void extractRemoteAddress() {
    final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    Mockito.when(request.getHeader("x-forwarded-for")).thenReturn(null);
    Mockito.when(request.getHeader("Proxy-Client-IP")).thenReturn(null);
    Mockito.when(request.getHeader("WL-Proxy-Client-IP")).thenReturn(null);
    Mockito.when(request.getRemoteAddr()).thenReturn("127.0.0.1");
    final String remoteAddress = HttpRequestUtil.extractIPAddress(request);
    assertThat(remoteAddress).isNotNull();
    assertThat(remoteAddress).isEqualTo("127.0.0.1");
}

76. HttpRequestHelperTest#extractWLProxyClientIPHeader()

View license
@Test
public void extractWLProxyClientIPHeader() {
    final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    Mockito.when(request.getHeader("x-forwarded-for")).thenReturn(null);
    Mockito.when(request.getHeader("Proxy-Client-IP")).thenReturn(null);
    Mockito.when(request.getHeader("WL-Proxy-Client-IP")).thenReturn("127.0.0.1");
    final String remoteAddress = HttpRequestUtil.extractIPAddress(request);
    assertThat(remoteAddress).isNotNull();
    assertThat(remoteAddress).isEqualTo("127.0.0.1");
}

77. TraceTokenFilter#doFilter()

Project: airlift
Source File: TraceTokenFilter.java
View license
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    String token = request.getHeader("X-Airlift-TraceToken");
    if (token != null) {
        traceTokenManager.registerRequestToken(token);
    } else {
        traceTokenManager.createAndRegisterNewRequestToken();
    }
    chain.doFilter(request, response);
}

78. DummyFilter#doFilter()

Project: airlift
Source File: DummyFilter.java
View license
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    String requestURI = request.getRequestURI();
    if ("/filter".equals(requestURI)) {
        response.sendError(HttpServletResponse.SC_PAYMENT_REQUIRED, "filtered");
        return;
    }
    chain.doFilter(request, response);
}

79. FilterDispather#doFilter()

View license
// ????????
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    // ???HttpServletRequest
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    // ??????????
    chain.doFilter(req, res);
    // ???HTTP???ACTION??
    String actionName = getActionNameFromURI(req);
    // ?ViewManager???
    ViewManager viewManager = new ViewManager(actionName);
    // ????????
    ValueStack valueStack = valueStackHelper.putIntoStack(req);
    // ?????????ActionDispatcher??
    String result = actionDispather.actionInvoke(actionName);
    String viewPath = viewManager.getViewPath(result);
    // ????
    RequestDispatcher rd = req.getRequestDispatcher(viewPath);
    rd.forward(req, res);
}

80. AuthenticationTokenProcessingFilter#doFilter()

View license
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest httpRequest = this.getAsHttpRequest(request);
    String authToken = this.extractAuthTokenFromRequest(httpRequest);
    String userName = TokenUtils.getUserNameFromToken(authToken);
    if (userName != null) {
        UserDetails userDetails = this.userService.loadUserByUsername(userName);
        if (TokenUtils.validateToken(authToken, userDetails)) {
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
    }
    chain.doFilter(request, response);
}

81. ApimanCorsFilter#doFilter()

Project: apiman
Source File: ApimanCorsFilter.java
View license
/**
     * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
     */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest httpReq = (HttpServletRequest) request;
    HttpServletResponse httpResp = (HttpServletResponse) response;
    if (isPreflightRequest(httpReq)) {
        //$NON-NLS-1$ //$NON-NLS-2$
        httpResp.setHeader("Access-Control-Allow-Origin", httpReq.getHeader("Origin"));
        //$NON-NLS-1$ //$NON-NLS-2$
        httpResp.setHeader("Access-Control-Allow-Credentials", "true");
        //$NON-NLS-1$ //$NON-NLS-2$
        httpResp.setHeader("Access-Control-Max-Age", "1800");
        //$NON-NLS-1$ //$NON-NLS-2$
        httpResp.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,HEAD,DELETE");
        //$NON-NLS-1$ //$NON-NLS-2$
        httpResp.setHeader("Access-Control-Allow-Headers", "X-Requested-With,Content-Type,Accept,Origin,Authorization");
        //$NON-NLS-1$ //$NON-NLS-2$
        httpResp.setHeader("Access-Control-Expose-Headers", "X-Apiman-Error");
    } else {
        if (hasOriginHeader(httpReq)) {
            //$NON-NLS-1$ //$NON-NLS-2$
            httpResp.setHeader("Access-Control-Allow-Origin", httpReq.getHeader("Origin"));
            //$NON-NLS-1$ //$NON-NLS-2$
            httpResp.setHeader("Access-Control-Allow-Credentials", "true");
            //$NON-NLS-1$ //$NON-NLS-2$
            httpResp.setHeader("Access-Control-Expose-Headers", "X-Apiman-Error");
        }
        chain.doFilter(httpReq, httpResp);
    }
}

82. AuthenticationFilter#doFilter()

Project: apiman
Source File: AuthenticationFilter.java
View license
/**
     * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
     */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    //$NON-NLS-1$
    String authHeader = req.getHeader("Authorization");
    if (authHeader == null) {
        sendAuthResponse((HttpServletResponse) response);
    } else if (authHeader.toUpperCase().startsWith("BASIC")) {
        //$NON-NLS-1$
        Creds credentials = parseAuthorizationBasic(authHeader);
        if (credentials == null) {
            sendAuthResponse((HttpServletResponse) response);
        } else {
            doBasicAuth(credentials, req, (HttpServletResponse) response, chain);
        }
    } else if (authHeader.toUpperCase().startsWith("AUTH-TOKEN")) {
        //$NON-NLS-1$
        AuthToken token = parseAuthorizationToken(authHeader);
        if (token == null) {
            sendAuthResponse((HttpServletResponse) response);
        } else {
            doTokenAuth(token, req, (HttpServletResponse) response, chain);
        }
    } else {
        sendAuthResponse((HttpServletResponse) response);
    }
}

83. PostCasAuthenticationFilter#doFilter()

View license
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    CasUser casUser = new CasUser();
    String uid = httpServletRequest.getRemoteUser();
    casUser.setUid(uid);
    if (admins.contains(uid)) {
        casUser.setAdmin(true);
    }
    httpServletRequest.getSession().setAttribute(POST_CAS_AUTHENTICATION_INFO, casUser);
    String uri = (String) httpServletRequest.getSession().getAttribute(REDIRECT_URL);
    httpResponse.sendRedirect(uri);
}

84. AuthorizationServerFilter#doFilter()

Project: apis
Source File: AuthorizationServerFilter.java
View license
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    if (handledCorsPreflightRequest(request, response)) {
        return;
    }
    /*
     * The Access Token from the Client app as documented in
     * http://tools.ietf.org/html/draft-ietf-oauth-v2#section-7
     */
    final String accessToken = getAccessToken(request);
    if (accessToken != null) {
        VerifyTokenResponse tokenResponse = getVerifyTokenResponse(accessToken);
        if (isValidResponse(tokenResponse)) {
            request.setAttribute(VERIFY_TOKEN_RESPONSE, tokenResponse);
            chain.doFilter(request, response);
            return;
        }
    }
    sendError(response, HttpServletResponse.SC_FORBIDDEN, "OAuth2 endpoint");
}

85. WebRequestRunIdTelemetryModule#onBeginRequest()

View license
@Override
public void onBeginRequest(ServletRequest req, ServletResponse res) {
    HttpServletRequest httpRequest = (HttpServletRequest) req;
    String queryString = httpRequest.getQueryString();
    String runId = getRunIdFromQueryString(queryString);
    if (runId == null) {
        return;
    }
    RequestTelemetry httpRequestTelemetry = ThreadContext.getRequestTelemetryContext().getHttpRequestTelemetry();
    httpRequestTelemetry.getProperties().put(RUN_ID_QUERY_PARAM_NAME, runId);
}

86. WebSyntheticRequestTelemetryInitializer#onInitializeTelemetry()

View license
@Override
protected void onInitializeTelemetry(Telemetry telemetry) {
    RequestTelemetryContext telemetryContext = ThreadContext.getRequestTelemetryContext();
    if (telemetryContext == null) {
        return;
    }
    HttpServletRequest request = telemetryContext.getHttpServletRequest();
    if (request == null) {
        return;
    }
    String syntheticSourceHeader = request.getHeader(SYNTHETIC_TEST_SOURCE);
    if (Strings.isNullOrEmpty(syntheticSourceHeader)) {
        handlePossibleGSMSyntheticRequest(telemetry, request);
    } else {
        handleCommonSyntheticRequest(syntheticSourceHeader, telemetry, request);
    }
}

87. WebSessionTrackingTelemetryModule#onBeginRequest()

View license
/**
     * Begin request processing.
     *
     * @param req The request to process
     * @param res The response to modify
     */
@Override
public void onBeginRequest(ServletRequest req, ServletResponse res) {
    HttpServletRequest request = (HttpServletRequest) req;
    RequestTelemetryContext context = ThreadContext.getRequestTelemetryContext();
    SessionCookie sessionCookie = com.microsoft.applicationinsights.web.internal.cookies.Cookie.getCookie(SessionCookie.class, request, SessionCookie.COOKIE_NAME);
    if (sessionCookie == null) {
        return;
    }
    context.setSessionCookie(sessionCookie);
    String sessionId = sessionCookie.getSessionId();
    getTelemetrySessionContext(context).setId(sessionId);
}

88. WebUserTrackingTelemetryModule#onBeginRequest()

View license
/**
     * Begin request processing.
     *
     * @param req The request to process
     * @param res The response to modify
     */
@Override
public void onBeginRequest(ServletRequest req, ServletResponse res) {
    HttpServletRequest request = (HttpServletRequest) req;
    RequestTelemetryContext context = ThreadContext.getRequestTelemetryContext();
    UserCookie userCookie = com.microsoft.applicationinsights.web.internal.cookies.Cookie.getCookie(UserCookie.class, request, UserCookie.COOKIE_NAME);
    if (userCookie == null) {
        return;
    }
    String userId = userCookie.getUserId();
    Date acquisitionDate = userCookie.getAcquisitionDate();
    context.setUserCookie(userCookie);
    UserContext userContext = context.getHttpRequestTelemetry().getContext().getUser();
    userContext.setId(userId);
    userContext.setAcquisitionDate(acquisitionDate);
}

89. WebSyntheticRequestTelemetryInitializerTest#noSyntheticHeadersTest()

View license
@Test
public void noSyntheticHeadersTest() {
    WebSyntheticRequestTelemetryInitializer tested = new WebSyntheticRequestTelemetryInitializer();
    HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class);
    Mockito.doReturn("").when(mockRequest).getHeader(anyString());
    RequestTelemetryContext context = new RequestTelemetryContext(DateTimeUtils.getDateTimeNow().getTime(), mockRequest);
    ThreadContext.setRequestTelemetryContext(context);
    TraceTelemetry telemetry = new TraceTelemetry();
    tested.initialize(telemetry);
    assertTrue(Strings.isNullOrEmpty(telemetry.getContext().getSession().getId()));
    assertTrue(Strings.isNullOrEmpty(telemetry.getContext().getUser().getId()));
    assertTrue(Strings.isNullOrEmpty(telemetry.getContext().getOperation().getId()));
}

90. WebSyntheticRequestTelemetryInitializerTest#gsmSyntheticHeadersTest()

View license
@Test
public void gsmSyntheticHeadersTest() {
    WebSyntheticRequestTelemetryInitializer tested = new WebSyntheticRequestTelemetryInitializer();
    HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class);
    Mockito.doReturn("").when(mockRequest).getHeader(WebSyntheticRequestTelemetryInitializer.SYNTHETIC_TEST_SOURCE);
    Mockito.doReturn("A1").when(mockRequest).getHeader(WebSyntheticRequestTelemetryInitializer.SYNTHETIC_TEST_RUN_ID);
    Mockito.doReturn("A2").when(mockRequest).getHeader(WebSyntheticRequestTelemetryInitializer.SYNTHETIC_TEST_LOCATION);
    RequestTelemetryContext context = new RequestTelemetryContext(DateTimeUtils.getDateTimeNow().getTime(), mockRequest);
    ThreadContext.setRequestTelemetryContext(context);
    TraceTelemetry telemetry = new TraceTelemetry();
    tested.initialize(telemetry);
    assertEquals(telemetry.getContext().getOperation().getSyntheticSource(), WebSyntheticRequestTelemetryInitializer.SYNTHETIC_SOURCE_NAME);
    assertEquals(telemetry.getContext().getSession().getId(), "A1");
    assertEquals(telemetry.getContext().getUser().getId(), "A2");
}

91. WebRequestTrackingTelemetryModuleTests#createServletRequest()

View license
private ServletRequest createServletRequest(String queryString, String pathVariable) {
    HttpServletRequest request = mock(HttpServletRequest.class);
    String uri = DEFAULT_REQUEST_URI;
    if (pathVariable != null) {
        uri = uri.concat(pathVariable);
    }
    when(request.getRequestURI()).thenReturn(uri);
    when(request.getMethod()).thenReturn(HttpMethods.GET);
    when(request.getScheme()).thenReturn("http");
    when(request.getHeader("Host")).thenReturn("localhost:1234");
    when(request.getQueryString()).thenReturn(queryString);
    return request;
}

92. WebSessionTrackingTelemetryModuleTests#callOnBeginRequestAndGetCookieResult()

View license
// endregion Tests
// region Private
private Cookie callOnBeginRequestAndGetCookieResult(WebSessionTrackingTelemetryModule module) {
    ThreadContext.setRequestTelemetryContext(new RequestTelemetryContext(DateTimeUtils.getDateTimeNow().getTime()));
    module.initialize(TelemetryConfiguration.getActive());
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);
    final Cookie[] cookies = new Cookie[1];
    Mockito.doAnswer(new Answer() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            cookies[0] = ((Cookie) invocation.getArguments()[0]);
            return null;
        }
    }).when(response).addCookie(any(Cookie.class));
    module.onBeginRequest(request, response);
    return cookies[0];
}

93. RequestNameHandlerInterceptorAdapterTests#testAdapterSetRequestNameCorrectly()

View license
@Test
public void testAdapterSetRequestNameCorrectly() throws Exception {
    HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getMethod()).thenReturn(HttpMethods.GET);
    interceptorAdapter.preHandle(request, null, handlerMethod);
    String requestName = ThreadContext.getRequestTelemetryContext().getHttpRequestTelemetry().getName();
    String expectedRequestName = String.format("%s %s/%s", HttpMethods.GET, DEFAULT_CONTROLLER_NAME, DEFAULT_ACTION_NAME);
    Assert.assertEquals(expectedRequestName, requestName);
}

94. RequestNameHandlerInterceptorAdapterTests#testAdapterReturnTrueWhenExceptionIsThrown()

View license
@Test
public void testAdapterReturnTrueWhenExceptionIsThrown() throws Exception {
    HttpServletRequest request = mock(HttpServletRequest.class);
    Mockito.doAnswer(new Answer() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            throw new Exception("FATAL!");
        }
    }).when(request).getMethod();
    boolean result = interceptorAdapter.preHandle(request, null, handlerMethod);
    Assert.assertTrue("Adapter should return true.", result);
}

95. LoggingFilter#doFilter()

Project: Argus
Source File: LoggingFilter.java
View license
/**
     * Logs basic session information, request count and timing information.
     *
     * @param   request   The HTTP request.
     * @param   response  The HTTP response.
     * @param   chain     The filter chain to execute.
     *
     * @throws  IOException       If an I/O exception occurs.
     * @throws  ServletException  If an unknown error occurs.
     */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = HttpServletRequest.class.cast(request);
    String url = req.getRequestURI();
    LoggerFactory.getLogger(getClass()).info("Request started: {}", url);
    long start = System.currentTimeMillis();
    try {
        chain.doFilter(request, response);
    } finally {
        long delta = System.currentTimeMillis() - start;
        LoggerFactory.getLogger(getClass()).info("Request completed in {}ms: {}", delta, url);
    }
}

96. PerfFilter#doFilter()

Project: Argus
Source File: PerfFilter.java
View license
/**
     * Updates performance counters using the Argus monitoring service.
     *
     * @param   request   The HTTP request.
     * @param   response  The HTTP response.
     * @param   chain     The filter chain to execute.
     *
     * @throws  IOException       If an I/O error occurs.
     * @throws  ServletException  If an unknown error occurs.
     * 
     */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = HttpServletRequest.class.cast(request);
    long start = System.currentTimeMillis();
    try {
        chain.doFilter(request, response);
    } finally {
        long delta = System.currentTimeMillis() - start;
        HttpServletResponse resp = HttpServletResponse.class.cast(response);
        updateCounters(req, resp, delta);
    }
}

97. LeaderRedirectTest#testRedirectTargetNoAttribute()

Project: aurora
Source File: LeaderRedirectTest.java
View license
@Test
public void testRedirectTargetNoAttribute() throws Exception {
    HttpServletRequest mockRequest = mockRequest(null, null);
    replayAndMonitor(1);
    HostAndPort remote = HostAndPort.fromParts("foobar", HTTP_PORT);
    publishSchedulers(remote);
    assertEquals(Optional.of("http://foobar:500/some/path"), leaderRedirector.getRedirectTarget(mockRequest));
}

98. LeaderRedirectTest#testRedirectTargetWithAttribute()

Project: aurora
Source File: LeaderRedirectTest.java
View license
@Test
public void testRedirectTargetWithAttribute() throws Exception {
    HttpServletRequest mockRequest = mockRequest("/the/original/path", null);
    replayAndMonitor(1);
    HostAndPort remote = HostAndPort.fromParts("foobar", HTTP_PORT);
    publishSchedulers(remote);
    assertEquals(Optional.of("http://foobar:500/the/original/path"), leaderRedirector.getRedirectTarget(mockRequest));
}

99. LeaderRedirectTest#testRedirectTargetQueryString()

Project: aurora
Source File: LeaderRedirectTest.java
View license
@Test
public void testRedirectTargetQueryString() throws Exception {
    HttpServletRequest mockRequest = mockRequest(null, "bar=baz");
    replayAndMonitor(1);
    HostAndPort remote = HostAndPort.fromParts("foobar", HTTP_PORT);
    publishSchedulers(remote);
    assertEquals(Optional.of("http://foobar:500/some/path?bar=baz"), leaderRedirector.getRedirectTarget(mockRequest));
}

100. ServletSecurityProvider#authenticate()

View license
/** Authenticate a user from a username/password pair.
     *
     * @param username the user name to check
     * @param password the password to check
     * @return an AuthenticatedUser or null
     */
public AuthenticatedUser authenticate(MessageContext msgContext) {
    HttpServletRequest req = (HttpServletRequest) msgContext.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
    if (req == null)
        return null;
    log.debug(Messages.getMessage("got00", "HttpServletRequest"));
    Principal principal = req.getUserPrincipal();
    if (principal == null) {
        log.debug(Messages.getMessage("noPrincipal00"));
        return null;
    }
    log.debug(Messages.getMessage("gotPrincipal00", principal.getName()));
    return new ServletAuthenticatedUser(req);
}