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 import java.io.BufferedOutputStream;
20 import java.io.File;
21 import java.io.FileInputStream;
22 import java.io.FileOutputStream;
23 import java.util.zip.ZipEntry;
24 import java.util.zip.ZipOutputStream;
25
26
27
28
29
30
31
32 public class ZipCompressionStrategy extends CompressionStrategyBase {
33
34 @Override
35 public void compress(String originalFileName, String compressedFileName, String innerEntryName) {
36
37 File file2zip = new File(originalFileName);
38
39 if (!file2zip.exists()) {
40 addStatus(new WarnStatus("The file to compress named [" + originalFileName + "] does not exist.", this));
41
42 return;
43 }
44
45 if (innerEntryName == null) {
46 addStatus(new WarnStatus("The innerEntryName parameter cannot be null", this));
47 return;
48 }
49
50 if (!compressedFileName.endsWith(".zip")) {
51 compressedFileName = compressedFileName + ".zip";
52 }
53
54 File zippedFile = new File(compressedFileName);
55
56 if (zippedFile.exists()) {
57 addStatus(new WarnStatus("The target compressed file named [" + compressedFileName + "] exist already.", this));
58
59 return;
60 }
61
62 addInfo("ZIP compressing [" + file2zip + "] as [" + zippedFile + "]");
63 createMissingTargetDirsIfNecessary(zippedFile);
64
65 boolean compressionSucceeded = false;
66 try (FileInputStream fis = new FileInputStream(originalFileName);
67 ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(compressedFileName), BUFFER_SIZE))) {
68
69 ZipEntry zipEntry = computeZipEntry(innerEntryName);
70 zos.putNextEntry(zipEntry);
71
72 byte[] inbuf = new byte[BUFFER_SIZE];
73 int n;
74
75 while ((n = fis.read(inbuf)) != -1) {
76 zos.write(inbuf, 0, n);
77 }
78
79 compressionSucceeded = true;
80 addInfo("Done ZIP compressing [" + file2zip + "] as [" + zippedFile + "]");
81 } catch (Exception e) {
82 addStatus(new ErrorStatus("Error occurred while compressing [" + originalFileName + "] into [" + compressedFileName + "].", this, e));
83 }
84
85
86 if (compressionSucceeded) {
87 if (!file2zip.delete()) {
88 addStatus(new WarnStatus("Could not delete [" + originalFileName + "].", this));
89 }
90 } else {
91 addStatus(new WarnStatus("Compression of [" + originalFileName + "] failed. Original file left intact.", this));
92 }
93 }
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114 ZipEntry computeZipEntry(String filename) {
115 String nameOfFileNestedWithinArchive = Compressor.computeFileNameStrWithoutCompSuffix(filename, CompressionMode.ZIP);
116 return new ZipEntry(nameOfFileNestedWithinArchive);
117 }
118 }