1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.kuali.common.util.spring.format;
17
18 import java.util.Locale;
19
20 import org.kuali.common.util.base.string.Replacer;
21 import org.springframework.format.Formatter;
22
23 public final class CsvStringFormatter implements Formatter<String> {
24
25 private final String nullToken;
26 private final String emptyToken;
27 private final Replacer replacer;
28
29 @Override
30 public String print(String string, Locale locale) {
31 if (string == null) {
32 return nullToken;
33 } else if (string.equals("")) {
34 return emptyToken;
35 } else {
36 return replacer.replace(string);
37 }
38
39 }
40
41 @Override
42 public String parse(String string, Locale locale) {
43 if (nullToken.equals(string)) {
44 return null;
45 } else if (emptyToken.equals(string)) {
46 return "";
47 } else {
48 return replacer.restore(string);
49 }
50 }
51
52 private CsvStringFormatter(Builder builder) {
53 this.nullToken = builder.nullToken;
54 this.emptyToken = builder.emptyToken;
55 this.replacer = builder.replacer;
56 }
57
58 public static CsvStringFormatter create() {
59 return builder().build();
60 }
61
62 public static Builder builder() {
63 return new Builder();
64 }
65
66 public static class Builder implements org.apache.commons.lang3.builder.Builder<CsvStringFormatter> {
67
68 private String nullToken = "${csv.null}";
69 private String emptyToken = "${csv.empty}";
70 private Replacer replacer = Replacer.builder().add("\r", "${csv.cr}").add("\n", "${csv.lf}").add(",", "${csv.comma}").build();
71
72 public Builder nullToken(String nullToken) {
73 this.nullToken = nullToken;
74 return this;
75 }
76
77 public Builder emptyToken(String emptyToken) {
78 this.emptyToken = emptyToken;
79 return this;
80 }
81
82 public Builder replacer(Replacer replacer) {
83 this.replacer = replacer;
84 return this;
85 }
86
87 @Override
88 public CsvStringFormatter build() {
89 return new CsvStringFormatter(this);
90 }
91
92 public String getNullToken() {
93 return nullToken;
94 }
95
96 public void setNullToken(String nullToken) {
97 this.nullToken = nullToken;
98 }
99
100 public String getEmptyToken() {
101 return emptyToken;
102 }
103
104 public void setEmptyToken(String emptyToken) {
105 this.emptyToken = emptyToken;
106 }
107
108 public Replacer getReplacer() {
109 return replacer;
110 }
111
112 public void setReplacer(Replacer replacer) {
113 this.replacer = replacer;
114 }
115 }
116
117 public String getNullToken() {
118 return nullToken;
119 }
120
121 public String getEmptyToken() {
122 return emptyToken;
123 }
124
125 public Replacer getReplacer() {
126 return replacer;
127 }
128
129 }