1 package com.github.mygreen.supercsv.cellprocessor.conversion;
2
3 import org.supercsv.cellprocessor.CellProcessorAdaptor;
4 import org.supercsv.cellprocessor.ift.StringCellProcessor;
5 import org.supercsv.util.CsvContext;
6
7
8
9
10
11
12
13
14 public class LeftPad extends CellProcessorAdaptor implements StringCellProcessor {
15
16 private final int padSize;
17
18 private final char padChar;
19
20 public LeftPad(final int padSize, final char padChar) {
21 super();
22
23 checkPreconditions(padSize);
24 this.padSize = padSize;
25 this.padChar = padChar;
26 }
27
28 public LeftPad(final int padSize, final char padChar, final StringCellProcessor next) {
29 super(next);
30
31 checkPreconditions(padSize);
32 this.padSize = padSize;
33 this.padChar = padChar;
34 }
35
36 private static void checkPreconditions(final int padSize) {
37 if(padSize <= 0) {
38 throw new IllegalArgumentException(String.format("padSize should be > 0 but was %d", padSize));
39 }
40 }
41
42 @Override
43 public <T> T execute(final Object value, final CsvContext context) {
44
45 if(value == null) {
46 return next.execute(value, context);
47 }
48
49 final String result = padding((String)value);
50
51 return next.execute(result, context);
52 }
53
54 private String padding(final String str) {
55
56 final int pads = padSize - str.length();
57 if(pads <= 0) {
58 return str;
59 }
60
61 final StringBuilder sb = new StringBuilder(str.length() + pads);
62
63 for(int i=0; i < pads; i++) {
64 sb.append(padChar);
65 }
66
67 sb.append(str);
68
69 return sb.toString();
70
71 }
72
73
74
75
76
77 public int getPadSize() {
78 return padSize;
79 }
80
81
82
83
84
85 public char getPadChar() {
86 return padChar;
87 }
88 }