1
2
3
4
5
6
7
8
9
10
11 package org.csveed.bean.conversion;
12
13 import static org.csveed.bean.conversion.ConversionUtil.hasLength;
14
15
16
17
18 public class CharacterConverter extends AbstractConverter<Character> {
19
20
21 private static final String UNICODE_PREFIX = "\\u";
22
23
24 private static final int UNICODE_LENGTH = 6;
25
26
27 private final boolean allowEmpty;
28
29
30
31
32
33
34
35 public CharacterConverter(boolean allowEmpty) {
36 super(Character.class);
37 this.allowEmpty = allowEmpty;
38 }
39
40 @Override
41 public Character fromString(String text) throws Exception {
42 if (this.allowEmpty && !hasLength(text)) {
43 return null;
44 }
45 if (text == null) {
46 throw new IllegalArgumentException("null String cannot be converted to char type");
47 }
48 if (isUnicodeCharacterSequence(text)) {
49 int code = Integer.parseInt(text.substring(UNICODE_PREFIX.length()), 16);
50 return (char) code;
51 }
52 if (text.length() != 1) {
53 throw new IllegalArgumentException(
54 "String [" + text + "] with length " + text.length() + " cannot be converted to char type");
55 }
56 return text.charAt(0);
57 }
58
59 @Override
60 public String toString(Character value) throws Exception {
61 return value != null ? value.toString() : "";
62 }
63
64
65
66
67
68
69
70
71
72 private boolean isUnicodeCharacterSequence(String sequence) {
73 return sequence.startsWith(UNICODE_PREFIX) && sequence.length() == UNICODE_LENGTH;
74 }
75
76 }