001/*
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2025, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v1.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package ch.qos.logback.core.rolling.helper;
015
016import java.io.*;
017
018import org.tukaani.xz.LZMA2Options;
019import org.tukaani.xz.XZOutputStream;
020
021/**
022 * Compresses files using <a href="https://tukaani.org/xz/">tukaani.org/xz</a> library.
023 *
024 * <p>Note that </p>
025 *
026 * @author Marian Kazimir
027 * @author Ceki G&uuml;lc&uuml;
028 * @since 1.5.18
029 */
030public class XZCompressionStrategy extends CompressionStrategyBase {
031
032    @Override
033    public void compress(String nameOfFile2xz, String nameOfxzedFile, String innerEntryName) {
034        File file2xz = new File(nameOfFile2xz);
035
036        if (!file2xz.exists()) {
037            addWarn("The file to compress named [" + nameOfFile2xz + "] does not exist.");
038
039            return;
040        }
041
042        if (!nameOfxzedFile.endsWith(".xz")) {
043            nameOfxzedFile = nameOfxzedFile + ".xz";
044        }
045
046        File xzedFile = new File(nameOfxzedFile);
047
048        if (xzedFile.exists()) {
049            addWarn("The target compressed file named [" + nameOfxzedFile + "] exist already. Aborting file compression.");
050            return;
051        }
052
053        addInfo("XZ compressing [" + file2xz + "] as [" + xzedFile + "]");
054        createMissingTargetDirsIfNecessary(xzedFile);
055
056        try (FileInputStream fis = new FileInputStream(nameOfFile2xz);
057             XZOutputStream xzos = new XZOutputStream(new BufferedOutputStream(new FileOutputStream(nameOfxzedFile), BUFFER_SIZE), new LZMA2Options())) {
058
059            byte[] inbuf = new byte[BUFFER_SIZE];
060            int n;
061
062            while ((n = fis.read(inbuf)) != -1) {
063                xzos.write(inbuf, 0, n);
064            }
065        } catch (Exception e) {
066            addError("Error occurred while compressing [" + nameOfFile2xz + "] into [" + nameOfxzedFile + "].", e);
067        }
068
069        if (!file2xz.delete()) {
070            addWarn("Could not delete [" + nameOfFile2xz + "].");
071        }
072    }
073}