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 */
014
015package ch.qos.logback.core.rolling.helper;
016
017import ch.qos.logback.core.status.ErrorStatus;
018import ch.qos.logback.core.status.WarnStatus;
019
020import java.io.BufferedInputStream;
021import java.io.File;
022import java.io.FileInputStream;
023import java.io.FileOutputStream;
024import java.util.zip.GZIPOutputStream;
025
026public class GZCompressionStrategy extends CompressionStrategyBase {
027
028
029    @Override
030    public void compress(String originalFileName, String compressedFileName, String innerEntryName) {
031
032        File file2gz = new File(originalFileName);
033
034        if (!file2gz.exists()) {
035            addStatus(new WarnStatus("The file to compress named [" + originalFileName + "] does not exist.", this));
036
037            return;
038        }
039
040        if (!compressedFileName.endsWith(".gz")) {
041            compressedFileName = compressedFileName + ".gz";
042        }
043
044        File gzedFile = new File(compressedFileName);
045
046        if (gzedFile.exists()) {
047            addWarn("The target compressed file named [" + compressedFileName + "] exist already. Aborting file compression.");
048            return;
049        }
050
051        addInfo("GZ compressing [" + file2gz + "] as [" + gzedFile + "]");
052        createMissingTargetDirsIfNecessary(gzedFile);
053
054        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(originalFileName));
055                        GZIPOutputStream gzos = new GZIPOutputStream(new FileOutputStream(compressedFileName))) {
056
057            byte[] inbuf = new byte[BUFFER_SIZE];
058            int n;
059
060            while ((n = bis.read(inbuf)) != -1) {
061                gzos.write(inbuf, 0, n);
062            }
063
064            addInfo("Done GZ compressing [" + file2gz + "] as [" + gzedFile + "]");
065        } catch (Exception e) {
066            addStatus(new ErrorStatus("Error occurred while compressing [" + originalFileName + "] into [" + compressedFileName + "].", this, e));
067        }
068
069        if (!file2gz.delete()) {
070            addStatus(new WarnStatus("Could not delete [" + originalFileName + "].", this));
071        }
072    }
073
074}