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

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

Introduction

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

Prototype

@Nullable
public static RequestAttributes getRequestAttributes() 

Source Link

Document

Return the RequestAttributes currently bound to the thread.

Usage

From source file:io.kahu.hawaii.rest.AbstractController.java

protected RequestLogBuilder requestLog() {

    String method = new Throwable().getStackTrace()[1].getMethodName();
    String type = logTypePrefix + "." + method;
    RequestLogBuilder builder = new RequestLogBuilder(logManager, type);

    try {// w ww. j ava2  s.co  m
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = sra.getRequest();

        // path variables
        Map<String, String> pathVariables = (Map<String, String>) request
                .getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
        if (pathVariables != null) {
            for (Map.Entry<String, String> entry : pathVariables.entrySet()) {
                builder.param(entry.getKey(), entry.getValue());
            }
        }

        // request parameters
        Enumeration<?> requestParameters = request.getParameterNames();
        while (requestParameters.hasMoreElements()) {
            String key = (String) requestParameters.nextElement();
            String[] values = request.getParameterValues(key);
            builder.param(key, values);
        }

    } catch (Throwable t) {
        logManager.warn(CoreLoggers.SERVER, "Unable to log request", t);
        // ignore
    }
    return builder.excludeParam("_");
}

From source file:com.lixiaocong.security.DaoBasedUserDetailsService.java

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
            .getRequest();/*  ww  w  . j a va2s. c  om*/
    if (request.getRequestURI().equals("/signin")) {
        String postcode = request.getParameter("imagecode");
        if (!codeService.check(postcode, request.getSession()))
            throw new UsernameNotFoundException("image code error");
    }
    com.lixiaocong.entity.User user = userRepository.findByUsername(username);
    if (user == null) {
        log.info("user not exists");
        throw new UsernameNotFoundException("user not exists");
    }
    Set<GrantedAuthority> authorities = new HashSet<>();

    authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
    if (user.isAdmin())
        authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));

    return new DaoBasedUserDetails(user.getId(), user.getUsername(), user.getPassword(), authorities);
}

From source file:org.jasig.portlet.emailpreview.dao.exchange.MailCredentialsProvider.java

@Override
public Authenticator getAuthenticator() {
    final RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    final Authenticator authenticator = (Authenticator) requestAttributes.getAttribute(
            MailCredentialsProvider.JAVAMAIL_CREDENTIALS_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST);
    return authenticator;
}

From source file:com.dushyant.sample.service.SampleGwtRpcServiceImpl.java

private PortletRequestAttributes getPortletRequestAttributes() {
    return (PortletRequestAttributes) RequestContextHolder.getRequestAttributes();
}

From source file:de.metas.ui.web.session.WebRestApiContextProvider.java

private final Properties getActualContext() {
    ///*from  ww w .  j  av  a 2  s.  co m*/
    // IMPORTANT: this method will be called very often, so please make sure it's FAST!
    //

    //
    // If there is currently a temporary context active, return it first
    final Properties temporaryCtx = temporaryCtxHolder.get();
    if (temporaryCtx != null) {
        logger.trace("Returning temporary context: {}", temporaryCtx);
        return temporaryCtx;
    }

    //
    // Get the context from current session
    final RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    if (requestAttributes != null) {
        Properties userSessionCtx = (Properties) requestAttributes.getAttribute(ATTRIBUTE_UserSessionCtx,
                RequestAttributes.SCOPE_SESSION);
        if (userSessionCtx == null) {
            // Create user session context
            userSessionCtx = new Properties();
            Env.setContext(userSessionCtx, CTXNAME_IsServerContext, false);

            requestAttributes.setAttribute(ATTRIBUTE_UserSessionCtx, userSessionCtx,
                    RequestAttributes.SCOPE_SESSION);

            if (logger.isDebugEnabled()) {
                logger.debug("Created user session context: sessionId={}, context={}",
                        requestAttributes.getSessionId(), userSessionCtx);
            }
        }

        logger.trace("Returning user session context: {}", temporaryCtx);
        return userSessionCtx;
    }

    //
    // If there was no current session it means we are running on server side, so return the server context
    logger.trace("Returning server context: {}", temporaryCtx);
    return serverCtx;
}

From source file:de.hybris.platform.security.captcha.ReCaptchaAspect.java

public Object advise(final ProceedingJoinPoint joinPoint) throws Throwable {

    final boolean captcaEnabledForCurrentStore = isCaptcaEnabledForCurrentStore();
    if (captcaEnabledForCurrentStore) {
        final List<Object> args = Arrays.asList(joinPoint.getArgs());
        HttpServletRequest request = (HttpServletRequest) CollectionUtils.find(args,
                PredicateUtils.instanceofPredicate(HttpServletRequest.class));

        if (request == null
                && RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes) {
            final ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                    .getRequestAttributes();
            request = requestAttributes.getRequest();
        }//ww w.  j  a  va2 s .c o  m

        if (request != null) {
            request.setAttribute("captcaEnabledForCurrentStore", Boolean.valueOf(captcaEnabledForCurrentStore));
            request.setAttribute("recaptchaPublicKey",
                    getSiteConfigService().getProperty(RECAPTCHA_PUBLIC_KEY_PROPERTY));
            final String challengeFieldValue = request.getParameter(RECAPTCHA_CHALLENGE_FIELD_PARAM);
            final String responseFieldValue = request.getParameter(RECAPTCHA_RESPONSE_FIELD_PARAM);
            if ((StringUtils.isBlank(challengeFieldValue) || StringUtils.isBlank(responseFieldValue))
                    || !checkAnswer(request, challengeFieldValue, responseFieldValue)) {
                // if there is an error add a message to binding result.
                final BindingResult bindingResult = (BindingResult) CollectionUtils.find(args,
                        PredicateUtils.instanceofPredicate(BindingResult.class));
                if (bindingResult != null) {
                    bindingResult.reject("recaptcha.challenge.field.invalid", "Challenge Answer is invalid.");
                }
                request.setAttribute("recaptchaChallangeAnswered", Boolean.FALSE);
            }
        }
    }
    return joinPoint.proceed();
}

From source file:at.ac.univie.isc.asio.engine.ReactiveInvokerTest.java

@Test
public void should_execute_invocation_in_captured_context() throws Exception {
    final Boolean contextPresent = subject.accept(CommandBuilder.empty().build()).isEmpty()
            .map(new Func1<Boolean, Boolean>() {
                @Override/*from  w  w w. ja  v  a2 s. c o  m*/
                public Boolean call(final Boolean aBoolean) {
                    return RequestContextHolder.getRequestAttributes() != null;
                }
            }).toBlocking().single();
    assertThat(contextPresent, equalTo(true));
}

From source file:org.craftercms.commons.jackson.mvc.GDataPropertyFilter.java

protected boolean checkProperty(final String propertyName) {

    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
            .getRequest();//from   ww w.j a  va2s  . com
    Object attributes = request.getParameter(selectorParameterName);

    if (attributes == null) {
        return true;
    } else {
        List<String> query = parseRequestSelector(attributes.toString());
        if (query == null || query.isEmpty()) {
            log.warn("Result of parsing selector {} is null or empty ignoring selector", attributes);
            return true;
        } else {
            return checkPropertyAgainstPattern(query, propertyName);
        }
    }
}

From source file:org.springjutsu.validation.context.MVCFormValidationContextHandler.java

/**
 * @return true if the current web request is associated
 * with Spring MVC./*from w ww. j  a v a  2  s  . c  o  m*/
 */
public static boolean isMVCRequest() {
    return RequestContextHolder.getRequestAttributes() != null;
}

From source file:com.vsc.dayspring.security.ShiroDbRealm.java

/**
 * ?,./* ww w.  j  a  v  a  2  s . c o  m*/
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
        throws AuthenticationException {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
            .getRequestAttributes();
    String serverName = attributes.getRequest().getHeader("Host");
    if (StringUtils.isEmpty(serverName)) {
        serverName = attributes.getRequest().getServerName();
    }

    if (this.getSubDomains(KEY_APP_DOMAIN).contains(serverName)) {
        throw new AuthenticationException();
    }

    MyUsernamePasswordToken token = (MyUsernamePasswordToken) authcToken;

    List<Account> accountList = null;
    List<CompanyAccount> companyAccountList = null;

    if (token.getUsername() == null) {
        return null;
    }

    byte[] salt = null;

    //DEMO&&?
    if (CodeConstant.CODE_WHETHER_1.equals(CodeConstant.SYS_TYPE_FLAG)
            && CodeConstant.CODE_LOGIN_TYPE_SERIAL_NUMBER_USER.equals(token.getType())) {
        companyAccountList = compAccountService.getCompAccountBySerialNumber(token.getUsername());
        if (CollectionUtils.isEmpty(companyAccountList)) {
            throw new AuthenticationException();
        }
        CompanyAccount loginInfo = companyAccountList.get(0);
        Company company = companyMapper.selectByPrimaryKey(loginInfo.getCompUuid());
        if (company == null || CodeConstant.CODE_DELETE_FLAG_YES.equals(company.getDeleteFlag())) {
            throw new AuthenticationException();
        }
        loginInfo.setCompInitFlg(company.getInitFlag());
        loginInfo.setCompName(company.getShortName());
        salt = DigestUtils.generateSalt(AuthServer.SALT_SIZE);
        SimpleHash hash = new SimpleHash(HASH_ALGORITHM, token.getPassword(), ByteSource.Util.bytes(salt),
                HASH_INTERATIONS);
        return new SimpleAuthenticationInfo(loginInfo, hash.toHex(), ByteSource.Util.bytes(salt), getName());
    } else {

        if (token.getUsername().toLowerCase().indexOf(ConditionConstant.CONDITION_AT_YOWITS_COM) > 0) {
            // TODO DEBUG
            try {
                accountList = authServer.getLoginInfo(token.getUsername());
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            // TODO DEBUG
            try {
                companyAccountList = compAccountService.getCompAccountCountNoOrgByLoginId(token.getUsername());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (!CollectionUtils.isEmpty(companyAccountList)) {

            CompanyAccount loginInfo = companyAccountList.get(0);

            if ("1".equals(loginInfo.getDeleteFlag())) {

                throw new AuthenticationException();
            }

            // ?wizard uuid????
            if (StringUtils.isEmpty(loginInfo.getWizardUuid())) {
                Company company = companyMapper.selectByPrimaryKey(loginInfo.getCompUuid());

                if (company == null || CodeConstant.CODE_DELETE_FLAG_YES.equals(company.getDeleteFlag())) {

                    throw new AuthenticationException();
                }

                loginInfo.setCompInitFlg(company.getInitFlag());
                loginInfo.setCompName(company.getShortName());
            }

            salt = EncodeUtils.decodeHex(loginInfo.getSalt());
            return new SimpleAuthenticationInfo(loginInfo, loginInfo.getPassword(), ByteSource.Util.bytes(salt),
                    getName());

        } else if (!CollectionUtils.isEmpty(accountList)) {

            if (!this.getSubDomains(KEY_OFFIC_DOMAIN).contains(serverName)) {
                throw new AuthenticationException();
            }

            Account loginInfo = accountList.get(0);

            if ("1".equals(loginInfo.getDeleteFlag())) {
                throw new AuthenticationException();
            }

            salt = EncodeUtils.decodeHex(loginInfo.getSalt());
            return new SimpleAuthenticationInfo(loginInfo, loginInfo.getPassword(), ByteSource.Util.bytes(salt),
                    getName());

        } else {
            throw new AuthenticationException();
        }
    }
}