001/* 002 * Logback: the reliable, generic, fast and flexible logging framework. 003 * Copyright (C) 1999-2026, 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 v2.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ülcü 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 boolean compressionSucceeded = false; 057 try (FileInputStream fis = new FileInputStream(nameOfFile2xz); 058 XZOutputStream xzos = new XZOutputStream(new BufferedOutputStream(new FileOutputStream(nameOfxzedFile), BUFFER_SIZE), new LZMA2Options())) { 059 060 byte[] inbuf = new byte[BUFFER_SIZE]; 061 int n; 062 063 while ((n = fis.read(inbuf)) != -1) { 064 xzos.write(inbuf, 0, n); 065 } 066 067 compressionSucceeded = true; 068 } catch (Exception e) { 069 addError("Error occurred while compressing [" + nameOfFile2xz + "] into [" + nameOfxzedFile + "].", e); 070 } 071 072 // Delete the original only after successful compression so a failure leaves it intact. 073 if (compressionSucceeded) { 074 if (!file2xz.delete()) { 075 addWarn("Could not delete [" + nameOfFile2xz + "]."); 076 } 077 } else { 078 addWarn("Compression of [" + nameOfFile2xz + "] failed. Original file left intact."); 079 } 080 } 081}