com.cn.util.Units.java Source code

Java tutorial

Introduction

Here is the source code for com.cn.util.Units.java

Source

/*
 * 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.cn.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;

/**
 *
 * @author LFeng
 */
public class Units {

    private static SerializeConfig mapping = new SerializeConfig();
    private static String dateFormat;

    static {
        dateFormat = "yyyy-MM-dd HH:mm:ss";
        mapping.put(Date.class, new SimpleDateFormatSerializer(dateFormat));
    }

    /**
     * ???
     */
    public static final char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
            'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8',
            '9' };

    public static final double EARTH_RADIUS = 6378137;//??(??m)
    public static final String BAIDU_CONVERT_KEY = "UGTSrlHZTd3O95SiMiQkhLO2";
    public static final SerializerFeature[] features = { SerializerFeature.WriteMapNullValue,
            SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteNullBooleanAsFalse,
            SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullListAsEmpty,
            SerializerFeature.WriteDateUseDateFormat };

    /**
     * ??????
     *
     * @param lnglat ??, ?: longitude,latitude
     * @param type ???, ?: 1GPS???wgs84??;
     * 2GPS????sogou??;
     * 3google?soso?aliyun?mapabcamap????; 43????;
     * 5???; 6??; 7mapbar??; 851??
     * @return ??: bd09ll(???)
     */
    public static String getBaiduLnglatConvert(String[] lnglat, int type) {
        String httpUrl = "http://api.map.baidu.com/geoconv/v1/";
        String httpArg = "";
        String coords = "coords=";
        if (lnglat.length < 100) {
            for (String lnglat1 : lnglat) {
                coords += (lnglat1 + ";");
            }
            coords = coords.substring(0, coords.length() - 1);
            httpArg += coords;
            httpArg += "&form=" + type + "&to=5&ak=" + BAIDU_CONVERT_KEY + "&output=json";
            return requestWithNoHeaderKey(httpUrl, httpArg);
        } else {
            return "?1000";
        }
    }

    /**
     * ?????
     *
     * @param idCardNO
     * @return JSON : { "errNum": 0, "retMsg": "success", "retData": {
     * "sex": "M", //M-F-N- "birthday": "1987-04-20", "address":
     * "???" } }
     */
    public static String getIDCardInfo(String idCardNO) {
        /*???URL*/
        String httpUrl = "http://apis.baidu.com/apistore/idservice/id";
        String httpArg = "id=" + idCardNO;
        String jsonResult = request(httpUrl, httpArg);
        return jsonResult;
    }

    /**
     * ?????
     *
     * @param cityName
     * @return * JSON :{ errNum: 0, errMsg: "success", retData: { city:
     * "", // pinyin: "beijing", // citycode: "101010100", //? date:
     * "15-02-11", // time: "11:00", //? postCode: "100000", //
     * longitude: 116.391, //? latitude: 39.904, // altitude: "33", //
     * weather: "", // temp: "10", // l_tmp: "-4", // h_tmp: "10",
     * // WD: "??",   //? WS: "(<10m/h)", // sunrise: "07:12", //
     * sunset: "17:44" //? } }
     */
    public static String getWeatherInfo(String cityName) {

        /*??*/
        String httpUrl = "http://apis.baidu.com/apistore/weatherservice/cityname";
        String httpArg = "cityname=" + cityName;
        String jsonResult = request(httpUrl, httpArg);
        return jsonResult;
    }

    /**
     * ???
     *
     * @param cityPinyin
     * @return JSON :{ errNum: 0, errMsg: "success", retData: { city: "",
     * // pinyin: "beijing", // citycode: "101010100", //? date:
     * "15-02-11", // time: "11:00", //? postCode: "100000", //
     * longitude: 116.391, //? latitude: 39.904, // altitude: "33", //
     * weather: "", // temp: "10", // l_tmp: "-4", // h_tmp: "10",
     * // WD: "??",   //? WS: "(<10m/h)", // sunrise: "07:12", //
     * sunset: "17:44" //? } }
     */
    public static String getWeacherInfoWithPinyin(String cityPinyin) {
        /*??*/
        String httpUrl = "http://apis.baidu.com/apistore/weatherservice/weather";
        String httpArg = "cityname=" + cityPinyin;
        String jsonResult = request(httpUrl, httpArg);
        return jsonResult;
    }

    /**
     * ?
     *
     * @param cityName
     * @return JSON : { errNum: 0, retMsg: "success", retData: { cityName:
     * "", provinceName: "", cityCode: "101010100", //? zipCode:
     * "100000", // telAreaCode: "010" //?? } }
     */
    public static String getCityInfo(String cityName) {
        /*??URL*/
        String httpUrl = "http://apis.baidu.com/apistore/weatherservice/cityinfo";
        String httpArg = "cityname=" + cityName;
        String jsonResult = request(httpUrl, httpArg);
        return jsonResult;
    }

    /**
     * @param httpUrl :?
     * @param httpArg :?
     * @return 
     */
    public static String request(String httpUrl, String httpArg) {
        BufferedReader reader;
        String result = null;
        StringBuilder sbf = new StringBuilder();
        httpUrl = httpUrl + "?" + httpArg;

        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            // apikeyHTTP header
            connection.setRequestProperty("apikey", "d39fd8a034a21aa3b7d45ebf97c8ffd9");
            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            result = sbf.toString();
        } catch (Exception e) {
        }
        return result;
    }

    /**
     * ????apikeyhttp
     *
     * @param httpUrl
     * @param httpArg
     * @return
     */
    public static String requestWithNoHeaderKey(String httpUrl, String httpArg) {
        BufferedReader reader;
        String result = null;
        StringBuilder sbf = new StringBuilder();
        httpUrl = httpUrl + "?" + httpArg;
        //System.out.println("httpUrl:" + httpUrl);
        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            // apikeyHTTP header
            //connection.setRequestProperty("apikey", "d39fd8a034a21aa3b7d45ebf97c8ffd9");
            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            result = sbf.toString();
        } catch (Exception e) {
        }
        return result;
    }

    /**
     * ??post
     *
     * @param httpUrl
     * @param sendBody
     * @return
     */
    public static String requestWithPost(String httpUrl, String sendBody) {
        BufferedReader reader;
        String result;
        StringBuilder sbf = new StringBuilder();
        try {

            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-type", "application/json");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.connect();

            if (null != sendBody) {
                System.out.println(sendBody);
                BufferedWriter out = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
                out.write(sendBody);
                out.flush();
                out.close();
            }

            if (connection.getResponseCode() == 200) {
                InputStream is = connection.getInputStream();
                reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                String strRead;
                while ((strRead = reader.readLine()) != null) {
                    sbf.append(strRead);
                    sbf.append("\r\n");
                }
                reader.close();
                result = sbf.toString();
                return result;
            } else {
                System.out.println(connection.getResponseCode() + ",message:" + connection.getResponseMessage());
            }
        } catch (IOException e) {
            Logger.getLogger(Units.class.getName()).log(Level.SEVERE, null, e);
        }

        return null;
    }

    /**
     * ??json??
     *
     * @param result
     * @param recordCount
     * @return
     */
    public static String listToJson(ArrayList<?> result, int recordCount) {
        StringBuilder json = new StringBuilder();
        json.append("{");
        if (null != result && result.size() > 0) {
            json.append("\"").append("status").append("\"").append(":");
            json.append(0).append(",");
            json.append("\"").append("message").append("\"").append(":");
            json.append("\"").append("\"").append(",");
            json.append("\"").append("count").append("\"").append(":");
            json.append("\"").append(recordCount).append("\"").append(",");
            json.append("\"").append("data").append("\"").append(":");
            json.append(JSONObject.toJSONString(result, features));
        } else {
            json.append("\"").append("status").append("\"").append(":");
            json.append(-1).append(",");
            json.append("\"").append("message").append("\"").append(":");
            json.append("\"").append("the record is null").append("\"").append(",");
            json.append("\"").append("count").append("\"").append(":");
            json.append("\"").append(0).append("\"").append(",");
            json.append("\"").append("data").append("\"").append(":");
            json.append("\"").append("\"");
        }
        json.append("}");
        return json.toString();
    }

    /**
     * ?json??
     *
     * @param status
     * @param message
     * @param object
     * @return
     */
    public static String objectToJson(int status, String message, Object object) {
        StringBuilder json = new StringBuilder();
        json.append("{");
        json.append("\"").append("status").append("\"").append(":");
        json.append(status).append(",");
        json.append("\"").append("message").append("\"").append(":");
        json.append("\"").append(message).append("\"").append(",");
        json.append("\"").append("data").append("\"").append(":");
        //json.append(JSONObject.toJSONString(object, features));
        json.append(JSON.toJSONStringWithDateFormat(object, "YYYY-MM-dd HH:mm:ss", features));
        json.append("}");
        return json.toString();
    }

    /**
     * json??json??
     *
     * @param status
     * @param message
     * @param jsonStr
     * @return
     */
    public static String jsonStrToJson(int status, String message, String jsonStr) {
        StringBuilder json = new StringBuilder();
        json.append("{");
        json.append("\"").append("status").append("\"").append(":");
        json.append(status).append(",");
        json.append("\"").append("message").append("\"").append(":");
        json.append("\"").append(message).append("\"").append(",");
        json.append("\"").append("data").append("\"").append(":");
        json.append(jsonStr);
        json.append("}");
        return json.toString();
    }

    /**
     * googleMap??,??0.2
     *
     * @param lon1 ?
     * @param lat1 
     * @param lon2 ?
     * @param lat2 
     * @return ???m
     */
    public static double GetDistance(double lon1, double lat1, double lon2, double lat2) {
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double a = radLat1 - radLat2;
        double b = rad(lon1) - rad(lon2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        return s;
    }

    /**
     * (rad)
     */
    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    /**
     * ? 00:00:00.000 
     *
     * @param date
     * @return
     */
    public static Date dayBegin(final Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        return c.getTime();
    }

    /**
     * ? 23:59:59.999 
     *
     * @param date
     * @return
     */
    public static Date dayEnd(final Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.set(Calendar.HOUR_OF_DAY, 23);
        c.set(Calendar.MINUTE, 59);
        c.set(Calendar.SECOND, 59);
        c.set(Calendar.MILLISECOND, 999);
        return c.getTime();
    }

    /**
     * ?
     *
     * @param date
     * @return
     */
    public static boolean isToday(Date date) {
        Date nowDate = new Date();
        return (date.getTime() >= dayBegin(nowDate).getTime()) && (date.getTime() <= dayEnd(nowDate).getTime());
    }

    /**
     * ??
     *
     * @return yyyy-MM-dd HH:mm:ss?
     */
    public static String getNowTime() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date nowDate = new Date();
        return format.format(nowDate);
    }

    /**
     * ??
     *
     * @return yyyyMMddHHmmss?
     */
    public static String getNowTimeNoSeparator() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        Date nowDate = new Date();
        return format.format(nowDate);
    }

    /**
     * ??
     *
     * @return
     */
    public static String getNowDate() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date nowDate = new Date();
        return format.format(nowDate);
    }

    /**
     * ?
     *
     * @param date
     * @return ?; ?.
     */
    public static long getIntervalTimeWithNow(Date date) {
        Date nowDate = new Date();
        return nowDate.getTime() - date.getTime();
    }

    /**
     * ?????json?
     *
     * @param statusCode
     * @param message
     * @return json??
     */
    public static String createJsonWithResult(String statusCode, String message) {
        StringBuilder builder = new StringBuilder();
        builder.append("{");
        builder.append("\"").append("status").append("\"").append(":");
        builder.append("\"").append("success").append("\"").append(",");
        builder.append("\"").append("message").append("\"").append(":");
        builder.append("\"").append(message).append("\"").append(",");
        builder.append("\"").append("result").append("\"").append(":");
        builder.append("\"").append(statusCode).append("\"");
        builder.append("}");

        return builder.toString();
    }

    /**
     * ?
     *
     * @param str
     * @param array
     * @return
     */
    public static boolean isStrInArray(String str, String[] array) {
        for (String string : array) {
            if (string.compareTo(str) == 0) {
                return true;
            }
        }
        return false;
    }

    /**
     * ?, 0null
     *
     * @param string
     * @return
     */
    public static boolean strIsEmpty(String string) {
        if (string == null) {
            return true;
        }
        if (string.trim().length() <= 0) {
            return true;
        }
        if (string.compareToIgnoreCase("null") == 0) {
            return true;
        }
        return false;
    }

    public static String getSubJsonStr(String jsonStr, String keyName) {
        JSONObject obj = new JSONObject();
        obj.put(keyName, JSONObject.parseObject(jsonStr).getString(keyName));
        return obj.toJSONString();
    }

    public static String getSubJsonValue(String jsonStr, String keyName) {
        return JSONObject.parseObject(jsonStr).getString(keyName);
    }

    /**
     * 
     *
     * @param path
     * @param fileName
     * @return
     * @throws FileNotFoundException
     */
    public static String returnFileContext(String path, String fileName) throws FileNotFoundException {
        File file = new File(path + fileName);
        StringBuilder builder = new StringBuilder();
        Scanner scanner = new Scanner(file, "utf-8");
        while (scanner.hasNextLine()) {
            builder.append(scanner.nextLine());
        }
        return builder.toString();
    }

    /**
     * ???
     *
     * @param filePath
     * @param fileName
     * @return
     * @throws IOException
     */
    public static File createNewFile(String filePath, String fileName) throws IOException {
        File path = new File(filePath);
        if (!path.exists()) {
            path.mkdir();
        }
        File file = new File(filePath, fileName);
        if (!file.exists()) {
            file.createNewFile();
        }
        return file;
    }

    /**
     * srcStrdesStr, ?desStr???insertStr
     *
     * @param srcStr
     * @param desStr
     * @param insertStr
     * @return
     */
    public static String insertStr(String srcStr, String desStr, String insertStr) {
        StringBuffer buffer = new StringBuffer(srcStr);
        int index = 0;
        while ((index = buffer.indexOf(desStr, index)) != -1) {
            index += desStr.length() - 1;
            buffer.insert(index, insertStr);
        }
        return buffer.toString();
    }

    /**
     * ?Excel?
     *
     * @param cell
     * @return
     */
    public static String getCellValue(Cell cell) {
        String result = null;
        switch (cell.getCellType()) {
        case Cell.CELL_TYPE_BOOLEAN:
            result = String.valueOf(cell.getBooleanCellValue());
            break;
        case Cell.CELL_TYPE_NUMERIC:
            result = String.valueOf(cell.getNumericCellValue());
            break;
        case Cell.CELL_TYPE_STRING:
            result = cell.getStringCellValue();
            break;
        default:
            result = cell.getStringCellValue();
            break;
        }
        return result.trim();
    }

    /**
     * ????
     *
     * @param cell Excel?
     * @return String ??
     */
    public static String getStringCellValue(Cell cell) {
        String strCell = "";
        switch (cell.getCellType()) {
        case Cell.CELL_TYPE_STRING:
            strCell = cell.getStringCellValue();
            break;
        case Cell.CELL_TYPE_NUMERIC:
            cell.setCellType(Cell.CELL_TYPE_STRING);
            strCell = cell.getStringCellValue();
            break;
        case Cell.CELL_TYPE_BOOLEAN:
            strCell = String.valueOf(cell.getBooleanCellValue());
            break;
        case Cell.CELL_TYPE_BLANK:
            strCell = "";
            break;
        default:
            strCell = "";
            break;
        }
        if (strCell.equals("") || strCell == null) {
            return "";
        }
        if (cell == null) {
            return "";
        }
        return strCell.trim();
    }

    /**
     * ????
     *
     * @param cell Excel?
     * @return String ??
     */
    public static String getDateCellValue(Cell cell) {
        String result = "";
        try {
            int cellType = cell.getCellType();
            if (cellType == Cell.CELL_TYPE_NUMERIC) {
                Date date = cell.getDateCellValue();
                result = (date.getYear() + 1900) + "-" + (date.getMonth() + 1) + "-" + date.getDate();
            } else if (cellType == Cell.CELL_TYPE_STRING) {
                String date = getStringCellValue(cell);
                result = date.replaceAll("[]", "-").replace("", "").trim();
            } else if (cellType == Cell.CELL_TYPE_BLANK) {
                result = "";
            }
        } catch (Exception e) {
            System.out.println("??!");
            e.printStackTrace();
        }
        return result.trim();
    }

    /**
     * ?Cell?
     *
     * @param cell
     * @return
     */
    public static String getCellFormatValue(Cell cell) {
        String cellvalue = "";
        if (cell != null) {
            // ?CellType
            switch (cell.getCellType()) {
            // ?CellTypeNUMERIC
            case Cell.CELL_TYPE_NUMERIC:
            case Cell.CELL_TYPE_FORMULA: {
                // ?cell?Date
                if (DateUtil.isCellDateFormatted(cell)) {
                    // DateData?

                    //1?data?2011-10-12 0:00:00
                    //cellvalue = cell.getDateCellValue().toLocaleString();
                    //2?data??2011-10-12
                    Date date = cell.getDateCellValue();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    cellvalue = sdf.format(date);
                } // 
                else {
                    // ??Cell
                    cellvalue = String.valueOf(cell.getNumericCellValue());
                }
                break;
            }
            // ?CellTypeSTRIN
            case Cell.CELL_TYPE_STRING:
                // ??Cell
                cellvalue = cell.getRichStringCellValue().getString();
                break;
            // Cell
            default:
                cellvalue = " ";
            }
        } else {
            cellvalue = "";
        }
        return cellvalue;
    }

    /**
     * java?.0
     *
     * @param s
     * @return
     */
    public static String subZeroAndDot(String s) {
        if (s.indexOf(".") > 0) {
            s = s.replaceAll("0+?$", "");//0  
            s = s.replaceAll("[.]$", "");//??.  
        }
        return s;
    }

    public static boolean isEmptyRowForExcel(Row row) {
        for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) {
            Cell cell = row.getCell(c);
            if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK) {
                return false;
            }
        }
        return true;
    }

    /**
     * ????
     *
     * @param res
     * @param columnName
     * @return
     */
    public static boolean isExistColumn(ResultSet res, String columnName) {
        try {
            if (res.findColumn(columnName) > 0) {
                return true;
            }
        } catch (Exception e) {
            return false;
        }
        return false;
    }

    /**
     * ************************************????*****************************************
     */
    /**
     * ????(??)
     *
     * @param codeCount
     * @return
     */
    /*
     public static String createPhoneValidateCode(int codeCount) {
     // randomCode???
     StringBuilder randomCode = new StringBuilder();
     Random random = new Random();
     // ?codeCount??
     for (int i = 0; i < codeCount; i++) {
        
     String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);
     // codeCount??
     randomCode.append(strRand);
     }
     return randomCode.toString();
     }
     */
    /**
     * ??????
     *
     * @param to ????????100?
     * @param verificationCode ?????
     * @return
     */

    /*
     public static String sendSMSVerificationCode(String to, String verificationCode) {
     //?SDK
     CCPRestSmsSDK restAPI = new CCPRestSmsSDK();
        
     //*????
     restAPI.init(Constants.SMS_PLATFORM_URL_DISTRIBUTION, Constants.SMS_PLATFORM_PORT);
        
     //*?????,??ACCOUNT SIDAUTH TOKEN
     restAPI.setAccount(Constants.SMS_PLATFORM_ACCOUNT_SID, Constants.SMS_PLATFORM_AUTH_TOKEN);
        
     //*?ID
     restAPI.setAppId(Constants.SMS_PLATFORM_APP_ID);
        
     //*??????
     HashMap<String, Object> result = restAPI.sendTemplateSMS(to, Constants.SMS_PLATFORM_TEMPLATE_ID, new String[]{verificationCode, Constants.SMS_EXPIRED_MINUTE});
        
     String json;
     if ("000000".equals(result.get("statusCode"))) {
     json = createJsonWithResult(String.valueOf(result.get("statusCode")), "????5????");
     } else {
     json = createJsonWithResult(String.valueOf(result.get("statusCode")), String.valueOf(result.get("statusMsg")));
     }
     return json;
     }
     */
    /**
     * ?IP??request.getRemoteAddr();?????IP?,
     *
     * ??????X-Forwarded-For?IP?IP
     * ?X-Forwarded-For?unknownIP
     *
     * X-Forwarded-For192.168.1.110, 192.168.1.120, 192.168.1.130,
     * 192.168.1.100
     *
     * IP 192.168.1.110
     *
     * @param request
     * @return
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * ?IP?,?????IP?;
     *
     * @param request
     * @return
     * @throws IOException
     */
    public final static String getRealIpAddress(HttpServletRequest request) throws IOException {
        // ?IP?,?????IP?  

        String ip = request.getHeader("X-Forwarded-For");

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        } else if (ip.length() > 15) {
            String[] ips = ip.split(",");
            for (int index = 0; index < ips.length; index++) {
                String strIp = (String) ips[index];
                if (!("unknown".equalsIgnoreCase(strIp))) {
                    ip = strIp;
                    break;
                }
            }
        }
        return ip;
    }
}