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
66 public CommonsCompressAction(final String name, final File source, final File destination,
67 final boolean deleteSource) {
68 Objects.requireNonNull(source, "source");
69 Objects.requireNonNull(destination, "destination");
70 this.name = name;
71 this.source = source;
72 this.destination = destination;
73 this.deleteSource = deleteSource;
74 }
75
76
77
78
79
80
81
82 @Override
83 public boolean execute() throws IOException {
84 return execute(name, source, destination, deleteSource);
85 }
86
87
88
89
90
91
92
93
94
95
96
97
98
99 public static boolean execute(final String name, final File source, final File destination,
100 final boolean deleteSource) throws IOException {
101 if (!source.exists()) {
102 return false;
103 }
104 try (final FileInputStream input = new FileInputStream(source);
105 final BufferedOutputStream output = new BufferedOutputStream(
106 new CompressorStreamFactory().createCompressorOutputStream(name, new FileOutputStream(
107 destination)))) {
108 IOUtils.copy(input, output, BUF_SIZE);
109 } catch (final CompressorException e) {
110 throw new IOException(e);
111 }
112
113 if (deleteSource && !source.delete()) {
114 LOGGER.warn("Unable to delete " + source.toString() + '.');
115 }
116 return true;
117 }
118
119
120
121
122
123
124 @Override
125 protected void reportException(final Exception ex) {
126 LOGGER.warn("Exception during " + name + " compression of '" + source.toString() + "'.", ex);
127 }
128
129 @Override
130 public String toString() {
131 return CommonsCompressAction.class.getSimpleName() + '[' + source + " to " + destination
132 + ", deleteSource=" + deleteSource + ']';
133 }
134
135 public String getName() {
136 return name;
137 }
138
139 public File getSource() {
140 return source;
141 }
142
143 public File getDestination() {
144 return destination;
145 }
146
147 public boolean isDeleteSource() {
148 return deleteSource;
149 }
150 }