webservice服务端和客户端实践

本文展示了如何使用Java实现调用WebService服务端的示例代码,包括加载WSDL文件,设置安全参数,并从服务端获取响应数据。通过对响应数据的处理,将结果转换为List<Map<String, String>>格式。" 121045061,9673637,CentOS8安装docker与docker-compose教程,"['Docker', 'Linux', 'CentOS', '容器技术', '系统管理']
摘要由CSDN通过智能技术生成

客户端:

 public List<Map<String, String>> getWSLogContent(String keyword, String starttime, String endtime)
    {
        // String keyword = " ";
        // String starttime = "20130629000000";
        // String endtime = "20131123000000";
        // String eamID = "HWU2000";
        // String emsEntityID = "G:/mLog/Log";
        String logInfo = "";
        List<Map<String, String>> csvContentList = new ArrayList<Map<String, String>>(CommonFinals.INIT_ARRAYLIST);
       
        try
        {
         String wsdlPath = "/opt/netwatcher/pm4h2/app/module/eamappproxy/conf/hello_world.wsdl";
         logger.info(Constants.LOG_COLLECT_CODE, "1001", "hello_world.wsdl path is :" + wsdlPath);
         String keyFlag = "secure";
//            if (args.length == 0) {
//                System.out.println("please specify wsdl");
//                System.exit(1);
//            }

            URL wsdlURL;
            File wsdlFile = new File(wsdlPath);
            logger.info(Constants.LOG_COLLECT_CODE, "1001", "wsdlFile is :" + wsdlFile.toString());
            if (wsdlFile.exists()) {
                wsdlURL = wsdlFile.toURL();
            } else {
                wsdlURL = new URL(wsdlPath);
            }
            logger.info(Constants.LOG_COLLECT_CODE, "1001", "wsdlURL is :" + wsdlURL.toString());
            System.out.println(wsdlURL);
            SOAPService ss = new SOAPService(wsdlURL, SERVICE_NAME);
            logger.info(Constants.LOG_COLLECT_CODE, "1001", "ss is :" + ss.toString());
            Greeter port = ss.getPort(PORT_NAME, Greeter.class); 
            logger.info(Constants.LOG_COLLECT_CODE, "1001", "port is :" + port.toString());
            if ("secure".equals(keyFlag)) {
                setupTLS(port);
            } else if ("insecure".equals(keyFlag)) {
                //do nothing
            } else {
                System.out.println("arg1 needs to be either secure or insecure");
                System.exit(1);
            }
            logger.info(Constants.LOG_COLLECT_CODE, "1001", "Invoking greetMe...");
            System.out.println("Invoking greetMe...");
         ///netwatcher/spool/HWM2000V2R3V2R11FI/1405652539404/molog_load/
         // objCode, eamID, emsEntityID, keyword, starttime, endtime   传入的6个参数 时间必须格式为20130629000000
//            String str = "NEW_USF8GU1250&&&&&&"+"HWM2000V2R3V2R11FI&&&&&&"+"1405652539404&&&&&&"+" &&&&&&"+"20140825000000&&&&&&"+"20140829000000";
         String str = this.objCode+"&&&&&&"+this.eamID+"&&&&&&"+this.emsEntityID+"&&&&&&"+keyword+"&&&&&&"+starttime+"&&&&&&"+endtime;
         logger.info(Constants.LOG_COLLECT_CODE, "1001", "all param is : " + str);
         
         logInfo = port.greetMe(str);
         
         logger.info(Constants.LOG_COLLECT_CODE, "1001", "responded result is : " + logInfo);
            System.out.println("Server responded with: " + logInfo);
            System.out.println();


//            logInfo = sh.getGreeting(this.objCode, this.eamID, this.emsEntityID, keyword, starttime, endtime);
            logInfo = logInfo.replace("]", ",");
            String[] logC = logInfo.split("},");
            for (int i = 0; i < logC.length; i++)
            {
                String[] logMap = logC[i].split("===");
                if (logMap.length > 5)
                {
                    Map<String, String> csvKeyMap = new HashMap<String, String>(16);
                    csvKeyMap.put("endtime", logMap[5]);
                    // String endT = logMap[4].replace(", endtime ", "");
                    csvKeyMap.put("starttime", logMap[4].replace(", endtime ", ""));
                    csvKeyMap.put("objCode", logMap[3].replace(", starttime ", ""));
                    csvKeyMap.put("operator", logMap[2].replace(", objCode ", ""));
                    csvKeyMap.put("content", logMap[1].replace(", operator ", ""));
                    csvContentList.add(csvKeyMap);
                }
            }
        }
        catch (Exception ex)
        {
            //ex.printStackTrace();
         logger.info(Constants.LOG_COLLECT_CODE, "100", "getWSLogContent() run time exception: "+ex);
        }
        // System.out.println(logInfo);
        // exit = true;
        // }
        // }
        // System.out.println("/nThank you for running the client.");
       
        // 对结果集进行按时间降序排列
        OperationLogComparator com = new OperationLogComparator();
        Collections.sort(csvContentList, com);
       
        return csvContentList;
    }
   
    private static void setupTLS(Greeter port)
            throws FileNotFoundException, IOException, GeneralSecurityException {
            String keyStoreLoc = "/opt/netwatcher/pm4h2/app/module/eamappproxy/conf/clientKeystore.jks";
            HTTPConduit httpConduit = (HTTPConduit) ClientProxy.getClient(port).getConduit();
    
            TLSClientParameters tlsCP = new TLSClientParameters();
            String keyPassword = "ckpass";
            KeyStore keyStore = KeyStore.getInstance("JKS");
            keyStore.load(new FileInputStream(keyStoreLoc), "cspass".toCharArray());
            KeyManager[] myKeyManagers = getKeyManagers(keyStore, keyPassword);
            tlsCP.setKeyManagers(myKeyManagers);
            tlsCP.setDisableCNCheck(true);
           
            KeyStore trustStore = KeyStore.getInstance("JKS");
            trustStore.load(new FileInputStream(keyStoreLoc), "cspass".toCharArray());
            TrustManager[] myTrustStoreKeyManagers = getTrustManagers(trustStore);
            tlsCP.setTrustManagers(myTrustStoreKeyManagers);
           
            httpConduit.setTlsClientParameters(tlsCP);
        }

        private static TrustManager[] getTrustManagers(KeyStore trustStore)
            throws NoSuchAlgorithmException, KeyStoreException {
            String alg = KeyManagerFactory.getDefaultAlgorithm();
            TrustManagerFactory fac = TrustManagerFactory.getInstance(alg);
            fac.init(trustStore);
            return fac.getTrustManagers();
        }
       
        private static KeyManager[] getKeyManagers(KeyStore keyStore, String keyPassword)
            throws GeneralSecurityException, IOException {
            String alg = KeyManagerFactory.getDefaultAlgorithm();
            char[] keyPass = keyPassword != null
                         ? keyPassword.toCharArray()
                         : null;
            KeyManagerFactory fac = KeyManagerFactory.getInstance(alg);
            fac.init(keyStore, keyPass);
            return fac.getKeyManagers();
        }


package com.inspur.pmv5.service.impl.collection.wsclient;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;

/**
 * This class was generated by Apache CXF 2.6.14
 * 2014-09-01T10:05:41.176+08:00
 * Generated source version: 2.6.14
 *
 */
@WebService(targetNamespace = "http://apache.org/hello_world_soap_http", name = "Greeter")
@XmlSeeAlso({com.inspur.pmv5.service.impl.collection.wsclient.types.ObjectFactory.class})
public interface Greeter {

    @WebResult(name = "responseType", targetNamespace = "http://apache.org/hello_world_soap_http/types")
    @RequestWrapper(localName = "greetMe", targetNamespace = "http://apache.org/hello_world_soap_http/types", className = "org.apache.hello_world_soap_http.types.GreetMe")
    @WebMethod
    @ResponseWrapper(localName = "greetMeResponse", targetNamespace = "http://apache.org/hello_world_soap_http/types", className = "org.apache.hello_world_soap_http.types.GreetMeResponse")
    public java.lang.String greetMe(
        @WebParam(name = "requestType", targetNamespace = "http://apache.org/hello_world_soap_http/types")
        java.lang.String requestType
    );
}

package com.inspur.pmv5.service.impl.collection.wsclient;

import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceFeature;
import javax.xml.ws.Service;

/**
 * This class was generated by Apache CXF 2.6.14
 * 2014-09-01T10:05:41.214+08:00
 * Generated source version: 2.6.14
 *
 */
@WebServiceClient(name = "SOAPService",
                  wsdlLocation = "file:/opt/netwatcher/pm4h2/app/module/eamappproxy/conf/hello_world.wsdl",
                  targetNamespace = "http://apache.org/hello_world_soap_http")
public class SOAPService extends Service {

    public final static URL WSDL_LOCATION;

    public final static QName SERVICE = new QName("http://apache.org/hello_world_soap_http", "SOAPService");
    public final static QName SoapPort = new QName("http://apache.org/hello_world_soap_http", "SoapPort");
    static {
        URL url = null;
        try {
            url = new URL("file:/opt/netwatcher/pm4h2/app/module/eamappproxy/conf/hello_world.wsdl");
        } catch (MalformedURLException e) {
            java.util.logging.Logger.getLogger(SOAPService.class.getName())
                .log(java.util.logging.Level.INFO,
                     "Can not initialize the default wsdl from {0}", "file:/E:/01-MyX220/Desktop/apache-cxf-2.6.14/samples/wsdl_first_https/src/main/config/hello_world.wsdl");
        }
        WSDL_LOCATION = url;
    }

    public SOAPService(URL wsdlLocation) {
        super(wsdlLocation, SERVICE);
    }

    public SOAPService(URL wsdlLocation, QName serviceName) {
        super(wsdlLocation, serviceName);
    }

    public SOAPService() {
        super(WSDL_LOCATION, SERVICE);
    }
   
    //This constructor requires JAX-WS API 2.2. You will need to endorse the 2.2
    //API jar or re-run wsdl2java with "-frontend jaxws21" to generate JAX-WS 2.1
    //compliant code instead.
    public SOAPService(WebServiceFeature ... features) {
        super(WSDL_LOCATION, SERVICE, features);
    }

    //This constructor requires JAX-WS API 2.2. You will need to endorse the 2.2
    //API jar or re-run wsdl2java with "-frontend jaxws21" to generate JAX-WS 2.1
    //compliant code instead.
    public SOAPService(URL wsdlLocation, WebServiceFeature ... features) {
        super(wsdlLocation, SERVICE, features);
    }

    //This constructor requires JAX-WS API 2.2. You will need to endorse the 2.2
    //API jar or re-run wsdl2java with "-frontend jaxws21" to generate JAX-WS 2.1
    //compliant code instead.
    public SOAPService(URL wsdlLocation, QName serviceName, WebServiceFeature ... features) {
        super(wsdlLocation, serviceName, features);
    }

    /**
     *
     * @return
     *     returns Greeter
     */
    @WebEndpoint(name = "SoapPort")
    public Greeter getSoapPort() {
        return super.getPort(SoapPort, Greeter.class);
    }

    /**
     *
     * @param features
     *     A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy.  Supported features not in the <code>features</code> parameter will have their default values.
     * @return
     *     returns Greeter
     */
    @WebEndpoint(name = "SoapPort")
    public Greeter getSoapPort(WebServiceFeature... features) {
        return super.getPort(SoapPort, Greeter.class, features);
    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值