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.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  w w  w .  j ava2s.c  om
    }
    if (paramValues == null)
        paramValues = Collections.emptyMap();
    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 += OPTIONAL_EXTENSION_WILDCARD;
        }
        Matcher m = OPTIONAL_EXTENSION_WILDCARD_PATTERN.matcher(token);
        if (m.find()) {

            boolean tokenSet = false;
            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());
                    tokenSet = true;
                } else {
                    token = token.replaceFirst(DOUBLE_WILDCARD_PATTERN.pattern(), "");
                }
            } else {
                tokenSet = true;
            }
            if (tokenSet) {

                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.jasig.portlet.calendar.adapter.exchange.ExchangeCredentialsInitializationServiceTest.java

@Test
public void testInitialize() {
    service.initialize(request);// w  w w .j ava  2  s  .  c o  m

    final RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    final NTCredentials credentials = (NTCredentials) requestAttributes.getAttribute(
            ExchangeWsCredentialsProvider.EXCHANGE_CREDENTIALS_ATTRIBUTE, RequestAttributes.SCOPE_SESSION);
    assertEquals("user", credentials.getUserName());
    assertEquals("pass", credentials.getPassword());
}

From source file:org.jasig.portlet.calendar.adapter.exchange.ExchangeCredentialsInitializationServiceTest.java

@Test
public void testWithExistingRequestInitialize() {
    final RequestAttributes requestAttributes = new PortletRequestAttributes(request);
    requestAttributes.setAttribute("testAttr", "testVal", RequestAttributes.SCOPE_SESSION);
    RequestContextHolder.setRequestAttributes(requestAttributes);

    service.initialize(request);/*  w  w  w  . ja  v a2s .  com*/

    final RequestAttributes newRequestAttributes = RequestContextHolder.getRequestAttributes();
    final NTCredentials credentials = (NTCredentials) newRequestAttributes.getAttribute(
            ExchangeWsCredentialsProvider.EXCHANGE_CREDENTIALS_ATTRIBUTE, RequestAttributes.SCOPE_SESSION);
    assertEquals("user", credentials.getUserName());
    assertEquals("pass", credentials.getPassword());
    assertEquals("testVal", newRequestAttributes.getAttribute("testAttr", RequestAttributes.SCOPE_SESSION));
}

From source file:org.kuali.rice.krad.uif.util.ObjectPropertyUtils.java

/**
 * Gets the property editor registry configured for the active request.
 *///  w ww.  j  a  va 2s. c om
public static PropertyEditorRegistry getPropertyEditorRegistry() {
    RequestAttributes attributes = RequestContextHolder.getRequestAttributes();

    PropertyEditorRegistry registry = null;
    if (attributes != null) {
        registry = (PropertyEditorRegistry) attributes.getAttribute(UifConstants.PROPERTY_EDITOR_REGISTRY,
                RequestAttributes.SCOPE_REQUEST);
    }

    return registry;
}

From source file:org.onebusaway.sms.impl.TextmarksSessionInterceptor.java

@Override
public String intercept(ActionInvocation invocation) throws Exception {

    processGoogleAnalytics();/*  ww w.  j a  v  a 2 s . co m*/

    ActionContext context = invocation.getInvocationContext();
    Map<String, Object> parameters = context.getParameters();

    Object phoneNumber = parameters.get(_phoneNumberParameterName);

    if (phoneNumber == null)
        return invocation.invoke();

    if (phoneNumber instanceof String[]) {
        String[] values = (String[]) phoneNumber;
        if (values.length == 0)
            return invocation.invoke();
        phoneNumber = values[0];
    }

    String sessionId = phoneNumber.toString();
    Map<String, Object> persistentSession = _sessionManager.getContext(sessionId);

    Map<String, Object> originalSession = context.getSession();
    context.setSession(persistentSession);

    XWorkRequestAttributes attributes = new XWorkRequestAttributes(context, sessionId);
    RequestAttributes originalAttributes = RequestContextHolder.getRequestAttributes();
    RequestContextHolder.setRequestAttributes(attributes);

    Object action = invocation.getAction();
    if (action instanceof SessionAware)
        ((SessionAware) action).setSession(persistentSession);

    try {
        return invocation.invoke();
    } finally {
        RequestContextHolder.setRequestAttributes(originalAttributes);
        context.setSession(originalSession);
    }
}

From source file:org.orcid.api.common.jaxb.OrcidExceptionMapper.java

private ApiSection getApiSection() {
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    ApiSection apiSection = (ApiSection) requestAttributes
            .getAttribute(ApiVersionFilter.API_SECTION_REQUEST_ATTRIBUTE_NAME, RequestAttributes.SCOPE_REQUEST);
    return apiSection != null ? apiSection : ApiSection.V1;
}

From source file:org.orcid.core.manager.impl.ValidationManagerForLegacyApiVersionsImpl.java

@Override
protected void doSchemaValidation(OrcidMessage orcidMessage) {
    // Hack to support legacy API versions
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    if (requestAttributes instanceof ServletRequestAttributes) {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        String contentType = servletRequestAttributes.getRequest().getContentType();
        if (!StringUtils.containsIgnoreCase(contentType, "json")) {
            super.doSchemaValidation(orcidMessage);
        }//from  w  ww .jav a 2 s . c om
    } else {
        super.doSchemaValidation(orcidMessage);
    }
}

From source file:org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetrics.java

public void tagWithException(Throwable exception) {
    RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
    attributes.setAttribute(EXCEPTION_ATTRIBUTE, exception, RequestAttributes.SCOPE_REQUEST);
}

From source file:org.springframework.metrics.instrument.web.MetricsHandlerInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    longTaskTimed(handler).forEach(t -> {
        if (t.value().isEmpty()) {
            logger.warn("Unable to perform metrics timing on " + ((HandlerMethod) handler).getShortLogMessage()
                    + ": @Timed annotation must have a value used to name the metric");
            return;
        }/*from  w  ww. j  a  va 2 s  .  c  o m*/
        longTaskTimerIds.put(t,
                registry.longTaskTimer(t.value(), tagConfigurer.httpLongRequestTags(request, handler)).start());
    });

    RequestContextHolder.getRequestAttributes().setAttribute(TIMING_REQUEST_ATTRIBUTE, System.nanoTime(),
            SCOPE_REQUEST);
    return super.preHandle(request, response, handler);
}

From source file:org.springframework.metrics.instrument.web.MetricsHandlerInterceptor.java

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
        Exception ex) throws Exception {
    RequestContextHolder.getRequestAttributes().setAttribute("exception", ex, SCOPE_REQUEST);

    Long startTime = (Long) RequestContextHolder.getRequestAttributes().getAttribute(TIMING_REQUEST_ATTRIBUTE,
            SCOPE_REQUEST);/*ww w  .  j av a2 s  .co m*/
    if (startTime != null)
        recordMetric(request, response, handler, startTime);

    super.afterCompletion(request, response, handler, ex);
}