Created
October 7, 2016 18:26
-
-
Save laszlocsontos/12b46ee51b0a759e83e186b6ebb35095 to your computer and use it in GitHub Desktop.
Groovy script for calling a WSDL-based web service dynamically with JAX-WS API back-end by CXF
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javax.xml.namespace.QName | |
import javax.xml.soap.* | |
import javax.xml.ws.Dispatch | |
import javax.xml.ws.Service | |
import javax.xml.ws.soap.SOAPBinding | |
import javax.xml.xpath.XPath | |
import javax.xml.xpath.XPathConstants | |
import javax.xml.xpath.XPathFactory | |
// Create the message | |
MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL) | |
SOAPMessage requestMessage = messageFactory.createMessage() | |
MimeHeaders mimeHeaders = requestMessage.getMimeHeaders() | |
mimeHeaders.setHeader("SOAPAction", "http://www.webserviceX.NET/GetCitiesByCountry") | |
// Add a body | |
SOAPBody body = requestMessage.getSOAPBody() | |
QName getCitiesByCountryName = new QName("http://www.webserviceX.NET", "GetCitiesByCountry") | |
SOAPBodyElement bodyElement = body.addBodyElement(getCitiesByCountryName) | |
QName countryNameName = new QName("http://www.webserviceX.NET", "CountryName") | |
SOAPElement countryNameElement = bodyElement.addChildElement(countryNameName) | |
countryNameElement.addTextNode("Hungary") | |
// Create service dynamically | |
QName serviceName = new QName("http://www.webserviceX.NET", "GlobalWeather") | |
Service service = Service.create(serviceName) | |
QName portName = new QName("http://www.webserviceX.NET", "GlobalWeatherSoap12") | |
service.addPort(portName, SOAPBinding.SOAP12HTTP_BINDING, "http://www.webservicex.net/globalweather.asmx") | |
Dispatch<SOAPMessage> dispatch = service.createDispatch(portName, SOAPMessage.class, Service.Mode.MESSAGE) | |
// Retrieve results | |
SOAPMessage responseMessage = dispatch.invoke(requestMessage) | |
SOAPBody responseBody = responseMessage.getSOAPBody() | |
/* | |
StringWriter sw = new StringWriter() | |
TransformerFactory tf = TransformerFactory.newInstance() | |
Transformer transformer = tf.newTransformer() | |
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no") | |
transformer.setOutputProperty(OutputKeys.METHOD, "xml") | |
transformer.setOutputProperty(OutputKeys.INDENT, "yes") | |
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8") | |
transformer.transform(new DOMSource(responseBody), new StreamResult(sw)) | |
println(sw.toString()) | |
*/ | |
XPath xPath = XPathFactory.newInstance().newXPath() | |
Object result = xPath.compile("//GetCitiesByCountryResult").evaluate(responseBody, XPathConstants.NODE) | |
println("Result: " + result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment