/**
 * Project Name:tuia-advert-manager-common
 * File Name:UrlBase64.java
 * Package Name:cn.com.duiba.tuia.manager.utils
 * Date:2018年3月8日下午5:51:48
 * Copyright (c) 2018, duiba.com.cn All Rights Reserved.
 *
*/

package com.duiba.tuia.youtui.web.tool;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * ClassName:UrlBase64 <br/>
 * Function: url base编码. <br/>
 * Reason:	 base64编码，将特殊字符换成url不会转移的字符. <br/>
 * Date:     2018年3月8日 下午5:51:48 <br/>
 * @author   chencheng
 * @version  
 * @since    JDK 1.8
 * @see 	 
 */
public class UrlBase64 {
    
    /** The logger. */
    private static Logger logger = LoggerFactory.getLogger(UrlBase64.class);
    
    /**
     * 
     * urlBase64Encode:(url base64 加密). <br/>
     *
     * @author chencheng
     * @param data
     * @return
     * @since JDK 1.8
     */
    public static String urlBase64Encode(String data){
        try {
            return safeUrlBase64Encode(data.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            logger.error("url base64 encode error", e);
            return StringUtils.EMPTY;
        }
    }
    
    /**
     * 
     * urlBase64Decode:(url base64 解密). <br/>
     *
     * @author chencheng
     * @param data
     * @return
     * @since JDK 1.8
     */
    public static String urlBase64Decode(String data) {
        try {
            if (StringUtils.isBlank(data)) {
                return StringUtils.EMPTY;
            }
            return new String(safeUrlBase64Decode(data),"UTF-8");
        } catch (IOException e) {
            logger.error("url base64 decode error", e);
            return StringUtils.EMPTY;
        }
    }
    
    /**
     * 
     * safeUrlBase64Encode:(加密). <br/>
     *
     * @author chencheng
     * @param data
     * @return
     * @since JDK 1.8
     */
    public static String safeUrlBase64Encode(byte[] data){
        String encodeBase64 = Base64.encode(data);
        String safeBase64Str = encodeBase64.replace('+', '-');
        safeBase64Str = safeBase64Str.replace('/', '_');
        safeBase64Str = safeBase64Str.replaceAll("=", "");
        return safeBase64Str;
    }
        
    /**
     * 
     * safeUrlBase64Decode:(解密). <br/>
     *
     * @author chencheng
     * @param safeBase64Str
     * @return
     * @throws IOException
     * @since JDK 1.8
     */
    public static byte[] safeUrlBase64Decode(final String safeBase64Str) throws IOException{
            String base64Str = safeBase64Str.replace('-', '+');
            base64Str = base64Str.replace('_', '/');
            int mod4 = base64Str.length()%4;
            if(mod4 > 0){
                base64Str = base64Str + "====".substring(mod4);
            }
            return Base64.decode(base64Str);
    }

}

