class NormalizeUtils {

  public static String replaceUnicodeEntities(String x) {
    if (x == null) {
      return x;
    }
    // decimal entities
    Matcher m = XML_ENTITIES_DEC.matcher(x);
    if (m.find()) {
      m.reset();
      StringBuffer sb = new StringBuffer();
      while (m.find()) {
        try {
          Character uc = (char) Integer.parseInt(m.group(1));
          m.appendReplacement(sb, uc.toString());
        } catch (NumberFormatException e) {
          // use original string
          m.appendReplacement(sb, m.group());
        }
      }
      m.appendTail(sb);
      x = sb.toString();
    }
    // hexadecimal entities
    m = XML_ENTITIES_HEX.matcher(x);
    if (m.find()) {
      m.reset();
      StringBuffer sb = new StringBuffer();
      while (m.find()) {
        try {
          Character uc = (char) Integer.parseInt(m.group(1), 16);
          m.appendReplacement(sb, uc.toString());
        } catch (NumberFormatException e) {
          // use original string
          m.appendReplacement(sb, m.group());
        }
      }
      m.appendTail(sb);
      x = sb.toString();
    }
    // java unicode
    m = UNICODE_HEX.matcher(x);
    if (m.find()) {
      m.reset();
      StringBuffer sb = new StringBuffer();
      while (m.find()) {
        try {
          Character uc = (char) Integer.parseInt(m.group(1), 16);
          m.appendReplacement(sb, uc.toString());
        } catch (NumberFormatException e) {
          // use original string
          m.appendReplacement(sb, m.group());
        }
      }
      m.appendTail(sb);
      x = sb.toString();
    }

    return x;
  }

}