View Javadoc
1   /*
2    * CSVeed (https://github.com/42BV/CSVeed)
3    *
4    * Copyright 2013-2023 CSVeed.
5    *
6    * All rights reserved. This program and the accompanying materials
7    * are made available under the terms of The Apache Software License,
8    * Version 2.0 which accompanies this distribution, and is available at
9    * https://www.apache.org/licenses/LICENSE-2.0.txt
10   */
11  package org.csveed.bean.conversion;
12  
13  import static org.csveed.bean.conversion.ConversionUtil.hasLength;
14  
15  /**
16   * The Class CharacterConverter.
17   */
18  public class CharacterConverter extends AbstractConverter<Character> {
19  
20      /** The Constant UNICODE_PREFIX. */
21      private static final String UNICODE_PREFIX = "\\u";
22  
23      /** The Constant UNICODE_LENGTH. */
24      private static final int UNICODE_LENGTH = 6;
25  
26      /** The allow empty. */
27      private final boolean allowEmpty;
28  
29      /**
30       * Instantiates a new character converter.
31       *
32       * @param allowEmpty
33       *            the allow empty
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       * Checks if is unicode character sequence.
66       *
67       * @param sequence
68       *            the sequence
69       *
70       * @return true, if is unicode character sequence
71       */
72      private boolean isUnicodeCharacterSequence(String sequence) {
73          return sequence.startsWith(UNICODE_PREFIX) && sequence.length() == UNICODE_LENGTH;
74      }
75  
76  }