diff --git a/README.MD b/README.MD index 1f6f367..af956e5 100644 --- a/README.MD +++ b/README.MD @@ -14,12 +14,12 @@ mvn install ## Usage ``` -java -jar wsdl2apigee-1.0.0-jar-with-dependencies.jar -wsdl= +java -jar wsdl2apigee-1.0.1-jar-with-dependencies.jar -wsdl= ``` ### Other Options ``` -java -jar wsdl2apigee-1.0.0-jar-with-dependencies.jar -wsdl= -passthru= -desc= -allpost= -opsmap= -service= -port= -debug= -oauth= -vhosts=comma separated values for virtuals hosts> -build= -cors= -apikey= -quota= -basepath= +java -jar wsdl2apigee-1.0.1-jar-with-dependencies.jar -wsdl= -passthru= -desc= -allpost= -opsmap= -service= -port= -debug= -oauth= -vhosts=comma separated values for virtuals hosts> -build= -cors= -apikey= -quota= -basepath= Defaults: passthru=false Do not convert to API/JSON. Treat as SOAP diff --git a/pom.xml b/pom.xml index dc31f3b..d3a6010 100644 --- a/pom.xml +++ b/pom.xml @@ -1,183 +1,195 @@ - 4.0.0 - wsdl2apigee - wsdl2apigee - 1.0.0 - wsdl2apigee - wsdl2apigee is an open source framework to generate Apigee Edge API Proxies from WSDLs. - - scm:git:git@github.com:apigee/wsdl2apigee.git - - - - Apache License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - - - - - Srinandan Sridhar - srinandans@google.com - Google - https://apigee.com/about/ - - - Charles Overbeck - coverbeck@google.com - Google - https://apigee.com/about/ - - - - Apigee Corporation - https://apigee.com/about/ - - - src/main/java - src/test/java - - - src/main/resources - - **/*.java - - - - - - src/test/resources - - - - - maven-compiler-plugin - 3.3 - - 1.7 - 1.7 - - - - org.apache.maven.plugins - maven-jar-plugin - 2.3.2 - - ${project.artifactId}-${project.version}-${buildNumber} - - - - maven-assembly-plugin - - - - com.apigee.proxywriter.GenerateProxy - - - - jar-with-dependencies - - - - - make-assembly - package - - single - - - - - - org.codehaus.mojo - buildnumber-maven-plugin - 1.4 - - - validate - - create - - - - - no.scm.config.in.pom - 5 - - - - - - - org.apache.httpcomponents - httpclient - 4.2.2 - - - - log4j - log4j - 1.2.17 - - - org.slf4j - slf4j-api - 1.7.2 - - - org.slf4j - slf4j-simple - 1.7.2 - - - commons-cli - commons-cli - 1.2 - - - org.apache.commons - commons-lang3 - 3.4 - - - commons-logging - commons-logging - 1.1.1 - - - com.predic8 - soa-model-core - 1.5.4 - - - com.google.code.gson - gson - 2.3 - - - commons-validator - commons-validator - 1.5.1 - - - - commons-io - commons-io - 2.5 - - - junit - junit - 4.11 - test - - - org.skyscreamer - jsonassert - 1.5.0 - - + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + wsdl2apigee + wsdl2apigee + 1.0.1 + wsdl2apigee + wsdl2apigee is an open source framework to generate Apigee Edge API Proxies from WSDLs. + + scm:git:git@github.com:apigee/wsdl2apigee.git + + + + Apache License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + + + + + Srinandan Sridhar + srinandans@google.com + Google + https://apigee.com/about/ + + + Charles Overbeck + coverbeck@google.com + Google + https://apigee.com/about/ + + + + Apigee Corporation + https://apigee.com/about/ + + + src/main/java + src/test/java + + + src/main/resources + + **/*.java + + + + + + src/test/resources + + + + + maven-surefire-plugin + + + + java.util.logging.config.file + src/test/resources/java-util-logging.properties + + + + + + + maven-compiler-plugin + 3.3 + + 1.7 + 1.7 + + + + org.apache.maven.plugins + maven-jar-plugin + 2.3.2 + + ${project.artifactId}-${project.version}-${buildNumber} + + + + maven-assembly-plugin + + + + com.apigee.proxywriter.GenerateProxy + + + + jar-with-dependencies + + + + + make-assembly + package + + single + + + + + + org.codehaus.mojo + buildnumber-maven-plugin + 1.4 + + + validate + + create + + + + + no.scm.config.in.pom + 5 + + + + + + + org.apache.httpcomponents + httpclient + 4.2.2 + + + + log4j + log4j + 1.2.17 + + + org.slf4j + slf4j-api + 1.7.2 + + + org.slf4j + slf4j-simple + 1.7.2 + + + commons-cli + commons-cli + 1.2 + + + org.apache.commons + commons-lang3 + 3.4 + + + commons-logging + commons-logging + 1.1.1 + + + com.predic8 + soa-model-core + 1.5.4 + + + com.google.code.gson + gson + 2.3 + + + commons-validator + commons-validator + 1.5.1 + + + + commons-io + commons-io + 2.5 + + + junit + junit + 4.11 + test + + + org.skyscreamer + jsonassert + 1.5.0 + + diff --git a/src/main/java/com/apigee/proxywriter/GenerateProxy.java b/src/main/java/com/apigee/proxywriter/GenerateProxy.java index dba21c4..17fa3ab 100644 --- a/src/main/java/com/apigee/proxywriter/GenerateProxy.java +++ b/src/main/java/com/apigee/proxywriter/GenerateProxy.java @@ -1,9 +1,9 @@ package com.apigee.proxywriter; /** - * + * * The GenerateProxy program generates a Apigee API Proxy from a WSDL Document. The generated proxy can be * passthru or converted to an API (REST/JSON over HTTP). - * + * * How does it work? * At a high level, here is the logic implemented for SOAP-to-API: * Step 1: Parse the WSDL @@ -13,51 +13,29 @@ * Step 3: Create the API Proxy folder structure * Step 4: Copy policies from the standard template * Step 5: Create the Extract Variables and Assign Message Policies - * Step 5a: If the operation is interpreted as a POST (create), then obtain JSON Paths from JSON request template + * Step 5a: If the operation is interpreted as a POST (create), then obtain JSON Paths from JSON request template * Step 5b: Use JSONPaths in the Extract Variables - * + * * At a high level, here is the logic implemented for SOAP-passthru: * Step 1: Parse the WSDL * Step 2: Copy policies from the standard template - * - * + * + * * @author Nandan Sridhar * @version 0.1 - * @since 2016-05-20 + * @since 2016-05-20 */ import java.io.*; import java.nio.file.*; - -import java.nio.file.attribute.BasicFileAttributes; -import java.util.*; -import java.util.logging.ConsoleHandler; -import java.util.logging.Handler; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.logging.SimpleFormatter; - import com.apigee.oas.OASUtils; import com.apigee.proxywriter.exception.*; import com.apigee.utils.*; -import com.google.gson.*; -import com.predic8.soamodel.*; -import com.predic8.util.HTTPUtil; -import com.predic8.wsdl.*; -import com.predic8.wsdl.Operation; -import com.predic8.wsi.WSIResult; -import com.predic8.xml.util.ExternalResolver; -import org.apache.commons.lang3.StringEscapeUtils; -import org.apache.commons.validator.routines.UrlValidator; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; - import com.apigee.utils.Options.Multiplicity; import com.apigee.utils.Options.Separator; import com.apigee.xsltgen.Rule; import com.apigee.xsltgen.RuleSet; +import com.google.gson.*; import com.predic8.schema.All; import com.predic8.schema.Attribute; import com.predic8.schema.BuiltInSchemaType; @@ -72,3187 +50,3197 @@ import com.predic8.schema.Sequence; import com.predic8.schema.SimpleContent; import com.predic8.schema.TypeDefinition; +import com.predic8.soamodel.*; +import com.predic8.util.HTTPUtil; +import com.predic8.wsdl.*; +import com.predic8.wsdl.Operation; +import com.predic8.wsi.WSIResult; import com.predic8.wstool.creator.RequestTemplateCreator; import com.predic8.wstool.creator.SOARequestCreator; - +import com.predic8.xml.util.ExternalResolver; import groovy.xml.MarkupBuilder; import groovy.xml.QName; - +import java.io.InputStream; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.*; +import java.util.logging.ConsoleHandler; +import java.util.logging.Handler; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.logging.SimpleFormatter; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; +import org.apache.commons.lang3.StringEscapeUtils; +import org.apache.commons.validator.routines.UrlValidator; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; public class GenerateProxy { - private static final Logger LOGGER = Logger.getLogger(GenerateProxy.class.getName()); - private static final ConsoleHandler handler = new ConsoleHandler(); - public static final String SOAP_11 = "SOAP11"; - public static final String SOAP_12 = "SOAP12"; + private static final String CLASS_NAME = GenerateProxy.class.getName(); + private static final Logger LOGGER; + private static final ConsoleHandler handler = new ConsoleHandler(); + public static final String SOAP_11 = "SOAP11"; + public static final String SOAP_12 = "SOAP12"; - public static String OPSMAPPING_TEMPLATE = "/templates/opsmap/opsmapping.xml";//"src/main/resources/templates/opsmap/opsmapping.xml"; + public static String OPSMAPPING_TEMPLATE = "/templates/opsmap/opsmapping.xml";//"src/main/resources/templates/opsmap/opsmapping.xml"; - private static String SOAP2API_XSL = ""; + private static String SOAP2API_XSL = ""; - private static final List primitiveTypes = Arrays.asList(new String[] { "int", "string", "boolean", - "decimal", "float", "double", "duration", "dateTime", "time", "date", "long", "gYearMonth", "gYear", - "gMonthDay", "gDay", "gMonth", "hexBinary", "base64Binary", "anyURI", "QName", "NOTATION" }); - private final String soap11Namespace = " xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" "; - //" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "; + private static final List primitiveTypes = Arrays.asList(new String[] { "int", "string", "boolean", + "decimal", "float", "double", "duration", "dateTime", "time", "date", "long", "gYearMonth", "gYear", + "gMonthDay", "gDay", "gMonth", "hexBinary", "base64Binary", "anyURI", "QName", "NOTATION" }); + private final String soap11Namespace = " xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" "; + //" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "; - private final String soap12Namespace = " xmlns:soapenv=\"http://www.w3.org/2003/05/soap-envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "; + private final String soap12Namespace = " xmlns:soapenv=\"http://www.w3.org/2003/05/soap-envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "; - private static final List blackListedNamespaces = Arrays.asList("http://schemas.xmlsoap.org/wsdl/", - "http://schemas.xmlsoap.org/wsdl/soap/"); + private static final List blackListedNamespaces = Arrays.asList("http://schemas.xmlsoap.org/wsdl/", + "http://schemas.xmlsoap.org/wsdl/soap/"); - private static final String emptySoap12 = ""; + private static final String emptySoap12 = ""; - private static final String emptySoap11 = ""; + private static final String emptySoap11 = ""; - private static final String SOAP2API_APIPROXY_TEMPLATE = "/templates/soap2api/apiProxyTemplate.xml"; - private static final String SOAP2API_PROXY_TEMPLATE = "/templates/soap2api/proxyDefault.xml"; - private static final String SOAP2API_TARGET_TEMPLATE = "/templates/soap2api/targetDefault.xml"; - private static final String SOAP2API_EXTRACT_TEMPLATE = "/templates/soap2api/ExtractPolicy.xml"; - private static final String SOAP2API_ASSIGN_TEMPLATE = "/templates/soap2api/AssignMessagePolicy.xml"; - private static final String SOAP2API_XSLT11POLICY_TEMPLATE = "/templates/soap2api/add-namespace11.xml"; - private static final String SOAP2API_XSLT11_TEMPLATE = "/templates/soap2api/add-namespace11.xslt"; - private static final String SOAP2API_XSLT12POLICY_TEMPLATE = "/templates/soap2api/add-namespace12.xml"; - private static final String SOAP2API_XSLT12_TEMPLATE = "/templates/soap2api/add-namespace12.xslt"; - private static final String SOAP2API_JSON_TO_XML_TEMPLATE = "/templates/soap2api/json-to-xml.xml"; - private static final String SOAP2API_ADD_SOAPACTION_TEMPLATE = "/templates/soap2api/add-soapaction.xml"; - // open-api feature - private static final String SOAP2API_RETURN_OPENAPI_TEMPLATE = "/templates/soap2api/return-open-api.xml"; - // private static final String SOAP2API_JSPOLICY_TEMPLATE = - // "/templates/soap2api/root-wrapper.xml"; + private static final String SOAP2API_APIPROXY_TEMPLATE = "/templates/soap2api/apiProxyTemplate.xml"; + private static final String SOAP2API_PROXY_TEMPLATE = "/templates/soap2api/proxyDefault.xml"; + private static final String SOAP2API_TARGET_TEMPLATE = "/templates/soap2api/targetDefault.xml"; + private static final String SOAP2API_EXTRACT_TEMPLATE = "/templates/soap2api/ExtractPolicy.xml"; + private static final String SOAP2API_ASSIGN_TEMPLATE = "/templates/soap2api/AssignMessagePolicy.xml"; + private static final String SOAP2API_XSLT11POLICY_TEMPLATE = "/templates/soap2api/add-namespace11.xml"; + private static final String SOAP2API_XSLT11_TEMPLATE = "/templates/soap2api/add-namespace11.xslt"; + private static final String SOAP2API_XSLT12POLICY_TEMPLATE = "/templates/soap2api/add-namespace12.xml"; + private static final String SOAP2API_XSLT12_TEMPLATE = "/templates/soap2api/add-namespace12.xslt"; + private static final String SOAP2API_JSON_TO_XML_TEMPLATE = "/templates/soap2api/json-to-xml.xml"; + private static final String SOAP2API_ADD_SOAPACTION_TEMPLATE = "/templates/soap2api/add-soapaction.xml"; + // open-api feature + private static final String SOAP2API_RETURN_OPENAPI_TEMPLATE = "/templates/soap2api/return-open-api.xml"; + // private static final String SOAP2API_JSPOLICY_TEMPLATE = + // "/templates/soap2api/root-wrapper.xml"; - private static final String SOAPPASSTHRU_APIPROXY_TEMPLATE = "/templates/soappassthru/apiProxyTemplate.xml"; - private static final String SOAPPASSTHRU_PROXY_TEMPLATE = "/templates/soappassthru/proxyDefault.xml"; - private static final String SOAPPASSTHRU_TARGET_TEMPLATE = "/templates/soappassthru/targetDefault.xml"; - private static final String SOAPPASSTHRU_GETWSDL_TEMPLATE = "/templates/soappassthru/return-wsdl.xml"; + private static final String SOAPPASSTHRU_APIPROXY_TEMPLATE = "/templates/soappassthru/apiProxyTemplate.xml"; + private static final String SOAPPASSTHRU_PROXY_TEMPLATE = "/templates/soappassthru/proxyDefault.xml"; + private static final String SOAPPASSTHRU_TARGET_TEMPLATE = "/templates/soappassthru/targetDefault.xml"; + private static final String SOAPPASSTHRU_GETWSDL_TEMPLATE = "/templates/soappassthru/return-wsdl.xml"; - private static final String OAS_TEMPLATE = "/templates/oas/oastemplate.json"; + private static final String OAS_TEMPLATE = "/templates/oas/oastemplate.json"; - private static final String SOAP11_CONTENT_TYPE = "text/xml; charset=utf-8";// "text/xml; - // charset=utf-8"; - private static final String SOAP12_CONTENT_TYPE = "application/soap+xml"; + private static final String SOAP11_CONTENT_TYPE = "text/xml; charset=utf-8";// "text/xml; + // charset=utf-8"; + private static final String SOAP12_CONTENT_TYPE = "application/soap+xml"; - private static final String SOAP11_PAYLOAD_TYPE = "text/xml";// "text/xml"; - private static final String SOAP12_PAYLOAD_TYPE = "application/soap+xml"; + private static final String SOAP11_PAYLOAD_TYPE = "text/xml";// "text/xml"; + private static final String SOAP12_PAYLOAD_TYPE = "application/soap+xml"; + + private static final String SOAP11 = "http://schemas.xmlsoap.org/soap/envelope/"; + private static final String SOAP12 = "http://www.w3.org/2003/05/soap-envelope"; + + // set this to true if SOAP passthru is needed + private boolean PASSTHRU; + // set this to true if all operations are to be consumed via POST verb + private boolean ALLPOST; + // set this to true if oauth should be added to the proxy + private boolean OAUTH; + // set this to true if apikey should be added to the proxy + private boolean APIKEY; + // enable this flag if api key based quota is enabled + private boolean QUOTAAPIKEY; + // enable this flag if oauth based quota is enabled + private boolean QUOTAOAUTH; + // enable this flag is cors is enabled + private boolean CORS; + // enable this flag if wsdl is of rpc style + private boolean RPCSTYLE; + // enable this flag if user sets desc + private boolean DESCSET; + // fail safe measure when schemas are heavily nested or have 100s of + // elements + private boolean TOO_MANY; + + private String targetEndpoint; + + private String soapVersion; + + private String serviceName; + + private String portName; + + private String basePath; + + private String proxyName; + + private String opsMap; + + private String wsdlContent; + + private String selectedOperationsJson; + + private List vHosts; + + private SelectedOperations selectedOperations; + + private OpsMap operationsMap; + + // default build folder is ./build + private String buildFolder; + + // Each row in this Map has the key as the operation name. The operation + // name has SOAP Request + // and JSON Equivalent of SOAP (without the SOAP Envelope) as values. + // private Map> messageTemplates; + private Map messageTemplates; + // tree to hold elements to build an xpath + private HashMap xpathElement; + // xpath tree element level + private int level; + // List of rules to generate XSLT + private ArrayList ruleList = new ArrayList(); + + private Definitions wsdl = null; + + private com.predic8.wsdl.Port port = null; + + public Map namespace = new LinkedHashMap(); + + // open-api feature + private JsonObject definitions; + private String oasContent; + // store openapi query params + private ArrayList queryParams; + + // initialize the logger + static { + try { + InputStream stream = GenerateProxy.class.getClassLoader(). + getResourceAsStream("java-util-logging.properties"); + java.util.logging.LogManager.getLogManager().readConfiguration(stream); + } catch (Exception e) { + } + LOGGER = Logger.getLogger(CLASS_NAME); + LOGGER.setUseParentHandlers(false); + + Handler[] handlers = LOGGER.getHandlers(); + for (Handler handler : handlers) { + if (handler.getClass() == ConsoleHandler.class) + LOGGER.removeHandler(handler); + } + handler.setFormatter(new SimpleFormatter()); + LOGGER.addHandler(handler); + } + + public GenerateProxy() { + // initialize hashmap + messageTemplates = new HashMap(); + xpathElement = new HashMap(); + operationsMap = new OpsMap(); + selectedOperations = new SelectedOperations(); + vHosts = new ArrayList(); + // open-api feature + queryParams = new ArrayList(); + + vHosts.add("default"); + + buildFolder = null; + soapVersion = SOAP_12; + ALLPOST = false; + PASSTHRU = false; + OAUTH = false; + APIKEY = false; + QUOTAAPIKEY = false; + QUOTAOAUTH = false; + CORS = false; + RPCSTYLE = false; + DESCSET = false; + basePath = null; + TOO_MANY = false; + level = 0; + } + + public void setSelectedOperationsJson(String json) throws Exception { + selectedOperations.parseSelectedOperations(json); + } + + public void setDesc(boolean descset) { + DESCSET = descset; + } + + public void setCORS(boolean cors) { + CORS = cors; + } + + public void setBasePath(String bp) { + basePath = bp; + } + + public void setQuotaAPIKey(boolean quotaAPIKey) { + QUOTAAPIKEY = quotaAPIKey; + } + + public void setQuotaOAuth(boolean quotaOAuth) { + QUOTAOAUTH = quotaOAuth; + } + + public void setAPIKey(boolean apikey) { + APIKEY = apikey; + } + + public void setOpsMap(String oMap) { + opsMap = oMap; + } + + public void setVHost(String vhosts) { + if (vhosts.indexOf(",") != -1) { + // contains > 1 vhosts + vHosts = Arrays.asList(vhosts.split(",")); + } else { + vHosts.remove(0);// remove default + vHosts.add(vhosts); + } + } - private static final String SOAP11 = "http://schemas.xmlsoap.org/soap/envelope/"; - private static final String SOAP12 = "http://www.w3.org/2003/05/soap-envelope"; + public void setAllPost(boolean allPost) { + ALLPOST = allPost; + } - // set this to true if SOAP passthru is needed - private boolean PASSTHRU; - // set this to true if all operations are to be consumed via POST verb - private boolean ALLPOST; - // set this to true if oauth should be added to the proxy - private boolean OAUTH; - // set this to true if apikey should be added to the proxy - private boolean APIKEY; - // enable this flag if api key based quota is enabled - private boolean QUOTAAPIKEY; - // enable this flag if oauth based quota is enabled - private boolean QUOTAOAUTH; - // enable this flag is cors is enabled - private boolean CORS; - // enable this flag if wsdl is of rpc style - private boolean RPCSTYLE; - // enable this flag if user sets desc - private boolean DESCSET; - // fail safe measure when schemas are heavily nested or have 100s of - // elements - private boolean TOO_MANY; + public void setBuildFolder(String folder) { + buildFolder = folder; + } - private String targetEndpoint; + public void setPassThru(boolean pass) { + PASSTHRU = pass; + } - private String soapVersion; + public void setService(String serv) { + serviceName = serv; + } - private String serviceName; + public void setPort(String prt) { + portName = prt; + } - private String portName; + public void setOAuth(boolean oauth) { + OAUTH = oauth; + } - private String basePath; + public String getTargetEndpoint() { + return targetEndpoint; + } - private String proxyName; + private void writeAPIProxy(String proxyDescription) throws Exception { + LOGGER.entering(CLASS_NAME, new Object() {}.getClass().getEnclosingMethod().getName()); + LOGGER.log(Level.FINER,"ENTRY {0}", new Object(){}.getClass().getEnclosingMethod().getName()); - private String opsMap; + XMLUtils xmlUtils = new XMLUtils(); + Document apiTemplateDocument; - private String wsdlContent; + if (PASSTHRU) { + apiTemplateDocument = xmlUtils.readXML(SOAPPASSTHRU_APIPROXY_TEMPLATE); + } else { + apiTemplateDocument = xmlUtils.readXML(SOAP2API_APIPROXY_TEMPLATE); + } + LOGGER.finest("Read API Proxy template file"); - private String selectedOperationsJson; + Node rootElement = apiTemplateDocument.getFirstChild(); + NamedNodeMap attr = rootElement.getAttributes(); + Node nodeAttr = attr.getNamedItem("name"); + nodeAttr.setNodeValue(proxyName); + LOGGER.fine("Set proxy name: " + proxyName); - private List vHosts; + Node displayName = apiTemplateDocument.getElementsByTagName("DisplayName").item(0); + displayName.setTextContent(proxyName); + LOGGER.fine("Set proxy display name: " + proxyName); - private SelectedOperations selectedOperations; + Node description = apiTemplateDocument.getElementsByTagName("Description").item(0); + description.setTextContent(proxyDescription); + LOGGER.fine("Set proxy description: " + proxyDescription); - private OpsMap operationsMap; + Node createdAt = apiTemplateDocument.getElementsByTagName("CreatedAt").item(0); + createdAt.setTextContent(Long.toString(java.lang.System.currentTimeMillis())); - // default build folder is ./build - private String buildFolder; + Node LastModifiedAt = apiTemplateDocument.getElementsByTagName("LastModifiedAt").item(0); + LastModifiedAt.setTextContent(Long.toString(java.lang.System.currentTimeMillis())); - // Each row in this Map has the key as the operation name. The operation - // name has SOAP Request - // and JSON Equivalent of SOAP (without the SOAP Envelope) as values. - // private Map> messageTemplates; - private Map messageTemplates; - // tree to hold elements to build an xpath - private HashMap xpathElement; - // xpath tree element level - private int level; - // List of rules to generate XSLT - private ArrayList ruleList = new ArrayList(); + xmlUtils.writeXML(apiTemplateDocument, + buildFolder + File.separator + "apiproxy" + File.separator + proxyName + ".xml"); + LOGGER.fine("Generated file: " + buildFolder + File.separator + "apiproxy" + File.separator + proxyName + ".xml"); + LOGGER.exiting(CLASS_NAME, new Object() {}.getClass().getEnclosingMethod().getName()); + } - private Definitions wsdl = null; + private void writeSOAP2APIProxyEndpoint(String proxyDescription) throws Exception { + LOGGER.entering(CLASS_NAME, new Object() {}.getClass().getEnclosingMethod().getName()); + XMLUtils xmlUtils = new XMLUtils(); - private com.predic8.wsdl.Port port = null; + Document proxyDefault = xmlUtils.readXML(SOAP2API_PROXY_TEMPLATE); + Node basePathNode = proxyDefault.getElementsByTagName("BasePath").item(0); - public Map namespace = new LinkedHashMap(); + if (basePath != null && basePath.equalsIgnoreCase("") != true) { + basePathNode.setTextContent(basePath); + } - // open-api feature - private JsonObject definitions; - private String oasContent; - // store openapi query params - private ArrayList queryParams; - - // initialize the logger - static { - LOGGER.setUseParentHandlers(false); - - Handler[] handlers = LOGGER.getHandlers(); - for (Handler handler : handlers) { - if (handler.getClass() == ConsoleHandler.class) - LOGGER.removeHandler(handler); - } - handler.setFormatter(new SimpleFormatter()); - LOGGER.addHandler(handler); + Node httpProxyConnection = proxyDefault.getElementsByTagName("HTTPProxyConnection").item(0); + Node virtualHost = null; + for (String vHost : vHosts) { + virtualHost = proxyDefault.createElement("VirtualHost"); + virtualHost.setTextContent(vHost); + httpProxyConnection.appendChild(virtualHost); } - public GenerateProxy() { - // initialize hashmap - messageTemplates = new HashMap(); - xpathElement = new HashMap(); - operationsMap = new OpsMap(); - selectedOperations = new SelectedOperations(); - vHosts = new ArrayList(); - // open-api feature - queryParams = new ArrayList(); + Document apiTemplateDocument = xmlUtils + .readXML(buildFolder + File.separator + "apiproxy" + File.separator + proxyName + ".xml"); - vHosts.add("default"); + Document extractTemplate = xmlUtils.readXML(SOAP2API_EXTRACT_TEMPLATE); - buildFolder = null; - soapVersion = SOAP_12; - ALLPOST = false; - PASSTHRU = false; - OAUTH = false; - APIKEY = false; - QUOTAAPIKEY = false; - QUOTAOAUTH = false; - CORS = false; - RPCSTYLE = false; - DESCSET = false; - basePath = null; - TOO_MANY = false; - level = 0; - } + Document assignTemplate = xmlUtils.readXML(SOAP2API_ASSIGN_TEMPLATE); - public void setSelectedOperationsJson(String json) throws Exception { - selectedOperations.parseSelectedOperations(json); - } + Document returnOASTemplate = xmlUtils.readXML(SOAP2API_RETURN_OPENAPI_TEMPLATE); - public void setDesc(boolean descset) { - DESCSET = descset; - } + // Document jsPolicyTemplate = + // xmlUtils.readXML(SOAP2API_JSPOLICY_TEMPLATE); - public void setCORS(boolean cors) { - CORS = cors; + Document addNamespaceTemplate = null; + if (soapVersion.equalsIgnoreCase(SOAP_11)) { + addNamespaceTemplate = xmlUtils.readXML(SOAP2API_XSLT11POLICY_TEMPLATE); + } else { + addNamespaceTemplate = xmlUtils.readXML(SOAP2API_XSLT12POLICY_TEMPLATE); } - public void setBasePath(String bp) { - basePath = bp; - } + Document jsonXMLTemplate = xmlUtils.readXML(SOAP2API_JSON_TO_XML_TEMPLATE); - public void setQuotaAPIKey(boolean quotaAPIKey) { - QUOTAAPIKEY = quotaAPIKey; - } + Document addSoapActionTemplate = xmlUtils.readXML(SOAP2API_ADD_SOAPACTION_TEMPLATE); - public void setQuotaOAuth(boolean quotaOAuth) { - QUOTAOAUTH = quotaOAuth; - } + Node description = proxyDefault.getElementsByTagName("Description").item(0); + description.setTextContent(proxyDescription); - public void setAPIKey(boolean apikey) { - APIKEY = apikey; - } + Node policies = apiTemplateDocument.getElementsByTagName("Policies").item(0); + Node resources = apiTemplateDocument.getElementsByTagName("Resources").item(0); - public void setOpsMap(String oMap) { - opsMap = oMap; - } + Node flows = proxyDefault.getElementsByTagName("Flows").item(0); + Node flow; + Node flowDescription; + Node request; + Node response; + Node condition, condition2; + Node step1, step2, step3, step4, step5; + Node name1, name2, name3, name4, name5; + boolean once = false; - public void setVHost(String vhosts) { - if (vhosts.indexOf(",") != -1) { - // contains > 1 vhosts - vHosts = Arrays.asList(vhosts.split(",")); - } else { - vHosts.remove(0);// remove default - vHosts.add(vhosts); - } - } + // add oauth policies if set + if (OAUTH) { + String oauthPolicy = "verify-oauth-v2-access-token"; + String remoOAuthPolicy = "remove-header-authorization"; + String quota = "impose-quota-oauth"; - public void setAllPost(boolean allPost) { - ALLPOST = allPost; - } + // Add policy to proxy.xml + Node policy1 = apiTemplateDocument.createElement("Policy"); + policy1.setTextContent(oauthPolicy); - public void setBuildFolder(String folder) { - buildFolder = folder; - } + Node policy2 = apiTemplateDocument.createElement("Policy"); + policy2.setTextContent(remoOAuthPolicy); - public void setPassThru(boolean pass) { - PASSTHRU = pass; - } + policies.appendChild(policy1); + policies.appendChild(policy2); - public void setService(String serv) { - serviceName = serv; - } + Node preFlowRequest = proxyDefault.getElementsByTagName("PreFlow").item(0).getChildNodes().item(1); - public void setPort(String prt) { - portName = prt; - } + step1 = proxyDefault.createElement("Step"); + name1 = proxyDefault.createElement("Name"); + name1.setTextContent(oauthPolicy); + step1.appendChild(name1); - public void setOAuth(boolean oauth) { - OAUTH = oauth; - } + step2 = proxyDefault.createElement("Step"); + name2 = proxyDefault.createElement("Name"); + name2.setTextContent(remoOAuthPolicy); + step2.appendChild(name2); + + preFlowRequest.appendChild(step1); + preFlowRequest.appendChild(step2); - public String getTargetEndpoint() { - return targetEndpoint; + if (QUOTAOAUTH) { + Node policy3 = apiTemplateDocument.createElement("Policy"); + policy2.setTextContent(quota); + policies.appendChild(policy3); + step3 = proxyDefault.createElement("Step"); + name3 = proxyDefault.createElement("Name"); + name3.setTextContent(quota); + step3.appendChild(name3); + preFlowRequest.appendChild(step3); + } } - private void writeAPIProxy(String proxyDescription) throws Exception { + if (APIKEY) { + String apiKeyPolicy = "verify-api-key"; + String remoAPIKeyPolicy = "remove-query-param-apikey"; + String quota = "impose-quota-apikey"; - LOGGER.entering(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - XMLUtils xmlUtils = new XMLUtils(); - Document apiTemplateDocument; + // Add policy to proxy.xml + Node policy1 = apiTemplateDocument.createElement("Policy"); + policy1.setTextContent(apiKeyPolicy); - if (PASSTHRU) { - apiTemplateDocument = xmlUtils.readXML(SOAPPASSTHRU_APIPROXY_TEMPLATE); - } else { - apiTemplateDocument = xmlUtils.readXML(SOAP2API_APIPROXY_TEMPLATE); - } - LOGGER.finest("Read API Proxy template file"); + Node policy2 = apiTemplateDocument.createElement("Policy"); + policy2.setTextContent(remoAPIKeyPolicy); - Node rootElement = apiTemplateDocument.getFirstChild(); - NamedNodeMap attr = rootElement.getAttributes(); - Node nodeAttr = attr.getNamedItem("name"); - nodeAttr.setNodeValue(proxyName); - LOGGER.fine("Set proxy name: " + proxyName); + policies.appendChild(policy1); + policies.appendChild(policy2); - Node displayName = apiTemplateDocument.getElementsByTagName("DisplayName").item(0); - displayName.setTextContent(proxyName); - LOGGER.fine("Set proxy display name: " + proxyName); + Node preFlowRequest = proxyDefault.getElementsByTagName("PreFlow").item(0).getChildNodes().item(1); - Node description = apiTemplateDocument.getElementsByTagName("Description").item(0); - description.setTextContent(proxyDescription); - LOGGER.fine("Set proxy description: " + proxyDescription); + step1 = proxyDefault.createElement("Step"); + name1 = proxyDefault.createElement("Name"); + name1.setTextContent(apiKeyPolicy); + step1.appendChild(name1); - Node createdAt = apiTemplateDocument.getElementsByTagName("CreatedAt").item(0); - createdAt.setTextContent(Long.toString(java.lang.System.currentTimeMillis())); + step2 = proxyDefault.createElement("Step"); + name2 = proxyDefault.createElement("Name"); + name2.setTextContent(remoAPIKeyPolicy); + step2.appendChild(name2); - Node LastModifiedAt = apiTemplateDocument.getElementsByTagName("LastModifiedAt").item(0); - LastModifiedAt.setTextContent(Long.toString(java.lang.System.currentTimeMillis())); + preFlowRequest.appendChild(step1); + preFlowRequest.appendChild(step2); + + if (QUOTAAPIKEY) { + Node policy3 = apiTemplateDocument.createElement("Policy"); + policy2.setTextContent(quota); + policies.appendChild(policy3); + step3 = proxyDefault.createElement("Step"); + name3 = proxyDefault.createElement("Name"); + name3.setTextContent(quota); + step3.appendChild(name3); + preFlowRequest.appendChild(step3); + } - xmlUtils.writeXML(apiTemplateDocument, - buildFolder + File.separator + "apiproxy" + File.separator + proxyName + ".xml"); - LOGGER.fine( - "Generated file: " + buildFolder + File.separator + "apiproxy" + File.separator + proxyName + ".xml"); - LOGGER.exiting(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); } - private void writeSOAP2APIProxyEndpoint(String proxyDescription) throws Exception { + if (CORS) { + Node proxyEndpoint = proxyDefault.getElementsByTagName("ProxyEndpoint").item(0); + Node routeRule = proxyDefault.createElement("RouteRule"); + ((Element) routeRule).setAttribute("name", "NoRoute"); - LOGGER.entering(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - XMLUtils xmlUtils = new XMLUtils(); + Node routeCondition = proxyDefault.createElement("Condition"); + routeCondition.setTextContent("request.verb == \"OPTIONS\""); + routeRule.appendChild(routeCondition); + proxyEndpoint.appendChild(routeRule); - Document proxyDefault = xmlUtils.readXML(SOAP2API_PROXY_TEMPLATE); - Node basePathNode = proxyDefault.getElementsByTagName("BasePath").item(0); + String cors = "add-cors"; + String corsCondition = "request.verb == \"OPTIONS\""; - if (basePath != null && basePath.equalsIgnoreCase("") != true) { - basePathNode.setTextContent(basePath); - } + // Add policy to proxy.xml + Node policy1 = apiTemplateDocument.createElement("Policy"); + policy1.setTextContent(cors); + policies.appendChild(policy1); - Node httpProxyConnection = proxyDefault.getElementsByTagName("HTTPProxyConnection").item(0); - Node virtualHost = null; - for (String vHost : vHosts) { - virtualHost = proxyDefault.createElement("VirtualHost"); - virtualHost.setTextContent(vHost); - httpProxyConnection.appendChild(virtualHost); - } + flow = proxyDefault.createElement("Flow"); + ((Element) flow).setAttribute("name", "OptionsPreFlight"); - Document apiTemplateDocument = xmlUtils - .readXML(buildFolder + File.separator + "apiproxy" + File.separator + proxyName + ".xml"); + flowDescription = proxyDefault.createElement("Description"); + flowDescription.setTextContent("OptionsPreFlight"); + flow.appendChild(flowDescription); - Document extractTemplate = xmlUtils.readXML(SOAP2API_EXTRACT_TEMPLATE); + request = proxyDefault.createElement("Request"); + response = proxyDefault.createElement("Response"); + condition = proxyDefault.createElement("Condition"); - Document assignTemplate = xmlUtils.readXML(SOAP2API_ASSIGN_TEMPLATE); + step1 = proxyDefault.createElement("Step"); + name1 = proxyDefault.createElement("Name"); - Document returnOASTemplate = xmlUtils.readXML(SOAP2API_RETURN_OPENAPI_TEMPLATE); + name1.setTextContent(cors); + step1.appendChild(name1); - // Document jsPolicyTemplate = - // xmlUtils.readXML(SOAP2API_JSPOLICY_TEMPLATE); + response.appendChild(step1); - Document addNamespaceTemplate = null; - if (soapVersion.equalsIgnoreCase(SOAP_11)) { - addNamespaceTemplate = xmlUtils.readXML(SOAP2API_XSLT11POLICY_TEMPLATE); - } else { - addNamespaceTemplate = xmlUtils.readXML(SOAP2API_XSLT12POLICY_TEMPLATE); + condition.setTextContent(corsCondition); + + flow.appendChild(request); + flow.appendChild(response); + flow.appendChild(condition); + + flows.appendChild(flow); + } + + // open-api feature + flow = proxyDefault.createElement("Flow"); + ((Element) flow).setAttribute("name", "GetOAS"); + flowDescription = proxyDefault.createElement("Description"); + flowDescription.setTextContent("Get OpenAPI Specification"); + flow.appendChild(flowDescription); + request = proxyDefault.createElement("Request"); + response = proxyDefault.createElement("Response"); + condition = proxyDefault.createElement("Condition"); + condition.setTextContent("(proxy.pathsuffix MatchesPath \"/openapi.json\") and (request.verb = \"GET\")"); + step1 = proxyDefault.createElement("Step"); + name1 = proxyDefault.createElement("Name"); + name1.setTextContent("return-open-api"); + step1.appendChild(name1); + request.appendChild(step1); + flow.appendChild(request); + flow.appendChild(response); + flow.appendChild(condition); + flows.appendChild(flow); + + writeOAS(returnOASTemplate); + + for (Map.Entry entry : messageTemplates.entrySet()) { + String operationName = entry.getKey(); + APIMap apiMap = entry.getValue(); + String buildSOAPPolicy = operationName + "-build-soap"; + String extractPolicyName = operationName + "-extract-query-param"; + String jsonToXML = operationName + "-json-to-xml"; + // String jsPolicyName = operationName + "-root-wrapper"; + String jsonToXMLCondition = "(request.header.Content-Type == \"application/json\")"; + + String httpVerb = apiMap.getVerb(); + String resourcePath = apiMap.getResourcePath(); + String Condition = "(proxy.pathsuffix MatchesPath \"" + resourcePath + "\") and (request.verb = \"" + + httpVerb + "\")"; + String addSoapAction = operationName + "-add-soapaction"; + + flow = proxyDefault.createElement("Flow"); + ((Element) flow).setAttribute("name", operationName); + + flowDescription = proxyDefault.createElement("Description"); + flowDescription.setTextContent(operationName); + flow.appendChild(flowDescription); + + request = proxyDefault.createElement("Request"); + response = proxyDefault.createElement("Response"); + condition = proxyDefault.createElement("Condition"); + condition2 = proxyDefault.createElement("Condition"); + condition2.setTextContent(jsonToXMLCondition); + + step1 = proxyDefault.createElement("Step"); + name1 = proxyDefault.createElement("Name"); + + step2 = proxyDefault.createElement("Step"); + name2 = proxyDefault.createElement("Name"); + + step3 = proxyDefault.createElement("Step"); + name3 = proxyDefault.createElement("Name"); + + step4 = proxyDefault.createElement("Step"); + name4 = proxyDefault.createElement("Name"); + + step5 = proxyDefault.createElement("Step"); + name5 = proxyDefault.createElement("Name"); + + if (httpVerb.equalsIgnoreCase("get")) { + if (apiMap.getJsonBody() != null) { + name1.setTextContent(extractPolicyName); + step1.appendChild(name1); + request.appendChild(step1); } - Document jsonXMLTemplate = xmlUtils.readXML(SOAP2API_JSON_TO_XML_TEMPLATE); + step2 = proxyDefault.createElement("Step"); + name2 = proxyDefault.createElement("Name"); + name2.setTextContent(buildSOAPPolicy); + step2.appendChild(name2); + request.appendChild(step2); - Document addSoapActionTemplate = xmlUtils.readXML(SOAP2API_ADD_SOAPACTION_TEMPLATE); + if (apiMap.getJsonBody() != null) { + step3 = proxyDefault.createElement("Step"); + name3 = proxyDefault.createElement("Name"); + name3.setTextContent("remove-empty-nodes"); + Node condition3 = proxyDefault.createElement("Condition"); + condition3.setTextContent("(verb == \"GET\")"); + step3.appendChild(name3); + step3.appendChild(condition3); + request.appendChild(step3); + } - Node description = proxyDefault.getElementsByTagName("Description").item(0); - description.setTextContent(proxyDescription); + LOGGER.fine("Assign Message: " + buildSOAPPolicy); + LOGGER.fine("Extract Variable: " + extractPolicyName); - Node policies = apiTemplateDocument.getElementsByTagName("Policies").item(0); - Node resources = apiTemplateDocument.getElementsByTagName("Resources").item(0); + } else { + // add root wrapper policy + /* + * name3.setTextContent(jsPolicyName); step3.appendChild(name3); + * step3.appendChild(condition2.cloneNode(true)); + * request.appendChild(step3); + */ - Node flows = proxyDefault.getElementsByTagName("Flows").item(0); - Node flow; - Node flowDescription; - Node request; - Node response; - Node condition, condition2; - Node step1, step2, step3, step4, step5; - Node name1, name2, name3, name4, name5; - boolean once = false; + // add the root wrapper only once + /* + * if (!once) { Node resourceRootWrapper = + * apiTemplateDocument.createElement("Resource"); + * resourceRootWrapper.setTextContent("jsc://root-wrapper.js"); + * resources.appendChild(resourceRootWrapper); once = true; } + */ - // add oauth policies if set - if (OAUTH) { - String oauthPolicy = "verify-oauth-v2-access-token"; - String remoOAuthPolicy = "remove-header-authorization"; - String quota = "impose-quota-oauth"; - - // Add policy to proxy.xml - Node policy1 = apiTemplateDocument.createElement("Policy"); - policy1.setTextContent(oauthPolicy); - - Node policy2 = apiTemplateDocument.createElement("Policy"); - policy2.setTextContent(remoOAuthPolicy); - - policies.appendChild(policy1); - policies.appendChild(policy2); - - Node preFlowRequest = proxyDefault.getElementsByTagName("PreFlow").item(0).getChildNodes().item(1); - - step1 = proxyDefault.createElement("Step"); - name1 = proxyDefault.createElement("Name"); - name1.setTextContent(oauthPolicy); - step1.appendChild(name1); - - step2 = proxyDefault.createElement("Step"); - name2 = proxyDefault.createElement("Name"); - name2.setTextContent(remoOAuthPolicy); - step2.appendChild(name2); - - preFlowRequest.appendChild(step1); - preFlowRequest.appendChild(step2); - - if (QUOTAOAUTH) { - Node policy3 = apiTemplateDocument.createElement("Policy"); - policy2.setTextContent(quota); - policies.appendChild(policy3); - step3 = proxyDefault.createElement("Step"); - name3 = proxyDefault.createElement("Name"); - name3.setTextContent(quota); - step3.appendChild(name3); - preFlowRequest.appendChild(step3); - } - } + name1.setTextContent(jsonToXML); + step1.appendChild(name1); + step1.appendChild(condition2); + request.appendChild(step1); + // TODO: add condition here to convert to XML only if + // Content-Type is json; - if (APIKEY) { - String apiKeyPolicy = "verify-api-key"; - String remoAPIKeyPolicy = "remove-query-param-apikey"; - String quota = "impose-quota-apikey"; - - // Add policy to proxy.xml - Node policy1 = apiTemplateDocument.createElement("Policy"); - policy1.setTextContent(apiKeyPolicy); - - Node policy2 = apiTemplateDocument.createElement("Policy"); - policy2.setTextContent(remoAPIKeyPolicy); - - policies.appendChild(policy1); - policies.appendChild(policy2); - - Node preFlowRequest = proxyDefault.getElementsByTagName("PreFlow").item(0).getChildNodes().item(1); - - step1 = proxyDefault.createElement("Step"); - name1 = proxyDefault.createElement("Name"); - name1.setTextContent(apiKeyPolicy); - step1.appendChild(name1); - - step2 = proxyDefault.createElement("Step"); - name2 = proxyDefault.createElement("Name"); - name2.setTextContent(remoAPIKeyPolicy); - step2.appendChild(name2); - - preFlowRequest.appendChild(step1); - preFlowRequest.appendChild(step2); - - if (QUOTAAPIKEY) { - Node policy3 = apiTemplateDocument.createElement("Policy"); - policy2.setTextContent(quota); - policies.appendChild(policy3); - step3 = proxyDefault.createElement("Step"); - name3 = proxyDefault.createElement("Name"); - name3.setTextContent(quota); - step3.appendChild(name3); - preFlowRequest.appendChild(step3); - } + name2.setTextContent(operationName + "-add-namespace"); + step2.appendChild(name2); + request.appendChild(step2); + if (apiMap.getOthernamespaces()) { + name4.setTextContent(operationName + "-add-other-namespaces"); + step4.appendChild(name4); + request.appendChild(step4); } - if (CORS) { - Node proxyEndpoint = proxyDefault.getElementsByTagName("ProxyEndpoint").item(0); - Node routeRule = proxyDefault.createElement("RouteRule"); - ((Element) routeRule).setAttribute("name", "NoRoute"); + // for soap 1.1 add soap action + if (soapVersion.equalsIgnoreCase(SOAP_11)) { + step5 = proxyDefault.createElement("Step"); + name5 = proxyDefault.createElement("Name"); + name5.setTextContent(addSoapAction); + step5.appendChild(name5); + request.appendChild(step5); + } + + } - Node routeCondition = proxyDefault.createElement("Condition"); - routeCondition.setTextContent("request.verb == \"OPTIONS\""); - routeRule.appendChild(routeCondition); - proxyEndpoint.appendChild(routeRule); + LOGGER.fine("Condition: " + Condition); + condition.setTextContent(Condition); - String cors = "add-cors"; - String corsCondition = "request.verb == \"OPTIONS\""; + flow.appendChild(request); + flow.appendChild(response); + flow.appendChild(condition); - // Add policy to proxy.xml - Node policy1 = apiTemplateDocument.createElement("Policy"); - policy1.setTextContent(cors); - policies.appendChild(policy1); + flows.appendChild(flow); - flow = proxyDefault.createElement("Flow"); - ((Element) flow).setAttribute("name", "OptionsPreFlight"); + if (httpVerb.equalsIgnoreCase("get")) { + // Add policy to proxy.xml + if (apiMap.getJsonBody() != null) { + Node policy1 = apiTemplateDocument.createElement("Policy"); + policy1.setTextContent(extractPolicyName); + policies.appendChild(policy1); + // write Extract Variable Policy + writeSOAP2APIExtractPolicy(extractTemplate, operationName, extractPolicyName); + } + Node policy2 = apiTemplateDocument.createElement("Policy"); + policy2.setTextContent(buildSOAPPolicy); + policies.appendChild(policy2); + // write Assign Message Policy + writeSOAP2APIAssignMessagePolicies(assignTemplate, operationName, buildSOAPPolicy, + apiMap.getSoapAction()); + } else { + + /* + * Node policy2 = apiTemplateDocument.createElement("Policy"); + * policy2.setTextContent(jsPolicyName); + * policies.appendChild(policy2); + */ - flowDescription = proxyDefault.createElement("Description"); - flowDescription.setTextContent("OptionsPreFlight"); - flow.appendChild(flowDescription); + // writeRootWrapper(jsPolicyTemplate, operationName, + // apiMap.getRootElement()); - request = proxyDefault.createElement("Request"); - response = proxyDefault.createElement("Response"); - condition = proxyDefault.createElement("Condition"); + Node policy1 = apiTemplateDocument.createElement("Policy"); + policy1.setTextContent(jsonToXML); + policies.appendChild(policy1); - step1 = proxyDefault.createElement("Step"); - name1 = proxyDefault.createElement("Name"); + writeJsonToXMLPolicy(jsonXMLTemplate, operationName, apiMap.getRootElement()); - name1.setTextContent(cors); - step1.appendChild(name1); + Node policy3 = apiTemplateDocument.createElement("Policy"); + policy3.setTextContent(operationName + "add-namespace"); + policies.appendChild(policy3); + Node resourceAddNamespaces = apiTemplateDocument.createElement("Resource"); + resourceAddNamespaces.setTextContent("xsl://" + operationName + "add-namespace.xslt"); + resources.appendChild(resourceAddNamespaces); - response.appendChild(step1); + if (apiMap.getOthernamespaces()) { + Node policy4 = apiTemplateDocument.createElement("Policy"); + policy4.setTextContent(operationName + "add-other-namespaces"); - condition.setTextContent(corsCondition); + policies.appendChild(policy4); - flow.appendChild(request); - flow.appendChild(response); - flow.appendChild(condition); + Node resourceAddOtherNamespaces = apiTemplateDocument.createElement("Resource"); + resourceAddOtherNamespaces.setTextContent("xsl://" + operationName + "add-other-namespaces.xslt"); + resources.appendChild(resourceAddOtherNamespaces); - flows.appendChild(flow); + writeAddNamespace(addNamespaceTemplate, operationName, true); + } else { + writeAddNamespace(addNamespaceTemplate, operationName, false); + } + // for soap 1.1 add soap action + if (soapVersion.equalsIgnoreCase(SOAP_11)) { + // Add policy to proxy.xml + Node policy5 = apiTemplateDocument.createElement("Policy"); + policy5.setTextContent(addSoapAction); + policies.appendChild(policy5); + writeAddSoapAction(addSoapActionTemplate, operationName, apiMap.getSoapAction()); } + } + } - // open-api feature - flow = proxyDefault.createElement("Flow"); - ((Element) flow).setAttribute("name", "GetOAS"); - flowDescription = proxyDefault.createElement("Description"); - flowDescription.setTextContent("Get OpenAPI Specification"); - flow.appendChild(flowDescription); - request = proxyDefault.createElement("Request"); - response = proxyDefault.createElement("Response"); - condition = proxyDefault.createElement("Condition"); - condition.setTextContent("(proxy.pathsuffix MatchesPath \"/openapi.json\") and (request.verb = \"GET\")"); - step1 = proxyDefault.createElement("Step"); - name1 = proxyDefault.createElement("Name"); - name1.setTextContent("return-open-api"); - step1.appendChild(name1); - request.appendChild(step1); - flow.appendChild(request); - flow.appendChild(response); - flow.appendChild(condition); - flows.appendChild(flow); - - writeOAS(returnOASTemplate); - - for (Map.Entry entry : messageTemplates.entrySet()) { - String operationName = entry.getKey(); - APIMap apiMap = entry.getValue(); - String buildSOAPPolicy = operationName + "-build-soap"; - String extractPolicyName = operationName + "-extract-query-param"; - String jsonToXML = operationName + "-json-to-xml"; - // String jsPolicyName = operationName + "-root-wrapper"; - String jsonToXMLCondition = "(request.header.Content-Type == \"application/json\")"; - - String httpVerb = apiMap.getVerb(); - String resourcePath = apiMap.getResourcePath(); - String Condition = "(proxy.pathsuffix MatchesPath \"" + resourcePath + "\") and (request.verb = \"" - + httpVerb + "\")"; - String addSoapAction = operationName + "-add-soapaction"; - - flow = proxyDefault.createElement("Flow"); - ((Element) flow).setAttribute("name", operationName); - - flowDescription = proxyDefault.createElement("Description"); - flowDescription.setTextContent(operationName); - flow.appendChild(flowDescription); - - request = proxyDefault.createElement("Request"); - response = proxyDefault.createElement("Response"); - condition = proxyDefault.createElement("Condition"); - condition2 = proxyDefault.createElement("Condition"); - condition2.setTextContent(jsonToXMLCondition); - - step1 = proxyDefault.createElement("Step"); - name1 = proxyDefault.createElement("Name"); - - step2 = proxyDefault.createElement("Step"); - name2 = proxyDefault.createElement("Name"); - - step3 = proxyDefault.createElement("Step"); - name3 = proxyDefault.createElement("Name"); - - step4 = proxyDefault.createElement("Step"); - name4 = proxyDefault.createElement("Name"); - - step5 = proxyDefault.createElement("Step"); - name5 = proxyDefault.createElement("Name"); - - if (httpVerb.equalsIgnoreCase("get")) { - if (apiMap.getJsonBody() != null) { - name1.setTextContent(extractPolicyName); - step1.appendChild(name1); - request.appendChild(step1); - } + // Add unknown resource + flow = proxyDefault.createElement("Flow"); + ((Element) flow).setAttribute("name", "unknown-resource"); - step2 = proxyDefault.createElement("Step"); - name2 = proxyDefault.createElement("Name"); - name2.setTextContent(buildSOAPPolicy); - step2.appendChild(name2); - request.appendChild(step2); - - if (apiMap.getJsonBody() != null) { - step3 = proxyDefault.createElement("Step"); - name3 = proxyDefault.createElement("Name"); - name3.setTextContent("remove-empty-nodes"); - Node condition3 = proxyDefault.createElement("Condition"); - condition3.setTextContent("(verb == \"GET\")"); - step3.appendChild(name3); - step3.appendChild(condition3); - request.appendChild(step3); - } + flowDescription = proxyDefault.createElement("Description"); + flowDescription.setTextContent("Unknown Resource"); + flow.appendChild(flowDescription); - LOGGER.fine("Assign Message: " + buildSOAPPolicy); - LOGGER.fine("Extract Variable: " + extractPolicyName); + request = proxyDefault.createElement("Request"); + response = proxyDefault.createElement("Response"); + condition = proxyDefault.createElement("Condition"); - } else { - // add root wrapper policy - /* - * name3.setTextContent(jsPolicyName); step3.appendChild(name3); - * step3.appendChild(condition2.cloneNode(true)); - * request.appendChild(step3); - */ - - // add the root wrapper only once - /* - * if (!once) { Node resourceRootWrapper = - * apiTemplateDocument.createElement("Resource"); - * resourceRootWrapper.setTextContent("jsc://root-wrapper.js"); - * resources.appendChild(resourceRootWrapper); once = true; } - */ - - name1.setTextContent(jsonToXML); - step1.appendChild(name1); - step1.appendChild(condition2); - request.appendChild(step1); - // TODO: add condition here to convert to XML only if - // Content-Type is json; - - name2.setTextContent(operationName + "-add-namespace"); - step2.appendChild(name2); - request.appendChild(step2); - - if (apiMap.getOthernamespaces()) { - name4.setTextContent(operationName + "-add-other-namespaces"); - step4.appendChild(name4); - request.appendChild(step4); - } + Node conditionA = proxyDefault.createElement("Condition"); + conditionA.setTextContent( + "(verb != \"GET\" AND contentformat == \"application/json\") OR (verb == \"GET\" AND acceptformat !~ \"*/xml\")"); + Node conditionB = proxyDefault.createElement("Condition"); + conditionB.setTextContent( + "(verb != \"GET\" AND contentformat != \"application/json\") OR (verb == \"GET\" AND acceptformat ~ \"*/xml\")"); - // for soap 1.1 add soap action - if (soapVersion.equalsIgnoreCase(SOAP_11)) { - step5 = proxyDefault.createElement("Step"); - name5 = proxyDefault.createElement("Name"); - name5.setTextContent(addSoapAction); - step5.appendChild(name5); - request.appendChild(step5); - } + step1 = proxyDefault.createElement("Step"); + name1 = proxyDefault.createElement("Name"); + name1.setTextContent("unknown-resource"); + step1.appendChild(name1); + step1.appendChild(conditionA);// added + request.appendChild(step1); - } + step2 = proxyDefault.createElement("Step"); + name2 = proxyDefault.createElement("Name"); + name2.setTextContent("unknown-resource-xml"); + step2.appendChild(name2); + step2.appendChild(conditionB); + request.appendChild(step2); - LOGGER.fine("Condition: " + Condition); - condition.setTextContent(Condition); + flow.appendChild(request); + flow.appendChild(response); + flow.appendChild(condition); - flow.appendChild(request); - flow.appendChild(response); - flow.appendChild(condition); + flows.appendChild(flow); - flows.appendChild(flow); + LOGGER.fine( + "Edited proxy xml: " + buildFolder + File.separator + "apiproxy" + File.separator + proxyName + ".xml"); + xmlUtils.writeXML(apiTemplateDocument, + buildFolder + File.separator + "apiproxy" + File.separator + proxyName + ".xml"); - if (httpVerb.equalsIgnoreCase("get")) { - // Add policy to proxy.xml - if (apiMap.getJsonBody() != null) { - Node policy1 = apiTemplateDocument.createElement("Policy"); - policy1.setTextContent(extractPolicyName); - policies.appendChild(policy1); - // write Extract Variable Policy - writeSOAP2APIExtractPolicy(extractTemplate, operationName, extractPolicyName); - } - Node policy2 = apiTemplateDocument.createElement("Policy"); - policy2.setTextContent(buildSOAPPolicy); - policies.appendChild(policy2); - // write Assign Message Policy - writeSOAP2APIAssignMessagePolicies(assignTemplate, operationName, buildSOAPPolicy, - apiMap.getSoapAction()); - } else { + xmlUtils.writeXML(proxyDefault, buildFolder + File.separator + "apiproxy" + File.separator + "proxies" + + File.separator + "default.xml"); + LOGGER.fine("Edited target xml: " + buildFolder + File.separator + "apiproxy" + File.separator + "proxies" + + File.separator + "default.xml"); + LOGGER.exiting(CLASS_NAME, new Object() {}.getClass().getEnclosingMethod().getName()); + } - /* - * Node policy2 = apiTemplateDocument.createElement("Policy"); - * policy2.setTextContent(jsPolicyName); - * policies.appendChild(policy2); - */ + private void writeOAS(Document returnOpenApiTemplate) throws Exception { + LOGGER.entering(CLASS_NAME, new Object() {}.getClass().getEnclosingMethod().getName()); - // writeRootWrapper(jsPolicyTemplate, operationName, - // apiMap.getRootElement()); + String targetPath = buildFolder + File.separator + "apiproxy" + File.separator + "policies" + File.separator; + XMLUtils xmlUtils = new XMLUtils(); + Document returnOASXML = xmlUtils.cloneDocument(returnOpenApiTemplate); - Node policy1 = apiTemplateDocument.createElement("Policy"); - policy1.setTextContent(jsonToXML); - policies.appendChild(policy1); + Node payload = returnOASXML.getElementsByTagName("Payload").item(0); + payload.setTextContent(oasContent); - writeJsonToXMLPolicy(jsonXMLTemplate, operationName, apiMap.getRootElement()); + xmlUtils.writeXML(returnOASXML, targetPath + "return-open-api.xml"); - Node policy3 = apiTemplateDocument.createElement("Policy"); - policy3.setTextContent(operationName + "add-namespace"); - policies.appendChild(policy3); - Node resourceAddNamespaces = apiTemplateDocument.createElement("Resource"); - resourceAddNamespaces.setTextContent("xsl://" + operationName + "add-namespace.xslt"); - resources.appendChild(resourceAddNamespaces); + LOGGER.exiting(CLASS_NAME, new Object() {}.getClass().getEnclosingMethod().getName()); + } - if (apiMap.getOthernamespaces()) { - Node policy4 = apiTemplateDocument.createElement("Policy"); - policy4.setTextContent(operationName + "add-other-namespaces"); + private void writeRootWrapper(Document rootWrapperTemplate, String operationName, String rootElement) + throws Exception { + LOGGER.entering(CLASS_NAME, new Object() {}.getClass().getEnclosingMethod().getName()); - policies.appendChild(policy4); + String targetPath = buildFolder + File.separator + "apiproxy" + File.separator + "policies" + File.separator; - Node resourceAddOtherNamespaces = apiTemplateDocument.createElement("Resource"); - resourceAddOtherNamespaces.setTextContent("xsl://" + operationName + "add-other-namespaces.xslt"); - resources.appendChild(resourceAddOtherNamespaces); + XMLUtils xmlUtils = new XMLUtils(); + Document jsPolicyXML = xmlUtils.cloneDocument(rootWrapperTemplate); - writeAddNamespace(addNamespaceTemplate, operationName, true); - } else { - writeAddNamespace(addNamespaceTemplate, operationName, false); - } - // for soap 1.1 add soap action - if (soapVersion.equalsIgnoreCase(SOAP_11)) { - // Add policy to proxy.xml - Node policy5 = apiTemplateDocument.createElement("Policy"); - policy5.setTextContent(addSoapAction); - policies.appendChild(policy5); - writeAddSoapAction(addSoapActionTemplate, operationName, apiMap.getSoapAction()); - } - } - } + Node root = jsPolicyXML.getFirstChild(); + NamedNodeMap attr = root.getAttributes(); + Node nodeAttr = attr.getNamedItem("name"); + nodeAttr.setNodeValue(operationName + "-root-wrapper"); - // Add unknown resource - flow = proxyDefault.createElement("Flow"); - ((Element) flow).setAttribute("name", "unknown-resource"); + Node displayName = jsPolicyXML.getElementsByTagName("DisplayName").item(0); + displayName.setTextContent(operationName + " Root Wrapper"); - flowDescription = proxyDefault.createElement("Description"); - flowDescription.setTextContent("Unknown Resource"); - flow.appendChild(flowDescription); + Node propertyElement = jsPolicyXML.getElementsByTagName("Property").item(0); + propertyElement.setTextContent(rootElement); - request = proxyDefault.createElement("Request"); - response = proxyDefault.createElement("Response"); - condition = proxyDefault.createElement("Condition"); + xmlUtils.writeXML(jsPolicyXML, targetPath + operationName + "-root-wrapper.xml"); - Node conditionA = proxyDefault.createElement("Condition"); - conditionA.setTextContent( - "(verb != \"GET\" AND contentformat == \"application/json\") OR (verb == \"GET\" AND acceptformat !~ \"*/xml\")"); - Node conditionB = proxyDefault.createElement("Condition"); - conditionB.setTextContent( - "(verb != \"GET\" AND contentformat != \"application/json\") OR (verb == \"GET\" AND acceptformat ~ \"*/xml\")"); + LOGGER.exiting(CLASS_NAME, new Object() {}.getClass().getEnclosingMethod().getName()); + } - step1 = proxyDefault.createElement("Step"); - name1 = proxyDefault.createElement("Name"); - name1.setTextContent("unknown-resource"); - step1.appendChild(name1); - step1.appendChild(conditionA);// added - request.appendChild(step1); + private void writeAddSoapAction(Document addSoapActionTemplate, String operationName, String soapAction) + throws Exception { + LOGGER.entering(CLASS_NAME, new Object() {}.getClass().getEnclosingMethod().getName()); + try { + XMLUtils xmlUtils = new XMLUtils(); + String policyName = operationName + "-add-soapaction"; + Document soapActionPolicyXML = xmlUtils.cloneDocument(addSoapActionTemplate); - step2 = proxyDefault.createElement("Step"); - name2 = proxyDefault.createElement("Name"); - name2.setTextContent("unknown-resource-xml"); - step2.appendChild(name2); - step2.appendChild(conditionB); - request.appendChild(step2); + Node rootElement = soapActionPolicyXML.getFirstChild(); + NamedNodeMap attr = rootElement.getAttributes(); + Node nodeAttr = attr.getNamedItem("name"); + nodeAttr.setNodeValue(policyName); - flow.appendChild(request); - flow.appendChild(response); - flow.appendChild(condition); + Node displayName = soapActionPolicyXML.getElementsByTagName("DisplayName").item(0); + displayName.setTextContent(operationName + " Add SOAPAction"); - flows.appendChild(flow); + Node header = soapActionPolicyXML.getElementsByTagName("Header").item(0); + header.setTextContent(soapAction); - LOGGER.fine( - "Edited proxy xml: " + buildFolder + File.separator + "apiproxy" + File.separator + proxyName + ".xml"); - xmlUtils.writeXML(apiTemplateDocument, - buildFolder + File.separator + "apiproxy" + File.separator + proxyName + ".xml"); + xmlUtils.writeXML(soapActionPolicyXML, buildFolder + File.separator + "apiproxy" + File.separator + + "policies" + File.separator + policyName + ".xml"); - xmlUtils.writeXML(proxyDefault, buildFolder + File.separator + "apiproxy" + File.separator + "proxies" - + File.separator + "default.xml"); - LOGGER.fine("Edited target xml: " + buildFolder + File.separator + "apiproxy" + File.separator + "proxies" - + File.separator + "default.xml"); - LOGGER.exiting(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); + } catch (Exception e) { + e.printStackTrace(); + throw e; } + LOGGER.exiting(CLASS_NAME, new Object() { }.getClass().getEnclosingMethod().getName()); + } - private void writeOAS(Document returnOpenApiTemplate) throws Exception { - LOGGER.entering(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - - String targetPath = buildFolder + File.separator + "apiproxy" + File.separator + "policies" + File.separator; - XMLUtils xmlUtils = new XMLUtils(); - Document returnOASXML = xmlUtils.cloneDocument(returnOpenApiTemplate); + private void writeAddNamespace(Document namespaceTemplate, String operationName, boolean addOtherNamespaces) + throws Exception { - Node payload = returnOASXML.getElementsByTagName("Payload").item(0); - payload.setTextContent(oasContent); + LOGGER.entering(CLASS_NAME, new Object() { }.getClass().getEnclosingMethod().getName()); + try { + XMLUtils xmlUtils = new XMLUtils(); + String policyName = operationName + "-add-namespace"; + Document xslPolicyXML = xmlUtils.cloneDocument(namespaceTemplate); - xmlUtils.writeXML(returnOASXML, targetPath + "return-open-api.xml"); + Node rootElement = xslPolicyXML.getFirstChild(); + NamedNodeMap attr = rootElement.getAttributes(); + Node nodeAttr = attr.getNamedItem("name"); + nodeAttr.setNodeValue(policyName); - LOGGER.exiting(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - } + Node displayName = xslPolicyXML.getElementsByTagName("DisplayName").item(0); + displayName.setTextContent(operationName + " Add Namespace"); - private void writeRootWrapper(Document rootWrapperTemplate, String operationName, String rootElement) - throws Exception { - LOGGER.entering(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); + Node resourceURL = xslPolicyXML.getElementsByTagName("ResourceURL").item(0); + resourceURL.setTextContent("xsl://" + policyName + ".xslt"); - String targetPath = buildFolder + File.separator + "apiproxy" + File.separator + "policies" + File.separator; + xmlUtils.writeXML(xslPolicyXML, buildFolder + File.separator + "apiproxy" + File.separator + "policies" + + File.separator + policyName + ".xml"); - XMLUtils xmlUtils = new XMLUtils(); - Document jsPolicyXML = xmlUtils.cloneDocument(rootWrapperTemplate); + if (addOtherNamespaces) { + String policyNameOther = operationName + "-add-other-namespaces"; + Document xslPolicyXMLOther = xmlUtils.cloneDocument(namespaceTemplate); - Node root = jsPolicyXML.getFirstChild(); - NamedNodeMap attr = root.getAttributes(); - Node nodeAttr = attr.getNamedItem("name"); - nodeAttr.setNodeValue(operationName + "-root-wrapper"); + Node rootElementOther = xslPolicyXMLOther.getFirstChild(); + NamedNodeMap attrOther = rootElementOther.getAttributes(); + Node nodeAttrOther = attrOther.getNamedItem("name"); + nodeAttrOther.setNodeValue(policyNameOther); - Node displayName = jsPolicyXML.getElementsByTagName("DisplayName").item(0); - displayName.setTextContent(operationName + " Root Wrapper"); + Node displayNameOther = xslPolicyXMLOther.getElementsByTagName("DisplayName").item(0); + displayNameOther.setTextContent(operationName + " Add Other Namespaces"); - Node propertyElement = jsPolicyXML.getElementsByTagName("Property").item(0); - propertyElement.setTextContent(rootElement); + Node resourceURLOther = xslPolicyXMLOther.getElementsByTagName("ResourceURL").item(0); + resourceURLOther.setTextContent("xsl://" + policyNameOther + ".xslt"); - xmlUtils.writeXML(jsPolicyXML, targetPath + operationName + "-root-wrapper.xml"); + xmlUtils.writeXML(xslPolicyXMLOther, buildFolder + File.separator + "apiproxy" + File.separator + + "policies" + File.separator + policyNameOther + ".xml"); + } - LOGGER.exiting(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); + } catch (Exception e) { + e.printStackTrace(); + throw e; } - private void writeAddSoapAction(Document addSoapActionTemplate, String operationName, String soapAction) - throws Exception { - LOGGER.entering(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - try { - XMLUtils xmlUtils = new XMLUtils(); - String policyName = operationName + "-add-soapaction"; - Document soapActionPolicyXML = xmlUtils.cloneDocument(addSoapActionTemplate); + LOGGER.exiting(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); + } - Node rootElement = soapActionPolicyXML.getFirstChild(); - NamedNodeMap attr = rootElement.getAttributes(); - Node nodeAttr = attr.getNamedItem("name"); - nodeAttr.setNodeValue(policyName); + private void writeSOAP2APIExtractPolicy(Document extractTemplate, String operationName, String policyName) + throws Exception { - Node displayName = soapActionPolicyXML.getElementsByTagName("DisplayName").item(0); - displayName.setTextContent(operationName + " Add SOAPAction"); + LOGGER.entering(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); + XMLUtils xmlUtils = new XMLUtils(); - Node header = soapActionPolicyXML.getElementsByTagName("Header").item(0); - header.setTextContent(soapAction); + Element queryParam; + Element pattern; - xmlUtils.writeXML(soapActionPolicyXML, buildFolder + File.separator + "apiproxy" + File.separator - + "policies" + File.separator + policyName + ".xml"); + Document extractPolicyXML = xmlUtils.cloneDocument(extractTemplate); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - LOGGER.exiting(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); + Node rootElement = extractPolicyXML.getFirstChild(); + NamedNodeMap attr = rootElement.getAttributes(); + Node nodeAttr = attr.getNamedItem("name"); + nodeAttr.setNodeValue(policyName); + + Node displayName = extractPolicyXML.getElementsByTagName("DisplayName").item(0); + displayName.setTextContent(operationName + " Extract Query Param"); + + APIMap apiMap = messageTemplates.get(operationName); + + // edgeui-654 + if (apiMap.getSoapBody().getBytes().length < 4096) { + List elementList = xmlUtils.getElementList(apiMap.getSoapBody()); + for (String elementName : elementList) { + queryParam = extractPolicyXML.createElement("QueryParam"); + queryParam.setAttribute("name", getQueryParamName(elementName)); + + pattern = extractPolicyXML.createElement("Pattern"); + pattern.setAttribute("ignoreCase", "true"); + pattern.setTextContent("{" + elementName + "}"); + + queryParam.appendChild(pattern); + rootElement.appendChild(queryParam); + } + } else { + // setting a sample query param;edgeui-654 + LOGGER.warning("Large SOAP Message Template; Skipping extract policy"); + queryParam = extractPolicyXML.createElement("QueryParam"); + queryParam.setAttribute("name", "sample"); + + pattern = extractPolicyXML.createElement("Pattern"); + pattern.setAttribute("ignoreCase", "true"); + pattern.setTextContent("{sample}"); + + queryParam.appendChild(pattern); + rootElement.appendChild(queryParam); } - private void writeAddNamespace(Document namespaceTemplate, String operationName, boolean addOtherNamespaces) - throws Exception { + xmlUtils.writeXML(extractPolicyXML, buildFolder + File.separator + "apiproxy" + File.separator + "policies" + + File.separator + policyName + ".xml"); + LOGGER.exiting(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); + } - LOGGER.entering(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - try { - XMLUtils xmlUtils = new XMLUtils(); - String policyName = operationName + "-add-namespace"; - Document xslPolicyXML = xmlUtils.cloneDocument(namespaceTemplate); + // EDGEUI-672 + private String replaceReservedVariables(String xmlPayload) { + final String findOrg = "organization>\\{organization\\}{org} elementList = xmlUtils.getElementList(apiMap.getSoapBody()); - for (String elementName : elementList) { - queryParam = extractPolicyXML.createElement("QueryParam"); - queryParam.setAttribute("name", getQueryParamName(elementName)); + Node soapCondition = proxyDefault.getElementsByTagName("Condition").item(2); + if (soapVersion.equalsIgnoreCase(SOAP_11)) { + soapCondition.setTextContent(soapConditionText + SOAP11 + "\")) and (request.verb != \"GET\")"); + } else { + soapCondition.setTextContent(soapConditionText + SOAP12 + "\")) and (request.verb != \"GET\")"); + } - pattern = extractPolicyXML.createElement("Pattern"); - pattern.setAttribute("ignoreCase", "true"); - pattern.setTextContent("{" + elementName + "}"); + String conditionText = "(proxy.pathsuffix MatchesPath \"/\") and (request.verb = \"POST\") and (operation = \""; + Node flows = proxyDefault.getElementsByTagName("Flows").item(0); + Node flow; + Node flowDescription; + Node request; + Node response; + Node condition; + Node step1; + Node name1; - queryParam.appendChild(pattern); - rootElement.appendChild(queryParam); - } - } else { - // setting a sample query param;edgeui-654 - LOGGER.warning("Large SOAP Message Template; Skipping extract policy"); - queryParam = extractPolicyXML.createElement("QueryParam"); - queryParam.setAttribute("name", "sample"); + for (Map.Entry entry : messageTemplates.entrySet()) { - pattern = extractPolicyXML.createElement("Pattern"); - pattern.setAttribute("ignoreCase", "true"); - pattern.setTextContent("{sample}"); + String operationName = entry.getKey(); + APIMap apiMap = entry.getValue(); - queryParam.appendChild(pattern); - rootElement.appendChild(queryParam); - } + flow = proxyDefault.createElement("Flow"); + ((Element) flow).setAttribute("name", operationName); - xmlUtils.writeXML(extractPolicyXML, buildFolder + File.separator + "apiproxy" + File.separator + "policies" - + File.separator + policyName + ".xml"); - LOGGER.exiting(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - } + flowDescription = proxyDefault.createElement("Description"); + flowDescription.setTextContent(operationName); + flow.appendChild(flowDescription); - // EDGEUI-672 - private String replaceReservedVariables(String xmlPayload) { - final String findOrg = "organization>\\{organization\\}{org} entry : namespace.entrySet()) { + if (entry.getKey().equalsIgnoreCase(prefix)) { + return entry.getValue(); + } + } + LOGGER.exiting(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); + return null; + } + + public String getPrefix(String namespaceUri) { + LOGGER.entering(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); + for (Map.Entry entry : namespace.entrySet()) { + if (entry.getValue().equalsIgnoreCase(namespaceUri)) { + if (entry.getKey().length() == 0) { + return "ns"; + } else { + return entry.getKey(); + } + } + } + LOGGER.exiting(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); + return "ns"; + } + + private void parseElement(com.predic8.schema.Element e, List schemas, JsonObject parent, + String parentName) { + if (e.getName() == null) { + if (e.getRef() != null) { + final String localPart = e.getRef().getLocalPart(); + final com.predic8.schema.Element element = elementFromSchema(localPart, schemas); + JsonObject complexType = OASUtils.createComplexType(element.getName(), element.getMinOccurs(), + element.getMaxOccurs()); + OASUtils.addObject(parent, parentName, element.getName()); + definitions.add(element.getName(), complexType); + parseSchema(element, schemas, element.getName(), complexType); + } else { + // TODO: handle this + LOGGER.warning("unhandle conditions getRef() = null"); + } + } else { + if (e.getEmbeddedType() instanceof ComplexType) { + ComplexType ct = (ComplexType) e.getEmbeddedType(); + JsonObject rootElement = OASUtils.createComplexType(e.getName(), e.getMinOccurs(), e.getMaxOccurs()); + OASUtils.addObject(parent, parentName, e.getName()); + definitions.add(e.getName(), rootElement); + parseSchema(ct.getModel(), schemas, e.getName(), rootElement); + } else if (e.getType() != null) { + TypeDefinition typeDefinition = getTypeFromSchema(e.getType(), schemas); + if (typeDefinition instanceof ComplexType) { + ComplexType ct = (ComplexType) typeDefinition; + JsonObject rootElement = OASUtils.createComplexType(e.getName(), e.getMinOccurs(), + e.getMaxOccurs()); + OASUtils.addObject(parent, parentName, e.getName()); + definitions.add(e.getName(), rootElement); + parseSchema(ct.getModel(), schemas, e.getName(), rootElement); + } + } + } + } + + private void parseElement(com.predic8.schema.Element e, List schemas, String rootElement, + String rootNamespace, String rootPrefix) { + if (e.getName() == null) { + if (e.getRef() != null) { + final String localPart = e.getRef().getLocalPart(); + final com.predic8.schema.Element element = elementFromSchema(localPart, schemas); + parseSchema(element, schemas, rootElement, rootNamespace, rootPrefix); + } else { + // fail silently + LOGGER.warning("unhandled conditions getRef() = null"); + } + } else { + if (!e.getName().equalsIgnoreCase(rootElement)) { + if (e.getEmbeddedType() instanceof ComplexType) { + ComplexType ct = (ComplexType) e.getEmbeddedType(); + if (!e.getNamespaceUri().equalsIgnoreCase(rootNamespace)) { + buildXPath(e, rootElement, rootNamespace, rootPrefix); + } + parseSchema(ct.getModel(), schemas, rootElement, rootNamespace, rootPrefix); + } else { + if (e.getType() != null) { + if (!getParentNamepace(e).equalsIgnoreCase(rootNamespace) + && !e.getType().getNamespaceURI().equalsIgnoreCase(rootNamespace)) { + buildXPath(e, rootElement, rootNamespace, rootPrefix); + } + TypeDefinition typeDefinition = getTypeFromSchema(e.getType(), schemas); + if (typeDefinition instanceof ComplexType) { + parseSchema(((ComplexType) typeDefinition).getModel(), schemas, rootElement, rootNamespace, + rootPrefix); + } + } else { + // handle this as anyType + buildXPath(e, rootElement, rootNamespace, rootPrefix, true); + if (!getParentNamepace(e).equalsIgnoreCase(rootNamespace)) { + buildXPath(e, rootElement, rootNamespace, rootPrefix); + } + LOGGER.warning("Found element " + e.getName() + " with no type. Handling as xsd:anyType"); - LOGGER.entering(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - XMLUtils xmlUtils = new XMLUtils(); - Document targetDefault; + } + } + } + } + } - if (PASSTHRU) { - targetDefault = xmlUtils.readXML(SOAPPASSTHRU_TARGET_TEMPLATE); + private com.predic8.schema.Element elementFromSchema(String name, List schemas) { + if (name != null) { + for (Schema schema : schemas) { + try { + final com.predic8.schema.Element element = schema.getElement(name); + if (element != null) { + return element; + } + } catch (Exception e) { + LOGGER.warning("unhandled conditions: " + e.getMessage()); + } + } + } + return null; + } + + private void parseSchema(SchemaComponent sc, List schemas, String rootElementName, JsonObject rootElement) { + + // fail safe measure. + if (Thread.currentThread().getStackTrace().length >= 128) { + TOO_MANY = true; + return; + } else if (TOO_MANY) + return; + else if (sc instanceof Sequence) { + Sequence seq = (Sequence) sc; + for (com.predic8.schema.Element e : seq.getElements()) { + if (e.getType() != null) { + if (isPrimitive(e.getType().getLocalPart())) { + if (rootElement == null) { + rootElement = OASUtils.createComplexType(e.getName(), e.getMinOccurs(), e.getMaxOccurs()); + rootElementName = e.getName(); + definitions.add(e.getName(), rootElement); + } + JsonObject properties = rootElement.getAsJsonObject("properties"); + properties.add(e.getName(), OASUtils.createSimpleType(e.getType().getLocalPart(), + e.getMinOccurs(), e.getMaxOccurs())); + queryParams.add(e.getName()); + } else { + parseElement(e, schemas, rootElement, rootElementName); + } + } else { + parseElement(e, schemas, rootElement, rootElementName); + } + } + } else if (sc instanceof Choice) { + Choice ch = (Choice) sc; + for (com.predic8.schema.Element e : ch.getElements()) { + if (e.getType() != null) { + if (isPrimitive(e.getType().getLocalPart())) { + if (rootElement == null) { + rootElement = OASUtils.createComplexType(e.getName(), e.getMinOccurs(), e.getMaxOccurs()); + rootElementName = e.getName(); + definitions.add(e.getName(), rootElement); + } + JsonObject properties = rootElement.getAsJsonObject("properties"); + properties.add(e.getName(), OASUtils.createSimpleType(e.getType().getLocalPart(), + e.getMinOccurs(), e.getMaxOccurs())); + queryParams.add(e.getName()); + } + } else { + parseElement(e, schemas, rootElement, rootElementName); + } + } + } else if (sc instanceof ComplexContent) { + ComplexContent complexContent = (ComplexContent) sc; + Derivation derivation = complexContent.getDerivation(); + + if (derivation != null) { + TypeDefinition typeDefinition = getTypeFromSchema(derivation.getBase(), schemas); + if (typeDefinition instanceof ComplexType) { + String name = ((ComplexType) typeDefinition).getName(); + JsonObject complexType = OASUtils.createComplexType(name, "0", "1"); + parseSchema(((ComplexType) typeDefinition).getModel(), schemas, name, complexType); + definitions.add(name, complexType); + } + } + } else if (sc instanceof SimpleContent) { + SimpleContent simpleContent = (SimpleContent) sc; + Derivation derivation = (Derivation) simpleContent.getDerivation(); + + JsonObject properties = rootElement.getAsJsonObject("properties"); + + if (derivation.getAllAttributes().size() > 0) { + // has attributes + for (Attribute attribute : derivation.getAllAttributes()) { + properties.add("@" + attribute.getName(), OASUtils.createSimpleType("string", "0", "1")); + } + } + } else if (sc instanceof com.predic8.schema.Element) { + parseElement((com.predic8.schema.Element) sc, schemas, rootElement, rootElementName); + } else if (sc instanceof All) { + All all = (All) sc; + for (com.predic8.schema.Element e : all.getElements()) { + parseElement(e, schemas, rootElement, rootElementName); + } + } + } + + private void parseSchema(SchemaComponent sc, List schemas, String rootElement, String rootNamespace, + String rootPrefix) { + + LOGGER.entering(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); + + // fail safe measures. + if (Thread.currentThread().getStackTrace().length >= 128) {// edgeui-654 + TOO_MANY = true; + return; + } + + else if (TOO_MANY) + return;// edgeui-654 + + else if (ruleList.size() >= 100) { + // the rules are too big. clear the rules. + TOO_MANY = true; + return; + } else if (sc instanceof Sequence) { + Sequence seq = (Sequence) sc; + level++; + for (com.predic8.schema.Element e : seq.getElements()) { + if (e.getName() == null) + level--; + if (e.getName() != null) { + xpathElement.put(level, e.getName()); + if (e.getType() != null) { + if (e.getType().getLocalPart().equalsIgnoreCase("anyType")) { + // found a anyType. remove namespaces for + // descendents + buildXPath(e, rootElement, rootNamespace, rootPrefix, true); + } + } + } + parseElement(e, schemas, rootElement, rootNamespace, rootPrefix); + } + level--; + cleanUpXPath(); + } else if (sc instanceof Choice) { + Choice ch = (Choice) sc; + level++; + for (com.predic8.schema.Element e : ch.getElements()) { + if (!e.getName().equalsIgnoreCase(rootElement)) { + if (e.getEmbeddedType() instanceof ComplexType) { + ComplexType ct = (ComplexType) e.getEmbeddedType(); + xpathElement.put(level, e.getName()); + parseSchema(ct.getModel(), schemas, rootElement, rootNamespace, rootPrefix); + } else { + final TypeDefinition typeDefinition = getTypeFromSchema(e.getType(), schemas); + if (typeDefinition instanceof ComplexType) { + xpathElement.put(level, e.getName()); + parseSchema(((ComplexType) typeDefinition).getModel(), schemas, rootElement, rootNamespace, + rootPrefix); + } + if (e.getType() == null) { + // handle this any anyType + buildXPath(e, rootElement, rootNamespace, rootPrefix, true); + LOGGER.warning("Element " + e.getName() + " type was null; treating as anyType"); + } else if (!getParentNamepace(e).equalsIgnoreCase(rootNamespace) + && !e.getType().getNamespaceURI().equalsIgnoreCase(rootNamespace)) { + buildXPath(e, rootElement, rootNamespace, rootPrefix); + } else if (e.getType().getLocalPart().equalsIgnoreCase("anyType")) { + // if you find a anyType, remove namespace for the + // descendents. + buildXPath(e, rootElement, rootNamespace, rootPrefix, true); + } + } + } + } + level--; + cleanUpXPath(); + } else if (sc instanceof ComplexContent) { + ComplexContent complexContent = (ComplexContent) sc; + Derivation derivation = complexContent.getDerivation(); + + if (derivation != null) { + TypeDefinition typeDefinition = getTypeFromSchema(derivation.getBase(), schemas); + if (typeDefinition instanceof ComplexType) { + parseSchema(((ComplexType) typeDefinition).getModel(), schemas, rootElement, rootNamespace, + rootPrefix); + } + if (derivation.getModel() instanceof Sequence) { + parseSchema(derivation.getModel(), schemas, rootElement, rootNamespace, rootPrefix); + } else if (derivation.getModel() instanceof ModelGroup) { + parseSchema(derivation.getModel(), schemas, rootElement, rootNamespace, rootPrefix); + } + } + } else if (sc instanceof SimpleContent) { + SimpleContent simpleContent = (SimpleContent) sc; + Derivation derivation = (Derivation) simpleContent.getDerivation(); + + if (derivation.getAllAttributes().size() > 0) { + // has attributes + buildXPath(derivation.getNamespaceUri(), rootElement, rootNamespace, rootPrefix); + } + } else if (sc instanceof com.predic8.schema.Element) { + level++; + xpathElement.put(level, ((com.predic8.schema.Element) sc).getName()); + parseElement((com.predic8.schema.Element) sc, schemas, rootElement, rootNamespace, rootPrefix); + } else if (sc instanceof All) { + All all = (All) sc; + level++; + for (com.predic8.schema.Element e : all.getElements()) { + if (e.getName() == null) + level--; + if (e.getName() != null) + xpathElement.put(level, e.getName()); + parseElement(e, schemas, rootElement, rootNamespace, rootPrefix); + } + level--; + cleanUpXPath(); + } else if (sc != null) { + // fail silently + LOGGER.warning("unhandled conditions - " + sc.getClass().getName()); + } + LOGGER.exiting(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); + } + + private void parseParts(List parts, List schemas, String rootElementName, JsonObject rootElement) { + for (Part part : parts) { + if (rootElement == null) { + rootElement = OASUtils.createComplexType(part.getName(), "0", "1"); + rootElementName = part.getName(); + definitions.add(part.getName(), rootElement); + } + if (isPrimitive(part.getType().getQname().getLocalPart())) { + JsonObject properties = rootElement.getAsJsonObject("properties"); + properties.add(part.getName(), + OASUtils.createSimpleType(part.getType().getQname().getLocalPart(), "0", "1")); + queryParams.add(part.getName()); + } else { + TypeDefinition typeDefinition = part.getType(); + if (typeDefinition instanceof ComplexType) { + ComplexType ct = (ComplexType) typeDefinition; + parseSchema(ct.getModel(), schemas, rootElementName, rootElement); + } + } + } + } + + private String parseParts(List parts, List schemas, String rootElement, String rootNamespace, + String rootPrefix, String soapRequest) { + LOGGER.entering(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); + for (Part part : parts) { + if (part.getType() != null) { + if (isPrimitive(part.getType().getQname().getLocalPart())) { + soapRequest = soapRequest + "<" + part.getName() + + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"" + part.getTypePN() + + "\">" + "?\n"; + // primitive elements are in the same namespace, skip xpath + } else { + TypeDefinition typeDefinition = part.getType(); + if (typeDefinition instanceof ComplexType) { + ComplexType ct = (ComplexType) typeDefinition; + SchemaComponent sc = ct.getModel(); + try { + soapRequest = soapRequest + "<" + part.getName() + + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"" + + part.getTypePN() + "\" xmlns:" + part.getType().getPrefix() + "=\"" + + part.getType().getNamespaceUri() + "\">\n"; + soapRequest += sc.getRequestTemplate(); + soapRequest += "\n"; + xpathElement.put(++level, part.getName()); + // since we already have the soap request template, + // no need to pass it. + // call parseRPCschema to find any elements with a + // different namespace + parseRPCSchema(sc, schemas, rootElement, rootNamespace, rootPrefix, ""); + level--; + } catch (Exception e) { + soapRequest += "\n"; + soapRequest = parseRPCSchema(sc, schemas, rootElement, rootNamespace, rootPrefix, + soapRequest); + } + } else if (typeDefinition instanceof com.predic8.schema.SimpleType) { + com.predic8.schema.SimpleType st = (com.predic8.schema.SimpleType)typeDefinition; + //TODO: + //LOGGER.warning("Handle simple type"); + } else if (typeDefinition instanceof BuiltInSchemaType) { + BuiltInSchemaType bst = (BuiltInSchemaType) typeDefinition; + soapRequest = soapRequest + bst.getRequestTemplate(); + } else { + LOGGER.warning("WARNING: unhandled type - " + typeDefinition.getClass().getName()); + } + } + } else { + soapRequest += part.getElement().getRequestTemplate(); + } + } + LOGGER.exiting(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); + return soapRequest; + } + + private String parseRPCSchema(SchemaComponent sc, List schemas, String rootElement, String rootNamespace, + String rootPrefix, String soapRequest) { + LOGGER.entering(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); + if (sc instanceof Sequence) { + Sequence sequence = (Sequence) sc; + level++; + soapRequest = soapRequest + sequence.getRequestTemplate(); + for (com.predic8.schema.Element e : sequence.getElements()) { + if (e.getName() == null) + level--; + if (e.getName() != null) + xpathElement.put(level, e.getName()); + parseRPCElement(e, schemas, rootElement, rootNamespace, rootPrefix, soapRequest); + } + level--; + cleanUpXPath(); + } else if (sc instanceof ComplexContent) { + ComplexContent complexContent = (ComplexContent) sc; + Derivation derivation = complexContent.getDerivation(); + + if (derivation != null) { + TypeDefinition typeDefinition = getTypeFromSchema(derivation.getBase(), schemas); + if (typeDefinition instanceof ComplexType) { + soapRequest = parseRPCSchema(((ComplexType) typeDefinition).getModel(), schemas, rootElement, + rootNamespace, rootPrefix, soapRequest); + } + if (derivation.getModel() instanceof Sequence) { + soapRequest = parseRPCSchema((Sequence) derivation.getModel(), schemas, rootElement, rootNamespace, + rootPrefix, soapRequest); + } else if (derivation.getModel() instanceof ModelGroup) { + soapRequest = parseRPCSchema((ModelGroup) derivation.getModel(), schemas, rootElement, + rootNamespace, rootPrefix, soapRequest); + } + } + } else if (sc instanceof SimpleContent) { + SimpleContent simpleContent = (SimpleContent) sc; + Derivation derivation = (Derivation) simpleContent.getDerivation(); + + if (derivation.getAllAttributes().size() > 0) { + // has attributes + buildXPath(derivation.getNamespaceUri(), rootElement, rootNamespace, rootPrefix); + } + } else if (sc instanceof GroupRef) { + // GroupRef groupRef = (GroupRef)sc; + LOGGER.fine("WARNING: GroupRef not handled."); + } else if (sc instanceof All) { + All all = (All) sc; + level++; + soapRequest = soapRequest + all.getRequestTemplate(); + for (com.predic8.schema.Element e : all.getElements()) { + if (e.getName() == null) + level--; + if (e.getName() != null) + xpathElement.put(level, e.getName()); + parseRPCElement(e, schemas, rootElement, rootNamespace, rootPrefix, soapRequest); + } + level--; + cleanUpXPath(); + } else { + LOGGER.warning("WARNING: unhandled type " + sc.getClass().getName()); + } + LOGGER.exiting(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); + return soapRequest; + } + + private void parseRPCElement(com.predic8.schema.Element e, List schemas, String rootElement, + String rootNamespace, String rootPrefix, String soapRequest) { + LOGGER.entering(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); + if (e.getName() == null) { + if (e.getRef() != null) { + final String localPart = e.getRef().getLocalPart(); + final com.predic8.schema.Element element = elementFromSchema(localPart, schemas); + parseRPCSchema(element, schemas, rootElement, rootNamespace, rootPrefix, soapRequest); + } else { + // TODO: handle this + LOGGER.warning("unhandle conditions getRef() = null"); + } + } else { + if (!e.getName().equalsIgnoreCase(rootElement)) { + if (e.getEmbeddedType() instanceof ComplexType) { + ComplexType ct = (ComplexType) e.getEmbeddedType(); + if (!e.getNamespaceUri().equalsIgnoreCase(rootNamespace)) { + buildXPath(e, rootElement, rootNamespace, rootPrefix); + } + parseRPCSchema(ct.getModel(), schemas, rootElement, rootNamespace, rootPrefix, soapRequest); } else { - targetDefault = xmlUtils.readXML(SOAP2API_TARGET_TEMPLATE); - if (CORS) { - Node response = targetDefault.getElementsByTagName("Response").item(0); - Node step = targetDefault.createElement("Step"); - Node name = targetDefault.createElement("Name"); - name.setTextContent("add-cors"); - step.appendChild(name); - response.appendChild(step); + if (e.getType() != null) { + if (!getParentNamepace(e).equalsIgnoreCase(rootNamespace) + && !e.getType().getNamespaceURI().equalsIgnoreCase(rootNamespace)) { + buildXPath(e, rootElement, rootNamespace, rootPrefix); + } + TypeDefinition typeDefinition = getTypeFromSchema(e.getType(), schemas); + if (typeDefinition instanceof ComplexType) { + parseRPCSchema(((ComplexType) typeDefinition).getModel(), schemas, rootElement, + rootNamespace, rootPrefix, soapRequest); } + } else { + // handle this as anyType + buildXPath(e, rootElement, rootNamespace, rootPrefix, true); + if (!getParentNamepace(e).equalsIgnoreCase(rootNamespace)) { + buildXPath(e, rootElement, rootNamespace, rootPrefix); + } + LOGGER.warning("Found element " + e.getName() + " with no type. Handling as xsd:anyType"); + } } + } + } + LOGGER.exiting(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); + } - Node urlNode = targetDefault.getElementsByTagName("URL").item(0); + private TypeDefinition getTypeFromSchema(QName qName, List schemas) { + LOGGER.entering(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); - if (targetEndpoint != null && targetEndpoint.equalsIgnoreCase("") != true) { - urlNode.setTextContent(targetEndpoint); - } else { - LOGGER.warning("No target URL set"); + if (qName != null) { + for (Schema schema : schemas) { + try { + final TypeDefinition type = schema.getType(qName); + if (type != null) { + return type; + } + } catch (Exception e) { + // Fail silently + LOGGER.warning("unhandle conditions: " + e.getMessage()); } - - xmlUtils.writeXML(targetDefault, buildFolder + File.separator + "apiproxy" + File.separator + "targets" - + File.separator + "default.xml"); - LOGGER.info("Generated Target xml: " + buildFolder + File.separator + "apiproxy" + File.separator + "targets" - + File.separator + "default.xml"); - LOGGER.exiting(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); + } } + return null; + } - private void writeJsonToXMLPolicy(Document jsonXMLTemplate, String operationName, String rootElement) - throws Exception { - LOGGER.entering(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - - String targetPath = buildFolder + File.separator + "apiproxy" + File.separator + "policies" + File.separator; + private void cleanUpXPath() { + LOGGER.entering(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); + final Iterator> iterator = xpathElement.entrySet().iterator(); + while (iterator.hasNext()) { + final Map.Entry next = iterator.next(); + if (next.getKey() > level) { + iterator.remove(); + } + } + LOGGER.exiting(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); + } + + private String getSoapNamespace() { + if (soapVersion.equalsIgnoreCase(SOAP_11)) { + return soap11Namespace; + } else { + return soap12Namespace; + } + } - XMLUtils xmlUtils = new XMLUtils(); - Document jsonxmlPolicyXML = xmlUtils.cloneDocument(jsonXMLTemplate); + private String buildSOAPRequest(List parts, List schemas, String rootElement, String rootNamespace, + boolean generateParts) { - Node root = jsonxmlPolicyXML.getFirstChild(); - NamedNodeMap attr = root.getAttributes(); - Node nodeAttr = attr.getNamedItem("name"); - nodeAttr.setNodeValue(operationName + "-json-to-xml"); + LOGGER.entering(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); - Node displayName = jsonxmlPolicyXML.getElementsByTagName("DisplayName").item(0); - displayName.setTextContent(operationName + " JSON TO XML"); + String prefix = getPrefix(rootNamespace); + String soapRequest = null; - /* - * Node objectRootElement = - * jsonxmlPolicyXML.getElementsByTagName("ObjectRootElementName").item(0 - * ); objectRootElement.setTextContent(rootElement); - * - * Node arrayRootElement = - * jsonxmlPolicyXML.getElementsByTagName("ArrayRootElementName").item(0) - * ; arrayRootElement.setTextContent(rootElement); - */ + if (RPCSTYLE) { + soapRequest = "\n\n" + "<" + + prefix + ":" + rootElement + ">\n"; + + } else { + soapRequest = "\n\n"; + } - xmlUtils.writeXML(jsonxmlPolicyXML, targetPath + operationName + "-json-to-xml.xml"); + if (generateParts) { + try { + soapRequest = parseParts(parts, schemas, rootElement, rootNamespace, prefix, soapRequest); + } catch (Exception e) { + LOGGER.warning( + "Failed to parse parts. Not generating SOAP Template. Try changing the verb to POST/PUT"); + } + } - LOGGER.exiting(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); + if (RPCSTYLE) { + soapRequest += "\n"; + } + + soapRequest += "\n"; + + LOGGER.exiting(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); + return soapRequest; + } + + private void buildXPath(com.predic8.schema.Element e, String rootElement, String rootNamespace, String rootPrefix, + boolean removeNamespace) { + LOGGER.entering(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); + + Rule r = null; + String xpathString = ""; + String prefix = "NULL"; + String namespaceUri = "NULL"; + String soapElements = "/soapenv:Envelope/soapenv:Body"; + String lastElement = ""; + + for (Map.Entry entry : xpathElement.entrySet()) { + xpathString = xpathString + "/" + rootPrefix + ":" + entry.getValue(); + lastElement = entry.getValue(); + } + + // add the last element to xpath + if (!lastElement.equalsIgnoreCase(e.getName())) + xpathString = xpathString + "/" + rootPrefix + ":" + e.getName(); + + r = new Rule(soapElements + xpathString, prefix, namespaceUri, "descendant"); + ruleList.add(r); + LOGGER.exiting(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); + + } + + private void buildXPath(com.predic8.schema.Element e, String rootElement, String rootNamespace, String rootPrefix) { + LOGGER.entering(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); + Rule r = null; + String xpathString = ""; + String soapElements = "/soapenv:Envelope/soapenv:Body"; + String prefix = getPrefix(e.getNamespaceUri()); + String namespaceUri = e.getNamespaceUri(); + for (Map.Entry entry : xpathElement.entrySet()) { + xpathString = xpathString + "/" + rootPrefix + ":" + entry.getValue(); + } + + r = new Rule(soapElements + xpathString, prefix, namespaceUri); + ruleList.add(r); + LOGGER.exiting(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); + } + + private void buildXPath(String namespaceUri, String rootElement, String rootNamespace, String rootPrefix) { + LOGGER.entering(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); + Rule r = null; + String prefix = getPrefix(namespaceUri); + String soapElements = "/soapenv:Envelope/soapenv:Body"; + String xpathString = ""; + + for (Map.Entry entry : xpathElement.entrySet()) { + xpathString = xpathString + "/" + rootPrefix + ":" + entry.getValue(); } - private void writeStdPolicies() throws Exception { - LOGGER.entering(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - try { - String sourcePath = "/templates/"; - String targetPath = buildFolder + File.separator + "apiproxy" + File.separator + "policies" - + File.separator; - String xslResourcePath = buildFolder + File.separator + "apiproxy" + File.separator + "resources" - + File.separator + "xsl" + File.separator; - /* - * String jsResourcePath = buildFolder + File.separator + "apiproxy" - * + File.separator + "resources" + File.separator + "jsc" + - * File.separator; - */ - - LOGGER.fine("Source Path: " + sourcePath); - LOGGER.fine("Target Path: " + targetPath); - if (PASSTHRU) { - sourcePath += "soappassthru/"; - Files.copy(getClass().getResourceAsStream(sourcePath + "Extract-Operation-Name.xml"), - Paths.get(targetPath + "Extract-Operation-Name.xml"), - java.nio.file.StandardCopyOption.REPLACE_EXISTING); - Files.copy(getClass().getResourceAsStream(sourcePath + "Invalid-SOAP.xml"), - Paths.get(targetPath + "Invalid-SOAP.xml"), java.nio.file.StandardCopyOption.REPLACE_EXISTING); - /* - * Files.copy(getClass().getResourceAsStream(sourcePath + - * "return-wsdl.xml"), Paths.get(targetPath + - * "return-wsdl.xml"), - * java.nio.file.StandardCopyOption.REPLACE_EXISTING); - */ - } else { - sourcePath += "soap2api/"; - Files.copy(getClass().getResourceAsStream(sourcePath + "xml-to-json.xml"), - Paths.get(targetPath + "xml-to-json.xml"), java.nio.file.StandardCopyOption.REPLACE_EXISTING); - Files.copy(getClass().getResourceAsStream(sourcePath + "set-response-soap-body.xml"), - Paths.get(targetPath + "set-response-soap-body.xml"), - java.nio.file.StandardCopyOption.REPLACE_EXISTING); - Files.copy(getClass().getResourceAsStream(sourcePath + "set-response-soap-body-accept.xml"), - Paths.get(targetPath + "set-response-soap-body-accept.xml"), - java.nio.file.StandardCopyOption.REPLACE_EXISTING); - Files.copy(getClass().getResourceAsStream(sourcePath + "get-response-soap-body.xml"), - Paths.get(targetPath + "get-response-soap-body.xml"), - java.nio.file.StandardCopyOption.REPLACE_EXISTING); - Files.copy(getClass().getResourceAsStream(sourcePath + "get-response-soap-body-xml.xml"), - Paths.get(targetPath + "get-response-soap-body-xml.xml"), - java.nio.file.StandardCopyOption.REPLACE_EXISTING); - Files.copy(getClass().getResourceAsStream(sourcePath + "set-target-url.xml"), - Paths.get(targetPath + "set-target-url.xml"), - java.nio.file.StandardCopyOption.REPLACE_EXISTING); - Files.copy(getClass().getResourceAsStream(sourcePath + "extract-format.xml"), - Paths.get(targetPath + "extract-format.xml"), - java.nio.file.StandardCopyOption.REPLACE_EXISTING); - Files.copy(getClass().getResourceAsStream(sourcePath + "unknown-resource.xml"), - Paths.get(targetPath + "unknown-resource.xml"), - java.nio.file.StandardCopyOption.REPLACE_EXISTING); - Files.copy(getClass().getResourceAsStream(sourcePath + "unknown-resource-xml.xml"), - Paths.get(targetPath + "unknown-resource-xml.xml"), - java.nio.file.StandardCopyOption.REPLACE_EXISTING); - Files.copy(getClass().getResourceAsStream(sourcePath + "remove-empty-nodes.xml"), - Paths.get(targetPath + "remove-empty-nodes.xml"), - java.nio.file.StandardCopyOption.REPLACE_EXISTING); - Files.copy(getClass().getResourceAsStream(sourcePath + "remove-empty-nodes.xslt"), - Paths.get(xslResourcePath + "remove-empty-nodes.xslt"), - java.nio.file.StandardCopyOption.REPLACE_EXISTING); - Files.copy(getClass().getResourceAsStream(sourcePath + "return-generic-error.xml"), - Paths.get(targetPath + "return-generic-error.xml"), - java.nio.file.StandardCopyOption.REPLACE_EXISTING); - Files.copy(getClass().getResourceAsStream(sourcePath + "return-generic-error-accept.xml"), - Paths.get(targetPath + "return-generic-error-accept.xml"), - java.nio.file.StandardCopyOption.REPLACE_EXISTING); - Files.copy(getClass().getResourceAsStream(sourcePath + "remove-namespaces.xml"), - Paths.get(targetPath + "remove-namespaces.xml"), - java.nio.file.StandardCopyOption.REPLACE_EXISTING); - Files.copy(getClass().getResourceAsStream(sourcePath + "remove-namespaces.xslt"), - Paths.get(xslResourcePath + "remove-namespaces.xslt"), - java.nio.file.StandardCopyOption.REPLACE_EXISTING); - /* - * Files.copy(getClass().getResourceAsStream(sourcePath + - * "root-wrapper.js"), Paths.get(jsResourcePath + - * "root-wrapper.js"), - * java.nio.file.StandardCopyOption.REPLACE_EXISTING); - */ - - if (OAUTH) { - Files.copy(getClass().getResourceAsStream(sourcePath + "verify-oauth-v2-access-token.xml"), - Paths.get(targetPath + "verify-oauth-v2-access-token.xml"), - java.nio.file.StandardCopyOption.REPLACE_EXISTING); - Files.copy(getClass().getResourceAsStream(sourcePath + "remove-header-authorization.xml"), - Paths.get(targetPath + "remove-header-authorization.xml"), - java.nio.file.StandardCopyOption.REPLACE_EXISTING); - if (QUOTAOAUTH) { - Files.copy(getClass().getResourceAsStream(sourcePath + "impose-quota-oauth.xml"), - Paths.get(targetPath + "impose-quota-oauth.xml"), - java.nio.file.StandardCopyOption.REPLACE_EXISTING); - } - } + r = new Rule(soapElements + xpathString + "/@*", prefix, namespaceUri); + ruleList.add(r); - if (APIKEY) { - Files.copy(getClass().getResourceAsStream(sourcePath + "verify-api-key.xml"), - Paths.get(targetPath + "verify-api-key.xml"), - java.nio.file.StandardCopyOption.REPLACE_EXISTING); - Files.copy(getClass().getResourceAsStream(sourcePath + "remove-query-param-apikey.xml"), - Paths.get(targetPath + "remove-query-param-apikey.xml"), - java.nio.file.StandardCopyOption.REPLACE_EXISTING); - if (QUOTAAPIKEY) { - Files.copy(getClass().getResourceAsStream(sourcePath + "impose-quota-apikey.xml"), - Paths.get(targetPath + "impose-quota-apikey.xml"), - java.nio.file.StandardCopyOption.REPLACE_EXISTING); - } - } + cleanUpXPath(); + LOGGER.exiting(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); + } + + private String getNamespacesAsString(boolean removeBlackListed) { + String namespaces = ""; + for (Map.Entry entry : namespace.entrySet()) { + if (removeBlackListed) { + if (!isBlackListed(entry.getValue())) { + namespaces += " xmlns:" + entry.getKey() + "=\"" + entry.getValue() + "\""; + } + } else { + namespaces += " xmlns:" + entry.getKey() + "=\"" + entry.getValue() + "\""; + } + } + return namespaces; + } + + private static boolean isBlackListed(String namespaceURI) { + return blackListedNamespaces.contains(namespaceURI); + } + + private String getParentNamepace(com.predic8.schema.Element e) { + XMLElement parent = e.getParent(); - if (CORS) { - Files.copy(getClass().getResourceAsStream(sourcePath + "add-cors.xml"), - Paths.get(targetPath + "add-cors.xml"), java.nio.file.StandardCopyOption.REPLACE_EXISTING); - } - } - } catch (Exception e) { - LOGGER.severe(e.getMessage()); - e.printStackTrace(); - throw e; - } - LOGGER.exiting(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); + try { + return parent.getNamespaceUri(); + } catch (NullPointerException npe) { + if (e.getNamespaceUri() != null) + return e.getNamespaceUri(); + else + return null; } + } - private void writeSOAPPassThruProxyEndpointConditions(String proxyDescription) throws Exception { - LOGGER.entering(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); + @SuppressWarnings("unchecked") + private APIMap createAPIMap(Operation op, Definitions wsdl, String verb, String resourcePath, XMLUtils xmlUtils) + throws Exception { - String soapConditionText = "((envelope != \"Envelope\") or (body != \"Body\") or (envelopeNamespace !=\""; + LOGGER.entering(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); - XMLUtils xmlUtils = new XMLUtils(); - Document proxyDefault = xmlUtils.readXML(SOAPPASSTHRU_PROXY_TEMPLATE); - Document getWsdlTemplate = xmlUtils.readXML(SOAPPASSTHRU_GETWSDL_TEMPLATE); + APIMap apiMap = null; + String soapRequest = ""; - Node basePathNode = proxyDefault.getElementsByTagName("BasePath").item(0); + namespace = (Map) op.getNamespaceContext(); - if (basePath != null && basePath.equalsIgnoreCase("") != true) { - basePathNode.setTextContent(basePath); - } + try { + if (verb.equalsIgnoreCase("GET")) { - Node httpProxyConnection = proxyDefault.getElementsByTagName("HTTPProxyConnection").item(0); - Node virtualHost = null; - for (String vHost : vHosts) { - virtualHost = proxyDefault.createElement("VirtualHost"); - virtualHost.setTextContent(vHost); - httpProxyConnection.appendChild(virtualHost); + soapRequest = buildSOAPRequest(op.getInput().getMessage().getParts(), wsdl.getSchemas(), op.getName(), + op.getNamespaceUri(), true); + + if (op.getInput().getMessage().getParts().size() == 0) { + apiMap = new APIMap(null, soapRequest, resourcePath, verb, op.getName(), false); + } else { + KeyValue kv = xmlUtils.replacePlaceHolders(soapRequest); + apiMap = new APIMap(kv.getValue(), kv.getKey(), resourcePath, verb, op.getName(), false); } + } else { + soapRequest = buildSOAPRequest(op.getInput().getMessage().getParts(), wsdl.getSchemas(), op.getName(), + op.getNamespaceUri(), true); - Node description = proxyDefault.getElementsByTagName("Description").item(0); - description.setTextContent(proxyDescription); + String namespaceUri = op.getNamespaceUri(); + String prefix = getPrefix(namespaceUri); - Node soapCondition = proxyDefault.getElementsByTagName("Condition").item(2); if (soapVersion.equalsIgnoreCase(SOAP_11)) { - soapCondition.setTextContent(soapConditionText + SOAP11 + "\")) and (request.verb != \"GET\")"); + xmlUtils.generateRootNamespaceXSLT(SOAP2API_XSLT11_TEMPLATE, SOAP2API_XSL, op.getName(), prefix, + null, namespaceUri, namespace); } else { - soapCondition.setTextContent(soapConditionText + SOAP12 + "\")) and (request.verb != \"GET\")"); - } - - String conditionText = "(proxy.pathsuffix MatchesPath \"/\") and (request.verb = \"POST\") and (operation = \""; - Node flows = proxyDefault.getElementsByTagName("Flows").item(0); - Node flow; - Node flowDescription; - Node request; - Node response; - Node condition; - Node step1; - Node name1; - - for (Map.Entry entry : messageTemplates.entrySet()) { - - String operationName = entry.getKey(); - APIMap apiMap = entry.getValue(); - - flow = proxyDefault.createElement("Flow"); - ((Element) flow).setAttribute("name", operationName); - - flowDescription = proxyDefault.createElement("Description"); - flowDescription.setTextContent(operationName); - flow.appendChild(flowDescription); - - request = proxyDefault.createElement("Request"); - response = proxyDefault.createElement("Response"); - condition = proxyDefault.createElement("Condition"); - condition.setTextContent(conditionText + apiMap.getRootElement() + "\")"); - - flow.appendChild(request); - flow.appendChild(response); - flow.appendChild(condition); - - flows.appendChild(flow); + xmlUtils.generateRootNamespaceXSLT(SOAP2API_XSLT12_TEMPLATE, SOAP2API_XSL, op.getName(), prefix, + null, namespaceUri, namespace); } - // Add get wsdl - flow = proxyDefault.createElement("Flow"); - ((Element) flow).setAttribute("name", "Get WSDL"); - flowDescription = proxyDefault.createElement("Description"); - flowDescription.setTextContent("Unknown Resource"); - flow.appendChild(flowDescription); - - request = proxyDefault.createElement("Request"); - response = proxyDefault.createElement("Response"); - condition = proxyDefault.createElement("Condition"); - condition.setTextContent( - "(proxy.pathsuffix MatchesPath \"/\") and (request.verb = \"GET\") and (request.queryparam.wsdl != \"\")"); - - step1 = proxyDefault.createElement("Step"); - name1 = proxyDefault.createElement("Name"); - name1.setTextContent("Return-WSDL"); - - step1.appendChild(name1); - request.appendChild(step1); - - flow.appendChild(request); - flow.appendChild(response); - flow.appendChild(condition); - - flows.appendChild(flow); - - // Add unknown resource - flow = proxyDefault.createElement("Flow"); - ((Element) flow).setAttribute("name", "unknown-resource"); - - flowDescription = proxyDefault.createElement("Description"); - flowDescription.setTextContent("Unknown Resource"); - flow.appendChild(flowDescription); - - request = proxyDefault.createElement("Request"); - response = proxyDefault.createElement("Response"); - condition = proxyDefault.createElement("Condition"); - - step1 = proxyDefault.createElement("Step"); - name1 = proxyDefault.createElement("Name"); - name1.setTextContent("Invalid-SOAP"); - step1.appendChild(name1); - request.appendChild(step1); - - flow.appendChild(request); - flow.appendChild(response); - flow.appendChild(condition); - - flows.appendChild(flow); - - writeRaiseFault(getWsdlTemplate); - - xmlUtils.writeXML(proxyDefault, buildFolder + File.separator + "apiproxy" + File.separator + "proxies" - + File.separator + "default.xml"); - LOGGER.fine("Edited target xml: " + buildFolder + File.separator + "apiproxy" + File.separator + "proxies" - + File.separator + "default.xml"); - - LOGGER.exiting(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - - } - - /** - * - * @param wsdlContent - * @return - * - * The predic8 "getAsString" method does not include a namespace prefix for the definitions - * element. It assumes default namespace. If the WSDL didn't include a default namespace, then - * WSDL importers like SOAP UI and others fail to import the WSDL. This method looks to see if the - * WSDL has a default namespace and adds it if missing - */ - private String addDefaultNamespace(String wsdlContent) { - - String containsString = "xmlns='http://schemas.xmlsoap.org/wsdl/'"; - String replaceString = "xmlns:wsdl='http://schemas.xmlsoap.org/wsdl/' xmlns='http://schemas.xmlsoap.org/wsdl/'"; - String findString = "xmlns:wsdl='http://schemas.xmlsoap.org/wsdl/'"; - - if (wsdlContent.indexOf(containsString) != -1) { //already has default namespace. - return wsdlContent; + if (ruleList.size() > 0) { + RuleSet rs = new RuleSet(); + rs.addRuleList(ruleList); + xmlUtils.generateOtherNamespacesXSLT(SOAP2API_XSL, op.getName(), rs.getTransform(soapVersion), + namespace); + ruleList.clear(); + apiMap = new APIMap("", soapRequest, resourcePath, verb, op.getName(), true); } else { - return wsdlContent.replaceAll(findString, replaceString); + apiMap = new APIMap("", soapRequest, resourcePath, verb, op.getName(), false); + } + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + + LOGGER.exiting(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); + return apiMap; + } + + public String getSOAPVersion(String wsdlPath) throws NoServicesFoundException { + + LOGGER.entering(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); + + Service service = null; + com.predic8.wsdl.Port port = null; + WSDLParser2 parser = new WSDLParser2(); + Definitions wsdl = null; + + wsdl = parser.parse(wsdlPath); + if (wsdl.getServices().size() == 0) { + LOGGER.severe("No services were found in the WSDL"); + throw new NoServicesFoundException("No services were found in the WSDL"); + } + + if (serviceName != null) { + for (Service svc : wsdl.getServices()) { + if (svc.getName().equalsIgnoreCase(serviceName)) { + service = svc; + break; + } + } + if (service == null) { // didn't find any service matching name + LOGGER.severe("No matching services were found in the WSDL"); + throw new NoServicesFoundException("No matching services were found in the WSDL"); + } + } else { + service = wsdl.getServices().get(0); // get the first service + } + + if (portName != null) { + for (com.predic8.wsdl.Port prt : service.getPorts()) { + if (prt.getName().equalsIgnoreCase(portName)) { + port = prt; + } + } + if (port == null) { // didn't find any port matching name + LOGGER.severe("No matching port was found in the WSDL"); + throw new NoServicesFoundException("No matching port found in the WSDL"); + } + } else { + port = service.getPorts().get(0); // get first port + } + + LOGGER.exiting(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); + return port.getBinding().getProtocol().toString(); + + } + + private void getOASDefinitions(Definitions wsdl, com.predic8.schema.Element e) { + + LOGGER.entering(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); + + if (e != null) { + TypeDefinition typeDefinition = null; + if (e.getEmbeddedType() != null) { + typeDefinition = e.getEmbeddedType(); + } else { + typeDefinition = getTypeFromSchema(e.getType(), wsdl.getSchemas()); + } + if (typeDefinition instanceof ComplexType) { + ComplexType ct = (ComplexType) typeDefinition; + JsonObject rootElement = OASUtils.createComplexType(e.getName(), e.getMinOccurs(), e.getMaxOccurs()); + definitions.add(e.getName(), rootElement); + parseSchema(ct.getModel(), wsdl.getSchemas(), e.getName(), rootElement); + } + } + LOGGER.exiting(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); + } + + private void getWSDLDetails(String wsdlPath) throws Exception { + LOGGER.entering(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); + + Service service = null; + List ports = new ArrayList(); + List services = new ArrayList(); + + try { + WSDLParser2 parser = new WSDLParser2(); + wsdl = parser.parse(wsdlPath); + if (wsdl.getServices().size() == 0) { + LOGGER.severe("No services were found in the WSDL"); + throw new NoServicesFoundException("No services were found in the WSDL"); + } + } catch (Exception e) { + e.printStackTrace(); + LOGGER.severe(e.getLocalizedMessage()); + throw e; + } + + KeyValue map = StringUtils.proxyNameAndBasePath(wsdlPath); + + if (serviceName != null) { + for (Service svc : wsdl.getServices()) { + if (svc.getName().equalsIgnoreCase(serviceName)) { + service = svc; + LOGGER.fine("Found Service: " + service.getName()); + break; + } + } + if (service == null) { // didn't find any service matching name + LOGGER.severe("No matching services were found in the WSDL"); + throw new NoServicesFoundException("No matching services were found in the WSDL"); + } else { + proxyName = serviceName; + } + } else { + service = wsdl.getServices().get(0); // get the first service + LOGGER.fine("Found Service: " + service.getName()); + serviceName = service.getName(); + proxyName = serviceName; + } + + if (basePath == null) { + if (serviceName != null) { + basePath = "/" + serviceName.toLowerCase(); + } else { + basePath = map.getValue(); + } + } + + if (portName != null) { + for (com.predic8.wsdl.Port prt : service.getPorts()) { + if (prt.getName().equalsIgnoreCase(portName)) { + port = prt; + } + } + if (port == null) { // didn't find any port matching name + LOGGER.severe("No matching port was found in the WSDL"); + throw new NoServicesFoundException("No matching port found in the WSDL"); + } + } else { + port = service.getPorts().get(0); // get first port + portName = port.getName(); + } + LOGGER.fine("Found Port: " + port.getName()); + + Binding binding = port.getBinding(); + soapVersion = binding.getProtocol().toString(); + + // EDGEUI-659 + if (!soapVersion.equalsIgnoreCase(SOAP_11) && !soapVersion.equalsIgnoreCase(SOAP_12)) { + // set default + LOGGER.warning("Unknow SOAP Version. Setting to SOAP 1.1"); + soapVersion = SOAP_11; + } + + if (binding.getStyle().toLowerCase().contains("rpc")) { + LOGGER.info("Binding Stype: " + binding.getStyle()); + RPCSTYLE = true; + } else if (binding.getStyle().toLowerCase().contains("document")) { + LOGGER.info("Binding Stype: " + binding.getStyle()); + RPCSTYLE = false; + } else { + LOGGER.info(binding.getStyle() + ". Treating as document"); + RPCSTYLE = false; + } + + targetEndpoint = port.getAddress().getLocation(); + + // start feature + port.getAddress().setLocation("@request.header.host#" + basePath); + ports.add(port); + service.setPorts(ports); + services.add(service); + wsdlContent = wsdl.getAsString(); + // end feature + + LOGGER.info("Retrieved WSDL endpoint: " + targetEndpoint); + + String[] schemes = { "http", "https" }; + UrlValidator urlValidator = new UrlValidator(schemes, UrlValidator.ALLOW_LOCAL_URLS); + + if (!urlValidator.isValid(targetEndpoint)) { + LOGGER.warning("Target endpoint is not http/https URL. Assigning a default value"); + targetEndpoint = "http://localhost:8080/soap"; + } + + LOGGER.exiting(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); + } + + @SuppressWarnings("unchecked") + private void parseWSDL() throws Exception { + LOGGER.entering(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); + XMLUtils xmlUtils = new XMLUtils(); + + StringWriter writer = new StringWriter(); + SOARequestCreator creator = new SOARequestCreator(wsdl, new RequestTemplateCreator(), + new MarkupBuilder(writer)); + // edgeui-654 + creator.setMaxRecursionDepth(2); + + Binding binding = port.getBinding(); + PortType portType = binding.getPortType(); + String bindingName = binding.getName(); + + LOGGER.fine("Found Binding: " + bindingName + " Binding Protocol: " + soapVersion + " Prefix: " + + binding.getPrefix() + " NamespaceURI: " + binding.getNamespaceUri()); + + APIMap apiMap = null; + HashMap selectedOperationList = selectedOperations.getSelectedOperations(); + + for (Operation op : portType.getOperations()) { + LOGGER.fine("Found Operation Name: " + op.getName() + " Prefix: " + op.getPrefix() + " NamespaceURI: " + + op.getNamespaceUri()); + try { + // the current operations is not in the list; skip. + if (selectedOperationList.size() > 0 && !selectedOperationList.containsKey(op.getName())) { + continue; } - } - - private void writeRaiseFault(Document getWsdlTemplate) throws Exception { - LOGGER.entering(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - XMLUtils xmlUtils = new XMLUtils(); - Document getWsdlRaiseFaultPolicy = xmlUtils.cloneDocument(getWsdlTemplate); - - Node payload = getWsdlRaiseFaultPolicy.getElementsByTagName("Payload").item(0); - payload.setTextContent(addDefaultNamespace(wsdlContent)); - - xmlUtils.writeXML(getWsdlRaiseFaultPolicy, buildFolder + File.separator + "apiproxy" + File.separator - + "policies" + File.separator + "return-wsdl.xml"); - - LOGGER.exiting(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - - } - - private static Boolean isPrimitive(String type) { - return primitiveTypes.contains(type); - } - - private String getNamespace(String prefix) { - LOGGER.entering(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - for (Map.Entry entry : namespace.entrySet()) { - if (entry.getKey().equalsIgnoreCase(prefix)) { - return entry.getValue(); - } - } - LOGGER.exiting(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - return null; - } - - public String getPrefix(String namespaceUri) { - LOGGER.entering(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - for (Map.Entry entry : namespace.entrySet()) { - if (entry.getValue().equalsIgnoreCase(namespaceUri)) { - if (entry.getKey().length() == 0) { - return "ns"; - } else { - return entry.getKey(); - } - } - } - LOGGER.exiting(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - return "ns"; - } - - private void parseElement(com.predic8.schema.Element e, List schemas, JsonObject parent, - String parentName) { - if (e.getName() == null) { - if (e.getRef() != null) { - final String localPart = e.getRef().getLocalPart(); - final com.predic8.schema.Element element = elementFromSchema(localPart, schemas); - JsonObject complexType = OASUtils.createComplexType(element.getName(), element.getMinOccurs(), - element.getMaxOccurs()); - OASUtils.addObject(parent, parentName, element.getName()); - definitions.add(element.getName(), complexType); - parseSchema(element, schemas, element.getName(), complexType); + // if passthru, then do nothing much + if (PASSTHRU) { + if (RPCSTYLE) { + apiMap = new APIMap(null, null, null, "POST", op.getName(), false); + } else { + // get root element + com.predic8.schema.Element requestElement = op.getInput().getMessage().getParts().get(0) + .getElement(); + if (requestElement != null) { + apiMap = new APIMap(null, null, null, "POST", requestElement.getName(), false); } else { - // TODO: handle this - LOGGER.warning("unhandle conditions getRef() = null"); + apiMap = new APIMap(null, null, null, "POST", op.getName(), false); } + } } else { - if (e.getEmbeddedType() instanceof ComplexType) { - ComplexType ct = (ComplexType) e.getEmbeddedType(); - JsonObject rootElement = OASUtils.createComplexType(e.getName(), e.getMinOccurs(), e.getMaxOccurs()); - OASUtils.addObject(parent, parentName, e.getName()); - definitions.add(e.getName(), rootElement); - parseSchema(ct.getModel(), schemas, e.getName(), rootElement); - } else if (e.getType() != null) { - TypeDefinition typeDefinition = getTypeFromSchema(e.getType(), schemas); - if (typeDefinition instanceof ComplexType) { - ComplexType ct = (ComplexType) typeDefinition; - JsonObject rootElement = OASUtils.createComplexType(e.getName(), e.getMinOccurs(), - e.getMaxOccurs()); - OASUtils.addObject(parent, parentName, e.getName()); - definitions.add(e.getName(), rootElement); - parseSchema(ct.getModel(), schemas, e.getName(), rootElement); - } - } - } - } - - private void parseElement(com.predic8.schema.Element e, List schemas, String rootElement, - String rootNamespace, String rootPrefix) { - if (e.getName() == null) { - if (e.getRef() != null) { - final String localPart = e.getRef().getLocalPart(); - final com.predic8.schema.Element element = elementFromSchema(localPart, schemas); - parseSchema(element, schemas, rootElement, rootNamespace, rootPrefix); + String resourcePath = operationsMap.getResourcePath(op.getName(), selectedOperationList); + String verb = ""; + // if all post options is not turned on, then interpret the + // operation from opsmap + if (!ALLPOST) { + verb = operationsMap.getVerb(op.getName(), selectedOperationList); + } else { // else POST + verb = "POST"; + } + + if (RPCSTYLE) { + apiMap = createAPIMap(op, wsdl, verb, resourcePath, xmlUtils); + } else {// document style + // there can be soap messages with no parts. membrane + // soap can't construct soap + // template for such messages. manually build + if (op.getInput().getMessage().getParts().size() == 0) { + apiMap = createAPIMap(op, wsdl, verb, resourcePath, xmlUtils); } else { - // fail silently - LOGGER.warning("unhandled conditions getRef() = null"); - } - } else { - if (!e.getName().equalsIgnoreCase(rootElement)) { - if (e.getEmbeddedType() instanceof ComplexType) { - ComplexType ct = (ComplexType) e.getEmbeddedType(); - if (!e.getNamespaceUri().equalsIgnoreCase(rootNamespace)) { - buildXPath(e, rootElement, rootNamespace, rootPrefix); + com.predic8.schema.Element requestElement = op.getInput().getMessage().getParts().get(0) + .getElement(); + + if (requestElement != null) { + namespace = (Map) requestElement.getNamespaceContext(); + + if (verb.equalsIgnoreCase("GET")) { + if (soapVersion.equalsIgnoreCase(SOAP_11) + || soapVersion.equalsIgnoreCase(SOAP_12)) { + creator.setCreator(new RequestTemplateCreator()); + // use membrane SOAP to generate a SOAP + // Request + try { + creator.createRequest(port.getName(), op.getName(), binding.getName()); + KeyValue kv = xmlUtils + .replacePlaceHolders(writer.toString()); + + // sometimes membrane soa generates + // invalid soap + // this will cause the bundle to not + // be uploaded + + // store the operation name, SOAP + // Request and + // the + // expected JSON Body in the map + apiMap = new APIMap(kv.getValue(), kv.getKey(), resourcePath, verb, + requestElement.getName(), false); + writer.getBuffer().setLength(0); + } catch (Exception e) { + LOGGER.warning("Membrane SOA failed to generate template."); + apiMap = createAPIMap(op, wsdl, verb, resourcePath, xmlUtils); } - parseSchema(ct.getModel(), schemas, rootElement, rootNamespace, rootPrefix); + } else { + apiMap = createAPIMap(op, wsdl, verb, resourcePath, xmlUtils); + } } else { - if (e.getType() != null) { - if (!getParentNamepace(e).equalsIgnoreCase(rootNamespace) - && !e.getType().getNamespaceURI().equalsIgnoreCase(rootNamespace)) { - buildXPath(e, rootElement, rootNamespace, rootPrefix); - } - TypeDefinition typeDefinition = getTypeFromSchema(e.getType(), schemas); - if (typeDefinition instanceof ComplexType) { - parseSchema(((ComplexType) typeDefinition).getModel(), schemas, rootElement, rootNamespace, - rootPrefix); - } - } else { - // handle this as anyType - buildXPath(e, rootElement, rootNamespace, rootPrefix, true); - if (!getParentNamepace(e).equalsIgnoreCase(rootNamespace)) { - buildXPath(e, rootElement, rootNamespace, rootPrefix); - } - LOGGER.warning("Found element " + e.getName() + " with no type. Handling as xsd:anyType"); - - } - } - } - } - } - - private com.predic8.schema.Element elementFromSchema(String name, List schemas) { - if (name != null) { - for (Schema schema : schemas) { - try { - final com.predic8.schema.Element element = schema.getElement(name); - if (element != null) { - return element; - } - } catch (Exception e) { - LOGGER.warning("unhandled conditions: " + e.getMessage()); - } - } - } - return null; - } - - private void parseSchema(SchemaComponent sc, List schemas, String rootElementName, JsonObject rootElement) { - - // fail safe measure. - if (Thread.currentThread().getStackTrace().length >= 128) { - TOO_MANY = true; - return; - } else if (TOO_MANY) - return; - else if (sc instanceof Sequence) { - Sequence seq = (Sequence) sc; - for (com.predic8.schema.Element e : seq.getElements()) { - if (e.getType() != null) { - if (isPrimitive(e.getType().getLocalPart())) { - if (rootElement == null) { - rootElement = OASUtils.createComplexType(e.getName(), e.getMinOccurs(), e.getMaxOccurs()); - rootElementName = e.getName(); - definitions.add(e.getName(), rootElement); - } - JsonObject properties = rootElement.getAsJsonObject("properties"); - properties.add(e.getName(), OASUtils.createSimpleType(e.getType().getLocalPart(), - e.getMinOccurs(), e.getMaxOccurs())); - queryParams.add(e.getName()); - } else { - parseElement(e, schemas, rootElement, rootElementName); - } - } else { - parseElement(e, schemas, rootElement, rootElementName); - } - } - } else if (sc instanceof Choice) { - Choice ch = (Choice) sc; - for (com.predic8.schema.Element e : ch.getElements()) { - if (e.getType() != null) { - if (isPrimitive(e.getType().getLocalPart())) { - if (rootElement == null) { - rootElement = OASUtils.createComplexType(e.getName(), e.getMinOccurs(), e.getMaxOccurs()); - rootElementName = e.getName(); - definitions.add(e.getName(), rootElement); - } - JsonObject properties = rootElement.getAsJsonObject("properties"); - properties.add(e.getName(), OASUtils.createSimpleType(e.getType().getLocalPart(), - e.getMinOccurs(), e.getMaxOccurs())); - queryParams.add(e.getName()); - } - } else { - parseElement(e, schemas, rootElement, rootElementName); - } - } - } else if (sc instanceof ComplexContent) { - ComplexContent complexContent = (ComplexContent) sc; - Derivation derivation = complexContent.getDerivation(); - - if (derivation != null) { - TypeDefinition typeDefinition = getTypeFromSchema(derivation.getBase(), schemas); - if (typeDefinition instanceof ComplexType) { - String name = ((ComplexType) typeDefinition).getName(); - JsonObject complexType = OASUtils.createComplexType(name, "0", "1"); - parseSchema(((ComplexType) typeDefinition).getModel(), schemas, name, complexType); - definitions.add(name, complexType); - } - } - } else if (sc instanceof SimpleContent) { - SimpleContent simpleContent = (SimpleContent) sc; - Derivation derivation = (Derivation) simpleContent.getDerivation(); - - JsonObject properties = rootElement.getAsJsonObject("properties"); - - if (derivation.getAllAttributes().size() > 0) { - // has attributes - for (Attribute attribute : derivation.getAllAttributes()) { - properties.add("@" + attribute.getName(), OASUtils.createSimpleType("string", "0", "1")); - } - } - } else if (sc instanceof com.predic8.schema.Element) { - parseElement((com.predic8.schema.Element) sc, schemas, rootElement, rootElementName); - } else if (sc instanceof All) { - All all = (All) sc; - for (com.predic8.schema.Element e : all.getElements()) { - parseElement(e, schemas, rootElement, rootElementName); - } - } - } - - private void parseSchema(SchemaComponent sc, List schemas, String rootElement, String rootNamespace, - String rootPrefix) { - - LOGGER.entering(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - - // fail safe measures. - if (Thread.currentThread().getStackTrace().length >= 128) {// edgeui-654 - TOO_MANY = true; - return; - } - - else if (TOO_MANY) - return;// edgeui-654 - - else if (ruleList.size() >= 100) { - // the rules are too big. clear the rules. - TOO_MANY = true; - return; - } else if (sc instanceof Sequence) { - Sequence seq = (Sequence) sc; - level++; - for (com.predic8.schema.Element e : seq.getElements()) { - if (e.getName() == null) - level--; - if (e.getName() != null) { - xpathElement.put(level, e.getName()); - if (e.getType() != null) { - if (e.getType().getLocalPart().equalsIgnoreCase("anyType")) { - // found a anyType. remove namespaces for - // descendents - buildXPath(e, rootElement, rootNamespace, rootPrefix, true); - } - } - } - parseElement(e, schemas, rootElement, rootNamespace, rootPrefix); - } - level--; - cleanUpXPath(); - } else if (sc instanceof Choice) { - Choice ch = (Choice) sc; - level++; - for (com.predic8.schema.Element e : ch.getElements()) { - if (!e.getName().equalsIgnoreCase(rootElement)) { - if (e.getEmbeddedType() instanceof ComplexType) { - ComplexType ct = (ComplexType) e.getEmbeddedType(); - xpathElement.put(level, e.getName()); - parseSchema(ct.getModel(), schemas, rootElement, rootNamespace, rootPrefix); - } else { - final TypeDefinition typeDefinition = getTypeFromSchema(e.getType(), schemas); - if (typeDefinition instanceof ComplexType) { - xpathElement.put(level, e.getName()); - parseSchema(((ComplexType) typeDefinition).getModel(), schemas, rootElement, rootNamespace, - rootPrefix); - } - if (e.getType() == null) { - // handle this any anyType - buildXPath(e, rootElement, rootNamespace, rootPrefix, true); - LOGGER.warning("Element " + e.getName() + " type was null; treating as anyType"); - } else if (!getParentNamepace(e).equalsIgnoreCase(rootNamespace) - && !e.getType().getNamespaceURI().equalsIgnoreCase(rootNamespace)) { - buildXPath(e, rootElement, rootNamespace, rootPrefix); - } else if (e.getType().getLocalPart().equalsIgnoreCase("anyType")) { - // if you find a anyType, remove namespace for the - // descendents. - buildXPath(e, rootElement, rootNamespace, rootPrefix, true); - } - } - } - } - level--; - cleanUpXPath(); - } else if (sc instanceof ComplexContent) { - ComplexContent complexContent = (ComplexContent) sc; - Derivation derivation = complexContent.getDerivation(); - - if (derivation != null) { - TypeDefinition typeDefinition = getTypeFromSchema(derivation.getBase(), schemas); - if (typeDefinition instanceof ComplexType) { - parseSchema(((ComplexType) typeDefinition).getModel(), schemas, rootElement, rootNamespace, - rootPrefix); - } - if (derivation.getModel() instanceof Sequence) { - parseSchema(derivation.getModel(), schemas, rootElement, rootNamespace, rootPrefix); - } else if (derivation.getModel() instanceof ModelGroup) { - parseSchema(derivation.getModel(), schemas, rootElement, rootNamespace, rootPrefix); - } - } - } else if (sc instanceof SimpleContent) { - SimpleContent simpleContent = (SimpleContent) sc; - Derivation derivation = (Derivation) simpleContent.getDerivation(); - - if (derivation.getAllAttributes().size() > 0) { - // has attributes - buildXPath(derivation.getNamespaceUri(), rootElement, rootNamespace, rootPrefix); - } - } else if (sc instanceof com.predic8.schema.Element) { - level++; - xpathElement.put(level, ((com.predic8.schema.Element) sc).getName()); - parseElement((com.predic8.schema.Element) sc, schemas, rootElement, rootNamespace, rootPrefix); - } else if (sc instanceof All) { - All all = (All) sc; - level++; - for (com.predic8.schema.Element e : all.getElements()) { - if (e.getName() == null) - level--; - if (e.getName() != null) - xpathElement.put(level, e.getName()); - parseElement(e, schemas, rootElement, rootNamespace, rootPrefix); - } - level--; - cleanUpXPath(); - } else if (sc != null) { - // fail silently - LOGGER.warning("unhandled conditions - " + sc.getClass().getName()); - } - LOGGER.exiting(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - } - - private void parseParts(List parts, List schemas, String rootElementName, JsonObject rootElement) { - for (Part part : parts) { - if (rootElement == null) { - rootElement = OASUtils.createComplexType(part.getName(), "0", "1"); - rootElementName = part.getName(); - definitions.add(part.getName(), rootElement); - } - if (isPrimitive(part.getType().getQname().getLocalPart())) { - JsonObject properties = rootElement.getAsJsonObject("properties"); - properties.add(part.getName(), - OASUtils.createSimpleType(part.getType().getQname().getLocalPart(), "0", "1")); - queryParams.add(part.getName()); - } else { - TypeDefinition typeDefinition = part.getType(); - if (typeDefinition instanceof ComplexType) { + String namespaceUri = null; + if (requestElement.getType() != null) { + namespaceUri = requestElement.getType().getNamespaceURI(); + } else { + namespaceUri = requestElement.getEmbeddedType().getNamespaceUri(); + } + String prefix = getPrefix(namespaceUri); + + if (soapVersion.equalsIgnoreCase(SOAP_11)) { + xmlUtils.generateRootNamespaceXSLT(SOAP2API_XSLT11_TEMPLATE, SOAP2API_XSL, + op.getName(), prefix, requestElement.getName(), namespaceUri, + namespace); + } else { + xmlUtils.generateRootNamespaceXSLT(SOAP2API_XSLT12_TEMPLATE, SOAP2API_XSL, + op.getName(), prefix, requestElement.getName(), namespaceUri, + namespace); + } + + TypeDefinition typeDefinition = null; + + if (requestElement.getEmbeddedType() != null) { + typeDefinition = requestElement.getEmbeddedType(); + } else { + typeDefinition = getTypeFromSchema(requestElement.getType(), wsdl.getSchemas()); + } + if (typeDefinition instanceof ComplexType) { ComplexType ct = (ComplexType) typeDefinition; - parseSchema(ct.getModel(), schemas, rootElementName, rootElement); - } - } - } - } - - private String parseParts(List parts, List schemas, String rootElement, String rootNamespace, - String rootPrefix, String soapRequest) { - LOGGER.entering(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - for (Part part : parts) { - if (part.getType() != null) { - if (isPrimitive(part.getType().getQname().getLocalPart())) { - soapRequest = soapRequest + "<" + part.getName() - + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"" + part.getTypePN() - + "\">" + "?\n"; - // primitive elements are in the same namespace, skip xpath - } else { - TypeDefinition typeDefinition = part.getType(); - if (typeDefinition instanceof ComplexType) { - ComplexType ct = (ComplexType) typeDefinition; - SchemaComponent sc = ct.getModel(); - try { - soapRequest = soapRequest + "<" + part.getName() - + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"" - + part.getTypePN() + "\" xmlns:" + part.getType().getPrefix() + "=\"" - + part.getType().getNamespaceUri() + "\">\n"; - soapRequest += sc.getRequestTemplate(); - soapRequest += "\n"; - xpathElement.put(++level, part.getName()); - // since we already have the soap request template, - // no need to pass it. - // call parseRPCschema to find any elements with a - // different namespace - parseRPCSchema(sc, schemas, rootElement, rootNamespace, rootPrefix, ""); - level--; - } catch (Exception e) { - soapRequest += "\n"; - soapRequest = parseRPCSchema(sc, schemas, rootElement, rootNamespace, rootPrefix, - soapRequest); - } - } else if (typeDefinition instanceof com.predic8.schema.SimpleType) { - com.predic8.schema.SimpleType st = (com.predic8.schema.SimpleType)typeDefinition; - //TODO: - //LOGGER.warning("Handle simple type"); - } else if (typeDefinition instanceof BuiltInSchemaType) { - BuiltInSchemaType bst = (BuiltInSchemaType) typeDefinition; - soapRequest = soapRequest + bst.getRequestTemplate(); + xpathElement.put(level, requestElement.getName()); + parseSchema(ct.getModel(), wsdl.getSchemas(), requestElement.getName(), + namespaceUri, prefix); + } + if (TOO_MANY) { + LOGGER.warning(op.getName() + + ": Too many nested schemas or elements. Skipping XSLT gen. Manual intervention necessary"); + ruleList.clear(); + apiMap = new APIMap("", "", resourcePath, verb, requestElement.getName(), + false); + } else { + // rule list is > 0, there are + // additional + // namespaces to add + if (ruleList.size() > 0) { + RuleSet rs = new RuleSet(); + rs.addRuleList(ruleList); + xmlUtils.generateOtherNamespacesXSLT(SOAP2API_XSL, op.getName(), + rs.getTransform(soapVersion), namespace); + ruleList.clear(); + apiMap = new APIMap("", "", resourcePath, verb, requestElement.getName(), + true); } else { - LOGGER.warning("WARNING: unhandled type - " + typeDefinition.getClass().getName()); + apiMap = new APIMap("", "", resourcePath, verb, requestElement.getName(), + false); } + } } - } else { - soapRequest += part.getElement().getRequestTemplate(); + } else {// if the request element is null, it + // appears membrane soap failed again. + // attempting manual build + apiMap = createAPIMap(op, wsdl, verb, resourcePath, xmlUtils); + } } + } } - LOGGER.exiting(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - return soapRequest; + messageTemplates.put(op.getName(), apiMap); + } catch (Exception e) { + LOGGER.severe(e.getMessage()); + e.printStackTrace(); + throw e; + } } - private String parseRPCSchema(SchemaComponent sc, List schemas, String rootElement, String rootNamespace, - String rootPrefix, String soapRequest) { - LOGGER.entering(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - if (sc instanceof Sequence) { - Sequence sequence = (Sequence) sc; - level++; - soapRequest = soapRequest + sequence.getRequestTemplate(); - for (com.predic8.schema.Element e : sequence.getElements()) { - if (e.getName() == null) - level--; - if (e.getName() != null) - xpathElement.put(level, e.getName()); - parseRPCElement(e, schemas, rootElement, rootNamespace, rootPrefix, soapRequest); - } - level--; - cleanUpXPath(); - } else if (sc instanceof ComplexContent) { - ComplexContent complexContent = (ComplexContent) sc; - Derivation derivation = complexContent.getDerivation(); - - if (derivation != null) { - TypeDefinition typeDefinition = getTypeFromSchema(derivation.getBase(), schemas); - if (typeDefinition instanceof ComplexType) { - soapRequest = parseRPCSchema(((ComplexType) typeDefinition).getModel(), schemas, rootElement, - rootNamespace, rootPrefix, soapRequest); - } - if (derivation.getModel() instanceof Sequence) { - soapRequest = parseRPCSchema((Sequence) derivation.getModel(), schemas, rootElement, rootNamespace, - rootPrefix, soapRequest); - } else if (derivation.getModel() instanceof ModelGroup) { - soapRequest = parseRPCSchema((ModelGroup) derivation.getModel(), schemas, rootElement, - rootNamespace, rootPrefix, soapRequest); - } - } - } else if (sc instanceof SimpleContent) { - SimpleContent simpleContent = (SimpleContent) sc; - Derivation derivation = (Derivation) simpleContent.getDerivation(); - - if (derivation.getAllAttributes().size() > 0) { - // has attributes - buildXPath(derivation.getNamespaceUri(), rootElement, rootNamespace, rootPrefix); - } - } else if (sc instanceof GroupRef) { - // GroupRef groupRef = (GroupRef)sc; - LOGGER.fine("WARNING: GroupRef not handled."); - } else if (sc instanceof All) { - All all = (All) sc; - level++; - soapRequest = soapRequest + all.getRequestTemplate(); - for (com.predic8.schema.Element e : all.getElements()) { - if (e.getName() == null) - level--; - if (e.getName() != null) - xpathElement.put(level, e.getName()); - parseRPCElement(e, schemas, rootElement, rootNamespace, rootPrefix, soapRequest); - } - level--; - cleanUpXPath(); - } else { - LOGGER.warning("WARNING: unhandled type " + sc.getClass().getName()); - } - LOGGER.exiting(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - return soapRequest; + if (messageTemplates.size() == 0) { + LOGGER.exiting(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); + throw new BindingNotFoundException("Soap version provided did not match any binding in WSDL"); } - private void parseRPCElement(com.predic8.schema.Element e, List schemas, String rootElement, - String rootNamespace, String rootPrefix, String soapRequest) { - LOGGER.entering(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - if (e.getName() == null) { - if (e.getRef() != null) { - final String localPart = e.getRef().getLocalPart(); - final com.predic8.schema.Element element = elementFromSchema(localPart, schemas); - parseRPCSchema(element, schemas, rootElement, rootNamespace, rootPrefix, soapRequest); - } else { - // TODO: handle this - LOGGER.warning("unhandle conditions getRef() = null"); + if (!PASSTHRU) { + for (Binding bnd : wsdl.getBindings()) { + if (bindingName.equalsIgnoreCase(bnd.getName())) { + for (BindingOperation bop : bnd.getOperations()) { + if (selectedOperationList.size() > 0 && !selectedOperationList.containsKey(bop.getName())) { + // the current operations is not in the list; skip. + continue; } - } else { - if (!e.getName().equalsIgnoreCase(rootElement)) { - if (e.getEmbeddedType() instanceof ComplexType) { - ComplexType ct = (ComplexType) e.getEmbeddedType(); - if (!e.getNamespaceUri().equalsIgnoreCase(rootNamespace)) { - buildXPath(e, rootElement, rootNamespace, rootPrefix); - } - parseRPCSchema(ct.getModel(), schemas, rootElement, rootNamespace, rootPrefix, soapRequest); - } else { - if (e.getType() != null) { - if (!getParentNamepace(e).equalsIgnoreCase(rootNamespace) - && !e.getType().getNamespaceURI().equalsIgnoreCase(rootNamespace)) { - buildXPath(e, rootElement, rootNamespace, rootPrefix); - } - TypeDefinition typeDefinition = getTypeFromSchema(e.getType(), schemas); - if (typeDefinition instanceof ComplexType) { - parseRPCSchema(((ComplexType) typeDefinition).getModel(), schemas, rootElement, - rootNamespace, rootPrefix, soapRequest); - } - } else { - // handle this as anyType - buildXPath(e, rootElement, rootNamespace, rootPrefix, true); - if (!getParentNamepace(e).equalsIgnoreCase(rootNamespace)) { - buildXPath(e, rootElement, rootNamespace, rootPrefix); - } - LOGGER.warning("Found element " + e.getName() + " with no type. Handling as xsd:anyType"); - } - } + if (bnd.getBinding() instanceof AbstractSOAPBinding) { + LOGGER.fine("Found Operation Name: " + bop.getName() + " SOAPAction: " + + bop.getOperation().getSoapAction()); + APIMap apiM = messageTemplates.get(bop.getName()); + apiM.setSoapAction(bop.getOperation().getSoapAction()); + messageTemplates.put(bop.getName(), apiM); } + } } - LOGGER.exiting(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); + } } + LOGGER.exiting(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); + } - private TypeDefinition getTypeFromSchema(QName qName, List schemas) { - LOGGER.entering(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); + private String generateOAS() throws Exception { - if (qName != null) { - for (Schema schema : schemas) { - try { - final TypeDefinition type = schema.getType(qName); - if (type != null) { - return type; - } - } catch (Exception e) { - // Fail silently - LOGGER.warning("unhandle conditions: " + e.getMessage()); - } - } - } - return null; - } - - private void cleanUpXPath() { - LOGGER.entering(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - final Iterator> iterator = xpathElement.entrySet().iterator(); - while (iterator.hasNext()) { - final Map.Entry next = iterator.next(); - if (next.getKey() > level) { - iterator.remove(); - } - } - LOGGER.exiting(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - } + LOGGER.entering(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); - private String getSoapNamespace() { - if (soapVersion.equalsIgnoreCase(SOAP_11)) { - return soap11Namespace; + @SuppressWarnings("resource") + String oasTemplate = new Scanner(getClass().getResourceAsStream(OAS_TEMPLATE), "UTF-8").useDelimiter("\\A") + .next(); + JsonObject oasObject = new JsonParser().parse(oasTemplate).getAsJsonObject(); + JsonObject paths = oasObject.getAsJsonObject("paths"); + JsonObject info = oasObject.getAsJsonObject("info"); + JsonObject operation = null; + JsonObject operationDetails = null; + JsonArray parameters = null; + + String verb = ""; + + definitions = oasObject.getAsJsonObject("definitions"); + + info.addProperty("title", proxyName); + oasObject.addProperty("host", "@request.header.host#"); + oasObject.addProperty("basePath", basePath); + + Binding binding = port.getBinding(); + PortType portType = binding.getPortType(); + HashMap selectedOperationList = selectedOperations.getSelectedOperations(); + + for (Operation op : portType.getOperations()) { + // the current operations is not in the list; skip. + if (selectedOperationList.size() > 0 && !selectedOperationList.containsKey(op.getName())) { + continue; + } + + operation = new JsonObject(); + operationDetails = new JsonObject(); + + String resourcePath = operationsMap.getResourcePath(op.getName(), selectedOperationList); + if (!ALLPOST) { + verb = operationsMap.getVerb(op.getName(), selectedOperationList).toLowerCase(); + } else { // else POST + verb = new String("POST").toLowerCase(); + } + + if (RPCSTYLE) { + parseParts(op.getInput().getMessage().getParts(), wsdl.getSchemas(), op.getName(), + OASUtils.createComplexType(op.getName(), "0", "1")); + + if (!verb.equalsIgnoreCase("GET")) { + parameters = OASUtils.getBodyParameter(op.getName()); } else { - return soap12Namespace; + parameters = OASUtils.getQueryParameters(queryParams); } - } - - private String buildSOAPRequest(List parts, List schemas, String rootElement, String rootNamespace, - boolean generateParts) { - - LOGGER.entering(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - - String prefix = getPrefix(rootNamespace); - String soapRequest = null; - - if (RPCSTYLE) { - soapRequest = "\n\n" + "<" - + prefix + ":" + rootElement + ">\n"; + queryParams.clear(); + } else { + if (op.getInput().getMessage().getParts().size() == 0) { + // TODO: handle 0 parts } else { - soapRequest = "\n\n"; - } + com.predic8.schema.Element eInput = op.getInput().getMessage().getParts().get(0).getElement(); + getOASDefinitions(wsdl, eInput); - if (generateParts) { - try { - soapRequest = parseParts(parts, schemas, rootElement, rootNamespace, prefix, soapRequest); - } catch (Exception e) { - LOGGER.warning( - "Failed to parse parts. Not generating SOAP Template. Try changing the verb to POST/PUT"); - } + if (!verb.equalsIgnoreCase("GET")) { + parameters = OASUtils.getBodyParameter(eInput.getName()); + } else { + parameters = OASUtils.getQueryParameters(queryParams); + } } - if (RPCSTYLE) { - soapRequest += "\n"; - } - - soapRequest += "\n"; - - LOGGER.exiting(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - return soapRequest; - } - - private void buildXPath(com.predic8.schema.Element e, String rootElement, String rootNamespace, String rootPrefix, - boolean removeNamespace) { - LOGGER.entering(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - - Rule r = null; - String xpathString = ""; - String prefix = "NULL"; - String namespaceUri = "NULL"; - String soapElements = "/soapenv:Envelope/soapenv:Body"; - String lastElement = ""; - - for (Map.Entry entry : xpathElement.entrySet()) { - xpathString = xpathString + "/" + rootPrefix + ":" + entry.getValue(); - lastElement = entry.getValue(); - } - - // add the last element to xpath - if (!lastElement.equalsIgnoreCase(e.getName())) - xpathString = xpathString + "/" + rootPrefix + ":" + e.getName(); - - r = new Rule(soapElements + xpathString, prefix, namespaceUri, "descendant"); - ruleList.add(r); - LOGGER.exiting(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - - } - - private void buildXPath(com.predic8.schema.Element e, String rootElement, String rootNamespace, String rootPrefix) { - LOGGER.entering(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - Rule r = null; - String xpathString = ""; - String soapElements = "/soapenv:Envelope/soapenv:Body"; - String prefix = getPrefix(e.getNamespaceUri()); - String namespaceUri = e.getNamespaceUri(); - for (Map.Entry entry : xpathElement.entrySet()) { - xpathString = xpathString + "/" + rootPrefix + ":" + entry.getValue(); - } - - r = new Rule(soapElements + xpathString, prefix, namespaceUri); - ruleList.add(r); - LOGGER.exiting(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - } - - private void buildXPath(String namespaceUri, String rootElement, String rootNamespace, String rootPrefix) { - LOGGER.entering(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - Rule r = null; - String prefix = getPrefix(namespaceUri); - String soapElements = "/soapenv:Envelope/soapenv:Body"; - String xpathString = ""; - - for (Map.Entry entry : xpathElement.entrySet()) { - xpathString = xpathString + "/" + rootPrefix + ":" + entry.getValue(); - } - - r = new Rule(soapElements + xpathString + "/@*", prefix, namespaceUri); - ruleList.add(r); - - cleanUpXPath(); - LOGGER.exiting(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - } - - private String getNamespacesAsString(boolean removeBlackListed) { - String namespaces = ""; - for (Map.Entry entry : namespace.entrySet()) { - if (removeBlackListed) { - if (!isBlackListed(entry.getValue())) { - namespaces += " xmlns:" + entry.getKey() + "=\"" + entry.getValue() + "\""; - } - } else { - namespaces += " xmlns:" + entry.getKey() + "=\"" + entry.getValue() + "\""; - } - } - return namespaces; - } - - private static boolean isBlackListed(String namespaceURI) { - return blackListedNamespaces.contains(namespaceURI); - } - - private String getParentNamepace(com.predic8.schema.Element e) { - XMLElement parent = e.getParent(); - - try { - return parent.getNamespaceUri(); - } catch (NullPointerException npe) { - if (e.getNamespaceUri() != null) - return e.getNamespaceUri(); - else - return null; - } - } - - @SuppressWarnings("unchecked") - private APIMap createAPIMap(Operation op, Definitions wsdl, String verb, String resourcePath, XMLUtils xmlUtils) - throws Exception { - - LOGGER.entering(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - - APIMap apiMap = null; - String soapRequest = ""; - - namespace = (Map) op.getNamespaceContext(); + queryParams.clear(); try { - if (verb.equalsIgnoreCase("GET")) { - - soapRequest = buildSOAPRequest(op.getInput().getMessage().getParts(), wsdl.getSchemas(), op.getName(), - op.getNamespaceUri(), true); - - if (op.getInput().getMessage().getParts().size() == 0) { - apiMap = new APIMap(null, soapRequest, resourcePath, verb, op.getName(), false); - } else { - KeyValue kv = xmlUtils.replacePlaceHolders(soapRequest); - apiMap = new APIMap(kv.getValue(), kv.getKey(), resourcePath, verb, op.getName(), false); - } - } else { - soapRequest = buildSOAPRequest(op.getInput().getMessage().getParts(), wsdl.getSchemas(), op.getName(), - op.getNamespaceUri(), true); - - String namespaceUri = op.getNamespaceUri(); - String prefix = getPrefix(namespaceUri); - - if (soapVersion.equalsIgnoreCase(SOAP_11)) { - xmlUtils.generateRootNamespaceXSLT(SOAP2API_XSLT11_TEMPLATE, SOAP2API_XSL, op.getName(), prefix, - null, namespaceUri, namespace); - } else { - xmlUtils.generateRootNamespaceXSLT(SOAP2API_XSLT12_TEMPLATE, SOAP2API_XSL, op.getName(), prefix, - null, namespaceUri, namespace); - } - - if (ruleList.size() > 0) { - RuleSet rs = new RuleSet(); - rs.addRuleList(ruleList); - xmlUtils.generateOtherNamespacesXSLT(SOAP2API_XSL, op.getName(), rs.getTransform(soapVersion), - namespace); - ruleList.clear(); - apiMap = new APIMap("", soapRequest, resourcePath, verb, op.getName(), true); - } else { - apiMap = new APIMap("", soapRequest, resourcePath, verb, op.getName(), false); - } - } + if (op.getOutput() != null) { + if (op.getOutput().getMessage().getParts().size() > 0) { + com.predic8.schema.Element eOutput = op.getOutput().getMessage().getParts().get(0).getElement(); + if (eOutput != null) { + getOASDefinitions(wsdl, eOutput); + operationDetails.add("responses", OASUtils.getResponse(eOutput.getName())); + } + } + } } catch (Exception e) { - e.printStackTrace(); - throw e; - } - - LOGGER.exiting(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - return apiMap; - } - - public String getSOAPVersion(String wsdlPath) throws NoServicesFoundException { - - LOGGER.entering(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - - Service service = null; - com.predic8.wsdl.Port port = null; - WSDLParser2 parser = new WSDLParser2(); - Definitions wsdl = null; - - wsdl = parser.parse(wsdlPath); - if (wsdl.getServices().size() == 0) { - LOGGER.severe("No services were found in the WSDL"); - throw new NoServicesFoundException("No services were found in the WSDL"); - } - - if (serviceName != null) { - for (Service svc : wsdl.getServices()) { - if (svc.getName().equalsIgnoreCase(serviceName)) { - service = svc; - break; - } - } - if (service == null) { // didn't find any service matching name - LOGGER.severe("No matching services were found in the WSDL"); - throw new NoServicesFoundException("No matching services were found in the WSDL"); - } - } else { - service = wsdl.getServices().get(0); // get the first service + //Ignore any errors here. Just don't generate the OAS for this portion } + } - if (portName != null) { - for (com.predic8.wsdl.Port prt : service.getPorts()) { - if (prt.getName().equalsIgnoreCase(portName)) { - port = prt; - } - } - if (port == null) { // didn't find any port matching name - LOGGER.severe("No matching port was found in the WSDL"); - throw new NoServicesFoundException("No matching port found in the WSDL"); - } - } else { - port = service.getPorts().get(0); // get first port - } - - LOGGER.exiting(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - return port.getBinding().getProtocol().toString(); - - } - - private void getOASDefinitions(Definitions wsdl, com.predic8.schema.Element e) { + operationDetails.addProperty("description", "Implements WSDL operation " + op.getName()); + operationDetails.add("parameters", parameters); - LOGGER.entering(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); + operation.add(verb, operationDetails); - if (e != null) { - TypeDefinition typeDefinition = null; - if (e.getEmbeddedType() != null) { - typeDefinition = e.getEmbeddedType(); - } else { - typeDefinition = getTypeFromSchema(e.getType(), wsdl.getSchemas()); - } - if (typeDefinition instanceof ComplexType) { - ComplexType ct = (ComplexType) typeDefinition; - JsonObject rootElement = OASUtils.createComplexType(e.getName(), e.getMinOccurs(), e.getMaxOccurs()); - definitions.add(e.getName(), rootElement); - parseSchema(ct.getModel(), wsdl.getSchemas(), e.getName(), rootElement); - } - } - LOGGER.exiting(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); + if (paths.has(resourcePath) && !paths.get(resourcePath).isJsonNull()) { + JsonObject resource = paths.getAsJsonObject(resourcePath); + resource.add(verb.toLowerCase(), operationDetails); + } else { + paths.add(resourcePath, operation); + } } - private void getWSDLDetails(String wsdlPath) throws Exception { - LOGGER.entering(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - - Service service = null; - List ports = new ArrayList(); - List services = new ArrayList(); - - try { - WSDLParser2 parser = new WSDLParser2(); - wsdl = parser.parse(wsdlPath); - if (wsdl.getServices().size() == 0) { - LOGGER.severe("No services were found in the WSDL"); - throw new NoServicesFoundException("No services were found in the WSDL"); - } - } catch (Exception e) { - e.printStackTrace(); - LOGGER.severe(e.getLocalizedMessage()); - throw e; - } - - KeyValue map = StringUtils.proxyNameAndBasePath(wsdlPath); - - if (serviceName != null) { - for (Service svc : wsdl.getServices()) { - if (svc.getName().equalsIgnoreCase(serviceName)) { - service = svc; - LOGGER.fine("Found Service: " + service.getName()); - break; - } - } - if (service == null) { // didn't find any service matching name - LOGGER.severe("No matching services were found in the WSDL"); - throw new NoServicesFoundException("No matching services were found in the WSDL"); - } else { - proxyName = serviceName; - } - } else { - service = wsdl.getServices().get(0); // get the first service - LOGGER.fine("Found Service: " + service.getName()); - serviceName = service.getName(); - proxyName = serviceName; - } - - if (basePath == null) { - if (serviceName != null) { - basePath = "/" + serviceName.toLowerCase(); - } else { - basePath = map.getValue(); - } - } - - if (portName != null) { - for (com.predic8.wsdl.Port prt : service.getPorts()) { - if (prt.getName().equalsIgnoreCase(portName)) { - port = prt; - } - } - if (port == null) { // didn't find any port matching name - LOGGER.severe("No matching port was found in the WSDL"); - throw new NoServicesFoundException("No matching port found in the WSDL"); - } - } else { - port = service.getPorts().get(0); // get first port - portName = port.getName(); - } - LOGGER.fine("Found Port: " + port.getName()); - - Binding binding = port.getBinding(); - soapVersion = binding.getProtocol().toString(); - - // EDGEUI-659 - if (!soapVersion.equalsIgnoreCase(SOAP_11) && !soapVersion.equalsIgnoreCase(SOAP_12)) { - // set default - LOGGER.warning("Unknow SOAP Version. Setting to SOAP 1.1"); - soapVersion = SOAP_11; - } - - if (binding.getStyle().toLowerCase().contains("rpc")) { - LOGGER.info("Binding Stype: " + binding.getStyle()); - RPCSTYLE = true; - } else if (binding.getStyle().toLowerCase().contains("document")) { - LOGGER.info("Binding Stype: " + binding.getStyle()); - RPCSTYLE = false; - } else { - LOGGER.info(binding.getStyle() + ". Treating as document"); - RPCSTYLE = false; - } - - targetEndpoint = port.getAddress().getLocation(); + final Gson gson = new GsonBuilder().setPrettyPrinting().create(); + oasContent = gson.toJson(oasObject); + LOGGER.fine(oasContent); - // start feature - port.getAddress().setLocation("@request.header.host#" + basePath); - ports.add(port); - service.setPorts(ports); - services.add(service); - wsdlContent = wsdl.getAsString(); - // end feature + LOGGER.info("Generated OpenAPI Spec successfully."); + LOGGER.exiting(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); - LOGGER.info("Retrieved WSDL endpoint: " + targetEndpoint); + return ""; + } - String[] schemes = { "http", "https" }; - UrlValidator urlValidator = new UrlValidator(schemes, UrlValidator.ALLOW_LOCAL_URLS); + private boolean prepareTargetFolder() { + LOGGER.entering(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); - if (!urlValidator.isValid(targetEndpoint)) { - LOGGER.warning("Target endpoint is not http/https URL. Assigning a default value"); - targetEndpoint = "http://localhost:8080/soap"; - } - - LOGGER.exiting(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - } + File f = new File(buildFolder); - @SuppressWarnings("unchecked") - private void parseWSDL() throws Exception { - LOGGER.entering(GenerateProxy.class.getName(), new Object() { + if (f.isDirectory()) { // ensure target is a folder + LOGGER.fine("Target is a folder"); + File apiproxy = new File(f.getAbsolutePath() + File.separator + "apiproxy"); + if (apiproxy.exists()) { + LOGGER.severe("Folder called apiproxy already exists"); + LOGGER.exiting(CLASS_NAME, new Object() { }.getClass().getEnclosingMethod().getName()); - XMLUtils xmlUtils = new XMLUtils(); - - StringWriter writer = new StringWriter(); - SOARequestCreator creator = new SOARequestCreator(wsdl, new RequestTemplateCreator(), - new MarkupBuilder(writer)); - // edgeui-654 - creator.setMaxRecursionDepth(2); - - Binding binding = port.getBinding(); - PortType portType = binding.getPortType(); - String bindingName = binding.getName(); - - LOGGER.fine("Found Binding: " + bindingName + " Binding Protocol: " + soapVersion + " Prefix: " - + binding.getPrefix() + " NamespaceURI: " + binding.getNamespaceUri()); - - APIMap apiMap = null; - HashMap selectedOperationList = selectedOperations.getSelectedOperations(); + return false; + } else { + apiproxy.mkdir(); + LOGGER.fine("created apiproxy folder"); + new File(apiproxy.getAbsolutePath() + File.separator + "policies").mkdirs(); + LOGGER.fine("created policies folder"); + new File(apiproxy.getAbsolutePath() + File.separator + "proxies").mkdirs(); + LOGGER.fine("created proxies folder"); + new File(apiproxy.getAbsolutePath() + File.separator + "targets").mkdirs(); + LOGGER.fine("created targets folder"); + if (!PASSTHRU) { + File xsltFolder = new File( + apiproxy.getAbsolutePath() + File.separator + "resources" + File.separator + "xsl"); + xsltFolder.mkdirs(); + SOAP2API_XSL = xsltFolder.getAbsolutePath() + File.separator; - for (Operation op : portType.getOperations()) { - LOGGER.fine("Found Operation Name: " + op.getName() + " Prefix: " + op.getPrefix() + " NamespaceURI: " - + op.getNamespaceUri()); - try { - // the current operations is not in the list; skip. - if (selectedOperationList.size() > 0 && !selectedOperationList.containsKey(op.getName())) { - continue; - } - // if passthru, then do nothing much - if (PASSTHRU) { - if (RPCSTYLE) { - apiMap = new APIMap(null, null, null, "POST", op.getName(), false); - } else { - // get root element - com.predic8.schema.Element requestElement = op.getInput().getMessage().getParts().get(0) - .getElement(); - if (requestElement != null) { - apiMap = new APIMap(null, null, null, "POST", requestElement.getName(), false); - } else { - apiMap = new APIMap(null, null, null, "POST", op.getName(), false); - } - } - } else { - String resourcePath = operationsMap.getResourcePath(op.getName(), selectedOperationList); - String verb = ""; - // if all post options is not turned on, then interpret the - // operation from opsmap - if (!ALLPOST) { - verb = operationsMap.getVerb(op.getName(), selectedOperationList); - } else { // else POST - verb = "POST"; - } + File jsFolder = new File( + apiproxy.getAbsolutePath() + File.separator + "resources" + File.separator + "jsc"); + jsFolder.mkdirs(); - if (RPCSTYLE) { - apiMap = createAPIMap(op, wsdl, verb, resourcePath, xmlUtils); - } else {// document style - // there can be soap messages with no parts. membrane - // soap can't construct soap - // template for such messages. manually build - if (op.getInput().getMessage().getParts().size() == 0) { - apiMap = createAPIMap(op, wsdl, verb, resourcePath, xmlUtils); - } else { - com.predic8.schema.Element requestElement = op.getInput().getMessage().getParts().get(0) - .getElement(); - - if (requestElement != null) { - namespace = (Map) requestElement.getNamespaceContext(); - - if (verb.equalsIgnoreCase("GET")) { - if (soapVersion.equalsIgnoreCase(SOAP_11) - || soapVersion.equalsIgnoreCase(SOAP_12)) { - creator.setCreator(new RequestTemplateCreator()); - // use membrane SOAP to generate a SOAP - // Request - try { - creator.createRequest(port.getName(), op.getName(), binding.getName()); - KeyValue kv = xmlUtils - .replacePlaceHolders(writer.toString()); - - // sometimes membrane soa generates - // invalid soap - // this will cause the bundle to not - // be uploaded - - // store the operation name, SOAP - // Request and - // the - // expected JSON Body in the map - apiMap = new APIMap(kv.getValue(), kv.getKey(), resourcePath, verb, - requestElement.getName(), false); - writer.getBuffer().setLength(0); - } catch (Exception e) { - LOGGER.warning("Membrane SOA failed to generate template."); - apiMap = createAPIMap(op, wsdl, verb, resourcePath, xmlUtils); - } - } else { - apiMap = createAPIMap(op, wsdl, verb, resourcePath, xmlUtils); - } - } else { - String namespaceUri = null; - if (requestElement.getType() != null) { - namespaceUri = requestElement.getType().getNamespaceURI(); - } else { - namespaceUri = requestElement.getEmbeddedType().getNamespaceUri(); - } - String prefix = getPrefix(namespaceUri); - - if (soapVersion.equalsIgnoreCase(SOAP_11)) { - xmlUtils.generateRootNamespaceXSLT(SOAP2API_XSLT11_TEMPLATE, SOAP2API_XSL, - op.getName(), prefix, requestElement.getName(), namespaceUri, - namespace); - } else { - xmlUtils.generateRootNamespaceXSLT(SOAP2API_XSLT12_TEMPLATE, SOAP2API_XSL, - op.getName(), prefix, requestElement.getName(), namespaceUri, - namespace); - } - - TypeDefinition typeDefinition = null; - - if (requestElement.getEmbeddedType() != null) { - typeDefinition = requestElement.getEmbeddedType(); - } else { - typeDefinition = getTypeFromSchema(requestElement.getType(), wsdl.getSchemas()); - } - if (typeDefinition instanceof ComplexType) { - ComplexType ct = (ComplexType) typeDefinition; - xpathElement.put(level, requestElement.getName()); - parseSchema(ct.getModel(), wsdl.getSchemas(), requestElement.getName(), - namespaceUri, prefix); - } - if (TOO_MANY) { - LOGGER.warning(op.getName() - + ": Too many nested schemas or elements. Skipping XSLT gen. Manual intervention necessary"); - ruleList.clear(); - apiMap = new APIMap("", "", resourcePath, verb, requestElement.getName(), - false); - } else { - // rule list is > 0, there are - // additional - // namespaces to add - if (ruleList.size() > 0) { - RuleSet rs = new RuleSet(); - rs.addRuleList(ruleList); - xmlUtils.generateOtherNamespacesXSLT(SOAP2API_XSL, op.getName(), - rs.getTransform(soapVersion), namespace); - ruleList.clear(); - apiMap = new APIMap("", "", resourcePath, verb, requestElement.getName(), - true); - } else { - apiMap = new APIMap("", "", resourcePath, verb, requestElement.getName(), - false); - } - } - } - } else {// if the request element is null, it - // appears membrane soap failed again. - // attempting manual build - apiMap = createAPIMap(op, wsdl, verb, resourcePath, xmlUtils); - } - } - } - } - messageTemplates.put(op.getName(), apiMap); - } catch (Exception e) { - LOGGER.severe(e.getMessage()); - e.printStackTrace(); - throw e; - } + LOGGER.fine("created resources folder"); } - - if (messageTemplates.size() == 0) { - LOGGER.exiting(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - throw new BindingNotFoundException("Soap version provided did not match any binding in WSDL"); - } - + LOGGER.info("Target proxy folder setup complete"); + LOGGER.exiting(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); + return true; + } + } else { + LOGGER.severe("Target folder is not a directory"); + LOGGER.exiting(CLASS_NAME, new Object() { + }.getClass().getEnclosingMethod().getName()); + return false; + } + } + + public InputStream begin(String proxyDescription, String wsdlPath) throws Exception { + + LOGGER.entering(CLASS_NAME, new Object() { }.getClass().getEnclosingMethod().getName()); + + LOGGER.fine("Preparing target folder"); + String zipFolder = null; + Path tempDirectory = null; + InputStream is = null; + GenerateBundle generateBundle = new GenerateBundle(); + + try { + if (buildFolder == null) { + tempDirectory = Files.createTempDirectory(null); + buildFolder = tempDirectory.toAbsolutePath().toString(); + } + zipFolder = buildFolder + File.separator + "apiproxy"; + + // prepare the target folder (create apiproxy folder and sub-folders + if (prepareTargetFolder()) { + + // if not passthru read conf file to interpret soap operations + // to resources if (!PASSTHRU) { - for (Binding bnd : wsdl.getBindings()) { - if (bindingName.equalsIgnoreCase(bnd.getName())) { - for (BindingOperation bop : bnd.getOperations()) { - if (selectedOperationList.size() > 0 && !selectedOperationList.containsKey(bop.getName())) { - // the current operations is not in the list; skip. - continue; - } - if (bnd.getBinding() instanceof AbstractSOAPBinding) { - LOGGER.fine("Found Operation Name: " + bop.getName() + " SOAPAction: " - + bop.getOperation().getSoapAction()); - APIMap apiM = messageTemplates.get(bop.getName()); - apiM.setSoapAction(bop.getOperation().getSoapAction()); - messageTemplates.put(bop.getName(), apiM); - } - } - } - } + operationsMap.readOperationsMap(opsMap); + LOGGER.info("Read operations map"); } - LOGGER.exiting(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - } - - private String generateOAS() throws Exception { - - LOGGER.entering(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - - @SuppressWarnings("resource") - String oasTemplate = new Scanner(getClass().getResourceAsStream(OAS_TEMPLATE), "UTF-8").useDelimiter("\\A") - .next(); - JsonObject oasObject = new JsonParser().parse(oasTemplate).getAsJsonObject(); - JsonObject paths = oasObject.getAsJsonObject("paths"); - JsonObject info = oasObject.getAsJsonObject("info"); - JsonObject operation = null; - JsonObject operationDetails = null; - JsonArray parameters = null; - - String verb = ""; - - definitions = oasObject.getAsJsonObject("definitions"); - info.addProperty("title", proxyName); - oasObject.addProperty("host", "@request.header.host#"); - oasObject.addProperty("basePath", basePath); + getWSDLDetails(wsdlPath); - Binding binding = port.getBinding(); - PortType portType = binding.getPortType(); - HashMap selectedOperationList = selectedOperations.getSelectedOperations(); + // generate OpenAPI Specification + generateOAS(); + // parse the wsdl + parseWSDL(); + LOGGER.info("Parsed WSDL Successfully."); - for (Operation op : portType.getOperations()) { - // the current operations is not in the list; skip. - if (selectedOperationList.size() > 0 && !selectedOperationList.containsKey(op.getName())) { - continue; - } - - operation = new JsonObject(); - operationDetails = new JsonObject(); - - String resourcePath = operationsMap.getResourcePath(op.getName(), selectedOperationList); - if (!ALLPOST) { - verb = operationsMap.getVerb(op.getName(), selectedOperationList).toLowerCase(); - } else { // else POST - verb = new String("POST").toLowerCase(); - } - - if (RPCSTYLE) { - parseParts(op.getInput().getMessage().getParts(), wsdl.getSchemas(), op.getName(), - OASUtils.createComplexType(op.getName(), "0", "1")); - - if (!verb.equalsIgnoreCase("GET")) { - parameters = OASUtils.getBodyParameter(op.getName()); - } else { - parameters = OASUtils.getQueryParameters(queryParams); - } - queryParams.clear(); - - } else { - if (op.getInput().getMessage().getParts().size() == 0) { - // TODO: handle 0 parts - } else { - com.predic8.schema.Element eInput = op.getInput().getMessage().getParts().get(0).getElement(); - getOASDefinitions(wsdl, eInput); - - if (!verb.equalsIgnoreCase("GET")) { - parameters = OASUtils.getBodyParameter(eInput.getName()); - } else { - parameters = OASUtils.getQueryParameters(queryParams); - } - } - - queryParams.clear(); - - try { - if (op.getOutput() != null) { - if (op.getOutput().getMessage().getParts().size() > 0) { - com.predic8.schema.Element eOutput = op.getOutput().getMessage().getParts().get(0).getElement(); - if (eOutput != null) { - getOASDefinitions(wsdl, eOutput); - operationDetails.add("responses", OASUtils.getResponse(eOutput.getName())); - } - } - } - } catch (Exception e) { - //Ignore any errors here. Just don't generate the OAS for this portion - } - } - - operationDetails.addProperty("description", "Implements WSDL operation " + op.getName()); - operationDetails.add("parameters", parameters); - - operation.add(verb, operationDetails); - - if (paths.has(resourcePath) && !paths.get(resourcePath).isJsonNull()) { - JsonObject resource = paths.getAsJsonObject(resourcePath); - resource.add(verb.toLowerCase(), operationDetails); - } else { - paths.add(resourcePath, operation); - } + if (!DESCSET) { + proxyDescription += serviceName; } - final Gson gson = new GsonBuilder().setPrettyPrinting().create(); - oasContent = gson.toJson(oasObject); - LOGGER.fine(oasContent); - - LOGGER.info("Generated OpenAPI Spec successfully."); - LOGGER.exiting(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - - return ""; - } - - private boolean prepareTargetFolder() { - LOGGER.entering(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); + LOGGER.info("Base Path: " + basePath); + LOGGER.info("WSDL Path: " + wsdlPath); + LOGGER.info("Build Folder: " + buildFolder); + LOGGER.info("SOAP Version: " + soapVersion); + LOGGER.info("Proxy Name: " + proxyName); + LOGGER.info("Proxy Description: " + proxyDescription); - File f = new File(buildFolder); + // create the basic proxy structure from templates + writeAPIProxy(proxyDescription); + LOGGER.info("Generated Apigee proxy file."); - if (f.isDirectory()) { // ensure target is a folder - LOGGER.fine("Target is a folder"); - File apiproxy = new File(f.getAbsolutePath() + File.separator + "apiproxy"); - if (apiproxy.exists()) { - LOGGER.severe("Folder called apiproxy already exists"); - LOGGER.exiting(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - return false; - } else { - apiproxy.mkdir(); - LOGGER.fine("created apiproxy folder"); - new File(apiproxy.getAbsolutePath() + File.separator + "policies").mkdirs(); - LOGGER.fine("created policies folder"); - new File(apiproxy.getAbsolutePath() + File.separator + "proxies").mkdirs(); - LOGGER.fine("created proxies folder"); - new File(apiproxy.getAbsolutePath() + File.separator + "targets").mkdirs(); - LOGGER.fine("created targets folder"); - if (!PASSTHRU) { - File xsltFolder = new File( - apiproxy.getAbsolutePath() + File.separator + "resources" + File.separator + "xsl"); - xsltFolder.mkdirs(); - SOAP2API_XSL = xsltFolder.getAbsolutePath() + File.separator; - - File jsFolder = new File( - apiproxy.getAbsolutePath() + File.separator + "resources" + File.separator + "jsc"); - jsFolder.mkdirs(); - - LOGGER.fine("created resources folder"); - } - LOGGER.info("Target proxy folder setup complete"); - LOGGER.exiting(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - return true; - } + if (!PASSTHRU) { + LOGGER.info("Generated SOAP Message Templates."); + writeSOAP2APIProxyEndpoint(proxyDescription); + LOGGER.info("Generated proxies XML."); + writeStdPolicies(); + LOGGER.info("Copied standard policies."); + writeTargetEndpoint(); + LOGGER.info("Generated target XML."); } else { - LOGGER.severe("Target folder is not a directory"); - LOGGER.exiting(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - return false; - } - } - - public InputStream begin(String proxyDescription, String wsdlPath) throws Exception { - - LOGGER.entering(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - - LOGGER.fine("Preparing target folder"); - String zipFolder = null; - Path tempDirectory = null; - InputStream is = null; - GenerateBundle generateBundle = new GenerateBundle(); - + writeStdPolicies(); + LOGGER.info("Copied standard policies."); + writeTargetEndpoint(); + LOGGER.info("Generated target XML."); + writeSOAPPassThruProxyEndpointConditions(proxyDescription); + } + + File file = generateBundle.build(zipFolder, proxyName); + LOGGER.info("Generated Apigee Edge API Bundle file: " + proxyName + ".zip"); + LOGGER.exiting(CLASS_NAME, new Object() { }.getClass().getEnclosingMethod().getName()); + return new ByteArrayInputStream(Files.readAllBytes(file.toPath())); + } else { + LOGGER.exiting(CLASS_NAME, new Object() {}.getClass().getEnclosingMethod().getName()); + throw new TargetFolderException("Error preparing target folder; target folder not empty " + buildFolder); + } + } catch (Exception e) { + LOGGER.severe(e.getMessage()); + throw e; + } finally { + if (tempDirectory != null) { try { - if (buildFolder == null) { - tempDirectory = Files.createTempDirectory(null); - buildFolder = tempDirectory.toAbsolutePath().toString(); - } - zipFolder = buildFolder + File.separator + "apiproxy"; - - // prepare the target folder (create apiproxy folder and sub-folders - if (prepareTargetFolder()) { - - // if not passthru read conf file to interpret soap operations - // to resources - if (!PASSTHRU) { - operationsMap.readOperationsMap(opsMap); - LOGGER.info("Read operations map"); - } + Files.walkFileTree(tempDirectory, new SimpleFileVisitor() { + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + Files.delete(file); + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { + Files.delete(dir); + return FileVisitResult.CONTINUE; + } + + }); + } catch (IOException e) { + LOGGER.severe(e.getMessage()); + } + } + } + } + + public static void usage() { + System.out.println(""); + System.out.println("Usage: java -jar wsdl2apigee.jar -wsdl={url or path to wsdl} "); + System.out.println(""); + System.out.println("Options:"); + System.out.println("-passthru= default is false;"); + System.out.println("-desc=\"description for proxy\""); + System.out.println("-service=servicename if wsdl has > 1 service, enter service name"); + System.out.println("-port=portname if service has > 1 port, enter port name"); + System.out.println("-opsmap=opsmapping.xml mapping file that to map wsdl operation to http verb"); + System.out.println("-allpost= set to true if all operations are http verb; default is false"); + System.out.println("-vhosts="); + System.out.println("-build=specify build folder default is temp/tmp"); + System.out.println("-oauth= default is false"); + System.out.println("-apikey= default is false"); + System.out.println("-quota= default is false; works only if apikey or oauth is set"); + System.out.println("-basepath=specify base path"); + System.out.println("-cors= default is false"); + System.out.println("-debug= default is false"); + System.out.println(""); + System.out.println(""); + System.out.println("Examples:"); + System.out.println("$ java -jar wsdl2apigee.jar -wsdl=\"https://paypalobjects.com/wsdl/PayPalSvc.wsdl\""); + System.out.println( + "$ java -jar wsdl2apigee.jar -wsdl=\"https://paypalobjects.com/wsdl/PayPalSvc.wsdl\" -passthru=true"); + System.out.println( + "$ java -jar wsdl2apigee.jar -wsdl=\"https://paypalobjects.com/wsdl/PayPalSvc.wsdl\" -vhosts=secure"); + System.out.println(""); + System.out.println("OpsMap:"); + System.out.println("A file that maps WSDL operations to HTTP Verbs. A Sample Ops Mapping file looks like:"); + System.out.println(""); + System.out.println( + "{\r\n \"proxywriter\": {\r\n \"get\": {\r\n \"operation\": [\r\n {\r\n \"pattern\": \"get\",\r\n \"location\": \"beginsWith\"\r\n },\r\n {\r\n \"pattern\": \"inq\",\r\n \"location\": \"beginsWith\"\r\n },\r\n {\r\n \"pattern\": \"search\",\r\n \"location\": \"beginsWith\"\r\n },\r\n {\r\n \"pattern\": \"list\",\r\n \"location\": \"beginsWith\"\r\n },\r\n {\r\n \"pattern\": \"retrieve\",\r\n \"location\": \"beginsWith\"\r\n }\r\n ]\r\n },\r\n \"post\": {\r\n \"operation\": [\r\n {\r\n \"pattern\": \"create\",\r\n \"location\": \"contains\"\r\n },\r\n {\r\n \"pattern\": \"add\",\r\n \"location\": \"beginsWith\"\r\n },\r\n {\r\n \"pattern\": \"process\",\r\n \"location\": \"beginsWith\"\r\n }\r\n ]\r\n },\r\n \"put\": {\r\n \"operation\": [\r\n {\r\n \"pattern\": \"update\",\r\n \"location\": \"beginsWith\"\r\n },\r\n {\r\n \"pattern\": \"change\",\r\n \"location\": \"beginsWith\"\r\n },\r\n {\r\n \"pattern\": \"modify\",\r\n \"location\": \"beginsWith\"\r\n },\r\n {\r\n \"pattern\": \"set\",\r\n \"location\": \"beginsWith\"\r\n }\r\n ]\r\n },\r\n \"delete\": {\r\n \"operation\": [\r\n {\r\n \"pattern\": \"delete\",\r\n \"location\": \"beginsWith\"\r\n },\r\n {\r\n \"pattern\": \"remove\",\r\n \"location\": \"beginsWith\"\r\n },\r\n {\r\n \"pattern\": \"del\",\r\n \"location\": \"beginsWith\"\r\n }\r\n ]\r\n }\r\n }\r\n}"); + + System.out.println("\n\n"); + System.out.println("Examples:"); + System.out.println( + "$ java -jar wsdl2apigee.jar -wsdl=\"http://www.thomas-bayer.com/axis2/services/BLZService?wsdl\" -oas=true"); + } + + private static List convertPorts(List ports, + List portTypes) { + List list = new ArrayList<>(ports.size()); + for (com.predic8.wsdl.Port port : ports) { + final Object protocol = port.getBinding().getProtocol(); + if (protocol != null) { + final String protocolStr = protocol.toString(); + if (SOAP_11.equalsIgnoreCase(protocolStr) || SOAP_12.equalsIgnoreCase(protocolStr)) { + list.add(new WsdlDefinitions.Port(port.getName(), convertOperations(port.getBinding(), portTypes))); + } + } + } + return list; + } + + private static List convertOperations(Binding binding, List portTypes) { + List list = new ArrayList<>(); + OpsMap opsMap = null; + try { + opsMap = new OpsMap(OPSMAPPING_TEMPLATE); + } catch (Exception e) { + } + + binding.getOperations(); + for (BindingOperation bindingOperation : binding.getOperations()) { + final String operationName = bindingOperation.getName(); + final WsdlDefinitions.Operation operation = new WsdlDefinitions.Operation(operationName, + findDocForOperation(operationName, portTypes), opsMap.getVerb(operationName, null), + opsMap.getResourcePath(operationName, null), null); + list.add(operation); + } + return list; + } + + private static String findDocForOperation(String operationName, List portTypes) { + for (PortType portType : portTypes) { + final Operation operation = portType.getOperation(operationName); + if (operation != null) { + return operation.getDocumentation() != null ? operation.getDocumentation().getContent() : ""; + } + } + return ""; + } + + private static WsdlDefinitions definitionsToWsdlDefinitions(Definitions definitions) { + List services = new ArrayList<>(); + definitions.getServices(); + for (Service service : definitions.getServices()) { + final WsdlDefinitions.Service service1 = new WsdlDefinitions.Service(service.getName(), + convertPorts(service.getPorts(), definitions.getPortTypes())); + services.add(service1); + } + return new WsdlDefinitions(services); + } + + public static void main(String[] args) throws Exception { + + GenerateProxy genProxy = new GenerateProxy(); + + String wsdlPath = ""; + String proxyDescription = ""; + + Options opt = new Options(args, 1); + // the wsdl param contains the URL or FilePath to a WSDL document + opt.getSet().addOption("wsdl", Separator.EQUALS, Multiplicity.ONCE); + // if this flag it set, the generate a passthru proxy + opt.getSet().addOption("passthru", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); + // set this flag to pass proxy description + opt.getSet().addOption("desc", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); + // set this flag to specify service name + opt.getSet().addOption("service", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); + // set this flag to specify port name + opt.getSet().addOption("port", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); + // set this flag to specify operations map + opt.getSet().addOption("opsmap", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); + // set this flag to handle all operations via post verb + opt.getSet().addOption("allpost", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); + // set virtual hosts + opt.getSet().addOption("vhosts", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); + // set build path + opt.getSet().addOption("build", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); + // add verify oauth policy + opt.getSet().addOption("oauth", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); + // add verify apikey policy + opt.getSet().addOption("apikey", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); + // add impose quota policy + opt.getSet().addOption("quota", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); + // set basepath + opt.getSet().addOption("basepath", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); + // add enable cors conditions + opt.getSet().addOption("cors", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); + // generate OAS spec + opt.getSet().addOption("oas", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); + // set this flag to enable debug + opt.getSet().addOption("debug", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); + + opt.check(); + + if (opt.getSet().isSet("wsdl")) { + // React to option -wsdl + wsdlPath = opt.getSet().getOption("wsdl").getResultValue(0); + } else { + System.out.println("-wsdl is a madatory parameter"); + usage(); + System.exit(1); + } + + if (opt.getSet().isSet("passthru")) { + // React to option -passthru + genProxy.setPassThru(Boolean.parseBoolean(opt.getSet().getOption("passthru").getResultValue(0))); + if (opt.getSet().isSet("cors")) { + LOGGER.warning("WARNING: cors can only be enabled for SOAP to REST. This flag will be ignored."); + } + if (opt.getSet().isSet("desc")) { + // React to option -des + proxyDescription = opt.getSet().getOption("desc").getResultValue(0); + genProxy.setDesc(true); + } else { + proxyDescription = "Generated SOAP proxy from "; + } + } else { + genProxy.setPassThru(false); + if (opt.getSet().isSet("desc")) { + // React to option -des + proxyDescription = opt.getSet().getOption("desc").getResultValue(0); + genProxy.setDesc(true); + } else { + proxyDescription = "Generated SOAP to API proxy from "; + } + } + + if (opt.getSet().isSet("service")) { + // React to option -service + genProxy.setService(opt.getSet().getOption("service").getResultValue(0)); + if (opt.getSet().isSet("port")) { + // React to option -port + genProxy.setPort(opt.getSet().getOption("port").getResultValue(0)); + } + } + + if (opt.getSet().isSet("opsmap")) { + genProxy.setOpsMap(opt.getSet().getOption("opsmap").getResultValue(0)); + } else { + genProxy.setOpsMap(GenerateProxy.OPSMAPPING_TEMPLATE); + } + + if (opt.getSet().isSet("allpost")) { + genProxy.setAllPost(new Boolean(opt.getSet().getOption("allpost").getResultValue(0))); + } + + if (opt.getSet().isSet("vhosts")) { + genProxy.setVHost(opt.getSet().getOption("vhosts").getResultValue(0)); + } + + if (opt.getSet().isSet("build")) { + genProxy.setBuildFolder(opt.getSet().getOption("build").getResultValue(0)); + } + + if (opt.getSet().isSet("basepath")) { + genProxy.setBasePath(opt.getSet().getOption("basepath").getResultValue(0)); + } + + if (opt.getSet().isSet("cors")) { + genProxy.setCORS(new Boolean(opt.getSet().getOption("cors").getResultValue(0))); + } + + if (opt.getSet().isSet("oauth")) { + genProxy.setOAuth(new Boolean(opt.getSet().getOption("oauth").getResultValue(0))); + if (opt.getSet().isSet("quota")) { + genProxy.setQuotaOAuth(new Boolean(opt.getSet().getOption("quota").getResultValue(0))); + } + } + + if (opt.getSet().isSet("apikey")) { + genProxy.setAPIKey(new Boolean(opt.getSet().getOption("apikey").getResultValue(0))); + if (opt.getSet().isSet("quota")) { + genProxy.setQuotaAPIKey(new Boolean(opt.getSet().getOption("quota").getResultValue(0))); + } + } + + if (!opt.getSet().isSet("apikey") && !opt.getSet().isSet("oauth") && opt.getSet().isSet("quota")) { + LOGGER.warning("WARNING: Quota is applicable with apikey or oauth flags. This flag will be ignored"); + } + + if (opt.getSet().isSet("debug")) { + // enable debug + LOGGER.setLevel(Level.FINEST); + handler.setLevel(Level.FINEST); + } else { + LOGGER.setLevel(Level.INFO); + handler.setLevel(Level.INFO); + } - getWSDLDetails(wsdlPath); - - // generate OpenAPI Specification - generateOAS(); - // parse the wsdl - parseWSDL(); - LOGGER.info("Parsed WSDL Successfully."); - - if (!DESCSET) { - proxyDescription += serviceName; - } - - LOGGER.info("Base Path: " + basePath + "\nWSDL Path: " + wsdlPath); - LOGGER.info("Build Folder: " + buildFolder + "\nSOAP Version: " + soapVersion); - LOGGER.info("Proxy Name: " + proxyName + "\nProxy Description: " + proxyDescription); - - // create the basic proxy structure from templates - writeAPIProxy(proxyDescription); - LOGGER.info("Generated Apigee proxy file."); - - if (!PASSTHRU) { - LOGGER.info("Generated SOAP Message Templates."); - writeSOAP2APIProxyEndpoint(proxyDescription); - LOGGER.info("Generated proxies XML."); - writeStdPolicies(); - LOGGER.info("Copied standard policies."); - writeTargetEndpoint(); - LOGGER.info("Generated target XML."); - } else { - writeStdPolicies(); - LOGGER.info("Copied standard policies."); - writeTargetEndpoint(); - LOGGER.info("Generated target XML."); - writeSOAPPassThruProxyEndpointConditions(proxyDescription); - } - - File file = generateBundle.build(zipFolder, proxyName); - LOGGER.info("Generated Apigee Edge API Bundle file: " + proxyName + ".zip"); - LOGGER.exiting(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - return new ByteArrayInputStream(Files.readAllBytes(file.toPath())); - } else { - LOGGER.exiting(GenerateProxy.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - throw new TargetFolderException( - "Erorr is preparing target folder; target folder not empty " + buildFolder); - } - } catch (Exception e) { - LOGGER.severe(e.getMessage()); - throw e; - } finally { - if (tempDirectory != null) { - try { - Files.walkFileTree(tempDirectory, new SimpleFileVisitor() { - @Override - public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { - Files.delete(file); - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { - Files.delete(dir); - return FileVisitResult.CONTINUE; - } - - }); - } catch (IOException e) { - LOGGER.severe(e.getMessage()); - } - } - } + final InputStream begin = genProxy.begin(proxyDescription, wsdlPath); + if (begin != null) { + Files.copy(begin, new File(genProxy.proxyName + ".zip").toPath(), StandardCopyOption.REPLACE_EXISTING); } - public static void usage() { - System.out.println(""); - System.out.println("Usage: java -jar wsdl2apigee.jar -wsdl={url or path to wsdl} "); - System.out.println(""); - System.out.println("Options:"); - System.out.println("-passthru= default is false;"); - System.out.println("-desc=\"description for proxy\""); - System.out.println("-service=servicename if wsdl has > 1 service, enter service name"); - System.out.println("-port=portname if service has > 1 port, enter port name"); - System.out.println("-opsmap=opsmapping.xml mapping file that to map wsdl operation to http verb"); - System.out.println("-allpost= set to true if all operations are http verb; default is false"); - System.out.println("-vhosts="); - System.out.println("-build=specify build folder default is temp/tmp"); - System.out.println("-oauth= default is false"); - System.out.println("-apikey= default is false"); - System.out.println("-quota= default is false; works only if apikey or oauth is set"); - System.out.println("-basepath=specify base path"); - System.out.println("-cors= default is false"); - System.out.println("-debug= default is false"); - System.out.println(""); - System.out.println(""); - System.out.println("Examples:"); - System.out.println("$ java -jar wsdl2apigee.jar -wsdl=\"https://paypalobjects.com/wsdl/PayPalSvc.wsdl\""); - System.out.println( - "$ java -jar wsdl2apigee.jar -wsdl=\"https://paypalobjects.com/wsdl/PayPalSvc.wsdl\" -passthru=true"); - System.out.println( - "$ java -jar wsdl2apigee.jar -wsdl=\"https://paypalobjects.com/wsdl/PayPalSvc.wsdl\" -vhosts=secure"); - System.out.println(""); - System.out.println("OpsMap:"); - System.out.println("A file that maps WSDL operations to HTTP Verbs. A Sample Ops Mapping file looks like:"); - System.out.println(""); - System.out.println( - "{\r\n \"proxywriter\": {\r\n \"get\": {\r\n \"operation\": [\r\n {\r\n \"pattern\": \"get\",\r\n \"location\": \"beginsWith\"\r\n },\r\n {\r\n \"pattern\": \"inq\",\r\n \"location\": \"beginsWith\"\r\n },\r\n {\r\n \"pattern\": \"search\",\r\n \"location\": \"beginsWith\"\r\n },\r\n {\r\n \"pattern\": \"list\",\r\n \"location\": \"beginsWith\"\r\n },\r\n {\r\n \"pattern\": \"retrieve\",\r\n \"location\": \"beginsWith\"\r\n }\r\n ]\r\n },\r\n \"post\": {\r\n \"operation\": [\r\n {\r\n \"pattern\": \"create\",\r\n \"location\": \"contains\"\r\n },\r\n {\r\n \"pattern\": \"add\",\r\n \"location\": \"beginsWith\"\r\n },\r\n {\r\n \"pattern\": \"process\",\r\n \"location\": \"beginsWith\"\r\n }\r\n ]\r\n },\r\n \"put\": {\r\n \"operation\": [\r\n {\r\n \"pattern\": \"update\",\r\n \"location\": \"beginsWith\"\r\n },\r\n {\r\n \"pattern\": \"change\",\r\n \"location\": \"beginsWith\"\r\n },\r\n {\r\n \"pattern\": \"modify\",\r\n \"location\": \"beginsWith\"\r\n },\r\n {\r\n \"pattern\": \"set\",\r\n \"location\": \"beginsWith\"\r\n }\r\n ]\r\n },\r\n \"delete\": {\r\n \"operation\": [\r\n {\r\n \"pattern\": \"delete\",\r\n \"location\": \"beginsWith\"\r\n },\r\n {\r\n \"pattern\": \"remove\",\r\n \"location\": \"beginsWith\"\r\n },\r\n {\r\n \"pattern\": \"del\",\r\n \"location\": \"beginsWith\"\r\n }\r\n ]\r\n }\r\n }\r\n}"); - - System.out.println("\n\n"); - System.out.println("Examples:"); - System.out.println( - "$ java -jar wsdl2apigee.jar -wsdl=\"http://www.thomas-bayer.com/axis2/services/BLZService?wsdl\" -oas=true"); - } - - private static List convertPorts(List ports, - List portTypes) { - List list = new ArrayList<>(ports.size()); - for (com.predic8.wsdl.Port port : ports) { - final Object protocol = port.getBinding().getProtocol(); - if (protocol != null) { - final String protocolStr = protocol.toString(); - if (SOAP_11.equalsIgnoreCase(protocolStr) || SOAP_12.equalsIgnoreCase(protocolStr)) { - list.add(new WsdlDefinitions.Port(port.getName(), convertOperations(port.getBinding(), portTypes))); - } - } - } - return list; - } - - private static List convertOperations(Binding binding, List portTypes) { - List list = new ArrayList<>(); - OpsMap opsMap = null; - try { - opsMap = new OpsMap(OPSMAPPING_TEMPLATE); - } catch (Exception e) { - } + } + + public static InputStream generateProxy(GenerateProxyOptions generateProxyOptions) throws Exception { + GenerateProxy genProxy = new GenerateProxy(); + genProxy.setOpsMap(OPSMAPPING_TEMPLATE); - binding.getOperations(); - for (BindingOperation bindingOperation : binding.getOperations()) { - final String operationName = bindingOperation.getName(); - final WsdlDefinitions.Operation operation = new WsdlDefinitions.Operation(operationName, - findDocForOperation(operationName, portTypes), opsMap.getVerb(operationName, null), - opsMap.getResourcePath(operationName, null), null); - list.add(operation); - } - return list; + genProxy.setPassThru(generateProxyOptions.isPassthrough()); + genProxy.setBasePath(generateProxyOptions.getBasepath()); + genProxy.setVHost(generateProxyOptions.getvHosts()); + genProxy.setPort(generateProxyOptions.getPort()); + genProxy.setCORS(generateProxyOptions.isCors()); + genProxy.setAPIKey(generateProxyOptions.isApiKey()); + genProxy.setOAuth(generateProxyOptions.isOauth()); + genProxy.setQuotaAPIKey(generateProxyOptions.isApiKey() && generateProxyOptions.isQuota()); + genProxy.setQuotaOAuth(generateProxyOptions.isOauth() && generateProxyOptions.isQuota()); + if (generateProxyOptions.getOperationsFilter() != null + && generateProxyOptions.getOperationsFilter().length() > 0) { + genProxy.setSelectedOperationsJson(generateProxyOptions.getOperationsFilter()); } + return genProxy.begin(generateProxyOptions.getDescription() != null ? generateProxyOptions.getDescription() + : "Generated SOAP to API proxy", generateProxyOptions.getWsdl()); + } - private static String findDocForOperation(String operationName, List portTypes) { - for (PortType portType : portTypes) { - final Operation operation = portType.getOperation(operationName); - if (operation != null) { - return operation.getDocumentation() != null ? operation.getDocumentation().getContent() : ""; - } - } - return ""; + public static WsdlDefinitions parseWsdl(String wsdl) throws ErrorParsingWsdlException { + final WSDLParser2 wsdlParser = new WSDLParser2(); + try { + final Definitions definitions = wsdlParser.parse(wsdl); + return definitionsToWsdlDefinitions(definitions); + } catch (com.predic8.xml.util.ResourceDownloadException e) { + String message = formatResourceError(e); + throw new ErrorParsingWsdlException(message, e); + } catch (Throwable t) { + String message = t.getLocalizedMessage(); + if (message == null) { + message = t.getMessage(); + } + if (message == null) { + message = "Error processing WSDL."; + } + throw new ErrorParsingWsdlException(message, t); } + } - private static WsdlDefinitions definitionsToWsdlDefinitions(Definitions definitions) { - List services = new ArrayList<>(); - definitions.getServices(); - for (Service service : definitions.getServices()) { - final WsdlDefinitions.Service service1 = new WsdlDefinitions.Service(service.getName(), - convertPorts(service.getPorts(), definitions.getPortTypes())); - services.add(service1); - } - return new WsdlDefinitions(services); - } - - public static void main(String[] args) throws Exception { - - GenerateProxy genProxy = new GenerateProxy(); - - String wsdlPath = ""; - String proxyDescription = ""; - - Options opt = new Options(args, 1); - // the wsdl param contains the URL or FilePath to a WSDL document - opt.getSet().addOption("wsdl", Separator.EQUALS, Multiplicity.ONCE); - // if this flag it set, the generate a passthru proxy - opt.getSet().addOption("passthru", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); - // set this flag to pass proxy description - opt.getSet().addOption("desc", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); - // set this flag to specify service name - opt.getSet().addOption("service", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); - // set this flag to specify port name - opt.getSet().addOption("port", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); - // set this flag to specify operations map - opt.getSet().addOption("opsmap", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); - // set this flag to handle all operations via post verb - opt.getSet().addOption("allpost", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); - // set virtual hosts - opt.getSet().addOption("vhosts", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); - // set build path - opt.getSet().addOption("build", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); - // add verify oauth policy - opt.getSet().addOption("oauth", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); - // add verify apikey policy - opt.getSet().addOption("apikey", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); - // add impose quota policy - opt.getSet().addOption("quota", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); - // set basepath - opt.getSet().addOption("basepath", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); - // add enable cors conditions - opt.getSet().addOption("cors", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); - // generate OAS spec - opt.getSet().addOption("oas", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); - // set this flag to enable debug - opt.getSet().addOption("debug", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); - - opt.check(); - - if (opt.getSet().isSet("wsdl")) { - // React to option -wsdl - wsdlPath = opt.getSet().getOption("wsdl").getResultValue(0); - } else { - System.out.println("-wsdl is a madatory parameter"); - usage(); - System.exit(1); - } - - if (opt.getSet().isSet("passthru")) { - // React to option -passthru - genProxy.setPassThru(Boolean.parseBoolean(opt.getSet().getOption("passthru").getResultValue(0))); - if (opt.getSet().isSet("cors")) { - LOGGER.warning("WARNING: cors can only be enabled for SOAP to REST. This flag will be ignored."); - } - if (opt.getSet().isSet("desc")) { - // React to option -des - proxyDescription = opt.getSet().getOption("desc").getResultValue(0); - genProxy.setDesc(true); - } else { - proxyDescription = "Generated SOAP proxy from "; - } - } else { - genProxy.setPassThru(false); - if (opt.getSet().isSet("desc")) { - // React to option -des - proxyDescription = opt.getSet().getOption("desc").getResultValue(0); - genProxy.setDesc(true); - } else { - proxyDescription = "Generated SOAP to API proxy from "; - } - } - - if (opt.getSet().isSet("service")) { - // React to option -service - genProxy.setService(opt.getSet().getOption("service").getResultValue(0)); - if (opt.getSet().isSet("port")) { - // React to option -port - genProxy.setPort(opt.getSet().getOption("port").getResultValue(0)); - } - } - - if (opt.getSet().isSet("opsmap")) { - genProxy.setOpsMap(opt.getSet().getOption("opsmap").getResultValue(0)); - } else { - genProxy.setOpsMap(GenerateProxy.OPSMAPPING_TEMPLATE); - } - - if (opt.getSet().isSet("allpost")) { - genProxy.setAllPost(new Boolean(opt.getSet().getOption("allpost").getResultValue(0))); - } - - if (opt.getSet().isSet("vhosts")) { - genProxy.setVHost(opt.getSet().getOption("vhosts").getResultValue(0)); - } - - if (opt.getSet().isSet("build")) { - genProxy.setBuildFolder(opt.getSet().getOption("build").getResultValue(0)); - } - - if (opt.getSet().isSet("basepath")) { - genProxy.setBasePath(opt.getSet().getOption("basepath").getResultValue(0)); - } - - if (opt.getSet().isSet("cors")) { - genProxy.setCORS(new Boolean(opt.getSet().getOption("cors").getResultValue(0))); - } - - if (opt.getSet().isSet("oauth")) { - genProxy.setOAuth(new Boolean(opt.getSet().getOption("oauth").getResultValue(0))); - if (opt.getSet().isSet("quota")) { - genProxy.setQuotaOAuth(new Boolean(opt.getSet().getOption("quota").getResultValue(0))); - } - } - - if (opt.getSet().isSet("apikey")) { - genProxy.setAPIKey(new Boolean(opt.getSet().getOption("apikey").getResultValue(0))); - if (opt.getSet().isSet("quota")) { - genProxy.setQuotaAPIKey(new Boolean(opt.getSet().getOption("quota").getResultValue(0))); - } - } - - if (!opt.getSet().isSet("apikey") && !opt.getSet().isSet("oauth") && opt.getSet().isSet("quota")) { - LOGGER.warning("WARNING: Quota is applicable with apikey or oauth flags. This flag will be ignored"); - } - - if (opt.getSet().isSet("debug")) { - // enable debug - LOGGER.setLevel(Level.FINEST); - handler.setLevel(Level.FINEST); - } else { - LOGGER.setLevel(Level.INFO); - handler.setLevel(Level.INFO); - } - - final InputStream begin = genProxy.begin(proxyDescription, wsdlPath); - if (begin != null) { - Files.copy(begin, new File(genProxy.proxyName + ".zip").toPath(), StandardCopyOption.REPLACE_EXISTING); - } - - } - - public static InputStream generateProxy(GenerateProxyOptions generateProxyOptions) throws Exception { - GenerateProxy genProxy = new GenerateProxy(); - genProxy.setOpsMap(OPSMAPPING_TEMPLATE); - - genProxy.setPassThru(generateProxyOptions.isPassthrough()); - genProxy.setBasePath(generateProxyOptions.getBasepath()); - genProxy.setVHost(generateProxyOptions.getvHosts()); - genProxy.setPort(generateProxyOptions.getPort()); - genProxy.setCORS(generateProxyOptions.isCors()); - genProxy.setAPIKey(generateProxyOptions.isApiKey()); - genProxy.setOAuth(generateProxyOptions.isOauth()); - genProxy.setQuotaAPIKey(generateProxyOptions.isApiKey() && generateProxyOptions.isQuota()); - genProxy.setQuotaOAuth(generateProxyOptions.isOauth() && generateProxyOptions.isQuota()); - if (generateProxyOptions.getOperationsFilter() != null - && generateProxyOptions.getOperationsFilter().length() > 0) { - genProxy.setSelectedOperationsJson(generateProxyOptions.getOperationsFilter()); - } - return genProxy.begin(generateProxyOptions.getDescription() != null ? generateProxyOptions.getDescription() - : "Generated SOAP to API proxy", generateProxyOptions.getWsdl()); + private static String formatResourceError(com.predic8.xml.util.ResourceDownloadException e) { + StringBuffer errorMessage = new StringBuffer("Could not download resource."); + String rootCause = e.getRootCause().getLocalizedMessage(); + if (!rootCause.isEmpty()) { + int pos = rootCause.indexOf("status for class:"); + if (pos == -1) { + errorMessage.append(" " + rootCause + "."); + } } - public static WsdlDefinitions parseWsdl(String wsdl) throws ErrorParsingWsdlException { - final WSDLParser2 wsdlParser = new WSDLParser2(); - try { - final Definitions definitions = wsdlParser.parse(wsdl); - return definitionsToWsdlDefinitions(definitions); - } catch (com.predic8.xml.util.ResourceDownloadException e) { - String message = formatResourceError(e); - throw new ErrorParsingWsdlException(message, e); - } catch (Throwable t) { - String message = t.getLocalizedMessage(); - if (message == null) { - message = t.getMessage(); - } - if (message == null) { - message = "Error processing WSDL."; - } - throw new ErrorParsingWsdlException(message, t); - } - } - - private static String formatResourceError(com.predic8.xml.util.ResourceDownloadException e) { - StringBuffer errorMessage = new StringBuffer("Could not download resource."); - String rootCause = e.getRootCause().getLocalizedMessage(); - if (!rootCause.isEmpty()) { - int pos = rootCause.indexOf("status for class:"); - if (pos == -1) { - errorMessage.append(" " + rootCause + "."); - } - } - - return (errorMessage.toString()); + return (errorMessage.toString()); - } + } /** * Copy and modify for Java com.predic8.wsdl.WSDLParser.groovy. Then update it to protect against XSS attacks - * in getToken + * in getToken */ - private static class WSDLParser2 { - - private ExternalResolver resourceResolver = new ExternalResolver(); - - public Definitions parse(String input) { - final WSDLParserContext wsdlParserContext = new WSDLParserContext(); - wsdlParserContext.setInput(input); - try { - return parse(wsdlParserContext); - } - catch (XMLStreamException e) { - throw new RuntimeException(e.getMessage()); - } - } - - protected Definitions parseLocal(XMLStreamReader token, AbstractParserContext ctx) throws XMLStreamException { - final String encoding = token.getCharacterEncodingScheme(); - if( encoding == null || (!encoding.equals("UTF-8") && !encoding.equals("UTF-16"))) { - final WSIResult wsiResults = new WSIResult(); - wsiResults.setRule("R4003"); - ArrayList wsiResultsList = (ArrayList) ctx.getWsiResults(); - wsiResultsList.add(wsiResults); - } - Definitions definitions = null; - while(token.hasNext()) { - if (token.isStartElement()) { - if(token.getName().equals(Definitions.ELEMENTNAME)) { - definitions = new Definitions(); - definitions.setBaseDir(ctx.getNewBaseDir()); - definitions.setResourceResolver(ctx.getResourceResolver()); - definitions.setRegistry(new Registry()); - ((WSDLParserContext) ctx).getWsdlElementOrder().add(definitions); - definitions.parse(token, ctx); - } - else if(token.getName().getNamespaceURI().equals(Consts.WSDL20_NS)) { - throw new WSDLVersion2NotSupportedException("WSDL 2.0 is not supported yet."); - } - else { - throw new WrongGrammarException("Expected root element '{http://schemas.xmlsoap.org/wsdl/}definitions' for the WSDL document but was '${token.name}'.", token.getName(), token.getLocation()); - } - } - if(token.hasNext()) token.next(); - } - if(definitions == null) throw new RuntimeException("The parsed document ${ctx.input} is not a valid WSDL document."); - return definitions; - - } - - protected Definitions parse(AbstractParserContext ctx) throws XMLStreamException { - updateCtx(ctx); - return parseLocal(getResourceToken(ctx), ctx); - } - - private void updateCtx(AbstractParserContext ctx) { - if (ctx.getBaseDir() == null) { - ctx.setBaseDir(""); - } - ctx.setNewBaseDir(HTTPUtil.updateBaseDir(ctx.getInput(), ctx.getBaseDir())); - if (ctx.getResourceResolver() == null) { - ctx.setResourceResolver(resourceResolver); - } - if (ctx.getWsiResults() == null) { - ctx.setWsiResults(new ArrayList()); - } - if (ctx.getErrors() == null) { - ctx.setErrors(new ArrayList()); - } - } - - private XMLStreamReader getResourceToken(AbstractParserContext ctx) throws XMLStreamException { - return getToken(resourceResolver.resolve(ctx.getInput(), ctx.getBaseDir())); - } - - private XMLStreamReader getToken(Object res) throws XMLStreamException { - final XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); - // XSS Protection added here - xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); - xmlInputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false); - xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false); - // End XSS Protection - if (res instanceof InputStream) { - return xmlInputFactory.createXMLStreamReader((InputStream) res); - } - else if (res instanceof Reader) { - return xmlInputFactory.createXMLStreamReader((Reader) res); - } - return null; - } - } + private static class WSDLParser2 { + + private ExternalResolver resourceResolver = new ExternalResolver(); + + public Definitions parse(String input) { + final WSDLParserContext wsdlParserContext = new WSDLParserContext(); + wsdlParserContext.setInput(input); + try { + return parse(wsdlParserContext); + } + catch (XMLStreamException e) { + throw new RuntimeException(e.getMessage()); + } + } + + protected Definitions parseLocal(XMLStreamReader token, AbstractParserContext ctx) throws XMLStreamException { + final String encoding = token.getCharacterEncodingScheme(); + if( encoding == null || (!encoding.equals("UTF-8") && !encoding.equals("UTF-16"))) { + final WSIResult wsiResults = new WSIResult(); + wsiResults.setRule("R4003"); + ArrayList wsiResultsList = (ArrayList) ctx.getWsiResults(); + wsiResultsList.add(wsiResults); + } + Definitions definitions = null; + while(token.hasNext()) { + if (token.isStartElement()) { + if(token.getName().equals(Definitions.ELEMENTNAME)) { + definitions = new Definitions(); + definitions.setBaseDir(ctx.getNewBaseDir()); + definitions.setResourceResolver(ctx.getResourceResolver()); + definitions.setRegistry(new Registry()); + ((WSDLParserContext) ctx).getWsdlElementOrder().add(definitions); + definitions.parse(token, ctx); + } + else if(token.getName().getNamespaceURI().equals(Consts.WSDL20_NS)) { + throw new WSDLVersion2NotSupportedException("WSDL 2.0 is not supported yet."); + } + else { + throw new WrongGrammarException("Expected root element '{http://schemas.xmlsoap.org/wsdl/}definitions' for the WSDL document but was '${token.name}'.", token.getName(), token.getLocation()); + } + } + if(token.hasNext()) token.next(); + } + if(definitions == null) throw new RuntimeException("The parsed document ${ctx.input} is not a valid WSDL document."); + return definitions; + + } + + protected Definitions parse(AbstractParserContext ctx) throws XMLStreamException { + updateCtx(ctx); + return parseLocal(getResourceToken(ctx), ctx); + } + + private void updateCtx(AbstractParserContext ctx) { + if (ctx.getBaseDir() == null) { + ctx.setBaseDir(""); + } + ctx.setNewBaseDir(HTTPUtil.updateBaseDir(ctx.getInput(), ctx.getBaseDir())); + if (ctx.getResourceResolver() == null) { + ctx.setResourceResolver(resourceResolver); + } + if (ctx.getWsiResults() == null) { + ctx.setWsiResults(new ArrayList()); + } + if (ctx.getErrors() == null) { + ctx.setErrors(new ArrayList()); + } + } + + private XMLStreamReader getResourceToken(AbstractParserContext ctx) throws XMLStreamException { + return getToken(resourceResolver.resolve(ctx.getInput(), ctx.getBaseDir())); + } + + private XMLStreamReader getToken(Object res) throws XMLStreamException { + final XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); + // XSS Protection added here + xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); + xmlInputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false); + xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false); + // End XSS Protection + if (res instanceof InputStream) { + return xmlInputFactory.createXMLStreamReader((InputStream) res); + } + else if (res instanceof Reader) { + return xmlInputFactory.createXMLStreamReader((Reader) res); + } + return null; + } + } } diff --git a/src/main/java/com/apigee/utils/OpsMap.java b/src/main/java/com/apigee/utils/OpsMap.java index a501759..9793751 100644 --- a/src/main/java/com/apigee/utils/OpsMap.java +++ b/src/main/java/com/apigee/utils/OpsMap.java @@ -15,130 +15,123 @@ public class OpsMap { - private static final Logger LOGGER = Logger.getLogger(OpsMap.class.getName()); - - static { - LOGGER.setLevel(Level.INFO); - ConsoleHandler handler = new ConsoleHandler(); - // PUBLISH this level - handler.setLevel(Level.INFO); - LOGGER.addHandler(handler); - } + private static final Logger LOGGER = Logger.getLogger(OpsMap.class.getName()); - private List opsMap; - - public OpsMap() { - opsMap = new ArrayList(); - } - - public OpsMap(String OPSMAPPING_TEMPLATE) throws Exception{ - opsMap = new ArrayList(); - readOperationsMap(OPSMAPPING_TEMPLATE); - } + static { + LOGGER.setLevel(Level.INFO); + ConsoleHandler handler = new ConsoleHandler(); + // PUBLISH this level + handler.setLevel(Level.INFO); + LOGGER.addHandler(handler); + } + + private List opsMap; + + public OpsMap() { + opsMap = new ArrayList(); + } + + public OpsMap(String OPSMAPPING_TEMPLATE) throws Exception{ + opsMap = new ArrayList(); + readOperationsMap(OPSMAPPING_TEMPLATE); + } + + private void addOps (String operationName, String location, String verb) { + Operation o = new Operation(operationName, location, verb); + opsMap.add(o); + } + + public String getVerb(String operationName, HashMap selectedOperations) { + String lcOperationName = operationName.toLowerCase(); - private void addOps (String operationName, String location, String verb) { - Operation o = new Operation(operationName, location, verb); - opsMap.add(o); + if (selectedOperations != null) { + if (selectedOperations.containsKey(operationName)) { + return selectedOperations.get(operationName).getVerb(); + } } - - public String getVerb(String operationName, HashMap selectedOperations) { - String lcOperationName = operationName.toLowerCase(); - - if (selectedOperations != null) { - if (selectedOperations.containsKey(operationName)) { - return selectedOperations.get(operationName).getVerb(); - } - } - - for (Operation o : opsMap) { - //found key in the operation name - if (lcOperationName.contains(o.getPattern())) { - if (o.getLocation().equalsIgnoreCase("beginsWith")) { - if (lcOperationName.startsWith(o.getPattern())) { - return o.getVerb(); - } - } else if (o.getLocation().equalsIgnoreCase("endsWith")) { - if (lcOperationName.startsWith(o.getPattern())) { - return o.getVerb(); - } - } else { //assume contains - return o.getVerb(); - } - } + + for (Operation o : opsMap) { + //found key in the operation name + if (lcOperationName.contains(o.getPattern())) { + if (o.getLocation().equalsIgnoreCase("beginsWith")) { + if (lcOperationName.startsWith(o.getPattern())) { + return o.getVerb(); + } + } else if (o.getLocation().equalsIgnoreCase("endsWith")) { + if (lcOperationName.startsWith(o.getPattern())) { + return o.getVerb(); + } + } else { //assume contains + return o.getVerb(); } - return "GET"; + } } - - public String getResourcePath (String operationName, HashMap selectedOperations) { - - String resourcePath = operationName; - - if (selectedOperations != null) { - if (selectedOperations.containsKey(operationName)) { - return selectedOperations.get(operationName).getResourcePath(); - } - } - - for (Operation o : opsMap) { - if (operationName.toLowerCase().startsWith(o.getPattern()) && !operationName.toLowerCase().startsWith("address") - && !operationName.equalsIgnoreCase(o.getPattern())) { //don't replace the entire resource - resourcePath = operationName.toLowerCase().replaceFirst(o.getPattern(), ""); - LOGGER.fine("Replacing " + operationName + " with " + resourcePath.toLowerCase()); - return "/" + resourcePath.toLowerCase(); - } - } + return "GET"; + } + + public String getResourcePath (String operationName, HashMap selectedOperations) { + + String resourcePath = operationName; + + if (selectedOperations != null) { + if (selectedOperations.containsKey(operationName)) { + return selectedOperations.get(operationName).getResourcePath(); + } + } + + for (Operation o : opsMap) { + if (operationName.toLowerCase().startsWith(o.getPattern()) && !operationName.toLowerCase().startsWith("address") + && !operationName.equalsIgnoreCase(o.getPattern())) { //don't replace the entire resource + resourcePath = operationName.toLowerCase().replaceFirst(o.getPattern(), ""); + LOGGER.fine("Replacing " + operationName + " with " + resourcePath.toLowerCase()); return "/" + resourcePath.toLowerCase(); + } } - - private void readOperation (String verb, Document opsMappingXML) throws Exception { - LOGGER.entering(OpsMap.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - - Node verbNode = opsMappingXML.getElementsByTagName(verb).item(0); - if (verbNode != null) { - NodeList getOpsList = verbNode.getChildNodes(); - for (int i = 0; i < getOpsList.getLength(); i++) { - if (getOpsList.item(i).getNodeType() == Node.ELEMENT_NODE) { - Element operation = (Element)getOpsList.item(i); - String name = operation.getElementsByTagName("pattern").item(0).getTextContent(); - String location = operation.getElementsByTagName("pattern").item(0).getTextContent(); - addOps (name, location, verb.toUpperCase()); - } - } + return "/" + resourcePath.toLowerCase(); + } + + private void readOperation (String verb, Document opsMappingXML) throws Exception { + LOGGER.entering(OpsMap.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); + + Node verbNode = opsMappingXML.getElementsByTagName(verb).item(0); + if (verbNode != null) { + NodeList getOpsList = verbNode.getChildNodes(); + for (int i = 0; i < getOpsList.getLength(); i++) { + if (getOpsList.item(i).getNodeType() == Node.ELEMENT_NODE) { + Element operation = (Element)getOpsList.item(i); + String name = operation.getElementsByTagName("pattern").item(0).getTextContent(); + String location = operation.getElementsByTagName("pattern").item(0).getTextContent(); + addOps (name, location, verb.toUpperCase()); } - LOGGER.exiting(OpsMap.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); + } } - - public void readOperationsMap(String OPSMAPPING_TEMPLATE) throws Exception { - - LOGGER.entering(OpsMap.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - - XMLUtils xmlUtils = new XMLUtils(); - Document opsMappingXML = null; - String[] verbs = {"get", "post", "put", "delete"}; - - try { - //first try to read it as a file containing xml - opsMappingXML = xmlUtils.readXML(OPSMAPPING_TEMPLATE); - } catch (Exception e) { - //second try to read it as a string containing xml - try { - opsMappingXML = xmlUtils.getXMLFromString(OPSMAPPING_TEMPLATE); - } catch (Exception ex) { - //third try to read it as a string containing json representation of xml -// opsMappingXML = xmlUtils.getXMLFromJSONString(OPSMAPPING_TEMPLATE); - } - } - - for (String v : verbs) { - readOperation(v, opsMappingXML); - } + LOGGER.exiting(OpsMap.class.getName(), new Object() {}.getClass().getEnclosingMethod().getName()); + } + + - LOGGER.exiting(OpsMap.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); + public void readOperationsMap(String OPSMAPPING_TEMPLATE) throws Exception { + LOGGER.entering(OpsMap.class.getName(), new Object(){}.getClass().getEnclosingMethod().getName()); + + XMLUtils xmlUtils = new XMLUtils(); + Document opsMappingXML = null; + String[] verbs = {"get", "post", "put", "delete"}; + + try { + //first try to read it as a file containing xml + opsMappingXML = xmlUtils.readXML(OPSMAPPING_TEMPLATE); + } catch (Exception e) { + LOGGER.severe(e.getMessage()); + e.printStackTrace(); + } + + for (String v : verbs) { + readOperation(v, opsMappingXML); } - + + LOGGER.exiting(OpsMap.class.getName(), new Object() { }.getClass().getEnclosingMethod().getName()); + + } + } diff --git a/src/main/java/com/apigee/utils/XMLUtils.java b/src/main/java/com/apigee/utils/XMLUtils.java index 91f41ab..bb69e98 100644 --- a/src/main/java/com/apigee/utils/XMLUtils.java +++ b/src/main/java/com/apigee/utils/XMLUtils.java @@ -25,70 +25,86 @@ public class XMLUtils { - private static final Logger LOGGER = Logger.getLogger(XMLUtils.class.getName()); - private static final ConsoleHandler handler = new ConsoleHandler(); - - static { - LOGGER.setLevel(Level.WARNING); - // PUBLISH this level - handler.setLevel(Level.WARNING); - LOGGER.addHandler(handler); - } - - private DocumentBuilder builder; - - private static final Set blacklist = new HashSet( - Arrays.asList(new String[] { "http://schemas.xmlsoap.org/wsdl/soap/", "http://schemas.xmlsoap.org/wsdl/", - "http://schemas.xmlsoap.org/ws/2003/05/partner-link/", "http://www.w3.org/2001/XMLSchema", - "http://schemas.xmlsoap.org/soap/encoding/" })); - - private static String elementName = ":{local-name()}"; - - public XMLUtils() throws Exception { - builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - } - - public boolean isValidXML(String xml) { - try { - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - documentBuilderFactory.setNamespaceAware(true); - documentBuilderFactory.setValidating(true); - - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - documentBuilder.setErrorHandler(new ErrorHandler() { - - @Override - public void warning(SAXParseException exception) throws SAXException { - } - - @Override - public void fatalError(SAXParseException exception) throws SAXException { - } - - @Override - public void error(SAXParseException exception) throws SAXException { + private final static String CLASS_NAME = XMLUtils.class.getName(); + private static final Logger LOGGER = Logger.getLogger(CLASS_NAME); + private static final ConsoleHandler handler = new ConsoleHandler(); + + static { + LOGGER.setLevel(Level.INFO); + //LOGGER.setLevel(Level.WARNING); + // PUBLISH this level + handler.setLevel(Level.WARNING); + LOGGER.addHandler(handler); + } + + private DocumentBuilder builder; + + private static final Set blacklist = + new HashSet( Arrays.asList(new String[] { + "http://schemas.xmlsoap.org/wsdl/soap/", + "http://schemas.xmlsoap.org/wsdl/", + "http://schemas.xmlsoap.org/ws/2003/05/partner-link/", + "http://www.w3.org/2001/XMLSchema", + "http://schemas.xmlsoap.org/soap/encoding/" })); + + private static String elementName = ":{local-name()}"; + + public XMLUtils() throws Exception { + builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + } + + public boolean isValidXML(String xml) { + try { + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + documentBuilderFactory.setNamespaceAware(true); + documentBuilderFactory.setValidating(true); + + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + documentBuilder.setErrorHandler(new ErrorHandler() { + + @Override + public void warning(SAXParseException exception) throws SAXException { + } + + @Override + public void fatalError(SAXParseException exception) throws SAXException { + } + + @Override + public void error(SAXParseException exception) throws SAXException { + } + }); + documentBuilder.parse(new InputSource(new StringReader(xml))); + + return true; + } catch (Exception e) { + return false; } - }); - documentBuilder.parse(new InputSource(new StringReader(xml))); - - return true; - } catch (Exception e) { - return false; } - } - + + private boolean seemsToBeXml(String candidate) { + String c = candidate.trim(); + return (c.startsWith("<") && c.endsWith(">")); + } + public Document readXML(String resource) throws Exception { - LOGGER.entering(XMLUtils.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); + LOGGER.entering(CLASS_NAME, new Object() {}.getClass().getEnclosingMethod().getName()); + + if (seemsToBeXml(resource)) { + // try to read it as a string containing xml + return this.getXMLFromString(resource); + } try { - try { - //first attempt to read as resource; otherwise, it must be a file - return builder.parse(getClass().getResourceAsStream(resource)); - } catch (IllegalArgumentException npe) { - return builder.parse(new File(resource)); - } - + try { + // attempt to read as resource + return builder.parse(getClass().getResourceAsStream(resource)); + } + catch (IllegalArgumentException npe) { + // try reading as a file + return builder.parse(new File(resource)); + } + } catch (SAXParseException spe) { // Error generated by the parser LOGGER.severe("\n** Parsing error" + ", line " + spe.getLineNumber() + ", uri " + spe.getSystemId()); @@ -99,397 +115,399 @@ public Document readXML(String resource) throws Exception { throw sxe; } catch (IOException ioe) { LOGGER.severe(ioe.getMessage()); + ioe.printStackTrace(); throw ioe; } catch (Exception e) { LOGGER.severe(e.getMessage()); throw e; - } + } } - public void writeXML(Document document, String filePath) throws Exception { - - LOGGER.entering(XMLUtils.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - - try { - document.setXmlStandalone(true); - // Use a Transformer for output - TransformerFactory tFactory = TransformerFactory.newInstance(); - Transformer transformer = tFactory.newTransformer(); - transformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); - transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); - transformer.setOutputProperty(OutputKeys.VERSION, "1.0"); - transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - - DOMSource source = new DOMSource(document); - File f = new File(filePath); - FileOutputStream fos = new FileOutputStream(f, false); - StreamResult result = new StreamResult(fos); - transformer.transform(source, result); - fos.close(); - } catch (IOException ioe) { - LOGGER.severe(ioe.getMessage()); - throw ioe; - } catch (TransformerConfigurationException tce) { - LOGGER.severe("* Transformer Factory error"); - LOGGER.severe(" " + tce.getMessage()); - throw tce; - } catch (TransformerException te) { - LOGGER.severe("* Transformation error"); - LOGGER.severe(" " + te.getMessage()); - throw te; + public void writeXML(Document document, String filePath) throws Exception { + + LOGGER.entering(CLASS_NAME, new Object() { }.getClass().getEnclosingMethod().getName()); + + try { + document.setXmlStandalone(true); + // Use a Transformer for output + TransformerFactory tFactory = TransformerFactory.newInstance(); + Transformer transformer = tFactory.newTransformer(); + transformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); + transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); + transformer.setOutputProperty(OutputKeys.VERSION, "1.0"); + transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + + DOMSource source = new DOMSource(document); + File f = new File(filePath); + FileOutputStream fos = new FileOutputStream(f, false); + StreamResult result = new StreamResult(fos); + transformer.transform(source, result); + fos.close(); + } catch (IOException ioe) { + LOGGER.severe(ioe.getMessage()); + throw ioe; + } catch (TransformerConfigurationException tce) { + LOGGER.severe("* Transformer Factory error"); + LOGGER.severe(" " + tce.getMessage()); + throw tce; + } catch (TransformerException te) { + LOGGER.severe("* Transformation error"); + LOGGER.severe(" " + te.getMessage()); + throw te; + } } - } - public void generateOtherNamespacesXSLT(String filePath, String operationName, String xsltTemplate, Map namespace) throws Exception { - LOGGER.entering(XMLUtils.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); + public void generateOtherNamespacesXSLT(String filePath, String operationName, String xsltTemplate, Map namespace) throws Exception { + LOGGER.entering(CLASS_NAME, new Object() {}.getClass().getEnclosingMethod().getName()); - DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); - docBuilderFactory.setNamespaceAware(true); - DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); + DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); + docBuilderFactory.setNamespaceAware(true); + DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); - Document document = docBuilder.parse(new InputSource(new StringReader(xsltTemplate))); + Document document = docBuilder.parse(new InputSource(new StringReader(xsltTemplate))); - Node stylesheet = document.getDocumentElement(); - for (Map.Entry entry : namespace.entrySet()) { - String key = entry.getKey(); - String value = entry.getValue(); - if (!blacklist.contains(value)) { - if (key.length() == 0) { - ((Element) stylesheet).setAttribute("xmlns:ns", value); - } else { - ((Element) stylesheet).setAttribute("xmlns:" + key, value); + Node stylesheet = document.getDocumentElement(); + for (Map.Entry entry : namespace.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + if (!blacklist.contains(value)) { + if (key.length() == 0) { + ((Element) stylesheet).setAttribute("xmlns:ns", value); + } else { + ((Element) stylesheet).setAttribute("xmlns:" + key, value); + } + } } - } - } - - writeXML(document, filePath + operationName + "-add-other-namespaces.xslt"); - - LOGGER.exiting(XMLUtils.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - } - - public Document getXMLFromString(String xml) throws Exception { - - LOGGER.entering(XMLUtils.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - - try { - InputSource is = new InputSource(new StringReader(xml)); - Document document = builder.parse(is); - return cloneDocument(document); - } catch (SAXException | IOException e) { - LOGGER.severe(e.getMessage()); - throw e; - } catch (Exception e) { - LOGGER.severe(e.getMessage()); - throw e; - } - } - -// public Document getXMLFromJSONString(String jsonString) throws Exception { -// JsonObject json = new JsonParser().parse(jsonString).getAsJsonObject(); -// return getXMLFromString(XML.toString(json)); -// } - - private String extractElement(String fullElementName) { - if (fullElementName.indexOf(":") != -1) { - String elements[] = fullElementName.split(":"); - return elements[1]; - } else { - return fullElementName; + + writeXML(document, filePath + operationName + "-add-other-namespaces.xslt"); + + LOGGER.exiting(CLASS_NAME, new Object() {}.getClass().getEnclosingMethod().getName()); } - } - - public List getElementList(String xml) throws Exception { - - LOGGER.entering(XMLUtils.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - - List elementList = new ArrayList(); - try { - Document doc = builder.parse(new InputSource(new StringReader(xml))); - - XPathFactory xpf = XPathFactory.newInstance(); - XPath xp = xpf.newXPath(); - - NodeList nodes = (NodeList) xp.evaluate("//@* | //*[not(*)]", doc, XPathConstants.NODESET); - - for (int i = 0, len = nodes.getLength(); i < len; i++) { - elementList.add(extractElement(nodes.item(i).getNodeName())); - } - return elementList; - } catch (SAXException e) { - LOGGER.severe(e.getMessage()); - throw e; - } catch (IOException e) { - LOGGER.severe(e.getMessage()); - throw e; - } catch (XPathExpressionException e) { - LOGGER.severe(e.getMessage()); - throw e; + + public Document getXMLFromString(String xml) throws Exception { + + LOGGER.entering(CLASS_NAME, new Object() { }.getClass().getEnclosingMethod().getName()); + + try { + InputSource is = new InputSource(new StringReader(xml)); + Document document = builder.parse(is); + return cloneDocument(document); + } catch (SAXException | IOException e) { + LOGGER.severe(e.getMessage()); + throw e; + } catch (Exception e) { + LOGGER.severe(e.getMessage()); + throw e; + } } - } - - public KeyValue replacePlaceHolders(String xml) throws Exception { - - LOGGER.entering(XMLUtils.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - - KeyValue keyValue; - try { - Document doc = builder.parse(new InputSource(new StringReader(xml))); - - XPathFactory xpf = XPathFactory.newInstance(); - XPath xp = xpf.newXPath(); - - NodeList nodes = (NodeList) xp.evaluate("//@* | //*[not(*)]", doc, XPathConstants.NODESET); - - for (int i = 0, len = nodes.getLength(); i < len; i++) { - Node item = nodes.item(i); - item.setTextContent("{" + extractElement(item.getNodeName()) + "}"); - } - - Node envelope = doc.getDocumentElement(); - NodeList nodeList = envelope.getChildNodes(); - Node body = null; - Node temp = null; - for (int i = 0; i < nodeList.getLength(); i++) { - temp = nodeList.item(i); - if (temp.getNodeName().indexOf(":Body") != -1) { - body = temp; - break; + + // public Document getXMLFromJSONString(String jsonString) throws Exception { + // JsonObject json = new JsonParser().parse(jsonString).getAsJsonObject(); + // return getXMLFromString(XML.toString(json)); + // } + + private String extractElement(String fullElementName) { + if (fullElementName.indexOf(":") != -1) { + String elements[] = fullElementName.split(":"); + return elements[1]; + } else { + return fullElementName; } - } - - TransformerFactory tf = TransformerFactory.newInstance(); - Transformer transformer = tf.newTransformer(); - transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); - StringWriter fullSoapWriter = new StringWriter(); - StringWriter bodySoapWriter = new StringWriter(); - - transformer.transform(new DOMSource(doc), new StreamResult(fullSoapWriter)); - String fullSoap = fullSoapWriter.getBuffer().toString().replaceAll("\n|\r", ""); - - transformer.transform(new DOMSource(getFirstChildElement(body)), new StreamResult(bodySoapWriter)); -// String bodySoap = bodySoapWriter.getBuffer().toString().replaceAll("\n|\r", ""); - String bodyJson = "{\"test\": \"not null\"}"; - - keyValue = new KeyValue(fullSoap, bodyJson); - return keyValue; - } catch (SAXException e) { - LOGGER.severe(e.getMessage()); - throw e; - } catch (IOException e) { - LOGGER.severe(e.getMessage()); - throw e; - } catch (XPathExpressionException e) { - LOGGER.severe(e.getMessage()); - throw e; - } catch (TransformerException e) { - LOGGER.severe(e.getMessage()); - throw e; } - } - - /** - * Gets the first child element of a node. - * - * @param node - * the node to get the child from - * @return the first element child of {@code node} or {@code null} if none - * @throws NullPointerException - * if {@code node} is {@code null} - */ - public Element getFirstChildElement(Node node) throws Exception { - - LOGGER.entering(XMLUtils.class.getName(), new Object() { - }.getClass().getEnclosingMethod().getName()); - - node = node.getFirstChild(); - while (node != null && node.getNodeType() != Node.ELEMENT_NODE) { - node = node.getNextSibling(); + + public List getElementList(String xml) throws Exception { + + LOGGER.entering(CLASS_NAME, new Object() { }.getClass().getEnclosingMethod().getName()); + + List elementList = new ArrayList(); + try { + Document doc = builder.parse(new InputSource(new StringReader(xml))); + + XPathFactory xpf = XPathFactory.newInstance(); + XPath xp = xpf.newXPath(); + + NodeList nodes = (NodeList) xp.evaluate("//@* | //*[not(*)]", doc, XPathConstants.NODESET); + + for (int i = 0, len = nodes.getLength(); i < len; i++) { + elementList.add(extractElement(nodes.item(i).getNodeName())); + } + return elementList; + } catch (SAXException e) { + LOGGER.severe(e.getMessage()); + throw e; + } catch (IOException e) { + LOGGER.severe(e.getMessage()); + throw e; + } catch (XPathExpressionException e) { + LOGGER.severe(e.getMessage()); + throw e; + } } - return (Element) node; - } - - /** - * - * @param doc - * @return - * @throws Exception - */ - public Document cloneDocument(Document doc) throws Exception { - Document clonedDoc = builder.newDocument(); - clonedDoc.appendChild(clonedDoc.importNode(doc.getDocumentElement(), true)); - return clonedDoc; - } - - public void generateRootNamespaceXSLT(String xsltTemplate, String target, String operationName, String prefix, - String rootElement, - String namespaceUri, Map namespace) throws Exception { - DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); - docBuilderFactory.setNamespaceAware(true); - DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); - - if (rootElement == null) { - rootElement = operationName; + + public KeyValue replacePlaceHolders(String xml) throws Exception { + + LOGGER.entering(CLASS_NAME, new Object() {}.getClass().getEnclosingMethod().getName()); + + KeyValue keyValue; + try { + Document doc = builder.parse(new InputSource(new StringReader(xml))); + + XPathFactory xpf = XPathFactory.newInstance(); + XPath xp = xpf.newXPath(); + + NodeList nodes = (NodeList) xp.evaluate("//@* | //*[not(*)]", doc, XPathConstants.NODESET); + + for (int i = 0, len = nodes.getLength(); i < len; i++) { + Node item = nodes.item(i); + item.setTextContent("{" + extractElement(item.getNodeName()) + "}"); + } + + Node envelope = doc.getDocumentElement(); + NodeList nodeList = envelope.getChildNodes(); + Node body = null; + Node temp = null; + for (int i = 0; i < nodeList.getLength(); i++) { + temp = nodeList.item(i); + if (temp.getNodeName().indexOf(":Body") != -1) { + body = temp; + break; + } + } + + TransformerFactory tf = TransformerFactory.newInstance(); + Transformer transformer = tf.newTransformer(); + transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); + StringWriter fullSoapWriter = new StringWriter(); + StringWriter bodySoapWriter = new StringWriter(); + + transformer.transform(new DOMSource(doc), new StreamResult(fullSoapWriter)); + String fullSoap = fullSoapWriter.getBuffer().toString().replaceAll("\n|\r", ""); + + transformer.transform(new DOMSource(getFirstChildElement(body)), new StreamResult(bodySoapWriter)); + // String bodySoap = bodySoapWriter.getBuffer().toString().replaceAll("\n|\r", ""); + String bodyJson = "{\"test\": \"not null\"}"; + + keyValue = new KeyValue(fullSoap, bodyJson); + return keyValue; + } catch (SAXException e) { + LOGGER.severe(e.getMessage()); + throw e; + } catch (IOException e) { + LOGGER.severe(e.getMessage()); + throw e; + } catch (XPathExpressionException e) { + LOGGER.severe(e.getMessage()); + throw e; + } catch (TransformerException e) { + LOGGER.severe(e.getMessage()); + throw e; + } } - - String newXsltTemplate = new Scanner(getClass() - .getResourceAsStream(xsltTemplate), "UTF-8") - .useDelimiter("\\A").next() - .replaceAll("@@ROOT", rootElement) - .replaceAll("@@PREFIX", prefix) - .replaceAll("@@NAMESPACE", namespaceUri); - - Document document = docBuilder.parse(new InputSource(new StringReader(newXsltTemplate))); - - Node stylesheet = document.getDocumentElement(); - - for (Map.Entry entry : namespace.entrySet()) { - String key = entry.getKey(); - String value = entry.getValue(); - if (!blacklist.contains(value)) { - if (key.length() == 0) { - ((Element) stylesheet).setAttribute("xmlns:ns", value); - } else { - ((Element) stylesheet).setAttribute("xmlns:" + key, value); + + /** + * Gets the first child element of a node. + * + * @param node + * the node to get the child from + * @return the first element child of {@code node} or {@code null} if none + * @throws NullPointerException + * if {@code node} is {@code null} + */ + public Element getFirstChildElement(Node node) throws Exception { + LOGGER.entering(CLASS_NAME, new Object() {}.getClass().getEnclosingMethod().getName()); + + node = node.getFirstChild(); + while (node != null && node.getNodeType() != Node.ELEMENT_NODE) { + node = node.getNextSibling(); } - } + return (Element) node; } - XPathFactory xpf = XPathFactory.newInstance(); - XPath xp = xpf.newXPath(); - // there's no default implementation for NamespaceContext - xp.setNamespaceContext(new NamespaceContext() { - - @Override - public Iterator getPrefixes(String namespaceURI) { - throw new UnsupportedOperationException(); - } - - @Override - public String getPrefix(String namespaceURI) { - throw new UnsupportedOperationException(); - } - - @Override - public String getNamespaceURI(String prefix) { - if (prefix == null) - throw new NullPointerException("Null prefix"); - else if ("xsl".equals(prefix)) - return "http://www.w3.org/1999/XSL/Transform"; - else if ("xml".equals(prefix)) - return XMLConstants.XML_NS_URI; - return XMLConstants.NULL_NS_URI; - } - }); - - /*NodeList nodes = (NodeList) xp.evaluate("/xsl:stylesheet/xsl:template/xsl:element", document, - XPathConstants.NODESET); - Node element = nodes.item(0); - - Node nspace = document.createElementNS("http://www.w3.org/1999/XSL/Transform", "xsl:namespace"); - ((Element) nspace).setAttribute("name", prefix); - ((Element) nspace).setAttribute("select", "'" + namespaceUri + "'"); - - element.insertBefore(nspace, element.getFirstChild());*/ - - writeXML(document, target + operationName + "-add-namespace.xslt"); - - } - - private String getFullXPath(Node n) { - // abort early - if (null == n) - return null; - - // declarations - Node parent = null; - Stack hierarchy = new Stack(); - StringBuffer buffer = new StringBuffer(); - - // push element on stack - hierarchy.push(n); - - switch (n.getNodeType()) { - case Node.ATTRIBUTE_NODE: - parent = ((Attr) n).getOwnerElement(); - break; - case Node.ELEMENT_NODE: - parent = n.getParentNode(); - break; - case Node.DOCUMENT_NODE: - parent = n.getParentNode(); - break; - default: - throw new IllegalStateException("Unexpected Node type" + n.getNodeType()); + /** + * + * @param doc + * @return + * @throws Exception + */ + public Document cloneDocument(Document doc) throws Exception { + Document clonedDoc = builder.newDocument(); + clonedDoc.appendChild(clonedDoc.importNode(doc.getDocumentElement(), true)); + return clonedDoc; } - while (null != parent && parent.getNodeType() != Node.DOCUMENT_NODE) { - // push on stack - hierarchy.push(parent); + public void generateRootNamespaceXSLT(String xsltTemplate, String target, String operationName, String prefix, + String rootElement, String namespaceUri, Map namespace) throws Exception { + DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); + docBuilderFactory.setNamespaceAware(true); + DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); - // get parent of parent - parent = parent.getParentNode(); - } + if (rootElement == null) { + rootElement = operationName; + } - // construct xpath - Object obj = null; - while (!hierarchy.isEmpty() && null != (obj = hierarchy.pop())) { - Node node = (Node) obj; - boolean handled = false; + String newXsltTemplate = new Scanner(getClass().getResourceAsStream(xsltTemplate), "UTF-8") + .useDelimiter("\\A") + .next() + .replaceAll("@@ROOT", rootElement); - if (node.getNodeType() == Node.ELEMENT_NODE) { - Element e = (Element) node; + if (namespaceUri == null || namespaceUri.equals("")) { + // If the namespaceUri is empty then we need to eliminate the + // declaration of the prefix and all subsequent references to it. + newXsltTemplate = newXsltTemplate.replaceAll("@@PREFIX:", "") + .replaceAll("xmlns:@@PREFIX=\"@@NAMESPACE\"", ""); + } + else { + newXsltTemplate = newXsltTemplate + .replaceAll("@@PREFIX", prefix) + .replaceAll("@@NAMESPACE", namespaceUri); + } - // is this the root element? - if (buffer.length() == 0) { - // root element - simply append element name - buffer.append(node.getNodeName()); - } else { - // child element - append slash and element name - buffer.append("/"); - buffer.append(node.getNodeName()); - - if (node.hasAttributes()) { - // see if the element has a name or id attribute - if (e.hasAttribute("id")) { - // id attribute found - use that - buffer.append("[@id='" + e.getAttribute("id") + "']"); - handled = true; - } else if (e.hasAttribute("name")) { - // name attribute found - use that - buffer.append("[@name='" + e.getAttribute("name") + "']"); - handled = true; + Document document = docBuilder.parse(new InputSource(new StringReader(newXsltTemplate))); + + Node stylesheet = document.getDocumentElement(); + + for (Map.Entry entry : namespace.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + if (!blacklist.contains(value)) { + if (key.length() == 0) { + ((Element) stylesheet).setAttribute("xmlns:ns", value); + } else { + ((Element) stylesheet).setAttribute("xmlns:" + key, value); + } } - } - - if (!handled) { - // no known attribute we could use - get sibling index - int prev_siblings = 1; - Node prev_sibling = node.getPreviousSibling(); - while (null != prev_sibling) { - if (prev_sibling.getNodeType() == node.getNodeType()) { - if (prev_sibling.getNodeName().equalsIgnoreCase(node.getNodeName())) { - prev_siblings++; + } + + XPathFactory xpf = XPathFactory.newInstance(); + XPath xp = xpf.newXPath(); + // there's no default implementation for NamespaceContext + xp.setNamespaceContext(new NamespaceContext() { + + @Override + public Iterator getPrefixes(String namespaceURI) { + throw new UnsupportedOperationException(); + } + + @Override + public String getPrefix(String namespaceURI) { + throw new UnsupportedOperationException(); + } + + @Override + public String getNamespaceURI(String prefix) { + if (prefix == null) + throw new NullPointerException("Null prefix"); + else if ("xsl".equals(prefix)) + return "http://www.w3.org/1999/XSL/Transform"; + else if ("xml".equals(prefix)) + return XMLConstants.XML_NS_URI; + return XMLConstants.NULL_NS_URI; + } + }); + + /*NodeList nodes = (NodeList) xp.evaluate("/xsl:stylesheet/xsl:template/xsl:element", document, + XPathConstants.NODESET); + Node element = nodes.item(0); + + Node nspace = document.createElementNS("http://www.w3.org/1999/XSL/Transform", "xsl:namespace"); + ((Element) nspace).setAttribute("name", prefix); + ((Element) nspace).setAttribute("select", "'" + namespaceUri + "'"); + + element.insertBefore(nspace, element.getFirstChild());*/ + + writeXML(document, target + operationName + "-add-namespace.xslt"); + + } + + private String getFullXPath(Node n) { + // abort early + if (null == n) + return null; + + // declarations + Node parent = null; + Stack hierarchy = new Stack(); + StringBuffer buffer = new StringBuffer(); + + // push element on stack + hierarchy.push(n); + + switch (n.getNodeType()) { + case Node.ATTRIBUTE_NODE: + parent = ((Attr) n).getOwnerElement(); + break; + case Node.ELEMENT_NODE: + parent = n.getParentNode(); + break; + case Node.DOCUMENT_NODE: + parent = n.getParentNode(); + break; + default: + throw new IllegalStateException("Unexpected Node type" + n.getNodeType()); + } + + while (null != parent && parent.getNodeType() != Node.DOCUMENT_NODE) { + // push on stack + hierarchy.push(parent); + + // get parent of parent + parent = parent.getParentNode(); + } + + // construct xpath + Object obj = null; + while (!hierarchy.isEmpty() && null != (obj = hierarchy.pop())) { + Node node = (Node) obj; + boolean handled = false; + + if (node.getNodeType() == Node.ELEMENT_NODE) { + Element e = (Element) node; + + // is this the root element? + if (buffer.length() == 0) { + // root element - simply append element name + buffer.append(node.getNodeName()); + } else { + // child element - append slash and element name + buffer.append("/"); + buffer.append(node.getNodeName()); + + if (node.hasAttributes()) { + // see if the element has a name or id attribute + if (e.hasAttribute("id")) { + // id attribute found - use that + buffer.append("[@id='" + e.getAttribute("id") + "']"); + handled = true; + } else if (e.hasAttribute("name")) { + // name attribute found - use that + buffer.append("[@name='" + e.getAttribute("name") + "']"); + handled = true; + } + } + + if (!handled) { + // no known attribute we could use - get sibling index + int prev_siblings = 1; + Node prev_sibling = node.getPreviousSibling(); + while (null != prev_sibling) { + if (prev_sibling.getNodeType() == node.getNodeType()) { + if (prev_sibling.getNodeName().equalsIgnoreCase(node.getNodeName())) { + prev_siblings++; + } + } + prev_sibling = prev_sibling.getPreviousSibling(); + } + buffer.append("[" + prev_siblings + "]"); + } } - } - prev_sibling = prev_sibling.getPreviousSibling(); + } else if (node.getNodeType() == Node.ATTRIBUTE_NODE) { + buffer.append("/@"); + buffer.append(node.getNodeName()); } - buffer.append("[" + prev_siblings + "]"); - } } - } else if (node.getNodeType() == Node.ATTRIBUTE_NODE) { - buffer.append("/@"); - buffer.append(node.getNodeName()); - } + // return buffer + return buffer.toString(); } - // return buffer - return buffer.toString(); - } } diff --git a/src/test/java/com/apigee/proxywriter/GenerateProxyTest.java b/src/test/java/com/apigee/proxywriter/GenerateProxyTest.java index 5ca9097..a47dc37 100644 --- a/src/test/java/com/apigee/proxywriter/GenerateProxyTest.java +++ b/src/test/java/com/apigee/proxywriter/GenerateProxyTest.java @@ -29,7 +29,15 @@ public class GenerateProxyTest { + static { + try { + InputStream stream = GenerateProxy.class.getClassLoader(). + getResourceAsStream("java-util-logging.properties"); + java.util.logging.LogManager.getLogManager().readConfiguration(stream); + } catch (Exception e) { + } + } public static final String WEATHER_WSDL = "/Weather.asmx.wsdl";//"http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"; public static final String BLZ_WSDL = "/BLZService.wsdl"; public static final String STOCK_WSDL = "/delayedstockquote.asmx.wsdl"; @@ -413,13 +421,13 @@ public void testOASpec() throws Exception { final String CLIENT_SERVICE_WSDL = url.toString(); final GenerateProxy generateProxy = new GenerateProxy(); //final String OAS = "{\r\n \"basePath\": \"/blzservice\",\r\n \"paths\": {\"/bank\": {\"get\": {\r\n \"description\": \"Implements WSDL operation getBank\",\r\n \"responses\": {\"200\": {\r\n \"schema\": {\"$ref\": \"#/definitions/undefined\"},\r\n \"description\": \"Successful response\"\r\n }},\r\n \"parameters\": [{\r\n \"in\": \"query\",\r\n \"name\": \"blz\",\r\n \"description\": \"\",\r\n \"type\": \"string\",\r\n \"required\": false\r\n }]\r\n }}},\r\n \"host\": \"www.thomas-bayer.com\",\r\n \"produces\": [\"application/json\"],\r\n \"schemes\": [\"http\"],\r\n \"definitions\": {\"undefined\": {\"properties\": {\"message\": {\"type\": \"string\"}}}},\r\n \"swagger\": \"2.0\",\r\n \"info\": {\r\n \"license\": {\"name\": \"Apache 2.0\"},\r\n \"contact\": {\"name\": \"API Team\"},\r\n \"description\": \"A OAS document generated from WSDL\",\r\n \"termsOfService\": \"\",\r\n \"title\": \"BLZService\",\r\n \"version\": \"1.0.0\"\r\n },\r\n \"consumes\": [\"application/json\"]\r\n}"; - generateProxy.setOpsMap(oMap); - final InputStream inputStream = generateProxy.begin("Test OAS generation", CLIENT_SERVICE_WSDL); + generateProxy.setOpsMap(oMap); + final InputStream inputStream = generateProxy.begin("Test OAS generation", CLIENT_SERVICE_WSDL); } @Test public void testReservedVariables() throws Exception { - URL url = this.getClass().getResource("/reservedVariables.wsdl"); + URL url = this.getClass().getResource("/reservedVariables.wsdl"); final String CLIENT_SERVICE_WSDL = url.toString(); final GenerateProxy generateProxy = new GenerateProxy(); @@ -433,11 +441,11 @@ public void testReservedVariables() throws Exception { @Test public void testRecursiveWSDL() throws Exception { - final String CLIENT_SERVICE_WSDL = "https://webservice.s7.exacttarget.com/etframework.wsdl"; - final GenerateProxy generateProxy = new GenerateProxy(); + final String CLIENT_SERVICE_WSDL = "https://webservice.s7.exacttarget.com/etframework.wsdl"; + final GenerateProxy generateProxy = new GenerateProxy(); - generateProxy.setOpsMap(oMap); - generateProxy.setPassThru(false); + generateProxy.setOpsMap(oMap); + generateProxy.setPassThru(false); final InputStream inputStream = generateProxy.begin("Test WSDL with recursive schema", CLIENT_SERVICE_WSDL); @@ -445,7 +453,7 @@ public void testRecursiveWSDL() throws Exception { @Test public void testNullOutput() throws Exception { - URL url = this.getClass().getResource("/availability.wsdl"); + URL url = this.getClass().getResource("/availability.wsdl"); final String CLIENT_SERVICE_WSDL = url.toString(); final GenerateProxy generateProxy = new GenerateProxy(); @@ -455,13 +463,25 @@ public void testNullOutput() throws Exception { final InputStream inputStream = generateProxy.begin("Test Null Output", CLIENT_SERVICE_WSDL); } + @Test + public void testEmptyTargetNamespace() throws Exception { + URL url = this.getClass().getResource("/empty_target_namespace.wsdl"); + final String CLIENT_SERVICE_WSDL = url.toString(); + final GenerateProxy generateProxy = new GenerateProxy(); + + generateProxy.setOpsMap(oMap); + generateProxy.setPassThru(false); + + final InputStream inputStream = generateProxy.begin("Empty Target Namespace", CLIENT_SERVICE_WSDL); + } + @Test public void testRPCAllTypeInSchema() throws Exception { - final String CLIENT_SERVICE_WSDL = "http://graphical.weather.gov/xml/DWMLgen/wsdl/ndfdXML.wsdl"; - final GenerateProxy generateProxy = new GenerateProxy(); + final String CLIENT_SERVICE_WSDL = "http://graphical.weather.gov/xml/DWMLgen/wsdl/ndfdXML.wsdl"; + final GenerateProxy generateProxy = new GenerateProxy(); - generateProxy.setOpsMap(oMap); - generateProxy.setPassThru(false); + generateProxy.setOpsMap(oMap); + generateProxy.setPassThru(false); final InputStream inputStream = generateProxy.begin("Test WSDL with All type in RPC schema", CLIENT_SERVICE_WSDL); } @@ -470,10 +490,10 @@ public void testRPCAllTypeInSchema() throws Exception { public void testInvalidOutputSchema() throws Exception { URL url = this.getClass().getResource(STOCK_WSDL); final String CLIENT_SERVICE_WSDL = url.toString(); - final GenerateProxy generateProxy = new GenerateProxy(); + final GenerateProxy generateProxy = new GenerateProxy(); - generateProxy.setOpsMap(oMap); - generateProxy.setPassThru(false); + generateProxy.setOpsMap(oMap); + generateProxy.setPassThru(false); final InputStream inputStream = generateProxy.begin("Test WSDL with invalid output schema", CLIENT_SERVICE_WSDL); } @@ -482,9 +502,9 @@ public void testInvalidOutputSchema() throws Exception { public void testDefaultNamespace() throws Exception { URL url = this.getClass().getResource(STOCK_WSDL); final String CLIENT_SERVICE_WSDL = url.toString(); - final GenerateProxy generateProxy = new GenerateProxy(); + final GenerateProxy generateProxy = new GenerateProxy(); - generateProxy.setPassThru(true); + generateProxy.setPassThru(true); final InputStream inputStream = generateProxy.begin("Test default namespace", CLIENT_SERVICE_WSDL); diff --git a/src/test/resources/empty_target_namespace.wsdl b/src/test/resources/empty_target_namespace.wsdl new file mode 100644 index 0000000..3f85afd --- /dev/null +++ b/src/test/resources/empty_target_namespace.wsdl @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/java-util-logging.properties b/src/test/resources/java-util-logging.properties new file mode 100644 index 0000000..a09ce32 --- /dev/null +++ b/src/test/resources/java-util-logging.properties @@ -0,0 +1,6 @@ +handlers= java.util.logging.ConsoleHandler +.level= FINER +java.util.logging.ConsoleHandler.level = FINER +java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter +#java.util.logging.SimpleFormatter.format=%1$tFT%1$tT %4$-7s %5$s %n +java.util.logging.SimpleFormatter.format=%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS.%1$tL %4$-7s [%2$s] %5$s %6$s%n