java webservice 简单发布、动态创建webservice 客户端 、wsdl4j解析 wsdl 文档获得接口名列表

wsdl文档阅读参考https://www.cnblogs.com/yzw23333/p/7245104.html

1.java自带jdk发布一个简单的webservice,仅供测试使用,非常简单

import javax.jws.WebParam;
import javax.jws.WebService;
import javax.xml.ws.Endpoint;

@WebService
public class HelloWebService {

    public String getMessage(@WebParam(name="name")String name,@WebParam(name="pass") String pass) {
        return "0";
    }


    public static void main(String[] args) {
        Endpoint.publish("http://localhost:8081/MyService/ServiceTest1", new HelloWebService());//发布服务
        System.out.println("ServiceTest已启动");
    }
}

 2.动态创建webserver客户端

客户端需要的jar

		
	
	org.apache.cxf
	cxf-rt-transports-http
	${cxf.version}
	

	
	
	org.apache.cxf
	cxf-rt-frontend-jaxws
	${cxf.version}
	

 


import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.wsdl.Definition;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.cxf.bus.CXFBusFactory;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.endpoint.dynamic.DynamicClientFactory;
import org.apache.cxf.wsdl.WSDLManager;



/**
 * webservice 调用器
 */
public class WebServiceInvoker {
    /**
     * 动态客户端工厂
     */
    private static DynamicClientFactory DYNAMIC_CLIENT_FACTORY;

    /**
     * WebService 客户端缓存
     */
    private static final Map CLIENT_MAP = new ConcurrentHashMap();

    /**
     * Webservice wsdl标识缓存
     */
    private static final Map URL_CODE_MAP = new ConcurrentHashMap();

    private static final Log logger = LogFactory.getLog(WebServiceInvoker.class);
    /**
     * Constant INVOKE_TIMEOUT_KEY.
     */
    private static final String INVOKE_TIMEOUT_KEY = "smp.webservice.invoke.timeout";

    /**
     * 初始化Webservice客户端
     * @param url webservice调用地址
     * @return 返回Webservice客户端
     */
    private static Client getWebServiceClient(String url) {
        Client client = null;
        if (DYNAMIC_CLIENT_FACTORY == null) {
            synchronized (WebServiceInvoker.class) {
                if (DYNAMIC_CLIENT_FACTORY == null) {
                    DYNAMIC_CLIENT_FACTORY = DynamicClientFactory.newInstance();
                }
            }
        }

        client = CLIENT_MAP.get(url);
        if (client == null) {
            client = DYNAMIC_CLIENT_FACTORY.createClient(url);
            CLIENT_MAP.put(url, client);
            URL_CODE_MAP.put(url, getWsdlHashCode(url));
        }
        return client;
    }

    /**
     * 获取Wsdl唯一标识
     * @param url 地址
     * @return 返回指定Url的Webservice接口内容的唯一标识
     */
    private static int getWsdlHashCode(String url) {
        try {
            InputStream inputStream = com.ibm.wsdl.util.StringUtils.getContentAsInputStream(new URL(url));
            if (inputStream != null) {
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);

                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String line = "";
                StringBuffer buffer = new StringBuffer();
                for (; line != null;) {
                    line = bufferedReader.readLine();
                    buffer.append(line);
                }
                String wsdlContent = buffer.toString();
                if (StringUtils.isBlank(wsdlContent) == false) {
                    return wsdlContent.hashCode();
                }
            }
        } catch (Exception ex) {
            logger.error("get wsdl hash coed fail!(" + url + ")", ex);
        }
        // 无法取得WSDL,直接返回URL的hashcode
        return url.hashCode();
    }

    /**
     * 校验Webservice是否改变
     * @param url 需要检查的Webservice接口
     */
    public static boolean checkWebserviceIsChanged(String url) {
        boolean ischanged = false;
        if (url != null) {
            if (!url.endsWith("?wsdl")) {
                url = url + "?wsdl";
            }
        }
        Integer hashCode = URL_CODE_MAP.get(url);
        if (hashCode == null || (hashCode.intValue() != getWsdlHashCode(url))) {
            try {
                ischanged = true;
                // CXF有对url的客户端缓存,必须清除原有实例
                WSDLManager manager = CXFBusFactory.getThreadDefaultBus().getExtension(WSDLManager.class);
                if (manager != null) {
                    Map definitionMap = manager.getDefinitions();
                    Set removeDefinitionSet = new HashSet();
                    for (Definition definition : definitionMap.values()) {
                        if (url.equals(definition.getDocumentBaseURI())) {
                            removeDefinitionSet.add(definition);
                        }
                    }
                    for (Definition removeDefinition : removeDefinitionSet) {
                        manager.removeDefinition(removeDefinition);
                    }

                }
                CLIENT_MAP.remove(url);
            } catch (Exception ex) {
                logger.error("checkWebserviceIsChanged fail:", ex);
            } 
        }
        return ischanged;
    }

    /**
     * 调用Webservice 接口.
     *
     * @param url webservice的Wsdl接口
     * @param invokeMethod 调用方法
     * @param params 调用参数
     * @return 返回调用结果
     * @throws Exception 抛出调用时异常
     */
    public static Object[] invoke(String url, String invokeMethod, Object... params) throws Exception {
        if (url != null) {
            if (!url.endsWith("?wsdl")) {
                url = url + "?wsdl";
            }
        }

        logger.debug("Web Service Url:" + url);

        if (url == null) {
            throw new NullPointerException("url can't be null when webservice invoke");
        }
        if (invokeMethod == null) {
            throw new NullPointerException("invokeMethod can't be null when webservice invoke");
        }

        return invokeWithTimeoutControl(url, invokeMethod, params);
    }

    /**
     * 调用Webservice,超过10秒则当作超时而返回。
     * @param url 连接的URL
     * @param method 方法名
     * @param params 参数
     * @return 返回调用结果
     * @throws TimeoutException 连接超时抛出此异常
     * @throws ExecutionException 执行失败异常
     * @throws InterruptedException 线程调用错误异常
     */
    private static Object[] invokeWithTimeoutControl(final String url, final String method, final Object... params)
            throws InterruptedException, ExecutionException, TimeoutException {

        int timeout = Integer.parseInt("10");

        FutureTask webserviceInvokeTask = new FutureTask(new Callable() {

            public Object[] call() throws Exception {
                logger.error("invokeWithTimeoutControl url == " +url);
                Client client = getWebServiceClient(url);
                return client.invoke(method, params);

            }
        });
        Thread invokeThread = new Thread(webserviceInvokeTask);
        invokeThread.start();
        return webserviceInvokeTask.get(timeout, TimeUnit.SECONDS);
    }
}

测试客户端

public class TestCXF {

	public static void main(String[] args) throws Exception {
		WebServiceInvoker w = new WebServiceInvoker();
		Object[] params = new Object[2];
		params[0] ="111";
		params[0] ="111";
		Object[] invoke = w.invoke("http://localhost:8081/MyService/ServiceTest1?wsdl", "getMessage", params);
		System.out.println(invoke[0]);
	}
}

 3.获取wsdl中的接口列表

 import javax.wsdl.Binding;
import javax.wsdl.Definition;
import javax.wsdl.Operation;
import javax.wsdl.PortType;
import javax.wsdl.WSDLException;
import javax.wsdl.xml.WSDLReader;

import com.ibm.wsdl.factory.WSDLFactoryImpl;   
@SuppressWarnings("unchecked")
    private List getWebServiceInterfaceList(String url) throws WSDLException {
        if (url != null) {
            if (!url.endsWith("?wsdl")) {
                url = url + "?wsdl";
            }
        }
        List interfaceNames = new ArrayList();
        WSDLReader newWSDLReader = WSDLFactoryImpl.newInstance().newWSDLReader();
        // do not user system.print to output msg
        newWSDLReader.setFeature(com.ibm.wsdl.Constants.FEATURE_VERBOSE, false);

        Definition def = newWSDLReader.readWSDL(url);
        if (def != null) {
            for (Object entity : def.getPortTypes().values()) {
                if (entity instanceof PortType) {
                    PortType portType = (PortType) entity;

                    List operations = (List) portType.getOperations();
                    if (operations != null) {
                        for (Operation operation : operations) {
                            if ((operation.isUndefined() == false)
                                    && (interfaceNames.contains(operation.getName()) == false)) {
                                interfaceNames.add(operation.getName());
                            }
                        }
                    }
                }

            }

        }
        
        // wsdl 没有PortType属性  从bindings属性中获取方法名
        if(interfaceNames.isEmpty()){
            if (def != null) {
                for (Object entity : def.getBindings().values()) {
                    if (entity instanceof Binding) {
                        Binding binding = (Binding) entity;

                        List operations = (List)binding.getPortType().getOperations();
                        if (operations != null) {
                            for (Operation operation : operations) {
                                if ((operation.isUndefined() == false)
                                        && (interfaceNames.contains(operation.getName()) == false)) {
                                    interfaceNames.add(operation.getName());
                                }
                            }
                        }
                    }

                }

            }
        }


        Collections.sort(interfaceNames);
        return interfaceNames;
    }

 

你可能感兴趣的:(webservice,工具类,wsdl阅读,动态webservice客户端,cxf依赖,wsdl4j获取接口列表)