package ${basePackage}.frame.utils;

import javax.servlet.http.HttpServletRequest;

/**
 * RequestUtil
 *
 * @author wangbing
 * @version 0.0.1
 * @since 2017-01-01
 */
public class RequestUtil {

    /**
     * 获取请求放IP
     *
     * @param request
     * @return
     */
    public static String getIp(HttpServletRequest request) {
        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;
    }

    /**
     * 获取情况方客户端信息
     *
     * @param request 请求
     * @return 客户端信息
     */
    public static String getUserAgent(HttpServletRequest request) {
        return request.getHeader("User-Agent");
    }

    /**
     * 获取转发至错误页之前的请求URL
     *
     * @param request 请求
     * @return 请求URL
     */
    public static String getErrorUrl(HttpServletRequest request) {
        if (request.getAttribute("javax.servlet.error.request_uri") != null) {
            return (String) request.getAttribute("javax.servlet.error.request_uri");
        } else {
            return "";
        }
    }
}
