1 /**
2  *  ServingXML
3  *
4  *  Copyright (C) 2006  Daniel Parker
5  *    daniel.parker@servingxml.com
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  **/
20 
21 package com.servingxml.util;
22 
23 /**
24  * The <code>LineFormatter</code> formats a line of text
25  *
26  *
27  * @author Daniel A. Parker (daniel.parker@servingxml.com)
28  */
29 
30 public class LineFormatter implements Formatter {
31   private final Alignment alignment;
32   private final char padCharacter;
33   private final int minLength;
34   private final int maxLength;
35 
LineFormatter(int length, Alignment alignment, char padCharacter)36   public LineFormatter(int length, Alignment alignment, char padCharacter) {
37     this.minLength = length;
38     this.maxLength = length;
39     this.alignment = alignment;
40     this.padCharacter = padCharacter;
41   }
42 
LineFormatter(int minLength, int maxLength, Alignment alignment, char padCharacter)43   public LineFormatter(int minLength, int maxLength, Alignment alignment, char padCharacter) {
44     this.minLength = minLength;
45     this.maxLength = maxLength;
46     this.alignment = alignment;
47     this.padCharacter = padCharacter;
48   }
49 
format(String value)50   public String format(String value) {
51 
52     String line = value;
53     if (maxLength >= 0 && line.length() > maxLength) {
54       line = line.substring(0,maxLength);
55     } else if (line.length() < minLength) {
56       StringBuilder buf = new StringBuilder(minLength);
57       if (value.length() > minLength) {
58         value = value.substring(0,minLength);
59       }
60 
61       int n = minLength - value.length();
62       int leftCount = 0;
63       int rightCount = 0;
64 
65       if (alignment.intValue() == Alignment.RIGHT.intValue()) {
66         leftCount = n;
67       } else if (alignment.intValue() == Alignment.CENTER.intValue()) {
68         leftCount = n/2;
69         rightCount = n - leftCount;
70       } else {
71         rightCount = n;
72       }
73 
74       if (leftCount > 0) {
75         for (int i = 0; i < leftCount; ++i) {
76           buf.append(padCharacter);
77         }
78 
79       }
80       buf.append(value);
81       if (rightCount > 0) {
82         for (int i = 0; i < rightCount; ++i) {
83           buf.append(padCharacter);
84         }
85 
86       }
87       line = buf.toString();
88     }
89 
90     return line;
91   }
92 }
93