@Override public long contentLength() throws IOException { return this.delegate.contentLength(); }
@Override public long contentLength() throws IOException { return this.gzipped.contentLength(); }
@Override public long contentLength() throws IOException { return this.original.contentLength(); }
@Override public long contentLength() throws IOException { return this.gzipped.contentLength(); }
@Override public long contentLength() throws IOException { return this.encoded.contentLength(); }
@Override public long contentLength() throws IOException { return this.encoded.contentLength(); }
@Override public long contentLength() throws IOException { return this.original.contentLength(); }
private static long lengthOf(Resource resource) { // Don't consume InputStream... if (InputStreamResource.class != resource.getClass()) { try { return resource.contentLength(); } catch (IOException ignored) { } } return -1; }
private static long getLengthFor(Resource resource) { long contentLength; try { contentLength = resource.contentLength(); Assert.isTrue(contentLength > 0, "Resource content length should be > 0"); } catch (IOException ex) { throw new IllegalArgumentException("Failed to obtain Resource content length", ex); } return contentLength; }
@Override protected Long getContentLength(Resource resource, @Nullable MediaType contentType) throws IOException { // Don't try to determine contentLength on InputStreamResource - cannot be read afterwards... // Note: custom InputStreamResource subclasses could provide a pre-calculated content length! if (InputStreamResource.class == resource.getClass()) { return null; } long contentLength = resource.contentLength(); return (contentLength < 0 ? null : contentLength); }
private static long getLengthFor(Resource resource) { long contentLength; try { contentLength = resource.contentLength(); Assert.isTrue(contentLength > 0, "Resource content length should be > 0"); } catch (IOException ex) { throw new IllegalArgumentException("Failed to obtain Resource content length", ex); } return contentLength; }
/** * Determine, if possible, the contentLength of the given resource without reading it. * @param resource the resource instance * @return the contentLength of the resource */ private OptionalLong contentLength(Resource resource) { // Don't try to determine contentLength on InputStreamResource - cannot be read afterwards... // Note: custom InputStreamResource subclasses could provide a pre-calculated content length! if (InputStreamResource.class != resource.getClass()) { try { return OptionalLong.of(resource.contentLength()); } catch (IOException ignored) { } } return OptionalLong.empty(); }
@Bean public TestBean testBean() throws IOException { return new TestBean(hostname, (int) resource.contentLength()); } }
protected void writeResourceRegion(ResourceRegion region, HttpOutputMessage outputMessage) throws IOException { Assert.notNull(region, "ResourceRegion must not be null"); HttpHeaders responseHeaders = outputMessage.getHeaders(); long start = region.getPosition(); long end = start + region.getCount() - 1; Long resourceLength = region.getResource().contentLength(); end = Math.min(end, resourceLength - 1); long rangeLength = end - start + 1; responseHeaders.add("Content-Range", "bytes " + start + '-' + end + '/' + resourceLength); responseHeaders.setContentLength(rangeLength); InputStream in = region.getResource().getInputStream(); try { StreamUtils.copyRange(in, outputMessage.getBody(), start, end); } finally { try { in.close(); } catch (IOException ex) { // ignore } } }
@Test public void testReadableChannel() throws IOException { Resource resource = new FileSystemResource(getClass().getResource("Resource.class").getFile()); ReadableByteChannel channel = null; try { channel = resource.readableChannel(); ByteBuffer buffer = ByteBuffer.allocate((int) resource.contentLength()); channel.read(buffer); buffer.rewind(); assertTrue(buffer.limit() > 0); } finally { if (channel != null) { channel.close(); } } }
/** * Set headers on the response. Called for both GET and HEAD requests. * @param exchange current exchange * @param resource the identified resource (never {@code null}) * @param mediaType the resource's media type (never {@code null}) */ protected void setHeaders(ServerWebExchange exchange, Resource resource, @Nullable MediaType mediaType) throws IOException { HttpHeaders headers = exchange.getResponse().getHeaders(); long length = resource.contentLength(); headers.setContentLength(length); if (mediaType != null) { headers.setContentType(mediaType); } if (resource instanceof HttpResource) { HttpHeaders resourceHeaders = ((HttpResource) resource).getResponseHeaders(); exchange.getResponse().getHeaders().putAll(resourceHeaders); } }
@Test public void zeroCopy() throws Exception { // Zero-copy only does not support servlet assumeTrue(server instanceof ReactorHttpServer || server instanceof UndertowHttpServer); URI url = new URI("http://localhost:" + port); RequestEntity<?> request = RequestEntity.get(url).build(); ResponseEntity<byte[]> response = new RestTemplate().exchange(request, byte[].class); Resource logo = new ClassPathResource("spring.png", ZeroCopyIntegrationTests.class); assertTrue(response.hasBody()); assertEquals(logo.contentLength(), response.getHeaders().getContentLength()); assertEquals(logo.contentLength(), response.getBody().length); assertEquals(MediaType.IMAGE_PNG, response.getHeaders().getContentType()); }
@Test // SPR-16376 public void customContentDisposition() throws IOException { Resource logo = new ClassPathResource("/org/springframework/http/converter/logo.jpg"); Flux<DataBuffer> buffers = DataBufferUtils.read(logo, new DefaultDataBufferFactory(), 1024); long contentLength = logo.contentLength(); MultipartBodyBuilder bodyBuilder = new MultipartBodyBuilder(); bodyBuilder.part("resource", logo) .headers(h -> h.setContentDispositionFormData("resource", "spring.jpg")); bodyBuilder.asyncPart("buffers", buffers, DataBuffer.class) .headers(h -> { h.setContentDispositionFormData("buffers", "buffers.jpg"); h.setContentType(MediaType.IMAGE_JPEG); h.setContentLength(contentLength); }); MultiValueMap<String, HttpEntity<?>> multipartData = bodyBuilder.build(); Map<String, Object> hints = Collections.emptyMap(); this.writer.write(Mono.just(multipartData), null, MediaType.MULTIPART_FORM_DATA, this.response, hints).block(); MultiValueMap<String, Part> requestParts = parse(hints); assertEquals(2, requestParts.size()); Part part = requestParts.getFirst("resource"); assertTrue(part instanceof FilePart); assertEquals("spring.jpg", ((FilePart) part).filename()); assertEquals(logo.getFile().length(), part.headers().getContentLength()); part = requestParts.getFirst("buffers"); assertTrue(part instanceof FilePart); assertEquals("buffers.jpg", ((FilePart) part).filename()); assertEquals(logo.getFile().length(), part.headers().getContentLength()); }
@Test public void head() throws IOException { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.head("http://localhost")); MockServerHttpResponse mockResponse = exchange.getResponse(); ServerRequest request = new DefaultServerRequest(exchange, HandlerStrategies.withDefaults().messageReaders()); Mono<ServerResponse> responseMono = this.handlerFunction.handle(request); Mono<Void> result = responseMono.flatMap(response -> { assertEquals(HttpStatus.OK, response.statusCode()); assertTrue(response instanceof EntityResponse); @SuppressWarnings("unchecked") EntityResponse<Resource> entityResponse = (EntityResponse<Resource>) response; assertEquals(this.resource.getFilename(), entityResponse.entity().getFilename()); return response.writeTo(exchange, context); }); StepVerifier.create(result).expectComplete().verify(); StepVerifier.create(mockResponse.getBody()).expectComplete().verify(); assertEquals(MediaType.TEXT_PLAIN, mockResponse.getHeaders().getContentType()); assertEquals(this.resource.contentLength(), mockResponse.getHeaders().getContentLength()); }
@Test public void get() throws IOException { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("http://localhost")); MockServerHttpResponse mockResponse = exchange.getResponse(); ServerRequest request = new DefaultServerRequest(exchange, HandlerStrategies.withDefaults().messageReaders()); Mono<ServerResponse> responseMono = this.handlerFunction.handle(request); Mono<Void> result = responseMono.flatMap(response -> { assertEquals(HttpStatus.OK, response.statusCode()); assertTrue(response instanceof EntityResponse); @SuppressWarnings("unchecked") EntityResponse<Resource> entityResponse = (EntityResponse<Resource>) response; assertEquals(this.resource, entityResponse.entity()); return response.writeTo(exchange, context); }); StepVerifier.create(result) .expectComplete() .verify(); byte[] expectedBytes = Files.readAllBytes(this.resource.getFile().toPath()); StepVerifier.create(mockResponse.getBody()) .consumeNextWith(dataBuffer -> { byte[] resultBytes = new byte[dataBuffer.readableByteCount()]; dataBuffer.read(resultBytes); assertArrayEquals(expectedBytes, resultBytes); }) .expectComplete() .verify(); assertEquals(MediaType.TEXT_PLAIN, mockResponse.getHeaders().getContentType()); assertEquals(this.resource.contentLength(), mockResponse.getHeaders().getContentLength()); }