1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package ch.qos.logback.core.rolling.helper;
16
17 import ch.qos.logback.core.status.ErrorStatus;
18 import ch.qos.logback.core.status.WarnStatus;
19
20 import java.io.File;
21 import java.io.FileInputStream;
22 import java.io.FileOutputStream;
23 import java.util.zip.GZIPOutputStream;
24
25 import static ch.qos.logback.core.rolling.helper.CompressionMode.GZ_SUFFIX;
26
27 public class GZCompressionStrategy extends CompressionStrategyBase {
28
29
30 @Override
31 public void compress(String originalFileName, String compressedFileName, String innerEntryName) {
32
33 File file2gz = new File(originalFileName);
34
35 if (!file2gz.exists()) {
36 addStatus(new WarnStatus("The file to compress named [" + originalFileName + "] does not exist.", this));
37
38 return;
39 }
40
41 if (!compressedFileName.endsWith(GZ_SUFFIX)) {
42 compressedFileName = compressedFileName + GZ_SUFFIX;
43 }
44
45 File gzedFile = new File(compressedFileName);
46
47 if (gzedFile.exists()) {
48 addWarn("The target compressed file named [" + compressedFileName + "] exist already. Aborting file compression.");
49 return;
50 }
51
52 addInfo("GZ compressing [" + file2gz + "] as [" + gzedFile + "]");
53 createMissingTargetDirsIfNecessary(gzedFile);
54 boolean compressionSucceeded = false;
55 try (FileInputStream fis = new FileInputStream(originalFileName);
56 GZIPOutputStream gzos = new GZIPOutputStream(new FileOutputStream(compressedFileName), BUFFER_SIZE)) {
57
58 byte[] inbuf = new byte[BUFFER_SIZE];
59 int n;
60
61 while ((n = fis.read(inbuf)) != -1) {
62 gzos.write(inbuf, 0, n);
63 }
64
65 compressionSucceeded = true;
66 addInfo("Done GZ compressing [" + file2gz + "] as [" + gzedFile + "]");
67 } catch (Exception e) {
68 addStatus(new ErrorStatus("Error occurred while compressing [" + originalFileName + "] into [" + compressedFileName + "].", this, e));
69 }
70
71
72
73 if (compressionSucceeded) {
74 if (!file2gz.delete()) {
75 addStatus(new WarnStatus("Could not delete [" + originalFileName + "].", this));
76 }
77 } else {
78 addStatus(new WarnStatus("Compression of [" + originalFileName + "] failed. Original file left intact.", this));
79 }
80
81 }
82
83 }