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.BufferedInputStream;
017import java.io.File;
018import java.io.FileInputStream;
019import java.io.FileOutputStream;
020import org.tukaani.xz.LZMA2Options;
021import org.tukaani.xz.XZOutputStream;
022
023/**
024 * Compresses files using {@link org.tukaani.xz xz} library.
025 *
026 * <p>Note that </p>
027 *
028 * @author Marian Kazimir
029 * @author Ceki G&uuml;lc&uuml;
030 * @since 1.5.18
031 */
032public class XZCompressionStrategy extends CompressionStrategyBase {
033
034    @Override
035    public void compress(String nameOfFile2xz, String nameOfxzedFile, String innerEntryName) {
036        File file2xz = new File(nameOfFile2xz);
037
038        if (!file2xz.exists()) {
039            addWarn("The file to compress named [" + nameOfFile2xz + "] does not exist.");
040
041            return;
042        }
043
044        if (!nameOfxzedFile.endsWith(".xz")) {
045            nameOfxzedFile = nameOfxzedFile + ".xz";
046        }
047
048        File xzedFile = new File(nameOfxzedFile);
049
050        if (xzedFile.exists()) {
051            addWarn("The target compressed file named [" + nameOfxzedFile + "] exist already. Aborting file compression.");
052            return;
053        }
054
055        addInfo("XZ compressing [" + file2xz + "] as [" + xzedFile + "]");
056        createMissingTargetDirsIfNecessary(xzedFile);
057
058        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(nameOfFile2xz));
059                        XZOutputStream xzos = new XZOutputStream(new FileOutputStream(nameOfxzedFile), new LZMA2Options())) {
060
061            byte[] inbuf = new byte[BUFFER_SIZE];
062            int n;
063
064            while ((n = bis.read(inbuf)) != -1) {
065                xzos.write(inbuf, 0, n);
066            }
067        } catch (Exception e) {
068            addError("Error occurred while compressing [" + nameOfFile2xz + "] into [" + nameOfxzedFile + "].", e);
069        }
070
071        if (!file2xz.delete()) {
072            addWarn("Could not delete [" + nameOfFile2xz + "].");
073        }
074    }
075}