View Javadoc

1   /**
2    * Logback: the generic, reliable, fast and flexible logging framework.
3    * 
4    * Copyright (C) 1999-2006, QOS.ch
5    * 
6    * This library is free software, you can redistribute it and/or modify it under
7    * the terms of the GNU Lesser General Public License as published by the Free
8    * Software Foundation.
9    */
10  package ch.qos.logback.core.pattern;
11  
12  abstract public class FormattingConverter<E> extends Converter<E> {
13  
14    static final int INITIAL_BUF_SIZE = 256;
15    static final int MAX_CAPACITY = 1024;
16  
17    
18    FormatInfo formattingInfo;
19  
20    final public FormatInfo getFormattingInfo() {
21      return formattingInfo;
22    }
23  
24    final public void setFormattingInfo(FormatInfo formattingInfo) {
25      if (this.formattingInfo != null) {
26        throw new IllegalStateException("FormattingInfo has been already set");
27      }
28      this.formattingInfo = formattingInfo;
29    }
30  
31    final public void write(StringBuffer buf, E event) {
32      String s = convert(event);
33      
34      if(formattingInfo == null) {
35        buf.append(s);
36        return;
37      }
38      
39      int min = formattingInfo.getMin();
40      int max = formattingInfo.getMax();
41  
42  
43      if (s == null) {
44        if (0 < min)
45          SpacePadder.spacePad(buf, min);
46        return;
47      }
48  
49      int len = s.length();
50  
51      if (len > max) {
52        if(formattingInfo.isLeftTruncate()) {
53          buf.append(s.substring(len - max));
54        } else {
55          buf.append(s.substring(0, max));
56        }
57      } else if (len < min) {
58        if (formattingInfo.isLeftPad()) {
59         SpacePadder.leftPad(buf, s, min);
60        } else {
61          SpacePadder.rightPad(buf, s, min);
62        }
63      } else {
64        buf.append(s);
65      }
66    }
67  }