Java Code Examples for org.springframework.core.io.Resource#contentLength()

The following examples show how to use org.springframework.core.io.Resource#contentLength() . 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: ResourceHttpRequestHandler.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Set headers on the given servlet response.
 * Called for GET requests as well as HEAD requests.
 * @param response current servlet response
 * @param resource the identified resource (never {@code null})
 * @param mediaType the resource's media type (never {@code null})
 * @throws IOException in case of errors while setting the headers
 */
protected void setHeaders(HttpServletResponse response, Resource resource, MediaType mediaType) throws IOException {
	long length = resource.contentLength();
	if (length > Integer.MAX_VALUE) {
		throw new IOException("Resource content too long (beyond Integer.MAX_VALUE): " + resource);
	}
	response.setContentLength((int) length);

	if (mediaType != null) {
		response.setContentType(mediaType.toString());
	}

	if (resource instanceof EncodedResource) {
		response.setHeader(HttpHeaders.CONTENT_ENCODING, ((EncodedResource) resource).getContentEncoding());
	}

	response.setHeader(HttpHeaders.ACCEPT_RANGES, "bytes");
}
 
Example 2
Source File: HttpRange.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Turn a {@code Resource} into a {@link ResourceRegion} using the range
 * information contained in the current {@code HttpRange}.
 * @param resource the {@code Resource} to select the region from
 * @return the selected region of the given {@code Resource}
 * @since 4.3
 */
public ResourceRegion toResourceRegion(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!
	Assert.isTrue(resource.getClass() != InputStreamResource.class,
			"Cannot convert an InputStreamResource to a ResourceRegion");
	try {
		long contentLength = resource.contentLength();
		Assert.isTrue(contentLength > 0, "Resource content length should be > 0");
		long start = getRangeStart(contentLength);
		long end = getRangeEnd(contentLength);
		return new ResourceRegion(resource, start, end - start + 1);
	}
	catch (IOException ex) {
		throw new IllegalArgumentException("Failed to convert Resource to ResourceRegion", ex);
	}
}
 
Example 3
Source File: ResourceWebHandler.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * 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);
	}
}
 
Example 4
Source File: ResourceHttpRequestHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Set headers on the given servlet response.
 * Called for GET requests as well as HEAD requests.
 * @param response current servlet response
 * @param resource the identified resource (never {@code null})
 * @param mediaType the resource's media type (never {@code null})
 * @throws IOException in case of errors while setting the headers
 */
protected void setHeaders(HttpServletResponse response, Resource resource, MediaType mediaType) throws IOException {
	long length = resource.contentLength();
	if (length > Integer.MAX_VALUE) {
		if (contentLengthLongAvailable) {
			response.setContentLengthLong(length);
		}
		else {
			response.setHeader(HttpHeaders.CONTENT_LENGTH, Long.toString(length));
		}
	}
	else {
		response.setContentLength((int) length);
	}

	if (mediaType != null) {
		response.setContentType(mediaType.toString());
	}
	if (resource instanceof EncodedResource) {
		response.setHeader(HttpHeaders.CONTENT_ENCODING, ((EncodedResource) resource).getContentEncoding());
	}
	if (resource instanceof VersionedResource) {
		response.setHeader(HttpHeaders.ETAG, "\"" + ((VersionedResource) resource).getVersion() + "\"");
	}
	response.setHeader(HttpHeaders.ACCEPT_RANGES, "bytes");
}
 
Example 5
Source File: FileSystemUtil.java    From n2o-framework with Apache License 2.0 6 votes vote down vote up
public static long getFileSizeByUri(String uri) throws IOException {
    if (uri == null)
        return 0;
    if (uri.startsWith("jar:") || uri.startsWith("classpath:")) {
        Resource resource = DEFAULT_RESOURCE_LOADER.getResource(uri);
        if (!resource.exists()) {
            throw new IllegalStateException("File Not Found:" + uri);
        }
        return resource.contentLength();
    } else if (uri.startsWith("file:")) {
        File file = new File(PathUtil.convertUrlToAbsolutePath(uri));
        if (!file.exists()) {
            throw new IllegalStateException("File Not Found:" + uri);
        }
        return file.length();
    }
    return 0;
}
 
Example 6
Source File: ResourceWebHandler.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * 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);
	}
}
 
Example 7
Source File: HttpRange.java    From java-technology-stack with MIT License 5 votes vote down vote up
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;
}
 
Example 8
Source File: TemplatedProjectInitializer.java    From ogham with Apache License 2.0 5 votes vote down vote up
private void copy(String resourceFolder, Path generatedProjectPath) throws IOException {
	ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
	Resource[] resources = resolver.getResources(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + resourceFolder + "/**");
	for (Resource resource : resources) {
		if (resource.exists() && resource.isReadable() && resource.contentLength() > 0) {
			URL url = resource.getURL();
			String urlString = url.toExternalForm();
			String targetName = urlString.substring(urlString.indexOf(resourceFolder) + resourceFolder.length() + 1);
			Path destination = generatedProjectPath.resolve(targetName);
			Files.createDirectories(destination.getParent());
			Files.copy(resource.getInputStream(), destination);
		}
	}
}
 
Example 9
Source File: DefaultMongoStoreImpl.java    From spring-content with Apache License 2.0 5 votes vote down vote up
@Override
public S setContent(S property, InputStream content) {
	Object contentId = BeanUtils.getFieldWithAnnotation(property, ContentId.class);
	if (contentId == null) {
		contentId = UUID.randomUUID();
		BeanUtils.setFieldWithAnnotation(property, ContentId.class,
				contentId.toString());
	}

	String location = placer.convert(contentId, String.class);
	Resource resource = gridFs.getResource(location);
	if (resource != null && resource.exists()) {
		gridFs.delete(query(whereFilename().is(resource.getFilename())));
	}

	try {
		gridFs.store(content, location);
		resource = gridFs.getResource(location);
	} catch (Exception e) {
		logger.error(format("Unexpected error setting content for entity  %s", property), e);
		throw new StoreAccessException(format("Setting content for entity %s", property), e);
	}

	long contentLen = 0L;
	try {
		contentLen = resource.contentLength();
	}
	catch (IOException ioe) {
		logger.debug(format("Unable to retrieve content length for %s", contentId));
	}
	BeanUtils.setFieldWithAnnotation(property, ContentLength.class, contentLen);

	return property;
}
 
Example 10
Source File: ResourceHttpMessageConverter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected Long getContentLength(Resource resource, 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);
}
 
Example 11
Source File: ResourceHttpMessageWriter.java    From java-technology-stack with MIT License 5 votes vote down vote up
private static long lengthOf(Resource resource) {
	// Don't consume InputStream...
	if (InputStreamResource.class != resource.getClass()) {
		try {
			return resource.contentLength();
		}
		catch (IOException ignored) {
		}
	}
	return -1;
}
 
Example 12
Source File: ResourceHttpMessageConverter.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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);
}
 
Example 13
Source File: ResourceHttpRequestHandler.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Set headers on the given servlet response.
 * Called for GET requests as well as HEAD requests.
 * @param response current servlet response
 * @param resource the identified resource (never {@code null})
 * @param mediaType the resource's media type (never {@code null})
 * @throws IOException in case of errors while setting the headers
 */
protected void setHeaders(HttpServletResponse response, Resource resource, @Nullable MediaType mediaType)
		throws IOException {

	long length = resource.contentLength();
	if (length > Integer.MAX_VALUE) {
		response.setContentLengthLong(length);
	}
	else {
		response.setContentLength((int) length);
	}

	if (mediaType != null) {
		response.setContentType(mediaType.toString());
	}
	if (resource instanceof HttpResource) {
		HttpHeaders resourceHeaders = ((HttpResource) resource).getResponseHeaders();
		resourceHeaders.forEach((headerName, headerValues) -> {
			boolean first = true;
			for (String headerValue : headerValues) {
				if (first) {
					response.setHeader(headerName, headerValue);
				}
				else {
					response.addHeader(headerName, headerValue);
				}
				first = false;
			}
		});
	}
	response.setHeader(HttpHeaders.ACCEPT_RANGES, "bytes");
}
 
Example 14
Source File: HttpRange.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private static long getLengthFor(Resource resource) {
	try {
		long contentLength = resource.contentLength();
		Assert.isTrue(contentLength > 0, "Resource content length should be > 0");
		return contentLength;
	}
	catch (IOException ex) {
		throw new IllegalArgumentException("Failed to obtain Resource content length", ex);
	}
}
 
Example 15
Source File: ResourceHttpMessageWriter.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private static long lengthOf(Resource resource) {
	// Don't consume InputStream...
	if (InputStreamResource.class != resource.getClass()) {
		try {
			return resource.contentLength();
		}
		catch (IOException ignored) {
		}
	}
	return -1;
}
 
Example 16
Source File: ResourceHttpMessageConverter.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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);
}
 
Example 17
Source File: ResourceHttpRequestHandler.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Set headers on the given servlet response.
 * Called for GET requests as well as HEAD requests.
 * @param response current servlet response
 * @param resource the identified resource (never {@code null})
 * @param mediaType the resource's media type (never {@code null})
 * @throws IOException in case of errors while setting the headers
 */
protected void setHeaders(HttpServletResponse response, Resource resource, @Nullable MediaType mediaType)
		throws IOException {

	long length = resource.contentLength();
	if (length > Integer.MAX_VALUE) {
		response.setContentLengthLong(length);
	}
	else {
		response.setContentLength((int) length);
	}

	if (mediaType != null) {
		response.setContentType(mediaType.toString());
	}
	if (resource instanceof HttpResource) {
		HttpHeaders resourceHeaders = ((HttpResource) resource).getResponseHeaders();
		resourceHeaders.forEach((headerName, headerValues) -> {
			boolean first = true;
			for (String headerValue : headerValues) {
				if (first) {
					response.setHeader(headerName, headerValue);
				}
				else {
					response.addHeader(headerName, headerValue);
				}
				first = false;
			}
		});
	}
	response.setHeader(HttpHeaders.ACCEPT_RANGES, "bytes");
}
 
Example 18
Source File: ResourceHttpMessageConverter.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
protected Long getContentLength(Resource resource, 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!
	return (InputStreamResource.class == resource.getClass() ? null : resource.contentLength());
}