/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @Title: UnicodeUtil
 * @Package cn.freemud.utils
 * @Description:
 * @author: liming.guo
 * @date: 2018/6/21 15:55
 * @version V1.0
 * @Copyright: 2018 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */
package cn.freemud.utils;

import org.apache.commons.lang.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UnicodeUtil {

    private static Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");

    public static String conventString2Unicode(String str) {
        char[] utfBytes = str.toCharArray();
        String unicodeBytes = "";
        for (int byteIndex = 0; byteIndex < utfBytes.length; byteIndex++) {
            String hexB = Integer.toHexString(utfBytes[byteIndex]);
            if (hexB.length() <= 2) {
                hexB = "00" + hexB;
            }
            unicodeBytes = unicodeBytes + "\\u" + hexB;
        }
        return unicodeBytes;
    }


    public static String conventUnicode2String(String str) {
        if (StringUtils.isBlank(str)) {
            return "";
        }
        Matcher matcher = pattern.matcher(str);
        char ch;
        while (matcher.find()) {
            ch = (char) Integer.parseInt(matcher.group(2), 16);
            str = str.replace(matcher.group(1), ch + "");
        }
        return str;
    }

    public static String filterSpecialChars(String txt) {
        if (StringUtils.isBlank(txt)) {
            return txt;
        }
        txt = txt.trim();
        StringBuffer res = new StringBuffer("");
        for (int i = 0; i < txt.length(); ++i) {
            char ch = txt.charAt(i);
            if (Character.isDefined(ch) &&
                    ch != '&' && ch != '<' && ch != '>' &&
                    !Character.isHighSurrogate(ch) &&
                    !Character.isISOControl(ch) &&
                    !Character.isLowSurrogate(ch) && Character.isWhitespace(' ')
                    ) {
                res.append(ch);
            }
        }
        return res.toString();
    }
}
