View Javadoc
1   package org.csveed.bean.conversion;
2   
3   import static org.csveed.bean.conversion.ConversionUtil.hasLength;
4   
5   public class CharacterConverter extends AbstractConverter<Character> {
6   
7       private static final String UNICODE_PREFIX = "\\u";
8   
9       private static final int UNICODE_LENGTH = 6;
10  
11      private final boolean allowEmpty;
12  
13      public CharacterConverter(boolean allowEmpty) {
14          super(Character.class);
15          this.allowEmpty = allowEmpty;
16      }
17  
18      @Override
19      public Character fromString(String text) throws Exception {
20          if (this.allowEmpty && !hasLength(text)) {
21              return null;
22          } else if (text == null) {
23              throw new IllegalArgumentException("null String cannot be converted to char type");
24          } else if (isUnicodeCharacterSequence(text)) {
25              int code = Integer.parseInt(text.substring(UNICODE_PREFIX.length()), 16);
26              return (char) code;
27          } else if (text.length() != 1) {
28              throw new IllegalArgumentException("String [" + text + "] with length " +
29                      text.length() + " cannot be converted to char type");
30          } else {
31              return text.charAt(0);
32          }
33      }
34  
35      @Override
36      public String toString(Character value) throws Exception {
37          return value != null ? value.toString() : "";
38      }
39  
40      private boolean isUnicodeCharacterSequence(String sequence) {
41          return sequence.startsWith(UNICODE_PREFIX) && sequence.length() == UNICODE_LENGTH;
42      }
43  
44  }