/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ifish.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.JavaType;

public class StringUtil {
    

    /**
     * Object转Json
     */
    public static String ObjectToJson(Object value) {
        try {
            if(value==null)
                return null;
            ObjectMapper mapper = new ObjectMapper();
            String js = mapper.writeValueAsString(value);
            return js;
        } catch (Exception ex) {
            System.out.println("【异常信息】 >>> " + ex.toString());
            return "Error";
        }
    }

    /**
     * Json转Object（List）
     *
     * @param json 需要转换的JSON字符串
     * @param bean JavaBean,
     * @return 拿到结果需要强转一次，因为你拿到的是Object, 例如这样调用和强转： List&lt;School&gt; lst
     * =(List&lt;School&gt;)StringUtil.JsonToObjectList(value, School.class);
     */
    public static Object JsonToList(String json, Class<?> bean) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, bean);
        return mapper.readValue(json, javaType);
    }

    /**
     * Json转Object（JavaBean）
     *
     * @param json 需要转换的JSON字符串
     * @param bean JavaBean,
     * @return 拿到结果需要强转一次，因为你拿到的是Object, 例如这样调用和强转： School lst
     * =(School)StringUtil.JsonToObjectList(value, School.class);
     */
    public static Object JsonToBean(String json, Class<?> bean) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        JavaType javaType = mapper.getTypeFactory().uncheckedSimpleType(bean);
        return mapper.readValue(json, javaType);
    }

    /**
     * 将json格式的字符串解析成Map对象
     */
    public static Map<String, Map<String, String>> JsonToMap(String json) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Map<String, String>> maps = mapper.readValue(json, Map.class);
            return maps;
        } catch (Exception e) {
            System.out.println("【异常信息】 >>> " + e.toString());
            return null;
        }
    }

    public static Map<String, Map> JsonToMapContainMap(String json) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Map> maps = mapper.readValue(json, Map.class);
            return maps;
        } catch (Exception e) {
            System.out.println("【异常信息】 >>> " + e.toString());
            return null;
        }
    }

    public static Map JsonToRealMap(String json) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            Map maps = mapper.readValue(json, Map.class);
            return maps;
        } catch (Exception e) {
            System.out.println("【异常信息】 >>> " + e.toString());
            return null;
        }
    }

    /**
     * 正则表达式验证
     *
     * @param value 需要验证的值
     * @param regexp 进行验证的正则表达式
     */
    public static boolean regExpTest(String value, String regexp) {
        //验证标识符必须由字母、数字、下划线组成 
        Pattern p = Pattern.compile(regexp);
        Matcher m = p.matcher(value);
        boolean flg = m.matches();
        return flg;
    }

    /**
     * ISO-8859-1转UTF-8 主要用于POST数据处理
     *
     * @param str 需要转码的值
     */
    public static String encodeStr(String str) {
        try {
            return new String(str.getBytes("ISO-8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }

    /**
     * 利用MD5进行加密
     *
     * @param str 待加密的字符串
     * @return 加密后的字符串
     * @throws NoSuchAlgorithmException 没有这种产生消息摘要的算法
     * @throws UnsupportedEncodingException
     */
    public static String EncoderByMd5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        
        byte[] bs = MessageDigest.getInstance("MD5").digest(str.getBytes());
        StringBuilder sb = new StringBuilder(40);
        for (byte x : bs) {
            if ((x & 0xff) >> 4 == 0) {
                sb.append("0").append(Integer.toHexString(x & 0xff));
            } else {
                sb.append(Integer.toHexString(x & 0xff));
            }
        }
        return sb.toString();
    }

    /**
     * 对文字进行编码处理
     *
     * @param str
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     */
    public static String encoderUrl(String str) {
        try {
            String urlStr = URLEncoder.encode(str, "utf-8");
            return urlStr.replace("%", "$");
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(StringUtil.class.getName()).log(Level.SEVERE, null, ex);
        }

        return null;
    }

    /**
     * 对编码后的文字进行解码
     *
     * @param str
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     */
    public static String decoderUrl(String str) {
        try {
            str = str.replace("$", "%");
            String urlStr = URLDecoder.decode(str, "utf-8");
            return urlStr;

        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(StringUtil.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    /**
     * byte数组转hex字符串<br/>
     * 一个byte转为2个hex字符
     *
     * @param src
     * @return
     */
    public static String bytes2Hex(byte[] src) {
        char[] res = new char[src.length * 2];
        final char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        for (int i = 0, j = 0; i < src.length; i++) {
            res[j++] = hexDigits[src[i] >>> 4 & 0x0f];
            res[j++] = hexDigits[src[i] & 0x0f];
        }

        return new String(res);
    }

    /**
     * hex字符串转byte数组<br/>
     * 2个hex转为一个byte
     *
     * @param src
     * @return
     */
    public static byte[] hex2Bytes(String src) {
        byte[] res = new byte[src.length() / 2];
        char[] chs = src.toCharArray();
        for (int i = 0, c = 0; i < chs.length; i += 2, c++) {
            res[c] = (byte) (Integer.parseInt(new String(chs, i, 2), 16));
        }

        return res;
    }
    
   
}
