Forma simples de processar um WSDL

Estou a tentar analisar um WSDL para obter as operações, o endpoint e um exemplo de carga útil. O WSDL in inputted pelo utilizador. Não consigo encontrar um tutorial para fazer isto.

Só consigo encontrar aqueles que geram código fonte de que não preciso. Tentei usar XBeans, mas aparentemente preciso do Saxon. Existe uma maneira simples e leve de fazer isto sem o Saxon?

por exemplo

   <?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>

deve obter operações: GetLastTradePrice, GetLastTradePrice

ponto final: StockQuotePort

Amostra De Carga Útil:

<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>
Isto é o que SoapUI faz. Mas estou principalmente preocupado em ser capaz de analisar o WSDL. Um pouco mais de contexto é o WSDL é carregado e, em seguida, o resultado é exibido em uma aplicação GWT (o envio de arquivos deve ir para o servlet). Então eu preciso analisar o arquivo e criar um objeto que o GWT será capaz de entender.

Author: informatik01, 2012-05-16

3 answers

Isto parece bom. http://www.membrane-soa.org/soa-model-doc/1.4/java-api/parse-wsdl-java-api.htm

Não funcionar na primeira tentativa para mim, Então eu escrevi um método que retorna os resultados sugeridos para a amostra wsdl - sem dependências fora do 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()]);
}

Parece que você gostaria de remover os duplicados, uma vez que cada operação está listada duas vezes no WSDL. É fácil usar um conjunto. Enviou o projecto eclipse completo que mostra tanto o único como o Não-único resultados aqui: https://github.com/sek/wsdlparser

 8
Author: Stan Kurdziel, 2017-01-25 11:27:55

Oi @Rebzie você pode usar JDOM é muito fácil e leve. Uso o ficheiro XML de análise. Espero ajudar-te. :)

 -1
Author: hekomobile, 2012-05-16 15:28:18
 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();     
}
 -1
Author: Shiv Pratap, 2017-05-25 11:41:17