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

The following examples show how to use org.springframework.http.HttpHeaders#putAll() . 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: ModifyRequestBodyGatewayFilterFactory.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
ServerHttpRequestDecorator decorate(ServerWebExchange exchange, HttpHeaders headers,
		CachedBodyOutputMessage outputMessage) {
	return new ServerHttpRequestDecorator(exchange.getRequest()) {
		@Override
		public HttpHeaders getHeaders() {
			long contentLength = headers.getContentLength();
			HttpHeaders httpHeaders = new HttpHeaders();
			httpHeaders.putAll(headers);
			if (contentLength > 0) {
				httpHeaders.setContentLength(contentLength);
			}
			else {
				// TODO: this causes a 'HTTP/1.1 411 Length Required' // on
				// httpbin.org
				httpHeaders.set(HttpHeaders.TRANSFER_ENCODING, "chunked");
			}
			return httpHeaders;
		}

		@Override
		public Flux<DataBuffer> getBody() {
			return outputMessage.getBody();
		}
	};
}
 
Example 2
Source File: SurgicalRoutingRequestTransformer.java    From spring-cloud-services-starters with Apache License 2.0 6 votes vote down vote up
@Override
public HttpRequest transformRequest(HttpRequest request, ServiceInstance instance) {
	Map<String, String> metadata = instance.getMetadata();
	if (metadata.containsKey(CF_APP_GUID) && metadata.containsKey(CF_INSTANCE_INDEX)) {
		final String headerValue = String.format("%s:%s", metadata.get(CF_APP_GUID),
				metadata.get(CF_INSTANCE_INDEX));
		// request.getHeaders might be immutable, so return a wrapper
		return new HttpRequestWrapper(request) {
			@Override
			public HttpHeaders getHeaders() {
				HttpHeaders headers = new HttpHeaders();
				headers.putAll(super.getHeaders());
				headers.add(SURGICAL_ROUTING_HEADER, headerValue);
				return headers;
			}
		};
	}
	return request;
}
 
Example 3
Source File: AbstractXhrTransport.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public String executeInfoRequest(URI infoUrl, @Nullable HttpHeaders headers) {
	if (logger.isDebugEnabled()) {
		logger.debug("Executing SockJS Info request, url=" + infoUrl);
	}
	HttpHeaders infoRequestHeaders = new HttpHeaders();
	if (headers != null) {
		infoRequestHeaders.putAll(headers);
	}
	ResponseEntity<String> response = executeInfoRequestInternal(infoUrl, infoRequestHeaders);
	if (response.getStatusCode() != HttpStatus.OK) {
		if (logger.isErrorEnabled()) {
			logger.error("SockJS Info request (url=" + infoUrl + ") failed: " + response);
		}
		throw new HttpServerErrorException(response.getStatusCode());
	}
	if (logger.isTraceEnabled()) {
		logger.trace("SockJS Info request (url=" + infoUrl + ") response: " + response);
	}
	String result = response.getBody();
	return (result != null ? result : "");
}
 
Example 4
Source File: GetResponseExtractor.java    From haven-platform with Apache License 2.0 6 votes vote down vote up
@Override
public Object extractData(ClientHttpResponse response) throws IOException {
    HttpHeaders headers = new HttpHeaders();
    headers.putAll(response.getHeaders());
    for(Map.Entry<String, List<String>> e: headers.entrySet()) {
        List<String> values = e.getValue();
        for(int i = 0; i < values.size(); i++) {
            final String key = e.getKey();
            if(FORBIDDEN_HEADERS.contains(key)) {
                continue;
            }
            servletResponse.setHeader(key, values.get(i));
        }
    }
    try(InputStream is = response.getBody();
        ServletOutputStream os = servletResponse.getOutputStream()) {
        IOUtils.copy(is, os);
        servletResponse.flushBuffer();

    }
    return null;
}
 
Example 5
Source File: AbstractXhrTransport.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public String executeInfoRequest(URI infoUrl, @Nullable HttpHeaders headers) {
	if (logger.isDebugEnabled()) {
		logger.debug("Executing SockJS Info request, url=" + infoUrl);
	}
	HttpHeaders infoRequestHeaders = new HttpHeaders();
	if (headers != null) {
		infoRequestHeaders.putAll(headers);
	}
	ResponseEntity<String> response = executeInfoRequestInternal(infoUrl, infoRequestHeaders);
	if (response.getStatusCode() != HttpStatus.OK) {
		if (logger.isErrorEnabled()) {
			logger.error("SockJS Info request (url=" + infoUrl + ") failed: " + response);
		}
		throw new HttpServerErrorException(response.getStatusCode());
	}
	if (logger.isTraceEnabled()) {
		logger.trace("SockJS Info request (url=" + infoUrl + ") response: " + response);
	}
	String result = response.getBody();
	return (result != null ? result : "");
}
 
Example 6
Source File: AbstractXhrTransport.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public ListenableFuture<WebSocketSession> connect(TransportRequest request, WebSocketHandler handler) {
	SettableListenableFuture<WebSocketSession> connectFuture = new SettableListenableFuture<>();
	XhrClientSockJsSession session = new XhrClientSockJsSession(request, handler, this, connectFuture);
	request.addTimeoutTask(session.getTimeoutTask());

	URI receiveUrl = request.getTransportUrl();
	if (logger.isDebugEnabled()) {
		logger.debug("Starting XHR " +
				(isXhrStreamingDisabled() ? "Polling" : "Streaming") + "session url=" + receiveUrl);
	}

	HttpHeaders handshakeHeaders = new HttpHeaders();
	handshakeHeaders.putAll(request.getHandshakeHeaders());

	connectInternal(request, handler, receiveUrl, handshakeHeaders, session, connectFuture);
	return connectFuture;
}
 
Example 7
Source File: SurgicalRoutingRequestTransformer.java    From spring-cloud-services-connector with Apache License 2.0 6 votes vote down vote up
@Override
public HttpRequest transformRequest(HttpRequest request, ServiceInstance instance) {
	Map<String, String> metadata = instance.getMetadata();
	if (metadata.containsKey(CF_APP_GUID) && metadata.containsKey(CF_INSTANCE_INDEX)) {
		final String headerValue = String.format("%s:%s", metadata.get(CF_APP_GUID), metadata.get(CF_INSTANCE_INDEX));
		// request.getHeaders might be immutable, so return a wrapper
		return new HttpRequestWrapper(request) {
			@Override
			public HttpHeaders getHeaders() {
				HttpHeaders headers = new HttpHeaders();
				headers.putAll(super.getHeaders());
				headers.add(SURGICAL_ROUTING_HEADER, headerValue);
				return headers;
			}
		};
	}
	return request;
}
 
Example 8
Source File: TraceRequestHttpHeadersFilterTests.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
private HttpHeaders requestHeaders(HttpHeaders originalHeaders) {
	HttpHeaders headers = new HttpHeaders();
	headers.putAll(originalHeaders);
	headers.add("X-Hello-Request", "Request World");
	headers.add("X-Auth-User", "aaaa");
	return headers;
}
 
Example 9
Source File: SentinelClientHttpResponse.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
@Override
public HttpHeaders getHeaders() {
	Map<String, List<String>> headers = new HashMap<>();
	headers.put(HttpHeaders.CONTENT_TYPE,
			Arrays.asList(MediaType.APPLICATION_JSON_UTF8_VALUE));
	HttpHeaders httpHeaders = new HttpHeaders();
	httpHeaders.putAll(headers);
	return httpHeaders;
}
 
Example 10
Source File: DefaultWebClient.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private HttpHeaders initHeaders() {
	if (CollectionUtils.isEmpty(this.headers)) {
		return (defaultHeaders != null ? defaultHeaders : new HttpHeaders());
	}
	else if (CollectionUtils.isEmpty(defaultHeaders)) {
		return this.headers;
	}
	else {
		HttpHeaders result = new HttpHeaders();
		result.putAll(defaultHeaders);
		result.putAll(this.headers);
		return result;
	}
}
 
Example 11
Source File: AdminServerConfiguration.java    From mPaaS with Apache License 2.0 5 votes vote down vote up
@Override
public HttpHeaders getHeaders(Instance instance) {
    HttpHeaders headers = super.getHeaders(instance);
    Map<String, List<String>> headerMap = new HashMap<>(1);
    DiscoveryHeaderHelper.getInstance().getRequestHeaderInfo().forEach((key, value) -> {
        headerMap.put(key, Collections.singletonList(value));
    });
    headers.putAll(headerMap);
    return headers;
}
 
Example 12
Source File: JettyWebSocketSession.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public void initializeNativeSession(Session session) {
	super.initializeNativeSession(session);

	this.uri = session.getUpgradeRequest().getRequestURI();

	HttpHeaders headers = new HttpHeaders();
	headers.putAll(session.getUpgradeRequest().getHeaders());
	this.headers = HttpHeaders.readOnlyHttpHeaders(headers);

	this.acceptedProtocol = session.getUpgradeResponse().getAcceptedSubProtocol();

	List<ExtensionConfig> jettyExtensions = session.getUpgradeResponse().getExtensions();
	if (!CollectionUtils.isEmpty(jettyExtensions)) {
		List<WebSocketExtension> extensions = new ArrayList<>(jettyExtensions.size());
		for (ExtensionConfig jettyExtension : jettyExtensions) {
			extensions.add(new WebSocketExtension(jettyExtension.getName(), jettyExtension.getParameters()));
		}
		this.extensions = Collections.unmodifiableList(extensions);
	}
	else {
		this.extensions = Collections.emptyList();
	}

	if (this.user == null) {
		this.user = session.getUpgradeRequest().getUserPrincipal();
	}
}
 
Example 13
Source File: HttpHeaderFilter.java    From spring-boot-admin with Apache License 2.0 4 votes vote down vote up
public HttpHeaders filterHeaders(HttpHeaders headers) {
	HttpHeaders filtered = new HttpHeaders();
	filtered.putAll(headers.entrySet().stream().filter((e) -> this.includeHeader(e.getKey()))
			.collect(toMap(Map.Entry::getKey, Map.Entry::getValue)));
	return filtered;
}
 
Example 14
Source File: InterceptEverythingAndLogController.java    From pcf-crash-course-with-spring-boot with MIT License 4 votes vote down vote up
@RequestMapping()
public ResponseEntity<byte[]> logRequestAndExecute(RequestEntity<byte[]> incomingRequest) {

	LOGGER.info("Intercepted Request: {}", incomingRequest);
	
	HttpHeaders headers = new HttpHeaders();
	
	headers.putAll(incomingRequest.getHeaders());

	URI uri = headers.remove(X_CF_FORWARDED_URL_HEADER).stream().findFirst().map(URI::create)
			.orElseThrow(() -> new RuntimeException("Header is missing " + X_CF_FORWARDED_URL_HEADER));

	RequestEntity<byte[]> outgoingRequest = new RequestEntity<>(incomingRequest.getBody(), headers, incomingRequest.getMethod(), uri);

	// Execute the request specified in the given RequestEntity and 
	// return the response as ResponseEntity.
	ResponseEntity<byte[]> response = restOperations.exchange(outgoingRequest, byte[].class);
	
	LOGGER.info("Sent Response: {}", response);
	
	return response;
}
 
Example 15
Source File: MultipartHttpMessageWriter.java    From java-technology-stack with MIT License 4 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> Flux<DataBuffer> encodePart(byte[] boundary, String name, T value) {
	MultipartHttpOutputMessage outputMessage = new MultipartHttpOutputMessage(this.bufferFactory, getCharset());
	HttpHeaders outputHeaders = outputMessage.getHeaders();

	T body;
	ResolvableType resolvableType = null;
	if (value instanceof HttpEntity) {
		HttpEntity<T> httpEntity = (HttpEntity<T>) value;
		outputHeaders.putAll(httpEntity.getHeaders());
		body = httpEntity.getBody();
		Assert.state(body != null, "MultipartHttpMessageWriter only supports HttpEntity with body");

		if (httpEntity instanceof MultipartBodyBuilder.PublisherEntity<?, ?>) {
			MultipartBodyBuilder.PublisherEntity<?, ?> publisherEntity =
					(MultipartBodyBuilder.PublisherEntity<?, ?>) httpEntity;
			resolvableType = publisherEntity.getResolvableType();
		}
	}
	else {
		body = value;
	}
	if (resolvableType == null) {
		resolvableType = ResolvableType.forClass(body.getClass());
	}

	if (!outputHeaders.containsKey(HttpHeaders.CONTENT_DISPOSITION)) {
		if (body instanceof Resource) {
			outputHeaders.setContentDispositionFormData(name, ((Resource) body).getFilename());
		}
		else if (resolvableType.resolve() == Resource.class) {
			body = (T) Mono.from((Publisher<?>) body).doOnNext(o -> outputHeaders
					.setContentDispositionFormData(name, ((Resource) o).getFilename()));
		}
		else {
			outputHeaders.setContentDispositionFormData(name, null);
		}
	}

	MediaType contentType = outputHeaders.getContentType();

	final ResolvableType finalBodyType = resolvableType;
	Optional<HttpMessageWriter<?>> writer = this.partWriters.stream()
			.filter(partWriter -> partWriter.canWrite(finalBodyType, contentType))
			.findFirst();

	if (!writer.isPresent()) {
		return Flux.error(new CodecException("No suitable writer found for part: " + name));
	}

	Publisher<T> bodyPublisher =
			body instanceof Publisher ? (Publisher<T>) body : Mono.just(body);

	// The writer will call MultipartHttpOutputMessage#write which doesn't actually write
	// but only stores the body Flux and returns Mono.empty().

	Mono<Void> partContentReady = ((HttpMessageWriter<T>) writer.get())
			.write(bodyPublisher, resolvableType, contentType, outputMessage, DEFAULT_HINTS);

	// After partContentReady, we can access the part content from MultipartHttpOutputMessage
	// and use it for writing to the actual request body

	Flux<DataBuffer> partContent = partContentReady.thenMany(Flux.defer(outputMessage::getBody));

	return Flux.concat(Mono.just(generateBoundaryLine(boundary)), partContent, Mono.just(generateNewLine()));
}
 
Example 16
Source File: SynchronossPartHttpMessageReader.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
public void onPartFinished(StreamStorage storage, Map<String, List<String>> headers) {
	HttpHeaders httpHeaders = new HttpHeaders();
	httpHeaders.putAll(headers);
	this.sink.next(createPart(storage, httpHeaders));
}
 
Example 17
Source File: SynchronossPartHttpMessageReader.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
public void onPartFinished(StreamStorage storage, Map<String, List<String>> headers) {
	HttpHeaders httpHeaders = new HttpHeaders();
	httpHeaders.putAll(headers);
	this.sink.next(createPart(storage, httpHeaders));
}
 
Example 18
Source File: MultipartHttpMessageWriter.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> Flux<DataBuffer> encodePart(byte[] boundary, String name, T value, DataBufferFactory bufferFactory) {
	MultipartHttpOutputMessage outputMessage = new MultipartHttpOutputMessage(bufferFactory, getCharset());
	HttpHeaders outputHeaders = outputMessage.getHeaders();

	T body;
	ResolvableType resolvableType = null;
	if (value instanceof HttpEntity) {
		HttpEntity<T> httpEntity = (HttpEntity<T>) value;
		outputHeaders.putAll(httpEntity.getHeaders());
		body = httpEntity.getBody();
		Assert.state(body != null, "MultipartHttpMessageWriter only supports HttpEntity with body");
		if (httpEntity instanceof ResolvableTypeProvider) {
			resolvableType = ((ResolvableTypeProvider) httpEntity).getResolvableType();
		}
	}
	else {
		body = value;
	}
	if (resolvableType == null) {
		resolvableType = ResolvableType.forClass(body.getClass());
	}

	if (!outputHeaders.containsKey(HttpHeaders.CONTENT_DISPOSITION)) {
		if (body instanceof Resource) {
			outputHeaders.setContentDispositionFormData(name, ((Resource) body).getFilename());
		}
		else if (resolvableType.resolve() == Resource.class) {
			body = (T) Mono.from((Publisher<?>) body).doOnNext(o -> outputHeaders
					.setContentDispositionFormData(name, ((Resource) o).getFilename()));
		}
		else {
			outputHeaders.setContentDispositionFormData(name, null);
		}
	}

	MediaType contentType = outputHeaders.getContentType();

	final ResolvableType finalBodyType = resolvableType;
	Optional<HttpMessageWriter<?>> writer = this.partWriters.stream()
			.filter(partWriter -> partWriter.canWrite(finalBodyType, contentType))
			.findFirst();

	if (!writer.isPresent()) {
		return Flux.error(new CodecException("No suitable writer found for part: " + name));
	}

	Publisher<T> bodyPublisher =
			body instanceof Publisher ? (Publisher<T>) body : Mono.just(body);

	// The writer will call MultipartHttpOutputMessage#write which doesn't actually write
	// but only stores the body Flux and returns Mono.empty().

	Mono<Void> partContentReady = ((HttpMessageWriter<T>) writer.get())
			.write(bodyPublisher, resolvableType, contentType, outputMessage, DEFAULT_HINTS);

	// After partContentReady, we can access the part content from MultipartHttpOutputMessage
	// and use it for writing to the actual request body

	Flux<DataBuffer> partContent = partContentReady.thenMany(Flux.defer(outputMessage::getBody));

	return Flux.concat(
			generateBoundaryLine(boundary, bufferFactory),
			partContent,
			generateNewLine(bufferFactory));
}
 
Example 19
Source File: AbstractRestTemplateClient.java    From documentum-rest-client-java with Apache License 2.0 4 votes vote down vote up
private HttpHeaders clone(HttpHeaders headers) {
    HttpHeaders result = new HttpHeaders();
    result.putAll(headers);
    return result;
}
 
Example 20
Source File: HttpRequestWrapperWithModifiableHeadersTest.java    From wingtips with Apache License 2.0 4 votes vote down vote up
private HttpHeaders generateImmutableHeaders(Map<String, List<String>> headers) {
    HttpHeaders orig = new HttpHeaders();
    orig.putAll(headers);
    return HttpHeaders.readOnlyHttpHeaders(orig);
}