// This script permits to save locally a WSDL document (from its URL) with all its dependencies with locations rewriting. // See https://www.odelia-technologies.com/blog/save-wsdl-files.html import groovy.xml.XmlUtil if (args.size() != 1) { println 'Script usage: groovy SaveWSDLFiles ' System.exit(0) } def works = [] works << [uri: args[0], parsed: false] // Used to provide a filename from an URI def uriToFileName = { uri, ext -> uri.replaceAll($/[/:?=]/$, '_') + ".$ext" } // Used to replace URI import locations by corresponding filenames def modifyLocations = { locations, ext, path, attr -> if (!path.@"$attr".isEmpty()) { path.each { node -> locations << node.@"$attr".toString() node.@"$attr" = uriToFileName(locations[-1], ext) } } } while(true) { def work = works.find { !it.parsed } if (!work) break println "Parse $work.uri" def slurper = new XmlParser(false, false) def xml = slurper.parse(work.uri) // Find namespace aliases def xsd = xml.attributes().find { it.value == 'http://www.w3.org/2001/XMLSchema' && it.key.startsWith('xmlns') }?.key.substring(6) def wsdl = xml.attributes().find { it.value == 'http://schemas.xmlsoap.org/wsdl/' && it.key.startsWith('xmlns') }?.key.substring(6) // Find next URIs to parse, in WSDL import tags, and/or schema imports tags def imports = [] if (wsdl) modifyLocations(imports, 'wsdl', xml."$wsdl:import", 'location') if (wsdl && xsd) modifyLocations(imports, 'xsd', xml."$wsdl:types"."$xsd:schema"."$xsd:import", 'schemaLocation') if (xsd) modifyLocations(imports, 'xsd', xml."$xsd:import", 'schemaLocation') def fileName = uriToFileName(work.uri, wsdl && xml.name() == "$wsdl:definitions" ? 'wsdl' : 'xsd') // Save .wsdl or .xsd file in out directory def outDir = new File('out'); if (!outDir.exists()) outDir.mkdir() XmlUtil.serialize(xml, new FileWriter(new File(outDir, fileName))) imports.findAll { !works.uri.contains(it) }.each { works << [uri: it.toString(), parsed: false] } work.parsed = true }