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:org.broadleafcommerce.common.web.resource.BroadleafResourceHttpRequestHandler.java

protected void establishThinRequestContext() {
    BroadleafRequestContext oldBrc = BroadleafRequestContext.getBroadleafRequestContext();
    if (oldBrc == null || oldBrc.getSite() == null || oldBrc.getTheme() == null) {
        // Resolving sites and sandboxes is often dependent on having a security context present in the request.
        // For example, resolving a sandbox requires the current user to have the BLC_ADMIN_USER in his Authentication.
        // For performance reasons, we do not go through the entire Spring Security filter chain on requests
        // for resources like JavaScript and CSS files. However, when theming is enabled, we potentially have to
        // resolve a specific version of the theme for a sandbox so that we can replace variables appropriately. This
        // then depends on the sandbox being resolved, which requires the Authentication object to be present.
        // We will grab the Authentication object associated with this user's session and set it on the
        // SecurityContextHolder since Spring Security will be bypassed.
        HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();//from  w  w  w .  ja v a  2s . co  m
        HttpSession session = req.getSession(false);
        SecurityContext ctx = readSecurityContextFromSession(session);
        if (ctx != null) {
            SecurityContextHolder.setContext(ctx);
        }

        BroadleafRequestContext newBrc = new BroadleafRequestContext();
        if (!isGlobalAdmin(req)) {
            ServletWebRequest swr = new ServletWebRequest(req);
            newBrc.setSite(siteResolver.resolveSite(swr, true));
            newBrc.setSandBox(sbResolver.resolveSandBox(swr, newBrc.getSite()));
            BroadleafRequestContext.setBroadleafRequestContext(newBrc);
            newBrc.setTheme(themeResolver.resolveTheme(swr));
        }
    }
}

From source file:org.broadleafcommerce.common.web.resource.resolver.BLCJSResourceResolver.java

protected Resource convertResource(Resource origResource, String resourceFileName) throws IOException {
    byte[] bytes = FileCopyUtils.copyToByteArray(origResource.getInputStream());
    String content = new String(bytes, DEFAULT_CHARSET);

    String newContent = content;/*w ww.ja  va2 s.c  om*/
    if (!StringUtils.isEmpty(content)) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        newContent = newContent.replace("//BLC-SERVLET-CONTEXT", request.getContextPath());

        String siteBaseUrl = urlResolver.getSiteBaseUrl();
        if (!StringUtils.isEmpty(siteBaseUrl)) {
            newContent = newContent.replace("//BLC-SITE-BASEURL", siteBaseUrl);
        }
    }

    return new GeneratedResource(newContent.getBytes(), resourceFileName);
}

From source file:org.broadleafcommerce.core.web.order.SessionOrderLockManager.java

protected HttpServletRequest getRequest() {
    if (RequestContextHolder.getRequestAttributes() == null) {
        return null;
    }// w w w . j  a v  a  2 s.  com
    return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
}

From source file:org.broadleafcommerce.openadmin.server.service.ExploitProtectionServiceImpl.java

@Override
public String getCSRFToken() throws ServiceException {
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
            .getRequest();// w  w  w  . ja v a2s . c o m
    HttpSession session = request.getSession();
    String token = (String) session.getAttribute(CSRFTOKEN);
    if (StringUtils.isEmpty(token)) {
        try {
            token = RandomGenerator.generateRandomId("SHA1PRNG", 32);
        } catch (NoSuchAlgorithmException e) {
            LOG.error("Unable to generate random number", e);
            throw new ServiceException("Unable to generate random number", e);
        }
        session.setAttribute(CSRFTOKEN, token);
    }
    return token;
}

From source file:org.broadleafcommerce.openadmin.server.service.UtilityRemoteService.java

@Override
public String getWebAppContext() throws ServiceException {
    try {//from  w w w .jav  a 2 s.c  o  m
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        return request.getContextPath();
    } catch (Exception e) {
        LOG.error("problem performing operation", e);
        throw new ServiceException("problem performing operation", e);
    }
}

From source file:org.codehaus.groovy.grails.plugins.web.api.ControllersApi.java

public static ApplicationContext getStaticApplicationContext() {
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    if (!(requestAttributes instanceof GrailsWebRequest)) {
        return null;
    }//from   www .j  av a  2  s  .c om

    return ((GrailsWebRequest) requestAttributes).getApplicationContext();
}

From source file:org.codehaus.groovy.grails.web.binding.DataBindingUtils.java

/**
 * Binds the given source object to the given target object performing type conversion if necessary
 *
 * @param domain The GrailsDomainClass instance
 * @param object The object to bind to//  w  w w .  j  av  a  2 s . c  om
 * @param source The source object
 * @param include The list of properties to include
 * @param exclude The list of properties to exclud
 * @param filter The prefix to filter by
 *
 * @see org.codehaus.groovy.grails.commons.GrailsDomainClass
 *
 * @return A BindingResult or null if it wasn't successful
 */
@SuppressWarnings("unchecked")
public static BindingResult bindObjectToDomainInstance(GrailsDomainClass domain, Object object, Object source,
        List include, List exclude, String filter) {
    BindingResult bindingResult = null;
    boolean useSpringBinder = false;
    GrailsApplication grailsApplication = null;
    if (domain != null) {
        grailsApplication = domain.getGrailsApplication();
    }
    if (grailsApplication == null) {
        grailsApplication = GrailsWebRequest.lookupApplication();
    }
    if (grailsApplication != null) {
        if (Boolean.TRUE.equals(grailsApplication.getFlatConfig().get("grails.databinding.useSpringBinder"))) {
            useSpringBinder = true;
        }
    }
    if (!useSpringBinder) {
        try {
            final DataBindingSource bindingSource = createDataBindingSource(grailsApplication,
                    object.getClass(), source);
            final DataBinder grailsWebDataBinder = getGrailsWebDataBinder(grailsApplication);
            grailsWebDataBinder.bind(object, bindingSource, filter, include, exclude);
        } catch (InvalidRequestBodyException e) {
            String messageCode = "invalidRequestBody";
            Class objectType = object.getClass();
            String defaultMessage = "An error occurred parsing the body of the request";
            String[] codes = getMessageCodes(messageCode, objectType);
            bindingResult = new BeanPropertyBindingResult(object, objectType.getName());
            bindingResult.addError(new ObjectError(bindingResult.getObjectName(), codes, null, defaultMessage));
        } catch (Exception e) {
            bindingResult = new BeanPropertyBindingResult(object, object.getClass().getName());
            bindingResult.addError(new ObjectError(bindingResult.getObjectName(), e.getMessage()));
        }
    } else {
        if (source instanceof GrailsParameterMap) {
            GrailsParameterMap parameterMap = (GrailsParameterMap) source;
            HttpServletRequest request = parameterMap.getRequest();
            GrailsDataBinder dataBinder = createDataBinder(object, include, exclude, request);
            dataBinder.bind(parameterMap, filter);
            bindingResult = dataBinder.getBindingResult();
        } else if (source instanceof HttpServletRequest) {
            HttpServletRequest request = (HttpServletRequest) source;
            GrailsDataBinder dataBinder = createDataBinder(object, include, exclude, request);
            performBindFromRequest(dataBinder, request, filter);
            bindingResult = dataBinder.getBindingResult();
        } else if (source instanceof Map) {
            Map propertyMap = convertPotentialGStrings((Map) source);
            GrailsDataBinder binder = createDataBinder(object, include, exclude, null);
            performBindFromPropertyValues(binder, new MutablePropertyValues(propertyMap), filter);
            bindingResult = binder.getBindingResult();
        }

        else {
            GrailsWebRequest webRequest = (GrailsWebRequest) RequestContextHolder.getRequestAttributes();
            if (webRequest != null) {
                GrailsDataBinder binder = createDataBinder(object, include, exclude,
                        webRequest.getCurrentRequest());
                HttpServletRequest request = webRequest.getCurrentRequest();
                performBindFromRequest(binder, request, filter);
            }
        }
    }

    if (domain != null && bindingResult != null) {
        BindingResult newResult = new ValidationErrors(object);
        for (Object error : bindingResult.getAllErrors()) {
            if (error instanceof FieldError) {
                FieldError fieldError = (FieldError) error;
                final boolean isBlank = BLANK.equals(fieldError.getRejectedValue());
                if (!isBlank) {
                    newResult.addError(fieldError);
                } else if (domain.hasPersistentProperty(fieldError.getField())) {
                    final boolean isOptional = domain.getPropertyByName(fieldError.getField()).isOptional();
                    if (!isOptional) {
                        newResult.addError(fieldError);
                    }
                } else {
                    newResult.addError(fieldError);
                }
            } else {
                newResult.addError((ObjectError) error);
            }
        }
        bindingResult = newResult;
    }
    MetaClass mc = GroovySystem.getMetaClassRegistry().getMetaClass(object.getClass());
    if (mc.hasProperty(object, "errors") != null && bindingResult != null) {
        ValidationErrors errors = new ValidationErrors(object);
        errors.addAllErrors(bindingResult);
        mc.setProperty(object, "errors", errors);
    }
    return bindingResult;
}

From source file:org.codehaus.groovy.grails.web.mapping.AbstractUrlMappingInfo.java

protected String evaluateNameForValue(Object value) {
    GrailsWebRequest webRequest = (GrailsWebRequest) RequestContextHolder.getRequestAttributes();
    return evaluateNameForValue(value, webRequest);
}

From source file:org.codehaus.groovy.grails.web.mapping.DefaultUrlCreator.java

public String createURL(Map parameterValues, String encoding) {
    if (parameterValues == null)
        parameterValues = Collections.EMPTY_MAP;
    GrailsWebRequest webRequest = (GrailsWebRequest) RequestContextHolder.getRequestAttributes();
    return createURLWithWebRequest(parameterValues, webRequest, true);
}

From source file:org.codehaus.groovy.grails.web.mapping.DefaultUrlCreator.java

private String createURLInternal(String controller, String action, Map<String, String> parameterValues,
        boolean includeContextPath) {
    GrailsWebRequest webRequest = (GrailsWebRequest) RequestContextHolder.getRequestAttributes();

    if (parameterValues == null)
        parameterValues = new HashMap<String, String>();
    boolean blankController = StringUtils.isBlank(controller);
    boolean blankAction = StringUtils.isBlank(action);

    if (!blankController) {
        parameterValues.put(GrailsControllerClass.CONTROLLER, controller);
    }/*from ww w. j  a  v  a2s .c  om*/
    if (!blankAction) {
        parameterValues.put(GrailsControllerClass.ACTION, action);
    }

    try {
        return createURLWithWebRequest(parameterValues, webRequest, includeContextPath);
    } finally {
        if (!blankController) {
            parameterValues.remove(GrailsControllerClass.CONTROLLER);
        }
        if (!blankAction) {
            parameterValues.remove(GrailsControllerClass.ACTION);
        }
    }
}