Example usage for javax.servlet ServletRequest setAttribute

List of usage examples for javax.servlet ServletRequest setAttribute

Introduction

In this page you can find the example usage for javax.servlet ServletRequest setAttribute.

Prototype

public void setAttribute(String name, Object o);

Source Link

Document

Stores an attribute in this request.

Usage

From source file:org.sonatype.nexus.security.filter.authc.NexusHttpAuthenticationFilter.java

protected boolean executeAnonymousLogin(ServletRequest request, ServletResponse response) {
    if (getLogger().isDebugEnabled()) {
        getLogger().debug("Attempting to authenticate Subject as Anonymous request...");
    }//w  ww  . j a  v a2  s .co  m

    Subject subject = getSubject(request, response);

    UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
            getNexusConfiguration().getAnonymousUsername(), getNexusConfiguration().getAnonymousPassword());

    try {
        request.setAttribute(ANONYMOUS_LOGIN, Boolean.TRUE);

        subject.login(usernamePasswordToken);

        if (getLogger().isDebugEnabled()) {
            getLogger().debug("Successfully logged in as anonymous");
        }

        postAuthcEvent(request, getNexusConfiguration().getAnonymousUsername(), true);

        return true;
    } catch (AuthenticationException ae) {
        getLogger().info("Unable to authenticate user [anonymous] from IP Address "
                + RemoteIPFinder.findIP((HttpServletRequest) request));

        if (getLogger().isDebugEnabled()) {
            getLogger().debug("Unable to log in subject as anonymous", ae);
        }
    }

    // always default to false. If we've made it to this point in the code, that
    // means the authentication attempt either never occured, or wasn't successful:
    return false;
}

From source file:com.vilt.spring.context.response.OncePerRequestContextFilter.java

/**
 * This <code>doFilter</code> implementation stores a request attribute for
 * "already filtered", proceeding without filtering again if the attribute
 * is already there./*w  w  w.jav  a2s.co m*/
 * 
 * @see #getAlreadyFilteredAttributeName
 * @see #doFilterInternal
 */
public final void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws ServletException, IOException {
    if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) {
        throw new ServletException("OncePerRequestContextFilter just supports HTTP requests");
    }
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    String alreadyFilteredAttributeName = getAlreadyFilteredAttributeName();
    if (request.getAttribute(alreadyFilteredAttributeName) != null) {
        // Proceed without invoking this filter...
        filterChain.doFilter(request, response);
        return;
    }
    // Do invoke this filter...
    request.setAttribute(alreadyFilteredAttributeName, TRUE);
    try {
        doFilterInternal(httpRequest, httpResponse, filterChain);
    } finally {
        // Remove the "already filtered" request attribute for this
        // request.
        request.removeAttribute(alreadyFilteredAttributeName);
    }
}

From source file:no.kantega.publishing.admin.content.InputScreenRenderer.java

private int renderRepeaterAttribute(JspWriter out, ServletRequest request,
        Map<String, List<ValidationError>> fieldErrors, RepeaterAttribute repeaterAttribute, Integer tabIndex)
        throws IOException {

    try {//from   ww  w  .j av  a 2s .c  o m
        out.print("\n<div class=\"contentAttributeRepeater");
        if (attributeIsHiddenEmpty(repeaterAttribute)) {
            this.hiddenAttributes = true;
            out.print(" attributeHiddenEmpty");
        }
        out.print("\" id=\"" + AttributeHelper.getInputContainerName(repeaterAttribute.getNameIncludingPath())
                + "\" data-title=\"" + repeaterAttribute.getTitle() + "\"\n>\n");
        request.setAttribute("repeater", repeaterAttribute);
        request.setAttribute("repeaterFieldName",
                AttributeHelper.getInputFieldName(repeaterAttribute.getNameIncludingPath()));

        pageContext.include("/admin/publish/attributes/repeater_start.jsp");

        int numberOfRows = repeaterAttribute.getNumberOfRows();

        for (int rowNo = 0; rowNo < numberOfRows; rowNo++) {
            out.print("<div class=\"contentAttributeRepeaterRow\">\n");
            request.setAttribute("repeaterRowNo", rowNo);
            pageContext.include("/admin/publish/attributes/repeater_row_start.jsp");
            List<Attribute> attributes = repeaterAttribute.getRow(rowNo);
            for (Attribute attribute : attributes) {
                tabIndex = renderAttribute(out, request, fieldErrors, attribute, tabIndex);
                tabIndex += 10;
            }
            pageContext.include("/admin/publish/attributes/repeater_row_end.jsp");
            out.print("</div>\n");
        }
        pageContext.include("/admin/publish/attributes/repeater_end.jsp");
        out.print("</div>");
    } catch (Exception e) {
        log.error("", e);
        String errorMessage = LocaleLabels.getLabel("aksess.editcontent.exception",
                Aksess.getDefaultAdminLocale());
        out.print("<div class=\"errorText\">" + errorMessage + ":" + repeaterAttribute.getTitle() + "</div>\n");
    }

    return tabIndex;
}

From source file:org.apache.tiles.web.util.TilesDecorationFilter.java

/**
 * {@inheritDoc}//from   w  w  w.j ava  2 s .  c om
 */
public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain)
        throws IOException, ServletException {
    // If the request contains the prevent token, we must not reapply the definition.
    // This is used to ensure that filters mapped to wild cards do not infinately
    // loop.
    if (isPreventTokenPresent(req)) {
        filterChain.doFilter(req, res);
        return;
    }

    TilesContainer container = ServletUtil.getContainer(getServletContext(), containerKey);
    mutator.mutate(container.getAttributeContext(req, res), req);
    if (preventDecorationToken != null) {
        req.setAttribute(preventDecorationToken, Boolean.TRUE);
    }
    String definitionName = getDefinitionForRequest(req);
    container.render(definitionName, req, res);
}

From source file:no.sesat.search.http.filters.SiteLocatorFilter.java

/** The method to obtain the correct Site from the request.
 * It only returns a site with a locale supported by that site.
 ** @param servletRequest//  www. jav a  2s  .c  om
 * @return the site instance. or null if no such skin has been deployed.
 */
public static Site getSite(final ServletRequest servletRequest) {
    // find the current site. Since we are behind a ajp13 connection request.getServerName() won't work!
    // httpd.conf needs:
    //      1) "JkEnvVar SERVER_NAME" inside the virtual host directive.
    //      2) "UseCanonicalName Off" to assign ServerName from client's request.
    final String vhost = getServerName(servletRequest);

    // Tweak the port if SERVER_PORT has been explicitly set. (We may have gone through Apache or Cisco LB).
    final String correctedVhost = Site.SERVER_PORT > 0 && vhost.indexOf(':') > 0
            ? vhost.substring(0, vhost.indexOf(':') + 1) + Site.SERVER_PORT
            : vhost;

    LOG.trace(DEBUG_REQUESTED_VHOST + correctedVhost);

    // Construct the site object off the browser's locale, even if it won't finally be used.
    final Locale locale = servletRequest.getLocale();

    final Site result;
    try {
        result = Site.valueOf(SITE_CONTEXT, correctedVhost, locale);

        final SiteConfiguration.Context siteConfCxt = UrlResourceLoader.newSiteConfigurationContext(result);
        final SiteConfiguration siteConf = SiteConfiguration.instanceOf(siteConfCxt);
        servletRequest.setAttribute(SiteConfiguration.NAME_KEY, siteConf);

        if (LOG.isTraceEnabled()) { // MessageFormat.format(..) is expensive
            LOG.trace(MessageFormat.format(LOCALE_DETAILS, locale.getLanguage(), locale.getCountry(),
                    locale.getVariant()));
        }

        // Check if the browser's locale is supported by this skin. Use it if so.
        if (siteConf.isSiteLocaleSupported(locale)) {
            return result;
        }

        // Use the skin's default locale. For some reason that fails use JVM's default.
        final String[] prefLocale = null != siteConf.getProperty(SiteConfiguration.SITE_LOCALE_DEFAULT)
                ? siteConf.getProperty(SiteConfiguration.SITE_LOCALE_DEFAULT).split("_")
                : new String[] { Locale.getDefault().toString() };

        switch (prefLocale.length) {

        case 3:
            LOG.trace(result + INFO_USING_DEFAULT_LOCALE + prefLocale[0] + '_' + prefLocale[1] + '_'
                    + prefLocale[2]);
            return Site.valueOf(SITE_CONTEXT, correctedVhost,
                    new Locale(prefLocale[0], prefLocale[1], prefLocale[2]));

        case 2:
            LOG.trace(result + INFO_USING_DEFAULT_LOCALE + prefLocale[0] + '_' + prefLocale[1]);
            return Site.valueOf(SITE_CONTEXT, correctedVhost, new Locale(prefLocale[0], prefLocale[1]));

        case 1:
        default:
            LOG.trace(result + INFO_USING_DEFAULT_LOCALE + prefLocale[0]);
            return Site.valueOf(SITE_CONTEXT, correctedVhost, new Locale(prefLocale[0]));

        }
    } catch (IllegalArgumentException iae) {
        return null;
    }
}

From source file:org.acmsl.commons.utils.http.HttpServletUtils.java

/**
 * Stores an object in the repository.//  w  w w .j  a va  2 s .c  o  m
 * @param object the object to store.
 * @param key the key.
 * @param request the request.
 * @param session the session.
 * @param servletContext the context.
 * @return <code>true</code> if the object has been stored successfully.
 */
public boolean store(@NotNull final Object object, @NotNull final String key,
        @Nullable final ServletRequest request, @Nullable final HttpSession session,
        @Nullable final ServletContext servletContext) {
    boolean result = false;

    // Thanks Sun for had missed an interface for
    // all classes that export setAttribute().
    if (request != null) {
        request.setAttribute(key, object);
        result = true;
    }

    if (session != null) {
        session.setAttribute(key, object);
        result = true;
    }

    if (servletContext != null) {
        servletContext.setAttribute(key, object);
        result = true;
    }

    return result;
}

From source file:org.glimpse.server.ConnectionFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    boolean userOk = false;
    String connectionId = GlimpseUtils.getConnectionId((HttpServletRequest) request);
    if (StringUtils.isNotEmpty(connectionId)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Connection id found : <" + connectionId + ">");
        }/*w w  w  .java2 s.  c om*/

        UserManager userManager = WebApplicationContextUtils.getWebApplicationContext(servletContext)
                .getBean(UserManager.class);
        String userId = userManager.getUserId(connectionId);
        if (StringUtils.isNotBlank(userId)) {
            if (logger.isDebugEnabled()) {
                logger.debug("User id is : <" + userId + ">");
            }

            request.setAttribute(GlimpseUtils.REQUEST_ATTRIBUTE_USER_ID, userId);
            UserAttributes userAttributes = userManager.getUserAttributes(userId);
            request.setAttribute(GlimpseUtils.REQUEST_ATTRIBUTE_USER_ATTRIBUTES, userAttributes);
            userOk = true;
        }
    }

    if (!userOk) {
        logger.debug("No valid connection id found");
        request.removeAttribute(GlimpseUtils.REQUEST_ATTRIBUTE_USER_ID);
        request.removeAttribute(GlimpseUtils.REQUEST_ATTRIBUTE_USER_ATTRIBUTES);
    }
    chain.doFilter(request, response);
}

From source file:edu.emory.cci.aiw.cvrg.eureka.servlet.filter.HaveUserRecordFilter.java

@Override
public void doFilter(ServletRequest inRequest, ServletResponse inResponse, FilterChain inFilterChain)
        throws IOException, ServletException {
    HttpServletRequest servletRequest = (HttpServletRequest) inRequest;
    HttpServletResponse servletResponse = (HttpServletResponse) inResponse;
    String remoteUser = servletRequest.getRemoteUser();
    if (!StringUtils.isEmpty(remoteUser)) {
        try {//  w  w w.  j a  v a2s. c om
            User user = this.servicesClient.getMe();
            if (!user.isActive()) {
                HttpSession session = servletRequest.getSession(false);
                if (session != null) {
                    session.invalidate();
                }
                sendForbiddenError(servletResponse, servletRequest, true);
            } else {
                inRequest.setAttribute("user", user);
                inFilterChain.doFilter(inRequest, inResponse);
            }
        } catch (ClientException ex) {
            if (Status.FORBIDDEN.equals(ex.getResponseStatus())) {
                HttpSession session = servletRequest.getSession(false);
                if (session != null) {
                    session.invalidate();
                }
                sendForbiddenError(servletResponse, servletRequest, false);
            } else if (Status.UNAUTHORIZED.equals(ex.getResponseStatus())) {
                HttpSession session = servletRequest.getSession(false);
                if (session != null) {
                    session.invalidate();
                }
                servletResponse.sendRedirect(servletRequest.getContextPath() + "/logout?goHome=true");
            } else {
                throw new ServletException("Error getting user " + servletRequest.getRemoteUser(), ex);
            }
        }
    } else {
        inFilterChain.doFilter(inRequest, inResponse);
    }
}

From source file:org.aludratest.cloud.selenium.impl.SeleniumHttpProxy.java

@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
    if (LOG.isTraceEnabled()) {
        // give a random ID for this request
        String id = Integer.toHexString((int) (Math.random() * Integer.MAX_VALUE));
        while (id.length() < 8) {
            id = "0" + id;
        }/*  w w w  .j  ava 2  s . com*/
        LOG.trace("service() enter for " + resource + ", unique request code " + id);
        req.setAttribute("selenium.requestId", id);
    }

    // wait for update proxy if in progress
    synchronized (SeleniumHttpProxy.class) {
    }

    super.service(req, res);

    if (Boolean.TRUE.equals(req.getAttribute("selenium.connectFailed"))) {
        ((HttpServletResponse) res).sendError(HttpServletResponse.SC_GATEWAY_TIMEOUT);
    }
}

From source file:org.eclipse.orion.server.useradmin.servlets.UserAuthFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    if ("POST".equals(httpRequest.getMethod()) && httpRequest.getParameter(UserConstants.KEY_RESET) == null) { //$NON-NLS-1$
        // either everyone can create users, or only the specific list
        if (authorizedAccountCreators == null
                || authorizedAccountCreators.contains(httpRequest.getRemoteUser())) {
            chain.doFilter(request, response);
            return;
        }/*from   w ww.  j a  va2 s .  c om*/
    }

    String login = authenticationService.authenticateUser(httpRequest, httpResponse, authProperties);
    if (login == null)
        return;

    request.setAttribute(HttpContext.REMOTE_USER, login);
    request.setAttribute(HttpContext.AUTHENTICATION_TYPE, authenticationService.getAuthType());

    try {
        String requestPath = httpRequest.getServletPath()
                + (httpRequest.getPathInfo() == null ? "" : httpRequest.getPathInfo());
        if (!AuthorizationService.checkRights(login, requestPath, httpRequest.getMethod())) {
            httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }
    } catch (JSONException e) {
        httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    chain.doFilter(request, response);
}