1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.log4j.rolling.helper;
18
19 import org.apache.log4j.helpers.LogLog;
20
21 import java.io.File;
22 import java.io.FileInputStream;
23 import java.io.FileOutputStream;
24 import java.io.IOException;
25
26 import java.util.zip.GZIPOutputStream;
27
28
29 /***
30 * Compresses a file using GZ compression.
31 *
32 * @author Curt Arnold
33 */
34 public final class GZCompressAction extends ActionBase {
35 /***
36 * Source file.
37 */
38 private final File source;
39
40 /***
41 * Destination file.
42 */
43 private final File destination;
44
45 /***
46 * If true, attempt to delete file on completion.
47 */
48 private final boolean deleteSource;
49
50
51 /***
52 * Create new instance of GZCompressAction.
53 *
54 * @param source file to compress, may not be null.
55 * @param destination compressed file, may not be null.
56 * @param deleteSource if true, attempt to delete file on completion. Failure to delete
57 * does not cause an exception to be thrown or affect return value.
58 */
59 public GZCompressAction(
60 final File source, final File destination, final boolean deleteSource) {
61 if (source == null) {
62 throw new NullPointerException("source");
63 }
64
65 if (destination == null) {
66 throw new NullPointerException("destination");
67 }
68
69 this.source = source;
70 this.destination = destination;
71 this.deleteSource = deleteSource;
72 }
73
74 /***
75 * Compress.
76 * @return true if successfully compressed.
77 * @throws IOException on IO exception.
78 */
79 public boolean execute() throws IOException {
80 return execute(source, destination, deleteSource);
81 }
82
83 /***
84 * Compress a file.
85 *
86 * @param source file to compress, may not be null.
87 * @param destination compressed file, may not be null.
88 * @param deleteSource if true, attempt to delete file on completion. Failure to delete
89 * does not cause an exception to be thrown or affect return value.
90 * @return true if source file compressed.
91 * @throws IOException on IO exception.
92 */
93 public static boolean execute(
94 final File source, final File destination, final boolean deleteSource)
95 throws IOException {
96 if (source.exists()) {
97 FileInputStream fis = new FileInputStream(source);
98 FileOutputStream fos = new FileOutputStream(destination);
99 GZIPOutputStream gzos = new GZIPOutputStream(fos);
100 byte[] inbuf = new byte[8102];
101 int n;
102
103 while ((n = fis.read(inbuf)) != -1) {
104 gzos.write(inbuf, 0, n);
105 }
106
107 gzos.close();
108 fis.close();
109
110 if (deleteSource && !source.delete()) {
111 LogLog.warn("Unable to delete " + source.toString() + ".");
112 }
113
114 return true;
115 }
116
117 return false;
118 }
119
120
121 /***
122 * Capture exception.
123 *
124 * @param ex exception.
125 */
126 protected void reportException(final Exception ex) {
127 LogLog.warn("Exception during compression of '" + source.toString() + "'.", ex);
128 }
129
130 }