package nc.vo.ws.esb;

import java.net.HttpURLConnection;
import java.net.URLConnection;

import javax.servlet.http.HttpServletRequest;

import nc.bs.framework.common.NCLocator;
import nc.itf.ws.esb.IEsbDAO;
import sun.misc.BASE64Encoder;	
/**
 * 访问地址前添加 Basic 认证信息
 * @author 廖声豪 20180602
 *
 */
public class BasicTool {
	
	private static IEsbDAO service;
	private static BASE64Encoder base64;
	
	/**
	 * Http添加Basic认证
	 * @param esbcode 接口安全授权 编码
	 * @param urlConn 访问地址对象
	 */
	public static void addHeaderBasic(String esbcode,final HttpURLConnection urlConn){
		EsbinfoVO[] esbinfos=(EsbinfoVO[]) getService().findESB("code='"+esbcode+"'");
		if(esbinfos!=null && esbinfos.length>0){
			CertificateVO typevo=getService().findByPkCode(esbinfos[0].getCertificate());
			if(typevo!=null){
				String basic=typevo.getUsername()+":"+typevo.getPassword();
				urlConn.addRequestProperty("Authorization", "Basic "+getBase64().encode(basic.getBytes()));
			}
		}
	}
	
	/**
	 * Http添加Basic认证
	 * @param esbcode 接口安全授权 编码
	 * @param urlConn 访问地址对象
	 */
	public static void addHeaderBasic(String esbcode,final URLConnection urlConn){
		EsbinfoVO[] esbinfos=(EsbinfoVO[]) getService().findESB("code='"+esbcode+"'");
		if(esbinfos!=null && esbinfos.length>0){
			CertificateVO typevo=getService().findByPkCode(esbinfos[0].getCertificate());
			if(typevo!=null){
				String basic=typevo.getUsername()+":"+typevo.getPassword();
				urlConn.addRequestProperty("Authorization", "Basic "+getBase64().encode(basic.getBytes()));
				urlConn.addRequestProperty("esbkey",typevo.getEsbkey());
			}
		}
	}
	
	/**
	 * 验证esbkey
	 * @param request 
	 * @return true(验证通过)/false(验证失败)
	 */
	public static boolean checkHeaderEsbkey(final HttpServletRequest request){
		boolean isok=true;
    	try{
    		String pathinfo=request.getPathInfo();
    		if(pathinfo!=null){
    			pathinfo=pathinfo.substring(1, pathinfo.length());
    			EsbinfoVO[] esbinfos=(EsbinfoVO[]) getService().findESB("interfacename='"+pathinfo+"'");
    			if(esbinfos!=null && esbinfos.length>0){
    				String esbkey=request.getHeader("esbkey");
    				for(EsbinfoVO esb:esbinfos){
    					if(esb.getIsstart()!=null && "1".equals(esb.getIsstart())){
	    					CertificateVO typevo=getService().findByPkCode(esb.getCertificate());
	    					if(typevo==null||!typevo.getEsbkey().equals(esbkey)){
	    						isok=false;
	    						break;
	    					}
    					}else{
    						isok=false;
    						break;
    					}
    				}
    			}else{
    				isok=false;
    			}
    		}
    	}catch(Exception e){
    		isok=false;
    	}
    	return isok;
	}
	
	 public static IEsbDAO getService(){
    	if(service==null)
    		service=NCLocator.getInstance().lookup(IEsbDAO.class);
    	return service;
	 }
	 public static BASE64Encoder getBase64(){
		 if(base64==null)
			 base64=new BASE64Encoder();
		 return base64;
	 }
}
