001/** 002 * Logback: the reliable, generic, fast and flexible logging framework. 003 * Copyright (C) 1999-2015, 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.pattern; 015 016abstract public class FormattingConverter<E> extends Converter<E> { 017 018 static final int INITIAL_BUF_SIZE = 256; 019 static final int MAX_CAPACITY = 1024; 020 021 FormatInfo formattingInfo; 022 023 final public FormatInfo getFormattingInfo() { 024 return formattingInfo; 025 } 026 027 final public void setFormattingInfo(FormatInfo formattingInfo) { 028 if (this.formattingInfo != null) { 029 throw new IllegalStateException("FormattingInfo has been already set"); 030 } 031 this.formattingInfo = formattingInfo; 032 } 033 034 @Override 035 final public void write(StringBuilder buf, E event) { 036 String s = convert(event); 037 038 if (formattingInfo == null) { 039 buf.append(s); 040 return; 041 } 042 043 int min = formattingInfo.getMin(); 044 int max = formattingInfo.getMax(); 045 046 if (s == null) { 047 if (0 < min) 048 SpacePadder.spacePad(buf, min); 049 return; 050 } 051 052 int len = s.length(); 053 054 if (len > max) { 055 if (formattingInfo.isLeftTruncate()) { 056 buf.append(s.substring(len - max)); 057 } else { 058 buf.append(s.substring(0, max)); 059 } 060 } else if (len < min) { 061 if (formattingInfo.isLeftPad()) { 062 SpacePadder.leftPad(buf, s, min); 063 } else { 064 SpacePadder.rightPad(buf, s, min); 065 } 066 } else { 067 buf.append(s); 068 } 069 } 070}