【问题标题】:Simple way to parse a WSDL解析 WSDL 的简单方法
【发布时间】:2012-05-23 13:44:41
【问题描述】:

我正在尝试解析 WSDL 以获取操作、端点和示例负载。用户输入的 WSDL。我找不到这样做的教程。

我只能找到那些生成我不需要的源代码的。我尝试过使用 XBeans,但显然我需要 Saxon。没有 Saxon 是否有一种简单的轻量级方法可以做到这一点?

例如

   <?xml version="1.0"?>
  <definitions name="StockQuote"
  targetNamespace=
    "http://example.com/stockquote.wsdl"
  xmlns:tns="http://example.com/stockquote.wsdl"
  xmlns:xsd1="http://example.com/stockquote.xsd"
  xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
  xmlns="http://schemas.xmlsoap.org/wsdl/">
   <types>
   <schema targetNamespace=
     "http://example.com/stockquote.xsd"
     xmlns="http://www.w3.org/2000/10/XMLSchema">
      <element name="TradePriceRequest">
        <complexType>
           <all>
             <element name="tickerSymbol" 
               type="string"/>
           </all>
        </complexType>
      </element>
      <element name="TradePrice">
        <complexType>
          <all>
            <element name="price" type="float"/>
          </all>
        </complexType>
      </element>
   </schema>
   </types>
   <message name="GetLastTradePriceInput">
     <part name="body" element=
       "xsd1:TradePriceRequest"/>
   </message>
   <message name="GetLastTradePriceOutput">
     <part name="body" element="xsd1:TradePrice"/>
   </message>
   <portType name="StockQuotePortType">
     <operation name="GetLastTradePrice">
       <input message="tns:GetLastTradePriceInput"/>
       <output message="tns:GetLastTradePriceOutput"/>
     </operation>
   </portType>
     <binding name="StockQuoteSoapBinding"
       type="tns:StockQuotePortType">
       <soap:binding style="document"
         transport=
           "http://schemas.xmlsoap.org/soap/http"/>
     <operation name="GetLastTradePrice">
       <soap:operation
         soapAction=
           "http://example.com/GetLastTradePrice"/>
         <input>
           <soap:body use="literal"/>
         </input>
         <output>
           <soap:body use="literal"/>
         </output>
       </operation>
     </binding>
     <service name="StockQuoteService">
       <documentation>My first service</documentation>
       <port name="StockQuotePort" 
         binding="tns:StockQuoteBinding">
         <soap:address location=
           "http://example.com/stockquote"/>
       </port>
     </service>
    </definitions>

应获取操作:GetLastTradePrice、GetLastTradePrice

端点:StockQuotePort

样本负载:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:stoc="http://example.com/stockquote.xsd">
   <soapenv:Header/>
   <soapenv:Body>
      <stoc:TradePriceRequest/>
   </soapenv:Body>
</soapenv:Envelope>

这就像 SoapUI 所做的那样。但我主要关心的是能够解析 WSDL。更多上下文是上传 WSDL,然后将结果显示在 GWT 应用程序中(文件上传必须转到 servlet)。所以我需要解析文件并创建一个 GWT 能够理解的对象。

【问题讨论】:

  • 可以使用 XML 解析器对 wsdl 进行解析,以从中获取所需内容。 SAX 非常轻量级,学习起来很轻松。见stackoverflow.com/questions/2134507/fast-lightweight-xml-parser
  • 似乎您正在寻找可以解决问题的库。 SOAPUI 有一些可以重用的库。我不记得 jar/类的名称,但我已经在 1 年前成功完成了。

标签: java parsing wsdl


【解决方案1】:

这看起来不错:http://www.membrane-soa.org/soa-model-doc/1.4/java-api/parse-wsdl-java-api.htm

虽然对我来说第一次尝试没有用,所以我编写了一个方法来返回示例 wsdl 的建议结果 - 在 J2SE6 之外没有依赖关系。

public String[] listOperations(String filename) throws FileNotFoundException, SAXException, IOException, ParserConfigurationException {
  Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new FileInputStream(filename));
  NodeList elements = d.getElementsByTagName("operation");
  ArrayList<String> operations = new ArrayList<String>();
  for (int i = 0; i < elements.getLength(); i++) {
    operations.add(elements.item(i).getAttributes().getNamedItem("name").getNodeValue());
  }
  return operations.toArray(new String[operations.size()]);
}

您似乎想要删除重复项,因为每个操作在 WSDL 中列出了两次。使用 Set 很容易。上传完整的 Eclipse 项目,在此处显示唯一和非唯一结果:https://github.com/sek/wsdlparser

【讨论】:

    【解决方案2】:

    我使用easywsdl。

    A place to start

    Maven:
    <dependency>
      <groupId>org.ow2.easywsdl</groupId>
      <artifactId>easywsdl-wsdl</artifactId>
      <version>2.1</version>
    </dependency>
    
    
    // Read a WSDL 1.1 or 2.0
    WSDLReader reader = WSDLFactory.newInstance().newWSDLReader();
    Description desc = reader.read(new URL("http://file/path/document.wsdl"));
    // Endpoints take place in services. 
    // Select a service
    Service service = desc.getServices().get(0);
    
    // List endpoints
    List<Endpoint> endpoints = service.getEndpoints(); 
    
    // Read specific endpoint
    //An endpoint has getBinding and then you getInterface from binding and so on
    Endpoint specificEndpoint = service.getEndpoint("endpointName");
    
    // Add endpoint to service
    service.addEndpoint(specificEndpoint);
    
    // Remove a specific enpoint
    service.removeEndpoint("endpointName");
    
    // Create endpoint
    Endpoint createdEndpoint = service.createEndpoint();
    service.addEndpoint(createdEndpoint);
    
    My sample code:
        try {
            // Read a WSDL 1.1 or 2.0
            WSDLReader reader = WSDLFactory.newInstance().newWSDLReader();
            Description desc = reader.read(new URL("file:///C:/your/file/path/sample.wsdl"));
            // Endpoints take place in services. 
            // Select a service
            Service service = desc.getServices().get(0);
            List<Endpoint> endpoints = service.getEndpoints();
            //Gets address of first endpoint
            System.out.println(endpoints.get(0).getAddress());
            //Gets http method
            System.out.println(endpoints.get(0).getBinding().getBindingOperations().get(0).getHttpMethod());
            //Gets input type
            System.out.println(endpoints.get(0).getBinding().getInterface().getOperations().get(0).getInput().getElement().getType().getQName().getLocalPart());
    
        } catch (WSDLException | IOException | URISyntaxException e1) {
            e1.printStackTrace();
        }
    

    【讨论】:

    【解决方案3】:
     private static String getMethodNameFromWSDL(String wsdlPath) throws FileNotFoundException, SAXException, IOException, ParserConfigurationException {
    
            String tagPrefix = null;
            String namespace =null;
            String location = null;
            NodeList nd = null;
            Set<String> operations = new HashSet<String>(); 
            NodeList nodeListOfOperations = null;
            String attr ="http://www.w3.org/2001/XMLSchema"
    
            Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(convertURLToString(wsdlPath).getBytes()));
    
            NodeList allNodesOfDocumnet = document.getChildNodes();
    
            for(int index = 0;index<allNodesOfDocumnet.getLength();index++){
                if( document.getFirstChild().getNodeName().equalsIgnoreCase("#comment")){
                        document.removeChild(document.getFirstChild());
                }    
            }
    
           int l =  document.getFirstChild().getAttributes().getLength();
           for (int i = 0; i < l; i++) {
             String cmpAttribute =  document.getFirstChild().getAttributes().item(i).getNodeValue();
                 if(cmpAttribute.equals(attr)){
                     tagPrefix =  document.getFirstChild().getAttributes().item(i).getNodeName().replace("xmlns:", "");
                 }
            }
    
            System.out.println(tagPrefix);
            String str1=tagPrefix+":import";
            String str2="wsdl:import";
            String str3 ="operation"; 
            String str4 ="wsdl:operation"; 
            // Getting Namespace
                    if((document.getElementsByTagName(str1).getLength()>0)||(document.getElementsByTagName(str2).getLength()>0)){
    
                                if(document.getElementsByTagName(tagPrefix+":import").getLength()>0)
                                     nd =document.getElementsByTagName(tagPrefix+":import");
    
                                else if (document.getElementsByTagName("wsdl:import").getLength()>0) 
                                     nd =document.getElementsByTagName("wsdl:import");  
    
                                for (int k = 0; k < nd.item(0).getAttributes().getLength(); k++) {
                                    String strAttributes = nd.item(0).getAttributes().item(k).getNodeName();
    
                                    if(strAttributes.equalsIgnoreCase("namespace")){
                                        namespace = nd.item(0).getAttributes().item(k).getNodeValue();
                                        System.out.println("Namespace : "+namespace);
                                    }
                                    else {
                                         location = nd.item(0).getAttributes().item(k).getNodeValue();
                                         System.out.println("Location : "+location);
                                    }
    
                                }
                    }else{
                            namespace = document.getFirstChild().getAttributes().getNamedItem("targetNamespace").getNodeValue();
                            System.out.println("Namespace : "+namespace);
                        }   
    
    
    
                    //Getting  Operations 
    
                     if((document.getElementsByTagName(str3).getLength()>0)||(document.getElementsByTagName(str4).getLength()>0)){
    
                        if(document.getElementsByTagName(str3).getLength()>0){
                            nodeListOfOperations =document.getElementsByTagName(str3);
                        }
                        else if (document.getElementsByTagName(str4).getLength()>0) {
                             nodeListOfOperations =document.getElementsByTagName(str4);
                        }
                        for (int i = 0; i < nodeListOfOperations.getLength(); i++) {
                                operations.add(nodeListOfOperations.item(i).getAttributes().getNamedItem("name").getNodeValue()); 
                        }
    
                    }   
    
                if(location!=null){ 
                    if(operations.isEmpty()){   
                        Document documentForOperation = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(convertURLToString(location).getBytes()));
                        NodeList nodesOfNewDoc = documentForOperation.getChildNodes();
                        for(int index = 0;index<nodesOfNewDoc.getLength();index++){
                            if( documentForOperation.getFirstChild().getNodeName().equalsIgnoreCase("#comment")){
                                    document.removeChild(document.getFirstChild());
                            }       
                        }
    
                        NodeList nodeList  = documentForOperation.getElementsByTagName(str4);
                        for (int i = 0; i < nodeList.getLength(); i++) {
                            operations.add(nodeList.item(i).getAttributes().getNamedItem("name").getNodeValue()); 
                        }
                    }
    
                }
    
                for (String string : operations) {
                    System.out.println(string);
                }
           System.out.println(operations.toString());           
            return operations.toString();           
        }
    
    public static String convertURLToString(String url){
    
        StringBuilder response = null;  
    
        try {    
    
            URL urlObj = new URL(url);
            URLConnection urlConnection = urlObj.openConnection();
            urlConnection.setDoOutput(true);
            urlConnection.connect();    
            //urlConnection.setConnectTimeout(30000);       
            BufferedReader reader = new BufferedReader(new 
               InputStreamReader(urlConnection.getInputStream()));
            response = new StringBuilder();
            String inputLine;
    
            while ((inputLine = reader.readLine()) != null){
                response.append(inputLine);
            }
    
            reader.close();
    
        } catch (IOException e) {
            e.printStackTrace();
        }
    
        return response.toString();     
    }
    

    【讨论】:

      【解决方案4】:

      您好@Rebzie,您可以使用 JDOM 吗?它非常简单且轻量级。我使用解析 XML 文件。我希望能帮助你。 :)

      【讨论】:

        猜你喜欢
        • 2011-10-25
        • 2021-12-21
        • 1970-01-01
        • 2016-03-06
        • 2019-05-09
        • 1970-01-01
        • 2017-09-07
        • 2011-08-22
        • 1970-01-01
        相关资源
        最近更新 更多