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
26 import org.apache.commons.compress.compressors.CompressorException;
27 import org.apache.commons.compress.compressors.CompressorStreamFactory;
28 import org.apache.commons.compress.utils.IOUtils;
29
30
31
32
33 public final class CommonsCompressAction extends AbstractAction {
34
35 private static final int BUF_SIZE = 8102;
36
37
38
39
40 private final String name;
41
42
43
44
45 private final File source;
46
47
48
49
50 private final File destination;
51
52
53
54
55 private final boolean deleteSource;
56
57
58
59
60
61
62
63
64
65 public CommonsCompressAction(final String name, final File source, final File destination, final boolean deleteSource) {
66 Objects.requireNonNull(source, "source");
67 Objects.requireNonNull(destination, "destination");
68 this.name = name;
69 this.source = source;
70 this.destination = destination;
71 this.deleteSource = deleteSource;
72 }
73
74
75
76
77
78
79
80 @Override
81 public boolean execute() throws IOException {
82 return execute(name, source, destination, deleteSource);
83 }
84
85
86
87
88
89
90
91
92
93
94
95
96 public static boolean execute(final String name, final File source, final File destination, final boolean deleteSource)
97 throws IOException {
98 if (!source.exists()) {
99 return false;
100 }
101 try (final FileInputStream input = new FileInputStream(source);
102 final BufferedOutputStream output = new BufferedOutputStream(new CompressorStreamFactory()
103 .createCompressorOutputStream(name, new FileOutputStream(destination)))) {
104 IOUtils.copy(input, output, BUF_SIZE);
105 } catch (final CompressorException e) {
106 throw new IOException(e);
107 }
108
109 if (deleteSource && !source.delete()) {
110 LOGGER.warn("Unable to delete " + source.toString() + '.');
111 }
112 return true;
113 }
114
115
116
117
118
119
120 @Override
121 protected void reportException(final Exception ex) {
122 LOGGER.warn("Exception during " + name + " compression of '" + source.toString() + "'.", ex);
123 }
124
125 @Override
126 public String toString() {
127 return CommonsCompressAction.class.getSimpleName() + '[' + source + " to " + destination
128 + ", deleteSource=" + deleteSource + ']';
129 }
130 }