Example usage for org.springframework.web.context.request ServletRequestAttributes getRequest

List of usage examples for org.springframework.web.context.request ServletRequestAttributes getRequest

Introduction

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

Prototype

public final HttpServletRequest getRequest() 

Source Link

Document

Exposes the native HttpServletRequest that we're wrapping.

Usage

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

/**
 * Return the identifier of the currently used tenant.
 *///  ww w  .  ja  v  a2 s  . c  o  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.scf.web.context.DefaultWebContext.java

@Override
protected HttpServletRequest getHttpServletRequest() {
    HttpServletRequest httpServletRequest = null;
    ServletRequestAttributes servletRequestAttributes = ((ServletRequestAttributes) RequestContextHolder
            .getRequestAttributes());/*from w  w w .j a va 2 s .  com*/
    if (servletRequestAttributes != null) {
        httpServletRequest = servletRequestAttributes.getRequest();
    }
    return httpServletRequest;
}

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();
        }/* w ww. j av  a  2  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:com.epam.cme.storefront.breadcrumb.impl.DefaultResourceBreadcrumbBuilder.java

protected MessageSource getMessageSource() {
    final ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
            .getRequestAttributes();//from   www.  j a  va  2  s  .c o  m
    if (requestAttributes != null) {
        final HttpServletRequest request = requestAttributes.getRequest();
        final Theme theme = RequestContextUtils.getTheme(request);
        if (theme != null) {
            return theme.getMessageSource();
        }
    }

    return null;
}

From source file:com.jaspersoft.jasperserver.remote.settings.DateTimeSettingsProvider.java

private File getSettingsFile(String path) {
    ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
    HttpServletRequest request = attr.getRequest();
    ServletContext servletContext = request.getSession().getServletContext();
    String realPath = servletContext.getRealPath(path);

    return new File(realPath);
}

From source file:nl.ctrlaltdev.harbinger.evidence.EvidenceCollector.java

private Evidence enhance(Evidence evidence) {
    if (evidence.getIp() == null) {
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (sra != null) {
            evidence = new Evidence(evidence, sra.getRequest());
        }//from   www.j a va2  s  .c  o m
    }
    if (evidence.getUser() == null) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null) {
            evidence = new Evidence(evidence, auth);
        }
    }
    return evidence;
}

From source file:com.cws.us.pws.controllers.ServicesController.java

@RequestMapping(value = "/default", method = RequestMethod.GET)
public final ModelAndView showDefaultPage() {
    final String methodName = ServicesController.CNAME + "#showDefaultPage()";

    if (DEBUG) {/*from  w ww  .  j a va  2s  .  co  m*/
        DEBUGGER.debug(methodName);
    }

    ModelAndView mView = new ModelAndView();

    final ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
            .currentRequestAttributes();
    final HttpServletRequest hRequest = requestAttributes.getRequest();
    final HttpSession hSession = hRequest.getSession();

    if (DEBUG) {
        DEBUGGER.debug("ServletRequestAttributes: {}", requestAttributes);
        DEBUGGER.debug("HttpServletRequest: {}", hRequest);
        DEBUGGER.debug("HttpSession: {}", hSession);

        DEBUGGER.debug("Dumping session content:");
        @SuppressWarnings("unchecked")
        Enumeration<String> sessionEnumeration = hSession.getAttributeNames();

        while (sessionEnumeration.hasMoreElements()) {
            String sessionElement = sessionEnumeration.nextElement();
            Object sessionValue = hSession.getAttribute(sessionElement);

            DEBUGGER.debug("Attribute: " + sessionElement + "; Value: " + sessionValue);
        }

        DEBUGGER.debug("Dumping request content:");
        @SuppressWarnings("unchecked")
        Enumeration<String> requestEnumeration = hRequest.getAttributeNames();

        while (requestEnumeration.hasMoreElements()) {
            String requestElement = requestEnumeration.nextElement();
            Object requestValue = hRequest.getAttribute(requestElement);

            DEBUGGER.debug("Attribute: " + requestElement + "; Value: " + requestValue);
        }

        DEBUGGER.debug("Dumping request parameters:");
        @SuppressWarnings("unchecked")
        Enumeration<String> paramsEnumeration = hRequest.getParameterNames();

        while (paramsEnumeration.hasMoreElements()) {
            String requestElement = paramsEnumeration.nextElement();
            Object requestValue = hRequest.getParameter(requestElement);

            DEBUGGER.debug("Parameter: " + requestElement + "; Value: " + requestValue);
        }
    }

    mView.setViewName(this.defaultPage);

    if (DEBUG) {
        DEBUGGER.debug("ModelAndView: {}", mView);
    }

    return mView;
}

From source file:de.appsolve.padelcampus.reporting.ErrorReporter.java

public void notify(Throwable ex) {
    boolean isDebug = java.lang.management.ManagementFactory.getRuntimeMXBean().getInputArguments().toString()
            .contains("jdwp");
    if (!isDebug) {
        if (ex != null && !IGNORED_EXCEPTION_CLASS_NAMES.contains(ex.getClass().getSimpleName())) {
            if (ex.getCause() == null
                    || !IGNORED_EXCEPTION_CLASS_NAMES.contains(ex.getCause().getClass().getSimpleName())) {
                try {
                    ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder
                            .currentRequestAttributes();
                    //log all errors when we don't have a request context, e.g. for scheduled tasks etc
                    if (attr == null || attr.getRequest() == null) {
                        LOG.error(ex.getMessage(), ex);
                    } else {
                        //if we have a request context, ignore bot requests
                        String userAgent = attr.getRequest().getHeader(HttpHeaders.USER_AGENT);
                        if (!StringUtils.isEmpty(userAgent)
                                && !IGNORED_USER_AGENT_PATTERN.matcher(userAgent).matches()) {
                            bugsnag.notify(ex);
                        }/* w w  w.java 2s  . c o m*/
                    }
                } catch (IllegalStateException e) {
                    LOG.error(ex.getMessage(), ex);
                }

            }
        }
    }
}

From source file:nl.surfnet.coin.selfservice.service.impl.CsaMock.java

private String getLocale() {
    Locale locale = null;//  www . j  a  v  a 2  s  .c  o  m
    ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    if (sra != null) {
        HttpServletRequest request = sra.getRequest();
        if (request != null) {
            locale = RequestContextUtils.getLocale(request);
        }
    }
    return locale != null ? locale.getLanguage() : "en";

}

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 ww.j av  a  2 s. c om
                    "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;
}