package com.quant.comm;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.quant.interceptor.LogInterceptor;

public class CommTool {
	private static Map<String,String> tableField;
	
	// 获取IP
	public static String getIP(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;
	}
	
	public static String getTableField(String str){
		if(tableField== null){
			tableField=new HashMap<String, String>();
			InputStream is = LogInterceptor.class.getClassLoader().getResourceAsStream("logConfig.xml"); 
			DocumentBuilderFactory dom=DocumentBuilderFactory.newInstance();
            DocumentBuilder dombuilder;
			try {
				dombuilder = dom.newDocumentBuilder();
				Document doc = dombuilder.parse(is);
				Element root = doc.getDocumentElement();
				NodeList config = root.getChildNodes();
                if(config!=null){
                	for(int i=0;i<config.getLength();i++){
                		Node node=config.item(i);
                		if (node.getNodeType()==Node.ELEMENT_NODE) {
							tableField.put(node.getNodeName(), node.getTextContent());
						}
                	}
                }
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return tableField.get(str);
		}else{
			return tableField.get(str);
		}		
	}
}
