001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache license, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the license for the specific language governing permissions and
015 * limitations under the license.
016 */
017package org.apache.logging.log4j.core.appender.rolling.action;
018
019import java.io.BufferedOutputStream;
020import java.io.File;
021import java.io.FileInputStream;
022import java.io.FileOutputStream;
023import java.io.IOException;
024import java.nio.file.Files;
025import java.util.Objects;
026
027import org.apache.commons.compress.compressors.CompressorException;
028import org.apache.commons.compress.compressors.CompressorStreamFactory;
029import org.apache.commons.compress.utils.IOUtils;
030
031/**
032 * Compresses a file using bzip2 compression.
033 */
034public final class CommonsCompressAction extends AbstractAction {
035
036    private static final int BUF_SIZE = 8192;
037
038    /**
039     * Compressor name. One of "gz", "bzip2", "xz", "pack200" or "deflate".
040     */
041    private final String name;
042
043    /**
044     * Source file.
045     */
046    private final File source;
047
048    /**
049     * Destination file.
050     */
051    private final File destination;
052
053    /**
054     * If true, attempt to delete file on completion.
055     */
056    private final boolean deleteSource;
057
058    /**
059     * Creates new instance of Bzip2CompressAction.
060     *
061     * @param name the compressor name. One of "gz", "bzip2", "xz", "pack200", or "deflate".
062     * @param source file to compress, may not be null.
063     * @param destination compressed file, may not be null.
064     * @param deleteSource if true, attempt to delete file on completion. Failure to delete does not cause an exception
065     *            to be thrown or affect return value.
066     */
067    public CommonsCompressAction(final String name, final File source, final File destination,
068            final boolean deleteSource) {
069        Objects.requireNonNull(source, "source");
070        Objects.requireNonNull(destination, "destination");
071        this.name = name;
072        this.source = source;
073        this.destination = destination;
074        this.deleteSource = deleteSource;
075    }
076
077    /**
078     * Compresses.
079     *
080     * @return true if successfully compressed.
081     * @throws IOException on IO exception.
082     */
083    @Override
084    public boolean execute() throws IOException {
085        return execute(name, source, destination, deleteSource);
086    }
087
088    /**
089     * Compresses a file.
090     *
091     * @param name the compressor name, i.e. "gz", "bzip2", "xz", "pack200", or "deflate".
092     * @param source file to compress, may not be null.
093     * @param destination compressed file, may not be null.
094     * @param deleteSource if true, attempt to delete file on completion. Failure to delete does not cause an exception
095     *            to be thrown or affect return value.
096     *
097     * @return true if source file compressed.
098     * @throws IOException on IO exception.
099     */
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}