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 LOGGER.debug("Starting {} compression of {}", name, source.getPath() );
105 try (final FileInputStream input = new FileInputStream(source);
106 final BufferedOutputStream output = new BufferedOutputStream(
107 new CompressorStreamFactory().createCompressorOutputStream(name, new FileOutputStream(
108 destination)))) {
109 IOUtils.copy(input, output, BUF_SIZE);
110 } catch (final CompressorException e) {
111 throw new IOException(e);
112 } finally {
113 LOGGER.debug("Finished {} compression of {}", name, source.getPath() );
114 }
115
116 if (deleteSource && !source.delete()) {
117 LOGGER.warn("Unable to delete " + source.toString() + '.');
118 } else {
119 LOGGER.debug("Deleted {}", source.toString());
120 }
121 return true;
122 }
123
124
125
126
127
128
129 @Override
130 protected void reportException(final Exception ex) {
131 LOGGER.warn("Exception during " + name + " compression of '" + source.toString() + "'.", ex);
132 }
133
134 @Override
135 public String toString() {
136 return CommonsCompressAction.class.getSimpleName() + '[' + source + " to " + destination
137 + ", deleteSource=" + deleteSource + ']';
138 }
139
140 public String getName() {
141 return name;
142 }
143
144 public File getSource() {
145 return source;
146 }
147
148 public File getDestination() {
149 return destination;
150 }
151
152 public boolean isDeleteSource() {
153 return deleteSource;
154 }
155 }