View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache license, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License. You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the license for the specific language governing permissions and
15   * limitations under the license.
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.nio.file.Files;
25  import java.util.Objects;
26  
27  import org.apache.commons.compress.compressors.CompressorException;
28  import org.apache.commons.compress.compressors.CompressorStreamFactory;
29  import org.apache.commons.compress.utils.IOUtils;
30  
31  /**
32   * Compresses a file using bzip2 compression.
33   */
34  public final class CommonsCompressAction extends AbstractAction {
35  
36      private static final int BUF_SIZE = 8192;
37  
38      /**
39       * Compressor name. One of "gz", "bzip2", "xz", "pack200" or "deflate".
40       */
41      private final String name;
42  
43      /**
44       * Source file.
45       */
46      private final File source;
47  
48      /**
49       * Destination file.
50       */
51      private final File destination;
52  
53      /**
54       * If true, attempt to delete file on completion.
55       */
56      private final boolean deleteSource;
57  
58      /**
59       * Creates new instance of Bzip2CompressAction.
60       *
61       * @param name the compressor name. One of "gz", "bzip2", "xz", "pack200", or "deflate".
62       * @param source file to compress, may not be null.
63       * @param destination compressed file, may not be null.
64       * @param deleteSource if true, attempt to delete file on completion. Failure to delete does not cause an exception
65       *            to be thrown or affect return value.
66       */
67      public CommonsCompressAction(final String name, final File source, final File destination,
68              final boolean deleteSource) {
69          Objects.requireNonNull(source, "source");
70          Objects.requireNonNull(destination, "destination");
71          this.name = name;
72          this.source = source;
73          this.destination = destination;
74          this.deleteSource = deleteSource;
75      }
76  
77      /**
78       * Compresses.
79       *
80       * @return true if successfully compressed.
81       * @throws IOException on IO exception.
82       */
83      @Override
84      public boolean execute() throws IOException {
85          return execute(name, source, destination, deleteSource);
86      }
87  
88      /**
89       * Compresses a file.
90       *
91       * @param name the compressor name, i.e. "gz", "bzip2", "xz", "pack200", or "deflate".
92       * @param source file to compress, may not be null.
93       * @param destination compressed file, may not be null.
94       * @param deleteSource if true, attempt to delete file on completion. Failure to delete does not cause an exception
95       *            to be thrown or affect return value.
96       *
97       * @return true if source file compressed.
98       * @throws IOException on IO exception.
99       */
100     public static boolean execute(final String name, final File source, final File destination,
101             final boolean deleteSource) throws IOException {
102         if (!source.exists()) {
103             return false;
104         }
105         LOGGER.debug("Starting {} compression of {}", name, source.getPath() );
106         try (final FileInputStream input = new FileInputStream(source);
107                 final BufferedOutputStream output = new BufferedOutputStream(
108                         new CompressorStreamFactory().createCompressorOutputStream(name, new FileOutputStream(
109                                 destination)))) {
110             IOUtils.copy(input, output, BUF_SIZE);
111             LOGGER.debug("Finished {} compression of {}", name, source.getPath() );
112         } catch (final CompressorException e) {
113             throw new IOException(e);
114         }
115 
116         if (deleteSource) {
117             try {
118                 if (Files.deleteIfExists(source.toPath())) {
119                     LOGGER.debug("Deleted {}", source.toString());
120                 } else {
121                     LOGGER.warn("Unable to delete {} after {} compression. File did not exist", source.toString(), name);
122                 }
123             } catch (final Exception ex) {
124                 LOGGER.warn("Unable to delete {} after {} compression, {}", source.toString(), name, ex.getMessage());
125             }
126         }
127 
128         return true;
129     }
130 
131     /**
132      * Reports exception.
133      *
134      * @param ex exception.
135      */
136     @Override
137     protected void reportException(final Exception ex) {
138         LOGGER.warn("Exception during " + name + " compression of '" + source.toString() + "'.", ex);
139     }
140 
141     @Override
142     public String toString() {
143         return CommonsCompressAction.class.getSimpleName() + '[' + source + " to " + destination
144                 + ", deleteSource=" + deleteSource + ']';
145     }
146 
147     public String getName() {
148         return name;
149     }
150 
151     public File getSource() {
152         return source;
153     }
154 
155     public File getDestination() {
156         return destination;
157     }
158 
159     public boolean isDeleteSource() {
160         return deleteSource;
161     }
162 }