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.codehaus.groovy.grails.web.mapping.RegexUrlMapping.java

@SuppressWarnings({ "unchecked" })
private String createURLInternal(Map paramValues, String encoding, boolean includeContextPath) {

    if (encoding == null)
        encoding = "utf-8";

    String contextPath = "";
    if (includeContextPath) {
        GrailsWebRequest webRequest = (GrailsWebRequest) RequestContextHolder.getRequestAttributes();
        if (webRequest != null) {
            contextPath = webRequest.getAttributes().getApplicationUri(webRequest.getCurrentRequest());
        }/*from www  .  j a  v a 2  s .c om*/
    }
    if (paramValues == null)
        paramValues = Collections.EMPTY_MAP;
    StringBuilder uri = new StringBuilder(contextPath);
    Set usedParams = new HashSet();

    String[] tokens = urlData.getTokens();
    int paramIndex = 0;
    for (int i = 0; i < tokens.length; i++) {
        String token = tokens[i];
        if (i == tokens.length - 1 && urlData.hasOptionalExtension()) {
            token += UrlMapping.OPTIONAL_EXTENSION_WILDCARD;
        }
        Matcher m = OPTIONAL_EXTENSION_WILDCARD_PATTERN.matcher(token);
        if (m.find()) {

            if (token.startsWith(CAPTURED_WILDCARD)) {
                ConstrainedProperty prop = constraints[paramIndex++];
                String propName = prop.getPropertyName();

                Object value = paramValues.get(propName);
                usedParams.add(propName);

                if (value != null) {
                    token = token.replaceFirst(DOUBLE_WILDCARD_PATTERN.pattern(), value.toString());
                } else if (prop.isNullable()) {
                    break;
                }
            }
            uri.append(SLASH);
            ConstrainedProperty prop = constraints[paramIndex++];
            String propName = prop.getPropertyName();
            Object value = paramValues.get(propName);
            usedParams.add(propName);
            if (value != null) {
                String ext = "." + value;
                uri.append(token.replace(OPTIONAL_EXTENSION_WILDCARD + '?', ext)
                        .replace(OPTIONAL_EXTENSION_WILDCARD, ext));
            } else {
                uri.append(token.replace(OPTIONAL_EXTENSION_WILDCARD + '?', "")
                        .replace(OPTIONAL_EXTENSION_WILDCARD, ""));
            }

            continue;
        }
        if (token.endsWith("?")) {
            token = token.substring(0, token.length() - 1);
        }
        m = DOUBLE_WILDCARD_PATTERN.matcher(token);
        if (m.find()) {
            StringBuffer buf = new StringBuffer();
            do {
                ConstrainedProperty prop = constraints[paramIndex++];
                String propName = prop.getPropertyName();
                Object value = paramValues.get(propName);
                usedParams.add(propName);
                if (value == null && !prop.isNullable()) {
                    throw new UrlMappingException("Unable to create URL for mapping [" + this
                            + "] and parameters [" + paramValues + "]. Parameter [" + prop.getPropertyName()
                            + "] is required, but was not specified!");
                } else if (value == null) {
                    m.appendReplacement(buf, "");
                } else {
                    m.appendReplacement(buf, Matcher.quoteReplacement(value.toString()));
                }
            } while (m.find());

            m.appendTail(buf);

            try {
                String v = buf.toString();
                if (v.indexOf(SLASH) > -1 && CAPTURED_DOUBLE_WILDCARD.equals(token)) {
                    // individually URL encode path segments
                    if (v.startsWith(SLASH)) {
                        // get rid of leading slash
                        v = v.substring(SLASH.length());
                    }
                    String[] segs = v.split(SLASH);
                    for (String segment : segs) {
                        uri.append(SLASH).append(encode(segment, encoding));
                    }
                } else if (v.length() > 0) {
                    // original behavior
                    uri.append(SLASH).append(encode(v, encoding));
                } else {
                    // Stop processing tokens once we hit an empty one.
                    break;
                }
            } catch (UnsupportedEncodingException e) {
                throw new ControllerExecutionException("Error creating URL for parameters [" + paramValues
                        + "], problem encoding URL part [" + buf + "]: " + e.getMessage(), e);
            }
        } else {
            uri.append(SLASH).append(token);
        }
    }
    populateParameterList(paramValues, encoding, uri, usedParams);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Created reverse URL mapping [" + uri.toString() + "] for parameters [" + paramValues + "]");
    }
    return uri.toString();
}

From source file:org.codehaus.groovy.grails.web.pages.GroovyPageWritable.java

public GroovyPageWritable(GroovyPageMetaInfo metaInfo, boolean allowSettingContentType) {
    this.metaInfo = metaInfo;
    this.allowSettingContentType = allowSettingContentType;
    webRequest = (GrailsWebRequest) RequestContextHolder.getRequestAttributes();
    if (webRequest != null) {
        request = webRequest.getCurrentRequest();
        HttpServletResponse wrapped = WrappedResponseHolder.getWrappedResponse();
        response = wrapped != null ? wrapped : webRequest.getCurrentResponse();
    }/*from  w w  w. ja  v  a2s. c om*/
    showSource = shouldShowGroovySource();
    debugTemplates = shouldDebugTemplates();
    if (debugTemplates) {
        debugTemplatesIdCounter = (AtomicInteger) request
                .getAttribute(ATTRIBUTE_NAME_DEBUG_TEMPLATES_ID_COUNTER);
        if (debugTemplatesIdCounter == null) {
            debugTemplatesIdCounter = new AtomicInteger(0);
            request.setAttribute(ATTRIBUTE_NAME_DEBUG_TEMPLATES_ID_COUNTER, debugTemplatesIdCounter);
        }
    }
}

From source file:org.codehaus.groovy.grails.web.servlet.mvc.SimpleGrailsController.java

/**
 * <p>Wraps regular request and response objects into Grails request and response objects.
 *
 * <p>It can handle maps as model types next to ModelAndView instances.
 *
 * @param request HTTP request//from ww  w. j  ava  2  s.  c o m
 * @param response HTTP response
 * @return the model
 */
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    // Step 1: determine the correct URI of the request.
    String uri = urlPathHelper.getPathWithinApplication(request);
    if (LOG.isDebugEnabled()) {
        LOG.debug("[SimpleGrailsController] Processing request for uri [" + uri + "]");
    }

    RequestAttributes ra = RequestContextHolder.getRequestAttributes();

    Assert.state(ra instanceof GrailsWebRequest, "Bound RequestContext is not an instance of GrailsWebRequest");

    GrailsWebRequest webRequest = (GrailsWebRequest) ra;

    ModelAndView mv = grailsControllerHelper.handleURI(uri, webRequest);

    if (mv != null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("[SimpleGrailsController] Forwarding model and view [" + mv + "] with class ["
                    + (mv.getView() != null ? mv.getView().getClass().getName() : mv.getViewName()) + "]");
        }
    }
    return mv;
}

From source file:org.codehaus.groovy.grails.web.util.WebUtils.java

/**
 * Removes any GrailsWebRequest instance from the current request.
 *//*from   w w  w .j  a  v a 2s .  c  om*/
public static void clearGrailsWebRequest() {
    RequestAttributes reqAttrs = RequestContextHolder.getRequestAttributes();
    if (reqAttrs != null) {
        // First remove the web request from the HTTP request attributes.
        GrailsWebRequest webRequest = (GrailsWebRequest) reqAttrs;
        webRequest.getRequest().removeAttribute(GrailsApplicationAttributes.WEB_REQUEST);

        // Now remove it from RequestContextHolder.
        RequestContextHolder.resetRequestAttributes();
    }
}

From source file:org.ednovo.gooru.application.util.SerializerUtil.java

private static Object protocolSwitch(final Object model) {
    HttpServletRequest request = null;//from  w  w w .  ja  v a 2 s  .c  o  m
    if (RequestContextHolder.getRequestAttributes() != null) {
        request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }
    if (request != null) {
        final String requestProtocol = request.getAttribute("requestProtocol") != null
                ? (String) request.getAttribute("requestProtocol")
                : null;
        final String protocolAutoSwitch = request.getAttribute("protocolAutoSwitch") != null
                ? (String) request.getAttribute("protocolAutoSwitch")
                : "true";
        if (protocolAutoSwitch != null && protocolAutoSwitch.equalsIgnoreCase("true")) {
            if (model instanceof Resource) {
                BaseUtil.changeHttpsProtocolByHeader(((Resource) model), requestProtocol,
                        BaseUtil.isSecure(request), request.getMethod());
            } else if (model instanceof CollectionItem) {
                BaseUtil.changeHttpsProtocolByHeader(((CollectionItem) model).getResource(), requestProtocol,
                        BaseUtil.isSecure(request), request.getMethod());
            } else if (model instanceof List) {
                List list = (List<?>) model;
                if (list != null && list.size() > 0 && list.get(0) instanceof Resource) {
                    for (int resourceIndex = 0; resourceIndex < list.size(); resourceIndex++) {
                        BaseUtil.changeHttpsProtocolByHeader(((Resource) list.get(resourceIndex)),
                                requestProtocol, BaseUtil.isSecure(request), request.getMethod());
                    }
                } else if (list != null && list.size() > 0 && list.get(0) instanceof CollectionItem) {
                    for (int resourceIndex = 0; resourceIndex < list.size(); resourceIndex++) {
                        BaseUtil.changeHttpsProtocolByHeader(
                                ((CollectionItem) list.get(resourceIndex)).getResource(), requestProtocol,
                                BaseUtil.isSecure(request), request.getMethod());
                    }
                }
            } else if (model instanceof Collection) {
                if (((Collection) model) != null && ((Collection) model).getCollectionItems() != null) {
                    for (CollectionItem collectionItem : ((Collection) model).getCollectionItems()) {
                        BaseUtil.changeHttpsProtocolByHeader(collectionItem.getResource(), requestProtocol,
                                BaseUtil.isSecure(request), request.getMethod());
                    }
                }
            }

        }
    }
    return model;
}

From source file:org.ednovo.gooru.application.util.SerializerUtil.java

private static void log(final Object model, final String data) {
    HttpServletRequest request = null;//w  w w  .java2 s . c  om
    if (RequestContextHolder.getRequestAttributes() != null) {
        request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (request != null && request.getMethod() != null
                && (request.getMethod().equalsIgnoreCase(RequestMethod.POST.name())
                        || request.getMethod().equalsIgnoreCase(RequestMethod.PUT.name()))) {
            org.json.simple.JSONObject payLoadObject = new org.json.simple.JSONObject();
            try {
                if (SessionContextSupport.getLog() != null
                        && SessionContextSupport.getLog().get("payLoadObject") != null) {
                    org.json.simple.parser.JSONParser payLoadParser = new org.json.simple.parser.JSONParser();
                    payLoadObject = (org.json.simple.JSONObject) payLoadParser
                            .parse(SessionContextSupport.getLog().get("payLoadObject").toString());
                }
                try {
                    if (data != null) {
                        payLoadObject.put("data", data);
                    }
                } catch (Exception e) {
                    LOGGER.error("Error: " + e);
                }

            } catch (Exception e) {
                LOGGER.error("Error : " + e);
            }

            SessionContextSupport.putLogParameter("payLoadObject", payLoadObject.toString());
        }
    }
}

From source file:org.ednovo.gooru.core.application.util.BaseUtil.java

public static String changeHttpsProtocol(String url) {
    if (RequestContextHolder.getRequestAttributes() != null) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();//from  w  w  w .  j a va  2s.  c om
        if (request != null && request.getRequestURL() != null && url != null && url.contains("http://")
                && request.getRequestURL().toString().contains("https://")) {
            url = url.replaceFirst("http://", "https://");
        }
    }
    return url;
}

From source file:org.ednovo.gooru.core.application.util.BaseUtil.java

public static String appendProtocol(String key) {
    ServletRequestAttributes requestAttributes = ((ServletRequestAttributes) RequestContextHolder
            .getRequestAttributes());//w w  w  .  j a va 2s.  co  m
    if (requestAttributes != null) {
        HttpServletRequest request = requestAttributes.getRequest();
        if (request != null && request.getRequestURL() != null
                && request.getRequestURL().toString().contains("https://")) {
            key += "https";
        } else {
            key += "http";
        }
    }
    return key;
}

From source file:org.ednovo.gooru.core.application.util.BaseUtil.java

public static String changeHttpsProtocolByHeader(String url) {
    HttpServletRequest request = null;/*from  w  ww  .  j a va 2  s .  com*/
    if (RequestContextHolder.getRequestAttributes() != null) {
        request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }
    if (url != null && isSecure(request)) {
        url = url.replaceFirst("http://", "https://");
    }
    return url;
}

From source file:org.geoserver.importer.Importer.java

public Long runAsync(final ImportContext context, final ImportFilter filter, final boolean init) {
    // we store the current request spring context
    final RequestAttributes parentRequestAttributes = RequestContextHolder.getRequestAttributes();
    final Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    Thread parentThread = Thread.currentThread();
    // creating an asynchronous importer job
    return jobs.submit(new Job<ImportContext>() {

        @Override//from  ww w . j  av a  2  s  .  co m
        protected ImportContext call(ProgressMonitor monitor) throws Exception {
            final Authentication oldAuth = SecurityContextHolder.getContext().getAuthentication();
            try {
                // set the parent request spring context, some interceptors like the security ones
                // for example may need to have access to the original request attributes
                RequestContextHolder.setRequestAttributes(parentRequestAttributes);
                SecurityContextHolder.getContext().setAuthentication(auth);
                if (init) {
                    init(context, true);
                }
                run(context, filter, monitor);
                return context;
            } finally {
                if (Thread.currentThread() != parentThread) {
                    // cleaning request spring context for the current thread
                    RequestContextHolder.resetRequestAttributes();
                    SecurityContextHolder.getContext().setAuthentication(oldAuth);
                }
            }
        }

        @Override
        public String toString() {
            return "Processing import " + context.getId();
        }
    });
}