Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reuse InputStream for ResourceRegionHttpMessageConverter #24214

Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -22,7 +22,11 @@
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourceRegion;
Expand Down Expand Up @@ -178,12 +182,28 @@ private void writeResourceRegionCollection(Collection<ResourceRegion> resourceRe
String boundaryString = MimeTypeUtils.generateMultipartBoundaryString();
responseHeaders.set(HttpHeaders.CONTENT_TYPE, "multipart/byteranges; boundary=" + boundaryString);
OutputStream out = outputMessage.getBody();
// Allows reuse of streams
Map<Resource, InputStream> cleanup = new HashMap<>();
List<IOException> exs = new ArrayList<>();

try {
for (ResourceRegion region : resourceRegions) {
long start = region.getPosition();
long end = start + region.getCount() - 1;

InputStream in = cleanup.computeIfAbsent(region.getResource(), r -> {
try {
return r.getInputStream();
} catch (IOException e) {
exs.add(e);
return null;
}
});

if (!exs.isEmpty()) {
throw exs.get(0);
}

for (ResourceRegion region : resourceRegions) {
long start = region.getPosition();
long end = start + region.getCount() - 1;
InputStream in = region.getResource().getInputStream();
try {
// Writing MIME header.
println(out);
print(out, "--" + boundaryString);
Expand All @@ -200,11 +220,11 @@ private void writeResourceRegionCollection(Collection<ResourceRegion> resourceRe
// Printing content
StreamUtils.copyRange(in, out, start, end);
}
finally {
} finally {
for (InputStream in : cleanup) {
try {
in.close();
}
catch (IOException ex) {
} catch (IOException ex) {
// ignore
}
}
Expand Down