1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.logging.log4j.core.appender.rolling.action;
18
19 import java.io.BufferedOutputStream;
20 import java.io.File;
21 import java.io.FileInputStream;
22 import java.io.FileOutputStream;
23 import java.io.IOException;
24 import java.util.Objects;
25 import java.util.zip.GZIPOutputStream;
26
27
28
29
30 public final class GzCompressAction extends AbstractAction {
31
32 private static final int BUF_SIZE = 8192;
33
34
35
36
37 private final File source;
38
39
40
41
42 private final File destination;
43
44
45
46
47 private final boolean deleteSource;
48
49
50
51
52
53
54
55
56
57 public GzCompressAction(final File source, final File destination, final boolean deleteSource) {
58 Objects.requireNonNull(source, "source");
59 Objects.requireNonNull(destination, "destination");
60
61 this.source = source;
62 this.destination = destination;
63 this.deleteSource = deleteSource;
64 }
65
66
67
68
69
70
71
72 @Override
73 public boolean execute() throws IOException {
74 return execute(source, destination, deleteSource);
75 }
76
77
78
79
80
81
82
83
84
85
86
87 public static boolean execute(final File source, final File destination, final boolean deleteSource)
88 throws IOException {
89 if (source.exists()) {
90 try (final FileInputStream fis = new FileInputStream(source);
91 final BufferedOutputStream os = new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(
92 destination)))) {
93 final byte[] inbuf = new byte[BUF_SIZE];
94 int n;
95
96 while ((n = fis.read(inbuf)) != -1) {
97 os.write(inbuf, 0, n);
98 }
99 }
100
101 if (deleteSource && !source.delete()) {
102 LOGGER.warn("Unable to delete " + source.toString() + '.');
103 }
104
105 return true;
106 }
107
108 return false;
109 }
110
111
112
113
114
115
116
117 @Override
118 protected void reportException(final Exception ex) {
119 LOGGER.warn("Exception during compression of '" + source.toString() + "'.", ex);
120 }
121
122 @Override
123 public String toString() {
124 return GzCompressAction.class.getSimpleName() + '[' + source + " to " + destination
125 + ", deleteSource=" + deleteSource + ']';
126 }
127
128 public File getSource() {
129 return source;
130 }
131
132 public File getDestination() {
133 return destination;
134 }
135
136 public boolean isDeleteSource() {
137 return deleteSource;
138 }
139 }