Skip to content

Commit a313e77

Browse files
committed
Ensure that corrupt GZIP data is not read.
1 parent f21a656 commit a313e77

File tree

1 file changed

+30
-2
lines changed

1 file changed

+30
-2
lines changed

src/main/java/org/radarcns/data/FileCache.java

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@
3838
import java.nio.file.StandardOpenOption;
3939
import java.util.zip.GZIPInputStream;
4040
import java.util.zip.GZIPOutputStream;
41+
import java.util.zip.ZipException;
4142

4243
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
4344

@@ -71,7 +72,7 @@ public FileCache(RecordConverterFactory converterFactory, Path path,
7172
} else {
7273
this.tmpPath = Files.createTempFile(tmpDir, path.getFileName().toString(),
7374
gzip ? ".tmp.gz" : ".tmp");
74-
outFile = Files.newOutputStream(tmpPath, StandardOpenOption.WRITE);
75+
outFile = Files.newOutputStream(tmpPath);
7576
}
7677

7778
OutputStream bufOut = new BufferedOutputStream(outFile);
@@ -86,7 +87,15 @@ public FileCache(RecordConverterFactory converterFactory, Path path,
8687
inputStream = inputStream(new BufferedInputStream(Files.newInputStream(path)), gzip);
8788

8889
if (tmpPath != null) {
89-
copy(path, bufOut, gzip);
90+
try {
91+
copy(path, bufOut, gzip);
92+
} catch (ZipException ex) {
93+
// restart output buffer
94+
bufOut.close();
95+
// clear output file
96+
outFile = Files.newOutputStream(tmpPath);
97+
bufOut = new GZIPOutputStream(new BufferedOutputStream(outFile));
98+
}
9099
}
91100
}
92101

@@ -152,6 +161,25 @@ public Path getPath() {
152161
private static void copy(Path source, OutputStream sink, boolean gzip) throws IOException {
153162
try (InputStream copyStream = inputStream(Files.newInputStream(source), gzip)) {
154163
copy(copyStream, sink);
164+
} catch (ZipException ex) {
165+
Path corruptPath = null;
166+
String suffix = "";
167+
for (int i = 0; corruptPath == null && i < 100; i++) {
168+
Path path = source.resolveSibling(source.getFileName() + ".corrupted" + suffix);
169+
if (!Files.exists(path)) {
170+
corruptPath = path;
171+
}
172+
suffix = "-" + i;
173+
}
174+
if (corruptPath != null) {
175+
logger.error("Original file {} was corrupted: {}."
176+
+ " Moved to {}.", source, ex, corruptPath);
177+
Files.move(source, corruptPath);
178+
} else {
179+
logger.error("Original file {} was corrupted: {}."
180+
+ " Too many corrupt backups stored, removing file.", source, ex);
181+
}
182+
throw ex;
155183
}
156184
}
157185

0 commit comments

Comments
 (0)