Example usage for org.springframework.web.context.request RequestContextHolder currentRequestAttributes

List of usage examples for org.springframework.web.context.request RequestContextHolder currentRequestAttributes

Introduction

In this page you can find the example usage for org.springframework.web.context.request RequestContextHolder currentRequestAttributes.

Prototype

public static RequestAttributes currentRequestAttributes() throws IllegalStateException 

Source Link

Document

Return the RequestAttributes currently bound to the thread.

Usage

From source file:ru.smsl.webkrona.util.FlashMap.java

/**
 * Removes the flash map from the window or session scope.
 *///w  w  w  .j  av  a2  s.  c om
public static void removeFlashMap() {
    RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
    requestAttributes.removeAttribute(FLASH_MAP_ATTRIBUTE, getFlashMapScope());
}

From source file:uk.ac.ebi.intact.editor.util.HybridSessionThreadScope.java

public Object resolveContextualObject(String key) {
    if (RequestContextHolder.getRequestAttributes() != null) {
        RequestAttributes attributes = RequestContextHolder.currentRequestAttributes();
        return attributes.resolveReference(key);
    }//from ww w  .j  a  va  2s.co  m

    return null;
}

From source file:org.jasig.portlet.cms.controller.PostValidator.java

@Override
public void validate(final Object arg0, final Errors errors) {
    final Post post = (Post) arg0;

    if (logger.isDebugEnabled())
        logger.debug("Validaing post content " + errors.getFieldValue("content"));
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "content", "invalid.post.content.empty");
    if (errors.getFieldValue("content") != null)
        if (post.getContent().trim().isEmpty() && !errors.hasErrors())
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "content", "invalid.post.content.empty");

    final RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
    final PortletRequest request = ((PortletRequestAttributes) requestAttributes).getRequest();
    final PortletPreferencesWrapper pref = new PortletPreferencesWrapper(request);

    if (pref.isXssValidationEnabled())
        validatePostContent(post, errors);

    validatePostAttachments(post, errors);

    if (logger.isDebugEnabled())
        if (errors.getErrorCount() == 0)
            logger.debug("Validated post successfully without errors");
        else//from www  .  ja  v  a 2 s.com
            logger.debug("Rejected post with " + errors.getErrorCount() + " errors");
}

From source file:py.una.pol.karaku.audit.KarakuRevisionListener.java

private boolean processJSFChange(KarakuRevisionEntity sre) {

    if (SecurityContextHolder.getContext() == null
            || SecurityContextHolder.getContext().getAuthentication() == null) {
        sre.setUsername(null);/*from   w  w  w.  j a  va2s  .c  o  m*/
        sre.setIp(null);
        return false;
    }

    notNull(SecurityContextHolder.getContext());
    notNull(SecurityContextHolder.getContext().getAuthentication());

    String userName = SecurityContextHolder.getContext().getAuthentication().getName();
    sre.setUsername(userName);

    String ip = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest()
            .getRemoteAddr();
    sre.setIp(ip);
    return true;

}

From source file:org.jresponder.service.SubscriberService.java

/**
 * Default log entry props//from   ww  w .ja v  a2 s . c  o m
 * @return
 */
private static Map<String, Object> defaultLogEntryProps() {

    Map<String, Object> myRet = new HashMap<String, Object>();

    try {
        // use some Spring magic to get the current request
        HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
                .getRequest();
        myRet.put("ip_address", req.getRemoteAddr());
    } catch (IllegalStateException e) {
        LoggerFactory.getLogger(SubscriberService.class).debug(
                "defaultLogEntryProps() got IllegalStateException - this is normal if testing outside of web env");
    }

    return myRet;
}

From source file:com.haulmont.restapi.auth.CubaUserAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
            .currentRequestAttributes();
    HttpServletRequest request = attributes.getRequest();

    String ipAddress = request.getRemoteAddr();

    if (authentication instanceof UsernamePasswordAuthenticationToken) {
        RestApiConfig config = configuration.getConfig(RestApiConfig.class);
        if (!config.getStandardAuthenticationEnabled()) {
            log.debug(/*from w  w  w. ja  va  2s.  c o  m*/
                    "Standard authentication is disabled. Property cuba.rest.standardAuthenticationEnabled is false");

            throw new InvalidGrantException("Authentication disabled");
        }

        UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;

        String login = (String) token.getPrincipal();

        UserSession session;
        try {
            String passwordHash = passwordEncryption.getPlainHash((String) token.getCredentials());

            LoginPasswordCredentials credentials = new LoginPasswordCredentials(login, passwordHash);
            credentials.setIpAddress(ipAddress);
            credentials.setClientType(ClientType.REST_API);
            credentials.setClientInfo(makeClientInfo(request.getHeader(HttpHeaders.USER_AGENT)));

            //if the locale value is explicitly passed in the Accept-Language header then set its value to the
            //credentials. Otherwise, the locale of the user should be used
            Locale locale = restAuthUtils.extractLocaleFromRequestHeader(request);
            if (locale != null) {
                credentials.setLocale(locale);
                credentials.setOverrideLocale(true);
            } else {
                credentials.setOverrideLocale(false);
            }

            session = authenticationService.login(credentials).getSession();
        } catch (AccountLockedException le) {
            log.info("Blocked user login attempt: login={}, ip={}", login, ipAddress);
            throw new LockedException("User temporarily blocked");
        } catch (RestApiAccessDeniedException ex) {
            log.info("User is not allowed to use the REST API {}", login);
            throw new BadCredentialsException("User is not allowed to use the REST API");
        } catch (LoginException e) {
            log.info("REST API authentication failed: {} {}", login, ipAddress);
            throw new BadCredentialsException("Bad credentials");
        }

        AppContext.setSecurityContext(new SecurityContext(session));

        UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(
                authentication.getPrincipal(), authentication.getCredentials(),
                getRoleUserAuthorities(authentication));
        @SuppressWarnings("unchecked")
        Map<String, String> details = (Map<String, String>) authentication.getDetails();
        details.put(SESSION_ID_DETAILS_ATTRIBUTE, session.getId().toString());
        result.setDetails(details);
        return result;
    }

    return null;
}

From source file:com.acc.storefront.security.cookie.EnhancedCookieGenerator.java

/**
 * Sets dynamically the {@link Cookie#setPath(String)} value using available
 * {@link HttpServletRequest#getContextPath()}.
 *///from   w w w  . j ava 2 s .c  o m
protected void setEnhancedCookiePath(final Cookie cookie) {
    if (!canUseDefaultPath()) {
        final HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .currentRequestAttributes()).getRequest();
        cookie.setPath(request.getContextPath());
    }
}

From source file:eu.supersede.fe.multitenant.CurrentTenantIdentifierResolverImpl.java

/**
 * Return the identifier of the currently used tenant.
 *//*  www  .  j a  v  a 2s  .  co  m*/
@Override
public String resolveCurrentTenantIdentifier() {
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

    if (requestAttributes != null) {
        String identifier = (String) requestAttributes.getAttribute("CURRENT_TENANT_IDENTIFIER",
                RequestAttributes.SCOPE_REQUEST);

        if (identifier != null) {
            return identifier;
        }
    }

    // current tenant identifier not set, this may happen on login, if present in header we can just use this one
    // TODO: investigate better (add MultiTenancyInterceptor before SecurityConfiguration)
    try {
        ServletRequestAttributes currentRequestAttributes = (ServletRequestAttributes) RequestContextHolder
                .currentRequestAttributes();
        String multiTenantId = currentRequestAttributes.getRequest().getHeader("TenantId");

        if (multiTenantId != null) {
            return multiTenantId;
        }
    } catch (IllegalStateException ex) {
        // throw if no request has been made (????)
    }

    return DEFAULT_TENANT_ID;
}

From source file:com.hack23.cia.web.impl.ui.application.views.common.pagemode.MainViewRegisterPageModContentFactoryImpl.java

@Secured({ "ROLE_ANONYMOUS" })
@Override//from   w  ww.ja v a  2s .  c o m
public Layout createContent(final String parameters, final MenuBar menuBar, final Panel panel) {
    final VerticalLayout content = createPanelContent();
    final String pageId = getPageId(parameters);

    getMenuItemFactory().createMainPageMenuBar(menuBar);

    final VerticalLayout registerLayout = new VerticalLayout();
    registerLayout.setSizeFull();

    final Panel formPanel = new Panel();
    formPanel.setSizeFull();

    registerLayout.addComponent(formPanel);

    final FormLayout formContent = new FormLayout();
    formPanel.setContent(formContent);

    final RegisterUserRequest reqisterRequest = new RegisterUserRequest();
    reqisterRequest.setSessionId(RequestContextHolder.currentRequestAttributes().getSessionId());
    reqisterRequest.setUsername("");
    reqisterRequest.setEmail("");
    reqisterRequest.setCountry("");
    reqisterRequest.setUserpassword("");
    final ClickListener reqisterListener = new RegisterUserClickListener(reqisterRequest,
            getApplicationManager());
    getFormFactory().addRequestInputFormFields(formContent, new BeanItem<>(reqisterRequest),
            RegisterUserRequest.class,
            Arrays.asList(new String[] { "username", "email", "country", "userpassword" }), "Register",
            reqisterListener);

    content.addComponent(registerLayout);

    panel.setCaption(CITIZEN_INTELLIGENCE_AGENCY_MAIN);
    getPageActionEventHelper().createPageEvent(ViewAction.VISIT_MAIN_VIEW, ApplicationEventGroup.USER,
            CommonsViews.MAIN_VIEW_NAME, parameters, pageId);

    return content;

}

From source file:net.groupbuy.controller.admin.BaseController.java

/**
 * ??/*w ww  . j ava  2  s .  co m*/
 * 
 * @param type
 *            
 * @param property
 *            
 * @param value
 *            
 * @param groups
 *            ?
 * @return ?
 */
protected boolean isValid(Class<?> type, String property, Object value, Class<?>... groups) {
    Set<?> constraintViolations = validator.validateValue(type, property, value, groups);
    if (constraintViolations.isEmpty()) {
        return true;
    } else {
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        requestAttributes.setAttribute(CONSTRAINT_VIOLATIONS_ATTRIBUTE_NAME, constraintViolations,
                RequestAttributes.SCOPE_REQUEST);
        return false;
    }
}