1   /*
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2026, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v2.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.core.rolling.helper;
15  
16  import java.io.*;
17  
18  import org.tukaani.xz.LZMA2Options;
19  import org.tukaani.xz.XZOutputStream;
20  
21  /**
22   * Compresses files using <a href="https://tukaani.org/xz/">tukaani.org/xz</a> library.
23   *
24   * <p>Note that </p>
25   *
26   * @author Marian Kazimir
27   * @author Ceki G&uuml;lc&uuml;
28   * @since 1.5.18
29   */
30  public class XZCompressionStrategy extends CompressionStrategyBase {
31  
32      @Override
33      public void compress(String nameOfFile2xz, String nameOfxzedFile, String innerEntryName) {
34          File file2xz = new File(nameOfFile2xz);
35  
36          if (!file2xz.exists()) {
37              addWarn("The file to compress named [" + nameOfFile2xz + "] does not exist.");
38  
39              return;
40          }
41  
42          if (!nameOfxzedFile.endsWith(".xz")) {
43              nameOfxzedFile = nameOfxzedFile + ".xz";
44          }
45  
46          File xzedFile = new File(nameOfxzedFile);
47  
48          if (xzedFile.exists()) {
49              addWarn("The target compressed file named [" + nameOfxzedFile + "] exist already. Aborting file compression.");
50              return;
51          }
52  
53          addInfo("XZ compressing [" + file2xz + "] as [" + xzedFile + "]");
54          createMissingTargetDirsIfNecessary(xzedFile);
55  
56          try (FileInputStream fis = new FileInputStream(nameOfFile2xz);
57               XZOutputStream xzos = new XZOutputStream(new BufferedOutputStream(new FileOutputStream(nameOfxzedFile), BUFFER_SIZE), new LZMA2Options())) {
58  
59              byte[] inbuf = new byte[BUFFER_SIZE];
60              int n;
61  
62              while ((n = fis.read(inbuf)) != -1) {
63                  xzos.write(inbuf, 0, n);
64              }
65          } catch (Exception e) {
66              addError("Error occurred while compressing [" + nameOfFile2xz + "] into [" + nameOfxzedFile + "].", e);
67          }
68  
69          if (!file2xz.delete()) {
70              addWarn("Could not delete [" + nameOfFile2xz + "].");
71          }
72      }
73  }