001/*
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2023, 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.testUtil;
015
016import java.nio.charset.Charset;
017
018import ch.qos.logback.core.CoreConstants;
019import ch.qos.logback.core.encoder.EncoderBase;
020
021public class DummyEncoder<E> extends EncoderBase<E> {
022
023    public static final String DUMMY = "dummy" + CoreConstants.LINE_SEPARATOR;
024    String val = DUMMY;
025    String fileHeader;
026    String fileFooter;
027    Charset charset;
028
029    public Charset getCharset() {
030        return charset;
031    }
032
033    public void setCharset(Charset charset) {
034        this.charset = charset;
035    }
036
037    public DummyEncoder() {
038    }
039
040    public DummyEncoder(String val) {
041        this.val = val;
042    }
043
044    public byte[] encode(E event) {
045        return encodeString(val);
046    }
047
048    byte[] encodeString(String s) {
049        if (charset == null) {
050            return s.getBytes();
051        } else {
052            return s.getBytes(charset);
053        }
054    }
055
056    private void appendIfNotNull(StringBuilder sb, String s) {
057        if (s != null) {
058            sb.append(s);
059        }
060    }
061
062    byte[] header() {
063        StringBuilder sb = new StringBuilder();
064        appendIfNotNull(sb, fileHeader);
065        if (sb.length() > 0) {
066            // If at least one of file header or presentation header were not
067            // null, then append a line separator.
068            // This should be useful in most cases and should not hurt.
069            sb.append(CoreConstants.LINE_SEPARATOR);
070        }
071        return encodeString(sb.toString());
072    }
073
074    public byte[] headerBytes() {
075        return header();
076    }
077
078    public byte[] footerBytes() {
079        if (fileFooter == null) {
080            return null;
081        }
082        return encodeString(fileFooter);
083    }
084
085    public String getFileHeader() {
086        return fileHeader;
087    }
088
089    public void setFileHeader(String fileHeader) {
090        this.fileHeader = fileHeader;
091    }
092
093    public String getFileFooter() {
094        return fileFooter;
095    }
096
097    public void setFileFooter(String fileFooter) {
098        this.fileFooter = fileFooter;
099    }
100
101}