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

The following examples show how to use org.springframework.http.HttpHeaders#getContentLength() . 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: SimpleStreamingAsyncClientHttpRequest.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
protected OutputStream getBodyInternal(HttpHeaders headers) throws IOException {
	if (this.body == null) {
		if (this.outputStreaming) {
			int contentLength = (int) headers.getContentLength();
			if (contentLength >= 0) {
				this.connection.setFixedLengthStreamingMode(contentLength);
			}
			else {
				this.connection.setChunkedStreamingMode(this.chunkSize);
			}
		}
		SimpleBufferingClientHttpRequest.addHeaders(this.connection, headers);
		this.connection.connect();
		this.body = this.connection.getOutputStream();
	}
	return StreamUtils.nonClosing(this.body);
}
 
Example 2
Source File: SimpleStreamingClientHttpRequest.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
protected OutputStream getBodyInternal(HttpHeaders headers) throws IOException {
	if (this.body == null) {
		if (this.outputStreaming) {
			int contentLength = (int) headers.getContentLength();
			if (contentLength >= 0) {
				this.connection.setFixedLengthStreamingMode(contentLength);
			}
			else {
				this.connection.setChunkedStreamingMode(this.chunkSize);
			}
		}
		SimpleBufferingClientHttpRequest.addHeaders(this.connection, headers);
		this.connection.connect();
		this.body = this.connection.getOutputStream();
	}
	return StreamUtils.nonClosing(this.body);
}
 
Example 3
Source File: GatewayContextFilter.java    From open-cloud with MIT License 6 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain){
    ServerHttpRequest request = exchange.getRequest();
    GatewayContext gatewayContext = new GatewayContext();
    HttpHeaders headers = request.getHeaders();
    gatewayContext.setRequestHeaders(headers);
    gatewayContext.getAllRequestData().addAll(request.getQueryParams());
    /*
     * save gateway context into exchange
     */
    exchange.getAttributes().put(GatewayContext.CACHE_GATEWAY_CONTEXT,gatewayContext);
    MediaType contentType = headers.getContentType();
    if(headers.getContentLength()>0){
        if(MediaType.APPLICATION_JSON.equals(contentType) || MediaType.APPLICATION_JSON_UTF8.equals(contentType)){
            return readBody(exchange, chain,gatewayContext);
        }
        if(MediaType.APPLICATION_FORM_URLENCODED.equals(contentType)){
            return readFormData(exchange, chain,gatewayContext);
        }
    }
    log.debug("[GatewayContext]ContentType:{},Gateway context is set with {}",contentType, gatewayContext);
    return chain.filter(exchange);

}
 
Example 4
Source File: ResourceHttpMessageWriter.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private Mono<Void> writeResource(Resource resource, ResolvableType type, @Nullable MediaType mediaType,
		ReactiveHttpOutputMessage message, Map<String, Object> hints) {

	HttpHeaders headers = message.getHeaders();
	MediaType resourceMediaType = getResourceMediaType(mediaType, resource, hints);
	headers.setContentType(resourceMediaType);

	if (headers.getContentLength() < 0) {
		long length = lengthOf(resource);
		if (length != -1) {
			headers.setContentLength(length);
		}
	}

	return zeroCopy(resource, null, message, hints)
			.orElseGet(() -> {
				Mono<Resource> input = Mono.just(resource);
				DataBufferFactory factory = message.bufferFactory();
				Flux<DataBuffer> body = this.encoder.encode(input, factory, type, resourceMediaType, hints);
				return message.writeWith(body);
			});
}
 
Example 5
Source File: SimpleStreamingClientHttpRequest.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
protected OutputStream getBodyInternal(HttpHeaders headers) throws IOException {
	if (this.body == null) {
		if (this.outputStreaming) {
			long contentLength = headers.getContentLength();
			if (contentLength >= 0) {
				this.connection.setFixedLengthStreamingMode(contentLength);
			}
			else {
				this.connection.setChunkedStreamingMode(this.chunkSize);
			}
		}
		SimpleBufferingClientHttpRequest.addHeaders(this.connection, headers);
		this.connection.connect();
		this.body = this.connection.getOutputStream();
	}
	return StreamUtils.nonClosing(this.body);
}
 
Example 6
Source File: AbstractBufferingAsyncClientHttpRequest.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
protected ListenableFuture<ClientHttpResponse> executeInternal(HttpHeaders headers) throws IOException {
	byte[] bytes = this.bufferedOutput.toByteArray();
	if (headers.getContentLength() < 0) {
		headers.setContentLength(bytes.length);
	}
	ListenableFuture<ClientHttpResponse> result = executeInternal(headers, bytes);
	this.bufferedOutput = new ByteArrayOutputStream(0);
	return result;
}
 
Example 7
Source File: ServletServerHttpRequest.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private static HttpHeaders initHeaders(HttpHeaders headers, HttpServletRequest request) {
	MediaType contentType = headers.getContentType();
	if (contentType == null) {
		String requestContentType = request.getContentType();
		if (StringUtils.hasLength(requestContentType)) {
			contentType = MediaType.parseMediaType(requestContentType);
			headers.setContentType(contentType);
		}
	}
	if (contentType != null && contentType.getCharset() == null) {
		String encoding = request.getCharacterEncoding();
		if (StringUtils.hasLength(encoding)) {
			Charset charset = Charset.forName(encoding);
			Map<String, String> params = new LinkedCaseInsensitiveMap<>();
			params.putAll(contentType.getParameters());
			params.put("charset", charset.toString());
			headers.setContentType(
					new MediaType(contentType.getType(), contentType.getSubtype(),
							params));
		}
	}
	if (headers.getContentLength() == -1) {
		int contentLength = request.getContentLength();
		if (contentLength != -1) {
			headers.setContentLength(contentLength);
		}
	}
	return headers;
}
 
Example 8
Source File: AbstractBufferingClientHttpRequest.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
protected ClientHttpResponse executeInternal(HttpHeaders headers) throws IOException {
	byte[] bytes = this.bufferedOutput.toByteArray();
	if (headers.getContentLength() < 0) {
		headers.setContentLength(bytes.length);
	}
	ClientHttpResponse result = executeInternal(headers, bytes);
	this.bufferedOutput = new ByteArrayOutputStream(0);
	return result;
}
 
Example 9
Source File: LargeFileDownloadIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenResumableUrl_whenDownloadCompletely_thenExpectCorrectFileSize() {
    HttpHeaders headers = restTemplate.headForHeaders(FILE_URL);
    long contentLength = headers.getContentLength();
    File file = restTemplate.execute(FILE_URL, HttpMethod.GET, null, clientHttpResponse -> {
        File ret = File.createTempFile("download", "tmp");
        StreamUtils.copy(clientHttpResponse.getBody(), new FileOutputStream(ret));
        return ret;
    });

    Assert.assertNotNull(file);
    Assertions
      .assertThat(file.length())
      .isEqualTo(contentLength);
}
 
Example 10
Source File: BackupStorageBase.java    From zstack with Apache License 2.0 5 votes vote down vote up
protected void exceptionIfImageSizeGreaterThanAvailableCapacity(String url) {
    if (CoreGlobalProperty.UNIT_TEST_ON) {
        return;
    }

    url = url.trim();
    if (!url.startsWith("http") && !url.startsWith("https")) {
        return;
    }

    HttpHeaders header;
    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
    factory.setReadTimeout(CoreGlobalProperty.REST_FACADE_READ_TIMEOUT);
    factory.setConnectTimeout(CoreGlobalProperty.REST_FACADE_CONNECT_TIMEOUT);
    factory.setHttpClient(HttpClients.createDefault());
    RestTemplate template = new RestTemplate(factory);
    try {
        header = template.headForHeaders(URI.create(url));
        logger.debug(String.format("get header from %s: %s", url, header));
    } catch (Exception e) {
        throw new OperationFailureException(operr("failed to get header of image url %s: %s", url, e.toString()));
    }

    if (header == null) {
        throw new OperationFailureException(operr("failed to get header of image url %s", url));
    }

    long size = header.getContentLength();
    if (size == -1) {
        logger.error(String.format("failed to get image size from url %s, but ignore this error and proceed", url));
    } else if (size < ImageConstant.MINI_IMAGE_SIZE_IN_BYTE) {
        throw new OperationFailureException(operr("the image size get from url %s is %d bytes, " +
                "it's too small for an image, please check the url again.", url, size));
    } else if (size > self.getAvailableCapacity()) {
        throw new OperationFailureException(operr("the backup storage[uuid:%s, name:%s] has not enough capacity to download the image[%s]." +
                        "Required size:%s, available size:%s", self.getUuid(), self.getName(), url, size, self.getAvailableCapacity()));
    }
}
 
Example 11
Source File: UploadResource.java    From tutorials with MIT License 5 votes vote down vote up
/**
 *  Standard file upload.
 */
@PostMapping
public Mono<ResponseEntity<UploadResult>> uploadHandler(@RequestHeader HttpHeaders headers, @RequestBody Flux<ByteBuffer> body) {

    long length = headers.getContentLength();
    if (length < 0) {
        throw new UploadFailedException(HttpStatus.BAD_REQUEST.value(), Optional.of("required header missing: Content-Length"));
    }

    String fileKey = UUID.randomUUID().toString();
    Map<String, String> metadata = new HashMap<String, String>();
    MediaType mediaType = headers.getContentType();

    if (mediaType == null) {
        mediaType = MediaType.APPLICATION_OCTET_STREAM;
    }

    log.info("[I95] uploadHandler: mediaType{}, length={}", mediaType, length);
    CompletableFuture<PutObjectResponse> future = s3client
      .putObject(PutObjectRequest.builder()
        .bucket(s3config.getBucket())
        .contentLength(length)
        .key(fileKey.toString())
        .contentType(mediaType.toString())
        .metadata(metadata)
        .build(), 
        AsyncRequestBody.fromPublisher(body));
    
    return Mono.fromFuture(future)
      .map((response) -> {
          checkResult(response);
          return ResponseEntity
            .status(HttpStatus.CREATED)
            .body(new UploadResult(HttpStatus.CREATED, new String[] {fileKey}));
      });
}
 
Example 12
Source File: AbstractBufferingAsyncClientHttpRequest.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected ListenableFuture<ClientHttpResponse> executeInternal(HttpHeaders headers) throws IOException {
	byte[] bytes = this.bufferedOutput.toByteArray();
	if (headers.getContentLength() < 0) {
		headers.setContentLength(bytes.length);
	}
	ListenableFuture<ClientHttpResponse> result = executeInternal(headers, bytes);
	this.bufferedOutput = new ByteArrayOutputStream(0);
	return result;
}
 
Example 13
Source File: ServletServerHttpRequest.java    From java-technology-stack with MIT License 5 votes vote down vote up
private static HttpHeaders initHeaders(HttpHeaders headers, HttpServletRequest request) {
	MediaType contentType = headers.getContentType();
	if (contentType == null) {
		String requestContentType = request.getContentType();
		if (StringUtils.hasLength(requestContentType)) {
			contentType = MediaType.parseMediaType(requestContentType);
			headers.setContentType(contentType);
		}
	}
	if (contentType != null && contentType.getCharset() == null) {
		String encoding = request.getCharacterEncoding();
		if (StringUtils.hasLength(encoding)) {
			Charset charset = Charset.forName(encoding);
			Map<String, String> params = new LinkedCaseInsensitiveMap<>();
			params.putAll(contentType.getParameters());
			params.put("charset", charset.toString());
			headers.setContentType(
					new MediaType(contentType.getType(), contentType.getSubtype(),
							params));
		}
	}
	if (headers.getContentLength() == -1) {
		int contentLength = request.getContentLength();
		if (contentLength != -1) {
			headers.setContentLength(contentLength);
		}
	}
	return headers;
}
 
Example 14
Source File: AbstractBufferingClientHttpRequest.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
protected ClientHttpResponse executeInternal(HttpHeaders headers) throws IOException {
	byte[] bytes = this.bufferedOutput.toByteArray();
	if (headers.getContentLength() == -1) {
		headers.setContentLength(bytes.length);
	}
	ClientHttpResponse result = executeInternal(headers, bytes);
	this.bufferedOutput = null;
	return result;
}
 
Example 15
Source File: LoggingClientHttpRequestInterceptor.java    From GreenSummer with GNU Lesser General Public License v2.1 5 votes vote down vote up
private boolean hasTextBody(HttpHeaders headers) {
    long contentLength = headers.getContentLength();
    if (contentLength != 0) {
        MediaType contentType = headers.getContentType();
        if (contentType != null) {
            String subtype = contentType.getSubtype();
            return "text".equals(contentType.getType()) || "xml".equals(subtype) || "json".equals(subtype);
        }
    }
    return false;
}
 
Example 16
Source File: AbstractBufferingAsyncClientHttpRequest.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
protected ListenableFuture<ClientHttpResponse> executeInternal(HttpHeaders headers) throws IOException {
	byte[] bytes = this.bufferedOutput.toByteArray();
	if (headers.getContentLength() == -1) {
		headers.setContentLength(bytes.length);
	}
	ListenableFuture<ClientHttpResponse> result = executeInternal(headers, bytes);
	this.bufferedOutput = null;
	return result;
}
 
Example 17
Source File: AbstractBufferingClientHttpRequest.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected ClientHttpResponse executeInternal(HttpHeaders headers) throws IOException {
	byte[] bytes = this.bufferedOutput.toByteArray();
	if (headers.getContentLength() < 0) {
		headers.setContentLength(bytes.length);
	}
	ClientHttpResponse result = executeInternal(headers, bytes);
	this.bufferedOutput = null;
	return result;
}
 
Example 18
Source File: AbstractBufferingAsyncClientHttpRequest.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected ListenableFuture<ClientHttpResponse> executeInternal(HttpHeaders headers) throws IOException {
	byte[] bytes = this.bufferedOutput.toByteArray();
	if (headers.getContentLength() < 0) {
		headers.setContentLength(bytes.length);
	}
	ListenableFuture<ClientHttpResponse> result = executeInternal(headers, bytes);
	this.bufferedOutput = null;
	return result;
}
 
Example 19
Source File: SynchronossPartHttpMessageReader.java    From spring-analysis-note with MIT License 4 votes vote down vote up
private int getContentLength(HttpHeaders headers) {
	// Until this is fixed https://github.com/synchronoss/nio-multipart/issues/10
	long length = headers.getContentLength();
	return (int) length == length ? (int) length : -1;
}
 
Example 20
Source File: SynchronossPartHttpMessageReader.java    From java-technology-stack with MIT License 4 votes vote down vote up
private int getContentLength(HttpHeaders headers) {
	// Until this is fixed https://github.com/synchronoss/nio-multipart/issues/10
	long length = headers.getContentLength();
	return (int) length == length ? (int) length : -1;
}