[Wsdl] minor improvements, bug fixes (#9613)

* minor improvements to wsdl-schema gen

* better code format

* update readme
This commit is contained in:
William Cheng 2021-05-28 21:38:36 +08:00 committed by GitHub
parent 28c3e1d544
commit 763f65f293
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 566 additions and 545 deletions

View File

@ -71,7 +71,7 @@ OpenAPI Generator allows generation of API client libraries (SDK generation), se
| **Server stubs** | **Ada**, **C#** (ASP.NET Core, NancyFx), **C++** (Pistache, Restbed, Qt5 QHTTPEngine), **Erlang**, **F#** (Giraffe), **Go** (net/http, Gin, Echo), **Haskell** (Servant), **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, Jersey, RestEasy, Play Framework, [PKMST](https://github.com/ProKarma-Inc/pkmst-getting-started-examples), [Vert.x](https://vertx.io/)), **Kotlin** (Spring Boot, Ktor, Vertx), **PHP** (Laravel, Lumen, Slim, Silex, [Symfony](https://symfony.com/), [Zend Expressive](https://github.com/zendframework/zend-expressive)), **Python** (Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Rust** (rust-server), **Scala** (Akka, [Finch](https://github.com/finagle/finch), [Lagom](https://github.com/lagom/lagom), [Play](https://www.playframework.com/), Scalatra) |
| **API documentation generators** | **HTML**, **Confluence Wiki**, **Asciidoc**, **Markdown**, **PlantUML** |
| **Configuration files** | [**Apache2**](https://httpd.apache.org/) |
| **Others** | **GraphQL**, **JMeter**, **Ktorm**, **MySQL Schema**, **Protocol Buffer** |
| **Others** | **GraphQL**, **JMeter**, **Ktorm**, **MySQL Schema**, **Protocol Buffer**, **WSDL** |
## Table of contents
@ -972,6 +972,7 @@ Here is a list of template creators:
* Ktorm: @Luiz-Monad
* MySQL: @ybelenko
* Protocol Buffer: @wing328
* WSDL @adessoDpd
:heart: = Link to support the contributor directly

View File

@ -0,0 +1,6 @@
generatorName: wsdl-schema
outputDir: samples/schema/petstore/wsdl-schema
inputSpec: modules/openapi-generator/src/test/resources/3_0/wsdl/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/wsdl-schema
additionalProperties:
hideGenerationTimestamp: "true"

View File

@ -1,6 +0,0 @@
generatorName: wsdl
outputDir: samples/documentation/wsdl
inputSpec: modules/openapi-generator/src/test/resources/3_0/wsdl/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/wsdl
additionalProperties:
hideGenerationTimestamp: "true"

View File

@ -142,7 +142,6 @@ The following generators are available:
* [openapi](generators/openapi.md)
* [openapi-yaml](generators/openapi-yaml.md)
* [plantuml (beta)](generators/plantuml.md)
* [wsdl](generators/wsdl.md)
## SCHEMA generators
@ -151,6 +150,7 @@ The following generators are available:
* [ktorm-schema (beta)](generators/ktorm-schema.md)
* [mysql-schema](generators/mysql-schema.md)
* [protobuf-schema (beta)](generators/protobuf-schema.md)
* [wsdl-schema (beta)](generators/wsdl-schema.md)
## CONFIG generators

View File

@ -1,6 +1,6 @@
---
title: Config Options for wsdl
sidebar_label: wsdl
title: Config Options for wsdl-schema
sidebar_label: wsdl-schema
---
These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details.

View File

@ -1,264 +0,0 @@
package org.openapitools.codegen.languages;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import java.io.File;
import java.text.Normalizer;
import java.util.List;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Map;
import org.openapitools.codegen.CliOption;
import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.CodegenModel;
import org.openapitools.codegen.CodegenOperation;
import org.openapitools.codegen.CodegenParameter;
import org.openapitools.codegen.CodegenProperty;
import org.openapitools.codegen.CodegenType;
import org.openapitools.codegen.DefaultCodegen;
import org.openapitools.codegen.SupportingFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class WsdlGeneratorCodegen extends DefaultCodegen implements CodegenConfig {
public static final String PROJECT_NAME = "projectName";
static final Logger LOGGER = LoggerFactory.getLogger(WsdlGeneratorCodegen.class);
public CodegenType getTag() {
return CodegenType.DOCUMENTATION;
}
public String getName() {
return "wsdl";
}
public String getHelp() {
return "Generates a wsdl-spec documentation.";
}
public WsdlGeneratorCodegen() {
super();
outputFolder = "generated-code" + File.separator + "wsdl-spec";
embeddedTemplateDir = templateDir = "wsdl";
apiPackage = "Apis";
modelPackage = "Models";
cliOptions.add(new CliOption("hostname", "the hostname of the service"));
cliOptions.add(new CliOption("soapPath", "basepath of the soap services"));
cliOptions.add(new CliOption("serviceName", "service name for the wsdl"));
additionalProperties.put("hostname", "localhost");
additionalProperties.put("soapPath", "soap");
additionalProperties.put("serviceName", "ServiceV1");
supportingFiles.add(new SupportingFile("wsdl-converter.mustache", "", "service.wsdl"));
supportingFiles.add(new SupportingFile("jaxb-customization.mustache", "",
"jaxb-customization.xml"));
}
public void preprocessOpenAPI(OpenAPI openAPI) {
Info info = openAPI.getInfo();
String title = info.getTitle();
String description = info.getDescription();
info.setDescription(this.processOpenapiSpecDescription(description));
info.setTitle(this.escapeTitle(title));
}
private String escapeTitle(String title) {
// strip umlauts etc.
final String normalizedTitle = Normalizer.normalize(title, Normalizer.Form.NFD)
.replaceAll("[^\\p{ASCII}]", "");
return super.escapeUnsafeCharacters(normalizedTitle);
}
public String processOpenapiSpecDescription(String description) {
if (description != null) {
return description.replaceAll("\\s+", " ");
} else {
return "No description provided";
}
}
@Override
public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> objs,
List<Object> allModels) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
List<CodegenOperation> operationList = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation op : operationList) {
op.operationId = this.generateOperationId(op);
// for xml compliant primitives, lowercase dataType of openapi
for (CodegenParameter param : op.allParams) {
Map<String, Object> paramVendorExtensions = param.vendorExtensions;
normalizeDataType(param);
// prevent default="null" in wsdl-tag if no default was specified for a param
if ("null".equals(param.defaultValue) || param.defaultValue == null) {
paramVendorExtensions.put("x-param-has-defaultvalue", false);
} else {
paramVendorExtensions.put("x-param-has-defaultvalue", true);
}
// check if param has a minimum or maximum number or lenght
if (param.minimum != null
|| param.maximum != null
|| param.minLength != null
|| param.maxLength != null) {
paramVendorExtensions.put("x-param-has-minormax", true);
} else {
paramVendorExtensions.put("x-param-has-minormax", false);
}
// if param is enum, uppercase 'baseName' to have a reference to wsdl simpletype
if (param.isEnum) {
char[] c = param.baseName.toCharArray();
c[0] = Character.toUpperCase(c[0]);
param.baseName = new String(c);
}
}
for (CodegenParameter param : op.bodyParams) {
normalizeDataType(param);
}
for (CodegenParameter param : op.pathParams) {
normalizeDataType(param);
}
for (CodegenParameter param : op.queryParams) {
normalizeDataType(param);
}
for (CodegenParameter param : op.formParams) {
normalizeDataType(param);
}
}
return objs;
}
private void normalizeDataType(CodegenParameter param) {
if (param.isPrimitiveType) {
param.dataType = param.dataType.toLowerCase(Locale.getDefault());
}
if (param.dataFormat != null && param.dataFormat.equalsIgnoreCase("date")) {
param.dataType = "date";
}
if (param.dataFormat != null && param.dataFormat.equalsIgnoreCase("date-time")) {
param.dataType = "dateTime";
}
if (param.dataFormat != null && param.dataFormat.equalsIgnoreCase("uuid")) {
param.dataType = "string";
}
}
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
List<Object> models = (List<Object>) objs.get("models");
for (Object mo : models) {
Map<String, Object> mod = (Map<String, Object>) mo;
CodegenModel model = (CodegenModel) mod.get("model");
Map<String, Object> modelVendorExtensions = model.getVendorExtensions();
/* check if model is a model with no properties
* Used in the mustache template to ensure that no complextype is created
* if model is just a schema with an enum defined in the openapi specification
*/
if (model.allowableValues != null) {
modelVendorExtensions.put("x-is-openapimodel-enum", true);
} else {
modelVendorExtensions.put("x-is-openapimodel-enum", false);
}
for (CodegenProperty var : model.vars) {
Map<String, Object> propertyVendorExtensions = var.getVendorExtensions();
// lowercase basetypes if openapitype is string
if (var.openApiType == "string") {
char[] c = var.baseType.toCharArray();
c[0] = Character.toLowerCase(c[0]);
var.baseType = new String(c);
}
// if string enum, uppercase 'name' to have a reference to wsdl simpletype
if (var.isEnum) {
char[] c = var.name.toCharArray();
c[0] = Character.toUpperCase(c[0]);
var.name = new String(c);
}
// prevent default="null" in wsdl-tag if no default was specified for a property
if ("null".equals(var.defaultValue) || var.defaultValue == null) {
propertyVendorExtensions.put("x-prop-has-defaultvalue", false);
} else {
propertyVendorExtensions.put("x-prop-has-defaultvalue", true);
}
// check if model property has a minimum or maximum number or lenght
if (var.minimum != null
|| var.maximum != null
|| var.minLength != null
|| var.maxLength != null) {
propertyVendorExtensions.put("x-prop-has-minormax", true);
} else {
propertyVendorExtensions.put("x-prop-has-minormax", false);
}
}
}
return super.postProcessModelsEnum(objs);
}
public String generateOperationId(CodegenOperation op) {
String newOperationid = this.lowerCaseStringExceptFirstLetter(op.httpMethod);
String[] pathElements = op.path.split("/");
List<String> pathParameters = new ArrayList();
for (int i = 0; i < pathElements.length; i++) {
if (pathElements[i].contains("{")) {
pathParameters.add(pathElements[i]);
pathElements[i] = "";
}
if (pathElements[i].length() > 0) {
newOperationid = newOperationid + this.lowerCaseStringExceptFirstLetter(pathElements[i]);
}
}
if (pathParameters.size() > 0) {
for (int i = 0; i < pathParameters.size(); i++) {
String pathParameter = pathParameters.get(i);
pathParameter = this.lowerCaseStringExceptFirstLetter(pathParameter
.substring(1, pathParameter.length() - 1));
if (i == 0) {
newOperationid = newOperationid + "By" + pathParameter;
} else {
newOperationid = newOperationid + "And" + pathParameter;
}
}
}
return newOperationid;
}
public String lowerCaseStringExceptFirstLetter(String value) {
String newOperationid = value.toLowerCase(Locale.getDefault());
return newOperationid.substring(0, 1).toUpperCase(Locale.getDefault())
+ newOperationid.substring(1);
}
@Override
public String escapeQuotationMark(String input) {
// just return the original string
return input;
}
@Override
public String escapeUnsafeCharacters(String input) {
// just return the original string
return input;
}
}

View File

@ -0,0 +1,287 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.languages;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import java.io.File;
import java.text.Normalizer;
import java.util.List;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Map;
import org.openapitools.codegen.CliOption;
import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.CodegenModel;
import org.openapitools.codegen.CodegenOperation;
import org.openapitools.codegen.CodegenParameter;
import org.openapitools.codegen.CodegenProperty;
import org.openapitools.codegen.CodegenType;
import org.openapitools.codegen.DefaultCodegen;
import org.openapitools.codegen.meta.GeneratorMetadata;
import org.openapitools.codegen.meta.Stability;
import org.openapitools.codegen.meta.features.*;
import org.openapitools.codegen.SupportingFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class WsdlSchemaCodegen extends DefaultCodegen implements CodegenConfig {
public static final String PROJECT_NAME = "projectName";
static final Logger LOGGER = LoggerFactory.getLogger(WsdlSchemaCodegen.class);
public CodegenType getTag() {
return CodegenType.SCHEMA;
}
public String getName() {
return "wsdl-schema";
}
public String getHelp() {
return "Generates WSDL files.";
}
public WsdlSchemaCodegen() {
super();
generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata)
.stability(Stability.BETA)
.build();
outputFolder = "generated-code" + File.separator + "wsdl-schema";
embeddedTemplateDir = templateDir = "wsdl-schema";
apiPackage = "Apis";
modelPackage = "Models";
cliOptions.add(new CliOption("hostname", "the hostname of the service"));
cliOptions.add(new CliOption("soapPath", "basepath of the soap services"));
cliOptions.add(new CliOption("serviceName", "service name for the wsdl"));
additionalProperties.put("hostname", "localhost");
additionalProperties.put("soapPath", "soap");
additionalProperties.put("serviceName", "ServiceV1");
supportingFiles.add(new SupportingFile("wsdl-converter.mustache", "", "service.wsdl"));
supportingFiles.add(new SupportingFile("jaxb-customization.mustache", "",
"jaxb-customization.xml"));
}
public void preprocessOpenAPI(OpenAPI openAPI) {
Info info = openAPI.getInfo();
String title = info.getTitle();
String description = info.getDescription();
info.setDescription(this.processOpenapiSpecDescription(description));
info.setTitle(this.escapeTitle(title));
}
private String escapeTitle(String title) {
// strip umlauts etc.
final String normalizedTitle = Normalizer.normalize(title, Normalizer.Form.NFD)
.replaceAll("[^\\p{ASCII}]", "");
return super.escapeUnsafeCharacters(normalizedTitle);
}
public String processOpenapiSpecDescription(String description) {
if (description != null) {
return description.replaceAll("\\s+", " ");
} else {
return "No description provided";
}
}
@Override
public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> objs,
List<Object> allModels) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
List<CodegenOperation> operationList = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation op : operationList) {
op.operationId = this.generateOperationId(op);
// for xml compliant primitives, lowercase dataType of openapi
for (CodegenParameter param : op.allParams) {
Map<String, Object> paramVendorExtensions = param.vendorExtensions;
normalizeDataType(param);
// prevent default="null" in wsdl-tag if no default was specified for a param
if ("null".equals(param.defaultValue) || param.defaultValue == null) {
paramVendorExtensions.put("x-param-has-defaultvalue", false);
} else {
paramVendorExtensions.put("x-param-has-defaultvalue", true);
}
// check if param has a minimum or maximum number or lenght
if (param.minimum != null
|| param.maximum != null
|| param.minLength != null
|| param.maxLength != null) {
paramVendorExtensions.put("x-param-has-minormax", true);
} else {
paramVendorExtensions.put("x-param-has-minormax", false);
}
// if param is enum, uppercase 'baseName' to have a reference to wsdl simpletype
if (param.isEnum) {
char[] c = param.baseName.toCharArray();
c[0] = Character.toUpperCase(c[0]);
param.baseName = new String(c);
}
}
for (CodegenParameter param : op.bodyParams) {
normalizeDataType(param);
}
for (CodegenParameter param : op.pathParams) {
normalizeDataType(param);
}
for (CodegenParameter param : op.queryParams) {
normalizeDataType(param);
}
for (CodegenParameter param : op.formParams) {
normalizeDataType(param);
}
}
return objs;
}
private void normalizeDataType(CodegenParameter param) {
if (param.isPrimitiveType) {
param.dataType = param.dataType.toLowerCase(Locale.getDefault());
}
if (param.dataFormat != null && param.dataFormat.equalsIgnoreCase("date")) {
param.dataType = "date";
}
if (param.dataFormat != null && param.dataFormat.equalsIgnoreCase("date-time")) {
param.dataType = "dateTime";
}
if (param.dataFormat != null && param.dataFormat.equalsIgnoreCase("uuid")) {
param.dataType = "string";
}
}
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
List<Object> models = (List<Object>) objs.get("models");
for (Object mo : models) {
Map<String, Object> mod = (Map<String, Object>) mo;
CodegenModel model = (CodegenModel) mod.get("model");
Map<String, Object> modelVendorExtensions = model.getVendorExtensions();
/* check if model is a model with no properties
* Used in the mustache template to ensure that no complextype is created
* if model is just a schema with an enum defined in the openapi specification
*/
if (model.allowableValues != null) {
modelVendorExtensions.put("x-is-openapimodel-enum", true);
} else {
modelVendorExtensions.put("x-is-openapimodel-enum", false);
}
for (CodegenProperty var : model.vars) {
Map<String, Object> propertyVendorExtensions = var.getVendorExtensions();
// lowercase basetypes if openapitype is string
if ("string".equals(var.openApiType)) {
char[] c = var.baseType.toCharArray();
c[0] = Character.toLowerCase(c[0]);
var.baseType = new String(c);
}
// if string enum, uppercase 'name' to have a reference to wsdl simpletype
if (var.isEnum) {
char[] c = var.name.toCharArray();
c[0] = Character.toUpperCase(c[0]);
var.name = new String(c);
}
// prevent default="null" in wsdl-tag if no default was specified for a property
if ("null".equals(var.defaultValue) || var.defaultValue == null) {
propertyVendorExtensions.put("x-prop-has-defaultvalue", false);
} else {
propertyVendorExtensions.put("x-prop-has-defaultvalue", true);
}
// check if model property has a minimum or maximum number or lenght
if (var.minimum != null
|| var.maximum != null
|| var.minLength != null
|| var.maxLength != null) {
propertyVendorExtensions.put("x-prop-has-minormax", true);
} else {
propertyVendorExtensions.put("x-prop-has-minormax", false);
}
}
}
return super.postProcessModelsEnum(objs);
}
public String generateOperationId(CodegenOperation op) {
String newOperationid = this.lowerCaseStringExceptFirstLetter(op.httpMethod);
String[] pathElements = op.path.split("/");
List<String> pathParameters = new ArrayList();
for (int i = 0; i < pathElements.length; i++) {
if (pathElements[i].contains("{")) {
pathParameters.add(pathElements[i]);
pathElements[i] = "";
}
if (pathElements[i].length() > 0) {
newOperationid = newOperationid + this.lowerCaseStringExceptFirstLetter(pathElements[i]);
}
}
if (pathParameters.size() > 0) {
for (int i = 0; i < pathParameters.size(); i++) {
String pathParameter = pathParameters.get(i);
pathParameter = this.lowerCaseStringExceptFirstLetter(pathParameter
.substring(1, pathParameter.length() - 1));
if (i == 0) {
newOperationid = newOperationid + "By" + pathParameter;
} else {
newOperationid = newOperationid + "And" + pathParameter;
}
}
}
return newOperationid;
}
public String lowerCaseStringExceptFirstLetter(String value) {
String newOperationid = value.toLowerCase(Locale.getDefault());
return newOperationid.substring(0, 1).toUpperCase(Locale.getDefault())
+ newOperationid.substring(1);
}
@Override
public String escapeQuotationMark(String input) {
// just return the original string
return input;
}
@Override
public String escapeUnsafeCharacters(String input) {
// just return the original string
return input;
}
}

View File

@ -38,6 +38,7 @@ org.openapitools.codegen.languages.FsharpFunctionsServerCodegen
org.openapitools.codegen.languages.FsharpGiraffeServerCodegen
org.openapitools.codegen.languages.GoClientCodegen
org.openapitools.codegen.languages.GoDeprecatedClientCodegen
org.openapitools.codegen.languages.GoEchoServerCodegen
org.openapitools.codegen.languages.GoServerCodegen
org.openapitools.codegen.languages.GoGinServerCodegen
org.openapitools.codegen.languages.GraphQLSchemaCodegen
@ -133,5 +134,4 @@ org.openapitools.codegen.languages.TypeScriptNestjsClientCodegen
org.openapitools.codegen.languages.TypeScriptNodeClientCodegen
org.openapitools.codegen.languages.TypeScriptReduxQueryClientCodegen
org.openapitools.codegen.languages.TypeScriptRxjsClientCodegen
org.openapitools.codegen.languages.GoEchoServerCodegen
org.openapitools.codegen.languages.WsdlGeneratorCodegen
org.openapitools.codegen.languages.WsdlSchemaCodegen

View File

@ -1,269 +0,0 @@
package org.openapitools.codegen.wsdl;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.openapitools.codegen.ClientOptInput;
import org.openapitools.codegen.CodegenOperation;
import org.openapitools.codegen.DefaultGenerator;
import org.openapitools.codegen.TestUtils;
import org.openapitools.codegen.languages.WsdlGeneratorCodegen;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static org.openapitools.codegen.TestUtils.assertFileContains;
import static org.openapitools.codegen.TestUtils.ensureContainsFile;
public class WsdlGeneratorTest {
private OpenAPI openAPI;
private File outputDirectory;
private String outputPath;
private List<File> listOfFiles;
@BeforeClass
public void setUp() throws IOException {
this.openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/wsdl/petstore.yaml");
this.outputDirectory = Files.createTempDirectory("test").toFile().getCanonicalFile();
this.outputPath = this.outputDirectory.getAbsolutePath().replace('\\', '/');
WsdlGeneratorCodegen codegen = new WsdlGeneratorCodegen();
codegen.setOutputDir(this.outputDirectory.getAbsolutePath());
ClientOptInput input = new ClientOptInput()
.openAPI(this.openAPI)
.config(codegen);
DefaultGenerator generator = new DefaultGenerator();
this.listOfFiles = generator.opts(input).generate();
}
@Test(description = "ensure that the operationid has been generated correctly")
public void testOperationIdGeneration() {
final OpenAPI openAPI = this.openAPI;
WsdlGeneratorCodegen codegen = new WsdlGeneratorCodegen();
codegen.setOpenAPI(openAPI);
String requestPathWithId = "/store/order/{orderId}";
Operation textOperationGet = openAPI.getPaths().get(requestPathWithId).getGet();
CodegenOperation opGet = codegen.fromOperation(requestPathWithId, "get", textOperationGet, null);
String newOperationIdWithId = codegen.generateOperationId(opGet);
String requestPathWithoutId = "/store/order";
Operation textOperationPost = openAPI.getPaths().get(requestPathWithoutId).getPost();
CodegenOperation opPost = codegen.fromOperation(requestPathWithoutId, "post", textOperationPost, null);
String newOperationIdWithoutId = codegen.generateOperationId(opPost);
Assert.assertEquals(newOperationIdWithId, "GetStoreOrderByOrderid");
Assert.assertEquals(newOperationIdWithoutId, "PostStoreOrder");
}
@Test(description = "Ensure that passed strings are processed correcly by this method")
public void testLowerCaseStringExceptFirstLetter() {
WsdlGeneratorCodegen codegen = new WsdlGeneratorCodegen();
String value = codegen.lowerCaseStringExceptFirstLetter("uploadPetByPathId");
Assert.assertEquals(value, "Uploadpetbypathid");
}
@Test(description = "Check if element tags has been created for an operation ")
public void testIfElementTagsExist() {
String xsElementRequestMessage =
"<xs:element name=\"PostPetByPetid_RequestMessage\" type=\"schemas:PostPetByPetid_RequestMessage\" />";
String xsElementResponseMessage =
"<xs:element name=\"PostPetByPetid_ResponseMessage\" type=\"schemas:PostPetByPetid_ResponseMessage\" />";
String xsElementErrorResponse =
" <xs:element name=\"PostPetByPetid_405\">\n"
+ " <xs:annotation>\n"
+ " <xs:documentation>Invalid input</xs:documentation>\n"
+ " </xs:annotation>\n"
+ " </xs:element>\n";
assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), xsElementRequestMessage);
assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), xsElementResponseMessage);
assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), xsElementErrorResponse);
}
@Test(description = "Check if complexType input- and output-message has been created for an operation ")
public void testIfInputAndResponseMessageExist() {
String complexTypeRequestMessage =
" <xs:complexType name=\"GetPetByPetid_RequestMessage\">\n"
+ " <xs:sequence>\n"
+ " <xs:element minOccurs=\"1\" name=\"petId\" type=\"xs:long\">\n"
+ " <xs:annotation>\n"
+ " <xs:documentation>ID of pet to return</xs:documentation>\n"
+ " </xs:annotation>\n"
+ " </xs:element>\n"
+ " </xs:sequence>\n"
+ " </xs:complexType>\n";
String complexTypeResponseMessage =
" <xs:complexType name=\"GetPetByPetid_ResponseMessage\">\n"
+ " <xs:sequence>\n"
+ " <xs:element minOccurs=\"1\" name=\"Pet\" type=\"schemas:Pet\">\n"
+ " <xs:annotation>\n"
+ " <xs:documentation>successful operation</xs:documentation>\n"
+ " </xs:annotation>\n"
+ " </xs:element>\n"
+ " </xs:sequence>\n"
+ " </xs:complexType>\n";
assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), complexTypeRequestMessage);
assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), complexTypeResponseMessage);
}
@Test(description =
"Check if complexType RequestMessage with minimum and maximum restriction has been created for an operation ")
public void testIfRequestMessageMinimumExists() {
String complexTypeRequestMessageMinimum =
" <xs:complexType name=\"GetStoreOrderByOrderid_RequestMessage\">\n"
+ " <xs:sequence>\n"
+ " <xs:element minOccurs=\"1\" name=\"orderId\">\n"
+ " <xs:simpleType>\n"
+ " <xs:annotation>\n"
+ " <xs:documentation>ID of pet that needs to be fetched</xs:documentation>\n"
+ " </xs:annotation>\n"
+ " <xs:restriction base=\"xs:long\">\n"
+ " <xs:maxInclusive value=\"10\" />\n"
+ " <xs:minInclusive value=\"1\" />\n"
+ " </xs:restriction>\n"
+ " </xs:simpleType>\n"
+ " </xs:element>\n"
+ " </xs:sequence>\n"
+ " </xs:complexType>\n";
assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), complexTypeRequestMessageMinimum);
}
@Test(description = "Check if complexType model has been created for an openapi model schema")
public void testIfComplexTypeModelExists() {
String complexTypeModel =
" <xs:complexType name=\"Pet\">\n"
+ " <xs:sequence>\n"
+ " <xs:element minOccurs=\"0\" name=\"id\" type=\"xs:long\" />\n"
+ " <xs:element minOccurs=\"0\" name=\"category\" type=\"schemas:Category\" />\n"
+ " <xs:element minOccurs=\"1\" name=\"name\" type=\"xs:string\" />\n"
+ " <xs:element minOccurs=\"1\" maxOccurs=\"unbounded\" name=\"photoUrls\" type=\"xs:string\" />\n"
+ " <xs:element minOccurs=\"0\" maxOccurs=\"unbounded\" name=\"tags\" type=\"schemas:Tag\" />\n"
+ " <xs:element minOccurs=\"0\" name=\"status\" type=\"schemas:Status\">\n"
+ " <xs:annotation>\n"
+ " <xs:documentation>pet status in the store</xs:documentation>\n"
+ " </xs:annotation>\n"
+ " </xs:element>\n"
+ " </xs:sequence>\n"
+ " </xs:complexType>\n";
assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), complexTypeModel);
}
@Test(description = "Check if message and part tags has been created for an operation ")
public void testIfMessageTagsAndContentExist() {
String messageRequestMessage =
" <message name=\"PostPetByPetid_RequestMessage\">\n"
+ " <part name=\"PostPetByPetid_RequestMessage\" element=\"schemas:PostPetByPetid_RequestMessage\" />\n"
+ " </message>";
String messageError =
" <message name=\"PostPetByPetid_405\">\n"
+ " <part name=\"PostPetByPetid_405\" element=\"schemas:PostPetByPetid_405\" />\n"
+ " </message>\n";
assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), messageRequestMessage);
assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), messageError);
}
@Test(description = "Check if portType tag and portType operation has been generated")
public void testIfPorttypeOperationExists() {
String portType = "<portType name=\"ServiceV1_PortType\">";
String portTypeOperation =
" <operation name=\"GetPetByPetid\">\n"
+ " <documentation>Returns a single pet</documentation>\n"
+ " <input message=\"wsdl:GetPetByPetid_RequestMessage\" />\n"
+ " <output message=\"wsdl:GetPetByPetid_ResponseMessage\">\n"
+ " <documentation>successful operation</documentation>\n"
+ " </output>\n"
+ " <fault name=\"GetPetByPetid_400\" message=\"wsdl:GetPetByPetid_400\">\n"
+ " <documentation>Invalid ID supplied</documentation>\n"
+ " </fault>\n"
+ " <fault name=\"GetPetByPetid_404\" message=\"wsdl:GetPetByPetid_404\">\n"
+ " <documentation>Pet not found</documentation>\n"
+ " </fault>\n"
+ " </operation>\n";
assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), portType);
assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), portTypeOperation);
}
@Test(description = "Check if portType tag and portType operation has been generated")
public void testIfBindingOperationExists() {
String binding = "<binding name=\"ServiceV1_Binding\" type=\"wsdl:ServiceV1_PortType\">";
String bindingOperation =
" <operation name=\"GetPetByPetid\">\n"
+ " <soap:operation soapAction=\"GetPetByPetid\" xmlns:soap=\"http://schemas.xmlsoap.org/wsdl/soap/\" />\n"
+ " <input>\n"
+ " <soap:body use=\"literal\" xmlns:soap=\"http://schemas.xmlsoap.org/wsdl/soap/\" />\n"
+ " </input>\n"
+ " <output>\n"
+ " <soap:body use=\"literal\" xmlns:soap=\"http://schemas.xmlsoap.org/wsdl/soap/\" />\n"
+ " </output>\n"
+ " <fault name=\"GetPetByPetid_400\">\n"
+ " <soap:fault use=\"literal\" name=\"GetPetByPetid_400\" xmlns:soap=\"http://schemas.xmlsoap.org/wsdl/soap/\" />\n"
+ " </fault>\n"
+ " <fault name=\"GetPetByPetid_404\">\n"
+ " <soap:fault use=\"literal\" name=\"GetPetByPetid_404\" xmlns:soap=\"http://schemas.xmlsoap.org/wsdl/soap/\" />\n"
+ " </fault>\n"
+ " </operation>\n";
assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), binding);
assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), bindingOperation);
}
@Test(description = "Ensure that all files have been correctly generated")
public void testFileGeneration() throws Exception {
Assert.assertEquals(this.listOfFiles.size(), 5);
ensureContainsFile(this.listOfFiles, this.outputDirectory, ".openapi-generator-ignore");
ensureContainsFile(this.listOfFiles, this.outputDirectory, ".openapi-generator/FILES");
ensureContainsFile(this.listOfFiles, this.outputDirectory, ".openapi-generator/VERSION");
ensureContainsFile(this.listOfFiles, this.outputDirectory, "service.wsdl");
ensureContainsFile(this.listOfFiles, this.outputDirectory, "jaxb-customization.xml");
}
@Test(description = "Ensure that default description is set if it doesn't exist")
public void testOpenapiDescriptionWasNotProvided() throws IOException {
final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/ping.yaml");
File outputDirectory = Files.createTempDirectory("test").toFile().getCanonicalFile();
String outputPath = this.outputDirectory.getAbsolutePath().replace('\\', '/');
WsdlGeneratorCodegen codegen = new WsdlGeneratorCodegen();
codegen.setOutputDir(this.outputDirectory.getAbsolutePath());
ClientOptInput input = new ClientOptInput().openAPI(openAPI).config(codegen);
DefaultGenerator generator = new DefaultGenerator();
generator.opts(input).generate();
String value = "<documentation>No description provided</documentation>";
assertFileContains(Paths.get(outputPath + "/service.wsdl"), value);
FileUtils.deleteDirectory(outputDirectory);
}
@AfterClass
public void cleanUp() throws Exception {
// Delete temp folder
FileUtils.deleteDirectory(this.outputDirectory);
}
}

View File

@ -0,0 +1,266 @@
package org.openapitools.codegen.wsdl;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import org.apache.commons.io.FileUtils;
import org.openapitools.codegen.ClientOptInput;
import org.openapitools.codegen.CodegenOperation;
import org.openapitools.codegen.DefaultGenerator;
import org.openapitools.codegen.TestUtils;
import org.openapitools.codegen.languages.WsdlSchemaCodegen;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import static org.openapitools.codegen.TestUtils.assertFileContains;
import static org.openapitools.codegen.TestUtils.ensureContainsFile;
public class WsdlSchemaCodegenTest {
private OpenAPI openAPI;
private File outputDirectory;
private String outputPath;
private List<File> listOfFiles;
@BeforeClass
public void setUp() throws IOException {
this.openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/wsdl/petstore.yaml");
this.outputDirectory = Files.createTempDirectory("test").toFile().getCanonicalFile();
this.outputPath = this.outputDirectory.getAbsolutePath().replace('\\', '/');
WsdlSchemaCodegen codegen = new WsdlSchemaCodegen();
codegen.setOutputDir(this.outputDirectory.getAbsolutePath());
ClientOptInput input = new ClientOptInput()
.openAPI(this.openAPI)
.config(codegen);
DefaultGenerator generator = new DefaultGenerator();
this.listOfFiles = generator.opts(input).generate();
}
@Test(description = "ensure that the operationid has been generated correctly")
public void testOperationIdGeneration() {
final OpenAPI openAPI = this.openAPI;
WsdlSchemaCodegen codegen = new WsdlSchemaCodegen();
codegen.setOpenAPI(openAPI);
String requestPathWithId = "/store/order/{orderId}";
Operation textOperationGet = openAPI.getPaths().get(requestPathWithId).getGet();
CodegenOperation opGet = codegen.fromOperation(requestPathWithId, "get", textOperationGet, null);
String newOperationIdWithId = codegen.generateOperationId(opGet);
String requestPathWithoutId = "/store/order";
Operation textOperationPost = openAPI.getPaths().get(requestPathWithoutId).getPost();
CodegenOperation opPost = codegen.fromOperation(requestPathWithoutId, "post", textOperationPost, null);
String newOperationIdWithoutId = codegen.generateOperationId(opPost);
Assert.assertEquals(newOperationIdWithId, "GetStoreOrderByOrderid");
Assert.assertEquals(newOperationIdWithoutId, "PostStoreOrder");
}
@Test(description = "Ensure that passed strings are processed correcly by this method")
public void testLowerCaseStringExceptFirstLetter() {
WsdlSchemaCodegen codegen = new WsdlSchemaCodegen();
String value = codegen.lowerCaseStringExceptFirstLetter("uploadPetByPathId");
Assert.assertEquals(value, "Uploadpetbypathid");
}
@Test(description = "Check if element tags has been created for an operation ")
public void testIfElementTagsExist() {
String xsElementRequestMessage =
"<xs:element name=\"PostPetByPetid_RequestMessage\" type=\"schemas:PostPetByPetid_RequestMessage\" />";
String xsElementResponseMessage =
"<xs:element name=\"PostPetByPetid_ResponseMessage\" type=\"schemas:PostPetByPetid_ResponseMessage\" />";
String xsElementErrorResponse =
" <xs:element name=\"PostPetByPetid_405\">\n"
+ " <xs:annotation>\n"
+ " <xs:documentation>Invalid input</xs:documentation>\n"
+ " </xs:annotation>\n"
+ " </xs:element>\n";
assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), xsElementRequestMessage);
assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), xsElementResponseMessage);
assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), xsElementErrorResponse);
}
@Test(description = "Check if complexType input- and output-message has been created for an operation ")
public void testIfInputAndResponseMessageExist() {
String complexTypeRequestMessage =
" <xs:complexType name=\"GetPetByPetid_RequestMessage\">\n"
+ " <xs:sequence>\n"
+ " <xs:element minOccurs=\"1\" name=\"petId\" type=\"xs:long\">\n"
+ " <xs:annotation>\n"
+ " <xs:documentation>ID of pet to return</xs:documentation>\n"
+ " </xs:annotation>\n"
+ " </xs:element>\n"
+ " </xs:sequence>\n"
+ " </xs:complexType>\n";
String complexTypeResponseMessage =
" <xs:complexType name=\"GetPetByPetid_ResponseMessage\">\n"
+ " <xs:sequence>\n"
+ " <xs:element minOccurs=\"1\" name=\"Pet\" type=\"schemas:Pet\">\n"
+ " <xs:annotation>\n"
+ " <xs:documentation>successful operation</xs:documentation>\n"
+ " </xs:annotation>\n"
+ " </xs:element>\n"
+ " </xs:sequence>\n"
+ " </xs:complexType>\n";
assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), complexTypeRequestMessage);
assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), complexTypeResponseMessage);
}
@Test(description =
"Check if complexType RequestMessage with minimum and maximum restriction has been created for an operation ")
public void testIfRequestMessageMinimumExists() {
String complexTypeRequestMessageMinimum =
" <xs:complexType name=\"GetStoreOrderByOrderid_RequestMessage\">\n"
+ " <xs:sequence>\n"
+ " <xs:element minOccurs=\"1\" name=\"orderId\">\n"
+ " <xs:simpleType>\n"
+ " <xs:annotation>\n"
+ " <xs:documentation>ID of pet that needs to be fetched</xs:documentation>\n"
+ " </xs:annotation>\n"
+ " <xs:restriction base=\"xs:long\">\n"
+ " <xs:maxInclusive value=\"10\" />\n"
+ " <xs:minInclusive value=\"1\" />\n"
+ " </xs:restriction>\n"
+ " </xs:simpleType>\n"
+ " </xs:element>\n"
+ " </xs:sequence>\n"
+ " </xs:complexType>\n";
assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), complexTypeRequestMessageMinimum);
}
@Test(description = "Check if complexType model has been created for an openapi model schema")
public void testIfComplexTypeModelExists() {
String complexTypeModel =
" <xs:complexType name=\"Pet\">\n"
+ " <xs:sequence>\n"
+ " <xs:element minOccurs=\"0\" name=\"id\" type=\"xs:long\" />\n"
+ " <xs:element minOccurs=\"0\" name=\"category\" type=\"schemas:Category\" />\n"
+ " <xs:element minOccurs=\"1\" name=\"name\" type=\"xs:string\" />\n"
+ " <xs:element minOccurs=\"1\" maxOccurs=\"unbounded\" name=\"photoUrls\" type=\"xs:string\" />\n"
+ " <xs:element minOccurs=\"0\" maxOccurs=\"unbounded\" name=\"tags\" type=\"schemas:Tag\" />\n"
+ " <xs:element minOccurs=\"0\" name=\"status\" type=\"schemas:Status\">\n"
+ " <xs:annotation>\n"
+ " <xs:documentation>pet status in the store</xs:documentation>\n"
+ " </xs:annotation>\n"
+ " </xs:element>\n"
+ " </xs:sequence>\n"
+ " </xs:complexType>\n";
assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), complexTypeModel);
}
@Test(description = "Check if message and part tags has been created for an operation ")
public void testIfMessageTagsAndContentExist() {
String messageRequestMessage =
" <message name=\"PostPetByPetid_RequestMessage\">\n"
+ " <part name=\"PostPetByPetid_RequestMessage\" element=\"schemas:PostPetByPetid_RequestMessage\" />\n"
+ " </message>";
String messageError =
" <message name=\"PostPetByPetid_405\">\n"
+ " <part name=\"PostPetByPetid_405\" element=\"schemas:PostPetByPetid_405\" />\n"
+ " </message>\n";
assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), messageRequestMessage);
assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), messageError);
}
@Test(description = "Check if portType tag and portType operation has been generated")
public void testIfPorttypeOperationExists() {
String portType = "<portType name=\"ServiceV1_PortType\">";
String portTypeOperation =
" <operation name=\"GetPetByPetid\">\n"
+ " <documentation>Returns a single pet</documentation>\n"
+ " <input message=\"wsdl:GetPetByPetid_RequestMessage\" />\n"
+ " <output message=\"wsdl:GetPetByPetid_ResponseMessage\">\n"
+ " <documentation>successful operation</documentation>\n"
+ " </output>\n"
+ " <fault name=\"GetPetByPetid_400\" message=\"wsdl:GetPetByPetid_400\">\n"
+ " <documentation>Invalid ID supplied</documentation>\n"
+ " </fault>\n"
+ " <fault name=\"GetPetByPetid_404\" message=\"wsdl:GetPetByPetid_404\">\n"
+ " <documentation>Pet not found</documentation>\n"
+ " </fault>\n"
+ " </operation>\n";
assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), portType);
assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), portTypeOperation);
}
@Test(description = "Check if portType tag and portType operation has been generated")
public void testIfBindingOperationExists() {
String binding = "<binding name=\"ServiceV1_Binding\" type=\"wsdl:ServiceV1_PortType\">";
String bindingOperation =
" <operation name=\"GetPetByPetid\">\n"
+ " <soap:operation soapAction=\"GetPetByPetid\" xmlns:soap=\"http://schemas.xmlsoap.org/wsdl/soap/\" />\n"
+ " <input>\n"
+ " <soap:body use=\"literal\" xmlns:soap=\"http://schemas.xmlsoap.org/wsdl/soap/\" />\n"
+ " </input>\n"
+ " <output>\n"
+ " <soap:body use=\"literal\" xmlns:soap=\"http://schemas.xmlsoap.org/wsdl/soap/\" />\n"
+ " </output>\n"
+ " <fault name=\"GetPetByPetid_400\">\n"
+ " <soap:fault use=\"literal\" name=\"GetPetByPetid_400\" xmlns:soap=\"http://schemas.xmlsoap.org/wsdl/soap/\" />\n"
+ " </fault>\n"
+ " <fault name=\"GetPetByPetid_404\">\n"
+ " <soap:fault use=\"literal\" name=\"GetPetByPetid_404\" xmlns:soap=\"http://schemas.xmlsoap.org/wsdl/soap/\" />\n"
+ " </fault>\n"
+ " </operation>\n";
assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), binding);
assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), bindingOperation);
}
@Test(description = "Ensure that all files have been correctly generated")
public void testFileGeneration() throws Exception {
Assert.assertEquals(this.listOfFiles.size(), 5);
ensureContainsFile(this.listOfFiles, this.outputDirectory, ".openapi-generator-ignore");
ensureContainsFile(this.listOfFiles, this.outputDirectory, ".openapi-generator/FILES");
ensureContainsFile(this.listOfFiles, this.outputDirectory, ".openapi-generator/VERSION");
ensureContainsFile(this.listOfFiles, this.outputDirectory, "service.wsdl");
ensureContainsFile(this.listOfFiles, this.outputDirectory, "jaxb-customization.xml");
}
@Test(description = "Ensure that default description is set if it doesn't exist")
public void testOpenapiDescriptionWasNotProvided() throws IOException {
final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/ping.yaml");
File outputDirectory = Files.createTempDirectory("test").toFile().getCanonicalFile();
String outputPath = this.outputDirectory.getAbsolutePath().replace('\\', '/');
WsdlSchemaCodegen codegen = new WsdlSchemaCodegen();
codegen.setOutputDir(this.outputDirectory.getAbsolutePath());
ClientOptInput input = new ClientOptInput().openAPI(openAPI).config(codegen);
DefaultGenerator generator = new DefaultGenerator();
generator.opts(input).generate();
String value = "<documentation>No description provided</documentation>";
assertFileContains(Paths.get(outputPath + "/service.wsdl"), value);
FileUtils.deleteDirectory(outputDirectory);
}
@AfterClass
public void cleanUp() throws Exception {
// Delete temp folder
FileUtils.deleteDirectory(this.outputDirectory);
}
}