1 /**
2  * Logback: the reliable, generic, fast and flexible logging framework.
3  * Copyright (C) 1999-2015, 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 v1.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.pattern;
15
16 abstract public class FormattingConverter<E> extends Converter<E> {
17
18     static final int INITIAL_BUF_SIZE = 256;
19     static final int MAX_CAPACITY = 1024;
20
21     FormatInfo formattingInfo;
22
23     final public FormatInfo getFormattingInfo() {
24         return formattingInfo;
25     }
26
27     final public void setFormattingInfo(FormatInfo formattingInfo) {
28         if (this.formattingInfo != null) {
29             throw new IllegalStateException("FormattingInfo has been already set");
30         }
31         this.formattingInfo = formattingInfo;
32     }
33
34     @Override
35     final public void write(StringBuilder buf, E event) {
36         String s = convert(event);
37
38         if (formattingInfo == null) {
39             buf.append(s);
40             return;
41         }
42
43         int min = formattingInfo.getMin();
44         int max = formattingInfo.getMax();
45
46         if (s == null) {
47             if (0 < min)
48                 SpacePadder.spacePad(buf, min);
49             return;
50         }
51
52         int len = s.length();
53
54         if (len > max) {
55             if (formattingInfo.isLeftTruncate()) {
56                 buf.append(s.substring(len - max));
57             } else {
58                 buf.append(s.substring(0, max));
59             }
60         } else if (len < min) {
61             if (formattingInfo.isLeftPad()) {
62                 SpacePadder.leftPad(buf, s, min);
63             } else {
64                 SpacePadder.rightPad(buf, s, min);
65             }
66         } else {
67             buf.append(s);
68         }
69     }
70 }
71