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 public class GZCompressionStrategy extends CompressionStrategyBase {
26
27
28 @Override
29 public void compress(String originalFileName, String compressedFileName, String innerEntryName) {
30
31 File file2gz = new File(originalFileName);
32
33 if (!file2gz.exists()) {
34 addStatus(new WarnStatus("The file to compress named [" + originalFileName + "] does not exist.", this));
35
36 return;
37 }
38
39 if (!compressedFileName.endsWith(".gz")) {
40 compressedFileName = compressedFileName + ".gz";
41 }
42
43 File gzedFile = new File(compressedFileName);
44
45 if (gzedFile.exists()) {
46 addWarn("The target compressed file named [" + compressedFileName + "] exist already. Aborting file compression.");
47 return;
48 }
49
50 addInfo("GZ compressing [" + file2gz + "] as [" + gzedFile + "]");
51 createMissingTargetDirsIfNecessary(gzedFile);
52 try (FileInputStream fis = new FileInputStream(originalFileName);
53 GZIPOutputStream gzos = new GZIPOutputStream(new FileOutputStream(compressedFileName), BUFFER_SIZE)) {
54
55 byte[] inbuf = new byte[BUFFER_SIZE];
56 int n;
57
58 while ((n = fis.read(inbuf)) != -1) {
59 gzos.write(inbuf, 0, n);
60 }
61
62 addInfo("Done GZ compressing [" + file2gz + "] as [" + gzedFile + "]");
63 } catch (Exception e) {
64 addStatus(new ErrorStatus("Error occurred while compressing [" + originalFileName + "] into [" + compressedFileName + "].", this, e));
65 }
66
67 if (!file2gz.delete()) {
68 addStatus(new WarnStatus("Could not delete [" + originalFileName + "].", this));
69 }
70 }
71
72 }