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