Java Code Examples for org.springframework.http.HttpHeaders#getFirst()

The following examples show how to use org.springframework.http.HttpHeaders#getFirst() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WebSocketConfig.java    From bearchoke with Apache License 2.0 6 votes vote down vote up
@Override
protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, Map<String, Object> attributes) {
    Principal result = null;
    String authToken = null;
    HttpHeaders headers = request.getHeaders();

    if (log.isDebugEnabled()) {
        log.debug("Determining user...");
    }

    if (headers.containsKey(ServerConstants.X_AUTH_TOKEN)) {
        authToken = headers.getFirst(ServerConstants.X_AUTH_TOKEN);
        authenticate(authToken);
    } else if (attributes.containsKey(ServerConstants.X_AUTH_TOKEN)) {
        authToken = (String) attributes.get(ServerConstants.X_AUTH_TOKEN);

        authenticate(authToken);
    } else {
        result = super.determineUser(request, wsHandler, attributes);
    }

    return result;
}
 
Example 2
Source File: ForwardedHeaderTransformer.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Nullable
private static String getForwardedPrefix(ServerHttpRequest request) {
	HttpHeaders headers = request.getHeaders();
	String prefix = headers.getFirst("X-Forwarded-Prefix");
	if (prefix != null) {
		int endIndex = prefix.length();
		while (endIndex > 1 && prefix.charAt(endIndex - 1) == '/') {
			endIndex--;
		}
		prefix = (endIndex != prefix.length() ? prefix.substring(0, endIndex) : prefix);
	}
	return prefix;
}
 
Example 3
Source File: GithubService.java    From github-release-notes-generator with Apache License 2.0 5 votes vote down vote up
private String getNextUrl(HttpHeaders headers) {
	String links = headers.getFirst("Link");
	for (String link : StringUtils.commaDelimitedListToStringArray(links)) {
		Matcher matcher = LINK_PATTERN.matcher(link.trim());
		if (matcher.matches() && "next".equals(matcher.group(2))) {
			return matcher.group(1);
		}
	}
	return null;
}
 
Example 4
Source File: TraceRestTemplateInterceptorTests.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
private void addHeaders(Map<String, String> map, HttpHeaders headers,
		String... names) {
	if (headers != null) {
		for (String name : names) {
			String value = headers.getFirst(name);
			if (value != null) {
				map.put(name, value);
			}
		}
	}
}
 
Example 5
Source File: HelloController2.java    From Mastering-Distributed-Tracing with MIT License 5 votes vote down vote up
private HttpHeaders copyHeaders(HttpHeaders headers) {
    HttpHeaders tracingHeaders = new HttpHeaders();
    for (String key : tracingHeaderKeys) {
        String value = headers.getFirst(key);
        if (value != null) {
            tracingHeaders.add(key, value);
        }
    }
    return tracingHeaders;
}
 
Example 6
Source File: WebSocketIntegrationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Mono<Void> handle(WebSocketSession session) {
	HttpHeaders headers = session.getHandshakeInfo().getHeaders();
	String payload = "my-header:" + headers.getFirst("my-header");
	WebSocketMessage message = session.textMessage(payload);
	return session.send(Mono.just(message));
}
 
Example 7
Source File: UriComponentsBuilder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Adapt this builder's scheme+host+port from the given headers, specifically
 * "Forwarded" (<a href="http://tools.ietf.org/html/rfc7239">RFC 7239</a>,
 * or "X-Forwarded-Host", "X-Forwarded-Port", and "X-Forwarded-Proto" if
 * "Forwarded" is not found.
 * @param headers the HTTP headers to consider
 * @return this UriComponentsBuilder
 * @since 4.2.7
 */
UriComponentsBuilder adaptFromForwardedHeaders(HttpHeaders headers) {
	String forwardedHeader = headers.getFirst("Forwarded");
	if (StringUtils.hasText(forwardedHeader)) {
		String forwardedToUse = StringUtils.tokenizeToStringArray(forwardedHeader, ",")[0];
		Matcher matcher = FORWARDED_HOST_PATTERN.matcher(forwardedToUse);
		if (matcher.find()) {
			adaptForwardedHost(matcher.group(1).trim());
		}
		matcher = FORWARDED_PROTO_PATTERN.matcher(forwardedToUse);
		if (matcher.find()) {
			scheme(matcher.group(1).trim());
		}
	}
	else {
		String hostHeader = headers.getFirst("X-Forwarded-Host");
		if (StringUtils.hasText(hostHeader)) {
			adaptForwardedHost(StringUtils.tokenizeToStringArray(hostHeader, ",")[0]);
		}

		String portHeader = headers.getFirst("X-Forwarded-Port");
		if (StringUtils.hasText(portHeader)) {
			port(Integer.parseInt(StringUtils.tokenizeToStringArray(portHeader, ",")[0]));
		}

		String protocolHeader = headers.getFirst("X-Forwarded-Proto");
		if (StringUtils.hasText(protocolHeader)) {
			scheme(StringUtils.tokenizeToStringArray(protocolHeader, ",")[0]);
		}
	}

	if ((this.scheme.equals("http") && "80".equals(this.port)) ||
			(this.scheme.equals("https") && "443".equals(this.port))) {
		this.port = null;
	}

	return this;
}
 
Example 8
Source File: WebSocketParamFilter.java    From soul with Apache License 2.0 5 votes vote down vote up
@Override
protected Mono<Boolean> doFilter(final ServerWebExchange exchange, final WebFilterChain chain) {
    final ServerHttpRequest request = exchange.getRequest();
    final HttpHeaders headers = request.getHeaders();
    final String upgrade = headers.getFirst("Upgrade");
    if (StringUtils.isNoneBlank(upgrade) && RpcTypeEnum.WEB_SOCKET.getName().equals(upgrade)) {
        return Mono.just(verify(request.getQueryParams()));
    }
    return Mono.just(true);
}
 
Example 9
Source File: ForwardedHeaderTransformer.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Nullable
private static String getForwardedPrefix(ServerHttpRequest request) {
	HttpHeaders headers = request.getHeaders();
	String prefix = headers.getFirst("X-Forwarded-Prefix");
	if (prefix != null) {
		int endIndex = prefix.length();
		while (endIndex > 1 && prefix.charAt(endIndex - 1) == '/') {
			endIndex--;
		}
		prefix = (endIndex != prefix.length() ? prefix.substring(0, endIndex) : prefix);
	}
	return prefix;
}
 
Example 10
Source File: RedisApplicationTestIT.java    From spring-cloud-zuul-ratelimit with Apache License 2.0 5 votes vote down vote up
private void assertHeaders(HttpHeaders headers, String key, boolean nullable, boolean quotaHeaders) {
    if (key != null && !key.startsWith("-")) {
      key = "-" + key;
    } else if (key == null) {
      key = "";
    }

    String quota = headers.getFirst(HEADER_QUOTA + key);
    String remainingQuota = headers.getFirst(HEADER_REMAINING_QUOTA + key);
    String limit = headers.getFirst(HEADER_LIMIT + key);
    String remaining = headers.getFirst(HEADER_REMAINING + key);
    String reset = headers.getFirst(HEADER_RESET + key);

    if (nullable) {
        if (quotaHeaders) {
            assertNull(quota);
            assertNull(remainingQuota);
        } else {
            assertNull(limit);
            assertNull(remaining);
        }
        assertNull(reset);
    } else {
        if (quotaHeaders) {
            assertNotNull(quota);
            assertNotNull(remainingQuota);
        } else {
            assertNotNull(limit);
            assertNotNull(remaining);
        }
        assertNotNull(reset);
    }
}
 
Example 11
Source File: RequestMappingIntegrationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void httpHead() {
	String url = "http://localhost:" + this.port + "/text";
	HttpHeaders headers = getRestTemplate().headForHeaders(url);
	String contentType = headers.getFirst("Content-Type");
	assertNotNull(contentType);
	assertEquals("text/html;charset=utf-8", contentType.toLowerCase());
	assertEquals(3, headers.getContentLength());
}
 
Example 12
Source File: HttpEntityMethodProcessor.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

	mavContainer.setRequestHandled(true);
	if (returnValue == null) {
		return;
	}

	ServletServerHttpRequest inputMessage = createInputMessage(webRequest);
	ServletServerHttpResponse outputMessage = createOutputMessage(webRequest);

	Assert.isInstanceOf(HttpEntity.class, returnValue);
	HttpEntity<?> responseEntity = (HttpEntity<?>) returnValue;

	HttpHeaders outputHeaders = outputMessage.getHeaders();
	HttpHeaders entityHeaders = responseEntity.getHeaders();
	if (!entityHeaders.isEmpty()) {
		entityHeaders.forEach((key, value) -> {
			if (HttpHeaders.VARY.equals(key) && outputHeaders.containsKey(HttpHeaders.VARY)) {
				List<String> values = getVaryRequestHeadersToAdd(outputHeaders, entityHeaders);
				if (!values.isEmpty()) {
					outputHeaders.setVary(values);
				}
			}
			else {
				outputHeaders.put(key, value);
			}
		});
	}

	if (responseEntity instanceof ResponseEntity) {
		int returnStatus = ((ResponseEntity<?>) responseEntity).getStatusCodeValue();
		outputMessage.getServletResponse().setStatus(returnStatus);
		if (returnStatus == 200) {
			if (SAFE_METHODS.contains(inputMessage.getMethod())
					&& isResourceNotModified(inputMessage, outputMessage)) {
				// Ensure headers are flushed, no body should be written.
				outputMessage.flush();
				ShallowEtagHeaderFilter.disableContentCaching(inputMessage.getServletRequest());
				// Skip call to converters, as they may update the body.
				return;
			}
		}
		else if (returnStatus / 100 == 3) {
			String location = outputHeaders.getFirst("location");
			if (location != null) {
				saveFlashAttributes(mavContainer, webRequest, location);
			}
		}
	}

	// Try even with null body. ResponseBodyAdvice could get involved.
	writeWithMessageConverters(responseEntity.getBody(), returnType, inputMessage, outputMessage);

	// Ensure headers are flushed even if no body was written.
	outputMessage.flush();
}
 
Example 13
Source File: OkHttpClientHttpRequest.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
private MediaType getContentType(HttpHeaders headers) {
	String rawContentType = headers.getFirst("Content-Type");
	return (StringUtils.hasText(rawContentType) ? MediaType.parse(rawContentType) : null);
}
 
Example 14
Source File: OkHttpClientHttpRequestFactory.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private static com.squareup.okhttp.MediaType getContentType(HttpHeaders headers) {
	String rawContentType = headers.getFirst(HttpHeaders.CONTENT_TYPE);
	return (StringUtils.hasText(rawContentType) ?
			com.squareup.okhttp.MediaType.parse(rawContentType) : null);
}
 
Example 15
Source File: OkHttp3ClientHttpRequestFactory.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private static okhttp3.MediaType getContentType(HttpHeaders headers) {
	String rawContentType = headers.getFirst(HttpHeaders.CONTENT_TYPE);
	return (StringUtils.hasText(rawContentType) ? okhttp3.MediaType.parse(rawContentType) : null);
}
 
Example 16
Source File: HeaderExpression.java    From spring-cloud-alibaba with Apache License 2.0 4 votes vote down vote up
@Override
protected boolean matchValue(HttpRequest request) {
	HttpHeaders httpHeaders = request.getHeaders();
	String headerValue = httpHeaders.getFirst(this.name);
	return ObjectUtils.nullSafeEquals(this.value, headerValue);
}
 
Example 17
Source File: JettyWebSocketClient.java    From spring-analysis-note with MIT License 4 votes vote down vote up
private HandshakeInfo createHandshakeInfo(URI url, Session jettySession) {
	HttpHeaders headers = new HttpHeaders();
	jettySession.getUpgradeResponse().getHeaders().forEach(headers::put);
	String protocol = headers.getFirst("Sec-WebSocket-Protocol");
	return new HandshakeInfo(url, headers, Mono.empty(), protocol);
}
 
Example 18
Source File: StandardWebSocketClient.java    From spring-analysis-note with MIT License 4 votes vote down vote up
private HandshakeInfo createHandshakeInfo(URI url, DefaultConfigurator configurator) {
	HttpHeaders responseHeaders = configurator.getResponseHeaders();
	String protocol = responseHeaders.getFirst("Sec-WebSocket-Protocol");
	return new HandshakeInfo(url, responseHeaders, Mono.empty(), protocol);
}
 
Example 19
Source File: ContractExchangeHandler.java    From spring-cloud-contract with Apache License 2.0 4 votes vote down vote up
@Override
public String getHeader(String key) {
	HttpHeaders headers = this.result.getRequestHeaders();
	return headers.containsKey(key) ? headers.getFirst(key) : null;
}
 
Example 20
Source File: UndertowWebSocketClient.java    From spring-analysis-note with MIT License 4 votes vote down vote up
private HandshakeInfo createHandshakeInfo(URI url, DefaultNegotiation negotiation) {
	HttpHeaders responseHeaders = negotiation.getResponseHeaders();
	String protocol = responseHeaders.getFirst("Sec-WebSocket-Protocol");
	return new HandshakeInfo(url, responseHeaders, Mono.empty(), protocol);
}