cn.bc.web.util.WebUtils.java Source code

Java tutorial

Introduction

Here is the source code for cn.bc.web.util.WebUtils.java

Source

/*
 * Copyright 2010- the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.bc.web.util;

import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.net.UnknownHostException;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import cn.bc.core.exception.CoreException;

/**
 * WebUI
 * 
 * @author dragon
 * @since 1.0.0
 */
public class WebUtils implements ServletContextAware {
    static Log logger = LogFactory.getLog(WebUtils.class);
    private static ServletContext servletContext = null;
    private static WebApplicationContext wac = null;

    private WebUtils() {
    }

    public void setServletContext(ServletContext _servletContext) {
        servletContext = _servletContext;

        // ?web:"",?"/[appName]"
        rootPath = servletContext.getRealPath("/");
        if (null == rootPath)
            throw new CoreException("Error occured when getting context path.");
        logger.fatal("rootPath=" + rootPath);
    }

    public static String rootPath = "";// File.separator

    /**
     * 
     * <p>
     * ??
     * </p>
     * 
     * @param rootPath
     */
    public static void setRootPath(String rootPath) {
        WebUtils.rootPath = rootPath;
    }

    /**
     * ?CSS?
     * 
     * @param cssPath
     *            ?CSS
     * @return CSSHTML?
     */
    public static String printCSS(String cssPath) {
        return "<link rel=\"stylesheet\" type=\"text/css\" href=\"" + cssPath + "\"/>";
    }

    /**
     * ?JS?
     * 
     * @param jsPath
     *            ?CSS
     * @return JSHTML?
     */
    public static String printJS(String jsPath) {
        return "<script type=\"text/javascript\" src=\"" + jsPath + "\"></script>";
    }

    /**
     * ???
     * 
     * <pre>
     * http://www.demo.com/demo/test.htm  -->  /demo/test.htm</span>
     * </pre>
     * 
     * @param request
     * @return ?/demo/test.htm
     */
    public static String getResourcePath(HttpServletRequest request) {
        // Adapted from VelocityViewServlet.handleRequest() method:

        // If we get here from RequestDispatcher.include(), getServletPath()
        // will return the original (wrong) URI requested. The following
        // special attribute holds the correct path. See section 8.3 of the
        // Servlet 2.3 specification.

        String path = (String) request.getAttribute("javax.servlet.include.servlet_path");

        // Also take into account the PathInfo stated on
        // SRV.4.4 Request Path Elements.
        String info = (String) request.getAttribute("javax.servlet.include.path_info");

        if (path == null) {
            path = request.getServletPath();
            info = request.getPathInfo();
        }

        if (info != null) {
            path += info;
        }

        return path;
    }

    /**
     * js?????
     * 
     * @param fnName
     *            ?js??
     * @return 
     */
    public static String wrapJSFunction(String fnName) {
        return "function(){return window['" + fnName + "'].apply(this,arguments);}";
    }

    public static String wrapJSFunctionWithVar(String fnName, String varName) {
        if (!StringUtils.hasLength(varName))
            return "function(){return window['" + fnName + "'].apply(this,arguments);}";
        else
            return "function(){this.pvar='" + varName + "';return window['" + fnName + "'].apply(this,arguments);}";
    }

    public static String encodeFileName(HttpServletRequest request, String srcFileName) {
        boolean isIE = request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") != -1;
        return encodeFileName(isIE, srcFileName);
    }

    /**
     * ????????
     * 
     * @param isIE
     * @param srcFileName
     *            ??
     * @return ????
     */
    public static String encodeFileName(boolean isIE, String srcFileName) {
        String _fileName;
        // ???
        // boolean isIE = request.getHeader("User-Agent").toUpperCase()
        // .indexOf("MSIE") != -1;
        try {
            if (isIE) {// IE?
                _fileName = URLEncoder.encode(srcFileName, "UTF-8");
                if (_fileName.length() > 150) {
                    // URLEncoder?17IE6
                    // IEbug??KB816868
                    // ?????ie6 sp1
                    String guessCharset = "gb2312"; // ?requestlocale???gb2312
                    _fileName = new String(srcFileName.getBytes(guessCharset), "ISO8859-1");
                }
            } else {// ?IE?:?URLEncoder.encode???url?
                _fileName = new String(srcFileName.getBytes("UTF-8"), "ISO8859-1");
            }
        } catch (UnsupportedEncodingException e) {
            logger.warn(e.getMessage());
            _fileName = srcFileName;
        }
        return _fileName;
    }

    /**
     * ?IP??
     * 
     * @param request
     * @return
     */
    public static String getClientIP(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");// apache?
        logger.debug("get clientIP by request.getHeader(\"x-forwarded-for\")");
        if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
            ip = request.getHeader("Proxy-Client-IP");// ?
            logger.debug("get clientIP by request.getHeader(\"Proxy-Client-IP\")");
        }
        if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
            ip = request.getHeader("WL-Proxy-Client-IP");// weblogic
            logger.debug("get clientIP by request.getHeader(\"WL-Proxy-Client-IP\")");
        }
        if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
            ip = request.getRemoteAddr();// 
            logger.debug("get clientIP by request.getRemoteAddr()");
        }
        return ip;
    }

    public static boolean trace = false;

    public static void setTrace(boolean trace) {
        WebUtils.trace = trace;
    }

    /**
     * ??:[0]-IP?,[1]-??,[2]-User Agent,[3]-mac
     * 
     * @param request
     * @return
     */
    public static String[] getClient(HttpServletRequest request) {
        String[] client = new String[] { null, null, null, null };

        // User Agent?
        client[2] = request.getHeader("User-Agent");

        // ?????X-Forwarded-For?Ip,?unknownIPIP
        String key = "X-Forwarded-For";

        String clientIp = request.getHeader(key);
        if (clientIp == null || clientIp.length() == 0 || "unknown".equalsIgnoreCase(clientIp)) {
            key = "Proxy-Client-IP";
            clientIp = request.getHeader(key);
        }
        if (clientIp == null || clientIp.length() == 0 || "unknown".equalsIgnoreCase(clientIp)) {
            key = "WL-Proxy-Client-IP"; // Weblogic?IP
            clientIp = request.getHeader(key);
        }
        if (clientIp == null || clientIp.length() == 0 || "unknown".equalsIgnoreCase(clientIp)) {
            key = "RemoteAddr";
            clientIp = request.getRemoteAddr();// ??ip?
        }
        client[0] = clientIp;
        if (trace) {// name+ip??+mac
            logger.info("start traceClientMachine...:clientIp=" + clientIp);
            if ("127.0.0.1".equals(clientIp) || "localhost".equals(clientIp)) {
                // ?()
                client[1] = clientIp + "|" + key;
                logger.info("skip traceClientMachine because local machine");
            } else {
                client[1] = request.getRemoteHost();// ???ip????(?)
                try {
                    // ?mac?
                    client[3] = WebUtils.getMac(clientIp);
                    client[1] = key + "|" + client[3];
                } catch (Exception e) {
                    logger.info(e.getMessage(), e);
                    client[1] = "notrace:" + key;
                    client[3] = "notrace:";
                }
            }
            logger.info("finished traceClientMachine");
        } else {
            client[1] = clientIp + "|" + key;
            client[3] = "notrace:";
        }
        return client;
    }

    // ip?IP
    public static boolean isOuterNet(String ip) {
        return !(ip.startsWith("192.168.") || ip.startsWith("10.0.") || ip.startsWith("127.0.")
                || ip.startsWith("localhost"));
    }

    /**
     * ???
     * 
     * @param userAgent
     * @return
     */
    public static boolean isMobile(String userAgent) {
        if (userAgent == null || userAgent.isEmpty())
            return false;

        String ua = userAgent.toLowerCase();
        for (String m : mobiles) {
            if (ua.indexOf(m) != -1)
                return true;
        }

        return false;
    }

    /**
     * 
     */
    private static String[] mobiles = new String[] { "android", "x11", "iphone", "iPod", "webos", "midp", "j2me",
            "avant", "docomo", "novarra", "palmos", "palmsource", "240x320", "opwv", "chtml", "pda", "windows ce",
            "mmp/", "blackberry", "mib/", "symbian", "wireless", "nokia", "hand", "mobi", "phone", "cdm", "up.b",
            "audio", "sie-", "sec-", "samsung", "htc", "mot-", "mitsu", "sagem", "sony", "alcatel", "lg", "eric",
            "vx", "NEC", "philips", "mmm", "xx", "panasonic", "sharp", "wap", "sch", "rover", "pocket", "benq",
            "java", "pt", "pg", "vox", "amoi", "bird", "compal", "kg", "voda", "sany", "kdd", "dbt", "sendo", "sgh",
            "gradi", "jb", "dddi", "moto", "incognito", "webmate", "dream", "cupcake", "s8000", "bada",
            "googlebot-mobile" };

    /**
     * ?Server IP??
     * 
     * @return
     */
    public static String getServerIP() {
        String ip;
        try {
            InetAddress localhost = InetAddress.getLocalHost();
            ip = localhost.getHostAddress();
        } catch (UnknownHostException e) {
            ip = "UnknownHost";
        }
        return ip;
    }

    /**
     * ?Server?:[0]-IP?,[1]-??,[2]-url
     * 
     * @return
     */
    public static String[] getServer(HttpServletRequest request) {
        String[] server = new String[] { null, null, null };
        try {
            InetAddress localhost = InetAddress.getLocalHost();
            server[0] = localhost.getHostAddress();
            server[1] = localhost.getHostName();
        } catch (UnknownHostException e) {
            server[0] = "unknown";
            server[1] = "unknown";
        }
        server[2] = request != null ? request.getRequestURL().toString() : "unknown";
        return server;
    }

    /**
     * ?ipmac?
     * 
     * @param ip
     * @return
     * @throws Exception
     */
    public static String getMac(String ip) throws Exception {
        if ("127.0.0.1".equals(ip) || "localhost".equals(ip))
            return "untrace because localhost";
        return new UdpGetClientMacAddr(ip).GetRemoteMacAddr();
    }

    /**
     * ? WebApplicationContext 
     * 
     * @return
     */
    public static synchronized WebApplicationContext getWac() {
        if (null == wac)
            wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
        return wac;
    }

    /**
     * ?Spring
     * 
     * @param name
     *            bean???
     * @return bean
     */
    public static <T> T getBean(String name, Class<T> requiredType) {
        return getWac().getBean(name, requiredType);
    }

    public static <T> T getBean(Class<T> requiredType) {
        return getWac().getBean(requiredType);
    }

    /**
     * ???
     * 
     * @param request
     * @return
     */
    public static String getBrowser(HttpServletRequest request) {
        return request.getHeader("User-Agent");
    }
}