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:shiver.me.timbers.spring.security.CookieAndHeaderJwtAuthenticationFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (request.getAttribute(FILTER_APPLIED) != null) {
        chain.doFilter(request, response);
        return;/*from w  w w.j a va2s  .c  o  m*/
    }

    try {
        final Authentication authentication = tokenParser.parse((HttpServletRequest) request);
        securityContextHolder.getContext().setAuthentication(authentication);
        authenticationApplier.apply(authentication, (HttpServletResponse) response);
        request.setAttribute(FILTER_APPLIED, TRUE);
    } catch (JwtInvalidTokenException e) {
        log.debug("Failed JWT authentication.", e);
    }
    chain.doFilter(request, response);
}

From source file:jp.eisbahn.oauth2.server.spi.servlet.ProtectedResourceFilter.java

/**
 * Check the request for whether can access or not to APIs to access the protected
 * resource.//from w w  w  .  j a  v a2s  . c  o m
 * 
 * @param req The request object.
 * @param resp The response object.
 * @param chain The chain object to chain some filters.
 * @exception IOException When the error regarding I/O occurred.
 * @exception ServletException When the first argument is not a HttpServletRequest
 * instance.
 */
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
        throws IOException, ServletException {
    if (req instanceof HttpServletRequest) {
        HttpServletRequest httpRequest = (HttpServletRequest) req;
        HttpServletRequestAdapter adapter = new HttpServletRequestAdapter(httpRequest);
        try {
            Response response = protectedResource.handleRequest(adapter);
            req.setAttribute("client_id", response.getClientId());
            req.setAttribute("remote_user", response.getRemoteUser());
            req.setAttribute("scope", response.getScope());
            chain.doFilter(req, resp);
        } catch (OAuthError e) {
            if (resp instanceof HttpServletResponse) {
                HttpServletResponse httpResponse = (HttpServletResponse) resp;
                httpResponse.setStatus(e.getCode());
                List<String> params = new ArrayList<String>();
                params.add("error=\"" + e.getType() + "\"");
                if (StringUtils.isNotBlank(e.getDescription())) {
                    params.add("error_description=\"" + e.getDescription() + "\"");
                }
                String error = StringUtils.join(params, ", ");
                httpResponse.setHeader("WWW-Authenticate", "Bearer " + error);
            } else {
                throw new ServletException("This filter is available under HTTP Servlet container.");
            }
        }
    } else {
        throw new ServletException("This filter is available under HTTP Servlet container.");
    }
}

From source file:com.day.cq.wcm.foundation.forms.FormsHelper.java

/**
 * Sets the Sling {@link RequestDispatcherOptions} to be used when
 * forwarding to {@link #getForwardPath(SlingHttpServletRequest)}.
 * /*from ww  w .  jav a2 s .  co  m*/
 * @since 5.5
 * 
 * @param req
 *            The current request
 * @param options
 *            options to use with forward path
 */
public static void setForwardOptions(final ServletRequest req, final RequestDispatcherOptions options) {
    req.setAttribute(REQ_ATTR_FORWARD_OPTIONS, options);
}

From source file:com.day.cq.wcm.foundation.forms.FormsHelper.java

/**
 * Sets a flag to redirect to the HTTP referrer after the forward of a form
 * POST request. This will usually only be used if no explicit redirect is
 * already given in the ":redirect" parameter used by the Sling POST servlet.
 * /*from ww  w .j a  va 2  s.  c  o m*/
 * @since 5.5
 * 
 * @param request
 *            current request
 * @param redirectToReferrer
 *            <code>true</code> to enable the redirect to the referrer
 */
public static void setRedirectToReferrer(ServletRequest request, boolean redirectToReferrer) {
    if (redirectToReferrer) {
        request.setAttribute(REQ_ATTR_REDIRECT_TO_REFERRER, "true");
    } else {
        request.removeAttribute(REQ_ATTR_REDIRECT_TO_REFERRER);
    }
}

From source file:org.echocat.jemoni.jmx.support.ServletHealth.java

@Override
public void doFilter(@Nonnull ServletRequest request, @Nonnull ServletResponse response,
        @Nonnull FilterChain chain) throws IOException, ServletException {
    final StopWatch stopWatch = new StopWatch();
    request.setAttribute(CURRENT_REQUEST_STOP_WATCH_ATTRIBUTE_NAME, stopWatch);
    final ScopeMapping globalMapping = _patternToMapping.get(null);
    final ScopeMapping specificMapping = request instanceof HttpServletRequest
            ? getMappingFor(((HttpServletRequest) request).getRequestURI())
            : null;//from  w  ww .j a va  2  s  .  c  o m
    try {
        chain.doFilter(request, response);
    } finally {
        request.removeAttribute(CURRENT_REQUEST_STOP_WATCH_ATTRIBUTE_NAME);
        final Duration duration = stopWatch.getCurrentDuration();
        final ServletHealthInterceptor interceptor = _interceptor;
        if (interceptor == null || interceptor.isRecordAllowed(request, globalMapping, specificMapping)) {
            globalMapping.record(null, duration);
            if (specificMapping != null) {
                final String targetName = interceptor != null
                        ? interceptor.getSpecificTargetName(request, specificMapping)
                        : null;
                specificMapping.record(targetName, duration);
            }
        }
    }
}

From source file:org.kuali.rice.krad.web.bind.UifServletRequestDataBinder.java

/**
 * Calls {@link org.kuali.rice.krad.web.form.UifFormBase#preBind(HttpServletRequest)}, Performs data binding
 * from servlet request parameters to the form, initializes view object, then calls
 * {@link org.kuali.rice.krad.web.form.UifFormBase#postBind(javax.servlet.http.HttpServletRequest)}
 *
 * <p>/*  w  w  w.  j  a v a2 s.  c  om*/
 * The view is initialized by first looking for the {@code viewId} parameter in the request. If found, the view is
 * retrieved based on this id. If the id is not present, then an attempt is made to find a view by type. In order
 * to retrieve a view based on type, the view request parameter {@code viewTypeName} must be present. If all else
 * fails and the viewId is populated on the form (could be populated from a previous request), this is used to
 * retrieve the view.
 * </p>
 *
 * @param request - HTTP Servlet Request instance
 */
@Override
public void bind(ServletRequest request) {
    UifFormBase form = (UifFormBase) UifServletRequestDataBinder.this.getTarget();

    request.setAttribute(UifConstants.REQUEST_FORM, form);

    form.preBind((HttpServletRequest) request);

    _bind(request);

    request.setAttribute(UifConstants.PROPERTY_EDITOR_REGISTRY, this.bindingResult.getPropertyEditorRegistry());

    executeAutomaticLinking(request, form);

    if (!form.isUpdateNoneRequest()) {
        // attempt to retrieve a view by unique identifier first, either as request attribute or parameter
        String viewId = (String) request.getAttribute(UifParameters.VIEW_ID);
        if (StringUtils.isBlank(viewId)) {
            viewId = request.getParameter(UifParameters.VIEW_ID);
        }

        View view = null;
        if (StringUtils.isNotBlank(viewId)) {
            view = getViewService().getViewById(viewId);
        }

        // attempt to get view instance by type parameters
        if (view == null) {
            view = getViewByType(request, form);
        }

        // if view not found attempt to find one based on the cached form
        if (view == null) {
            view = getViewFromPreviousModel(form);

            if (view != null) {
                LOG.warn("Obtained viewId from cached form, this may not be safe!");
            }
        }

        if (view != null) {
            form.setViewId(view.getId());

        } else {
            form.setViewId(null);
        }

        form.setView(view);
    }

    // invoke form callback for custom binding
    form.postBind((HttpServletRequest) request);
}

From source file:org.sakaiproject.nakamura.http.qos.QoSFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    boolean accepted = false;
    QoSToken qoSToken = getQoSControl(request);
    try {//  w  w  w.  java  2s . c  o  m
        if (request.getAttribute(suspendedAttributeName) == null) {
            accepted = qoSToken.acquire(waitMs);
            if (accepted) {
                request.setAttribute(suspendedAttributeName, Boolean.FALSE);
            } else {
                LOGGER.debug("Suspending request");
                request.setAttribute(suspendedAttributeName, Boolean.TRUE);
                Continuation continuation = ContinuationSupport.getContinuation((HttpServletRequest) request,
                        qoSToken.getMutex());
                continuation.suspend(qoSToken.getSuspendTime());
                qoSToken.queue(continuation);
                return;
            }
        } else {
            Boolean suspended = (Boolean) request.getAttribute(suspendedAttributeName);

            if (suspended.booleanValue()) {
                request.setAttribute(suspendedAttributeName, Boolean.FALSE);
                if (request.getAttribute("javax.servlet.resumed") == Boolean.TRUE) {
                    qoSToken.acquire();
                    accepted = true;
                } else {
                    // Timeout! try 1 more time.
                    accepted = qoSToken.acquire(waitMs);
                }
            } else {
                // pass through resume of previously accepted request
                qoSToken.acquire();
                accepted = true;
            }
        }

        if (accepted) {
            chain.doFilter(request, response);
        } else {
            ((HttpServletResponse) response).sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        }
    } catch (InterruptedException e) {
        LOGGER.warn("QoS", e);
        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    } finally {
        if (accepted) {
            qoSToken.release();
        }
    }
}

From source file:org.opencms.jsp.CmsJspTagDisplay.java

/**
 * Includes the formatter rendering the given element.<p>
 *
 * @param element the element/*from   w  w  w  .  j a  v a 2s. com*/
 * @param formatter the formatter configuration bean
 * @param editable if editable
 * @param canCreate if new resources may be created
 * @param canDelete if the resource may be deleted
 * @param creationSiteMap the create location sub site
 * @param postCreateHandler the post create handler
 * @param context the page context
 * @param request the request
 * @param response the response
 */
public static void displayAction(CmsContainerElementBean element, I_CmsFormatterBean formatter,
        boolean editable, boolean canCreate, boolean canDelete, String creationSiteMap,
        String postCreateHandler, PageContext context, ServletRequest request, ServletResponse response) {

    if (CmsFlexController.isCmsRequest(request)) {
        // this will always be true if the page is called through OpenCms
        CmsObject cms = CmsFlexController.getCmsObject(request);
        Locale locale = cms.getRequestContext().getLocale();
        boolean isOnline = cms.getRequestContext().getCurrentProject().isOnlineProject();
        CmsJspStandardContextBean contextBean = CmsJspStandardContextBean.getInstance(request);
        CmsContainerElementBean parentElement = contextBean.getElement();

        try {
            if (formatter != null) {
                element.initResource(cms);
                element.initSettings(cms, formatter);
                boolean openedEditable = false;
                if (editable && contextBean.getIsEditMode()) {
                    if (CmsJspTagEditable.getDirectEditProvider(context) == null) {
                        I_CmsDirectEditProvider eb = new CmsAdvancedDirectEditProvider();
                        eb.init(cms, CmsDirectEditMode.TRUE, element.getSitePath());
                        request.setAttribute(I_CmsDirectEditProvider.ATTRIBUTE_DIRECT_EDIT_PROVIDER, eb);
                    }
                    openedEditable = CmsJspTagEdit.insertDirectEditStart(cms, context, element.getResource(),
                            canCreate, canDelete, null, creationSiteMap, postCreateHandler);
                }
                contextBean.setElement(element);
                try {
                    CmsJspTagInclude.includeTagAction(context,
                            cms.getRequestContext().removeSiteRoot(formatter.getJspRootPath()), null, locale,
                            false, isOnline, null, CmsRequestUtil.getAtrributeMap(request), request, response);
                } catch (JspException e) {
                    LOG.error(e.getLocalizedMessage(), e);
                }
                if (openedEditable) {
                    CmsJspTagEdit.insertDirectEditEnd(context);
                }
            }
        } catch (CmsException e) {
            LOG.error(e.getLocalizedMessage(), e);
        }
        contextBean.setElement(parentElement);
    }

}

From source file:org.eclipse.skalli.view.internal.filter.ext.GitGerritFilter.java

/**
 * Dispatch this request to error page//from w ww .j  av a  2s.  c  o m
 */
private void handleException(ServletRequest request, ServletResponse response, Exception e)
        throws ServletException, IOException {
    RequestDispatcher rd = request.getRequestDispatcher(Consts.URL_ERROR);
    request.setAttribute(ATTRIBUTE_EXCEPTION, e);
    rd.forward(request, response);
}

From source file:com.sonicle.webtop.core.app.shiro.WTFormAuthFilter.java

@Override
protected void setFailureAttribute(ServletRequest request, AuthenticationException ae) {
    String value = null;//www .  ja va2  s.com
    if (ae instanceof UnknownAccountException) {
        value = Login.LOGINFAILURE_INVALID;
    } else if (ae instanceof IncorrectCredentialsException) {
        value = Login.LOGINFAILURE_INVALID;
    } else if (ae instanceof LockedAccountException) {
        value = Login.LOGINFAILURE_INVALID;
    } else { // AuthenticationException
        value = Login.LOGINFAILURE_INVALID;
    }
    request.setAttribute(getFailureKeyAttribute(), value);
    //String message = ae.getMessage();
    //request.setAttribute(getFailureKeyAttribute(), message);
}