Fix inputstream connection leak when downloading files

This commit is contained in:
Kevin Van de Velde
2022-01-14 13:10:10 +01:00
parent 69345ff3fc
commit 82cdf48987
7 changed files with 97 additions and 79 deletions

View File

@@ -21,7 +21,6 @@ import java.util.List;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.pdfbox.pdmodel.PDDocument;
@@ -297,8 +296,21 @@ public class CitationDocumentServiceImpl implements CitationDocumentService, Ini
}
@Override
public Pair<InputStream, Long> makeCitedDocument(Context context, Bitstream bitstream)
throws IOException, SQLException, AuthorizeException {
public InputStream getCitedDocument(Context context, Bitstream bitstream)
throws SQLException, AuthorizeException, IOException {
byte [] citedDocumentContent = getCitedDocumentContent(context, bitstream);
return new ByteArrayInputStream(citedDocumentContent);
}
@Override
public Long getCitedDocumentLength(Context context, Bitstream bitstream)
throws SQLException, AuthorizeException, IOException {
byte[] citedDocumentContent = getCitedDocumentContent(context, bitstream);
return Long.valueOf(citedDocumentContent.length);
}
private byte[] getCitedDocumentContent(Context context, Bitstream bitstream)
throws SQLException, AuthorizeException, IOException {
PDDocument document = new PDDocument();
PDDocument sourceDocument = new PDDocument();
try {
@@ -307,15 +319,10 @@ public class CitationDocumentServiceImpl implements CitationDocumentService, Ini
PDPage coverPage = new PDPage(citationPageFormat);
generateCoverPage(context, document, coverPage, item);
addCoverPageToDocument(document, sourceDocument, coverPage);
//We already have the full PDF in memory, so keep it there
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
document.save(out);
byte[] data = out.toByteArray();
return Pair.of((InputStream) new ByteArrayInputStream(data), Long.valueOf(data.length));
return out.toByteArray();
}
} finally {
sourceDocument.close();
document.close();