package com.yxcheng.token.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.cxf.binding.soap.saaj.SAAJOutInterceptor;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.transport.common.gzip.GZIPInInterceptor;
import org.apache.cxf.transport.common.gzip.GZIPOutInterceptor;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;


@Slf4j
public class WebserviceClientUtils {
	
	public static final int CXF_CLIENT_CONNECT_TIMEOUT = 30000;
	public static final int CXF_CLIENT_RECEIVE_TIMEOUT = 30000;
	/**
	 * 创建Webservice远程服务对象
	 * @param <T> 要返回的Service类型（接口）
	 * @param clazz 要返回的Service类
	 * @param url Webservice接口地址
	 * @return Service，可直接调用其中的方法
	 */
	public static <T> T createService(Class<T> clazz, String url){
		log.debug("createService(), URL: " +url);
		JaxWsProxyFactoryBean bean = new JaxWsProxyFactoryBean();
        bean.getOutInterceptors().add(new SAAJOutInterceptor()); 
        bean.setServiceClass(clazz);
        bean.setAddress(url);
        return (T) bean.create();
	}
	
	public static void configTimeout(Object service) {  
        Client proxy = ClientProxy.getClient(service);  
        HTTPConduit conduit = (HTTPConduit) proxy.getConduit();  
        HTTPClientPolicy policy = new HTTPClientPolicy();  
        policy.setConnectionTimeout(CXF_CLIENT_CONNECT_TIMEOUT);  
        policy.setReceiveTimeout(CXF_CLIENT_RECEIVE_TIMEOUT);
        policy.setAllowChunking(false);
        conduit.setClient(policy);  
    }
	
	public static <T> T createService(Class<T> clazz, String url, String userName, String password){
		log.debug("createService(), URL: " +url);
		JaxWsProxyFactoryBean bean = new JaxWsProxyFactoryBean();
        bean.getOutInterceptors().add(new SAAJOutInterceptor()); 
        bean.setServiceClass(clazz);
        bean.setUsername(userName);
        bean.setPassword(password);
        bean.setAddress(url);
        return (T) bean.create();
	}
	
	public static <T> T createGzipService(Class<T> clazz, String url){
		log.debug("createService(), URL: " +url);
		JaxWsProxyFactoryBean bean = new JaxWsProxyFactoryBean();
        bean.getOutInterceptors().add(new SAAJOutInterceptor()); 
        bean.getInInterceptors().add(new LoggingInInterceptor());
	    bean.getOutInterceptors().add(new LoggingOutInterceptor());
	    bean.getInInterceptors().add(new GZIPInInterceptor());
	    GZIPOutInterceptor oin = new GZIPOutInterceptor();
	    oin.setForce(true);
	    oin.setThreshold(0);
	    bean.getOutInterceptors().add(oin);
        bean.setServiceClass(clazz);
        bean.setAddress(url);
        return (T) bean.create();
	}
}
